body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>I wrote the following code for <a href="https://automatetheboringstuff.com/chapter3/#calibre_link-2229" rel="nofollow noreferrer">the Collatz exercise: <em>The Collatz Sequence</em></a></p>
<p>Any feedback is appreciated.</p>
<blockquote>
<p>Write a function named <code>collatz()</code> that has one parameter named <code>number</code>. If <code>number</code> is even, then <code>collatz()</code> should print <code>number // 2</code> and return this value. If <code>number</code> is odd, then <code>collatz()</code> should print and return <code>3 * number + 1</code>.</p>
</blockquote>
<pre><code>def collatz(n):
while n > 1:
if n % 2 == 0:
n = int(n // 2)
print (n)
elif n % 2 == 1:
n = int(3 * n + 1)
print (n)
n = int(input("Enter a number: "))
collatz (n)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T06:39:04.227",
"Id": "428980",
"Score": "3",
"body": "@drapozo It would be welcome if you'd provide either a link or a small description of the problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T14:27:03.410",
"Id": "429220",
"Score": "1",
"body": "It´s a problem form the Book automate the boring stuff with python. The problem is \"The Collatz Sequence\" and can be found in this link. https://automatetheboringstuff.com/chapter3/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-20T15:35:13.813",
"Id": "431063",
"Score": "2",
"body": "When adding additional information you should [edit] your question instead of adding a comment. I have added that information to your post. Learn more about comments including when to comment and when not to in [the Help Center page about Comments](https://codereview.stackexchange.com/help/privileges/comment)."
}
] | [
{
"body": "<p>A few simple observations:</p>\n\n<ul>\n<li><blockquote>\n<pre><code> if n % 2 == 0:\n ...\n elif n % 2 == 1:\n ...\n</code></pre>\n</blockquote>\n\n<p>Here, we know that if <code>n % 2</code> isn't 0, it <em>must</em> be 1, since <code>n</code> is an integer. So that <code>elif</code> can be simply <code>else</code>, making it simpler to read. More experienced programmers will reverse the test, knowing that <code>1</code> is the only truthy result of <code>n % 2</code>, so write <code>if n % 2: ... ; else ...</code>.</p></li>\n<li><blockquote>\n<pre><code> if ...:\n ...\n print (n)\n else:\n ...\n print (n)\n</code></pre>\n</blockquote>\n\n<p>The <code>print</code> that's present in both branches could be placed after the <code>if</code>/<code>else</code>, since it doesn't depend on the condition.</p></li>\n<li><p>The results of the arithmetic expressions are already <code>int</code>, so no conversion is necessary.</p></li>\n<li><p>The <code>if</code>/<code>else</code> could be reduced to a single line:</p>\n\n<pre><code>n = 3 * n + 1 if n % 2 else n // 2\n</code></pre>\n\n<p>but to me, that looks less clear, so I don't recommend that level of terseness here.</p></li>\n</ul>\n\n<hr>\n\n<h1>Modified code</h1>\n\n<p>Applying the observations above, I get a simpler version of the function:</p>\n\n<pre><code>def collatz(n):\n while n > 1:\n if n % 2:\n n = 3 * n + 1\n else:\n n = n // 2\n print(n)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T14:24:34.853",
"Id": "429218",
"Score": "0",
"body": "Thanks for your observations. In the simpler version you wrote i think you meant if n % 2 == 1."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T08:34:19.423",
"Id": "429539",
"Score": "0",
"body": "No, I didn't mean `if n % 2 == 1`. Because `n % 2` can only be 0 or 1, it's simpler to just test whether `n % 2` is truthy."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T08:04:17.540",
"Id": "221765",
"ParentId": "221741",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-05T19:57:14.010",
"Id": "221741",
"Score": "0",
"Tags": [
"python",
"beginner",
"python-3.x",
"collatz-sequence"
],
"Title": "Automate the Boring Stuff - Collatz Exercise"
} | 221741 |
<p>I have the following working tic tac toe program. Someone said it's a convoluted mess and I'm looking for pointers on how to clean it up.</p>
<pre><code>import java.util.Scanner;
import java.util.ArrayList;
import java.util.Random;
import java.util.Arrays;
public class Shortver{
private static final int boardRowDim = 3;
private static final int boardColDim = 3;
private String[][] board;
private String playerName;
private String playerMark;
private String computerMark;
private boolean humanGoes;
private boolean winner;
private boolean draw;
private int gameTargetScore;
private boolean output = false;
private boolean toSeed = false;
private ArrayList<Integer> availableMoves;
public Shortver(String name, boolean whoGoesFirst){
availableMoves = new ArrayList<Integer>();
board = new String[boardRowDim][boardColDim];
for (int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
board[i][j] = ((Integer)(double2single(i,j))).toString();
availableMoves.add(double2single(i,j));
}
}
playerName = name;
humanGoes = whoGoesFirst;
playerMark = "X";
computerMark = "O";
gameTargetScore = 15;
if(!humanGoes){
playerMark = "O";
computerMark = "X";
gameTargetScore = - 15;
}
winner = false;
draw = false;
}
public static void main(String[] args)throws Exception{
System.out.println("\u000C");
Scanner kboard = new Scanner(System.in);
printHeader();
System.out.print(" Please enter your name ; ");
String name = kboard.next();
name = capitalize(name);
System.out.print("\n\n X's go first. " + name + ", please enter your mark ('X' or 'O')");
String mark = kboard.next().toUpperCase();
boolean whoPlaysFirst = (mark.equals("X")) ? true : false;
Shortver myGame = new Shortver(name,whoPlaysFirst);
myGame.playGame(kboard);
}
public void playGame(Scanner kboard)throws Exception{
Integer move = null;
boolean goodMove;
String kboardInput = null;
Scanner input;
int[] cell2D = new int[2];
Random random = new Random();
int nextComputerMove;
if(toSeed){
board = seedBoard();
availableMoves = seedAvailable(board);
int x = 0;
int o = 0;
for(int i = 0; i < 3;i++){
for(int j = 0;j < 3;j++){
if(board[i][j].equals("X"))x++;
else if(board[i][j].equals("O"))o++;
}
}
if((x - o) == 1) humanGoes = true;
else if((x - o) == 0) humanGoes = false;
else{
System.out.println("Fatal Error: seed bad");
System.exit(0);
}
System.out.println("humangoes = " + humanGoes + x + o);
}
while(!winner && !draw){
printHeader();
goodMove = false;
drawBoard(board);
if(!humanGoes && availableMoves.size() < 9){
System.out.println("That's a great move, I'll have to think about this");
Thread.sleep(2000);
}
if(humanGoes){
while(!goodMove){
System.out.print("\n\n Please enter a number for your move : ");
kboardInput = kboard.next();
input = new Scanner(kboardInput);
if(input.hasNextInt()){
move = input.nextInt();
if(move == 99){
System.out.println("You found the secret exit code");
Thread.sleep(2000);
printHeader();
System.out.println("bye");
System.exit(0);
}
goodMove = checkMove(move);
if(!goodMove)System.out.println(" WARNING: Incorrect input, try again");
}else{
System.out.println(" WARNING: Incorrect input, try again");
}
}
cell2D = single2Double(move);
board[cell2D[0]][cell2D[1]] = playerMark;
}else{
String[][] currentBoard = new String[boardRowDim][boardColDim];
currentBoard = copyBoard(board);
ArrayList<Integer> currentAvailableMoves= new ArrayList<Integer>();
currentAvailableMoves = copyAvailableMoves(availableMoves);
//System.out.println(System.identityHashCode(currentAvailableMoves));
int[] bestScoreMove = new int[2];
bestScoreMove = findBestMove(currentBoard,currentAvailableMoves,true,0,kboard);
move = availableMoves.get(availableMoves.indexOf(bestScoreMove[1]));
cell2D = single2Double(move);
board[cell2D[0]][cell2D[1]] = computerMark;
}
humanGoes = humanGoes ? false:true;
availableMoves = updateAvailableMoves(move,availableMoves);
if (Math.abs(score(board)) == 15) winner = true;
if (availableMoves.size() == 0) draw = true;
if(winner || draw){
printHeader();
drawBoard(board);
}
if(score(board) == gameTargetScore)System.out.println(playerName + " you are too good for me. \n" +
"Congratulations you won!!\n\n");
else if(score(board) == -gameTargetScore)System.out.println("IWONIWONIWONohboyIWONIWONIWON");
else if(draw)System.out.println("Good game. It's a draw!");
}
}
public void drawBoard(String[][] someBoard){
String mark = " ";
Integer row,col;
String type;
for( int i = 0;i < 15; i++){
System.out.print(" ");
for (int j = 0; j < 27; j++){
mark = " ";
if(i==5 || i == 10)mark = "-";
if(j==8 || j == 17)mark = "|";
row = i/5;
col = j/9;
type = someBoard[row][col];
if(type == "X"){
if( ((i%5 == 1 || i%5 == 3) &&
(j%9 == 3 || j%9 == 5)) ||
(i%5 == 2 &&
j%9 == 4))mark = "X";
}else if(type == "O"){
if( ((i%5 == 1 || i%5 == 3) &&
(j%9 == 3 || j%9 == 4 || j%9 == 5)) ||
((i%5 == 2) &&
(j%9 == 3 || j%9 == 5))) mark = "O";
}else{
if( i%5 == 2 && j%9 == 4){
mark = ((Integer)(row * 3 + col)).toString();
}
}
System.out.print(mark);
}
System.out.println();
}
System.out.println("\n\n\n");
}
public boolean checkMove(Integer move){
boolean goodMove = false;
for(Integer available : availableMoves){
if (available == move) goodMove = true;
}
return goodMove;
}
public int score(String[][] newBoard){
int row;
int newCol;
int score = 0;
for (int strategy = 0; strategy < 8; strategy++){
score = 0;
for (int col = 0; col < 3; col++){
if(strategy < 3){ //rows
row = strategy ;
newCol = col;
}else if (strategy < 6){ //cols
row = col;
newCol = strategy - 3;
}else{//diag
int diag = strategy - 6;
row = col - 2 * diag * (col - 1);
newCol = col;
}
if(newBoard[row][newCol].equals("X")){
score+=5;
}else if(newBoard[row][newCol].equals("O")){
score+=-5;
}
}
score = (Math.abs(score)== 15) ? score : 0;
if(Math.abs(score) == 15) break;
}
return score;
}
public String[][] copyBoard(String[][] originalBoard){
String[][] duplicateBoard = new String[boardRowDim][boardColDim];
for (int i = 0;i < boardRowDim; i++){
for(int j = 0; j < boardColDim; j++){
duplicateBoard[i][j] = originalBoard[i][j];
}
}
return duplicateBoard;
}
public String[][] updateBoard(Integer move, String mark, String[][]oldBoard){
String[][] currentBoard = new String[boardRowDim][boardColDim];
int[] cell2D = new int[2];
currentBoard = copyBoard(oldBoard);
cell2D = single2Double(move);
currentBoard[cell2D[0]][cell2D[1]] = mark;
return currentBoard;
}
public ArrayList<Integer> copyAvailableMoves(ArrayList<Integer> originalAvailableMoves){
ArrayList<Integer> duplicateAvailableMoves = new ArrayList<Integer>();
for(int i = 0; i < originalAvailableMoves.size();i++){
duplicateAvailableMoves.add(originalAvailableMoves.get(i));
}
return duplicateAvailableMoves;
}
public ArrayList<Integer> updateAvailableMoves(Integer move, ArrayList<Integer> oldAvailableMoves){
ArrayList<Integer> currentAvailableMoves = new ArrayList<Integer>();
currentAvailableMoves = copyAvailableMoves(oldAvailableMoves);
currentAvailableMoves.remove(move);
return currentAvailableMoves;
}
public String[][] seedBoard(){
String[][] sampleBoard ={{"0","O","X"},{"X","4","O"},{"6","7","X"}};
//String[][] sampleBoard ={{"X","O","O"},{"3","4","X"},{"6","7","8"}};
return sampleBoard;
}
public ArrayList<Integer> seedAvailable(String[][] seedBoard){
ArrayList seedMoves = new ArrayList<Integer>();
int index = -1;
for(int i = 0; i < 3;i++){
for (int j = 0; j < 3; j++){
if(!seedBoard[i][j].equals("X") && !seedBoard[i][j].equals("O")){
index = i*3 + j;
seedMoves.add(index);
}
}
}
return seedMoves;
}
public int[] findBestMove(String[][] currentBoard, ArrayList<Integer> currentAvailableMoves,boolean currentComputerMoves,int depth,Scanner kboard){
ArrayList<Integer> simulateAvailableMoves = new ArrayList<Integer>();
String[][] simulateBoard = new String[boardRowDim][boardColDim];
int[] scoreMove = new int[2]; //return array with score and associated move
int[] cell2D = new int[2]; //array holding i and j of board to place Mark (X or O)
int computerTargetScore = (computerMark.equals("X")) ? 15:-15;
int[][] scoreMoveAvailable = new int[currentAvailableMoves.size()][2];
Integer simulateMove = null; //current move inside loop
Boolean simulateComputerMoves = null;
for(int i = 0; i < currentAvailableMoves.size(); i++){
scoreMoveAvailable[i][0] = 0; //score
scoreMoveAvailable[i][1] = -1; // square 0 - 8
}
for (int i = 0; i < currentAvailableMoves.size() ;i++){
simulateAvailableMoves = copyAvailableMoves(currentAvailableMoves);
simulateBoard = copyBoard(currentBoard);
simulateComputerMoves = currentComputerMoves;
simulateMove = simulateAvailableMoves.get(i);
simulateAvailableMoves = updateAvailableMoves(simulateMove,simulateAvailableMoves);
cell2D = single2Double(simulateMove);
if(simulateComputerMoves){
simulateBoard[cell2D[0]][cell2D[1]] = computerMark;
simulateComputerMoves = false;
if(score(simulateBoard) == computerTargetScore || simulateAvailableMoves.size() == 0){
scoreMove[0] = score(simulateBoard);
scoreMove[1] = simulateMove;
}else{
depth++;
scoreMove = findBestMove(simulateBoard,simulateAvailableMoves,simulateComputerMoves,depth,kboard);
}
}else{
simulateBoard[cell2D[0]][cell2D[1]] = playerMark;
simulateComputerMoves = true;
if(score(simulateBoard) == (-computerTargetScore) || simulateAvailableMoves.size() == 0){
scoreMove[0] = score(simulateBoard);
scoreMove[1] = simulateMove;
}else{
depth++;
scoreMove = findBestMove(simulateBoard,simulateAvailableMoves,simulateComputerMoves,depth,kboard);
}
}
scoreMoveAvailable[i][0] = scoreMove[0] ;
scoreMoveAvailable[i][1] = simulateMove;
}
int[] bestScoreMove = new int[2];
bestScoreMove[0] = scoreMoveAvailable[0][0]; //set bestScoreMove to first element in arraylist
bestScoreMove[1] = scoreMoveAvailable[0][1];
if( (currentComputerMoves && computerMark.equals("X") ) || (!currentComputerMoves && computerMark.equals("O") ) ) {
for (int i = 0; i < scoreMoveAvailable.length;i++){
if(scoreMoveAvailable[i][0] > bestScoreMove[0]){
bestScoreMove[0] = scoreMoveAvailable[i][0] ;
bestScoreMove[1] = scoreMoveAvailable[i][1];
}
}
}else{
for (int i = 0; i < scoreMoveAvailable.length;i++){
if(scoreMoveAvailable[i][0] < bestScoreMove[0]){
bestScoreMove[0] = scoreMoveAvailable[i][0] ;
bestScoreMove[1] = scoreMoveAvailable[i][1];
}
}
}
return bestScoreMove;
}
/*
* just some static methods to help make things easy
*/
public static void printHeader(){
System.out.println("u000C Welcome to TicTacToe\n" +
" where you can match wits\n" +
" against the computer\n" +
"(the real challenge is making it a draw)\n");
}
/*
* the next 2 methods convert the index of a double array to a single array
* and the index of a single array to a double array
*/
public static int double2single(int row, int col){
int singleCell = 0;
singleCell = boardRowDim * row + col;
return singleCell;
}
public static int[] single2Double(int cell){
int[] cell2D = new int[2];
cell2D[0] = cell / boardColDim;
cell2D[1] = cell % boardColDim;
return cell2D;
}
public static String capitalize(String word){
word = word.substring(0,1).toUpperCase() + word.substring(1);
return word;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-05T21:17:30.590",
"Id": "428954",
"Score": "1",
"body": "I wrote this for my high school class where we are using blueJ. I can use eclipse too"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-05T21:20:42.590",
"Id": "428957",
"Score": "0",
"body": "Well, I've done some stuff in SAS, html, css, javascript, c, and php but I'm not really an expert at any of them"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-05T21:21:42.397",
"Id": "428958",
"Score": "0",
"body": "It's visible in the code that you implemted something else before :-) That's why I ask."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-05T21:22:12.947",
"Id": "428959",
"Score": "0",
"body": "I hope that's a good thing. I did the CS50 edX course from Harvard a few years ago"
}
] | [
{
"body": "<p>Sorry, but that someone is probably right. At the same time, thanks for being thus brave and asking on how to improve here.</p>\n\n<p>It's not so simple to give feedback in such a scenario, since there are so many details that go \"wrong\". Since you tagged this for beginner, I'll focus on things that will benefit you most as well as things you can easily adapt. You might want to apply some of these to see how your code becomes more and more readable.</p>\n\n<h3>Designing</h3>\n\n<p>When thinking about the software (don't forget to do that before coding), write down some sentences in prose English that describe the game. Let me give an example:</p>\n\n<blockquote>\n <p>TicTacToe is a game played by two players. They play on a square 3x3 sized board. In an alternating manner, player 1 puts an X onto a cell and player 2 puts an O onto a cell. Only one sign is allowed per cell. The game ends when the first player has 3 contiguous of his own signs in any direction (horizontal, vertical, diagonal)</p>\n</blockquote>\n\n<p>Find the subjects in these sentences. Each one is a candidate for a class. We have <code>Game</code>, <code>Player</code>, <code>Board</code>, <code>Cell</code>, <code>Sign</code>, <code>Direction</code>.</p>\n\n<p>Next, find out what each of these could be doing (methods) and what data it needs to do that (members). <code>Game</code> might hold the rules, e.g. alternating the players and ending the game. <code>Player</code> could have the name of the player and the sign and perhaps a statistic of wins versus looses. <code>Board</code> might not do a lot, but it needs to hold the data (empty cells, full cells, size). <code>Sign</code> is just <code>X</code> or <code>O</code> - perhaps not enough to recitify a class. <code>Direction</code> could hold masks for all 8 ways to get a win.</p>\n\n<p>It'll be a long way to go from the current code to 4 classes. This really is a hint for your next project or a complete rewrite.</p>\n\n<h3>IDE</h3>\n\n<p>Use a real IDE. It's clearly visible that your IDE (BlueJ) did not help you write good code.</p>\n\n<p>A good IDE will give you hints about</p>\n\n<ul>\n<li>unused variables</li>\n<li>unnecessary imports</li>\n<li>typos</li>\n<li>redundant initializers</li>\n<li>simplification of boolean expressions</li>\n<li>invalid <code>String</code> comparisons</li>\n<li>unnecessary public access to methods</li>\n<li>prefer primitive types</li>\n<li>move assignments to declaration</li>\n<li>join declaration and assignment</li>\n<li>replace for loops by foreach loops</li>\n</ul>\n\n<p>I'll not go into details with any of these, because it's usually not necessary to do a review on those, because the IDE does the review for me (or you).</p>\n\n<p>You can learn a lot from the hints of the IDE alone. And it will make review easier for us. </p>\n\n<p>In this review, I'll tell you a bit about IntelliJ.</p>\n\n<h3>Size of the class</h3>\n\n<p>Your code has 450 lines. Some people would say it's ok and fits the rule of 30. Others, including me, would like to see classes <a href=\"https://softwareengineering.stackexchange.com/a/66598/109304\">with about 200 lines</a>. Assuming that this code would split up evenly with the 4 classes mentioned in the designing chapter, that's ~ 110 lines each. That would be great!</p>\n\n<p>Why does size matter? If a method is very long, it does probably more than one thing. If a class is too big, it likely has too many reasons for change.</p>\n\n<p>One file (which is one class in Java) is often the smalles unit a developer needs to read in order to understand something. Reading and understanding 450 lines is a lot and I'd better not be interrupted during that time.</p>\n\n<p>What can easily be separated here?</p>\n\n<p>A <code>Main</code> class which only contains the <code>main()</code> method. Some call it <code>Application</code> or <code>Program</code>. You could also name it <code>TicTacToe</code>. That <code>main()</code> method will wire up all other parts, so it does <strong>integration</strong> work.</p>\n\n<p>How would you do that? Don't do it manually. Assuming IntelliJ as the IDE, right click the main method and choose <code>Refactor / Move</code>. Then enter <code>Main</code> as the class name and ignore the fact that it's red. The class will be created when you click <code>Refactor</code>.</p>\n\n<p>The method <code>drawBoard()</code> seems to do drawing only. You could move it to a <code>Board</code> class.</p>\n\n<p>The method <code>capitalize()</code> is used in <code>main()</code> only. It can be moved to the <code>Main</code> class.</p>\n\n<h3>Remove dead code</h3>\n\n<p>Applying all the IDE suggestions will reveal dead code at this point:</p>\n\n<pre><code>boolean toSeed = false;\n if(toSeed){\n ...\n }\n</code></pre>\n\n<p>You can get rid of 22 lines (5%) immediately.</p>\n\n<p>How would you do that? Don't do it manually. Click on the condition. Press <code>Alt+Enter</code> to access the quick tip light bulb. Choose <code>Remove if statement</code>.</p>\n\n<p>You'll then find that <code>updateBoard()</code> and <code>seedBoard()</code> and <code>seedAvailable()</code> are unused. Similar, use <code>Remove unused method</code>. Again 30 lines (6%) less reading.</p>\n\n<p>Also: delete all commented code without thinking.</p>\n\n<h3>Naming</h3>\n\n<p>What is <code>Shortver</code>? Is that in contrast to <code>Longver</code>?</p>\n\n<p>Do you see how class names <code>TicTacToe</code>, <code>Game</code>, <code>Player</code> and <code>Board</code> tell me so much more about what the program is about in comparison to <code>Shortver</code>?</p>\n\n<p>Example: at what time do I figure out what the code is about? In line 440, the code mentions the term \"TicTacToe\" for the first time. Usually people read top to bottom, so that's very late.</p>\n\n<p>How would you rename that? Don't do it manually. Right click the class name <code>Shortver</code>, choose <code>Refactor / Rename</code> and give it at least a slightly better name, following the <a href=\"http://arlobelshee.com/good-naming-is-a-process-not-a-single-step/\" rel=\"noreferrer\">6 steps of naming</a>.</p>\n\n<h3>Too many empty lines</h3>\n\n<p>Use empty lines for separating things. Using empty lines you can create paragraphs. Paragraphs will help the reader understand what code belongs together and where something new starts.</p>\n\n<p>Paragraphs will help you finding methods to extract (example later).</p>\n\n<h3>Remove nonsense comments</h3>\n\n<p>Like </p>\n\n<pre><code>/*\n * just some static methods to help make things easy\n */\n</code></pre>\n\n<p>Hopefully every method in your code does something useful and makes things easier.</p>\n\n<h3>Size of methods</h3>\n\n<p>You can reduce the size of methods by extracting smaller methods. Example:</p>\n\n<pre><code>if(score(board) == gameTargetScore) {\n System.out.println(playerName + \" you are too good for me. \\n\" +\n \"Congratulations you won!!\\n\\n\");\n} else if(score(board) == -gameTargetScore) {\n System.out.println(\"IWONIWONIWONohboyIWONIWONIWON\");\n} else if(draw) {\n System.out.println(\"Good game. It's a draw!\");\n}\n</code></pre>\n\n<p>That would make an excellent method <code>printGameEndMessage()</code>.</p>\n\n<p>How would you do that? Don't do it manually. Mark all of these lines, right click, choose <code>Refactor / Extract / Method</code>.</p>\n\n<p>Another example:</p>\n\n<pre><code> if(humanGoes){\n ...\n }else{\n ...\n }\n</code></pre>\n\n<p>The code inside the if block would make up a method <code>humanMove()</code> and the code in the else block goes into <code>computerMove()</code>.</p>\n\n<p>That way, you end up with a short 30 line method <code>playGame()</code>.</p>\n\n<h3>Bugs</h3>\n\n<p>In <code>drawBoard()</code>, you're doing string comparison with the <code>==</code> operator. IMHO this only accidentally works due to string interning. The correct way is to use <code>.equals()</code>.</p>\n\n<p>To me that was an indicator that you might have been a <a href=\"/questions/tagged/beginner\" class=\"post-tag\" title=\"show questions tagged 'beginner'\" rel=\"tag\">beginner</a> on Java and you have probably worked with a language before that allowed string comparisons with <code>==</code>. (I asked both questions in the comments)</p>\n\n<h3>Magic numbers</h3>\n\n<p>When we find numbers in code that don't have a name, we call them \"magic numbers\", because they don't have an explanation.</p>\n\n<p>If the number 3.14 is in your code without the name <code>pi</code>, do you know that should be <code>pi</code> or it's just 3.14000?</p>\n\n<p>One of these methods is <code>drawBoard()</code>. All that <code>i</code> and <code>j</code> and numbers... Which one is a column, which one is a line? But then there is <code>row</code> and <code>col</code>, argh ...!</p>\n\n<p>Rename <code>i</code> to <code>consoleRow</code>, <code>j</code> to <code>colsoleColumn</code>, <code>row</code> to <code>boardRow</code>, <code>col</code> to <code>boardColumn</code>.</p>\n\n<p>Change 15 to 3*5. Change 27 to 3*9. This will make it more clear that we still have a 3*3 board. Change 10 to 2*5. Change 8 to 9-1. Change 17 to 2*9-1.</p>\n\n<p>That way you have less different numbers and it's easier to guess their meaning.</p>\n\n<h3>Conclusion</h3>\n\n<p>After about 2 hour of working on your code, I slowly begin to understand what it does. </p>\n\n<p>I reduced from 460 lines of code to 28 + 53 + 275 = 357 lines (in 3 classes).</p>\n\n<p>At this point I would need a few more advanced changes, since I need to remove duplicate code. I still don't understand the 80 lines method <code>findBestMove()</code>.</p>\n\n<p>So, that's pretty bad for a simple game like TicTacToe - but hey, I probably wrote worse code when I was your age. Nothing to worry about. Keep on learning. Keep on asking. Embrace feedback. Do pair programming.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T14:16:57.807",
"Id": "429039",
"Score": "1",
"body": "Thomas, this was really helpful, thank you. I will rewrite and repost,"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-05T23:09:54.003",
"Id": "221754",
"ParentId": "221744",
"Score": "9"
}
}
] | {
"AcceptedAnswerId": "221754",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-05T20:11:43.580",
"Id": "221744",
"Score": "7",
"Tags": [
"java",
"beginner",
"tic-tac-toe",
"ai"
],
"Title": "Minimax implementation of tic tac toe"
} | 221744 |
<p>I have a set of nested functions that I need to call multiple times. I know <code>scipy.quad</code> is pretty fast, but I will need to call the integrator recursively and want to remove as much overhead as possible.</p>
<p>I know I need to pre-allocate the arrays for some of the base functions at the bottom half of the code to get a speed up (the functions <code>rvec</code>, and below). However, my integration classes look like they can be optimized and I am puzzled as to how to go about this. Basically, I am preloading two vectors: <code>weights</code> and <code>abscissas</code> — which I will use for my <code>Integrator</code> class — these vectors are a constant and will never change.
I have a class <code>INorm</code> that inherits from <code>Integrator</code> and a class <code>klRatio</code> that inherits from <code>INorm</code>. I think I need to use the <code>__cinit__</code> function for the class initializations, but I am not sure the best way to go about this.</p>
<p>EDIT: I'm writing out Math Jax equations for all of the functions in a way that should match the code.</p>
<pre><code>#!python
#cython: boundscheck=False
#cython: cdivision=True
#cython: wraparound=False
import numpy as np
cimport numpy as np
cimport cython
from libc.math cimport sinh, cosh, sin, cos, sqrt, fabs, M_PI, floor, fmax, log
import h5py as h5
# C Math constants and functions
cdef double pi = float(3.141592653589793)
cdef extern from "complex.h":
double complex exp(double complex)
cdef extern from "complex.h":
double cabs(double complex)
cdef double[:] Abscissas2048
cdef double[:] Weights2048
with h5.File('LobattoNodes2048.h5','r') as hf:
Abscissas2048 = hf['Abscissas'][:]
Weights2048 = hf['Weights'][:]
# lobatto integrator
cdef class Integrator:
cdef double[:] abscissas
cdef double[:] weights
cdef int numEval
def __init__(self):
self.abscissas = Abscissas2048
self.weights = Weights2048
self.numEval = 2048
cdef double function(self,double x) except? 0.0:
raise NotImplementedError()
cdef double lobatto(self, double leftA, double rightB):
cdef double ax,dx,q
cdef int ii
ax = (leftA+rightB)/2.0
dx = (rightB-leftA)/2.0
cdef int startC = <unsigned int> self.numEval & <unsigned int> 0x1
cdef int endC = int((self.numEval+startC)/2)
q = startC*self.weights[0]*self.function(ax)
for ii in range(startC,endC):
q += self.weights[ii]*(self.function(ax-dx*self.abscissas[ii])
+ self.function(ax+dx*self.abscissas[ii]))
return q*dx
cdef class INorm(Integrator):
cdef double leftB,rightB,Norm
cdef double[:,:] Pts
cdef double R,k,N
def __init__(self, double[:,:] Pts, double R, double k, int flag):
Integrator.__init__(self)
self.Pts = Pts
self.N = len(Pts)
self.R = R
self.k = k
self.leftB = 0.0
self.rightB = 2*pi
self.Norm = 1.0
if flag == 1:
self.updateNorm()
cdef double function(self, double theta) except? 0.0:
return self.R*Intensity(self.Pts, theta, self.R, self.k)/self.Norm
cdef double updateNorm(self):
self.Norm *= self.lobatto(self.leftB,self.rightB)
return 0.0
cdef class klRatio(INorm):
cdef double[:,:] Pts1,Pts2
cdef INorm N1
cdef INorm N2
cdef double KLoss, RingScore
def __init__(self, double[:,:] Pts1, double[:,:] Pts2, double R, double k):
INorm.__init__(self,Pts1, R, k,0)
self.N1 = INorm(Pts1,R,k,1)
self.N2 = INorm(Pts2,R,k,1)
self.KLoss = self.lobatto(self.leftB,self.rightB)
self.RingScore = fabs(log(self.N1.N/self.N2.N)) + self.KLoss
#print(self.RingScore)
cdef double function(self, double theta) except? 0.0:
return self.N1.function(theta)*log(self.N1.function(theta)
/self.N2.function(theta))
def get_RingScore(self):
return self.RingScore
# radial vectors of points from a position theta along the ring
cdef double[:] rvec(double[:,:] Pts, double theta, double R, Py_ssize_t N):
cdef int ii
cdef double [:] rvec = np.zeros(N)
for ii in range(0,N):
rvec[ii] = (R-Pts[ii,0]*cos(theta)
-Pts[ii,1]*sin(theta))
return rvec
# distance squared of points from a position theta along the ring
cdef double[:] r2Distance(double[:,:] Pts, double theta, double R, Py_ssize_t N):
cdef int ii
cdef double [:] r2 = np.zeros(N)
cdef double rx,ry
for ii in range(0,N):
rx = R*cos(theta)-Pts[ii,0]
ry = R*sin(theta)-Pts[ii,1]
r2[ii] = rx*rx + ry*ry
return r2
# Amplitude has to be normal vector to surface!
cdef double[:] Amplitude(double[:,:] Pts, double theta, double R, Py_ssize_t N):
cdef int ii
cdef double[:] numerator = rvec(Pts,theta,R,N)
cdef double[:] denominator = r2Distance(Pts,theta,R,N)
cdef double[:] Amp = np.zeros(N)
for ii in range(0,N):
Amp[ii] = sqrt(numerator[ii]/denominator[ii]/2/pi)
return Amp
# Phase returns an N vector of complex numbers
cdef double complex[:] Phase(double[:,:] Pts, double theta, double R, double k, Py_ssize_t N):
cdef int ii
cdef double[:] xComp = np.zeros(N)
cdef double[:] yComp = np.zeros(N)
cdef double complex[:] Pout = np.zeros(N,dtype=np.cdouble)
for ii in range(0,N):
xComp[ii] = (R*cos(theta)-Pts[ii,0])*cos(theta)
yComp[ii] = (R*sin(theta)-Pts[ii,1])*sin(theta)
Pout[ii] = exp(1j*k*(xComp[ii]+yComp[ii]))
return Pout
# Intensity, top level function to be integrated in classes
cdef double Intensity(double[:,:] Pts, double theta, double R, double k):
cdef size_t N
N = Pts.shape[0]
cdef double[:] Amplitudes = Amplitude(Pts,theta,R,N)
cdef double complex[:] Phases = Phase(Pts,theta,R,k,N)
# pull out probability amplitudes as bras and kets
cdef double complex bra=0
cdef double complex ket
cdef int ii
cdef double Int
for ii in range(0,N):
bra += Amplitudes[ii]*Phases[ii]
ket = bra.conjugate()
Int = cabs(bra*ket)
return Int
</code></pre>
<p>The code is tested with something like this:</p>
<pre><code>a = np.random.randn(30,2)/4
b = np.random.randn(30,2)/4
b[0:20,:] = a[0:20,:] # make some similarity among clusters
R = 1
k = 4*np.pi/R
zz = klRatio(a,b,R,k)
print(zz.get_RingScore)
</code></pre>
<p>OK, I'm going to stick with the scope of this code. Once I optimize this, I need to add another upper level so it's likely I'll be calling the quadrature operation a few hundred times, so getting it as fast as possible in Cython would be really nice. The theory specifically for the problem above:</p>
<p>The problem: There are two sets of 2-D coordinates, and we would like to measure how similar they are in a structural manner.</p>
<p>The solution: Solve for a modified KL-Divergence between two hypothetical radiation patterns given the provided coordinate information and measurement parameters.</p>
<p>We have two sets of coordinates <span class="math-container">\$ P \$</span> and <span class="math-container">\$ Q \$</span> with <span class="math-container">\$ n \$</span> and <span class="math-container">\$ m \$</span> member coordinates, respectively. There exists a normalizeable mapping function <span class="math-container">\$ I(P,\theta,R,k) \$</span> such that <span class="math-container">\$ \int I(P,\theta,R,k) R d\theta \propto 1\$</span>. Here we have defined our measurement parameters in polar coordinates, where <span class="math-container">\$ R \$</span> is the radius of a ring shaped detector, <span class="math-container">\$ \theta \$</span> is a relative angle along the ring to some reference point, and k is the frequency of the radiation.</p>
<p>Since <span class="math-container">\$ I() \$</span> is normalizeable, we could effectively use the KL-divergence to a provide a quantitative divergence score. Since <span class="math-container">\$ P \$</span> and <span class="math-container">\$ Q \$</span> may have a different number of coordinates, the respective intensity measurements should scale accordingly to factor in this information. Without derivation, I include a symmetric penalty term for the loss function so that my modified KL-divergence, which I'll denote by the variable <span class="math-container">\$ K \$</span>:</p>
<p><span class="math-container">\$ K = |\ln(n/m)| + \int R d\theta \tilde{I}(P,\theta,R,k) * \ln \frac{\tilde{I}(P,\theta,R,k)}{\tilde{I}(Q,\theta,R,k)} \$</span> </p>
<p>That is the final term that I wish to compute. To get to that term, I need to compute a normalized intensity: <span class="math-container">\$ \tilde{I}(P,\theta,R,k)) = \frac{I(P,\theta,R,k)}{\int R d\theta I(P,\theta,R,k)}\$</span>. Since the intensity pattern is along a closed ring, the integral is closed at the end points (<span class="math-container">\$0\$</span> and <span class="math-container">\$2 \pi \$</span>), I went with Lobatto integration. In the code above, I am starting with 2048 point integration but I will probably reduce the count when I incorporate the error estimate later.</p>
<p>The Intensity can be described from the direct measurement of probability amplitudes with sources defined by the <span class="math-container">\$ P \$</span> coordinates such that:
<span class="math-container">\$ I(P,\theta,R,k) = \Psi(P,\theta,R,k)^{\dagger} \Psi(P,\theta,R,k) \$</span>.</p>
<p>The probability amplitude given <span class="math-container">\$P\$</span> is defined as
<span class="math-container">\$ \Psi(P,\theta,R,k) = \sum^n_{i=1} A(P_i,\theta,R) \phi(P_i, \theta, R, k) \$</span>.
The probability amplitude is complex, so it is described with an Amplitude <span class="math-container">\$ A() \$</span> and a phase <span class="math-container">\$ \phi() \$</span>.</p>
<p>Where <span class="math-container">\$ A(P_i,\theta,R) = \sqrt{\frac{R-x_i cos(\theta) - y_i sin(\theta)}{2 \pi ((R*cos(\theta)-x_i)^2 + (R*sin(\theta)-y_i)^2})} \$</span>. The amplitude term is the square root of the normal component <span class="math-container">\$\hat{R}\$</span> of the DC electric field in 2D. Here each coordinate member <span class="math-container">\$ P_i = {x_i,y_i} \$</span> is provided in the Cartesian system and is entirely enclosed within a radial distance <span class="math-container">\$ R \$</span>. The code is not expected to work if the points are not enclosed.</p>
<p>The phase is defined as <span class="math-container">\$ \phi(P_i,\theta,R,k) = \mathrm{exp}[\mathcal{i} k (R-x_i cos(\theta) - y_i sin(\theta)) ] \$</span> The last part of the phase term is the dot product between the wave propagation vector and the normal component unit vector <span class="math-container">\$ \hat{R} \$</span> (normal to the circular ring).</p>
<p>That covers all the functions, more or less. My goal here is to be able to calculate several hundred kl-divergences in a reasonable amount of time as this is just one component in a larger algorithm. Thanks.</p>
<p>EDIT: In the future, I will have modified intensity/phase functions with an extra term and I will have to calculate a matrix of KL-divergences in order to deal with varying sub populations of structures. The number of integrations required will scales O(n^2) with this approach -- but dealing with 20 sub populations for each set, ~800 integrations is kind of a target I'd like to set for myself. The math is worked out for the sub population problem, I'm just trying to optimize all the simpler functions now before I re-work the larger problem. Thanks.</p>
<p>EDIT: For completeness, I'm adding the code for generating the lobatto weights and abscissas below:</p>
<pre><code>import numpy as np
import h5py as h5
r8_epsilon = 2.220446049250313E-016
def r8vec_diff_norm_li ( n, a, b ):
value = 0.0
for i in range ( 0, n ):
value = max ( value, abs ( a[i] - b[i] ) )
return value
def r8vec_reverse ( n, a1 ):
a2 = np.zeros ( n )
for i in range ( 0, n ):
a2[i] = a1[n-1-i]
return a2
def getWeightsAbscissas(N):
A = np.zeros(N)
W = np.zeros(N)
if (N == 1):
A[0] = -1.0
W[0] = 2.0
return A, W
tol = 100 * r8_epsilon
for ii in range(0,N):
A[ii] = np.cos(np.pi * ii / (N-1))
Aold = np.zeros(N)
p = np.zeros([N,N])
while(True):
for ii in range(0,N):
Aold[ii] = A[ii]
for ii in range(0,N):
p[ii,0] = 1.0
p[ii,1] = A[ii]
for jj in range(2,N):
for ii in range(0,N):
p[ii,jj] = ((2*jj-1)*A[ii]*p[ii,jj-1]
+ (-jj+1)*p[ii,jj-2]) / jj
for ii in range(0,N):
A[ii] = Aold[ii] - (A[ii]*p[ii,N-1] - p[ii,N-2]) / (N*p[ii,N-1])
dif = r8vec_diff_norm_li(N,A,Aold)
if (dif <= tol): break
A = r8vec_reverse(N,A)
for ii in range(0,N):
W[ii] = 2.0/ (N*(N-1)*p[ii,N-1]**2)
return A,W
# write out weights and abscissas into an hdf5 file for pre-cached use
def WriteOutWA(N):
Ab,Wb = getWeightsAbscissas(N)
midPoint = int(np.floor(N/2))
Abscissas = Ab[midPoint:]
Weights = Wb[midPoint:]
# write out the h5 file
fileName = 'LobattoNodes{}.h5'.format(N)
h5f = h5.File(fileName,'w')
h5f.create_dataset("Abscissas", data=Abscissas)
h5f.create_dataset("Weights", data=Weights)
h5f.create_dataset("N", data=N)
h5f.close()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-05T22:23:07.207",
"Id": "428960",
"Score": "0",
"body": "Welcome to Code Review! You could probably make this a better question if you also add the describe the calculation that the code is performing with mathematical notation, using MathJax."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-05T21:46:15.217",
"Id": "221748",
"Score": "7",
"Tags": [
"numpy",
"numerical-methods",
"cython"
],
"Title": "Numerical integration in cython"
} | 221748 |
<p>SQL Server 2016 introduced some JSON features, but they're far from robust. As far as I can tell, there's <a href="https://stackoverflow.com/questions/37494211/sql-server-2016-for-json-output-integer-array">no way yet to output a simple array</a>; everything must be in <code>"key": "value"</code> format. I <em>don't</em> want to do what some answers propose and write a partial JSON encoder within SQL.</p>
<p>Therefore, I'm stripping out certain keys in the Python side of my program.</p>
<p>SQL statement (I'd tag this with PowerCampus, the ERP product, if the tag existed):</p>
<pre><code>SELECT SECTIONS.EVENT_ID
,SECTIONS.EVENT_LONG_NAME
,SECTIONS.ACADEMIC_YEAR
,SECTIONS.ACADEMIC_TERM
,SECTIONS.ACADEMIC_SESSION
,SECTIONS.EVENT_SUB_TYPE
,SECTIONS.SECTION
,TRANSCRIPTDETAIL.PEOPLE_CODE_ID
FROM [SECTIONS]
INNER JOIN [TRANSCRIPTDETAIL]
ON TRANSCRIPTDETAIL.EVENT_ID = SECTIONS.EVENT_ID
AND TRANSCRIPTDETAIL.ACADEMIC_YEAR = SECTIONS.ACADEMIC_YEAR
AND TRANSCRIPTDETAIL.ACADEMIC_TERM = SECTIONS.ACADEMIC_TERM
AND TRANSCRIPTDETAIL.ACADEMIC_SESSION = SECTIONS.ACADEMIC_SESSION
AND TRANSCRIPTDETAIL.EVENT_SUB_TYPE = SECTIONS.EVENT_SUB_TYPE
AND TRANSCRIPTDETAIL.SECTION = SECTIONS.SECTION
AND TRANSCRIPTDETAIL.ADD_DROP_WAIT = 'A'
WHERE SECTIONS.ACADEMIC_YEAR = '2019'
AND SECTIONS.ACADEMIC_TERM = 'SPRING'
FOR JSON AUTO
</code></pre>
<p>JSON output:</p>
<pre><code>[
{
"SectionId": "ENG101",
"LongName": "English 102",
"AcademicYear": "2019",
"AcademicTerm": "SPRING",
"AcademicSession": "01",
"SubType": "LEC",
"Section": "ABC",
"Students": [
{
"PeopleCodeId": "P000111602"
},
{
"PeopleCodeId": "P000109552"
},
{
"PeopleCodeId": "P000110652"
},
{
"PeopleCodeId": "P000111872"
},
{
"PeopleCodeId": "P000111772"
},
{
"PeopleCodeId": "P000111802"
},
{
"PeopleCodeId": "P000111792"
},
{
"PeopleCodeId": "P000111722"
},
{
"PeopleCodeId": "P000111802"
},
{
"PeopleCodeId": "P000111442"
}
]
},
{
"EVENT_ID": "ENG101",
"EVENT_LONG_NAME": "English 102",
"ACADEMIC_YEAR": "2019",
"ACADEMIC_TERM": "SPRING",
"ACADEMIC_SESSION": "01",
"EVENT_SUB_TYPE": "LEC",
"SECTION": "ABC",
"TRANSCRIPTDETAIL": [
{
"PEOPLE_CODE_ID": "P000112582"
},
{
"PEOPLE_CODE_ID": "P000113022"
},
{
"PEOPLE_CODE_ID": "P000113062"
},
{
"PEOPLE_CODE_ID": "P000112152"
},
{
"PEOPLE_CODE_ID": "P000112212"
},
{
"PEOPLE_CODE_ID": "P000112812"
},
{
"PEOPLE_CODE_ID": "P000112662"
},
{
"PEOPLE_CODE_ID": "P000112072"
},
{
"PEOPLE_CODE_ID": "P000112222"
},
{
"PEOPLE_CODE_ID": "P000112442"
}
]
}
]
</code></pre>
<p>My Python function correctly collapses the PEOPLE_CODE_ID's into a simple array:</p>
<pre><code>[
{
"SectionId": "ENG101",
"LongName": "English 102",
"AcademicYear": "2019",
"AcademicTerm": "SPRING",
"AcademicSession": "01",
"SubType": "LEC",
"Section": "ABC",
"Students": [
"P000111602",
"P000109552",
"P000110652",
"P000111872",
"P000111772",
"P000111802",
"P000111792",
"P000111722",
"P000111802",
"P000111442"
]
},
{
"EVENT_ID": "ENG101",
"EVENT_LONG_NAME": "English 102",
"ACADEMIC_YEAR": "2019",
"ACADEMIC_TERM": "SPRING",
"ACADEMIC_SESSION": "01",
"EVENT_SUB_TYPE": "LEC",
"SECTION": "ABC",
"TRANSCRIPTDETAIL": [
"P000112582",
"P000113022",
"P000113062",
"P000112152",
"P000112212",
"P000112812",
"P000112662",
"P000112072",
"P000112222",
"P000112442"
]
}
]
</code></pre>
<p>Here's the function:</p>
<pre><code>def clean_sql_json(x):
"""Cleans up JSON produced by SQL Server by reducing this pattern:
[{"Key": [{"Key": "Value"}]}]
to this:
[{'Key': ['Value']}]
Also removes duplicates (and ordering) from the reduced list.
"""
data = json.loads(x)
for k in data:
for kk, vv in k.items():
if type(vv) == list and type(vv[0] == dict) and len(vv[0]) == 1:
newlist = [kkk[list(vv[0].keys())[0]] for kkk in vv]
data[data.index(k)][kk] = list(set(newlist))
return data
</code></pre>
<p>I'm a little concerned about the Python. Is it safe to modify and return <code>data</code> on the fly like this?</p>
| [] | [
{
"body": "<ul>\n<li><code>type(x) == y</code> is unidiomatic, and prone to errors. Use <code>isinstance(x, y)</code> instead.</li>\n<li>Your variable names aren't great. <code>k</code>, <code>kk</code>, <code>kkk</code>, <code>vv</code>.</li>\n<li>You can simplify changing the data. <code>data[data.index(k)] == k</code>.</li>\n<li>You can simplify <code>kkk[list(vv[0].keys())[0]]</code> to <code>list(kkk.values())[0]</code>.</li>\n<li>You can simplify <code>set([...])</code> with a set comprehension <code>{...}</code>.</li>\n<li>Your function looks like a hack. I wouldn't want this to reach production.</li>\n</ul>\n\n<pre><code>def clean_sql_json(x):\n datas = json.loads(x)\n\n for data in datas:\n for key, value in data.items():\n if (isinstance(value, list)\n and isinstance(value[0], dict)\n and len(value[0]) == 1\n ):\n data[key] = list({\n list(item.values())[0]\n for item in value\n })\n\n return datas\n</code></pre>\n\n<p>The way I'd further improve this is:</p>\n\n<ol>\n<li>Create a wrapper that eased walking the JSON tree.</li>\n<li>Walk the tree. When a list is found check if <em>all</em> it's children are dictionaries with one item.</li>\n<li>Reduce the dictionaries, like you are now.</li>\n</ol>\n\n<p>This would have the benefit that it can work on any and all values you give it. However it would be overkill if this is the only time you are doing this.</p>\n\n<blockquote>\n <p>I'm a little concerned about the Python. Is it safe to modify and return data on the fly like this?</p>\n</blockquote>\n\n<p>Yes it's safe to do this, as you create the data in that function. <code>datas = json.loads(x)</code>.</p>\n\n<p>It can be safe to implement it in a function where this isn't the case, but you shouldn't return the data. This shows that the output is via side-effects. If you return and mutate then that will cause people to think there are no side-effects and it would be unsafe.</p>\n\n<p>It also makes the code simpler than otherwise.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T00:39:23.890",
"Id": "221756",
"ParentId": "221749",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "221756",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-05T22:10:08.790",
"Id": "221749",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"sql",
"json",
"sql-server"
],
"Title": "JSON from SQL Server: Reduce lists of single dicts to list of values"
} | 221749 |
<h2>Background</h2>
<p>The Pythagorean theorem asserts that for a right triangle with hypotenuse <span class="math-container">\$c\$</span> and other sides <span class="math-container">\$a\$</span> and <span class="math-container">\$b\$</span>, the area of the square placed upon <span class="math-container">\$c\$</span> is equal to the sum of the areas placed upon
<span class="math-container">\$a\$</span> and <span class="math-container">\$b\$</span>. This is normally written algebraically as <span class="math-container">\$a^2+b^2 = c^2\$</span>. </p>
<p>One way to prove this is to draw two squares of side length <span class="math-container">\$a+b\$</span>. In one, draw four identical <span class="math-container">\$abc\$</span> triangles such that their hypotenuses form a square of side length <span class="math-container">\$c\$</span>. In the other, draw four more identical <span class="math-container">\$abc\$</span> triangles such that they form two rectangles with side lengths <span class="math-container">\$a\$</span> and <span class="math-container">\$b\$</span> and the same length sides are adjacent. This creates two squares with side length <span class="math-container">\$a\$</span> and <span class="math-container">\$b\$</span> respectively. </p>
<p><a href="https://i.stack.imgur.com/dR9Q7.png" rel="noreferrer"><img src="https://i.stack.imgur.com/dR9Q7m.png" alt="Visualization of the Pythagorean theorem"></a></p>
<p>So now we have four triangles of area <span class="math-container">\$\frac{1}{2}ab\$</span> in each square of area <span class="math-container">\$(a+b)^2\$</span>. In addition, the left square contains a square of area <span class="math-container">\$c^2\$</span> and the right square contains two squares of area <span class="math-container">\$a^2\$</span> and <span class="math-container">\$b^2\$</span> respectively. Summing up the areas inside the two equal squares, we get </p>
<p><span class="math-container">$$c^2 + 4(\frac{1}{2}ab) = a^2 + b^2 + 4(\frac{1}{2}ab)$$</span></p>
<p>Subtracting like terms from both sides, we get </p>
<p><span class="math-container">$$c^2 = a^2 + b^2$$</span></p>
<p>The nifty thing about this method is that it actually shows what "the area of the square placed upon" a side means. </p>
<p>Now of course you're wondering how I generated the diagram. I used a free SVG to PNG converter (<a href="https://convertio.co/svg-png/" rel="noreferrer">this one</a>) to generate the image from an SVG. </p>
<h2>The SVG</h2>
<pre><code><svg width="4400" height="2200"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink= "http://www.w3.org/1999/xlink">
<style>
svg {
background-color: white;
}
text {
font: 3000% "Times New Roman";
text-anchor: end;
}
text.superscript {
font-size: 1200%;
text-anchor: start;
}
</style>
<rect x="100" y="100" width="2000" height="2000" fill="none" stroke="black" />
<polygon points="900,100 100,1300 1300,2100 2100,900" fill="none" stroke="black" />
<text x="1100" y="1300">c</text>
<text x="1100" y="1100" class="superscript">2</text>
<rect x="2300" y="100" width="2000" height="2000" fill="none" stroke="black" />
<polygon points="3100,1300 3100,100 2300,1300 4300,1300 3100,2100"
fill="none" stroke="black" />
<text x="2750" y="1850">a</text>
<text x="2750" y="1700" class="superscript">2</text>
<text x="3750" y="950">b</text>
<text x="3750" y="700" class="superscript">2</text>
</svg>
</code></pre>
<p>Some tags broken across multiple lines to eliminate scrolling on this site. This does not seem to affect parsing of the SVG code (I ported it back to my code to check). </p>
<h2>Review suggestions</h2>
<p>As always, you <em>can</em> review any aspect of the SVG or CSS code. But here are some areas that are of particular interest to me. </p>
<ol>
<li>Does this meet best standards for an SVG? </li>
<li>In particular, is there a better way of keeping the numbers consistent? </li>
<li>Is the resulting image visually appealing and easy to read? </li>
<li>Is there a better visualization? For example, I've seen images that put both squares atop one another and use different colors or animation. Is there an appealing way to do something like that with a static black and white image? </li>
</ol>
<p>Some requirements that may not be obvious. </p>
<ol>
<li>This is a black and white image. No color. </li>
<li>No animation. Just a static image. </li>
<li><span class="math-container">\$a \le b \lt c\$</span>. The first two simply by definition. If there's a smaller leg, we're calling that one <span class="math-container">\$a\$</span>. The last by the definition of a right triangle. The hypotenuse is always the longest side. </li>
<li>The image is deliberately created large. Please keep the <span class="math-container">\$a+b\$</span> squares the same size. </li>
</ol>
<p>Beyond that feel free to move things around, change the stroke, change the margins, or change the proportions. But do try to remember that this is a code review. While I am certain that any number of people could draw a better visualization by hand or GImP, this uses SVG for that purpose. So please propose edits to the SVG rather than changes to the image. For example, a patterned fill is certainly possible, but please include how to do that rather than just saying, "The image would look better filled with a polka-dot pattern." </p>
<p>My plan is to use this to fix my T-shirt design on Zazzle, as the current image doesn't scale well. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-15T15:13:39.587",
"Id": "430292",
"Score": "0",
"body": "You’re asking for changes to code and not to the image. So this is unsolicited advice: make the darkness of the lines and the text more similar. The lines now are very thin wrt the letters, and fade into the background. (I’m reading on a phone so that might exaggerate the effect.)"
}
] | [
{
"body": "<p>Wow! I’ve never reviewed an image before. Neat.</p>\n\n<p>First, I’d flip your left square to align the corners of the right-most triangles in the left square with the horizontal line in the right square. This gives a visual indication that those dimensions (<code>a</code> and <code>b</code>) in both squares are the same. With the original image, your eye has to draw the line all the way across the left square to see it line up with the left triangles of the left square.</p>\n\n<p>Second, both squares have the same four triangles, except in your right diagram, you have to mentally flip 2 of the triangles to make corresponding triangles in the same orientation between left and right squares. If you drew one of the diagonals between the opposite corners of the a/b rectangles, then all 4 triangles can be mentally translated from the left to the right image, without needing rotations or flips.</p>\n\n<p>I’ve number the triangles in my image, below, to show you what I mean, but I’m not certain you’d want to number them in your final t-shirt design.</p>\n\n<p><a href=\"https://i.stack.imgur.com/OsGDi.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/OsGDi.jpg\" alt=\"Pythagorean squares with corresponding triangles numbered for comparison\"></a></p>\n\n<h2>The SVG Code</h2>\n\n<h3>Styling</h3>\n\n<p>You've used styles to assign attribute to text elements, so you don't have to specify the attributes in each <code><text/></code> element, but you continue to specify both the <code>fill</code> and <code>stroke</code> for <code><rect/></code> and <code><polygon/></code> elements. Let's add a style for these:</p>\n\n<pre><code>rect, polygon {\n fill: none;\n stroke: black;\n}\n</code></pre>\n\n<h3>Coordinates</h3>\n\n<p>I would use two group nodes with translations to draw the left and right squares using the same coordinate system, with the <code>0,0</code> coordinate to where the centre of the large rectangles will be. The rectangle's corners will then all be <code>±1000,±1000</code>.</p>\n\n<pre><code><g transform=\"translate(1100, 1100)\">\n <rect x=\"-1000\" y=\"-1000\" width=\"2000\" height=\"2000\" />\n</g>\n\n<g transform=\"translate(3300, 1100)\">\n <rect x=\"-1000\" y=\"-1000\" width=\"2000\" height=\"2000\" />\n</g>\n</code></pre>\n\n<h3>Symbols</h3>\n\n<p>It is pretty clear both these rectangles will be the same; the code for them is identical. But we can do better. Like moving common code into a subroutine, let's move our common shapes into a definition.</p>\n\n<pre><code><defs>\n <rect id=\"square\" x=\"-1000\" y=\"-1000\" width=\"2000\" height=\"2000\" />\n</defs>\n\n<g transform=\"translate(1100, 1100)\">\n <use xlink:href=\"#square\" />\n</g>\n\n<g transform=\"translate(3300, 1100)\">\n <use xlink:href=\"#square\" />\n</g>\n</code></pre>\n\n<p>Next, let's add our triangles. The triangles are all identical, so again it makes sense to use a common definition.</p>\n\n<pre><code><defs>\n <rect id=\"square\" x=\"-1000\" y=\"-1000\" width=\"2000\" height=\"2000\" />\n <polygon id=\"triangle\" points=\"0,0 1200,0 0,800\" />\n</defs>\n</code></pre>\n\n<p>I've put the right-angle of the triangle at the <code>0,0</code> coordinate, which will make it fairly easy to position each triangle at one of the 4 corners of the left square:</p>\n\n<pre><code><g transform=\"translate(1100, 1100)\">\n <use xlink:href=\"#square\" />\n <use xlink:href=\"#triangle\" transform=\"translate(-1000,-1000) rotate(0)\" />\n <use xlink:href=\"#triangle\" transform=\"translate(+1000,-1000) rotate(90)\" />\n <use xlink:href=\"#triangle\" transform=\"translate(+1000,+1000) rotate(180)\" />\n <use xlink:href=\"#triangle\" transform=\"translate(-1000,+1000) rotate(270)\" />\n</g>\n</code></pre>\n\n<p>For the right square, we just need to update the positions of the triangles. Unfortunately, these require knowledge of the <code>a,b</code> values:</p>\n\n<pre><code><g transform=\"translate(3300, 1100)\">\n<use xlink:href=\"#square\"/>\n <use xlink:href=\"#triangle\" transform=\"translate( -200, +200) rotate(0)\" />\n <use xlink:href=\"#triangle\" transform=\"translate( -200,-1000) rotate(90)\" />\n <use xlink:href=\"#triangle\" transform=\"translate(+1000,+1000) rotate(180)\" />\n <use xlink:href=\"#triangle\" transform=\"translate(-1000, +200) rotate(270)\" />\n</g>\n</code></pre>\n\n<h3>Text Grouping</h3>\n\n<p>Finally, the text nodes need to be added back in, taking into account the new coordinate system. Again, you draw these in similar ways. You draw a letter, and then draw the superscript \"2\" at an offset from the letter's origin. Sometimes, it is 200 pixels higher, sometimes it is 150 pixels higher. Why the discrepancy? Intentional or accidental?</p>\n\n<p>Let's be more rigid about how we lay out the text. Let's put the text into a group, with the letter at <code>0,0</code> and the superscript at <code>0,200</code>, and move the text group to the correct position with a transform.</p>\n\n<pre><code> <g transform=\"translate(-550, 550)\">\n <text x=\"0\" y=\"200\">a</text>\n <text x=\"0\" y=\"0\" class=\"superscript\">2</text>\n </g>\n\n <g transform=\"translate(450, -450)\">\n <text x=\"0\" y=\"200\">b</text>\n <text x=\"0\" y=\"0\" class=\"superscript\">2</text>\n </g>\n</code></pre>\n\n<p>Now we can see a structure to how the text is drawn, and be consistent between the areas.</p>\n\n<h3>Refactored Code</h3>\n\n<pre><code><svg width=\"4400\" height=\"2200\"\n xmlns=\"http://www.w3.org/2000/svg\"\n xmlns:xlink= \"http://www.w3.org/1999/xlink\">\n <style>\n svg {\n background-color: white;\n }\n\n rect, polygon {\n fill: none;\n stroke: black;\n }\n\n text {\n font: 3000% \"Times New Roman\";\n text-anchor: end;\n }\n\n text.superscript {\n font-size: 1200%;\n text-anchor: start;\n }\n </style>\n\n <defs>\n <rect id=\"square\" x=\"-1000\" y=\"-1000\" width=\"2000\" height=\"2000\"/>\n <polygon id=\"triangle\" points=\"0,0 1200,0 0,800\" />\n </defs>\n\n <g transform=\"translate(1100, 1100)\">\n <use xlink:href=\"#square\" />\n\n <use xlink:href=\"#triangle\" transform=\"translate(-1000,-1000) rotate(0)\" />\n <use xlink:href=\"#triangle\" transform=\"translate(+1000,-1000) rotate(90)\" />\n <use xlink:href=\"#triangle\" transform=\"translate(+1000,+1000) rotate(180)\" />\n <use xlink:href=\"#triangle\" transform=\"translate(-1000,+1000) rotate(270)\" />\n\n <text x=\"0\" y=\"200\">c</text>\n <text x=\"0\" y=\"0\" class=\"superscript\">2</text>\n </g>\n\n <g transform=\"translate(3300, 1100)\">\n <use xlink:href=\"#square\"/>\n\n <use xlink:href=\"#triangle\" transform=\"translate( -200, +200) rotate(0)\" />\n <use xlink:href=\"#triangle\" transform=\"translate( -200,-1000) rotate(90)\" />\n <use xlink:href=\"#triangle\" transform=\"translate(+1000,+1000) rotate(180)\" />\n <use xlink:href=\"#triangle\" transform=\"translate(-1000, +200) rotate(270)\" />\n\n <g transform=\"translate(-550, 550)\">\n <text x=\"0\" y=\"200\">a</text>\n <text x=\"0\" y=\"0\" class=\"superscript\">2</text>\n </g>\n\n <g transform=\"translate(450, -450)\">\n <text x=\"0\" y=\"200\">b</text>\n <text x=\"0\" y=\"0\" class=\"superscript\">2</text>\n </g>\n </g>\n</svg>\n</code></pre>\n\n<p>Is this a better? It is certainly longer, so that is a negative. However, I like that the triangle coordinates are simply <code>0,0</code>, <code>1200,0</code> and <code>0,800</code>. Changing the size of the triangle works perfectly for the left square; the right square you still need to adjust 4 numbers in the <code>translate()</code> calls to get the triangles to line up properly, and will need to manually move the a² and b² text positions, but at least the superscripted 2's don't need to be adjusted separately.</p>\n\n<p>You could use a PHP script, or an XSLT stylesheet to generate this SVG document, with the <code>a</code> parameter as input, and it could do the calculations for you, and fill in the calculated numbers in the required 10 places.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T05:26:27.840",
"Id": "221762",
"ParentId": "221751",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "221762",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-05T22:46:16.730",
"Id": "221751",
"Score": "11",
"Tags": [
"image",
"mathematics",
"svg"
],
"Title": "Visualization of the Pythagorean theorem"
} | 221751 |
<p>How is the logic, efficiency and can it be improved?</p>
<p>This is a snippet from my <code>.bashrc</code> file; I just wrote it and I've tested it and it almost works. <a href="/q/221692">This was the first version review</a>.</p>
<p><strong>I feel I haven't fully gotten a grasp of what I've done at the end of the code, could you help me understand the logic and improve it; does it have to create a new file every time this evaluates<code>~/.bash_history) >= 99900</code> to true, I'm sure no?</strong></p>
<p>As it is now, it creates two files and then stops if I don't use any commands and update <code>~/.bash_history</code>.</p>
<p>It runs every time when the shell/terminal starts and when there are 100 lines or less left in history (<code>if (( $(wc -l < ~/.bash_history) >= 99900 ))</code>).</p>
<p>The code is supposed to do this:</p>
<p><strong>Backup my .bash_history file if it is 100 lines or less from the defined size of HISTSIZE=100000 and HISTFILESIZE=100000 lines, then backup the file.</strong></p>
<ol>
<li>Check if <code>.bash_history</code> is 99900 lines or more.</li>
<li>Check if <code>~/.bash_history.old</code> exists; if it doesn't use that filename.</li>
<li>Increment <code>incre</code> one digit larger than is already used by filenames.(filename-4.old)</li>
<li>Check if there are more than 20 files already backed up and warn if there are.</li>
<li>Set the new filename into a variable.</li>
<li>Check if the last file with a digit in its filename is older than the original.</li>
<li>copy the file to new_name</li>
</ol>
<h2>Here is the UPDATED code:</h2>
<pre><code>########################333############# backup history
if (( $(wc -l < ~/.bash_history) >= 99900 ))
then
name=~/.bash_history
old=.old
if [[ ! -e "$name""$old" ]]
then
printf "%s\n" "##################################################" ".bash_history will be cleared soon, backing up....!" "##################################################"
cp "$name" "$name""$old"
else
incre=0
if [[ -e "$name""$old" ]]
then
while [[ -e "$name"-"$incre""$old" ]]
do
(( incre++ ))
done
fi
if [[ "$incre" -ge 20 ]]
then
printf "%s\n" "********************************************************" "You need to arhive your history files they are mounting up!!!" "**************************************************************"
fi
# collect both times in seconds-since-the-epoch
twelve_days_ago=$(date -d 'now - 12 days' +%s)
file_time=$(date -r "$name" +%s)
new_name="$name"-"$incre""$old"
increMinusOne=$(( incre - 1 ))
#answer=""
#printf "%s\n" "Do you want to backup 'bash_history' now?"
#read -r answer
#if [[ "$answer" == "y" ]] || [[ "$answer" == "Y" ]]
#minus=$(( i - 1 ))
if [ -e "$name-$increMinusOne$old" ]
then
if [ $name -ot "$name-$increMinusOne$old" ]
then
printf "%s\n" "##################################################" ".bash_history will be cleared soon, backing up....!" "##################################################"
cp "$name" "$name-$increMinusOne$old"
fi
elif [ -e "new_name" ]
then
new_time=$(date -r "$new_name" +%s)
if [ "$name" -nt "$new_name" ] && (( $(wc -l < "$name") > $(wc -l < "$new_name") ))
then
printf "%s\n" "##################################################" ".bash_history will be cleared soon, backing up....!" "##################################################"
cp "$name" "$new_name"
# ...and then just use integer math:
elif (( new_time <= twelve_days_ago ))
then
echo "$new_name is older than 12 days"
printf "%s\n" "##################################################" ".bash_history will be cleared soon, backing up....!" "##################################################"
cp "$name" "$new_name"
fi
else
printf "%s\n" "##################################################" ".bash_history will be cleared soon, backing up....!" "##################################################"
cp "$name" "$new_name"
fi
fi
fi
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-05T22:50:09.803",
"Id": "221752",
"Score": "2",
"Tags": [
"beginner",
"bash",
"linux",
"shell",
"sh"
],
"Title": "Code to backup the history file in Linux"
} | 221752 |
<p>On an overly abused workbook we've hit the limit and <code>NumberFormat</code>s can no longer be added. If we do want to add more we need to consolidate current formats. My code requires a reference to <code>Microsoft Scripting Runtime</code> as it uses the <code>Dictionary</code> class. Is there anything I can do to further improve performance?</p>
<p>I started by looking for a NumberFormat already known to be in use on a worksheet. </p>
<pre class="lang-vb prettyprint-override"><code>Private Function GetFoundNumberFormatOnWS(ByVal numberFormatToFind As String, ByVal ws As Worksheet) As Range
Application.FindFormat.Clear
Application.FindFormat.NumberFormat = numberFormatToFind
Dim searchArea As Range
Set searchArea = ws.UsedRange
Dim firstCell As Range
Set firstCell = searchArea.Find(What:=vbNullString, After:=searchArea.Cells(searchArea.Rows.Count, searchArea.Columns.Count), SearchFormat:=True)
Dim foundCell As Range
Set foundCell = searchArea.Find(What:=vbNullString, After:=firstCell, SearchFormat:=True)
If foundCell Is Nothing Or foundCell.Address = firstCell.Address Then
Set GetFoundNumberFormatOnWS = firstCell
Exit Function
End If
Set GetFoundNumberFormatOnWS = Union(firstCell, foundCell)
Do While foundCell.Address <> firstCell.Address And Not foundCell Is Nothing
'Range.Find() is used as Range.FindNext() doesn't search for a SearchFormat.
Set foundCell = searchArea.Find(What:=vbNullString, After:=foundCell, SearchFormat:=True)
If foundCell Is Nothing Then
Exit Function
End If
Set GetFoundNumberFormatOnWS = Union(GetFoundNumberFormatOnWS, foundCell)
Loop
End Function
</code></pre>
<p>The next step was to search for all the NumberFormats on a given worksheet. If the NumberFormat is non-General I care about it and store it. <code>delimitChar</code> is a module level variable <code>Private Const delimitChar As String = "|"</code> since it is also used later as part of the table creation.</p>
<pre class="lang-vb prettyprint-override"><code>Public Function GetAllNumberFormatsFromWorksheet(ByVal ws As Worksheet) As Scripting.Dictionary
Set GetAllNumberFormatsFromWorksheet = New Scripting.Dictionary
Dim sheetName As String
sheetName = ws.Name
Dim cell As Range
For Each cell In ws.UsedRange
If cell.NumberFormat <> "General" Then
Dim formatWSKey As String
formatWSKey = cell.NumberFormat & delimitChar & sheetName
If Not GetAllNumberFormatsFromWorksheet.Exists(formatWSKey) Then
Dim foundCells As Range
Set foundCells = GetFoundNumberFormatOnWS(cell.NumberFormat, ws)
GetAllNumberFormatsFromWorksheet.Add formatWSKey, foundCells.Address
End If
End If
Next
End Function
</code></pre>
<p>From there the next step was to get all the NumberFormats in a workbook.</p>
<pre class="lang-vb prettyprint-override"><code>Private Function GetAllNumberFormatsFromWorkbook(ByVal wb As Workbook) As Scripting.Dictionary
Dim formatsInWorkbook As Scripting.Dictionary
Set formatsInWorkbook = New Scripting.Dictionary
Dim ws As Worksheet
For Each ws In wb.Worksheets
Dim formatsInWorksheet As Scripting.Dictionary
Set formatsInWorksheet = GetAllNumberFormatsFromWorksheet(ws)
Dim keyValue As Variant
For Each keyValue In formatsInWorksheet.Keys
formatsInWorkbook.Add keyValue, formatsInWorksheet.Item(keyValue)
Next
Next
Set GetAllNumberFormatsFromWorkbook = formatsInWorkbook
End Function
</code></pre>
<p>When one of the function returns I can then use it to create a table from the consolidated information. The <code>Keys</code> and <code>Items</code> are converted to Nx1 "vertical" array for population.</p>
<pre class="lang-vb prettyprint-override"><code>Private Function CreateTable(ByVal numberFormatsDictionary As Scripting.Dictionary, ByVal addToWorkbook As Workbook) As ListObject
Dim formatUsedOnWorksheet As Worksheet
Set formatUsedOnWorksheet = addToWorkbook.Worksheets.Add
formatUsedOnWorksheet.Name = "UsedNumberFormats"
formatUsedOnWorksheet.Range("A1").Value2 = "NumberFormat"
formatUsedOnWorksheet.Range("B1").Value2 = "Worksheet"
formatUsedOnWorksheet.Range("C1").Value2 = "Cells"
Const dataStartRow As Long = 2
With formatUsedOnWorksheet.Cells(dataStartRow, 1).Resize(numberFormatsDictionary.Count, 1)
.NumberFormat = "@"
.Value2 = WorksheetFunction.Transpose(numberFormatsDictionary.Keys)
'FieldInfo preserves `0.000` and `0.0` as distinct formats. Otherwise they
'are treated as `0` and their distinct format is not preserved.
.TextToColumns DataType:=xlDelimited, Other:=True, OtherChar:=delimitChar, FieldInfo:=Array(Array(1, XlColumnDataType.xlTextFormat), Array(2, XlColumnDataType.xlGeneralFormat))
End With
'Originally Application.WorksheetFunction.Transpose() was used.
'Under certain conditions it would error out
Dim verticalArray() As Variant
verticalArray = ConvertToVerticalArray(numberFormatsDictionary.Items)
formatUsedOnWorksheet.Cells(dataStartRow, 3).Resize(numberFormatsDictionary.Count, 1).Value2 = verticalArray
Set CreateTable = formatUsedOnWorksheet.ListObjects.Add(xlSrcRange, formatUsedOnWorksheet.Range("A1").CurrentRegion, XlListObjectHasHeaders:=xlYes)
End Function
Private Function ConvertToVerticalArray(ByRef horizontalArray As Variant) As Variant
Dim lowerBound As Long
lowerBound = LBound(horizontalArray)
Dim upperBound As Long
upperBound = UBound(horizontalArray)
Dim elementCounter As Long
Dim foo As Variant
ReDim foo(lowerBound To upperBound, 0 To 0)
For elementCounter = lowerBound To upperBound
foo(elementCounter, 0) = horizontalArray(elementCounter)
Next
ConvertToVerticalArray = foo
End Function
</code></pre>
<p>The calling Sub takes the returned information and creates a table from it.</p>
<pre class="lang-vb prettyprint-override"><code>Public Sub AddWorksheetThatListsWhereNumberFormatsAreUsedInWorkbook()
Dim usedInWB As Scripting.Dictionary
Set usedInWB = GetAllNumberFormatsFromWorkbook(ThisWorkbook)
With CreateTable(usedInWB, ThisWorkbook)
.HeaderRowRange.Columns.AutoFit
.Sort.SortFields.Add .ListColumns(1).Range
.Sort.SortFields.Add .ListColumns(2).Range
.Sort.Apply
End With
End Sub
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T00:21:32.170",
"Id": "221755",
"Score": "5",
"Tags": [
"vba",
"excel"
],
"Title": "Search for used Range.NumberFormats in Excel workbook"
} | 221755 |
<p>I recently did a interview with WalmartLabs. I was tasked with a take home assignment. I didn't sign a NDA and a team at WalmartLabs said I could post the code on GitHub. I was tasked with developing a program that would deliver orders in such a way to maximize customer satisfaction. My approach to solve this problem was to use a priority queue. The priority queue would prioritize by order created date and distance from the target. Admittedly, I made a mistake by not considering the total passing time when prioritizing orders. I want to become a better developer. I would like to know if someone could look at my github project at <a href="https://github.com/vaughnshaun/Walmart_DroneChallenge" rel="noreferrer">https://github.com/vaughnshaun/Walmart_DroneChallenge</a> and tell me any flaws and/or good points of my design. Below is a snippet of a main class for my program. The full project is at my github. The spec for the project is in a pdf named DroneDeliveryChallengeSpec.pdf.</p>
<pre><code>public class OrderDeliverer
{
private List<DeliveredOrder> completedOrders = new List<DeliveredOrder>();
private IOrderStreamer orderStreamer;
private Warehouse warehouse;
private Double promoters;
private Double detractors;
private Action<DeliveredOrder> deliveredOrderAction;
public OrderDeliverer(Warehouse warehouse, IOrderStreamer orderStreamer)
{
this.warehouse = warehouse;
this.orderStreamer = orderStreamer;
}
public virtual void ProcessOrder()
{
// Artificially advance the time to the next order waiting to be created
// This is a fail safe, just in case the the processing of orders don't advance time enough
if (!warehouse.HasOrders)
{
orderStreamer.AdvanceTime();
}
// Keep processing orders while there are orders
if (warehouse.HasOrders)
{
Order order;
// If there isn't time for delivery the order should be moved to next day delivery
if (!warehouse.HasTimeToDeliverNextOrder(orderStreamer.CurrentTime))
{
warehouse.MoveNextOrderToNextDay();
}
else if (warehouse.TrySendNextOrder(out order)) // Try to send the order out of the warehouse
{
// Create a delivered order and track its status and times
DeliveredOrder outboundOrder = new DeliveredOrder(order.Id);
outboundOrder.OrderPlaced = order.Created;
outboundOrder.DepartureTime = orderStreamer.CurrentTime;
outboundOrder.DeliveredTime = outboundOrder.DepartureTime;
// Time traveled to the destination
double travelMinutes = warehouse.GetOrderDeliveryMinutes(order);
outboundOrder.DeliveredTime = outboundOrder.DeliveredTime.AddMinutes(travelMinutes);
// Total time traveled, includes to destination and returning back to the warehouse
travelMinutes += warehouse.GetOrderReturnMinutes(order);
completedOrders.Add(outboundOrder);
deliveredOrderAction(outboundOrder);
switch (outboundOrder.GetRating())
{
case OrderHelper.RatingType.Detractor:
detractors++;
break;
case OrderHelper.RatingType.Promoter:
promoters++;
break;
}
warehouse.DockDrone();
// Update the mock global time (will also bring more new orders depending on the time)
orderStreamer.AddMinutesToTime(travelMinutes);
}
}
}
public void OnDeliveredOrder(Action<DeliveredOrder> deliveredAction)
{
deliveredOrderAction += deliveredAction;
}
/// <summary>
/// The number of orders successfully delivered
/// </summary>
/// <returns>Returns an int for the count of delivered orders</returns>
public int GetNumberOfCompleted()
{
return completedOrders.Count;
}
public double GetNps()
{
double nps = 0;
if (completedOrders.Count > 0)
{
double promoterPercent = (promoters / completedOrders.Count) * 100;
double detractorPercent = (detractors / completedOrders.Count) * 100;
int decimalPlaces = 2;
nps = Math.Round(promoterPercent - detractorPercent, decimalPlaces);
}
return nps;
}
}
</code></pre>
| [] | [
{
"body": "<p>There are some basic considerations to make in your design.</p>\n\n<h3>Guard arguments</h3>\n\n<p>Perform at least <em>NotNull</em> checks on arguments on public entrypoints of your API.</p>\n\n<blockquote>\n<pre><code>public OrderDeliverer(Warehouse warehouse, IOrderStreamer orderStreamer)\n {\n this.warehouse = warehouse;\n this.orderStreamer = orderStreamer;\n }\n</code></pre>\n</blockquote>\n\n<pre><code>public OrderDeliverer(Warehouse warehouse, IOrderStreamer orderStreamer)\n {\n if (warehouse == null)\n throw new ArgumentNullException(nameof(warehouse));\n if (orderStreamer== null)\n throw new ArgumentNullException(nameof(orderStreamer));\n this.warehouse = warehouse;\n this.orderStreamer = orderStreamer;\n }\n</code></pre>\n\n<h3>Avoid nesting statements if you can</h3>\n\n<p>Code reads easier with the amount of nested statements kept to a minimum.</p>\n\n<blockquote>\n<pre><code>if (!warehouse.HasOrders)\n{\n orderStreamer.AdvanceTime();\n}\n\n// Keep processing orders while there are orders\nif (warehouse.HasOrders)\n{\n // code when HasOrders ..\n}\n</code></pre>\n</blockquote>\n\n<pre><code>if (!warehouse.HasOrders)\n{\n orderStreamer.AdvanceTime();\n return;\n}\n\n// Keep processing orders while there are orders\n// code when HasOrders ..\n</code></pre>\n\n<h3>Avoid redundant comments</h3>\n\n<p>Comments should be added only if they add substantial new information to the code.\nIn the above snippet, you could do without</p>\n\n<blockquote>\n <p><code>// Keep processing orders while there are orders</code></p>\n</blockquote>\n\n<h3>Inline variable declaration</h3>\n\n<p>This can be written in a more concise fashion.</p>\n\n<blockquote>\n<pre><code> Order order;\n else if (warehouse.TrySendNextOrder(out order))\n</code></pre>\n</blockquote>\n\n<pre><code>else if (warehouse.TrySendNextOrder(out Order order))\n</code></pre>\n\n<h3>Redundant variable type</h3>\n\n<p>The declared type does not need to be printed out when it can be derived logically from the instantiated type.</p>\n\n<blockquote>\n <p><code>DeliveredOrder outboundOrder = new DeliveredOrder(order.Id);</code></p>\n</blockquote>\n\n<pre><code> var outboundOrder = new DeliveredOrder(order.Id);\n</code></pre>\n\n<h3>Event lifetime management</h3>\n\n<p>Do you have a way to unsubscribe from the event? <strong>This is the cause of many memory leaks.</strong></p>\n\n<blockquote>\n <p><code>travelMinutes += warehouse.GetOrderReturnMinutes(order);</code></p>\n</blockquote>\n\n<h3>Property vs Method</h3>\n\n<p><a href=\"http://firebreaksice.com/csharp-property-vs-method-guidelines/\" rel=\"nofollow noreferrer\">How to decide?</a> Consider using a property for a simple getter <code>GetNumberOfCompleted</code>. </p>\n\n<h3>Virtual methods</h3>\n\n<p>Declare virtual methods when there is a use case for it. What is the reason you declare your method virtual?</p>\n\n<blockquote>\n <p><code>public virtual void ProcessOrder(</code></p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T02:57:18.570",
"Id": "429127",
"Score": "1",
"body": "I agree 100%. These are some really good suggestions that I will implement. For the event lifetime I think you must be referring to deliveredOrderAction and not travelMinutes. I do have to unsubscribe for that.The nested if statement is a good catch because my service will recall the method anyways. As for ProcessOrder, it is virtual because of unit testing. Even though I didn't get the job, I plan to keep improving this project for others and my own improvement. If you would like to contribute feel free to join the full project at my github."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T05:08:55.923",
"Id": "221761",
"ParentId": "221757",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "221761",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T00:59:25.247",
"Id": "221757",
"Score": "9",
"Tags": [
"c#",
"interview-questions"
],
"Title": "Drone Delivery Scheduling Service"
} | 221757 |
<p>Well, I'm trying to generate the following:</p>
<p><strong>Input:</strong></p>
<pre><code>Level1a/Level2a/Level3a/Level4a
Level1a/Level2a/Level3a/Level4b
Level1a/Level2a/Level3a/Level4c
Level1a/Level2a/Level3b/Level4a
Level1a/Level2a/Level3b/Level4b
Level1a/Level2a/Level3b/Level4c
Level1a/Level2a/Level3c/Level4a
Level1a/Level2a/Level3c/Level4b
Level1a/Level2a/Level3c/Level4c
Level1a/Level2b/Level3a/Level4a
Level1a/Level2b/Level3a/Level4b
Level1a/Level2b/Level3a/Level4c
Level1a/Level2b/Level3b/Level4a
Level1a/Level2b/Level3b/Level4b
Level1a/Level2b/Level3b/Level4c
Level1a/Level2b/Level3c/Level4a
Level1a/Level2b/Level3c/Level4b
Level1a/Level2b/Level3c/Level4c
Level1a/Level2c/Level3a/Level4a
Level1a/Level2c/Level3a/Level4b
Level1a/Level2c/Level3a/Level4c
Level1a/Level2c/Level3b/Level4a
Level1a/Level2c/Level3b/Level4b
Level1a/Level2c/Level3b/Level4c
Level1a/Level2c/Level3c/Level4a
Level1a/Level2c/Level3c/Level4b
Level1a/Level2c/Level3c/Level4c
Level1b/Level2a/Level3a/Level4a
Level1b/Level2a/Level3a/Level4b
Level1b/Level2a/Level3a/Level4c
Level1b/Level2a/Level3b/Level4a
Level1b/Level2a/Level3b/Level4b
Level1b/Level2a/Level3b/Level4c
Level1b/Level2a/Level3c/Level4a
Level1b/Level2a/Level3c/Level4b
Level1b/Level2a/Level3c/Level4c
Level1b/Level2b/Level3a/Level4a
Level1b/Level2b/Level3a/Level4b
Level1b/Level2b/Level3a/Level4c
Level1b/Level2b/Level3b/Level4a
Level1b/Level2b/Level3b/Level4b
Level1b/Level2b/Level3b/Level4c
Level1b/Level2b/Level3c/Level4a
Level1b/Level2b/Level3c/Level4b
Level1b/Level2b/Level3c/Level4c
Level1b/Level2c/Level3a/Level4a
Level1b/Level2c/Level3a/Level4b
Level1b/Level2c/Level3a/Level4c
Level1b/Level2c/Level3b/Level4a
Level1b/Level2c/Level3b/Level4b
Level1b/Level2c/Level3b/Level4c
Level1b/Level2c/Level3c/Level4a
Level1b/Level2c/Level3c/Level4b
Level1b/Level2c/Level3c/Level4c
Level1c/Level2a/Level3a/Level4a
Level1c/Level2a/Level3a/Level4b
Level1c/Level2a/Level3a/Level4c
Level1c/Level2a/Level3b/Level4a
Level1c/Level2a/Level3b/Level4b
Level1c/Level2a/Level3b/Level4c
Level1c/Level2a/Level3c/Level4a
Level1c/Level2a/Level3c/Level4b
Level1c/Level2a/Level3c/Level4c
Level1c/Level2b/Level3a/Level4a
Level1c/Level2b/Level3a/Level4b
Level1c/Level2b/Level3a/Level4c
Level1c/Level2b/Level3b/Level4a
Level1c/Level2b/Level3b/Level4b
Level1c/Level2b/Level3b/Level4c
Level1c/Level2b/Level3c/Level4a
Level1c/Level2b/Level3c/Level4b
Level1c/Level2b/Level3c/Level4c
Level1c/Level2c/Level3a/Level4a
Level1c/Level2c/Level3a/Level4b
Level1c/Level2c/Level3a/Level4c
Level1c/Level2c/Level3b/Level4a
Level1c/Level2c/Level3b/Level4b
Level1c/Level2c/Level3b/Level4c
Level1c/Level2c/Level3c/Level4a
Level1c/Level2c/Level3c/Level4b
Level1c/Level2c/Level3c/Level4c
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>public static class Level1a
{
public static class Level2a
{
public static class Level3a
{
public static string Level4a = "1488761881";
public static string Level4b = "193501299";
public static string Level4c = "1176619638";
}
public static class Level3b
{
public static string Level4a = "1399332350";
public static string Level4b = "2052111229";
public static string Level4c = "890332317";
}
public static class Level3c
{
public static string Level4a = "1532225081";
public static string Level4b = "573356654";
public static string Level4c = "2062588997";
}
}
public static class Level2b
{
public static class Level3a
{
public static string Level4a = "1529741837";
public static string Level4b = "222585494";
public static string Level4c = "891285919";
}
public static class Level3b
{
public static string Level4a = "390696166";
public static string Level4b = "594192298";
public static string Level4c = "1083220943";
}
public static class Level3c
{
public static string Level4a = "702598359";
public static string Level4b = "722402607";
public static string Level4c = "1405833999";
}
}
public static class Level2c
{
public static class Level3a
{
public static string Level4a = "2048595403";
public static string Level4b = "58370073";
public static string Level4c = "524601020";
}
public static class Level3b
{
public static string Level4a = "980100293";
public static string Level4b = "207581761";
public static string Level4c = "1504264127";
}
public static class Level3c
{
public static string Level4a = "1572666752";
public static string Level4b = "643931200";
public static string Level4c = "1591869757";
}
}
}
public static class Level1b
{
public static class Level2a
{
public static class Level3a
{
public static string Level4a = "347647206";
public static string Level4b = "1229370062";
public static string Level4c = "2009415733";
}
public static class Level3b
{
public static string Level4a = "1676726159";
public static string Level4b = "1215950520";
public static string Level4c = "524327104";
}
public static class Level3c
{
public static string Level4a = "1167245618";
public static string Level4b = "1439144914";
public static string Level4c = "132046132";
}
}
public static class Level2b
{
public static class Level3a
{
public static string Level4a = "226999070";
public static string Level4b = "1279391946";
public static string Level4c = "192015774";
}
public static class Level3b
{
public static string Level4a = "1312893735";
public static string Level4b = "1056858701";
public static string Level4c = "1619871324";
}
public static class Level3c
{
public static string Level4a = "167695140";
public static string Level4b = "1184979870";
public static string Level4c = "802335777";
}
}
public static class Level2c
{
public static class Level3a
{
public static string Level4a = "620553654";
public static string Level4b = "539272091";
public static string Level4c = "877305211";
}
public static class Level3b
{
public static string Level4a = "868125815";
public static string Level4b = "687971845";
public static string Level4c = "1271690402";
}
public static class Level3c
{
public static string Level4a = "2002666349";
public static string Level4b = "543891764";
public static string Level4c = "531171485";
}
}
}
public static class Level1c
{
public static class Level2a
{
public static class Level3a
{
public static string Level4a = "1037815829";
public static string Level4b = "508661588";
public static string Level4c = "2133403185";
}
public static class Level3b
{
public static string Level4a = "1819839158";
public static string Level4b = "1974149245";
public static string Level4c = "1408180029";
}
public static class Level3c
{
public static string Level4a = "1445946207";
public static string Level4b = "1184577875";
public static string Level4c = "1491470239";
}
}
public static class Level2b
{
public static class Level3a
{
public static string Level4a = "53173264";
public static string Level4b = "2000499325";
public static string Level4c = "1154118621";
}
public static class Level3b
{
public static string Level4a = "366958815";
public static string Level4b = "1370934195";
public static string Level4c = "1302531031";
}
public static class Level3c
{
public static string Level4a = "951174811";
public static string Level4b = "475599289";
public static string Level4c = "1590494308";
}
}
public static class Level2c
{
public static class Level3a
{
public static string Level4a = "1213818225";
public static string Level4b = "735701668";
public static string Level4c = "1148995019";
}
public static class Level3b
{
public static string Level4a = "1052213343";
public static string Level4b = "812405153";
public static string Level4c = "1170085538";
}
public static class Level3c
{
public static string Level4a = "701928350";
public static string Level4b = "952113098";
public static string Level4c = "104659109";
}
}
}
</code></pre>
<p>Actually, it works (as the rules marks), but I need to optimize it.</p>
<p>I'm using the following fiddle: <a href="https://dotnetfiddle.net/zhtHbe" rel="nofollow noreferrer">https://dotnetfiddle.net/zhtHbe</a></p>
<p>And to generate this actually uses almost 10Mb of RAM...</p>
<p>This is my code (you can use my <em>Fiddle</em> to experiment):</p>
<pre><code>const bool debug = false;
private static IEnumerable<RecursiveNode> RecursiveSplitting(IEnumerable<string> arrs, string currentParent = "", string splitChar = "/", bool nestedDebug = false)
{
if(!string.IsNullOrEmpty(Separator))
splitChar = Separator;
UsedSeparator = splitChar;
var _arrs = debug && !nestedDebug ? arrs.Where(a => a.Contains("Comix/")) : arrs;
if(debug)
nestedDebug = true;
// bool wasFirstIteration = false;
/*if(firstIteration) {
wasFirstIteration = true;
firstIteration = false;
}*/
string lastHandle = "";
foreach (var item in _arrs)
{
if (string.IsNullOrEmpty(item))
// yield break;
continue;
string parent = string.IsNullOrEmpty(currentParent) && item.Contains(splitChar) ? item.Substring(0, item.LastIndexOf(splitChar)) : currentParent;
if(!item.Contains(splitChar)) {
yield return new RecursiveNode(item, parent);
// yield break;
continue;
// throw new Exception("Nothing to split!");
}
var splitted = item.Split(splitChar.ToCharArray());
if (lastHandle == splitted[0])
// yield break;
continue;
lastHandle = splitted[0];
var node = new RecursiveNode(lastHandle, parent);
var subItems = arrs.Where(i => i.StartsWith(splitted[0] + splitChar) && i.Contains(splitChar))
.Select(i => i.Replace(splitted[0] + splitChar, string.Empty));
// if(debug)
Console.WriteLine("[Item={0}, SubItem Count={1}]", item, subItems.Count());
// if(subItems.Count() == 0)
// continue;
// Console.WriteLine(subItems.Count());
if (splitted.Length == 1)
{
yield return new RecursiveNode(splitted[0], parent);
// yield break;
continue;
}
var subNodes = RecursiveSplitting(subItems, parent, splitChar, nestedDebug);
node.Childs.AddRange(subNodes);
yield return node;
}
}
private static string OutputRecursiveNode(IEnumerable<RecursiveNode> nodes, Func<string, string> getFieldValue, int count = -1)
{
var sb = new StringBuilder();
++count;
foreach (var node in nodes)
{
string indenter = new string('\t', count);
var @class = indenter + GenerateClass(node.Value).Replace(Environment.NewLine, Environment.NewLine + indenter);
if (node.Childs.Count > 0)
{
sb.AppendLine(@class);
sb.AppendLine(OutputRecursiveNode(node.Childs, getFieldValue, count));
if (!string.IsNullOrEmpty(@class))
sb.AppendLine(indenter + "}");
sb.AppendLine();
}
else
{
string field = GenerateField(node.Value, getFieldValue(node.CurrentParent + UsedSeparator + node.Value));
sb.AppendLine(indenter + field);
}
}
return sb.ToString();
}
private static string GenerateClass(string name)
{
if (string.IsNullOrEmpty(name))
return string.Empty;
return string.Format("public static class {0}{1}{{", name, Environment.NewLine);
// return $@"public static class {name}{Environment.NewLine}{{";
}
private static string GenerateField(string name, string fieldValue) // , Func<string> str)
{
if (string.IsNullOrEmpty(name))
return string.Empty;
return string.Format(@"public static string {0} = ""{1}"";", name, fieldValue);
}
</code></pre>
<p>Please, to experiment with the fiddle change the following part:</p>
<pre><code>Console.WriteLine(LevelTest.CreateLevelsOneLine());
Console.WriteLine(DebugClasses());
// Console.WriteLine(MapClasses(nameMapping));
</code></pre>
<p>To:</p>
<pre><code>// Console.WriteLine(LevelTest.CreateLevelsOneLine());
// Console.WriteLine(DebugClasses());
Console.WriteLine(MapClasses(nameMapping));
</code></pre>
<p>This is my model class:</p>
<pre><code>public class RecursiveNode
{
public string Value { get; set; }
public string CurrentParent { get; set; }
public List<RecursiveNode> Childs { get; set; }
private RecursiveNode()
{
Childs = new List<RecursiveNode>();
}
public RecursiveNode(string value, string parent)
: this()
{
Value = value;
CurrentParent = parent;
}
}
</code></pre>
<p>And I still don't know where can be my memory leak, because I don't materialize any of the <code>IEnumerable</code>s... Until I reach the <code>StringBuilder</code> part where I build the final string... (But if you test the other part, the Fiddle just stops due to a timeout and the last memory report is about 1.50Gb)</p>
<p><strong>Note:</strong> The only part that I materialize everything is in <code>node.Childs.AddRange(subNodes);</code> but is this causing the issue?</p>
<p><strong>Note2:</strong> I would like that any nice person that answer this question helps me guiding me with possible refactors to this methods... (As my last && first question)</p>
<p>Any help is welcome!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T04:53:13.513",
"Id": "428968",
"Score": "0",
"body": "For class generation, consider using CodeDom (https://thuru.net/2015/01/22/generating-code-using-system-codedom/). T4 (https://books.google.be/books?id=wWyFCeTpruYC&pg=PT355&lpg=PT355&dq=T4+class+generation&source=bl&ots=49fnuLvhgZ&sig=ACfU3U1RJgOWsf5dnfUGFY3I-M_MQ_00Uw&hl=nl&sa=X&ved=2ahUKEwjivdfXh9TiAhUHJ1AKHYhuAxYQ6AEwCXoECAUQAQ#v=onepage&q=T4%20class%20generation&f=false) is also a good bootstrapper for generating code. And of course Roslyn (https://msdn.microsoft.com/en-us/magazine/mt808499.aspx)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T04:58:37.807",
"Id": "428969",
"Score": "0",
"body": "Yes, I know CodeDom, but I prefer to keep it simple. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T05:10:59.130",
"Id": "428971",
"Score": "0",
"body": "Perhaps these APIs have better memory management than a StringBuilder. It could be something to try... I also notice you do alot of string concatenation using the '+'-operator. https://stackoverflow.com/questions/16431909/string-concatenation-memory-usage-in-c-sharp"
}
] | [
{
"body": "<h3>Lazy versus eager</h3>\n\n<blockquote>\n <p>I don't materialize any of the IEnumerables</p>\n</blockquote>\n\n<p>Perhaps you should, because you're enumerating them many times, throwing away work again and again:</p>\n\n<ul>\n<li>In <code>Main</code>, that <code>nameMapping.Count()</code> debug output enumerates <code>nameMapping</code>, calling <code>GetName(node.Texture.Source)</code> for every item.</li>\n<li>In <code>MapClasses</code>, there's a materializing <code>ToArray</code> call.</li>\n<li>In <code>GetFieldValue</code>, <code>mapping.FirstOrDefault</code> has to enumerate <code>mapping</code> until it finds the first match. Because <code>mapping</code> is that same lazy <code>nameMapping</code> sequence, this too ends up calling <code>GetName(node.Texture.Source)</code> many times. It doesn't help that <code>GetFieldValue</code> gets called a lot - very likely resulting in <span class=\"math-container\">\\$O(n^2)\\$</span> performance.</li>\n<li>In <code>RecursiveSplitting</code>, you're enumerating the given sequence with a <code>foreach</code> loop. There's also a debug <code>Count()</code> call there, and you're appending several <code>Where</code> and <code>Select</code> calls to the given sequence, resulting in more work for deeper recursive calls.</li>\n</ul>\n\n<p>Or, in other words:</p>\n\n<pre><code>var lazy = items.Select(DoExpensiveWork); // Returns a select wrapper, cheap.\nlazy.Count(); // Enumerates, doing expensive work.\nlazy.FirstOrDefault(AlwaysFalse); // Enumerates again, repeating expensive work.\n// DoExpensiveWork has been called twice for every item, but all the results have been thrown away.\n// Enumerating 'lazy' will repeat that work.\n\n// versus:\n\nvar eager = items.Select(DoExpensiveWork).ToArray(); // Materializes immediately, expensive.\neager.Count(); // No enumeration required, cheap.\neager.FirstOrDefault(AlwaysFalse); // Enumerates materialized results, cheap.\n// DoExpensiveWork has been called once for every item, and the results are stored.\n// Enumerating 'eager' simply returns those results without repeating any work.\n</code></pre>\n\n<h3>Use the right data structure</h3>\n\n<p>Repeated <code>FirstOrDefault</code> calls, where the selector just compares a single property, are an indication that you should be using a lookup table or dictionary instead - those offer <span class=\"math-container\">\\$O(1)\\$</span> lookup instead of <span class=\"math-container\">\\$O(n)\\$</span>. Linq's <code>ToLookup</code> and <code>ToDictionary</code> methods are useful here. Originally, your code took about 17 seconds on my system. With an <code>ILookup</code>, that got cut down to about 0.3 second. Memory consumption got similarly reduced.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T08:49:50.417",
"Id": "221767",
"ParentId": "221759",
"Score": "6"
}
},
{
"body": "<p><code>OutputRecursiveNode()</code></p>\n\n<ul>\n<li>You are sometimes using <code>var</code> where the concrete type it isn't quite obvious from the right-hand-side of the assignment. Sometimes you use the concrete type where the type is obvious from the right-hand-side of the assignment (<code>string indenter = new string('\\t', count);</code>) </li>\n<li>Appending a concatenated string to a <code>StringBuilder</code> should better be done by using multiple <code>Append()</code>'s. </li>\n<li>the <code>var @class</code> is created for each node but is only needed if <code>node.Childs.Count > 0</code>. </li>\n<li>the <code>indenter</code>is created for each iteration of the loop which should be done outside of the loop. </li>\n<li>The <code>StringBuilder</code>'s <code>ApendXx()</code> methods provide a fluent implementation, meaning these methods are returning a <code>StringBuilder</code> which could be used as well. </li>\n<li>The <code>GenerateClass()</code> method adds a <code>Environment.NewLine</code> which is then replaced by <code>Environment.NewLine + indenter</code>. By simply returning <code>\"public static class \" + name</code> from that method we can then <code>Append()</code> new line, the <code>indenter</code> and the opening brace.</li>\n<li>The condition <code>!string.IsNullOrEmpty(@class)</code> can't never evaluate to <code>false</code>. </li>\n</ul>\n\n<p>Implementing these points will lead to </p>\n\n<pre><code>private static string OutputRecursiveNode(IEnumerable<RecursiveNode> nodes, Func<string, string> getFieldValue, int count = -1)\n{\n var sb = new StringBuilder();\n\n ++count;\n\n var indenter = new string('\\t', count);\n foreach (var node in nodes)\n {\n\n if (node.Childs.Count > 0)\n {\n sb.Append(indenter)\n .AppendLine(GenerateClass(node.Value))\n .Append(indenter)\n .Append(\"{\")\n .AppendLine(indenter)\n .Append(OutputRecursiveNode(node.Childs, getFieldValue, count))\n .Append(indenter)\n .AppendLine(\"}\");\n }\n else\n {\n sb.Append(indenter)\n .Append(GenerateField(node.Value, getFieldValue(node.CurrentParent + UsedSeparator + node.Value)));\n }\n sb.AppendLine();\n }\n\n return sb.ToString();\n} \n</code></pre>\n\n<p>and the changed <code>GenerateClass()</code> would look like so </p>\n\n<pre><code>private static string GenerateClass(string name)\n{\n if (string.IsNullOrEmpty(name))\n {\n return string.Empty;\n }\n return \"public static class \" + name;\n} \n</code></pre>\n\n<p>which leads to the next problem. If the name of the class is either <code>null</code> or <code>Empty</code> returning <code>string.Empty</code> wouldn't produce correct code. It would be better to either throw an <code>tException</code> (in the <code>OutputRecursiveNode()</code> method) or omitting classes which names are <code>null</code> or <code>Empty</code> but because the same applies to the <code>GenerateField()</code> method you should throw an Exception. </p>\n\n<p>Just placing </p>\n\n<pre><code>if (nodes.Any(n => string.IsNullOrEmpty(n.Value))) { throw new YourDesiredtException(); } \n</code></pre>\n\n<p>at the top of the <code>OutputRecursiveNode()</code> method will do the trick.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T20:53:03.703",
"Id": "221808",
"ParentId": "221759",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T04:43:57.607",
"Id": "221759",
"Score": "2",
"Tags": [
"c#",
"recursion",
"memory-optimization"
],
"Title": "Generating recursive class instances from an array of splitted values by dashes (as a folder tree)"
} | 221759 |
<p>Hi I have a simple tcp server, and that server receives messages with specific length so basically i need to wait for TcpClient to fill buffer with that amount of data, and it works. </p>
<p>But I am not sure if this should look like it looks as I am writing this in f# and still learning:</p>
<pre><code>let private WaitForData (client : TcpClient, dataLength : int) : Async<bool>=
async {
let mutable loopBreaker : bool = true
let mutable result : bool = false
while loopBreaker do
let isConnectionAlive : bool = IsConnectionEstablished client && client <> null
if isConnectionAlive && client.Available >= dataLength then
result <- true
loopBreaker <- false
if isConnectionAlive = false then
result <- false
loopBreaker <- false
Task.Delay(500)
|> Async.AwaitTask
|> ignore
return result
}
</code></pre>
<p>So as you see I use mutables to exit while loop and set result value, and have some if there. </p>
<p>Is this OK or maybe there is some more elegant way to write this</p>
| [] | [
{
"body": "<p>The first thing is when you use parenthesis it means that you pass a tuple to a function instead of single parameters. So you can ditch them.</p>\n\n<p>The second thing is that <code>bool</code> supports <a href=\"https://fsharpforfunandprofit.com/posts/match-expression/\" rel=\"noreferrer\">pattern matching</a></p>\n\n<p>The third thing is that you can use recursion instead of mutable variables. Note the usage of <code>rec</code> which enables <a href=\"https://devblogs.microsoft.com/fsharpteam/tail-calls-in-f/\" rel=\"noreferrer\">tail call optimisation</a>. </p>\n\n<p>The code would look something like this. </p>\n\n<pre><code>let rec private WaitForData2 (client : TcpClient) (dataLength : int) (loopBreaker : bool) (result: bool) : Async<bool>= \n async {\n match loopBreaker with\n | true -> \n let isConnectionAlive : bool = IsConnectionEstablished client && client <> null\n match isConnectionAlive, client.Available >= dataLength with\n | true, true -> \n Task.Delay(500) \n |> Async.AwaitTask \n |> ignore\n return! WaitForData2 client dataLength false true \n | false, _ -> \n Task.Delay(500) \n |> Async.AwaitTask \n |> ignore\n return! WaitForData2 client dataLength false false\n | _, _ -> \n Task.Delay(500) \n |> Async.AwaitTask \n |> ignore\n return! WaitForData2 client dataLength true false\n | false -> return result \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T08:54:48.567",
"Id": "221768",
"ParentId": "221764",
"Score": "5"
}
},
{
"body": "<blockquote>\n <p><code>let private WaitForData (client : TcpClient, dataLength : int) : Async<bool>=</code> </p>\n \n <p><code>let mutable loopBreaker : bool = true</code></p>\n \n <p><code>let isConnectionAlive : bool = IsConnectionEstablished client && client <> null</code></p>\n</blockquote>\n\n<p>You should only use explicit type declaration when the compiler demands it: </p>\n\n<p><code>let private WaitForData (client : TcpClient) dataLength =</code> </p>\n\n<p><code>let mutable loopBreaker = true</code></p>\n\n<p><code>let isConnectionAlive = IsConnectionEstablished client && client <> null</code></p>\n\n<hr>\n\n<blockquote>\n <p><code>let isConnectionAlive : bool = IsConnectionEstablished client && client <> null</code></p>\n</blockquote>\n\n<p>It seems rather risky to me that you use <code>client</code> in a function call before testing it for null. I would do it in reverse order:</p>\n\n<pre><code>let isConnectionAlive = client <> null && IsConnectionEstablished client\n</code></pre>\n\n<p>But why evaluate the <code>client</code> for <code>null</code> in the loop in the first place? You should return false immediately if it's <code>null</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> Task.Delay(500) \n |> Async.AwaitTask \n |> ignore\n</code></pre>\n</blockquote>\n\n<p>I don't think this is actually waiting 500 ms as you may expect.</p>\n\n<p>Instead you can do:</p>\n\n<pre><code>do! Async.Sleep 500\n</code></pre>\n\n<p>or </p>\n\n<pre><code>do! Task.Delay(500) |> Async.AwaitTask \n</code></pre>\n\n<hr>\n\n<p>As Bohdan Stupak shows you can do the same in a recursive fashion like:</p>\n\n<pre><code>let private waitForData (client: TcpClient) dataLength = \n let rec waiter () =\n async {\n if client = null then\n return false\n else \n match isConnected client, client.Available >= dataLength with\n | true, true -> return true\n | true, false ->\n do! Async.Sleep 500\n return! waiter ()\n | false, dataFound -> return dataFound \n }\n waiter()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T09:04:49.117",
"Id": "429556",
"Score": "1",
"body": "Thank you, looks nice."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T12:00:46.583",
"Id": "221855",
"ParentId": "221764",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "221768",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T07:51:16.007",
"Id": "221764",
"Score": "4",
"Tags": [
"f#",
"async-await",
"tcp"
],
"Title": "Tcp server messenger awaiter in f#"
} | 221764 |
<p>I wanted to create a set of functions that would allow me to easily implement images for multiple screen resolutions in my custom page templates.</p>
<p>WordPress offers some functionality for implementing responsive images but this assumes that the image will be 100% of the viewport with up until the maximum size of the image.</p>
<p>How could my code been improved?</p>
<pre class="lang-php prettyprint-override"><code>/**
* Returns all registered images sizes as an associative array.
*
* Thanks to https://gist.github.com/eduardozulian/6467854
*/
function relative_get_all_image_sizes() {
global $_wp_additional_image_sizes;
$image_sizes = array();
$default_image_sizes = array( 'thumbnail', 'medium', 'large', 'full' );
foreach ( $default_image_sizes as $size ) {
$image_sizes[$size] = array(
'width' => intval( get_option( "{$size}_size_w" ) ),
'height' => intval( get_option( "{$size}_size_h" ) ),
'crop' => get_option( "{$size}_crop" ) ? get_option( "{$size}_crop" ) : false,
);
}
if ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) ) :
$image_sizes = array_merge( $image_sizes, $_wp_additional_image_sizes );
endif;
return $image_sizes;
}
/**
* Will return an array of img attributes of a given $attachment_id
*
* $attachment_id - The attachment id of the image
* $html_class - When given this will be included in the returned array
* $mobile, $tablet, $desktop - viewport width or pixel value you would like the image to take up on each screen size
* $fallback_size - This is the size that will be used for the `src` attribute
*
* returns an array of attributes: src, srcset, alt, class
*
*/
function relative_get_img_src( $attachment_id, $html_class = '', $mobile = '100vw', $tablet = '50vw', $desktop = '33px', $fallback_size = 'full' ) {
if ( ! is_numeric( $attachment_id ) ) {
return false;
}
$available_img_sizes = relative_get_all_image_sizes();
$attributes = array(
'src' => '',
'srcset' => array(),
'alt' => get_post_meta( $attachment_id, '_wp_attachment_image_alt', TRUE ),
'class' => $html_class,
);
foreach ( $available_img_sizes as $name => $data ) {
$image = wp_get_attachment_image_src( $attachment_id, $name );
if ( ! $image ) {
continue;
}
if( $name === $fallback_size ) {
$attributes['src'] = $image[0];
}
$attributes['srcset'][] = $image[0] . ' ' . $image[1] . 'w';
}
$attributes['srcset'] = join( ', ', $attributes['srcset'] );
$viewport_sizes = array(
'mobile' => apply_filters( 'relative_mobile_viewport_max_width', '414px' ),
'tablet' => apply_filters( 'relative_tablet_viewport_max_width', '1366px' ),
);
$attributes['sizes'] = '(max-width: ' . $viewport_sizes['mobile'] . ') ' . $mobile . ', (max-width: ' . $viewport_sizes['tablet'] . ') ' . $tablet . ', ' . $desktop;
return $attributes;
}
/**
* Returns a fully formatted image element from a given attachment_id
*
* Essentially a wrapper of relative_get_img_src but formats the array returned from that function into an img element.
* For more info see relative_get_img_src
*
*/
function relative_get_img_element( $attachment_id, $html_class = '', $mobile = '100vw', $tablet = '50vw', $desktop = '33px', $fallback_size = 'full' ) {
$atts = relative_get_img_src( $attachment_id, $html_class, $mobile, $tablet, $desktop, $fallback_size );
if ( empty( $atts['src'] ) ) {
return false;
}
$img = '';
foreach($atts as $att => $val) {
$img .= $att . '="' . $val . '" ';
}
return "<img {$img} >";
}
</code></pre>
<p>Based on the following usage:</p>
<pre class="lang-php prettyprint-override"><code>$contact_image = get_field('contact_image', 'bdt-options');
echo relative_get_img_element( $contact_image['id'], 'round-10', '100vw', '41vw', '467px', 'ipad_m_2_3' );
</code></pre>
<p>I get the following:</p>
<pre class="lang-html prettyprint-override"><code><img src="https://example.com/img-461x307.png" srcset="https://example.com/img-150x150.png 150w, https://example.com/img-300x200.png 300w, https://example.com/img-1024x683.png 990w, https://example.com/img.png 1440w, https://example.com/img-256x171.png 256w, https://example.com/img-461x307.png 461w, https://example.com/img-768x512.png 768w, https://example.com/img-840x560.png 840w, https://example.com/img-1242x828.png 1242w, https://example.com/img-1440x960.png 1440w, https://example.com/img.png 1440w, https://example.com/img.png 1440w, https://example.com/img.png 1440w, https://example.com/img-570x380.png 570w, https://example.com/img-935x623.png 935w, https://example.com/img.png 1440w, https://example.com/img.png 1440w" alt="some alt example" class="round-10" sizes="(max-width: 414px) 100vw, (max-width: 1366px) 41vw, 467px">
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T09:41:57.053",
"Id": "429179",
"Score": "0",
"body": "As far as I'm aware it works in all cases. If you can see a way that it doesn't let me know and I will update"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T09:45:26.680",
"Id": "429181",
"Score": "2",
"body": "One tip: when you want to check `isset()` and has `count()`, `!empty()` is the way."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T09:24:41.113",
"Id": "221770",
"Score": "1",
"Tags": [
"php",
"html",
"image",
"wordpress"
],
"Title": "Proper image sizes in WordPress"
} | 221770 |
<blockquote>
<p>Calculate the number of loans issued by the Regional offices for each business week in the period from 38 to 40 business week of 2011 inclusive. Sort by name of the regional unit, business week.</p>
</blockquote>
<p>dataset and snippet here - <a href="http://www.sqlfiddle.com/#!18/53151/4" rel="nofollow noreferrer">http://www.sqlfiddle.com/#!18/53151/4</a></p>
<p>Are the joins correct in this query?</p>
<p>DDL:</p>
<pre><code>create table territory_type(
id int primary key identity (1,1),
name nvarchar(50) not null,
);
create table territory(
id int primary key identity (1,1),
parent_id int null,
name nvarchar(50) not null,
territory_type_id int not null,
foreign key(territory_type_id) references territory_type(id),
constraint fk_tr_parent foreign key (parent_id) references territory(id) on delete no action
);
create table deal(
dl_id int primary key identity (1,1),
dl_valutation_date datetime not null,
dl_sum decimal not null,
dl_territory_id int not null,
foreign key(dl_territory_id) references territory(id)
);
create table business_calendar(
id int primary key identity (1,1),
bc_year int not null,
week int not null,
date_begin date not null
);
</code></pre>
<p>QUERY:</p>
<pre><code>select
trd.name as "Regional office",
bc.bc_year as "Year",
bc.week as "Week",
sum(d.dl_sum) as "Sum of credits",
count(d.dl_id) as "Count of credits"
from deal as d
join business_calendar as bc
on (bc.date_begin < d.dl_valutation_date
or bc.date_begin = d.dl_valutation_date)
and (dateadd(day, 6, bc.date_begin) > d.dl_valutation_date
or dateadd(day, 6, bc.date_begin) = d.dl_valutation_date)
join territory as t on t.id = d.dl_territory_id
join territory as trd on t.parent_id = trd.id
where bc.week in (38,39,40)
group by trd.name,bc.bc_year, bc.week
order by trd.name, bc.week asc;
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T10:43:28.250",
"Id": "429006",
"Score": "0",
"body": "To improve readability, you should format your sql by some tool. That being said, does your sql work as intended?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T10:44:34.997",
"Id": "429007",
"Score": "0",
"body": "**We require that the code be working correctly, to the best of the author's knowledge**, before proceeding with a review. Your title indicates you don't know this. Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T10:47:53.920",
"Id": "429008",
"Score": "0",
"body": "This code works correctly, there are no errors in syntax but I think I can skip or miss something according to the task."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T10:50:33.393",
"Id": "429009",
"Score": "0",
"body": "@dfhwze thank you for advice, the answer to your question yes and no at the same time, I'm not sure that I understand task correctly. Maybe I missed something. Please read full description in snippet by the link above."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T10:58:39.523",
"Id": "429011",
"Score": "1",
"body": "I think that this question is allowable, if you believe that the code is correct, to the best of your knowledge. Please copy the `CREATE TABLE` statements into the question, though, so that the post still makes sense even without the SQLfiddle link."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T11:00:42.353",
"Id": "429012",
"Score": "0",
"body": "@200_success Thanks, done)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T12:29:58.360",
"Id": "429021",
"Score": "1",
"body": "@PavelKononenko Please don't change the query after an answer was made."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T15:01:48.327",
"Id": "429041",
"Score": "0",
"body": "What @dfhwze said. Once you have received an answer, you are in general no longer allowed to change the code in the question (otherwise it would become a moving target for the reviewers, where you could continuously invalidate their review by fixing what they recommend). I have rolled back your post to the version prior to the edit. Have a look at [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) for more information. Note that you can always ask a follow-up question if you feel there are more improvements possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T15:25:18.743",
"Id": "429043",
"Score": "1",
"body": "@Graipher Thanks, it was my fault, sorry."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T15:27:47.267",
"Id": "429044",
"Score": "1",
"body": "@PavelKononenko No worries, we are all here to learn. That includes learning how each site of the SE network works (they all have their quirks)."
}
] | [
{
"body": "<p>Your query could be simplified.</p>\n\n<ul>\n<li>use <a href=\"https://stackoverflow.com/questions/565620/difference-between-join-and-inner-join\">inner join</a> to avoid ambiguity when reading the query</li>\n<li>temporal interval join <code>date between start and end</code> (<a href=\"https://stackoverflow.com/questions/16347649/sql-between-not-inclusive\">inclusive end</a>)</li>\n</ul>\n\n<blockquote>\n<pre><code>join business_calendar as bc\n on (bc.date_begin < d.dl_valutation_date \n or bc.date_begin = d.dl_valutation_date)\n and (dateadd(day, 6, bc.date_begin) > d.dl_valutation_date\n or dateadd(day, 6, bc.date_begin) = d.dl_valutation_date)\n</code></pre>\n</blockquote>\n\n<pre><code> inner join business_calendar as bc\n on d.dl_valutation_date between bc.date_begin and dateadd(day, 6, bc.date_begin)\n</code></pre>\n\n<p>snippet:</p>\n\n<pre><code>select \n trd.name as \"Региональное подразделение\",\n bc.bc_year as \"Год\",\n bc.week as \"Неделя\",\n sum(d.dl_sum) as \"Сумма выданных займов\",\n count(d.dl_id) as \"Кол-во займов\"\nfrom deal as d\ninner join business_calendar as bc\n on d.dl_valutation_date between bc.date_begin and dateadd(day, 6, bc.date_begin)\ninner join territory as t on t.id = d.dl_territory_id\ninner join territory as trd on t.parent_id = trd.id\nwhere bc.week in (38,39,40) \ngroup by trd.name,bc.bc_year, bc.week\norder by trd.name, bc.week asc\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T11:06:12.693",
"Id": "221775",
"ParentId": "221771",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "221775",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T10:28:31.317",
"Id": "221771",
"Score": "4",
"Tags": [
"sql",
"interview-questions",
"t-sql",
"join"
],
"Title": "SQL query to count loans issued during each week"
} | 221771 |
<p>I am writing a function to decode data from a run length encoded format like: </p>
<pre><code>
{
dataGroup: {
count: [4, 4, 2, 1],
dataOne: [1, 3, 2, 1],
dataTwo: [7, -1, 9, 0],
dataThree: [3, 8, 1, 2]
}
}
</code></pre>
<p>to </p>
<pre><code>{
groupName: {
dataOne: [1, 1, 1, 1, 3, 3, 3, 3, 2, 2, 1],
dataTwo: [7, 7, 7, 7,-1,-1,-1,-1, 9, 9, 0],
dataThree: [3, 3, 3, 3, 8, 8, 8, 8, 1, 1, 2]
}
}
</code></pre>
<p>I have written two solutions to date but feel like there may yet be a better way.</p>
<pre><code>function decode(obj) {
const arrayLengthN = (N, data=null) => [...Array(N)].map(_ => data);
const [ group ] = Object.keys(obj);
const { count, ...data } = obj[group];
const dataKeys = Object.keys(data);
// method one
// output object to be written upon iteration over count and data
const output = {};
// populate output with empty arrays to push to
dataKeys.map(key => output[key] = []);
// do the decoding
count
.map((n, i) => {
dataKeys
.map(key => {
output[key].push(...arrayLengthN(n, data[key][i]));
});
});
// method two
const otherMethod = {
[group]: Object.assign(
{},
...dataKeys.map((key) => {
return {
[key] : count
.map((n, i) => dataKeys
.map(key => arrayLengthN(n, data[key][i]))
)
.flat(2)
};
})
)};
return {[group]: output}
// or return otherMethod
}
</code></pre>
<p>Is there anything wrong with the first method? It feels clunky to create an object, add empty arrays to it, and then mutate that object from within a .map call. That being said, to me it seems far more readable.</p>
<p>Any help or comments much appreciated.</p>
<p>Cheers,</p>
<p>P</p>
| [] | [
{
"body": "<p>May i suggest a shorter code?</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 data = {\n dataGroup: {\n count: [4, 4, 2, 1],\n dataOne: [1, 3, 2, 1],\n dataTwo: [7, -1, 9, 0],\n dataThree: [3, 8, 1, 2]\n }\n}\n\nvar processedData = Object.keys(data.dataGroup).filter(key => key != 'count').reduce((acc, key) => {\n acc.groupName[key] = [];\n data.dataGroup.count.forEach((amount, index) => {\n for (let i = 0; i < amount; i++) {\n acc.groupName[key].push(data.dataGroup[key][index]);\n }\n });\n return acc;\n}, { groupName: {}});\nconsole.log(processedData);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T13:02:44.047",
"Id": "429028",
"Score": "0",
"body": "Offering an alternate solution isn't really considered giving a good answer, and \"Your code is too long\" might not really be an insightful observation. Could you discuss why you think the code is too long? Please read https://codereview.stackexchange.com/help/how-to-answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T13:32:18.930",
"Id": "429037",
"Score": "0",
"body": "Hi, thanks for your solution. One thing to point out is that you've fixed the key 'groupName' in your output. For my purposes, the group key must be matched to the input object's group key."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T12:46:02.520",
"Id": "221778",
"ParentId": "221776",
"Score": "1"
}
},
{
"body": "<p>A bit late but looks good to me. You could use <code>Array.prototype.fill</code> instead of <code>arrayLengthN</code>, and perhaps a reducer as the function but that’s a matter of taste:</p>\n\n<pre><code>// assignment as expression to avoid explicit returns\nset = (obj, key, value) => (obj[key] = value, obj)\n\ndecode = (output, [group, {count, ...entries}]) =>\n set(output, group, Object.entries(entries).reduce((acc, [key, values]) =>\n set(acc, key, [].concat(...values.map((n, i) => Array(count[i]).fill(n))))\n , {}))\n</code></pre>\n\n<p>so you could <code>Object.entries(data).reduce(decode, {})</code>.</p>\n\n<p>I used <code>concat</code> because in my node version there wasn’t support for <code>flat</code>.</p>\n\n<p>I like this because all the “variable” names are argument names (although that’s bit of a moot point).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-02T19:29:53.270",
"Id": "223374",
"ParentId": "221776",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T11:57:05.073",
"Id": "221776",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "Javascript Object of Arrays manipulation"
} | 221776 |
<p>I've got a working solution for an <code>onMouseOver</code> event which rolls over a set of images and replaces them in the element. Due to my lack of knowledge in JS I would like to know if this is a proper solution. It works in Chrome and Firefox. </p>
<p>The solution sets attributes (i.e. <code>isRunning="true"</code>, <code>isCanceled="true"</code>) , reads them depending on the user action (<code>onMouseOver</code>, <code>onMouseOut</code>) and determines if the action should be continued. </p>
<p>Contraint: The solution must stay in Vanilla JS. No libraries may be used.</p>
<p>Thanks for any suggestion!</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>var thumbNails = {
123: [
"https://image.flaticon.com/icons/svg/188/188234.svg",
"https://image.flaticon.com/icons/svg/188/188235.svg",
"https://image.flaticon.com/icons/svg/188/188236.svg",
"https://image.flaticon.com/icons/svg/188/188237.svg",
"https://image.flaticon.com/icons/svg/188/188238.svg",
"https://image.flaticon.com/icons/svg/188/188239.svg",
"https://image.flaticon.com/icons/svg/188/188240.svg",
"https://image.flaticon.com/icons/svg/188/188241.svg",
"https://image.flaticon.com/icons/svg/188/188242.svg"
]
};
function rollover(element) {
var id = element.getAttribute("id");
if (!isRunning(element)) {
setRunning(element, "true");
setImageSrc(element, thumbNails[id][0]);
start(1, thumbNails[id], element);
}
}
function start(startIndex, thumbNails, element) {
if (!isCanceled(element) && startIndex < thumbNails.length) {
setTimeout(function() {
if (!isCanceled(element)) {
setImageSrc(element, thumbNails[startIndex]);
}
startIndex++;
console.log("currentIndex: " + startIndex + " - Running? " + isRunning(element) + " - Cancel? " + isCanceled(element));
start(startIndex, thumbNails, element);
}, 700);
} else {
setRunning(element, "false");
setCanceled(element, "false");
}
}
function cancel(element) {
console.log("cancel");
if (isRunning(element)) {
setCanceled(element, "true");
}
}
// HELPERS
function isRunning(element) {
return element.getAttribute("isrunning") === "true";
}
function setRunning(element, state) {
element.setAttribute("isrunning", state);
}
function isCanceled(element) {
return element.getAttribute("iscanceled") === "true";
}
function setCanceled(element, state) {
element.setAttribute("iscanceled", state);
}
function setImageSrc(element, url) {
element.setAttribute("src", url);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
</head>
<body>
<img id="123" onmouseover="rollover(this)" onmouseout="cancel(this)" src="https://image.flaticon.com/icons/svg/188/188238.svg" width="100" height="100">
</body>
</html></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<h2>Response to your prompt</h2>\n\n<blockquote>\n <p><strong>Due to my lack of knowledge in JS I would like to know if this is a proper solution.</strong></p>\n</blockquote>\n\n<p>This code sets attributes on the elements to store properties. While this works, it technically leads to invalid HTML<sup><a href=\"https://stackoverflow.com/a/13041243/1575353\">1</a></sup>. Alternatives include using <a href=\"https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes\" rel=\"nofollow noreferrer\">data attributes</a> and setting properties on the variable representing the element. See responses to <a href=\"https://stackoverflow.com/q/992115/1575353\"><em>Custom attributes - Yea or nay?</em></a> and <a href=\"https://stackoverflow.com/q/28650570/1575353\"><em>Associate Data With HTML Element (without jQuery)</em></a></p>\n\n<h2>Other review feedback</h2>\n\n<p>Many developers believe it is good to move all JavaScript code out of the markup. So instead of the <code>onmouseover=...</code> and <code>onmouseout=...</code> attributes, you could register those event handlers in the JavaScript using <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener\" rel=\"nofollow noreferrer\"><code>EventTarget.addEventListener()</code></a></p>\n\n<pre><code>document.addEventListener('DOMContentLoaded', function() {\n var image = document.getElementById('123');\n image.addEventListener('mouseover', rollover);\n image.addEventListener('mouseout', cancel);\n});\n</code></pre>\n\n<p>With an approach like this, the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this\" rel=\"nofollow noreferrer\"><code>this</code></a> keyword inside the functions <code>rollover</code> and <code>cancel</code> refers to the element, so there isn't a need to accept the element as a parameter. If you did want to pass parameters to those functions, it could be achieved using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Partially_applied_functions\" rel=\"nofollow noreferrer\">partially applied-functions</a> with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind\" rel=\"nofollow noreferrer\"><code>Function.bind()</code></a>:</p>\n\n<pre><code> //set context of 'this' to the image and pass string literal '123' as the first parameter\n image.addEventListener('mouseover', rollover.bind(image, '123'));\n</code></pre>\n\n<hr>\n\n<p>The <strong><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/id\" rel=\"nofollow noreferrer\"><code>id</code></a></strong> attribute can be used instead of <code>.getAttribute('id')</code>.</p>\n\n<p>So instead of this line:</p>\n\n<blockquote>\n<pre><code>var id = element.getAttribute(\"id\");\n</code></pre>\n</blockquote>\n\n<p>the same can easily be achieved with:</p>\n\n<pre><code>var id = element.id;\n</code></pre>\n\n<p>This may make assigning that value to a new variable superfluous. </p>\n\n<p><sup>1</sup><sub><a href=\"https://stackoverflow.com/a/13041243/1575353\">https://stackoverflow.com/a/13041243/1575353</a></sub></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T17:26:56.233",
"Id": "429075",
"Score": "0",
"body": "Awesome answer, thank you very much."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T17:02:09.863",
"Id": "221794",
"ParentId": "221777",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "221794",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T12:44:14.323",
"Id": "221777",
"Score": "2",
"Tags": [
"javascript",
"html",
"event-handling",
"dom",
"properties"
],
"Title": "Is this a proper way to cancel an onMouseOver which uses setTimeout? (Vanilla JS)"
} | 221777 |
<p><strong>The task</strong> is taken from <a href="https://leetcode.com/problems/merge-k-sorted-lists/" rel="nofollow noreferrer">LeetCode</a></p>
<blockquote>
<p><em>Merge <code>k</code> sorted linked lists and return it as one sorted list. Analyze and describe its complexity.</em></p>
<p><strong>Example:</strong></p>
<pre><code>Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
</code></pre>
</blockquote>
<p>I'm struggling with the solution as none of them seem to be very fast:</p>
<p><strong>My solution 1</strong></p>
<pre><code>/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode[]} lists
* @return {ListNode}
*/
var mergeKLists = function(lists) {
if (!lists || !lists.length) { return null; }
let pointer;
let firstElement = null;
while (!lists.every(x => x === null)) {
let min;
let iMin;
for (let i = 0; i < lists.length; i++) {
if (lists[i] && (min === void 0 || min > lists[i].val)) {
min = lists[i].val;
iMin = i;
}
}
if (!firstElement) {
firstElement = lists[iMin];
} else {
pointer.next = lists[iMin];
}
pointer = lists[iMin];
if (!lists[iMin].next) {
lists.splice(iMin,1);
} else {
lists[iMin] = lists[iMin].next;
}
}
return firstElement;
};
</code></pre>
<p>Runtime <code>O(k n)</code></p>
<p><strong>My solution 2</strong></p>
<pre><code>/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode[]} lists
* @return {ListNode}
*/
var mergeKLists = function(lists) {
if (!lists || !lists.length) { return null; }
const mergeLists = (l1, l2) => {
if (!l1 || !l2) { return l1 ? l1 : l2; }
let first = null;
let pointer = null;
while(l1 || l2) {
let current;
if (!l1 || !l2) {
current = l1 ? l1 : l2;
if (!first) { return current; }
pointer.next = current;
return first;
}
if (l1.val < l2.val) {
current = l1;
l1 = l1.next;
} else {
current = l2;
l2 = l2.next;
}
if (first) {
pointer.next = current;
} else {
first = current;
}
pointer = current;
}
return first;
}
return lists.reduce((ac, l) => mergeLists(ac, l));
};
</code></pre>
<p>Runtime <code>O(n log k)</code></p>
<p>with <code>k</code> the number of lists elements.</p>
<p><strong>EDIT:</strong></p>
<p>Not really my solution because I read them up and then played around with it:</p>
<p><strong>My solution 3</strong></p>
<pre><code>/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode[]} lists
* @return {ListNode}
*/
var mergeKLists = function(lists) {
if (!lists || !lists.length) { return null; }
const mergeLists = (l1, l2) => {
if (!l1) { return l2; }
if (!l2) { return l1; }
if (l1.val < l2.val) {
l1.next = mergeLists(l1.next, l2);
return l1;
} else {
l2.next = mergeLists(l2.next, l1);
return l2;
}
}
return lists.reduce((ac, l) => mergeLists(ac, l));
};
</code></pre>
<p><strong>My solution 4</strong></p>
<pre><code>/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode[]} lists
* @return {ListNode}
*/
var mergeKLists = function(lists) {
if (!lists || !lists.length) { return null; }
const mergeLists = (l1, l2) => {
if (!l1) { return l2; }
if (!l2) { return l1; }
if (l1.val < l2.val) {
l1.next = mergeLists(l1.next, l2);
return l1;
} else {
l2.next = mergeLists(l2.next, l1);
return l2;
}
}
let i = lists.length;
while(i-- >= 2) {
const l1 = lists.shift();
const l2 = lists.shift();
lists.push(mergeLists(l1,l2));
}
return lists[0];
};
</code></pre>
<p>The solution 3 is just as slow as the other first two. But solution 4 is nearly 3 times as fast, eventhough I just replaced the while loop with the reduce function (<code>reduce</code> is at the end of the day also a loop; but how come the difference is that big?)</p>
<p>Also when I applied the following ecmascript6 syntax to solution 4 it would then be even slower than the other solutions:</p>
<pre><code>var mergeKLists = function(lists) {
if (!lists || !lists.length) { return null; }
const mergeLists = (l1, l2) => {
if (!l1) { return l2; }
if (!l2) { return l1; }
if (l1.val < l2.val) {
l1.next = mergeLists(l1.next, l2);
return l1;
} else {
l2.next = mergeLists(l2.next, l1);
return l2;
}
}
let i = lists.length;
while(i-- >= 2) {
// const l1 = lists.shift();
// const l2 = lists.shift();
// start making changes
const [l1, l2, ...rest] = lists;
lists = rest;
// end making changes
lists.push(mergeLists(l1,l2));
}
return lists[0];
};
</code></pre>
<p>Does deconstructing has such a negative impact on performance?</p>
| [] | [
{
"body": "<h2>Strategies</h2>\n\n<p>It would have been good to summarize the key points and strategies of the different implementations.\nMostly for yourself, to clarify your thinking and solidify your understanding.\nSecondly for reviewers :-)\nLet me take a jab at that now.</p>\n\n<h3>Solution 1</h3>\n\n<ul>\n<li>while there are lists to merge</li>\n<li>find the minimum head and merge it</li>\n<li>update the list with the minimum head or remove it</li>\n</ul>\n\n<p><strong>⇒</strong> The weakness of this solution is the linear step of finding the minimum head.\nA significant improvement would be to use something better.\nFor example, you could put the lists in a heap.\nThen finding the list with the minimum head would become logarithmic.</p>\n\n<h3>Solution 2</h3>\n\n<ul>\n<li>reduce the lists, using a helper function that merges two lists</li>\n<li>the helper function uses a loop to traverse the lists</li>\n</ul>\n\n<p><strong>⇒</strong> The weakness of this solution is the reduce step is sub-optimal.\nIt merges the lists into a single growing list.\nA significant improvement would be to use a divide and conquer approach:\nmerge the first <span class=\"math-container\">\\$k/2\\$</span> lists and the last <span class=\"math-container\">\\$k/2\\$</span> lists,\nmerge their result, and apply this logic recursively.\nThey key is dividing intervals in half.</p>\n\n<h3>Solution 3</h3>\n\n<ul>\n<li>reduce the lists, using a helper function that merges two lists</li>\n<li>the helper function uses recursion to traverse the lists</li>\n</ul>\n\n<p><strong>⇒</strong> The weakness of this solution is the same as the previous:\nthe reduce is not using divide and conquer.\nWhether you use a loop or recursion doesn't make a difference if the stack limit is not reached during recursion.</p>\n\n<h3>Solution 4</h3>\n\n<ul>\n<li>while there are lists to merge</li>\n<li>merge the first two lists, append the resulting list to the end</li>\n<li>the helper function uses recursion to traverse the lists</li>\n</ul>\n\n<p><strong>⇒</strong> This solution implements a divide and conquer logic,\nand that makes it significantly faster as the input grows.\nThis solution does pass the online judge.</p>\n\n<p>It seems you thought the loop in this solution is the same as what reduce does,\nand that's not the case, that's the key difference.</p>\n\n<h3>Key takeaways</h3>\n\n<ul>\n<li>verify assumptions (how reduce actually works)</li>\n<li>trust what you know: recursion and iteration are equivalent in terms of time complexity. If you see an important difference in the result, then you're probably overlooking a key difference somewhere else, perhaps due to an incorrect assumption</li>\n<li>clear your mind and seek the key differences</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-17T07:35:23.603",
"Id": "237421",
"ParentId": "221780",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T13:04:18.530",
"Id": "221780",
"Score": "1",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"linked-list",
"functional-programming"
],
"Title": "Merge k Sorted Lists"
} | 221780 |
<p>I finished my university project for calculating <span class="math-container">\$1/\pi\$</span> and I would love to get some feedback.</p>
<p>Before you guys jump into this code please keep in mind newcomer to C++ just decided to use it for this project because I assumed libraries will be better than others in terms of arbitrary precision.</p>
<p>Few words about the project, it should be a console application with some parameters like (how many terms of the formula to be calculated, how many threads should be used, log level and more if desired).</p>
<p>I am using MPFR and MPIR on Windows for the arbitrary precision calculations and Visual C++ compiler with no extra flags other than the one set up by Visual Studio (perhaps I can be advised here :) ).</p>
<p>I am interested in following feedbacks priority is in the given order</p>
<ol>
<li>Performance</li>
<li>Readability</li>
<li>Design?</li>
</ol>
<p>Since the project tends to be big I will only put the parts I am interested the most (calculation) if anyone else would like to advise me over the overall design please check my <a href="https://github.com/kuskmen/Random/tree/bba7134ffc3be81e06be21f5e307b5e009719d3a/ParallelPi" rel="noreferrer">repository</a> for the full code base.</p>
<p><strong>main.cpp</strong></p>
<pre class="lang-cpp prettyprint-override"><code>boost::multiprecision::mpfr_float inc_multiply(long start, long end)
{
boost::multiprecision::mpfr_float fact = 1;
for (; start <= end; ++start)
fact *= start;
return fact;
}
// <-- the real calculation of pi
boost::multiprecision::mpfr_float calculatePi(int count, ...)
{
using boost::multiprecision::mpfr_float;
mpfr_float partition;
std::stringstream ss;
ss << std::this_thread::get_id();
std::string thread_id = ss.str();
LOG_VERBOSE("Thread id: " + thread_id + " started.\n");
auto clock_start = std::chrono::system_clock::now();
std::va_list ranges;
va_start(ranges, count);
for (int i = 0; i < count; ++i)
{
auto boundary = va_arg(ranges, range_t);
mpfr_float previous_fac_start = 1.0;
mpfr_float previous_fac_4xstart = 1.0;
for (; boundary.first < boundary.second; ++boundary.first)
{
mpfr_float fac_start = previous_fac_start * (boundary.first == 0 ? 1 : boundary.first);
mpfr_float fac_4xstart = previous_fac_4xstart * inc_multiply((4 * boundary.first - 3) < 0 ? 1 : 4 * boundary.first - 3, 4 * boundary.first);
mpfr_float n = fac_4xstart * mpfr_float(1103 + 26390 * boundary.first);
mpfr_float d = boost::multiprecision::pow(fac_start, 4) * boost::multiprecision::pow((mpfr_float)396, 4 * boundary.first);
partition += (n / d);
previous_fac_start = fac_start;
previous_fac_4xstart = fac_4xstart;
}
}
va_end(ranges);
std::chrono::duration<double> elapsed = std::chrono::system_clock::now() - clock_start;
LOG_VERBOSE("Thread id: " + thread_id + " stopped.\n");
LOG_VERBOSE("Thread " + thread_id + " execution time was " + std::to_string(elapsed.count()) + "ms\n");
return (2 * boost::multiprecision::sqrt((mpfr_float)2) / 9801) * partition;
}
// <-- used to setup the strategy for calculation
boost::multiprecision::mpfr_float calculate(ProgramOptions* options)
{
std::vector<std::future<boost::multiprecision::mpfr_float>> futures;
// Choose thread work sepration strategy
// TODO: Fix duplication, think of dynamic creation of strategies.
if (options->IsOptimized())
{
auto strategy = new OptimizedSeparationStrategy();
auto partitions = strategy->Separate(options->GetIterations(), options->GetThreadsCount());
for (auto partition : partitions)
futures.emplace_back(std::async(calculatePi, 2, partition.first, partition.second));
}
else
{
auto strategy = new EqualSeparationStrategy();
auto partitions = strategy->Separate(options->GetIterations(), options->GetThreadsCount());
for (auto partition : partitions)
futures.emplace_back(std::async(calculatePi, 1, partition));
}
boost::multiprecision::mpfr_float pi;
for (auto threadId = 0; threadId < futures.size(); ++threadId)
pi += futures[threadId].get();
return pi;
}
</code></pre>
<p><strong>SeparationStrategy.cpp</strong></p>
<pre class="lang-cpp prettyprint-override"><code>simple_ranges NaiveSeparationStrategy::Separate(long iterations, short threads)
{
simple_ranges ranges;
if (threads == 0)
return ranges;
ranges.reserve(threads);
auto chunk = iterations / threads;
auto remainder = iterations % threads;
auto loopIterations = 0;
for (auto partition = 0; partition <= iterations - chunk + loopIterations; partition += chunk + 1)
{
ranges.emplace_back(partition, partition + chunk > iterations ? iterations : partition + chunk);
++loopIterations;
}
return ranges;
}
advanced_ranges OptimizedSeparationStrategy::Separate(long iterations, short threads)
{
advanced_ranges ranges;
if (threads == 0)
return ranges;
ranges.reserve(threads);
auto leftChunk = 0, rightChunk = 0;
if ((iterations / threads) % 2 != 0)
{
leftChunk = (iterations / threads) / 2;
rightChunk = (iterations / threads) / 2 + 1;
}
else
{
leftChunk = rightChunk = (iterations / threads) / 2;
}
long l = 0, r = iterations, previous_l = l, previous_r = r;
while (l < r)
{
ranges.emplace_back(std::make_pair(previous_l, l + leftChunk), std::make_pair(r - rightChunk, previous_r));
previous_l = l + leftChunk + 1;
previous_r = r - rightChunk - 1;
l += leftChunk;
r -= rightChunk;
}
// make last range excluding last number
// as it will be calculated from the second last range.
ranges.back().first.second--;
return ranges;
}
</code></pre>
| [] | [
{
"body": "<p>Couple of things I found myself so far.</p>\n\n<h3>Performance wise</h3>\n\n<hr>\n\n<p><a href=\"https://stackoverflow.com/questions/600795/asynchronous-vs-multithreading-is-there-a-difference\">Huge mistake</a>, to use <code>std::async</code> for multiprocessing, while testing it on my local machine with only one CPU it worked okay, using all the cores, but when switched to test server with more than one CPU, I failed to use all of them (actually 32). Changing this <code>std::thread</code> , without any pain btw, did the job and I wasable to utilize all the CPUs on the test server.</p>\n\n<h3>Design</h3>\n\n<hr>\n\n<p>My so-called \"optimized\" separation of work of the threads prevents me from implementing graceful shutdown eventually because if I need to calculate 1000 terms of this formula, work is separated like so </p>\n\n<p><img src=\"https://raw.githubusercontent.com/kuskmen/Random/master/ParallelPi/assets/optimized-intervals.png\" /></p>\n\n<p>where 1,2,3... are thread_ids. A separation like this is good for maintaining equal work among your threads, but like I said it prevents the ability to provide graceful shutdown due to calculation not being done in a serial matter.</p>\n\n<hr>\n\n<p>Well, so far, this is what I've found, I will add more to the list whenever I found other problems with my code. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T16:27:19.410",
"Id": "221937",
"ParentId": "221781",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T13:53:22.600",
"Id": "221781",
"Score": "7",
"Tags": [
"c++",
"performance",
"c++11",
"numerical-methods",
"boost"
],
"Title": "Parallel Ramanujan's formula for 1/π calculation"
} | 221781 |
<p>I created a code that import the data regularly into a selected workbook. The code run well, it takes less than 20 seconds before the data is imported successfully.</p>
<p>How does it work?</p>
<p>I get a monthly data with Excel format. I want the data to be imported into my workbook to be analysed further.</p>
<ul>
<li>Step by step</li>
</ul>
<p>The first part of my code run to copy the data from monthly workbook to analysis workbook.</p>
<p>The second part is a macro that will copy the content from the new data imported into a template table analysis based on the header. The code will only copy the content of columns if the header between 2 tables match.</p>
<p>Finally, I decided to add in the middle of the body of code, only for client's name column, before the macro copies all the rows at that column. I asked it to change the case of the value for each row to be UPPERCASE.</p>
<p>After adding this one line of code, my code run for 20 minutes.</p>
<p>Can someone help me to give another solution for the code to change the case to be "UPPERCASE" and also to reduce the runtime?</p>
<pre><code>Option Explicit
Dim lastRow As Long, LastTemp As Long 'lasttemp is "last row for table template
Const StartRowTemp As Byte = 1
Dim c As Byte 'number of columns
Dim GetHeader As Range 'find
Call Entry_Point 'to prevent screen updating and display alert, the value is False
' On Error GoTo Handle
'pick files to import - allow multiselect
FiletoOpen = Application.GetOpenFilename _
(FileFilter:="Excel Files (*.xlsx), *.xlsx", Title:="Select Workbook to Import", MultiSelect:=True)
If IsArray(FiletoOpen) Then
For FileCnt = 1 To UBound(FiletoOpen)
Set SelectedBook = Workbooks.Open(Filename:=FiletoOpen(FileCnt))
ShDataN.Cells.Clear
SelectedBook.Worksheets("Client").Cells.Copy
ShDataN.Range("A1").PasteSpecial xlPasteValuesAndNumberFormats
SelectedBook.Close
'locate last empty row in Monthly Table
lastRow = ShMN.Cells(Rows.Count, 1).End(xlUp).Row + 1
'locate last row in the new data
LastTemp = ShDataN.Cells(Rows.Count, 1).End(xlUp).Row
'delete the content from Analysis table
ShMN.Rows("2:" & ShMN.Rows.Count).ClearContents
'do while to find matching headers before copy paste
c = 1
Do While ShMN.Cells(1, c) <> ""
Set GetHeader = ShDataN.Rows(StartRowTemp).Find _
(What:=ShMN.Cells(1, c).Value, LookIn:=xlValues, MatchCase:=False, lookat:=xlWhole)
If Not GetHeader Is Nothing Then
ShDataN.Range(ShDataN.Cells(StartRowTemp + 1, GetHeader.Column), ShDataN.Cells(LastTemp, GetHeader.Column)).Copy
ShMN.Cells(2, c).PasteSpecial
ShMN.Rows("2:" & ShMN.Rows.Count).ClearFormats
Call Range_Case
'to change the case on column Client's name after copying
'
' Set myrange = ShMN.Range("B2", "B" & Cells(Rows.Count, 1).Row)
'
' For Each cell In myrange
'
' cell.Value = UCase(cell)
'
' Next cell
End If 'get Header
c = c + 1
Loop
Next FileCnt
MsgBox "Data imported sucessfully", vbInformation, "General Information"
End If 'isArray
ShDataN.Cells.Clear
With ShNote
.Select
.Range("A1").Select
End With
Call Exit_Point
'Handle:
' If Err.Number = 9 Then
' Else
' MsgBox "An error has occured"
' End If
Call Exit_Point
End Sub
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T15:52:37.497",
"Id": "429045",
"Score": "0",
"body": "You have an `Exit Sub` but no opening `Sub` statement. In order to give a meaningful review we need code that can compile in order for us to run it. Please edit your question so that your provided example can compile."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T05:09:47.020",
"Id": "429139",
"Score": "0",
"body": "*sigh* `Call` is deprecated. Funny, if you weren't using `Call`, you would probably have thought of using a `Function` to either return a modified string or to loop through a given range changing the case of each value if appropriate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T15:35:29.167",
"Id": "429232",
"Score": "0",
"body": "@IvenBach thanks for your comments. I forgot to delete exit sub, it was part of my previous code that I didn't use anymore. I edited my code. Can you help me please?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T18:50:26.720",
"Id": "429264",
"Score": "0",
"body": "You'll need to edit your code further. You have no `Public Sub SubproceduresName` indicating where your sub starts, I'm assuming immediately after `Option Explicit`. Because you have `Option Explicit` included you have to `Explicit`ly declare all variables. `ShDataN` is used but never declared somewhere like `Dim ShDataN as Worksheet`. You need to include `Entry_Point` as well. Until we can copy/paste your example code and have it compile we will be unable to give an adequate review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-11T15:17:32.847",
"Id": "429724",
"Score": "1",
"body": "Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have [rolled back Rev 5 → 4](https://codereview.stackexchange.com/posts/221785/revisions#rev-arrow-ff162341-0d23-47b8-83cf-086cd8aa29a5)"
}
] | [
{
"body": "<p>For testing your code following assumption are made</p>\n\n<ol>\n<li><p>Sub Entry_Point was disabling screen updating, events and display alerts. </p></li>\n<li><p>Sub Exit_Point was enabling screen updating, events and display alerts.</p></li>\n<li><p>It is being used for importing data from <em>multiple files</em> and to be finally placed in Sheet<code>ShMN</code> one below another</p></li>\n</ol>\n\n<p>according to the above assumption following modification was done</p>\n\n<p>1 Sheet <code>ShMN</code> is being cleared with in loop <code>For FileCnt = 1 To UBound(FiletoOpen)</code> with line <code>ShMN.Rows(\"2:\" & ShMN.Rows.Count).ClearContents</code>. I pulled out the line out of the For loop for testing purpose.</p>\n\n<p>2.The line <code>ShMN.Cells(2, c).PasteSpecial</code> modifed to <code>ShMN.Cells(lastRow, c).PasteSpecial</code> for placing data from each file one below another (This to avoid 1st files data to be overwritten by subsequent files data). </p>\n\n<ol start=\"3\">\n<li>Finally as the cause of slow performance, it is found the <strong>Case Changing codes are placed inside header finding loop</strong>.So it is executing Number of files X Number of columns times. I pulled it out of even file loop and placed just after completion of Data import.</li>\n<li>Myrange was defined \"B2:B\" & Rows Count. I change it to <code>Set MyRange = ShMN.Range(\"B2:B\" & ShMN.Cells(Rows.Count, 2).End(xlUp).Row)</code></li>\n</ol>\n\n<p>For Testing purpose, I used 5 files consisting same Data of 500 rows X 52 Columns with header. I have not used Calculation mode manual, Screen update disable etc (as I generally don't prefer these). You may use the techniques as per your requirement. It takes around 50 seconds to import all 5 files data and only another <strong>3 odd seconds</strong> to change the case of B column (in my old laptop)</p>\n\n<p>My test code:</p>\n\n<pre><code>Option Explicit\nSub test()\nDim Tm As Long\nDim FiletoOpen As Variant, ShDataN As Worksheet, ShMN As Worksheet\nDim FileCnt As Long, SelectedBook As Workbook, MyRange As Range, cell As Range\nTm = Timer\nSet ShDataN = ThisWorkbook.Sheets(1)\nSet ShMN = ThisWorkbook.Sheets(2)\n\n\n\n Dim lastRow As Long, LastTemp As Long 'lasttemp is \"last row for table template\n Const StartRowTemp As Byte = 1\n Dim c As Byte 'number of columns\n Dim GetHeader As Range 'find\n\n 'Call Entry_Point 'to prevent screen updating and display alert, the value is False\n 'Application.ScreenUpdating = False\n 'Application.EnableEvents = False\n Application.DisplayAlerts = False\n' On Error GoTo Handle\n\n 'pick files to import - allow multiselect\n FiletoOpen = Application.GetOpenFilename _\n (FileFilter:=\"Excel Files (*.xlsx), *.xlsx\", Title:=\"Select Workbook to Import\", MultiSelect:=True)\n\n If IsArray(FiletoOpen) Then\n 'delete the content from Analysis table\n ShMN.Rows(\"2:\" & ShMN.Rows.Count).ClearContents ' moved out of For foleCnt loop\n\n For FileCnt = 1 To UBound(FiletoOpen)\n Set SelectedBook = Workbooks.Open(Filename:=FiletoOpen(FileCnt))\n ShDataN.Cells.Clear\n SelectedBook.Worksheets(\"Client\").Cells.Copy\n ShDataN.Range(\"A1\").PasteSpecial xlPasteValuesAndNumberFormats\n SelectedBook.Close False\n\n 'locate last empty row in Monthly Table\n lastRow = ShMN.Cells(Rows.Count, 1).End(xlUp).Row + 1\n\n 'locate last row in the new data\n LastTemp = ShDataN.Cells(Rows.Count, 1).End(xlUp).Row\n\n\n 'do while to find matching headers before copy paste\n c = 1\n Do While ShMN.Cells(1, c) <> \"\"\n\n Set GetHeader = ShDataN.Rows(StartRowTemp).Find _\n (What:=ShMN.Cells(1, c).Value, LookIn:=xlValues, MatchCase:=False, lookat:=xlWhole)\n If Not GetHeader Is Nothing Then\n ShDataN.Range(ShDataN.Cells(StartRowTemp + 1, GetHeader.Column), ShDataN.Cells(LastTemp, GetHeader.Column)).Copy\n ShMN.Cells(lastRow, c).PasteSpecial ' row 2 modified to lastRow\n ShMN.Rows(\"2:\" & ShMN.Rows.Count).ClearFormats\n' Call Range_Case\n 'to change the case on column Client's name after copying\n\n\n End If 'get Header\n c = c + 1\n Loop\n\n Next FileCnt\n\nDebug.Print Timer - Tm\nDim MyArr As Variant, FinalArr() As Variant, i As Long\n Set MyRange = ShMN.Range(\"B2:B\" & ShMN.Cells(Rows.Count, 2).End(xlUp).Row)\n\n 'For Each cell In MyRange\n 'cell.Value = UCase(cell)\n 'Next cell\n\n MyArr = MyRange.Value\n ReDim FinalArr(LBound(MyArr, 1) To UBound(MyArr, 1))\n For i = LBound(MyArr, 1) To UBound(MyArr, 1)\n FinalArr(i) = UCase(MyArr(i, 1))\n Next\n\n MyRange.Value = FinalArr\n\n 'MsgBox \"Data imported sucessfully\", vbInformation, \"General Information\"\n\n End If 'isArray\n ShDataN.Cells.Clear\n\n 'With ShNote\n ' .Select\n ' .Range(\"A1\").Select\n 'End With\n\n Application.ScreenUpdating = True\n Application.EnableEvents = True\n Application.DisplayAlerts = True\n\nDebug.Print Timer - Tm\nEnd Sub\n</code></pre>\n\n<p>Finally I tried the case changing with arrays to minimize excel cell operations as my ethic. You may use your process (commented out). it hardly affect performance in this case.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-11T13:27:41.893",
"Id": "429708",
"Score": "0",
"body": "Hello, Thank you for your help. You described very well each part of my code. However, after trying your code for \"Range Case\" it didn't work. I will edit my original post and hope you can tell me which part that I have mistakenly written. Thank again @Ahmed AU"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-11T13:32:02.653",
"Id": "429710",
"Score": "0",
"body": "I forgot to explain the reason behind \"ShMN.Cells(lastRow, c).PasteSpecial\", why I didn't put \"lastrow\" on the place of \"2\" because I didn't want the macro to bring the new data and paste it on the next empty row. To prevent the overwritten data, I put this macro \"ShMN.Rows(\"2:\" & ShMN.Rows.Count).ClearContents\" before \"do while function\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-11T14:23:17.607",
"Id": "429718",
"Score": "0",
"body": "Hello, I got the right code for change case. Thanks for your help"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T14:30:31.577",
"Id": "221965",
"ParentId": "221785",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T15:13:06.177",
"Id": "221785",
"Score": "2",
"Tags": [
"vba",
"excel"
],
"Title": "Change case the data inside a column"
} | 221785 |
<p>This is a simple gravity simulator coded in Python 3.7 using Numpy and Pygame. I was wondering if it can be optimized further. Initially I had coded it using pure Python lists, using nested loops to calculate forces between each body, but then <a href="https://www.reddit.com/r/Python/comments/bw88o8/my_computer_fried_at_1000_particles_gravity/" rel="nofollow noreferrer">the good people of Reddit</a> suggested me to use Numpy, Cython or Numba to improve the runtime of the code. Some even suggested a few highly optimized algorithms which are used to improve the time complexity of N-Body simulations like the <a href="https://en.wikipedia.org/wiki/Barnes%E2%80%93Hut_simulation" rel="nofollow noreferrer">Barnes Hut algorithm</a>. For v2, I decided to use Numpy and have kept Barnes-Hut for the scope of future. Here is the implementation in numpy : </p>
<p>Can it be optimized further?</p>
<pre><code>import sys
import time
import numpy as np
import pygame
G = 6.67408e-11 * 100_000_000 # Otherwise the bodies would not move given the small value of gravitational constant
NUM_OF_BODIES = 4000
WIDTH = 1200
HEIGHT = 800
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (109, 196, 255)
vx = np.zeros((NUM_OF_BODIES,),dtype=np.float)
vy = np.zeros((NUM_OF_BODIES,),dtype=np.float)
px = np.random.uniform(low=10, high=WIDTH-10,size=NUM_OF_BODIES)
py = np.random.uniform(low=10, high=HEIGHT-10,size=NUM_OF_BODIES)
m = np.random.randint(1,25,size=NUM_OF_BODIES)
fx = np.zeros((NUM_OF_BODIES,),dtype=float)
fy = np.zeros((NUM_OF_BODIES,),dtype=float)
pygame.init()
size = WIDTH, HEIGHT
screen = pygame.display.set_mode(size)
font = pygame.font.SysFont('Arial', 16)
text = font.render('0', True, BLUE)
textRect = text.get_rect()
while True:
screen.fill(BLACK)
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
in_t = time.time()
for i in range(0,NUM_OF_BODIES):
xdiff = (px - px[i])
ydiff = (py - py[i])
distance = np.sqrt(xdiff ** 2 + ydiff ** 2)
f = G * m[i] * np.divide(m,distance ** 2)
sin = np.divide(ydiff,distance)
cos = np.divide(xdiff,distance)
fx_total = np.nansum(np.multiply(f, cos))
fy_total = np.nansum(np.multiply(f,sin))
vx[i] = vx[i] + fx_total / m[i]
vy[i] = vy[i] + fy_total / m[i]
px[i] = px[i] + vx[i]
py[i] = py[i] + vy[i]
pygame.draw.rect(screen, (255, 255, 255), pygame.Rect(px[i], py[i], m[i],m[i]))
print(time.time() - in_t)
pygame.display.flip()
</code></pre>
| [] | [
{
"body": "<ul>\n<li><p>The positions of the bodies are modified in-place, while the loop is running. It means that in your universe the action is not equal to reaction. Your simulation will exhibit some nonrealistic behaviors, like drift of the center of the mass.</p></li>\n<li><p>Euler integration method is not the most accurate. Consider Runge-Kutta. At least, monitor the motion invariants (total energy, momentum, and angular momentum of the ensemble), and do corrective actions when they start diverging.</p></li>\n<li><p>After <code>f = m[i] * ...</code> and <code>f_total / m[i]</code> the mass cancels. Multiplication and division could be safely omitted.</p></li>\n<li><p>Along the same line, scale the masses by <code>G</code> once, before the simulation begins.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T20:18:41.570",
"Id": "221807",
"ParentId": "221786",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T15:18:51.720",
"Id": "221786",
"Score": "4",
"Tags": [
"python",
"performance",
"numpy",
"pygame",
"physics"
],
"Title": "Gravity simulation using Numpy and Pygame"
} | 221786 |
<p>Function queries data from an Aurora database. Aurora database is the MySQL engine therefore, I'm querying it with a MySQL NPM module. If there is something better, I'm all ears.</p>
<p>The calling function has a try-catch block to manage exceptions. This function just connects to Aurora, submits a query, and displays the results to the console.</p>
<pre><code>const mysql = require('mysql');
function aurora_query_decorator(host, user, password, port, database) {
const esb_db_connectionstring = {
"host" : host,
"user" : user,
"password" : password,
"port" : port,
"database" : database,
"connectTimeout" : 5000
};
console.log('Connection String: ', esb_db_connectionstring);
console.log("Attempting to connect to Aurora...");
const esb_db = mysql.createConnection(esb_db_connectionstring);
esb_db.connect( (error) => {
if (error) throw error;
const esb_db_query_sql = "select * from things";
console.log('Query: ', esb_db_query_sql);
console.log("Attempting to query Aurora...");
esb_db_query = esb_db.query(esb_db_query_sql);
esb_db_query.on('error', error => { throw error } );
esb_db_query.on('fields', data => { console.log(data) } );
esb_db_query.on('end', () => { esb_db.end() } );
});
return;
}
</code></pre>
<p>Looking for general feedback. All constructive feedback welcome.</p>
<p>Ultimately, I'll be querying Aurora from Lambda functions. Does it make sense to try to <a href="https://www.npmjs.com/package/mysql#pooling-connections" rel="nofollow noreferrer">pool connections</a>?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T15:23:21.223",
"Id": "221787",
"Score": "2",
"Tags": [
"javascript",
"mysql",
"node.js"
],
"Title": "Querying Aurora via Node.js"
} | 221787 |
<p>I have <span class="math-container">\$10^5\$</span> to <span class="math-container">\$10^6\$</span> points on a sphere, and want to choose some points from them which are as close as uniformly distributed as possible. For that reason, I do the following: at each step I add the point in the data which is farthest away from any point which I have already chosen. In order to do this, I find the closest distance from each point in the data to any of the points that are already chosen. Then I pick the point from the data which has the largest minimum distance to any of the points that are already chosen. The algorithm is the following:</p>
<ol>
<li><p>Choose a random point from all the <span class="math-container">\$10^6\$</span> points, add it to the chosen set of points</p></li>
<li><p>For each of the <span class="math-container">\$10^6\$</span> points:</p>
<p>2.1 Find the distances to all the points which are chosen already</p>
<p>2.2 Find the min distance to a point which is chosen already</p>
<p>2.3 Find the point which is furthest away from any point which is chosen already</p>
<p>2.4 Add this point to the chosen points</p></li>
<li><p>Repeat 2 until I have enough points (say 1000 or 10000 or 100000).</p></li>
</ol>
<p><code>data</code> is <span class="math-container">\$10^6\$</span> by 3 array of points on a sphere, e.g.</p>
<pre><code>[[ 0.26750522 -0.92342735 0.27517791]
[-0.26753053 0.9228284 -0.27715548]
[ 0.34058837 0.35873472 0.86908513]
[-0.33563178 -0.35794416 -0.8713365 ]
[-0.8945523 -0.15682272 0.41854847]
[ 0.906739 0.15103321 -0.39371734]
[ 0.49138659 -0.64830133 -0.581588 ]
[-0.87922161 0.24492971 -0.40863039]
[ 0.18062012 0.39852148 -0.89919798]
[-0.49103509 0.65872966 0.57005243]
[-0.55615839 -0.82248645 -0.11918007]
[ 0.85802915 -0.25207255 0.44748789]
[-0.16990087 -0.40390349 0.89888579]]
</code></pre>
<p>I have implemented this in Python:</p>
<pre><code>import random
import numpy
N = 1000
starting_point_ind = random.SystemRandom().randint (1 , len(data))
points_from_data = numpy.array(numpy.zeros((N, 3)), dtype=float, order='C')
points_from_data[0] = data[starting_point_ind]
for i in range(1, N):
distancesToClosestPoints = numpy.array(numpy.zeros(len(data)), dtype=float)
for j, point in enumerate(data):
distancesToEstablishedPoints = numpy.linalg.norm (point - points_from_data[0:i] , axis=1)
distancesToClosestPoints[j] = distancesToEstablishedPoints.min()
k = distancesToClosestPoints.argmax()
points_from_data[i] = data[k]
</code></pre>
<p>This doesn't run very efficiently for large N, so I also tried to optimise it by doing</p>
<pre><code>import random
from sklearn.metrics import pairwise_distances
import time
t0 = time.time()
N = 1000
starting_point_ind = random.SystemRandom().randint (1 , len(data))
points_from_data = numpy.array([data[starting_point_ind]])
for i in range(1, N):
pairwise_distances_to_data = pairwise_distances (data, Y=points_from_data, metric='euclidean', n_jobs=-1)
pairwise_distances_to_data = numpy.array(pairwise_distances_to_data)
min_distances_to_data = numpy.amin(pairwise_distances_to_data, axis=1)
k = min_distances_to_data.argmax()
points_from_data = numpy.append(points_from_data, [data[k]], axis=0)
print(points_from_data)
</code></pre>
<p>But this still has the issue that the pairwise distances are computed each time, and has obvious memory issues for large N. I would like to hear suggestions how I can improve the performance of the algorithm.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T17:13:43.060",
"Id": "429068",
"Score": "0",
"body": "You might be interested in this [article](https://arxiv.org/pdf/cs/0701164.pdf). Make a mesh of necessary size, and pick one point per triangle."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T18:32:14.393",
"Id": "429084",
"Score": "0",
"body": "@Gordon I think you've got a good question in your hands, you just need to clarify what your code really does and what you really want your code to do, then ask yourself if you've achieved your goal."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T18:49:23.077",
"Id": "429086",
"Score": "0",
"body": "If I compute the norm of two of the vectors you gave in the `data` example, they are not the same length, so points in data aren't part of a sphere. Is the example data not good or is there something that doesn't work?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T18:53:43.293",
"Id": "429087",
"Score": "2",
"body": "@IEatBagels I realise my description of what I am trying to achieve was loose at first, but I think our discussion narrowed it down. At any rate, the results produced by the 2 chunks of code are equivalent and are exactly what I need. I just want to know if I can do it in a better way and faster. The vectors in data should have a norm of around 1.0+/-eps. I think the discrepancy comes from not copying enough significant figures when I pasted it from Jupyter. You can easily generate 10^6 points on the sphere, though."
}
] | [
{
"body": "<p>Since we can assume all your points are on a sphere, there is a better way to compute distance than using the L2 Norm (Euclidean distance, which you're using).</p>\n\n<p>If we transform your data points to <a href=\"https://en.wikipedia.org/wiki/Spherical_coordinate_system#Cartesian_coordinates\" rel=\"nofollow noreferrer\">Spherical coordinates</a>, we could use a simple Manhattan distance on the theta and rho coordinates, which is less expensive to compute. Since you compute this distance about <span class=\"math-container\">\\$Nm\\$</span> times (6 million points * 1000 sample points), I'm sure it would make a good performance difference.</p>\n\n<p>Small note on the Spherical Coordinates :</p>\n\n<p>Instead of having x,y,z coordinates, we use r, theta, rho, which correspond to :</p>\n\n<ul>\n<li>r : the length of the vector</li>\n<li>theta : angle on the XY plane</li>\n<li>phi : angle of inclination starting from theta</li>\n</ul>\n\n<p>So, to change <code>data</code> to spherical coordinates, we'd do the following (I assume data is arranged in a x,y,z manner). The conversion is very fast, but it could be further optimized if needed :</p>\n\n<pre><code>def convert_to_spherical(data):\n spherical_data = np.zeros_like(data)\n for i,d in enumerate(data):\n r = math.sqrt(d[0]**2 + d[1]**2 + d[2]**2)\n theta = math.acos(d[2] / r)\n phi = math.atan(d[1] / d[0])\n\n spherical_data[i] = np.array([r, theta, phi])\n\n return spherical_data\n</code></pre>\n\n<p>Then, you could use this instead of <code>data</code> and change the metric used by <code>pairwise_distances</code> to <code>manhattan</code>. You'll need to dig a little bit to understand why this works, but consider that since the parameter r is always the same, you can simply compute the difference between the angles.</p>\n\n<p>Since my laptop is pretty bad, I couldn't generate data to sample 1000 points out of 1000000. These times were generated sampling 300 points from 100000 points, I started timing after generating the points but I included the coordinates transformation in the times :</p>\n\n<pre><code>Time using your optimized solution : 213.1844208240509s\nTime using the spherical coordinates : 140.83173203468323s\n</code></pre>\n\n<p>Considering this pretty big time difference, I'm pretty sure performance would be much better on your data sample.</p>\n\n<p>If afterwards, you need to get your coordinates back to the cartesian plane, the formula is pretty easy and you can find it online easily.</p>\n\n<p>I've generated the points using thanks to <a href=\"https://stackoverflow.com/questions/33976911/generate-a-random-sample-of-points-distributed-on-the-surface-of-a-unit-sphere/33977070\">this answer</a> : </p>\n\n<pre><code>def sample_spherical(npoints, ndim=3):\n vec = numpy.random.randn(ndim, npoints)\n vec /= numpy.linalg.norm(vec, axis=0)\n return numpy.transpose(vec)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T21:01:17.110",
"Id": "429109",
"Score": "0",
"body": "Thank you for the answer. I have a question about using the Manhattan distances. Imagine I am comparing 2 points with \\((\\theta_1, \\phi_1) = (0, 0.1)\\) and \\((\\theta_2, \\phi_2) = (0, 2\\pi - 0.1)\\). This would imply they are a distance \\(2\\pi - 0.2\\) apart, when in reality they are a distance of 0.2 apart. Wouldn't this mess up the algorithm?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T21:58:45.897",
"Id": "429113",
"Score": "1",
"body": "I'm pretty damn sure `convert_to_spherical` can also be computed using numpy instead of looping over the data rows as you do in your current implementation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T00:12:26.633",
"Id": "429123",
"Score": "0",
"body": "So how would I compare the distances then?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T13:42:04.647",
"Id": "429213",
"Score": "0",
"body": "@Gordon I misread your question I'm sorry. I understand your problem and I didn't think about it at first, because if we're talking about radians 2*pi = , but the algorithm won't figure that out. You'd need to create a custom distance metric based on the manhattan distance that makes a modulo 2*pi. I'm pretty confident it'll still be faster, but I'm sorry I didn't think about it first."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T13:44:13.850",
"Id": "429214",
"Score": "0",
"body": "@Gordon you could also check this out : https://en.wikipedia.org/wiki/Great-circle_distance"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T15:29:22.500",
"Id": "429230",
"Score": "0",
"body": "@IEatBagels yes, but computing the great circle distance would be at least as expensive as computing the Euclidean distance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T15:31:12.530",
"Id": "429231",
"Score": "0",
"body": "@Gordon I'm unsure about what to do ahah, I feel like my answer is misleading because it is incomplete, do you see any value to it or do you feel like I should delete it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T18:07:54.443",
"Id": "429258",
"Score": "0",
"body": "@IEatBagels no need to delete it, if nothing else it demonstrates that using spherical coordinates does not help much."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T19:47:33.510",
"Id": "221803",
"ParentId": "221789",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T15:58:37.797",
"Id": "221789",
"Score": "6",
"Tags": [
"python",
"performance",
"algorithm",
"numpy",
"computational-geometry"
],
"Title": "Choosing evenly distributed points from a million points on a sphere"
} | 221789 |
<p>This code takes in input as audio files (.wav or .WAV) and divides them into fixed-size (chunkSize in seconds) samples. Then these chunks are converted to spectrogram images after applying PCEN (Per-Channel Energy Normalization) and then wavelet denoising using librosa.</p>
<p>My concern now is how to improve the performance and <strong>speed</strong> up this whole process of conversion. The code actually maintains the directory structure of the parent which is essential for my project.</p>
<p>I'll be running this on Google Colab over approx. ~50k audio files of varying durations from 5min - 25mins. But eventually, the script needs to run better and fast in my local computer. Is there a way to use parallel-processing here?
Currently while running this on Google Colab, in the conversion stage of audio chunks to images and saving them, after saving around ~1k images, it eats up all the RAM and stops.</p>
<pre><code>#!/usr/bin/env python3
# coding=utf-8
# Imports
import os
import argparse
import matplotlib.pyplot as plt
import librosa
import librosa.display
import numpy as np
from skimage.restoration import (denoise_wavelet, estimate_sigma)
from pydub import AudioSegment
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
# Supress matplotlib warnings
plt.rcParams.update({'figure.max_open_warning': 0})
def padding(data, input_length):
'''Padding of samples to make them of same length'''
if len(data) > input_length:
max_offset = len(data) - input_length
offset = np.random.randint(max_offset)
data = data[offset:(input_length + offset)]
else:
if input_length > len(data):
max_offset = input_length - len(data)
offset = np.random.randint(max_offset)
else:
offset = 0
data = np.pad(data, (offset, input_length - len(data) - offset), "constant")
return data
def audio_norm(data):
'''Normalization of audio'''
max_data = np.max(data)
min_data = np.min(data)
data = (data - min_data) / (max_data - min_data + 1e-6)
return data - 0.5
def mfcc(data, sampling_rate, n_mfcc):
'''Compute mel-scaled feature using librosa'''
data = librosa.feature.mfcc(data, sr=sampling_rate, n_mfcc=n_mfcc)
# data = np.expand_dims(data, axis=-1)
return data
def apply_per_channel_energy_norm(data, sampling_rate):
'''Compute Per-Channel Energy Normalization (PCEN)'''
S = librosa.feature.melspectrogram(
data, sr=sampling_rate, power=1) # Compute mel-scaled spectrogram
# Convert an amplitude spectrogram to dB-scaled spectrogram
log_S = librosa.amplitude_to_db(S, ref=np.max)
pcen_S = librosa.core.pcen(S)
return pcen_S
def wavelet_denoising(data):
'''
Wavelet Denoising using scikit-image
NOTE: Wavelet denoising is an effective method for SNR improvement in environments with
wide range of noise types competing for the same subspace.
'''
sigma_est = estimate_sigma(data, multichannel=True, average_sigmas=True)
im_bayes = denoise_wavelet(data, multichannel=False, convert2ycbcr=True, method='BayesShrink',
mode='soft')
im_visushrink = denoise_wavelet(data, multichannel=False, convert2ycbcr=True, method='VisuShrink',
mode='soft')
# VisuShrink is designed to eliminate noise with high probability, but this
# results in a visually over-smooth appearance. Here, we specify a reduction
# in the threshold by factors of 2 and 4.
im_visushrink2 = denoise_wavelet(data, multichannel=False, convert2ycbcr=True, method='VisuShrink',
mode='soft', sigma=sigma_est / 2)
im_visushrink4 = denoise_wavelet(data, multichannel=False, convert2ycbcr=True, method='VisuShrink',
mode='soft', sigma=sigma_est / 4)
return im_bayes
def set_rate(audio, rate):
'''Set sampling rate'''
return audio.set_frame_rate(rate)
def make_chunks(filename, chunk_size, sampling_rate, target_location):
'''Divide the audio file into chunk_size samples'''
f = AudioSegment.from_wav(filename)
if f.frame_rate != sampling_rate:
f = set_rate(f, sampling_rate)
j = 0
if not os.path.exists(target_location):
os.makedirs(target_location)
os.chdir(target_location)
f_name = os.path.basename(filename)
while len(f[:]) >= chunk_size * 1000:
chunk = f[:chunk_size * 1000]
chunk.export(f_name[:-4] + "_{:04d}.wav".format(j), format="wav")
logger.info("Padded file stored as " + f_name[:-4] + "_{:04d}.wav".format(j))
f = f[chunk_size * 1000:]
j += 1
if 0 < len(f[:]) and len(f[:]) < chunk_size * 1000:
silent = AudioSegment.silent(duration=chunk_size * 1000)
paddedData = silent.overlay(f, position=0, times=1)
paddedData.export(f_name[:-4] + "_{:04d}.wav".format(j), format="wav")
logger.info("Padded file stored as " + f_name[:-4] + "_{:04d}.wav".format(j))
def plot_and_save(denoised_data, f_name):
fig, ax = plt.subplots()
i = 0
# Add this line to show plots else ignore warnings
# plt.ion()
ax.imshow(denoised_data)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
fig.set_size_inches(10, 10)
fig.savefig(
f"{f_name[:-4]}" + "_{:04d}.png".format(i),
dpi=80,
bbox_inches="tight",
quality=95,
pad_inches=0.0)
fig.canvas.draw()
fig.canvas.flush_events()
i += 1
def standardize_and_plot(sampling_rate, file_path_image):
logger.info(f"All files will be resampled to {sampling_rate}Hz")
output_image_folder = "PreProcessed_image/"
for dirs, subdirs, files in os.walk(file_path_image):
for i, file in enumerate(files):
if file.endswith(('.wav', '.WAV')):
logger.info(f"Pre-Processing file: {file}")
data, sr = librosa.core.load(
os.path.join(dirs, file), sr=sampling_rate, res_type='kaiser_fast')
target_path = os.path.join(output_image_folder, dirs)
# There is no need to apply padding since all samples are of same length
# padded_data = padding(data, input_length)
# TODO: mismatch of shape
# if use_mfcc:
# mfcc_data = mfcc(padded_data, sampling_rate, n_mfcc)
# else:
# mfcc_data = preprocessing_fn(padded_data)[:, np.newaxis]
pcen_S = apply_per_channel_energy_norm(data, sr)
denoised_data = wavelet_denoising(pcen_S)
work_dir = os.getcwd()
if not os.path.exists(target_path):
os.makedirs(target_path)
os.chdir(target_path)
f_name = os.path.basename(file)
plot_and_save(denoised_data, f_name)
os.chdir(work_dir)
def main(args):
sampling_rate = args.resampling
audio_duration = args.dur
use_mfcc = args.mfcc
n_mfcc = args.nmfcc
file_path_audio = args.classpath
chunkSize = args.chunks
audio_length = sampling_rate * audio_duration
def preprocessing_fn(x): return x
input_length = audio_length
no_of_files = len(os.listdir('.'))
output_audio_folder = "PreProcessed_audio/"
# Traverse all files inside each sub-folder and make chunks of audio file
for dirs, subdirs, files in os.walk(file_path_audio):
for file in files:
if file.endswith(('.wav', '.WAV')):
logger.info(f"Making chunks of size {chunkSize}s of file: {file}")
input_file = os.path.join(dirs, file)
work_dir = os.getcwd()
output_path = os.path.join(output_audio_folder, dirs)
'''
CouldntDecodeError: Decoding failed. ffmpeg returned error
code: 1 in file ._20180605_0645_AD8.wav 2018, so catching exception
'''
try:
make_chunks(
input_file,
chunkSize,
sampling_rate,
output_path)
except Exception as e:
logger.error(f"Exception: {e}", exc_info=True)
pass
os.chdir(work_dir)
file_path_image = os.path.join(output_audio_folder, file_path_audio)
logger.info(f"Starting to load {no_of_files} data files in the directory")
standardize_and_plot(sampling_rate, file_path_image)
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description="Pre-Process the audio files and save as spectrogram images")
parser.add_argument(
'-c',
'--classpath',
type=str,
help='directory with list of classes',
required=True)
parser.add_argument(
'-r',
'--resampling',
type=int,
default=44100,
help='choose sampling rate')
parser.add_argument(
'-d',
"--dur",
type=int,
default=2,
help='Max duration (in seconds) of each clip')
parser.add_argument(
'-s',
"--chunks",
type=int,
default=5,
help='Chunk Size for each sample to be divided to')
parser.add_argument(
'-m',
"--mfcc",
type=bool,
default=False,
help='apply mfcc')
parser.add_argument(
'-n',
"--nmfcc",
type=int,
default=20,
help='Number of mfcc to return')
args = parser.parse_args()
main(args)
<span class="math-container">```</span>
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T16:16:47.067",
"Id": "221790",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"image",
"audio",
"matplotlib"
],
"Title": "Converts audio files to fixed size chunks and the chunks to spectrogram images"
} | 221790 |
<p>Based on my previous attempt.</p>
<p><a href="https://codereview.stackexchange.com/q/221678/507">Prime Sieve and brute force</a></p>
<p>Trying to make the interface simpler I have moved all the code into a class. This way I can keep track of the <code>primes</code> and <code>inc</code> and the <code>next</code> value to look at. This way I can control accesses to <code>isPrime()</code> so it can not be called on values directly (as it makes the assumption you have already calculated all previous primes).</p>
<p>When my code is manipulating a potential prime it uses <code>int</code> as the type. If the code is working on the size of a container or index into a container directly then I use <code>std::size_t</code>.</p>
<p>I tried being consistent with my braces. But an <code>if</code> statement that just had a return inside looked so ugly with my standard braces.</p>
<pre><code>if (<test>)
{
return;
}
// I know it only saves one line but that looks ugly and wasteful
if (<test>) {
return;
}
</code></pre>
<p>So I have kept them small but otherwise open/closing braces are aligned on the left.</p>
<h3>se.h</h3>
<pre><code>#ifndef THORSANVIL_UTIL_SIEVE_ERATOSTHENES_H
#define THORSANVIL_UTIL_SIEVE_ERATOSTHENES_H
#include <vector>
#include <ostream>
#include <cstddef>
namespace ThorsAnvil
{
class SieveEratosthenes
{
public:
using Primes = std::vector<int>;
private:
static std::size_t constexpr maxSieveSize = 1024 * 1024;// approx 1M
Primes primes;
int inc;
int next;
public:
SieveEratosthenes(int nTh);
Primes const& thePrimes() const {return primes;}
int count() const {return primes.size();}
int getCurrent() const {return primes.back();}
int getNext() {calcNext(); return getCurrent();}
private:
void calcNext();
bool isPrime(int num);
int getNextInc() {inc = 6 - inc;return inc;}
friend std::ostream& operator<<(std::ostream& str, SieveEratosthenes const& data)
{
for(auto prime: data.primes) {
str << prime << " ";
}
return str;
}
};
}
#endif
</code></pre>
<h2>se.cpp</h2>
<pre><code>#include "se.h"
#include <cmath>
using namespace ThorsAnvil;
SieveEratosthenes::SieveEratosthenes(int nTH)
: inc(4)
, next(5)
{
// We know we will have `nTH` primes.
primes.reserve(nTH);
// Take care of people trying to be silly and break things.
if (nTH <= 0) {
return;
}
primes.emplace_back(2);
if (nTH == 1) {
return;
}
primes.emplace_back(3);
if (nTH == 2) {
return;
}
// Estimate the sieve size we will need to find the `nth` prime.
// This is not exact so it will get you most of the way there.
// But this means you will have to brute force the rest.
// See the last loop in the constructor for that.
std::size_t sieveSize = nTH * std::log(nTH) / 2; // Note: div 2 because we don't hold even numbers
sieveSize = std::min(sieveSize, maxSieveSize / sizeof(typename Primes::value_type) * CHAR_BIT);
// primeCandidates holds true/false for each potential prime candidate.
// The index represents the potential prime (index * 2 + 1)
// This allows us to ignore all multiple of 2
// max is one past the highest prime candidate we can test for and store in primeCandidates
std::vector<bool> primeCandidates(sieveSize, true);
// We will use the technique of incrementing by 2 then 4 then 2 then 4
// This means skip all multiple of 2 and 3 automatically.
for(; next < sieveSize && nTH != count(); next += getNextInc())
{
std::size_t index = next/2;
// If we find a candidate that is valid then add it to results.
if (primeCandidates[index])
{
primes.push_back(next);
// Now strain out all multiple of the prime we just found.
for(index = next * next / 2; index < primeCandidates.size(); index += next)
{
primeCandidates[index] = false;
}
}
}
while(nTH != count())
{
calcNext();
}
}
void SieveEratosthenes::calcNext()
{
while(!isPrime(next))
{
next += getNextInc();
}
primes.push_back(next);
next += getNextInc();
}
bool SieveEratosthenes::isPrime(int num)
{
// Note: All primes less than num have already been found and stored in
// the container `primes`. So this can only be used as part of
// a brute force attack where you iterate up the number space and
// store any found primes in `prime`. See: calcNext()
int max = std::sqrt(num);
for(auto const& prime: primes)
{
if (prime > max) {
return true;
}
if (num % prime == 0) {
return false;
}
}
return true;
}
</code></pre>
<h2>main.cpp</h2>
<p>Just a test to hang things from:</p>
<pre><code>#include "se.h"
#include <string>
#include <iostream>
int main(int argc, char* argv[])
{
try
{
int find;
if ((argc != 2) || ((find = std::stoi(argv[1])) < 1))
{
throw std::runtime_error("Invalid Arguments");
}
using SE = ThorsAnvil::SieveEratosthenes;
SE sieve(find);
std::cout << find << " prime: " << sieve.getCurrent() << "\n"
<< sieve << "\n";
}
catch(std::exception const& e)
{
std::cerr << "Exception: " << e.what() << "\n";
throw;
}
catch(...)
{
std::cerr << "Exception: Unknown Type\n";
throw;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T18:27:18.577",
"Id": "429081",
"Score": "0",
"body": "Our coding guidelines allow `if (<test>) return;` (but just in case of `return`, nothing else, e.g. not `i++`). That's the [return early](https://softwareengineering.stackexchange.com/a/18459/109304) pattern. I'd personally not use it in general, but for Desktop C++ it's fine. May not be fine in embedded C++ environment where you have limited breakpoints"
}
] | [
{
"body": "<p>At first, I was surprised by the use of a class here, but having read the code (and especially the <code>main()</code>), it clearly makes sense. It might be possible to make it more natural to use by providing a (const) iterator to access the values, rather than the <code>getCurrent()</code>/<code>getNext()</code> interface.</p>\n\n<p>Consider defining the streaming operator in the implementation file. Not a big deal for this small program, but in well-used classes, it can make a difference, by allowing the header to include <code><iosfwd></code> instead of <code><ostream></code>. The former is intended to be faster for compilation.</p>\n\n<p>A missing include in the implementation file: <code><climits></code> is required, for <code>CHAR_BIT</code>.</p>\n\n<p>The class delegates all its resource management, smoothly satisfying the Rule of Zero. <code>:-)</code></p>\n\n<p>I don't see why we accept (signed) <code>int</code> as argument, if we're not allowing negative numbers. There's a serious bug anyway, in that we <code>reserve(nTH)</code> before we know it's not negative.</p>\n\n<p><code>-Weffc++</code> warns about the default-initialised <code>primes</code> member. It's good to be explicit, and in this case it can simplify the constructor a little:</p>\n\n<pre><code>SieveEratosthenes::SieveEratosthenes(int nTH)\n : inc(4)\n , next(5)\n , primes{2, 3}\n{\n // Take care of people trying to be silly and break things.\n if (nTH <= 0) {\n primes.clear()\n return;\n }\n if (nTH <= 2) {\n primes.resize(nTH);\n return;\n }\n\n // We know we will have `nTH` primes.\n primes.reserve(nTH);\n</code></pre>\n\n<p><code>std::vector<bool></code> optimises space at the expense of speed. We may find that <code>std::vector<char></code> is more performant for reasonable sizes - have you done any benchmarks to justify this choice?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-14T13:13:41.273",
"Id": "222283",
"ParentId": "221795",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T17:10:17.413",
"Id": "221795",
"Score": "5",
"Tags": [
"c++",
"primes",
"sieve-of-eratosthenes"
],
"Title": "Prime Sieve and brute force #2"
} | 221795 |
<p>I'm working on a responsive login page (open source). Could you try to review a bit the code on Github ?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{
font-family: "Montserrat", sans-serif;
margin: 0;
background-image: linear-gradient(to right bottom, #ff0000, #ff5600, #ff8000, #ffa200, #ffc200);
}
#title {
font-size: 60px;
margin: 0;
text-align: center;
position: absolute;
width: 100%;
}
#subtitle {
margin: 0;
margin-bottom: 10px;
text-align: center;
font-weight: 200;
color: #fff;
}
#title a {
text-decoration: none;
color: #fff;
}
.body {
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
.page {
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
.box {
background-color: #F7F7F7;
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
width: 368px;
height: 350px;
padding: 48px 40px;
border-radius: 5px;
box-shadow: 0 3px 6px rgba(0,0,0,0.16), 0 3px 6px rgba(0,0,0,0.23);
}
.top-box {
height: 30%;
}
.box form {
width: 100%;
height: 70%;
display: flex;
flex-wrap: wrap;
justify-content: center;
flex-direction: column;
}
#user-icon {
width: 100px;
height: 100px;
}
#email, #password{
height: 48px;
padding-left: 10px;
font-size: 15px;
border-style: solid;
border-color: #c0c0c0;
border-width: thin;
-moz-box-shadow: inset 0 0 1px #000000;
-webkit-box-shadow: inset 0 0 1px #000000;
box-shadow: inset 0 0 1px #000000;
width: 100%;
}
#email {
border-top-left-radius: 2px;
border-top-right-radius: 2px;
border-bottom-style: hidden;
}
#password {
border-bottom-left-radius: 2px;
border-bottom-right-radius: 2px;
}
#email::placeholder, #password::placeholder {
color: rgb(179, 179, 179);
}
#submit {
height: 44px;
background: rgb(68, 112, 255);
color: white;
margin-top: 15px;
border-radius: 5px;
font-size: 15px;
border: 0;
}
@media screen and (max-width: 600px) {
body {
background: #F7F7F7;
}
.box{
border-radius: 0;
width: 85%;
height: 100%;
border: none;
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;
padding: 0;
height: 400px;
}
.body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
#user-icon {
display: none;
}
#title a{
color: black;
}
#title {
margin-top: 10px;
font-size: 35px;
}
#subtitle {
font-size: 15px;
color: black;
position: fixed;
top: 50px;
}
}
@media screen and (max-height: 320px) {
#title {
font-size: 0;
}
#subtitle {
position: fixed;
top: 15px;
}
}
@media screen and (max-height: 300px) {
#title {
font-size: 0;
}
#subtitle {
font-size: 0;
}
}
@media screen and (min-width: 600px) and (max-height: 600px) {
#title {
font-size: 0;
}
}
@media screen and (min-width: 600px) and (max-height: 475px) {
#subtitle {
font-size: 0;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css?family=Montserrat:200,400,500&display=swap" rel="stylesheet">
<title>Sign in</title>
</head>
<body>
<span id="title-span"><h1 id="title"><a href="https://github.com/eloisb">Eloi SB</a></h1></span>
<div class="page">
<h2 id="subtitle">Sign in to continue</h2>
<div class="body">
<div class="box">
<img src="https://cdn1.imggmi.com/uploads/2019/6/6/7e0f9ccff2b62a855e5d611467ce65c9-full.png" alt="" id="user-icon">
<form class="form">
<input type="text" placeholder="Email" id="email">
<input type="password" placeholder="Password" id="password">
<input type="submit" value="Sign in" id="submit">
</form>
</div>
</div>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
<p><a href="https://github.com/eloisb/login_page" rel="nofollow noreferrer">https://github.com/eloisb/login_page/</a></p>
<p>Thanks you </p>
| [] | [
{
"body": "<p>Your style is that of Google. It's simple and consice. However, I have a few remarks.</p>\n\n<ol>\n<li>The <a href=\"https://www.smashingmagazine.com/2010/01/color-theory-for-designers-part-1-the-meaning-of-color/\" rel=\"nofollow noreferrer\">color classes</a> are in conflict. You have a mix of warm (red) and cold (blue) colors.</li>\n<li>There is no warning when the user has <a href=\"https://www.w3schools.com/howto/howto_js_detect_capslock.asp\" rel=\"nofollow noreferrer\">Caps Lock</a> on when typing in the password.</li>\n<li>You are missing support functions as 'Need help logging in' and 'Stay logged in'.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T05:12:48.917",
"Id": "221825",
"ParentId": "221804",
"Score": "0"
}
},
{
"body": "<p>It's invalid HTML to have <code>h1</code> inside <code>span</code>.</p>\n\n<p>Don't use IDs for general styling use classes instead (see for example <a href=\"https://dev.to/claireparkerjones/reasons-not-to-use-ids-in-css-4ni4\" rel=\"nofollow noreferrer\">https://dev.to/claireparkerjones/reasons-not-to-use-ids-in-css-4ni4</a>).</p>\n\n<p>Regarding the HTML structure it seems to make sense to have the title inside the <code>.page</code> element.</p>\n\n<p>Many of the used id and class names are very generic. Considering this is a login page I would at the very least expect the word \"login\" to be used somewhere. Have a look at some CSS naming schemes, for example BEM.</p>\n\n<p>It seems to me to be a bad idea to use <code>font-size: 0</code> to hide elements. Why not use <code>display: none</code>?</p>\n\n<p>The layout breaks for small browser windows heights.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T11:53:49.840",
"Id": "429203",
"Score": "0",
"body": "Thanks, I published a new version on github. But aren't id better for unique elements ?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T08:00:02.563",
"Id": "221840",
"ParentId": "221804",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T19:51:40.017",
"Id": "221804",
"Score": "2",
"Tags": [
"html",
"css",
"user-interface"
],
"Title": "responsive login page (html/css only)"
} | 221804 |
<p>I have two modules, <strong>Notification</strong> which basically contains <strong>SignalR hubs</strong> and <strong>CoreSetup</strong> which contains core setup logic in it.</p>
<p>I have a class in <strong>CoreSetup</strong> module which keeps track of employee location . I want SignalR hubs to be notified and those locations to be on MAP when new data are inserted through Web API.
I don't want <strong>CoreSetup</strong> module to have dependency on <strong>SignalR</strong> module.
This is what I have done currently.</p>
<pre><code>[Route("api/salesman-location")]
[ApiController]
public class SalesmanLocationController : BaseController
{
private readonly SalesmanLocationService _salesmanLocationService;
private readonly IHubContext<ChatHub> _hubContext;
public SalesmanLocationController(SalesmanLocationService salesmanLocationService,IHubContext<ChatHub> hubContext)
{
_salesmanLocationService = salesmanLocationService;
_hubContext = hubContext;
}
[Route("save")]
[HttpPost]
public IActionResult save([FromBody]List<SalesmanLocationDto> datas)
{
try
{
_hubContext.Clients.All.SendAsync("SalesManLocationfromHub", datas);
_salesmanLocationService.save(datas);
return Ok();
}
catch (CustomException ex)
{
return ApiResponse.getErrorResponseJson(ex.Message);
}
catch (Exception ex)
{
return ApiResponse.getErrorResponseJson("Failed to save data.");
}
}
}
</code></pre>
<p>It works pretty well but I have some logic inside <strong>save()</strong> method of <strong>SalesmanLocationService</strong> . It would be great if hub can subscribe to <strong>save()</strong> method of <strong>SalesmanLocationService</strong> without <strong>SalesmanLocationService</strong> knowing anything about Hub.Under some condition, I should not broadcast data through hub.</p>
<p>This is how my interface of <strong>SalesmanLocationService</strong> looks like:</p>
<pre><code> public interface SalesmanLocationService
{
void save(List<SalesmanLocationDto> datas);
}
</code></pre>
<p>This is the actual implementation of <strong>SalesmanLocationService</strong></p>
<pre><code> public class SalesmanLocationServiceImpl : SalesmanLocationService
{
public SalesmanLocationServiceImpl()
{
}
public void save(List<SalesmanLocationDto> datas)
{
foreach (var data in datas)
{
save(data);
}
}
private void save(SalesmanLocationDto data)
{
if(someCondition){
//broadcast to hub
}
}
}
</code></pre>
| [] | [
{
"body": "<p>Its very much hard coded for that single domain type, SalesmanLocation. I would instead use some kind of event aggregation pattern. The domain fires off these events and the singalr hub listenes to these events. </p>\n\n<p>I have made a singalr library that seamlessly forwards events to signalr. Maybe it can give you some ideas</p>\n\n<p><a href=\"https://github.com/AndersMalmgren/SignalR.EventAggregatorProxy/wiki\" rel=\"nofollow noreferrer\">https://github.com/AndersMalmgren/SignalR.EventAggregatorProxy/wiki</a></p>\n\n<p>Bascily with my design you would do</p>\n\n<pre><code>private void Save(SalesmanLocationDto dto) \n{\n repository.Save(dto);\n eventAggregator.Publish(new SalesmanLocationSavedEvent{ /* map data from dto */ }); \n}\n</code></pre>\n\n<p>Its completely decoupled and nor the domain or the signalr parts know about each other</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T13:09:30.177",
"Id": "221857",
"ParentId": "221805",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T19:56:14.603",
"Id": "221805",
"Score": "1",
"Tags": [
"c#",
"design-patterns",
"asp.net-core",
"signalr"
],
"Title": "Inter module communication"
} | 221805 |
<p>I am writing a program that will take images in a folder, get the GPS Coordinates (from the EXIF data), then return the closest "major city". </p>
<p><sub>(I define a major city as one with an airport, so technically I'm taking the GPS coords of an image, and finding the closest airport and returning that city)</sub></p>
<p>I've looked at this a lot and think I have it pretty efficient. However, aside from any other general or specific comments, and curious on the following points:</p>
<ol>
<li>Naming could be better on the functions</li>
<li>Are the doc strings good, or are they too broad/obvious?</li>
<li>For the constants I declare up top, should I use <code>enum</code>?</li>
<li>Am I logging correctly?</li>
<li><p>Are my try/except options in good order?
I feel that the setting of <code>None</code>/<code>False</code> is a little repetitive, and not
too DRY - can that be improved?</p>
<p>5b) How should I handle exceptions I don't know about, or haven't already handled? </p></li>
<li><p>Specifically, is <code>airports_by_country()</code> a good/necessary function
or should I just directly filter the DF in the original funtion
that calls it?</p></li>
<li>Does the "order" of the functions matter?</li>
</ol>
<p>find_city.py:</p>
<pre><code>import os
import logging
import _pickle as cPickle
from GPSPhoto import gpsphoto
import pandas as pd
from geopy.geocoders import Nominatim
from geopy import distance
THIS_PY_LOC = os.path.dirname(os.path.abspath(__file__))
IMAGE_FOLDER = "Images/"
IMAGE_INFO_DICT = "image_data_dict.txt"
# Airport info from https://openflights.org/data.html
AIRPORT_INFO = os.path.join(THIS_PY_LOC, "airports.csv")
LOG_FILENAME = str(os.path.basename(__file__)) + '.log'
logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG)
def image_paths(top_folder):
"""
With the top_folder, return all files in that folder with path.
This will NOT look in subdirectories.
https://docs.python.org/3/library/os.path.html#os.path.isfile
"""
paths = []
for filename in os.listdir(IMAGE_FOLDER):
_file = os.path.join(IMAGE_FOLDER, filename)
if os.path.isfile(_file):
paths.append(_file)
return paths
def return_image_data_from_list(image_list):
"""
Takes a list of Image Paths, and will
return Lat/Long data
"""
info = {}
geolocator = Nominatim(user_agent="my-application")
for img in image_list:
data = gpsphoto.getGPSData(img)
try:
_coords = str(data['Latitude']) + "," + str(data['Longitude'])
locale = geolocator.reverse(_coords, timeout=20)
full_info = geolocator.geocode(locale, addressdetails=True)
# address = full_info.raw["address"]
if full_info is None:
full_info = locale
info[img] = {"address": locale,
"country": full_info.raw['address']['country'],
"gps": {"latitude": data['Latitude'],
"longitude": data['Longitude']},
"location unknown": False}
except KeyError as err:
logging.info(img + " had error: " + str(err))
info[img] = {"address": None,
"country": None,
"gps": {"latitude": None,
"longitude": None},
"location unknown": True}
return info
def airports_by_country(airport_df, country):
"""
Using a dataframe, extract only the rows where the
airport is in a particular country and return just that
information as a DF
"""
airports = airport_df[airport_df['Country'] == country]
return airports
def load_image_dict(image_folder=IMAGE_FOLDER):
"""
Using Pickle, this will check to see if the image dictionary
which has the address/GPS data exists. If so, use that as the
dictionary. Otherwise, create it. This will help cut down
on the requests, as if the dict with the info exists, we will
just use that.
"""
try:
with open(IMAGE_INFO_DICT, 'rb') as dict_items_open:
logging.info("Pickle dictionary found, using that.")
image_gps_info = cPickle.load(dict_items_open)
except (EOFError, FileNotFoundError) as err:
logging.info("Creating Pickle dictionary.")
images = image_paths(IMAGE_FOLDER)
image_gps_info = return_image_data_from_list(images)
with open(IMAGE_INFO_DICT, 'wb') as dict_items_save:
cPickle.dump(image_gps_info, dict_items_save)
return image_gps_info
def get_distance_to_airport(org_lat, org_lon, country_df):
"""
Takes the origin latitutde and longitude
and searches through a Pandas DATAFRAME that has
columns "Latitude" and "Longitude" and finds the closest
coordinate pair and returns that pair.
Uses Vincenty distance, per
https://stackoverflow.com/a/43211266
"""
closest_airport = {'distance': 1000000000000000000}
for row in country_df.itertuples():
row_lat = row.Latitude
row_lon = row.Longitude
# dist = gpxpy.geo.haversine_distance(float(org_lat), float(org_lon),
# float(row_lat), float(row_lon))
vin_dist = distance.vincenty(
(float(org_lat), float(org_lon)),
(float(row_lat), float(row_lon))).miles
if vin_dist < closest_airport['distance']:
closest_airport['distance'] = vin_dist
closest_airport['airport'] = row.Name
closest_airport['city'] = row.City
return closest_airport
def update_dict_with_airport(primary_dict, airport_df):
"""
This takes the original dictionary and adds in the
closest airport information
"""
for key, val in primary_dict.items():
try:
_country = val["country"]
img_gps = val['gps']
country_df = airports_by_country(airport_df, _country)
closest_airport = get_distance_to_airport(img_gps['latitude'],
img_gps['longitude'],
country_df)
primary_dict[key]['closest city'] = closest_airport['city']
primary_dict[key]['airport'] = closest_airport['airport']
primary_dict[key]['miles_to_airport'] = closest_airport['distance']
except KeyError:
primary_dict[key]['closest city'] = None
primary_dict[key]['airport'] = None
primary_dict[key]['distance_to_airport'] = None
return primary_dict
def image_data_from_folder(fldr):
"""
This is for running externally.
Pass in a folder location, and this will
check all the images in that folder for the information
and return that in a dictionary.
"""
image_gps_info = load_image_dict(fldr)
airport_df = pd.read_csv(AIRPORT_INFO)
full_image_dict = update_dict_with_airport(image_gps_info, airport_df)
unknown_locs = unknown_coords(full_image_dict)
logging.info("UNKNOWN IMAGE COORDS: " + str(unknown_locs))
logging.info("-----------------------------------------------------------")
return full_image_dict
def unknown_coords(image_dict):
"""
Takes a dictionary and returns the key name for
files where 'unknown' key is False.
"""
_files = []
for image, vals in image_dict.items():
# print(image, "\n", vals)
if not image_dict[image]["location unknown"]:
_files.append(image)
return _files
def main():
full_image_dict = image_data_from_folder(IMAGE_FOLDER)
for key, val in full_image_dict.items():
print(key, "\n", val)
if __name__ == '__main__':
main()
</code></pre>
<p>A final comment is that I'd like this to work well as an import to another file. So later on, if I have a folder of images, I could <code>import find_city as fc</code> then do <code>image_city_info = fc.image_data_from_folder("/myFolder")</code></p>
| [] | [
{
"body": "<h2>General</h2>\n\n<p>Going through your list of concerns:</p>\n\n<ol>\n<li>the function names are not crazy, though you could definitely benefit from implementing type hints;</li>\n<li>the doc strings should specifically describe all parameters and return values;</li>\n<li>no, I don't see <code>enum</code> being useful here;</li>\n<li>logging seems fine to me;</li>\n<li>Your exceptions are fine. The DRY concern is... not really that big of a deal. You could go out of your way to define a tuple of default keys needed for a dictionary, but it's more hassle than it's worth. About unhandled exceptions: let them stay exceptional. At the most, you may want a top-level <code>except Exception</code> in your <code>main</code> that logs exceptions that fall through.</li>\n<li>Seems fine, though I don't understand your data well enough to speak authoritatively</li>\n<li>Yes. Generally, they should be listed in order of dependency (callee first, caller later). This is already what you have.</li>\n</ol>\n\n<h2>Add a shebang</h2>\n\n<p>at the top, probably <code>#!/usr/bin/env python3</code> .</p>\n\n<h2>Use pathlib instead of path.join</h2>\n\n<p>Something like <code>AIRPORT_INFO = Path(THIS_PY_LOC) / 'airports.csv'</code></p>\n\n<h2>Use f-strings instead of concatenates</h2>\n\n<p>Something like <code>LOG_FILENAME = f'{os.path.basename(__file__)}.log'</code></p>\n\n<p>Also seen: <code>str(data['Latitude']) + \",\" + str(data['Longitude'])</code> becomes </p>\n\n<p><code>f'{data[\"Latitude\"]},{data[\"Longitude\"]}'</code></p>\n\n<h2>Use generators</h2>\n\n<pre><code>def image_paths(top_folder):\n for filename in os.listdir(IMAGE_FOLDER):\n _file = Path(IMAGE_FOLDER) / filename\n if _file.exists():\n yield _file\n</code></pre>\n\n<p>This also applies to your <code>unknown_coords</code>. </p>\n\n<h2>Use <code>update</code> on dicts</h2>\n\n<p>i.e.</p>\n\n<pre><code> primary_dict[key]['closest city'] = None\n primary_dict[key]['airport'] = None\n primary_dict[key]['distance_to_airport'] = None\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>primary_dict[key].update({\n 'closest city': None,\n 'airport': None,\n 'distance_to_airport': None\n})\n</code></pre>\n\n<h2>Use <code>scandir</code> instead of <code>listdir</code></h2>\n\n<p>According to the docs:</p>\n\n<blockquote>\n <p>The <code>scandir()</code> function returns directory entries along with file attribute information, giving better performance for many common use cases.</p>\n</blockquote>\n\n<p>So use that in your <code>image_paths</code> function. In fact... reading that function again, why are you looping at all? This can be a one-liner - just call <code>scandir()</code>. I'm not sure why you are checking for existence of the files - do you not trust the values returned by <code>listdir</code>?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T16:33:57.543",
"Id": "429599",
"Score": "0",
"body": "Thanks very much, I appreciate all the comments! While I'm also googling around for more details, can you add a little more info on why to use pathlib instead of path.join and the generators? I use `listdir` because later on, I plan on checking for the filetype of each file and see if it's an image media type. (In the event I scan a folder of images, video, xlsx, etc. so I don't include stuff that *couldn't* have GPS."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T20:45:21.163",
"Id": "429638",
"Score": "0",
"body": "Pathlib because it more or less looks nicer during path construction, plus it returns a more useful object instead of just a string. Generators because they take up less memory, and reduce complexity of your application."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-11T16:32:27.703",
"Id": "429736",
"Score": "0",
"body": "For the generator, to make sure I understand, I'll then have to do `for img in list(image_list):`, correct? Since `image_list` would be the returned generator?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-11T17:16:08.743",
"Id": "429739",
"Score": "1",
"body": "It's even easier - you don't need to convert it into a list unless (a) you need to iterate twice, or (b) you need it all in memory for random access or something else. In your case, for one `for` loop, just write `for img in image_list`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T02:58:25.833",
"Id": "221896",
"ParentId": "221809",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "221896",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T21:04:32.167",
"Id": "221809",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"image",
"pandas",
"geospatial"
],
"Title": "Get nearest major city of an image (using EXIF GPS data)"
} | 221809 |
<p>Background: I'm trying to create functionality that would display two layouts of the same data. The position and size each data record must be independently saved per layout and each layout will have different functionality and be displayed in a different way (one will display the records as squares, the other circles).</p>
<p>This is my first time using <a href="/questions/tagged/mobx-state-tree" class="post-tag" title="show questions tagged 'mobx-state-tree'" rel="tag">mobx-state-tree</a>, I would appreciate any thoughts on the models and the overall logic. Mostly I'm worried that the models are too tightly coupled and that the structure isn't correct. </p>
<p>This <code>RootStore</code> holds an array of <code>Records</code>, a reference to <code>StageStore</code> and a reference to the selected <code>Record</code></p>
<pre><code>export const RootStore = types
.model("RootStore", {
records: types.array(Record),
selection: types.maybeNull(types.reference(Record)),
stage: types.optional(StageStore, {})
})
.actions(self => ({
setSelected(selection){
self.selection = selection
},
addRecord(){
const record = Record.create({id: v4()});
record.addLayout(Layout.create({name: 'adjacency', id: 'adjacency'}));
record.addLayout(Layout.create({name: 'plan', id: 'plan'}));
self.records.push(record);
return record;
},
createRecord(x, y){
const record = self.addRecord();
record.setPosition(x, y);
self.setSelected(record);
}
}));
</code></pre>
<p><code>StageStore</code> holds information about the scale and translate of the SVG element acting as the stage. It also holds the active <code>Layout</code> key. This part I'm most unsure about because it tightly couples <code>StageStore</code> with <code>RecordStore</code>. </p>
<pre><code>const position = types
.model({
x: types.optional(types.number, 0),
y: types.optional(types.number, 0),
})
.actions(self => ({
setPosition(x, y){
self.x = x;
self.y = y;
}
}));
export const StageStore = types
.model("StageStore", {
translate: types.optional(types.compose(position), {}),
scale: types.optional(types.number, 1),
activeLayout: types.optional(types.string, 'adjacency')
})
.actions(self => ({
setActiveLayout(id){
self.activeLayout = id;
},
setScale(scale){
self.scale = scale;
},
}));
</code></pre>
<p>Holds information about each record and a reference to the two layouts.</p>
<pre><code>export const Record = types
.model('Record', {
id: types.identifier,
name: types.optional(types.string, ""),
layouts: types.map(Layout),
})
.views(self => ({
get isSelected(){
return getParent(self, 2).selection === self
},
get isDragging(){
return getParent(self, 2).selection === self && getParent(self, 2).stage.dragging
},
get x(){
let activeLayout = getRoot(self).stage.activeLayout;
return self.layouts.get(activeLayout).x;
},
get y(){
let activeLayout = getRoot(self).stage.activeLayout;
return self.layouts.get(activeLayout).y;
},
get width(){
let activeLayout = getRoot(self).stage.activeLayout;
return self.layouts.get(activeLayout).width;
},
get height(){
let activeLayout = getRoot(self).stage.activeLayout;
return self.layouts.get(activeLayout).height;
},
get fill(){
let activeLayout = getRoot(self).stage.activeLayout;
return self.layouts.get(activeLayout).fill;
},
get rx(){
return Math.sqrt(self.height * self.width / 3.14);
}
}))
.volatile(self => ({
SVGElement: null
}))
.actions(self => ({
addLayout(layout){
self.layouts.put(layout);
},
setSVGElement(el){
self.SVGElement = el;
},
setPosition(x, y){
let activeLayout = getRoot(self).stage.activeLayout;
self.layouts.get(activeLayout).setPosition(x, y);
},
setName(newName) {
self.name = newName
}
}));
</code></pre>
<p>Holds positional data per each different <code>Layout</code>.</p>
<pre><code>export const Layout = types
.model('Layout', {
id: types.identifier,
name: types.optional(types.string, ""),
x: types.optional(types.number, 0),
y: types.optional(types.number, 0),
height: types.optional(types.number, 50),
width: types.optional(types.number, 50),
rx: types.optional(types.number, 0),
fill: types.optional(types.string, "transparent")
})
.views(self => ({
}))
.actions(self => ({
setPosition(x, y){
self.x = x;
self.y = y;
},
setName(newName) {
self.name = newName
}
}));
</code></pre>
| [] | [
{
"body": "<h3>A couple of minor remarks</h3>\n<p>The <em>active layout</em> is used in various locations. Perhaps you should create a getter for it to avoid redundant code.</p>\n<blockquote>\n<p><code>let activeLayout = getRoot(self).stage.activeLayout;</code></p>\n</blockquote>\n<p>Writing in a fluent style is a delight for the eye, but it should not come at too much cost in code quality. <code>getParent(self, 2)</code> should have been set in a local variable.</p>\n<blockquote>\n<p><code>return getParent(self, 2).selection === self && getParent(self, 2).stage.dragging</code></p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T05:37:22.803",
"Id": "221827",
"ParentId": "221812",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T21:57:44.737",
"Id": "221812",
"Score": "1",
"Tags": [
"javascript",
"react.js",
"mobx"
],
"Title": "Data models with mobx-state-tree for multiple views"
} | 221812 |
<p>I am writing an HTTP client for terminal, similar to curl, as a learning exercise. </p>
<p>There's one limitation it suffers from and that is that it won't return until the client closes the socket. I fixed this problem with a hack by setting the socket to timeout after 1 second, but I feel like there has to be a better way.</p>
<p>Here is my code, I've commented what I already tried.</p>
<pre class="lang-rust prettyprint-override"><code>const BUFLEN: usize = 1024;
const NEWLINE: &str = "\r\n";
fn send_http(_s: &String) -> String {
let mut stream = TcpStream::connect(_s).unwrap();
let _ = stream.write(b"GET / HTTP/1.1\r\n\r\n");
let mut response = String::new();
let mut read;
// This is the line that fixed the problem.
let res = stream.set_read_timeout(Some(Duration::new(1,0)));
loop {
read = [0; BUFLEN];
let result = stream.read(&mut read);
match result {
Ok(n) => {
let resp = String::from_utf8_lossy(&read).into_owned();
print!("{}", resp);
response.push_str(&resp);
//here I tried this:
//if n > 0 && n < 1024 { break; }
//because if it reads any less than 1024,
//that should be the last block it reads.
} Err(err) => { return response }
}
}
response
}
fn main() {
let addr = "www.yahoo.com:80";
let addr_str = String::from(addr);
print!("{}", send_http(&addr_str));
}
</code></pre>
<p>The if statement in the match arm does nothing. Like I said, the code works fine but it's been hacked together. Doesn't feel right. Suggestions?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T04:42:30.893",
"Id": "429133",
"Score": "0",
"body": "Try reading from the stream until `n == 0`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T04:43:16.543",
"Id": "429134",
"Score": "0",
"body": "I have. It ends up just doing the same thing."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T22:10:19.490",
"Id": "221814",
"Score": "2",
"Tags": [
"http",
"rust",
"socket"
],
"Title": "Rust HTTP Requester"
} | 221814 |
<p>Scenario: Return a String that contains only alphabets without spaces.</p>
<p>input = "A man, a plan, a canal: Panama"</p>
<p>output = "AmanaplanacanalPanama"</p>
<p>Can you please critique my code?</p>
<pre><code>private String OnlyAlphabets(final String string) {
StringBuilder sb = new StringBuilder();
char ch;
for (int i = 0; i < string.length(); i++) {
ch = string.charAt(i);
if (!Character.isAlphabetic(ch)) {
continue;
}
sb.append(ch);
}
return sb.toString();
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T11:36:25.767",
"Id": "429198",
"Score": "1",
"body": "Separate from you current implementation, this is an excellent use case for [regular expressions](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=4&cad=rja&uact=8&ved=2ahUKEwjXnb3Ro9fiAhVpn-AKHbrWBk4QFjADegQIABAB&url=https%3A%2F%2Fwww.geeksforgeeks.org%2Fregular-expressions-in-java%2F&usg=AOvVaw0Gf0u4hHyvtPkLyflRmYdV), which tend to be simpler, faster, and shorter than manual implementations, but do require some specialized learning. The regular expression for this would be just `\\S*` (`\\S` = anything not whitespace, `*` = repeated 0 or more times), for example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T22:18:54.000",
"Id": "429298",
"Score": "0",
"body": "@gntskn He also wants to get rid of anything not an alphabetic character. Also, a regular expression will be slower."
}
] | [
{
"body": "<p>You code seems pretty straightforward. However, checking for true rather than false is probably more clear.</p>\n\n<pre><code>if (Character.isAlphabetic(ch)) \n{\n sb.append(ch);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T04:57:26.087",
"Id": "429136",
"Score": "1",
"body": "I favor your check because there is just a single statement in the if, and no else. If there were more code after `sb.append(ch);`, `continue` would have been the best practice to avoid unnecessary nesting."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T05:10:04.810",
"Id": "429140",
"Score": "0",
"body": "@dfhwze what are your thoughts on a lot schools teaching only one return per function. Or the don't use continue or break in a loop. Fyi, I agree with your continue statement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T05:17:05.517",
"Id": "429141",
"Score": "2",
"body": "I find the job of a teacher to make you think critically about things. They can advice and challenge us, but should not impose their standards :-) Unfortunately, these days, I feel .. hold on, let's not get political here."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T03:04:34.560",
"Id": "221819",
"ParentId": "221818",
"Score": "6"
}
},
{
"body": "<blockquote>\n<pre><code> char ch;\n</code></pre>\n</blockquote>\n\n<p>In general, we want to declare as late and at as small a scope as possible. You never use this outside the loop, so it could just be </p>\n\n<pre><code> char ch = string.charAt(i);\n</code></pre>\n\n<p>inside the loop. </p>\n\n<p>Even better, use the range-based/foreach style: </p>\n\n<pre><code> for (char character : string.toCharArray()) {\n</code></pre>\n\n<p>Now you don't have to worry about <code>i</code> or <code>charAt</code> at all. </p>\n\n<p>If you're using Java 8, you may want to look into the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html\" rel=\"noreferrer\">streaming API</a>. E.g. combining <a href=\"https://stackoverflow.com/a/39222166/6660678\">this post</a> and <a href=\"https://stackoverflow.com/a/36809412/6660678\">this post</a>. </p>\n\n<pre><code> return string.codePoints()\n .filter( Character::isAlphabetic )\n .collect( StringBuilder::new,\n StringBuilder::appendCodePoint,\n StringBuilder::append )\n .toString();\n</code></pre>\n\n<p>I haven't tested this. I just combined the two solutions to similar problems in a way that I believe does what you want. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T06:03:29.683",
"Id": "429143",
"Score": "1",
"body": "You should be wary of using toCharArray() when the intention is to only read the content. It creates full copy of the internal char array, which can be detrimental to memory performance, if the string is long."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T04:26:09.620",
"Id": "221824",
"ParentId": "221818",
"Score": "7"
}
},
{
"body": "<p>Your code looks good for very simple text. However, real life is much more complicated.</p>\n\n<p>In languages other than English, there are characters that are combined from other characters. For example, the German Umlaut <code>ä</code> can be written either as <code>\\u00E4</code> or as an <code>a</code>, followed by the combining dots above, which is written <code>a\\u0308</code>. Both representations look the same, yet your code treats them differently.</p>\n\n<p>To get really international, you should read about the <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/BreakIterator.html\" rel=\"noreferrer\">BreakIterator</a> and how it breaks strings into \"perceived characters\". The Java type <code>char</code> does not represent such a perceived character, but only a small part of it.</p>\n\n<p>To test whether such a perceived character (which is really a <code>String</code> in Java) is alphabetic, I guess if suffices to test whether that string <em>contains</em> an alphabetic code point (not char). Have a look at <code>String.codePoints</code>.</p>\n\n<p>Learning how to handle international text properly takes time. Don't rush into it, and take the time needed. Here a little, there a little. It's impossible to get \"the single correct algorithm\" since languages of the world differ a lot in their interpretation of what a <em>character</em> really is. To take the first step in this journey, don't treat a string as a sequence of <code>char</code>, but as a sequence of code points. This alone makes your code handle most emojis correctly, and this simple step makes your code above-average already.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T06:06:37.587",
"Id": "429144",
"Score": "0",
"body": "Even the letter `a` can be represented by different unicode code points :-) When dealing with strings, I would always distinguish common ANSI (windows-1252) vs Extended Unicode (UTF-*) when deciding the scope and complexity of a method. I don't think we should always be compliant to the latter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T08:51:54.937",
"Id": "429174",
"Score": "1",
"body": "java.text.Normalizer and https://en.wikipedia.org/wiki/Unicode_equivalence seem relevant in this discussion."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T05:52:45.810",
"Id": "221829",
"ParentId": "221818",
"Score": "5"
}
},
{
"body": "<p>Your code looks good however, I have few suggestions.</p>\n\n<pre><code>private String OnlyAlphabets\n</code></pre>\n\n<p>the convention is to use camel case for method names, so it should be</p>\n\n<pre><code>private String onlyAlphabets\n</code></pre>\n\n<p>Although this is your sample program however, if such small utilities are required throughout the application then make them static and public. This will allow ease of access and since such utility does not modify the state of object so it is better to make them static.</p>\n\n<pre><code>public static String onlyAlphabets\n</code></pre>\n\n<p>Always check of null before doing further operations on your input string</p>\n\n<pre><code>if (Objects.isNull(string))\n return string;\n</code></pre>\n\n<p>If you are using java-8 or above then streams will surely make your code more compact with the below statement</p>\n\n<pre><code>return string.codePoints()\n .filter(Character::isAlphabetic)\n .collect(StringBuilder::new, \n StringBuilder::appendCodePoint, \n StringBuilder::append)\n .toString();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T06:34:49.920",
"Id": "221832",
"ParentId": "221818",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "221824",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T02:50:30.470",
"Id": "221818",
"Score": "6",
"Tags": [
"java",
"strings"
],
"Title": "Return a String containing only alphabets without spaces"
} | 221818 |
<p>I am fairly new to python, been coding in it for about a year or so. My company is switching from using SAS and a Netezza database for some of our data management. In order to access certain information, I have to load .dat.gz files now using Python3 in unix. In order to access similar information I used to access using basic SQL queries, I now have to import a list of files containing similar information and sort it using python. While this is not an issue for most of the data, there is an instance where I am running into performance issues. In order to access certain data I need, I must load over 300 files to python and try to append them together. This is an issue as the program takes a long time just to load the data. I am currently using pandas <code>read_csv</code> using <code>usecols</code> option to limit the data to the three columns I need. I first used <code>df.append(df2)</code>, but it was slow. I then changed the dataframe to list, but that still did not seem to improve performance that much. All together the data contains over 50 Million rows. While I do not expect this program to run in seconds, I would like some help to improve performance where I can.</p>
<p>Just to note it is important to keep the integrity of the original .dat.gz files. The files I read in very in size from 2 rows to 50k rows or more. Any help would be greatly appreciated!</p>
<p>I have tried <code>df.append(df2)</code> and concatenating lists. I also tried appending the data to a new CSV in my working directory so the data would not all be stored while the program was running. That did not improve performance either.</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import sys
#function to read in directories list from agrv[1]
def import_file_list(file_name):
file_list = []
with open(file_name) as f:
for row in f:
row = row.strip()
file_list.append(row)
return file_list
#main loop to read in all files and append the data
def import_data(list_of_files)
for count, item in enumerate(list_of_files):
exposure_data = pd.read_csv(item, sep='|', usecols=['A', 'B', 'C'], compression='gzip')
if count == 0:
data_dict = exposure_data.to_dict('split')
values_list = list(data_dict['data'])
else:
temp_dict = exposure_data.to_dict('split')
temp_list = list(temp_dict['data'])
values_list = values_list + temp_list
def main():
import_data(import_file_list(sys.argv[1]))
if __name__ == '__main__':
main()
</code></pre>
<p>Expected results would be to loop through all the files I need and combine them to one dataframe, list of lists, dictionary of all the data, or whatever object is most efficient with the three columns I need to do my calculations.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T20:49:02.300",
"Id": "429129",
"Score": "1",
"body": "What is MM? Mega millions (10^12)?"
}
] | [
{
"body": "<p>A suggestion that may help is to make generators of loops in <code>import_file_list</code> and <code>import_data</code>. <br>\nThis is more memory efficient on the intermediate steps and defers building the dataframe until the end.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def import_file_list(file_name):\n with open(file_name) as f:\n for row in f:\n yield row.strip()\n\n\ndef import_data_to_dfs_iter(list_of_files)\n for item in list_of_files:\n yield pd.read_csv(\n item, sep='|', usecols=['A', 'B', 'C'], compression='gzip')\n\ndef main():\n dfs_iter = import_data_to_dfs(import_file_list(sys.argv[1]))\n df = pd.concat(dfs_iter)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T15:43:39.960",
"Id": "429234",
"Score": "0",
"body": "I am testing this out now. Is there a place where I can add a print statement to show the number of files being loaded from the import. I am assume I can add a print statement after the df = pd.concat(dfs_iter) for the total count. I just want to make sure things align."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T16:56:31.797",
"Id": "429245",
"Score": "0",
"body": "I added a print statement at the end appears to have worked. The processing time went way down thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T19:01:09.710",
"Id": "429266",
"Score": "0",
"body": "Great news! Glad you figured it out."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T01:35:47.063",
"Id": "221822",
"ParentId": "221821",
"Score": "3"
}
},
{
"body": "<p>Apart from the functional improvements that were already presented to you, there are also a few non-functional facets that could be improved.</p>\n\n<p>Python has an official <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide</a>, often just called PEP8. This guide presents a variety of recommendations to write consistent and good looking Python code.</p>\n\n<p>IMGO the points most relevant to your code would be:</p>\n\n<ol>\n<li>Sort the <a href=\"https://www.python.org/dev/peps/pep-0008/#imports\" rel=\"nofollow noreferrer\">imports</a>. Standard library imports come first, followed by third-party libraries, and eventually local import from other Python files you have written.</li>\n<li>Write proper <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\">documentation strings</a>. The officially recommended docstring syntax is to enclose them in <code>\"\"\"triple quotes\"\"\"</code> and place them immediately below the function definition. Apart from a unified style with most of the Python coding world, this will also make sure that Python's built-in <code>help(...)</code> function as well as most proper Python IDEs will easily pick it up and show it to you.</li>\n<li>Use 4 spaces per <a href=\"https://www.python.org/dev/peps/pep-0008/#indentation\" rel=\"nofollow noreferrer\">indentation</a> level. There is an overindented block in the body of the <code>if</code> statement in <code>import_data</code>.</li>\n</ol>\n\n<p>There are a lot of tools that may help you to keep a consistent style even on a larger scale. Some of these tools would be <a href=\"https://pylint.org/\" rel=\"nofollow noreferrer\">pylint</a> (style and static code checking), <a href=\"http://flake8.pycqa.org/\" rel=\"nofollow noreferrer\">flake8</a>, <a href=\"https://black.readthedocs.io/en/stable/\" rel=\"nofollow noreferrer\">black</a> (style check and auto-formatting), or <a href=\"https://github.com/google/yapf\" rel=\"nofollow noreferrer\">yapf</a> (style check and auto-formatting) to name a few. Most Python IDEs support at least some of these tools so they will mark violating pieces of code while you write them and not just afterwards.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T15:46:09.710",
"Id": "429236",
"Score": "0",
"body": "Thanks for the advice. I have heard of PEP8, but I have not looked into at this point. I been mainly working on the functionality and efficiency in my code. Plus, all the functionality that python offers. Can be overwhelming at times, but I do enjoy it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T06:39:13.360",
"Id": "221833",
"ParentId": "221821",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "221822",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-06T20:16:06.283",
"Id": "221821",
"Score": "2",
"Tags": [
"python",
"python-3.x"
],
"Title": "Appending multiple file loads in Python"
} | 221821 |
<p>I just finished making an implementation of a SHA256 hashing function (<a href="https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf" rel="nofollow noreferrer">https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf</a>) in Rust and I was looking for some feedback.</p>
<p>As far as I can tell it works properly, but I haven't used Rust before so I'm looking for some advice regarding the style. Performance advice would also be nice, it runs a bit slower than my implementation in C (1.8 vs 1.4 seconds for some test file I have). In my testing I ran with <code>cargo run --release inputfile.txt</code>.</p>
<p>The program is in two parts, <code>main.rs</code> and <code>shafuncs.rs</code></p>
<p><strong>main.rs</strong></p>
<pre><code>use std::io::Read;
use std::fs::File;
use std::num::Wrapping;
use std::env;
mod shafuncs;
use shafuncs::CHUNKBYTES;
macro_rules! wraparray {
( $( $x:expr),* ) => {
[$(Wrapping($x)),*]
}
}
fn main() {
let args: Vec<String> = env::args().collect();
let filename = &args[1];
let mut f = File::open(filename).expect("Could not open file.");
let mut buffer: [u8; CHUNKBYTES] = [0; CHUNKBYTES];
let mut readlen;
let mut messagelength : u64 = 0;
let mut digest: [Wrapping<u32>; 8]= wraparray![
0x6a09e667,
0xbb67ae85,
0x3c6ef372,
0xa54ff53a,
0x510e527f,
0x9b05688c,
0x1f83d9ab,
0x5be0cd19];
while {readlen = f.read(&mut buffer).expect("Could not read from file!"); readlen==CHUNKBYTES} {
messagelength += readlen as u64;
hashround(&mut digest, buffer)
}
messagelength += readlen as u64;
shafuncs::padmessage(&mut buffer, readlen, messagelength);
hashround(&mut digest, buffer);
// Final output
for i in digest.iter() {
print!("{:08x}", i);
}
println!(" {}", filename);
}
fn hashround(digest: &mut [Wrapping<u32>; 8], bytebuffer: [u8; CHUNKBYTES]) {
let mut t1: Wrapping<u32>;
let mut t2: Wrapping<u32>;
let wordbuffer = shafuncs::bytestowords(bytebuffer);
// Message Schedule
let w = shafuncs::message_schedule(wordbuffer);
let mut a: Wrapping<u32> = digest[0];
let mut b: Wrapping<u32> = digest[1];
let mut c: Wrapping<u32> = digest[2];
let mut d: Wrapping<u32> = digest[3];
let mut e: Wrapping<u32> = digest[4];
let mut f: Wrapping<u32> = digest[5];
let mut g: Wrapping<u32> = digest[6];
let mut h: Wrapping<u32> = digest[7];
for t in 0..64 {
t1 = h + shafuncs::ls1(e) + shafuncs::ch(e,f,g) + K[t] + w[t];
t2 = shafuncs::ls0(a) + shafuncs::maj(a,b,c);
h = g;
g = f;
f = e;
e = d+t1;
d = c;
c = b;
b = a;
a = t1+t2;
}
digest[0] += a;
digest[1] += b;
digest[2] += c;
digest[3] += d;
digest[4] += e;
digest[5] += f;
digest[6] += g;
digest[7] += h;
}
const K: [Wrapping<u32>; 64] = wraparray![
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
];
</code></pre>
<p><strong>shafuncs.rs</strong></p>
<pre><code>use std::num::Wrapping;
const WORDSIZE_BITS: usize = 32;
const LENBYTES: usize = 8;
pub const CHUNKBYTES: usize = 64;
const ONEPAD: u8 = 0x80;
fn rotr(x: Wrapping<u32>, n: usize) -> Wrapping<u32> {
(x >> n) | (x << (WORDSIZE_BITS - n) )
}
pub fn ch(x: Wrapping<u32>, y: Wrapping<u32>, z: Wrapping<u32>) -> Wrapping<u32> {
(x & y) ^ ((!x) & z)
}
pub fn maj(x: Wrapping<u32>, y: Wrapping<u32>, z: Wrapping<u32>) -> Wrapping<u32> {
(x & y) ^ (x & z) ^ (y & z)
}
pub fn ls0(x: Wrapping<u32>) -> Wrapping<u32> {
rotr(x, 2) ^ rotr(x,13) ^ rotr(x,22)
}
pub fn ls1(x: Wrapping<u32>) -> Wrapping<u32> {
rotr(x,6) ^ rotr(x,11) ^ rotr(x,25)
}
fn s0(x: Wrapping<u32>) -> Wrapping<u32> {
rotr(x,7) ^ rotr(x,18) ^ (x >> 3)
}
fn s1(x: Wrapping<u32>) -> Wrapping<u32> {
rotr(x,17) ^ rotr(x,19) ^ (x >> 10)
}
pub fn padmessage(bytebuffer : &mut [u8], readbyte : usize, messagelength: u64) -> () {
let bitsize: u64 = messagelength * 8;
let mut pos: usize = readbyte ;
bytebuffer[pos] = ONEPAD;
pos+=1;
for i in pos..(CHUNKBYTES-LENBYTES) {
bytebuffer[i] = 0;
}
let mut v: u8;
for i in 0..8 {
v = ((bitsize >> i*8) & 0xff) as u8;
bytebuffer[63-i] = v;
}
}
pub fn message_schedule(wordbuffer: [Wrapping<u32>; 16]) -> [Wrapping<u32>; 64] {
let mut ms: [Wrapping<u32>; 64] = [Wrapping(0); 64];
ms[..16].clone_from_slice(&wordbuffer);
for t in 16..64 {
ms[t] = s1(ms[t-2]) + ms[t-7] + s0(ms[t-15]) + ms[t-16];
}
ms
}
pub fn bytestowords(bytebuffer: [u8; CHUNKBYTES]) -> [Wrapping<u32>; 16] {
let mut wordbuffer: [Wrapping<u32>; 16] = [Wrapping(0);16];
let mut v: Wrapping<u32>;
for i in 0..16 {
v=Wrapping(0);
v += Wrapping(bytebuffer[4*i] as u32) << (3*8);
v += Wrapping(bytebuffer[4*i+1] as u32) << (2*8);
v += Wrapping(bytebuffer[4*i+2] as u32) << (1*8);
v += Wrapping(bytebuffer[4*i+3] as u32);
wordbuffer[i] = v;
}
wordbuffer
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T17:45:11.257",
"Id": "429255",
"Score": "0",
"body": "Check out `-C target-cpu=native`. Also, assuming your benchmark includes I/O, note that stdout is line buffered and must be locked on every call to `print`. See [this helpful article](https://llogiq.github.io/2017/06/01/perf-pitfalls.html)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T17:56:18.410",
"Id": "429257",
"Score": "0",
"body": "Also note that returning the array `[Wrapping<u32>; 64]` requires copying 4*64 = 256 bytes if not optimized away. You may prefer taking a `&mut [Wrapping<u32>; 64]` argument if the function is in a hot loop or otherwise determined to be taking a lot of time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-12T12:16:12.480",
"Id": "464901",
"Score": "0",
"body": "The above code looks good from a design perspective IMHO. I'm a bit wondering why you decided to mix main and part of the function though. I'd first test against test vectors, then optimize (unroll loop, inline functions) and finally clean up. If you use vars from the standard or from another implementation, then please provide a reference to that standard in the code (visiting unanswered crypto questions)."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T05:16:49.097",
"Id": "221826",
"Score": "4",
"Tags": [
"strings",
"reinventing-the-wheel",
"cryptography",
"rust"
],
"Title": "SHA256 implemented in Rust"
} | 221826 |
<p>C++17 introduces <code>std::invoke</code> which calls the exposition-only <code>INVOKE</code>. Here is an implementation. This isn't a large amount of code, and it is to a large extent a transliteration of <a href="https://timsong-cpp.github.io/cppwp/n4659/func.require" rel="nofollow noreferrer">[func.require]</a>.</p>
<p>I took the liberty to add <code>invoke_r</code> which calls <code>INVOKE<R></code> since I find it quite useful at times.</p>
<pre><code>// C++17 std::invoke implementation
#ifndef INC_INVOKE_HPP_6AY08xPaOo
#define INC_INVOKE_HPP_6AY08xPaOo
#include <functional>
#include <type_traits>
#include <utility>
namespace my_std {
// 23.14.4 Function template invoke [func.invoke]
// Returns: INVOKE(std::forward<F>(f), std::forward<Args>(args)...)
// (See 23.14.3 Requirements [func.require] Paragraph 1)
template <typename F, typename... Args>
std::invoke_result_t<F, Args...> invoke(F&& f, Args&&... args)
noexcept(std::is_nothrow_invocable_v<F, Args...>);
// Added functionality
// Returns: INVOKE<R>(std::forward<F>(f), std::forward<Args>(args)...)
// (See 23.14.3 Requirements [func.require] Paragraph 2)
template <typename R, typename F, typename... Args>
R invoke_r(F&& f, Args&&... args)
noexcept(std::is_nothrow_invocable_r_v<R, F, Args...>);
namespace detail {
template <typename T>
struct is_reference_wrapper :std::false_type {};
template <typename T>
struct is_reference_wrapper<std::reference_wrapper<T>>
:std::true_type {};
template <typename T>
inline constexpr bool is_reference_wrapper_v =
is_reference_wrapper<T>::value;
template <typename F, typename C, typename T, typename... Args>
decltype(auto) invoke_mfp(F C::*f, T&& t, Args&&... args)
{
// (1.1)
if constexpr (std::is_base_of_v<C, std::decay_t<T>>)
return (t.*f)(std::forward<Args>(args)...);
// (1.2)
else if constexpr (is_reference_wrapper_v<std::decay_t<T>>)
return (t.get().*f)(std::forward<Args>(args)...);
// (1.3)
else
return ((*t).*f)(std::forward<Args>(args)...);
}
template <typename M, typename C, typename T>
decltype(auto) invoke_mop(M C::*f, T&& t)
{
// (1.4)
if constexpr (std::is_base_of_v<C, std::decay_t<T>>)
return t.*f;
// (1.5)
else if constexpr (is_reference_wrapper_v<std::decay_t<T>>)
return t.get().*f;
// (1.6)
else
return (*t).*f;
}
}
template <typename F, typename... Args>
std::invoke_result_t<F, Args...> invoke(F&& f, Args&&... args)
noexcept(std::is_nothrow_invocable_v<F, Args...>)
{
// (1.1), (1.2), (1.3)
if constexpr (std::is_member_function_pointer_v<std::remove_reference_t<F>>)
return detail::invoke_mfp(f, std::forward<Args>(args)...);
// (1.4), (1.5), (1.6)
else if constexpr (sizeof...(Args) == 1 &&
std::is_member_object_pointer_v<std::remove_reference_t<F>>)
return detail::invoke_mop(f, std::forward<Args>(args)...);
// (1.7)
else
return std::forward<F>(f)(std::forward<Args>(args)...);
}
template <typename R, typename F, typename... Args>
R invoke_r(F&& f, Args&&... args)
noexcept(std::is_nothrow_invocable_r_v<R, F, Args...>)
{
if constexpr (std::is_void_v<R>)
return static_cast<void>(
invoke(std::forward<F>(f), std::forward<Args>(args)...)
);
else
return invoke(std::forward<F>(f), std::forward<Args>(args)...);
}
}
#endif
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T05:41:51.807",
"Id": "221828",
"Score": "4",
"Tags": [
"c++",
"reinventing-the-wheel",
"c++17",
"template-meta-programming"
],
"Title": "C++17 implementation of std::invoke"
} | 221828 |
<p>My program opens a website and downloads a text file. The text file is a simple file with one word per line. I save the file to local disk and then create a list to hold each line of the text file for later processing. I would like to know if I am doing these first steps in a way that would be considered idiomatic Python and have I made any big mistakes that will hamper my efforts to expand on it later.</p>
<p>This is similar to an exercise in Think Python by Allen Downey. He suggests using a browser to download the text file but I wanted to do it with Python. </p>
<pre><code>import requests
def get_webpage(uri):
return requests.get(uri)
def save_webpagecontent(r, filename):
""" This function saves the page retrieved by get_webpage. r is the
response from the call to requests.get and
filename is where we want to save the file to in the filesystem."""
chunk_size = 8388608 # number of bytes to write to disk in each chunk
with open(filename, 'wb') as fd:
for chunk in r.iter_content(chunk_size):
fd.write(chunk)
def make_wordlist(filename):
wordlist = []
with open(filename) as fd:
wordlist = fd.readlines()
return wordlist
def get_mylist(wordlist, num_lines=10):
if len(wordlist) <= num_lines:
return wordlist
return wordlist[:num_lines]
def print_mylist(mylist):
for word in mylist:
print(word.strip())
return None
"""List of words collected and contributed to the public domain by
Grady Ward as part of the Moby lexicon project. See https://en.wikipedia.org/wiki/Moby_Project
"""
uri = 'https://ia802308.us.archive.org/7/items/mobywordlists03201gut/CROSSWD.TXT'
filename = 'wordlist.txt'
r = get_webpage(uri)
save_webpagecontent(r, filename)
wordlist = make_wordlist(filename)
mylist = get_mylist(wordlist)
print_mylist(mylist)
</code></pre>
<p>My program works as I expect it to. I have basically found how to do each individual piece by reading this forum and but I would like to know if I'm putting all the pieces together correctly. By correctly I mean something that not only functions as expected but also will be easy to build larger programs and modules from.</p>
<p>I hope it isn't wrong of me to post this much code. I wasn't sure how I could trim it down and still show what I am doing. Please let me know if I need to change the format of my question.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T06:12:17.463",
"Id": "429145",
"Score": "3",
"body": "Your code looks good, and it is not really long. Here on Code Review it is accepted to sometimes post around 1000 lines, if that's necessary for understanding the code. When pasting your code, you made a small mistake with the indentation around the `chunk_size` line. After you repaired this, your question is in a perfect format for this site, especially since you explained in detail what code you wrote and why. That's something essential that several other questions are missing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T06:21:42.140",
"Id": "429147",
"Score": "1",
"body": "Thank you for your remarks. I feel more encouraged about the process now!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T06:29:14.920",
"Id": "429148",
"Score": "3",
"body": "Don't worry, the SE network can be confusing for new users. You're in The Good Place now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T19:49:17.753",
"Id": "429276",
"Score": "0",
"body": "Might want to add an event in case the request can't be completed and you can't download the code."
}
] | [
{
"body": "<p>Your program is concise and well-readable. One thing that is probably less pythonic is storing the received data in a file. If you have no further use for the file, you could just process the data into a wordlist while receiving it. This saves one intermediate step, and your program would not leave a residual <code>wordlist.txt</code> file around.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T10:11:44.573",
"Id": "429186",
"Score": "3",
"body": "Besides the gains mentioned, file I/O is expensive CPU-wise. However, it's unclear at the moment whether the further processing of the words (*\"and then create a list to hold each line of the text file for later processing\"*) is going to be done by the same Python program or a different program altogether. Saving to file as an intermediary step for safety/redundancy/whatever reasons is still a good reason to keep it around."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T17:27:28.700",
"Id": "429254",
"Score": "0",
"body": "Thank you both. I saved the file for two reasons: 1) I knew that I would want to be accessing the file many times over and over to try different analysis techniques as my knowledge grows. I'll be running word length analysis and letter frequency analysis and then trying out different ways to display the results. I thought it would be more efficient that downloading it many times over and over and also more polite to the site I'm downloading from. 2) I am thinking about how I should write programs in case I have less than ideal network conditions. Thanks again!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T20:48:19.460",
"Id": "429289",
"Score": "0",
"body": "One way to download the file only once would be to check for its existence and only download it if the file is not present. That's basically a simple cache without an invalidation policy, and you can manually invalidate the cache by removing the file. Alternatively, you could write separate download and analysis programs, which would help to avoid code duplication with the associated risk of having slightly different versions of the download code in each program."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T03:11:37.917",
"Id": "429312",
"Score": "0",
"body": "Thank you to everyone for the reviews. I have made some big updates to my code using the suggestions I received here. Should I now open another request for a code review or should I answer my question with my updated code? The changes include splitting the file handling into another module and using contextmanager to handle file not found errors."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T08:24:30.670",
"Id": "221843",
"ParentId": "221830",
"Score": "3"
}
},
{
"body": "<p>Your code is nice and concise however there are some changes you can make:</p>\n\n<ol>\n<li>You can just return <code>f.readlines()</code> in <code>make_wordlist</code>.</li>\n<li><p>If you've done this to show that the result is a list then it'd be better to use the <code>typing</code> module.</p>\n\n<pre><code>from typing import List\n\n\ndef make_wordlist(filename: str) -> List[str]:\n ...\n</code></pre></li>\n<li><code>get_mylist</code> can be replaced with <code>wordlist[:numlines]</code>. This is because if <code>len(wordlist)</code> is smaller or equal to <code>numlines</code>, then it will return the entire thing anyway.</li>\n<li>Performance wise it's best to use <code>print('\\n'.join(list))</code> rather than <code>for item in list: print(item)</code>.</li>\n<li>I would prefer to be able to change <code>chunk_size</code> in <code>save_webpagecontent</code> and so you can make it a default argument.</li>\n<li>IIRC multi-line docstrings shouldn't start on the same line as the <code>\"\"\"</code>, nor should they end on the same line either.</li>\n</ol>\n\n<pre><code>import requests\nfrom typing import List\n\nResponse = requests.Response\n\n\ndef get_webpage(uri) -> Response:\n return requests.get(uri)\n\n\ndef save_webpagecontent(r: Response, filename: str,\n chunk_size: int=8388608) -> None:\n \"\"\"\n This function saves the page retrieved by get_webpage. r is the \n response from the call to requests.get and\n filename is where we want to save the file to in the filesystem.\n \"\"\"\n with open(filename, 'wb') as fd:\n for chunk in r.iter_content(chunk_size):\n fd.write(chunk)\n\n\ndef read_wordlist(filename: str) -> List[str]:\n with open(filename) as fd:\n return fd.readlines()\n\n\ndef print_mylist(word_list: List[str]) -> None:\n print('\\n'.join(word.strip() for word in word_list))\n\n\n\"\"\"\nList of words collected and contributed to the public domain by\nGrady Ward as part of the Moby lexicon project. See https://en.wikipedia.org/wiki/Moby_Project\n\"\"\"\nuri = 'https://ia802308.us.archive.org/7/items/mobywordlists03201gut/CROSSWD.TXT'\nfilename = 'wordlist.txt'\n\nr = get_webpage(uri)\nsave_webpagecontent(r, filename)\nprint_mylist(read_wordlist(filename)[:10])\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T09:51:31.673",
"Id": "429183",
"Score": "1",
"body": "`requests.get()` returns a `Response` object, not a `Request`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T09:54:01.537",
"Id": "429184",
"Score": "1",
"body": "@LukaszSalitra Thank you, I've updated the code with that. Thought I read the docs correctly :/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T13:35:09.293",
"Id": "429209",
"Score": "1",
"body": "As per [PEP257](https://www.python.org/dev/peps/pep-0257/#multi-line-docstrings) multi-line docstrings can start either right after the opening `\"\"\"` or on the line below."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T17:14:28.893",
"Id": "429249",
"Score": "0",
"body": "Thank you for your review. So is type hinting (I think that's what it's called) the defacto Pythonic way now? I have to admit that now that I know what the syntax means it does seem really easy to look at a function and know how to use it. Readability is reason enough to start using it but I am also wondering if Python uses to make code safer or more efficient? Again, thanks for the review and tips."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T18:27:54.013",
"Id": "429262",
"Score": "1",
"body": "@DuaneWhitty It's 100% optional. They don't make the code faster. If you use one of mypy, pyright, pyre or pytype then they can perform static code analysis which should make your code safer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T22:26:32.457",
"Id": "429299",
"Score": "0",
"body": "print_mylist(read_wordlist(filename)[:10])\n\nIf I am understanding this correctly what is happening is that make_wordlist() and get_mylist have been replaced by one function, read_wordlist(), which all in one go opens the file and returns a list. Then we pass a slice of that list to the print_mylist() function. No intermediary functions or variables involved. So to make concrete my takeaway, regardless of how an object is delivered, whether assigned to a variable name or not, the object is the same. So,\n\n read_wordlist(filename)[:10]\n\nis the same as wordlist[:10]. That's cool!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T22:28:29.523",
"Id": "429300",
"Score": "0",
"body": "Sorry for the formatting of my comment. I've tried to fix it twice but I seem not to be doing the code block mode or blank lines correctly"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T22:38:03.080",
"Id": "429303",
"Score": "1",
"body": "@DuaneWhitty No problem to use `this text` you need to write \\`this text\\`. Feel free to try that out here. You also can't put newlines in comments. (They would look like a mess) Yeah looks like you're correct."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T00:17:30.523",
"Id": "429307",
"Score": "0",
"body": "Thanks. So I was trying to get this effect `print_mylist(read_wordlist(filename)[:10])`"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T09:43:18.583",
"Id": "221847",
"ParentId": "221830",
"Score": "7"
}
},
{
"body": "<p>Code downloads a text file from a website, saves it to local disk, and then loads it into a list for further processing - Version 2.0</p>\n\n<p>In my new version of this code I have separated my code into 3 modules (my start at a 12 factor app):</p>\n\n<p><code>download.py</code> for handling downloading the text file from the website and saving it as a file to local storage;</p>\n\n<p><code>config.py</code> for specifying the URI of the website and the filename for local storage;</p>\n\n<p><code>moby.py</code> is the actual code that reads the words in the text file, 1 per line, into a list. For now all it does is prints out the words from the file, one per line.</p>\n\n<p>The review my code received provided valuable suggestions on how it could be made more Pythonic, more modular, and more efficient.</p>\n\n<p>Motivated by <a href=\"https://codereview.stackexchange.com/users/190512/hans-martin-mosner\">Hans-Martin Mosner</a> to separate the file download code here is that module. Also made the chunk_size a parameter to the save_webpagecontent() function based on as suggested by <a href=\"https://codereview.stackexchange.com/users/42401/peilonrayz\">Peilonrayz</a></p>\n\n<p><strong>download.py</strong></p>\n\n<pre><code>import requests\nfrom typing import List\n\nResponse = requests.Response\n\ndef get_webpage(uri) -> Response:\n return requests.get(uri)\n\n\ndef save_webpagecontent(r: Response, filename: str, chunk_size=8388608) -> None:\n \"\"\"\n This function saves the page retrieved by get_webpage.\n r is the response from the call to requests.get.\n filename is where we want to save the file to in the filesystem.\n chunk_size is the number of bytes to write to disk in each chunk\n \"\"\"\n\n with open(filename, 'wb') as fd:\n for chunk in r.iter_content(chunk_size):\n fd.write(chunk)\n</code></pre>\n\n<p><strong>config.py</strong></p>\n\n<pre><code>uri = 'https://ia802308.us.archive.org/7/items/mobywordlists03201gut/CROSSWD.TXT'\nfilename = 'wordlist.txt'\n</code></pre>\n\n<p>I feel I made the most gains in my Python profiency as a result of implementing the changes suggested by <a href=\"https://codereview.stackexchange.com/users/42401/peilonrayz\">Peilonrayz</a> where I did away with intermediate function calls and variables and by working on the suggestion by <a href=\"https://codereview.stackexchange.com/users/92133/brucewayne\">BruceWayne</a> to add an event for failing to open the file. The file opening code turned out to be the most challenging. I wasn't able to get `opened_w_error() working exactly based on the example from <a href=\"https://www.python.org/dev/peps/pep-0343/\" rel=\"nofollow noreferrer\">PEP343</a>. Figuring it out was very rewarding.</p>\n\n<p><strong>moby.py</strong></p>\n\n<pre><code>import download_file as df\nimport config as cfg\nfrom contextlib import contextmanager\nfrom typing import List\n\nfilename = cfg.filename\nuri = cfg.uri\n\n@contextmanager\ndef opened_w_error(filename, mode=\"r\"):\n try:\n f = open(filename, mode)\n except OSError as err:\n yield None, err\n else:\n try:\n yield f, None\n finally:\n f.close()\n\n\ndef read_wordlist(filename: str) -> List[str]:\n with opened_w_error(filename, 'r') as (fd, err):\n if type(err) == FileNotFoundError:\n df.save_webpagecontent(df.get_webpage(uri), filename) #since it failed the first time we need to actually download it\n with opened_w_error(filename, 'r') as (fd, err): # if it fails again abort\n if err:\n print(\"OSError:\", err)\n else:\n return fd.readlines()\n else:\n return fd.readlines()\n\n\ndef print_mylist(wordlist: List[str]) -> None:\n print('\\n'.join(word.strip() for word in wordlist))\n\n\nprint_mylist(read_wordlist(filename)[:50])\n</code></pre>\n\n<p>Thank you to everyone, especially <a href=\"https://codereview.stackexchange.com/users/6499/roland-illig\">Roland Illig</a>, <a href=\"https://codereview.stackexchange.com/users/190512/hans-martin-mosner\">Hans-Martin Mosner</a>, and <a href=\"https://codereview.stackexchange.com/users/52915/mast\">Mast</a> for all your help and encouragement and a safe place to learn!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T04:40:09.633",
"Id": "221901",
"ParentId": "221830",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "221847",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T05:56:43.647",
"Id": "221830",
"Score": "11",
"Tags": [
"python",
"array",
"file"
],
"Title": "Code downloads a text file from a website, saves it to local disk, and then loads it into a list for further processing"
} | 221830 |
<p>Someone asked <a href="https://stackoverflow.com/questions/24248596/how-to-tell-if-a-function-is-being-called-from-a-multiple-threads">here</a> how to determine a function is being called from multiple threads. My take on this is that they are asking about <em>concurrent</em> access not sequential access. The accepted answer therefore seems inadequate. Detecting concurrent access is also a problem I need to solve for debugging purposes so I thought I'd take a stab at a solution.</p>
<p>This takes an RAII-style approach to the solution, requiring only an instantiation of the class at the top of the function in question.</p>
<pre><code>template <std::ostream& stream> class ConcurrentPrint: public std::ostringstream
{
public:
~ConcurrentPrint()
{
std::scoped_lock lock(printMutex);
stream << this->str();
}
private:
static std::mutex printMutex;
};
template <std::ostream& stream> std::mutex ConcurrentPrint<stream>::printMutex;
class ConcurrencyChecker
{
public:
ConcurrencyChecker(const std::string& id_) :
id(id_)
{
std::scoped_lock lock(mapMutex);
if (++numInstances[id] > 1)
{
ConcurrentPrint<std::cerr>() << "Warning: concurrent access to " << id << " from " << std::this_thread::get_id() << std::endl;
abort();
}
}
~ConcurrencyChecker()
{
std::scoped_lock lock(mapMutex);
--numInstances[id];
}
private:
static std::map<std::string, int> numInstances;
static std::mutex cerrMutex;
const std::string id;
std::mutex mapMutex;
};
std::map<std::string, int> ConcurrencyChecker::numInstances = {};
</code></pre>
<p>Intended usage:</p>
<pre><code>void functionToCheck()
{
ConcurrencyChecker check(__func__);
/* Function body */
}
</code></pre>
<p>Working example <a href="http://coliru.stacked-crooked.com/a/37925367df06370d" rel="nofollow noreferrer">here</a></p>
<p>Things I'm interested in:</p>
<ul>
<li>Are there any flaws in this general approach and is there a better one?</li>
<li>Any general improvements to the code</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T07:28:38.547",
"Id": "429150",
"Score": "1",
"body": "Are you missing a definition of `ConcurrencyChecker::cerrMutex`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T07:47:44.047",
"Id": "429151",
"Score": "0",
"body": "@TobySpeight good catch. `cerrMutex` is actually unneeded and just residual from before I broke `ConcurrentPrint` into its own class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T12:24:40.683",
"Id": "429204",
"Score": "0",
"body": "This is a non deterministic detector. Even if the caller does everything she can to cause concurrent access, it might not get caught by your detector (even your test is not deterministic -- suppose the ith thread yields for 10*i seconds immediately after being called and there are no other breaks). In my opinion, you're better off proving the fn can/cannot be called concurrently at design time rather than trying to debug it at runtime. There are tools that can automate this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T13:11:12.430",
"Id": "429208",
"Score": "0",
"body": "@sudorm-rfslash I'm a bit confused by what you mean here. How is it possible for `i` threads to enter the function (i.e. *after* the construction of `ConcurrencyChecker`) without `numInstances` being incremented `i` times? Since it is incremented during object construction and decremented during destruction don't we have determinism for measuring concurrent execution of the function body following construction of `ConcurrencyChecker` (marked `/* Function body */` in the code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T13:37:57.543",
"Id": "429211",
"Score": "0",
"body": "\"i.e. after the construction of ConcurrencyChecker\" ... this is where our assumptions differ. the pc could point to the first instruction in the function, which in these examples would be the ctor of the checker. the pc is clearly in the function, but the checker hasn't run yet. threads can block anywhere for any amount of time"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T15:02:46.507",
"Id": "429223",
"Score": "2",
"body": "The core of the claim here is that while your construction can tell you that you do have a problem, it cannot tell you that you do not. That is to say, it is possible to run your thing in testing a dozen times and it be fine, but the code could still exhibit race conditions that happen on run number twenty-four. Therefore although it can be helpful, especially for detection of frequent collisions, it should not be relied on alone."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T15:04:11.940",
"Id": "429224",
"Score": "0",
"body": "@sudorm-rfslash that's a fair point. I think the key is to state the assumptions of the checker clearly. I'm also thinking that a better overall solution may to be use a macro that wraps the function call rather than trying to measure inside the function itself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T21:57:11.573",
"Id": "429295",
"Score": "1",
"body": "A macro actually wouldn't materially change the point made. You don't care about whether two threads are technically running the same function. You do care whether they are might be doing mutually dangerous operations, and being in the same function is shorthand for that. Therefore, whether the check is technically before or after the function call is less important than that it is before any dangerous stuff."
}
] | [
{
"body": "<p>A few observations off the top of my head</p>\n\n<p><code>cerrMutex</code> is unused, and should be removed if not needed.</p>\n\n<p><code>mapMutex</code> is used to guard a static <code>std::map</code> but is itself a regular class member variable. That suggests it probably isn't guarding the map against concurrent access. This is probably a bug.</p>\n\n<p>This seems like a fairly heavyweight tool. The uses of maps and strings all smell bloaty. That's not of itself a killer, but it's worth being at least aware of. If there were the possibility of just using, say, object-local integers for counting (and perhaps a function scope static declaration to use the same counting variables), that would probably be lighter. </p>\n\n<p>On the other hand, in a general use case, concurrency causes problems whenever two threads are interacting with the same resource, not only when executing the same function. For example this tool would be significantly more useful if it could detect different threads concurrently running two methods of a single object.<br>\nAt the same time, it would be more helpful if it actually <strong>did not</strong> interfere with two threads each holding their own object of a given class and each running methods on their own object. This is perhaps more of a documentation enhancement suggestion: your rough approach could work by changing what ID you pass, but it would benefit from examples. (And don't go changing it to make it lightweight if it means losing the ability to do this!)</p>\n\n<hr>\n\n<p>A final thing that is worth thinking about is whether this causes any inadvertant synchronisation that actually masks the very problems you're trying to detect. This is hard to predict, because schedulers can be such a dark art in general, but you could run into a problem like this.</p>\n\n<p>Suppose that you have two threads running a function that does something lightweight, perhaps just increment a shared integer. Without this tool in place, you'd expect them to keep stomping on each other. </p>\n\n<p>Because you're syncing up on <code>mapMutex</code> (which I'm going to assume as above is meant to be static) then each call to the function has to do a lot of extra work in the constructor and destructor of your tool, and that is all under exclusion. If thread 2 starts while thread 1 is still in the constructor, it will fail to take <code>mapMutex</code> and the scheduler will probably send it to sleep for a bit. The window for it to wake up in which thread 1 is in the function and does not have the mutex is actually quite small. What you could get, then, is the function seems to behave fine (albeit slowly) while this object is trying to help with debugging and then goes back into data races for release code when the debug object is removed. Suffice to say, that's unhelpful! </p>\n\n<p>I don't have any suggestions about how to fix this problem, just that it's the sort of thing that is worth being aware of. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T08:00:01.317",
"Id": "429156",
"Score": "0",
"body": "thanks for the helpful feedback. I used the `map` to facilitate differentiating usage from different functions. An `unordered_map<int, int>` using integer ids would be lighter but then you lose the option to identify the caller by name. OTOH, taking on board your overall points, I wonder if the problem might be better solved with a macro..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T07:37:31.057",
"Id": "221837",
"ParentId": "221831",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T06:17:24.480",
"Id": "221831",
"Score": "4",
"Tags": [
"c++",
"multithreading",
"thread-safety",
"concurrency"
],
"Title": "Determine concurrent access to a function"
} | 221831 |
<p>I'm developing a web app that will be used privately by a company (no need for SEO and old browsers support).</p>
<p>I made some interactive components (calendar, file manager, etc) that I am not sure if I implemented them properly. I use the simplest of them (contact picker) as an example here.</p>
<p>I'm wondering if I should make a js object for each component (with getters, setters, etc), or if there is any other design flaw.<br>
Also is it ok to write plain html code inside js like I did in <code>createContactPicker</code>, considering that it would be a much longer code if I used a bunch of <code>createElement</code> and <code>setAttribute</code>?</p>
<h1>The contact picker:</h1>
<p>The contact picker is a text box that shows suggestions for contacts (based on server's response to ajax requests) while the user types the name of the contact. The hidden input with <code>name="contact_id"</code> is the value that will actually be used in html forms, the rest is there for the user's convenience.</p>
<h2>contactPicker.js</h2>
<pre><code>function createContactPicker(container, contactType){
const picker = document.createElement('div');
picker.classList.add('contact_picker');
let html = '<input type="hidden" name="contact_id">';
if(contactType != null){
picker.setAttribute('data-type', contactType);
}
html += '<input type="text" class="contact_name" oninput="suggestContacts(this)" onfocus="toggleSuggestions(this, true)" onblur="toggleSuggestions(this, false)"><table class="dropdown"></table>';
picker.innerHTML = html;
container.appendChild(picker);
}
// onload replace elements of class 'onload_create_contact_picker' with contact pickers
window.addEventListener('DOMContentLoaded', function(){
let elements = document.getElementsByClassName('onload_create_contact_picker');
for(let i = elements.length - 1; i >=0; i--){
let elem = elements.item(i);
createContactPicker(elem, elem.getAttribute('data-type'));
let parent = elem.parentElement;
parent.insertBefore(elem.firstChild, elem);
parent.removeChild(elem);
}
});
function suggestContacts(sender){
const picker = sender.closest('.contact_picker');
unpickContant(picker);
const contactName = picker.getElementsByClassName('contact_name')[0].value;
if(contactName == ''){
const container = picker.getElementsByClassName('dropdown')[0];
container.innerHTML = '';
return;
}
const contactType = picker.getAttribute('data-type');
const ajaxData = {name: contactName, type: contactType};
if(contactType == null){
delete ajaxData.type;
}
$.ajax({
type: 'GET',
url: '../ajax/suggestContacts.php',
data: ajaxData,
success: function(data){
updateSuggestions(data, picker);
}
});
}
function updateSuggestions(data, picker){
const container = picker.getElementsByClassName('dropdown')[0];
data = JSON.parse(data);
if(data.length == 0){
container.innerHTML = '<span class="note">No matches</span>';
} else {
container.innerHTML = '';
for(contact of data){
const tr = document.createElement('tr');
let td = document.createElement('td');
td.textContent = contact.type;
tr.appendChild(td);
td = document.createElement('td');
td.textContent = contact.name;
let span = document.createElement('span');
span.textContent = contact.title;
span.classList.add('note');
td.appendChild(document.createElement('br'));
td.appendChild(span);
tr.appendChild(td);
tr.setAttribute('data-contact-id', contact.id);
tr.setAttribute('data-contact-name', contact.name);
tr.setAttribute('onmousedown', 'pickContact(this)');
container.appendChild(tr);
}
}
positionSuggestions(picker, container);
}
function positionSuggestions(picker, container){
const rectP = picker.getBoundingClientRect();
const rectC = container.getBoundingClientRect();
if(rectP.bottom + rectC.height > (window.innerHeight || document.documentElement.clientHeight)){
container.style.top = 'auto';
container.style.bottom = 'calc(100% - 3px)';
} else {
container.style.bottom = 'auto';
container.style.top = 'calc(100% - 3px)';
}
}
function clearSuggestions(sender){
const picker = sender.closest('.contact_picker');
const container = picker.getElementsByClassName('dropdown')[0];
container.innerHTML = '';
}
function toggleSuggestions(sender, visible){
const picker = sender.closest('.contact_picker');
const container = picker.getElementsByClassName('dropdown')[0];
container.style.display = visible ? '' : 'none';
}
function pickContact(selected){
const picker = selected.closest('.contact_picker');
const idElem = picker.querySelector('input[name="contact_id"]');
const nameElem = picker.getElementsByClassName('contact_name')[0];
nameElem.value = selected.getAttribute('data-contact-name');
idElem.value = selected.getAttribute('data-contact-id');
if(!picker.classList.contains('picked')){
picker.classList.add('picked');
}
}
function unpickContant(picker){
picker.querySelector('input[name="contact_id"]').value = null;
picker.classList.remove('picked');
}
</code></pre>
<h2>css (only the suggestions positioning)</h2>
<pre><code>.contact_picker{
position: relative;
}
.contact_picker .dropdown{
position: absolute;
z-index: 1;
left: 2px;
}
</code></pre>
<h1>Usage example:</h1>
<pre><code><html>
<head>
<script src="javascript/jquery-3.4.0.min.js"></script>
<script src="components/contactPicker.js"></script>
</head>
<body>
<form name="choose_client_example">
Choose a client:
<div class="onload_create_contact_picker" data-type="client"></div>
<button>Submit</button>
</form>
</body>
</html>
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T07:00:44.337",
"Id": "221835",
"Score": "2",
"Tags": [
"javascript",
"beginner",
"html"
],
"Title": "Javascript contact picker"
} | 221835 |
<p>I have C# code that makes some calculations for physical models. I have this project class:</p>
<pre><code>public class Project
{
public IEnumerable<GenericComponent> components;
private ValueService valueService = new ValueService(Guid.NewGuid().ToString());
public Project(string norm)
{
components = FactoryGenerator.GetFactory(norm).GetComponents();
}
public void SetValues(IEnumerable<ValueViewModel> values)
{
values.ToList().ForEach(t => valueService.SetValue(t.Key, t.Value));
}
public bool Valid(string componentName)
{
return components.Where(s => s.Title == componentName).Single().Valid();
}
}
</code></pre>
<p>That creates smaller components that do some calculations. E.g. </p>
<pre><code>public class CrossSectionComponent: GenericComponent
{
public CrossSectionComponent(ValueService valueService): base(valueService)
{
}
ICrossSectionViewModel crossSection;
double valuex;
override
public bool Valid()
{
return valuex > valueService.GetValue<double>("valuey") ? true : false;
}
}
</code></pre>
<p>Each component has a list of values with keys that are unique over the entire model. At the moment I use a <code>ValueService</code>, where each component registers its values with the respective keys. The <code>ValueService</code> can be used to get values from other components in order to do validation calculations. </p>
<pre><code> private string projectUUID;
private List<ValueViewModel> values = new List<ValueViewModel>();
public ValueService(string projectUUID)
{
this.projectUUID = projectUUID;
}
public void RegisterValue(string key)
{
if (!this.hasKey(key))
{
values.Add(new ValueViewModel()
{
Key = key,
});
}
}
public void SetValue(string key, object value)
{
if (this.hasKey(key))
this.values.Find(t => t.Key == key).Value = value;
}
public T GetValue<T>(string key)
{
return (T)values.Find(t => t.Key == key)?.Value;
}
private bool hasKey(string key)
{
return values.Any(t => t.Key == key);
}
}
</code></pre>
<p>This is part of a stateless API, i.e. for each HTTP request (at the moment) a new <code>Project</code> object is generated and used to make validations. </p>
<p>My API controller looks like this:</p>
<pre><code> public IActionResult postData([FromRoute] string norm, [FromRoute] string component, [FromBody] ValueViewModel[] data)
{
Project project = new Project(norm);
project.SetValues(data);
return Ok(project.Valid(component));
}
</code></pre>
<p>The validity of one component does depend in most cases on values of other components. If one wants to check the validity of a components, the use sends a list of values (<code>ValueViewModel[] data</code>), the server creates the project where all available values are stored. Then <em>IF AND ONLY IF</em> all required values are set, the validity can actually be calculated. If not all values are provided inside the "data list", then the validity of said component is false. So there are two cases where component.Valid() => false</p>
<ol>
<li>The calculations yield false</li>
<li>Not all values have been submitted</li>
</ol>
<p>My concerns are</p>
<ul>
<li>When the project continues, the number of components will get quite large, I fear there will be a performance issue if for each request the whole set of components needs to be generated --> <strong>should I use LazyLoading</strong>?</li>
<li>Is the <code>ValueService</code> approach good to share data between the components? <strong>Is there a better solution</strong>?</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T08:38:35.313",
"Id": "429170",
"Score": "1",
"body": "There is alot that can be reviewed here. One tip I could give you of the bat is to use another type of collection for key-value lookup. `IDictionary<string, ValueViewModel>` for instance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T09:24:11.577",
"Id": "429176",
"Score": "0",
"body": "So the validity of a component can depend on other components? And the server only stores a collection of components, but the actual values must all be provided by the client?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T09:31:37.273",
"Id": "429177",
"Score": "0",
"body": "@PieterWitvoet I updated the OP. Basically yes, they highly depend on other components, whereas the other components \"only register values\", the actual storage is inside the valueservice (at the moment). The server itself doesn't store anything, it gets all values via the HTTPBody of the request."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T09:42:59.090",
"Id": "429180",
"Score": "0",
"body": "@rst Perhaps you should provide us a more tangible use case. With what you provide in the example, I would argue the need for the components altogether."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T09:58:22.753",
"Id": "429185",
"Score": "0",
"body": "The logic, how a validation is performed is stored inside the components, delivered by the component factory depending on the norm you provide. That structure is bascially set, I just don't know how to nicely share values among those components (now done by ValueService)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T11:21:28.993",
"Id": "429196",
"Score": "0",
"body": "@rst So you are creating all components, just to let 1 component perform validation on the input values. And components don't know eachother, and they don't rely on data provided by eachother, correct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T08:56:26.357",
"Id": "429337",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] | [
{
"body": "<p>You have built a system of components and shared objects, but don't use its potential. In fact, for your use case the complete setup is an overkill.</p>\n\n<ul>\n<li>There is no component hierarchy</li>\n<li>There are no component-sensitive or -specific values</li>\n<li>You only need a single component to verify any incoming request</li>\n</ul>\n\n<blockquote>\n<pre><code> public IActionResult postData(\n [FromRoute] string norm, \n [FromRoute] string component, \n [FromBody] ValueViewModel[] data)\n {\n Project project = new Project(norm);\n project.SetValues(data);\n return Ok(project.Valid(component));\n }\n</code></pre>\n</blockquote>\n\n<p>For the aforementioned reasons, I don't see a need for having a list of components and values. I would rewrite the API to be as simple as possible:</p>\n\n<ul>\n<li>Let the factory retrieved by <code>FactoryGenerator</code> get the requested component</li>\n<li>Let that component validate the input values</li>\n</ul>\n\n<p>code:</p>\n\n<pre><code>public IActionResult postData(\n [FromRoute] string norm, \n [FromRoute] string component, \n [FromBody] ValueViewModel[] data)\n {\n var component = FactoryGenerator.GetFactory(norm).GetComponent(component);\n return Ok(component.Valid(data));\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T11:41:46.680",
"Id": "429199",
"Score": "1",
"body": "I have omitted a part of the code which I thought is not essential for the \"problem\" I wanted to address. However, I believe now it indeed is essential. I would like to rethink on how to properly ask the question and would simply accept your answer for the sake of reputation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T11:42:54.550",
"Id": "429202",
"Score": "0",
"body": "@rst Good call. I am happy to review an updated question that shows the potential of your API."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T11:31:26.033",
"Id": "221853",
"ParentId": "221842",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "221853",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T08:13:42.363",
"Id": "221842",
"Score": "1",
"Tags": [
"c#",
"asp.net-core-webapi"
],
"Title": "A ValueService is used to share data among objects"
} | 221842 |
<p>Question:
There is an Exam_Merge table into which to import
records from a similarly structured table in another database.
In this case, the Exam_Merge table contains the values of the primary key ID
from another database, but this field is not unique.
For some reason, some of the entries in it were duplicated:
an entry with the same ID is contained in the table 2 times,
the values of the remaining field of duplicate records also coincide.</p>
<p>It is necessary to remove duplicates, leaving only non-duplicate IDs.</p>
<p>My question - is it correct and efficient approach or something efficient way exists?
sqlfiddle: <a href="http://www.sqlfiddle.com/#!18/dce35/1" rel="nofollow noreferrer">http://www.sqlfiddle.com/#!18/dce35/1</a></p>
<p>DDL: </p>
<pre><code>CREATE TABLE exam_merge
(
id INT NOT NULL,
student_code NVARCHAR(10) NOT NULL,
exam_code NVARCHAR(10) NOT NULL,
mark INT NULL
);
</code></pre>
<p>QUERY: </p>
<pre><code>WITH cte
AS (SELECT id,
student_code,
exam_code,
mark,
Row_number()
OVER(
partition BY id, student_code, exam_code, mark
ORDER BY student_code) AS rn
FROM exam_merge)
DELETE cte
WHERE rn > 1
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T09:40:21.103",
"Id": "429178",
"Score": "1",
"body": "I believe it is optimal: https://stackoverflow.com/questions/18390574/how-to-delete-duplicate-rows-in-sql-server/38938704"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T11:16:19.987",
"Id": "429195",
"Score": "0",
"body": "@dfhwze Thank you twice! the first answer by your link is a great solution!"
}
] | [
{
"body": "<h2>Review</h2>\n\n<p>Your SQL seems the generally accepted way (<a href=\"https://stackoverflow.com/questions/18390574/how-to-delete-duplicate-rows-in-sql-server/38938704\">Discussed Before</a>) of deleting duplicates.</p>\n\n<blockquote>\n<pre><code>WITH cte \n AS (SELECT id, \n student_code, \n exam_code, \n mark, \n Row_number() \n OVER( \n partition BY id, student_code, exam_code, mark \n ORDER BY student_code) AS rn \n FROM exam_merge) \nDELETE cte \nWHERE rn > 1\n</code></pre>\n</blockquote>\n\n<h2>Optimization</h2>\n\n<p>I found a possible optimization using a non-clustered index. You would like to create a (non-unique) index on your key (id) with the other columns included.</p>\n\n<pre><code>CREATE NONCLUSTERED INDEX idx_exam_merge ON exam_merge\n(id) \nINCLUDE (student_code, exam_code, mark);\n</code></pre>\n\n<p><a href=\"https://www.sqlshack.com/sql-server-non-clustered-indexes-with-included-columns/\" rel=\"nofollow noreferrer\">This example</a> shows how such index could optimize the query plan to avoid clustered index lookup.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-27T17:27:38.170",
"Id": "225047",
"ParentId": "221844",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T09:10:25.380",
"Id": "221844",
"Score": "3",
"Tags": [
"sql",
"interview-questions",
"sql-server",
"t-sql"
],
"Title": "T-SQL Query remove duplicates except for original row from the table"
} | 221844 |
<p><strong>The task</strong> is taken from <a href="https://leetcode.com/problems/merge-two-sorted-lists/" rel="noreferrer">LeetCode</a></p>
<blockquote>
<p><em>Merge two sorted linked lists and return it as a new <strong>list</strong>. The new list should be made by splicing together the nodes of the first two
lists.</em></p>
<p><strong>Example 1</strong>:
<a href="https://i.stack.imgur.com/MAhz5.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/MAhz5.jpg" alt="enter image description here" /></a></p>
<pre><code>Input: l1 = [1,2,4], l2 = [1,3,4]
Output: [1,1,2,3,4,4]
</code></pre>
<p><strong>Example 2</strong>:</p>
<pre><code>Input: l1 = [], l2 = []
Output: []
</code></pre>
</blockquote>
<blockquote>
<p><strong>Example 3</strong>:</p>
<pre><code>Input: l1 = [], l2 = [0]
Output: [0]
</code></pre>
<p><strong>Constraints</strong>:</p>
<ul>
<li>The number of nodes in both lists is in the range [0, 50].</li>
<li><code>-100 <= Node.val <= 100</code></li>
<li>Both <code>l1</code> and <code>l2</code> are sorted in <strong>non-decreasing</strong> order.</li>
</ul>
</blockquote>
<p>The following <strong>solutions</strong> are identical logically. They only differ in style:</p>
<p><strong>Style 1</strong></p>
<pre><code> /**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var mergeTwoLists = function(l1, l2) {
if (!l1) return l2;
if (!l2) return l1;
if (l1.val < l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
}
l2.next = mergeTwoLists(l2.next, l1);
return l2;
};
</code></pre>
<p><strong>Style 2</strong></p>
<pre><code> /**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var mergeTwoLists = function(l1, l2) {
if (!l1 || !l2) return l1 || l2;
const linkThem = (smaller, greater) => {
smaller.next = mergeTwoLists(smaller.next, greater);
return smaller;
};
return l1.val < l2.val ? linkThem(l1,l2) : linkThem(l2,l1);
};
</code></pre>
| [] | [
{
"body": "<h3>Looks good!</h3>\n<ul>\n<li><p>I would say maybe the following styles would be just a bit more readable, easier to follow.</p>\n</li>\n<li><p>We can also alter <code>l1</code> and <code>l2</code> with more descriptive variable names.</p>\n</li>\n</ul>\n<h3>Line Counting Fallacy:</h3>\n<ul>\n<li>Sometimes, Line/character countings are helpful for command line languages/scripts (<code>awk</code>, <code>grep</code>, <code>sed</code>, <code>regex</code>, etc.) or maybe <a href=\"https://en.wikipedia.org/wiki/Code_golf\" rel=\"nofollow noreferrer\">Code Golfing</a>, is not a JavaScript practice though.</li>\n</ul>\n<h3>Iterative using a <a href=\"https://en.wikipedia.org/wiki/Sentinel_node\" rel=\"nofollow noreferrer\">Sentinel Node</a></h3>\n<pre><code>const mergeTwoLists = function(l1, l2) {\n const sentinel = {\n val: -1,\n next: null\n }\n\n let head = sentinel\n while (l1 && l2) {\n if (l1.val > l2.val) {\n head.next = l2\n l2 = l2.next\n } else {\n head.next = l1\n l1 = l1.next\n }\n \n head = head.next\n }\n\n head.next = l1 || l2\n\n return sentinel.next\n}\n\n</code></pre>\n<hr />\n<h3>Recursive</h3>\n<pre><code>const mergeTwoLists = function(l1, l2) {\n if (l1 === null) {\n return l2\n }\n\n if (l2 === null) {\n return l1\n }\n\n if (l1.val < l2.val) {\n l1.next = mergeTwoLists(l1.next, l2)\n return l1\n\n } else {\n l2.next = mergeTwoLists(l1, l2.next)\n return l2\n }\n}\n</code></pre>\n<h3>Or even better that those:</h3>\n<pre><code>const mergeTwoLists = function(l1, l2) {\n if (l1 === null) {\n return l2;\n }\n\n if (l2 === null) {\n return l1;\n }\n\n if (l1.val < l2.val) {\n l1.next = mergeTwoLists(l1.next, l2)\n return l1;\n\n } else {\n l2.next = mergeTwoLists(l1, l2.next)\n return l2;\n }\n}\n\n</code></pre>\n<hr />\n<pre><code>\nconst mergeTwoLists = function(l1, l2) {\n const sentinel = {\n val: -1,\n next: null\n };\n\n let head = sentinel;\n while (l1 && l2) {\n if (l1.val > l2.val) {\n head.next = l2;\n l2 = l2.next;\n } else {\n head.next = l1;\n l1 = l1.next;\n }\n \n head = head.next;\n }\n\n head.next = l1 || l2;\n\n return sentinel.next;\n} \n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-29T18:55:45.960",
"Id": "520411",
"Score": "0",
"body": "this doesn't work at all! What if one of the list items gets empty ? and other still have items left?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-13T09:35:08.557",
"Id": "521355",
"Score": "0",
"body": "@programoholic What do you mean? They handle that case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-13T13:26:59.707",
"Id": "533051",
"Score": "0",
"body": "(I guess I don't \"get\" the 17:04 edit from [revision 3](https://codereview.stackexchange.com/revisions/250592/3) to [revision 4](https://codereview.stackexchange.com/revisions/250592/4).)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-13T16:37:46.263",
"Id": "250592",
"ParentId": "221845",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T09:22:50.743",
"Id": "221845",
"Score": "5",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"comparative-review",
"ecmascript-6"
],
"Title": "Merge Two Sorted Lists in JavaScript"
} | 221845 |
<p>I'm posting a follow-up question based on my <a href="https://codereview.stackexchange.com/questions/221391/sql-e-commerce-database-design">first question</a>. My goal is to, as an exercise for myself, create a complex (in my opinion) e-commerce application. The explanation of the application can be found in my first question.</p>
<p>This concerns the parties of my application. It can have Users & Companies. Companies always have an owner (user) and they can have Employees who act on behalf of the company. Companies can buy products from other companies, users can buy products from companies. To negotiate the internal messaging system will be used.</p>
<ol>
<li><p>How can I make sure I know which of the company contacts (employees) was in contact (messaging) with the buyer (who also can be an employee of another company)? Maybe this should also include orders as I would also like to know which employee made the purchase or which employee sold the product.</p></li>
<li><p>How do I make sure an employee is linked to 1 company? And that employee cannot act in the role of user.</p></li>
</ol>
<p>This is my db schema: (updated with missing relationship between user and company)</p>
<p><a href="https://i.stack.imgur.com/4cuh4.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4cuh4.jpg" alt="DB Schema"></a></p>
<p>As requested I've only put a subset of code to be reviewed. This is the part with Parties (Users and Companies) and Messages.</p>
<p>This is the SQL code:</p>
<pre><code>-- ************************************** [dbo].[PartyType]
CREATE TABLE [dbo].[PartyType]
(
[PartyTypeCode] nvarchar(5) NOT NULL ,
[Description] nvarchar(50) NOT NULL ,
[Name] nvarchar(50) NOT NULL ,
CONSTRAINT [PK_PartyType] PRIMARY KEY CLUSTERED ([PartyTypeCode] ASC)
);
GO
-- ************************************** [dbo].[Party]
CREATE TABLE [dbo].[Party]
(
[PartyId] uniqueidentifier NOT NULL ,
[PartyTypeCode] nvarchar(5) NOT NULL ,
CONSTRAINT [PK_Party] PRIMARY KEY CLUSTERED ([PartyId] ASC),
CONSTRAINT [PartyToPartyType_FK] FOREIGN KEY ([PartyTypeCode]) REFERENCES [dbo].[PartyType]([PartyTypeCode])
);
GO
-- ************************************** [dbo].[User]
CREATE TABLE [dbo].[User]
(
[UserId] uniqueidentifier NOT NULL ,
CONSTRAINT [PK_User] PRIMARY KEY NONCLUSTERED ([UserId] ASC),
CONSTRAINT [FK_18] FOREIGN KEY ([UserId]) REFERENCES [dbo].[Party]([PartyId])
);
GO
-- ************************************** [dbo].[Company]
CREATE TABLE [dbo].[Company]
(
[CompanyId] uniqueidentifier NOT NULL ,
[OwnerId] uniqueidentifier NOT NULL ,
CONSTRAINT [PK_Company] PRIMARY KEY CLUSTERED ([CompanyId] ASC),
CONSTRAINT [FK_21] FOREIGN KEY ([CompanyId]) REFERENCES [dbo].[Party]([PartyId]),
CONSTRAINT [FK_243] FOREIGN KEY ([OwnerId]) REFERENCES [dbo].[User]([UserId])
);
GO
-- ************************************** [dbo].[Contact]
CREATE TABLE [dbo].[Contact]
(
[ContactId] uniqueidentifier NOT NULL ,
[CompanyId] uniqueidentifier NOT NULL ,
CONSTRAINT [PK_Contact] PRIMARY KEY CLUSTERED ([ContactId] ASC),
CONSTRAINT [FK_229] FOREIGN KEY ([CompanyId]) REFERENCES [dbo].[Company]([CompanyId])
);
GO
-- ************************************** [dbo].[Thread]
CREATE TABLE [dbo].[Thread]
(
[ThreadId] uniqueidentifier NOT NULL ,
CONSTRAINT [PK_Thread] PRIMARY KEY CLUSTERED ([ThreadId] ASC)
);
GO
-- ************************************** [dbo].[ThreadParticipator]
CREATE TABLE [dbo].[ThreadParticipator]
(
[ThreadId] uniqueidentifier NOT NULL ,
[PartyId] uniqueidentifier NOT NULL ,
CONSTRAINT [PK_ThreadParticipator] PRIMARY KEY CLUSTERED ([PartyId] ASC, [ThreadId] ASC),
CONSTRAINT [FK_100] FOREIGN KEY ([PartyId]) REFERENCES [dbo].[Party]([PartyId]),
CONSTRAINT [FK_97] FOREIGN KEY ([ThreadId]) REFERENCES [dbo].[Thread]([ThreadId])
);
GO
-- ************************************** [dbo].[Message]
CREATE TABLE [dbo].[Message]
(
[MessageId] uniqueidentifier NOT NULL ,
[ThreadId] uniqueidentifier NOT NULL ,
[AuthorId] uniqueidentifier NOT NULL ,
CONSTRAINT [PK_Message] PRIMARY KEY CLUSTERED ([MessageId] ASC),
CONSTRAINT [FK_211] FOREIGN KEY ([ThreadId]) REFERENCES [dbo].[Thread]([ThreadId]),
CONSTRAINT [FK_214] FOREIGN KEY ([AuthorId]) REFERENCES [dbo].[Party]([PartyId])
);
GO
-- ************************************** [dbo].[MessageReadState]
CREATE TABLE [dbo].[MessageReadState]
(
[MessageId] uniqueidentifier NOT NULL ,
[PartyId] uniqueidentifier NOT NULL ,
CONSTRAINT [PK_MessageReadState] PRIMARY KEY CLUSTERED ([MessageId] ASC, [PartyId] ASC),
CONSTRAINT [FK_88] FOREIGN KEY ([MessageId]) REFERENCES [dbo].[Message]([MessageId]),
CONSTRAINT [FK_91] FOREIGN KEY ([PartyId]) REFERENCES [dbo].[Party]([PartyId])
);
GO
-- ************************************** [dbo].[Address]
CREATE TABLE [dbo].[Address]
(
[AddressId] uniqueidentifier NOT NULL ,
CONSTRAINT [PK_Address] PRIMARY KEY CLUSTERED ([AddressId] ASC)
);
GO
-- ************************************** [dbo].[PartyAddress]
CREATE TABLE [dbo].[PartyAddress]
(
[PartyId] uniqueidentifier NOT NULL ,
[AddressId] uniqueidentifier NOT NULL ,
CONSTRAINT [PK_PartyAddress] PRIMARY KEY CLUSTERED ([AddressId] ASC, [PartyId] ASC),
CONSTRAINT [FK_55] FOREIGN KEY ([PartyId]) REFERENCES [dbo].[Party]([PartyId]),
CONSTRAINT [FK_58] FOREIGN KEY ([AddressId]) REFERENCES [dbo].[Address]([AddressId])
);
GO
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T14:10:12.300",
"Id": "429217",
"Score": "1",
"body": "Can you add some more detail about your entities? What defines a party, party type and contact?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T08:17:09.607",
"Id": "429329",
"Score": "0",
"body": "@Wes, trying to answer this question got me thinking that I might not need the party and contact entities. If I were to replace Party with User And have the relationship that a company can have 1 to many users and that a user belongs to 0 or 1 company and maintain the partytype entity to know what type of user it is, then it would be more logical and more realistic I think.\nA User would always be needed then to perform some sort of interaction and based on the FK it can be determined if the user is linked to a company or not."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T10:48:17.943",
"Id": "221851",
"Score": "0",
"Tags": [
"sql",
"sql-server",
"database",
"t-sql"
],
"Title": "Parties and Messages in SQL e-Commerce db design"
} | 221851 |
<p>QUESTION: Choose the name of clients,
concluded more than one loan agreement in 2010,
as the numbers and dates of issue of these contracts.
Sort by name of the client and date of issue of the loan.</p>
<p>My question: Is it the correct way of solving this task?
Sqlfiddle: <a href="http://www.sqlfiddle.com/#!18/c140c/1" rel="nofollow noreferrer">http://www.sqlfiddle.com/#!18/c140c/1</a></p>
<p>DDL:</p>
<pre><code>create table client(
cl_id int primary key identity (1,1),
cl_full_name nvarchar(100) not null,
);
create table deal(
dl_id int primary key identity (1,1),
dl_client_id int not null,
dl_code nvarchar(100) not null,
dl_valutation_date datetime not null,
foreign key(dl_client_id) references client(cl_id)
);
</code></pre>
<p>QUERY: </p>
<pre><code>SELECT c.cl_full_name AS "ФИО Клиента",
d2.dl_code AS "Номер договора",
Cast(d2.dl_valutation_date AS DATE) AS "Дата выдачи"
FROM (
SELECT d.dl_client_id
FROM deal AS d
WHERE Year(d.dl_valutation_date) = 2010
GROUP BY d.dl_client_id
HAVING Count(*) > 1
) AS t1
INNER JOIN deal AS d2
ON d2.dl_client_id = t1.dl_client_id
INNER JOIN client AS c
ON c.cl_id = d2.dl_client_id
ORDER BY c.cl_full_name,
d2.dl_valutation_date
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T11:32:05.900",
"Id": "429197",
"Score": "2",
"body": "\"Is it the correct way of solving this task?\" Did you test it? Does it work the way you expect it to? How did you test it? Your query has hardcoded values."
}
] | [
{
"body": "<p>I believe your code will work based on what you provided. However, I would recommend a couple of changes.</p>\n\n<ul>\n<li>T1 does not need to be part of the result set as you do not retrieve anything from it. Since it is only used to filter, I've moved it to an exists clause.</li>\n<li><p>Avoid expressions on the data field when comparing to a static or known value. It takes a bit more typing, but can provide performance benefits in your code.</p>\n\n<pre><code>SELECT c.cl_full_name AS \"ФИО Клиента\",\n d2.dl_code AS \"Номер договора\",\n CAST(d2.dl_valutation_date AS DATE) AS \"Дата выдачи\"\nFROM deal AS d2\n INNER JOIN client AS c ON c.cl_id = d2.dl_client_id\nWHERE EXISTS ( SELECT 1\n FROM deal AS d\n WHERE d.dl_valutation_date >= '20100101'\n AND d.dl_valutation_date < '20110101'\n AND c.cl_id = d.dl_client_id\n GROUP BY d.dl_client_id\n HAVING COUNT(*) > 1)\nORDER BY c.cl_full_name,\n d2.dl_valutation_date ;\n</code></pre></li>\n</ul>\n\n<hr>\n\n<p>UPDATE to respond to comment</p>\n\n<hr>\n\n<p>Leveraging good performance practices builds a foundation that makes good performance possible. If there is another part of your query that has a greater impact to performance, the first recommendation may or may not affect performance by itself. However, it can help to reveal other performance bottlenecks.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-07T15:39:33.770",
"Id": "433654",
"Score": "1",
"body": "Your first suggestion, do you think it would also increase performance?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-08T16:11:46.947",
"Id": "433834",
"Score": "1",
"body": "I've responded as part of my answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T14:41:37.987",
"Id": "221860",
"ParentId": "221852",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T11:14:15.617",
"Id": "221852",
"Score": "1",
"Tags": [
"sql",
"interview-questions",
"sql-server",
"t-sql"
],
"Title": "T-SQL query Choose name of clients, concluded more than one loan agreement in 2010"
} | 221852 |
<p>Here's an implementation of a multi-producer single consumer queue that I wanted to use with tasks such as logging from multiple points in a program to a single sink. The implementation is inspired from <a href="https://github.com/dbittman/waitfree-mpsc-queue" rel="nofollow noreferrer">https://github.com/dbittman/waitfree-mpsc-queue</a> but modified mostly to use C++17 features. Comments? Specifically:</p>
<ul>
<li>Are there race conditions that I am missing?</li>
<li>Is this the best I could do if I wanted to avoid copying data as they are pushed and popped? </li>
<li>Could it be done in a way that is simpler, cleaner, more maintainable?</li>
</ul>
<p>Some design choices that I made:</p>
<ul>
<li><p>API is essentially tryPush() and tryPop(). They are non-blocking - easy to make blocking versions by wrapping them around in a <code>while()</code> statement in user code. </p></li>
<li><p>Fixed capacity buffer to avoid memory allocation and associated complexities of maintaining a dynamically growing buffer. I want to be able to use this at least in soft real-time applications.</p></li>
</ul>
<p>The header-only class implementation of the queue <code>mpscq.h</code>:</p>
<pre><code>#ifndef MPSCQ_H
#define MPSCQ_H
#include <atomic>
#include <cassert>
#include <cinttypes>
#include <cstddef>
#include <optional>
#include <vector>
/// multi-producer, single consumer queue.
/// Inspired from https://github.com/dbittman/waitfree-mpsc-queue
template <typename T, size_t capacity_>
class mpscq
{
public:
mpscq();
bool tryPush(T &&obj);
std::optional<T> tryPop();
size_t count() const;
private:
std::atomic<size_t> count_{0};
std::atomic<size_t> head_{0};
size_t tail_{0};
std::vector<std::atomic<bool>> is_readable_;
std::vector<T> buffer_;
};
template <typename T, size_t capacity_>
mpscq<T, capacity_>::mpscq() : is_readable_(capacity_), buffer_(capacity_)
{
assert(capacity_ >= 1);
for (auto &i : is_readable_) {
i = false;
}
}
/// Attempt to enqueue without blocking. This is safe to call from multiple threads.
/// \return true on success and false if queue is full.
template <typename T, size_t capacity_>
bool mpscq<T, capacity_>::tryPush(T &&obj)
{
auto count = count_.fetch_add(1, std::memory_order_acquire);
if (count >= capacity_) {
// back off, queue is full
count_.fetch_sub(1, std::memory_order_release);
return false;
}
// increment the head, which gives us 'exclusive' access to that element until
// is_reabable_ flag is set
const auto head = head_.fetch_add(1, std::memory_order_acquire) % capacity_;
buffer_[head] = std::move(obj);
assert(is_readable_[head] == false);
is_readable_[head].store(true, std::memory_order_release);
return true;
}
/// Attempt to dequeue without blocking
/// \note: This is not safe to call from multiple threads.
/// \return A valid item from queue if the operation won't block, else nothing
template <typename T, size_t capacity_>
std::optional<T> mpscq<T, capacity_>::tryPop()
{
if (!is_readable_[tail_].load(std::memory_order_acquire)) {
// A thread could still be writing to this location
return {};
}
assert(is_readable_[tail_]);
auto ret = std::move(buffer_[tail_]);
is_readable_[tail_].store(false, std::memory_order_release);
if (++tail_ >= capacity_) {
tail_ = 0;
}
const auto count = count_.fetch_sub(1, std::memory_order_release);
assert(count > 0);
return ret;
}
/// \return The number of items in queue
template <typename T, size_t capacity_>
size_t mpscq<T, capacity_>::count() const
{
return count_.load(std::memory_order_relaxed);
}
#endif // MPSCQ_H
</code></pre>
<p>The example program to test it <code>mpscq_example.cpp</code>:</p>
<pre><code>#include "mpscq.h"
#include <chrono>
#include <csignal>
#include <cstring>
#include <iostream>
#include <thread>
struct HeavyObject
{
HeavyObject(uint32_t val = 0) { value[0] = val; }
uint32_t value[128];
};
constexpr size_t Q_LEN = 1000;
static mpscq<HeavyObject, Q_LEN> s_queue;
static std::atomic_bool s_exit = false;
static std::atomic_uint s_value = 0;
void onSignal(int signum)
{
std::cout << "Received signal " << strsignal(signum) << std::endl;
s_exit = true;
}
void producer()
{
while (!s_exit) {
HeavyObject obj(s_value.load());
auto pushed = s_queue.tryPush(std::move(obj));
std::this_thread::sleep_for(std::chrono::microseconds(1));
std::this_thread::yield();
if (pushed) {
std::cout << std::hex << std::this_thread::get_id() << " produced - value: " << s_value << "\n";
++s_value;
}
}
}
void consumer()
{
while (!s_exit) {
std::this_thread::yield();
std::this_thread::sleep_for(std::chrono::microseconds(1));
if (s_queue.count() > 0) {
auto t = s_queue.tryPop();
if (t.has_value()) {
auto val_now = t.value().value[0];
std::cout << "consumer - value: " << val_now << "\n";
}
}
}
}
int main()
{
signal(SIGINT, onSignal);
signal(SIGTERM, onSignal);
std::thread t1(producer);
std::thread t2(producer);
consumer();
t1.join();
t2.join();
return 0;
}
</code></pre>
<p>And the CMakeLists.txt file to build it</p>
<pre><code>cmake_minimum_required(VERSION 3.10)
project(mpscq LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17) # Turn on C++17 compile flags
set(CMAKE_CXX_STANDARD_REQUIRED ON) # Yes we really need it
set(CMAKE_CXX_EXTENSIONS OFF) # Turn off non-standard extensions to ISO C++
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
add_executable(mpscq_example mpscq_example.cpp mpscq.h)
target_link_libraries(mpscq_example Threads::Threads)
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-18T20:03:16.923",
"Id": "508359",
"Score": "0",
"body": "Are you still interested in a review / constructive communication? I need something like this myself, so perhaps we can make something up. So far I just read through the code once and it seems OK to me. I dislike a few things, but I don't see a bug."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T11:46:40.133",
"Id": "221854",
"Score": "7",
"Tags": [
"c++",
"queue",
"c++17",
"lock-free"
],
"Title": "Yet another multi-producer single consumer queue in C++17"
} | 221854 |
<p>I have written a program that takes a number <code>n</code> and prints Pascal's triangle having <code>n</code> number of rows. </p>
<p>Here is my code -</p>
<pre><code>n = int(input("Enter number of rows: "))
a = []
for i in range(n):
a.append([])
a[i].append(1)
for j in range(1, i):
a[i].append(a[i - 1][j - 1] + a[i - 1][j])
if (n != 0):
a[i].append(1)
for i in range(n):
print(" " * (n - i), end = " ", sep = " ")
for j in range(0, i + 1):
print('{0:5}'.format(a[i][j]), end = " ", sep = " ")
print()
</code></pre>
<p>Here are some example outputs -</p>
<pre><code>Enter number of rows: 3
1
1 1
1 2 1
</code></pre>
<hr>
<pre><code>Enter number of rows: 6
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
</code></pre>
<hr>
<pre><code>Enter number of rows: 10
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
</code></pre>
<p>Therefore, I would like to know whether I could make this program shorter and more efficient.</p>
<p>Any help would be highly appreciated.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T14:55:36.093",
"Id": "429221",
"Score": "1",
"body": "You say \"more efficient\" but it doesn't look like you care with all those prints."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T14:10:21.687",
"Id": "429366",
"Score": "1",
"body": "As a general rule in Python, you want to avoid calling `append` as much as possible. It's usually easy to do so."
}
] | [
{
"body": "<p><strong>Functions & code organisation</strong></p>\n\n<p>At the moment, your code is basically split into 3 parts:</p>\n\n<ul>\n<li>getting the input from the user</li>\n<li>generating a triangle</li>\n<li>printing a triangle</li>\n</ul>\n\n<p>Things would be easier to understand/test/reuse if we could split them into 3 logical parts. Functions could be a good way to do things here.</p>\n\n<p>Also, it could be a good occasion to use the <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> trick</a> to split function definitions from the code using it and performing Input/Output.</p>\n\n<pre><code>def generate_pascal(n):\n ...\n return a\n\ndef print_pascal(a):\n ...\n\nif __name__ == \"__main__\":\n n = int(input(\"Enter number of rows: \"))\n p = generate_pascal(n)\n print_pascal(p)\n</code></pre>\n\n<hr>\n\n<p><strong>Simplifying <code>print_pascal</code></strong></p>\n\n<p>You can define <code>end</code> and <code>sep</code> as parameters to <code>print_pascal</code>.</p>\n\n<p><strong>Loop like a native</strong>: I highly recommend <a href=\"https://nedbatchelder.com/text/iter.html\" rel=\"nofollow noreferrer\">Ned Batchelder's excellent talk called \"Loop like a native\"</a>. You usually do not need to write loops based on the length of the list you are working on, you can just iterate over it.</p>\n\n<p>In our case, this leads to the following code:</p>\n\n<pre><code>def print_pascal(a, end = \" \", sep = \" \"):\n n = len(a)\n for i, line in enumerate(a):\n print(\" \" * (n - i), end = end, sep = sep)\n for e in line:\n print('{0:5}'.format(e), end = sep, sep = sep)\n print()\n</code></pre>\n\n<p>Note: This hilight an issue with the structure provided to the printing procedure as the first line contains 2 numbers.</p>\n\n<hr>\n\n<p><strong>Simplifying <code>generate_pascal</code></strong></p>\n\n<p>In <code>generate_pascal</code>, you add a list to a there refer to that list using <code>a[i]</code>.</p>\n\n<p>It would be clearer and more efficient to just define a new list that you fill and then eventually add to a.</p>\n\n<p>We get:</p>\n\n<pre><code>def generate_pascal(n):\n a = []\n for i in range(n):\n line = []\n line.append(1)\n for j in range(1, i):\n line.append(a[i - 1][j - 1] + a[i - 1][j])\n if (n != 0):\n line.append(1)\n a.append(line)\n return a\n</code></pre>\n\n<p><strong>Fixing a bug in <code>generate_pascal</code></strong></p>\n\n<p>The issue hilighted previously can probably be fixed by replacing <code>if (n != 0)</code> with <code>if (i != 0)</code> which is more usually written without the superfluous parenthesis: <code>if i != 0</code> or even <code>if i</code>.</p>\n\n<p>More generally, this <code>if</code> could be applied to most of the logic in the loop:</p>\n\n<pre><code>def generate_pascal(n):\n a = []\n for i in range(n):\n line = []\n line.append(1)\n if i:\n for j in range(1, i):\n line.append(a[i - 1][j - 1] + a[i - 1][j])\n line.append(1)\n a.append(line)\n return a\n</code></pre>\n\n<p>Now, we can take this chance to access <code>a[i - 1]</code> via a variable with a proper name for instance <code>prev_line</code>. Also, The conventional way to access the latest element from an array is to use the <code>-1</code> index. We could write:</p>\n\n<pre><code> prev_line = a[-1]\n for j in range(1, i):\n line.append(prev_line[j - 1] + prev_line[j])\n</code></pre>\n\n<hr>\n\n<p>This this stage, the full code looks like:</p>\n\n<pre><code>def generate_pascal(n):\n p = []\n for i in range(n):\n line = [1]\n if i:\n prev_line = p[-1]\n for j in range(1, i):\n line.append(prev_line[j - 1] + prev_line[j])\n line.append(1)\n p.append(line)\n return p\n\ndef print_pascal(p, end = \" \", sep = \" \"):\n n = len(p)\n for i, line in enumerate(p):\n print(\" \" * (n - i), end = end, sep = sep)\n for e in line:\n print('{0:5}'.format(e), end = sep, sep = sep)\n print()\n\nif __name__ == \"__main__\":\n n = int(input(\"Enter number of rows: \"))\n p = generate_pascal(n)\n print_pascal(p)\n\n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T15:41:26.403",
"Id": "429233",
"Score": "0",
"body": "Do we review code organization and simplification if [tag:performance] is the goal?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T15:50:40.773",
"Id": "429239",
"Score": "1",
"body": "@ThomasWeller you can review whatever you like in the question no matter what the tags are."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T16:24:57.803",
"Id": "429243",
"Score": "0",
"body": "@ThomasWeller I've edited my answer to add details that may have a positive performance impact."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-16T03:06:49.090",
"Id": "430348",
"Score": "0",
"body": "@Josay - *To be continued* - Is there still more?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-16T06:53:01.500",
"Id": "430352",
"Score": "0",
"body": "@Justin nothing more than what the others have said. I've edited my answer accordingly"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T14:46:14.310",
"Id": "221862",
"ParentId": "221858",
"Score": "5"
}
},
{
"body": "<p>One issue with your approach is your memory usage is <span class=\"math-container\">\\$O(n^2)\\$</span>. You are building up the entire Pascal's Triangle, and subsequently printing it. If you simply want to print Pascal's Triangle, you don't need to keep the entire triangle in memory. You can simply generate and print it row by row. Since you generate the next row from only the previous row, the memory requirement is simply two rows, which is <span class=\"math-container\">\\$O(n)\\$</span>.</p>\n\n<pre><code>>>> row = [1]\n>>> for _ in range(5):\n... row = [1] + [x + y for x, y in zip(row[:-1], row[1:])] + [1]\n... print(row)\n... \n[1, 1]\n[1, 2, 1]\n[1, 3, 3, 1]\n[1, 4, 6, 4, 1]\n[1, 5, 10, 10, 5, 1]\n>>> \n</code></pre>\n\n<p>Demystifying <code>[1] + [x + y for x, y in zip(row[:-1], row[1:])] + [1]</code>:</p>\n\n<p><code>row[:-1]</code> is all the values in <code>row</code>, except the last one. For example, if <code>row</code> is <code>[1, 3, 3, 1]</code>, then <code>row[:-1]</code> is <code>[1, 3, 3]</code>. Similarly, <code>row[1:]</code> is all the values of <code>row</code> except the first, so <code>[3, 3, 1]</code>. <code>zip()</code> takes the first value of each of the lists, and returns those as the tuple <code>(1, 3)</code>, which get assigned to <code>x</code> and <code>y</code> respectively, which get added together to get <code>4</code>. Then, <code>zip()</code> emits the next pair of values, <code>(3, 3)</code> which results in <code>6</code>, and then the final pair <code>(3, 1)</code> results in <code>4</code>, producing the list <code>[4, 6, 4]</code>. The <code>[1] + ... + [1]</code> adds the bookends, which results in the next row of the triangle: <code>[1, 4, 6, 4, 1]</code>.</p>\n\n<p>Instead of needing to keep track of the last row, and feed that back to generate the next row, we can package that up into a generator function, which can prime the loop and do the feedback itself:</p>\n\n<pre><code>>>> def pascals_triangle(n):\n... row = [1]\n... yield row\n... for _ in range(n):\n... row = [1] + [x + y for x, y in zip(row[:-1], row[1:])] + [1]\n... yield row\n... \n>>> for row in pascals_triangle(5):\n... print(row)\n... \n[1]\n[1, 1]\n[1, 2, 1]\n[1, 3, 3, 1]\n[1, 4, 6, 4, 1]\n[1, 5, 10, 10, 5, 1]\n>>> \n</code></pre>\n\n<p>Format the resulting rows as desired.</p>\n\n<pre><code>>>> for i, row in enumerate(pascals_triangle(5)):\n... print((\" \"*(5-i) + \"{:6}\"*(i+1)).format(*row))\n... \n 1\n 1 1\n 1 2 1\n 1 3 3 1\n 1 4 6 4 1\n 1 5 10 10 5 1\n>>> \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T03:09:48.120",
"Id": "429311",
"Score": "1",
"body": "If you want to get really picky about performance, your one-liner print probably has to be rethought a little. Maybe use writes to `sys.stdout` to avoid the implicit buffer flush with `print`; don't do string concatenation; maybe other micro-optimizations associated with the format string."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T03:12:05.090",
"Id": "429313",
"Score": "1",
"body": "@Reinderien The performance was the generation of the triangle rows. My print is horrendously inefficient 2-line statement I used for demonstration purposes; I said “as desired” ... mine was just a (bad/cool) example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T03:19:09.283",
"Id": "429314",
"Score": "0",
"body": "It's a fair point. Also, if you want to get technical, you've generated one too many rows given `n=5`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T03:19:46.660",
"Id": "429315",
"Score": "0",
"body": "@Reinderien Yup! I can’t from zero."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T03:41:20.780",
"Id": "429320",
"Score": "0",
"body": "Uhh. Five things counting from zero is still five things, not six things."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T03:50:34.707",
"Id": "429321",
"Score": "0",
"body": "Also you should be using `n-i`, not `5-i` - otherwise your rendering code fails for values of `n` greater than 5."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T18:05:53.077",
"Id": "221873",
"ParentId": "221858",
"Score": "10"
}
},
{
"body": "<p>There's an even better way to generate the Pascal's triangle that only requires O(1) memory. It can even calculate a certain row directly without requiring previous rows to be computed.</p>\n\n<p>It works like this:</p>\n\n<ul>\n<li>the first number in each row is always 1.</li>\n<li>consider the fraction (n / 1) where n in the row index (1-based)</li>\n<li>the 2nd number is obtained by multiplying the first number by this fraction</li>\n<li>decrement the numerator of the fraction by 1 and increment the denominator by 1</li>\n<li>obtain the 3rd number by multiplying the fraction with the 2nd number</li>\n<li>and so on, for (n + 1) numbers</li>\n</ul>\n\n<p>Worked Example:</p>\n\n<p>suppose n = 4</p>\n\n<ul>\n<li>1st number = 1</li>\n<li>2nd number = 1 * (4 / 1) = 4</li>\n<li>3rd number = 4 * (3 / 2) = 6</li>\n<li>4th number = 6 * (2 / 3) = 4</li>\n<li>5th number = 4 * (1 / 4) = 1</li>\n</ul>\n\n<p>which is exactly the 4th row of triangle</p>\n\n<p>Code:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def print_row(n):\n numerator, denominator = n, 1\n cur = 1\n for _ in range(n + 1):\n print(cur, end='\\t')\n cur = (cur * numerator) // denominator\n numerator -= 1\n denominator += 1\n print()\n\nfor row in range(5):\n print_row(row)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T13:24:57.607",
"Id": "429355",
"Score": "0",
"body": "While this might be a great SO answer for Code Review it would be better if you made some observations about the posters code as well."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T12:20:40.710",
"Id": "221924",
"ParentId": "221858",
"Score": "4"
}
},
{
"body": "<p>The following is a profiling run of all of the methods I've seen above, with some improvements to the I/O.</p>\n\n<pre><code>from io import StringIO\nfrom timeit import timeit\nfrom sys import stdout, stderr\nimport numpy as np\n\n\ndef justin(n):\n a = []\n\n for i in range(n):\n a.append([])\n a[i].append(1)\n\n for j in range(1, i):\n a[i].append(a[i - 1][j - 1] + a[i - 1][j])\n if n != 0:\n a[i].append(1)\n\n for i in range(n):\n print(\" \" * (n - i), end=\" \", sep=\" \")\n\n for j in range(0, i + 1):\n print('{0:5}'.format(a[i][j]), end=\" \", sep=\" \")\n print()\n\n\ndef josay(n):\n def generate_pascal():\n p = []\n for i in range(n):\n line = [1]\n if i:\n prev_line = p[-1]\n for j in range(1, i):\n line.append(prev_line[j - 1] + prev_line[j])\n line.append(1)\n p.append(line)\n return p\n\n def print_pascal(p, end=\" \", sep=\" \"):\n for i, line in enumerate(p):\n print(\" \" * (n - i), end=end, sep=sep)\n for e in line:\n print('{0:5}'.format(e), end=sep, sep=sep)\n print()\n\n print_pascal(generate_pascal())\n\n\ndef neufeld_pascals_triangle(n):\n row = [1]\n yield row\n for _ in range(n - 1):\n row = [1] + [x + y for x, y in zip(row[:-1], row[1:])] + [1]\n yield row\n\n\ndef neufeld(n):\n for i, r in enumerate(neufeld_pascals_triangle(n)):\n print((\" \"*(n-i) + \"{:6}\"*(i+1)).format(*r))\n\n\ndef neufeld_stdout(n):\n for i, r in enumerate(neufeld_pascals_triangle(n)):\n stdout.write((' '*(n-i-1) + '{:<6}'*(i+1) + '\\n').format(*r))\n\n\ndef neufeld_noenum(n):\n for r in neufeld_pascals_triangle(n):\n i = len(r)\n stdout.write((' '*(n-i) + '{:<6}'*i + '\\n').format(*r))\n\n\ndef neufeld_fmt(n):\n fmt = ' '*n\n for r in neufeld_pascals_triangle(n):\n fmt = fmt[3:] + '{:<6}'\n stdout.write((fmt + '\\n').format(*r))\n\n\ndef neufeld_onewrite(n):\n fmt = ' '*n\n msg = ''\n for r in neufeld_pascals_triangle(n):\n fmt = fmt[3:] + '{:<6}'\n msg += fmt.format(*r) + '\\n'\n stdout.write(msg)\n\n\ndef neufeld_strio(n):\n fmt = ' '*n\n msg = StringIO()\n for r in neufeld_pascals_triangle(n):\n fmt = fmt[3:] + '{:<6}'\n msg.write(fmt.format(*r) + '\\n')\n stdout.write(msg.getvalue())\n\n\ndef tri_rishav(n):\n for y in range(n):\n numerator, denominator = y, 1\n cur = 1\n row = [None] * (y + 1)\n for x in range(y + 1):\n row[x] = cur\n cur = (cur * numerator) // denominator\n numerator -= 1\n denominator += 1\n yield row\ndef rishav_strio(n):\n fmt = ' '*n\n msg = StringIO()\n for r in tri_rishav(n):\n fmt = fmt[3:] + '{:<6}'\n msg.write(fmt.format(*r) + '\\n')\n stdout.write(msg.getvalue())\n\n\ndef tri_numpy(n):\n row = []\n for _ in range(n):\n new_row = np.ones(1 + len(row), np.int32)\n new_row[1:-1] = row[1:] + row[:-1]\n row = new_row\n yield row\ndef numpy_strio(n):\n fmt = ' '*n\n msg = StringIO()\n for r in tri_numpy(n):\n fmt = fmt[3:] + '{:<6}'\n msg.write(fmt.format(*r) + '\\n')\n stdout.write(msg.getvalue())\n\n\ndef tri_onearray(n):\n row = np.ones(n, np.int32)\n x = n - 1\n for y in range(n):\n yield row[x: x+y+1]\n row[x: x+y] += row[x+1: x+y+1]\n x -= 1\ndef onearray_strio(n):\n fmt = ' '*n\n msg = StringIO()\n for r in tri_onearray(n):\n fmt = fmt[3:] + '{:<6}'\n msg.write(fmt.format(*r) + '\\n')\n stdout.write(msg.getvalue())\n\n\nmethods = ((n, globals()[n]) for n in (\n 'justin', 'josay', 'neufeld',\n 'neufeld_stdout', 'neufeld_noenum', 'neufeld_fmt', 'neufeld_onewrite',\n 'neufeld_strio', 'rishav_strio',\n 'numpy_strio', 'onearray_strio'))\n\n\ndef profile():\n # IMPORTANT - run redirecting stdout to /dev/null !\n first = None\n for name, method in methods:\n method = globals()[name]\n n = 50\n\n def run():\n method(n)\n reps = 200\n stdout.flush()\n dur = timeit(run, number=reps) / reps\n if first is None:\n first = dur\n rel = 0\n else:\n rel = first/dur - 1\n print(f'n={n} method={name:16} {1e3*dur:5.3f}ms speedup={rel:7.2%}',\n file=stderr, flush=True)\n\n\ndef print_test():\n for name, method in methods:\n method(6)\n print(name)\n\n\nprofile()\n# print_test()\n</code></pre>\n\n<p>This yields the following results:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>n=50 method=justin 7.276ms speedup= 0.00%\nn=50 method=josay 6.956ms speedup= 4.60%\nn=50 method=neufeld 2.110ms speedup=244.85%\nn=50 method=neufeld_stdout 1.947ms speedup=273.78%\nn=50 method=neufeld_noenum 1.951ms speedup=273.02%\nn=50 method=neufeld_fmt 1.925ms speedup=277.90%\nn=50 method=neufeld_onewrite 1.577ms speedup=361.45%\nn=50 method=neufeld_strio 1.555ms speedup=367.87%\nn=50 method=rishav_strio 1.714ms speedup=324.50%\nn=50 method=numpy_strio 2.687ms speedup=170.80%\nn=50 method=onearray_strio 2.529ms speedup=187.66%\n</code></pre>\n\n<p>Of note:</p>\n\n<ul>\n<li>It was quite interesting to me that neither Rishav's computed method nor Numpy vectorization are able to beat Neufeld's simple, array-based method</li>\n<li>Building up the printed output in memory before writing it to stdout is much faster than writing to stdout on each iteration, especially if you avoid <code>print</code></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T19:20:59.610",
"Id": "429397",
"Score": "0",
"body": "You should really compare displaying separately from generating. Also you've made your tests really biased against Josay. wtf is their code in closures, but no-one elses is? Making all the functions return the same output (yes they don't) and build a list in the same way I get [this graph](https://i.stack.imgur.com/46ygr.png)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T17:57:19.630",
"Id": "221947",
"ParentId": "221858",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "221873",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T13:38:00.183",
"Id": "221858",
"Score": "5",
"Tags": [
"python",
"performance",
"python-3.x"
],
"Title": "Printing Pascal’s triangle for n number of rows in Python"
} | 221858 |
<p>This function returns the indices of all white spaces as an array of Integer. It works fine with a small string:</p>
<pre><code>func whiteSpacesIndices(value : String) -> Array<Int> {
var indices: Array<Int> = []
for (index, char) in value.enumerated() {
if char == " " || char == "\n" || char == "\t" {
indices.append(index)
}
}
return indices
}
</code></pre>
<p>However when the string is too long, it could be very slow, because it is looping in every character.</p>
<p>Is there a better way for doing it? </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T23:58:55.437",
"Id": "429306",
"Score": "0",
"body": "How long is the string tested? Could you please give the character count and the number of spaces?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T18:46:50.580",
"Id": "429393",
"Score": "1",
"body": "With a string that has `8447` characters and `1307` spaces, your code takes 0.5ms on my machine"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-21T04:50:20.293",
"Id": "431127",
"Score": "0",
"body": "This returns integral positions of white space, but they're not indices, per say. I.e., they cannot be used to index back into the string"
}
] | [
{
"body": "<h1>General remarks</h1>\n\n<ul>\n<li><code>value</code>, as a parameter name, isn't very descriptive,</li>\n<li><p>The code considers that white spaces can only be <code>\" \"</code> or <code>\"\\n\"</code> or <code>\"\\t\"</code>. This a performance optimization and supposes prior knowledge of the contents of the string. More generally you could make the check this way:</p>\n\n<pre><code>if char.isWhitespace {\n indices.append(index)\n}\n</code></pre></li>\n<li><p><code>Array<Int></code> is not the same as <code>[String.Index]</code> of <a href=\"https://developer.apple.com/documentation/foundation/indexset\" rel=\"nofollow noreferrer\">IndexSet</a>. A <code>String</code> can be traversed using <code>String.Index</code> and not and <code>Int</code>. </p></li>\n</ul>\n\n<h2>Performance</h2>\n\n<p>The following codeis twice as fast in my tests, but doesn’t work with emoji :</p>\n\n<pre><code>func whiteSpacesIndices(in str : String) -> Array<Int> {\n var indices: Array<Int> = []\n let blanks: [UInt32] = [32, 10, 9] //these values correspond to space, new line, and tabulation respectively.\n for (index, scalar) in str.unicodeScalars.enumerated() {\n if blanks.contains(scalar.value) {\n indices.append(index)\n }\n }\n return indices\n}\n</code></pre>\n\n<p>You can learn more about the Unicode scalar representation <a href=\"https://docs.swift.org/swift-book/LanguageGuide/StringsAndCharacters.html#ID304\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<h1>Free function or instance method?</h1>\n\n<p>The <code>whiteSpacesIndices</code> function seems more like a property on strings. It is appropriate for a String to know about the indices of white spaces (and new lines) within itself:</p>\n\n<pre><code>extension String {\n var whiteSpaceIndices: [Int] {\n var indices = [Int]()\n let blanks: [UInt32] = [32, 10, 9]\n for (index, scalar) in self.unicodeScalars.enumerated() {\n if blanks.contains(scalar.value) {\n indices.append(index)\n }\n }\n return indices\n }\n}\n</code></pre>\n\n<p>And could be used like so:</p>\n\n<pre><code>\"Hello world!\".whiteSpaceIndices //[5]\n\"ä ö ü\".whiteSpaceIndices //[1, 3]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T19:49:55.633",
"Id": "429409",
"Score": "0",
"body": "Note that your method returns other results than the original code. For the string `\"ä ö ü\"` the original code returns `[1, 3]` and your code returns `[2, 5]`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T19:54:04.650",
"Id": "429410",
"Score": "0",
"body": "Btw, `char.isWhitespace` returns true for newline characters, the `|| char.isNewline` is not needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T04:37:00.647",
"Id": "429440",
"Score": "0",
"body": "Still different results for `\" ⚖️ x\"`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T04:56:49.520",
"Id": "429442",
"Score": "0",
"body": "@MartinR from my limited knowledge, I think if we’d like to take emoji into consideration, we’ll have to revert to the code in question. Do share any trick if there is any."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T05:08:57.683",
"Id": "429443",
"Score": "1",
"body": "The character/utf8/unicodeScalars *are* different and have different offsets. But it was not my intention to say that your code “does not work.” I just wanted to make you aware of the difference. It may not be relevant for OP (who did not provide more information about the text), but should be mentioned."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-28T02:51:44.757",
"Id": "432191",
"Score": "0",
"body": "This for loop is better expressed as a `filer` expression"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T19:29:40.897",
"Id": "221949",
"ParentId": "221859",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "221949",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T14:05:52.710",
"Id": "221859",
"Score": "2",
"Tags": [
"performance",
"strings",
"swift"
],
"Title": "Find indices of white space characters in a string"
} | 221859 |
<p>My php page displays a slider of images and when the user clicks on an image(.item), the div below (#team_single) changes the content without reloading the page. Content of the div changes also when the user clicks the arrow of the slider (.slick-prev, .slick-next, .slick-arrow).</p>
<p>I'm looking for a way to improve the following code :</p>
<pre><code>function team_push($image, $position, $sousposition, $title, $content) {
$('#team_single .single-img').html($image);
$('#team_single .position').html($position);
$('#team_single .sousposition').html($sousposition);
$('#team_single .title').html($title);
$('#team_single .description').html($content);
}
var image = $('.slick-current').find("img").clone();
var position = $('.slick-current .position').html();
var sousposition = $('.slick-current .sousposition').html();
var title = $('.slick-current .title').html();
var content = $('.slick-current .content').html();
team_push(image, position, sousposition, title, content);
$('#team_slider .item').on('click', function(){
var image = $(this).find("img").clone();
var position = $(this).find('.position').html();
var sousposition = $(this).find('.sousposition').html();
var title = $(this).find('.title').html();
var content = $(this).find('.content').html();
team_push(image, position, sousposition, title, content);
});
$('#team_slider .slick-arrow').on('click', function(){
var image = $('.slick-current').find("img").clone();
var position = $('.slick-current .position').html();
var sousposition = $('.slick-current .sousposition').html();
var title = $('.slick-current .title').html();
var content = $('.slick-current .content').html();
team_push(image, position, sousposition, title, content);
});
$('#team_single .slick-prev').on("click", function(e){
e.preventDefault();
$('#team_slider').slick('slickSetOption', 'slidesToScroll', 1, true);
$('#team_slider').slick('slickPrev');
var image = $('.slick-current').find("img").clone();
var position = $('.slick-current .position').html();
var sousposition = $('.slick-current .sousposition').html();
var title = $('.slick-current .title').html();
var content = $('.slick-current .content').html();
team_push(image, position, sousposition, title, content);
});
$('#team_single .slick-next').on("click", function(e){
e.preventDefault();
$('#team_slider').slick('slickSetOption', 'slidesToScroll', 1, true);
$('#team_slider').slick('slickNext');
var image = $('.slick-current').find("img").clone();
var position = $('.slick-current .position').html();
var sousposition = $('.slick-current .sousposition').html();
var title = $('.slick-current .title').html();
var content = $('.slick-current .content').html();
team_push(image, position, sousposition, title, content);
});
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T15:08:25.373",
"Id": "221863",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"image"
],
"Title": "jQuery code to display images served by PHP, without reloading"
} | 221863 |
<p>I am working on a backend for an application using a microservice framework with Sequelize and it is populating in the following way (it does based on the table field):</p>
<pre><code>{
"resourceId":{
"name":"Serra Eléctrica",
"unitId":{
"id":2,
"name":"Hora"
},
"resourceTypeId":{
"id":8,
"name":"Patrimoniais"
}
},
"quantity":8,
"price":"9.00",
"vat":"0.00"
}
</code></pre>
<p>The frontend developer said that this is bad because the objects are inside <code>fieldId</code> like <code>resourceId.unitId.id</code> instead of <code>resource.unit.id</code>. Is this really bad or is it actually irrelevant?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T15:27:51.657",
"Id": "429229",
"Score": "0",
"body": "It's not really a 'resourceId' is it - It's a 'resource'."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T15:46:03.347",
"Id": "429235",
"Score": "0",
"body": "You're right, @Peilonrayz"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T15:50:35.800",
"Id": "429238",
"Score": "0",
"body": "This is rather opinionated I guess. I can understand your frontend developer though as the content of all those xxxId fields does not only contain an ID but also a name and other other data. I also wonder about [tag:rest] as the payload has nothing to do with REST. It does not contain links nor is a plain `application/json` a good media-type for REST also, as it lacks support for HATEOAS in particular"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T16:21:16.823",
"Id": "429242",
"Score": "0",
"body": "@RomanVottner that payload is just a part of it but it is a RESTful API. Perhaps he is right and I will be changing that, it does not look good itself."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T15:11:06.097",
"Id": "221864",
"Score": "1",
"Tags": [
"json",
"api",
"rest"
],
"Title": "Response structure with populated fields"
} | 221864 |
<p>Want to level up my skills. It hits a php script that starts a long running export that can take few minutes to few hours. The export script outputs a progress file that this form's javascript uses for the progress bar.</p>
<p>How maintainable is this? What can I do to improve?</p>
<pre><code><link rel="stylesheet" href="/css/minified.css">
<form id="exportForm">
<input id="submitBtn" class="btn btn-primary" type="submit" value="Start Export">
</form>
<div class="text-center">
<progress id="progressBar" class="" value="0"></progress>
<i id="spinner" class="hidden icon icon-spinner icon-pulse" aria-hidden="true"></i>
</div>
<script src="/js/minified.js"></script>
<script>
(function($){
let form = $('#exportForm');
let submitBtn = $('#submitBtn');
let progressBar = $('#progressBar');
let spinner = $('#spinner');
let interval;
let exportProgress;
form.on('submit', submitHandler);
function submitHandler(e) {
e.preventDefault();
submitBtn.attr('disabled', true);
progressBar.val(0);
startSpinner();
beginCheckingProgress();
}
function beginCheckingProgress() { interval = setInterval(getProgress, 1000); }
function getProgress() {
$.getJSON('some.json', function(data) {
exportProgress = data;
progressHandler();
});
}
function progressHandler() {
progressBar.val(exportProgress.progress / exportProgress.total);
if(exportProgress.completed) reset();
}
function reset() {
submitBtn.attr('disabled', false);
clearInterval(interval);
stopSpinner();
}
function startSpinner() { spinner.removeClass('hidden'); }
function stopSpinner() { spinner.addClass('hidden'); }
})(jQuery);
</script>
</code></pre>
| [] | [
{
"body": "<ol>\n<li><p>Is there any reason you're using global variables rather than passing function arguments? e.g. </p>\n\n<blockquote>\n<pre><code>exportProgress = data; progressHandler();\n</code></pre>\n</blockquote>\n\n<p>instead of <code>progressHandler(data);</code> ?</p>\n\n<p>It's a much better practice to avoid globals as much as possible.</p></li>\n<li><p>Instead of polling for progress every second, you could subscribe to SSE (Server Side Events), thus getting the latest progress updates and no unneeded traffic.</p>\n\n<p>In JS this amounts to:</p>\n\n<pre><code>window.onload = function (e) {\n var source = new EventSource(\"get_progress\");\n source.onmessage = function(event) {\n try {\n const response = JSON.parse(event.data);\n progressHandler(response)\n if (response.completed) {\n source.close();\n }\n } catch (error) {\n console.log(error);\n }\n }\n}\n\nfunction progressHandler(response) {\n progressBar.val(response.progress / response.total);\n if(response.completed) reset();\n}\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-01T19:37:48.290",
"Id": "227283",
"ParentId": "221866",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T15:39:43.387",
"Id": "221866",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"html5"
],
"Title": "Simple Form Starts Long Running Task and Watches Progress"
} | 221866 |
<p>I am planning to write a reasonably feature rich serial library but wanted to cut my teeth on something fairly basic. This serial library is fairly simple. It is a thin wrapper on the UNIX open, close, read and write functions. It is blocking for simplicity and on error the caller can use the errno procedure to get further error info.</p>
<p>How can this be improved?</p>
<p>serial_port.h:</p>
<pre><code>/* Blocking serial port class for unix platform.
Thin wrapper for blocking open, read, write and close.
Functions return either zero or a +ve integer on success
or -1 on error. Query errno for further details on error.
*/
#ifndef SERIAL_PORT_H_
#define SERIAL_PORT_H_
#include <stdlib.h>
struct serial_port;
typedef struct serial_port serial_port_t;
/* returns port object if portname can be opened at selected baud rate */
serial_port_t* port_open(const char* portname, int baudrate);
/* returns characters written or -1 on error */
int port_write(serial_port_t* port, const char* data, size_t length);
/* returns characters read or -1 on error */
int port_read(serial_port_t* port, char* buffer, int buffer_size);
/* close port and free allocated resources */
int port_close(serial_port_t* port);
#endif // SERIAL_PORT_H_
</code></pre>
<p>serial_port.c:</p>
<pre><code>/* blocking serial port class for unix platform */
#include "serial_port.h"
#include <unistd.h> // posix api
#include <fcntl.h> // file control operations
#include <termios.h> // terminal
struct serial_port {
int fd;
int baudrate;
struct termios restore_tty;
struct termios current_tty;
};
static int set_speed(struct termios tty, int speed) {
speed_t sp;
switch(speed) {
case 1200: sp = B1200; break;
case 1800: sp = B1800; break;
case 2400: sp = B2400; break;
case 4800: sp = B4800; break;
case 9600: sp = B9600; break;
case 19200: sp = B19200; break;
case 38400: sp = B38400; break;
case 57600: sp = B57600; break;
case 115200: sp = B115200; break;
default:
return -1; // unsupported
}
int baudset = cfsetospeed(&tty, sp);
baudset = cfsetispeed(&tty, sp);
return baudset;
}
static int get_term(int fd, struct termios* ptty) {
/* Upon successful completion, 0 shall be returned. Otherwise, -1
shall be returned and errno set to indicate the error. */
return tcgetattr(fd, ptty);
}
/* configure tty */
static int set_terminal(int fd, struct termios* ptty) {
ptty->c_cflag |= (CLOCAL | CREAD); /* ignore modem controls */
ptty->c_cflag &= ~CSIZE;
ptty->c_cflag |= CS8; /* 8-bit characters */
ptty->c_cflag &= ~PARENB; /* no parity bit */
ptty->c_cflag &= ~CSTOPB; /* only need 1 stop bit */
ptty->c_cflag &= ~CRTSCTS; /* no hardware flowcontrol */
/* setup for non-canonical mode */
ptty->c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
ptty->c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
ptty->c_oflag &= ~OPOST;
/* fetch bytes as they become available */
ptty->c_cc[VMIN] = 1;
ptty->c_cc[VTIME] = 1;
if (tcsetattr(fd, TCSANOW, ptty) != 0) {
// Error from tcsetattr- use strerror(errno)
return -1;
}
return 0;
}
serial_port_t* port_open(const char* portname, int baudrate) {
int fd = open(portname, O_RDWR | O_NOCTTY);
if (fd == -1) {
return NULL;
}
serial_port_t* port = malloc(sizeof(serial_port_t));
if (port) {
port->fd = fd;
port->baudrate = baudrate;
// cache prior terminal settings for restore later
if(get_term(port->fd, &port->current_tty) != 0) {
// cache port - should we fai if not possible?
port->restore_tty = port->current_tty;
}
// set port speed
if(set_speed(port->current_tty, port->baudrate) != 0) {
// error setting tty speed - should we fail?
}
// set terminal attribs
if(set_terminal(port->fd, &port->current_tty) < 0) {
// error configuring port - should we fail?
}
}
return port;
}
int port_write(serial_port_t* port, const char* data, size_t length) {
return write(port->fd, data, length);
}
int port_read(serial_port_t* port, char* buffer, int buffer_size) {
return read(port->fd, buffer, buffer_size);
}
int port_close(serial_port_t* port) {
if (tcsetattr(port->fd, TCSANOW, &port->restore_tty) < 0) {
// error restoring attributes
}
int result = close(port->fd);
free(port);
return result;
}
</code></pre>
<p>main.c:</p>
<pre><code>#include <stdio.h>
#include <string.h> // strerror
#include <errno.h> // errno
#include "serial_port.h"
// test serial library with modem
int main() {
const char* portname = "/dev/ttyACM0";
serial_port_t* port = port_open(portname, 9600);
if(port) {
printf("port %s successfully opened\n", portname);
int result = port_write(port, "AT\r\n", 4);
printf("writing AT to port - %d characters written\n", result);
char buffer[100];
result = port_read(port, buffer, 100);
printf("reading port - %d characters read\n", result);
if (result > 0) {
for (int i = 0; i < result; i++) {
printf("%2x ", (unsigned)buffer[i] & 0xFF);
}
}
result = port_close(port);
printf("port_close returned %d\n", result);
} else {
printf("Error opening port: %s\n", strerror(errno));
}
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T17:10:19.497",
"Id": "221870",
"Score": "2",
"Tags": [
"c",
"linux",
"unix",
"serial-port"
],
"Title": "Blocking serial port C library"
} | 221870 |
<p>This is a <a href="https://leetcode.com/problems/perfect-rectangle/" rel="nofollow noreferrer">Leetcode problem</a> -</p>
<blockquote>
<p><em>Given <span class="math-container">\$N\$</span> axis-aligned rectangles where <span class="math-container">\$N\$</span> <span class="math-container">\$>\$</span> <code>0</code>, determine if
they all together form an exact cover of a rectangular region.</em></p>
<p><em>Each rectangle is represented as a bottom-left point and a top-right
point. For example, a unit square is represented as <code>[1, 1, 2, 2]</code>.
(coordinate of the bottom-left point is <code>(1, 1)</code> and the top-right
point is <code>(2, 2)</code>).</em></p>
<p><strong><em>Example 1 -</em></strong></p>
<pre><code>rectangles = [
[1, 1, 3, 3],
[3, 1, 4, 2],
[3, 2, 4, 4],
[1, 3, 2, 4],
[2, 3, 3, 4]
]
# Explanation - Return True. All 5 rectangles together form an exact cover of a rectangular region.
</code></pre>
<p><a href="https://i.stack.imgur.com/8yGdB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8yGdB.png" alt="enter image description here"></a></p>
<p><strong><em>Example 2 -</em></strong></p>
<pre><code>rectangles = [
[1, 1, 2, 3],
[1, 3, 2, 4],
[3, 1, 4, 2],
[3, 2, 4, 4]
]
# Explanation - Return False. Because there is a gap between the two rectangular regions.
</code></pre>
<p><a href="https://i.stack.imgur.com/dBMfU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dBMfU.png" alt="enter image description here"></a></p>
<p><strong><em>Example 3 -</em></strong></p>
<pre><code>rectangles = [
[1, 1, 3, 3],
[3, 1, 4, 2],
[1, 3, 2, 4],
[3, 2, 4, 4]
]
# Explanation - Return False. Because there is a gap in the top center.
</code></pre>
<p><a href="https://i.stack.imgur.com/vFuEN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vFuEN.png" alt="enter image description here"></a></p>
<p><strong><em>Example 4 -</em></strong></p>
<pre><code>rectangles = [
[1, 1, 3, 3],
[3, 1, 4, 2],
[1, 3, 2, 4],
[2, 2, 4, 4]
]
# Explanation - Return False. Because two of the rectangles overlap with each other.
</code></pre>
<p><a href="https://i.stack.imgur.com/4NsTw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4NsTw.png" alt="enter image description here"></a></p>
</blockquote>
<p>Here is my solution to this challenge -</p>
<pre><code>def is_rectangle_cover(rectangles):
if len(rectangles) == 0 or len(rectangles[0]) == 0:
return False
x1 = float("inf")
y1 = float("inf")
x2 = 0
y2 = 0
rect = set()
area = 0
for points in rectangles:
x1 = min(points[0], x1)
y1 = min(points[1], y1)
x2 = max(points[2], x2)
y2 = max(points[3], y2)
area += (points[3] - points[1]) * (points[2] - points[0])
rect.remove((points[0], points[3])) if (points[0], points[3]) in rect else rect.add((points[0], points[3]))
rect.remove((points[0], points[1])) if (points[0], points[1]) in rect else rect.add((points[0], points[1]))
rect.remove((points[2], points[3])) if (points[2], points[3]) in rect else rect.add((points[2], points[3]))
rect.remove((points[2], points[1])) if (points[2], points[1]) in rect else rect.add((points[2], points[1]))
if (x1, y2) not in rect or (x2, y1) not in rect or (x1, y1) not in rect or (x2, y2) not in rect or len(rect) != 4:
return False
return area == (y2 - y1) * (x2 - x1)
</code></pre>
<p>Here are the times taken for each example output -</p>
<p><strong><em>Example 1 -</em></strong></p>
<pre><code># %timeit is_rectangle_cover([[1, 1, 3, 3], [3, 1, 4, 2], [3, 2, 4, 4], [1, 3, 2, 4], [2, 3, 3, 4]])
14.9 µs ± 117 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
</code></pre>
<p><strong><em>Example 2 -</em></strong></p>
<pre><code># %timeit is_rectangle_cover([[1, 1, 2, 3], [1, 3, 2, 4], [3, 1, 4, 2],[3, 2, 4, 4]])
12.5 µs ± 494 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
</code></pre>
<p><strong><em>Example 3 -</em></strong></p>
<pre><code># %timeit is_rectangle_cover([[1, 1, 3, 3], [3, 1, 4, 2], [1, 3, 2, 4], [3, 2, 4, 4]])
12.4 µs ± 195 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
</code></pre>
<p><strong><em>Example 4 -</em></strong></p>
<pre><code># %timeit is_rectangle_cover([[1, 1, 3, 3], [3, 1, 4, 2], [1, 3, 2, 4], [2, 2, 4, 4]])
12 µs ± 159 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
</code></pre>
<p>Here is my Leetcode result for 46 test cases - </p>
<blockquote>
<p><a href="https://i.stack.imgur.com/PT1wc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PT1wc.png" alt="enter image description here"></a></p>
</blockquote>
<p>Therefore, I would like to know whether I could make this program shorter and more efficient.</p>
<p>Any help would be highly appreciated.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T20:16:46.203",
"Id": "429283",
"Score": "1",
"body": "Unrelated, but hope this may help you. You can see the fastest solution codes on leetcode (only works if you have an accepted submission) by going to the problem, clicking submissions, clicking accepted, and then clicking on the furthest bar to the left of the graph"
}
] | [
{
"body": "<h2>Use tuples</h2>\n\n<p>...instead of lists when your data are immutable. There are a few advantages, including marginal performance increases in some scenarios, and catching \"surprises\" where code is attempting to modify your data where it shouldn't.</p>\n\n<h2>Unpack your tuples</h2>\n\n<p>Indexing <code>points</code> is nasty.</p>\n\n<h2>Use more sets</h2>\n\n<p>I <em>think</em> my rewritten code with set operators is equivalent. Peruse <a href=\"https://docs.python.org/3/library/stdtypes.html#set\" rel=\"nofollow noreferrer\">the documentation</a> for info on the symmetric difference <code>^</code> and subset <code><</code> operators.</p>\n\n<p>Edit: you don't even need the subset test; all you need is set equality.</p>\n\n<h2>Don't \"ternary instead of if\"</h2>\n\n<p>Even if you didn't do the symmetric set operation and kept your add/remove code, just... don't do this. It's the worst mix of \"too clever\", \"too illegible\" and \"difficult to maintain\".</p>\n\n<h2>Coalesce your returns</h2>\n\n<p>...into one boolean statement, for simplicity.</p>\n\n<h2>Proposed</h2>\n\n<pre><code>def is_rectangle_cover_orig(rectangles):\n if len(rectangles) == 0 or len(rectangles[0]) == 0:\n return False\n x1 = float(\"inf\")\n y1 = float(\"inf\")\n x2 = 0\n y2 = 0\n rect = set()\n area = 0\n for points in rectangles:\n x1 = min(points[0], x1)\n y1 = min(points[1], y1)\n x2 = max(points[2], x2)\n y2 = max(points[3], y2)\n area += (points[3] - points[1]) * (points[2] - points[0])\n rect.remove((points[0], points[3])) if (points[0], points[\n 3]) in rect else rect.add((points[0], points[3]))\n rect.remove((points[0], points[1])) if (points[0], points[\n 1]) in rect else rect.add((points[0], points[1]))\n rect.remove((points[2], points[3])) if (points[2], points[\n 3]) in rect else rect.add((points[2], points[3]))\n rect.remove((points[2], points[1])) if (points[2], points[\n 1]) in rect else rect.add((points[2], points[1]))\n if (x1, y2) not in rect or (x2, y1) not in rect or \\\n (x1, y1) not in rect or (x2, y2) not in rect or len(rect) != 4:\n return False\n return area == (y2 - y1) * (x2 - x1)\n\n\ndef is_rectangle_cover_new(rectangles):\n if len(rectangles) == 0 or len(rectangles[0]) == 0:\n return False\n x1, y1 = float(\"inf\"), float(\"inf\")\n x2, y2 = 0, 0\n rect = set()\n area = 0\n for xr1, yr1, xr2, yr2 in rectangles:\n x1 = min(xr1, x1)\n y1 = min(yr1, y1)\n x2 = max(xr2, x2)\n y2 = max(yr2, y2)\n area += (yr2 - yr1) * (xr2 - xr1)\n rect ^= {(xr1, yr2), (xr1, yr1), (xr2, yr2), (xr2, yr1)}\n return (\n rect == {(x1, y2), (x2, y1), (x1, y1), (x2, y2)} and\n area == (y2 - y1) * (x2 - x1)\n )\n\n\ndef test():\n for i, rects in enumerate((\n (\n (1, 1, 3, 3),\n (3, 1, 4, 2),\n (3, 2, 4, 4),\n (1, 3, 2, 4),\n (2, 3, 3, 4)\n ),\n (\n (1, 1, 2, 3),\n (1, 3, 2, 4),\n (3, 1, 4, 2),\n (3, 2, 4, 4)\n ),\n (\n (1, 1, 3, 3),\n (3, 1, 4, 2),\n (1, 3, 2, 4),\n (3, 2, 4, 4)\n ),\n (\n (1, 1, 3, 3),\n (3, 1, 4, 2),\n (1, 3, 2, 4),\n (2, 2, 4, 4)\n )\n ), 1):\n old_ans = is_rectangle_cover_orig(rects)\n new_ans = is_rectangle_cover_new(rects)\n print(f'Example {i}: {old_ans}')\n assert old_ans == new_ans\n\n\ntest()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T02:24:29.873",
"Id": "221894",
"ParentId": "221875",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "221894",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T18:20:55.463",
"Id": "221875",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x",
"programming-challenge"
],
"Title": "(Leetcode) Perfect Rectangle"
} | 221875 |
<p>I need to make a project related to a library catalog.</p>
<p>It should have following methods relevant to these books:</p>
<p>add
delete
list
There are two types of books: novels and poetry. Both types have number of pages and names. Novels have categories (SF...) and poetry have themes. Need to be able to list the books in the library.</p>
<p>How should I model the code for this (using inheritance, Lists, no hashmap)? I have thought to create a class BasicBook (fields pages, names), Novels (field category) and Poetry (field theme) to inherit from BasicBook. Create a class Library (fields List Novel, List Poetry) and methods to add, delete, print).
Is there a better way to tackle this problem? Thanks a lot!</p>
<pre><code>package com.andy85;
public class Book {
private String name;
private int numOfPages;
public Book(String name, int numOfPages) {
this.name = name;
this.numOfPages = numOfPages;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumOfPages() {
return numOfPages;
}
public void setNumOfPages(int numOfPages) {
this.numOfPages = numOfPages;
}
@Override
public String toString() {
return this.name + ", " + this.numOfPages;
}
}
public class Novel extends Book {
private String types;
public Novel(String name, int numOfPages, String types) {
super(name, numOfPages);
this.types = types;
}
public String getTypes() {
return types;
}
public void setTypes(String types) {
this.types = types;
}
@Override
public String toString() {
return super.toString() + ": " + types;
}
}
public class ArtAlbum extends Book {
private String paperQuality;
public ArtAlbum(String name, int numOfPages, String paperQuality) {
super(name, numOfPages);
this.paperQuality = paperQuality;
}
public String getPaperQuality() {
return paperQuality;
}
public void setPaperQuality(String paperQuality) {
this.paperQuality = paperQuality;
}
@Override
public String toString() {
return super.toString() + paperQuality;
}
public class LibraryCatalog {
private List<Novel> novel = new ArrayList<>();
private List<ArtAlbum> artAlbum = new ArrayList<>();
public LibraryCatalog(List<Novel> novel, List<ArtAlbum> artAlbum) {
this.novel = new ArrayList<>(novel);
this.artAlbum = new ArrayList<>(artAlbum);
}
public List<Novel> getNovel() {
return novel;
}
public void setNovel(List<Novel> novel) {
this.novel = novel;
}
public List<ArtAlbum> getArtAlbum() {
return artAlbum;
}
public void setArtAlbum(List<ArtAlbum> artAlbum) {
this.artAlbum = artAlbum;
}
public void addNovel (Novel newNovel) {
this.novel.add(newNovel);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T19:36:02.760",
"Id": "429272",
"Score": "0",
"body": "Can your library have duplicate books?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T19:40:18.520",
"Id": "429273",
"Score": "0",
"body": "yes, no need to cover corner cases, just a simple code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T19:46:39.210",
"Id": "429275",
"Score": "0",
"body": "sure, I have added missing code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T12:47:30.167",
"Id": "429348",
"Score": "0",
"body": "Are you looking for the \"how's my homework\" review, or the \"is this professional code\" review?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T18:20:24.347",
"Id": "429622",
"Score": "0",
"body": "Request for Clarification: Your questions mentions two subtypes, Novels having categories and Poems(PoetryCollection maybe) having themes. Your code, however, details Novels having a Type and ArtAlbums having a PaperQuality. Is this intentional? If so I am confused, and if not I would recommend an edit of the question to match the code, or of the code to match the question"
}
] | [
{
"body": "<h3>Design</h3>\n\n<p>Since duplicates are allowed (no Set required) and you don't need to fetch books by name (no Map required), <code>ArrayList</code> will do just fine.</p>\n\n<p><a href=\"https://en.wikiversity.org/wiki/Java_Collections_Overview\" rel=\"nofollow noreferrer\">Overview Collection Types</a></p>\n\n<h3>Guard public entrypoints</h3>\n\n<p>Make sure to checks arguments on all publically available code that takes input from calling code.</p>\n\n<pre><code>if (novels == null) throw new IllegalArgumentException(\"novels must be set\");\n</code></pre>\n\n<h3>Use plural for variable names that represent collections</h3>\n\n<pre><code>private List<Novel> novels = new ArrayList<>();\nprivate List<ArtAlbum> artAlbums = new ArrayList<>();\n</code></pre>\n\n<h3>Initialize object members only once</h3>\n\n<p>Don't create the <code>ArrayList</code> instances twice. You can use <code>addAll</code> to add a range of items to a list. Perhaps you also want to create public methods to perform these actions.</p>\n\n<pre><code>public class LibraryCatalog {\n private List<Novel> novels = new ArrayList<>();\n private List<ArtAlbum> artAlbums = new ArrayList<>();\n\n public LibraryCatalog(List<Novel> novels, List<ArtAlbum> artAlbums) {\n if (novels == null)\n throw new IllegalArgumentException(\"novels must be set\");\n if (artAlbums == null)\n throw new IllegalArgumentException(\"argument must be set\");\n this.novels.addAll(novels);\n this.artAlbums.addAll(artAlbums);\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T20:15:51.440",
"Id": "429282",
"Score": "0",
"body": "thanks a lot! and how can i list the books with all details (specific for novels and art albums)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T20:17:35.290",
"Id": "429285",
"Score": "0",
"body": "@Andy What do you mean with 'with all details'?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T20:21:16.567",
"Id": "429286",
"Score": "0",
"body": "for example novels to have name, numOfPages, types and artAlbum to have name, numOfPages, paperQuality. i can create separate toString for each class but how to list them together"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T20:23:25.020",
"Id": "429287",
"Score": "0",
"body": "@Andy That is out of scope for your question. I would await a couple more answers, and then you could decide to have a follow-up question with more code to review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T18:09:13.833",
"Id": "429615",
"Score": "0",
"body": "A general rule of thumb: if your question has working code and boils down to “is this the best way to {something}” it is generally valid for CR. If your question instead involves “How do I {anything}” it is likely better suited to a Stack Overflow question"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T20:10:15.717",
"Id": "221880",
"ParentId": "221878",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T19:25:48.350",
"Id": "221878",
"Score": "2",
"Tags": [
"java",
"inheritance"
],
"Title": "library having two types of books"
} | 221878 |
<p>I wrote a <code>HttpClient</code> instantiable class that will be used as reference to simplify API calls in other methods inside other classes, so the user could call it in a simple way when using my project as reference. I made both synchronous and asynchronous methods, as it was requested for me to made like this.</p>
<p>The main class to build the client is built in:</p>
<pre><code>public class Client : IDisposable
{
private static HttpClient _client;
public Client(bool payment)
{
var baseUrl = payment ? "https://payment.apiaddress.com/" : "https://api.apiaddress.com/";
_client = new HttpClient {BaseAddress = new Uri(baseUrl)};
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
_client.DefaultRequestHeaders.Add("X-API-KEY", Config.GetToken());
}
public void Dispose() => _client.Dispose();
public HttpResponseMessage Request(Methods method, string url, object data)
{
switch (method)
{
case Methods.GET: return _client.GetAsync(url).Result;
case Methods.POST: return _client.PostAsJsonAsync(url, data).Result;
case Methods.PUT: return _client.PutAsJsonAsync(url, data).Result;
case Methods.DELETE: return _client.DeleteAsync(url).Result;
default: return _client.GetAsync(url).Result;
}
}
public string Get(string url) =>
Request(Methods.GET, url, null).Content.ReadAsStringAsync().Result;
public string Post(string url, object data) =>
Request(Methods.POST, url, data).Content.ReadAsStringAsync().Result;
public string Put(string url, object data) =>
Request(Methods.PUT, url, data).Content.ReadAsStringAsync().Result;
public string Delete(string url) =>
Request(Methods.PUT, url, null).Content.ReadAsStringAsync().Result;
public async Task<HttpResponseMessage> RequestAsync(Methods method, string url, object data)
{
switch (method)
{
case Methods.GET: return await _client.GetAsync(url).ConfigureAwait(false);
case Methods.POST: return await _client.PostAsJsonAsync(url, data).ConfigureAwait(false);
case Methods.PUT: return await _client.PutAsJsonAsync(url, data).ConfigureAwait(false);
case Methods.DELETE: return await _client.DeleteAsync(url).ConfigureAwait(false);
default: return await _client.GetAsync(url).ConfigureAwait(false);
}
}
public Task<HttpResponseMessage> GetAsync(string url) =>
RequestAsync(Methods.GET, url, null);
public Task<HttpResponseMessage> PostAsync(string url, object data) =>
RequestAsync(Methods.POST, url, data);
public Task<HttpResponseMessage> PutAsync(string url, object data) =>
RequestAsync(Methods.PUT, url, data);
public Task<HttpResponseMessage> DeleteAsync(string url) =>
RequestAsync(Methods.DELETE, url, null);
}
</code></pre>
<p>It's used on other classes like this one, to start a new checkout for custom objects based on specific models, which are made by a third part:</p>
<pre><code>public class Payment
{
private static readonly Client _client = new Client(true);
public static async Task<string> CreditAsync(object data)
{
var response = await _client.PostAsync("Payment", data);
var content = await response.Content.ReadAsStringAsync();
return content;
}
public static string Credit(object data)
{
var response = _client.Post("Payment", data);
return response;
}
}
</code></pre>
<p>The <code>new Client(true)</code> value is to provide the both expected address for the API, as there will be moments that in production environment it will use the <code>api.etc</code> and other that will use the <code>payment.etc</code>, also to use the provided relative path inside the method content as well.</p>
<p>So the usage could be simplified just as:</p>
<pre><code>public void Credit() //OR: public async Task CreditAsync()
{
var transaction = new Transaction<Credit>
{
PaymentMethod = new PaymentMethod {Code = "1"},
Application = "Tests",
Vendor = "Felipe",
Customer = new Customer
{
//Customer data goes here...
},
Products = new List<TransactionProduct>
{
//Product data goes here...
}
};
var test = Payment.Credit(transaction); //OR: await Payment.CreditAsync(transaction);
Console.WriteLine(teste);
}
</code></pre>
<p>It works fine and provide the expected responses, that I'll do a better treatment later as required, but I would really appreciate any different and more experienced views to know if this could be considered a good approach for this need and/or if there are ways to improve it, as the idea is to release it as a NuGet/SDK for the final project.</p>
| [] | [
{
"body": "<h3>Dispose Strategy</h3>\n<p>It seems your class doesn't even need to implement <code>IDisposable</code>. <a href=\"https://stackoverflow.com/questions/15705092/do-httpclient-and-httpclienthandler-have-to-be-disposed\">Should dispose HttpClient?</a></p>\n<hr />\n<h3>Single Responsibility</h3>\n<p>I would extract configuration management from the implementation of <code>Client</code>.</p>\n<pre><code>public Client(string baseUrl)\n{\n _baseUrl = baseUrl ?? throw new ArgumentNullException(nameof(baseUrl));\n // ..\n}\n</code></pre>\n<p>Add a factory for generating the client instance. This one uses hardcoded uri's, but you could also read from a config file or database.</p>\n<pre><code>public static class ClientFactory\n{\n public static Client Create(bool payment)\n {\n var baseUrl = payment \n ? "https://payment.apiaddress.com/" : "https://api.apiaddress.com/";\n return new Client(baseUrl);\n }\n}\n</code></pre>\n<hr />\n<h3>Method Design</h3>\n<p>I have my doubts about having <code>*..1..*</code> (junction) method interactions. I would refactor this to <code>1..1</code> (simple) or <code>1..*..1</code> (fork).</p>\n<p>Original <code>*..1..*</code>:</p>\n<blockquote>\n<pre><code> public HttpResponseMessage Request(Methods method, string url, object data)\n {\n switch (method)\n {\n case Methods.GET: return _client.GetAsync(url).Result;\n case Methods.POST: return _client.PostAsJsonAsync(url, data).Result;\n case Methods.PUT: return _client.PutAsJsonAsync(url, data).Result;\n case Methods.DELETE: return _client.DeleteAsync(url).Result;\n default: return _client.GetAsync(url).Result;\n }\n }\n\n public string Get(string url) => \n Request(Methods.GET, url, null).Content.ReadAsStringAsync().Result;\n\n // others ..\n</code></pre>\n</blockquote>\n<p>Refactored to <code>1..1</code>:</p>\n<pre><code>public string Get(string url) => \n _client.GetAsync(url).Result.Content.ReadAsStringAsync().Result;\n\npublic string Post(string url, object data) => \n _client.PostAsJsonAsync(url, data).Result.Content.ReadAsStringAsync().Result;\n\npublic string Put(string url, object data) => \n _client.PutAsJsonAsync(url, data).Result.Content.ReadAsStringAsync().Result;\n\npublic string Delete(string url) => \n _client.DeleteAsync(url).Result.Content.ReadAsStringAsync().Result;\n</code></pre>\n<p>And if you really must have wrapper function <code>1..*..1</code>:</p>\n<pre><code> public HttpResponseMessage Request(Methods method, string url, object data)\n {\n switch (method)\n {\n case Methods.GET: return Get(url);\n case Methods.POST: return Post(url, data);\n case Methods.PUT: return Put(url, data);\n case Methods.DELETE: return Delete(url);\n default: return _client.GetAsync(url).Result;\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T20:37:56.767",
"Id": "221882",
"ParentId": "221879",
"Score": "6"
}
},
{
"body": "<p>I think, you should be concerned about this behavior:</p>\n\n<blockquote>\n<pre><code>public class Client : IDisposable {\n private static HttpClient _client;\n\n public Client(bool payment)\n {\n var baseUrl = payment ? \"https://payment.apiaddress.com/\" : \"https://api.apiaddress.com/\";\n\n _client = new HttpClient {BaseAddress = new Uri(baseUrl)};\n _client.DefaultRequestHeaders.Accept.Clear();\n _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(\"application/json\"));\n _client.DefaultRequestHeaders.Add(\"X-API-KEY\", Config.GetToken());\n }\n\n public Uri BaseAddress => _client?.BaseAddress; // Added by HH\n ....\n</code></pre>\n</blockquote>\n\n<p>Test case</p>\n\n<pre><code> // \n Client client1 = new Client(true);\n Console.WriteLine(client1.BaseAddress);\n Console.WriteLine();\n Client client2 = new Client(false);\n Console.WriteLine(client1.BaseAddress);\n Console.WriteLine(client2.BaseAddress);\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>https://payment.apiaddress.com/\n\nhttps://api.apiaddress.com/\nhttps://api.apiaddress.com/\n</code></pre>\n\n<p>As you see the inner <code>static HttpClient _client</code> becomes a new instance when <code>client2</code> is called and therefore <code>client1</code> also changes base address which may result in unexpected behavior.</p>\n\n<p>So as I see it, you can't use this concept with two different base addresses.</p>\n\n<p>A solution could be to provide what could be called a \"Dualton\" in a fashion like:</p>\n\n<pre><code>public class Client : IDisposable\n{\n private HttpClient _client;\n\n private Client(string baseUrl)\n {\n //var baseUrl = payment ? \"https://payment.apiaddress.com/\" : \"https://api.apiaddress.com/\";\n\n _client = new HttpClient { BaseAddress = new Uri(baseUrl) };\n _client.DefaultRequestHeaders.Accept.Clear();\n _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(\"application/json\"));\n _client.DefaultRequestHeaders.Add(\"X-API-KEY\", Config.GetToken());\n }\n\n static Client paymentClient;\n static Client normalClient;\n\n public static Client Create(bool payment)\n {\n if (payment)\n {\n paymentClient = paymentClient ?? new Client(\"https://payment.apiaddress.com/\");\n return paymentClient;\n }\n\n normalClient = normalClient ?? new Client(\"https://api.apiaddress.com/\");\n return normalClient;\n }\n</code></pre>\n\n<p>Someone would probably called that an anti pattern? </p>\n\n<p>A more general solution could be to have a <code>static Dictionary<string, Client> clients</code> and the matching <code>public static Client Create(string baseUrl) {}</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-11T19:34:48.740",
"Id": "222103",
"ParentId": "221879",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T20:08:38.870",
"Id": "221879",
"Score": "5",
"Tags": [
"c#",
"api",
"http",
"rest"
],
"Title": "HttpClient reusable instance for simple calls on another methods"
} | 221879 |
<p>For the longest time I always felt lost designing a robust OOP program, especially in C++. I felt like I didn't know enough theory or algorithms so I would study and never write code, not to mention I was always afraid of criticism or looking amateurish. Recently I came to the realization that I been holding myself back by doing this and moving beyond my insecurities. I have taken more leaps by writing common C++ programs to build my knowledge of the language and architecture. Everyone told me writing a Blackjack game would help build my knowledge purely for practice for more ambitious projects and contributing to open source projects that is hard for me to understand.</p>
<p><strong>TL;DR:</strong> I been creating a Blackjack program to help me learn programming and design at a more advanced level.</p>
<p>I tried utilizing things I never used before such as namespaces, enums, and maps with operator overloading. Right now it's a work in progress: it only handles 2 players, the dealer logic hasn't been developed yet until I get the game working correctly, thinking about making a derived class for Blackjack rules in case I want to make poker rules. I already know this is a mess, but I guess it's part of the learning process, huh?</p>
<p>main.cpp</p>
<pre><code>#include <iostream>
#include <string>
#include "BlackJack.h"
#include "Player.h"
int main() {
BlackJack game(2); // only two players for now, requires user for both
game.play();
return 0;
}
</code></pre>
<p>CardInfo.h</p>
<pre><code>#pragma once
#include <string>
#include <unordered_map>
namespace Cards {
enum class Rank {
ONE = 1, TWO, THREE,
FOUR, FIVE, SIX,
SEVEN, EIGHT, NINE,
TEN, JACK, QUEEN, KING, ACE
};
enum class Suit {
CLUBS, DIAMONDS, HEARTS, SPADES
};
};
namespace CardData {
// TODO make a derived card class specifically for Blackjack rules
struct Card {
Cards::Rank rank;
Cards::Suit suit;
// TODO define this so the map works
bool operator<(const CardData::Card &card) const {
return this->rank < card.rank;
}
};
}
</code></pre>
<p>Player.h</p>
<pre><code>#pragma once
#include <vector>
#include <string>
#include "CardInfo.h"
class Player {
int points{ 0 };
int numAces{ 0 }; // count aces in order to deduce 1 or 11 logic in updateScore
int id;
std::vector<CardData::Card> hand;
public:
Player(int ID);
void dealtCard(CardData::Card &drawnCard);
void updateScore(int score); // call after every dealt card
bool requestHit(); // request to exchange cards
bool hasBust();
int getScore();
int getId();
};
</code></pre>
<p>Player.cpp</p>
<pre><code>#include "Player.h"
#include <string>
#include <iostream>
Player::Player(int ID) : id(ID) {}
void Player::dealtCard(CardData::Card &drawnCard) {
//Card drawnCard{ Cards::Rank::ACE, Cards::Suit::SPADES }; remove possibly
hand.push_back(drawnCard); // test insert
}
void Player::updateScore(const int score) {
if (score == 11)
numAces++;
points += score;
if (points > 21)
while (numAces > 0) {
numAces--;
points--;
}
}
bool Player::requestHit() {
char answer;
std::cout << "Player " << id << ": Hit or stick? [y|n]" << std::endl;
std::cin >> answer;
return tolower(answer) == 'y';
}
bool Player::hasBust() {
return getScore() > 21;
}
int Player::getScore() { return points; }
int Player::getId() { return id; }
</code></pre>
<p>BlackJack.h</p>
<pre><code>#pragma once
#include <set>
#include <random>
#include "Player.h"
#include <string>
class BlackJack {
int numPlayers;
static std::unordered_map<Cards::Rank, int> score;
std::vector<Player> players;
std::set<CardData::Card> inPlay; // drawn cards inserted here to prevent duplication
CardData::Card drawCard();
void hitOrStick();
void playHands();
int enumerateCard(const CardData::Card &card) const; // converts cards to score, deals with Aces and Royals
void deal(Player &player);
public:
BlackJack(int players);
void play();
};
</code></pre>
<p>BlackJack.cpp</p>
<pre><code>#include "BlackJack.h"
#include <iostream>
#include <string>
std::unordered_map<Cards::Rank, int> BlackJack::score{
{Cards::Rank::ONE, 1},{Cards::Rank::TWO, 2},{Cards::Rank::THREE, 3},
{Cards::Rank::FOUR, 4},{Cards::Rank::FIVE, 5},{Cards::Rank::SIX, 6},
{Cards::Rank::SEVEN, 7},{Cards::Rank::EIGHT, 8},{Cards::Rank::NINE, 9},
{Cards::Rank::TEN, 10},{Cards::Rank::JACK, 10},{Cards::Rank::QUEEN, 10},
{Cards::Rank::KING, 10},{Cards::Rank::ACE, 11}
};
BlackJack::BlackJack(int players = 2) : numPlayers(players) {
for (int i = 0; i < numPlayers; i++) {
this->players.push_back(Player(i));
}
}
void BlackJack::play() {
// Shuffle workflow and distribute cards
for (Player player : players) {
std::cout << "Player \'" << player.getId() << "\' These are your cards: " << std::endl;
for (int i = 0; i < 2; i++) {
deal(player);
}
}
hitOrStick();
playHands();
}
void BlackJack::deal(Player &player) {
CardData::Card drawn;
drawn = drawCard();
while (inPlay.find(drawn) != inPlay.end())
drawn = drawCard();
std::cout << score[drawn.rank] << std::endl;
player.dealtCard(drawn);
player.updateScore(enumerateCard(drawn));
inPlay.insert(drawn);
}
CardData::Card BlackJack::drawCard() {
std::uniform_int_distribution<> suitDistrib(0, 3);
std::uniform_int_distribution<> rankDistrib(1, 14);
std::random_device rd;
std::mt19937 generator(rd());
int newRank = rankDistrib(generator);
int newSuit = suitDistrib(generator);
return CardData::Card{ static_cast<Cards::Rank>(newRank), static_cast<Cards::Suit>(newSuit) };
}
int BlackJack::enumerateCard(const CardData::Card &card) const {
return score[card.rank];
}
void BlackJack::hitOrStick() {
for (Player player : players)
while (!player.hasBust() && player.requestHit())
deal(player);
}
void BlackJack::playHands() {
int winner = -1;
int maxScore = -1;
bool push = false;
for (Player player : players) {
std::cout << "Player " << player.getId() << ": " << player.getScore() << std::endl;
if (player.getScore() > maxScore) {
push = false;
winner = player.getId();
maxScore = player.getScore();
} else if (maxScore == player.getScore()) {
push = true;
}
}
if (push)
std::cout << "Push!" << std::endl;
else if (winner == 0)
std::cout << "House wins!" << std::endl;
else
std::cout << "Player " << winner << " wins!" << std::endl;
}
</code></pre>
<hr>
<p>Any advice on what I need to improve or design/clean code faux pas I'm breaking? If you also having any suggestions on how I should focus on my dealer AI or operator< overload, I really appreciate. Here's to getting better every day!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T20:47:14.117",
"Id": "429288",
"Score": "3",
"body": "`Right now it's a work in progress` Does it work?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T20:52:20.560",
"Id": "429290",
"Score": "0",
"body": "@yuri each function works as intended, but to completion it doesn't. Right now I'm trying to figure out the overload for `bool operator<(const CardData::Card &card) const` so that the comparisons work correctly for the set and map containers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T05:38:55.220",
"Id": "429325",
"Score": "1",
"body": "Deja vu! I just reviewed [another Blackjack game](https://codereview.stackexchange.com/questions/221454/console-blackjack-game-without-split-or-betting-system-for-now/221565#221565) probably a week ago! I think I like your design better. Anyway, if you want to see how someone else tried to accomplish the same thing, here you go."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T22:27:12.143",
"Id": "429511",
"Score": "0",
"body": "@Chipster thanks, just having other references is helpful enough to see what may work or be easier."
}
] | [
{
"body": "<blockquote>\n <p>Recently I came to the realization that I been holding myself back by doing this and moving beyond my insecurities. I have taken more leaps by writing common C++ programs to build my knowledge of the language and architecture.</p>\n</blockquote>\n\n<p>Learning by doing is a good approach IMO. \nHopefully you can improve your game and submit it again for review!</p>\n\n<hr>\n\n<h2>main</h2>\n\n<p>Is <code>Player.h</code> needed in main? </p>\n\n<p>Turn <code>2</code> into a named constant: </p>\n\n<pre><code>int constexpr players{2};\nBlackJack game{players}; \n</code></pre>\n\n<p>This makes it much clearer what is being passed to your game. </p>\n\n<p>While some people really don't like this, you can omit <code>return 0</code> from <code>main</code> if you don't depend on it. The compiler will generate it for you.</p>\n\n<hr>\n\n<h2>cardinfo</h2>\n\n<p>Personally I don't mind <code>#pragma once</code>, just remember it's <a href=\"https://en.wikipedia.org/wiki/Pragma_once\" rel=\"nofollow noreferrer\">not standard</a>. </p>\n\n<p>[Subjective] Don't indent after <code>namespace</code>. </p>\n\n<p>[Subjective] Don't write more than one statement per line in your enums. </p>\n\n<p>If you want to use an unordered container with a custom key you need to provide <em>hash</em> and <em>compare</em> functions. Have a look at <a href=\"https://stackoverflow.com/questions/17016175/c-unordered-map-using-a-custom-class-type-as-the-key\">this SO question</a> and this <a href=\"https://en.cppreference.com/w/cpp/container/unordered_map/unordered_map\" rel=\"nofollow noreferrer\">link from cppreference</a>.</p>\n\n<hr>\n\n<h2>player</h2>\n\n<p>Class interfaces should go from least restricted to most restricted (i.e. <code>public</code>, <code>protected</code>, <code>private</code>). Reason being that when someone reads your interface he is most likely interested in the public functions that can be worked with.</p>\n\n<p>[Subjective] Don't omit braces as that can lead to bugs down the line.\nE.g.:</p>\n\n<pre><code>// bad\nif (foo) \n // code here\n\n// good\nif (foo)\n{\n // code here\n}\n</code></pre>\n\n<p><a href=\"https://softwareengineering.stackexchange.com/questions/59880/avoid-postfix-increment-operator\">Prefer prefix (++foo) over postfix (foo++) operator</a>.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/213907/c-stdendl-vs-n\">Prefer using <code>\\n</code> over <code>std::endl</code></a></p>\n\n<p>I'm not familiar with blackjack but if you ask <em>\"hit or stick\"</em> should the answer options really be <em>\"yes/no\"</em> not maybe <em>\"hit/stick\"</em>?</p>\n\n<hr>\n\n<h2>blackjack</h2>\n\n<p>Reuse your RNG. Have a look at <a href=\"https://codereview.stackexchange.com/questions/213842/rock-paper-scissors-engine\">this question</a> to see how it could be done.</p>\n\n<p><a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es23-prefer-the--initializer-syntax\" rel=\"nofollow noreferrer\">You can and should use brace initialization when possible.</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T16:49:22.017",
"Id": "429605",
"Score": "0",
"body": "Thank you @yuri this was more than I was expecting. This should put me on the right track. This pretty much covers everything I been having uncertainty with. I'll be sure to submit my updates again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-14T15:36:03.803",
"Id": "430161",
"Score": "0",
"body": "I guess I'm in the crowd that doesn't like not returning from main. I think doing that might technically be undefined behavior, although since it's main, there may be an exception for that. I don't remember."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-14T15:46:34.657",
"Id": "430163",
"Score": "0",
"body": "Nvm. I found where it said that in the standard. I guess I still don't like it, though :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T08:28:28.567",
"Id": "221994",
"ParentId": "221881",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "221994",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T20:18:17.223",
"Id": "221881",
"Score": "5",
"Tags": [
"c++",
"beginner",
"object-oriented",
"playing-cards"
],
"Title": "C++ practice project: Blackjack"
} | 221881 |
<p><strong>Problem Description:</strong></p>
<blockquote>
<p>Given a 32-bit signed integer, reverse digits of an integer in
JavaScript.</p>
<p><strong>Example 1:</strong></p>
<ul>
<li>Input: 123 </li>
<li>Output: 321</li>
</ul>
<p><strong>Example 2:</strong></p>
<ul>
<li><p>Input: -123 </p></li>
<li><p>Output: -321</p></li>
</ul>
<p><strong>Example 3:</strong></p>
<ul>
<li><p>Input: 120</p></li>
<li><p>Output: 21</p></li>
</ul>
<p><strong>Note:</strong> It should return zero when it reaches out of limit [−2 ^31, 2 ^31 − 1]</p>
</blockquote>
<p><strong>My implementation</strong></p>
<pre><code>var reverse = function (x) {
var minRange = Math.pow(-2, 31)
var maxRange = Math.pow(2, 31) - 1
var isNegative = false;
if (x < 0) {
isNegative = true;
x = (x - x - x);
}
var result = Number(x.toString().split('').reverse().join(''));
(isNegative) ? result = (result - result - result) : result;
if (result < minRange || result > maxRange) {
return 0
} else {
return result;
}
};
</code></pre>
<p>Please help to improve.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T21:21:43.877",
"Id": "429293",
"Score": "1",
"body": "Check out https://codereview.stackexchange.com/questions/220274"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T09:07:16.363",
"Id": "429338",
"Score": "0",
"body": "Check this out - https://leetcode.com/problems/reverse-integer/solution/, it might help you."
}
] | [
{
"body": "<p>-- adding this as an answer because I can't comment.</p>\n\n<p>The answer referenced in ggorlen's comment, can be improved by remarking that a (negative number % 10) is a negative number, so there is no need for sign checking.</p>\n\n<pre><code>const reverse = val => {\n let res = 0;\n const Base = 10;\n while (val) {\n res = res * Base + (val % Base);\n val = (val / Base) | 0;\n }\n return (res | 0) == res ? res : 0;\n}\n</code></pre>\n\n<p>Tests:</p>\n\n<pre><code>reverse(1) === 1; \nreverse(-1) === -1 \nreverse(0) === 0 \nreverse(Math.pow(2,31) - 1) === 0 \nreverse(Math.pow(-2,31)) === 0 \nreverse(1463847412) === 2147483641\nreverse(1463847413) === 0 \n</code></pre>\n\n<p>By the way, what's the reasoning behind \"x = (x - x - x)\"? x-x evaluates to zero. so that's just x = - x.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T22:43:01.440",
"Id": "429424",
"Score": "0",
"body": "+1 Welcome to CR. You can skip the sign but I will point out that numbers are converted to int in a standard way, ignoring the sign will only work for integers in range. Outside the range and you return the wrong value because to do not account for the correct conversion. Eg `(new Int32Array([21474836481]))[0] === 1` yet you reverse it to `reverse(21474836481) === 1536152588`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T04:25:17.830",
"Id": "429439",
"Score": "0",
"body": "I don't understand, the question said we are guaranteed to receive a signed 32 bit integer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T22:20:06.887",
"Id": "221888",
"ParentId": "221884",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "221888",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T20:47:47.253",
"Id": "221884",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Reverse Integer in JavaScript"
} | 221884 |
<p>I want a rate-limiter that permits, at most, N operations over T seconds. I found a sample implementation <a href="http://www.jackleitch.net/2010/10/better-rate-limiting-with-dot-net/" rel="noreferrer">here</a> but it makes an assumption that operations complete in a predictable, consistent amount of time. I don't want to make that assumption.</p>
<p>My attempt to solve this simplifies the approach in the linked article by requiring the caller to signal when their operation completes. A timer fires every T seconds, releasing a SlimSemaphore the number of completed operations since the timer previously fired.</p>
<p>I'm looking for feedback on potential bugs, areas for improvement, and ways to make this more efficient. </p>
<pre><code>using System;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using Timer = System.Timers.Timer;
public class RateLimiter : IDisposable
{
// Semaphore used to count and limit the number of occurrences per unit time.
private readonly SemaphoreSlim semaphore;
// Timer used to trigger exiting the semaphore.
private readonly Timer batchTimer;
// Whether this instance is disposed.
private bool isDisposed;
private int countCompleted;
/// <summary>
/// Number of occurrences allowed per unit of time.
/// </summary>
public int Occurrences { get; private set; }
/// <summary>
/// The length of the time unit, in milliseconds.
/// </summary>
public int TimeUnitMilliseconds { get; private set; }
public RateLimiter(int occurrences, TimeSpan timeUnit)
{
// Check the arguments.
if (occurrences <= 0)
{
throw new ArgumentOutOfRangeException(nameof(occurrences), "Number of occurrences must be a positive integer");
}
if (timeUnit != timeUnit.Duration())
{
throw new ArgumentOutOfRangeException(nameof(timeUnit), "Time unit must be a positive span of time");
}
if (timeUnit >= TimeSpan.FromMilliseconds(uint.MaxValue))
{
throw new ArgumentOutOfRangeException(nameof(timeUnit), "Time unit must be less than 2^32 milliseconds");
}
this.Occurrences = occurrences;
this.TimeUnitMilliseconds = (int)timeUnit.TotalMilliseconds;
Interlocked.Exchange(ref this.countCompleted, 0);
// Create the semaphore, with the number of occurrences as the maximum count.
this.semaphore = new SemaphoreSlim(this.Occurrences, this.Occurrences);
// Create a timer to exit the semaphore. Use the time unit as the original
// interval length because that's the earliest we will need to exit the semaphore.
this.batchTimer = new Timer(this.TimeUnitMilliseconds);
this.batchTimer.Elapsed += this.OnBatchTimerElapsed;
this.batchTimer.AutoReset = true;
this.batchTimer.Enabled = true;
}
private void OnBatchTimerElapsed(object sender, ElapsedEventArgs e)
{
this.semaphore.Release(Interlocked.Exchange(ref this.countCompleted, 0));
}
public void Completed()
{
Interlocked.Increment(ref this.countCompleted);
}
/// <summary>
/// Blocks the current thread until allowed to proceed, or until the specified timeout elapses.
/// </summary>
/// <param name="millisecondsTimeout">Number of milliseconds to wait, or -1 to wait indefinitely.</param>
/// <returns>true if the thread is allowed to proceed, or false if timed out</returns>
public async Task<bool> WaitToProceed(int millisecondsTimeout)
{
// Check the arguments.
if (millisecondsTimeout < -1)
{
throw new ArgumentOutOfRangeException("millisecondsTimeout");
}
this.CheckDisposed();
// Block until we can enter the semaphore or until the timeout expires.
return await this.semaphore.WaitAsync(millisecondsTimeout);
}
/// <summary>
/// Blocks the current thread indefinitely, until allowed to proceed.
/// </summary>
public async Task<bool> WaitToProceed()
{
return await this.WaitToProceed(Timeout.Infinite);
}
// Throws an ObjectDisposedException if this object is disposed.
private void CheckDisposed()
{
if (this.isDisposed)
{
throw new ObjectDisposedException("RateLimiter is already disposed");
}
}
/// <summary>
/// Releases unmanaged resources held by an instance of this class.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged resources held by an instance of this class.
/// </summary>
/// <param name="isDisposing">Whether this object is being disposed.</param>
protected virtual void Dispose(bool isDisposing)
{
if (this.isDisposed)
{
if (isDisposing)
{
// The semaphore and timer both implement IDisposable and
// therefore must be disposed.
this.semaphore.Dispose();
this.batchTimer.Dispose();
this.isDisposed = true;
}
}
}
}
</code></pre>
<p>Sample Usage:</p>
<pre><code>var tasks = new List<Task>();
// Can process up to 40 operations per 10 seconds.
var rateLimiter = new RateLimiter(40, TimeSpan.FromSeconds(10));
for (int i = 0; i < 90; i++)
{
tasks.Add(Task.Run(async () =>
{
await rateLimiter.WaitToProceed();
// do stuff
await Task.Delay(2000);
rateLimiter.Completed();
}));
}
await Task.WhenAll(tasks);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T03:29:44.083",
"Id": "429319",
"Score": "0",
"body": "One potential problem is that the user doesn't place the Completed function in a finally block. So if the // do stuff portion throws, a semaphore count is never released."
}
] | [
{
"body": "<p>IMO the use of <code>this.</code> before members in the methods reduces readability and is unnecessary.</p>\n\n<hr>\n\n<p><code>Occurrences</code> and <code>TimeUnitMilliseconds</code> should be immutable and only settable in the constructor so make it <code>private int Occurrences {get;}</code> or <code>private readonly int Occurrences</code>\n Alternatively you can make it public settable to allow for dynamic configuration?</p>\n\n<hr>\n\n<blockquote>\n<pre><code>protected virtual void Dispose(bool isDisposing)\n{\n if (this.isDisposed)\n {\n if (isDisposing)\n {\n</code></pre>\n</blockquote>\n\n<p>I think the <code>if (this.isDisposed)</code> should be <code>if (!isDisposed)</code></p>\n\n<hr>\n\n<blockquote>\n<pre><code> if (timeUnit >= TimeSpan.FromMilliseconds(uint.MaxValue))\n {\n throw new ArgumentOutOfRangeException(nameof(timeUnit), \"Time unit must be less than 2^32 milliseconds\");\n }\n Occurrences = occurrences;\n TimeUnitMilliseconds = (int)timeUnit.TotalMilliseconds;\n</code></pre>\n</blockquote>\n\n<p>Here you test <code>timeUnit</code> against <code>uint.MaxValue</code> and after that the value is cast to <code>int</code>. If <code>int.MaxValue < timeUnit < uint.MaxValue</code> the test is passed but the cast will result in a negative <code>TimeUnitMilliseconds</code>. </p>\n\n<hr>\n\n<p>Your test case doesn't dispose the <code>RateLimiter</code> instance.</p>\n\n<hr>\n\n<blockquote>\n <p><code>semaphore.Release(Interlocked.Exchange(ref countCompleted, 0));</code></p>\n</blockquote>\n\n<p>If <code>countCompleted == 0</code> this will fail. It can happen if no actions haven't terminated before the timer ticks.</p>\n\n<hr>\n\n<blockquote>\n <p><code>GC.SuppressFinalize(this);</code></p>\n</blockquote>\n\n<p>This has no meaning if the class doesn't have a finalizer (<code>~RateLimiter()</code>) <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.gc.suppressfinalize?view=netframework-4.8\" rel=\"noreferrer\">GC.SuppressFinalize(Object) Method</a></p>\n\n<hr>\n\n<p>A way to avoid that the users fail to call <code>Completed()</code> is to let <code>RateLimiter</code> handle the execution of the methods it self in a pattern like:</p>\n\n<pre><code>public class RateLimiter : IDisposable\n{\n async public Task Run(Func<Task> func)\n {\n try\n {\n await WaitToProceed();\n await func();\n }\n finally\n {\n Completed();\n }\n }\n\n ....\n}\n</code></pre>\n\n<p>And then make <code>WaitToProceed()</code> and <code>Completed()</code> as private members. </p>\n\n<p>You'll of course need to provide serveral overloads of the above, that take a timeout value and/or cancellation token and/or have return values etc. And the class should maybe be renamed to something more suitable. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T16:15:06.117",
"Id": "429376",
"Score": "0",
"body": "In your last point, if I use a Func, will exceptions thrown from func() bubble up to the caller of Run()."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T16:28:36.870",
"Id": "429378",
"Score": "0",
"body": "@Craig: Yes it will, but you can also catch exceptions inside Run() if you want to know about them there - and optionally rethrow them to be handled by the caller. All exceptions will be collected by the system and delivered to the caller in one `AggregateException`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T07:41:26.747",
"Id": "221909",
"ParentId": "221885",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "221909",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T21:12:54.343",
"Id": "221885",
"Score": "5",
"Tags": [
"c#",
".net",
"thread-safety"
],
"Title": "Rate limiting variable-duration operations over a time interval"
} | 221885 |
<p>I am trying to learn Objective C and want to make sure I am following the proper practices/convention.</p>
<p>I would very much appreciate advice on what to change/improve</p>
<p>I also have some questions:</p>
<ul>
<li>when do I use entity.position vs [entity position]?</li>
<li>when do I use NSNumber vs double</li>
<li>when do I use int vs NSInteger vs NSNumber</li>
<li>can I hide methods from super class as RotationalVector can do [RotationalVector vector3] but I would like for it to be only able to use [RotationalVector rotationalVector]</li>
<li>within an instance method whats the difference between _x, [self x] and self.x</li>
<li>would it be a good idea to only include init methods in the .m file?</li>
<li>am I using proper return types for init and factory method?</li>
</ul>
<p>Vector3.h:</p>
<pre><code>#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface Vector3 : NSObject
@property NSNumber* x;
@property NSNumber* y;
@property NSNumber* z;
- (id)init;
- (id)initWithX:(NSNumber*)x Y:(NSNumber*)y Z:(NSNumber*)z;
+ (instancetype)vector3;
+ (instancetype)vector3WithX:(NSNumber*)x Y:(NSNumber*)y Z:(NSNumber*)z;
- (void)addX:(NSNumber*)x Y:(NSNumber*)y Z:(NSNumber*)z;
- (void)setX:(NSNumber*)x Y:(NSNumber*)y Z:(NSNumber*)z;
@end
NS_ASSUME_NONNULL_END
</code></pre>
<p>Vector3.m</p>
<pre><code>#import "Vector3.h"
@implementation Vector3
- (id)init{
if (self = [super init]){
_x = [NSNumber numberWithDouble:0];
_y = [NSNumber numberWithDouble:0];
_z = [NSNumber numberWithDouble:0];
}
return self;
}
- (id)initWithX:(NSNumber*)x Y:(NSNumber*)y Z:(NSNumber*)z{
if (self = [super init]){
[self setX:x Y:y Z:z];
}
return self;
}
+ (instancetype)vector3{
return [[self alloc] init];
}
+ (instancetype)vector3WithX:(NSNumber*)x Y:(NSNumber*)y Z:(NSNumber*)z{
return [[self alloc] initWithX:x Y:y Z:z];
}
- (NSString*)description{
return [NSString stringWithFormat:@"(%@, %@, %@)",_x,_y,_z];
}
- (void)addX:(NSNumber*)x Y:(NSNumber*)y Z:(NSNumber*)z{
_x = [NSNumber numberWithDouble:[_x doubleValue] + [x doubleValue]];
_y = [NSNumber numberWithDouble:[_y doubleValue] + [y doubleValue]];
_z = [NSNumber numberWithDouble:[_z doubleValue] + [z doubleValue]];
}
- (void)setX:(NSNumber*)x Y:(NSNumber*)y Z:(NSNumber*)z{
_x = x;
_y = y;
_z = z;
}
@end
</code></pre>
<p>RotationVector.h</p>
<pre><code>#import "Vector3.h"
NS_ASSUME_NONNULL_BEGIN
@interface RotationVector : Vector3
- (id)init;
- (id)initWithX:(NSNumber*)x Y:(NSNumber*)y Z:(NSNumber*)z;
+ (instancetype)rotationVector;
+ (instancetype)rotationVectorWithX:(NSNumber*)x Y:(NSNumber*)y Z:(NSNumber*)z;
- (void)normalize;
- (void)addX:(NSNumber*)x Y:(NSNumber*)y Z:(NSNumber*)z;
- (void)setX:(NSNumber*)x Y:(NSNumber*)y Z:(NSNumber*)z;
@end
NS_ASSUME_NONNULL_END
</code></pre>
<p>RotationVector.m</p>
<pre><code>#import "RotationVector.h"
@implementation RotationVector
- (id)init{
self = [super init];
return self;
}
- (id)initWithX:(NSNumber*)x Y:(NSNumber*)y Z:(NSNumber*)z{
if (self = [super initWithX:x Y:y Z:y]){
[self normalize];
}
return self;
}
+ (instancetype)rotationVector{
return [[self alloc] init];
}
+ (instancetype)rotationVectorWithX:(NSNumber*)x Y:(NSNumber*)y Z:(NSNumber*)z{
return [[self alloc] initWithX:x Y:y Z:z];
}
- (void)addX:(NSNumber*)x Y:(NSNumber*)y Z:(NSNumber*)z{
[super addX:x Y:y Z:z];
[self normalize];
}
- (void)setX:(NSNumber*)x Y:(NSNumber*)y Z:(NSNumber*)z{
[super setX:x Y:y Z:z];
[self normalize];
}
- (void)normalize{
if ([[self x] doubleValue] >= 360.0 || [[self x] doubleValue] < 0.0){
int rotations = fmod([[self x] doubleValue], 360.0);
self.x = [NSNumber numberWithDouble:[[self x] doubleValue] - rotations * 360.0];
}
if ([[self y] doubleValue] >= 360.0 || [[self y] doubleValue] < 0.0){
int rotations = fmod([[self x] doubleValue], 360.0);
self.y = [NSNumber numberWithDouble:[[self y] doubleValue] - rotations * 360.0];
}
if ([[self y] doubleValue] >= 360.0 || [[self y] doubleValue] < 0.0){
int rotations = fmod([[self y] doubleValue], 360.0);
self.y = [NSNumber numberWithDouble:[[self y] doubleValue] - rotations * 360.0];
}
}
@end
</code></pre>
<p>BaseEntity.h</p>
<pre><code>#import <Foundation/Foundation.h>
#import "Vector3.h"
#import "RotationVector.h"
NS_ASSUME_NONNULL_BEGIN
@interface BaseEntity : NSObject
@property Vector3* position;
@property RotationVector* rotation;
- (id)init;
- (id)initWithPositionX:(NSNumber*)x Y:(NSNumber*)y Z:(NSNumber*)z;
+ (instancetype)baseEntity;
+ (instancetype)baseEntityWithX:(NSNumber*)x Y:(NSNumber*)y Z:(NSNumber*)z;
- (void)moveX:(NSNumber*)x Y:(NSNumber*)y Z:(NSNumber*)z;
- (void)moveToX:(NSNumber*)x Y:(NSNumber*)y Z:(NSNumber*)z;
- (void)rotateX:(NSNumber*)x Y:(NSNumber*)y Z:(NSNumber*)z;
- (void)rotateToX:(NSNumber*)x Y:(NSNumber*)y Z:(NSNumber*)z;
@end
NS_ASSUME_NONNULL_END
</code></pre>
<p>BaseEntity.m</p>
<pre><code>#import "BaseEntity.h"
@implementation BaseEntity
- (id)init{
if (self = [super init]){
_position = [Vector3 vector3];
_rotation = [RotationVector rotationVector];
}
return self;
}
- (id)initWithPositionX:(NSNumber*)x Y:(NSNumber*)y Z:(NSNumber*)z{
if (self = [super init]){
_position = [Vector3 vector3WithX:x Y:y Z:z];
_rotation = [RotationVector rotationVector];
}
return self;
}
+ (instancetype)baseEntity{
return [[self alloc] init];
}
+ (instancetype)baseEntityWithX:(NSNumber*)x Y:(NSNumber*)y Z:(NSNumber*)z{
return [[self alloc] initWithPositionX:x Y:y Z:z];
}
- (NSString*)description{
return [NSString stringWithFormat:@"Entity with pos: (%@, %@, %@) rot:(%@, %@, %@)",
[[self position] x],
[[self position] y],
[[self position] z],
[[self rotation] x],
[[self rotation] y],
[[self rotation] z]];
}
- (void)moveX:(NSNumber*)x Y:(NSNumber*)y Z:(NSNumber*)z{
[[self position] addX:x Y:y Z:z];
}
- (void)moveToX:(NSNumber*)x Y:(NSNumber*)y Z:(NSNumber*)z{
[[self position] setX:x Y:y Z:z];
}
- (void)rotateX:(NSNumber*)x Y:(NSNumber*)y Z:(NSNumber*)z{
[[self rotation] addX:x Y:y Z:z];
}
- (void)rotateToX:(NSNumber*)x Y:(NSNumber*)y Z:(NSNumber*)z{
[[self rotation] setX:x Y:y Z:z];
}
@end
</code></pre>
<p>main.m</p>
<pre><code>#import <Foundation/Foundation.h>
#import "BaseEntity.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
NSLog(@"Hello, World!");
BaseEntity* entity1 = [BaseEntity baseEntity];
BaseEntity* entity2 = [BaseEntity baseEntityWithX:[NSNumber numberWithDouble:10.0]
Y:[NSNumber numberWithDouble:10.0]
Z:[NSNumber numberWithDouble:10.0]];
NSLog(@"Entity #1: %@",entity1);
NSLog(@"Entity #2: %@",entity2);
[entity1 moveToX:[NSNumber numberWithDouble:5.0]
Y:[NSNumber numberWithDouble:6.0]
Z:[NSNumber numberWithDouble:7.0]];
[entity1 rotateToX:[NSNumber numberWithDouble:3.0]
Y:[NSNumber numberWithDouble:2.0]
Z:[NSNumber numberWithDouble:1.0]];
[entity2 rotateToX:[NSNumber numberWithDouble:3.0]
Y:[NSNumber numberWithDouble:2.0]
Z:[NSNumber numberWithDouble:1.0]];
[entity2 moveX:[NSNumber numberWithDouble:5.0]
Y:[NSNumber numberWithDouble:6.0]
Z:[NSNumber numberWithDouble:7.0]];
[entity2 rotateX:[NSNumber numberWithDouble:3.0]
Y:[NSNumber numberWithDouble:2.0]
Z:[NSNumber numberWithDouble:1.0]];
NSLog(@"Entity #1: %@",entity1);
NSLog(@"Entity #2: %@",entity2);
}
return 0;
}
</code></pre>
<p>Everything works fine and produces the output:</p>
<pre><code>2019-06-07 16:49:51.525097-0600 ObjCProj[57486:829658] Hello, World!
2019-06-07 16:49:51.525371-0600 ObjCProj[57486:829658] Entity #1: Entity with pos: (0, 0, 0) rot:(0, 0, 0)
2019-06-07 16:49:51.525404-0600 ObjCProj[57486:829658] Entity #2: Entity with pos: (10, 10, 10) rot:(0, 0, 0)
2019-06-07 16:49:51.525456-0600 ObjCProj[57486:829658] Entity #1: Entity with pos: (5, 6, 7) rot:(3, 2, 1)
2019-06-07 16:49:51.525479-0600 ObjCProj[57486:829658] Entity #2: Entity with pos: (15, 16, 17) rot:(6, 4, 2)
Program ended with exit code: 0
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T03:24:46.163",
"Id": "429317",
"Score": "1",
"body": "The current question title, which states your concerns about the code, is too general to be useful here. 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."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T13:32:17.847",
"Id": "429358",
"Score": "0",
"body": "If you are just coming into IOS programming it might be better to learn Swift rather than Objective-C."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T16:39:28.093",
"Id": "429381",
"Score": "1",
"body": "@pacmaninbw I already am fluent in swift. This is just for fun and learning"
}
] | [
{
"body": "<p>You asked:</p>\n\n<blockquote>\n <p>when do I use <code>entity.position</code> vs <code>[entity position]</code>?</p>\n</blockquote>\n\n<p>The former is syntactic sugar for the latter, used with properties. I personally use <code>.</code> notation when dealing with <code>@property</code>, and otherwise use <code>[</code>...<code>]</code> syntax. But this is a matter of opinion, so use your own good judgment. I’d only suggest consistency throughout your project.</p>\n\n<blockquote>\n <p>when do I use <code>NSNumber</code> vs <code>double</code></p>\n</blockquote>\n\n<p>Use <code>NSNumber</code> when you need an object. A few cases:</p>\n\n<ul>\n<li>if the values might go into a <code>NSArray</code> or other collection;</li>\n<li>if you you want to use with <code>NSNumberFormatter</code>;</li>\n<li>where the numeric value is not required and you’d like to distinguish between <code>nil</code> and <code>NSNumber</code> and you want to avoid magical “sentinel” values in your code.</li>\n</ul>\n\n<p>If you don’t need object behaviors, then feel free to use <code>double</code>, especially where doing something computationally intensive.</p>\n\n<blockquote>\n <p>when do I use <code>int</code> vs <code>NSInteger</code> ...</p>\n</blockquote>\n\n<p>Generally prefer <code>NSInteger</code> over <code>int</code>, unless there’s some reason that you need to specify the <code>int</code> type explicitly. See <a href=\"https://stackoverflow.com/a/4445199/1271826\">https://stackoverflow.com/a/4445199/1271826</a>.</p>\n\n<blockquote>\n <p>... vs <code>NSNumber</code></p>\n</blockquote>\n\n<p>See <code>double</code>/<code>NSNumber</code> discussion.</p>\n\n<blockquote>\n <p>can I hide methods from super class as <code>RotationalVector</code> can do <code>[RotationalVector vector3]</code> but I would like for it to be only able to use <code>[RotationalVector rotationalVector]</code></p>\n</blockquote>\n\n<p>In general, we tend to want to follow the “<a href=\"https://en.wikipedia.org/wiki/Liskov_substitution_principle\" rel=\"nofollow noreferrer\">Liskov substitution principle</a>”, (LSP) where anywhere you used the base class you should be able to use a subclass. The notion of “hiding” some behavior of the parent is contrary to this notion.</p>\n\n<p>And before you go down the road of “well, instead of hiding, I can just change the behavior of the parent’s method,” that would violate the “<a href=\"https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle\" rel=\"nofollow noreferrer\">Open-closed principle</a>”, another guiding design principle.</p>\n\n<blockquote>\n <p>within an instance method whats the difference between <code>_x</code>, <code>[self x]</code> and <code>self.x</code></p>\n</blockquote>\n\n<p><code>self.x</code> is simply syntactic sugar for <code>[self x]</code>. As discussed above, you’d tend to use the former for properties.</p>\n\n<p>Re <code>_x</code>, that is bypassing the accessor methods (getters/setters) and interacting with the instance variable (ivar) directly. That’s in contrast to <code>self.x</code> (and <code>[self x]</code>), which are interacting with the accessor methods (getters and setters), which is a higher level of abstraction. In general, the <code>self.x</code> pattern offers better future-proofing of your code (e.g. if you decide to implement custom getters and setters at some future date, it saves you from pouring through your code for when you bypassed the accessor methods and interacted directly with the ivar). </p>\n\n<p>You just want to avoid using <code>self.x</code> pattern inside the getters/setters for <code>x</code> (or else you can end up with infinite recursion). And, arguably, you should avoid it inside your initializer method, too. </p>\n\n<blockquote>\n <p>would it be a good idea to only include <code>init</code> methods in the .m file?</p>\n</blockquote>\n\n<p>The implementation of the <code>init</code> methods (as do the implementations of all methods) belong in <code>.m</code> file. The declaration of the <code>init</code> methods belongs in the <code>.h</code> file if you choose to expose that initializer to other classes. Think of the <code>.h</code> as your “public interface” for your class and the <code>.m</code> is for implementations (and any private interfaces).</p>\n\n<blockquote>\n <p>am I using proper return types for init and factory method?</p>\n</blockquote>\n\n<p>I’d suggest using <code>instancetype</code> in both cases for consistency’s sake, though the compiler is smart enough to infer <code>instancetype</code> when the method starts with <code>init</code>. But definitely use <code>instancetype</code> for your class methods, especially if you might subclass this class in the future.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T18:07:53.540",
"Id": "429614",
"Score": "0",
"body": "This was exactly what I was hoping for, thank you for explaining so thoroughly! I hope this will help others as well. One follow up question, is the _x only because I used the @property(Macro?)? Or do all instance variables prepend an underscore for when you are directly accessing? Once again thanks, this was a great help!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T18:14:24.483",
"Id": "429617",
"Score": "0",
"body": "Also is there any modern Obj-C books you would recommend or should I continue learning off Apple Developer documentation and online tutorials?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T18:19:58.767",
"Id": "429621",
"Score": "0",
"body": "When you declare a `@property` it “synthesizes” an ivar for your with the leading `_` underscore. If you manually declare your own ivars (e.g. for something that is not a property), it will not prepend anything, using exactly what you specified."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T18:22:13.563",
"Id": "429624",
"Score": "0",
"body": "Re resources, that’s off topic for this forum, but Apple’s documentation and WWDC videos are a great place to start. I’m sure there are good books out there, but make sure you get the most contemporary rendition as older resources show old patterns that are now discouraged and/or are obsolete. Also, Stack Overflow has tons of information for Objective-C (e.g. all of the above has been covered there extensively)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T16:52:25.633",
"Id": "222033",
"ParentId": "221889",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "222033",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-07T23:17:48.343",
"Id": "221889",
"Score": "-2",
"Tags": [
"beginner",
"objective-c",
"coordinate-system"
],
"Title": "3D vectors in Objective C"
} | 221889 |
<p>I am looking for a way to transform JSON data into a flat "csv-like" data object. In some way, I am looking to "sqlirize" a mongodb collection. I have already check some json flat libraries in NPM but non of them quite solve my problem. I have solved it in my own way but wanted to know if there is a more efficient way.</p>
<p>I have a collection that presents the data through an API in the following way:</p>
<pre><code>[{
"data": {
"name": "John",
"age": 23,
"friends": [{
"name": "Arya",
"age": 18,
"gender": "female"
}, {
"name": "Sansa",
"age": 20,
"gender": "female"
}, {
"name": "Bran",
"age": 17,
"gender": "male"
}]
}
}, {
"data": {
"name": "Daenerys",
"age": 24,
"friends": [{
"name": "Grey Worm",
"age": 20,
"gender": "male"
}, {
"name": "Missandei",
"age": 17,
"gender": "female"
}]
}
}]
</code></pre>
<p>This is the function that I have created to reflat a safe-flattened json (e.i.: everything is flattened except arrays)</p>
<pre class="lang-js prettyprint-override"><code>const { cloneDeep } = require('lodash')
const flatten = require('flat')
const reflatten = (items) => {
const reflatted = []
items.forEach(item => {
let array = false
for (const key of Object.keys(item)) {
if (Array.isArray(item[key])) {
array = true
const children = Array(item[key].length).fill().map(() => cloneDeep(item))
for (let i = 0; i < children.length; i++) {
const keys = Object.keys(children[i][key][i])
keys.forEach(k => {
children[i][`${key}.${k}`] = children[i][key][i][k]
})
delete children[i][key]
reflatted.push(children[i])
}
break
}
}
if (!array) {
reflatted.push(item)
}
})
return reflatted.length === items.length
? reflatted
: reflatten(reflatted)
}
const rows = []
for (const item of items) {
const flat = [flatten(item)]
rows.push(...reflatten(flat)]
}
console.log(rows)
</code></pre>
<p>The expected (and current) output is the following:</p>
<pre><code>[{
"data.name": "John",
"data.age": 23,
"data.friends.name": "Arya",
"data.friends.age": 18,
"data.friends.gender": "female"
}, {
"data.name": "John",
"data.age": 23,
"data.friends.name": "Sansa",
"data.friends.age": 20,
"data.friends.gender": "female"
}, {
"data.name": "John",
"data.age": 23,
"data.friends.name": "Bran",
"data.friends.age": 17,
"data.friends.gender": "male"
}, {
"data.name": "Daenerys",
"data.age": 24,
"data.friends.name": "Grey Worm",
"data.friends.age": 20,
"data.friends.gender": "male"
}, {
"data.name": "Daenerys",
"data.age": 24,
"data.friends.name": "Missandei",
"data.friends.age": 17,
"data.friends.gender": "female"
}]
</code></pre>
<p>Although I achieved the expected output, I keep wondering if there are other libraries there or if there is a more efficient way of doing it.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T00:39:27.383",
"Id": "221890",
"Score": "3",
"Tags": [
"javascript",
"recursion",
"node.js",
"json"
],
"Title": "JSON flattening with object duplication on array property for CSV generation"
} | 221890 |
<p>I have modified a particle system to create an effect similar to the one that I want. However, with any substantial amount of particles it performs very slowly on my laptop (around 1.7 fps at the worst when I remove the if statement limiting the creation of new particles). I'm guessing that this is because all the work is on the CPU? Can I batch together the processing somehow?</p>
<p><a href="https://jsfiddle.net/Zeaklous/uLzp0n8g/11/" rel="noreferrer">Demo here</a>.</p>
<pre><code>// Based on https://github.com/benjaminmbrown/particle-system-repeller
var Repeller = function(x, y) {
this.power = 500;
this.position = createVector(x, y);
this.display = function() {
stroke(0);
strokeWeight(2);
fill(127);
ellipse(this.position.x, this.position.y, 40, 40);
}
this.repel = function(p) {
var dir = p5.Vector.sub(this.position, p.position);
var d = dir.mag();
dir.normalize(); //just want the direction
d = constrain(d, 1, 100);
var force = -1 * this.power / (d * d);
dir.mult(force);
return dir;
}
}
var Attractor = function(x, y) {
this.power = 150;
this.position = createVector(x, y);
this.display = function() {
stroke(255);
strokeWeight(2);
fill(127);
ellipse(this.position.x, this.position.y, 40, 40);
}
this.attract = function(p) {
var force = p5.Vector.sub(this.position, p.position);
var distance = force.mag();
distance = constrain(distance, 5, 50);
force.normalize();
var strength = 1 * this.power / (distance * distance);
force.mult(strength);
return force;
}
}
function Particle(position, velObj, color) {
this.position = position.copy();
this.acceleration = createVector(0, 0.00);
this.velocity = createVector(random(velObj.xMin, velObj.xMax), random(velObj.yMin, velObj.yMax));
color = color || {r: 0, g: 0, b: 0};
this.lifespan = 255;
this.mass = 5;
this.run = function() {
this.update();
this.display();
}
this.display = function() {
stroke(255, this.lifespan); //gets more transparent as it dies
strokeWeight(2);
fill(color.r, color.g, color.b, this.lifespan);
ellipse(this.position.x, this.position.y, 4, 4);
}
this.update = function() {
this.velocity.add(this.acceleration);
this.position.add(this.velocity);
this.acceleration.mult(0);
this.lifespan -= 1.5;
}
this.isDead = function() {
return this.lifespan < 0.0 ? true : false;
}
this.applyForce = function(force) {
var f = force.copy();
f.div(this.mass);
this.acceleration.add(f);
}
}
function ParticleSystem(num, position, velObj, color) {
this.origin = position.copy();
this.particles = [];
this.run = function() {
for(var i = this.particles.length - 1; i >= 0; i--) {
var p = this.particles[i];
p.run();
if(p.isDead()) {
this.particles.splice(i, 1);
}
}
};
this.applyForce = function(force) {
for(var i = 0; i < this.particles.length; i++) {
this.particles[i].applyForce(force);
}
}
this.applyRepeller = function(r) {
for(var i = 0; i < this.particles.length; i++) {
this.particles[i].applyForce(r.repel(this.particles[i]));
}
}
this.applyAttractor = function(r) {
for(var i = 0; i < this.particles.length; i++) {
this.particles[i].applyForce(r.attract(this.particles[i]));
var p = this.particles[i];
var force = r.attract(p);
p.applyForce(force);
}
}
this.addParticle = function() {
var r = random(1);
this.particles.push(new Particle(this.origin, velObj, color));
};
}
var particleSystems = [];
var repeller, attractor;
function setup() {
createCanvas(windowWidth, windowHeight, WEBGL);
setFrameRate(60);
repeller = new Repeller(0, 0);
leftAttractor = new Attractor(0, height / 2);
rightAttractor = new Attractor(width, height / 2);
particleSystems.push(new ParticleSystem(1, createVector(width / 5, height / 2), {xMin: 0, xMax: 2, yMin: -4, yMax: 4}, {r: 0, g: 0, b: 255}));
particleSystems.push(new ParticleSystem(1, createVector(width * 4 / 5, height / 2), {xMin: -2, xMax: 0, yMin: -4, yMax: 4}, {r: 255, g: 0, b: 0}));
// Ones not affected by attractor
particleSystems.push(new ParticleSystem(1, createVector(width / 5, height / 2), {xMin: -2, xMax: 1, yMin: -2, yMax: 2}, {r: 0, g: 0, b: 255}));
particleSystems.push(new ParticleSystem(1, createVector(width * 4 / 5, height / 2), {xMin: -1, xMax: 2, yMin: -2, yMax: 2}, {r: 255, g: 0, b: 0}));
}
var numDraws = 0;
function draw() {
background(255);
// var gravity = createVector(0.0, 0.1);
translate(-windowWidth / 2, -windowHeight / 2);
for(var i = 0; i < particleSystems.length; i++) {
// particleSystems[i].applyForce(gravity);
particleSystems[i].applyRepeller(repeller);
if(i === 0) {
particleSystems[i].applyAttractor(rightAttractor);
} else if(i === 1) {
particleSystems[i].applyAttractor(leftAttractor);
}
// if(numDraws % 3 === 0 || i < 2)
particleSystems[i].addParticle();
particleSystems[i].run();
}
repeller.display();
numDraws++;
}
function mouseMoved() {
repeller.position = createVector(mouseX, mouseY);
}
function touchMoved() {
repeller.position = createVector(mouseX, mouseY);
}
</code></pre>
<p>Any insight as to how to improve this performance is appreciated. </p>
| [] | [
{
"body": "<p>You might be able to improve performance by removing particles once they have left the boundaries of the screen. This should reduce your particle count substantially.</p>\n\n<p>Another option to pursue would be to use <code>getFrameRate</code> to check your current frame rate against a target value and reduce the number of particles you generate based on that.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T05:34:17.953",
"Id": "221904",
"ParentId": "221891",
"Score": "2"
}
},
{
"body": "<h2>Performance</h2>\n\n<ol>\n<li><p>The main reason for the slow down are the state changes you incur each time you change the color and transparency of the particle (which is each particle). Unless you are prepared to write some shaders (webGL) you are not going to get past this problem. You will need to sacrifice some features to get performance.</p></li>\n<li><p>The second reason for the slowdown is that P5 is as slow as they get, I mean snails can draw faster than p5. </p>\n\n<p>For example the call to <code>var dir = p5.Vector.sub(this.position, p.position);</code> subtract one vector from another. With P5 you have to execute 13 lines of code, assign memory for new two arrays, one new vector, go through 4 branching statements and you get back a 3D vector.</p>\n\n<p>It can be done in 2 expressions and 100 times faster.</p></li>\n<li><p>You loop over ever particle ever time you do something to it. If you want performance you need to have as little overhead as you can manage. Loops are overhead so do everything in one pass.</p></li>\n<li><p>JavaScripts memory management is s slow. If you are creating many short lived objects you have to avoid deleting them when you are done with them. </p>\n\n<p>Eg You splice out a particle when its dead with <code>this.particles.splice(i, 1);</code> so GC must clean it up. Then you create a new particle with <code>this.particles.push(new Particle(this.origin, velObj, color));</code> </p>\n\n<p>Memory is cheap and plentifully, CPU cycles are not, so for performance sections of your code you should reuse objects rather than delete then. Only grow arrays never shorten them.</p>\n\n<p>Nor should you splice from arrays in performance code. When you splice Javascript has to move every item above the splice point down one. And if the array size falls below half its size, it will dump the reserved space for GC to clean up. Then if you add one item javascript will ask for all that memory back. This can be very costly.</p></li>\n</ol>\n\n<h2>Rewrite</h2>\n\n<p>This can be done in webGL but with a few modifications the standard 2D API does it very well.</p>\n\n<ul>\n<li><p>To avoid state changes particles do not fade out but rather change size. That means all the particles from a single particle system can be rendered in one go (one state change). This gives you 10 time + improvement in rendering speed.</p></li>\n<li><p>To avoid memory allocation and GC overhead particles are in two arrays. There is a <code>pool</code> that contains dead particles. When a particle is dead it is moved to the pool, the iterator in <code>Particles.run</code> has two indexes and keeps the main array packed with live particles. It never deletes anything while in the main loop.</p>\n\n<p>Rather than use the array length property, <code>count</code> and <code>deadCount</code> hold the number of usable particles. Note do not use particles above there counts as what they reference is unknown and can not be trusted.</p></li>\n<li><p>To avoid overhead for vector math most of its done inline and vectors are stored in a very simple <code>Vec</code> object or anything that has a <code>x</code>, or <code>y</code> property. (unlike p5 which refuses to handle anything but defined vectors (Crazzy))</p></li>\n</ul>\n\n<p>I have doubled the particle count in this example compared to the one you provided in the question.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const ctx = canvas.getContext(\"2d\");\n\nconst mouse = {x : 0, y : 0}\nfunction mouseEvents(e){\n mouse.x = e.pageX;\n mouse.y = e.pageY;\n}\ndocument.addEventListener(\"mousemove\", mouseEvents);\n\nMath.TAU = Math.PI * 2;\nMath.rand = (min, max) => Math.random() * (max - min) + min;\nconst Vec = (x, y) => ({x,y}); // Simple vector object\nconst mousePos = Vec(0,0);\nconst particleSystems = [];\nvar repeller, numDraws = 0, width, height;\n\nsetTimeout(setup, 0); // Just waits for all objects to be defined\nfunction setup() {\n width = canvas.width = innerWidth;\n height = canvas.height = innerHeight;\n particleSystems.length = 0;\n\n \n repeller = Force(mouse, -500, 2, 100);\n const leftAttractor = Force(Vec(0, height / 2), 1150, 5, 50);\n const rightAttractor = Force(Vec(width, height / 2), 1150, 5, 50);\n\n\n particleSystems.push(Particles({origin : Vec(width / 5, height / 2), min: Vec(-4,-4), max: Vec(0, 4)}, \"#00F\", [repeller, rightAttractor]));\n particleSystems.push(Particles({origin : Vec(width * 4 / 5, height / 2), min: Vec(0,-4), max: Vec(4, 4)}, \"#F00\", [repeller, leftAttractor]));\n \n // Ones not affected by attractor\n particleSystems.push(Particles({origin : Vec(width / 5, height / 2), min: Vec(-2,-2), max: Vec(1, 2)}, \"#0FF\", [repeller]));\n particleSystems.push(Particles({origin : Vec(width * 4 / 5, height / 2), min: Vec(-1,-2), max: Vec(2, 2)}, \"#FF0\", [repeller]));\n\n requestAnimationFrame(draw);\n}\n\nfunction draw() {\n if (width !== innerWidth || height !== innerHeight) { // check for resize\n setTimeout(setup, 0); \n return;\n }\n ctx.fillStyle = \"#FFF\";\n ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);\n\n for(const system of particleSystems) {\n system.addParticle();\n system.addParticle();\n system.run();\n }\n repeller.display();\n numDraws++;\n requestAnimationFrame(draw); // At fixed rate of 60Fps if it can\n}\n\nfunction Force(pos, force, min, max) { // force negative to repel, positive to attract\n min *= min; // raise to power 2\n max *= max;\n var x,y,d,d2; // working variables created so they do not need to be created each call to repel\n return {\n display() {\n ctx.strokeStyle = \"#000\";\n ctx.fillStyle = \"#9999\" // yes 4 the last digit is alpha\n ctx.globalAlpha = 1;\n ctx.lineWidth = 2;\n ctx.beginPath();\n ctx.arc(pos.x, pos.y, 30, 0, Math.TAU);\n ctx.fill();\n ctx.stroke();\n },\n apply(p) { // p is particle \n x = pos.x - p.x;\n y = pos.y - p.y;\n d = Math.sqrt(d2 = x * x + y * y) * p.mass; \n d2 = force / (d2 < min ? min : d2 > max ? max : d2) / d;\n p.ax += x * d2;\n p.ay += y * d2;\n }\n };\n}\n\nfunction Particle() {}\nParticle.prototype = { // Use prototype when creating many instances\n init(emitter) {\n this.x = emitter.origin.x;\n this.y = emitter.origin.y;\n this.life = 255;\n this.mass = 5;\n this.vx = Math.rand(emitter.min.x, emitter.max.x); \n this.vy = Math.rand(emitter.min.y, emitter.max.y); \n this.ay = this.ax = 0;\n },\n display() {\n const size = (this.life / 255) * 4; \n if (size < 2) { // draw faster rect when too small to discern\n ctx.rect(this.x - size / 2, this.y - size / 2, size, size)\n } else {\n ctx.moveTo(this.x + size, this.y);\n ctx.arc(this.x, this.y, size, 0, Math.TAU);\n }\n },\n update() { // return true if dead\n this.x += (this.vx += this.ax);\n this.y += (this.vy += this.ay);\n this.ay = this.ax = 0;\n return (this.life -= 1.5) <= 0;\n },\n}\n\n\nfunction Particles(emitter, color, forces) {\n const particles = []; // holds live particles\n var count = 0;\n var deadCount = 0;\n const pool = []; // holds dead particles\n return {\n run() {\n var i = 0, top = 0;\n ctx.beginPath(); // prep state change and start defining paths\n ctx.fillStyle = color;\n while (top < count) {\n const p = particles[i] = particles[top];\n for (const force of forces) { force.apply(p) }\n if (p.update()) { \n pool[deadCount++] = p;\n } else {\n p.display();\n i ++;\n }\n top++;\n }\n ctx.fill(); // applies the state and renders\n count = i;\n },\n addParticle() {\n if (deadCount > 0) { \n p = pool[--deadCount]; // get from pool if available\n } else {\n p = new Particle(); // else create a new one\n }\n p.init(emitter);\n particles[count++] = p;\n },\n };\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>canvas { position : absolute; top : 0px; left : 0px; }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><canvas id=\"canvas\"></canvas></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T14:19:44.013",
"Id": "429369",
"Score": "0",
"body": "Thanks for the feedback and help! I will be looking into the details but this seems like a much better approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T00:07:11.810",
"Id": "429520",
"Score": "0",
"body": "I'm trying to make it responsive in a perfectly circular shape by sizing the width and height on the minimum of the two and changing the force parameter of the attractors by a polynomial (`size * i`). However, the force does not seem to scale in this way. Where'd you get the Force.apply math from? That would help me understand how to scale the force based on the size. [Demo of where I'm at here](https://jsfiddle.net/Zeaklous/uLzp0n8g/22/)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T03:02:35.517",
"Id": "429526",
"Score": "0",
"body": "@ZachSaucier Its just a simplification of your original force function. I applied the particle mass and then added directly to the acceleration. Rather than normalize the direction vector separately I put the normalization scalar into `d2` that then multiplies `x`,`y` to give the acceleration"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T07:50:14.393",
"Id": "221912",
"ParentId": "221891",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": "221912",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T01:15:06.823",
"Id": "221891",
"Score": "6",
"Tags": [
"javascript",
"performance",
"canvas",
"processing"
],
"Title": "Improving particle performance in P5.js"
} | 221891 |
<p>These are the first lines of code I've ever written. I've been interested in the idea of learning to program for quite a while, but never really pulled the trigger, and now I've been playing around with some HTML & CSS and thought this might be a good starter project. So after a couple of days of furious googling, I managed to cobble this script together.</p>
<p>What I'm mostly curious about is the overall logic and structure of the code. The whole script grew organically from me looking up the Bash constructs and figuring out how to combine them to do what I want, so I don't know how sensible it is from the programming standpoint.</p>
<p>The idea is to keep the script in my project's folder and use relative paths, so I can just run it when I need to regenerate the CSS.</p>
<pre class="lang-bsh prettyprint-override"><code>#!/bin/bash
# CSS ruleset template:
#
# .________::before { background-image: url(data:________;base64,__________); }
# filename mimetype base64 str
#
# CSS class names and other identifiers can contain the characters
# A-Z, a-z, 0-9, hyphen, underscore and Unicode characters U+00A0 and higher.
# They cannot start with a digit, two hyphens or a hyphen followed by a digit.
# (https://www.w3.org/TR/CSS2/syndata.html#characters)
#
# url(), unquoted, requires escaping the characters ()'" and whitespace.
# url('') & url("") require escaping newlines and the quote used for quoting.
# (https://www.w3.org/TR/CSS2/syndata.html#uri)
#
# Base64 encoding uses characters A-Z, a-z, 0-9 and any two of these: +-.,:/_~
# Therefore, there's never need to escape anything, so no quotes are necessary.
css_path="icons.css" # relative to the script
cd "${BASH_SOURCE%/*}"
: > "$css_path"
for file in icons/*; do
echo Processing "$file"
filename="$(name_ext="${file##*/}"; echo "${name_ext%.*}")"
ext="${file##*.}"
shopt -s nocasematch
case "$ext" in
avif ) mime="image/avif" ;;
bmp ) mime="image/bmp" ;;
gif ) mime="image/gif" ;;
jpg | jpeg) mime="image/jpeg" ;;
png ) mime="image/png" ;;
svg ) mime="image/svg+xml";;
* ) mime="unsupported" ;;
esac
if [[ "$mime" = "unsupported" ]]; then
unsupported+=("$file")
elif [[ ! "$filename" =~ ^-?[A-Za-z_][A-Za-z0-9_-]*$ ]]; then
invalid_class_name+=("$file")
else
base64str="$(base64 --wrap=0 "$file")"
printf ".%s::before { background-image: url(data:%s;base64,%s); }\n" \
"$filename" "$mime" "$base64str" \
>> "$css_path"
fi
done
if [[ -z "$unsupported" && -z "$invalid_class_name" ]]; then
echo "All done!"
else
if [[ -n "$unsupported" ]]; then
printf "\n\n%s\n\n" "UNSUPPORTED FILES (SKIPPED)"
printf " %s\n" "${unsupported[@]}"
fi
if [[ -n "$invalid_class_name" ]]; then
printf "\n\n%s\n" "FILENAMES INVALID AS CSS CLASS NAMES (SKIPPED)"
printf " %s\n" "Allowed characters: A-Z, a-z, 0-9, '-', '_'"
printf " %s\n\n" "Can't begin with: 0-9, '--', '-0' through '-9'"
printf " %s\n" "${invalid_class_name[@]}"
fi
fi
<span class="math-container">```</span>
</code></pre>
| [] | [
{
"body": "<blockquote>\n<pre><code>cd \"${BASH_SOURCE%/*}\"\n\n: > \"$css_path\"\n</code></pre>\n</blockquote>\n\n<p>What happens if <code>cd</code> fails? Nothing good. Make a habit of always, always testing the result of <code>cd</code> (and synonyms like <code>pushd</code>) for failure. Bash's <code>-e</code> switch will promote all error exits to fatal script errors; a less extreme approach is simply:</p>\n\n<pre><code>cd … || exit 1\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>if [[ -z \"$unsupported\" && -z \"$invalid_class_name\" ]]\n</code></pre>\n</blockquote>\n\n<p>This is testing the <em>first elements</em> of these two arrays for zero length. You want to test the lengths of the arrays instead. </p>\n\n<p>When testing for zero, the use of arithmetic <code>(( … ))</code> is a nice touch: it returns truth for non-zero and false for zero. </p>\n\n<p>When a conditional includes an <code>else</code> block, avoid negating the condition. In other words: prefer <code>if x then yes else no</code> over <code>if not x then no else yes</code>.</p>\n\n<pre><code> if (( ${#unsupported[@]} || ${#invalid_class_name[@]} )) \n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>filename=\"$(name_ext=\"${file##*/}\"; echo \"${name_ext%.*}\")\"\next=\"${file##*.}\"\n</code></pre>\n</blockquote>\n\n<p>This is awkward. Most of the fault rests with Bash itself. A regular expression is a little cleaner:</p>\n\n<pre><code>[[ $file =~ ([^/]*)\\.([^.]*)$ ]] && filename=${BASH_REMATCH[1]} ext=${BASH_REMATCH[2]}\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>if [[ \"$mime\" = \"unsupported\" ]]; then\n</code></pre>\n</blockquote>\n\n<p>Quotes aren't needed around variables (or literal strings that lack whitespace) inside <code>[[ … ]]</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> printf \".%s::before { background-image: url(data:%s;base64,%s); }\\n\" \\\n \"$filename\" \"$mime\" \"$base64str\" \\\n >> \"$css_path\"\n</code></pre>\n</blockquote>\n\n<p>It's good practice to indent continuations. In the specific case of <code>printf</code>, it can be helpful to align variables with their format-string placeholders.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>unsupported+=(\"$file\")\n\ninvalid_class_name+=(\"$file\")\n</code></pre>\n</blockquote>\n\n<p>If these exist in the shell that invokes your script, their initial values will persist and muck things up. Make a habit of zeroing variables you intend to append to (or increment, etc.). At the same time, improve readability by expressly declaring your arrays as such: </p>\n\n<pre><code>declare -a unsupported=() invalid_class_name=()\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>: > \"$css_path\"\n</code></pre>\n</blockquote>\n\n<p>This could be annoying if the script fails. Consider taking a backup of the output file before zeroing it, and restoring the backup on error exit.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T06:32:18.250",
"Id": "221907",
"ParentId": "221895",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T02:31:22.010",
"Id": "221895",
"Score": "7",
"Tags": [
"beginner",
"css",
"image",
"bash",
"base64"
],
"Title": "Bash script to encode images in base64 and generate a CSS file from them"
} | 221895 |
<p>I have a <code>malloc()</code> implementation that relies purely on <code>mmap</code>. I'm fairly sure that it doesn't overwrite any of the internal structures or have any other breaking issues, but I'm not totally sure about that.</p>
<p>Some details:</p>
<ul>
<li><code>__PTRx__</code> (where <code>x</code> is <code>16</code>, <code>32</code>, or <code>64</code>) is defined when a pointer is <code>x</code> bits in size.</li>
<li>I would appreciate any notes as to if this isn't ISO C or POSIX-compatible.</li>
<li>I'm going for compiled code-size.</li>
<li>Please, no notes on <code>goto</code>.</li>
</ul>
<p>Here's the code:</p>
<p>allocation.c:</p>
<pre><code>#include <unistd.h>
#include <stddef.h>
#include <sys/mman.h>
#include "malloc.h"
int __get_next_allocation(size_t size)
{
size_t ctr = 0;
int found_allocation = 0;
struct allocation_info *tmp_alloc = NULL;
struct malloc_chunk *tmp_chnk = NULL;
if(!__mallchunk)
if(__get_next_chunk())
return -1;
if(!__allocinfo)
__allocinfo = __mallchunk->start;
tmp_alloc = __allocinfo;
tmp_chnk = __mallchunk;
while(tmp_chnk->prev != NULL)
tmp_chnk = tmp_chnk->prev;
for(ctr = 0;
ctr < tmp_chnk->alloc_cnt && tmp_alloc;
ctr++, tmp_alloc = tmp_alloc->next)
{
if( tmp_alloc->free &&
tmp_alloc->size >= size )
{
found_allocation = 1;
tmp_alloc->prev->next = tmp_alloc->next;
tmp_alloc->next->prev = tmp_alloc->prev;
tmp_alloc->next = NULL;
break;
}
}
if(!found_allocation)
{
if((size_t)(__allocinfo->start - __mallchunk->start)
> ((CHUNK_SIZE - size) - sizeof(*tmp_alloc)))
{
if(__get_next_chunk())
return -1;
tmp_alloc = __mallchunk->start;
}
else
{
tmp_alloc = __allocinfo->start +
__allocinfo->size;
}
tmp_alloc->start = (void *)tmp_alloc
+ sizeof(*tmp_alloc);
tmp_alloc->next = NULL;
}
__allocinfo->next = tmp_alloc;
__allocinfo->next->prev = __allocinfo;
__allocinfo = __allocinfo->next;
__allocinfo->size = size;
__allocinfo->free = 0;
__mallchunk->alloc_cnt++;
return 0;
}
</code></pre>
<p>calloc.c:</p>
<pre><code>#include <stddef.h>
#include <stdlib.h>
#include <string.h>
void *calloc(size_t nmemb, size_t size)
{
void *ret;
if(size % 2) size++;
if(nmemb % 2) nmemb++;
size *= nmemb;
ret = malloc(size);
if(!ret) return NULL;
return memset(ret, 0, size);
}
</code></pre>
<p>chunk.c:</p>
<pre><code>#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <stddef.h>
#include <stdlib.h>
#include <sys/mman.h>
#include "malloc.h"
int __get_next_chunk(void)
{
struct malloc_chunk *mallchunk = mmap(NULL,
CHUNK_SIZE,
PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS,
-1,
0);
if(mallchunk == MAP_FAILED)
{
errno = ENOMEM;
return -1;
}
if (!__mallchunk)
{
__mallchunk = mallchunk;
__mallchunk->chunk_cnt = 0;
__mallchunk->alloc_cnt = 0;
__mallchunk->prev = NULL;
__mallchunk->next = NULL;
}
else
{
__mallchunk->chunk_cnt++;
__mallchunk->next = mallchunk;
__mallchunk->next->chunk_cnt =
__mallchunk->chunk_cnt;
__mallchunk->next->prev = __mallchunk;
__mallchunk = __mallchunk->next;
__mallchunk->alloc_cnt = 0;
__mallchunk->next = NULL;
}
__mallchunk->start = (void *)__mallchunk +
sizeof(*__mallchunk);
return 0;
}
</code></pre>
<p>free.c:</p>
<pre><code>#include "malloc.h"
#include <stdlib.h>
#include <string.h>
void free(void *ptr)
{
struct allocation_info *tmp_allinfo = __allocinfo;
if(!ptr) return;
while(tmp_allinfo->prev)
tmp_allinfo = tmp_allinfo->prev;
while(tmp_allinfo && tmp_allinfo->start != ptr)
tmp_allinfo = tmp_allinfo->next;
if(!tmp_allinfo) return;
memset(tmp_allinfo->start, 0, tmp_allinfo->size);
tmp_allinfo->free = 1;
}
</code></pre>
<p>malloc.c:</p>
<pre><code>#include <stdlib.h>
#include <unistd.h>
#include "malloc.h"
void *malloc(size_t size)
{
if(__get_next_allocation(size))
return NULL;
return __allocinfo->start;
}
</code></pre>
<p>malloc.h:</p>
<pre><code>#ifndef _MALLOC_H
#define _MALLOC_H 1
#include <features.h>
#include <sys/types.h>
#ifdef __PTR16__
# define CHUNK_SIZE (0x4000) /* 16K */
#else
# define CHUNK_SIZE (0x10000) /* 64K */
#endif
struct malloc_chunk
{
void *start;
size_t alloc_cnt;
size_t chunk_cnt;
struct malloc_chunk *prev;
struct malloc_chunk *next;
};
struct allocation_info
{
void *start;
size_t size;
int free;
struct allocation_info *prev;
struct allocation_info *next;
};
extern struct malloc_chunk *__mallchunk;
extern struct allocation_info *__allocinfo;
extern int __get_next_chunk(void);
extern int __get_next_allocation(size_t size);
#endif
</code></pre>
<p>metadata.c:</p>
<pre><code>#include "malloc.h"
struct malloc_chunk *__mallchunk;
struct allocation_info *__allocinfo;
</code></pre>
<p>realloc.c:</p>
<pre><code>#include "malloc.h"
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#define LESSER(x,y) ((x) > (y) ? (y) : (x))
void *realloc(void *ptr, size_t size)
{
size_t newsize = 0;
void *newptr = malloc(size);
struct allocation_info *tmp_allinfo = __allocinfo;
if(!ptr) goto end;
while(tmp_allinfo->prev)
tmp_allinfo = tmp_allinfo->prev;
while(tmp_allinfo && tmp_allinfo->start != ptr)
tmp_allinfo = tmp_allinfo->next;
if(!tmp_allinfo)
return NULL;
newsize = LESSER(tmp_allinfo->size, size);
memcpy(newptr, ptr, newsize);
end:
free(ptr);
return newptr;
}
</code></pre>
<p>EDIT: If anybody wants to use this code, it's licensed under the LGPL: <a href="https://github.com/JL2210/minilibc.git" rel="noreferrer">link to repository</a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T03:28:02.523",
"Id": "429318",
"Score": "2",
"body": "What happens if you try to malloc 150K? That's larger than your CHUNK size. `realloc` will misbehave if the `malloc` call fails."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T04:50:18.377",
"Id": "429323",
"Score": "0",
"body": "@1201ProgramAlarm Yeah, I'm working in fixing that; for now, I'll impose a hard limit. I just fixed a bug (used `strace`, great tool) that caused this to always allocate a new block of memory every time it was called. I'll keep this as is, though, to see if somebody else catches it (and comes up with a better solution)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-17T17:28:08.220",
"Id": "430622",
"Score": "1",
"body": "No notes on `goto`? Not even to say that it's perfectly appropriate here?"
}
] | [
{
"body": "<p><strong>Unnecessary code</strong></p>\n\n<p>There is no need to make <code>size, nemb</code> even values.</p>\n\n<pre><code>if(size % 2) size++;\nif(nmemb % 2) nmemb++;\n</code></pre>\n\n<p><strong><code>__get_next_allocation(size_t size)</code> may benefit with rounding up of <code>size</code></strong></p>\n\n<p>Say you want allocations to be a multiple of 8.</p>\n\n<pre><code>#define ALLOC_MULTIPLE 8\nint __get_next_allocation(size_t size) {\n if (size % ALLOC_MULTIPLE) {\n if (size > SIZE_MAX - ALLOC_MULTIPLE) {\n return -1;\n }\n size += ALLOC_MULTIPLE - (size % ALLOC_MULTIPLE); \n }\n ...\n</code></pre>\n\n<p><strong><code>calloc()</code> does not detect overflow</strong></p>\n\n<pre><code>if (nmemb > 0 && SIZE_MAX/nmemb > size) {\n return NULL; // allocation too big.\n} \n// Now safe to multiply.\nsize *= nmemb;\n</code></pre>\n\n<p><strong>Non compliant math</strong></p>\n\n<p>In C, adding to a <code>void *</code> is UB. May be OK in Posix.</p>\n\n<pre><code>// (void *)tmp_alloc + sizeof(*tmp_alloc);\n(char *)tmp_alloc + sizeof(*tmp_alloc);\n</code></pre>\n\n<p>Note: <code>ENOMEM</code> is not ISO C.</p>\n\n<p><strong>Non compliant alignment</strong></p>\n\n<p>The value returned from <code>*alloc()</code> is expected to be aligned for all types. By adding <code>sizeof(*__mallchunk)</code>, coding may lose this vital property - thus UB. Various ways to handle this, yet code needs to insure <code>__mallchunk->start</code> has an aligned value. </p>\n\n<blockquote>\n <p>The pointer returned if the allocation succeeds is suitably aligned so that it may be assigned to a pointer to any type of object with a fundamental alignment requirement and then used to access such an object or an array of such objects in the space allocated §7.22.3 1.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-15T23:20:45.243",
"Id": "430330",
"Score": "1",
"body": "In POSIX, it's also UB. Thanks for pointing that out."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-15T20:48:07.757",
"Id": "222377",
"ParentId": "221897",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "222377",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T03:13:42.940",
"Id": "221897",
"Score": "9",
"Tags": [
"c",
"memory-management",
"memory-optimization",
"posix"
],
"Title": "Custom malloc implementation"
} | 221897 |
<p>Recently, I have been trying to improve my functional programming skills and understanding. While at work today, my coworkers and I were playing Hangman in a group chat. I thought of a program that would guess the likeliest letter in the word to guess. So I implemented it when I got home. <a href="https://github.com/Duke02/HangmanSolver" rel="nofollow noreferrer">Here</a> is the repository if you would like any more information (such as the word text file that is required for this script).</p>
<p>I would definitely appreciate comments on the readability of my code, as well as the uses of functional programming. Also, I was thinking that I may have been over commenting in my code. Is that the case?</p>
<pre><code>import re
def get_words(word_len):
# Open the file with all the words in the English language.
with open("words.txt") as word_file:
# Get all the words without any newlines.
words_temp = map(lambda s: s.strip(), word_file.readlines())
# filter the words so that they have the same number of characters as the word in play.
words = [word.lower() for word in words_temp if len(word) is word_len]
# Get rid of any possible duplicates in the file.
words = list(set(words))
return words
def get_possible_words(guesses, current_word):
# The total number of characters in the word.
num_of_characters = len(current_word)
# Load the words in from the words.txt file.
words = get_words(num_of_characters)
# Get all words with just letters.
words = list(filter(lambda w: w.isalpha(), words))
# Regex will give us an error if we have
# no wrong guesses, so if we don't need to exclude
# anything, include everything!
if len(guesses) is 0:
substitute = '.'
else:
# exclude all of the wrong guesses
substitute = f"[^{guesses}]"
# Make the current_word a regex phrase.
current_word_regex = current_word.replace('_', substitute)
# Get the regex object for the current word
regex_obj = re.compile(current_word_regex)
# Get all possible matches to the word.
possible_matches = list(map(lambda word: regex_obj.match(word), words))
# Get all the words from those matches (filter None matches)
possible_words = [match.string for match in possible_matches if match is not None]
# Print the list of possible words.
return possible_words
def get_statistics(possible_words):
# Join all of the words in the list into a giant string.
words_as_str = ''.join(possible_words)
# sort the characters in each word.
words_as_str = ''.join(sorted(words_as_str))
# get all of the characters in the words.
characters_in_words = ''.join(set(words_as_str))
# Get the frequencies of each letter in the words.
frequencies = {c: words_as_str.count(c) for c in characters_in_words}
return frequencies
def get_likeliest_letter(stats):
# Get the most likely letter to guess.
likeliest_letter = max(stats, key=stats.get)
# Get the likelihood of the letter as a percent.
likelihood = stats[likeliest_letter] / sum(stats.values()) * 100.0
return likeliest_letter, likelihood
def play_hangman():
is_playing = True
# All of the characters that the computer guessed wrong.
guesses = ""
# the number of guesses the computer has made.
num_of_guesses = 0
current_word = ""
was_correct = True
while is_playing:
# Get input from the user if the current word on the board
# changed or is new.
if was_correct:
print("What is currently on the board?")
current_word = input("(Input unknown characters with _) ").lower()
# if we found the word, we can stop playing.
if current_word.count('_') is 0:
break
# Get all of the possible words that can be guessed
possible_words = get_possible_words(guesses, current_word)
print(f"There are {len(possible_words)} possible words.")
# Print all of the possible words if there's not too many of them.
if len(possible_words) <= 10:
[print(word) for word in possible_words]
# Early exit if it we only have one guess.
if len(possible_words) is 1:
print(f"It's obviously {possible_words[0]}.")
break
# Get the frequencies of each character in the possible words.
stats = get_statistics(possible_words)
# Remove characters we've already guessed from the statistics.
[stats.pop(guessed_letter, None) for guessed_letter in guesses]
print("Your most likely letter is...")
likeliest_letter, likelihood = get_likeliest_letter(stats)
print(f"{likeliest_letter} with a likelihood of {likelihood:.2f}%")
was_correct = input("Was I correct? (y/n) ").lower() == 'y'
# add our guess to the total listing of guesses.
num_of_guesses += 1
guesses += likeliest_letter
# Print a new line to break each round up.
print("")
print(f"It took me {num_of_guesses} guesses to get it.")
if __name__ == '__main__':
play_hangman()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T04:48:30.850",
"Id": "429322",
"Score": "0",
"body": "Yup! There's definitely more comments than code :)"
}
] | [
{
"body": "<p>A starter note, throughout my answer: <code>FP = \"functional programming\"</code>.</p>\n\n<h1>Possible Improvements</h1>\n\n<p><strong>Use <code>==</code> rather than <code>is</code> for value comparisons.</strong></p>\n\n<p>I see <code>if var is number</code> in multiple places. Specifically, lines 29, 96, 109. One could argue that <code>is</code> reads better than <code>==</code>, but the two are computationally different. (<code>is</code> breaks for large numbers.) Use <code>==</code> instead. See also: <a href=\"https://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is\">Is there a difference between “==” and “is”?</a></p>\n\n<p><strong>Thinking Functionally</strong></p>\n\n<p>FP tends to avoid mutability, i.e. changing state. FP is more about telling the computer what things <em>are</em> rather than what things <em>do</em>. Here are a couple lines of code from <code>get_words</code> (lines 9-12):</p>\n\n<pre><code># filter the words so that they have the same number of characters as the word in play.\nwords = [word.lower() for word in words_temp if len(word) is word_len]\n# Get rid of any possible duplicates in the file.\nwords = list(set(words))\n</code></pre>\n\n<p>Sweet, looks innocent. But you're assigning to <code>words</code> twice... you're changing its state.</p>\n\n<p>I like how Miran Lipovača (author of a Haskell tutorial) puts it:</p>\n\n<blockquote>\n <p>[Y]ou set variable <code>a</code> to 5 and then do some stuff and then set it to something else. [...] If you say that <code>a</code> is 5, you can't say it's something else later because you just said it was 5. What are you, some kind of liar?<br>\n <sub><a href=\"http://learnyouahaskell.com/introduction\" rel=\"nofollow noreferrer\"><em>(source)</em></a></sub></p>\n</blockquote>\n\n<p>We can actually trim your two lines down to one by directly using a set comprehension and thereby eliminating the mutation of <code>words</code> (note also the replacement of <code>is</code> with <code>==</code>):</p>\n\n<pre><code>words = list({word.lower() for word in words_temp if len(word) == word_len})\n</code></pre>\n\n<p>You could even return the list directly from the function!</p>\n\n<p>Next, another interesting snippet (lines 29-33):</p>\n\n<pre><code>if len(guesses) is 0:\n substitute = '.'\nelse:\n # exclude all of the wrong guesses\n substitute = f\"[^{guesses}]\"\n</code></pre>\n\n<p>This looks innocent too! But it also resembles an imperative statement: \"if this, <code>substitute</code> is this, else <code>substitute</code> is that\". We can make this more functional by clearly defining what <code>substitute</code> is:</p>\n\n<pre><code>substitute = '.' if len(guesses) == 0 else f\"[^{guesses}]\"\n</code></pre>\n\n<p>And this reads \"<code>substitute</code> is <code>'.'</code> if this else that\". (Note how the statement is now <em>declarative</em> and the variable becomes the <em>subject</em> of the statement.)</p>\n\n<p>Yet another snippet (lines 113-117):</p>\n\n<pre><code># Get the frequencies of each character in the possible words.\nstats = get_statistics(possible_words)\n\n# Remove characters we've already guessed from the statistics.\n[stats.pop(guessed_letter, None) for guessed_letter in guesses]\n</code></pre>\n\n<p>Line 117 is a list comprehension, which is in itself functional... <strong>but</strong> it's changing the state of <code>stats</code>! Instead of removing the <em>unneeded</em> letters, make a new dictionary with the <em>needed</em> letters.</p>\n\n<p>And back to my point: with functional programming, avoid mutability, define variables as what they are and not what they do/how they come about.</p>\n\n<p><strong>Game Loop and Mutability</strong></p>\n\n<p>The game loop... ah. It's a while-loop... and this presents a couple problems.</p>\n\n<ol>\n<li>While-loops tend to be imperative construct (telling the interpreter to loop while something isn't true).</li>\n<li><p>Since this is a dynamic game and since it's a single while-loop, you'll inevitably modify the state of surrounding variables to either keep track of progress.</p>\n\n<pre><code>## Line 81 ##\n# the number of guesses the computer has made.\nnum_of_guesses = 0\n\n## Line 127 ##\n# add our guess to the total listing of guesses.\nnum_of_guesses += 1\n</code></pre>\n\n<p>Lipovača: \"But you just said <code>num_of_guesses</code> is 0!\"</p></li>\n</ol>\n\n<p>Solution? Recursion. Pass in the mutable variables as arguments to the function and recurse all the way to the end. (Or of course, you could stick with the more readable <code>while</code>-loop. Some things are inevitable – <em>sigh</em>.)</p>\n\n<p><strong>Consider using type-hints.</strong></p>\n\n<p>This is really helpful in the world of FP. What does a function receive? What does it return? This allows you to reason with the input and output of functions. See also: <a href=\"https://stackoverflow.com/questions/32557920/what-are-type-hints-in-python-3-5\">What are Type hints in Python 3.5</a></p>\n\n<p><strong>Comments</strong></p>\n\n<p>Yes, there are quite a lot. Some are unnecessary... and some of them are untruths.</p>\n\n<p>Lines 20-21:</p>\n\n<pre><code># Load the words in from the words.txt file.\nwords = get_words(num_of_characters)\n</code></pre>\n\n<p>What if the implementation of <code>get_words</code> changes? This comment becomes obsolete.</p>\n\n<p>Lines 47-48:</p>\n\n<pre><code># Print the list of possible words.\nreturn possible_words\n</code></pre>\n\n<p>No printing here. You print it sometime later in the game loop, but not here. Here, there's only a return, which in itself doesn't do any printing.</p>\n\n<p>Instead, consider commenting what each function <em>does</em>, preferably using Python doc-strings.</p>\n\n<pre><code>def get_words(word_len):\n \"\"\"\n Returns a list of words each with length equal to `word_len`.\n \"\"\"\n</code></pre>\n\n<p>As above, you can choose to leave out the details of the implementation. Sure, <code>get_words</code> will open, read, and close a file, but this won't have any side-effects<sup>1</sup>. Perhaps in the future, you might want to load the words from a database, and the doc-string won't need to be updated, because the input and output are unchanged.</p>\n\n<p><sup>1 – Unless if say, you're in a multi-threaded environment where the files will be accessed from different threads concurrently.</sup></p>\n\n<p>We also don't need the comment on line 20: <code># Load the words in from the words.txt file.</code>. We can simply scroll to <code>get_words</code> and read the doc-string to know what it does.</p>\n\n<p>See also: <a href=\"https://en.wikipedia.org/wiki/Self-documenting_code\" rel=\"nofollow noreferrer\">Self-Documenting Code</a>; <a href=\"https://stackoverflow.com/questions/209015/what-is-self-documenting-code-and-can-it-replace-well-documented-code\">What is self-documenting code and can it replace well-documented code?</a></p>\n\n<h1>The Bright Side</h1>\n\n<p>Your program still has merits:</p>\n\n<p><strong>Use of Functions</strong></p>\n\n<p>Although all your functions are used only once, the functions clearly separate individual tasks, and this aids the reader to reason about the code.</p>\n\n<p><strong>Variables</strong></p>\n\n<p>Some are slightly redundant, but the names you've given them are helpful enough to remove at least a third of the comments.</p>\n\n<p><strong>Use of f-strings</strong></p>\n\n<p>f-strings are relatively new in Python, and they're not only more convenient, but also more functional over the OOP-variants: <code>str.format</code> and the <code>%</code>-printf notation. </p>\n\n<p><strong>Use of Comprehensions</strong></p>\n\n<p>I'm seeing quite a lot of comprehensions and no for-loop blocks. This is a merit: using a for-loop block with colon and suite bears the air of imperative programming (tells the interpreter to loop over an iterable), but comprehensions are more functional as they pack your values into a handy list/set/dictionary/generator expression.</p>\n\n<p><strong>PEP 8</strong></p>\n\n<p>Formatting is superb overall. What with snake_case, spacing, double line-breaks before and after functions, and a <code>if __name__ == '__main__'</code>. All this is good practice.</p>\n\n<p>Keep it up!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T16:31:35.837",
"Id": "429379",
"Score": "1",
"body": "Thank you for your help! I'll take these suggestions and see if I can implement them. I was already thinking of using the typing module as I come from statically typed languages. Also thank you for the clarification between is and ==. I always get them confused and end up just using is."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T06:40:46.033",
"Id": "221908",
"ParentId": "221898",
"Score": "4"
}
},
{
"body": "<p>apart from TrebledJ's excellent review of the functional improvements of your code, here some general Python improvements</p>\n\n<h1>get_words</h1>\n\n<p>There is no need for this function to return a list. The rets of your code only cares that it gets an iterable, so you might as well return the set.\nYou can also avoid the lambda expression by doing <code>map(str.strip, word_file)</code>\nYou can also incorporate the <code>isalpha</code> check here. Better to filter as soon as possible</p>\n\n<p>This way this function can be reduced to:</p>\n\n<pre><code>def get_words(word_len):\n # Open the file with all the words in the English language.\n with open(\"words.txt\") as word_file:\n # Get all the words without any newlines.\n return {\n word.lower()\n for word in map(str.strip, word_file)\n if len(word) == word_len and word.isalpha()\n }\n</code></pre>\n\n<h1>get_statistics</h1>\n\n<p>Here you:</p>\n\n<ul>\n<li>glue all the wordt together to one long string</li>\n<li>get a sorted list of letters that you </li>\n<li>get the unique letters</li>\n<li>ask for each of these letters the count in the long string</li>\n</ul>\n\n<p>This is very inefficient. There is no reason for the sorting, or the <code>characters_in_words</code>. </p>\n\n<p>Also remember Python is <em>batteries-included</em>. <code>itertools.chain</code> and <code>collections.Counter</code> do all you need from this function</p>\n\n<pre><code>from itertools import chain\nfrom collections import Counter\ndef get_statistics(possible_words) -> Counter:\n return Counter(chain.from_iterable(possible_words))\n</code></pre>\n\n<h1>get_likeliest_letter</h1>\n\n<p>´collections.Counter´ also contains a <code>most_common</code> method that simplifies the ´get_likeliest_letter´</p>\n\n<pre><code>def get_likeliest_letter(stats: Counter):\n likeliest_letter, count = stats.most_common(1)[0]\n likelihood = count / sum(stats.values()) * 100.0\n return likeliest_letter, likelihood\n</code></pre>\n\n<h1>get_possible_words</h1>\n\n<p>In each call to <code>get_possible_words</code>, you read all the words in <code>words.txt</code>. Since you can assume they don't change bewteen different tries, you can cache this, and pass it in the function as argument</p>\n\n<p>There is also no need for the <code>len(guesses) == 0</code>. Just <code>guesses</code> as codition suffices. If it's an empty string, it is counted as <code>False</code></p>\n\n<p>Instead of the intermediary <code>possible_matches</code>, you can just return the list of words where <code>current_word_regex.match(word)</code> retuns a <code>match</code> object instead of <code>None</code> (which evaluates to <code>False</code>)</p>\n\n<pre><code>def get_possible_words(guesses, current_word, all_words):\n substitute = '.' if guesses else f\"[^{guesses}]\"\n # Make the current_word a regex phrase.\n current_word_regex = re.compile(current_word.replace('_', substitute))\n return [word for words in all_words if current_word_regex.match(word)]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T17:11:12.767",
"Id": "429382",
"Score": "0",
"body": "Wow I honestly didn't realize I could shave down `get_possible_words` to just 3 lines (excluding comments). Also thank you for the tips on Counter. I tend to not use a ton of the Python library excluding what I've used above, so this will definitely help me with learning more of Python. Thank you for your help!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T16:52:12.217",
"Id": "221941",
"ParentId": "221898",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "221908",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T03:18:54.467",
"Id": "221898",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"functional-programming",
"hangman"
],
"Title": "Functional Programming Hangman Practice"
} | 221898 |
<p>I did a script to extract information from the Egyptian national ID, e.g. national id is 14 digit ex(29501023201952). It could divide as described below:</p>
<pre><code>2 - 990115 - 01 - 0192 - 1
x - yymmdd - ss - iiig - z
</code></pre>
<ul>
<li><p><code>x (2)</code> is the birth century (2 represent 1900 to 1999, 3 represent 2000 to 2099 .. etc)</p></li>
<li><p><code>yymmdd (200115)</code> is the date of birth, yy(99) year,mm(01) month, dd(15) day </p></li>
<li><p><code>ss(01)</code> birth governorate coda (88 for people who born in a foreign country, 01 for who born in Cairo, ...etc )</p></li>
<li><p><code>iiig(0192)</code> the sequence in the computer between births in this birthday and </p></li>
<li><p><code>g(2)</code> represent the gender (2,4,6,8 for females and 1,3,5,7,9)</p></li>
<li><p><code>z(1)</code> number Ministry of Interior added it to validate if the National ID fake or not (1 to 9)</p></li>
</ul>
<p>I am looking for some general feedback on how I can improve the structure and efficiency of my code.</p>
<pre><code>import argparse
from datetime import datetime
import textwrap
governorates = {'01': 'Cairo',
'02': 'Alexandria',
'03': 'Port Said',
'04': 'Suez',
'11': 'Damietta',
'12': 'Dakahlia',
'13': 'Ash Sharqia',
'14': 'Kaliobeya',
'15': 'Kafr El - Sheikh',
'16': 'Gharbia',
'17': 'Monoufia',
'18': 'El Beheira',
'19': 'Ismailia',
'21': 'Giza',
'22': 'Beni Suef',
'23': 'Fayoum',
'24': 'El Menia',
'25': 'Assiut',
'26': 'Sohag',
'27': 'Qena',
'28': 'Aswan',
'29': 'Luxor',
'31': 'Red Sea',
'32': 'New Valley',
'33': 'Matrouh',
'34': 'North Sinai',
'35': 'South Sinai',
'88': 'Foreign'}
fake_national_id_message = 'This ID Not Valid'
def extract_birth_century(birth_century_code: int) -> int:
"""
extract birth century from national id it's in index 0
:param birth_century_code: one digit
:return: birth century
"""
assert type(birth_century_code) == int, 'birth century code must be int value'
current_century = get_century_from_year(int(datetime.now().year))
birth_century = birth_century_code + 18
assert (birth_century >= 19) and (birth_century <= current_century), fake_national_id_message
return birth_century
def get_century_from_year(year):
return year // 100 + 1
def convert_birthdate(birthdate: str) -> str:
"""
Convert birthday in national id from fromat yymmdd to yyyy - mm - dd format
it's from index 0 to 6 in EG national id
:param birthdate: str
format cyymmdd, c represent birth century code
:return: str
yyyy-mm-dd
"""
assert len(str(birthdate)) == 7, "birthdate must be 7 digit"
birth_century = extract_birth_century(int(birthdate[0]))
birth_year = birthdate[1:3]
birth_month = birthdate[3:5]
birth_day = birthdate[5:]
birth_full_year = (birth_century * 100) - 100 + int(birth_year)
birthdate_str = '{0}-{1}-{2}'.format(birth_full_year, birth_month, birth_day)
birthdate_date = datetime.strptime(birthdate_str, '%Y-%m-%d')
assert birthdate_date <= datetime.now() and birthdate_date >= datetime.strptime('1900-01-01','%Y-%m-%d'), fake_national_id_message
return birthdate_str
def get_birth_governorate(birth_governorate_coda: str) -> str:
"""
:param birth_governorate_coda:
Index 7 and 8 in EG national id
:return: str
Birth governorate
"""
assert type(birth_governorate_coda) == str, 'Birth governorate coda must be string not integer'
assert len(birth_governorate_coda) == 2, 'Birth governorate coda must be 2 digit'
assert birth_governorate_coda in governorates, 'Birth governorate coda not valid'
return governorates[birth_governorate_coda]
def get_gender(gender_code: int) -> str:
"""
:param gender_code:
Index 12 in EG National ID
:return: str
Gender
"""
assert type(gender_code) == int and gender_code > 0 and gender_code <= 9, 'gender code not valid'
if gender_code % 2 == 0:
return 'Female'
else:
return 'Male'
def extract_info_from_national_id(national_id: int):
"""
Extract information from national EG national ID
:param national_id: int
EG national id must be number of 14 digit
:return: dict
birth_century
date_of_birth
birth_governorate
sequence_in_computer
gender
"""
assert type(national_id) == int, "National ID must be Numbers not string"
assert len(str(national_id)) == 14, "National ID must be 14 Number "
national_id_str = str(national_id)
info ={}
info['birth_century'] = extract_birth_century(int(national_id_str[0]))
info['date_of_birth'] = convert_birthdate(national_id_str[0:7])
info['birth_governorate'] = get_birth_governorate(national_id_str[7:9])
info['sequence_in_computer'] = national_id_str[9:13]
info['gender'] = get_gender(int(national_id_str[12]))
# last_number = national_id_str[13]
return info
def print_info(information):
print('Birth Century :', information['birth_century'])
print('Date Of Birth :', information['date_of_birth'])
print('Birth Governorate :', information['birth_governorate'])
print('Gender :', information['gender'])
if __name__ == '__main__':
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,
description=textwrap.dedent('''\
Extract Information from Egyptian National ID
-----------------------------------------
Birth century
Date Of Birth
Birth Governorate
Gender
'''))
parser.add_argument('national_id', type=int,
help="Add The Egyption National ID 14 Digit")
args = parser.parse_args()
info = extract_info_from_national_id(args.national_id)
print_info(info)
</code></pre>
| [] | [
{
"body": "<p>This seems like exactly the sort of thing you would use a class for. Not just any class, but an immutable one! </p>\n\n<p>I'd suggest you create a <code>class EgyptianNationalId</code> and initialize it from a string. You could then parse out all the fields at the time of creation, and store them using read-only attributes (such as with a <a href=\"https://docs.python.org/3/library/collections.html?collections.namedtuple\" rel=\"noreferrer\"><code>namedtuple</code></a>).</p>\n\n<p>Something like this:</p>\n\n<pre><code>import collections\nfrom datetime import datetime as dt\n\n_ENID = collections.namedtuple('_ENID', 'list of fields')\n\nclass EgyptianNationalId(_ENID):\n ''' Model an Egyptian National ID string.\n\n >>> id = EgyptianNationalId('29501023201952')\n >>> 1999 in id.century\n True\n >>> id.birth_date.year == 1995\n True\n >>> id.birth_date.month\n 1\n >>> id.birth_date.day\n 2\n >>> id.birth_date.governorate\n 'New Valley'\n ''' \n century = {\n '1': range(1800, 1900),\n '2': range(1900, 2000),\n '3': range(2000, 2100),\n '4': range(2100, 2200),\n }\n\n @classmethod\n def from_str(cls, s):\n fields = cls.parse_str(s)\n return cls(*fields)\n\n @classmethod\n def parse_str(cls, s):\n scent = s[0]\n syymmdd = s[1:7]\n ... other fields ...\n\n birth_date = dt.strptime(syymmdd, '%y%m%d')\n # TODO: Validate birth_date, maybe against century?\n\n fields = (\n cls.century[scent],\n birth_date,\n ... other fields ...\n )\n return fields\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-12T03:27:40.420",
"Id": "429803",
"Score": "0",
"body": "Perhaps a `dataclass` then?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-12T17:54:53.900",
"Id": "429909",
"Score": "0",
"body": "A dataclass could work, if the python version is high enough."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T04:33:09.627",
"Id": "221900",
"ParentId": "221899",
"Score": "6"
}
},
{
"body": "<p>At first: well done, your code quality is already at a high level!\nHere are some remarks that you could integrate besides the class approach mentioned before.</p>\n\n<h3>The <code>assert</code> statement works only if python is in debug mode</h3>\n\n<p>It's not running when you interpret it with optimization flags, see <a href=\"https://docs.python.org/3/reference/simple_stmts.html#the-assert-statement\" rel=\"nofollow noreferrer\">officialdocs</a>. It is meant as a debug tool that helps tracking down bugs. For your purpose of validation I'd suggest implementing a custom function that raises an exception manually.</p>\n\n<h3>The <code>assert</code> statements are scattered in every function</h3>\n\n<p>This makes it unnecessarily harder to understand what the function actually does. I recommend either factoring out the asserts, or, and that's what I'd prefer, do in two steps: First do syntax check of the id, meaning a check if the format is correct. Then do all your processing. And second, after the processing, you do a logical check of the data, meaning if the syntactically correct string contained actually meaningful data.</p>\n\n<h3>The naming of the functions appears inconsistent</h3>\n\n<p>In <code>extract_info_from_national_id()</code> it reads:</p>\n\n<pre><code>info['birth_century'] = extract_birth_century(int(national_id_str[0]))\ninfo['date_of_birth'] = convert_birthdate(national_id_str[0:7])\ninfo['birth_governorate'] = get_birth_governorate(national_id_str[7:9])\ninfo['sequence_in_computer'] = national_id_str[9:13]\ninfo['gender'] = get_gender(int(national_id_str[12]))\n</code></pre>\n\n<p>So every function is meant to convert a string into something more meaningful, which makes me expect a standardized naming pattern. I'd probably stick to <code>get_something()</code>.</p>\n\n<h3>You can build a string splitter</h3>\n\n<p>In <code>extract_info_from_national_id()</code> you do the string splitting. That mixes different levels of abstraction. One could go for a simple function <code>split_enid</code> that returns a dictionary or a named tuple, which holds the different substrings, but nicely accessible by name. Once done, you can use it like this:</p>\n\n<pre><code>enid_strs = splid_enid(notional_id)\ninfo['birth_century'] = get_birth_century(enid_strs.birth_century)\ninfo['date_of_birth'] = convert_birthdate(enid_strs.birthdate)\ninfo['birth_governorate'] = get_birth_governorate(splitted_enid.governorate)\n...\n</code></pre>\n\n<p>Keep going, I like your code!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T08:29:32.783",
"Id": "221995",
"ParentId": "221899",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "221900",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T03:25:15.800",
"Id": "221899",
"Score": "10",
"Tags": [
"python",
"python-3.x",
"parsing"
],
"Title": "Extract Information from Egyptian National ID"
} | 221899 |
<p>To work on my Java skills, I decided to create a structure for a pool that I work at. Lifeguards get shifted when their time at their position is up, and managers periodically check the pH level of the pool. I would like feedback on the following items please.</p>
<ul>
<li><strong>Structure:</strong> Is how the current project is built acceptable? Is it coded in the most efficient way possible?</li>
<li><strong>Methods</strong></li>
<li><code>advancePosition</code> Is using a switch statement the most efficient way to change the position of the guards? Is using an enum a good practice for this type of system?</li>
<li><code>checkpHLevel</code> Is the logic hard to understand? Are there any ways I can improve upon this methods to get rid of bad habits? To the scientists here: I haven't had that much experience with working with pH levels, so is it correct to increase the pH level with Alkaline's and decrease the level with Acids?</li>
<li><code>admitPatron</code> Can this method be implemented in any way that can make it more efficient?</li>
</ul>
<p><strong>Pool.java</strong></p>
<pre><code>package Vets;
public class Pool {
private final String name;
private final int capacity;
private int patronCount;
private double pHLevel;
private boolean isClosed;
private ArrayList<Patron> patrons;
private ArrayList<Staff> staff;
public Pool(String name, int capacity) {
this.name = name;
this.capacity = capacity;
this.patronCount = 0;
this.pHLevel = 7.45;
this.isClosed = false;
this.patrons = new ArrayList<Patron>();
this.staff = new ArrayList<Staff>();
}
//Class methods
public boolean admitPatron(Patron patron) {
if((this.patronCount + 1) <= this.capacity) {
this.patrons.add(patron);
this.patronCount++;
return true;
}
return false;
}
public void rotateLifeguards() {
for(Lifeguard lifeguard : this.staff) {
lifeguard.advancePosition();
}
}
public void addAcids(double amount) {
this.pHLevel -= amount;
}
public void addAlkalis(double amount) {
this.phLevel += amount;
}
//Getters
public String getName() { return this.name; }
public int getCapacity() { return this.capacity; }
public int getPatronCount() { return this.patronCount; }
public double getpHLevel() { return this.pHLevel; }
public boolean isClosed() { return this.isClosed; }
public ArrayList<Patron> getPatrons() { return this.patrons; }
public ArrayList<Staff> getStaff() { return this.staff; }
//Custom getters
public double getOptimumLevel() { return 7.45; }
}
</code></pre>
<p><strong>Staff.java</strong></p>
<pre><code>package Vets;
public class Staff {
private final String name;
public Staff(String name) {
this.name = name;
}
//Getters
public String getName() { return this.name; }
}
</code></pre>
<p><strong>Lifeguard.java</strong></p>
<pre><code>package Vets;
public class Lifeguard extends Staff {
private Position position;
public Lifeguard(String name, Position position) {
super(name);
this.position = position;
}
//Class methods
public void advancePosition() {
switch(this.position) {
case ONE: this.position = Position.TWO; break;
case TWO: this.position = Position.BREAK_ONE; break;
case BREAK_ONE: this.position = Position.THREE; break;
case THREE: this.position = Position.FOUR; break;
case FOUR: this.position = Position.BREAK_TWO; break;
case BREAK_TWO; this.position = Position.ONE; break;
}
}
//Getters and setters
public Position getPosition() { return this.position; }
}
</code></pre>
<p><strong>Manager.java</strong></p>
<pre><code>package Vets;
public class Manager extends Staff {
public Manager(String name) {
super(name);
}
//Class methods
public boolean checkpHLevel(Pool pool) {
if(pool.getpHLevel() != pool.getOptimumLevel()) {
int amountToAdd = pool.getOptimumLevel() - pool.getpHLevel();
if(amountToAdd > 0.0) {
pool.addAcids(amountToAdd);
} else {
pool.addAlkalis(amountToAdd);
}
}
}
}
</code></pre>
<p><strong>Patron.java</strong></p>
<pre><code>package Vets;
public class Patron {
private final String name;
public Patron(String name) {
this.name = name;
}
}
</code></pre>
<p><strong>Position.java</strong></p>
<pre><code>package Vets;
public enum Position {
ONE, TWO, BREAK_ONE, THREE, FOUR, BREAK_TWO
}
</code></pre>
<p><strong>Here is a picture of the structure of the program</strong></p>
<p><a href="https://i.stack.imgur.com/Xtvfw.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Xtvfw.png" alt="Program Structure"></a></p>
| [] | [
{
"body": "<blockquote>\n <p>Is how the current project is built acceptable? Is it coded in the most efficient way possible?</p>\n</blockquote>\n\n<p>That depends on your definition of effiency. I guess you mean in it OO-Terms, i.e. maintainability, encapsulation, decoupling, etc.. In that terms, yes, your program has a good encapsulation and a good overall structure. I do not know the exact purpose of <code>Staff.java</code>, as far as I see it is designed for inheritance and not for direct instantiation so you could consider making it <code>abstract</code>. Furthermore <code>Patron.java</code> is not able to do any actions after initialization as it does not have any <code>public</code> methods besides a constructor, so the class just does nothing. As it has a field <code>name</code> a getter would be suitable. If it really surves no purpose other than to count the number of patrons you could just replace it by an <code>int</code> in <code>Pool.java</code>.</p>\n\n<blockquote>\n <p>advancePosition Is using a switch statement the most efficient way to change the position of the guards? Is using an enum a good practice for this type of system?</p>\n</blockquote>\n\n<p>Yes, using an enum is definitely the best way of modeling a finite set of states, as it provides type safety and the range of values is clear. The <code>switch</code> statement could be replaced by a <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Map.html\" rel=\"nofollow noreferrer\">Map</a> in order to keep things clean, e.g.:</p>\n\n<pre><code>// initialize this map in a constructor or better use it as constant\nMap<Position, Position> nextPosition = new Hashmap<>();\nnextPosition.put(Position.ONE, Position.TWO);\n// etc\n// ...\n// then in advancePosition()\n// getting them is then as simple as:\nposition = nextPosition.get(position);\n</code></pre>\n\n<blockquote>\n <p>checkpHLevel Is the logic hard to understand? Are there any ways I can improve upon this methods to get rid of bad habits? To the scientists here: I haven't had that much experience with working with pH levels, so is it correct to increase the pH level with Alkaline's and decrease the level with Acids?</p>\n</blockquote>\n\n<p>The logic itself is understandable, but your condition can be expressed in a more readable way. As you want to add acids or alcalines I suggest changing <code>int amountToAdd = pool.getOptimumLevel() - pool.getpHLevel();</code> to something more readable like <code>boolean isAcid = pool.getpHLevel() < pool.getOptimumLevel();</code>. This way it is immediately clear what you are trying to achieve, add acids when it's to alcaline and add alcalines when it's too acid. Your ph-level question: an acid ph-value ranges from 0-7 and alcaline from 7-14 so you add acids to an acid environment (not good :p)</p>\n\n<blockquote>\n <p>admitPatron Can this method be implemented in any way that can make it more efficient?</p>\n</blockquote>\n\n<p>Your <code>if</code>-condition could be simplified to <code>if(patronCount < capacity)</code>.</p>\n\n<p>Some overall hints for your code. You got some <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">magic numbers</a> i.e., numbers that are not directly understandable e.g., <code>this.pHLevel = 7.45;</code>. Why is it 7.45? In case of that it is common to use constants as you can give them names like <code>private static final int optimumPhLevel = 7.45</code>. If you then use it everyone knows that your ph-level is the optimum level and 7.45 doesn't really matter anymore. Furthermore you can write <code>this.patrons = new ArrayList<>();</code> instead of <code>this.patrons = new ArrayList<Patron>();</code>. This is called the <a href=\"https://stackoverflow.com/questions/4166966/what-is-the-point-of-the-diamond-operator-in-java-7\">diamond operator</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T11:33:08.910",
"Id": "221920",
"ParentId": "221903",
"Score": "4"
}
},
{
"body": "<p>@vajk already mentioned most important points, but I will add comments on some things that I see.</p>\n\n<p><code>patronCount</code> is redundant, you can simply use <code>patrons.size()</code>.</p>\n\n<p>Both arrays that are Pool members can be made final.</p>\n\n<p><code>phLevel</code> is a double meaning you have to work with floating point. You have to consider which values are used and perhaps better to use integer, since no actual meter will have such low/high range of possible values.</p>\n\n<p><code>checkPhLevel</code> and <code>getOptimumPhLevel</code> are compared in a wrong way, since <code>checkPhLevel</code> is a double you need to compare range of values instead of exact values, this comes out from previous comment about <code>phLevel</code> being a double.</p>\n\n<p><code>checkPhLevel</code> method does not say what it actually does, meaning it has a side effect. Therefore either split it in two methods where one checks ph level and returns boolean and second method adds required chemical to the pool or rename it to something like <code>balansePoolPhLevel</code>.</p>\n\n<p><code>checkPhLevel</code> can be simplified to:</p>\n\n<pre><code>double actualLevel = pool.getpHLevel();\ndouble desiredLevel = pool.getOptimumLevel()\n\nif(Math.abs(actualLevel - desiredLevel) < SOME_DELTA_YOU_THING_IS_PRECISE_ENOUGH) {\n return;\n}\n\nint amountToAdd = actualLevel - desiredLevel;\n\namountToAdd > 0 \n ? pool.addAcids(amountToAdd) \n : pool.addAlkalis(-amountToAdd); // I think you need to invert it otherwise you are adding it to phLevel in pool class\n</code></pre>\n\n<p>A good thing to consider would be creating another constructor where you can pass arrays used in <code>Pool</code> class therefore it would be much easier to test, but that's only when you write tests.</p>\n\n<p><code>admitPatron</code> method can be refactored:</p>\n\n<pre><code>if(this.patronCount >= this.capacity) {\n return false;\n}\n\nthis.patrons.add(patron);\nthis.patronCount++;\n\nreturn true;\n</code></pre>\n\n<p>But instead of doing two things in <code>admitPatron</code>. First being to check if item can be added and second add the item in a list. You could change class API to <code>boolean isPatronLimitReached()</code> and then <code>void addPatron(patron)</code>. <code>isPatronLimitReached()</code> simply return boolean if max value is reached and <code>addPatron(patron)</code> add a patron and if list is full throw an error.</p>\n\n<p>I'm bit confused about <code>rotateLifeguards</code> method since you are casting <code>Staff</code> to <code>Lifeguard</code>. <code>Staff</code> also is parent class of <code>Manager</code> and actually can be <code>Staff</code> object itself therefore you could be casting to the wrong class therefore it is not very safe. I don't write Java, but you should not cast <code>Staff</code> instead have a separate list of <code>Lifeguards</code> and <code>Managers</code>. Also you are not using managers anywhere in shown code.</p>\n\n<p><code>Patron</code> class can be just a string, no reason to keep it as class.</p>\n\n<p><code>advancePosition</code> method could be split in two parts one which get next position and second part where you assign new position to current position:</p>\n\n<pre><code>public void advancePosition() {\n this.position = this.getNextPosition();\n}\n\nPosition getNextPosition() {\n switch(this.position) {\n case Position.ONE:\n return Position.Two;\n ...\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T13:48:49.863",
"Id": "221931",
"ParentId": "221903",
"Score": "3"
}
},
{
"body": "<p>This looks like a fairly common exercise (in futility?) A common scenario that can't be represented here is be a lifeguard who is promoted to a manager but still does a few shifts saving lives.</p>\n\n<p>The position should be a property of staff. Checking pH should be a task that has a requirement for managerial position from whoever is assigned to it. It has to be performed regularly so there should be a work schedule. Might as well throw the lifeguard shifts in the schedule too with clocking in and out too. It gets complicated very quickly.</p>\n\n<p>What I am trying to say is that attempts to represent organization hierarchies or taxonomies as a class structure always fail quickly when they encounter real life. Usually this is done with vehicles or animals but this works as an example too. The correct way is to represent roles as properties. :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T05:32:50.400",
"Id": "221986",
"ParentId": "221903",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "221920",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T05:17:28.800",
"Id": "221903",
"Score": "4",
"Tags": [
"java",
"beginner"
],
"Title": "Swimming Pool Staff/Patron Structure"
} | 221903 |
<p>Is this the most efficient way to write this piece of code? Is there a better way of handling errors inside of a while/for loop, instead of calling back to the original function? I have tried using <code>break</code> or <code>continue</code>, but it breaks the functionality of my program. Any help would be awesome, thanks.</p>
<pre><code>## calculate binary to decimal ##
def binaryToDecimal(binary):
### reverse the number
decimal_num = 0
reverse_binary = binary[::-1]
for x in range(7,-1,-1):
if len(binary) <= x:
continue
if int(reverse_binary[x]) == 1:
decimal_num += 2**x
print(f"Your binary number converts to {str(decimal_num)}. ")
binaryToDecimal(checkUI())
def getUserInput():
return input("Please enter a binary number that you "
"want to convert into a decimal.\n Type 'quit' to quit program.\n")
def checkUI():
userInput = getUserInput()
if userInput == "quit" or userInput == "q":
quit()
for character in userInput:
try:
if len(userInput) > 8:
print("Binary numbers are a maximum of 8 digits. Please try again")
binaryToDecimal(checkUI())
val = int(character)
if val != 1 or 0:
print("Invalid binary number. Please enter a 1 or 0 (binary numbers: 11110000)")
binaryToDecimal(checkUI())
except ValueError:
print("You did not enter a binary number. (11110000) Please try again.")
binaryToDecimal(checkUI())
return str(userInput)
binaryToDecimal(checkUI())
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T08:46:56.013",
"Id": "429333",
"Score": "1",
"body": "Welcome to Code Review. Before posting your next question, please read how to ask questions here. The introductory text in a question should describe what the code is supposed to do, and in this question you didn't mention this at all. The title of the \"question\" should describe what the code does, and not that you need help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T10:35:18.873",
"Id": "429345",
"Score": "0",
"body": "Thank you. I will make sure to follow these guidelines"
}
] | [
{
"body": "<h1>TL;DR:</h1>\n\n<p>It's unlikely to beat Python's own implementation of this which is basically as simple as </p>\n\n<pre><code>decimal = int(binary, base=2)\n</code></pre>\n\n<p>in terms of convenience, clearity, and performance.\nThis will throw a <code>ValueError</code>in case the number cannot be converted to a binary, e.g. if the user enters something like <code>101010103</code>.</p>\n\n<p>Welcome to the world of Python, where \"batteries included\" is a real thing!</p>\n\n<p>If you, for whatever reason, do not want to use the most convenient Python has to offer, it is still possible to write a <em>Pythonic</em> alternative:</p>\n\n<pre><code>decimal = sum(int(digit)* 2**index for index, digit in enumerate(user_input[::-1]))\n</code></pre>\n\n<p>This little piece of code is called <em>generator expression</em> (relevant <a href=\"https://www.python.org/dev/peps/pep-0289/\" rel=\"nofollow noreferrer\">PEP</a>, good Stack Overflow <a href=\"https://stackoverflow.com/q/47789/5682996\">post</a>) and is basically the equivalent of:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>decimal = 0\nfor exponent, digit in enumerate(user_input[::-1]):\n decimal += digit * 2**exponent\n</code></pre>\n\n<h2>which is close(r) to what you did in your original implementation. Apart from that you don't have to care about the actual length of the input.</h2>\n\n<h1>Detailed review</h1>\n\n<p>Of course there is more to say about your code than this, especially since you're asking about other aspects as well. So let's look at your code.</p>\n\n<h2>Style</h2>\n\n<p>Python has an official <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide</a> called PEP8 (batteries included, you remember?). The main takeaways that are follow by the better part of Python programmers are</p>\n\n<ol>\n<li>Use <code>snake_case</code> for variable and function names and <code>CamelCase</code>/<code>PascalCase</code> for class names.</li>\n<li>Write function documentation (often just <em>docstrings</em>) <code>\"\"\"Enclosed in triple quotes\"\"\"</code>.</li>\n</ol>\n\n<p>I will demonstrate how to apply these principles to your code in a moment.\nThere are other useful recommendations which help you to keep the appearance of your code clean and readable, so it's definitely worth a read.</p>\n\n<h2>Naming</h2>\n\n<p>Apart from the stylistic point in the names, there is always the name itself. It's good that you decided to use functions and most of their names are totally fine. The odd one out is clearly <code>checkUI</code>. If you were just left with this name, I highly doubt that you would be able to tell what it does. Since it basically handles most of the interaction with the user, as well as validating and converting the numbers, the obvious (though maybe not ideal) name would be simply <code>main()</code>.</p>\n\n<h2>The script itself</h2>\n\n<p>After we have gone through some high-level aspects of the code, let's dive into the details. I will go through the code function by function.</p>\n\n<h3>binaryToDecimal - soon to be binary_to_decimal</h3>\n\n<p>As I already said above, the core functionality of the function can basically be replaced by a single line of Python code. And that's likely all the function should do. Apart from the <code>main</code> function, all of them should basically have a single responsibility. At the moment there are three</p>\n\n<ol>\n<li>converting the number</li>\n<li>printing the converted number</li>\n<li>starting a new round of user input</li>\n</ol>\n\n<p>The 2nd one is easy to fix: simple move the call to <code>print</code> from <code>binary_to_decimal</code> to <code>main</code>. The 3rd one is really, really (and I mean really really) bad design. <strong>The conversion function should absolutely not be tasked with starting a new round of user input.</strong> To make it worse, this will also lead to recursive calls of your functions, that will eventually end with a <code>RuntimeError</code> when your program exceeds the <a href=\"https://stackoverflow.com/q/3323001/5682996\">maximum recursion depth</a> allowed by the Python interpreter. So drop that and never do it again!</p>\n\n<h3>getUserInput - soon to be get_user_input</h3>\n\n<p>The function is basically fine and a prime example of single responsibility. Maybe it's functionality is even a bit to minimalistic, so you might not actually need it.</p>\n\n<h3>checkUI - soon to be main</h3>\n\n<p>This is where things get serious. The first and foremost recommendation for this piece of code is similar to the first function we looked at: <strong>Get rid of the recursion!</strong>. Recursion as such is not a bad thing and valid programming technique in their own right, but not for this purpose!</p>\n\n<p>The idiomatic way to ask for user input repeatedly would be something like</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def main():\n \"\"\"Repeatedly ask for user input and convert its decimal equivalent\"\"\"\n while True:\n # read and normalize the user input\n # Note: this might also (better) be done in get_user_input\n user_input = get_user_input().strip().lower()\n if user_input.startswith(\"q\")\n break\n\n # further validation and conversion\n ...\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n\n<p>The check to stop the program was slightly modified to be a little bit more robust. The way I chose to implement it will also make sure that things like <code>Q</code>, <code>Quit</code>, <code>qsomethingelse</code>, and the like end the program. If that's not what you want, simply replace it with the check you had originally. I also added <a href=\"https://docs.python.org/3/library/__main__.html\" rel=\"nofollow noreferrer\"><code>if __name__ == \"__main__\":</code></a> which adds as a kind of safeguard to make sure the \"interactive\" of your code is only triggered if you use it as script and not try to <code>import</code> it.</p>\n\n<p>Now for the validation and conversion part. With all the other changes in place it will become as simple as</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def main():\n \"\"\"Repeatedly ask for user input and convert its decimal equivalent\"\"\"\n while True:\n # read and normalize the user input\n # Note: this might also (better) be done in get_user_input\n user_input = get_user_input().strip().lower()\n if user_input.startswith(\"q\"):\n break\n\n if len(user_input) > 8:\n print(\"Binary numbers are a maximum of 8 digits. Please try again\")\n continue\n\n try:\n decimal = binary_to_decimal(user_input)\n print(f\"Your binary number converts to {decimal}. \")\n except ValueError:\n print(\"You did not enter a binary number. (11110000) Please try again.\")\n</code></pre>\n\n<p>Since you chose to limit binary numbers to a maximum length of 8bit (why?), you should likely also include this in the prompt.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T10:25:25.400",
"Id": "429344",
"Score": "0",
"body": "Hi Alex, thanks for your detailed response! I am a noobie to Python coding, this was just a fun side learning project for me during my Computer Networking class. I know I could have just used what is already built into Python, but I wanted to learn a little bit about Python and how to code efficiently and effective. I didn't even know about docstrings, they certainly look cleaner than just a normal comment. I limited the binary numbers to 8bits because I was working with IPv4 subnets in my Computer Networking class. Now that I see the cleaned up code everything makes so much more sense. Thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T14:15:54.050",
"Id": "429367",
"Score": "1",
"body": "@brandontaz2k2: I added an alternative, more \"Pythonic\" implementation of your original code, to show some more of the cool things Python has to offer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T07:57:56.930",
"Id": "221913",
"ParentId": "221906",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "221913",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T06:26:38.193",
"Id": "221906",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"error-handling",
"number-systems"
],
"Title": "Interactive command-line binary to decimal converter"
} | 221906 |
<p>So I have been programming in VB.net and want to learn C#. </p>
<p>I "successfully" created a simple program that retrieves data from Sql Server during <code>Form1_Load</code>. The program also retrieves data from an MDB file and converts it into a connection string, which I can use throughout the system. I would like to ask for your comments regarding my first time coding in C#.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.Odbc;
using System.Data.OleDb;
namespace TestInventoryApp
{
public partial class frmForex : Form
{
public bool blnFrx = false;
public bool blnFpass = true;
public frmForex()
{
InitializeComponent();
}
static public string connect()
{
//I used using because I have read somewhere that 'using' properly disposes an object
//This method checks if I can connect to sql server using MDBfile
string strCONNECTIONSTRING;
string TableName = "BACKUP";
string constr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MyProject\bin\system_common.mdb";
string connstr;
using (OleDbConnection dbCn = new OleDbConnection(constr))
using (OleDbCommand dbCo = dbCn.CreateCommand())
{
dbCo.CommandText = "SELECT m_TableType.TableType AS TableType,m_TableType.DatabaseSystem AS DatabaseSystem,m_TableType.ConnectionString AS ConnectionString FROM m_table,m_TableType WHERE m_table.TableType = m_TableType.TableType AND m_table.TableName = '" + TableName +"'";
dbCn.Open();
using (OleDbDataReader dbRE = dbCo.ExecuteReader())
{
if (dbRE.Read())
{
//This line of code gets a single string in the MDB file
//Then chops it into parts to make a connection string to sql server
strCONNECTIONSTRING = dbRE["ConnectionString"].ToString();
strCONNECTIONSTRING = strCONNECTIONSTRING.Substring(27);
int hhh = strCONNECTIONSTRING.IndexOf(";");
int aaa = strCONNECTIONSTRING.IndexOf(";")+ 1;
string dtsrc = strCONNECTIONSTRING.Substring(0, hhh);
strCONNECTIONSTRING = strCONNECTIONSTRING.Substring(aaa);
strCONNECTIONSTRING = strCONNECTIONSTRING.Substring(4);
hhh = strCONNECTIONSTRING.IndexOf(";");
aaa = strCONNECTIONSTRING.IndexOf(";")+ 1;
string userid = strCONNECTIONSTRING.Substring(0, hhh);
strCONNECTIONSTRING = strCONNECTIONSTRING.Substring(aaa);
strCONNECTIONSTRING = strCONNECTIONSTRING.Substring(4);
hhh = strCONNECTIONSTRING.IndexOf(";");
aaa = strCONNECTIONSTRING.IndexOf(";") + 1;
string password = strCONNECTIONSTRING.Substring(0, hhh);
strCONNECTIONSTRING = strCONNECTIONSTRING.Substring(aaa);
strCONNECTIONSTRING = strCONNECTIONSTRING.Substring(9);
string initcat = strCONNECTIONSTRING;
connstr = "Password=" + password + ";Persist Security Info=True;User ID="+ userid +";Initial Catalog=" + initcat + ";Data Source=" + dtsrc + "";
try
{
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
}
// I'm still figuring out how to use messagebox.show(e.exception) in c#
catch (Exception e)
{
return "";
}
return connstr;
}
}
}
// an error occurs everytime, stating that "Not" all code paths return a value, hence this code
return "";
}
public void sp_FRX_getForexToday(string frxDate, string connected)
{
//This sub gets data from sql server
using (SqlConnection conn = new SqlConnection(connected))
using (SqlCommand sqlcomm = conn.CreateCommand())
{
sqlcomm.CommandText = "dbo.sp_FRX_getFRX";
sqlcomm.CommandType = CommandType.StoredProcedure;
sqlcomm.Parameters.AddWithValue("@Date", frxDate);
using (SqlDataAdapter dta = new SqlDataAdapter(sqlcomm))
using (DataTable dt = new DataTable())
{
dta.Fill(dt);
if (dt.Rows.Count > 0)
{
txtPHP.Text = dt.Rows[0][0].ToString();
txtJPY.Text = dt.Rows[0][1].ToString();
txtEUR.Text = dt.Rows[0][2].ToString();
}
else
{
txtPHP.Text = "";
txtJPY.Text = "";
txtEUR.Text = "";
}
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
string connected;
connected = connect();
if (connected.Length > 0)
{
MessageBox.Show("Successful");
}
blnFpass = false;
sp_FRX_getForexToday("2019/06/03", connected);
}
}
}
</code></pre>
<p>Other things that I would like to learn:</p>
<ol>
<li>Regarding method <code>connect</code>, I would like to use the connection throughout the system, so I declared a local variable in <code>Form1_Load</code> named <code>connected</code> and put the connection in it. Is this the best practice? In Vb.Net, I could use <code>conn.open</code> and declare <code>Public conn As New SqlClient.SqlConnection</code> then use <code>conn</code> throughout the code. How can I do it in C#?</li>
</ol>
<p>Thank you for your time and comments.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T08:36:15.940",
"Id": "429331",
"Score": "1",
"body": "There is a class called `OleDbConnectionStringBuilder` to help you out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T13:21:13.007",
"Id": "429353",
"Score": "0",
"body": "The question in `Other things that I would like to learn` almost makes this question off-topic (please see https://codereview.stackexchange.com/help/dont-ask). I wouldn't store the connection itself, but I would store the connection string. The connection string could be stored in in either the app or the program."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T23:36:24.777",
"Id": "429518",
"Score": "0",
"body": "@pacmaninbw so,am I correct that I stored the connection string on a method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T12:10:28.997",
"Id": "429572",
"Score": "1",
"body": "Look up class properties."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-11T11:52:54.993",
"Id": "429685",
"Score": "1",
"body": "Research Entity Framework"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-25T08:39:28.773",
"Id": "440968",
"Score": "0",
"body": "Don't write ADO.NET code, use Dapper or a full ORM like Entity Framework."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T17:22:16.457",
"Id": "441791",
"Score": "0",
"body": "I strongly disagree with the ORM comments. I've never met a \"mystery magic black box\" technology that I didn't end having to beat up and wrangle into submission to get it to handle things that are complex. At a minimum, it's absolutely not a bad thing for @Mr.J to get the feet wet learning the ins and outs of ADO.NET."
}
] | [
{
"body": "<h3>Review</h3>\n\n<ul>\n<li>order your using statements to get a better overview of imports</li>\n<li>don't put more than 1 blank line between lines of code, that's just wasting space</li>\n<li>don't camel case a class name or prefix with an abbreviated type name <code>frmForex</code>; a better name would be <code>ForexForm</code></li>\n<li>don't put the type name in variable names and don't use abbrevations <code>blnFrx</code>, <code>blnFpass</code>; pick meaningful names (I have no clue what they mean)</li>\n<li>prefer properties over fields for public state; but your state should not even be declared public here, so use <code>private bool</code> instead</li>\n<li>don't use capitals in variable names <code>strCONNECTIONSTRING</code></li>\n<li>use an instance of <code>OleDbConnectionStringBuilder</code> to build the connection string for you</li>\n<li>you are doing good by using using-blocks for <code>IDisposable</code> instances</li>\n<li>avoid meaningless variable names <code>aaa</code> and <code>hhh</code></li>\n<li>don't catch the exception explicitly if you are not going to handle it <code>catch (Exception e)</code> -> <code>catch</code></li>\n<li>use <code>var</code> to avoid redundant code <code>var connection = new SqlConnection(connstr);</code></li>\n<li>you could use <code>return string.Empty</code> instead of <code>return \"\";</code></li>\n<li>don't snake case method names <code>sp_FRX_getForexToday</code></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-29T17:29:45.060",
"Id": "441795",
"Score": "1",
"body": "To add emphasis to a few things you noted: Do not use Hungarian notation. And always give names to your classes, properties, methods, etc that are meaningful and clearly self-documenting (i.e. the name clearly portrays what the thing is, and/or what it does). Avoid abbreviations that are cryptic or not well known. [General Naming Conventions](https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/general-naming-conventions)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T21:38:04.040",
"Id": "226760",
"ParentId": "221910",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "226760",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T07:42:19.487",
"Id": "221910",
"Score": "2",
"Tags": [
"c#",
"beginner",
"sql-server"
],
"Title": "My first c# program: Get Data from Sql Server and show it in Textboxes"
} | 221910 |
<p>I would like to know whether I could make my solution to this challenge shorter and more efficient. Below is the description of the challenge (this is a <a href="https://leetcode.com/problems/freedom-trail/" rel="nofollow noreferrer">Leetcode problem</a>) -</p>
<blockquote>
<p><em>In the video game Fallout 4, the quest "Road to Freedom" requires
players to reach a metal dial called the "Freedom Trail Ring", and use
the dial to spell a specific keyword in order to open the door.</em></p>
<p><em>Given a string <strong>ring</strong>, which represents the code engraved on the
outer ring and another string <strong>key</strong>, which represents the keyword
needs to be spelled. You need to find the <strong>minimum</strong> number of steps
in order to spell all the characters in the keyword.</em></p>
<p><em>Initially, the first character of the <strong>ring</strong> is aligned at the 12:00
direction. You need to spell all the characters in the string <strong>key</strong>
one by one by rotating the ring clockwise or anticlockwise to make
each character of the string <strong>key</strong> aligned at the 12:00 direction
and then by pressing the center button.</em></p>
<p><em>At the stage of rotating the ring to spell the key character
<strong>key[i]</strong> -</em></p>
<ul>
<li><p><em>You can rotate the <strong>ring</strong> clockwise or anticlockwise <strong>one place</strong>, which counts as 1 step. The final purpose of the rotation is
to align one of the string <strong>ring's</strong> characters at the 12:00
direction, where this character must equal to the character
<strong>key[i]</strong>.</em></p></li>
<li><p><em>If the character <strong>key[i]</strong> has been aligned at the 12:00 direction, you need to press the center button to spell, which also
counts as 1 step. After the pressing, you could begin to spell the
next character in the key (next stage), otherwise, you've finished all
the spelling.</em></p></li>
</ul>
<p><strong><em>Example -</em></strong></p>
<p><a href="https://i.stack.imgur.com/78JPT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/78JPT.png" alt="enter image description here"></a></p>
<pre><code>Input: ring = "godding", key = "gd"
Output: 4
# Explanation:
# For the first key character 'g', since it is already in place, we just need 1 step to spell this character.
# For the second key character 'd', we need to rotate the ring "godding" anticlockwise by two steps to make it become "ddinggo".
# Also, we need 1 more step for spelling.
# So the final output is 4.
</code></pre>
<p><strong><em>Note -</em></strong></p>
<ul>
<li><p><em>Length of both <strong>ring</strong> and <strong>key</strong> will be in range <code>1</code> to <code>100</code>.</em></p></li>
<li><p><em>There are only lowercase letters in both strings and might be some duplicate characters in both strings.</em></p></li>
<li><p><em>It's guaranteed that string <strong>key</strong> could always be spelled by rotating the string <strong>ring</strong>.</em></p></li>
</ul>
</blockquote>
<p>Here is my solution to this challenge -</p>
<pre><code># Uses dynamic programming
def find_rotate_steps(ring, key):
"""
:type ring: str
:type key: str
:rtype: int
"""
dp = [[min(i, len(ring) - i) for i in range(len(ring))]]
dp.extend([[float('inf')] * len(ring) for _ in range(len(key))])
for i in range(1, len(key) + 1):
for j in range(len(ring)):
if ring[j] != key[i - 1]:
continue
min_step = float('inf')
for k in range(len(ring)):
if dp[i - 1][k] == float('inf'):
continue
step = abs(k - j)
step = min(step, len(ring) - step) + 1 + dp[i - 1][k]
min_step = min(min_step, step)
dp[i][j] = min_step
return min(dp[-1])
</code></pre>
<p>Here is the time taken for the example output -</p>
<pre><code># %timeit find_rotate_steps("godding", "gd")
36.2 µs ± 1.33 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
</code></pre>
<p>Here is my Leetcode result for 302 test cases -</p>
<blockquote>
<p><a href="https://i.stack.imgur.com/ikPNw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ikPNw.png" alt="enter image description here"></a></p>
</blockquote>
<p><strong>NOTE -</strong> Here is what dynamic programming means (according to <a href="https://www.freecodecamp.org/news/demystifying-dynamic-programming-3efafb8d4296/" rel="nofollow noreferrer">freeCodeCamp</a>) -</p>
<blockquote>
<p><em>Dynamic programming amounts to breaking down an optimization problem
into simpler sub-problems and storing the solution to each sub-problem
so that each sub-problem is only solved once.</em></p>
</blockquote>
| [] | [
{
"body": "<p>It was hard to understand, how your code works, so I started by changing variable names to more meaningful form, also unnecessary <code>+1</code>, <code>-1</code> operation were fixed (<code>i - 1</code>, <code>1, len(key) + 1</code>, etc):</p>\n\n<pre><code>class Solution:\n def findRotateSteps(self, ring, key):\n cumulative_lens = [[min(i, len(ring) - i) for i in range(len(ring))]]\n cumulative_lens.extend([[float('inf')] * len(ring) for _ in range(len(key))])\n\n for key_num in range(len(key)):\n for new_ring_pos in range(len(ring)):\n if ring[new_ring_pos] != key[key_num]:\n continue\n\n min_sum_len = float('inf')\n\n for prev_ring_pos in range(len(ring)):\n prev_ltr_sum_len = cumulative_lens[key_num][prev_ring_pos] \n\n if prev_ltr_sum_len == float('inf'):\n continue\n\n clk_w_len = abs(prev_ring_pos - new_ring_pos)\n a_clk_len = len(ring) - clk_w_len\n\n new_sum_len = min(clk_w_len, a_clk_len) + prev_ltr_sum_len + 1\n min_sum_len = min(min_sum_len, new_sum_len)\n\n cumulative_lens[key_num + 1][new_ring_pos] = min_sum_len\n\n return min(cumulative_lens[-1])\n</code></pre>\n\n<p>Now, it is possible to read the code like a story. The cause of low performance is how you store and search visited letter lens (<code>cumulative_lens</code>). You keep them in the list, thus you need to iterate through all items to find <strong>not inf</strong> ones for each key value: </p>\n\n<pre><code>for prev_ring_pos in range(len(ring)):\n prev_ltr_sum_len = cumulative_lens[key_num][prev_ring_pos] \n\n if prev_ltr_sum_len == float('inf'):\n continue\n</code></pre>\n\n<p><strong>Example:</strong> you have 100 letters in the ring and 10 letters in the key. You found all possible lengths in the ring (there are 3 only) to the first key's letter and move to the second. It will be good to take just needed <strong>3</strong> in the next key's letter processing, not checking others <strong>97</strong> items, which are 'infs'. It can be done by storing ring letters in the <strong>dictionary</strong> - the Python's hash table structure, like this: </p>\n\n<pre><code>letter_indexes = {\n 'a' : [first a's index, second a's index],\n 'c' : [first c's index, second c's index, third c's index],\n etc\n}\n</code></pre>\n\n<p>In this case, we can get the list of the needed letter positions by doing <code>letter_indexes[letter]</code>, not messing with the others. I wrote my own solution, see it in the end.</p>\n\n<p>Also, I did some refactoring of your code:</p>\n\n<ul>\n<li>changed multiple <code>len(ring)</code> calls to the <code>ln_ring</code> variable - no performance gain, but more readable.</li>\n<li><p>changed</p>\n\n<pre><code>for key_num in range(len(key)):\n for new_ring_pos in range(len(ring)):\n if ring[new_ring_pos] != key[key_num]:\n</code></pre>\n\n<p>like constructions to more pythonic:</p>\n\n<pre><code>for key_num, key_ltr in enumerate(key):\n for new_ring_pos, ring_ltr in enumerate(ring):\n if key_ltr != ring_ltr:\n</code></pre></li>\n</ul>\n\n<p><strong>Result:</strong></p>\n\n<pre><code>class Solution:\n def findRotateSteps(self, ring, key):\n ln_ring = len(ring)\n\n cumulative_lens = [[min(i, ln_ring - i) for i in range(ln_ring)]]\n cumulative_lens.extend([[float('inf')] * ln_ring for _ in range(len(key))])\n\n for key_num, key_ltr in enumerate(key):\n for new_ring_pos, ring_ltr in enumerate(ring):\n if key_ltr != ring_ltr:\n continue\n\n min_sum_len = float('inf')\n\n for prev_ring_pos, prev_ltr_sum_len in enumerate(cumulative_lens[key_num]):\n\n if prev_ltr_sum_len == float('inf'):\n continue\n\n clk_w_len = abs(prev_ring_pos - new_ring_pos)\n a_clk_len = ln_ring - clk_w_len\n\n new_sum_len = min(clk_w_len, a_clk_len) + prev_ltr_sum_len + 1\n min_sum_len = min(min_sum_len, new_sum_len)\n\n cumulative_lens[key_num + 1][new_ring_pos] = min_sum_len\n\n return min(cumulative_lens[-1])\n</code></pre>\n\n<hr>\n\n<h3>My solution:</h3>\n\n<p>It works similar to your, but is much faster due to dictionary usage.</p>\n\n<pre><code>class Solution:\n def findRotateSteps(self, ring, key):\n # the 'prev_ltr' variable should have the start value in the\n # beginning, so the '#' character is choosed\n # It can be changed to any character different from key's content\n # In other words, it is like '-1' item with 0 index.\n ltr_indexes = {'#' : [0]}\n\n for idx, ltr in enumerate(ring):\n ltr_indexes.setdefault(ltr, []).append(idx)\n\n ln = len(ring)\n l_lens = [0] * ln\n\n prev_ltr = '#'\n for ltr in key:\n for pos in ltr_indexes[ltr]: \n all_variants = []\n\n for prev_pos in ltr_indexes[prev_ltr]: \n clk_w = abs(prev_pos - pos) \n a_clk = ln - clk_w \n all_variants.append(min(clk_w, a_clk) + l_lens[prev_pos])\n\n l_lens[pos] = min(all_variants)\n\n prev_ltr = ltr\n\n return min(l_lens[pos] for pos in ltr_indexes[ltr]) + len(key)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-17T15:43:43.847",
"Id": "430595",
"Score": "0",
"body": "Thanks for your amazing solution! It helped me a lot. +1"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-17T15:41:10.680",
"Id": "222470",
"ParentId": "221915",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "222470",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T08:42:58.157",
"Id": "221915",
"Score": "1",
"Tags": [
"python",
"performance",
"python-3.x",
"programming-challenge",
"depth-first-search"
],
"Title": "(Leetcode) Freedom Trail"
} | 221915 |
<p>I have C# ASP.Net Core Webapi application that makes some calculations for physical models. I have this project class:</p>
<pre><code>public class Project {
public IEnumerable<GenericComponent> components;
private ValueService valueService = new ValueService();
public Project(string norm) {
components = FactoryGenerator.GetFactory(norm).GetComponents(valueService);
}
public IEnumerable<ValueViewModel> GetResults() {
return valueService.GetResults();
}
public void SetValues(IEnumerable<ValueViewModel> values) {
values.ToList().ForEach(t => valueService.SetValue(t.Key, t.Value));
}
public bool Valid(string componentName) {
return components.Where(s => s.Title == componentName).Single().Valid();
}
}
</code></pre>
<p>That creates smaller components that do some calculations. Depending on the <code>norm</code> parameter, another set of components is created (via the factory). Each component has a list of variables that may exist (the frontend know which ones) and it can do some calculations on those variables and on variables that are being initialized in other components (with 3 example implementations of <code>GenericComponent</code>). </p>
<pre><code>public abstract class GenericComponent : IObserver<Tuple<string, object>> {
public readonly IValueService valueService;
protected IDisposable cancellation;
public List<string> variables;
public List<string> observingVariables;
public GenericComponent(IValueService _valueService) {
valueService = _valueService;
}
public string Title { get; set; }
public void OnCompleted() { throw new NotImplementedException(); }
public void OnError(Exception error) {// no implementation
}
public abstract void OnNext(Tuple<string, object> value);
public abstract bool Valid();
}
public class LoadComponent : GenericComponent {
public LoadComponent(IValueService valueService) : base(valueService) {
variables = new List<string>() { "load" };
variables.ForEach(s => valueService.RegisterValue(s));
cancellation = valueService.Subscribe(this, variables);
}
public override bool Valid() => valueService.GetValue("load")?.Valid ?? false;
public override void OnNext(Tuple<string, object> value) {
double load = (double)value.Item2;
if (Math.Abs(load) < 1) {
valueService.SetWarning(value.Item1, "Small load, should be larger");
}
}
}
public class ValidationComponent : GenericComponent {
public ValidationComponent(IValueService valueService) : base(valueService) {
variables = new List<string>() { "validation.load" };
variables.ForEach(s => valueService.RegisterValue(s));
observingVariables = new List<string>() { "load", "area" };
cancellation = valueService.Subscribe(this, observingVariables);
}
private double CalcMargin() {
return 0.5 * (double)valueService.GetValue("area").Value
- (double)valueService.GetValue("load").Value;
}
public override bool Valid() => CalcMargin() > 0;
public override void OnNext(Tuple<string, object> value) {
if (valueService.GetValue("load").Value != null &&
valueService.GetValue("area").Value != null) {
double margin = CalcMargin();
bool valid = margin > 0;
valueService.SetValue("validation.load", "margin is: " + margin.ToString(),
valid);
if (margin < 1) {
valueService.SetWarning("validation.load", "Very tight margin");
}
}
}
}
public class CrossSectionComponent : GenericComponent {
public CrossSectionComponent(IValueService valueService) : base(valueService) {
variables = new List<string>() { "area", "radius" };
variables.ForEach(s => valueService.RegisterValue(s));
cancellation = valueService.Subscribe(this, variables);
}
public override bool Valid() => valueService.GetValue("radius")?.Valid ?? false;
public override void OnNext(Tuple<string, object> value) {
if (value.Item1 == "radius") {
double radius = (double)value.Item2;
if (radius < 0) {
valueService.SetError("radius", "Radius is must be larger than 0");
} else if (radius < 1) {
valueService.SetWarning("radius", "Radius is very small");
}
valueService.SetValid("radius", true);
valueService.SetValue("area", radius * radius * Math.PI, true);
}
}
}
</code></pre>
<p>Each component has a list of values with keys that are unique over the entire model (here I probably need more checks, whether truly all keys are unique).
At the moment I use a <code>ValueService</code>, where each component registers its values with the respective keys. The <code>ValueService</code> can be used to get values from other components in order to do validation calculations or intermediate steps. </p>
<pre><code>public class ValueService : IValueService {
private IDictionary<string, ValueViewModel> values = new Dictionary<string, ValueViewModel>();
private IDictionary<string, List<IObserver<Tuple<string, object>>>> observers =
new Dictionary<string, List<IObserver<Tuple<string, object>>>>();
public void RegisterValue(string key) {
if (!values.ContainsKey(key)) {
values.Add(key, new ValueViewModel() {
Key = key,
Value = null
});
observers.Add(key, new List<IObserver<Tuple<string, object>>>());
}
}
public IEnumerable<ValueViewModel> GetResults() {
return values.Where(s => s.Value.Value != null).Select(s => s.Value);
}
public void SetValue(string key, object value) {
if (values.ContainsKey(key)) {
values[key].Value = value;
observers[key].ForEach(t => {
t.OnNext(new Tuple<string, object>(key, value));
});
}
}
public void SetValue(string key, object value, bool status) {
SetValue(key, value);
SetValid(key, status);
}
public void SetValid(string key, bool status) {
if (values.ContainsKey(key)) {
values[key].Valid = status;
}
}
public ValueViewModel GetValue(string key) {
if (values.ContainsKey(key))
return values[key];
return null;
}
public IDisposable Subscribe(IObserver<Tuple<string, object>> observer) {
return new Unsubscriber(observers.Values.ToList().SelectMany(s => s).ToList(), observer);
}
public IDisposable Subscribe(IObserver<Tuple<string, object>> observer, IEnumerable<string> keys) {
keys.ToList().ForEach(key => {
if (!observers.ContainsKey(key))
observers.Add(key, new List<IObserver<Tuple<string, object>>>());
if (!observers[key].Contains(observer))
observers[key].Add(observer);
});
return new Unsubscriber(observers.Values.ToList().SelectMany(s => s).ToList(), observer);
}
public void SetWarning(string key, string warning) {
if (values.ContainsKey(key)) {
values[key].Warning = warning;
values[key].Valid = true;
}
}
public void SetError(string key, string error) {
if (values.ContainsKey(key)) {
values[key].Error = error;
values[key].Valid = false;
}
}
}
</code></pre>
<p>The ValueViewModel is used to communicate with the front end</p>
<pre><code>public class ValueViewModel
{
public string Key { get; set; }
public object Value { get; set; }
public bool Valid { get; set; }
public string Warning { get; set; }
public string Error { get; set; }
}
</code></pre>
<p>This is part of a stateless API, i.e. for each HTTP request (at the moment) a new <code>Project</code> object is generated and used to make validations (via an array of ValueViewModels). </p>
<p>My API controller looks like this:</p>
<pre><code> public IActionResult postData([FromRoute] string norm, [FromRoute] string component, [FromBody] ValueViewModel[] data)
{
Project project = new Project(norm);
project.SetValues(data);
return Ok(project.GetResults()); // <<-- previously mistake, it should be GetResults, that returns a ValueViewModel with populated values (where possible)
}
</code></pre>
<p>In order to make some local tests, I created the following console application</p>
<pre><code>class Program {
static void Main(string[] args) {
Console.WriteLine("Hello world");
Project project = new Project("Eurocode_CH");
List<ValueViewModel> values = new List<ValueViewModel> {
new ValueViewModel() {
Key = "radius",
Value = 12.0
}
};
project.SetValues(values);
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(project.GetResults()));
values[0].Value = -0.4;
project.SetValues(values);
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(project.GetResults()));
values[0].Value = 0.4;
project.SetValues(values);
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(project.GetResults()));
values.Add(new ValueViewModel() {
Key = "load",
Value = 1.2
});
project.SetValues(values);
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(project.GetResults()));
}
}
</code></pre>
<p>This is the output</p>
<blockquote>
<p>[{"Key":"area","Value":452.38934211693021,"Valid":true,"Warning":null,"Error":null},{"Key":"radius","Value":12.0,"Valid":true,"Warning":null,"Error":null}]</p>
<p>[{"Key":"area","Value":0.50265482457436694,"Valid":true,"Warning":null,"Error":null},{"Key":"radius","Value":-0.4,"Valid":true,"Warning":null,"Error":"Radius
is must be larger than 0"}]</p>
<p>[{"Key":"area","Value":0.50265482457436694,"Valid":true,"Warning":null,"Error":null},{"Key":"radius","Value":0.4,"Valid":true,"Warning":"Radius
is very small","Error":"Radius is must be larger than 0"}]</p>
<p>[{"Key":"area","Value":0.50265482457436694,"Valid":true,"Warning":null,"Error":null},{"Key":"radius","Value":0.4,"Valid":true,"Warning":"Radius
is very small","Error":"Radius is must be larger than
0"},{"Key":"load","Value":1.2,"Valid":false,"Warning":null,"Error":null}]</p>
</blockquote>
<p>My concerns are</p>
<ul>
<li>When the project continues, the number of components will get quite large, I fear there will be a performance issue if for each request the whole set of components needs to be generated --> <strong>should I use LazyLoading</strong>?</li>
<li>Is the <code>ValueService</code> approach good to share data between the components? <strong>Is there a better solution</strong>?</li>
<li>I still need to implement a specific value-getter, e.g. a user requests the ValueViewModel for a specific key, the components needs to yield an error or warning if not all values were set. </li>
<li>I think "AbstractComponent" is a better name than "GenericComponent", on a side note. </li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T12:53:44.307",
"Id": "429350",
"Score": "0",
"body": "You take the view models as input, perform manipulations on these objects, and then return a boolean. Are there other operations in your API that allow to send the view models back over HTTP?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T13:03:56.397",
"Id": "429351",
"Score": "0",
"body": "'getresults' is one Im sending back. The frontend loops through all items and populates the from accordingly. What boolean do you mean?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T13:06:19.740",
"Id": "429352",
"Score": "0",
"body": "return Ok(project.Valid(component)); // <- you return a boolean here and I was wondering whether all your operations would return the boolean (is valid) orsometimes also the `getresults`. Because atm you only have `Post` implemented."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T13:24:46.197",
"Id": "429354",
"Score": "0",
"body": "What's the difference between norms - do they return entirely different components, or the same components but with a different configuration (such as different load/radius thresholds)? Also, the example could be simplified to a single function that takes `load` and `radius` parameters. What problem does having a component system solve?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T15:55:57.893",
"Id": "429373",
"Score": "0",
"body": "@dfhwze That was wrong, sorry, I copied the false Post request. The main purpose is of course the `GetResult` method that returns a more populated `ValueViewModel`. The `Valid` method can be used further in the project, where you want to use single validations for certain components (mainly in the project object)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T15:57:59.810",
"Id": "429374",
"Score": "0",
"body": "@PieterWitvoet These are physical calculations for mechanical objects. Depending on the country you operate in, the calculations are different. Each norm has about (estimated) 30 - 50 different components where some are shared and some not. Like this, my engineers only need to focus on \"self contained\" components and we have to agree on unique keys (that are registered in the `ValueService` )"
}
] | [
{
"body": "<h2>Design Choice</h2>\n\n<ul>\n<li>At first, your API looked like a convoluted pattern to validate user input. However, since you elaborated that validation is highly configurable by country, implies many backend calculations and requires the reuse of intermediate results, I feel your design is justified. </li>\n<li>I will focus on design decisions that I can't make for you, but I hope you take into consideration for improving your code.</li>\n</ul>\n\n<hr>\n\n<h2>Data Integrity</h2>\n\n<p>You allow consumers of the API to directly change the data, bypassing your code. Is this by design or an unwanted leak of data? If this behavior is not wanted, you should either use a different class for storing the values internally, or clone the data both in <code>SetValues</code> and <code>GetValues</code>.</p>\n\n<blockquote>\n<pre><code>List<ValueViewModel> values = new List<ValueViewModel> {\n new ValueViewModel() {\n Key = \"radius\",\n Value = 12.0\n }\n};\nvalues[0].Value = 0.4; // <- change data without notifying observers!\nproject.SetValues(values); // <- only now, observers get notified\n</code></pre>\n</blockquote>\n\n<p>When using ValueViewModel as internal type to store the values, would you allow consumers to change all these properties?</p>\n\n<blockquote>\n<pre><code>public class ValueViewModel\n{\n public string Key { get; set; } // <- change key, while having a different key in the dictionary\n public object Value { get; set; } // <- change value, but perhaps the type is invalid\n public bool Valid { get; set; } // <- override validity, even though there might be an error\n public string Warning { get; set; } // <- are multiple warnings possible?\n public string Error { get; set; } // <- are multiple errors possible, can the data be valid even if there is an error?\n}\n</code></pre>\n</blockquote>\n\n<p>You have included convenience methods which enforce some enacapsulation, but the consumer is not forced to use these, and can still bypass them by calling <code>GetValues</code>.</p>\n\n<blockquote>\n<pre><code> public void SetError(string key, string error) {\n if (values.ContainsKey(key)) {\n values[key].Error = error;\n values[key].Valid = false;\n } \n }\n</code></pre>\n</blockquote>\n\n<hr>\n\n<h2>Consistency</h2>\n\n<p>Consumers can get the values as <code>ValueViewModel</code> by calling <code>GetValues</code>, but observers get a different representation of the data <code>Tuple<string, object></code>. Your components, being observers, work on both these structures. This introduces unnecessary complexity for consumers of the API.</p>\n\n<blockquote>\n<pre><code>public IDisposable Subscribe(IObserver<Tuple<string, object>> observer) {\n return new Unsubscriber(observers.Values.ToList()\n .SelectMany(s => s).ToList(), observer);\n}\n</code></pre>\n</blockquote>\n\n<hr>\n\n<h2>Interface compatibility</h2>\n\n<p>A component implements <code>IObserver<T></code>. This means it can be used in any model that works with observers. Models that call <code>OnCompleted</code> will receive a nice exception. Is there a specific reason to throw an error, or could you just leave it empty as you did with <code>OnError</code>?</p>\n\n<blockquote>\n <p><code>public void OnCompleted() { throw new NotImplementedException(); }</code></p>\n</blockquote>\n\n<hr>\n\n<h2>Single Responsibility</h2>\n\n<p>A project cannot be instantiated with components, instead it requires a norm. A project should not care about the norm, it should care about its components. This would facilitate unit testing. Else you would have to mock <code>FactoryGenerator</code>, while you just need components to work with.</p>\n\n<blockquote>\n<pre><code> public Project(string norm) {\n components = FactoryGenerator.GetFactory(norm).GetComponents(valueService);\n }\n</code></pre>\n</blockquote>\n\n<p>I would instead make a project factory to create a project given a norm.</p>\n\n<pre><code>public Project(IEnumerable<GenericComponent> components, ValueService valueService) {\n // perform arg checks ..\n this.components = components;\n this.valueService = valueService;\n}\n\npublic static class ProjectFactory {\n public static Project Create(string norm, ValueService valueService) {\n return new Project(\n FactoryGenerator.GetFactory(norm).GetComponents(valueService)\n , valueService);\n }\n}\n</code></pre>\n\n<hr>\n\n<h2>Conflict Resolutions</h2>\n\n<p>Since any component can work with any value, you need a good specification on which components are the owner of which values. What if two components want to register a value using the same key?</p>\n\n<ul>\n<li>first one wins: the other uses the value registered by the first</li>\n<li>last one wins: the first one will use the value overriden by the second</li>\n<li>error: make clear there is a flaw in the design</li>\n</ul>\n\n<blockquote>\n<pre><code>public void RegisterValue(string key) {\n if (!values.ContainsKey(key)) {\n values.Add(key, new ValueViewModel() {\n Key = key,\n Value = null\n });\n observers.Add(key, new List<IObserver<Tuple<string, object>>>());\n } // <- what else ??\n }\n</code></pre>\n</blockquote>\n\n<p>I would opt for the first choice. This way, components are independant and flexible. They will only register values that haven't already been registered by another component. There should still be a policy that given a unique key, any component uses the same type and definition for the value.</p>\n\n<hr>\n\n<h2>General Design</h2>\n\n<h3>ValueViewModel</h3>\n\n<ul>\n<li>Decide whether to use this type internally in your API or you use another type with better encapsulation, maybe even immutable.</li>\n</ul>\n\n<h3>ValueService</h3>\n\n<ul>\n<li>Be consistent and use only one internal type, both usable by consumers of the API and observers of the values.</li>\n<li>Determine a strategy for handling conflicts when registering values.</li>\n</ul>\n\n<h3>Component</h3>\n\n<ul>\n<li>Consider creating an interface <code>IComponent</code> for better testability.</li>\n<li>Take into account values might already be registered when registering values.</li>\n<li>Decide which component is responsible for cascading updates of other values when changing a value. <code>radius</code> changed -> change <code>area</code>.</li>\n<li>Ensure two-way cascaded updates don't result in an infinite loop. What if <code>area</code> changed -> update <code>radius</code> is allowed as well?</li>\n</ul>\n\n<h3>Project</h3>\n\n<ul>\n<li>Extract configuration logic and move it to a factory.</li>\n</ul>\n\n<hr>\n\n<h2>Q&A</h2>\n\n<blockquote>\n <p>When the project continues, the number of components will get quite\n large, I fear there will be a performance issue if for each request\n the whole set of components needs to be generated --> should I use\n LazyLoading?</p>\n</blockquote>\n\n<p>Since your components are passive objects (as opposed to <a href=\"https://en.wikipedia.org/wiki/Active_object\" rel=\"nofollow noreferrer\">active object</a>) that get instantiated on demand given the <em>norm</em>, I don't see the need to implement <em>lazy loading</em> here.</p>\n\n<blockquote>\n <p>Is the ValueService approach good to share data between the\n components? Is there a better solution?</p>\n</blockquote>\n\n<p>By using <code>ValueService</code> you have decoupled component logic with the extended state (the value cache) of a project. This is common practice when building <a href=\"https://en.wikipedia.org/wiki/Finite-state_machine\" rel=\"nofollow noreferrer\">state machines</a>.</p>\n\n<blockquote>\n <p>I still need to implement a specific value-getter, e.g. a user\n requests the ValueViewModel for a specific key, the components needs\n to yield an error or warning if not all values were set.</p>\n</blockquote>\n\n<p>I have addressed possible strategies for conflict resolution in the review. You could extend these strategies to your getter and setters as well.</p>\n\n<blockquote>\n <p>I think \"AbstractComponent\" is a better name than \"GenericComponent\",\n on a side note.</p>\n</blockquote>\n\n<p><code>AbstractComponent</code> is the better name, although it's a typical java name. In C#, it's more common to call this <code>ComponentBase</code>. Some API's would call it <code>ComponentSkeleton</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T19:37:21.413",
"Id": "429402",
"Score": "0",
"body": "Wow, that really is extensive! On *Consistency*: I agree, I really don't like the Tuple approach but I needed to tell an observer which `OnNext` value I'm actually passing. Passing the whole `ValueViewModel` appears to be an overkill although an IValueVM would be better with different implementations for different use-cases. Interface compatibility: that part is just missing, you're right."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T19:40:22.493",
"Id": "429403",
"Score": "0",
"body": "@rst I'm not sure it's overkill, since I see that some of your components call `ValueService` for the `ValueViewModel` in `OnNext`. So they need the full instance, rather than just the value in some occasions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T19:44:00.003",
"Id": "429404",
"Score": "0",
"body": "The part with the `ProjectFactory` is good, that should be implemented. On the part with *Conflict Resolutions*, I will make options 3, it should be clear there is a flaw. *Component*: Issue 3 and 4 are actually tough ones!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T19:47:27.323",
"Id": "429405",
"Score": "0",
"body": "@rst I agree with issue 3 and 4 being both tough design decisions and technically challenging. One thing you can do is to only update a value if it differs from the current value. This way, whether radius or area gets changed first, results in updating the other, results in a requested update of self. But because the value does not differ, the flow short-circuits, avoiding an infinite loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T19:48:00.567",
"Id": "429406",
"Score": "0",
"body": "I do lots of Angular coding (for my taste) and there there are many \"AbstractForms\" e.g., ComponentBase sounds better than ComponentSkeleton."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T19:49:34.463",
"Id": "429407",
"Score": "0",
"body": "@rst Check this post for default base class names in .NET. https://stackoverflow.com/questions/826821/c-sharp-class-naming-convention-is-it-baseclass-or-classbase-or-abstractclass. *Base is most common."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T19:49:51.873",
"Id": "429408",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/94673/discussion-between-rst-and-dfhwze)."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T17:01:40.270",
"Id": "221942",
"ParentId": "221917",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "221942",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T09:14:17.160",
"Id": "221917",
"Score": "3",
"Tags": [
"c#",
"asp.net",
"observer-pattern",
"asp.net-core"
],
"Title": "Logic is stored in Components that receive input data and update output data via Observables"
} | 221917 |
<p>Please can someone confirm if this code is the best way to build the following tree</p>
<pre><code> 0
/ \
1 1
/ \ / \
3 8 4 7
</code></pre>
<pre><code>class Node():
def __init__(self, value, right = None, left= None):
self.value = value
self.right = right
self.left = left
def addNode (self, list_parent_nodes, child_value):
if self.value >=0:
if len(list_parent_nodes) > 1:
if list_parent_nodes[0] == 0:
self.left.addNode (list_parent_nodes[1:], child_value)
else:
self.right.addNode (list_parent_nodes[1:], child_value)
else:
if list_parent_nodes[0] == 0:
self.left = Node(child_value)
else:
self.right = Node(child_value)
def printTree(self,level=0):
if self.value >=0:
output = self.value
print(" "*level + str(output))
if self.left: self.left.printTree(level+1)
if self.right: self.right.printTree(level+1)
g = Node(0)
g.addNode ([0], 1)
g.addNode ([1], 1)
"""Graph looks like
0
/ \
1 1
"""
g.addNode ([0,0], 3)
g.addNode ([0,1], 8)
g.addNode ([1,0], 4)
g.addNode ([1,1], 7)
"""Graph looks like
0
/ \
1 1
/ \ / \
3 8 4 7
"""
g.printTree()
<span class="math-container">```</span>
</code></pre>
| [] | [
{
"body": "<ul>\n<li>Please read over <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> as your naming style is unidiomatic, and would cause programmers to be confused when seeing your code in the wild.</li>\n<li>I would move getting and setting a node by index into their own functions.</li>\n<li><code>if self.value >= 0</code> only hinders your code, the value <code>-1</code> is perfectly valid in binary trees. It also means that you're limiting <code>value</code> to types that can be compared to integers, meaning you can't enter strings.</li>\n<li>Using recursion in <code>addNode</code> is a good idea, but I find the non-recursive alternate to be easier to understand.</li>\n<li>Your code doesn't care if I enter <code>addNode([0, 2], 1)</code>. This seems fishy as if this were a Trinary Tree that would mean something completely different. I recommend raising a <code>ValueError</code> in this case.</li>\n<li>Your <code>printTree</code> is pretty good.</li>\n<li>I'd change the <code>level</code> argument in <code>printTree</code> to be a keyword argument only. This is because then it's explicit that it's changing the level, and it's something normal code shouldn't accidentally change.</li>\n<li>Personally I think <code>if self.left is not None</code> is better here than <code>if self.left</code>, but as <code>Node</code> can't be falsy it doesn't matter too much.</li>\n<li>I've added some basic docstrings, defined in <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">PEP 257</a>.</li>\n<li>I have also added some <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\"><code>typing</code></a> to your code.</li>\n<li>By using <code>typing</code> and <a href=\"https://pypi.org/project/mypy/\" rel=\"nofollow noreferrer\">mypy</a> I found that <code>addNode</code> can error when the specified path doesn't exist. It would be better in these cases to raise an error telling the user why.</li>\n<li>You can use a <code>if __name__ == '__main__':</code> guard to prevent code running on import. This means if you later import this code in another module then the testing code won't run.</li>\n</ul>\n\n<pre><code>from __future__ import annotations\n\nfrom typing import Any, Optional, Sequence\n\n\nclass Node:\n \"\"\"Test binary tree.\"\"\"\n\n def __init__(\n self,\n value: Any,\n right: Optional[Node] = None,\n left: Optional[Node] = None,\n ):\n \"\"\"Initialize binary tree, with specified children nodes.\"\"\"\n self.value = value\n self.right = right\n self.left = left\n\n def _get_index(self, index: int) -> Optional[Node]:\n \"\"\"Get node via integer index.\"\"\"\n if index == 0:\n return self.left\n elif index == 1:\n return self.right\n else:\n raise ValueError(f'Invalid index {index}')\n\n def _set_index(self, index: int, value: Node) -> None:\n \"\"\"Set node via integer index.\"\"\"\n if index == 0:\n self.left = value\n elif index == 1:\n self.right = value\n else:\n raise ValueError(f'Invalid index {index}')\n\n def add_node(self, parents: Sequence[int], value: Node) -> None:\n \"\"\"Add the provided node to the tree.\"\"\"\n node: Optional[Node] = self\n for index in parents[:-1]:\n if node is not None:\n node = node._get_index(index)\n if node is None:\n raise ValueError(\"Parent node doesn't exist.\")\n node._set_index(parents[-1], value)\n\n def add_value(self, parents: Sequence[int], value: Any) -> None:\n \"\"\"Add the provided value to the tree.\"\"\"\n self.add_node(parents, Node(value))\n\n def print_tree(self, *, level: int = 0) -> None:\n \"\"\"Print the tree.\"\"\"\n print(' ' * level + str(self.value))\n for child in (self.left, self.right):\n if child is not None:\n child.print_tree(level=level + 1)\n\n\nif __name__ == '__main__':\n tree = Node(0)\n tree.add_value([0], 1)\n tree.add_value([1], 1)\n r\"\"\"\n Graph looks like\n 0\n / \\\n 1 1\n \"\"\"\n\n tree.add_value([0, 0], 3)\n tree.add_value([0, 1], 8)\n tree.add_value([1, 0], 4)\n tree.add_value([1, 1], 7)\n r\"\"\"\n Graph looks like\n 0\n / \\\n 1 1\n / \\ / \\\n 3 8 4 7\n \"\"\"\n tree.print_tree()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T12:20:32.367",
"Id": "221923",
"ParentId": "221919",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "221923",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T11:21:32.877",
"Id": "221919",
"Score": "4",
"Tags": [
"python",
"tree"
],
"Title": "Building a tree in python"
} | 221919 |
<p>Some time ago I implemented <code>dynamic_array</code> and <a href="https://codereview.stackexchange.com/q/221719">posted</a> it on Code Review. It used <code>std::function</code> internally for type erasure. This inspired me to implement a standard-conforming <code>std::function</code> myself. This is just a showcase of how static polymorphism with templates can play well with dynamic polymorphism with inheritance and virtual functions. </p>
<p>Incidentally, some time ago I implemented <code>std::invoke</code> and my own <code>invoke_r</code> and also <a href="https://codereview.stackexchange.com/q/221828">posted</a> it on Code Review. Internally, <code>function</code> uses <code>invoke_r</code>. Its implementation is very short, so I included it as part of the code.</p>
<p>Here is the <code>function.hpp</code> header: (the deduction guide was really painful to write)</p>
<pre><code>// C++17 std::function implementation
// [func.wrap] and [depr.func.adaptor.typedefs]
#ifndef INC_FUNCTION_HPP_QLxVtsa5Mv
#define INC_FUNCTION_HPP_QLxVtsa5Mv
#include <cstddef>
#include <exception>
#include <functional>
#include <memory>
#include <typeinfo>
#include <type_traits>
namespace my_std {
// [func.wrap.badcall], class bad_function_call
struct bad_function_call :std::exception {
// [func.wrap.badcall.const], constructor
bad_function_call() = default;
};
// [func.wrap.func], class template function
template <class F>
class function; // not defined
namespace detail {
// [depr.func.adaptor.typedefs], typedefs to support function binders
template <class... Args>
struct function_base {};
template <class T>
struct function_base<T> {
using argument_type [[deprecated]] = T;
};
template <class T, class U>
struct function_base<T, U> {
using first_argument_type [[deprecated]] = T;
using second_argument_type [[deprecated]] = U;
};
// trait to check if a type is a pointer to function
template <class T>
struct is_function_pointer :std::false_type {};
template <class T>
struct is_function_pointer<T*> :std::is_function<T> {};
template <class T>
inline constexpr bool is_function_pointer_v = is_function_pointer<T>::value;
// trait to check if a type is a specialization of the class template function
template <class T>
struct is_function :std::false_type {};
template <class T>
struct is_function<function<T>> :std::true_type {};
template <class T>
inline constexpr bool is_function_v = is_function<T>::value;
// INVOKE<R>(f, args...), see [func.require]/2
template <class R, class F, class... Args>
R invoke_r(F&& f, Args&&... args)
noexcept(std::is_nothrow_invocable_r_v<R, F, Args...>)
{
if constexpr (std::is_void_v<R>)
return static_cast<void>(
std::invoke(std::forward<F>(f), std::forward<Args>(args)...)
);
else
return std::invoke(std::forward<F>(f), std::forward<Args>(args)...);
}
// polymorphic base for callable wrappers
template <class R, class... Args>
struct callable_base {
virtual ~callable_base() {}
virtual R invoke(Args...) const = 0;
virtual std::unique_ptr<callable_base> clone() const = 0;
virtual const std::type_info& target_type() const noexcept = 0;
virtual void* target() const noexcept = 0;
};
// callable wrapper
template <class F, class R, class... Args>
struct callable :callable_base<R, Args...> {
using Base = callable_base<R, Args...>;
public:
callable(F f)
:func{std::move(f)}
{
}
~callable() {}
R invoke(Args... args) const override
{
return invoke_r<R>(func, std::forward<Args>(args)...);
}
std::unique_ptr<Base> clone() const override
{
return std::unique_ptr<Base>{new callable{func}};
}
const std::type_info& target_type() const noexcept override
{
return typeid(F);
}
void* target() const noexcept override
{
return &func;
}
private:
mutable F func;
};
}
// [func.wrap.func], class template function
template <class R, class... Args>
class function<R(Args...)> :public detail::function_base<Args...> {
public:
using result_type = R;
// [func.wrap.func.con], construct/copy/destroy
function() noexcept
{
}
function(std::nullptr_t) noexcept
{
}
function(const function& f)
:func{f ? f.func->clone() : nullptr}
{
}
function(function&& f) noexcept // strengthened
{
swap(f);
}
template <class F,
std::enable_if_t<std::is_invocable_r_v<R, F&, Args...>, int> = 0>
function(F f)
{
if constexpr (detail::is_function_pointer_v<F> ||
std::is_member_pointer_v<F> ||
detail::is_function_v<F>) {
if (!f) return;
}
func.reset(new detail::callable<F, R, Args...>{std::move(f)});
}
function& operator=(const function& f)
{
function{f}.swap(*this);
return *this;
}
function& operator=(function&& f)
{
swap(f);
return *this;
}
function& operator=(std::nullptr_t) noexcept
{
func.reset();
return *this;
}
template <class F,
std::enable_if_t<
std::is_invocable_r_v<R, std::decay_t<F>&, Args...>,
int> = 0>
function& operator=(F&& f)
{
function{std::forward<F>(f)}.swap(*this);
return *this;
}
template <class F>
function& operator=(std::reference_wrapper<F> f) noexcept
{
function{f}.swap(*this);
return *this;
}
~function() = default;
// [func.wrap.func.mod], function modifiers
void swap(function& other) noexcept
{
using std::swap;
swap(func, other.func);
}
// [func.wrap.func.cap], function capacity
explicit operator bool() const noexcept
{
return static_cast<bool>(func);
}
// [func.wrap.func.inv], function invocation
R operator()(Args... args) const
{
if (*this)
return func->invoke(std::forward<Args>(args)...);
else
throw bad_function_call{};
}
// [func.wrap.func.targ], function target access
const type_info& target_type() const noexcept
{
if (*this)
return func->target_type();
else
return typeid(void);
}
template <class T>
T* target() noexcept
{
if (target_type() == typeid(T))
return reinterpret_cast<T*>(func->target());
else
return nullptr;
}
template <class T>
const T* target() const noexcept
{
if (target_type() == typeid(T))
return reinterpret_cast<const T*>(func->target());
else
return nullptr;
}
private:
std::unique_ptr<detail::callable_base<R, Args...>> func = nullptr;
};
namespace detail {
template <typename T>
struct deduce_function {};
template <typename T>
using deduce_function_t = typename deduce_function<T>::type;
template <typename G, typename R, typename... Args>
struct deduce_function<R (G::*)(Args...)> {
using type = R(Args...);
};
template <typename G, typename R, typename... Args>
struct deduce_function<R (G::*)(Args...) const> {
using type = R(Args...);
};
template <typename G, typename R, typename... Args>
struct deduce_function<R (G::*)(Args...) volatile> {
using type = R(Args...);
};
template <typename G, typename R, typename... Args>
struct deduce_function<R (G::*)(Args...) const volatile> {
using type = R(Args...);
};
template <typename G, typename R, typename... Args>
struct deduce_function<R (G::*)(Args...) &> {
using type = R(Args...);
};
template <typename G, typename R, typename... Args>
struct deduce_function<R (G::*)(Args...) const &> {
using type = R(Args...);
};
template <typename G, typename R, typename... Args>
struct deduce_function<R (G::*)(Args...) volatile &> {
using type = R(Args...);
};
template <typename G, typename R, typename... Args>
struct deduce_function<R (G::*)(Args...) const volatile &> {
using type = R(Args...);
};
template <typename G, typename R, typename... Args>
struct deduce_function<R (G::*)(Args...) noexcept> {
using type = R(Args...);
};
template <typename G, typename R, typename... Args>
struct deduce_function<R (G::*)(Args...) const noexcept> {
using type = R(Args...);
};
template <typename G, typename R, typename... Args>
struct deduce_function<R (G::*)(Args...) volatile noexcept> {
using type = R(Args...);
};
template <typename G, typename R, typename... Args>
struct deduce_function<R (G::*)(Args...) const volatile noexcept> {
using type = R(Args...);
};
template <typename G, typename R, typename... Args>
struct deduce_function<R (G::*)(Args...) & noexcept> {
using type = R(Args...);
};
template <typename G, typename R, typename... Args>
struct deduce_function<R (G::*)(Args...) const & noexcept> {
using type = R(Args...);
};
template <typename G, typename R, typename... Args>
struct deduce_function<R (G::*)(Args...) volatile & noexcept> {
using type = R(Args...);
};
template <typename G, typename R, typename... Args>
struct deduce_function<R (G::*)(Args...) const volatile & noexcept> {
using type = R(Args...);
};
}
template <class R, class... Args>
function(R (*)(Args...)) -> function<R(Args...)>;
template <class F, class Op = decltype(&F::operator())>
function(F) -> function<detail::deduce_function_t<Op>>;
// [func.wrap.func.nullptr], null pointer comparisons
template <class R, class... Args>
bool operator==(const function<R(Args...)>& f, std::nullptr_t) noexcept
{
return !f;
}
template <class R, class... Args>
bool operator==(std::nullptr_t, const function<R(Args...)>& f) noexcept
{
return !f;
}
template <class R, class... Args>
bool operator!=(const function<R(Args...)>& f, std::nullptr_t) noexcept
{
return static_cast<bool>(f);
}
template <class R, class... Args>
bool operator!=(std::nullptr_t, const function<R(Args...)>& f) noexcept
{
return static_cast<bool>(f);
}
// [func.wrap.func.alg], specialized algorithms
template <class R, class... Args>
void swap(function<R(Args...)>& lhs, function<R(Args...)>& rhs) noexcept
{
lhs.swap(rhs);
}
}
#endif
</code></pre>
| [] | [
{
"body": "<p>Nice, clean and functional.<br>\nStill, there are a few things:</p>\n\n<ol>\n<li><p>If you don't have to declare a special member-function, just don't:<br>\n<code>bad_function_call::bad_function_call()</code>, <code>callable::~callable()</code>, and <code>function::~function()</code> are superfluous.</p></li>\n<li><p>If you actually have to declare a special member-function, explicitly default it in-class where that is enough:<br>\n<code>callable_base::~ callable_base()</code>, and <code>function::function()</code> should be explicitly defaulted.</p></li>\n<li><p>Consider investing in small-object-optimization. Yes, it <em>will</em> make the code a bit more complicated, but on the flip-side it should result in much improved efficiency. Also, <a href=\"https://en.cppreference.com/w/cpp/utility/functional/function/function\" rel=\"nofollow noreferrer\">it is mandatory</a>.</p></li>\n<li><p>Consider using the null-object-pattern to pare down on checks. There is considerable synergy with the previous point.</p></li>\n<li><p>You can replace (most of) your uses of <code>static_cast<bool>()</code> with double-negation.</p></li>\n<li><p>Personally, I prefer a bigger indentation-step, but whatever. Also, not having colon <code>:</code> followed by any whitespace takes some getting used to.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-23T16:04:24.073",
"Id": "222813",
"ParentId": "221921",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "222813",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T11:43:49.040",
"Id": "221921",
"Score": "9",
"Tags": [
"c++",
"reinventing-the-wheel",
"c++17",
"template-meta-programming",
"polymorphism"
],
"Title": "A C++17 std::function implementation"
} | 221921 |
<p>I am creating a logging library in C++, and I wanted your opinion on code quality and performance within some methods.</p>
<p>You may ask why yet another logger - the answer is simple. This logging library that I am developing is not exclusively said to be released, it's purely for my own experience and fun. But if it turns out to be atleast decent, why not.</p>
<p>Here is the code</p>
<p><strong>lwlog.h</strong></p>
<pre><code>#pragma once
#include <iostream>
#include <string>
#include <cctype>
#include "core.h"
#include "detail.h"
#include "datetime.h"
#include "registry.h"
namespace lwlog
{
enum class log_level
{
all = (1 << 0),
info = (1 << 1),
warning = (1 << 2),
error = (1 << 3),
critical = (1 << 4),
debug = (1 << 5),
none = (1 << 6)
};
static log_level operator |(log_level lhs, log_level rhs)
{
return static_cast<log_level> (
static_cast<std::underlying_type<log_level>::type>(lhs)
| static_cast<std::underlying_type<log_level>::type>(rhs)
);
}
static log_level operator &(log_level lhs, log_level rhs)
{
return static_cast<log_level> (
static_cast<std::underlying_type<log_level>::type>(lhs)
& static_cast<std::underlying_type<log_level>::type>(rhs)
);
}
class LWLOG logger
{
private:
std::string m_message;
std::string m_loggerName;
std::string m_pattern;
std::string m_logLevel;
log_level m_logLevel_visibility = log_level::all;
std::unordered_map<std::string, std::string> m_patterns_data;
private:
void print_formatted(const std::string& message, std::string pattern);
public:
explicit logger(const std::string& name);
~logger();
void set_name(const std::string& loggerName);
void set_logLevel_visibility(log_level logLevel);
void set_pattern(const std::string& pattern);
void info(const std::string& message);
void warning(const std::string& message);
void error(const std::string& message);
void critical(const std::string& message);
void debug(const std::string& message);
inline std::string get_name() const { return m_loggerName; }
inline std::string get_logLevel() const { return m_logLevel; }
};
template<typename... Args>
void print(std::string format_str, Args&&... args)
{
std::vector<std::string> format_string_tokens_vec;
std::vector<int> format_numeric_tokens_vec;
std::vector<std::string> variadic_arguments_vec;
std::regex reg("(\\{\\d\\})");
(detail::populate_vec_with_variadic_params(variadic_arguments_vec, std::forward<Args>(args)), ...);
detail::populate_vec_with_regex_matches_from_str(format_string_tokens_vec, reg, format_str);
detail::remove_duplicates_in_vec(variadic_arguments_vec);
detail::string_to_numeric_vec(format_string_tokens_vec, format_numeric_tokens_vec, "{}");
for (int i = 0; i < format_string_tokens_vec.size(); ++i)
{
detail::replace_in_string(format_str, format_string_tokens_vec[i], variadic_arguments_vec[format_numeric_tokens_vec[i]]);
}
std::cout << format_str;
}
}
</code></pre>
<p><strong>lwlog.cpp</strong></p>
<pre><code>#include "lwlog.h"
namespace lwlog
{
logger::logger(const std::string& logger_name)
: m_loggerName(logger_name), m_pattern("[%d, %x] [%l] [%n]: %v")
{
if (registry::instance().is_registry_automatic() == true)
{
registry::instance().register_logger(this);
}
}
logger::~logger()
{
}
void logger::set_name(const std::string& logger_name)
{
m_loggerName = logger_name;
}
void logger::set_logLevel_visibility(log_level logLevel)
{
if (logLevel == log_level::all)
{
m_logLevel_visibility = log_level::info | log_level::warning | log_level::error
| log_level::critical | log_level::debug;
}
else if (logLevel == log_level::none)
{
m_logLevel_visibility = log_level::none;
}
else
{
m_logLevel_visibility = logLevel;
}
}
void logger::set_pattern(const std::string& pattern)
{
m_pattern = pattern;
}
void logger::info(const std::string& message)
{
m_message = message;
m_logLevel = "info";
if (static_cast<std::underlying_type_t<log_level>>(m_logLevel_visibility)
& static_cast<std::underlying_type_t<log_level>>(log_level::info))
{
print_formatted(message, m_pattern);
}
}
void logger::warning(const std::string& message)
{
m_message = message;
m_logLevel = "warning";
if (static_cast<std::underlying_type_t<log_level>>(m_logLevel_visibility)
& static_cast<std::underlying_type_t<log_level>>(log_level::warning))
{
print_formatted(message, m_pattern);
}
}
void logger::error(const std::string& message)
{
m_message = message;
m_logLevel = "error";
if (static_cast<std::underlying_type_t<log_level>>(m_logLevel_visibility)
& static_cast<std::underlying_type_t<log_level>>(log_level::error))
{
print_formatted(message, m_pattern);
}
}
void logger::critical(const std::string& message)
{
m_message = message;
m_logLevel = "critical";
if (static_cast<std::underlying_type_t<log_level>>(m_logLevel_visibility)
& static_cast<std::underlying_type_t<log_level>>(log_level::critical))
{
print_formatted(message, m_pattern);
}
}
void logger::debug(const std::string& message)
{
m_message = message;
m_logLevel = "debug";
if (static_cast<std::underlying_type_t<log_level>>(m_logLevel_visibility)
& static_cast<std::underlying_type_t<log_level>>(log_level::debug))
{
print_formatted(message, m_pattern);
}
}
void logger::print_formatted(const std::string& message, std::string pattern)
{
m_patterns_data.emplace("%d", datetime::get_current_date());
m_patterns_data.emplace("%L", std::string(1, toupper(m_logLevel[0])));
m_patterns_data.emplace("%l", m_logLevel);
m_patterns_data.emplace("%n", m_loggerName);
m_patterns_data.emplace("%v", message);
m_patterns_data.emplace("%x", datetime::get_current_time());
std::vector<std::string> pattern_string_tokens_vec;
std::regex rg("(\\%[DdLlnvx]{1})");
detail::populate_vec_with_regex_matches_from_str(pattern_string_tokens_vec, rg, pattern);
for (int i = 0; i < pattern_string_tokens_vec.size(); ++i)
{
for (auto it = m_patterns_data.begin(); it != m_patterns_data.end(); ++it)
{
if (pattern_string_tokens_vec[i] == it->first)
{
detail::replace_in_string(pattern, pattern_string_tokens_vec[i], it->second);
}
}
}
print("{0} \n", pattern);
m_patterns_data.clear();
}
}
</code></pre>
<p><strong>registry.h</strong></p>
<pre><code>#pragma once
#include <vector>
#include <memory>
#include <string>
#include <unordered_map>
#include "core.h"
namespace lwlog
{
class logger;
class LWLOG registry
{
private:
registry() {}
std::unordered_map<std::string, logger*> m_loggersMap;
bool m_automatic_registry = true;
public:
registry(const registry&) = delete;
registry& operator=(const registry&) = delete;
void register_logger(logger* new_logger);
void drop(const std::string& logger_name);
void drop_all();
void set_automatic_registry(bool automatic);
void display_all_loggers();
inline bool is_registry_automatic() { return m_automatic_registry ? true : false; }
static registry& instance()
{
static registry s_instance;
return s_instance;
}
};
}
</code></pre>
<p><strong>registry.cpp</strong></p>
<pre><code>#include "registry.h"
#include "lwlog.h"
namespace lwlog
{
void registry::register_logger(logger* new_logger)
{
m_loggersMap.emplace(new_logger->get_name(), new_logger);
}
void registry::drop(const std::string& logger_name)
{
for (auto it = m_loggersMap.begin(); it != m_loggersMap.end(); ++it)
{
if (it->first == logger_name)
{
m_loggersMap.erase(logger_name);
break;
}
}
}
void registry::drop_all()
{
m_loggersMap.clear();
}
void registry::set_automatic_registry(bool automatic)
{
m_automatic_registry = automatic;
}
void registry::display_all_loggers()
{
for (auto it = m_loggersMap.begin(); it != m_loggersMap.end(); it++)
{
print("{0} \n", it->first);
}
}
}
</code></pre>
<p><strong>detail.h</strong></p>
<pre><code>#pragma once
#include <regex>
#include <vector>
#include <map>
#include <unordered_set>
namespace detail
{
static void populate_vec_with_regex_matches_from_str(std::vector<std::string>& v, std::regex rg, std::string& s)
{
std::smatch matches;
std::string temp = s;
while (std::regex_search(temp, matches, rg))
{
v.push_back(matches.str(1));
temp = matches.suffix().str();
}
}
template<typename... Args>
void populate_vec_with_variadic_params(std::vector<std::string>& v, Args&&... args)
{
std::vector<std::string> vec =
{
[](auto && arg)
{
if constexpr (std::is_same_v<std::remove_reference_t<decltype(arg)>, char>)
{
return std::string(1, arg);
}
else if constexpr (std::is_arithmetic_v<std::remove_reference_t<decltype(arg)>>)
{
return std::to_string(std::forward<decltype(arg)>(arg));
}
else
{
return arg;
}
}(std::forward<Args>(args))...
};
for (const auto& i : vec)
{
v.push_back(i);
}
}
template<typename T, typename T1>
void string_to_numeric_vec(std::vector<T>& sv, std::vector<T1>& nv, const char* chars_to_remove)
{
for (int i = 0; i < sv.size(); ++i)
{
std::string temp = sv[i];
for (int i = 0; i < strlen(chars_to_remove); ++i)
{
temp.erase(std::remove(temp.begin(), temp.end(), chars_to_remove[i]), temp.end());
}
nv.push_back(std::stoi(temp));
}
}
template<typename T>
void remove_duplicates_in_vec(std::vector<T>& v)
{
std::unordered_set<T> s;
for (const auto& i : v)
{
s.insert(i);
}
v.assign(s.begin(), s.end());
}
static void replace_in_string(std::string& s, const std::string& to_replace, const std::string& replace_with)
{
size_t index = 0;
while (true)
{
index = s.find(to_replace, index);
if (index == std::string::npos)
{
break;
}
s.replace(index, to_replace.length(), replace_with);
index += to_replace.length();
}
}
}
</code></pre>
<p><strong>datetime.h</strong></p>
<pre><code>#pragma once
#include <iomanip>
#include <sstream>
#include <chrono>
#include <ctime>
namespace lwlog
{
namespace datetime
{
static std::string get_current_time_and_date(const char* format)
{
auto now = std::chrono::system_clock::now();
auto in_time_t = std::chrono::system_clock::to_time_t(now);
std::stringstream ss;
ss << std::put_time(std::localtime(&in_time_t), format);
return ss.str();
}
static std::string get_current_time()
{
return get_current_time_and_date("%X");
}
static std::string get_current_date()
{
return get_current_time_and_date("%Y-%m-%d");
}
}
}
</code></pre>
<p><strong>core.h</strong></p>
<pre><code>#pragma once
#ifdef _WIN32
#define LWLOG_PLATFORM_WINDOWS
#endif
#ifdef __linux__
#define LWLOG_PLATFORM_LINUX
#endif
#ifdef __APPLE__
#define LWLOG_PLATFORM_MAC
#endif
#ifndef LWLOG
#ifdef LWLOG_PLATFORM_WINDOWS
#if defined(LWLOG_BUILD_DLL)
#define LWLOG __declspec(dllexport)
#elif !defined(LWLOG_BUILD_STATIC)
#define LWLOG __declspec(dllimport)
#else
#define LWLOG
#endif
#else
#if __GNUC__ >= 4
#define LWLOG __attribute__((visibility("default")))
#else
#define LWLOG
#endif
#endif
#endif
</code></pre>
<p>And here is the sandbox (example usage) for you to play with the logger</p>
<p><strong>Sandbox.cpp</strong></p>
<pre><code>#include "lwlog/lwlog.h"
int main()
{
std::string str1 = "test";
std::string str2 = "for";
lwlog::print("That's a {0} message {1} you. \n\n", str1, str2);
std::shared_ptr<lwlog::logger> core_logger = std::make_shared<lwlog::logger>("LOGGER");
std::shared_ptr<lwlog::logger> core_ldsdogger = std::make_shared<lwlog::logger>("LOGGER2");
std::shared_ptr<lwlog::logger> core_logaager = std::make_shared<lwlog::logger>("LOGGER3");
lwlog::registry::instance().display_all_loggers();
lwlog::registry::instance().drop("LOGGER2");
lwlog::print("\n");
lwlog::registry::instance().display_all_loggers();
core_logger->set_logLevel_visibility(lwlog::log_level::error | lwlog::log_level::critical);
core_logger->set_pattern("[%x] [%n]: %v");
core_logger->critical("A very critical message!");
return 0;
}
</code></pre>
<p>Still, there is no documentation, but I guess it will be simple to navigate since there is a Sandbox project for you to play with the library's features.</p>
<p>Any suggestions, opinions on code quality and performance are welcome, as well as feature suggestions. I suggest taking a closer look in terms of performance into the print method within lwlog.h, and maybe the detail.h file's contents.</p>
<p>P.S. Be aware that I started it a couple of days ago, so It's not so rich in features, so again, any suggestions for features are welcome. When it comes to multithreaded loggers, thread-safety, async and logging in files - I have these features on my mind, will try my best to implement them. Also, colored logs are something I'm working on using the ANSI escape codes.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T17:47:02.677",
"Id": "429387",
"Score": "4",
"body": "If it makes you feel better, my experience with code review is that they don't judge you for \"reinventing-the-whee\"'. They just help improve your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T17:56:15.147",
"Id": "429388",
"Score": "1",
"body": "Yes, figured that out. I only want constructive critique, opinions and suggestions all for the improvement of the code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T21:10:00.893",
"Id": "429498",
"Score": "0",
"body": "Why is `m_message` a field? Unless I missed it, nothing ever reads it. Why is `m_logLevel` a field instead of being passed into the print method like `message`? If this were ever used from multiple threads, bad things would happen. I guess the intent is that every thread would use its own logger?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T21:12:26.623",
"Id": "429501",
"Score": "0",
"body": "I'm not a C++ dev; I haven't really touched it in many years, but it seems strange to see a logging library with no facility for logging exceptions. Maybe it's because I'm coming from the managed code world, but aren't exception stack traces a thing in C++?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T21:39:49.583",
"Id": "429505",
"Score": "1",
"body": "@David Not in standard C++. You have to write platform-specific code to get a stack trace from an exception."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T23:02:02.360",
"Id": "429516",
"Score": "0",
"body": "@CodyGray Fair enough. Thanks for the info. Cheers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T02:45:39.580",
"Id": "429525",
"Score": "0",
"body": "*Must* *have* *trace* ... ! No, seriously. I realize that this is really about the code itself, but you are surely asking about API design, too. A logging library that does not have a trace-level would be very disappointing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T07:22:34.317",
"Id": "429531",
"Score": "0",
"body": "@CodyGray: Look at [Boost::stacktrace](https://www.boost.org/doc/libs/1_70_0/doc/html/stacktrace.html)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T07:38:33.107",
"Id": "429532",
"Score": "1",
"body": "@DavidConrad: See my answer (and my last comment)."
}
] | [
{
"body": "<p>I see a number of things that may help you improve your code.</p>\n\n<h2>Separate interface from implementation</h2>\n\n<p>The interface goes into a header file and the implementation (that is, everything that actually emits bytes including all functions and data) should be in a separate <code>.cpp</code> file. In this case virtually everything in <code>datetime.h</code> and all <code>static</code> functions in <code>detail.h</code> should actually not be <code>static</code> but should instead be split into <code>.h</code> and <code>.cpp</code> files instead. The same is true for both the <code>log_level</code> operator functions in <code>lwlog.h</code>.</p>\n\n<h2>Make sure you have all required <code>#include</code>s</h2>\n\n<p>The code uses <code>std::string</code> in <code>datetime.h</code> but doesn't <code>#include <string></code>. Also, carefully consider which <code>#include</code>s are part of the interface (and belong in the <code>.h</code> file) and which are part of the implementation per the above advice.</p>\n\n<h2>Be careful with signed and unsigned</h2>\n\n<p>In the current <code>string_to_numeric_vec()</code> routine, the loop integers <code>i</code> is a signed <code>int</code> value, but it's being compared with quantity <code>format_string_tokens_vec.size()</code> which returns a <code>std::size_t</code>. Better would be to declare <code>i</code> as <code>std::size_t</code>.</p>\n\n<h2>Fix the bugs</h2>\n\n<p>Right now, the <code>remove_duplicates_in_vec</code> routine incorrectly reverses the order of the passed parameters so the message printed says \"That's a for message test you.\" which is clearly not what was intended. Also, if we call it like this:</p>\n\n<pre><code>lwlog::print(\"That's a {0} message {1} you. \\n\\n\", str1, \"{1}\");\n</code></pre>\n\n<p>It prints \"That's a test message test you.\" which is also suspect.</p>\n\n<h2>Reconsider the approach</h2>\n\n<p>The use of the <code>regex</code> and <code>unordered_set</code> and <code>vector</code> variables in this seem overly complicated to me. A lot of wasted work is done as well, such as setting up all of the variables in <code>print_formatted</code> instead of just the ones that are actually used. Further, the use of variadic templates instead of variadic functions means that there is considerable code bloat. On my 64-bit Linux box using <code>gcc</code> with <code>-O2</code> optimizations, adding these five lines adds over 11120 bytes to the size of the executable.</p>\n\n<pre><code> lwlog::print(\"{0}\\n\", 1);\n lwlog::print(\"{0}\\n\", 1.0f);\n lwlog::print(\"{0}\\n\", 1u);\n lwlog::print(\"{0}\\n\", 1l);\n lwlog::print(\"{0}\\n\", \"no\");\n</code></pre>\n\n<p>Also, this code is not thread safe. If I were writing this, I would probably start with something like <a href=\"https://en.cppreference.com/w/cpp/io/basic_osyncstream\" rel=\"noreferrer\"><code>std::basic_osyncstream</code></a>.</p>\n\n<h2>Use <code>const</code> where practical</h2>\n\n<p>There are a few places, such as the <code>reg</code> declaration in <code>print</code> that would be better as <code>static const</code>.</p>\n\n<h2>Avoid relative paths in <code>#include</code>s</h2>\n\n<p>Generally it's better to omit relative path names from <code>#include</code> files and instead point the compiler to the appropriate location.</p>\n\n<pre><code>#include \"lwlog/lwlog.h\"\n</code></pre>\n\n<p>For gcc, you'd use <code>-I</code>. This makes the code less dependent on the actual file structure, and leaving such details in a single location: a Makefile or compiler configuration file.</p>\n\n<h2>Omit <code>return 0</code> at the end of <code>main</code></h2>\n\n<p>In both C and C++, the compiler will automatically create the code that is the exact equivalent of <code>return 0;</code> so it can safely be omitted.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T06:25:14.467",
"Id": "429446",
"Score": "24",
"body": "Man, I hate that omitting the return statement at the end of the main function has become standard fare on Code Review. It is not good advice. Yes, it's legal and the compiler will silently generate the equivalent code on your behalf, but that doesn't make it a good idea. Good code is clear and explicit. Therefore, good code should `return EXIT_SUCCESS` at the end of the main function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T07:44:12.547",
"Id": "429447",
"Score": "2",
"body": "@CodyGray do you also explicitly write `return;` at the end of every `void` function?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T08:50:00.120",
"Id": "429451",
"Score": "8",
"body": "@Edward no, but void functions do not return an int somewhere else as main() does to the OS. We do write \"return 0;\" at the end of each function that returns an int."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T08:51:52.900",
"Id": "429452",
"Score": "2",
"body": "It seems to be a matter of taste. Some like it and others don’t."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T08:54:47.643",
"Id": "429453",
"Score": "8",
"body": "@Edward main doesn't return `void`, it turns `int`. `void` is valueless, `int` is not. This is why we omit `return void; ` at the end of void returning functions even though it's allowed. Your question is a strawman. It doesn't motivate why we shouldn't be explicit about the return from main."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T08:58:34.470",
"Id": "429454",
"Score": "4",
"body": "I value concise, accurate code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T09:52:44.557",
"Id": "429458",
"Score": "0",
"body": "@Edward concise = short code = no `return`ing; accurate = code that clearly shows what it does = with `return EXIT_SUCCESS;`. While I do agree that it's matter of taste, I wouldn't post this as recommendation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T11:36:25.813",
"Id": "429462",
"Score": "10",
"body": "@Edward I do not have a problem with you omitting the return or what type of code you value. What I'm concerned about is that omitting it is being presented as if it was best practice while it is clearly not established as such. It is a personal preference that is being passed on as general advice, and I believe that's misinformation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T12:08:41.630",
"Id": "429463",
"Score": "6",
"body": "I’ll think about a better way to convey the idea in future answers. Thanks all for your feedback."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T15:34:25.907",
"Id": "429592",
"Score": "0",
"body": "A rule-of-thumb that works for me is *if there are any error exits, then explicitly return at the end of `main()`, else don't*. I too, was slow to see the value of omitting the `return` statement from `main()`, but it does reduce clutter in simple straight-through programs such as this one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T15:36:26.490",
"Id": "429594",
"Score": "0",
"body": "@TobySpeight: That's exactly the rule of thumb that I use."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-11T10:13:05.777",
"Id": "429678",
"Score": "0",
"body": "@val \"accurate\" = syntactically correct code which has exactly the desired effects. Not more and not less. Being *easily understandable* is an orthogonal feature (inaccurate code may well be easily understandable, sometimes more so because it may not handle all the border cases)."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T15:46:03.817",
"Id": "221934",
"ParentId": "221922",
"Score": "20"
}
},
{
"body": "<ul>\n<li><p>Making functions in header files static means that <a href=\"https://stackoverflow.com/questions/780730/c-c-static-function-in-header-file-what-does-it-mean\">each translation unit gets its own separate definition</a>. This usually isn't what we want. Standard practice is to declare the function in the header, and then define it in a <code>.cpp</code> file, e.g.:</p>\n\n<pre><code>// header:\n\n#include <string>\n\nnamespace lwlog\n{\n namespace datetime\n {\n std::string get_current_time_and_date(const char* format);\n }\n}\n</code></pre>\n\n<p>.</p>\n\n<pre><code>// .cpp:\n\n#include <iomanip>\n#include <sstream>\n#include <chrono>\n#include <ctime>\n\nnamespace lwlog\n{\n namespace datetime\n {\n static std::string get_current_time_and_date(const char* format)\n {\n auto now = std::chrono::system_clock::now();\n auto in_time_t = std::chrono::system_clock::to_time_t(now);\n\n std::stringstream ss;\n ss << std::put_time(std::localtime(&in_time_t), format);\n return ss.str();\n }\n }\n}\n</code></pre>\n\n<p>While this is a pain in the butt, it means that anyone including <code>datetime.h</code> doesn't also get the <code>sstream</code> <code>chrono</code>, etc. headers as an unnecessary side-effect.</p></li>\n</ul>\n\n<hr>\n\n<ul>\n<li><p>Prefer to declare variables as close to the point of use as possible, and (ideally) assign the necessary value directly, e.g. for the local variables in the print function.</p></li>\n<li><p>Descriptive names are nice, but something like <code>detail::populate_vec_with_variadic_params</code> is probably overkill. Maybe <code>detail::string_vec_from_args</code> instead? Likewise with the local variables: <code>variadic_arguments_vec</code> -> <code>arguments</code>, <code>format_string_tokens_vec</code> -> <code>format_tokens</code>.</p></li>\n</ul>\n\n<hr>\n\n<p>The various <code>detail</code> functions used to print with could be simplified quite a bit:</p>\n\n<ul>\n<li><p>Rather than <code>populate_vec_with_variadic_params</code> we can define our own to_string function, and then do something like:</p>\n\n<pre><code>namespace detail\n{\n\n std::string to_string(std::string s) { return s; }\n\n template<class T>\n std::string arg_to_string(T&& t)\n {\n using detail::to_string;\n using std::to_string;\n return to_string(std::forward<T>(t));\n }\n\n} // detail\n\n...\n\n auto arguments = std::vector<std::string>{ detail::arg_to_string(std::forward<Args>(args))... };\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/a/37425306/673679\">This has the advantage of allowing users to specify to_string functions for their own classes too.</a></p></li>\n</ul>\n\n<hr>\n\n<ul>\n<li><p><code>populate_vec_with_regex_matches_from_str</code>:</p>\n\n<ul>\n<li>shouldn't take <code>s</code> by reference, as it doesn't change <code>s</code> (this allows us to eliminate the temp variable).</li>\n<li>should simply return a vector, instead of altering one.</li>\n<li>should use iterators to avoid unnecessary copies (both internally, and in the vector it returns).</li>\n<li>rather than capturing the curly brackets and then removing them later, we can just capture the number inside the curly brackets.</li>\n<li><p>we need to capture one or more digit inside the brackets, not a single digit character, or the function will stop working when we get to 10 arguments.</p>\n\n<pre><code>using substring_view = std::pair<std::string::const_iterator, std::string::const_iterator>;\n\nstd::vector<substring_view> find_matches(std::regex rg, std::string const& s)\n{\n auto result = std::vector<substring_view>();\n\n auto begin = s.cbegin();\n auto const end = s.cend();\n\n std::smatch match;\n while (std::regex_search(begin, end, match, rg))\n {\n result.push_back({ match[1].first, match[1].second });\n begin = match.suffix().first;\n }\n\n return result;\n}\n\n...\n\n auto format_strings = detail::find_matches(std::regex(\"\\\\{(\\\\d+)\\\\}\"), format_str);\n</code></pre></li>\n</ul></li>\n</ul>\n\n<hr>\n\n<ul>\n<li><code>remove_duplicates_in_vec</code>:\n\n<ul>\n<li>can be a call to <code>std::unique</code>. </li>\n<li>should be applied to <code>format_strings_tokens_vec</code> instead of <code>variadic_arguments_vec</code>!!! We want to remove duplicate indices, not duplicate arguments.</li>\n</ul></li>\n</ul>\n\n<hr>\n\n<ul>\n<li><p><code>string_to_numeric_vec</code>:</p>\n\n<ul>\n<li>could use <code>std::transform</code>.</li>\n<li>should produce indices of <code>std::size_t</code> (a.k.a. <code>std::vector<T>::size_type</code>), not <code>int</code>.</li>\n<li>should probably do some sort of error handling on conversion failure (even just assertions).</li>\n<li><p><code>std::from_chars</code> is probably the best standard converter available for this.</p>\n\n<pre><code>std::vector<std::size_t> convert_indices(std::vector<substring_view> const& s)\n{\n auto result = std::vector<std::size_t>(s.size(), 0);\n\n auto convert = [] (substring_view const& v)\n {\n auto const begin = &*v.first;\n auto end = &*v.second;\n auto value = std::size_t{ 0 };\n auto result = std::from_chars(begin, end, value);\n\n assert(result.ptr == end);\n assert(result.ec == std::errc{ });\n\n return value;\n };\n\n std::transform(s.begin(), s.end(), result.begin(), convert);\n\n return result;\n}\n</code></pre></li>\n</ul></li>\n</ul>\n\n<hr>\n\n<ul>\n<li><p><code>replace_in_string</code> is called for every format token index, and iterates over the whole string each time, turning the complexity from O(n) to O(n^2). Yikes!</p>\n\n<p>We'll be doing much less work if we do the \"replacement\" at the same time as we do the regex search.</p></li>\n</ul>\n\n<p>So I'd probably do something like this:</p>\n\n<pre><code>#include <cassert>\n#include <charconv>\n#include <iostream>\n#include <regex>\n#include <string>\n#include <vector>\n\nnamespace detail\n{\n\n std::string to_string(std::string s) { return s; }\n\n template<class T>\n std::string arg_to_string(T&& t)\n {\n using detail::to_string;\n using std::to_string;\n return to_string(std::forward<T>(t));\n }\n\n std::size_t convert_index(std::string::const_iterator begin, std::string::const_iterator end)\n {\n auto value = std::size_t{ 0 };\n auto result = std::from_chars(&*begin, &*end, value);\n\n assert(result.ptr == &*end);\n assert(result.ec == std::errc{ });\n\n return value;\n };\n\n} // detail\n\ntemplate<typename... Args>\nstd::string format(std::string const& format_str, Args&&... args)\n{\n auto const arguments = std::array<std::string, sizeof...(Args)>{ detail::arg_to_string(std::forward<Args>(args))... };\n\n auto arguments_total_size = std::size_t{ 0 };\n for (auto const& a : arguments)\n arguments_total_size += a.size();\n\n auto result = std::string();\n result.reserve(format_str.size() + arguments_total_size);\n\n auto begin = format_str.cbegin();\n auto const end = format_str.cend();\n auto const regex = std::regex(\"\\\\{(\\\\d+)\\\\}\");\n\n while (true)\n {\n std::smatch match;\n if (!std::regex_search(begin, end, match, regex))\n break;\n\n result.append(match.prefix().first, match.prefix().second);\n\n auto index = detail::convert_index(match[1].first, match[1].second);\n result.append(arguments.at(index));\n\n begin = match.suffix().first;\n }\n\n result.append(begin, end);\n\n return result;\n}\n\nint main()\n{\n std::cout << format(\"test: {0}, {1}, {0}, {3}\", \"5\", 5, 123.f, std::string(\"test\")) << std::endl;\n}\n</code></pre>\n\n<p>N.B. We could just send everything straight to <code>std::cout</code> instead of building the formatted string.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T16:46:01.483",
"Id": "221940",
"ParentId": "221922",
"Score": "14"
}
},
{
"body": "<p>Lots of good code comments already given. I'll focus on non-code aspects.</p>\n\n<p>Take this from a DevOps engineer that regularly troubleshoots complex, unfamiliar systems from logs under time pressure.</p>\n\n<p>You want all logs to always be consistently formatted and to have timestamp and location (source file and line) by default, it looks like you request the date with format specifiers. You want context if it is available (e.g. request id). You want to easily print non-pod types as well and it looks like that is not possible with your design relying on <code>to_string()</code> which only accepts pods. Typically you'd use a design based on something that inherits from <code>std::ostream</code> so that your regular <code>operator<<(ostream&, const T&)</code> will work.</p>\n\n<p>When I did this AGES ago, I used a custom buffer class that <em>tee'd</em> to a file and <code>cout</code> that I injected into <code>std::clog</code> using <a href=\"https://en.cppreference.com/w/cpp/io/basic_ios/rdbuf\" rel=\"noreferrer\">rdbuf(...)</a>and then created a set of macros to print location and time like: </p>\n\n<pre><code> #define ERROR std::clog<<date_time_now()<<\", status=ERROR (\"<<__FILE__<<\":\"<<__LINE__<<\"): \"\n\n ERROR << \"Honey, I shrunk the kids! \" << m_kids << std::endl;\n</code></pre>\n\n<p>Macros are the devil but also the only way of getting line number and file name automatically into the log line. Unless there is some new hotness in c++17/2x i don't know off.</p>\n\n<p>Please excuse the brevity and lack of formatting, I'm typing this on a phone.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T09:55:30.093",
"Id": "429459",
"Score": "0",
"body": "Isn't it better to make this macro-like function and drop `;` at the end of line?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T11:24:51.947",
"Id": "429461",
"Score": "2",
"body": "Whatever works for you. The semicolon was unintended force of habit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T01:56:21.663",
"Id": "429523",
"Score": "6",
"body": "Regarding new hotness, `source_location` has design approval, so there's a good chance we'll see that standardized in time for C++2b and finally have a good way of capturing that information."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T17:28:44.340",
"Id": "221945",
"ParentId": "221922",
"Score": "26"
}
},
{
"body": "<p>You have some good answers already. My criticism comes from one word. \"printf\".</p>\n\n<p>The problem for fault-finding is not just knowing what each part has reported, but also knowing in what order they happened. Any practical logging library is going to hit threads sooner or later, and at that point things go wrong.</p>\n\n<p>For starters, we need to think about thread-safe printing. The behaviour of printf when called from two threads simultaneously is not defined, but typically you'll find one interrupts the other mid-print to print its own text, then the next one finishes. The result is not very readable.</p>\n\n<p>And we also need to think about \"Heisenbugs\" where the test code changes the behaviour of the system so that your fault-finding is invalidated. printf is relatively slow, so by the time it's done, a second thread whose interaction caused the bug you're investigating would be in a completely different state.</p>\n\n<p>And lastly, you might want your logging to in several different directions. Perhaps you want normal level messages to go to the screen, verbose to go to the main log file, and critical messages to go to a secure registry. You can't do that here.</p>\n\n<p>I've built a logging library myself to sort these problems. (This was a few years ago, when the libraries available were less good.) There were several key features:-</p>\n\n<ul>\n<li>The function logging an error in a thread stored the log details.</li>\n<li>The function then passed that atomically to a singleton log store which pushed the log details into a FIFO. (Actually a FIFO of pointers, because you don't want to waste time copying stuff.)</li>\n<li>At regular intervals and at low priority, the log store popped a batch of FIFO entries and sent them to one or more registered log printers.</li>\n<li>Each log printer had options for setting log levels it was interested in.Running in separate threads and again at low priority, each dumped details of those logs it was interested in to its chosen destination.</li>\n</ul>\n\n<p>So it became quite a complex structure, and the output side needed to be much more heavyweight, but the result was to make logging during execution almost unnoticeable. This allowed us to use our logging to accurately fault-find issues happening between threads in an application controlling hardware, databases, user interface, files, etc..</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T23:42:30.057",
"Id": "221982",
"ParentId": "221922",
"Score": "10"
}
},
{
"body": "<p>A few more suggestions in addition to the great existing answers:</p>\n\n<h2>Support logging stack traces - it's easy!</h2>\n\n<p>Standard C++ offers no facilities for obtaining stack traces, so traditionally - logging libraries and manual logging have foregone those. But these traces are extremely useful in inspecting logs and debugging programs (despite their verbosity); and developers in other languages, especially non-compiled ones, ridicule us for not having them!</p>\n\n<p>Well, recently, Antony Polukhin (of magic_get fame) has undertaken the task of combining the available platform-specific stack walking libraries into a single multi-platform Boost library named <a href=\"https://www.boost.org/doc/libs/1_70_0/doc/html/stacktrace.html\" rel=\"noreferrer\">stacktrace</a>. Its plain vanilla use is as simple as:</p>\n\n<pre><code>#include <boost/stacktrace.hpp>\n\n// ... etc. etc. ...\n\nstd::cout << boost::stacktrace::stacktrace();\n</code></pre>\n\n<p>and it has facilities for decorating exceptions with stack traces etc.</p>\n\n<h3>Consider using string views instead of std::string references</h3>\n\n<p>If you pass a temporary string to a function taking a <code>const string&</code>, but then initialize some <code>std::string</code> with it, you get - yes, you know it - you get a string copy. And indeed, it seems you do just that. </p>\n\n<p>Also, <code>std::string</code>'s live on the heap. Do you really want to be making a bunch of heap allocations? Surely not; or at least - as few as possible. What's more, you may be forcing whoever is passing you the string to construct an <code>std::string</code> and to know about <code>std::string</code>. I would try to avoid that too.</p>\n\n<p>So, what's the alternative? <a href=\"https://en.cppreference.com/w/cpp/string/basic_string_view\" rel=\"noreferrer\"><code>std::string_view</code></a>. It's not perfect (in the sense you have to be a little careful when using it), but it's a pretty good idea still:</p>\n\n<p><a href=\"https://stackoverflow.com/q/40127965/1593077\">How exactly is <code>std::string_view</code> faster than <code>const std::string&</code>?</a></p>\n\n<p>if you're writing pre-C++17 code, you can find a string view in <a href=\"https://github.com/Microsoft/GSL\" rel=\"noreferrer\">implementations</a> of the Guidelines Support Library.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T07:38:10.040",
"Id": "221989",
"ParentId": "221922",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T11:58:26.010",
"Id": "221922",
"Score": "28",
"Tags": [
"c++",
"performance",
"reinventing-the-wheel",
"logging",
"c++17"
],
"Title": "C++ logging library"
} | 221922 |
<p>It's a simple bash script but I'm hoping for feedback, advice and examples on how to improve the script and code. Can you guide me how to put more checks in the code and more if possible?</p>
<p>This code:</p>
<ul>
<li>Sets <code>IFS</code> variable and backs it up</li>
<li>Sets a trap for signals that can kill the script and a trap for exit to do run a cleanup function.</li>
<li>Then it pushes changes from the local <code>TO</code> the remote repository</li>
<li>Then it syncs the local copy <code>FROM</code> the repository/fork</li>
<li>Then there is code to update the <code>Fork</code> from the <code>original</code> but that will be used later on other repositories.</li>
<li>Then it gives control back to these signals <code>SIGINT</code> <code>SIGQUIT</code> <code>SIGTERM</code></li>
<li>Then it's set to send a email with the result/status of what's been run after the<code>exit</code></li>
</ul>
<p></p>
<pre><code>#!/usr/bin/env bash
IFS_OLD=$IFS
IFS=$'\n\t'
cleanup ()
{
if [ -n "$1" ]; then
echo "Aborted by $1"
elif [ $status -ne 0 ]; then
echo "Failure (status $status)"
else
echo "Success"
IFS=$IFS_OLD
#cd "$HOME" || { echo "cd $HOME failed"; exit 155; }
fi
}
trap 'status=$?; cleanup; exit $status' EXIT
trap 'trap - HUP; cleanup SIGHUP; kill -HUP $$' HUP
############################################################################ Sync the local TO the remote ##########################################
#{
#{ #...part of script with redirection...
#} > file1 2>file2 # ...and others as appropriate...
cd /home/kristjan/gitRepo_May2019/ || { echo "Failed to cd to /home/kristjan/gitRepo_May2019/!!!!!!!!"; exit 155; }
git add -A || { echo "Failed to git add -A: Sync the local TO the remote!!!!!!!!"; exit 155; } |
if ! `grep -r up-to-date`
then
git commit -m 'One small commit for man, one giant leap for melted MacBooks, UNIX and Linux are the best!!!!!!!!!!!!!!!!!!!!!!!!!' || { echo "Failed to git commit -m '......': Sync the local TO the remote!!!!!!!!"; exit 155; }
git push -u origin master || { echo "Failed to git push -u origin master: Sync the local TO remote!!!!!!!!"; exit 155; }
fi
##################################################################333#3# Sync the local copy FROM the original repository/fork(github) ####################################
#git remote add upstream https://github.com/ORIGINAL_OWNER/ORIGINAL_REPOSITORY.git
#git remote add upstream https://github.com/somethingSomething78/C_Programming.git || { echo "Failed to git remote add upstream ........https://....: sync local copy FROM repo!!!!!!!!"; exit 155; }
#cd gitRepo_May2019/ || { echo "Failed to cd to the install directory!!!!!!!!"; exit 155; }
#sleep 2
git fetch upstream || { echo "Failed to fetch upstream: sync local copy FROM repo!!!!!!!!"; exit 155; }
git checkout master || { echo "Failed to git checkout master: sync local copy FROM repo!!!!!!!!"; exit 155; }
git merge upstream/master || { echo "Failed to git merge upstream/master: sync local copy FROM repo!!!!!!!!"; exit 155; }
####################################################################### Sync the remote fork with the ORIGINAL repository(github)
# Setting and configuring under a new filename and for other repo's
#git clone git@github.com:YOUR-USERNAME/YOUR-FORKED-REPO.git
#cd into/cloned/fork-repo
#git remote add upstream git://github.com/ORIGINAL-DEV-USERNAME/REPO-YOU-FORKED-FROM.git
#git fetch upstream
#git pull upstream master
echo "Finished syncing system and remotes!"
sleep 2
############ Give control back to these signals
trap SIGINT SIGQUIT SIGTERM
############################
#} > file1 2>file2 # ...and others as appropriate...
exit 0
</code></pre>
<p><strong>This is my <code>.git/config</code></strong> for connecting to the servers with <code>ssh keys</code> (you could notice that <code>origin</code> and <code>upstream</code> are the same but that's because this git is not a fork but my personal private repo, this code will come to much better use when I setup <code>syncing</code> my forks):</p>
<pre><code> [core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
[remote "origin"]
url = ssh://C_Programming:somethingSomething78/C_Programming.git
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
remote = origin
merge = refs/heads/master
[remote "upstream"]
url = ssh://C_Programming/somethingSomething78/C_Programming.git
fetch = +refs/heads/*:refs/remotes/upstream/*
</code></pre>
<p>I also had to setup <code>ssh key</code> for this particular repo and I have edited my <code>.ssh/config</code> file like this:</p>
<pre class="lang-none prettyprint-override"><code>Host C_Programming
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa-GITHUBSCRIPT
</code></pre>
<h2>Here I am testing the script:</h2>
<pre class="lang-none prettyprint-override"><code>[08:58:57][kristjan] ~ ~↓↓$↓↓ ./gitRepo_May2019.sh | mail -s "Github SYNC System Report: `hostname`" somethingSomething@mail.com
Already on 'master'
</code></pre>
<h2>This is the mail it sent afterwards:</h2>
<pre class="lang-none prettyprint-override"><code>> Github SYNC System Report: Kundrum Hallur Kristjan Stefansson
> <somethingSomething@mail.com> 09:00 (3 hours ago)
> Your branch is
> up-to-date with 'origin/master'.
> Already up-to-date.
> Finished syncing system and remotes!
> Success
</code></pre>
<p>I put it in a cron(<code>crontab -e</code>) on my <code>Debian Stretch 9.9</code> system:</p>
<pre class="lang-none prettyprint-override"><code>21 00 * * 7 /bin/bash /home/kristjan/gitRepo_May2019.sh | mail -s "Github SYNC System Report: `hostname`" somethingSomething@mail.com
</code></pre>
<p>Here are other questions on this site with code for the same or similar purpose:</p>
<p><a href="https://codereview.stackexchange.com/questions/166646/rust-github-repository-downloader">Rust GitHub repository downloader</a></p>
<p><a href="https://codereview.stackexchange.com/questions/75432/clone-github-repository-using-python">Clone GitHub repository using Python</a></p>
<p><a href="https://codereview.stackexchange.com/questions/159451/python-script-to-synchronise-your-locally-cloned-fork-to-its-parent-github-repos">Python script to synchronise your locally cloned fork to its parent github repository</a></p>
| [] | [
{
"body": "<p>There's no need to reinstate the initial value of <code>IFS</code> because there's nowhere for the new value to propogate. When your script exits, the new value just ceases to exist. Same goes for the signal handlers.</p>\n\n<p>On that note, why set <code>IFS</code> at all? I can't see any place that it has an effect.</p>\n\n<p>Prefer <code>[[ … ]]</code> over <code>[ … ]</code> for tests (<a href=\"https://stackoverflow.com/a/3427931/2570502\">detailed explanation</a>). </p>\n\n<p>When testing for zero, consider an arithmetic test <code>(( … ))</code>: it returns true for non-zero and false for zero, and doesn't require <code>$</code> in front of ordinary variable names (specials like <code>$*</code> or <code>$#</code> still need the dollar sign).</p>\n\n<p>For example, <code>cleanup()</code> might be rewritten:</p>\n\n<pre><code>cleanup() { \n (( $# )) && echo \"Aborted by $1\" && return\n (( status )) && echo \"Failure (status $status)\" && return $status\n echo \"Success\"\n}\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>cd /home/kristjan/gitRepo_May2019/ || { echo \"Failed to cd to /home/kristjan/gitRepo_May2019/!!!!!!!!\"; exit 155; }\n</code></pre>\n</blockquote>\n\n<p>This is a common pattern that can benefit from the use of a function:</p>\n\n<pre><code> die() { echo \"$2\"; exit $1; }\n\n cd $dir || die 155 \"Failed to cd to $dir\" \n</code></pre>\n\n<p>Alternatively, the command's error output is usually good enough:</p>\n\n<pre><code> cd $dir || exit 155 \n</code></pre>\n\n<p>Or, since you're checking basically everything for error exit, put <code>set -e</code> at the top of the script to make any error fatal.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>if ! `grep -r up-to-date`\n</code></pre>\n</blockquote>\n\n<p>Don't use backticks here, recursively grepping STDIN doesn't make any sense, and grep's <code>-w</code> switch is probably appropriate:</p>\n\n<pre><code> if ! grep -w up-to-date\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T01:57:07.667",
"Id": "221953",
"ParentId": "221926",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "221953",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T13:07:27.160",
"Id": "221926",
"Score": "3",
"Tags": [
"beginner",
"bash",
"linux",
"git",
"ssh"
],
"Title": "Syncing GitHub repositories local, remote and forks"
} | 221926 |
<p><strong>The task</strong> is taken from LeetCode</p>
<blockquote>
<p><em>Given an array of meeting time intervals consisting of start and end times [[s1,e1],[s2,e2],...] (si < ei), find the minimum number of
conference rooms required.</em></p>
<p><strong>Example 1:</strong></p>
<pre><code>Input: [[0, 30],[5, 10],[15, 20]]
Output: 2
</code></pre>
<p><strong>Example 2:</strong></p>
<pre><code>Input: [[7,10],[2,4]]
Output: 1
</code></pre>
<p><strong>NOTE:</strong> <em>input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.</em></p>
</blockquote>
<p><strong>My solution</strong></p>
<pre><code>/**
* @param {number[][]} intervals
* @return {number}
*/
var minMeetingRooms = function(intervals) {
if (intervals.length <= 1) { return intervals.length; }
const startTimes = [];
const endTimes = [];
intervals.forEach(x => {
startTimes.push(x[0]);
endTimes.push(x[1]);
});
startTimes.sort((a, b) => a - b);
endTimes.sort((a, b) => a - b);
let startPointer = 0;
let endPointer = 0;
let rooms = 0;
while(startPointer < intervals.length) {
if (startTimes[startPointer++] >= endTimes[endPointer]) {
++endPointer;
} else {
++rooms
}
}
return rooms;
};
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T13:34:39.700",
"Id": "429359",
"Score": "0",
"body": "Can downvoters please explain the reason why they downvoted this question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T14:17:25.313",
"Id": "429368",
"Score": "3",
"body": "I personally did not downvote but I'd recommend taking a look at [Simon's Guide to posting a good question](//codereview.meta.stackexchange.com/a/6429). You could improve by providing a description of the approach you are using, for example. Also, why is this called \"Meeting Rooms II\"? Is it a follow-up to a previous question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T14:44:14.177",
"Id": "429372",
"Score": "1",
"body": "Also, your link leads to Leetcode Premium. I mean, not everyone will have a premium account on Leetcode (such as myself)."
}
] | [
{
"body": "<p>The code looks much simpler than I would expect for this task. I tried several examples but could neither make it fail, nor did I understand why and how this algorithm works, I was only delighted that it seems to work. Therefore I have only a few remarks.</p>\n\n<p>The early return for <code>length <= 1</code> is not necessary.</p>\n\n<p>The <code>++rooms</code> is missing the semicolon.</p>\n\n<p>Apart from that, it looks perfect.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T06:07:03.143",
"Id": "440601",
"Score": "1",
"body": "Whenever a meeting finishes, no new room is required for the next start. Whenever a meeting starts while a meeting is in progress, a new room is required. A meeting is in progress when _startTimes[startPointer] < endTimes[endPointer]_. The neat trick is that _endPointer_ gets incremented conditionally and that the algorithm does not care about a meeting as start-end, but looks at all meetings as a set of starts and ends."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-24T21:55:11.287",
"Id": "440947",
"Score": "1",
"body": "You sort the `startTime` and `endTime`. Then you iterate through every `startTime` and compare it with the current smallest `endTime`. If there is a `startTime` that is less than the current `endTime`, then you know there is a meeting still going on. Therefore you need a room. If the `startTime` is equal or greater than the `endTime`, then you know a meeting has ended and is free and you can use that free room for your current meeting. Therefore no new room is need, instead you look at the next `endTime` (i.e. increment the `endPointer`). And so on. You do this until all meetings are checked."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T05:40:43.383",
"Id": "226666",
"ParentId": "221927",
"Score": "2"
}
},
{
"body": "<p>A solution in C++ could use a min heap to store the end times.\nThis will help clean the code as you could achieve implicit sorting by using min heap.</p>\n<pre><code>int solve(vector<vector<int> > &A) {\n priority_queue<int,vector<int>,greater<int>> pq;\n sort(A.begin(), A.end());\n for(auto& i : A){\n pq.push(i[1]);\n }\n int ans = 0;\n for(int i = 0 ; i < A.size() ; ++i){\n if(!pq.empty() && A[i][0] >= pq.top())\n pq.pop();\n else\n ++ans;\n }\n return ans;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T13:34:20.513",
"Id": "498060",
"Score": "0",
"body": "Welcome to the Code Review Community, you could improve your answer by explaining why adding a min heap improves the solution. Code only answers can be down voted and deleted by the community."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-28T13:55:17.360",
"Id": "498230",
"Score": "0",
"body": "@RolandIllig This is true. I added the language."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-26T13:19:06.647",
"Id": "252711",
"ParentId": "221927",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "226666",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T13:14:20.267",
"Id": "221927",
"Score": "3",
"Tags": [
"javascript",
"algorithm",
"programming-challenge"
],
"Title": "Given time intervals, find the minimum number of conference rooms required"
} | 221927 |
<p>I am looking for some way to improve my code. It works but it doesn't look good and I am almost sure that lot of Best Practices rules are violated.</p>
<p>The <code>save_session()</code> function, creates dictionary with other dictionaries nested in. At the end the dictionary is dump to .json file.</p>
<p><strong>I will appreciate any suggestions and advice for improvement of this code.</strong></p>
<p>For better understanding the code of <code>save_session()</code>:</p>
<p><code>workouts_instances</code> is the list of current <code>WorkoutPlan</code> instances,</p>
<p><code>WorkoutPlan</code> stores instances of <code>Training</code> and <code>Exercise</code>,</p>
<p><code>Training</code> stores instances of <code>Exercise</code>,</p>
<pre class="lang-py prettyprint-override"><code>class WorkoutPlan:
def __init__(self, name, trainings=list(), exercises=list()):
self.name = name
self.trainings = trainings
self.exercises = exercises
...
class Training:
def __init__(self, name, exercises=list()):
self.name = name
self.exercises = exercises
...
class Exercise:
def __init__(self, name, details=dict()):
self.name = name
self.details = details
...
</code></pre>
<p>Here is the code of <code>save_session()</code>:</p>
<pre class="lang-py prettyprint-override"><code>def save_session():
"""Exports current data to .json file."""
data_to_save = {}
# add workout plans
for workout in workouts_instances:
data_to_save[workout.name] = {}
# add trainings
if workout.trainings:
data_to_save[workout.name]["trainings"] = {}
for training in workout.trainings:
data_to_save[workout.name]["trainings"][training.name] = {}
# add training exercises
if training.exercises:
data_to_save[workout.name]["trainings"][training.name]['exercises'] = {
exercise.name: {} for exercise in training.exercises
}
for exercise in training.exercises:
if exercise.details:
data_to_save[workout.name]["trainings"][training.name]['exercises'][exercise.name][
'details'] = {detail: value for detail, value in
exercise.details.items()}
# add exercises
if workout.exercises:
data_to_save[workout.name]["exercises"] = {}
exercises_to_save = data_to_save[workout.name]["exercises"]
for exercise in workout.exercises:
exercises_to_save[exercise.name] = {}
if exercise.details:
details = exercise.details
exercises_to_save[exercise.name]['details'] = {detail: value for detail, value in details.items()}
with open(WORKOUTS_FILE, 'w') as json_file:
json.dump(data_to_save, json_file, indent=4)
</code></pre>
<p>and here is the example of output, data stored in .json file:</p>
<pre><code>{
"FBV - Full Body Workout": {
"trainings": {
"Training A": {
"exercises": {
"squats": {
"details": {
"description": "squats with barbell",
"series": 4,
"repeats": 4,
"load": 70
}
}
}
}
},
"exercises": {
"some exercise name": {
"details": {
"description": "some description",
"series": 5,
"repeats": 5,
"load": 60
}
},
"bench press - wide": {
"details": {
"description": "bench press with wide grip",
"series": 5,
"repeats": 5,
"load": 60
}
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T13:29:21.483",
"Id": "429357",
"Score": "0",
"body": "It would be better if you provide the code calling the function or example usage as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T13:38:22.063",
"Id": "429360",
"Score": "0",
"body": "@pacmaninbw: ```save_session()``` is one of the menu options in console app. All it has to do is to write data into dictionaries and dump it to .json later.\nAll I want to know is how to build this dictionary of nested dictionaries in more proper way than it is right now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T13:43:28.793",
"Id": "429361",
"Score": "1",
"body": "Right now the question is off-topic please see https://codereview.stackexchange.com/help/dont-ask and https://codereview.stackexchange.com/help/how-to-ask. By asking for examples of use I was trying to improve the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T13:51:32.463",
"Id": "429362",
"Score": "2",
"body": "Simply put, if you add example input and output it means it's easier for people to understand the transformation that is happening - help us, help you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T14:40:50.400",
"Id": "429371",
"Score": "0",
"body": "I made some edits. Is it better now?"
}
] | [
{
"body": "<p>Some suggestions:</p>\n\n<ul>\n<li>Do not use <a href=\"https://stackoverflow.com/a/1145781/96588\">mutable default arguments</a>, they will mess with your subsequent calls. There are some very rare cases where mutable default arguments make sense, but this does not look like one of those.</li>\n<li>Split generation of data from saving that data to a file. That way either method can be reused. If you also pull out the file handle to a <code>main</code> method you can dependency inject the file handle and test the whole functionality.</li>\n<li><code>details</code> have the same pattern everywhere, so they should also be a class or should be part of <code>Exercise</code>.</li>\n<li>Like most Python code this could benefit from type annotations using MyPy.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T06:33:01.253",
"Id": "221959",
"ParentId": "221928",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T13:20:23.297",
"Id": "221928",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"json",
"hash-map"
],
"Title": "Building nested dictionaries to dump it to .json later"
} | 221928 |
<p>I am currently learning Java Servlets and JSP at university. As a little practice I created a project where I want to be able to login into a protected area. Now, I got it working by using a RequestDispatcher. However, after I have been forwarded to the protected area, the URL in the browser shows <code>http://localhost:8080/jspractice02/FrontController</code>. I think it would make more sense to be <code>http://localhost:8080/jspractice02/protected/dashboard.jsp</code>. Should I use <code>sendRedirect</code> instead of a Dispatcher?
Another thing is that I don't know if my code structure is somewhat senseful, especially how I handle the login. I would love to get some feedback on that.</p>
<p><strong>Directory Structure</strong></p>
<pre><code>+-- src
| +-- main
| +-- java
| | +-- de.practice.PresentationLayer
| | +-- FrontController.java
| +-- webapp
| | +-- home.jsp
| | +-- protected
| | +-- dashboard.jsp
| | +-- add-student.jsp
</code></pre>
<p><strong>FrontController.java</strong></p>
<pre><code>package de.practice.Presentation;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class FrontController
*/
@WebServlet("/FrontController")
public class FrontController extends HttpServlet {
private static final long serialVersionUID = 1L;
private static String username = "";
private static String password = "";
private static String queryString = "";
/**
* Constructor
*/
public FrontController() {
super();
}
/**
* doGet
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String jsp = "";
queryString = request.getParameter("action");
if(queryString != null) {
switch(queryString) {
case "addStudent":
jsp = "protected/student.jsp";
}
RequestDispatcher rd = request.getRequestDispatcher(jsp);
rd.forward(request, response);
}
}
/**
* doPost
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
login(request, response);
}
/**
* validPassword
* @param request
* @param response
* @param password
* @return
*/
private boolean validPassword(HttpServletRequest request, HttpServletResponse response, String password) {
if(password.length() >= 3) {
return true;
}
return false;
}
/**
* validUsername
* @param request
* @param response
* @param username
* @return
*/
private boolean validUsername(HttpServletRequest request, HttpServletResponse response, String username) {
if(username.length() >= 3) {
return true;
}
return false;
}
/**
*
* @param request
* @param response
* @param password
* @param username
* @throws IOException
* @throws ServletException
*/
private void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// Get username and password
username = request.getParameter("username");
password = request.getParameter("password");
// check if they are valid
if(validUsername(request, response, username) && validPassword(request, response, password)) {
// If valid create session
HttpSession session = request.getSession();
session.setAttribute("username", username);
// and redirect to protected area
RequestDispatcher rd = request.getRequestDispatcher("protected/dashboard.jsp");
rd.forward(request, response);
} else {
// Code for invalid login
RequestDispatcher rd = request.getRequestDispatcher("login-failed.jsp");
rd.forward(request, response);
}
}
}
</code></pre>
<pre><code><%@ include file="partials/header.jsp"%>
<section id="start" class="panel">
<div class="container">
<h1>Home</h1>
<form class="form" method="post" action="FrontController">
<div class="form-group">
<label for="username">Username</label>
<input type="text" name="username" class="form-control">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" class="form-control">
</div>
<input type="submit" name="submitBtn" class="btn btn-primary">
</form>
</div>
</section>
<%@ include file="partials/footer.jsp"%>
</code></pre>
| [] | [
{
"body": "<pre><code>package de.practice.Presentation\n</code></pre>\n\n<p>That's not a valid package name under the Java convention. Packages are all lowercase with <em>maybe</em> underscores.</p>\n\n<hr>\n\n<pre><code>private static String username = \"\";\n</code></pre>\n\n<p>You don't want these <code>static</code>, actually, you don't want them as fields at all. When dealing with requests, you have to consider that one instance of the same class might handle multiple requests <em>simultaneously</em>. Having a state in the class (f.e. fields) has to be carefully considered.</p>\n\n<hr>\n\n<pre><code>protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n\n String jsp = \"\";\n queryString = request.getParameter(\"action\");\n\n if(queryString != null) {\n\n switch(queryString) {\n case \"addStudent\":\n jsp = \"protected/student.jsp\";\n }\n\n RequestDispatcher rd = request.getRequestDispatcher(jsp);\n rd.forward(request, response);\n }\n}\n</code></pre>\n\n<p>Consider mapping your requests and actions in a way which allows you to refer to locations directly without having to resort to a big switch statement.</p>\n\n<hr>\n\n<pre><code>private boolean validPassword(HttpServletRequest request, HttpServletResponse response, String password) {\n\n if(password.length() >= 3) {\n return true;\n }\n return false;\n}\n</code></pre>\n\n<p>We all know that's just a placeholder, but you could return directly:</p>\n\n<pre><code>return password.length() >= 3;\n</code></pre>\n\n<hr>\n\n<pre><code>RequestDispatcher rd = request.getRequestDispatcher(\"login-failed.jsp\");\nrd.forward(request, response);\n</code></pre>\n\n<p>You're repeating this action multiple times, consider a helper function. But you could also write that in one line.</p>\n\n<hr>\n\n<pre><code>/**\n * Constructor\n */\n</code></pre>\n\n<p>You might as well omit the Javadoc if it's not going to be useful.</p>\n\n<hr>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T16:35:42.193",
"Id": "221938",
"ParentId": "221929",
"Score": "5"
}
},
{
"body": "<p><strong>Critical error</strong></p>\n\n<pre><code>private static String username = \"\";\nprivate static String password = \"\";\nprivate static String queryString = \"\";\n</code></pre>\n\n<p>You should never keep request-scoped data in a field in a servlet. Servlet is created only once during application startup, and shared among all requests. So if several clients connect to your servlet at the same time, they might not reach the protected page, even if they provide correct password. It will also lead to setting wrong username attribute in the session object. If you had customized pages for each user, this could also lead to people seeing protected pages of other people. </p>\n\n<p>Solution - extract the sensitive request-scoped data in doGet method only. Also, simply removing the <code>static</code> keyword <strong>will not</strong> resolve the issue. </p>\n\n<p><strong>Code style</strong></p>\n\n<ol>\n<li>Get rid of empty JavaDoc that only makes the code harder to read</li>\n<li>Get rid of obvious comments that only make the code harder to read, like <code>// Get username and password</code></li>\n<li>Do not introduce redunant code (constructor that only calls <code>super()</code>)</li>\n<li>Improve method ordering. When you call <code>validUsername()</code> in <code>login()</code>, then <code>validUsername()</code> should be below <code>login()</code> in the class. this improves readability. </li>\n<li>Get rid of redundant logic. For example, the <code>validUsername()</code> method body can be elegantly expressed in one line - <code>return username.length() >= 3</code>. By the way, I think this method should be named <code>isUsernameValid()</code> in my opinion. </li>\n<li>Do not pass unnecessary arguments to methods. For example, <code>validUsername()</code> does not need <code>request</code> and <code>response</code>.</li>\n</ol>\n\n<p><strong>Other</strong></p>\n\n<p>The browser shows <code>http://localhost:8080/jspractice02/FrontController</code> because you've annotated the class with <code>@WebServlet(\"/FrontController\")</code>. Please read the documentation on how that works.</p>\n\n<p>I'm not sure if calling <code>doGet()</code> from <code>doPost()</code> is necessary (and I'm not sure if it's best practice). Your <code>doPost()</code> should just login the user and redirect them if the credentials provided are valid. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T08:32:07.130",
"Id": "429448",
"Score": "0",
"body": "\"Do not introduce redunant code (constructor that only calls super())\" Keep in mind that there are instances when declaring default constructors is required, for example when the binary is being obfuscated (obfuscator strips the default ones, but leaves user defined ones intact)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T08:33:00.480",
"Id": "429449",
"Score": "0",
"body": "\"Can you think how?\" We're doing a code review here, not playing guessing games. Just tell the people."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T16:41:42.557",
"Id": "221939",
"ParentId": "221929",
"Score": "7"
}
},
{
"body": "<p>You've received some good comments on the coding style, so I'll focus on the best practice principles of structure and design.</p>\n\n<ul>\n<li>Follow the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">single responsibility principle</a> in your controller, it should do one thing, dispatch the commands it receives. A class should do one thing, the <a href=\"https://en.wikipedia.org/wiki/Front_controller\" rel=\"nofollow noreferrer\"><code>front controller</code></a> shows how this can be decomposed in a flexible and expansive way.</li>\n<li>Applying the SRP with a <code>FrontController</code> will make it unnecessary to change the controller to add new commands. Replace your switch with a command mapping, see the <a href=\"https://en.wikipedia.org/wiki/Command_pattern\" rel=\"nofollow noreferrer\">Command Pattern</a>. A good approach to this is to load the commands from a property file into a <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html\" rel=\"nofollow noreferrer\">Hashmap</a>; so <code>Command=ClassName</code> that maps the command-name to a class name.</li>\n<li>Use the <a href=\"https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#forName(java.lang.String)\" rel=\"nofollow noreferrer\"><code>Class.forName(className).newInstance()</code></a> idiom to construct new instances of the commands on demand. Commands should qualify as light weight classes for immediate construction.</li>\n<li>Create a hierarchy of commands, this will allow controlled and uncontrolled commands. The access controlled commands will to minimise the risk of a security/access holes when all the controlled commands inherit from an access controlled command.</li>\n</ul>\n\n<p>See this answer for a more elaborate explanation of this approach : <a href=\"https://softwareengineering.stackexchange.com/a/345714/241947\">https://softwareengineering.stackexchange.com/a/345714/241947</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T17:52:38.573",
"Id": "429612",
"Score": "0",
"body": "\"Use the Class.forName(className).newInstance() idiom to make the commands\" Could you iterate on that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-13T17:35:25.490",
"Id": "430051",
"Score": "0",
"body": "@Bobby It is factory method that constructs a new instance of a class using a variable name rather than a hard coded class name. The className value needs to be fully qualified with the package but is really simple to use and extremely powerful factory method. I've added a link to the JavaDoc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-13T19:11:31.627",
"Id": "430056",
"Score": "1",
"body": "Oh, `className` is not a placeholder but an actual variable, then I get what you mean."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T09:31:22.113",
"Id": "222002",
"ParentId": "221929",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T13:22:37.130",
"Id": "221929",
"Score": "7",
"Tags": [
"java",
"authentication",
"servlets",
"jsp"
],
"Title": "Java Servlet & JSP simple login"
} | 221929 |
<p>Here is my solution to the following <strong>Daily Coding Problem challenge</strong> </p>
<blockquote>
<p>Given a string, find the palindrome that can be made by inserting the
fewest number of characters as possible anywhere in the word. If there
is more than one palindrome of minimum length that can be made, return
the lexicographically earliest one (the first one alphabetically).</p>
</blockquote>
<p><strong>Example</strong></p>
<p><code>Input</code>: race</p>
<p><code>Output</code>: ecarace</p>
<p>I used a PEP8 checker for this code and the only issue I couldn't fix was the "UPPER_CASE" naming style as I don't understand what I am supposed to do to fix this</p>
<pre><code>import itertools
def find_palindrome(word, new_strings) -> str:
"""Find the first palindromic word of a given string by adding new letters"""
for add_string in new_strings:
for index in range(len(word)):
new_word = word[:index] + "".join(add_string) + word[index:]
if new_word == new_word[::-1]:
return new_word
if __name__ == "__main__":
word = "r"
if word != word[::-1]:
new_strings = sorted(list(itertools.chain.from_iterable(itertools.permutations(word, n)
for n in range(len(word)+1))))
print(find_palindrome(word, new_strings))
else:
print(word)
</code></pre>
<p><strong>EDIT</strong>
I noticed the <code>find_palindrome</code> function didn't return the first alphabetic palindrome so here is an update for this function</p>
<pre><code>def find_palindrome(word, new_strings) -> str:
"""Find the first palindromic word of a given string by adding new letters"""
add_string_length = 0
list_new_words = []
for add_string in new_strings:
if len(add_string) > add_string_length and list_new_words:
return (sorted(list_new_words)[0])
add_string_length = len(add_string)
for index in range(len(word)+1):
new_word = word[:index] + "".join(add_string) + word[index:]
if new_word == new_word[::-1]:
list_new_words.append(new_word)
</code></pre>
<p><strong>EDIT 2</strong>:
It turns out I had updated the main function too, so here is the update for that:</p>
<pre><code>if __name__ == "__main__":
word = "race"
if word != word[::-1]:
new_strings = sorted(list(itertools.chain.from_iterable(itertools.permutations(word, n)
for n in range(len(word)+1))),key=len)
print(find_palindrome(word, new_strings))
else:
print(word)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T13:53:45.803",
"Id": "429363",
"Score": "0",
"body": "Ignore the \"UPPER_CASE\" warnings, it's because you have code in global scope. If you put it in a function it doesn't complain."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T05:24:22.797",
"Id": "429445",
"Score": "0",
"body": "@EML - I believe your update doesn't work for the word \"`race`\". It prints out \"`racecar`\" instead of \"`ecarace`\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T09:49:18.550",
"Id": "429457",
"Score": "0",
"body": "Sorry...I had updated the main function too to set the ```sorted key = len```. Posted update above"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T13:34:32.933",
"Id": "221930",
"Score": "5",
"Tags": [
"python",
"programming-challenge",
"strings"
],
"Title": "Palindrome insertion challenge"
} | 221930 |
<p>I am working on a typescript react/redux app that provides a visual interface for the code editor with a predefined set of instructions. It's basically a tree structure of objects that I call <code>Handlers</code> and these can be nested. All these handlers implement a simple <code>IHandler</code> interface and common functionality is implemented in <code>HandlerBase</code> class.</p>
<pre class="lang-js prettyprint-override"><code>export default interface IHandler {
id: Id;
type: string;
isDisabled?: boolean;
isExpanded?: boolean;
codeTemplate: CodeTemplate;
toJson: () => string;
toCode: () => string;
}
export default class HandlerBase<Type extends string, T extends HandlerBase<Type, T>> implements IHandler {
id: Id<T>;
type: Type;
isDisabled?: boolean;
isExpanded?: boolean;
codeTemplate: CodeTemplate<T>;
}
</code></pre>
<p>The <code>Id</code> type is a strongly typed string that makes it easier to save the types of handlers under the ids.</p>
<pre class="lang-js prettyprint-override"><code>export type Id<T extends IHandler = IHandler> = string & { __type: T["type"] };
</code></pre>
<p>All the handlers are saved in a redux store by their keys and refer to other handlers that are nested under them also by the <code>Id</code> type. Also, each handler has it's own unique <code>Type</code> which is a string literal type.</p>
<pre class="lang-js prettyprint-override"><code>class ExampleHandlerModel extends HandlerBase<"Example", ExampleHandler> {
child: Id<ExampleHandlerModel>;
}
</code></pre>
<p>What I would like to achieve is to strongly type the <code>IHandler.type</code> attribute, which right now is just a string type, automatically as a union of all implemented handlers in my codebase. I looked into class decorators, but since I've never worked with them, I wasn't able to come up with any solution, nor am I sure that this problem can be solved by decorating the deriving classes (my inspiration was C# attributes that can do similar kind of type registration).</p>
<p>Another problem I would like to also solve is that these implementations of handler class at some point in my code need to be instantiated and they also have static methods that should be able to be called based on the <code>type</code> property. The really ugly and unmaintainable way I'm doing it now is a function that takes an <code>IHandler</code> argument and then just runs it through a switch statement that I manually maintain and update every time I implement a new handler type.</p>
<pre class="lang-js prettyprint-override"><code>export const HandlerGetStatic = <T extends IHandler>(handler: T, attr: string): any => {
switch (handler.type) {
case "Example": return (ExampleHandlerModel)[attr];
case "Foo": return (FooHandlerModel)[attr];
// etc.
}
}
export const InstantiateHandler = <T extends HandlerBase<string, T>>(model: Model<T>): IHandler => {
switch (model.type) {
case "Example": return new ExampleHandlerModel(model);
case "Foo": return new FooHandlerModel(model);
// etc.
}
}
</code></pre>
<p>Here I would also like to remove the need for manual updating of these helpers.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T14:57:18.217",
"Id": "221932",
"Score": "1",
"Tags": [
"typescript",
"redux",
"variant-type"
],
"Title": "Dynamically build tagged union and helper that allows its instantiation and calling of its static methods"
} | 221932 |
<p>I got a warning when I am returning "list" in the function createList "Address of stack memory associated with local variable 'list' returned"</p>
<p>I am confused about pointers and memory allocation and not sure how to fix it.</p>
<pre><code>int* createList(int quantity) {
int list[quantity];
printf("Please enter a list of numbers\n");
for(int i = 0 ; i < quantity ; i++){
scanf("%i",&list[i]);
}
return list;
}
int findNumber(int number) {
printf("Please chose a number\n");
scanf("%i",&number);
return number;
}
int main() {
int quantity;
printf("How many numbers do you want?\n");
scanf("%i",&quantity);
return 0;
}
</code></pre>
| [] | [
{
"body": "<p>In this function you declare an array of <code>int</code>:</p>\n\n<pre><code>int* createList(int quantity) {\n int list[quantity]; /* <- here */\n\n printf(\"Please enter a list of numbers\\n\");\n for(int i = 0; i < quantity; i++) {\n scanf(\"%i\", &list[i]);\n }\n return list;\n} /* list is free'd here, so you return a pointer to free'd memory */\n</code></pre>\n\n<p>Accessing the free'd memory you return may cause your program to crash or give you access to part of the memory previously owned by your <code>int</code> array that's since been allocated by other entities in your program. It may vary from day to day what the effect will be. It may even look like it works sometimes. You need to find other means to pass your arrays around. I have ideas but since this is far from working code, you could try to get help at <a href=\"https://stackoverflow.com/\">stackoverflow</a> instead.</p>\n\n<blockquote>\n <p>How to Ask @ Code Review</p>\n \n <p>Your question must contain code that is already working correctly, and\n the relevant code sections must be embedded in the question.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T17:22:39.363",
"Id": "429383",
"Score": "1",
"body": "I would write a comment and flag the question in the future. https://codereview.stackexchange.com/help/how-to-answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T17:26:31.720",
"Id": "429384",
"Score": "0",
"body": "@dfhwze I tried, but I don't have reputation to write comments :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T17:31:05.323",
"Id": "429385",
"Score": "1",
"body": "Oh yes, been there to :p This can be a bit frustating at the beginning."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T20:41:59.093",
"Id": "429412",
"Score": "0",
"body": "@dfhwze et al. Please refer to: https://codereview.meta.stackexchange.com/questions/762/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T20:45:37.580",
"Id": "429413",
"Score": "0",
"body": "@StephenRauch Ted Lyngmo fixed a formatting mistake by the OP. Is there a reason why I should not have approved it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T20:47:22.520",
"Id": "429414",
"Score": "0",
"body": "Yes, it should not be approved. As the meta questions states, we should not \"fix\" the code in the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T22:03:56.870",
"Id": "429420",
"Score": "0",
"body": "@StephenRauch There was no code fix, only formatting and a correction in the usage of MarkDown. The accepted answer in the link you provided allows such changes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T22:10:38.573",
"Id": "429421",
"Score": "0",
"body": "@dfhwze,I suggest you look more carefully at the suggested edits that you approved: https://codereview.stackexchange.com/review/suggested-edits/117513 & https://codereview.stackexchange.com/review/suggested-edits/117515. In both cases more experienced reviewers rejected the edits. Fixing because of MarkDown problems means the OP did not understand how to do Markdown, (IE: usually the entire block needs to be indented) but that is not the case here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T00:57:05.293",
"Id": "429429",
"Score": "0",
"body": "@StephenRauch Missing a markdown when otherwise doing well has never been the end for me. I fixed it because it was a so obvious typo."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T01:32:18.877",
"Id": "429432",
"Score": "0",
"body": "@TedLyngmo, I understand your confusion. I was also there previously. But you reformatted the OP's code. In a Code Review situation, this is not what we do. We comment on the code as presented."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T01:34:36.713",
"Id": "429434",
"Score": "0",
"body": "@StephenRauch Fair enough ... My first try. I'm looking forward to what I'm working at getting love :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T01:40:49.633",
"Id": "429436",
"Score": "0",
"body": "@TedLyngmo, this is why your answer, even though it probably should not not have been applied to this question (the code does not work) was upvoted. We want to encourage as many as we can to come and take the time discuss questions here. My only quibble was with the edit, not with the answer... Cheers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T01:45:02.480",
"Id": "429437",
"Score": "0",
"body": "@StephenRauch - Ah .. Ok, I'm from `SO` and quick-fix as soon as I see someone making a simple typo-like mistake. Well, cheers mate! Off to the brew again! - and the reason I've started frequenting _review_ is ... my upcoming review - and I'm nervous about it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T09:06:27.187",
"Id": "429455",
"Score": "0",
"body": "@StephenRauch Alright, I'll be more strict in approving suggested code formatting edits. Nuff said :)"
}
],
"meta_data": {
"CommentCount": "14",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T17:02:54.520",
"Id": "221944",
"ParentId": "221933",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T15:13:49.017",
"Id": "221933",
"Score": "-2",
"Tags": [
"algorithm",
"c"
],
"Title": "Binary Search in C - Pointers and Memory"
} | 221933 |
<p>I'm learning myself C and to make sure that I learn to code C in a proper way I created tic tac toe and want to hear your opinion on what I should do and what I shouldn't do.</p>
<p>One thing is sure is to divide the code up in several files maybe but outside of that.</p>
<p>The code:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#define ROWS 3
#define BOARD_SIZE ROWS * ROWS
typedef enum { false, true } bool;
bool enter_entry(char *board, char character, int x, int y);
void print_board(const char *board);
void *init_board();
bool is_solved(char *board, char item);
bool is_draw(char *board);
bool is_equal(char *board, int indexA, int indexB, int indexC, char item);
void player_selection(char *board, char item);
void game_loop(char *board);
int main()
{
char *board = init_board();
game_loop(board);
return 0;
}
void *init_board()
{
char *board = malloc(sizeof(char) * BOARD_SIZE);
for(int i = 0; i < BOARD_SIZE; i++)
{
board[i] = ' ';
}
return board;
}
void print_board(const char *board)
{
for(int i = 1; i < BOARD_SIZE+1; i++)
{
printf("| %c ", board[i-1]);
if(i % 3 == 0)
{
printf("|\n");
}
}
printf("\n");
}
bool is_solved(char *board, char item)
{
if(is_equal(board, 0, 1, 2, item)) { return true; }
if(is_equal(board, 3, 4, 5, item)) { return true; }
if(is_equal(board, 6, 7, 8, item)) { return true; }
if(is_equal(board, 0, 3, 6, item)) { return true; }
if(is_equal(board, 1, 4, 7, item)) { return true; }
if(is_equal(board, 2, 5, 8, item)) { return true; }
if(is_equal(board, 0, 4, 8, item)) { return true; }
if(is_equal(board, 2, 4, 6, item)) { return true; }
return false;
}
bool is_draw(char *board)
{
for(int i = 0; i < BOARD_SIZE; i++)
{
if(board[i] == ' ')
{
return false;
}
}
return true;
}
bool is_equal(char *board, int indexA, int indexB, int indexC, char item)
{
if(board[indexA] == item && board[indexB] == item && board[indexC] == item)
{
return true;
}
return false;
}
bool enter_entry(char *board, char character, int x, int y)
{
int index = x + ROWS * y;
if(board[index] != ' ')
{
return false;
}
board[index] = character;
return true;
}
void player_selection(char *board, char item)
{
int x, y;
printf("enter coords (x, y): \n");
while(1)
{
scanf(" %d %d", &x, &y);
bool succes = enter_entry(board, item, x-1, y-1);
if(succes)
{
break;
}
printf("This coord is already used or not valid enter new ones:\n");
}
print_board(board);
}
void game_loop(char *board)
{
char playerOneChar = 'o';
char playerTwoChar = 'x';
printf("Welcome to tic tac toe!\n");
printf("Press enter to continue\n");
char enter = 0;
while (enter != '\r' && enter != '\n') { enter = getchar(); }
printf("Let's start the game!\n");
print_board(board);
while(1)
{
printf("Player one: \n");
player_selection(board, playerOneChar);
if(is_solved(board, playerOneChar))
{
printf("Player one won!\n");
break;
}
if(is_draw(board))
{
printf("No winners!\n");
break;
}
printf("Player two: \n");
player_selection(board, playerTwoChar);
if(is_solved(board, playerTwoChar))
{
printf("Player two won!");
break;
}
if(is_draw(board))
{
printf("No winners!\n");
break;
}
}
}
</code></pre>
<p>Thank you in advance!</p>
| [] | [
{
"body": "<h2>malloc</h2>\n\n<p>I start with one of the most common ones. Instead of <code>char *board = malloc(sizeof(char) * BOARD_SIZE)</code> write <code>char *board = malloc(sizeof(*board) * BOARD_SIZE)</code>. If you decide to change the type in the future, you don't have to change at more than one place. And besides, <code>sizeof(char)</code> is ALWAYS 1.</p>\n\n<p>But the biggest problem is that you're not checking the return value. It should look like this:</p>\n\n<pre><code>void *init_board()\n{\n char *board = malloc(sizeof(char) * BOARD_SIZE);\n if(!board) { \n /* Handle error */ \n } else { \n for(int i = 0; i < BOARD_SIZE; i++) {\n board[i] = ' ';\n }\n }\n return board;\n}\n</code></pre>\n\n<p>Or like this:</p>\n\n<pre><code>void *init_board()\n{\n char *board = malloc(sizeof(char) * BOARD_SIZE);\n if(board) {\n for(int i = 0; i < BOARD_SIZE; i++) {\n board[i] = ' ';\n }\n }\n return board;\n}\n</code></pre>\n\n<p>But if you choose the latter one, then you need to check the return value of <code>init_board()</code>.</p>\n\n<p>Another thing about the board variable. Why not make it into a 3x3 array instead? It's overkill to call malloc for a 9 byte array. I would do like this instead:</p>\n\n<pre><code>const int dim=3;\n\nvoid init_board(char board[dim][dim]) \n{\n for(int i=0; i<dim; i++)\n for(int j=0; j<dim, j++)\n board[i][j]=' ';\n}\n</code></pre>\n\n<p>And then in <code>main()</code></p>\n\n<pre><code>char board[3][3];\ninit_board(board);\n</code></pre>\n\n<h2>scanf</h2>\n\n<p>You're also not checking the return value of <code>scanf</code>. That should also always be done.</p>\n\n<pre><code>scanf(\" %d %d\", &x, &y);\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>if(scanf(\" %d %d\", &x, &y) != 2) {\n /* Handle error */\n} else {\n</code></pre>\n\n<p>But if you ask me, the best method, even though it takes a few more lines, is this:</p>\n\n<pre><code>const size_t buffer_size = 100;\nchar buffer[buffer_size];\nif(!fgets(buffer, buffer_size, stdin)) {\n /* Handle error */\n} else {\n if(sscanf(buffer, \"%d %d\", &x, &y) != 2) {\n /* Handle error */\n }\n}\n</code></pre>\n\n<h2>bool</h2>\n\n<p>No reason to define <code>bool</code>, <code>true</code> and <code>false</code> on your own. Just include <code>stdbool.h</code>.</p>\n\n<h2>const</h2>\n\n<p>A minor thing is that you should declare <code>playerOneChar</code> and <code>playerTwoChar</code> as <code>const</code>.</p>\n\n<h2>style</h2>\n\n<p>This is my personal preference, but I think you waste a lot of space with unnecessary braces. I would at least move the opening brace to then end of previous line, except for functions. Like this:</p>\n\n<pre><code>bool is_draw(char *board)\n{\n for(int i = 0; i < BOARD_SIZE; i++) {\n if(board[i] == ' ') {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n\n<p>or even</p>\n\n<pre><code>bool is_draw(char *board)\n{\n for(int i = 0; i < BOARD_SIZE; i++) \n if(board[i] == ' ') \n return false;\n return true;\n}\n</code></pre>\n\n<p>Remember that readability also includes not having to scroll more than necessary. Putting the opening brace on the line before or sometimes even removing them completely barely makes it harder to read at all. If you ask me it's even easier. But it can save you a ton of lines, making more code visible at the same time. In the above example I would probably remove the braces for the if statement, but keep the braces for the for loop.</p>\n\n<p>I usually go by the <a href=\"https://www.kernel.org/doc/html/v4.10/process/coding-style.html\" rel=\"nofollow noreferrer\">coding style guide for the Linux kernel</a>, except that I prefer a tab size of 4 instead of 8.</p>\n\n<p>Apart from these things, I think it looks pretty good. Nice work.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T18:30:09.027",
"Id": "429392",
"Score": "0",
"body": "Thanks Broman for your comments, I will take them into account! Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T13:02:56.870",
"Id": "429464",
"Score": "0",
"body": "Does this code really work? See https://stackoverflow.com/questions/2828648/how-to-pass-a-multidimensional-array-to-a-function-in-c-and-c"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T13:55:47.823",
"Id": "429466",
"Score": "0",
"body": "I do not agree with the modification of the brace style. It is much better to align the braces vertically rather than scattering them left and right, all over the page"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T13:57:18.617",
"Id": "429467",
"Score": "0",
"body": "the number of lines used is not important. Extra lines for the braces makes the code much easier for humans to read and the compiler does not care"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T16:02:08.227",
"Id": "429475",
"Score": "0",
"body": "@user3629249 I do not agree that those extra lines makes it easier. Empty lines CAN make it easier to read, but they can also do the opposite if used the wrong way."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T17:50:39.117",
"Id": "221946",
"ParentId": "221943",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "221946",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-08T17:02:05.930",
"Id": "221943",
"Score": "5",
"Tags": [
"beginner",
"c",
"tic-tac-toe"
],
"Title": "TicTacToe classic in C"
} | 221943 |
<p>I was messing around with GPU compute shaders the other day and created a Mandelbrot shader. Unfortunately, Metal doesn't support double-precision in compute shaders, so beyond a certain zoom level, I need to switch back to the CPU. In doing so, I decided to try writing SIMD code for the calculations to make it faster. </p>
<p>In the code below I'm using AVX512 instructions, and I do get a speedup over the scalar code. I break the image into 64x64 pixel tiles and farm them out to available cores. For the scalar code on one particular test image, the average time to calculate a tile is 0.757288 seconds. For the SIMD version below it's 0.466437. That's about a 33% increase, which is OK. Given that I'm calculating 8 times as many pixels at once, I was hoping for more.</p>
<p>These are some useful types I use in the code.</p>
<pre><code>#include <immintrin.h>
typedef struct RGBA8Pixel {
uint8_t red;
uint8_t green;
uint8_t blue;
uint8_t alpha;
} RGBA8Pixel;
typedef union intVec8 {
__m512i ivec;
int64_t vec[8];
} intVec8;
typedef union doubleVec8 {
__m512d dvec;
double vec[8];
} doubleVec8;
</code></pre>
<p>And here's my function for calculating 1 64x64 tile: </p>
<pre><code>- (void)calculateSIMDFromRow:(int)startPixelRow
toRow:(int)endPixelRow
fromCol:(int)startPixelCol
toCol:(int)endPixelCol;
{
if (!_keepRendering)
{
return;
}
const doubleVec8 k0s = {
.vec[0] = 0.0,
.vec[1] = 0.0,
.vec[2] = 0.0,
.vec[3] = 0.0,
.vec[4] = 0.0,
.vec[5] = 0.0,
.vec[6] = 0.0,
.vec[7] = 0.0,
};
const intVec8 k1s = {
.vec[0] = 1,
.vec[1] = 1,
.vec[2] = 1,
.vec[3] = 1,
.vec[4] = 1,
.vec[5] = 1,
.vec[6] = 1,
.vec[7] = 1,
};
const doubleVec8 k2s = {
.vec[0] = 2.0,
.vec[1] = 2.0,
.vec[2] = 2.0,
.vec[3] = 2.0,
.vec[4] = 2.0,
.vec[5] = 2.0,
.vec[6] = 2.0,
.vec[7] = 2.0,
};
const doubleVec8 k4s = {
.vec[0] = 4.0,
.vec[1] = 4.0,
.vec[2] = 4.0,
.vec[3] = 4.0,
.vec[4] = 4.0,
.vec[5] = 4.0,
.vec[6] = 4.0,
.vec[7] = 4.0,
};
UInt64 maxIterations = [self maxIterations];
NSSize viewportSize = [self viewportSize];
for (int row = startPixelRow; (row < endPixelRow) && (_keepRendering); ++row)
{
RGBA8Pixel* nextPixel = _outputBitmap + (row * (int)viewportSize.width) + startPixelCol;
double yCoord = _yCoords [ row ];
doubleVec8 yCoords;
for (int i = 0; i < 8; i++)
{
yCoords.vec [ i ] = yCoord;
}
double* nextXCoord = &_xCoords [ startPixelCol ];
for (int col = startPixelCol; (col < endPixelCol) && (_keepRendering); col += 8)
{
__m512d as = _mm512_load_pd(nextXCoord);
nextXCoord += 8;
__m512d bs = yCoords.dvec;
__m512d cs = as;
__m512d ds = bs;
UInt64 scalarIters = 1;
__m512i iterations = k1s.ivec;
__m512d dists = k0s.dvec;
__mmask8 allDone = 0;
while ((allDone != 0xFF) && (_keepRendering))
{
// newA = a * a - b * b + c
__m512d newA;
__m512d newB;
newA = _mm512_mul_pd(as, as);
newA = _mm512_sub_pd(newA, _mm512_mul_pd(bs, bs));
newA = _mm512_add_pd(newA, cs);
//double newB = 2 * a * b + d;
newB = _mm512_mul_pd(_mm512_mul_pd(k2s.dvec, as), bs);
newB = _mm512_add_pd(newB, ds);
as = newA;
bs = newB;
dists = _mm512_mul_pd(newB, newB);
dists = _mm512_add_pd(_mm512_mul_pd(newA, newA), dists);
__mmask8 escaped = _mm512_cmplt_pd_mask(dists, k4s.dvec);
iterations = _mm512_mask_add_epi64(iterations, escaped, iterations, k1s.ivec);
scalarIters++;
__mmask8 hitMaxIterations = (scalarIters == maxIterations) ? 0xFF : 0;
allDone = ~escaped | hitMaxIterations;
}
intVec8 iters = { .ivec = iterations };
for (int i = 0; i < 8; i++)
{
UInt64 nextIteration = iters.vec [ i ];
if (nextIteration == maxIterations)
{
*nextPixel = kBlack;
}
else
{
*nextPixel = kPalette [ nextIteration % kPaletteSize ];
}
nextPixel++;
}
}
}
}
</code></pre>
<p>I'm new to Intel SIMD instructions and frankly find them quite confusing. If there are better ways to do any of the above, please let me know. I tried using the fused multiply-add and multiply-add-negate instructions, and they made the code significantly slower than using 2 or 3 separate instructions, unfortunately.</p>
<p>I'm working on macOS using Xcode 10.2.1 using the Intel data types and intrinsics found in <code><immintrin.h></code>.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T21:10:20.017",
"Id": "429499",
"Score": "0",
"body": "I've added info about the environment. You mention an MCVE. I'm trying to figure out what more you need. I can show how the x and y coords are set up, if that would be useful. Beyond that, is there anything else you need?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T21:11:33.897",
"Id": "429500",
"Score": "0",
"body": "No, that’s sufficient."
}
] | [
{
"body": "<p>A couple of thoughts:</p>\n\n<ol>\n<li><p>You say</p>\n\n<blockquote>\n <p>Given that I'm calculating 8 times as many pixels at once, I was hoping for more.</p>\n</blockquote>\n\n<p>Yes, simd delivers some pretty spectacular performance improvements when doing vector/matrix operations, but for the Mandelbrot, all you’re doing is elementwise addition and multiplication, so you should see improvements, but nothing approaching 8× for these simple elementwise calculations. In my tests, the simd achieved just about twice the performance of the scalar rendition on both i9 Mac and iPhone Xs Max.</p></li>\n<li><p>Two algorithmic observations:</p>\n\n<ul>\n<li><p>I notice that you’re squaring <code>as</code> and <code>bs</code> twice, once during the algorithm and again in the escaping test. I’d suggest refactoring this so you use the results of this squaring for both the algorithm and for the escaping test.</p></li>\n<li><p>I notice that you’re doing vector multiplication for <code>2</code> in the <code>2×a×b</code> portion. I used the vector × scalar product rather than the vector elementwise product. That might be a tad faster.</p></li>\n</ul></li>\n<li><p>If you’d like to eliminate those unintuitive <code>_mm512_xxx</code> calls, you might consider the simd library, which is part of the <a href=\"https://developer.apple.com/documentation/accelerate?language=objc\" rel=\"nofollow noreferrer\">Accelerate</a> framework. This is a higher level of abstraction and, especially in Swift, you end up with very natural looking code which is, IMHO, easier to read.</p></li>\n<li><p>Conceptually, it should be noted that the simd performance gains are going to be offset by those boundary cases where some pixels have escaped and others haven’t, as you’re going to be calculating iterations for all eight pixels in the vector, including those that have already escaped.</p>\n\n<p>This probably doesn’t have a material impact on the performance, but it’s worth noting, especially if dealing with cases where dealing with intricate portions of the Mandelbrot set (which are the most interesting parts).</p></li>\n</ol>\n\n\n\n<hr>\n\n<p>For what it’s worth, this is what a Swift simd rendition might look like:</p>\n\n<pre><code>import simd\n\nfunc calculate(real: simd_double8, imaginary: simd_double8) -> simd_double8 {\n var zReal = real // simd_double8.zero\n var zImaginary = imaginary // simd_double8.zero\n\n let thresholds = simd_double8(repeating: 4)\n let maxIterations = 10_000.0\n\n var notEscaped = SIMDMask<SIMD8<Double.SIMDMaskScalar>>(repeating: true)\n let isDone = SIMDMask<SIMD8<Double.SIMDMaskScalar>>(repeating: false)\n\n var currentIterations = 0.0\n var iterations = simd_double8.zero\n\n repeat { // z = z^2 + c\n currentIterations += 1.0\n iterations.replace(with: currentIterations, where: notEscaped)\n\n let zRealSquared = zReal * zReal\n let zImaginarySquared = zImaginary * zImaginary\n\n zImaginary = 2.0 * zReal * zImaginary + imaginary // 2 × zr × zi + ci\n zReal = zRealSquared - zImaginarySquared + real // zr^2 - zi^2 + cr\n\n notEscaped = zRealSquared + zImaginarySquared .< thresholds\n } while notEscaped != isDone && currentIterations < maxIterations\n\n iterations.replace(with: 0, where: notEscaped)\n\n return iterations\n}\n</code></pre>\n\n<p>What’s nice about that, is that it’s very similar to the scalar rendition, free of cryptic method references. For example, here is the scalar version:</p>\n\n<pre><code>func calculate(real: Double, imaginary: Double) -> Int {\n var zReal = real\n var zImaginary = imaginary\n\n let thresholds = 4.0\n let maxIterations = 10_000\n\n var notEscaped = false\n\n var currentIterations = 0\n\n repeat { // z = z^2 + c\n currentIterations += 1\n\n let zRealSquared = zReal * zReal\n let zImaginarySquared = zImaginary * zImaginary\n\n zImaginary = 2.0 * zReal * zImaginary + imaginary // 2 × zr × zi + ci\n zReal = zRealSquared - zImaginarySquared + real // zr^2 - zi^2 + cr\n\n notEscaped = zRealSquared + zImaginarySquared < thresholds\n } while notEscaped && currentIterations < maxIterations\n\n return currentIterations >= maxIterations ? 0 : currentIterations\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T15:04:46.730",
"Id": "429589",
"Score": "0",
"body": "Thank you! Good point on calculating the squares twice. It's funny because I've used the SIMD library for the GPU version, but didn't realize it would emit vector instructions on the CPU. That's great news!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T08:41:19.427",
"Id": "221998",
"ParentId": "221952",
"Score": "2"
}
},
{
"body": "<blockquote>\n <p>I tried using the fused multiply-add and multiply-add-negate instructions, and they made the code significantly slower than using 2 or 3 separate instructions, unfortunately.</p>\n</blockquote>\n\n<p>This is usually indicative of a latency bottleneck,</p>\n\n<blockquote>\n <p>That's about a 33% increase, which is OK. Given that I'm calculating 8 times as many pixels at once, I was hoping for more.</p>\n</blockquote>\n\n<p>And so is this.</p>\n\n<p>Actually this is expected for Mandelbrot, because it based on iterated function application, so it inherently has a non-trivial loop-carried dependency. Floating point operations on Intel have a high throughput, but they are still slow operations in the sense of having a high latency compared to their throughput. On Skylake X (which I guess you are using, from your use of AVX512), an FMA takes 4 cycles but the processor can start two of them every cycle. So if they are too \"tied up\" (and with FMA things get even more tied up, because every FMA is waiting for 3 instead of 2 inputs to be ready), it might be that there is always some floating point operation being executed, but actually on Skylake X we would want 8 operations to be \"busy\" at any time. On Haswell it was even worse, taking 10 \"overlapping\" FMAs to saturate the floating point units.</p>\n\n<p>That situation can be improved by interleaving the calculation of several (4? 8?) independent rows of 8 pixels, though an unfortunate side-effect of this is that it would also \"round up\" the loop count to the max count among all pixels in the block. That already happens at a smaller scale now but it will get worse, and suppress the potential gain from doing this.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-12T01:16:18.437",
"Id": "429796",
"Score": "0",
"body": "Thank you for the explanation! That makes sense, though it is unfortunate."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T18:41:14.947",
"Id": "222043",
"ParentId": "221952",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "221998",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T00:51:09.790",
"Id": "221952",
"Score": "4",
"Tags": [
"performance",
"objective-c",
"fractals",
"simd"
],
"Title": "SIMD Mandelbrot calculation"
} | 221952 |
<p>I am currently developing an e-commerce website where users can upload their photos to customise their products. The use case begins when the user selects a product from our website (e.g. shirt). After that, they will select the quantity and upload their photos. The client-side will then append the following fields to the using <code>FormData</code>: <code>productId</code>, <code>productName</code> and <code>imageBlob</code>. The <code>imageBlob</code> is the user uploaded images. I will then send these data over to my server-side (asp.net core) for sanitisation by checking the <code>productId</code> received with the database. I feel that there is a lot of improvement that can be done to my code but I just do not have the knowledge to do so. Is there anyone that can give feedback or help to improve my code?</p>
<p><strong>Client-side (JavaScript)</strong></p>
<pre><code>function b64toBlob(b64Data, contentType, sliceSize) {
contentType = contentType || "";
sliceSize = sliceSize || 512;
var byteCharacters = atob(b64Data);
var byteArrays = [];
for (
var offset = 0;
offset < byteCharacters.length;
offset += sliceSize
) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
var blob = new Blob(byteArrays, { type: contentType });
return blob;
}
function imagetoblob(base64Image) {
// Split the base64 string in data and contentType
var block = base64Image.split(";");
// Get the content type of the image
var contentType = block[0].split(":")[1]; // In this case "image/gif"
// get the real base64 content of the file
var realData = block[1].split(",")[1]; // In this case "R0lGODlhPQBEAPeoAJosM...."
// Convert it to a blob to upload
return b64toBlob(realData, contentType);
}
const formData = new FormData();
for (var i = 0; i < userProducts.length; i++) {
formData.append("arr[" + i + "]", userProducts[i].productId);
formData.append("arr[" + i + "]", userProducts[i].productName);
formData.append(
"arr[" + i + "]",
imagetoblob(userProducts[i].base64Image)
);
}
</code></pre>
<p><strong>Server-side (ASP.NET Ccore)</strong></p>
<pre><code>[AllowAnonymous]
[HttpPost("sanitizeUserCart")]
public async Task<IActionResult> sanitizeUserCart([FromForm] IFormCollection inFormData)
{
List<Task<Product>> productTasks = new List<Task<Product>>();
try
{
foreach (var key in inFormData.Keys)
{
if (key.Contains("arr"))
{
int i = 0;
var id = int.Parse(inFormData[key][0]);
var name = inFormData[key][1];
var image = inFormData.Files[i];
productTasks.Add(_productService.GetUserCart(id, name));
i++;
}
}
var productResults = await Task.WhenAll<Product>(productTasks);
return new JsonResult(productResults);
}
catch (Exception ex)
{
// return error message
return BadRequest(new { message = ex.Message });
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T10:04:23.570",
"Id": "429564",
"Score": "0",
"body": "I would suggest adopting a more strongly typed approach. You can use the code from [this question](https://stackoverflow.com/questions/40172051/asp-net-core-model-doesnt-bind-from-form) as an inspiration. For now, your product server-side handling looks shady on too many levels."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T11:44:41.040",
"Id": "429570",
"Score": "0",
"body": "Hi @BohdanStupak May I know why is it \"shady on too many levels\"? What needs to be changed?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T12:17:01.960",
"Id": "429573",
"Score": "0",
"body": "`arr` is some sort of magic string. you have to keep in mind that it should be synced on a client and on a backend. Your parsing logic is hard to comprehend. Looks rely on the fact that your files are sent in some sort of exact order, and it takes quite a lot of time to figure that out. Also, you actually never use the `image` var so I doubt if there any need to parse it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T12:23:45.067",
"Id": "429575",
"Score": "0",
"body": "@BohdanStupak Thanks for the reply! As for your comment, \"Looks rely on the fact that your files are sent in some sort of exact order\". I am trying to avoid that but I do not know, the only way that I could think of is in exact order. Is there a better way to retrieve the data without following an order?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T13:16:24.923",
"Id": "429579",
"Score": "0",
"body": "I do think that the best idea is to leave mapping to ASP.NET core as per my first comment"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T13:48:47.017",
"Id": "429583",
"Score": "0",
"body": "@BohdanStupak Oh, I see. Will make the changes, thanks for your reply. Besides model binding, is there anything else I need to improve on?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T05:30:49.127",
"Id": "221957",
"Score": "2",
"Tags": [
"c#",
"javascript",
"performance",
"controller",
"asp.net-core"
],
"Title": "Retrieve file and other input fields from JavaScript to send to ASP.NET Core"
} | 221957 |
<p>I am trying to implement a hashtable that supports character keys and can return any type of value contained in a struct as long as it contains as long as it contains <code>Bucket</code> as one of its members. </p>
<p>The user has to supply the size of the hashtable (preferrably a large enough prime number) in the calling function.</p>
<p>It uses sdbm as a hash function. (Maybe adding a function pointer to let the user specify the kind of hash function they want to use could be a flexible option?)</p>
<p>Any code improvements/suggestions are welcome.</p>
<p>It uses a chaining mechanism using linked lists.</p>
<p>Here is the prototype:</p>
<pre><code>#ifndef HASHTABLE_H
#define HASHTABLE_H
#include "../linked_list/linked_list.h"
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#define HT_INIT_FAILURE -1
#define HT_INIT_SUCCESS 0
#define HT_MAGIC_SIZE 997
typedef struct bucket
{
char * key;
LL_Node ll_node;
} Bucket;
typedef struct hashtable
{
Bucket ** buckets;
unsigned int size;
} Hashtable;
int hashtable_init(Hashtable * hashtable, int size);
void hashtable_put(Hashtable * hashtable, char * key, Bucket * bucket);
int hashtable_key_exists(Hashtable * hashtable, char * key);
void hashtable_close(Hashtable * hashtable);
Bucket * __hashtable_get_bucket(Hashtable * hashtable, char * key);
#define hashtable_get_value(bucket, struct_type, struct_member) \
((struct_type *)((char *)(bucket) - (unsigned long)(offsetof(struct_type, struct_member))))
#define hashtable_get(hashtable, key, struct_type, struct_member) \
hashtable_get_value(__hashtable_get_bucket(hashtable, key), struct_type, struct_member);
#endif
</code></pre>
<p><strong>hashtable.c</strong></p>
<pre><code>#include "hashtable.h"
int hashtable_init(Hashtable * ht, int size)
{
if ((ht->buckets = (Bucket **) malloc (sizeof(Bucket *) * size)) == NULL)
return HT_INIT_FAILURE;
ht->size = size;
for (int i = 0; i < size; i++)
ht->buckets[i] = NULL;
return HT_INIT_SUCCESS;
}
unsigned long __hash_sdbm(char *str)
{
unsigned long hash = 0;
int c;
while ((c = *str++))
hash = c + (hash << 6) + (hash << 16) - hash;
return hash;
}
int __key_matches(char * source, char * target)
{
return (strcmp(source, target) == 0);
}
void __insert_bucket(Hashtable * hashtable, int index, Bucket * bucket)
{
if (hashtable->buckets[index] == NULL) {
LL_Node * head = &bucket->ll_node;
ll_create_list(head);
hashtable->buckets[index] = bucket;
}
else {
LL_Node * head = &(hashtable->buckets[index]->ll_node);
LL_Node * ptr = head;
int head_key_matches = (__key_matches(bucket->key,
hashtable->buckets[index]->key));
Bucket * search_bucket;
ll_foreach(ptr, head) {
search_bucket = ll_get(ptr, Bucket, ll_node);
if (head_key_matches || __key_matches(bucket->key, search_bucket->key)) {
ll_replace(ptr, &bucket->ll_node);
return;
}
}
ll_push_front(head, &(bucket->ll_node));
}
}
void hashtable_put(Hashtable * ht, char * key, Bucket * bucket)
{
int index = __hash_sdbm(key) % ht->size;
bucket->key = key;
__insert_bucket(ht, index, bucket);
}
Bucket * __hashtable_get_bucket(Hashtable * hashtable, char * key)
{
int index = __hash_sdbm(key) % hashtable->size;
if (hashtable->buckets[index] == NULL)
return NULL;
Bucket * bucket = hashtable->buckets[index];
if (__key_matches(bucket->key, key)) {
return bucket;
}
else {
LL_Node * ptr;
LL_Node * head = &(hashtable->buckets[index]->ll_node);
ll_foreach(ptr, head) {
bucket = ll_get(ptr, Bucket, ll_node);
if (__key_matches(key, bucket->key)) {
return bucket;
}
}
return NULL;
}
}
int hashtable_key_exists(Hashtable * ht, char * key)
{
return (__hashtable_get_bucket(ht, key) == NULL);
}
void hashtable_close(Hashtable *ht)
{
free(ht->buckets);
ht->size = 0;
}
</code></pre>
<p>Here is an example of how it can be used:</p>
<pre><code>#include "hashtable.h"
#include <stdlib.h>
#include <stdio.h>
typedef struct entry_t {
int val;
Bucket bucket;
} Entry;
int main()
{
Hashtable hashtable;
Hashtable * ht = &hashtable;
if (hashtable_init(ht, 10) == HT_INIT_FAILURE)
return EXIT_FAILURE;
Entry * entry = (Entry *) malloc(sizeof(Entry));
entry->val = 10;
hashtable_put(ht, "john", &(entry->bucket));
Entry * res;
Entry * entry2 = (Entry *) malloc(sizeof(Entry));
entry2->val = 12;
hashtable_put(ht, "pan", &(entry2->bucket));
Entry * entry3 = (Entry *) malloc(sizeof(Entry));
entry3->val = 15;
hashtable_put(ht, "tran", &(entry3->bucket));
res = hashtable_get(ht, "john", Entry, bucket);
printf("%d\n", res->val);
res = hashtable_get(ht, "pan", Entry, bucket);
printf("%d\n", res->val);
res = hashtable_get(ht, "tran", Entry, bucket);
printf("%d\n", res->val);
Entry * entry4 = (Entry *) malloc(sizeof(Entry));
entry4->val = 100;
hashtable_put(ht, "pan", &(entry4->bucket));
res = hashtable_get(ht, "john", Entry, bucket);
printf("Replaced\n%d\n", res->val);
res = hashtable_get(ht, "pan", Entry, bucket);
printf("%d\n", res->val);
res = hashtable_get(ht, "tran", Entry, bucket);
printf("%d\n", res->val);
if (hashtable_key_exists(ht, "trans"))
printf("Doesn't exist");
else
printf("Exists");
if (hashtable_key_exists(ht, "tran"))
printf("Doesn't exist");
else
printf("Exists");
free(entry);
free(entry3);
free(entry2);
free(entry4);
hashtable_close(ht);
return EXIT_SUCCESS;
}
</code></pre>
<p>Please excuse the lazily written test main function.</p>
<p><strong>Linked list implementation</strong></p>
<p>linked_list.h</p>
<pre><code>#ifndef LLIST_H
#define LLIST_H
/* A generic-ish typed circular doubly linked list implementation
* A part of the DSLIBC
* This is loosely based on the Linux kernel's list.h
*/
#include <stddef.h>
typedef struct ll_node
{
struct ll_node * next, * prev;
} LL_Node;
void ll_push_back(LL_Node * head, LL_Node * new_node);
void ll_push_front(LL_Node * head, LL_Node * new_node);
void ll_delete(LL_Node * node);
void ll_replace(LL_Node * old, LL_Node * new);
void ll_create_list(LL_Node * new_head_ptr);
/*
* Get the struct stored in that node location
* A neat trick that gets the address of the struct housing the \
* LL_Node
*/
#define ll_get(node, struct_type, struct_member) \
((struct_type *)((char *)(node) - (unsigned long)(offsetof(struct_type, struct_member))))
/*
* Iterate over the list
*/
#define ll_foreach(ptr, head) \
for (ptr = (head)->next; ptr != head; \
ptr = ptr->next)
/*
* Iterate backwards
*/
#define ll_foreach_back(ptr, head) \
for (ptr = (head)->prev; ptr != head; \
ptr = ptr->prev)
/*
* Iterate over each item safely
* Allows for freeing of objects without any errors
*/
#define ll_foreach_safe(ptr, temp, head) \
for (ptr = (head)->next, temp = ptr->next; ptr != head; \
ptr = temp, temp = ptr->next)
#endif
</code></pre>
<p>linked_list.c:</p>
<pre><code>#include "linked_list.h"
/**
* Initialize the list
* Supply the head ptr address from the actual structure that is to be stored
*/
void ll_create_list(LL_Node * new_head_ptr)
{
new_head_ptr->next = new_head_ptr;
new_head_ptr->prev = new_head_ptr;
}
void __ll_push_between(LL_Node * prev, LL_Node * next, LL_Node * new)
{
prev->next = new;
new->prev = prev;
new->next = next;
next->prev = new;
}
/*
* Insert an element at the end of the list
* Having a circular list makes sense since we don't have to \
* traverse all the way to to end to insert an element
*/
void ll_push_back(LL_Node * head, LL_Node * new_node)
{
__ll_push_between(head->prev, head, new_node);
}
void ll_push_front(LL_Node * head, LL_Node * new_node)
{
__ll_push_between(head, head->next, new_node);
}
void __ll_re_link(LL_Node * prev, LL_Node * next)
{
prev->next = next;
next->prev = prev;
}
void __ll_nullify(LL_Node * node)
{
node->next = NULL;
node->prev = NULL;
}
void ll_delete(LL_Node * node)
{
__ll_re_link(node->prev, node->next);
__ll_nullify(node);
}
void ll_replace(LL_Node * old, LL_Node * new)
{
__ll_re_link(old->prev, new);
__ll_re_link(new, old->next);
__ll_nullify(old);
}
</code></pre>
<p><strong>Note:</strong> The above linked list is a generic circular doubly linked list implementation and not specifically made for the hash table. I understand that a singly linked list should suffice for this, but since I made the Linked List library to be used somewhere else, I went ahead and reused it for the hash table.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T13:42:46.393",
"Id": "429465",
"Score": "0",
"body": "The code looks incomplete now because the linked list functions are not included but are used. Could you please add the linked list header and c file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T15:26:56.353",
"Id": "429474",
"Score": "0",
"body": "@pacmaninbw Thanks for the suggestion, I have added the linked list implementation as well."
}
] | [
{
"body": "<p><strong>Don't Hide the Use of Macros</strong> </p>\n\n<p>Currently it is unclear in the main program that you are calling macros rather than functions in this line <code>res = hashtable_get(ht, \"john\", Entry, bucket);</code>. It is not really clear why you are using a macro rather than a function. There does not seem to be a real benefit to using a macro over a function here. Anything that needs to be hidden in the implementation should be hidden in hashtable.c in static functions.</p>\n\n<p><strong>Protect the Global Name Space</strong> </p>\n\n<p>All the functions in linked_list.c and hashtable.c are currently global symbols, the use of the double underscore does not hide them from the global name space. The way to remove these functions from the global name space is to make them all <code>static</code> functions. It would also be better to remove the <a href=\"https://stackoverflow.com/questions/25090635/use-and-in-c-programs\">double underscore, this is reserved for library functions</a>.</p>\n\n<p>Two examples would be :</p>\n\n<pre><code>static unsigned long hash_sdbm(char *str)\n{\n unsigned long hash = 0;\n int c;\n\n while ((c = *str++))\n hash = c + (hash << 6) + (hash << 16) - hash;\n\n return hash;\n}\n\nstatic int key_matches(char * source, char * target)\n{\n return (strcmp(source, target) == 0);\n}\n</code></pre>\n\n<p>This might require changes to hashtable.h because of the prototype declaration of </p>\n\n<pre><code>Bucket * __hashtable_get_bucket(Hashtable * hashtable, char * key);\n</code></pre>\n\n<p><strong>Prefer Calloc Over Malloc When Allocating Arrays</strong> </p>\n\n<p>The function <code>calloc(size_t n_items, size_t item_size);</code> is specifically for allocating arrays. In addition to calculating the space necessary to allocate it also clears the values in the entire array. The method it uses to clear the values in the array is more efficient then the method the code is currently using.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T19:41:57.890",
"Id": "429631",
"Score": "0",
"body": "I'm using macros so that I can supply the struct type and the member name of the Bucket so that I can calculate the address of the struct and return the necessary value with the correct datatype, thus making it slightly \"generic\". Could you suggest a replacement using functions to those macros? That would be very helpful."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T18:15:36.973",
"Id": "222041",
"ParentId": "221958",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T05:40:14.913",
"Id": "221958",
"Score": "5",
"Tags": [
"c",
"linked-list",
"hash-map"
],
"Title": "Hashtable implementation in C for generic values"
} | 221958 |
<p><strong>The task</strong> is taken from <a href="https://leetcode.com/problems/meeting-rooms/" rel="nofollow noreferrer">LeetCode</a></p>
<blockquote>
<p><em>Given an array of meeting time intervals consisting of start and end times <code>[[s1,e1],[s2,e2],...]</code> <code>(si < ei)</code>, determine if a person could
attend all meetings.</em></p>
<p><strong>Example 1:</strong></p>
<pre><code>Input: [[0,30],[5,10],[15,20]]
Output: false
</code></pre>
<p><strong>Example 2:</strong></p>
<pre><code>Input: [[7,10],[2,4]]
Output: true
</code></pre>
</blockquote>
<p><strong>My imperative solution:</strong></p>
<pre><code>/**
* @param {number[][]} intervals
* @return {boolean}
*/
var canAttendMeetings = function(intervals) {
intervals.sort((a,b) => a[0] - b[0]);
for (let i = 1; i < intervals.length; i++) {
if (intervals[i][0] < intervals[i - 1][1]) { return false; }
}
return true;
};
</code></pre>
<p><strong>My functional solution:</strong></p>
<pre><code>/**
* @param {number[][]} intervals
* @return {boolean}
*/
var canAttendMeetings = function(intervals) {
return intervals
.sort((a,b) => a[0] - b[0])
.flat()
.every((x,i, src) => i % 2 === 0 || src[i + 1] === void 0 || src[i] < src[i + 1]);
};
</code></pre>
| [] | [
{
"body": "<p>These two functions look quite sufficient to solve the task. I will say that the functional solution will likely be slower, not only because it is functional but also because of the call to <code>.flat()</code> and iterating over twice as many elements. </p>\n\n<p>Correct me if this is incorrect, but the call to <code>.flat()</code> could be removed if the call to <code>.every()</code> was changed to a condition similar to the condition in the imperative solution: </p>\n\n<pre><code>.every((x,i, src) => i === 0 || !(src[i][0] < src[i - 1][1]));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-25T22:56:33.080",
"Id": "229669",
"ParentId": "221960",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "229669",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T09:28:54.453",
"Id": "221960",
"Score": "2",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"functional-programming",
"ecmascript-6"
],
"Title": "Given time intervals determine if a person could attend all meetings"
} | 221960 |
<p>Here is my coded solution to the <a href="https://leetcode.com/problems/zigzag-conversion/" rel="nofollow noreferrer">LeetCode zig-zag</a> problem -</p>
<blockquote>
<p><em>The string "<code>PAYPALISHIRING</code>" is written in a zigzag pattern on a given
number of rows like this (you may want to display this pattern in a
fixed font for better legibility) -</em></p>
<pre><code>P A H N
A P L S I I G
Y I R
</code></pre>
<p><em>And then read line by line: "<code>PAHNAPLSIIGYIR</code>"</em></p>
<p><em>Write the code that will take a string and make this conversion given
a number of rows.</em></p>
</blockquote>
<p>I know the final line is a bit messy, and I could unpack it into a two-line <code>for</code> loop, but I really like single-line <code>for</code> loops.</p>
<pre><code>def zigzag() -> list:
"""Returns the zig-zag word of a given input as a list."""
array = []
for _ in range(num_rows):
array.append([])
increasing = 1
array_index = 0
word_index = 0
while word_index < len(word):
if increasing:
array[array_index].append(word[word_index])
array_index += 1
word_index += 1
else:
array[array_index].append(word[word_index])
array_index -= 1
word_index += 1
if array_index == -1 and increasing == 0:
increasing = 1
array_index = 1
if array_index == num_rows and increasing == 1:
increasing = 0
array_index = num_rows - 2
return array
if __name__ == "__main__":
word = "PAYPALISHIRING"
num_rows = 3
print("".join(line for array in zigzag() for line in array))
</code></pre>
| [] | [
{
"body": "<h1><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> implementation is great, now to focus on being concise -</h1>\n\n<p>While you have started writing immaculate programs, as in <a href=\"https://codereview.stackexchange.com/questions/221930/palindrome-insertion-challenge\">here</a> and your current question, I believe you should start making your programs more concise. This decreases memory space and sometimes, makes your program faster. Also, I'm glad to see you've started implementing the <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do/419185#419185\"><code>if __name__ == '__main__'</code></a> guard.</p>\n\n<p>Here's one approach you could use to make your program really concise and fast -</p>\n\n<pre><code>def zigzag(word: str, num_rows: int) -> str:\n\n ans = [''] * num_rows\n x = 0\n direction = 1\n for i in word:\n ans[x] += i\n if 0 <= x + direction < num_rows:\n x += direction\n else:\n direction *= -1\n x += direction\n return ''.join(ans)\n\nif __name__ == \"__main__\":\n print(zigzag(\"PAYPALISHIRING\", 3))\n</code></pre>\n\n<p>Here, I believe that it would be better if you don't declare <code>word</code> and <code>num_rows</code> before calling the function. This -</p>\n\n<pre><code>print(zigzag(\"PAYPALISHIRING\", 3))\n</code></pre>\n\n<p>looks much shorter (and better) than -</p>\n\n<blockquote>\n<pre><code>word = \"PAYPALISHIRING\"\nnum_rows = 3\nprint(\"\".join(line for array in zigzag() for line in array))\n</code></pre>\n</blockquote>\n\n<p>Also, (hey, I'm <em>kind of</em> like a beginner, so please correct me if I'm wrong) I feel that you should perform the <code>.join()</code> function, or any other function really, in the principal function, as I have done above -</p>\n\n<pre><code># rest of the principal function\nreturn ''.join(ans)\n</code></pre>\n\n<p>Just use the <code>if __name__ == __main__</code> guard to (simply) call the principal function and execute the entire program (you <em>shouldn't</em> really perform any other function(s) in it <em>except</em> calling the principal function to execute it) -</p>\n\n<pre><code>if __name__ == \"__main__\":\n print(zigzag(\"PAYPALISHIRING\", 3))\n</code></pre>\n\n<hr>\n\n<p>Also, I would rename <code>increasing</code> to <code>direction</code> as it suits this task better (\"the value of \"<code>direction</code>\" changes only when we have moved up to the topmost row or moved down to the bottommost row\" (taken from <a href=\"https://leetcode.com/problems/zigzag-conversion/solution/\" rel=\"nofollow noreferrer\">Leetcode</a>). If you're wondering what <code>*=</code> means, it's just another way of doing <code>x = x * 5</code>, which is specified <a href=\"https://www.programiz.com/python-programming/operators#assignment\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Also, you could make -</p>\n\n<blockquote>\n<pre><code>array = []\nfor _ in range(num_rows):\n array.append([])\n</code></pre>\n</blockquote>\n\n<pre><code>num_rows = 3\nprint(array)\n# [[], [], []]\n</code></pre>\n\n<p>more concise by just simply initializing it -</p>\n\n<pre><code>array = [[] for _ in range(num_rows)] # Thanks to Maarten Fabré\n\nnum_rows = 3\nprint(array)\n# [[], [], []]\n</code></pre>\n\n<p>See how concise you can get by doing this? This removes the need to use <code>.append()</code>, which, in this case, is unnecessary (this will also take up less memory space).</p>\n\n<hr>\n\n<blockquote>\n <p><em>I know the final line is a bit messy, and I could unpack it into a\n two-line for loop but I really like single-line for loops.</em></p>\n</blockquote>\n\n<p>Nah, don't worry. As far as I know,</p>\n\n<pre><code>print(\"\".join(line for array in zigzag() for line in array))\n</code></pre>\n\n<p>is so much more concise than unpacking it into a two-line <code>for</code> loop. I'm glad you like single-line <code>for</code> loops :)</p>\n\n<p>Here are the times taken for each function -</p>\n\n<p>Your function -</p>\n\n<pre><code>%timeit \"\".join(line for array in zigzag() for line in array)\n8.34 µs ± 834 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n</code></pre>\n\n<hr>\n\n<p>My function -</p>\n\n<pre><code>%timeit zigzag(\"PAYPALISHIRING\", 3)\n4.19 µs ± 134 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n</code></pre>\n\n<p>As you can see above, the time taken for execution has been approximately halved, which also shows that making your function concise, down to what I have done in my function, can make your program much faster.</p>\n\n<p>Here is the Leetcode result for my program (if need be) -</p>\n\n<blockquote>\n <p><a href=\"https://i.stack.imgur.com/xbtRJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xbtRJ.png\" alt=\"enter image description here\"></a></p>\n</blockquote>\n\n<p>Hope this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T15:07:08.543",
"Id": "429469",
"Score": "2",
"body": "Thanks so much. I'm glad you like the improvements in PEP8. I've started using a PEP8 checker on my code as I am aware this is often the main feedback. I appreciate your help in pushing me towards this :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T15:16:50.610",
"Id": "429472",
"Score": "1",
"body": "As a point I tried ```array = [[]] * num_rows``` but appending an item to array[0] appends it too array[1] and array[2] as well. Don't know why though"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T16:38:56.460",
"Id": "429476",
"Score": "1",
"body": "@EML - Sorry for the late reply (Internet was down). I believe I have made a mistake and have removed the content from my answer. Sorry for any inconveniences ;("
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T16:44:17.457",
"Id": "429477",
"Score": "1",
"body": "Thanks. Don't worry. I appreciate all your help. Its nice to know that I can teach you things too about Python (even if I come across these things by accident myself) :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T16:48:00.230",
"Id": "429478",
"Score": "3",
"body": "Instead of `array = [[]] * 3` you need `[[] for _ in range (num_rows)]`. Else you just chop copy the same reference you a list 3 times"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T16:53:50.577",
"Id": "429479",
"Score": "1",
"body": "Thanks @MaartenFabré. I have edited my answer according to your suggestion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T17:07:13.860",
"Id": "429480",
"Score": "1",
"body": "@EML - I have edited my answer according to Martin Fabré's suggestion. Please take a look at it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T17:20:58.530",
"Id": "429482",
"Score": "1",
"body": "Thanks. That is an elegant way around the problem"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T17:48:29.403",
"Id": "429486",
"Score": "2",
"body": "You can also take the `x += direction` out of the if else, since it's the same for both. Just negate the condition"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T14:24:33.460",
"Id": "221964",
"ParentId": "221961",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "221964",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T11:03:00.327",
"Id": "221961",
"Score": "3",
"Tags": [
"python",
"programming-challenge",
"strings"
],
"Title": "Zig-zag function - coded solution"
} | 221961 |
<p>I'm implementing the Probabilistic Exponentially Weighted Mean for real time prediction of sensor data in pandas but have issues with optimising the pandas notebook for quick iterations.</p>
<p>Is there a more optimal way to completely remove the <code>for</code> loop as it currently runs longer than expected. How can I take advantage of <code>apply()</code> ; or vectorized operations etc. here?</p>
<pre><code>import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import datetime
import matplotlib.pyplot as plt
#plt.style.use('fivethirtyeight')
#%config InlineBackend.figure_format = 'retina'
#%matplotlib inline
from itertools import islice
from math import sqrt
from scipy.stats import norm
ts = pd.date_range(start ='1-1-2019',
end ='1-10-2019', freq ='5T')
np.random.seed(seed=1111)
data = np.random.normal(2.012547, 1.557331,size=len(ts))
df = pd.DataFrame({'timestamp': ts, 'speed': data})
df.speed = df.speed.abs()
df = df.set_index('timestamp')
time_col = 'timestamp'
value_col = 'speed'
#pewna parameters
T = 30 # initialization period (in cycles)
beta = 0.5 # lower values make the algorithm behave more like regular EWMA
a = 0.99 # the maximum value of the EWMA a parameter, used for outliers
z = 3
#the PEWNA Model
# create a DataFrame for the run time variables we'll need to calculate
pewm = pd.DataFrame(index=df.index, columns=['Mean', 'Var', 'Std'], dtype=float)
pewm.iloc[0] = [df.iloc[0][value_col], 0, 0]
t = 0
for _, row in islice(df.iterrows(), 1, None):
diff = row[value_col] - pewm.iloc[t].Mean # difference from moving average
p = norm.pdf(diff / pewm.iloc[t].Std) if pewm.iloc[t].Std != 0 else 0 # Prob of observing diff
a_t = a * (1 - beta * p) if t > T else 1 - 1/(t+1) # weight to give to this point
incr = (1 - a_t) * diff
# Update Mean, Var, Std
pewm.iloc[t+1].Mean = pewm.iloc[t].Mean + incr
pewm.iloc[t+1].Var = a_t * (pewm.iloc[t].Var + diff * incr)
pewm.iloc[t+1].Std = sqrt(pewm.iloc[t+1].Var)
t += 1
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T09:24:02.357",
"Id": "429560",
"Score": "1",
"body": "@Graipher Ive added dummy data to show what the df looks like."
}
] | [
{
"body": "<p>I think you can use just raw numpy arrays for speeding it up:</p>\n\n<p>after #the PEWMA Model you can just use following code:</p>\n\n<pre><code>_x = df[value_col]\n_mean, _std, _var = np.zeros(_x.shape), np.zeros(_x.shape), np.zeros(_x.shape)\n\nfor i in range(1, len(_x)):\n diff = _x[i] - _mean[i-1]\n\n p = norm.pdf(diff / _std[i-1]) if _std[i-1] != 0 else 0 # Prob of observing diff\n a_t = a * (1 - beta * p) if (i-1) > T else 1 - 1/i # weight to give to this point\n incr = (1 - a_t) * diff\n\n # Update Mean, Var, Std\n v = a_t * (_var[i-1] + diff * incr)\n _mean[i] = _mean[i-1] + incr\n _var[i] = v\n _std[i] = np.sqrt(v)\n\npewm = pd.DataFrame({'Mean': _mean, 'Var': _var, 'Std': _std}, index=df.index)\n</code></pre>\n\n<p>If you need to apply it to really big data you could make it even faster by using numba package:</p>\n\n<pre><code>from numba import njit\n\n# numba has some issues with stats's norm.pdf so redefine it here as function\n@njit\ndef norm_pdf(x):\n return np.exp(-x**2/2)/np.sqrt(2*np.pi)\n\n@njit\ndef pwma(_x, a, beta, T):\n _mean, _std, _var = np.zeros(_x.shape), np.zeros(_x.shape), np.zeros(_x.shape)\n _mean[0] = _x[0]\n\n for i in range(1, len(_x)):\n diff = _x[i] - _mean[i-1]\n\n p = norm_pdf(diff / _std[i-1]) if _std[i-1] != 0 else 0 # Prob of observing diff\n a_t = a * (1 - beta * p) if (i-1) > T else 1 - 1/(i) # weight to give to this point\n incr = (1 - a_t) * diff\n\n # Update Mean, Var, Std\n v = a_t * (_var[i-1] + diff * incr)\n _mean[i] = _mean[i-1] + incr\n _var[i] = v\n _std[i] = np.sqrt(v)\n return _mean, _var, _std\n\n# Using :\n_mean, _var, _std = pwma(df[value_col].values, 0.99, 0.5, 30)\npewm = pd.DataFrame({'Mean': _mean, 'Var': _var, 'Std': _std}, index=df.index)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-19T18:21:01.900",
"Id": "235860",
"ParentId": "221962",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T12:29:42.773",
"Id": "221962",
"Score": "4",
"Tags": [
"python",
"performance",
"numpy",
"pandas"
],
"Title": "Optimising Probabilistic Weighted Moving Average (PEWMA) df.iterrows loop in Pandas"
} | 221962 |
<p>I'm a beginner programmer and i'm looking for interesting projects to improve my low skills. I decided to spend one evening on simple snake game in console. I made it with the help of YouTube tutorial. But then i have modified some parts of the code and commented it.It seems like it's still have a lot of problems. It will be great if someone explain me how to improve it :)</p>
<p>Code:</p>
<pre><code>#include <iostream>
#include <stdlib.h>
#include <windows.h>
#include <conio.h>
#include <ctime>
using namespace std;
// Variables and arrays declaration
bool gameOver;
bool invalidCoord;
const int width = 20;
const int height = 20;
int x, y, fruitX, fruitY, score;
int tailX[100], tailY[100];
int tailLength;
enum Direction { STOP = 0, LEFT, RIGHT, UP, DOWN};
Direction dir;
void ClearScreen()
{
// Function which cleans the screen without flickering
COORD cursorPosition; cursorPosition.X = 0; cursorPosition.Y = 0; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), cursorPosition);
}
void Setup()
{ // Initialise variables
gameOver = false;
dir = STOP;
srand(time(0));
x = width / 2;
y = height / 2;
fruitX = rand() % width;
fruitY = rand() % height;
score = 0;
}
void Draw() // Drawing playing field, snake and fruits
{
ClearScreen();
// Draws top border
for (int i = 0; i < width + 2; i++)
cout << '-';
cout << endl;
for (int i = 0; i < height; i++)
{
for (int k = 0; k < width; k++)
{
// Left border
if (k == 0)
cout << '|';
// Snake's head
if (i == y && k == x)
cout << '@';
// Fruit
else if (i == fruitY && k == fruitX)
cout << '*';
else
{
// Checks if there is a tail block with appropriate coordinates and draws it
bool printTail = false;
for (int j = 0; j < tailLength; j++)
{
if (tailX[j] == k && tailY[j] == i)
{
cout << 'o';
printTail = true;
}
}
// Draws blank space if there is nothing to display
if (!printTail)
cout << ' ';
}
// Right border
if (k == width - 1)
cout << '|';
}
cout << endl;
}
// Draws bottom border
for (int i = 0; i < width + 2; i++)
cout << '-';
cout << endl;
// Displays player's score
cout << endl;
cout << "Score: " << score << endl;
}
void Input()
{
// Changes snake's direction depending on the button pressed and doesn't allow player to change direction in invalid way
if (_kbhit())
{
switch (_getch())
{
case 'w':
if (dir != DOWN)
dir = UP;
break;
case 'a':
if (dir != RIGHT)
dir = LEFT;
break;
case 's':
if (dir != UP)
dir = DOWN;
break;
case 'd':
if (dir != LEFT)
dir = RIGHT;
break;
case 'k':
gameOver = true;
break;
}
}
}
void Logic()
{
// Tail logic. Every new eteration we remember previous position of the head and save it to prevX, prevY.
// Then we update array with snake's parts positions (change first numbers in arrays tailX, tailY to a new head coordinates).
// And after that for each number in arrays except the first ones we make some changes.
// Save tailX[i], tailY[i] to prevX2, prevY2 and equate tailX[i], tailY[i] to prevX, prevY.
// And equate prevX, prevY to prevX2, prevY2.
// Then change rest of the arrays in the same way.
int prevX = tailX[0];
int prevY = tailY[0];
int prevX2, prevY2;
tailX[0] = x;
tailY[0] = y;
for (int i = 1; i < tailLength; i++)
{
prevX2 = tailX[i];
prevY2 = tailY[i];
tailX[i] = prevX;
tailY[i] = prevY;
prevX = prevX2;
prevY = prevY2;
}
// Changes snake's head coordinates depending on a direction
switch (dir)
{
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
case UP:
y--;
break;
case DOWN:
y++;
break;
}
// Detects collision with a tail
for (int i = 0; i < tailLength; i++)
if (tailX[i] == x && tailY[i] == y)
gameOver = true;
// Detects collision with a fruit
if (x == fruitX && y == fruitY)
{
score += 1;
fruitX = rand() % width;
fruitY = rand() % height;
// Generate new fruit position if it consides with snake's tail position
for (int i = 0; i < tailLength; )
{
invalidCoord = false;
if (tailX[i] == fruitX && tailY[i] == fruitY) {
invalidCoord = true;
fruitX = rand() % width;
fruitY = rand() % height;
break;
}
if (!invalidCoord)
i++;
}
tailLength++;
}
// Changes snake position if it goes through the wall
if (y >= height)
y = 0;
else if (y < 0)
y = height - 1;
if (x >= width)
x = 0;
else if (x < 0)
x = width - 1;
}
int main()
{
Setup();
while (!gameOver) // Game mainloop
{
Draw();
if (dir == UP || DOWN)
Sleep(25); // Helps to equate vertical snake movement speed and horizontal speed
Sleep(40);
Input();
Logic();
}
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T17:11:27.327",
"Id": "429481",
"Score": "3",
"body": "`i have modified some parts of the code` So how much of this was actually written by you?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-11T10:09:35.280",
"Id": "429677",
"Score": "1",
"body": "@yuri I wrote it by myself from the top to the bottom, i just use vital conception of game logic"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-25T17:52:38.290",
"Id": "431790",
"Score": "0",
"body": "\"It seems like it's still have a lot of problems.\" What kind of problems? Because if the code doesn't work as it should, it will be closed as off-topic. If you mean \"problems\" as in code style etc, you should specify it to make it clear."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-27T08:20:01.867",
"Id": "432046",
"Score": "0",
"body": "@IEatBagels Game works correctly, but the main problem is that fruit can spawn in the snake‘s tail, i tried to solve it by making a for loop which generate new coordinates for fruit if they equal to any coordinates in tailX, tailY Arrays, but there are a still chance that new coordinates will be inappropriate again"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T13:08:32.233",
"Id": "221963",
"Score": "4",
"Tags": [
"c++",
"beginner",
"game",
"snake-game",
"winapi"
],
"Title": "Simple C++ Console Snake Game"
} | 221963 |
<p>I have an implementation of an algorithm to return the in-order successor of a given node in a binary search tree. We are allowed to assume that each node in the BST has a reference to its parent node. The in-order successor of a node is the node with the next largest key. So, if we received a node with a value of 5, and the tree contained a node with the value 6, we should return the node with the value 6.</p>
<p>My implementation differs slightly from most I've seen online. Most solutions, when given an input node with no right child, iterate back up the tree until the node is the left child of its parent and then returns the parent. I iterate back up the tree until the node's value is greater than our input node's value and then return that node. I think this is equivalent and results in a little more compact and easier to follow implementation. Let me know if I'm overlooking something with this implementation.</p>
<pre><code>def successor( node, targetValue ):
if node.right:
node = node.right
while node.left:
node = node.left
else:
while node:
node = node.parent
if node.value > targetValue:
break
return node
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-12T03:26:26.910",
"Id": "429802",
"Score": "0",
"body": "I think your code is good; it's clear, easy to follow, and appears to handle the corner cases!"
}
] | [
{
"body": "<p>For idiomatic Python:</p>\n\n<ul>\n<li>You should not put spaces between the brackets and the values in function calls.</li>\n<li>You should use <code>snake_case</code> for variables.</li>\n</ul>\n\n<hr>\n\n<p>You've said you have concerns over finding the parent node that is the ancestor. Lets say we have the tree:</p>\n\n<pre><code> A\n B\nC D\n</code></pre>\n\n<p>Since that all left nodes are smaller than the current value in binary trees we know that <span class=\"math-container\">\\$B < A\\$</span>, <span class=\"math-container\">\\$C < B\\$</span> and <span class=\"math-container\">\\$D < A\\$</span>. We also know that the right nodes are larger than the current node, and so <span class=\"math-container\">\\$B < D\\$</span>. And so we know <span class=\"math-container\">\\$C < B < D < A\\$</span>.</p>\n\n<p>From this we can see that logically <code>if node.parent.left == node</code> is the same as <code>if node.parent.value > target</code>.</p>\n\n<p>The benefit to the former is you don't have to create <code>target</code>.</p>\n\n<hr>\n\n<p>Your implementation is awkward, <code>successor</code> should always be called duplicating the input.</p>\n\n<pre><code>successor(node, node.value)\n</code></pre>\n\n<p>If you don't then you'll have problems. Say <span class=\"math-container\">\\$A = 1\\$</span>, and <span class=\"math-container\">\\$\\text{node} = D\\$</span>. The successor to <span class=\"math-container\">\\$D\\$</span> is <span class=\"math-container\">\\$A\\$</span>, however <code>successor(node, 1)</code> will incorrectly return <span class=\"math-container\">\\$B\\$</span>.</p>\n\n<p>To fix this just define <code>target_value</code> in <code>successor</code>.</p>\n\n<pre><code>def successor(node):\n if node.right:\n node = node.right\n while node.left:\n node = node.left\n else:\n target_value = node.value\n while node:\n node = node.parent\n if node.value > target_value:\n break\n return node\n</code></pre>\n\n<hr>\n\n<p>If you follow what you've seen online you can reduce the amount of lines of code:</p>\n\n<pre><code>def successor(node):\n if node.right:\n node = node.right\n while node.left:\n node = node.left\n else:\n while node != node.parent.left:\n node = node.parent\n node = node.parent\n return node\n</code></pre>\n\n<hr>\n\n<p>It should be noted that if there is no successor in the tree all implementations will raise an <code>AttributeError</code>.</p>\n\n<p>This is rather confusing, and so you may want to change it to a different error.</p>\n\n<pre><code>def successor(node):\n try:\n if node.right:\n node = node.right\n while node.left:\n node = node.left\n else:\n while node != node.parent.left:\n node = node.parent\n node = node.parent\n return node\n except AttributeError:\n raise ValueError('No successor exists.') from None\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-12T09:11:19.217",
"Id": "429829",
"Score": "0",
"body": "Thanks Peilonrayz. As for the last point, I was trying to avoid throwing an exception and intended to return None upon there being no in-order successor. I didn't notice I'd throw an AttributeError when accessing the node in `if node.value > targetValue`. I think this can be remedied by changing this condition to `if node is None or node.value > targetValue`. So, we either break if the current node is the in-order successor or we've reached the top of the tree and arrived at our parent's root. This way we either return the in-order successor or None."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-11T23:38:29.347",
"Id": "222120",
"ParentId": "221967",
"Score": "4"
}
},
{
"body": "<ul>\n<li><code>successor(node, targetValue)</code> does not necessarily return the in-order successor even if called with a node in a valid search tree and that node's value: what about search trees where a value can occur more than once? </li>\n<li>I notice no <a href=\"https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring\" rel=\"nofollow noreferrer\">docstrings</a>. <code>successor()</code> in a binary tree (I could guess that much from <code>left</code> and <code>right</code>) might be the <em>in-order</em> successor, <code>target_value</code> could clue me in the tree is a <em>search tree</em>, but <em>don't make me guess</em>. </li>\n<li>I have to second <a href=\"https://codereview.stackexchange.com/a/222120/93149\">Peilonrayz</a> in rejecting the possibility to call <code>successor()</code> with parameters that make it return something else. </li>\n</ul>\n\n<p>Trying to <code>reduce the amount of lines of code</code> while sticking to comparing <code>value</code>s seems to use more attribute accesses:</p>\n\n<pre><code>def successor(node):\n '''Return the in-order successor of node in its search-tree.'''\n if node:\n if not node.right:\n target_value = node.value\n while node.parent and node.parent.value < target_value:\n node = node.parent\n return node.parent\n node = node.right\n while node.left:\n node = node.left\n return node\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-12T04:39:47.660",
"Id": "222132",
"ParentId": "221967",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "222120",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T15:03:14.160",
"Id": "221967",
"Score": "4",
"Tags": [
"python",
"algorithm",
"python-3.x",
"interview-questions",
"tree"
],
"Title": "Find the in-order successor of a given node in a binary search tree"
} | 221967 |
<p>I have written a simple pool allocator for C++ and I'm looking for ways to improve it, in speed, usability or safety. For example, I don't know how to allocate a buffer larger than the pool size.</p>
<pre><code>#pragma once
#include <limits>
#include <vector>
template<class T, size_t poolObjectCount = 100>
class PoolAllocator
{
public:
template<class U>
struct rebind
{
typedef PoolAllocator<U> other;
};
private:
const size_t m_poolSize = poolObjectCount * sizeof(T);
std::vector<T*> m_pools;
size_t m_nextObject = 0;
public:
PoolAllocator()
{
allocateNewPool();
}
PoolAllocator(const PoolAllocator& other) = delete; // Copy is deleted
PoolAllocator(PoolAllocator& other) = delete; // Copy is deleted
PoolAllocator(PoolAllocator<T, poolObjectCount>&& other) noexcept
:m_poolSize(std::move(other.m_poolSize)),
m_pools(std::move(other.m_pools)), m_nextObject(other.m_nextObject)
{}
PoolAllocator(const PoolAllocator<T, poolObjectCount>&& other) noexcept
:m_poolSize(std::move(other.m_poolSize)),
m_pools(std::move(other.m_pools)), m_nextObject(other.m_nextObject)
{}
~PoolAllocator()
{
while (!m_pools.empty())
{
T* backPool = m_pools.back();
for (T* i = backPool + poolObjectCount - 1; i > backPool; i--)
i->~T();
operator delete((void *)backPool);
m_pools.pop_back();
}
}
T* allocate(size_t objectCount)
{
if (objectCount >= poolObjectCount)
throw "Cannot allocate array greater than pool size";
if (m_nextObject + objectCount >= poolObjectCount)
allocateNewPool();
T* returnValue = m_pools.back() + m_nextObject;
m_nextObject++;
return returnValue;
}
template<class U = T>
void construct(U * object)
{
new(object) U();
}
template<class U = T>
void construct(U* object, const U& other)
{
new(object) U(other);
}
template<class U = T>
void construct(U* object, U&& other)
{
new(object) U(other);
}
template<class U = T, class... ConstructorArguments>
void construct(U* object, ConstructorArguments&& ...constructorArguments)
{
new(object) U(std::forward<ConstructorArguments>(constructorArguments)...);
}
private:
void allocateNewPool()
{
m_nextObject = 0;
m_pools.emplace_back((T*)operator new(m_poolSize));
}
};
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T16:33:16.857",
"Id": "221969",
"Score": "3",
"Tags": [
"c++",
"memory-management"
],
"Title": "Simple and safe C++ pool allocator"
} | 221969 |
<p>I've created a small module with a function <code>plog()</code> that allows to easily print to both a log file and the console. It also creates a directory "log" at the location of the file that imports the module. Although I'm quite a beginner in terms of Python I'm not satisfied with my code since I'm using two global variables. I need those, because they store the name of the last file and function that called <code>plog()</code>. So could you guys give me recommendations how I could improve the code and make it more 'pythonic'? This is my code so far:</p>
<pre class="lang-py prettyprint-override"><code>import datetime
import inspect
import os
print("Setting up logfile via very_nice_log.py")
# create name of log file via datetime
log_file_name = str(datetime.datetime.now())[:-9]
log_file_name = log_file_name.replace("-", "")
log_file_name = log_file_name.replace(" ", "")
log_file_name = log_file_name.replace(":", "")
# check if it is possible to get the path of the file that called very_nice_log
if len(inspect.stack()[1:]) == 0:
print("WARNING: could not locate file that called very_nice_log")
# get path of the file that imported very_nice_log
for frame in inspect.stack()[1:]:
if frame.filename[0] != '<':
log_path = "/".join(frame.filename.split("/")[:-1])
print("Log path is " + log_path)
break
log_path = log_path + "/log"
# check if there is a directory called "log", create one if not
if not os.path.isdir(log_path):
os.mkdir(log_path)
# create log file
print(log_path + "/" + log_file_name + ".txt")
log_file = open(log_path + "/" + log_file_name + ".txt", "w+")
print("Created log file")
log_file.write("Starting to log...\n\n")
# set up 2 variables to store the last function and file that called plog()
last_func_name = ""
last_module_name = ""
# define a function that prints to both the log file and the console
def plog(amk):
# set those variables to global to store the names of the last file and function
global last_func_name
global last_module_name
# print the string to console
print(amk)
# get the name and function that called plog()
module_name = (inspect.stack()[1][1].split("/")[-1])[:-3]
func_name = inspect.stack()[1][3]
# if plog is not called from a function, set function name to "main"
if func_name == "<module>":
func_name = "main"
# if file or function has changed since last time plog got called, write a seperator
if module_name != last_module_name:
log_file.write("=====================================================================\n")
elif func_name != last_func_name:
log_file.write("---------------------------\n")
# write to log file
log_file.write(str(datetime.datetime.now())[:-7] + ": " + module_name + ": " + func_name + ": " + amk + "\n")
# update the names of last file and function
last_func_name = func_name
last_module_name = module_name
</code></pre>
<p>edit: Usage
Simply write</p>
<pre class="lang-py prettyprint-override"><code>from very_nice_log import plog
plog("foo")
</code></pre>
<p>in another python file.</p>
<p>This is an example output to the log file. 2 files hello.py and testing2.py were used:</p>
<pre><code>Starting to log...
=====================================================================
2019-06-09 16:51:02: hello: main: Amk1
2019-06-09 16:51:02: hello: main: amk2
---------------------------
2019-06-09 16:51:02: hello: func1: func1mak
2019-06-09 16:51:02: hello: func1: func1mak
---------------------------
2019-06-09 16:51:02: hello: func2: func2amk
---------------------------
2019-06-09 16:51:02: hello: func1: func1mak
=====================================================================
2019-06-09 16:51:02: testing2: func45: amkanderesfile
2019-06-09 16:51:02: testing2: func45: amkanderesfile
=====================================================================
2019-06-09 16:51:02: hello: func1: func1mak
=====================================================================
2019-06-09 16:51:02: testing2: func45: amkanderesfile
---------------------------
2019-06-09 16:51:02: testing2: func46: yoyoyo
2019-06-09 16:51:02: testing2: func46: yoyoyo
---------------------------
2019-06-09 16:51:02: testing2: func45: amkanderesfile
</code></pre>
<p>As you can see it nicely separates the log-file into section between different files and functions. I'm very happy with this but as I said, I'm a bit concerned about the quality of my code. Especially the global variables seem to be a bad solution. So what would you guys change and why? I am very curious about your suggestions and would love to learn how to write better code.</p>
<p>Best,
Tobi</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T18:41:10.063",
"Id": "429490",
"Score": "0",
"body": "Idk about you...but the code already seems beautiful...I was just searching for a logger...more than happy to find one...the output looks pretty neat...thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T20:24:04.473",
"Id": "429494",
"Score": "0",
"body": "Do you know about the `logging` library? If you don't want an answer to be \"Try using`logging`\" you should tag this with [tag:reinventing-the-wheel]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T22:07:46.177",
"Id": "429507",
"Score": "0",
"body": "@Peilonrayz alright, I've added the tag. I know about the logging-library but to be honest I preferred to write my own code instead of trying to understand the library"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T08:51:12.623",
"Id": "429551",
"Score": "1",
"body": "Generally when I write a custom logger, I will use a decorator. These are great because they just wrap around any function/method call and can tell you about state; capture errors; print to files etc. There will also be ways around using globals by capturing what you need from the function you're decorating."
}
] | [
{
"body": "<p>Some suggestions:</p>\n\n<ul>\n<li>You could use <code>str(datetime.date.today())</code> to get the current date.</li>\n<li><p>You can chain <code>replace</code> calls:</p>\n\n<pre><code>>>> 'abba'.replace('a', 'c').replace('b', 'd')\n'cddc'\n</code></pre></li>\n<li><code>if len(inspect.stack()[1:]) == 0:</code> would usually be replaced with just <code>if inspect.stack()[1:]</code>.</li>\n<li>Treating your variables as immutable makes the code much easier to read. For example, <code>log_path = \"/\".join(frame.filename.split(\"/\")[:-1]) + \"/log\"</code> means you only have to understand one assignment rather than the connection between two of them.</li>\n<li><code>os.makedirs</code> takes <a href=\"https://docs.python.org/3/library/os.html?highlight=makedirs#os.makedirs\" rel=\"nofollow noreferrer\">an option so you don't have to check whether the directory exists already</a>.</li>\n<li>String concatenation using <code>+</code> is discouraged for anything more than two strings. Probably the best solution available today is <a href=\"https://docs.python.org/3/reference/lexical_analysis.html#f-strings\" rel=\"nofollow noreferrer\">f-strings</a>. For example, <code>log_path + \"/\" + log_file_name + \".txt\"</code> would become <code>f\"{log_path}/{log_file_name}.txt\"</code>.</li>\n<li>I don't understand the name <code>amk</code>. Names are incredibly important for the maintainability of your code, but I don't know what to suggest as a replacement except possibly <code>message</code>.</li>\n<li>You could put the globals into fields in a class; that way they would be kept between invocations without polluting the main namespace.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T07:53:48.270",
"Id": "221992",
"ParentId": "221971",
"Score": "1"
}
},
{
"body": "<p>To expand on l0b0's answer:</p>\n\n<ul>\n<li><p>Don't chain <code>str.replace</code>'s for the same reason you don't concatenate strings. If you need to perform multiple translations at the same time instead use <code>str.maketrans</code> and <code>str.translate</code>.</p>\n\n<pre><code>>>> table = str.maketrans('ab', 'cd', 'e')\n>>> 'abeeba'.translate(table)\n'cddc'\n</code></pre></li>\n<li><p>Your code only supports Unix paths, this means it doesn't work on Windows. To fix this change all of your <code>'/'</code> to <code>os.sep</code>.</p></li>\n<li><p>Rather than manual string file handling, you should use <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"nofollow noreferrer\"><code>pathlib</code></a>.</p>\n\n<pre><code># From\n\"/\".join(frame.filename.split(\"/\")[:-1])\nlogpath + os.sep + \"log\"\n\n# To\npathlib.Path(frame.filename).parent\nlogpath / \"log\"\n</code></pre></li>\n<li>Add some more function calls. With good names they should remove your comments.</li>\n<li>You have two quite large bugs with <code>log_path</code> generation. Firstly if the <code>inspect.stack()[1:]</code> is empty or all the file names start with <code>'<'</code> your code results in a <code>NameError</code>. The second won't even print the warning.</li>\n<li>If you can't create the log file, you can always default to <code>os.devnull</code> or some other reasonable default.</li>\n</ul>\n\n<pre><code>import datetime\nimport inspect\nimport os\nimport pathlib\n\nprint(\"Setting up logfile via very_nice_log.py\")\n\n\ndef get_datetime_file_name():\n table = str.maketrans(None, None, \"- :\")\n return (\n str(datetime.datetime.today()).translate(table)\n + '.txt'\n )\n\n\ndef get_log_path():\n for frame in inspect.stack()[1:]:\n if frame.filename[0] != '<':\n return pathlib.Path(frame.filename).parent\n print(\"WARNING: could not locate file that called very_nice_log\")\n return None\n\n\ndef make_log_file():\n log_path = get_log_path()\n if log_path is None:\n return open(os.devnull, \"w\")\n log_path /= \"log\"\n log_path.mkdir(parents=True, exists_ok=True)\n log_path /= get_datetime_file_name()\n print(str(log_path))\n return log_path.open(\"w+\")\n\n\nprint(\"Created log file\")\nlog_file = make_log_file()\nlog_file.write(\"Starting to log...\\n\\n\")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T11:09:26.950",
"Id": "222010",
"ParentId": "221971",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T17:02:15.690",
"Id": "221971",
"Score": "4",
"Tags": [
"python",
"beginner",
"python-3.x",
"reinventing-the-wheel",
"logging"
],
"Title": "Python logging-module that writes to both the console and a file"
} | 221971 |
<p>Inspired by the <a href="https://www.youtube.com/watch?v=527F51qTcTg" rel="nofollow noreferrer">video</a> from Scam Nation and James Grime from Numberphile, I tried to make a <a href="https://en.wikipedia.org/wiki/Razzle_(game)" rel="nofollow noreferrer">Razzle Dazzle</a> simulator.</p>
<p>Razzle Dazzle is a scam in the form of a game. Per turn, the player pays a fee and throws 8 marbles onto a board, so they land in holes in the board. Each hole has a score from 1 to 6. Throwing 8 dice instead can also be done. The scores are added to form a score from 8 to 48. This score is translated into points via table/chart. The points are accumulated across turns. When the player reaches 100 points, it wins a prize. Some scores increase the number of prizes when 100 points are reached. A score of 29 doubles the fee per turn, multiplicatively, so scoring 29 10 times increases the fee to 1024x the initial fee.</p>
<p><a href="https://i.stack.imgur.com/ceD6h.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ceD6h.jpg" alt="enter image description here"></a></p>
<p>The trick is that the most common scores (22-34) do not give any points. This means that only 2.7% of the turns by fair dice rolls give out points, needing 369.5 turns to reach 100 points. For the board in the video, only 0.28% give points, resulting in 5000+ turns to get 100 points. The probability to score 29 is about 8%, this leads to massive fees when playing lots of turns.</p>
<pre class="lang-py prettyprint-override"><code>import random, numpy
import matplotlib.pyplot as plt
# return one int with random value [1,6], with the probability density described in rawMassDist
# every 1000 turns, sample 1000 loaded die throws and put them in a list
randoms = []
idxRandom = 0
def throwLoadedDie():
global idxRandom
global randoms
rawMassDist = [11, 17, 39, 44, 21, 11]
#rawMassDist = [50, 5, 5, 5, 5, 50]
massDist = [float(i)/sum(rawMassDist) for i in rawMassDist]
if (idxRandom % 1000) == 0:
#randoms = numpy.random.choice(range(1, 7), size=1000, p=massDist)
randoms = random.choices(range(1,7), massDist, k=1000)
idxRandom = 0
idxRandom += 1
return randoms[idxRandom-1]
# throw 8 dice, fairDice indicates whether fair dice or loaded dice are used
# returns the sum of the dice values, which equals the score for this turn
def throwDice():
total = 0
for _ in range(0,8):
if fairDice:
total += random.randint(1,6);
else:
total += throwLoadedDie()
return total
# translates the score into points using dictionary toPoints
def getPoints(score):
toPoints = {8:100, 9:100, 10:50, 11:30, 12:50,
13:50, 14:20, 15:15, 16:10, 17:5,
39:5, 40:5, 41:15, 42:20, 43:50,
44:50, 45:50, 46:50, 47:50, 48:100}
if score in toPoints:
return toPoints[score]
return 0
# returns if this score results in an extra price
def isExtraPrize(score):
if (18 <= score <= 21) or (score == 29) or (35 <= score <= 38):
return True
return False
# returns if this score doubles the fee for one turn
def needDoubleFee(score):
return score == 29
# simulate one turn, return the new number of points, prizes and fee for the next turn
def simulateTurn(points, prizes, fee):
score = throwDice()
if isExtraPrize(score):
prizes += 1
if needDoubleFee(score):
fee *= 2
points += getPoints(score)
return [points, prizes, fee, score]
# simulate single game, can result in win or loss in maxTurns turns
# can print result and histogram of scores
def playGame(printResult = True, maxTurns = 1000):
points = 0
prizes = 1
hist = list() # start with empty list, add score after every turn
hist2 = [0]*49 # entries 0-7 is always 0, other entries 8-48 represent the number of times a score has occurred
fee = 1
totalFee = 0
goal = 100
won = False
for turn in range(1, maxTurns+1):
#print('Turn {0}, points: {1}'.format(turn, points))
totalFee += fee
[points, prizes, fee, score] = simulateTurn(points, prizes, fee)
hist.append(score)
if points >= goal:
won = True
break
# finalize
[hist2, _] = numpy.histogram(hist, bins=49, range=[0,48])
if printResult:
if won:
print('You win {0} prizes in {1} turns, cost: {2}'.format(prizes, turn, totalFee))
else:
print('You only got {0} points in {1} turns, cost: {2}'.format(points, turn, totalFee))
print(hist2)
if not won:
prizes = 0
return [prizes, turn, totalFee, hist2]
# simulate multiple games, allow many turns per game to practically ensure win
# also disable result printing in each game
def playGames(numGames, plot=False):
hist = [0]*49
totalPrizes = 0
totalTurns = 0
totalFee = 0
withPoints = 0
gamesLost = 0
for i in range(0, numGames):
[prizes, turns, fee, hist2] = playGame(False, 100000)
if prizes == 0:
gamesLost += 1
hist = [x + y for x, y in zip(hist, hist2)]
totalPrizes += prizes
totalFee += fee
totalTurns += turns
for i in range(8, 18):
withPoints += hist[i]
for i in range(39, 49):
withPoints += hist[i]
print('{0} games, lost {1}'.format(numGames, gamesLost))
print('Avg prizes: {}'.format(totalPrizes/numGames))
print('Avg turns: {}'.format(totalTurns/numGames))
print('Avg fee: {}'.format(totalFee/numGames))
print(hist)
print('Percentage turns with points: {:.2f}'.format(100.0*withPoints/sum(hist)))
if plot:
# create list of colors to color each bar differently
colors = [item for sublist in [['red']*18, ['blue']*21, ['red']*10] for item in sublist]
plt.bar(range(0, 49), hist, color=colors)
plt.title('Score distribution across multiple games')
plt.xlabel('Score = sum of 8 dice')
plt.ylabel('Number of turns')
plt.text(40, 0.6*max(hist), 'Red bars\ngive points')
plt.show()
fairDice = False
#playGame()
playGames(100, plot=True)
</code></pre>
<p>Concrete questions: </p>
<ol>
<li>Since calling <code>random.choices()</code> has some overhead, I generate 1000 loaded die rolls and put it in a global array. Is there a better of doing this without classes? In C I'd probably use static variables.</li>
<li>To generate a histogram of all the scores during a game, I append to a list every turn, and then generate the histogram. Is this efficient performance-wise?</li>
<li>How are my names? Especially <code>hist</code>, <code>hist2</code>, <code>isExtraPrize()</code> and <code>needDoubleFee()</code>.</li>
<li>My Ryzen 5 2400G with 3200 MHz RAM takes about 15s to simulate 100 loaded games, averaging.
3550 turns per game. I somehow feel like this should be faster, any performance related suggestions are welcome.</li>
<li>And of course, general code review answers are welcome.</li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T03:16:03.473",
"Id": "429527",
"Score": "1",
"body": "Is there a reason to avoid classes? Much of this seems like a class or two would be useful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T15:41:43.340",
"Id": "429595",
"Score": "0",
"body": "No particular reason, I guess using class also avoids passing [points,prizes,fee] back and forth."
}
] | [
{
"body": "<p>First, your use of camelCase isn't ideal in Python. For variable and function names, snake_case is preferred. I'll be using that with any re-written code that I show.</p>\n\n<hr>\n\n<p>I think <code>throw_dice</code> can be improved a bit. You're checking for the value of <code>fair_dice</code> once per iteration in the function instead of once at the beginning. This will be negligible performance-wise, but it's unnecessary and checking once per loop suggests that it's a value that can change in the loop, which isn't the case here.</p>\n\n<p>There's different ways of approaching this depending on how close to <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP</a> you want to adhere to; but both ways I'll show depend on dispatching to a function using a conditional expression. Following PEP, you could do something like:</p>\n\n<pre><code>def throw_loaded_die():\n return 1 # For brevity\n\n# Break this off into its own function\ndef throw_fair_die():\n return random.randint(1, 6)\n\ndef throw_dice():\n # Figure out what we need first\n roll_f = throw_fair_die if fair_dice else throw_loaded_die\n\n total = 0\n for _ in range(8):\n total += roll_f() # Then use it here\n\n return total\n</code></pre>\n\n<p>That cuts down on duplication which is nice. I also got rid of the <code>0</code> argument in the call to <code>range</code> as that's implicit if it isn't specified.</p>\n\n<p>I think the separate <code>def throw_fair_die</code> is unfortunate though. For such a simple function that isn't needed anywhere else, I find it to be noisy, and looking around, I'm not the <a href=\"https://stackoverflow.com/a/37489941/3000206\">only one to feel this way</a>. Personally, I'd prefer to just write:</p>\n\n<pre><code>def throw_dice():\n # Notice the lambda\n roll_f = (lambda: random.randint(1, 6)) if fair_dice else throw_loaded_die\n\n total = 0\n for _ in range(8): # Specifying the start is unnecessary when it's 0\n total += roll_f()\n\n return total\n</code></pre>\n\n<p>This is arguably a \"named lambda\" though, which is in violation of the recommendations of <a href=\"https://www.python.org/dev/peps/pep-0008/#id51\" rel=\"nofollow noreferrer\">PEP</a>:</p>\n\n<blockquote>\n <p>Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier.</p>\n</blockquote>\n\n<p>¯\\_(ツ)_/¯ </p>\n\n<p>I still think it can be improved though. Look carefully at the loop. It's just a summing loop! Python has a built-in for that that can be used cleanly with a generator expression:</p>\n\n<pre><code>def throw_dice():\n roll_f = throw_fair_die if fair_dice else throw_loaded_die\n\n return sum(roll_f() for _ in range(8))\n</code></pre>\n\n<hr>\n\n<p><code>is_extra_prize</code> has a redundant return. It can be simplified to:</p>\n\n<pre><code>def is_extra_prize(score):\n return (18 <= score <= 21) or (score == 29) or (35 <= score <= 38)\n</code></pre>\n\n<p>I'll point out though that right below it you have <code>need_double_fee</code>. Either it's justified to have <code>score == 29</code> broken off into its own function (in which case it should be used in the appropriate cases), or it's not. If you feel the need to have it as a separate function, I'd use it:</p>\n\n<pre><code>def need_double_fee(score):\n return score == 29\n\ndef is_extra_prize(score):\n return (18 <= score <= 21) or need_double_fee(score) or (35 <= score <= 38)\n</code></pre>\n\n<p>Although it could be argued that the other two parts of the condition in <code>is_extra_prize</code> are more complicated than <code>score == 29</code>, and may benefit from having a name attached to them as well. There's also the alternative of naming the <code>29</code> magic number directly, which I feel would probably be an even better option:</p>\n\n<pre><code>EXTRA_PRIZE_SCORE = 29\n\ndef is_extra_prize(score):\n return (18 <= score <= 21) or (score == EXTRA_PRIZE_SCORE) or (35 <= score <= 38)\n</code></pre>\n\n<p>You may find naming <code>18</code>, <code>21</code>, <code>35</code> and <code>38</code> are beneficial as well; although that will certainly make that function more verbose.</p>\n\n<hr>\n\n<p>I think <code>get_points</code> can be improved as well. The score dictionary seems like it's a \"member of the entire program\", not something that should be local to the function. You can also use <code>get</code> on the dictionary to avoid the explicit membership lookup:</p>\n\n<pre><code>SCORE_TO_POINTS = {8:100, 9:100, 10:50, 11:30, 12:50,\n 13:50, 14:20, 15:15, 16:10, 17:5, \n 39:5, 40:5, 41:15, 42:20, 43:50, \n 44:50, 45:50, 46:50, 47:50, 48:100}\n\ndef get_points(score):\n # 0 is the default if the key doesn't exist\n return SCORE_TO_POINTS.get(score, 0)\n</code></pre>\n\n<hr>\n\n<p><code>simulate_turn</code> returns a tuple (actually a list, although it probably should be a tuple) representing the new state of the game. This is fine for simple states, but your current state has four pieces, and accessing them requires memorizing what order they're in, and allows mistakes to be made if data is placed incorrectly. You may want to look into using a class here for organization and clarity, or even a <a href=\"https://docs.python.org/3/library/collections.html#collections.namedtuple\" rel=\"nofollow noreferrer\">named tuple</a> as a shortcut.</p>\n\n<p>In that same function, I'd also add some lines to space things out a bit:</p>\n\n<pre><code>def simulate_turn(points, prizes, fee):\n score = throwDice()\n\n if isExtraPrize(score):\n prizes += 1\n\n if needDoubleFee(score):\n fee *= 2\n\n points += getPoints(score)\n\n return (points, prizes, fee, score)\n</code></pre>\n\n<p>Personal style, but I like open space in code.</p>\n\n<p>You could also do away with the mutation of the parameters:</p>\n\n<pre><code>def simulate_turn(points, prizes, fee):\n score = throw_dice()\n\n return (points + get_points(score),\n prizes + 1 if is_extra_prize(score) else prizes,\n fee * 2 if need_double_fee(score) else fee,\n score)\n</code></pre>\n\n<p>Although now that it's written out, I'm not sure how I feel about it.</p>\n\n<hr>\n\n<hr>\n\n<p>I really only dealt with <code>5.</code> here. Hopefully someone else can touch on the first four points.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T13:30:45.507",
"Id": "429581",
"Score": "0",
"body": "There is no need for brackets in `return (points, prizes, fee, score)`. Also `get_points` probably shouldn't be a function at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T14:56:09.503",
"Id": "429588",
"Score": "1",
"body": "@Georgy For the first, true, but I prefer the explicitness of wrapping tuples. And for `get_points`, while it certainly isn't very complex, having it as a function prevents needing to worry about the default value every time you want to do the conversion, which is beneficial in a couple ways. Personally, I would have it as a function, but I also prefer having many small functions."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T23:41:25.683",
"Id": "221981",
"ParentId": "221972",
"Score": "10"
}
},
{
"body": "<p>Your original implementation of <code>throwLoadedDie</code> performs some unnecessary computations on each call,\nnamely</p>\n\n<pre><code>rawMassDist = [11, 17, 39, 44, 21, 11]\nmassDist = [float(i)/sum(rawMassDist) for i in rawMassDist]\n</code></pre>\n\n<p>are computed on every call. Simply moving them to the <code>if</code>'s body like</p>\n\n<pre><code>if (idxRandom % 1000) == 0:\n rawMassDist = [11, 17, 39, 44, 21, 11]\n massDist = [float(i) / sum(rawMassDist) for i in rawMassDist]\n</code></pre>\n\n<p>brought the computation time down from around 18s to less than 6s on my old laptop.\nOf course this can be optimized even further, since the weights don't change at all during the computation.</p>\n\n<p>Combining this with a cool Python feature called <em>generator expression</em>, respectively the <code>yield</code> keyword, you can build something like</p>\n\n<pre><code>def throw_loaded_die(raw_mass_dist=(11, 17, 39, 44, 21, 11)):\n \"\"\"return one random value from [1,6] following a probability density\"\"\"\n throws = []\n mass_dist_sum = sum(raw_mass_dist)\n mass_dist = [float(i) / mass_dist_sum for i in raw_mass_dist]\n while True:\n if not throws:\n throws = random.choices((1, 2, 3, 4, 5, 6), mass_dist, k=1000)\n yield throws.pop()\n\nloaded_throws = throw_loaded_die()\n</code></pre>\n\n<p>which you can use like <code>sum(next(loaded_throws) for _ in range(8))</code> in the <code>throw_dice</code>. As <a href=\"https://codereview.stackexchange.com/users/154946/georgy\">@Georgy</a> pointed out in a comment, <code>random.choices</code> also works fine with <code>raw_mass_dist</code>, so there is no strict need to normalize for the non-NumPy version. For further explanations see <a href=\"https://stackoverflow.com/q/231767/5682996\">this excellent Stack Overflow post</a>.</p>\n\n<p>I also created a version using NumPy and indexing - much like your original solution - to see if the performance can be improved even further.</p>\n\n<pre><code> \"\"\"return one random value from [1,6] following a probability density\"\"\"\n throws = []\n mass_dist = numpy.array(raw_mass_dist) / numpy.sum(raw_mass_dist)\n idx = 1000\n while True:\n if idx >= 1000:\n idx = 0\n throws = numpy.random.choice((1, 2, 3, 4, 5, 6), p=mass_dist, size=(1000, ))\n yield throws[idx]\n idx += 1\n</code></pre>\n\n<p>This implementation performs on par with my first proposed implementation when used in your script without any further changes. Some more extensive timing suggests that the NumPy/indexing version will win if you increase the number of throws significantly.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T15:24:43.297",
"Id": "429591",
"Score": "0",
"body": "You don't need to calculate `mass_dist`, simply pass `raw_mass_dist` to `random.choices`. Also, I don't understand the point of generating a list of 1000 elements and then popping them one by one. Why not generate just one element each call?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T16:48:30.750",
"Id": "429604",
"Score": "0",
"body": "@Georgy: The OP rightfully pointed out that `random.choices` has some calling overhead. If you use `yield random.choices((1, 2, 3, 4, 5, 6), mass_dist, k=1)[0]` you end up with a version that performs five times slower than the one with the internal buffer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T14:54:43.790",
"Id": "222027",
"ParentId": "221972",
"Score": "4"
}
},
{
"body": "<blockquote>\n <ol start=\"3\">\n <li>How are my names? Especially <code>hist</code>, <code>hist2</code>, <code>isExtraPrize()</code> and <code>needDoubleFee()</code></li>\n </ol>\n</blockquote>\n\n<p>Not really great. For one, they don't follow <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> conventions, and, for two, there is no real reason for abreviating variable names anyway.</p>\n\n<blockquote>\n <ol>\n <li>Since calling <code>random.choices()</code> has some overhead, I generate 1000 loaded die rolls and put it in a global array. Is there a better of doing this without classes? In C I'd probably use static variables</li>\n </ol>\n</blockquote>\n\n<p>You would have to generate 1000 random numbers anyway when simulating 1000 turns. And this should be the bottleneck of your code, so I’d rather avoid overly complicating things and make it straighforward. The only reason I’d still keep a function to generate a bunch of random values at once would be to keep the option of messing with the probability of rolling a particular number (the <code>weights</code> parameter of <code>random.choices</code> or the <code>p</code> parameter of <code>numpy.random.choice</code>).</p>\n\n<blockquote>\n <ol start=\"2\">\n <li>To generate a histogram of all the scores during a game, I append to a list every turn, and then generate the histogram. Is this efficient performance-wise?</li>\n </ol>\n</blockquote>\n\n<p>I think you would probably benefit from using a <a href=\"https://docs.python.org/3/library/collections.html#collections.Counter\" rel=\"nofollow noreferrer\"><code>Counter</code></a> to, at least, <code>update</code> it efficiently and then convert it to the proper structure for display, if need be. But wait, there is an even better option:</p>\n\n<blockquote>\n <ol start=\"4\">\n <li>My Ryzen 5 2400G with 3200 MHz RAM takes about 15s to simulate 100 loaded games, averaging \n 3550 turns per game. I somehow feel like this should be faster, any performance related suggestions are welcome</li>\n </ol>\n</blockquote>\n\n<p>Since you are loading <code>numpy</code> for some of your computation, why not delegate the entire simulation to it? Its fancy indexing can simplify your <code>isExtraPrize</code> and <code>getPoints</code> function. For instance:</p>\n\n<pre><code>>>> POINTS = np.array([\n 0, 0, 0, 0, 0, 0, 0, 0, 100, 100, 50, 30, 50,\n 50, 20, 15, 10, 5, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 5, 5, 15, 20, 50, 50, 30, 50, 100, 100])\n>>> POINTS[[8, 22, 19, 48, 17]]\narray([100, 0, 0, 100, 5])\n</code></pre>\n\n<p>You can then easily benefit from <code>np.sum</code> and <code>np.cumsum</code> on the resulting arrays and even perform vecorized mathematical operations to compute fees.</p>\n\n<p>Using <code>np.random.choice</code>, you can generate up to <span class=\"math-container\">\\$8 \\times 100000\\$</span> die at once and discard those not needed if you reach 100 points before that many throws.</p>\n\n<p>Example code using these:</p>\n\n<pre><code>import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef build_scoring_chart():\n prizes = np.zeros(49, dtype=bool)\n prizes[[*range(18, 22), 29, *range(35, 39)]] = True\n\n points = np.zeros(49, dtype=int)\n points[[*range(8, 18), *range(39, 49)]] = [\n 100, 100, 50, 30, 50, 50, 20, 15, 10, 5,\n 5, 5, 15, 20, 50, 50, 30, 50, 100, 100,\n ]\n\n return points, prizes\n\n\nPOINTS, PRIZES = build_scoring_chart()\n\n\ndef throw_die(amount=1000, weights=None):\n if weights is not None:\n weights = np.array(weights)\n weights /= weights.sum()\n return np.random.choice(range(1, 7), size=(amount, 8), p=weights).sum(axis=1)\n\n\ndef play_game(max_turns=1000):\n results = throw_die(max_turns)\n turns = POINTS[results].cumsum() < 100\n results = results[turns] # keep only actual, meaninful, throws\n\n prizes = 1 + PRIZES[results].sum()\n fees = (2 ** (results == 29).cumsum(dtype=np.uint64)).sum()\n\n histogram, _ = np.histogram(results, bins=49, range=[0, 49])\n return prizes, len(results), fees, histogram\n\n\ndef play_games(games_count, max_turns=1000, verbose=False):\n throws_count = np.zeros(49, dtype=int)\n prizes = 0\n fees = 0\n turns = 0\n games_lost = 0\n points_scored = 0\n\n for _ in range(games_count):\n prizes_won, turns_played, fees_paid, histogram = play_game(max_turns)\n lost = turns_played == max_turns\n games_lost += lost\n if verbose:\n if lost:\n print('You couldn\\'t achieve 100 points in', turns_played, 'turns but paid', fees_paid)\n else:\n print('You won', prizes_won, 'prizes in', turns_played, 'turns and paid', fees_paid)\n\n throws_count += histogram\n prizes += prizes_won\n fees += fees_paid\n turns += turns_played\n points_scored += histogram[POINTS != 0].sum()\n\n if verbose:\n print(games_count, 'games,', games_lost, 'lost')\n print('Average prizes:', prizes / games_count)\n print('Average turns:', turns / games_count)\n print('Average fees:', fees / games_count)\n print('Percentage of turns scoring points:', points_scored / throws_count.sum() * 100)\n\n # create list of colors to color each bar differently\n colors = ['red'] * 18 + ['blue'] * 21 + ['red'] * 10\n plt.bar(range(0, 49), throws_count, color=colors)\n plt.title('Score distribution across multiple games')\n plt.xlabel('Score = sum of 8 dice')\n plt.ylabel('Number of throws')\n plt.text(40, 0.6 * throws_count.max(), 'Red bars\\ngive points')\n plt.show()\n\n\nif __name__ == '__main__':\n play_games(100, 2000, True)\n</code></pre>\n\n<p>Note that I moved output in the outermost function to ease testing and reusability; and this meant losing the ability to print the score reached if unable to reach the 100 points mark.</p>\n\n<p>This code runs in less than 3 seconds on my machine when generating 800000 random numbers per game, and in around half a second when generating 16000 numbers per game (as in the posted example).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-13T11:04:22.587",
"Id": "429973",
"Score": "0",
"body": "Oh, nice! I came up with something very similar but didn't have time to polish it to show here. I also created a `NamedTuple` class with those `prizes, turns, fees, games_lost` packed in it, so I could use `functools.reduce` to add them in one line instead of writing `prizes += prizes_won`, `fees += fees_paid`, `turns += turns_played` etc."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-12T15:07:14.930",
"Id": "222163",
"ParentId": "221972",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "221981",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T17:22:14.773",
"Id": "221972",
"Score": "16",
"Tags": [
"python",
"performance",
"simulation",
"dice"
],
"Title": "Razzle Dazzle simulator"
} | 221972 |
<p><strong>The task</strong> is taken from <a href="https://leetcode.com/problems/generate-parentheses/" rel="nofollow noreferrer">LeetCode</a></p>
<blockquote>
<p><em>Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.</em></p>
<p><em>For example, given n = 3, a solution set is:</em></p>
<pre><code>[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
</code></pre>
</blockquote>
<p><strong>My solution</strong></p>
<p>is based on <a href="https://de.wikipedia.org/wiki/Backtracking" rel="nofollow noreferrer">backtracking</a>. Maybe there's a better approach than that? The reason I do this task is because I want to improve my skills. So, if you got any improvement suggestions or an alternative approach - no matter how fancy it is - feel free to post it here.</p>
<pre><code>/**
* @param {number} n
* @return {string[]}
*/
var generateParenthesis = function(n) {
const addParanthesis = (cur, open, close) => {
if (cur.length === n * 2) {
res.push(cur);
return;
}
if (open < n) { addParanthesis(cur + '(', open + 1, close); }
if (close < open) { addParanthesis(cur + ')', open, close + 1); }
};
const res = [];
addParanthesis('', 0, 0);
return res;
};
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T17:42:47.507",
"Id": "429483",
"Score": "2",
"body": "Please provide us with some insights how you got to this solution or what parts you think can be improved. https://codereview.stackexchange.com/help/how-to-ask"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T21:17:29.860",
"Id": "429503",
"Score": "0",
"body": "I updated with additional information even though I didn't had to do it in my previous questions. I always assumed CR works like code review in real life: You get code and than review it. Usually you don't have to provide the other party the information how you got to the solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T21:27:46.133",
"Id": "429504",
"Score": "0",
"body": "The problem with posting code without any additional information or question, is that we don't know what you are looking for in a review. In addition, statistically, the quality of an answer correlates with that of the question :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T09:03:05.390",
"Id": "429555",
"Score": "1",
"body": "@thadeuszlay - Here is javascript's style guide - https://github.com/airbnb/javascript - I found it really helpful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-12T05:46:11.107",
"Id": "429811",
"Score": "0",
"body": "Other than the minor naming issues / lack of immediate clarity about how it's working, this solution is quite nice."
}
] | [
{
"body": "<h3>Names</h3>\n\n<p>The plural of <em>parenthesis</em> is <em>parentheses</em> (as used in the specification). So I think it would make more sense to call the top level function <code>generateParentheses</code>, or even <code>generateBalancedParentheses</code>.</p>\n\n<p>The inner function should be <code>addParenthesis</code> (with an <code>e</code> substituted for the third <code>a</code>).</p>\n\n<p>Opinions will vary on <code>cur</code> as an abbreviation for <code>current</code>. I think it's common enough to be easily recognised, although given the meaning of the value it names perhaps <code>prefix</code> would be better.</p>\n\n<p><code>open</code> and <code>close</code> read to me as verbs, although <code>open</code> could also be a count of the number of parentheses which have been opened and not closed (i.e. the surplus of <code>(</code> over <code>)</code> in <code>cur</code>). I've reverse engineered that they count, respectively, the number of <code>(</code> and <code>)</code> in <code>cur</code>. Perhaps <code>opened</code> and <code>closed</code> would be clearer, along with a comment explaining what they are.</p>\n\n<h3>Scope</h3>\n\n<p>Although JavaScript is very forgiving of the order of declarations, humans tend to read code in order. I would find it clearer if <code>res</code> were defined <em>before</em> <code>addParenthesis</code>, since that references it.</p>\n\n<h3>Correctness</h3>\n\n<p>Although the code looks correct to me, I would like to see some comments to justify <em>why</em> it's correct. Why are the <code>if</code> guards necessary and sufficient?</p>\n\n<p>With these comments, you would also be able to justify a slight simplification:</p>\n\n<pre><code> const addParenthesis = (prefix, opened, closed) => {\n if (closed === n) { res.push(prefix); }\n if (opened < n) { addParenthesis(prefix + '(', opened + 1, closed); }\n if (closed < opened) { addParenthesis(prefix + ')', opened, closed + 1); }\n };\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T08:42:03.167",
"Id": "221999",
"ParentId": "221973",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "221999",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T17:34:23.643",
"Id": "221973",
"Score": "4",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"combinatorics",
"balanced-delimiters"
],
"Title": "Generate all possible combination of n-pair parentheses"
} | 221973 |
<p>I have an API that provides data that is updated on an infrequent schedule, about once every 2½ minutes on average. Assuming that it's okay to fetch only as often as every 2½ minutes or less often, I'd like to construct a saga (I use redux-saga) in a way that it does nothing if it's not yet time to do an API call. The code I came up with is quite simplistic (API error handling omitted):</p>
<pre><code>import { select, put, call } from "redux-saga/effects";
const FETCH_INTERVAL = 1000 * 60 * 60 * 2.5;
function* fetchApiSaga(apiUrl) {
// get data from the store
const data = select(state => state.theDataWeNeed);
// signal to the user that we're about to fetch data
put(WAITING_FOR_DATA);
// if fetched 2.5 ago or earlier, fetch again
if (!data || new Date() - !data.lastFetchedAt > FETCH_INTERVAL) {
const response = yield call(apiUrl);
// signal to the user that now we have new data from the API
put(REWRITE_DATA, response);
} else {
// signal to the user that we just reuse old data
put(JUST_USE_CACHED_DATA);
}
}
</code></pre>
<p>Now, I have two questions:</p>
<ol>
<li>Is this an idiomatic way to suppress consecutive actions in Redux Saga based on time?</li>
<li>Is this idiomatic Redux Saga if the generator function <code>select</code>s from the store and therefore is not pure?</li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-08T14:07:39.947",
"Id": "452943",
"Score": "0",
"body": "does this help? https://github.com/redux-saga/redux-saga/blob/master/docs/advanced/RacingEffects.md"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-08T17:15:50.043",
"Id": "452966",
"Score": "0",
"body": "It's a bit reverse: race starts two sagas and finishes as soon as any of them finishes. My question is more about finishing a saga and not starting it (i.e. not executing the generator function again) until some time has passed since the previous call. But I'll look into this as well, thanks!"
}
] | [
{
"body": "<p>Disclaimer: I´m not an expert in redux / redux-saga. This post is not directly answering your questions. Rather, it is focused on code design / architecture and what is the most useful approach for the underlying problem.</p>\n\n<p>For me, the main question is: Who is in charge of determining when the data is invalid?</p>\n\n<p>Imho, there are at least three answers to this:</p>\n\n<ol>\n<li>The API / backend / server</li>\n<li>The frontend application</li>\n<li>One particular UI component</li>\n</ol>\n\n<p>If it is 1., then I would use HTTP cache headers like <code>Cache-Control: max-age=150</code>. This way, the backend can change the value without requiring to adapt the frontend. Also, it removes the need for any conditional code. The saga can always call the API and the browser does the caching.</p>\n\n<p>If it is 2., then the saga should contain the conditional code to determine whether to fetch new data or to used cached values. Where to put the actual cache and how to do this is a question on its own with regards to frontend application architecture.</p>\n\n<p>If it is 3., then the particular UI component should contain the conditional code and it should also contain / be in charge of the cached values.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T10:00:24.880",
"Id": "222004",
"ParentId": "221975",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T20:59:09.327",
"Id": "221975",
"Score": "1",
"Tags": [
"javascript",
"timer",
"cache",
"redux"
],
"Title": "Suppress API call in Redux Saga based on a timer"
} | 221975 |
<p><strong>The task</strong></p>
<p>is taken from <a href="https://leetcode.com/problems/letter-combinations-of-a-phone-number/" rel="nofollow noreferrer">LeetCode</a></p>
<blockquote>
<p><em>Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. A
mapping of digit to letters (just like on the telephone buttons) is
given below. Note that 1 does not map to any letters.</em></p>
<p><a href="https://i.stack.imgur.com/9z5PY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9z5PY.png" alt="enter image description here"></a></p>
<p><strong>Example:</strong></p>
<pre><code>Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
</code></pre>
<p><strong>Note:</strong></p>
<p><em>Although the above answer is in lexicographical order, your answer could be in any order you want.</em></p>
</blockquote>
<p><strong>My solution</strong></p>
<p><em>(I've been told I should provide additional information to my solution otherwise I get downvoted.)</em></p>
<p>is based on <a href="https://de.wikipedia.org/wiki/Backtracking" rel="nofollow noreferrer">backtracking</a>. Why I choosed that approach? Well, whenever you encounter a task where you have to combine or permutate things, then backtracking is a possible approach. </p>
<p>But if you know a better one, then please go ahead. Otherwise I only got generic questions to my code: Can you make it <strong>faster, cleaner, more readable,</strong> etc.? </p>
<p>Also I'm interested in <strong>functional programming.</strong> So, if you got a good functional approach, feel free to post it here, too. Other than that, I'm always interested in a different perspective. So, if you got a <strong>fancy or conservative approach,</strong> please feel free to post them here.</p>
<p><strong>Imperative approach</strong></p>
<pre><code>/**
* @param {string} digits
* @return {string[]}
*/
var letterCombinations = function(digits) {
if (digits === '') { return []; }
const strDigits = {
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz',
};
if (digits.length === 1) { return [...strDigits[digits]]; }
const res = [];
const combine = (cur, n) => {
if (cur.length === digits.length) {
res.push(cur);
return;
}
[...strDigits[digits[n]]].forEach(x => {
combine(cur + x, n + 1);
});
};
combine('', 0);
return res;
};
</code></pre>
<p><strong>Functional approach</strong></p>
<pre><code>/**
* @param {string} digits
* @return {string[]}
*/
var letterCombinations = function(digits) {
if (digits === '') { return []; }
const strDigits = {
'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz',
};
const combine = (cur, n) => cur.length === digits.length
? cur
: [...strDigits[digits[n]]].flatMap(x => combine(cur + x, n + 1));
return combine('', 0);
};
</code></pre>
| [] | [
{
"body": "<blockquote>\n <p>whenever you encounter a task where you have to combine or permute things, then backtracking is a possible approach.</p>\n</blockquote>\n\n<p>True. It is not necessarily the best though (in fact it is rarely the best).</p>\n\n<p>In this particular case, the problem naturally maps to finding the <em>next combination</em>. In turn, it is no more than an increment of a number in some fancy numbering system. In your example, the minimal possible string is <code>ad</code>. Subsequent increments yield <code>ae</code>, then <code>af</code>, then (<code>'f' + 1</code> is <code>d</code> and a carry bit does carry) <code>bd</code>, etc.</p>\n\n<p>Consider implementing the <code>increment/next</code> method directly. The space complexity will definitely benefit; and it is trivial to convert into a generator. The time complexity is likely to also benefit, depending on the use case.</p>\n\n<p>PS: thank you for posting your train of thoughts.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T00:20:23.867",
"Id": "221983",
"ParentId": "221976",
"Score": "8"
}
},
{
"body": "<p>I think your functional approach is very nice, and scores high points for readability. As long as the recursion wasn't causing performance issues, that's how I'd approach it.</p>\n\n<p>However, it's not very efficient, and as vnp points out, listing permutations is really just a matter of counting from 1 to \"the number of combinations\" in a mixed base numbering system. </p>\n\n<h2>mixed base counting</h2>\n\n<p>These are easy implement, and it's worth going through the exercise, because <em>assuming you have a utility that does the mixed base counting for you</em>, the solution to the original problem will be both straightforward and efficient:</p>\n\n<pre><code>function mixedBaseCounter(bases) {\n let cnt = 0\n let maxCnt = bases.length ? [...bases].reduce((m, x) => m * x, 1) : 0\n let digits = bases.map(() => 0)\n\n const increment = (i = 0) => {\n digits[i] = (digits[i] + 1) % bases[i]\n if (digits[i] == 0) increment(i + 1)\n }\n\n return {\n [Symbol.iterator]: function* () {\n while (cnt++ < maxCnt) {\n yield digits.join('')\n increment()\n }\n }\n }\n}\n</code></pre>\n\n<p>This uses <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator#Examples\" rel=\"nofollow noreferrer\">ECMA script's iterable interface</a>. Note the above implementation has the least significant bit on the left (easily changed, if you need to).</p>\n\n<p>Let's verify it counts correctly in binary:</p>\n\n<pre><code>[...mixedBaseCounter([2, 2, 2])]\n// [ '000', '100', '010', '110', '001', '101', '011', '111' ]\n</code></pre>\n\n<p>And that it handles mixed bases:</p>\n\n<pre><code>console.log([...mixedBaseCounter([2, 3])])\n// [ '00', '10', '01', '11', '02', '12' ]\n</code></pre>\n\n<p><a href=\"https://tio.run/##jZHNTsMwEITveYq5oNptsQrcKgoSfQSOUQ5psk1d@adyHEiF@uzBNmmKxAUpsrK7n2dH42P5UbaVkyd/b2xNw7DvTOWlNdCyp/qtbGlrO@PJsV34bzm@MkCRR2U8NliNlS77bWokSigyjT/gFbkQIrUK4ajuKmJML9FzbF6gMUe/xAPHetKpZSN9O@no8sRYglc8C0hlTeshTeVIU9rHZHSRkOgMo0Iuizi8FYu45@5HNtQJlfvfxCbpTNpBON4J4CVuduQ7Z8Yd@ftZ76wSMuRSeuuKNa65zcH4SAGfB6kILES1WOB5DOk2Bs6SVD1aFkcrDZvN@DS9ebn2Ltn1vGTBVozDKhLKNiwm/efN8scl4lfwgv8Tf4rsMHwD\" rel=\"nofollow noreferrer\" title=\"JavaScript (Node.js) – Try It Online\">Try it online!</a></p>\n\n<h2>applying it to the problem</h2>\n\n<p>Now the solutions becomes:</p>\n\n<pre><code>function letterCombinations(digits) {\n\n const strDigits = {\n '2': 'abc',\n '3': 'def',\n '4': 'ghi',\n '5': 'jkl',\n '6': 'mno',\n '7': 'pqrs',\n '8': 'tuv',\n '9': 'wxyz',\n }\n\n const letterOptions = [...digits].map(x => strDigits[x])\n const bases = [...letterOptions].map(x => x.length)\n const masks = mixedBaseCounter(bases)\n\n return [...masks].map(m =>\n [...m].map((x, i) => letterOptions[i][x]).join('')\n )\n}\n</code></pre>\n\n<p>where each \"mask\" (or number, within the mixed base numbering system) chooses one combination.</p>\n\n<p>Note also we no longer need to treat the empty string as a special case. </p>\n\n<p><a href=\"https://tio.run/##jVLLbtswELzrK/ZSiIwdIX0lrRGnQN17Dz0aOtASbdMRSYekErmFvt3lUqRkHwr0ImiWs7OzjwN7ZbYy4uhula75eduqygmtQIqO19@Z5SvdKscN2fh/S@FPBtBwB5VysIS7iCTrViEQWEXD1c7t4Rusi6IIobIwvG4rToicQ0dh@QQSbqCbw3sKi1GnFjvh7Kgj2ZGQQL6jmadUWlkHQlWGSx7qEYEuAgWdQVRYixIfJzDDOu8GWY8DVWwvGcugM2p7YczxxB4rG@5ao2KN9a@T3OimEH4uzGlTLiDN7QYIjSyAt71oOBA/qtkMHuOQpmeAk@BNHS0XBy0UyXM6vk5eUqzP0rfP@mlXfnLeyUrLjVAMIzb2hbXGsVlnfqTxDhbyD/kCcrap8vmAPyKu@TbhT4h3e5HwZ8SH5ybhe8RS6YQfEB9fjE2BLxhw7WvCXxG/daffIdBP5oYWfh6De28QD2fooQxX0OGGxw7WXUnH1LDTmHIlc5HZxZOcsiSzz5j1jzufVo6ygTzISS83HAHGhxjxZyzCDV7V91eFRi8XSzPfc5ahBd3wotE7Mtm@WmD@cJ9T3@X/UJF4Pv8F\" rel=\"nofollow noreferrer\" title=\"JavaScript (Node.js) – Try It Online\">Try it online!</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T05:52:07.260",
"Id": "221987",
"ParentId": "221976",
"Score": "4"
}
},
{
"body": "<p>I see a couple of simplifications that could be made:</p>\n\n<p>A feature of <a href=\"/questions/tagged/ecmascript-6\" class=\"post-tag\" title=\"show questions tagged 'ecmascript-6'\" rel=\"tag\">ecmascript-6</a> that could be used here is <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters\" rel=\"nofollow noreferrer\">default parameters</a>:</p>\n\n<pre><code>const combine = (cur = '', n = 0) => {\n</code></pre>\n\n<p>Then the first call to that function doesn't need to pass any parameters:</p>\n\n<pre><code>combine();\n</code></pre>\n\n<hr>\n\n<p>The arrow function in the imperative approach feels too brief to warrant the need for brackets:</p>\n\n<blockquote>\n<pre><code>[...strDigits[digits[n]]].forEach(x => {\n combine(cur + x, n + 1);\n});\n</code></pre>\n</blockquote>\n\n<p>So that could be shortened to a single line:</p>\n\n<pre><code>[...strDigits[digits[n]]].forEach(x => combine(cur + x, n + 1));\n</code></pre>\n\n<p>But if that is longer than your desired maximum length of a line of code, pull out the arrow function:</p>\n\n<pre><code>const combineNext = x => combine(cur + x, n + 1);\n[...strDigits[digits[n]]].forEach(combineNext);\n</code></pre>\n\n<p>Actually, in an <em>imperative</em> solution, I might expect to see a <code>for...of</code> loop, which should be faster:</p>\n\n<pre><code>for (const x of [...strDigits[digits[n]]]) {\n combine(cur + x, n + 1);\n}\n</code></pre>\n\n<hr>\n\n<p>I considered suggesting that the keys of <code>strDigits</code> be integers instead of string literals, each element in <code>digits</code> would be a string so the types would then be different.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T17:18:24.370",
"Id": "222035",
"ParentId": "221976",
"Score": "2"
}
},
{
"body": "<h2>Make it faster</h2>\n\n<p>This is only improvements on the algorithm you have used.</p>\n\n<p>There are a few ways to improve the performance. The majority are minor a few % points improvement but due to the complexity ~<span class=\"math-container\">\\$O(3^n)\\$</span> quickly sum up to be worth the effort. </p>\n\n<h2>The last step</h2>\n\n<p>There is a very common mistake in recursive code that will nearly always give a huge performance gain (30-40% in this case).</p>\n\n<p>First think about why you are using a recursive function. In this case you are using it to hold the current <code>cur</code> combination until it is complete. In other words you are using the recursive call to place <code>cur</code> on a stack, the stack being the call stack. The call stack is easy to use (transparent) but comes with the cost of stacking everything within the functions context, including all that is not relevant to the next step.</p>\n\n<p>The common error in recursion is to place the exit clause at the beginning of the function. \nIn the snippet below, you recurse at <code>#A</code> with <code>cur + x</code> which pushes a new context to the call stack, then at point <code>#B</code> you check to see if <code>cur + x</code> now as <code>cur</code> is the final length to exit. </p>\n\n<p>So at point <code>#A</code> you have all the information needed to know whether or not to exit, thus wasting the creation on a new context.</p>\n\n<h3>Redundant recursion call</h3>\n\n<pre><code> // For seven digit number (ignoring 9) the following calls combine 3280\n const combine = (cur, n) => {\n if (cur.length === digits.length) { // code point #B\n res.push(cur); \n return;\n }\n [...strDigits[digits[n]]].forEach(x => combine(cur + x, n + 1)); // code point #A\n };\n</code></pre>\n\n<h3>Exit one recursion step earlier</h3>\n\n<p>To avoid that extra call by testing for the length early</p>\n\n<pre><code> // For seven digit number (ignoring 9) the following calls combine 1093 times\n const FINAL_LEN = digits.length - 1\n const combine = (cur, n) => {\n if (cur.length === FINAL_LEN) { // only one char remaining to add\n [...strDigits[digits[n]]].forEach(x => res.push(cur + x));\n\n } else { [...strDigits[digits[n]]].forEach(x => combine(cur + x, n + 1)) }\n };\n</code></pre>\n\n<p>So for a 7 digit number (ignoring \"9\") the complexity is <span class=\"math-container\">\\$O(3^n)\\$</span> saving 2187 needless pushes to the call stack. About a 30-40% saving in performance.</p>\n\n<h2>Example <strong>~40%</strong> performance improvement</h2>\n\n<p>The following example has a <strong>~40%</strong> improvement in performance when processing a set of random number strings in the range 2 - 79999999. (I did note that as the range grew there was a small drop in the improvement with a ~37% for 10 digits, and 34% for 12 digits and is likely due to the array size growth and memory management overhead)</p>\n\n<p>Other improvements.</p>\n\n<ul>\n<li>Avoid capturing (closure) of function's <code>combine</code> state by using for loops.</li>\n<li>Using an pre processed array of digits, avoiding the need to build the array <code>[...strDigits[digits[n]]]</code></li>\n<li>Convert the digits string to numbers and use indexed array to lookup characters to reduce JS hashing to locate items in <code>strDigits</code> </li>\n</ul>\n\n<p>The rest of the changes are just style as performance testing iteration required many versions and my style slowly intruded into the final iteration</p>\n\n<p>I moved <code>ALPHAS</code> previously <code>strDigits</code> outside the function because that is my style (avoid repeated processing) and does not provide an improvement. You would normally capture it in a IIF closure.</p>\n\n<pre><code>const ALPHAS = \",,abc,def,ghi,jkl,mno,pqrs,tuv,wxyz\".split(\",\").map(a => [...a]);\nfunction letterCombinations(numStr) {\n const alphas = ALPHAS; // local scope reference for shallower scope search\n const nums = [...numStr].map(Number);\n const res = [];\n const count = nums.length - 1;\n (function combine(n, cur) {\n if (n === count) {\n for (const char of alphas[nums[n]]) { res.push(cur + char) }\n } else {\n for (const char of alphas[nums[n]]) { combine(n + 1, cur + char) }\n }\n })(0, \"\");\n return res;\n}\n</code></pre>\n\n<h2>Functional</h2>\n\n<p>My distaste for functional code has another example of why it is to be avoided and decried at every opportunity. You functional code a an order of magnitude slower than your imperative solution. </p>\n\n<p>Not only was it slow but the fans on the machine kicked in so I looked at the load. There was the equivalent to an extra core running near flat out (JS GC and memory management threads) and power consumption jumped by <strong>20W</strong>!!! (thats a 3rd of a solar panel) over running the tests without the functional solution.</p>\n\n<p>The list below shows the comparative results for set of random digits to 8 digits long. (an operation is one test cycle)</p>\n\n<pre><code>BM67....: Time: 3,875µs OPS: 258 100% Total time: 3,798ms for 980 operations\nOP imp..: Time: 6,370µs OPS: 156 60% Total time: 6,307ms for 990 operations\nOP func.: Time: 84,988µs OPS: 11 4% Total time: 82,439ms for 970 operations\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T20:13:56.107",
"Id": "429633",
"Score": "0",
"body": "Is there a use case where you would prefer functional over imperative (a general question and not related to this problem)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T20:38:28.153",
"Id": "429637",
"Score": "0",
"body": "BTW: Some stuff you wrote are quite genius and i could have wrote it myself, e.g. using of IIFE, move the ALPHAS outside of the functions, ... . It's so clear once you see it, but when I wrote it I thought, my code was quite good. But it wasn't I still have to learn a lot .....and also learn to apply what I already know. Thanks again for pointing out my mistakes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T20:53:54.950",
"Id": "429639",
"Score": "0",
"body": "@thadeuszlay There is no reason I would use a functional approach in javascript unless it (JS) was modified to allow function calls to be multi threaded. IE call to `myFunc(...blah)` is run in a new thread returning on an implied `await`. I do not buy the no side effects argument as it is defensive (protecting poor coding from itself) rather than encouraging good coding skills. There is good reason functional coding is a realm of academia and seldom seen in the industry sector as it provides no benefit over good traditional coding paradigms."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T21:00:49.157",
"Id": "429640",
"Score": "0",
"body": "I spent a few months learning FP, because I thought it would improve my coding skills, e.g. by reading books, solving puzzles using FP, etc.. I now feel it was a waste of my time. What would you recommend for someone who wants to improve his coding skills, e.g. some books, projects, ...?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T21:18:51.393",
"Id": "429641",
"Score": "0",
"body": "@thadeuszlay The best way to gain skill is to write, not just small solutions but big projects 10,000+ lines. Big is when bugs start to dominate and your skill to write well is paramount to keep it all working. If you are stuck for a project, write a game as they can be amongst the most difficult code challenges there are (write from the ground up, don't use frameworks or libraries). And always keep in mind segregate and ENCAPSULATE or you will spend more time hunting bugs than writing code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-13T02:38:28.603",
"Id": "429930",
"Score": "0",
"body": "Regarding fp: what is your opinion about the advantages that comes with writing to style: , e.g. testable code, more concise, and easier to reason about?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-13T09:07:18.167",
"Id": "429959",
"Score": "0",
"body": "I mean \"fp style\" (not \"to style\")"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-13T16:01:36.437",
"Id": "430035",
"Score": "0",
"body": "@thadeuszlay There is a big difference between FP in JavaScript (FJS) and in Haskell. JS does not enforce \"no side effects\" thus testing is no different from any other JS project. Concise and Easier is more about the skill set of the coders on the job. Side by side the development process is no more or less expensive, so the deciding factor is the end product. FJS results in under performing apps that will never compete with a well written OO (classless) alternative. I see FJS as a dead end if the performance issues are not addressed."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T19:25:27.287",
"Id": "222046",
"ParentId": "221976",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "222046",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-09T21:42:08.077",
"Id": "221976",
"Score": "6",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"functional-programming",
"ecmascript-6"
],
"Title": "Find all letter Combinations of a Phone Number"
} | 221976 |
<p>I have a number of custom events that a class might or might not subscribe to. </p>
<pre><code>Action<Game1, MoveEventArgs> MoveEvent;
Action<Game1, InitializeEventArgs> InitializeEvent;
Action<Game1, DrawEventArgs> DrawEvent;
Action<Game1, LoadContentEventArgs> LoadContentEvent;
</code></pre>
<p>Each event is currently very similar just containing a number of properties such as:</p>
<pre><code>public class MoveEventArgs : EventArgs
{
public Vector2 Direction { get; set; }
}
public class LoadContentEventArgs : EventArgs
{
public ContentManager Content { get; set; }
}
</code></pre>
<p>Some have more some have less. These are likely to be either expanded on or changed in the future if I need to pass more information.</p>
<p>A method subscribing to these events will generally access these arguments using them in someway that is specific to that event. For example a move event may look like this.</p>
<pre><code>public void Move(object o, MoveEventArgs e)
{
spriteInfo.Position = new Vector2(
spriteInfo.Position.X + e.Direction.X, spriteInfo.Position.Y + e.Direction.Y
);
}
</code></pre>
<p>And a content event may look like this.</p>
<pre><code>public virtual void LoadContent(object o, LoadContentEventArgs e)
{
spriteInfo.Texture = e.Content.Load<Texture2D>(spriteInfo.TextureName);
}
</code></pre>
<p>I would like to bundle these in someway so I can easily pass them into other functions. Such as in a list or dictionary.</p>
<p>I have come up with two solutions.
The first is to change my event declarations from:</p>
<pre><code>Action<Game1, InitializeEventArgs> InitializeEvent;
public virtual void Initialize(object o, InitializeEventArgs e) { }
</code></pre>
<p>to:</p>
<pre><code>Action<Game1, EventArgs> InitializeEvent;
public virtual void Initialize(object o, EventArgs e)
{
InitializeEventArgs initializeEventArgs = (InitializeEventArgs)e;
}
</code></pre>
<p>This will allow me to create data stuctures using the type <code>Action<Game1, EventArgs></code> but will mean I lose the typing on my event subscriber methods possibly resulting in cast exceptions.</p>
<p>The second is creating a struct with my Events in which I can pass to classes/methods.</p>
<pre><code>public struct Events
{
public Action<Game1, MoveEventArgs> MoveEvent { get; set; }
public Action<Game1, InitializeEventArgs> InitializeEvent { get; set; }
public Action<Game1, DrawEventArgs> DrawEvent { get; set; }
public Action<Game1, LoadContentEventArgs> LoadContentEvent { get; set; }
}
</code></pre>
<p>Which I can then use to subscribe to the event in the appropriate class/method using:</p>
<p><code>Events.InitializeEvent += Initialize;</code></p>
<p>This seems good but it could potentially become a very large struct especially if I were to have a large number of events.</p>
<p>So I guess my main question is does anyone have improvements for these ideas or something different?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T01:26:26.350",
"Id": "429522",
"Score": "5",
"body": "Welcome to Code Review. Please provide more concrete code, so that we can fully understand your situation and give you the proper advice. Specifically, what do these args look like, and how are they used?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T06:38:16.143",
"Id": "429528",
"Score": "0",
"body": "I have added some more information about what the args look like and some of my methods that use them. If you feel that this still isn't enough please let me know what else you feel is missing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-11T18:03:32.400",
"Id": "429746",
"Score": "0",
"body": "I have rolled back your last edit. Please see [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers): _**Do not add an improved version of the code** after receiving an answer. Including revised versions of the code makes the question confusing, especially if someone later reviews the newer code._"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-11T20:26:21.387",
"Id": "429773",
"Score": "0",
"body": "@AntonyCapper You can always post a self-answer with your conclusions."
}
] | [
{
"body": "<h3>Review Solution 1</h3>\n<p>Sacrificing usability for the common consumer of your API in order to gain some usability for specific consumers that happen to subscribe on a multitude of events, should never be considered best practice.</p>\n<blockquote>\n<pre><code>Action<Game1, EventArgs> InitializeEvent;\npublic virtual void Initialize(object o, EventArgs e) \n{ \n // the average consumer does not want to cast here \n // if he only wants to be subscribed to this event ->\n InitializeEventArgs initializeEventArgs = (InitializeEventArgs)e; \n}\n</code></pre>\n</blockquote>\n<h3>Review Solution 2</h3>\n<p>Grouping events together is a better approach, since the common consumer is not impacted. It is an augmentation, rather than a substitution, of the event pattern. Though your implementation using a <code>struct</code> is viable, I would opt to use a more common approach - the <a href=\"http://www.informit.com/articles/article.aspx?p=708378&seqNum=3\" rel=\"nofollow noreferrer\">Callback Interface</a>.</p>\n<blockquote>\n<pre><code>public struct Events\n{\n public Action<Game1, MoveEventArgs> MoveEvent { get; set; }\n public Action<Game1, InitializeEventArgs> InitializeEvent { get; set; }\n public Action<Game1, DrawEventArgs> DrawEvent { get; set; }\n public Action<Game1, LoadContentEventArgs> LoadContentEvent { get; set; }\n}\n</code></pre>\n</blockquote>\n<hr />\n<h3>Proposed Solution</h3>\n<p>You should determine whether to use either events, a callback interface or a mixture of both.</p>\n<p>Let's assume you would like consumers to be able to subscribe to single events, and allow specific consumers to subscribe to all of them. The mixture of events and a callback interface could be implemented as follows.</p>\n<p>Create event arguments</p>\n<pre><code>public class MoveEventArgs : EventArgs { /* .. impl */ }\npublic class InitializeEventArgs : EventArgs { /* .. impl */ }\npublic class DrawEventArgs : EventArgs { /* .. impl */ }\npublic class LoadContentEventArgs : EventArgs { /* .. impl */ }\n</code></pre>\n<p>Create a callback interface that bundles handlers for all the relevant events.</p>\n<pre><code> public interface IGameListener\n {\n void OnMove(Game1 game, MoveEventArgs e);\n void OnInitialize(Game1 game, InitializeEventArgs e);\n void OnDraw(Game1 game, DrawEventArgs e);\n void OnLoadContent(Game1 game, LoadContentEventArgs e);\n }\n</code></pre>\n<p>As discussed, you may want to create an <a href=\"https://blogs.oracle.com/corejavatechtips/listeners-vs-adapters\" rel=\"nofollow noreferrer\">adapter</a>. This allows derived classes to decide which event handlers to override.</p>\n<pre><code>public abstract class GameAdapter : IGameListener\n{\n public virtual void OnMove(Game1 game, MoveEventArgs e) {}\n public virtual void OnInitialize(Game1 game, InitializeEventArgs e) {}\n public virtual void OnDraw(Game1 game, DrawEventArgs e) {}\n public virtual void OnLoadContent(Game1 game, LoadContentEventArgs e) {}\n}\n</code></pre>\n<p><code>Game1</code> uses events and allows for registration of specific listeners. If you don't like to 'pollute' the game with these actions, you could let a <a href=\"https://en.wikipedia.org/wiki/Mediator_pattern\" rel=\"nofollow noreferrer\">mediator</a> perform the registration of the callback interface. <em>Argument checks are omitted for brevity.</em></p>\n<pre><code> public class Game1\n {\n public event Action<Game1, MoveEventArgs> MoveEvent;\n public event Action<Game1, InitializeEventArgs> InitializeEvent;\n public event Action<Game1, DrawEventArgs> DrawEvent;\n public event Action<Game1, LoadContentEventArgs> LoadContentEvent;\n\n public void Register(IGameListener listener)\n {\n MoveEvent += listener.OnMove;\n InitializeEvent += listener.OnInitialize;\n DrawEvent += listener.OnDraw;\n LoadContentEvent += listener.OnLoadContent;\n }\n\n public void Unregister(IGameListener listener)\n {\n MoveEvent -= listener.OnMove;\n InitializeEvent -= listener.OnInitialize;\n DrawEvent -= listener.OnDraw;\n LoadContentEvent -= listener.OnLoadContent;\n }\n\n // other instance code ..\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T17:02:15.087",
"Id": "429606",
"Score": "0",
"body": "Your interface solution does for the most part solve my problem. The main piece of functionality missing is the ability to not have all the Events eg. if I want one class to have all but MoveEvent. Using your solution I would have to create an Interface for each combination as well as register methods for each new Interface."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T17:03:57.890",
"Id": "429607",
"Score": "1",
"body": "@Antony This is a famous problem. Java has built-in framework listeners and adapters to solve this for many of their API's. You could do the same in C#. https://www.javatpoint.com/java-adapter-classes"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T15:41:11.237",
"Id": "222029",
"ParentId": "221984",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "222029",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T00:28:26.057",
"Id": "221984",
"Score": "4",
"Tags": [
"c#",
"design-patterns",
"event-handling"
],
"Title": "How to group custom events"
} | 221984 |
<p>I have got a technical challenge from a company but they reject my code and I'm not sure how to do this challenge in a more efficient way so I'm here to get some guidance.</p>
<p>The Technical challenge was:</p>
<blockquote>
<p>Manage a list of products that have prices.</p>
<ul>
<li>Enable the administrator to set concrete prices (such as 10EUR) and discounts to prices either by a concrete amount (-1 EUR) or by
percentage (-10%).</li>
<li>Enable the administrator to group products together to form bundles (which is also a product) that have independent prices.</li>
<li>Enable customers to get the list of products and respective prices.</li>
<li>Enable customers to place an order for one or more products, and provide customers with the list of products and the total price.</li>
</ul>
</blockquote>
<p>I have used Symfony framework to build this API and I'm writing the company response here:</p>
<blockquote>
<ul>
<li><code>SingleProduct</code> and <code>BundleProduct</code> should be polymorphic.</li>
<li><code>ConcretePrice</code>, <code>DiscountedPriceByAmount</code>, <code>DiscountedPriceByPercentage</code> should be polymorphic.</li>
<li>The computation of the overall sum of prices for the order should make no assumption about how the individual price was calculated (fix
price, or discounted).</li>
<li>The response should provide a deep object structure (as opposed to a flat list) that preserves the semantics of the model and is suitable
for rendering.</li>
</ul>
</blockquote>
<p>/src/Entity/Product.php</p>
<pre><code><?php
// src/Entity/Product.php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity(repositoryClass="App\Repository\ProductRepository")
* @ORM\Table(name="products")
*/
class Product {
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @Assert\NotBlank()
* @ORM\Column(type="string", length=150)
*/
private $title;
/**
* @ORM\Column(type="text", length=150, nullable=true)
*/
private $slug;
/**
* @Assert\NotBlank()
* @ORM\Column(type="float", scale=2)
*/
private $price;
/**
* @ORM\Column(type="string", length=5)
*/
private $currency = '€';
/**
* @ORM\Column(type="string", length=3, options={"comment":"Yes, No"})
*/
private $isDiscount = 'No';
/**
* @ORM\Column(type="string", length=10, options={"comment":"Concrete amount (-1 EUR) or by Percentage (-10%)"}, nullable=true)
*/
private $discountType;
/**
* @ORM\Column(type="integer", length=5, options={"comment":"1 or 10"})
*/
private $discount = 0;
/**
* @ORM\Column(type="string", length=5, options={"comment":"No, Yes, if yes then save product ids in product bundle items"})
*/
private $isProductBundle = 'No';
/**
* @ORM\Column(type="text", length=150, nullable=true)
*/
private $sku;
/**
* @ORM\Column(type="string", length=15, options={"comment":"Active or Pending , only Active products will display to customers"})
*/
private $status = 'Active';
/**
* @ORM\Column(type="string", length=150, options={"comment":"Upload or Link of image"})
*/
private $imageType = 'Link';
/**
* @ORM\Column(type="text")
*/
private $image = 'https://via.placeholder.com/400x300.png';
/**
* @ORM\Column(type="text", nullable=true)
*/
private $description;
/**
* @ORM\Column(type="datetime", nullable=true)
*/
private $createdAt;
/**
* @ORM\Column(type="datetime", nullable=true)
*/
private $updatedAt;
//Getters and Setters
}
</code></pre>
<p>/src/Entity/ProductBundleItem.php</p>
<pre><code><?php
// src/Entity/ProductBundleItem.php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity(repositoryClass="App\Repository\ProductBundleItemRepository")
* @ORM\Table(name="product_bundle_items")
*/
class ProductBundleItem {
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="integer")
*/
private $productBundleId;
/**
* @ORM\Column(type="integer")
*/
private $productId;
//Getters and Setters
</code></pre>
<p>/src/Repository/ProductRepository.php</p>
<pre><code><?php
namespace App\Repository;
use App\Entity\Product;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Symfony\Bridge\Doctrine\RegistryInterface;
/**
* @method Product|null find($id, $lockMode = null, $lockVersion = null)
* @method Product|null findOneBy(array $criteria, array $orderBy = null)
* @method Product[] findAll()
* @method Product[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class ProductRepository extends ServiceEntityRepository
{
public function __construct(RegistryInterface $registry)
{
parent::__construct($registry, Product::class);
}
public function findAllQueryBuilder()
{
return $this->createQueryBuilder('products');
}
// /**
// * @return Product[] Returns an array of Product objects
// */
/*
public function findByExampleField($value)
{
return $this->createQueryBuilder('t')
->andWhere('t.exampleField = :val')
->setParameter('val', $value)
->orderBy('t.id', 'ASC')
->setMaxResults(10)
->getQuery()
->getResult()
;
}
*/
/*
public function findOneBySomeField($value): ?Product
{
return $this->createQueryBuilder('t')
->andWhere('t.exampleField = :val')
->setParameter('val', $value)
->getQuery()
->getOneOrNullResult()
;
}
*/
}
</code></pre>
<p>/src/Repository/ProductBundleItemRepository.php</p>
<pre><code><?php
namespace App\Repository;
use App\Entity\ProductBundleItem;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Symfony\Bridge\Doctrine\RegistryInterface;
/**
* @method ProductBundleItem|null find($id, $lockMode = null, $lockVersion = null)
* @method ProductBundleItem|null findOneBy(array $criteria, array $orderBy = null)
* @method ProductBundleItem[] findAll()
* @method ProductBundleItem[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class ProductBundleItemRepository extends ServiceEntityRepository
{
public function __construct(RegistryInterface $registry)
{
parent::__construct($registry, ProductBundleItem::class);
}
public function findByProductBundleIdJoinedToProduct($productBundleId)
{
return $this->createQueryBuilder('pbi')
->select('p.id','p.title', 'p.price', 'p.currency')
->leftJoin('App\Entity\Product', 'p', 'WITH', 'p.id = pbi.productId')
->where('pbi.productBundleId = :productBundleIdParam')
->setParameter('productBundleIdParam', $productBundleId)
->getQuery()
->getResult();
}
// /**
// * @return ProductBundleItem[] Returns an array of ProductBundleItem objects
// */
/*
public function findByExampleField($value)
{
return $this->createQueryBuilder('t')
->andWhere('t.exampleField = :val')
->setParameter('val', $value)
->orderBy('t.id', 'ASC')
->setMaxResults(10)
->getQuery()
->getResult()
;
}
*/
/*
public function findOneBySomeField($value): ?ProductBundleItem
{
return $this->createQueryBuilder('t')
->andWhere('t.exampleField = :val')
->setParameter('val', $value)
->getQuery()
->getOneOrNullResult()
;
}
*/
}
</code></pre>
<p>/src/Controller/Api/ProductController.php</p>
<pre><code><?php
// src/Controller/Api/ProductController.php
namespace App\Controller\Api;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Controller\AbstractFOSRestController;
use FOS\RestBundle\View\View;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Service\ProductService;
class ProductController extends AbstractFOSRestController
{
private $productService;
public function __construct(ProductService $productService){
$this->productService = $productService;
}
/**
* Retrieves a collection of Product resource
* @Rest\Get("/products")
*/
public function getProducts(Request $request): View
{
$params['page'] = $request->query->getInt('page', 1);
$params['limit'] = $request->query->getInt('limit', 10);
$products = $this->productService->getProducts($params);
return View::create($products, Response::HTTP_OK);
}
/**
* Retrieves a Product resource
* @Rest\Get("/products/{slug}")
*/
public function getProduct(Request $request, $slug): View
{
$product = $this->productService->getProduct($slug);
return View::create($product, Response::HTTP_OK);
}
/**
* Creates an Product resource
* @Rest\Post("/products")
* @param Request $request
* @return View
*/
public function addProduct(Request $request): View
{
$user = $this->getUser();
if(!in_array('ROLE_ADMIN',$user->getRoles())){
return View::create([], Response::HTTP_UNAUTHORIZED);
}
$params = json_decode($request->getContent(), true);
$product = $this->productService->addProduct($params);
return View::create($product, Response::HTTP_OK);
}
/**
* Creates an Product resource
* @Rest\Put("/products/{id}")
* @param Request $request
* @return View
*/
public function updateProduct(Request $request, $id): View
{
$user = $this->getUser();
if(!in_array('ROLE_ADMIN',$user->getRoles())){
return View::create([], Response::HTTP_UNAUTHORIZED);
}
$params = json_decode($request->getContent(), true);
$product = $this->productService->updateProduct($params, $id);
return View::create($product, Response::HTTP_OK);
}
/**
* Removes the Product resource
* @Rest\Delete("/products/{id}")
*/
public function deleteProduct($id): View
{
$user = $this->getUser();
if(!in_array('ROLE_ADMIN',$user->getRoles())){
return View::create([], Response::HTTP_UNAUTHORIZED);
}
$this->productService->deleteProduct($id);
return View::create([], Response::HTTP_NO_CONTENT);
}
}
</code></pre>
<p>/src/Controller/Api/ProductBundleController.php</p>
<pre><code><?php
// src/Controller/Api/ProductController.php
namespace App\Controller\Api;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Controller\AbstractFOSRestController;
use FOS\RestBundle\View\View;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use App\Service\ProductBundleService;
class ProductBundleController extends AbstractFOSRestController
{
private $productBundleService;
public function __construct(ProductBundleService $productBundleService){
$this->productBundleService = $productBundleService;
}
/**
* Retrieves a collection of Product bundle resource
* @Rest\Get("/products-not-bundles")
*/
public function getProductsIsNotBundles(): View
{
$products = $this->productBundleService->getProductsIsNotBundles();
return View::create($products, Response::HTTP_OK);
}
/**
* Retrieves a collection of Product bundle resource
* @Rest\Get("/product-bundles")
*/
public function getProductBundles(): View
{
$products = $this->productBundleService->getProducts();
return View::create($products, Response::HTTP_OK);
}
/**
* Retrieves a Product bundle resource
* @Rest\Get("/product-bundles/{id}")
*/
public function getProduct(Request $request, $id): View
{
$product = $this->productBundleService->getProduct($id);
return View::create($product, Response::HTTP_OK);
}
/**
* Creates an Product bundle resource
* @Rest\Post("/product-bundles")
* @param Request $request
* @return View
*/
public function addProduct(Request $request): View
{
$user = $this->getUser();
if(!in_array('ROLE_ADMIN',$user->getRoles())){
return View::create([], Response::HTTP_UNAUTHORIZED);
}
$params = json_decode($request->getContent(), true);
$product = $this->productBundleService->addProduct($params);
return View::create($product, Response::HTTP_OK);
}
/**
* Update an Product bundle resource
* @Rest\Put("/product-bundles/{id}")
* @param Request $request
* @return View
*/
public function updateProduct(Request $request, $id): View
{
$user = $this->getUser();
if(!in_array('ROLE_ADMIN',$user->getRoles())){
return View::create([], Response::HTTP_UNAUTHORIZED);
}
$params = json_decode($request->getContent(), true);
$product = $this->productBundleService->updateProduct($params, $id);
return View::create($product, Response::HTTP_OK);
}
/**
* Removes the Product bundle resource
* @Rest\Delete("/product-bundles/{id}")
*/
public function deleteProduct($id): View
{
$user = $this->getUser();
if(!in_array('ROLE_ADMIN',$user->getRoles())){
return View::create([], Response::HTTP_UNAUTHORIZED);
}
$this->productBundleService->deleteProduct($id);
return View::create([], Response::HTTP_NO_CONTENT);
}
}
</code></pre>
<p>/src/Service/ProductService.php</p>
<pre><code><?php
namespace App\Service;
use Doctrine\ORM\EntityManagerInterface;
use Pagerfanta\Adapter\DoctrineORMAdapter;
use Pagerfanta\Pagerfanta;
use App\Repository\ProductRepository;
use App\Utils\Slugger;
use App\Entity\Product;
final class ProductService
{
/**
* @var ProductRepository
*/
private $productRepository;
private $slugger;
private $em;
public function __construct(ProductRepository $productRepository, Slugger $slugger, EntityManagerInterface $em){
$this->productRepository = $productRepository;
$this->slugger = $slugger;
$this->em = $em;
}
public function getProducts($params): ?array
{
$qb = $this->productRepository->findAllQueryBuilder();
$adapter = new DoctrineORMAdapter($qb);
$pagerfanta = new Pagerfanta($adapter);
$pagerfanta->setMaxPerPage($params['limit']);
$pagerfanta->setCurrentPage($params['page']);
$products = [];
foreach ($pagerfanta->getCurrentPageResults() as $result) {
$products[] = $result;
}
$response =[
'total' => $pagerfanta->getNbResults(),
'count' => count($products),
'products' => $products,
];
return $response;
}
public function getProduct($slug){
#Find by id
//return $this->productRepository->find($id);
#Or find by slug
return $this->productRepository->findBy(['slug'=>$slug]);
}
public function addProduct($params){
$product = new Product();
foreach($params as $key=>$val){
$property = 'set'.strtoupper($key);
if(property_exists('App\Entity\Product',$key)){
$product->$property($val);
}
}
$slug = $this->slugger->slugify($product->getTitle());
$product->setSlug($slug);
$product->setCreatedAt(date("Y-m-d H:i:s"));
$product->setUpdatedAt(date("Y-m-d H:i:s"));
$this->em->persist($product);
$this->em->flush();
return $product;
}
public function updateProduct($params, $id){
if(empty($id))
return [];
$product = $this->productRepository->find($id);
if(!$product){
return [];
}
foreach($params as $key=>$val){
if($key=='id')
continue;
$property = 'set'.ucfirst($key);
if(property_exists('App\Entity\Product',$key)){
$product->$property($val);
}
}
$slug = $this->slugger->slugify($product->getTitle());
$product->setSlug($slug);
$product->setUpdatedAt(date("Y-m-d H:i:s"));
$this->em->persist($product);
$this->em->flush();
return $product;
}
public function deleteProduct($id){
$product = $this->productRepository->find($id);
if($product){
$this->em->remove($product);
$this->em->flush();
}
}
}
</code></pre>
<p>/src/Service/ProductBundleService.php</p>
<pre><code><?php
namespace App\Service;
use Doctrine\ORM\EntityManagerInterface;
use App\Repository\ProductRepository;
use App\Repository\ProductBundleItemRepository;
use App\Utils\Slugger;
use App\Entity\Product;
use App\Entity\ProductBundleItem;
final class ProductBundleService
{
/**
* @var ProductRepository
*/
private $productRepository;
private $productBundleItemRepository;
private $slugger;
private $em;
public function __construct(ProductRepository $productRepository, Slugger $slugger, EntityManagerInterface $em, ProductBundleItemRepository $productBundleItemRepository){
$this->productRepository = $productRepository;
$this->productBundleItemRepository = $productBundleItemRepository;
$this->slugger = $slugger;
$this->em = $em;
}
public function getProductsIsNotBundles(): ?array
{
return $this->productRepository->findBy(['status'=>'Active', 'isProductBundle'=>'No']);
}
public function getProducts(): ?array
{
return $this->productRepository->findBy(['isProductBundle'=>'Yes'],['id'=>'DESC']);
}
public function getProduct($id){
#Find by id
//return $this->productRepository->find($id);
#Or find by slug
$product = $this->productRepository->findBy(['id'=>$id,'isProductBundle'=>'Yes']);
$bunleItems = $this->productBundleItemRepository->findByProductBundleIdJoinedToProduct($product[0]->getId());
$returnData['product'] = $product;
$returnData['bunleItems'] = $bunleItems;
return $returnData;
}
public function addProduct($params){
$product = new Product();
foreach($params as $key=>$val){
$property = 'set'.strtoupper($key);
if(property_exists('App\Entity\Product',$key)){
$product->$property($val);
}
}
$product->setIsProductBundle("Yes");
$slug = $this->slugger->slugify($product->getTitle());
$product->setSlug($slug);
$product->setCreatedAt(date("Y-m-d H:i:s"));
$product->setUpdatedAt(date("Y-m-d H:i:s"));
$this->em->persist($product);
$this->em->flush();
$productsArr = $params['productsArr'];
if(count($productsArr)>0){
foreach($productsArr as $productId){
$productBundleItem = new ProductBundleItem();
$productBundleItem->setProductBundleId($product->getId());
$productBundleItem->setProductId($productId);
$this->em->persist($productBundleItem);
$this->em->flush();
}
}
$returnData['product'] = $product;
$returnData['productsArr'] = $productsArr;
return $returnData;
}
public function updateProduct($params, $id){
if(empty($id))
return [];
$product = $this->productRepository->find($id);
if(!$product){
return [];
}
foreach($params as $key=>$val){
if($key=='id')
continue;
$property = 'set'.ucfirst($key);
if(property_exists('App\Entity\Product',$key)){
$product->$property($val);
}
}
$product->setIsProductBundle("Yes");
$slug = $this->slugger->slugify($product->getTitle());
$product->setSlug($slug);
$product->setUpdatedAt(date("Y-m-d H:i:s"));
$this->em->persist($product);
$this->em->flush();
$productsArr = $params['productsArr'];
if(count($productsArr)>0){
foreach($productsArr as $productId){
$isExist = $this->productBundleItemRepository->findBy(['productId'=>$productId]);
if(!$isExist){
$productBundleItem = new ProductBundleItem();
$productBundleItem->setProductBundleId($product->getId());
$productBundleItem->setProductId($productId);
$this->em->persist($productBundleItem);
$this->em->flush();
}
}
}
$returnData['product'] = $product;
$returnData['productsArr'] = $productsArr;
return $returnData;
}
public function deleteProduct($id){
$product = $this->productRepository->find($id);
if($product){
$productBundleItems = $this->productBundleItemRepository->findBy(['productBundleId'=>$product->getId()]);
$this->em->remove($product);
foreach($productBundleItems as $item){
$this->em->remove($item);
}
$this->em->flush();
}
}
}
</code></pre>
<p>The whole code can be view <a href="https://github.com/shahzadthathal/symfony4-shopping-web-rest-app" rel="noreferrer">here</a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-12T16:48:01.060",
"Id": "429900",
"Score": "0",
"body": "Welcome to Code Review! You stated: \"_`I'm writing the company response here`_\". Does that mean that is the response from the company about the code you submitted? If so, I would expect to see those class names like `BundleProduct` in your code and/or repo but I don't..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-12T16:59:13.870",
"Id": "429902",
"Score": "1",
"body": "Yes, that is the response from the company where I submitted code, I have used ```isProductBundle``` column in Product entity but I have not made a separate class."
}
] | [
{
"body": "<p>I'll try to cover the response part.</p>\n\n<blockquote>\n <p><code>SingleProduct</code> and <code>BundleProduct</code> should be polymorphic.\n <code>ConcretePrice</code>, <code>DiscountedPriceByAmount</code>, <code>DiscountedPriceByPercentage</code> should be polymorphic.</p>\n</blockquote>\n\n<p>I think they are talking about the following:</p>\n\n<ul>\n<li>you need to have a table of products</li>\n<li>and a table of prices\n\n<ul>\n<li>this is not exactly a requirement, but I guess this would be a very logical step because at some point you might need to handle price history, different pricelists due to geography, currencies, payment methods, etc.; but again: this does not seem to be a requirement at this point</li>\n</ul></li>\n<li>you need to have a several entities per table, i.e. one \"physical\" record upon retrieval could be resolved into one of several classes (specifics are here: <a href=\"https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/inheritance-mapping.html\" rel=\"noreferrer\">https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/inheritance-mapping.html</a>)\n\n<ul>\n<li>e.g. there is your entity <code>Product</code>, which should be an abstract class with mostly protected members, and some public methods that make sense for any kind of product</li>\n<li>then there should be <code>SingleProduct</code> inherited from Product, which exposes additional members specific to this kind of product, and maybe override (or provide implementation) to some members of <code>Product</code></li>\n<li>and <code>BundleProduct</code> too, inherits from <code>Product</code></li>\n<li>as for what exactly must be polymorphic, I guess things like <code>getPrice()</code> -- implementation would be different for <code>SingleProduct</code> and <code>BundleProduct</code></li>\n<li>how exactly to do that -- the link above talks about several ways, and their procs and cons; I'd go with \"Single Table Inheritance\" for the sake of simplicity</li>\n<li>and of course you need one-to-many/many-to-one relations, e.g. '<code>BundleProduct</code> has many <code>ProductBundleItem</code>'; currently you're manipulating with IDs directly, but that's not how Doctrine encourages you to do things (see example below, where I talk about REST response)</li>\n</ul></li>\n</ul>\n\n<p>So, to reiterate:</p>\n\n<ul>\n<li>currently you have one <code>Product</code> class with all price/discount/bundling functionality built-in</li>\n<li>you've been asked to make a nice hierarchy of classes (<code>SingleProduct</code>, <code>BundleProduct</code>, etc.) and make them do one thing, but do it good (think less <code>if</code> statements, more class diversity)</li>\n<li>this does not imply you should put all functionality there -- a service is a good place to have your business logic; but functionality related to data itself -- how to interpret price, discounts, bundles -- that's a task for some code inside entities</li>\n</ul>\n\n<blockquote>\n <p>The computation of the overall sum of prices for the order should make no assumption about how the individual price was calculated (fix price, or discounted).</p>\n</blockquote>\n\n<p>This one is a natural continuation of previous point.</p>\n\n<p>Currently your <code>OrderService</code> has pretty complex code that calculates individual product price. But that's not its concern! If at some place it has a reference to <code>Product</code> -- that is, base product class -- it should not check if this is a concrete product, or bundle, if discount is in effect. It should just be able to do this:</p>\n\n<pre><code>$product->getPrice();\n</code></pre>\n\n<p>And your class hierarchy should take care about specifics. Re how to achieve that, see above.</p>\n\n<blockquote>\n <p>The response should provide a deep object structure (as opposed to a flat list) that preserves the semantics of the model and is suitable for rendering.</p>\n</blockquote>\n\n<p>I believe what they talk about is how your API response looks when is compared to your DB structure: it should be really close, basically 1-to-1.</p>\n\n<p>E.g. your method <code>\\App\\Service\\OrderService::getOrder</code> which prepares data for <code>/customer/orders/single/{id}</code> route:</p>\n\n<ul>\n<li>route could be <code>/customer/orders/{id}</code> -- the fact that it is 'single' is already obvious, as API user does <code>GET</code> with URL containing ID.\n\n<ul>\n<li>doing <code>PUT</code> to the same URL would do update of order</li>\n<li>doing <code>POST</code> to <code>/customer/orders</code> (instead of <code>/customers/orders/save</code>) would create a new one</li>\n<li>etc., this is basically any REST API around -- URL and HTTP method clearly defines what kind of operation that particular API call assumes</li>\n</ul></li>\n<li>result of <code>getOrder()</code> is some custom array with items like 'order' and 'orderItems', but it could be literal representation of your object hierarchy (your hierarchy is rather vague at this moment due to lacking relations between entities, so, I'm just guessing here):</li>\n</ul>\n\n<pre><code>GET /customer/orders/id\n{\n timestamp: '...',\n address: {\n billing: { city: ..., country: ...},\n shipping: { city: ..., country: ...}\n },\n items: [\n product: {\n name: '...',\n price: ...\n },\n quantity: ...\n ],\n total: ...\n}\n</code></pre>\n\n<p>As you can see, this sample JSON contains implicit (from Doctrine point of view, anyway) relations from your code:</p>\n\n<ul>\n<li>order points to several order items</li>\n<li>order item points to one product</li>\n<li>order item also has quantity field</li>\n<li>order has total field</li>\n<li>order points to one or more addresses of different kind</li>\n</ul>\n\n<p>So, resulting structure should be rich in data, deep (I could get value of order.address.billing.city), and exactly reflect your data structures (\"physical\" DB records, then your polymorphic entities).</p>\n\n<p>I hope that helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-12T19:26:01.963",
"Id": "429916",
"Score": "2",
"body": "You have put quite some effort in this review. Perhaps adding in code snippets here and there would make it easier to visualise your recommendations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T05:56:41.413",
"Id": "456186",
"Score": "0",
"body": "Thanks for your great answer"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-12T16:58:39.073",
"Id": "222169",
"ParentId": "221991",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T07:46:36.407",
"Id": "221991",
"Score": "7",
"Tags": [
"php",
"interview-questions",
"api",
"rest",
"symfony3"
],
"Title": "Build a set of REST interfaces using Symfony framework"
} | 221991 |
<p>I have a Python code that deals with parsing xml-feeds of footwear online stores. I want to let the code look more professional for the sake of optimal reusability for other programmers.</p>
<p>It includes more script files, but I'm more interested in utils.py</p>
<pre><code>import re
from .setup_logger import *
from .metadata import reference_categories, ref_cat_list
def get_ref_text(offer_element, anchor):
linked_tuple = (offer_element[key].lower() for key in anchor if key in offer_element.keys()
and type(offer_element[key]) is str)
return ''.join(linked_tuple)
def asos_size(meta_size, offer_element):
meta_size = meta_size.replace(',', '.')
sizetype = re.search(r'[a-zA-Zа-яА-Я]+', meta_size)
int_size = re.search(r'\d+\.?\d+?', meta_size)
fract_size = re.search(r' \d{1}/\d{1}', meta_size)
if sizetype is None or int_size is None:
return False
str_size = int_size.group(0)
sizetype = sizetype.group(0)
size = float(str_size) if '.5' in str_size else int(str_size)
offer_element['sizetype'] = sizetype.lower()
offer_element['size'] = size
if fract_size is not None:
offer_element['size'] = size + 0.5
offer_element['size'] = str(offer_element['size'])
def yoox_size(offer_element):
if offer_element['sizetype'] != 'eu':
del offer_element['size']
return False
else:
size_l = []
for meta_size in offer_element['size'].split(','):
int_size = re.search(r'(\d+)\.?(\d+)?', meta_size)
frac_size = re.search(r'(⅔)|(⅓)', meta_size)
if int_size is None:
continue
elif frac_size is None:
res_size = int_size.group(0)
size_l.append(res_size)
elif frac_size is not None:
res_size = int_size.group(0) + '.5'
size_l.append(res_size)
offer_element['size'] = size_l
def add_size(xml_element, offer_element, shop, unit_attr_name='unit'):
if type(xml_element.text) is not str:
return False
if re.findall(r'[/-]', xml_element.text) or xml_element.text.isalpha():
return False
# exceptions for size
# and size type switch
if shop == 'nike':
offer_element['sizetype'] = 'us'
offer_element['size'] = xml_element.text
return True
if shop == 'asos':
asos_size(xml_element.text, offer_element)
return True
if shop == 'adidas':
sizetype = xml_element.attrib[unit_attr_name].lower()
eur = re.search('eur', sizetype)
ru = re.search('ru', sizetype)
uk = re.search('uk', sizetype)
if eur is not None:
offer_element['sizetype'] = eur.group(0)
elif ru is not None:
offer_element['sizetype'] = ru.group(0)
elif uk is not None:
offer_element['sizetype'] = uk.group(0)
offer_element['size'] = xml_element.text
return True
if unit_attr_name in xml_element.keys():
offer_element['sizetype'] = xml_element.attrib[unit_attr_name].lower()
offer_element['size'] = xml_element.text
if shop == 'yoox':
yoox_size(offer_element)
if shop in ('vans', 'lamoda', 'aupontrouge', 'kupivip'):
offer_element['size'] = offer_element['size'].replace(',', '.')
# exceptions for puma and slamdunk
def add_gender(shop, offer_element):
exception_list = ['puma', 'slamdunk']
if shop not in exception_list:
return False
men = ('мужские', 'мужская', 'мужской', 'мужчин')
women = ('женские', 'женская', 'женский', 'женщин')
unisex = ('унисекс', 'unisex')
kid = ('детские', 'детская', 'детский', 'детей', 'мальчиков', 'девочек')
anchor = ('description', 'category', 'title')
ref_text = get_ref_text(offer_element, anchor)
for word in kid:
if word in ref_text:
offer_element['sex'] = 'kid'
return True
for word in women:
if word in ref_text:
offer_element['sex'] = 'women'
return True
for word in men:
if word in ref_text:
offer_element['sex'] = 'men'
return True
for word in unisex:
if word in ref_text:
offer_element['sex'] = 'unisex'
return True
offer_element['sex'] = 'men'
# revert categories
def add_categories(categories_dict, offer_element):
if 'category' in offer_element.keys() and offer_element['category'] is not None \
and offer_element['category'] in categories_dict.keys():
offer_element['category'] = reference_categories[categories_dict[offer_element['category']]]
else:
del offer_element['category']
return False
anchor = ('description', 'category', 'title', 'model')
ref_text = get_ref_text(offer_element, anchor)
for ref in ref_cat_list:
if ref in ref_text:
offer_element['category'] = ref
return True
# getting model out of description
def add_model(shop, offer_element):
def from_title(offer_vendor, offer_title, offer):
vendor_len = len(offer_vendor)
start_pos = title.index(offer_vendor)
model_index = start_pos + vendor_len
result_model = offer_title[model_index:]
offer['model'] = result_model.strip()
if 'title' not in offer_element.keys() or offer_element['title'] is None:
return False
if shop == 'nike':
title = offer_element['title']
for vendor in ('Nike', 'Jordan'):
if vendor in title:
from_title(vendor, title, offer_element)
return True
result = re.sub(r'[а-яА-я]', '', title)
offer_element['model'] = result.strip()
if shop in ('adidas', 'puma', 'aizel'):
title = offer_element['title']
result = re.sub(r'[а-яА-я]', '', title)
offer_element['model'] = result.strip()
# exceptions for offer
def add_exceptions(shop, offer_element):
if shop == 'nike' and 'picture' in offer_element.keys() and offer_element['picture'] is not None:
offer_element['picture'] = offer_element['picture'].replace('_PREM', '')[:-1] + 'A'
if shop == 'sportpoint' and 'title' in offer_element.keys():
offer_element['description'] = offer_element['title']
if shop == 'puma' and 'description' in offer_element.keys():
desc = offer_element['description']
if type(desc) is str:
offer_element['description'] = re.sub(r'[&amp;,lt;,li,&amp;,gt;,strong,\\li,\\ul,]', ' ', desc)
# exceptions for tag
def add_tag_exception(shop, xml_element, offer_element):
if shop == 'lamoda' and xml_element.tag == 'model' and xml_element.text is not None:
offer_element['model'] = xml_element.text
if shop == 'asos' and xml_element.tag == 'model' and xml_element.text is not None:
result = re.sub(r'[а-яА-я]', '', xml_element.text)
offer_element['model'] = result.strip()
</code></pre>
<p>and the main class Feed.py</p>
<pre><code>import re
import datetime
import xml.etree.ElementTree as Etree
from .resources.setup_logger import *
from pytz import timezone
from .resources.links import urls
from .resources.metadata import categories, tags, size_type_dict, gender_dict
from .resources.utils import *
from os import remove, rename, listdir, mkdir
from os.path import isfile, isdir, getsize, join, abspath
from urllib import request
from math import ceil
class Feed(object):
"""Works with data feeds for importing to site.
Converts object to a Feed object for working with
data to be imported to site"""
downloads = abspath('downloads')
def __init__(self, shop, partner='admitad', _type='.xml'):
self.shop = shop
self.url = urls[self.shop]
self.partner = partner
self.filtered = False
self.type = _type
self.file_name = self.shop + self.type
self.folder = join(self.downloads, self.partner)
self.previous_file_name = 'previous_{}'.format(self.file_name)
self.path = join(self.downloads, self.partner, self.file_name)
self.previous_path = join(self.downloads, self.partner, self.previous_file_name)
if not isdir(self.folder):
mkdir(self.folder)
self.shoe_categories = categories[shop]
self.replace_tags = tags[shop]
def __eq__(self, other):
"""Overloaded the equation operator checks if
the feed file self is equal to the other one"""
return getsize(self.path) == getsize(other.path)
def downloaded(self):
"""Checks if feed (not the previous one) is downloaded"""
return isfile(self.path)
def previously_downloaded(self):
"""Checks if previous_feed is downloaded"""
return isfile(self.previous_path)
def archive(self):
"""Moves previous feed to archive"""
rename(self.path, self.previous_path)
logger.info('Archived {0} to {1}'.format(self.shop.upper(), self.previous_path))
def remove_feed(self, previous=False):
"""Deletes certain feed from a given path (in self.path) previous
(boolean) key sets what exact feed has to be removed (old or new)"""
if self.downloaded() and not previous:
remove(self.path)
logger.info('Removed {} xml feed'.format(self.shop.upper()))
if self.previously_downloaded() and previous:
remove(self.previous_path)
logger.info('Removed {} archive xml feed'.format(self.shop.upper()))
def download_feed(self):
"""Downloads feed from a given url (in self.url), deleting previous
feed if exists, renames previous feed to an archived feed"""
try:
file_data = request.urlopen(self.url)
except ValueError:
logger.info('ERROR: Unknown url\nNot reachable site')
return None
else:
if self.previously_downloaded() and self.downloaded():
self.remove_feed(previous=True)
if self.downloaded():
self.archive()
logger.info('Downloading {} xml feed...'.format(self.shop.upper()))
data_to_write = file_data.read()
with open(self.path, 'wb') as f:
f.write(data_to_write)
logger.info('Saved {0} xml feed to {1}\n'.format(self.shop.upper(), self.path))
def to_list(self):
"""Converting feed to a raw list of dicts with tags as
keys and tags as content. Returns list as self.list"""
shoe_categories = self.shoe_categories
replace_tags = self.replace_tags
necessary_tags = list(replace_tags.values())
necessary_tags.remove('oldprice')
# data tags
category_tag = 'category'
offer_tag = 'offer'
raw_category_tag = 'categoryId'
param_tag = 'param'
category_id = 'id'
raw_time_tag = 'modified_time'
time_tag = 'time'
size_tag = 'size'
sizetype_tag = 'sizetype'
sex_tag = 'sex'
price_tag = 'price'
oldprice_tag = 'oldprice'
discount_tag = 'discount'
xml = self.path
if self.type == '.xml':
if not isfile(xml):
xml = self.previous_path
logger.warning('Parsing archived {} feed...'.format(self.shop.upper()))
else:
logger.info('Parsing {} feed...'.format(self.shop.upper()))
categories_dict = {}
offers = []
raw_size_tag = [k for k, v in replace_tags.items() if v == size_tag][0]
for event, elem in Etree.iterparse(xml, events=('start',)):
# parsing and filtering categories
if elem.tag == category_tag and elem.text is not None and \
elem.text.lower() in shoe_categories and \
elem.attrib[category_id] is not None:
categories_dict[elem.attrib[category_id]] = elem.text.lower()
# parsing offers
if elem.tag == offer_tag and elem.find(raw_category_tag) is not None and \
elem.find(raw_category_tag).text in categories_dict.keys():
offer = {}
for el in elem.getchildren():
# size & sizetype
if (el.tag == param_tag and el.attrib[el.items()[0][0]].lower() == raw_size_tag) \
or el.tag.lower() == size_tag:
add_size(el, offer, self.shop)
continue
# timestamp
if el.tag == raw_time_tag and el.text is not None:
mod_time = datetime.fromtimestamp(int(el.text)).strftime('%Y-%m-%d %H:%M:%S')
offer[time_tag] = mod_time
continue
# other params (gender, size, etc)
if el.tag == param_tag:
key = el.attrib[el.items()[0][0]]
else:
key = el.tag
if key.lower() in replace_tags.keys() and key.lower() not in offer.keys():
key = replace_tags[key.lower()]
offer[key] = el.text
# exceptional tag added
add_tag_exception(self.shop, el, offer)
# discount
if price_tag in offer.keys() and oldprice_tag in offer.keys() \
and offer[price_tag] is not None and offer[oldprice_tag] is not None:
old = float(offer[oldprice_tag])
new = float(offer[price_tag])
offer[discount_tag] = str(ceil(100 * ((old - new) / old)))
# exceptions (gender info, nike pic)
add_gender(self.shop, offer)
add_exceptions(self.shop, offer)
add_categories(categories_dict, offer)
add_model(self.shop, offer)
if sizetype_tag in offer.keys() and offer[sizetype_tag] in size_type_dict.keys():
offer[sizetype_tag] = size_type_dict[offer[sizetype_tag]]
else:
continue
if sex_tag in offer.keys() and offer[sex_tag] is not None \
and offer[sex_tag].lower() in gender_dict.keys():
offer[sex_tag] = gender_dict[offer[sex_tag].lower()]
else:
continue
# check for necessary tags
if set(necessary_tags).issubset(offer.keys()):
if type(offer[size_tag]) is list:
for offer_size in offer[size_tag]:
sub_offer = offer
sub_offer[size_tag] = offer_size
offers.append(sub_offer)
else:
offers.append(offer)
elem.clear()
logger.info('Parsing {0} done\nIn total ({0} offers): {1} items'.format(self.shop.upper(), len(offers)))
return offers
</code></pre>
<p>To use this parser first I run 'python3 upload.py'</p>
<pre><code>import logging
from lib.Feed import Feed
from lib.resources.links import shops
for shop in ['slamdunk', 'newbalance', 'lamoda', 'asos', 'adidas', 'yoox', 'puma',
'aupontrouge', 'aizel', 'nike', 'sportpoint', 'streetball', 'vans']:
Feed(shop).download_feed()
</code></pre>
<p>and then parser in test.py</p>
<pre><code>from lib.Feed import Feed
from lib.resources.setup_logger import *
i = 0
shops = ['slamdunk', 'newbalance', 'lamoda', 'asos', 'yoox', 'adidas', 'puma',
'aupontrouge', 'aizel', 'nike', 'sportpoint', 'streetball', 'vans']
for shop in shops:
offers = Feed(shop).to_list()
i += len(offers)
logger.info('total items (offers): {}'.format(i))
</code></pre>
<p>Please help me to do this code better, you can just simply give me an advise or show what can be optimized.
Thanks a lot!</p>
| [] | [
{
"body": "<p>Some suggestions:</p>\n\n<ul>\n<li>I don't know whether this is community standard, but I <strong>never <code>import *</code> from anything.</strong> It's a quick way to get a naming collision, and I prefer being explicit about where my IDE has to look to find the implementation of something. An IDE will let you write out the name of the thing from another file and tell it to add the import statement <em>for you,</em> right at the correctly ordered place in your file.</li>\n<li><strong>Naming</strong> is super duper important for maintainability. Ideally any piece of code should be understandable without knowing much about the context. Finding a balance between long, easily understood names and needless verbosity is an art, but code is read many, many times more than it is written, IDEs will help you complete names, and abbrs are t. b. of readab. <code>ref</code>, for example, could mean any of probably a dozen words, and many of those words have multiple meanings. Expanding the word is very likely going to make the code easier to read. <code>gender</code> and <code>sex</code> are also used interchangeably, which may be fine in casual conversation, but it also makes code harder to read.</li>\n<li><strong>Regular expressions</strong> can also make code really hard to read in no time at all. Once you've got some working code using a regular expression I would recommend converting it into using things like <a href=\"https://docs.python.org/3/library/stdtypes.html#str.split\" rel=\"nofollow noreferrer\"><code>str.split()</code></a>, <a href=\"https://docs.python.org/3/library/stdtypes.html#str.replace\" rel=\"nofollow noreferrer\"><code>str.replace()</code></a> and the like which are by comparison super easy to read.</li>\n<li><strong>Type hinting</strong> and MyPy with a strict configuration can make this code much easier to read. It might also highlight common problems such as treating convertible types as equal when they really aren't. Things like <code>type(xml_element.text) is not str</code>, for example, are a big no-no in duck typed languages like Python. </li>\n<li>You have a bunch of <strong>magic strings</strong> in your code. They would probably work better as constants.</li>\n<li>There are a lot of <strong>duplicate code.</strong> Pulling these bits into methods or classes should make the code easier to navigate.</li>\n<li><strong>Using <code>abspath</code> is unnecessary</strong> unless your script actually changes working directory at some point.</li>\n<li><code>Feed</code> is a bit of a monster class. It looks like it contains basically every piece of important code in this application, which is a pretty serious anti-pattern.</li>\n<li><strong><code>__eq__</code> is meant to compare object <em>equality.</em></strong> Overriding it to compare the size of two things is seriously harmful to maintainability.</li>\n<li><strong>Conditionals in <code>__init__</code></strong> is an anti-pattern - the constructor is meant to unconditionally populate the fields of an object before doing anything non-trivial.</li>\n<li><strong>Modifying external state in <code>__init__</code></strong> (<code>mkdir(self.folder)</code>) is a serious anti-pattern. It makes the code essentially impossible to test, and would be very surprising to someone reusing this code.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T10:51:50.983",
"Id": "429566",
"Score": "0",
"body": "wow, that's what I exactly needed to know! thanks a lot! got a ton of work to do hah."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T11:07:53.990",
"Id": "429567",
"Score": "0",
"body": "you said that Feed contains every piece of important code (as I thought, that's the point of the class), so do I have to move some of Feed functions to another script files or how to do it better?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T11:09:59.700",
"Id": "429568",
"Score": "0",
"body": "The point of a class is to encapsulate functionality and data which belongs together. `Feed` does too many things to consider them all closely related: downloading, conversion, archiving, deletion, XML parsing etc."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T10:26:48.147",
"Id": "222005",
"ParentId": "221993",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "222005",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T08:01:43.453",
"Id": "221993",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"xml",
"lxml"
],
"Title": "Python xml-parsing script"
} | 221993 |
<p>So I have a list of files which names are something like this</p>
<pre><code>long_boring_filename_del_1.tex
long_boring_filename_del_2.tex
long_boring_filename_del_3.sty
long_boring_filename_del_4.tex
</code></pre>
<p>I want to cycle through these filenames using some mapping defined in vim. Meaning if I have <code>long_boring_filename_del_2.tex</code> open and hit the mapping it should take me to the next file <code>long_boring_filename_del_3.sty</code>. It should also loop, meaning <code>long_boring_filename_del_4.tex</code> should take me back to <code>long_boring_filename_del_4.tex</code>. </p>
<p><em>In addition I want to be able to cycle thorugh the files in both directions.</em></p>
<p>After obtaining a bit of <a href="https://vi.stackexchange.com/questions/20259/cycle-between-filenames">help over at vi and vim</a> I was able to come up with the following solution (which works).</p>
<pre><code>function! s:next_del()
" do nothing if current filename doesn't match "
if @% !~# 'del-\v[1234]\.'
return
endif
" open next file "
let fnameA = substitute(@%, '\v[1234]\ze\.', '\=submatch(0)%4+1', '')
if filereadable(fnameA)
exec 'echo'
exec 'e ' . fnameA
else
" if the .tex file does not exist check if the .sty versions does "
let fnameB = substitute(fnameA, '\.tex', '\.sty', '')
if filereadable(fnameB)
exec 'e ' . fnameB
else
" if the above fails, check if changing sty to tex works "
let fnameB = substitute(fnameA, '\.sty', '\.tex', '')
if filereadable(fnameB)
exec 'e ' . fnameB
endif
endif
endif
endfunction
" Same as s:next_del() except this cycles in the opposite direction "
function! s:prev_del()
" do nothing if current filename doesn't match "
if @% !~# 'del-\v[1234]\.'
return
endif
" open previous file "
let fnameA = substitute(@%, '\v[1234]\ze\.', '\=submatch(0)-1', '')
let fnameA = substitute(fnameA, '\v[0]\ze\.', '\=submatch(0)+4', '')
if filereadable(fnameA)
exec 'e ' . fnameA
else
" if the .tex file does not exist check if the .sty versions does "
let fnameB = substitute(fnameA, '\.tex', '\.sty', '')
if filereadable(fnameB)
exec 'e ' . fnameB
else
" if the above fails, check if changing sty to tex works "
let fnameB = substitute(fnameA, '\.sty', '\.tex', '')
if filereadable(fnameB)
exec 'e ' . fnameB
endif
endif
endif
endfunction
nnoremap <silent> <localleader>w :call <sid>next_del()<CR>
nnoremap <silent> <localleader>q :call <sid>prev_del()<CR>
</code></pre>
<p>While it work I would love to get some pointers on how to improve the code as I am very much a beginner when it come to <code>vimscript</code>. Here are the major points in the code that needs improvement:</p>
<ul>
<li>Can the two functions <code>s:next_del()</code> and <code>s:prev_del()</code> be combined into one? </li>
<li><p>My method of cycling backwards is very barbaric. </p>
<pre><code>let fnameA = substitute(@%, '\v[1234]\ze\.', '\=submatch(0)-1', '')
let fnameA = substitute(fnameA, '\v[0]\ze\.', '\=submatch(0)+4', '')
</code></pre>
<p>I did it in this fashion because apparently you can't separate the
leading \ and = , as otherwise it's a pure string. I would like to get some pointers on how to improve it. </p></li>
<li><p>Lastly my method of "checking" whether I have a <code>sty</code> file or <code>tex</code> file is strange at best. I do not really check, just change <code>sty</code> to <code>tex</code> and see if it works. I tried to get some <code>regex</code> going by using <code>(tex|sty)</code> but for some reason vimscript did not accept it. I would like to learn a better method of alternating between the <code>sty</code> and <code>tex</code> files.</p></li>
</ul>
| [] | [
{
"body": "<p>Your code can be improved in many aspects, so it is easier to write my own solution rather to rewrite your.</p>\n\n<p><strong>Differences from your:</strong></p>\n\n<ol>\n<li>I suggest to use <code>glob()</code> function to find all files, which are matching to a pattern.</li>\n<li>Singular <code>Move(move_direction)</code> function is enough, a duplication is not needed.</li>\n<li>Not only new files are opened, but switching between already opened buffers are supported.</li>\n</ol>\n\n<hr>\n\n<pre><code>function! s:MyCompare(i1, i2)\n let l:f = str2nr(matchstr(a:i1, '[0-9]\\+'))\n let l:s = str2nr(matchstr(a:i2, '[0-9]\\+'))\n return l:f == l:s ? 0 : l:f > l:s ? 1 : -1\nendfunc\n\nfunction! s:Move(step)\n let l:current_filename = bufname('%')\n let l:common_part = matchstr(l:current_filename, '[^0-9]*')\n\n \"\" sort() is needed for numerical order\n let l:matched_file_list = sort(glob(l:common_part . '*', 0, 1), 's:MyCompare') \n\n let l:list_size = len(l:matched_file_list)\n let l:cur_idx = index(l:matched_file_list, l:current_filename)\n\n let l:next_idx = (l:cur_idx + a:step) % l:list_size\n let l:next_buf_name = l:matched_file_list[l:next_idx]\n\n if !bufloaded(l:next_buf_name)\n execute 'e' l:next_buf_name\n endif\n\n execute 'buffer' l:next_buf_name\nendfunction\n\ncommand! Fwrd call s:Move(1)\ncommand! Bwrd call s:Move(-1)\n\nnoremap <Leader>c :Fwrd<CR>\nnoremap <Leader>d :Bwrd<CR>\n</code></pre>\n\n<p><strong>Directory content</strong></p>\n\n<pre><code>ls -1\n\nlong_boring_filename_del_101.tex\nlong_boring_filename_del_1.tex\nlong_boring_filename_del_202.tex\nlong_boring_filename_del_2.tex\nlong_boring_filename_del_3.sty\nlong_boring_filename_del_4.tex\nlong_boring_filename_del_5.tex\n</code></pre>\n\n<p><strong>Demonstration</strong></p>\n\n<p><kbd>,</kbd> is a Leader key.</p>\n\n<p><a href=\"https://i.stack.imgur.com/epXYp.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/epXYp.gif\" alt=\"enter image description here\"></a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-05T13:07:23.177",
"Id": "238427",
"ParentId": "221997",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T08:35:59.800",
"Id": "221997",
"Score": "4",
"Tags": [
"beginner",
"linux",
"vimscript"
],
"Title": "Cycle through filenames in vim"
} | 221997 |
<p>I've just started practicing Functional Programming in Scala in some days. This is the code I used to perform KS-test on a random number generator.</p>
<pre><code>class RNG {
def next(): Double;
}
import scala.math.sqrt;
object main {
val length: Int = 100000;
def main(args: Array[String]) {
// generate 100000 random numbers
var seed: Array[Long] = Array.range(1, 7).map(x => x.toLong);
var gen: RNG = new RNG(seed);
var data: Array[Double] = (new Array[Double](length)).map {case (x) => gen.next()};
// sort data
val sorted = data.sortWith((x, y) => x < y);
// perform ks test
val baseline: Array[Int] = Array.range(0, length);
val baselinemin: Array[Double] = baseline.map {case (x) => x.toDouble/length}
val baselinemax: Array[Double] = baseline.map {case (x) => (1+x.toDouble)/length}
val diffmin = (sorted.zip(baselinemin)).map {case (x, y) => x - y};
val diffmax = (sorted.zip(baselinemax)).map {case (x, y) => y - x};
val max1 = diffmin.max;
val max2 = diffmax.max;
val d = if (max1 > max2) max1 else max2;
println("D\t" + d);
val dbase = 2/sqrt(length);
println("D base\t" + dbase);
}
}
</code></pre>
<p>There is a little weird thing that in line </p>
<pre><code>var data: Array[Double] = (new Array[Double](length)).map {case (x) => gen.next()};
</code></pre>
<p>Question:</p>
<ul>
<li>if I remove new, the program returns a wrong answer.</li>
<li>Is there any way to make this code looks more professional?</li>
</ul>
<p>Thanks!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T09:46:18.100",
"Id": "429562",
"Score": "2",
"body": "Please be more specific in what you are looking for in a review. What do you mean with \"looks more professional?\". Also, do you understand what is happening with that `map` function? https://codereview.stackexchange.com/help/on-topic"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T11:44:00.133",
"Id": "429569",
"Score": "2",
"body": "This isn't a question: \"*if I remove new, the program returns a wrong answer.*\" That's a statement (and probably means you shouldn't remove `new`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-12T03:41:50.740",
"Id": "429805",
"Score": "0",
"body": "@TobySpeight I think it should be some kind of error comes out due to undefined behavior, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-12T03:43:00.663",
"Id": "429806",
"Score": "0",
"body": "@dfhwze I'm practicing Scala, It should be some kinda standard."
}
] | [
{
"body": "<ul>\n<li>The code, as posted, does not compile.</li>\n<li>All the semicolons <code>;</code> can be removed. You almost never see them in idiomatic Scala.</li>\n<li>Unnecessary use of <code>var</code>. Use <code>val</code>.</li>\n<li>Replace <code>Array.range(1, 7).map(x => x.toLong)</code> with <code>Array.iterate(1L, 7)(_+1)</code>.</li>\n<li>Replace <code>case (x)</code> with underscore <code>_</code> when <code>x</code> is unused.</li>\n<li>Replace <code>case (x) => x</code> with underscore <code>_</code> when <code>x</code> is used immediately and once.</li>\n<li><code>data.sortWith((x, y) => x < y)</code> same thing as <code>data.sorted</code>.</li>\n<li>Variable <code>data</code> not needed: <code>val sorted : Array[Double] = Array.fill(length)(gen.next()).sorted</code></li>\n<li>Unnecessary parentheses when defining <code>diffmin</code> and <code>diffmax</code>.</li>\n<li>Variables <code>max1</code> and <code>max2</code> not needed: <code>val d = diffmin.max max diffmax.max</code></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-12T05:45:56.560",
"Id": "429810",
"Score": "0",
"body": "@jwvh I would refrain from answering on code that does not compile."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-11T09:41:31.887",
"Id": "222070",
"ParentId": "222000",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "222070",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T09:17:34.210",
"Id": "222000",
"Score": "-1",
"Tags": [
"beginner",
"functional-programming",
"scala"
],
"Title": "Perform KS-test on Random Number Generator"
} | 222000 |
<p>I'm creating a new website, so I am thinking about how to protect my email address and phone number against crawlers, I actually mean <a href="https://en.wikipedia.org/wiki/Email_address_harvesting" rel="nofollow noreferrer">email harvesters</a> (most of which I suppose don't have JavaScript enabled, but I don't have any proof of it). What I do now is definitely <a href="https://en.wikipedia.org/wiki/Security_through_obscurity" rel="nofollow noreferrer">security by obscurity</a> or <a href="https://en.wikipedia.org/wiki/Obfuscation" rel="nofollow noreferrer">obfuscation</a> (I might be confusing the two terms), as <strong>I want the email address to be <em>normally visible</em> and <em>clickable</em> by the user</strong>.</p>
<p>I started with resurrecting my 10+ years old code and editing it a little. The basics remain the same as 10+ years ago when I first coded this principle.</p>
<p>My question for Code Review SE - as I already posted <strong>Is this a valid option?</strong> in Security SE <a href="https://security.stackexchange.com/q/211626/82570">question</a> - is rather clear. Primarily, I am interested in a review of this piece of code:</p>
<hr>
<h2>HTML part</h2>
<pre class="lang-html prettyprint-override"><code><span id="m_link">test [a.t] example [d.o.t] com</span>
<span id="t_link">+444 444 6[eight]6 6[eight][eight]</span>
</code></pre>
<h2>JavaScript part</h2>
<pre class="lang-js prettyprint-override"><code>function fix_m_link()
{
var item1 = '@'; var item2 = '.'; var m_clear_text = 'test' + item1 + 'example' + item2 + 'com';
document.getElementById('m_link').innerHTML = '<a href="mai' + 'lto:' + m_clear_text + '">' + m_clear_text + '</a>';
}
function fix_t_link()
{
var item8 = '8'; var t_with_spaces = '444 6' + item8 + '6 6' + item8 + item8; var t = t_with_spaces.replace(/\s+/g, '');
document.getElementById('t_link').innerHTML = '<a href="tel:+444' + t + '">' + '+444 ' + t_with_spaces + '</a>';
}
</code></pre>
<p>These functions I then call in the <code>body</code>'s <code>onload</code>.</p>
| [] | [
{
"body": "<p>First of all, ES2015+ onwards have <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals\" rel=\"noreferrer\">template literals</a> forw easier interpolation of string and data. For instance:</p>\n\n<pre><code>function fix_m_link(){\n var item1 = '@'\n var item2 = '.'\n var m_clear_text = `test${item1}example${item2}com`\n document.getElementById('m_link').innerHTML = `<a href=\"mailto:${m_clear_text}\">${m_clear_text}</a>`\n}\n</code></pre>\n\n<p>Also, JavaScript uses camel case for naming. So you might want to change <code>fix_m_link</code> and <code>m_clear_text</code>.</p>\n\n<p>Putting code in one line makes it hard to read. If you have a build step, let a minifier do this. If the code is very short (like in your question), the extra kilobytes saved from omitted newlines is not worth making the code unreadable. Write code for humans to read.</p>\n\n<p>Now if you <em>really</em> want to obscure your email, use a contact form instead. Some CMSes support this out of the box. And if your site is static, there are third-party services that allow you to embed a contact form. Most of them also support captchas, which will deter automated form submissions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T13:27:06.660",
"Id": "222022",
"ParentId": "222003",
"Score": "5"
}
},
{
"body": "<h2><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals\" rel=\"nofollow noreferrer\">Template literals</a></h2>\n\n<p>Thanks to <a href=\"https://codereview.stackexchange.com/a/222022/104270\">Joseph's answer</a> about <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals\" rel=\"nofollow noreferrer\">template literals</a>, much appreciated, and implemented.</p>\n\n<hr>\n\n<h2><a href=\"https://developer.mozilla.org/en-US/docs/Glossary/IIFE\" rel=\"nofollow noreferrer\">Immediately Invoked Function Expression</a></h2>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Glossary/IIFE\" rel=\"nofollow noreferrer\">Immediately Invoked Function Expression</a> is used here to bypass my <a href=\"https://content-security-policy.com/\" rel=\"nofollow noreferrer\">Content Security Policy</a>, as <strong>no inline scripts</strong> - like I had in the <code>body</code>'s <code>onload</code> - <strong>are allowed</strong> now.</p>\n\n<hr>\n\n<h2>Readability - goodbye long lines</h2>\n\n<p>It's imperative for new script readers (and the owner too) to have a clean-looking in front of their eyes for the code to be easily maintained. Thus, an enhancement has been implemented in the form of line breaks.</p>\n\n<hr>\n\n<h2><a href=\"https://en.wikipedia.org/wiki/Obfuscation\" rel=\"nofollow noreferrer\">Obfuscation</a> (like <code>mail:</code> + <code>tel:</code> gone, hexa <code>char</code>s, etc.)</h2>\n\n<p>The script contains no texts as whole for crawlers to <code>grep</code> for now.</p>\n\n<p>Not only the <code>mail:</code> and <code>tel:</code> are gone, split in pieces; more importantly, some key characters have been encoded into hexadecimal codes and are being converted on-the-fly.</p>\n\n<hr>\n\n<h2><a href=\"https://en.wikipedia.org/wiki/Camel_case\" rel=\"nofollow noreferrer\">camelCase</a></h2>\n\n<p>Regarding the camelCase, it is established in JavaScript, so I implemented it into the script.</p>\n\n<hr>\n\n<h2>Re-written code</h2>\n\n<p>I was now able to tweak my script as follows:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>( function fixEmlLink ()\n{\n\n var itemX = String.fromCharCode(parseInt('0x40'));\n var itemY = String.fromCharCode(parseInt('0x2e'));\n\n var emlClearText = `info${itemX}example${itemY}com`;\n\n document.getElementById('eml_link').innerHTML =\n '<a href=\"mai' + `lto:${emlClearText}\">${emlClearText}</a>`;\n\n} () );\n\n\n( function fixPhnLink ()\n{\n\n var itemX = String.fromCharCode(parseInt('0x37'));\n var itemY = String.fromCharCode(parseInt('0x30'));\n\n var phnWithSpace = `${itemX}${itemX}8 8${itemY}8 8${itemY}${itemY}`;\n var phnClearText = phnWithSpace.replace(/\\s+/g, '');\n\n document.getElementById('phn_link').innerHTML =\n '<a href=\"te' + `l:+88${itemY}${phnClearText}\">+88${itemY} ${phnWithSpace}</a>`;\n\n} () );\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-15T05:40:52.577",
"Id": "234058",
"ParentId": "222003",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "222022",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T09:39:22.530",
"Id": "222003",
"Score": "4",
"Tags": [
"javascript",
"html",
"reinventing-the-wheel"
],
"Title": "Obfuscation of email and phone using JavaScript"
} | 222003 |
<p>I have written some code that prints out all unique pre-ordered binary search trees containing numbers <code>1</code> to <code>n</code>. </p>
<p>It is not an especially efficient solution and has a time complexity (I believe) of O(n!) but hopefully it is fairly easy to understand. </p>
<p>As I am using <code>sets</code> the output is not sorted.</p>
<pre><code>"""Module constructs and prints unique BST."""
import itertools
class Node():
"""Builds a BST"""
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def add_node(self, value):
"""Adds new elemenet to binary search tree."""
if self.value:
if value > self.value:
if not self.right:
self.right = Node(value)
else:
self.right.add_node(value)
else:
if not self.left:
self.left = Node(value)
else:
self.left.add_node(value)
def print_tree(self):
"""Return the BST as a string"""
string_tree = ""
if self.value:
string_tree += (str(self.value) + " ")
if self.left:
string_tree += self.left.print_tree()
if self.right:
string_tree += self.right.print_tree()
return string_tree
def build_BST(permutation):
"""Builds a BST from a list of numbers"""
if permutation:
tree = Node(permutation[0])
for i in range(1, len(permutation)):
tree.add_node(permutation[i])
string_tree = tree.print_tree()
return string_tree
return False
def build_trees(size_tree):
"""Build BST containing numbers in range 1 to n"""
if not isinstance(size_tree, int):
print("Please enter an integer")
return
if size_tree <= 0:
print("Function only prints trees with numbers >= 1")
return
permutations = list(itertools.permutations([i for i in range(1, size_tree + 1)],
size_tree))
set_solutions = set()
for permutation in permutations:
string_tree = build_BST(permutation)
set_solutions.add(string_tree)
for solution in set_solutions:
print(solution)
print(f"==========\n{len(set_solutions)} solutions.")
if __name__ == "__main__":
build_trees(4)
</code></pre>
| [] | [
{
"body": "<p>Some suggestions:</p>\n\n<ul>\n<li>You can use <a href=\"https://docs.python.org/3/library/sys.html#sys.argv\" rel=\"nofollow noreferrer\"><code>sys.argv</code></a> or <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\"><code>argparse</code></a> to pass the size on the command line. The latter can check the type and range for you, and print an appropriate error message and usage string. You can <a href=\"https://stackoverflow.com/a/14117511/96588\">specify a validator function in the <code>type</code> argument to check for non-trivial values</a>.</li>\n<li><code>print_tree</code> does not print the tree, it returns a string representation of it. That is the job of <code>__str__</code>, a special internal method you can override to define the string representation of a class.</li>\n<li>\"node\" in <code>add_node</code> is redundant.</li>\n<li>Running this code through <code>black</code> will improve the formatting slightly. <code>flake8</code> and <code>mypy</code> (with a strict configuration) can help make the code more idiomatic.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T17:29:40.617",
"Id": "429608",
"Score": "0",
"body": "I can see how ```argparse``` can throw a non ```int``` error. But I can't work out how to throw a neat out of range error (the ```choices``` argument is very ugly)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T11:01:21.167",
"Id": "222009",
"ParentId": "222006",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "222009",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T10:32:47.687",
"Id": "222006",
"Score": "2",
"Tags": [
"python",
"tree"
],
"Title": "Unique binary search trees"
} | 222006 |
<p>Intro -> I have to convert an excel file, which comes usually in this way:</p>
<p><a href="https://i.stack.imgur.com/AWTLl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AWTLl.png" alt="enter image description here"></a></p>
<p>to a Json file that must looks like this: </p>
<pre><code>"DE": {
"Title":"Title_DE",
"Subtitle":"Subtitle_DE",
"Title_2":"Title_2_DE",
"Subtitle_2":"Subtitle_2_DE"
}
"GR": {
"Title":"Title_GR",
"Subtitle":"Subtitle_GR",
"Title_2":"Title_2_GR",
"Subtitle_2":"Subtitle_2_GR"
}
"EN": {
"Title":"Title_EN",
"Subtitle":"Subtitle_EN",
"Title_2":"Title_2_EN",
"Subtitle_2":"Subtitle_2_EN"
}
</code></pre>
<p>What I've done -> I have used this node module <a href="https://www.npmjs.com/package/xlsx" rel="nofollow noreferrer">xlsx</a> to parse the excel file. The code currently works but something in my mind tells me that was not the best way to do it or at least there was a clearest or a smartest way.</p>
<pre><code>const XLSX = require('xlsx');
const fs = require('fs');
let workbook = XLSX.readFile('./src/xls/test.xlsx');
let sheet_name_list = workbook.SheetNames; //--> sheet names
let isocodes = [];
let labels = [];
let copy = [];
let obj = {};
let j = 0;
sheet_name_list.map(sheet => { //--> sheet names loop
let worksheet = workbook.Sheets[sheet];
for (index in worksheet) {
let idCol = index.substring(1, 3);
let idRow = index.substring(0, 1);
if (idCol === "1") {
isocodes.push((worksheet[index].v).trim()); //--> isocodes
}
if (idRow === "A") {
labels.push((worksheet[index].v).trim()); //--> labels
}
if (idRow != "A" && idCol != "1") {
copy.push(worksheet[index].v); //--> copy
}
}
});
isocodes.shift(); //--> delete undefined
labels.shift();
copy.shift();
isocodes.map(iso => { //--> create object to convert
obj[iso] = {};
for (let i = 0; i < labels.length; i++) {
obj[iso][labels[i]] = copy[(i * isocodes.length) + j];
}
j++;
});
//--> write json files in their folder
fs.writeFile('src/lang/desktop.json', JSON.stringify(obj).replace(/\\n|\\r/g, ''), 'utf8', console.log("desktop json file created"));
fs.writeFile('src/lang/mobile.json', JSON.stringify(obj).replace(/\\n|\\r/g, ''), 'utf8', console.log("mobile json file created"));
</code></pre>
<p>Please share your thoughts!!! </p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T10:56:01.090",
"Id": "222008",
"Score": "4",
"Tags": [
"javascript",
"excel",
"node.js",
"json"
],
"Title": "Node JS | From Excel to Json"
} | 222008 |
<p>I'm trying to make a timed background service in .NET Core (<a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-2.2&tabs=visual-studio" rel="nofollow noreferrer">I found this approach in Microsoft Docs</a>), that every 15 seconds it gets data from the database (1000 rows max, if something exists) then sends it to the API using a <code>foreach</code> loop. If a response status code is not 200 or 202, I change thr status column by id in the database.</p>
<p>How can I make this code faster? Should I use another approach?</p>
<pre><code>using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace FDProcessor
{
class FDSenderService : IHostedService, IDisposable
{
private Timer timer;
private HttpClient httpClient = new HttpClient
{
BaseAddress = new Uri("https://example.com")
};
public Task StartAsync(CancellationToken cancellationToken)
{
Console.WriteLine("Service is started.");
timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(15));
return Task.CompletedTask;
}
private async void DoWork(object state)
{
var data = DbManager.GetTransactions();
foreach (var r in data)
{
StringContent jsonRequestBody = new StringContent(JsonConvert.SerializeObject(r));
var response = await httpClient.PostAsync("/example/path", jsonRequestBody);
if (!response.IsSuccessStatusCode)
{
Console.WriteLine("Bad request. Status returned.");
Console.WriteLine(await response.Content.ReadAsStringAsync());
DbManager.UpdateTransaction(null, r.TrnID);
}
}
}
public Task StopAsync(CancellationToken cancellationToken)
{
Console.WriteLine("Stopping!");
timer?.Change(Timeout.Infinite, 0);
return Task.CompletedTask;
}
public void Dispose()
{
timer.Dispose();
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-11T05:54:10.410",
"Id": "429660",
"Score": "0",
"body": "Is DoWork considered Atomic? e.g. when calling `StopAsync`, does the current execution of DoWork need to finish?"
}
] | [
{
"body": "<p>If <code>Dowork</code> takes longer than 15 seconds to execute, it will be called a second time. Will this cause issues? One way around that would be to disable the timer while you're doing work, then start it up again when the work is done, or add an appropriately typed and thread safe \"busy\" member to the class so that you can skip starting any new work if work is currently being done.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-11T09:29:44.527",
"Id": "429671",
"Score": "0",
"body": "Sorry, I just realized that I didn't mentioned it before. But every 15 seconds `DbManager` will get new set of data(next 1000 rows). So it doesn't matter if `DoWork` finished job or not. I think, that multiple threads can work in the same time and that's exactly what I need."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-11T04:12:33.977",
"Id": "222058",
"ParentId": "222012",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "222058",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T11:23:00.103",
"Id": "222012",
"Score": "2",
"Tags": [
"c#",
"performance",
"scheduled-tasks",
".net-core"
],
"Title": "Periodically sending data from database to an API"
} | 222012 |
<p>I'm writing a project management system focused on forking and web-of-trusting-code, which is a fancy way of saying "take someone's code, do whatever you want with it, and see if others agree with you".</p>
<p>I am trying to use classes to organize the code: an "instance" class, a "project" class, and a "repo" class. An instance contains projects and some extra metadata, a project contains repos and some extra metadata, and finally a repo is a git repo, basically. I'm not sure I'm following best practices, however.</p>
<p>In my <code>Project</code> class, for example, I'm doing some mangling with the <code>project_commit</code> for some degree of compatibility with older versions, so that users can freely downgrade, and I'm not sure I should be doing it like this.</p>
<p>Here are my 3 classes:</p>
<pre><code>class Repo:
def __init__(self, dbconn, project, url, branch, list_metadata=False):
self.url = url
self.branch = branch
self.project_commit = project.commit
if not branch:
self.branchname = "gan" + hashlib.sha256(url.encode("utf-8")).hexdigest()
self.head = "HEAD"
else:
self.branchname = "gan" + hmac.new(branch.encode("utf-8"), url.encode("utf-8"), "sha256").hexdigest()
self.head = "refs/heads/" + branch
try:
self.hash = subprocess.check_output(["git", "-C", cache_home, "show", self.branchname, "-s", "--format=%H", "--"], stderr=subprocess.DEVNULL).decode("utf-8").strip()
except subprocess.CalledProcessError:
self.hash = None
self.message = None
if list_metadata:
try:
self.fetch_metadata()
except GitError:
pass
def fetch_metadata(self):
try:
self.message = subprocess.check_output(["git", "-C", cache_home, "show", self.branchname, "-s", "--format=%B", "--"], stderr=subprocess.DEVNULL).decode("utf-8", "replace")
except subprocess.CalledProcessError as e:
raise GitError from e
def update(self): # FIXME?
try:
subprocess.check_output(["git", "-C", cache_home, "fetch", "-q", self.url, "+" + self.head + ":" + self.branchname], stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
# This may error for various reasons, but some are important: dead links, etc
click.echo(e.output, err=True)
return None
pre_hash = self.hash
post_hash = subprocess.check_output(["git", "-C", cache_home, "show", self.branchname, "-s", "--format=%H", "--"], stderr=subprocess.DEVNULL).decode("utf-8").strip()
self.hash = post_hash
if not pre_hash:
pre_hash = post_hash
try:
count = int(subprocess.check_output(["git", "-C", cache_home, "rev-list", "--count", pre_hash + ".." + post_hash, "--"]).decode("utf-8").strip())
except subprocess.CalledProcessError:
count = 0 # force-pushed
try:
subprocess.check_call(["git", "-C", cache_home, "merge-base", "--is-ancestor", self.project_commit, self.branchname], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
self.fetch_metadata()
return count, post_hash, self.message
except (subprocess.CalledProcessError, GitError) as e:
click.echo(e, err=True)
return None
class Project:
def __init__(self, dbconn, ganarchy, project_commit, list_repos=False):
self.commit = project_commit
if ganarchy.project_commit == project_commit:
project_commit = None
self.refresh_metadata()
if list_repos:
repos = []
with dbconn:
for (e, url, branch) in dbconn.execute('''SELECT "max"("e"), "url", "branch" FROM (SELECT "max"("T1"."entry") "e", "T1"."url", "T1"."branch" FROM "repo_history" "T1"
WHERE (SELECT "active" FROM "repos" "T2" WHERE "url" = "T1"."url" AND "branch" IS "T1"."branch" AND "project" IS ?1)
GROUP BY "T1"."url", "T1"."branch"
UNION
SELECT null, "T3"."url", "T3"."branch" FROM "repos" "T3" WHERE "active" AND "project" IS ?1)
GROUP BY "url" ORDER BY "e"''', (project_commit,)):
repos.append(Repo(dbconn, self, url, branch))
self.repos = repos
else:
self.repos = None
def refresh_metadata(self):
try:
project = subprocess.check_output(["git", "-C", cache_home, "show", self.commit, "-s", "--format=%B", "--"], stderr=subprocess.DEVNULL).decode("utf-8", "replace")
project_title, project_desc = (lambda x: x.groups() if x is not None else ('', None))(re.fullmatch('^\\[Project\\]\s+(.+?)(?:\n\n(.+))?$', project, flags=re.ASCII|re.DOTALL|re.IGNORECASE))
if not project_title.strip():
project_title, project_desc = ("Error parsing project commit",)*2
if project_desc:
project_desc = project_desc.strip()
self.commit_body = project
self.title = project_title
self.description = project_desc
except subprocess.CalledProcessError:
self.commit_body = None
self.title = None
self.description = None
def update(self):
# TODO
self.refresh_metadata()
class GAnarchy:
def __init__(self, dbconn, list_projects=False):
with dbconn:
# TODO
#(project_commit, base_url, title) = dbconn.execute('''SELECT "git_commit", "base_url", "title" FROM "config"''').fetchone()
(project_commit, base_url) = dbconn.execute('''SELECT "git_commit", "base_url" FROM "config"''').fetchone()
title = None
self.project_commit = project_commit
self.base_url = base_url
if not base_url:
pass ## TODO
if not title:
from urllib.parse import urlparse
title = "GAnarchy on " + urlparse(base_url).hostname
self.title = title
if list_projects:
projects = []
with dbconn:
for (project,) in dbconn.execute('''SELECT DISTINCT "project" FROM "repos" '''): # FIXME? *maybe* sort by activity in the future
if project == None:
project = self.project_commit
projects.append(Project(dbconn, ganarchy, project))
projects.sort(key=lambda project: project.title)
self.projects = projects
else:
self.projects = None
</code></pre>
<p>Here's the rest of my code: <a href="https://cybre.tech/SoniEx2/ganarchy/src/commit/4bd53221bb86c7fefe6b8294b7576486a3d8eb44/ganarchy.py" rel="nofollow noreferrer">https://cybre.tech/SoniEx2/ganarchy/src/commit/4bd53221bb86c7fefe6b8294b7576486a3d8eb44/ganarchy.py</a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T19:41:44.467",
"Id": "429630",
"Score": "0",
"body": "Be sure to include all relevant parts of your code that you want to have reviewed with the question. That includes imports and other referenced classes you have written yourself."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T11:30:29.413",
"Id": "222013",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"git"
],
"Title": "Project Management System focused on forking and web-of-trusting-code"
} | 222013 |
<p>Can someone tell me if this code is safe? Can be sql-injected or something else hacked? Code get some rows from db and show in pages with pagination... if i can improve let me know and show me how, thanks.</p>
<pre><code>$conn = new PDO('mysql:host=localhost;dbname=admin_admin', 'admin_admin', 'password');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$num_rows = $conn->query('SELECT COUNT(*) FROM a_topics')->fetchColumn();
$pages = new Paginator($num_rows,25,array(25,50,100,250,'All'));
$stmt = $conn->prepare('SELECT a_topics.pid, a_topics.title, a_topics.forum_id, b_forums.id, b_forums.name
FROM a_topics INNER JOIN b_forums ON a_topics.forum_id = b_forums.id
ORDER BY a_topics.pid DESC LIMIT :start,:end');
$stmt->bindParam(':start', $pages->limit_start, PDO::PARAM_INT);
$stmt->bindParam(':end', $pages->limit_end, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll();
echo $pages->display_jump_menu().$pages->display_items_per_page();
echo $pages->display_pages();
foreach($result as $row) {
echo "$row[0] - $row[1] - $row[2]";
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
</code></pre>
| [] | [
{
"body": "<p>This code is <strong>safe</strong> from the SQL injection standpoint but it is likely <strong>prone to XSS</strong> because of the untreated output, and also to possibly leak the sensitive information due to the error message unconditionally spat out. </p>\n\n<p>Regarding other improvements I would suggest a <a href=\"https://phpdelusions.net/pdo_examples/connect_to_mysql\" rel=\"nofollow noreferrer\">more robust connection code</a> and to avoid bindParam calls thanks to <a href=\"https://phpdelusions.net/pdo#limit\" rel=\"nofollow noreferrer\">disabled emulation mode</a>. </p>\n\n<p>The rewritten code would be </p>\n\n<pre><code>include 'pdo.php';\n$num_rows = $conn->query('SELECT COUNT(*) FROM a_topics')->fetchColumn(); \n$pages = new Paginator($num_rows,25,array(25,50,100,250,'All'));\n$stmt = $conn->prepare('SELECT a_topics.pid, a_topics.title, a_topics.forum_id, b_forums.id, b_forums.name \n FROM a_topics INNER JOIN b_forums ON a_topics.forum_id = b_forums.id\n ORDER BY a_topics.pid DESC LIMIT :start,:end');\n$stmt->execute(['start' => $pages->limit_start, 'end' => $pages->limit_end]);\n$result = $stmt->fetchAll();\n\necho $pages->display_jump_menu().$pages->display_items_per_page();\necho $pages->display_pages();\nforeach($result as $row) {\n echo htmlspecialchars($row[0]),\n \" - \", \n htmlspecialchars($row[1]),\n \" - \", \n htmlspecialchars($row[2])\";\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-11T08:07:12.180",
"Id": "429665",
"Score": "0",
"body": "I undestand thank you. One more question and i'm done, what if i use --> if ($_GET[\"id\"] == \"$row[0]\" { echo \"page1\"; } <-- inside foreach, is safe?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T13:04:29.183",
"Id": "222019",
"ParentId": "222015",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "222019",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T12:00:35.977",
"Id": "222015",
"Score": "1",
"Tags": [
"php",
"sql",
"mysql",
"pdo",
"pagination"
],
"Title": "Displaying a paginated list of forum topics using PHP PDO"
} | 222015 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.