body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I've made this program here (~240 lines) in which the user has to match their RGB Panel(right) with a randomized color on the left. It's a pretty fun program, and I suggest you try it out! It's fully runnable as is.</p>
<p>But a lot of the code seems repetitive and I was wondering how it could be condensed and made any more efficient if possible. Any other tips would be greatly appreciated. This is my first java program in a few years so I may have broken some unwritten rules.</p>
<p>My biggest concern with this program is the repetitiveness of the <code>JButtons</code> and the functions which they run. There are 6 buttons, one that adds red, one that subtracts red, one that adds green, one that subtracts green, one that adds blue, and one that subtracts blue. The functionality is very similar because they all either increase or decrease the color by 15, so I was wondering if there was a way to condense them all into just one function. Thanks!</p>
<p>I added some comments to help explain what's going on</p>
<pre><code>package guessColor;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class GuessColor extends JFrame {
private static final long serialVersionUID = 1L;
Font font = new Font("Times New Roman", Font.BOLD, 30);
static Random rand = new Random();
static int randRed = (rand.nextInt(17)+1)*15; //randomized red green and blue values, multiples of 15
static int randGrn = (rand.nextInt(17)+1)*15;
static int randBlu = (rand.nextInt(17)+1)*15;
static int userRed = 0;
static int userGrn = 0;
static int userBlu = 0;
Color randColor = new Color(randRed, randGrn, randBlu);
static Color userColor = new Color(userRed, userGrn, userBlu);
Dimension d = new Dimension(500, 500); //color panel size
Dimension b = new Dimension(50,50); //button size
public GuessColor() {
initGUI();
System.out.println("SOLUTION: " + randRed + " " + randGrn + " " + randBlu); // This is just to show what the RGB values are so you can easily solve
setTitle("Match the color!");
pack();
setLocationRelativeTo(null);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private void initGUI() { //sets up the frame and functionality of UI
JLabel title = new JLabel("Match The Color!", JLabel.CENTER);
title.setFont(font);
title.setBackground(Color.BLACK);
title.setForeground(Color.WHITE);
title.setOpaque(true);
add(title, BorderLayout.NORTH);
JPanel center = new JPanel();
center.setBackground(Color.CYAN);
add(center, BorderLayout.CENTER);
JPanel randPan = new JPanel(); //random color panel
randPan.setBackground(randColor);
randPan.setPreferredSize(d);
center.add(randPan, BorderLayout.EAST);
JPanel userPan = new JPanel(); //adjustable color panel
userPan.setBackground(userColor);
userPan.setPreferredSize(d);
center.add(userPan, BorderLayout.WEST);
/**BUTTONS**/
JPanel butPan = new JPanel();
add(butPan, BorderLayout.SOUTH);
JButton addRed = new JButton("+");
addRed.setBackground(Color.RED);
addRed.setPreferredSize(b);
addRed.setFocusPainted(false);
addRed.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
increaseRed();
userPan.setBackground(userColor);
repaint();
check();
}
});
butPan.add(addRed);
JButton subRed = new JButton("-");
subRed.setBackground(Color.RED);
subRed.setPreferredSize(b);
subRed.setFocusPainted(false);
subRed.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
decreaseRed();
userPan.setBackground(userColor);
repaint();
check();
}
});
butPan.add(subRed);
JButton addGrn = new JButton("+");
addGrn.setBackground(Color.GREEN);
addGrn.setPreferredSize(b);
addGrn.setFocusPainted(false);
addGrn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
increaseGrn();
userPan.setBackground(userColor);
repaint();
check();
}
});
butPan.add(addGrn);
JButton subGrn = new JButton("-");
subGrn.setBackground(Color.GREEN);
subGrn.setPreferredSize(b);
subGrn.setFocusPainted(false);
subGrn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
decreaseGrn();
userPan.setBackground(userColor);
repaint();
check();
}
});
butPan.add(subGrn);
JButton addBlu = new JButton("+");
addBlu.setBackground(Color.BLUE);
addBlu.setPreferredSize(b);
addBlu.setFocusPainted(false);
addBlu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
increaseBlu();
userPan.setBackground(userColor);
repaint();
check();
}
});
butPan.add(addBlu);
JButton subBlu = new JButton("-");
subBlu.setBackground(Color.BLUE);
subBlu.setPreferredSize(b);
subBlu.setFocusPainted(false);
subBlu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
decreaseBlu();
userPan.setBackground(userColor);
repaint();
check();
}
});
butPan.add(subBlu);
}
//function names say it all...
private static void increaseRed() {
if (userRed < 255) {
userRed += 15;
userColor = new Color(userRed, userGrn, userBlu);
}
}
private static void increaseGrn() {
if (userGrn < 255) {
userGrn += 15;
userColor = new Color(userRed, userGrn, userBlu);
}
}
private static void increaseBlu() {
if (userBlu < 255) {
userBlu += 15;
userColor = new Color(userRed, userGrn, userBlu);
}
}
private static void decreaseRed() {
if (userRed > 0) {
userRed -= 15;
userColor = new Color(userRed, userGrn, userBlu);
}
}
private static void decreaseGrn() {
if (userGrn > 0) {
userGrn -= 15;
userColor = new Color(userRed, userGrn, userBlu);
}
}
private static void decreaseBlu() {
if (userBlu > 0) {
userBlu -= 15;
userColor = new Color(userRed, userGrn, userBlu);
}
}
//checks if the color panels are the same and displays winning message if they are
private static void check() {
if (userRed == randRed && userGrn == randGrn && userBlu == randBlu) {
int choose = JOptionPane.showConfirmDialog(null, "You win! Play again?");
if(choose == JOptionPane.YES_OPTION) {
reset();
} else if(choose == JOptionPane.NO_OPTION) {
System.exit(0);
}
}
}
//resets game for when user wins and wants to play again
private static void reset() {
randRed = (rand.nextInt(17)+1)*15;
randGrn = (rand.nextInt(17)+1)*15;
randBlu = (rand.nextInt(17)+1)*15;
userRed = 0;
userGrn = 0;
userBlu = 0;
userColor = new Color(userRed, userGrn, userBlu);
new GuessColor();
}
//main method
public static void main(String[] args) {
try {
String laf = UIManager.getCrossPlatformLookAndFeelClassName();
UIManager.setLookAndFeel(laf);
}
catch (Exception e) {}
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new GuessColor();
}
});
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T07:44:20.620",
"Id": "494710",
"Score": "0",
"body": "no black possible?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T08:06:26.550",
"Id": "494715",
"Score": "0",
"body": "@HagenvonEitzen what do you mean?"
}
] |
[
{
"body": "<p>Most of what I would change at the first pass is about correctly defining and limiting the scope of your objects to make it easier to read and think about the code. (I would change more too, but I just wanted to offer you feedback in this area for now)</p>\n<p>You can skip the whole <code>initGui()</code> thing and just define the top level items (<code>title</code>, <code>center</code>, <code>butPan</code>) as members of the class, and then using initializer blocks so that they are created and set up how you want, including their children. Initializer blocks and the constructor are called in file order. (see my version below)</p>\n<p>When you have a long method, that's not <em>always</em> a sign of a problem. But when you do, it can be useful to use scope blocks to limit where things are visible. It just makes it easier to tell at a glance that whole sections of the code <em>don't</em> define variables that are going to matter later on in the long method. (So I used this in the initializer block for <code>butPan</code> below).</p>\n<p>Other than that, you've got <code>static</code> on a lot of things that don't feel static as they belong to the particular game being played. That's why you have a <code>reset</code> method which primarily just sets everything back - but it's normally easier and less prone to errors if you just make a whole new instance for a new game.</p>\n<p>Here's where I got to so far. I hope it helps, even though I guess I haven't actually answered your question about how to better handle creating the buttons.</p>\n<pre><code>import java.awt.BorderLayout;\nimport java.awt.Color;\nimport java.awt.Dimension;\nimport java.awt.Font;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.util.Random;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.SwingUtilities;\nimport javax.swing.UIManager;\nimport javax.swing.UnsupportedLookAndFeelException;\n\npublic class GuessColor extends JFrame {\n\n private static final long serialVersionUID = 1L;\n private static final Font font = new Font("Times New Roman", Font.BOLD, 30);\n private static final Dimension d = new Dimension(500, 500); // color panel size\n private static final Dimension b = new Dimension(50, 50); // button size\n private static final Random rand = new Random();\n\n private Color userColor = new Color(0, 0, 0);\n private Color goalColor = randomColor();\n\n private JLabel title = new JLabel("Match The Color!", JLabel.CENTER);\n {\n this.add(title, BorderLayout.NORTH);\n title.setFont(font);\n title.setBackground(Color.BLACK);\n title.setForeground(Color.WHITE);\n title.setOpaque(true);\n }\n\n private JPanel center = new JPanel();\n {\n this.add(center, BorderLayout.CENTER);\n center.setBackground(Color.CYAN);\n }\n\n private JPanel randPan = new JPanel(); // random color panel\n {\n center.add(randPan, BorderLayout.EAST);\n randPan.setBackground(goalColor);\n randPan.setPreferredSize(d);\n }\n\n private JPanel userPan = new JPanel(); // adjustable color panel\n {\n center.add(userPan, BorderLayout.WEST);\n userPan.setBackground(userColor);\n userPan.setPreferredSize(d);\n }\n\n private JPanel butPan = new JPanel();\n {\n this.add(butPan, BorderLayout.SOUTH);\n\n {\n JButton addRed = new JButton("+");\n addRed.setBackground(Color.RED);\n addRed.setPreferredSize(b);\n addRed.setFocusPainted(false);\n addRed.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n increaseRed();\n userPan.setBackground(userColor);\n repaint();\n check();\n }\n });\n butPan.add(addRed);\n }\n\n {\n JButton subRed = new JButton("-");\n subRed.setBackground(Color.RED);\n subRed.setPreferredSize(b);\n subRed.setFocusPainted(false);\n subRed.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n decreaseRed();\n userPan.setBackground(userColor);\n repaint();\n check();\n }\n });\n butPan.add(subRed);\n }\n\n {\n JButton addGrn = new JButton("+");\n addGrn.setBackground(Color.GREEN);\n addGrn.setPreferredSize(b);\n addGrn.setFocusPainted(false);\n addGrn.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n increaseGrn();\n userPan.setBackground(userColor);\n repaint();\n check();\n }\n });\n butPan.add(addGrn);\n }\n\n {\n JButton subGrn = new JButton("-");\n subGrn.setBackground(Color.GREEN);\n subGrn.setPreferredSize(b);\n subGrn.setFocusPainted(false);\n subGrn.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n decreaseGrn();\n userPan.setBackground(userColor);\n repaint();\n check();\n }\n });\n butPan.add(subGrn);\n }\n\n {\n JButton addBlu = new JButton("+");\n addBlu.setBackground(Color.BLUE);\n addBlu.setPreferredSize(b);\n addBlu.setFocusPainted(false);\n addBlu.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n increaseBlu();\n userPan.setBackground(userColor);\n repaint();\n check();\n }\n });\n butPan.add(addBlu);\n }\n\n {\n JButton subBlu = new JButton("-");\n subBlu.setBackground(Color.BLUE);\n subBlu.setPreferredSize(b);\n subBlu.setFocusPainted(false);\n subBlu.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n decreaseBlu();\n userPan.setBackground(userColor);\n repaint();\n check();\n }\n });\n butPan.add(subBlu);\n }\n }\n\n public GuessColor() {\n System.out.println("SOLUTION: " + goalColor);\n this.setTitle("Match the color!");\n this.pack();\n this.setLocationRelativeTo(null);\n this.setVisible(true);\n this.setResizable(false);\n this.setDefaultCloseOperation(EXIT_ON_CLOSE);\n }\n\n private Color randomColor() {\n return new Color((rand.nextInt(17) + 1) * 15, (rand.nextInt(17) + 1) * 15,\n (rand.nextInt(17) + 1) * 15);\n }\n\n private void increaseRed() {\n if (userColor.getRed() < 255) {\n userColor = new Color(userColor.getRed() + 15, userColor.getGreen(),\n userColor.getBlue());\n }\n }\n\n private void increaseGrn() {\n if (userColor.getGreen() < 255) {\n userColor = new Color(userColor.getRed(), userColor.getGreen() + 15,\n userColor.getBlue());\n }\n }\n\n private void increaseBlu() {\n if (userColor.getBlue() < 255) {\n userColor = new Color(userColor.getRed(), userColor.getGreen() + 15,\n userColor.getBlue() + 15);\n }\n }\n\n private void decreaseRed() {\n if (userColor.getRed() > 0) {\n userColor = new Color(userColor.getRed() - 15, userColor.getGreen() + 15,\n userColor.getBlue());\n }\n }\n\n private void decreaseGrn() {\n if (userColor.getGreen() > 0) {\n userColor = new Color(userColor.getRed(), userColor.getGreen() - 15,\n userColor.getBlue());\n }\n }\n\n private void decreaseBlu() {\n if (userColor.getBlue() > 0) {\n userColor = new Color(userColor.getRed(), userColor.getGreen(),\n userColor.getBlue() - 15);\n }\n }\n\n private void check() {\n if (userColor.equals(goalColor)) {\n int choose = JOptionPane.showConfirmDialog(null, "You win! Play again?");\n if (choose == JOptionPane.YES_OPTION) {\n this.dispose();\n new GuessColor();\n } else if (choose == JOptionPane.NO_OPTION) {\n System.exit(0);\n }\n }\n }\n\n public static void main(String[] args)\n throws ClassNotFoundException, InstantiationException, IllegalAccessException,\n UnsupportedLookAndFeelException {\n UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());\n SwingUtilities.invokeLater(new Runnable() {\n public void run() {\n new GuessColor();\n }\n });\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T17:07:24.783",
"Id": "495099",
"Score": "0",
"body": "Thanks! although it didn't answer about the buttons it was still a very useful. upvoted :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T09:42:42.990",
"Id": "251329",
"ParentId": "251322",
"Score": "1"
}
},
{
"body": "<p>Building on my <a href=\"https://codereview.stackexchange.com/a/251329/210456\">previous answer</a>, now I'll address simplifying the creation of the buttons.</p>\n<p>The main thing here is that you have some code which is repeated, so we can pull that logic out to a function and parameterise the parts that change. (<code>createGameButton</code>)</p>\n<p>The ActionListeners you create just call their respective methods -- that's a little unnecessary as we can just put those instructions for the ActionListener directly where we define them. It also helps that we don't need to name the buttons when we only refer to them once. (<code>butPan</code> initializer block)</p>\n<p>Lastly, the bits that are called every time afterwards can go into a method, and just call that method. (<code>update</code>)</p>\n<pre><code>import java.awt.BorderLayout;\nimport java.awt.Color;\nimport java.awt.Dimension;\nimport java.awt.Font;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.util.Random;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.SwingUtilities;\nimport javax.swing.UIManager;\nimport javax.swing.UnsupportedLookAndFeelException;\n\npublic class GuessColor extends JFrame {\n\n private static final long serialVersionUID = 1L;\n private static final Font font = new Font("Times New Roman", Font.BOLD, 30);\n private static final Dimension d = new Dimension(500, 500); // color panel size\n private static final Dimension b = new Dimension(50, 50); // button size\n private static final Random rand = new Random();\n\n private Color userColor = new Color(0, 0, 0);\n private Color goalColor = randomColor();\n\n private JLabel title = new JLabel("Match The Color!", JLabel.CENTER);\n {\n this.add(title, BorderLayout.NORTH);\n title.setFont(font);\n title.setBackground(Color.BLACK);\n title.setForeground(Color.WHITE);\n title.setOpaque(true);\n }\n\n private JPanel center = new JPanel();\n {\n this.add(center, BorderLayout.CENTER);\n center.setBackground(Color.CYAN);\n }\n\n private JPanel randPan = new JPanel(); // random color panel\n {\n center.add(randPan, BorderLayout.EAST);\n randPan.setBackground(goalColor);\n randPan.setPreferredSize(d);\n }\n\n private JPanel userPan = new JPanel(); // adjustable color panel\n {\n center.add(userPan, BorderLayout.WEST);\n userPan.setBackground(userColor);\n userPan.setPreferredSize(d);\n }\n\n private JPanel butPan = new JPanel();\n {\n this.add(butPan, BorderLayout.SOUTH);\n butPan.add(createGameButton(Color.RED, "+", new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n if (userColor.getRed() < 255) {\n userColor = new Color(userColor.getRed() + 15, userColor.getGreen(),\n userColor.getBlue());\n }\n update();\n }\n }));\n butPan.add(createGameButton(Color.RED, "-", new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n if (userColor.getRed() > 0) {\n userColor = new Color(userColor.getRed() - 15, userColor.getGreen(),\n userColor.getBlue());\n }\n update();\n }\n }));\n butPan.add(createGameButton(Color.GREEN, "+", new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n if (userColor.getGreen() < 255) {\n userColor = new Color(userColor.getRed(), userColor.getGreen() + 15,\n userColor.getBlue());\n }\n update();\n }\n }));\n butPan.add(createGameButton(Color.GREEN, "-", new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n if (userColor.getGreen() > 0) {\n userColor = new Color(userColor.getRed(), userColor.getGreen() - 15,\n userColor.getBlue());\n }\n update();\n }\n }));\n butPan.add(createGameButton(Color.BLUE, "+", new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n if (userColor.getBlue() < 255) {\n userColor = new Color(userColor.getRed(), userColor.getGreen(),\n userColor.getBlue() + 15);\n }\n update();\n }\n }));\n butPan.add(createGameButton(Color.BLUE, "-", new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n if (userColor.getBlue() > 0) {\n userColor = new Color(userColor.getRed(), userColor.getGreen(),\n userColor.getBlue() - 15);\n }\n }\n }));\n\n }\n\n public GuessColor() {\n System.out.println("SOLUTION: " + goalColor);\n this.setTitle("Match the color!");\n this.pack();\n this.setLocationRelativeTo(null);\n this.setVisible(true);\n this.setResizable(false);\n this.setDefaultCloseOperation(EXIT_ON_CLOSE);\n }\n\n private Color randomColor() {\n return new Color((rand.nextInt(17) + 1) * 15, (rand.nextInt(17) + 1) * 15,\n (rand.nextInt(17) + 1) * 15);\n }\n\n private JButton createGameButton(Color color, String label, ActionListener listener) {\n JButton button = new JButton(label);\n button.setBackground(color);\n button.setPreferredSize(b);\n button.setFocusPainted(false);\n button.addActionListener(listener);\n return button;\n }\n\n private void update() {\n userPan.setBackground(userColor);\n repaint();\n check();\n }\n\n private void check() {\n if (userColor.equals(goalColor)) {\n int choose = JOptionPane.showConfirmDialog(null, "You win! Play again?");\n if (choose == JOptionPane.YES_OPTION) {\n this.dispose();\n new GuessColor();\n } else if (choose == JOptionPane.NO_OPTION) {\n System.exit(0);\n }\n }\n }\n\n public static void main(String[] args)\n throws ClassNotFoundException, InstantiationException, IllegalAccessException,\n UnsupportedLookAndFeelException {\n UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());\n SwingUtilities.invokeLater(new Runnable() {\n public void run() {\n new GuessColor();\n }\n });\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T17:14:45.853",
"Id": "495101",
"Score": "0",
"body": "Yeah this is a good answer but it doesn't really shorten the code a whole lot. I guess its not really possible considering the buttons all perform different functions. Maybe if you added a increase/decrease boolean and color into the `createGameButton` function I could cut it down some more?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T10:49:56.797",
"Id": "251331",
"ParentId": "251322",
"Score": "1"
}
},
{
"body": "<p>My version isn't any shorter, but hopefully, it's clearer and provides a firmer foundation to build more complex games.</p>\n<p>When developing a Swing game, it helps to separate the model, view, and controller. This is called the <a href=\"https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow noreferrer\">model / view / controller pattern</a>.</p>\n<p>So, I created a model class, <code>GameModel</code>. Here's the code for the <code>GameModel</code> class.</p>\n<pre><code>public class GameModel {\n \n private Color randomColor;\n private Color userColor;\n \n private final Random random;\n \n public GameModel() {\n this.random = new Random();\n }\n \n public void createColors() {\n setRandomColor();\n setUserColor();\n }\n\n public Color getUserColor() {\n return userColor;\n }\n\n public void setUserColor() {\n int userRed = 0;\n int userGrn = 0;\n int userBlu = 0;\n this.userColor = new Color(userRed, userGrn, userBlu);\n }\n \n public void setUserColor(int red, int green, int blue) {\n this.userColor = new Color(red, green, blue);\n }\n\n public Color getRandomColor() {\n return randomColor;\n }\n\n public void setRandomColor() {\n int randRed = (random.nextInt(17) + 1) * 15;\n int randGrn = (random.nextInt(17) + 1) * 15;\n int randBlu = (random.nextInt(17) + 1) * 15;\n this.randomColor = new Color(randRed, randGrn, randBlu);\n }\n \n}\n</code></pre>\n<p><code>GameModel</code> is a plain Java class that holds the data for the game. In this simple game, we have two color fields, one for the random color and one for the user to adjust using the GUI buttons.</p>\n<p>We moved the color initiation code to this class.</p>\n<p>We have two <code>setRandomColor</code> methods, one to initialize the user color, and one to set the user color based on the GUI button actions.</p>\n<p>Now that we've created a working game model, we can focus on the view. Here's the view code.</p>\n<pre><code>public class GuessColor {\n \n private GameModel model;\n \n private JFrame frame;\n \n private JPanel userPanel;\n\n public GuessColor() {\n this.model = new GameModel();\n this.model.createColors();\n \n frame = new JFrame("Match the color!");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n \n frame.add(createMainPanel(), BorderLayout.CENTER);\n \n frame.pack();\n frame.setLocationRelativeTo(null);\n frame.setResizable(false);\n frame.setVisible(true);\n \n printSolution();\n }\n\n // sets up the frame and functionality of UI\n private JPanel createMainPanel() { \n JPanel panel = new JPanel(new BorderLayout());\n \n JLabel title = new JLabel("Match The Color!", JLabel.CENTER);\n Font font = new Font("Times New Roman", Font.BOLD, 30);\n title.setFont(font);\n title.setBackground(Color.BLACK);\n title.setForeground(Color.WHITE);\n title.setOpaque(true);\n panel.add(title, BorderLayout.NORTH);\n\n JPanel center = new JPanel(new BorderLayout());\n center.setBackground(Color.CYAN);\n panel.add(center, BorderLayout.CENTER);\n \n Dimension d = new Dimension(500, 500); // color panel size\n\n JPanel randPan = new JPanel(); // random color panel\n randPan.setBackground(model.getRandomColor());\n randPan.setPreferredSize(d);\n center.add(randPan, BorderLayout.WEST);\n\n userPanel = new JPanel(); // adjustable color panel\n userPanel.setBackground(model.getUserColor());\n userPanel.setPreferredSize(d);\n center.add(userPanel, BorderLayout.EAST);\n\n /** BUTTONS **/\n\n JPanel buttonPanel = new JPanel();\n panel.add(buttonPanel, BorderLayout.SOUTH);\n \n // This Object array makes it possible to create the JButtons in a loop\n // buttonObject[0] - JButton labels\n // buttonObject[1] - JButton action commands\n // buttonObject[2] - JButton background colors\n // buttonObject[3] - JButton foreground colors\n Object[][] buttonObject = new Object[][] { { "+", "-", "+", "-", "+", "-" },\n { "red", "red", "green", "green", "blue", "blue" },\n { Color.RED, Color.RED, Color.GREEN, \n Color.GREEN, Color.BLUE, Color.BLUE },\n { Color.WHITE, Color.WHITE, Color.BLACK, \n Color.BLACK, Color.WHITE, Color.WHITE } };\n Dimension b = new Dimension(50, 50); // button size\n ButtonListener listener = new ButtonListener();\n \n for (int i = 0; i < buttonObject[0].length; i++) {\n JButton button = new JButton((String) buttonObject[0][i]);\n button.setActionCommand((String) buttonObject[1][i]);\n button.setBackground((Color) buttonObject[2][i]);\n button.setForeground((Color) buttonObject[3][i]);\n button.setPreferredSize(b);\n button.setFocusPainted(false);\n button.addActionListener(listener);\n buttonPanel.add(button);\n }\n\n return panel; \n }\n \n public void setUserPanelColor() {\n userPanel.setBackground(model.getUserColor());\n }\n \n public void printSolution() {\n // This is just to show what the RGB\n // values are so you can easily solve\n System.out.println("SOLUTION: " + model.getRandomColor());\n\n }\n\n // main method\n public static void main(String[] args) {\n try {\n String laf = UIManager.getCrossPlatformLookAndFeelClassName();\n UIManager.setLookAndFeel(laf);\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n SwingUtilities.invokeLater(new Runnable() {\n public void run() {\n new GuessColor();\n }\n });\n }\n\n}\n</code></pre>\n<p>I made quite a few changes to your code. Here are the major changes I want to emphasize.</p>\n<ol>\n<li><p>In the <code>main</code> method, I added an <code>e.printStackTrace();</code> to the <code>catch</code> block. You should always print or log errors.</p>\n</li>\n<li><p>I separated the code to construct the <code>JFrame</code> from the code to construct the main <code>JPanel</code>. This allows me to focus on one part of the GUI at a time.</p>\n</li>\n<li><p>I used a <code>JFrame</code>. The only time you should extend a Swing component, or any Java class, is when you want to override one or more of the class methods.</p>\n</li>\n<li><p>I moved almost all of the <code>GuessColor</code> class variables to their respective methods. The only class variables that remain as class variables are the variables used in more than one method.</p>\n</li>\n<li><p>I created an admittedly complex <code>Object</code> array so I could create the <code>JButtons</code> in a loop.</p>\n</li>\n</ol>\n<p>Finally, I created the <code>ActionListener</code>. I was able to move the <code>check</code> method in the <code>ActionListener</code>.</p>\n<pre><code>public class ButtonListener implements ActionListener {\n\n @Override\n public void actionPerformed(ActionEvent event) {\n JButton button = (JButton) event.getSource();\n String text = button.getText();\n String action = event.getActionCommand();\n \n Color color = model.getUserColor();\n int red = color.getRed();\n int green = color.getGreen();\n int blue = color.getBlue();\n \n if (action.equals("red")) {\n if (text.equals("+")) {\n red += 15;\n red = Math.min(255, red);\n model.setUserColor(red, green, blue);\n } else {\n red -= 15;\n red = Math.max(0, red);\n model.setUserColor(red, green, blue);\n }\n } else if (action.equals("green")) {\n if (text.equals("+")) {\n green += 15;\n green = Math.min(255, green);\n model.setUserColor(red, green, blue);\n } else {\n green -= 15;\n green = Math.max(0, green);\n model.setUserColor(red, green, blue);\n }\n } else if (action.equals("blue")) {\n if (text.equals("+")) {\n blue += 15;\n blue = Math.min(255, blue);\n model.setUserColor(red, green, blue);\n } else {\n blue -= 15;\n blue = Math.max(0, blue);\n model.setUserColor(red, green, blue);\n }\n }\n \n setUserPanelColor();\n System.out.println(model.getUserColor());\n check();\n }\n \n // checks if the color panels are the same and displays \n // winning message if they are the same\n\n private void check() {\n if (model.getRandomColor().equals(model.getUserColor())) {\n int choose = JOptionPane.showConfirmDialog(frame, \n "You win! Play again?");\n if (choose == JOptionPane.YES_OPTION) {\n model.createColors();\n setUserPanelColor();\n printSolution();\n } else if (choose == JOptionPane.NO_OPTION) {\n System.exit(0);\n }\n }\n }\n \n}\n</code></pre>\n<p>Here's the complete runnable code. I hope this explanation helps you.</p>\n<pre><code>import java.awt.BorderLayout;\nimport java.awt.Color;\nimport java.awt.Dimension;\nimport java.awt.Font;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.util.Random;\n\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.SwingUtilities;\nimport javax.swing.UIManager;\n\npublic class GuessColor {\n \n private GameModel model;\n \n private JFrame frame;\n \n private JPanel userPanel;\n\n public GuessColor() {\n this.model = new GameModel();\n this.model.createColors();\n \n frame = new JFrame("Match the color!");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n \n frame.add(createMainPanel(), BorderLayout.CENTER);\n \n frame.pack();\n frame.setLocationRelativeTo(null);\n frame.setResizable(false);\n frame.setVisible(true);\n \n printSolution();\n }\n\n // sets up the frame and functionality of UI\n private JPanel createMainPanel() { \n JPanel panel = new JPanel(new BorderLayout());\n \n JLabel title = new JLabel("Match The Color!", JLabel.CENTER);\n Font font = new Font("Times New Roman", Font.BOLD, 30);\n title.setFont(font);\n title.setBackground(Color.BLACK);\n title.setForeground(Color.WHITE);\n title.setOpaque(true);\n panel.add(title, BorderLayout.NORTH);\n\n JPanel center = new JPanel(new BorderLayout());\n center.setBackground(Color.CYAN);\n panel.add(center, BorderLayout.CENTER);\n \n Dimension d = new Dimension(500, 500); // color panel size\n\n JPanel randPan = new JPanel(); // random color panel\n randPan.setBackground(model.getRandomColor());\n randPan.setPreferredSize(d);\n center.add(randPan, BorderLayout.WEST);\n\n userPanel = new JPanel(); // adjustable color panel\n userPanel.setBackground(model.getUserColor());\n userPanel.setPreferredSize(d);\n center.add(userPanel, BorderLayout.EAST);\n\n /** BUTTONS **/\n\n JPanel buttonPanel = new JPanel();\n panel.add(buttonPanel, BorderLayout.SOUTH);\n \n // This Object array makes it possible to create the JButtons in a loop\n // buttonObject[0] - JButton labels\n // buttonObject[1] - JButton action commands\n // buttonObject[2] - JButton background colors\n // buttonObject[3] - JButton foreground colors\n Object[][] buttonObject = new Object[][] { { "+", "-", "+", "-", "+", "-" },\n { "red", "red", "green", "green", "blue", "blue" },\n { Color.RED, Color.RED, Color.GREEN, \n Color.GREEN, Color.BLUE, Color.BLUE },\n { Color.WHITE, Color.WHITE, Color.BLACK, \n Color.BLACK, Color.WHITE, Color.WHITE } };\n Dimension b = new Dimension(50, 50); // button size\n ButtonListener listener = new ButtonListener();\n \n for (int i = 0; i < buttonObject[0].length; i++) {\n JButton button = new JButton((String) buttonObject[0][i]);\n button.setActionCommand((String) buttonObject[1][i]);\n button.setBackground((Color) buttonObject[2][i]);\n button.setForeground((Color) buttonObject[3][i]);\n button.setPreferredSize(b);\n button.setFocusPainted(false);\n button.addActionListener(listener);\n buttonPanel.add(button);\n }\n\n return panel; \n }\n \n public void setUserPanelColor() {\n userPanel.setBackground(model.getUserColor());\n }\n \n public void printSolution() {\n // This is just to show what the RGB\n // values are so you can easily solve\n System.out.println("SOLUTION: " + model.getRandomColor());\n\n }\n\n // main method\n public static void main(String[] args) {\n try {\n String laf = UIManager.getCrossPlatformLookAndFeelClassName();\n UIManager.setLookAndFeel(laf);\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n SwingUtilities.invokeLater(new Runnable() {\n public void run() {\n new GuessColor();\n }\n });\n }\n \n public class ButtonListener implements ActionListener {\n\n @Override\n public void actionPerformed(ActionEvent event) {\n JButton button = (JButton) event.getSource();\n String text = button.getText();\n String action = event.getActionCommand();\n \n Color color = model.getUserColor();\n int red = color.getRed();\n int green = color.getGreen();\n int blue = color.getBlue();\n \n if (action.equals("red")) {\n if (text.equals("+")) {\n red += 15;\n red = Math.min(255, red);\n model.setUserColor(red, green, blue);\n } else {\n red -= 15;\n red = Math.max(0, red);\n model.setUserColor(red, green, blue);\n }\n } else if (action.equals("green")) {\n if (text.equals("+")) {\n green += 15;\n green = Math.min(255, green);\n model.setUserColor(red, green, blue);\n } else {\n green -= 15;\n green = Math.max(0, green);\n model.setUserColor(red, green, blue);\n }\n } else if (action.equals("blue")) {\n if (text.equals("+")) {\n blue += 15;\n blue = Math.min(255, blue);\n model.setUserColor(red, green, blue);\n } else {\n blue -= 15;\n blue = Math.max(0, blue);\n model.setUserColor(red, green, blue);\n }\n }\n \n setUserPanelColor();\n System.out.println(model.getUserColor());\n check();\n }\n \n // checks if the color panels are the same and displays \n // winning message if they are the same\n\n private void check() {\n if (model.getRandomColor().equals(model.getUserColor())) {\n int choose = JOptionPane.showConfirmDialog(frame, \n "You win! Play again?");\n if (choose == JOptionPane.YES_OPTION) {\n model.createColors();\n setUserPanelColor();\n printSolution();\n } else if (choose == JOptionPane.NO_OPTION) {\n System.exit(0);\n }\n }\n }\n \n }\n \n public class GameModel {\n \n private Color randomColor;\n private Color userColor;\n \n private final Random random;\n \n public GameModel() {\n this.random = new Random();\n }\n \n public void createColors() {\n setRandomColor();\n setUserColor();\n }\n\n public Color getUserColor() {\n return userColor;\n }\n\n public void setUserColor() {\n int userRed = 0;\n int userGrn = 0;\n int userBlu = 0;\n this.userColor = new Color(userRed, userGrn, userBlu);\n }\n \n public void setUserColor(int red, int green, int blue) {\n this.userColor = new Color(red, green, blue);\n }\n\n public Color getRandomColor() {\n return randomColor;\n }\n\n public void setRandomColor() {\n int randRed = (random.nextInt(17) + 1) * 15;\n int randGrn = (random.nextInt(17) + 1) * 15;\n int randBlu = (random.nextInt(17) + 1) * 15;\n this.randomColor = new Color(randRed, randGrn, randBlu);\n }\n \n }\n}\n</code></pre>\n<p>Edited to add: I made the game more accessible to younger players by adding an RGB display for each color.</p>\n<p>Here's the GUI.</p>\n<p><a href=\"https://i.stack.imgur.com/jNyjJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jNyjJ.png\" alt=\"Match The Color GUI\" /></a></p>\n<p>Here's the revised complete runnable code.</p>\n<pre><code>import java.awt.BorderLayout;\nimport java.awt.Color;\nimport java.awt.Dimension;\nimport java.awt.Font;\nimport java.awt.GridBagConstraints;\nimport java.awt.GridBagLayout;\nimport java.awt.Insets;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.util.Random;\n\nimport javax.swing.BorderFactory;\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JOptionPane;\nimport javax.swing.JPanel;\nimport javax.swing.JTextField;\nimport javax.swing.SwingUtilities;\nimport javax.swing.UIManager;\n\npublic class GuessColor {\n \n private DisplayPanel randomDisplayPanel;\n private DisplayPanel userDisplayPanel;\n \n private GameModel model;\n \n private JFrame frame;\n \n private JPanel randomPanel;\n private JPanel userPanel;\n\n public GuessColor() {\n this.model = new GameModel();\n this.model.createColors();\n \n frame = new JFrame("Match the color!");\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n \n frame.add(createMainPanel(), BorderLayout.CENTER);\n \n frame.pack();\n frame.setLocationRelativeTo(null);\n frame.setResizable(false);\n frame.setVisible(true);\n }\n\n // sets up the frame and functionality of UI\n private JPanel createMainPanel() { \n JPanel panel = new JPanel(new BorderLayout());\n \n JLabel title = new JLabel("Match The Color!", JLabel.CENTER);\n Font font = new Font("Times New Roman", Font.BOLD, 30);\n title.setFont(font);\n title.setBackground(Color.BLACK);\n title.setForeground(Color.WHITE);\n title.setOpaque(true);\n panel.add(title, BorderLayout.NORTH);\n\n JPanel center = new JPanel(new BorderLayout());\n center.setBackground(Color.CYAN);\n panel.add(center, BorderLayout.CENTER);\n \n Dimension d = new Dimension(500, 500); // color panel size\n\n randomPanel = new JPanel(new BorderLayout()); // random color panel\n randomPanel.setBackground(model.getRandomColor());\n randomPanel.setPreferredSize(d);\n randomDisplayPanel = new DisplayPanel(model.getRandomColor());\n randomPanel.add(randomDisplayPanel.getPanel(), BorderLayout.NORTH);\n center.add(randomPanel, BorderLayout.WEST);\n\n userPanel = new JPanel(new BorderLayout()); // adjustable color panel\n userPanel.setBackground(model.getUserColor());\n userPanel.setPreferredSize(d);\n userDisplayPanel = new DisplayPanel(model.getUserColor());\n userPanel.add(userDisplayPanel.getPanel(), BorderLayout.NORTH);\n center.add(userPanel, BorderLayout.EAST);\n\n /** BUTTONS **/\n\n JPanel buttonPanel = new JPanel();\n panel.add(buttonPanel, BorderLayout.SOUTH);\n \n // This Object array makes it possible to create the JButtons in a loop\n // buttonObject[0] - JButton labels\n // buttonObject[1] - JButton action commands\n // buttonObject[2] - JButton background colors\n // buttonObject[3] - JButton foreground colors\n Object[][] buttonObject = new Object[][] { { "+", "-", "+", "-", "+", "-" },\n { "red", "red", "green", "green", "blue", "blue" },\n { Color.RED, Color.RED, Color.GREEN, \n Color.GREEN, Color.BLUE, Color.BLUE },\n { Color.WHITE, Color.WHITE, Color.BLACK, \n Color.BLACK, Color.WHITE, Color.WHITE } };\n Dimension b = new Dimension(50, 50); // button size\n ButtonListener listener = new ButtonListener();\n \n for (int i = 0; i < buttonObject[0].length; i++) {\n JButton button = new JButton((String) buttonObject[0][i]);\n button.setActionCommand((String) buttonObject[1][i]);\n button.setBackground((Color) buttonObject[2][i]);\n button.setForeground((Color) buttonObject[3][i]);\n button.setPreferredSize(b);\n button.setFocusPainted(false);\n button.addActionListener(listener);\n buttonPanel.add(button);\n }\n\n return panel; \n }\n \n public void setRandomPanelColor() {\n randomPanel.setBackground(model.getRandomColor());\n randomDisplayPanel.setColor(model.getRandomColor());\n }\n \n public void setUserPanelColor() {\n userPanel.setBackground(model.getUserColor());\n userDisplayPanel.setColor(model.getUserColor());\n }\n \n // main method\n public static void main(String[] args) {\n try {\n String laf = UIManager.getCrossPlatformLookAndFeelClassName();\n UIManager.setLookAndFeel(laf);\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n SwingUtilities.invokeLater(new Runnable() {\n public void run() {\n new GuessColor();\n }\n });\n }\n \n public class DisplayPanel {\n \n private JPanel panel;\n \n private JTextField redField;\n private JTextField greenField;\n private JTextField blueField;\n \n public DisplayPanel(Color color) {\n createJPanel();\n setColor(color);\n }\n \n private void createJPanel() {\n panel = new JPanel(new GridBagLayout());\n panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));\n \n GridBagConstraints gbc = new GridBagConstraints();\n gbc.anchor = GridBagConstraints.LINE_START;\n gbc.fill = GridBagConstraints.HORIZONTAL;\n gbc.insets = new Insets(5, 5, 5, 5);\n gbc.gridx = 0;\n gbc.gridy = 0;\n \n JLabel redLabel = new JLabel("Red:");\n redLabel.setForeground(Color.WHITE);\n panel.add(redLabel, gbc);\n \n gbc.gridx++;\n redField = new JTextField(3);\n redField.setEditable(false);\n redField.setHorizontalAlignment(JTextField.TRAILING);\n panel.add(redField, gbc);\n \n gbc.gridx = 0;\n gbc.gridy++;\n JLabel greenLabel = new JLabel("Green:");\n greenLabel.setForeground(Color.WHITE);\n panel.add(greenLabel, gbc);\n \n gbc.gridx++;\n greenField = new JTextField(3);\n greenField.setEditable(false);\n greenField.setHorizontalAlignment(JTextField.TRAILING);\n panel.add(greenField, gbc);\n \n gbc.gridx = 0;\n gbc.gridy++;\n JLabel blueLabel = new JLabel("Blue:");\n blueLabel.setForeground(Color.WHITE);\n panel.add(blueLabel, gbc);\n \n gbc.gridx++;\n blueField = new JTextField(3);\n blueField.setEditable(false);\n blueField.setHorizontalAlignment(JTextField.TRAILING);\n panel.add(blueField, gbc);\n }\n\n public JPanel getPanel() {\n return panel;\n }\n\n public void setColor(Color color) {\n panel.setBackground(color);\n redField.setText(Integer.toString(color.getRed()));\n greenField.setText(Integer.toString(color.getGreen()));\n blueField.setText(Integer.toString(color.getBlue()));\n }\n \n }\n \n public class ButtonListener implements ActionListener {\n\n @Override\n public void actionPerformed(ActionEvent event) {\n JButton button = (JButton) event.getSource();\n String text = button.getText();\n String action = event.getActionCommand();\n \n Color color = model.getUserColor();\n int red = color.getRed();\n int green = color.getGreen();\n int blue = color.getBlue();\n \n if (action.equals("red")) {\n if (text.equals("+")) {\n red += 15;\n red = Math.min(255, red);\n } else {\n red -= 15;\n red = Math.max(0, red);\n }\n } else if (action.equals("green")) {\n if (text.equals("+")) {\n green += 15;\n green = Math.min(255, green);\n } else {\n green -= 15;\n green = Math.max(0, green);\n }\n } else if (action.equals("blue")) {\n if (text.equals("+")) {\n blue += 15;\n blue = Math.min(255, blue);\n } else {\n blue -= 15;\n blue = Math.max(0, blue);\n }\n }\n \n model.setUserColor(red, green, blue);\n setUserPanelColor();\n check();\n }\n \n // checks if the color panels are the same and displays \n // winning message if they are the same\n\n private void check() {\n if (model.getRandomColor().equals(model.getUserColor())) {\n int choose = JOptionPane.showConfirmDialog(frame, \n "You win! Play again?");\n if (choose == JOptionPane.YES_OPTION) {\n model.createColors();\n setRandomPanelColor();\n setUserPanelColor();\n } else if (choose == JOptionPane.NO_OPTION) {\n frame.dispose();\n System.exit(0);\n }\n }\n }\n \n }\n \n public class GameModel {\n \n private Color randomColor;\n private Color userColor;\n \n private final Random random;\n \n public GameModel() {\n this.random = new Random();\n }\n \n public void createColors() {\n setRandomColor();\n setUserColor();\n }\n\n public Color getUserColor() {\n return userColor;\n }\n\n public void setUserColor() {\n int userRed = 135;\n int userGrn = 135;\n int userBlu = 135;\n this.userColor = new Color(userRed, userGrn, userBlu);\n }\n \n public void setUserColor(int red, int green, int blue) {\n this.userColor = new Color(red, green, blue);\n }\n\n public Color getRandomColor() {\n return randomColor;\n }\n\n public void setRandomColor() {\n int randRed = (random.nextInt(17) + 1) * 15;\n int randGrn = (random.nextInt(17) + 1) * 15;\n int randBlu = (random.nextInt(17) + 1) * 15;\n this.randomColor = new Color(randRed, randGrn, randBlu);\n }\n \n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T17:17:12.867",
"Id": "495102",
"Score": "0",
"body": "Great answer, very helpful. I like the idea of the object array for the buttons!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T13:27:31.657",
"Id": "251375",
"ParentId": "251322",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "251375",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T05:39:29.480",
"Id": "251322",
"Score": "3",
"Tags": [
"java",
"game",
"swing",
"gui"
],
"Title": "Color matching swing GUI game"
}
|
251322
|
<p>I'm working with a REST service that responds with indeterminate types. In particular, it can respond with a <code>String</code>, a correct payload (<code>T: Decodable</code>) or an error payload (<code>PayloadError</code>).</p>
<p>In order to cope with this type of requirement I've ended up with the following solution:</p>
<pre><code>do {
let decoder = JSONDecoder()
let either = try decoder.decode(Either<T, PayloadError>.self, from: data)
switch either {
case .left(let value):
completion(.success(value))
case .right(let payloadError):
completion(.failure(.generic)))
}
} catch {
if let value = String(data: data, encoding: .utf8) as? T {
completion(.success(value))
} else {
completion(.failure(.generic))
}
}
</code></pre>
<p>where <code>Either</code> is defined as:</p>
<pre><code>enum Either<T, U> {
case left(T)
case right(U)
}
extension Either: Decodable where T: Decodable, U: Decodable {
init(from decoder: Decoder) throws {
if let value = try? T(from: decoder) {
self = .left(value)
} else if let value = try? U(from: decoder) {
self = .right(value)
} else {
let context = DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot decode \(T.self) or \(U.self)"
)
throw DecodingError.dataCorrupted(context)
}
}
}
</code></pre>
<p>Do you think the code looks good or should I use a more elegant solution?</p>
<p><strong>Update 01.11.2020</strong></p>
<p>These are the possible use cases along side with concrete responses.</p>
<p><em>Use Case 1</em></p>
<p>The client calls API method <code>/authenticate</code>. The server can responds with an authentication token of type <code>String</code> or a payload error of type <code>PayloadError</code> (if the server responds with unauthorized, for example). The JSON used to decode <code>PayloadError</code> is something like:</p>
<pre><code>{
code: 1,
message: "Error message here"
}
</code></pre>
<p><code>PayloadError</code> is defined as:</p>
<pre><code>struct PayloadError: Decodable {
let code: Int
let message: String
}
</code></pre>
<p><em>Use Case 2</em></p>
<p>The client calls any other method. For example, it can call <code>/user</code> that gives back the info for the current user (the auth token is passed along). A <code>struct User: Decodable</code> is decoded from the returned JSON. If there is an error, the server replies with a <code>PayloadError</code>.</p>
<p>Based on the above use cases, the server can respond with:</p>
<ul>
<li><code>String</code></li>
<li><code>T: Decodable</code> (like <code>User</code>)</li>
<li><code>PayloadError</code></li>
</ul>
<p>What I don't like is the code in <code>catch</code> since its intent is not clear.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T19:30:22.020",
"Id": "494850",
"Score": "1",
"body": "Can you provide an example of concrete responses of the various types, and the corresponding `T` and `PayloadError` types? – I wonder how `String(data: data, encoding: .utf8) as? T` works if `T` is anything but `String`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T10:41:41.940",
"Id": "494917",
"Score": "1",
"body": "@MartinR thanks for your comment. I've added an update as you requested. Hope it's clear."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T11:12:25.953",
"Id": "495199",
"Score": "0",
"body": "I assume that `.generic` is from your custom error type? Perhaps you can add the signature of the completion function (including the used types), just to avoid misunderstandings. – As far as I can see, there is a general problem: If a string is expected, then *any* response which is not a well-formed PayloadError will be interpreted as a string."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T11:59:31.667",
"Id": "495538",
"Score": "0",
"body": "@MartinR sorry for the delay. I've finally end up splitting the two use cases. See below. Thanks."
}
] |
[
{
"body": "<p>I've finally end up splitting the two use cases. This in order to make the code readable and more maintainable.</p>\n<p><code>PayloadError</code> is mapped to a <code>ServiceError: Error</code> in order to align the output.</p>\n<p><em>Use case 1</em></p>\n<pre><code>guard let data = response.data else {\n completion(.failure(.invalidData))\n return\n}\n\nlet jsonDecoder = JSONDecoder()\nif let payloadError = try? jsonDecoder.decode(PayloadError.self, from: data) {\n completion(.failure(ServiceError.from(payloadError)))\n} else if let token = String(data: data, encoding: .utf8) {\n completion(.success(token))\n} else {\n completion(.failure(.decodingError))\n}\n</code></pre>\n<p><em>Use case 2</em></p>\n<pre><code>guard let data = response.data else {\n completion(.failure(.invalidData))\n return\n}\nlet decoder = JSONDecoder()\nguard let either = try? decoder.decode(Either<T, PayloadError>.self, from: data) else {\n completion(.failure(.decodingError))\n return\n}\nswitch either {\ncase .left(let value):\n completion(.success(value))\ncase .right(let payloadError):\n completion(.failure(ServiceError.from(payloadError)))\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T11:59:03.720",
"Id": "251649",
"ParentId": "251333",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "251649",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T11:28:00.223",
"Id": "251333",
"Score": "4",
"Tags": [
"swift"
],
"Title": "Decoding indeterminate types using JSON Decoder"
}
|
251333
|
<p>Can I reduce the loop inside my method with map or is there a shorter implementation of this code that's dropping elements in sequence?</p>
<pre><code>
// Method that drops one element in sequence
def drop_Val_In_List[String](ls: Seq[String], value: String): Seq[String] = {
val index = ls.indexOf(value) //index is -1 if there is no matc
if (index < 0) {
ls
} else if (index == 0) {
ls.tail
} else {
// splitAt keeps the matching element in the second group
val (a, b) = ls.splitAt(index)
a ++ b.tail
}
}
val KeepCols = Seq("id", "type", "month", "car", "road")
// Generalization of the above method to drop multiple elements
def drop_Val_List_In_List[String](ls: Seq[String], in_ls: Seq[String]): Seq[String] = {
var tmp_ = ls
//println(tmp.getClass)
for(x <- in_ls ){ // should work without var x
tmp_ = drop_Val_In_List(tmp_, x)
}
tmp_;
}
val tmp = drop_Val_List_In_List(KeepCols, List("id", "type", "month"))
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T12:21:12.203",
"Id": "494734",
"Score": "0",
"body": "Welcome to the Code Review site where we review working code and provide suggestions on how to improve that code. Code that is not working as expected is considered [off-topic](https://codereview.stackexchange.com/help/dont-ask) and the question may be closed by the community. This type of question is more appropriate on stack overflow, but please read [their guidelines](https://stackoverflow.com/help/how-to-ask) for asking a good question first."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T12:22:28.350",
"Id": "494735",
"Score": "0",
"body": "Got it. Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T15:58:47.613",
"Id": "494758",
"Score": "0",
"body": "Welcome to Code Review. It appears that you updated the code in revision 2 and removed the text about an error in [revision 3](https://codereview.stackexchange.com/posts/251334/revisions#rev-arrow-b802b5f8-af2c-4c96-9c85-006fd841fafa). However, trying the code in multiple online tools shows there is still an error on that line that calls `drop_Val_In_List()` i.e.: `type mismatch; found : java.lang.String; required: String(in method drop_Val_List_In_List)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T16:21:37.093",
"Id": "494764",
"Score": "1",
"body": "I appreciate your observation. Now it should work"
}
] |
[
{
"body": "<h1>Follow the naming convention of the language</h1>\n<p>For scala, this is <a href=\"https://docs.scala-lang.org/style/naming-conventions.html\" rel=\"nofollow noreferrer\">here</a>. Spell methods and variables in lower camel case:</p>\n<pre><code>drop_Val_In_List\ndrop_Val_List_In_List\nin_ls\n</code></pre>\n<h1>Use the most appropriate data structure</h1>\n<p>To me, it seems like you want a set, not a sequence/list. <code>Set</code> also has the method you want:</p>\n<pre><code>val KeepCols = Set("id", "type", "month", "car", "road")\nval tmp = KeepCols.diff(Set("id", "type", "month"))\n</code></pre>\n<p>If you don't want to use a set, <code>Seq</code> also has <code>diff</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T13:36:13.297",
"Id": "251338",
"ParentId": "251334",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "251338",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T11:38:18.683",
"Id": "251334",
"Score": "2",
"Tags": [
"scala"
],
"Title": "Scala: drop elements in Sequence"
}
|
251334
|
<p>Let's say you are living in a controlled economy where there is a baker in town, and every day he bakes a random number of loaves of bread (sometimes the oven breaks, or he has less ingredients). The people in the town queue up to buy a loaf of bread (you can only buy one loaf) based on a pre-assigned ticketing system. Your position in the queue is constant every single day.</p>
<p>There are more people in the queue than loaves of bread available. The bread is ready at different times each day, and some people in the queue need to be at work. If the bread isn't ready before they have to leave for work, they leave the queue and the next person in line takes their place. But they still have their original queue ticket. The values in the people list are the number of hours before the person in the queue has to leave for work</p>
<p>I want to know what is the number on the last ticket given to the baker each day before he runs out of loaves of bread.</p>
<p>I can get my existing code to work for relatively small numbers of people, but if there are millions of people, lots of days (planned economies plan for 5 years ahead), you get the picture.</p>
<pre><code>def BakerQueue(loaves, people, bake_time):
got_some_bread = []
for b in bake_time:
counter = 0
for p in range(len(people)):
if people[p] >= b:
counter += 1
if counter == loaves:
got_some_bread.append(p + 1)
counter = 0
break
elif p == len(people) - 1:
got_some_bread.append(0)
break
elif counter < loaves and p == len(people) - 1:
got_some_bread.append(0)
counter = 0
return got_some_bread
</code></pre>
<p>You can use this to run the code:
in this example, there are 3 loaves, 19 people in the queue [list], and different bake times [list] for each of the days in a week, so on the first day, ticket 1, 2, 3 get loaves, on the second day 2,3,4 get loaves because 1 went to work as the bread wasn't ready in time, on the third day, 7, 9 and 15 get loaves because the bread took 5 hours to be ready and those people went to work. I only care about who gets the last loaf on each day which is what the function is returning.</p>
<pre><code>BakerQueue(3, [1, 4, 4, 3, 1, 2, 6, 1, 9, 4, 4, 3, 1, 2, 6, 9, 4, 5, 8],[1, 2, 5, 4, 5, 4, 7])
</code></pre>
<p>This will return as expected</p>
<pre><code>[3, 4, 15, 7, 15, 7, 19]
</code></pre>
<p>So I thought about implementing a priority queue using the heapq library, however, I need to maintain the original ticket order, so I thought to create a list of tuples with the values and the index and convert to a heap and pop the top person off of the heap if they have gone to work or if they have gotten a loaf of bread and there are still loaves available. This is the point where I begin to fail. I only care which ticket number got the last loaf of bread each day</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T12:41:37.317",
"Id": "494737",
"Score": "4",
"body": "The baker sounds like Seinfeld's soup guy"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T13:48:35.087",
"Id": "494744",
"Score": "0",
"body": "done, see the edited post. It's an old problem, dealing with people waiting in line for stuff. I just want to see how to do it with people queuing for food in a planned economy where the numbers can be 100s of millions of people, obviously with more than on baker."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T14:01:19.210",
"Id": "494745",
"Score": "0",
"body": "Welcome to the Code Review site. This is a fascinating question, but what are you seeking from this code review. Is the code working as expected, if not then the question is off-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T14:06:18.167",
"Id": "494746",
"Score": "0",
"body": "It works until you try it with millions of people and 1000s of days. I am trying to find a way to make it run really quickly, say O(NlogN) as opposed O(N^2)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T14:29:25.493",
"Id": "494749",
"Score": "1",
"body": "Thanks for the example. So `people` will be a list of millions of ints from 1 to 12 or so? For benchmarking, code to generate large test data would be good."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T14:37:26.007",
"Id": "494750",
"Score": "1",
"body": "What's the N in your O(N^2)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T14:50:37.683",
"Id": "494752",
"Score": "0",
"body": "The people is the N"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T15:11:27.593",
"Id": "494753",
"Score": "1",
"body": "Welll the number of possible different values does matter, because that's also the number of possible different *results*. Like if they're ints from 1 to 12, then you could just pre-compute the 12 results and handle the \"1000s of days\" by looking up the results without re-computing them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T15:14:28.480",
"Id": "494754",
"Score": "1",
"body": "If N is the people, I don't see why you're saying O(N^2). That ignores the number of days. And you don't have two nested loops over the people or so."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T15:27:47.217",
"Id": "494756",
"Score": "0",
"body": "People could be a number from 1 to 12, yes. The function takes an. int and two lists of ints (hours before work, how long to bake). It’s an arbitrary question, could easily be used in pharmaceuticals e.g. number of vaccines (int), days to live (list of ints),how long before vaccine arrives (list of ints). Days to live has no bearing on your priority in the vaccine queue, only your number in the queue defines your priority, which could be defined as who got ill the earliest"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T15:38:06.550",
"Id": "494757",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/115681/discussion-between-tennis-tubbies-and-heap-overflow)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T18:10:03.987",
"Id": "494766",
"Score": "2",
"body": "You say \"every day he bakes a random number of loaves\" but in your example and code it's the same for all days?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T01:52:31.287",
"Id": "494787",
"Score": "0",
"body": "sorry, i was keeping it simple, i can generate the random number of loaves everytime, but I didn't want to over complicate it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T12:32:49.023",
"Id": "494827",
"Score": "0",
"body": "Well it does make a big difference algorithmically if you can assume that the number of loaves is static or dynamic ... If the number of loaves is dynamic, it would require my preprocessing step every day. Should still be a lot faster than the naive approach, though."
}
] |
[
{
"body": "<p>I think I understood your problem.</p>\n<h2>Problem description</h2>\n<p><strong>Given:</strong></p>\n<ul>\n<li><code>num_items</code> - the number of available items</li>\n<li><code>targets</code> - a list of potential targets, each having a value</li>\n<li><code>threshold</code> - a cutoff limit</li>\n</ul>\n<p><strong>Task:</strong></p>\n<ul>\n<li>Choose the first <code>num_items</code> elements of <code>targets</code>, whose values are above or equal to <code>threshold</code>.</li>\n<li>Return the array index of the last chosen element from <code>targets</code> (starting with <code>1</code>), or <code>0</code> if not enough targets are available. (Odd decision, I would have gone with indices starting at <code>0</code> and return <code>len(targets)</code> if none found, but fine)</li>\n<li>Optimize for speed. <code>targets</code> and <code>num_items</code> are identical every time, <code>threshold</code> is the only value that changes.</li>\n</ul>\n<hr />\n<h2>Example</h2>\n<pre><code>num_items = 3\ntargets = [5,3,4,1,3,3,7,4]\nthreshold = 4\n</code></pre>\n<p>Chosen targets would be the ones at the positions <code>[0,2,6]</code>, with the values <code>[5,4,7]</code>, as those are the first <code>3</code> values that are above or equal to <code>threshold</code>. We only search the index of the last one, which in this case would be <code>6</code>.</p>\n<hr />\n<h2>Approach</h2>\n<p>Your original idea was to iterate through all the people which is very fast if the threshold is very low, but becomes really slow if the threshold is higher, as we need to iterate through all the people until we find a candidate.</p>\n<p>I rewrote your original idea to iterate through all of them, as I wasn't able to understand your code:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def choose_first_n(num_items, targets, threshold):\n for target_id, target in enumerate(targets):\n if target >= threshold:\n num_items -= 1\n if num_items == 0:\n return target_id + 1\n return 0\n\ndef baker_queue(num_loaves_per_day, people_max_waiting_time, required_baking_times):\n results = []\n for today_baking_time in required_baking_times:\n results.append(choose_first_n(num_loaves_per_day, people_max_waiting_time, today_baking_time))\n return results\n\nprint(baker_queue(3,\n [1, 4, 4, 3, 1, 2, 6, 1, 9, 4, 4, 3, 1, 2, 6, 9, 4, 5, 8],\n [1, 2, 5, 4, 5, 4, 7]))\n# Returns: [3, 4, 15, 7, 15, 7, 19], as in the original code.\n</code></pre>\n<p>Using a heap is an interesting idea, but I don't think we benefit from that in any way. Heaps are only really fast for item removal/insertion, which we don't do. We just iterate over them.</p>\n<p>The fastest way that I could think of is to pre-process the <code>threshold</code> list into something more efficient, as if, create an 'index' of the last target.</p>\n<p><em>Demonstration:</em>\nWe use our previous code, and look at the results based on the threshold value:</p>\n<pre><code>def choose_first_n(num_items, targets, threshold):\n for target_id, target in enumerate(targets):\n if target >= threshold:\n num_items -= 1\n if num_items == 0:\n return target_id + 1\n return 0\n\ntargets = [1, 4, 4, 3, 1, 2, 6, 1, 9, 4, 4, 3, 1, 2, 6, 9, 4, 5, 8]\nnum_items = 3\n\nfor threshold in range (10):\n result = choose_first_n(num_items, targets, threshold)\n print(f"Threshold: {threshold}, Result: {result}")\n</code></pre>\n<pre><code>Threshold: 0, Result: 3\nThreshold: 1, Result: 3\nThreshold: 2, Result: 4\nThreshold: 3, Result: 4\nThreshold: 4, Result: 7\nThreshold: 5, Result: 15\nThreshold: 6, Result: 15\nThreshold: 7, Result: 19\nThreshold: 8, Result: 19\nThreshold: 9, Result: 0\n</code></pre>\n<p>You can see that if the threshold goes up, the result goes up. There is a steadily increasing relationship between the threshold and the result.</p>\n<p>If we can compute the values at which the result changes, we can compute the result directly via a divide-and-conquer search, which is a LOT faster than iterating through the list. (<code>O(logn)</code> instead of <code>O(n)</code>, in case you are familiar with Big-O notation)</p>\n<p>One thing to note here is that the last result is <code>0</code>, which breaks that scheme. That is the reason why it is benefitial to let the indices start with <code>0</code> instead of <code>1</code>, and have the 'error' case be <code>len(targets)</code> instead of <code>0</code>.</p>\n<h2>Preprocessing</h2>\n<p>The hardest thing is the preprocessing to get to that mapping.</p>\n<p>Let's look at it from the other way round.</p>\n<p>For the sake of simplicity, let's say num_items is 3, and we have 10 targets.\nWill the chosen targets be within the first 5 targets?</p>\n<p>The answer is: yes, IF at least 3 of the first 5 targets are above or equal to the threshold. Or in other words, the 3rd largest number in the list is the deciding factor. If the threshold is above the 3rd largest number, the first 5 targets will not provide all the chosen targets.</p>\n<p>Therefore, for all items, we need to compute the 3rd largest number. Funnily, this is actually where a heap WILL come in handy ;)</p>\n<h2>Implementation</h2>\n<pre><code>import heapq\nimport bisect\n\ndef preprocess(targets, num_items):\n # Special case if we have more items than targets, would break later.\n # Return an empty lookup table with len(targets) as fallback, so the\n # result will always be len(targets)\n if num_items > len(targets):\n lookup_table = ([], [], len(targets))\n return lookup_table\n\n # our heap, will contain the first num_items smallest targets\n largest_targets_heap = []\n\n # Our first preprocessing result, will contain the\n # third large number between the first item and the current item,\n # for every item.\n third_largest_number_per_target = []\n\n # Compute the third largest previous value for every target\n for target in targets:\n heapq.heappush(largest_targets_heap, target)\n if len(largest_targets_heap) > num_items:\n heapq.heappop(largest_targets_heap)\n\n current_third_largest = largest_targets_heap[0]\n third_largest_number_per_target.append(current_third_largest)\n\n # We now have the third largest number for every target.\n # Now, consolidate that data into a lookup table, to prevent duplication.\n # Therefore, find the first occurrence of every number\n lookup_table_indices = []\n lookup_table_values = []\n current_value = third_largest_number_per_target[num_items - 1]\n\n # Push the (num_items-1)th value to account for the fact our heap wasn't filled up until the\n # first num_items were processed\n lookup_table_indices.append(num_items - 1)\n lookup_table_values.append(current_value)\n\n # Fill the rest of the lookup table\n for index, value in enumerate(third_largest_number_per_target):\n if index < num_items - 1:\n continue\n if value != current_value:\n lookup_table_indices.append(index)\n lookup_table_values.append(value)\n current_value = value\n\n # The lookup table we have, consisting of values, indices and a maximum value\n lookup_table = (lookup_table_values, lookup_table_indices, len(targets))\n\n return lookup_table\n\ndef choose_first_n_preprocessed(lookup_table, threshold):\n (lookup_table_values, lookup_table_indices, max_value) = lookup_table\n\n # We need to find the first (value,index) pair in lookup table where value is larger or equal to threshold\n # We do this by using bisect, which is really fast. This is only possible because of our preprocessing.\n position = bisect.bisect_left(lookup_table_values, threshold)\n\n # If we didn't find a result in the preprocessed table, we return the max value, to indicate that the\n # threshold ist too high.\n if position >= len(lookup_table_indices):\n return max_value\n\n # Read the result from the table of incides\n value = lookup_table_indices[position]\n return value\n\ndef baker_queue(num_loaves_per_day, people_max_waiting_time, required_baking_times):\n # Create the preprocessed lookup table\n lookup_table = preprocess(people_max_waiting_time, num_loaves_per_day)\n\n # For every day, compute the result\n results = []\n for today_baking_time in required_baking_times:\n # Use our fast lookup based algorithm now\n result = choose_first_n_preprocessed(lookup_table, today_baking_time)\n\n # Convert indices back to starting with 1, and 0 in error case, as\n # the original format was\n if result == len(people_max_waiting_time):\n results.append(0)\n else:\n results.append(result + 1)\n return results\n\nprint(baker_queue(3,\n [1, 4, 4, 3, 1, 2, 6, 1, 9, 4, 4, 3, 1, 2, 6, 9, 4, 5, 8],\n [1, 2, 5, 4, 5, 4, 7]))\n# [3, 4, 15, 7, 15, 7, 19]\n</code></pre>\n<h2>Theoretical Analysis</h2>\n<p>This should now be a LOT faster, especially for a large number of days, but also for a large number of people.</p>\n<p>The complexity of the naive implementation was</p>\n<pre><code>O(days * people)\n</code></pre>\n<p>The complexity of the preprocessed implementation is</p>\n<pre><code>O(people * log(bread) + days * log(people))\n</code></pre>\n<p>This doesn't sound a lot different, but it is. It basically says if the limiting factor is the people, it doesn't matter how many days, and if the limiting factor is the days, it doesn't matter how many people.</p>\n<h2>Benchmarking Results</h2>\n<p>Setup was:</p>\n<ul>\n<li>900 bread per day</li>\n<li>10,000 people</li>\n<li>10,000 days</li>\n</ul>\n<p>Result:</p>\n<ul>\n<li>Naive: 2.13 seconds</li>\n<li>Preprocessed: 0.012 seconds</li>\n</ul>\n<p>I then tried to push the algorithm so far that it also takes 2 seconds, and got those numbers:</p>\n<ul>\n<li>90,000 bread per day</li>\n<li>1,000,000 people</li>\n<li>1,000,000 days</li>\n</ul>\n<p>I didn't run those numbers on the naive algorithm, but the math says it would have taken about 20,000 seconds, or 5.5 hours.</p>\n<p>The benchmark code can be found at <a href=\"https://ideone.com/2ZMBVH\" rel=\"nofollow noreferrer\">https://ideone.com/2ZMBVH</a> or here:</p>\n<pre><code>import heapq\nimport bisect\nimport random\nimport time\n\ndef choose_first_n(num_items, targets, threshold):\n for target_id, target in enumerate(targets):\n if target >= threshold:\n num_items -= 1\n if num_items == 0:\n return target_id\n return len(targets)\n\n# 2s for optimised\n#num_bread = 90000\n#num_days = 1000000\n#num_people = 1000000\n\n# 2s for unoptimized\nnum_bread = 900\nnum_days = 10000\nnum_people = 10000\n\n\ntargets = [random.random() for _ in range(num_people)]\n\nresult_sum = 0\nalgo_naive_start = time.time()\nfor threshold in range(num_days):\n result = choose_first_n(num_bread, targets, threshold/num_days)\n result_sum += result\n #print(f"Threshold: {threshold}, Result: {result}")\nalgo_naive_end = time.time()\nprint(f"Result naive: {result_sum}")\n\n\ndef preprocess(targets, num_items):\n # Special case if we have more items than targets, would break later.\n # Return an empty lookup table with len(targets) as fallback, so the\n # result will always be len(targets)\n if num_items > len(targets):\n lookup_table = ([], [], num_items, len(targets))\n return lookup_table\n\n # our heap, will contain the first num_items smallest targets\n largest_targets_heap = []\n\n # Our first preprocessing result, will contain the\n # third large number between the first item and the current item,\n # for every item.\n third_largest_number_per_target = []\n\n # Compute the third largest previous value for every target\n for target in targets:\n heapq.heappush(largest_targets_heap, target)\n if len(largest_targets_heap) > num_items:\n heapq.heappop(largest_targets_heap)\n\n current_third_largest = largest_targets_heap[0]\n third_largest_number_per_target.append(current_third_largest)\n\n # We now have the third largest number for every target.\n # Now, consolidate that data into a lookup table, to prevent duplication.\n # Therefore, find the first occurrence of every number\n lookup_table_indices = []\n lookup_table_values = []\n current_value = third_largest_number_per_target[num_items - 1]\n\n # Push the (num_items-1)th value to account for the fact our heap wasn't filled up until the\n # first num_items were processed\n lookup_table_indices.append(num_items - 1)\n lookup_table_values.append(current_value)\n\n # Fill the rest of the lookup table\n for index, value in enumerate(third_largest_number_per_target):\n if index < num_items - 1:\n continue\n if value != current_value:\n lookup_table_indices.append(index)\n lookup_table_values.append(value)\n current_value = value\n\n # The lookup table we have, consisting of values, indices, a minimum and a maximum value\n lookup_table = (lookup_table_values, lookup_table_indices, num_items, len(targets))\n\n return lookup_table\n\n\ndef choose_first_n_preprocessed(lookup_table, threshold):\n (lookup_table_values, lookup_table_indices, min_value, max_value) = lookup_table\n\n # We need to find the first (value,index) pair in lookup table where value is larger or equal to threshold\n # We do this by using bisect, which is really fast. This is only possible because of our preprocessing.\n position = bisect.bisect_left(lookup_table_values, threshold)\n\n # If we didn't find a result in the preprocessed table, we return the max value, to indicate that the\n # threshold ist too high.\n if position >= len(lookup_table_indices):\n return max_value\n\n # Read the result from the table of incides\n value = lookup_table_indices[position]\n return value\n\n\ndef baker_queue(num_loaves_per_day, people_max_waiting_time, required_baking_times):\n # Create the preprocessed lookup table\n lookup_table = preprocess(people_max_waiting_time, num_loaves_per_day)\n\n # For every day, compute the result\n results = []\n for today_baking_time in required_baking_times:\n # Use our fast lookup based algorithm now\n result = choose_first_n_preprocessed(lookup_table, today_baking_time)\n\n # Convert indices back to starting with 1, and 0 in error case, as\n # the original format was\n if result == len(people_max_waiting_time):\n results.append(0)\n else:\n results.append(result + 1)\n return results\n\n\nalgo_preprocessed_start = time.time()\n\nlookup_table = preprocess(targets, num_bread)\n\nalgo_preprocessed_mid = time.time()\n#print(lookup_table)\n\nresult_sum = 0\nfor threshold in range(num_days):\n result = choose_first_n_preprocessed(lookup_table, threshold/num_days)\n result_sum += result\n #print(f"Threshold: {threshold}, Result: {result}")\nalgo_preprocessed_end = time.time()\nprint(f"Result preprocessed: {result_sum}")\n\nprint(f"Time naive: {algo_naive_end - algo_naive_start} s")\nprint(f"Time preprocessed (preprocessing step): {algo_preprocessed_mid - algo_preprocessed_start} s")\nprint(f"Time preprocessed (evaluation step): {algo_preprocessed_end - algo_preprocessed_mid} s")\nprint(f"Time preprocessed total: {algo_preprocessed_end - algo_preprocessed_start} s")\n</code></pre>\n<p>Well that took a while, I hope it was worth it ;)</p>\n<p>I think this was my biggest post yet, it was a really interesting task!</p>\n<p>I hope you appreciate it.</p>\n<p>Greetings</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T02:02:02.223",
"Id": "494788",
"Score": "1",
"body": "\"One thing to note here is that the last result is 0, which brakes that scheme.\" break, not brake. Given that it's a keyword in Python, it's important to know the spelling."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T07:41:04.060",
"Id": "494799",
"Score": "0",
"body": "Thanks, fixed. Will delete this comment after acknowledgement."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T18:26:52.327",
"Id": "251349",
"ParentId": "251335",
"Score": "10"
}
},
{
"body": "<p>@Finomnis offers an excellent theoretical and algorithmic analysis. As is my wont, I'll take a different approach and examine your usage of Python.</p>\n<pre><code> counter = 0\n break\n</code></pre>\n<p>does not need the <code>counter</code> assignment at all. You're breaking, so you will return to the top of the outer loop where this assignment is done the first time; it needn't be repeated.</p>\n<p>This is a classic example of the need for <code>enumerate</code>:</p>\n<pre><code> for p in range(len(people)):\n if people[p] >= b:\n</code></pre>\n<p>In other words,</p>\n<pre><code>for p, person in enumerate(people):\n if person >= b:\n</code></pre>\n<p>The entire method can be well-expressed as a generator rather than using successive list concatenation:</p>\n<pre><code>def baker_queue(loaves, people, bake_time):\n for b in bake_time:\n counter = 0\n for p, person in enumerate(people):\n if person >= b:\n counter += 1\n if counter == loaves:\n yield p + 1\n break\n elif p == len(people) - 1:\n yield 0\n break\n elif counter < loaves and p == len(people) - 1:\n yield 0\n counter = 0\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T20:22:59.067",
"Id": "494780",
"Score": "2",
"body": "Nice! And if bake_time is a generator as well, you have a continuous stream :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T04:46:28.933",
"Id": "494789",
"Score": "1",
"body": "Thanks, this is a really nice solution, I changed line 28 from:\n\n````current_value = third_largest_number_per_target[num_items - 1]````\n\nto\n\n````current_value = third_largest_number_per_target[- 1]````\n\nto solve the following test case"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T04:48:34.310",
"Id": "494790",
"Score": "0",
"body": "baker_queue(80, [19, 74, 78, 60, 60, 16, 45, 16, 10, 6, 46, 87, 34, 61, 15, 71, 66, 3, 6, 97, 73, 84, 94, 22, 1, 19, 100, 19, 62, 31, 62, 53, 1, 44, 3, 30, 53, 62], [40, 14, 5, 30, 98, 37, 24, 46, 10, 79, 62, 20, 39, 52, 99, 60, 47, 5, 86, 61, 69, 18, 46, 7, 2, 95, 95, 97, 57, 81, 39, 31, 2, 10, 24, 69, 25, 45, 69, 13, 61, 50, 84, 4, 18, 91, 40, 26, 19, 67, 76, 32, 43, 53, 21, 55, 57, 19, 4, 97, 85, 78, 45, 94, 40, 90, 93, 60, 73, 93, 33, 9, 58, 20, 53, 5, 97, 33, 85, 39, 75, 28, 54, 83, 59, 36, 97, 29, 61, 55, 28, 15, 30, 81, 17, 8])"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T07:41:59.883",
"Id": "494800",
"Score": "2",
"body": "@TennisTubbies I think you commented on the wrong solution, but not problem. The reason seems to be that bread > people, meaning that we always get 0 as result. I'll add a special case to catch that error.\nI think your fix is incorrect, as it breaks real cases. I'll fix it a different way."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T20:03:08.983",
"Id": "251355",
"ParentId": "251335",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "251349",
"CommentCount": "14",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T12:18:55.353",
"Id": "251335",
"Score": "8",
"Tags": [
"python",
"python-3.x",
"priority-queue",
"heap-sort"
],
"Title": "Planned Economy Bakery - Trying to scale a nested loop with a heap"
}
|
251335
|
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/251295/231235">A Summation Function For Boost.MultiArray in C++</a>. Besides the summation operation of all elements, I am trying to focus on the element-wise operation here. The main idea of this question is to implement an <code>element_wise_add</code> function for Boost.MultiArray. The purpose of this <code>element_wise_add</code> function is to perform element-wise add operation on two <code>boost::multi_array</code>s. The function <code>element_wise_add</code> has two input parameters <code>input1</code> and <code>input2</code> for element-wise add operation and the return type is the element-wised result.</p>
<pre><code>template<class T> requires is_summable<T>
auto element_wise_add(const T& input1, const T& input2)
{
return input1 + input2;
}
// Deal with the two input case
template<class T, std::size_t Dims> requires is_summable<T>
auto element_wise_add(const boost::detail::multi_array::const_sub_array<T, Dims>& input1, const boost::detail::multi_array::const_sub_array<T, Dims>& input2)
{
boost::multi_array<T, Dims> output(reinterpret_cast<boost::array<size_t, Dims> const&>(*input1.shape()));
for (typename boost::detail::multi_array::const_sub_array<T, Dims>::index i = 0; i < input1.shape()[0]; i++)
{
output[i] = element_wise_add(input1[i], input2[i]);
}
return output;
}
// Deal with the two input case
template<class T, std::size_t Dims> requires is_summable<T>
auto element_wise_add(const boost::detail::multi_array::sub_array<T, Dims>& input1, const boost::detail::multi_array::sub_array<T, Dims>& input2)
{
boost::multi_array<T, Dims> output(reinterpret_cast<boost::array<size_t, Dims> const&>(*input1.shape()));
for (typename boost::detail::multi_array::sub_array<T, Dims>::index i = 0; i < input1.shape()[0]; i++)
{
output[i] = element_wise_add(input1[i], input2[i]);
}
return output;
}
// Deal with the two input case
template<class T, std::size_t Dims> requires is_summable<T>
auto element_wise_add(const boost::multi_array<T, Dims>& input1, const boost::multi_array<T, Dims>& input2)
{
if (*input1.shape() != *input2.shape()) // if shape is different
{
return input1; // unable to perform element-wise add operation
}
boost::multi_array<T, Dims> output(reinterpret_cast<boost::array<size_t, Dims> const&>(*input1.shape()));
for (typename boost::multi_array<T, Dims>::index i = 0; i < input1.shape()[0]; i++)
{
output[i] = element_wise_add(input1[i], input2[i]);
}
return output;
}
</code></pre>
<p>The used <code>is_summable</code> concept:</p>
<pre><code>template<typename T>
concept is_summable = requires(T x) { x + x; };
</code></pre>
<p>The test of this <code>element_wise_add</code> function is as follows.</p>
<pre><code>// Create a 3D array that is 3 x 4 x 2
typedef boost::multi_array<double, 3> array_type;
typedef array_type::index index;
array_type A(boost::extents[3][4][2]);
// Assign values to the elements
int values = 0;
for (index i = 0; i != 3; ++i)
for (index j = 0; j != 4; ++j)
for (index k = 0; k != 2; ++k)
A[i][j][k] = values++;
for (index i = 0; i != 3; ++i)
for (index j = 0; j != 4; ++j)
for (index k = 0; k != 2; ++k)
std::cout << A[i][j][k] << std::endl;
auto DoubleA = element_wise_add(A, A);
for (index i = 0; i != 3; ++i)
for (index j = 0; j != 4; ++j)
for (index k = 0; k != 2; ++k)
std::cout << DoubleA[i][j][k] << std::endl;
</code></pre>
<p>All suggestions are welcome.</p>
<ul>
<li><p>Which question it is a follow-up to?</p>
<p><a href="https://codereview.stackexchange.com/q/251295/231235">A Summation Function For Boost.MultiArray in C++</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p>The previous question is the implementation of a summation function for Boost.MultiArray and the main idea of this question is to implement an <code>element_wise_add</code> function for Boost.MultiArray.</p>
</li>
<li><p>Why a new review is being asked for?</p>
<p>The similar usage of three types overload function for <code>boost::multi_array</code>, <code>boost::detail::multi_array::sub_array</code> and <code>boost::detail::multi_array::const_sub_array</code> appears again. I know maybe this is not a good idea. However, there is no any better way coming up in my mind. Moreover, the exception handling for the "shape is different" situation is not perfect. In the case of <code>boost::detail::multi_array::sub_array</code> and <code>boost::detail::multi_array::const_sub_array</code>, I am not sure what's the appropriate thing to return back. I have ever tried something with <code>std::optional</code> like this:</p>
<pre><code>template<class T, std::size_t Dims> requires is_summable<T>
auto element_wise_add(const boost::detail::multi_array::const_sub_array<T, Dims>& input1, const boost::detail::multi_array::const_sub_array<T, Dims>& input2)
{
std::optional<boost::detail::multi_array::const_sub_array<T, Dims>> final_output;
if (*input1.shape() != *input2.shape()) // if shape is different
{
final_output = std::nullopt;
}
else
{
boost::multi_array<T, Dims> output(reinterpret_cast<boost::array<size_t, Dims> const&>(*input1.shape()));
for (typename boost::detail::multi_array::const_sub_array<T, Dims>::index i = 0; i < input1.shape()[0]; i++)
{
output[i] = element_wise_add(input1[i], input2[i]);
}
final_output = output;
}
return final_output;
}
</code></pre>
<p>And this:</p>
<pre><code>template<class T, std::size_t Dims> requires is_summable<T>
auto element_wise_add(const boost::detail::multi_array::sub_array<T, Dims>& input1, const boost::detail::multi_array::sub_array<T, Dims>& input2)
{
std::optional<boost::detail::multi_array::sub_array<T, Dims>> final_output;
if (*input1.shape() != *input2.shape()) // if shape is different
{
final_output = std::nullopt;
}
else
{
boost::multi_array<T, Dims> output(reinterpret_cast<boost::array<size_t, Dims> const&>(*input1.shape()));
for (typename boost::detail::multi_array::sub_array<T, Dims>::index i = 0; i < input1.shape()[0]; i++)
{
output[i] = element_wise_add(input1[i], input2[i]);
}
final_output = output;
}
return final_output;
}
</code></pre>
<p>However, this is so complex to use (the usage of <code>.value()</code> or <code>.value_or()</code> function is needed to access the content in <code>std::optional<></code> structure) and a little horrible I think. If there is any suggestion or possible improvement, please tell me!</p>
</li>
</ul>
|
[] |
[
{
"body": "<h1>Consider turning this into an <code>operator+()</code></h1>\n<p>Since element-wise addition is quite a common and natural operation (for example, the STL supports this for <a href=\"https://en.cppreference.com/w/cpp/numeric/valarray\" rel=\"nofollow noreferrer\"><code>std::valarray</code></a>), it might be more intuitive to overload <code>operator+()</code> instead of creating a function <code>element_wise_add()</code>.\nSee <a href=\"https://stackoverflow.com/questions/62744851/how-to-execute-mathematical-operations-between-two-boostmulti-arrays-c\">this question</a> for a possible implementation that also extends this easily to other operators.</p>\n<p>Another advantage of making this an <code>operator+()</code> is that it makes a <code>boost::multi_array</code> itself satisfy <code>is_summable</code>, so without adding explicit support for recursive containers, the following would then work:</p>\n<pre><code>boost::multi_array<boost::multi_array<double, 2>, 3> array1, array2;\nauto array3 = array1 + array2;\n</code></pre>\n<h1>Handling mismatched array dimensions</h1>\n<p>I would indeed not use <code>std::optional</code> to signal errors for mathematical operations. I see two ways:</p>\n<ol>\n<li><p>Ensure the dimensions of the returned array are the maximums of the dimensions of the two input arrays. So if I add <code>{{1}, {2}}</code> to <code>{{3, 5}}</code> the result will be <code>{{4, 5}, {2, 0}}</code>.</p>\n</li>\n<li><p>Throw a <a href=\"https://en.cppreference.com/w/cpp/error/logic_error\" rel=\"nofollow noreferrer\"><code>std::logic_error</code></a>, in the assumption that it is a programming error to add two mismatched errors.</p>\n</li>\n</ol>\n<h1>Avoiding repetition</h1>\n<p>You are basically writing the same thing thrice, the only variation is whether the inputs are regular <code>boost::multi_array</code>s, <code>sub_array</code>s or <code>const_sub_array</code>s. To avoid this, you want to make the input types templated, and to ensure that it only matches <code>boost::multi_array</code> related types, just write a concept for that. Again, you can use expressions that you already use for this:</p>\n<pre><code>template<T>\nconcept is_multi_array = requires(T x) {\n x.shape();\n boost::multi_array(x);\n};\n</code></pre>\n<p>This will test that the type of <code>x</code> has a <code>shape()</code> member function and that a <code>boost::multi_array</code> can be copy-constructed from it. Then just write:</p>\n<pre><code>template<class T> requires is_multi_array<T>\nauto element_wise_add(const T& input1, const T& input2)\n{\n if (*input1.shape() != *input2.shape())\n {\n throw std::logic_error("array shape mismatch");\n }\n\n boost::multi_array output(input1);\n\n for (decltype(+input1.shape()[0]) i = 0; i < input1.shape()[0]; i++)\n {\n output[i] = element_wise_add(input1[i], input2[i]);\n }\n\n return output;\n}\n</code></pre>\n<p>The drawback here is that the whole <code>input1</code> array is copied into <code>output</code> for no good reason, except that I don't see how to construct a new <code>multi_array</code> more efficiently without going into the type hell that comes with <code>boost::multi_array</code>. Perhaps this can be outsourced to another template function.</p>\n<p>You'll also notice I changed the way the type for <code>i</code> is determined: I use <code>decltype()</code>, but since that keeps the <code>const</code>-ness, I have to cast that away. There are <a href=\"https://stackoverflow.com/questions/19235496/using-decltype-to-get-an-expressions-type-without-the-const\">various ways</a> to do that, I used the unary <code>+</code> trick here.</p>\n<h1>Handling more combinations</h1>\n<p>What if I want to add an <code>sub_array</code> to a regular <code>multi_array</code> of the same size? With your approach, you would have to handle all possible combinations separately, but with the single function example I showed, you can just write:</p>\n<pre><code>template<class T1, class T2> requires (is_multi_array<T1> && is_multi_array<T2>)\nauto element_wise_add(const T1& input1, const T2& input2)\n{\n ...\n}\n</code></pre>\n<p>However, also consider that you might want to add an array of doubles to an array of integers. That could be made to work, if you also write:</p>\n<pre><code>template<typename T1, typename T2>\nconcept is_summable = requires(T1 x, T2 y) { x + y; };\n\ntemplate<class T1, class T2> requires is_summable<T1, T2>\nauto element_wise_add(const T1& input1, const T2& input2)\n{\n return input1 + input2;\n}\n</code></pre>\n<p>Although to make it truly useful, you want the type of <code>output</code> to have a value type that matches the result of adding the value types of the two input arrays.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T17:17:49.973",
"Id": "251348",
"ParentId": "251336",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "251348",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T13:32:02.527",
"Id": "251336",
"Score": "3",
"Tags": [
"c++",
"recursion",
"boost",
"c++20"
],
"Title": "An element_wise_add Function For Boost.MultiArray in C++"
}
|
251336
|
<p>Can someone look over my code and clean it up?</p>
<p>I am trying to make a calculator with multiple inputs to add up. This is a snippet of the code that just needs to be cleaned up and shortened and I am relatively new to python so if anyone wants to clean this up thank you.</p>
<pre><code>#functions
def x():
#needed for the the loop later
x.x = int(input("Type how many numbers you would like to add up: "))
x.xCON = int(input("Please confirm by typing the same number: "))
#welcome to the code
print("Would you like to add up lots of numbers?")
print("If so you came to the right place")
#neaten up
print("________________________________________________")
#run function
x()
#cheack if the numbers are the same if not they have to retype them
if x.x == x.xCON:
#neaten up
print("____________________________________")
#setting veriables for the loops and the list of the numbers
i = 0
nums = []
#while i is not = to the input number(x.x) do the loop
while i != x.x:
#asks for the numbers to be added up
INTnum = float(input("Write the numbers to be added up: "))
#adds the numbers to the list
nums.append(INTnum)
#updates the veriable cheacking how many times the code has been ran
i+=1
#creating new veriables for the next loop
index = 0
ans = 0
#while indxex is not = to the amount to numbers in the list run the code
while index != len(nums):
#veriable nums is now set as the lists index of the veriable index
num = nums[index]
#the ans veriable is eqal to itself + the number that was recorded from the idex
ans = ans + num
#moves the number along one everytime the code is run
index+=1
#gives the rueult of the sum
print("\nThe sum of the numbers is", ans)
#neaten up
print("____________________________________________________")
#what happens if the numbers are not the same sending the bacn to the x() function
else:
print("The numbers were not the same.")
x()
#end of the code
print("\nThank you for using the calculator")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T14:07:19.567",
"Id": "494747",
"Score": "1",
"body": "Welcome to the Code Review site, the current title applies to every question on this site, and makes no attempt to explain what the code does. Please read [How do I ask a good question](https://codereview.stackexchange.com/help/how-to-ask) for some advice on how to title the question."
}
] |
[
{
"body": "<p>Your <code>x</code> function has a few notable things:</p>\n<ul>\n<li><p><code>x</code> is a very poor name. It doesn't give any hints as to what the function is supposed to do. The name of your function should let the reader of your code know what its purpose is. Something like <code>get_user_input</code> would be much better.</p>\n</li>\n<li><p>You're associating data with the function object itself; essentially creating static variables. This is not a good idea though. This means that this function can only be called once before you overwrite the previous entered data. In your case here, that may not be a big deal, but it is <em>not</em> a good habit to get into. This will significantly complicate code later when you have functions that you're calling in multiple places in your code. Return the results instead.</p>\n</li>\n<li><p>You're having the user enter a confirmation, but then you're checking that they match outside of the function. Just check inside the function and loop until they match.</p>\n</li>\n</ul>\n<p>After fixing up those points, I have:</p>\n<pre><code>def get_user_input():\n while True:\n n_numbers = int(input("Type how many numbers you would like to add up: "))\n confirmation = int(input("Please confirm by typing the same number: "))\n\n if n_numbers == confirmation:\n return n_numbers\n else:\n print("The numbers were not the same.")\n</code></pre>\n<p>They you can get rid of the <code>else</code> case at the bottom of your code. You'd then use this function like:</p>\n<pre><code>n_numbers = get_user_input()\n</code></pre>\n<p>And use <code>n_numbers</code> instead of <code>x.x</code>.</p>\n<hr />\n<p>You don't do any error handling anywhere. I find it odd that in your code, you require confirmation to ensure the user didn't typo the number they entered, but you aren't protecting against them typing in nonsensical input (like <code>hello</code>). If the user types a non-number, you'll get a <code>ValueError</code> that will crash your program. You may want to consider wrapping calls to <code>int</code> and <code>float</code> in a <code>try</code>/<code>except</code> to ensure that your program won't crash.</p>\n<hr />\n<p>This loop:</p>\n<pre><code>nums = []\nwhile i != n_numbers:\n INTnum = float(input("Write the numbers to be added up: "))\n nums.append(INTnum)\n i+=1\n</code></pre>\n<p>Can be cleaned up by using a <code>range</code>:</p>\n<pre><code>nums = []\nfor _ in range(n_numbers):\n INTnum = float(input("Write the numbers to be added up: "))\n nums.append(INTnum)\n</code></pre>\n<p>Now you don't need to manually handle <code>i</code>. This can be further cleaned up by using a list comprehension:</p>\n<pre><code>nums = [float(input("Write the numbers to be added up: "))\n for _ in range(n_numbers)]\n</code></pre>\n<p>Whenever you find yourself manually handling loop indices like you were with <code>i</code>, there's likely a better way that handles the looping for you.</p>\n<p>The same can be said for this loop:</p>\n<pre><code>while index != len(nums):\n num = nums[index]\n ans = ans + num\n index+=1\n</code></pre>\n<p>Note how you never need <code>index</code> except to access <code>nums</code>. Just loop over <code>nums</code> directly:</p>\n<pre><code>for num in nums:\n ans += num # The same as "ans = ans + num"\n</code></pre>\n<p>If you need to loop over a list, just loop over the list directly.</p>\n<p>Really though, that's just <code>sum</code>:</p>\n<pre><code>ans = sum(nums)\n</code></pre>\n<hr />\n<p>Your comments aren't a good use of commenting. A lot of them are simply restating what the code itself says:</p>\n<pre><code>#the ans veriable is eqal to itself + the number that was recorded from the idex\nans = ans + num\n\n. . .\n\n#creating new veriables for the next loop\nindex = 0\n</code></pre>\n<p>If something is already self-explanatory, don't simply restate that in a comment. Your code reads like you're under the impression that every line of code requires a comment, but this isn't true. <em>Ideally</em>, your code itself should be all the explanation the reader needs, but if more explanation is required, note why the code is unreadable or why it's behaving as it is. When half your code is comments that just restate the code, it detracts from the important part: the code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T14:36:06.200",
"Id": "251341",
"ParentId": "251339",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "251341",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T13:40:19.843",
"Id": "251339",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"calculator"
],
"Title": "Calculator with multiple inputs to add up"
}
|
251339
|
<p>I recently created an intermediate calculator program, primarily to practice programming in C# but also for use with my college subjects. Any feedback on coding practices I can implement to optimise this program and any other programs I write in the future would be greatly appreciated.</p>
<p>Thanks.</p>
<pre><code>using System;
namespace calculatormessingaroundthingy
{
class Program
{
static void Main()
{
Console.WriteLine("Hello World!");
bool loopInt=false; // Sets value of loop variable to false.
while (loopInt == false) // Causes the program to repeatedly run until the user chooses to stop.
{
MessageOptions(); // Calls a procedure which lists the user's options.
var input = Console.ReadLine();
int inputInt;
while ((!int.TryParse(input, out inputInt)) | (!(inputInt>=0 && inputInt<=6))) // Loop repeats while either the user's input can't be passed into an int variable or while the int is not between 0 and 6 inclusive.
{
Console.WriteLine("ERROR: Invalid Input");
MessageOptions();
input = Console.ReadLine();
}
if (inputInt==0) // Input of 0 exits the program
{
Console.WriteLine("Goodbye!");
loopInt = true;
break;
}
FirstInput(inputInt); // Calls a procedure which gets the user's first number, the message depending on the user's previous input.
var strNum1 = Console.ReadLine();
double num1;
while ((!double.TryParse(strNum1, out num1))) // Loop repeats while the user's input can't be passed into a double variable.
{
Console.WriteLine("ERROR: Invalid Input");
FirstInput(inputInt);
strNum1 = Console.ReadLine();
}
SecondInput(inputInt); // Calls a procedure which gets the user's first number, the message depending on the user's previous input
var strNum2 = Console.ReadLine();
double num2;
while ((!double.TryParse(strNum2, out num2))) // Loop repeats while the user's input can't be passed into a double variable.
{
Console.WriteLine("ERROR: Invalid Input");
SecondInput(inputInt);
strNum2 = Console.ReadLine();
}
switch (inputInt) // Passes the user's two numbers into corresponding procedure for a certain mathematical operation.
{
// inputInt corresponds to the user's respones to the operation they wish to perform.
case 1:
Console.WriteLine(Add(num1, num2));
break;
case 2:
Console.WriteLine(Subtract(num1, num2));
break;
case 3:
Console.WriteLine(Multiply(num1, num2));
break;
case 4:
Console.WriteLine(Divide(num1, num2));
break;
case 5:
Console.WriteLine(Powers(num1, num2));
break;
case 6:
Console.WriteLine(Logarithm(num1, num2));
break;
}
}
}
static double Powers(double number, double power) // Raises the first number to the power of the second number and returns the result.
{
return Math.Pow(number, power);
}
static double Add(double number, double number2) // Adds together both numbers and returns the result.
{
return number + number2;
}
static double Subtract(double number, double number2) // Subtracts the second number from the first number and returns the result.
{
return number - number2;
}
static double Multiply(double number, double number2) // Multiplies together both numbers and returns the result.
{
return number * number2;
}
static double Divide(double number, double number2) // Divides the first number by the second number and returns the result.
{
return number / number2;
}
static double Logarithm(double number, double number2) // Returns the logarithm of base first number and argument second number.
{
return Math.Log(number2, number);
}
static public void MessageOptions() // Displays the user's inital options.
{
Console.WriteLine();
Console.WriteLine("-------------------------------------");
Console.WriteLine("Choose one of the following options: ");
Console.WriteLine("1. Addition");
Console.WriteLine("2. Subtraction");
Console.WriteLine("3. Multiplication");
Console.WriteLine("4. Division");
Console.WriteLine("5. Powers");
Console.WriteLine("6. Logarithms");
Console.WriteLine("0. Exit");
Console.WriteLine("-------------------------------------");
}
static public void FirstInput(int input) // Displays what number should be entered dependent on the inital input.
{
switch (input)
{
case 1: case 2: case 3: case 4:
Console.WriteLine("Enter the first number: ");
break;
case 5:
Console.WriteLine("Enter the base number: ");
break;
case 6:
Console.WriteLine("Enter the logarithm's base: ");
break;
}
}
static public void SecondInput(int input) // Displays what number should be entered dependenent on the inital input.
{
switch (input)
{
case 1: case 2: case 3: case 4:
Console.WriteLine("Enter the second number: ");
break;
case 5:
Console.WriteLine("Enter the exponent: ");
break;
case 6:
Console.WriteLine("Enter the logarithm's argument: ");
break;
}
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T18:39:37.993",
"Id": "494767",
"Score": "3",
"body": "`calculatormessingaroundthingy` - Naming is hard. I don't blame you."
}
] |
[
{
"body": "<h2>First of all, let's review some semantics that make the program a bit clumsy:</h2>\n<ol>\n<li><code>while (loopInt == false)</code> > <code>while (!loopInt)</code></li>\n<li>Your <code>loopInt</code> variable is useless, in the only occasion you change it to <code>true</code> you also <code>break;</code> so your loop can just be <code>while (true)</code> (which, IMO, really expresses its purpose better - unless you want to stop, it shows you the same interface forever.</li>\n<li>Spacing. Although that should be enforced by your IDE, it makes reading your code way easier. So, for instance, <code>if (inputInt==0)</code> should really be <code>if (inputInt == 0)</code></li>\n<li>Hungarian notation is a variable naming convention that prefixes the variable type before its name. You seem to use something similar (<code>inputInt</code> is of type <code>int</code>). This is not encouraged in C#. Your variable may just as well be called <code>input</code>, and with today's advanced IDEs, you just have to hover over the variable name to see its value. No need to clutter its name with the type suffix. Also, you seem to call your loop variable <code>loopInt</code> where it really should say <code>loopBool</code>.</li>\n<li>Inconsistent use of <code>var</code>. Either you (1) use it everywhere (2) use it nowhere (3) use it in places where you need to use complex types (e.g. <code>Dictionary<string, List<int>></code>). You seem to use it <em>sometimes</em>, which really is not critical but a little annoying to look at. I think you should form yourself some guidelines when to use var. If you ask me for the guidelines that I follow, usually if any generics are involved or if the type is a class name <code>WithMoreThanTwoWords</code>, then I use <code>var</code>. Otherwise I stick with the actual type name.</li>\n<li>Function names should be denoting actions, since functions are entities that are supposed to <strong>do stuff</strong>. For example, <code>SecondInput</code>, IMO, would be a function that displays a message and returns the input. But it's actually quite unclear what it does. In fact, in your code - it does something different than what I would have thought of. In this particular example, I would call the function <code>ShowSecondInputMessage</code>. Although it's longer, it expresses the purpose of the function better.</li>\n</ol>\n<h2>Now let's get for things that are more important/about program structure itself:</h2>\n<p>Since your <code>while ... TryParse</code> logic repeats two times (and might repeat some more times) I would separate it into a function <code>double GetInput(string message)</code> and just call it two times (instead of having that logic twice)</p>\n<p>I don't like the <code>FirstInput</code> and <code>SecondInput</code> pattern. I think it limits your functions (for instance, what if you need to add a 10eX function that takes only one parameter, X? If you're accommodated to classes in C#, I think I would use this feature to organize the code (see below).</p>\n<p>(Note, the following is only a bunch of ideas. You may take some, all or none of them. It is completely different from your code to enable you (and I) to think more open-mindedly)</p>\n<h3>Let's create a generic <code>MathOperation</code> class:</h3>\n<pre><code>abstract class MathOperation\n{\n public abstract string Name { get; }\n public virtual string[] InputNames => new[] { "First number", "Second number" };\n\n protected abstract double Calculate(double[] inputs);\n}\n</code></pre>\n<p>That structure will let us accept an arbitrary number of inputs and make custom calculations.</p>\n<p>Let's try to start extending it. Write a simple <code>AdditionOperation</code>:</p>\n<pre><code>sealed class AdditionOperation : MathOperation\n{\n public override string Name => "Addition";\n\n protected override double Calculate(double[] inputs)\n {\n return inputs[0] + inputs[1];\n }\n}\n</code></pre>\n<p>Pay attention to the fact that we can just refer to <code>inputs[0]</code> and <code>inputs[1]</code> inside our <code>Calculate</code> function since we are going to ensure the inputs validity.</p>\n<p>Let's write the input function that will retrieve the input from the user. We'll implement it inside the <code>MathOperation</code> class.</p>\n<pre><code> protected double[] GetInputs()\n {\n double[] inputs = new double[InputNames.Length];\n for (int i = 0; i < InputNames.Length; ++i)\n {\n inputs[i] = TakeSingleInput(InputNames[i]);\n }\n return inputs;\n }\n\n private double TakeSingleInput(string parameterName)\n {\n Console.Write("Please enter value for {0}: ", parameterName);\n string userInput = Console.ReadLine();\n double parsedInput;\n\n while (!double.TryParse(userInput, out parsedInput))\n {\n Console.Write("Invalid input. Please re-enter number: ");\n userInput = Console.ReadLine();\n }\n\n return parsedInput;\n }\n</code></pre>\n<p>For the sake of completeness of this class, let's also implement a function that will just "do what the operation does":</p>\n<pre><code> public void Run()\n {\n double[] inputs = GetInputs();\n double result = Calculate(inputs);\n Console.WriteLine("The result: {0}", result);\n }\n</code></pre>\n<p>And now, we still only have that <code>switch (inputInt)</code> that we have to take care of. <a href=\"https://levelup.gitconnected.com/if-else-is-a-poor-mans-polymorphism-ab0b333b7265\" rel=\"noreferrer\">The If-Else Is a Poor Man’s Polymorphism</a> is a good article I recommend reading.</p>\n<p>So, now we'll create a simple <code>Calculator</code> class to manage multiple operations:</p>\n<pre><code>class Calculator\n{\n private List<MathOperation> Operations = new List<MathOperation>();\n\n public void AddOperation(MathOperation operation) { Operations.Add(operation); }\n public MathOperation SelectOperation()\n {\n Console.WriteLine("Select an operation:");\n for (int i = 0; i < Operations.Count; ++i)\n {\n Console.WriteLine(Operations[i].Name);\n }\n\n int i = int.Parse(Console.ReadLine()); // TODO: Error handling (not relevant so I'm not implementing it right now)\n return Operations[i];\n }\n}\n</code></pre>\n<p>And then your main loop looks roughly like:</p>\n<pre><code> static void Main(string[] args)\n {\n Calculator c = new Calculator();\n c.AddOperation(new AdditionOperation);\n\n while (true)\n {\n MathOperation operation = c.SelectOperation();\n operation.Run();\n }\n }\n</code></pre>\n<p>Repeating the disclaimer again, this program is larger and more complex than your simple program. But it contains patterns that are very important for the scalability of your code, which is why I suggest you read through my code examples and try to implement it yourself in order to accommodate yourself to those practices of OOP (which is [currently] ruling paradigm in C#)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T15:58:51.077",
"Id": "494972",
"Score": "0",
"body": "Hey really appreciate the response. Can definitely see the benefit of a more object-oriented approach and will absolutely try to implement these techniques in my current and future projects."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T20:42:30.770",
"Id": "251357",
"ParentId": "251344",
"Score": "11"
}
},
{
"body": "<p>logically, it's fine. Your coding is better than average beginner. You have used the proper way to validate and parse integers, this is something most of beginners lake, even some advanced programmers still parse without validations, which is a real issue when it comes to coding. Why? simply because it's simple validation that would avoid <code>annoying exceptions</code>.</p>\n<p>My notes will just give you more thoughts on how things could be done in different ways according to what you've already learned (I'll try to avoid given advanced techniques, to strengthen your current level and to focus on what you have).</p>\n<p><strong>Access Modifiers</strong></p>\n<p>You need to use access modifiers more often, and also don't misplace them. For a better code readability purpose.<br />\nSo this :</p>\n<pre><code>static double Powers(double number, double power)\n</code></pre>\n<p>should be :</p>\n<pre><code>private static double Powers(double number, double power)\n</code></pre>\n<p>And this :</p>\n<pre><code>static public void FirstInput(int input)\n</code></pre>\n<p>Should be :</p>\n<pre><code>public static void FirstInput(int input)\n</code></pre>\n<p><strong>Comments</strong></p>\n<p>You need to use the proper commenting on your code. use <code>summary</code> comments for methods, classes, properties, and structs. The rest you can use single comment line.</p>\n<p>So this :</p>\n<pre><code>public static double Powers(double number, double power) // Raises the first number to the power of the second number and returns the result.\n</code></pre>\n<p>Should be :</p>\n<pre><code>/// <summary>\n/// Raises the first number to the power of the second number and returns the result.\n/// </summary>\n/// <param name="number"></param>\n/// <param name="power"></param>\n/// <returns></returns>\npublic static double Powers(double number, double power)\n</code></pre>\n<p>Also, when you have a long comment, like this :</p>\n<pre><code>FirstInput(inputInt); // Calls a procedure which gets the user's first number, the message depending on the user's previous input.\n</code></pre>\n<p>The comment is longer than the action itself. Just do this instead :</p>\n<pre><code>// Calls a procedure which gets the user's first number,\n// the message depending on the user's previous input.\nFirstInput(inputInt); \n</code></pre>\n<p>Why? you should consider that not every screen is large enough to show all the code at once. So, it would be a good idea to simplify the comments and shorten them to be readable and more helpful.</p>\n<p><strong>Conditions and Operators</strong></p>\n<p>when dealing with conditions, you must consider readability and simplicity above all things. This would help you to handle even complex conditions with ease, because you'll always try to make it simple and readable. For instance, <code>loopInt</code> is not used probably, because this line :</p>\n<pre><code>if (inputInt == 0) // Input of 0 exits the program\n{\n Console.WriteLine("Goodbye!");\n loopInt = true;\n break;\n}\n</code></pre>\n<p>the issue here is that <code>loopInt = true;</code> is meaningless because of <code>break;</code>. When you break the loop. So, this <code>loopInt == false</code> is not well used, because you can replace it with <code>while (true)</code> and it would work as expected !</p>\n<p>Let's check this another condition :</p>\n<pre><code>while((!int.TryParse(input, out inputInt)) | (!(inputInt>=0 && inputInt<=6))) {...}\n</code></pre>\n<p>It seems a bit unclear, The issue in this is that whenever you have multiple conditions that you need to invert, either invert the condition itself, or group them in parentheses then invert it. which would be more clear to the naked eye. The best practice is to invert the condition itself if you have control on it, if not, then invert the part you can control to the same result of the other part that you don't have control on (like int.TryParse`). So, to make it more practical, we can apply that in your condition above to be like :</p>\n<pre><code>while(!int.TryParse(input, out inputInt) || (inputInt < 0 || inputInt > 6)) {...}\n</code></pre>\n<p>Also, don't use single <code>|</code> operator, as the difference between <code>|</code> and <code>||</code> is that the single <code>|</code> would check each condition even if the first one is true. It's rarely used, because it comes with some performance cost, but it has it has its own cases. However, in most cases along with yours, it's not necessary. So, stick with the usual double operator <code>||</code> for OR and <code>&&</code> for AND.</p>\n<p><strong>Object-Oriented-Programming (OOP)</strong></p>\n<p><code>C#</code> is an <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/tutorials/intro-to-csharp/object-oriented-programming\" rel=\"noreferrer\">OOP programming language</a>, so you should always try to apply that in your coding. Not only to <code>C#</code> but also to any other <code>OOP</code> programming language.</p>\n<p>One way to apply that to your current code is applying <code>Encapsulation</code> and <code>Reusability</code> principles. To do that, you can rethink of your application and divide it into layers based on your code purpose. Currently, your code can be divided into (calculator) and (user interface). The <code>calculator</code> would contain all code that used to calculate the values such as <code>Add, Subtract ..etc.</code>. The <code>user interface</code> is where you handle user interactivity. We can then separate them in separate classes, and then use them. If you see any repetitive code, just move them into a method and reuse them (applying another principle <code>Don't Repeat Yourself</code> AKA <code>DRY</code> principle). Though, you could apply more principles but for simplicity sake I prefer to avoid the rest.</p>\n<p>So, what we need to do, is to gather all the needed logic under one roof, then modify them to be easy to expand if needed. For instance, if you need to add a new option, on your current work, you would add a new method then you would do several modifications on your code to include the new method. So, this has to be solved. We need only to add a method and just modify one thing, the rest is auto!. We can can take advantage of <code>enum</code> or <code>Dictionary<int, string></code> to do that. So, first we need the class as following :</p>\n<pre><code>public class Calculator\n{\n /// <summary>\n /// Raises the first number to the power of the second number and returns the result.\n /// </summary>\n /// <param name="number"></param>\n /// <param name="power"></param>\n /// <returns></returns>\n public double Powers(double baseNumber, double exponent) \n {\n return Math.Pow(baseNumber , exponent);\n }\n\n /// <summary>\n /// Adds together both numbers and returns the result.\n /// </summary>\n /// <param name="number"></param>\n /// <param name="number2"></param>\n /// <returns></returns>\n public double Add(double leftHand , double rightHand)\n {\n return leftHand + rightHand;\n }\n\n /// <summary>\n /// Subtracts the second number from the first number and returns the result.\n /// </summary>\n /// <param name="number"></param>\n /// <param name="number2"></param>\n /// <returns></returns>\n public double Subtract(double leftHand , double rightHand) \n {\n return leftHand - rightHand;\n }\n\n /// <summary>\n /// Multiplies together both numbers and returns the result.\n /// </summary>\n /// <param name="number"></param>\n /// <param name="number2"></param>\n /// <returns></returns>\n public double Multiply(double leftHand , double rightHand) \n {\n return leftHand * rightHand;\n }\n\n /// <summary>\n /// Divides the first number by the second number and returns the result.\n /// </summary>\n /// <param name="number"></param>\n /// <param name="number2"></param>\n /// <returns></returns>\n public double Divide(double leftHand , double rightHand) \n {\n return leftHand / rightHand;\n }\n\n /// <summary>\n /// Returns the logarithm of base first number and argument second number.\n /// </summary>\n /// <param name="number"></param>\n /// <param name="number2"></param>\n /// <returns></returns>\n public double Logarithm(double number , double nBase)\n {\n return Math.Log(number, nBase);\n }\n\n\n}\n</code></pre>\n<p>Note the comments and the names of the arguments. All of which, gives you a better view of the code.</p>\n<p>Now, we can take advantage of <code>enum</code>. We will use it to describe the functions and have a better readability:</p>\n<pre><code>public enum CalculatorOption\n{\n Undefined = -1, // in case of invalid inputs\n Exit = 0,\n Addition = 1,\n Subtraction = 2,\n Multiplication = 3,\n Division = 4,\n Power = 5,\n Logarithm = 6\n}\n</code></pre>\n<p>Now, all we need is two methods, one to parse string as enum and second one is to get these options as string.</p>\n<p>For parsing we can do this :</p>\n<pre><code>public bool TryParseOption(string option, out CalculatorOption result)\n{\n result = CalculatorOption.Undefined;\n\n if(int.TryParse(option, out int resultInt))\n {\n if(Enum.IsDefined(typeof(CalculatorOption) , resultInt))\n {\n result = (CalculatorOption) resultInt;\n return true;\n }\n }\n else\n {\n return Enum.TryParse<CalculatorOption>(option, true, out result);\n }\n\n return false;\n}\n</code></pre>\n<p>Here I gave the option to parse either by an <code>int</code> or <code>string</code> which means, you can either pass the value or the name of the enum. Example,</p>\n<pre><code>// Let's say we need subtraction\n\nCalculatorOption result1; \nCalculatorOption result2; \n\nvar isValidByValue = TryParseOption("2", out CalculatorOption result1);\nvar isValidByName = TryParseOption("Subtraction", out CalculatorOption result2);\n\nConsole.WriteLine(result1 == result2); // True\n</code></pre>\n<p>Now, we need to list the <code>CalculatorOption</code> values, we will use <code>Linq</code> to do that (some <code>Linq</code> won't hurt though, it's a good way of learning).</p>\n<pre><code>public string GetOptionsAsString()\n{\n var options = Enum.GetValues(typeof(CalculatorOption))\n .Cast<CalculatorOption>()\n .Where(x=> x != CalculatorOption.Undefined)\n .Select(x=> $"{(int)x}. {x}");\n\n return string.Join(Environment.NewLine , options);\n}\n</code></pre>\n<p>What is happening above is that we've accessed the <code>enum</code> and get all members under that <code>enum</code>, excluded <code>Undefined</code> from the list, because it's going to be used for the application not the user. Then, we iterate over each element in the enumeration using <code>Select</code> to convert it to string. Finally, we join these elements using <code>string.Join</code> into one string to be presented to the user.</p>\n<p>Finally, we need a method to calculate based on the option, So we can add the following method into the <code>Calculator</code>:</p>\n<pre><code>public double Calculate(CalculatorOption option, double firstNumber , double secondNumber)\n{\n switch(option)\n {\n case CalculatorOption.Addition:\n return Add(firstNumber , secondNumber);\n case CalculatorOption.Subtraction:\n return Subtract(firstNumber , secondNumber);\n case CalculatorOption.Multiplication:\n return Multiply(firstNumber , secondNumber);\n case CalculatorOption.Division:\n return Divide(firstNumber , secondNumber);\n case CalculatorOption.Power:\n return Powers(firstNumber , secondNumber);\n case CalculatorOption.Logarithm:\n return Logarithm(firstNumber , secondNumber);\n default:\n return 0;\n }\n}\n</code></pre>\n<p>Now, you only need to change your <code>Program</code> class to include the changes as following:</p>\n<pre><code>public class Program\n{\n private static readonly Calculator _calculator = new Calculator();\n\n static void Main(string[] args)\n {\n\n Console.WriteLine("Hello World!");\n\n\n while(true)\n {\n PrintOptions();\n\n var inputOption = GetSelectedOption(Console.ReadLine());\n\n if(inputOption == CalculatorOption.Exit)\n {\n Console.WriteLine("Goodbye!");\n break;\n }\n\n Console.WriteLine("Enter the first number: ");\n\n var firstInput = TryParseInput(Console.ReadLine());\n\n Console.WriteLine("Enter the second number: ");\n\n var secondInput = TryParseInput(Console.ReadLine());\n\n var result = _calculator.Calculate(inputOption , firstInput , secondInput);\n\n Console.WriteLine();\n Console.WriteLine($"Result = {result}");\n }\n\n Console.ReadLine();\n }\n\n\n private static void PrintOptions()\n {\n Console.WriteLine();\n Console.WriteLine("-------------------------------------");\n Console.WriteLine("Choose one of the following options: ");\n Console.WriteLine(_calculator.GetOptionsAsString());\n Console.WriteLine("-------------------------------------");\n }\n\n private static double TryParseInput(string input)\n {\n double result;\n\n while(!double.TryParse(input , out result))\n {\n Console.WriteLine("ERROR: Invalid Input");\n Console.WriteLine("Please enter a valid integer");\n input = Console.ReadLine();\n }\n\n return result;\n }\n\n private static CalculatorOption GetSelectedOption(string input)\n {\n CalculatorOption result;\n\n while(!_calculator.TryParseOption(input , out result) || result == CalculatorOption.Undefined)\n {\n Console.WriteLine("ERROR: Invalid Input");\n PrintOptions();\n input = Console.ReadLine();\n }\n\n return result;\n }\n\n}\n</code></pre>\n<p>Now, let's say you want to add <code>Max</code> function to the list, all you need to do is to add <code>Max = 7</code> to the <code>enum</code> and add the method, then adjust <code>Calculate</code> method to include the new method. This would be it.</p>\n<p>As I mentioned, I've tried to avoid advanced techniques, which you'll learn in the future, however, for better expandability you'll need to learn about inheritance and design patterns along with what you've learned. To overcome the design issues.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T16:02:16.750",
"Id": "494973",
"Score": "0",
"body": "Hey thanks a lot for the response. Yeah sorry about the commenting mess, my college wants us to comment every piece of code we write but never really said how to so thanks. \nI think this might be slightly too advanced for me at the moment, but I'll definitely bear what you've said in mind and try to implement said techniques where possible."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T04:01:53.897",
"Id": "251365",
"ParentId": "251344",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "251357",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T16:00:18.550",
"Id": "251344",
"Score": "10",
"Tags": [
"c#",
"calculator"
],
"Title": "C# Intermediate Calculator Program"
}
|
251344
|
<p>What I want to do is for an example command have it defined in its own file - e.g. <strong>command.js</strong> - and the same for the other methods. I want to make a separate file for every module - for example "command.js", "vanish.js" and I can not think of a way to call the methods without making a big switch statement in a file where I would require all the "modules".</p>
<p>This is how I do it currently:</p>
<pre><code>const client = require('../../../src/bot');
const logger = require('../../../config/logger');
const {isCommand} = require('../../../helpers/checkCommand');
const {addCommand, deleteCommand, updateCommand} = require('../../../db/commandFunctions')
const isAuthorized = require('../isAuthorized');
const builtInCmdHelpers = require('../builtInCommandHelpers');
const USER_MODULES = 'everyone';
const MOD_MODULES = 'moderator';
const executeBuiltInCommand = async ({channel, args}, userstate) => {
const isSubArg = await isCommandSubArg(args[1]);
if(isSubArg) await builtInCmdHelpers[args[1]].apply(null, [{channel, args}, userstate]);
};
const command = async ({channel, args}, userstate) => {
const canExecute = await isAuthorized(channel, userstate.badges, MOD_MODULES);
if(canExecute) await executeBuiltInCommand({channel, args}, userstate);
};
const vanish = async ({channel}, {username}) => {
const canExecute = await isAuthorized(channel, username, USER_MODULES);
if(canExecute) {
client.timeout(channel, username, 1, "VANISH")
.catch((err) => {
logger.error(err);
});
}
};
module.exports = {
command,
vanish,
};
</code></pre>
<p>This is how i execute the commands currently:</p>
<pre><code>const executeBuiltIn = async ({channel, args}, userstate) => {
await builtin[args[0]].apply(null, [{channel, args}, userstate]);
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T13:02:13.400",
"Id": "495212",
"Score": "0",
"body": "Do you mean that you want to put each function in a separate file? E.g. one for `add`, one for `remove` , one for `edit`, etc.?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T13:08:13.557",
"Id": "495213",
"Score": "0",
"body": "i mean a custom file for \"command\" and \"vanish\" i thought of using a index file where i would import the files command.js and vanish.js but when i did that it did not work. I moved add, remove, edit and show already to an own file."
}
] |
[
{
"body": "<h2>Separate modules</h2>\n<p>You didn’t specify a file name for the code in the first block- is it something like <em>builtin.js</em>?</p>\n<p>The code in the first block should be divisible into two files- one for <code>command</code> with <code>executeBuiltInCommand</code> and <code>MOD_MODULES</code>, and the other for <code>vanish</code> with <code>USER_MODULES</code>. They could be combined to a single module to replace the current file in the first block - what I presume is <em>builtin.js</em>.</p>\n<h2>Simplify <code>.apply()</code> syntax</h2>\n<p>The ES6 feature <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"nofollow noreferrer\">spread syntax</a> can be used to replace calls to <code>.apply()</code>.</p>\n<p>For example:</p>\n<blockquote>\n<pre class=\"lang-javascript prettyprint-override\"><code>if(isSubArg) await builtInCmdHelpers[args[1]].apply(null, [{channel,\nargs}, userstate]);\n</code></pre>\n</blockquote>\n<p>can be simplified to:</p>\n<pre><code>if(isSubArg) await builtInCmdHelpers[args[1]](...[{channel, args}, userstate]);\n</code></pre>\n<p>However, since there is a fixed length on that array of arguments, the method can be called directly:</p>\n<pre><code>if(isSubArg) await builtInCmdHelpers[args[1]]({channel, args}, userstate);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-16T04:35:02.460",
"Id": "502487",
"Score": "0",
"body": "I'm not sure .apply()/spread needed to be used in the first place. Couldn't it just be `builtInCmdHelpers[args[1]]({channel, args}, userstate)`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-20T08:40:16.583",
"Id": "502948",
"Score": "0",
"body": "Yes- that seems to be sufficient given that the array of args is not very variadic. Thanks for pointing that out!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-06T22:30:13.323",
"Id": "251736",
"ParentId": "251345",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T16:06:31.340",
"Id": "251345",
"Score": "7",
"Tags": [
"javascript",
"performance",
"node.js",
"delegates",
"ecmascript-8"
],
"Title": "Way to delegate command to methods in different files"
}
|
251345
|
<p>I tried implementing a radix tree using C language in order to get the auto complete suggestions of a dictionary. What are the improvements that I can do here? Also, is there any better way of doing this?</p>
<p>The text file I used has the following format</p>
<pre><code>a
at
along
bat
cat
</code></pre>
<p>Here's my implementation.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
// define a maximum length for the string.
#define MAX_LEN (200)
// define the alphabet size for english.
#define ALPHABET_SIZE (26)
// linked String structure
typedef struct LinkedString {
// linked string node contains a char.
char character;
struct LinkedString *next;
} LinkedString;
// TrieNode structure
typedef struct TrieNode {
struct TrieNode *children[ALPHABET_SIZE];
// linked string to place the str inside the trie node.
LinkedString *LinkedString;
// boolean to check for leaf_nodes
bool is_leaf;
} TrieNode;
/* function signatures */
// create a trie Node.
TrieNode *createNode();
// appends to the string[initial: end] and return a linked string.
LinkedString *appendLinkedString(char *str, int inital, int end);
// break the linked string and create a node with the breaked string and returns intial.
TrieNode *breakLinkedString(TrieNode *previousNode, TrieNode *node, LinkedString *breakPoint);
// insert a str to the trie node.
void insert(TrieNode *root, char *str);
// returns the pointer if found the str else returns NULL
TrieNode *searchNodes(TrieNode *root, char *str);
// convert a string in to charactors
int str_to_char(LinkedString *begin, char *str, int initial);
// print suggestions for the prefix.
void printSuggetions(TrieNode *suggestedNode, char str[], int Size);
// create a linked string with a given char.
LinkedString *createString(char Char);
// node count to get the memory used.
int node_count = 0;
// link string count to get the memory.
int link_string_node_count = 0;
int main(){
char input[MAX_LEN];
char str[MAX_LEN];
char lowerCase[MAX_LEN];
// read the file
TrieNode *root = createNode();
// file name of the wordlist
char *fileName = "wordlist70000.txt";
// create a file pointer to read the file
FILE *fptr = fopen(fileName, "r");
int j = 0;
// elapsed time ro insert all entries ti the trie
clock_t start_time = clock();
// read the file and insert words into the tire
while (fgets(str, MAX_LEN - 1, fptr))
{
j = 0;
// check whether the character is in alphabet
for (int i = 0; i < MAX_LEN; ++i){
if (((str[i] > 64) && (str[i] < 91)) || (str[i] > 96) && (str[i] < 123)) {
// converts the characters into lowercase
lowerCase[j] = tolower(str[i]);
j++;
}
if (str[i] == '\n'|| str[i] == '\0') {
break;
}
}
// configure the terminating character
lowerCase[j] = 0;
// insert into the trie
insert(root, lowerCase);
}
clock_t end = clock();
// end the timer
double elapsedtime = (double)(end - start_time) / CLOCKS_PER_SEC;
printf("\nElapsed time for insert: %f s\n", elapsedtime);
while (true){
// prompt the user to inputs
printf("Enter the prefix['0' for quit!] :\n");
// get the input
scanf("%s", input);
// copy the input to the str
strcpy(str, input);
//if the exit condition is met
if (strcmp(str, "0") == 0){
printf("Quit! \n");
break;
}
j = 0;
// check whether the character is in alphabet
for (int i = 0; i < MAX_LEN; ++i){
if (((str[i] > 64) && (str[i] < 91)) || (str[i] > 96) && (str[i] < 123)) {
// converts the characters into lowercase
lowerCase[j] = tolower(str[i]);
j++;
}
if (str[i] == '\n' || str[i] == '\0') {
break;
}
}
// configure the terminating character
lowerCase[j] = 0;
strcpy(str, lowerCase);
// star the time to track the elapsed time
clock_t start_time = clock();
// check for the prefix
TrieNode *suggestedNode = searchNodes(root, str);
if (!suggestedNode) {
// if prefix not found
printf("Prefix Not Found!\n\n");
continue;
}
printf("\n ***************** SUGGETIONS ****************** \n");
printSuggetions(suggestedNode, str, strlen(str));
// end the timer
clock_t end = clock();
// calculate the elapse time
double elapsedtime = (double)(end - start_time) / CLOCKS_PER_SEC;
// print the elapsed time and memory used.
printf("\nElapsed time : %f s\n", elapsedtime);
int count1 = (int)sizeof(*(root)) * node_count;
int count2 = (int)sizeof(LinkedString) * link_string_node_count;
printf("Memory used : %d Bytes\n\n", count1 + count2);
}
return 0;
}
TrieNode *createNode() {
node_count++;
// allocate space for new trie node.
TrieNode *newtrieNode = (TrieNode *)malloc(sizeof(TrieNode));
// initialize the linked string with NULL
newtrieNode->LinkedString = NULL;
// make it as not a leaf
newtrieNode->is_leaf = false;
int i;
for (i = 0; i < ALPHABET_SIZE; ++i) {
// make all the chiledrens null.
newtrieNode->children[i] = NULL;
}
return newtrieNode;
}
LinkedString *createString(char Char) {
link_string_node_count++;
// allocate space for a new string dynamically.
LinkedString *newString = (LinkedString *)malloc(sizeof(LinkedString));
// put the char into its character
newString->character = Char;
// make the next pointer null.
newString->next = NULL;
// return the new string.
return newString;
}
LinkedString *appendLinkedString(char *str, int inital, int end) {
int i;
// create a pointers to linked strings.
LinkedString *current = createString(str[inital]);
LinkedString *newString = NULL;
LinkedString *string = current;
// go from initial position to end position
for (i = inital + 1; i < end; ++i) {
// crate a new string with char index i or str
newString = createString(str[i]);
// make the next pointer point to new string.
current->next = newString;
// go through the string
current = current->next;
}
// make the last pointer at the end.
current = NULL;
return string;
}
TrieNode *breakLinkedString(TrieNode *previousNode, TrieNode *node, LinkedString *breakPoint) {
// create a new trie node pointer.
TrieNode *newNode = createNode();
// create a new string beginning next to the break point.
LinkedString *newString = breakPoint->next;
breakPoint->next = NULL;
// convert char to index
int index1 = (newString->character) &mdash; 'a';
newNode->LinkedString = node->LinkedString;
node->LinkedString = newString;
newNode->children[index1] = node;
int index2 = (newNode->LinkedString->character) - 'a';
// pointer the new node to the relevent index of the parent node.
previousNode->children[index2] = newNode;
// return the newnode.
return newNode;
}
void insert(TrieNode *root, char *str) {
// get the length of the str
int lastLetterIndex = strlen(str);
int i = 0, charIndex;
// create trie nodes and likedlist pointers to track
// previous current and next pointer nodes.
TrieNode *currentNode = root, *previousNode = NULL;
TrieNode *newNode = NULL;
LinkedString *currentLetter, *previousLetter = NULL;
currentLetter = currentNode -> LinkedString;
// go till the last leter of the string.
while (i < lastLetterIndex) {
charIndex = (str[i]) - 'a';
// if current letter is null
if (currentLetter == NULL) {
// if the trie is empty.
if (currentNode->children[charIndex] == NULL) {
// create a new node.
newNode = createNode();
// append the string[i:lastLetterIndex] point to the new nodes linked
newNode->LinkedString = appendLinkedString(str, i, lastLetterIndex);
newNode->is_leaf = true;
currentNode->children[charIndex] = newNode;
break;
} else { // if it is the first node.
// make the previous node pointing to the current node.
previousNode = currentNode;
currentNode = currentNode->children[charIndex];
previousLetter = currentNode->LinkedString;
currentLetter = currentNode->LinkedString->next;
}
} else {
if (currentLetter->character != str[i]) {
// make the current node pointing to the breakedLinkedString.
currentNode = breakLinkedString(previousNode, currentNode, previousLetter);
// create a new node.
newNode = createNode();
// append the link string to the newNodes LinkedString.
newNode->LinkedString = appendLinkedString(str, i, lastLetterIndex);
// make new node a leaf node
newNode->is_leaf = true;
// put newNode as a child of a current node.
currentNode->children[charIndex] = newNode;
break;
} else {
previousLetter = currentLetter;
currentLetter = currentLetter->next;
}
}
i++;
}
}
TrieNode *searchNodes(TrieNode *root, char *str) {
// get the lastIndex of the str
int lastIndex = strlen(str);
int i = 0, charIndex;
TrieNode *currentNode = root;
LinkedString *currentLetter = currentNode->LinkedString;
while (i < lastIndex) {
// get the index from the char Index.
charIndex = str[i] - 'a';
// if current letter is null.
if (currentLetter == NULL) {
// point the relevent index to the currentNode.
currentNode = currentNode->children[charIndex];
// if the word is not found. Then the current node
// and the currentLetter is NULL.
if (!currentNode) return NULL;
// make the currentLeter pointing to the linked strings next letter.
currentLetter = currentNode->LinkedString->next;
} else {
// go to the next letter.
currentLetter = currentLetter->next;
}
i++;
}
// go untilll the current letter is found null
while (currentLetter != NULL) {
// go till the end of the character.
str[lastIndex] = currentLetter->character;
currentLetter = currentLetter->next;
lastIndex++;
}
// make the last index pointing to the terminating character
str[lastIndex] = '\0';
return currentNode;
}
int str_to_char(LinkedString *begin, char *str, int initial) {
int newSize = initial;
LinkedString *currentLetter = begin;
// go while current lettter is not null
while (currentLetter != NULL) {
// put the char by char in str
str[newSize] = currentLetter->character;
// goto the next letter
currentLetter = currentLetter->next;
newSize++;
}
// set the terminating character.
str[newSize] = '\0';
return newSize - 1;
}
void printSuggetions(TrieNode *suggestedNode, char str[], int Size) {
// create a poiter to the suggested node
TrieNode *currentNode = suggestedNode;
int i, j, newSize;
if (currentNode->is_leaf){
// go till the word_size
for (j = 0; j < Size; ++j){
// print the uppercased char
printf("%c", toupper(str[j]));
}
// print the endline
printf("\n");
}
// go through each children node.
for (i = 0; i < ALPHABET_SIZE; ++i) {
// if each child is not null
if (currentNode->children[i] != NULL) {
// break down the string and get the characters
newSize = str_to_char(currentNode->children[i]->LinkedString, str, Size);
// print the suggestion.
printSuggetions(currentNode->children[i], str, newSize + 1);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<h2>Parenthesized macros</h2>\n<p>The parens around</p>\n<pre><code>(200)\n</code></pre>\n<p>aren't strictly necessary. Most of the time that we see these, it's because you want to enforce order of operations at the calling site, but there are no operations here.</p>\n<h2>Statics</h2>\n<p>This is a one-file (one-translation-unit) program, so all of your methods except <code>main</code> should be marked <code>static</code>.</p>\n<h2>Const</h2>\n<p>It's important that <code>fileName</code> be marked <code>const</code>.</p>\n<h2>Pre-declaration</h2>\n<p>You're using C99 or later due to your placement of <code>int j</code>. That means that you can actually narrow its scope and move the declaration into the loop itself:</p>\n<pre><code>// read the file and insert words into the tire\nwhile (fgets(str, MAX_LEN - 1, fptr))\n{\n int j = 0;\n</code></pre>\n<h2>Encoding and literals</h2>\n<p>Numeric literals for characters is generally not a good idea (e.g. 64 for <code>@</code>). Just use the <code>'@'</code> character literal instead. Reasons include legibility, maintainability, and easier transition to other character sets than ASCII if you use alternate compiler flags.</p>\n<p>Also, rather than <code>str[i] > '@'</code>, it would be much clearer to write <code>str[i] >= 'A'</code>.</p>\n<h2>Else</h2>\n<pre><code> if (str[i] == '\\n'|| str[i] == '\\0') {\n</code></pre>\n<p>should be an <code>else if</code> since those conditions are entirely disjoint from the ones above. Or you can move the null-or-newline check to be the first condition, in which case the second one wouldn't benefit from an <code>else</code> due to the <code>break</code>.</p>\n<h2>Factoring out functions</h2>\n<p>The loop after</p>\n<pre><code> // check whether the character is in alphabet\n</code></pre>\n<p>is copy-and-pasted. Move this into a function for reuse.</p>\n<h2>Mdash instead of hyphen?</h2>\n<p>There's an encoding quirk:</p>\n<pre><code>int index1 = (newString->character) &mdash; 'a';\n</code></pre>\n<p>You're probably going to want to replace <code>&mdash</code> with a plain hyphen.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T00:48:44.217",
"Id": "494873",
"Score": "0",
"body": "I think it would have been good if you had explained why `fileName` should be declared as const. Otherwise good review."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T18:26:55.133",
"Id": "251350",
"ParentId": "251347",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "251350",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T16:49:53.187",
"Id": "251347",
"Score": "8",
"Tags": [
"c",
"linked-list",
"c++17",
"trie",
"autocomplete"
],
"Title": "Radix Tree Implementation in c"
}
|
251347
|
<p>Hi I using Vue 3 with Typescript. In my code I have variable:</p>
<pre><code>const editItem = ref<{
id: number
title: string
author: string
}>({
id: 0,
title: '',
author: '',
})
</code></pre>
<p>This variable I update using this method:</p>
<pre><code>const updateItem = (data: {
id: number
title: string
author: string
}) => {
const { title, author } = data
getBooks.value = getBooks.value.map(book => ({
...book,
title: editItem.value.id === book.id ? title : book.title,
author: editItem.value.id === book.id ? author : book.author,
}))
}
</code></pre>
<p>Did this code is correctly by typescript? I readed that I should using reactive instead of ref to object, but reactive value can not be <code>empty</code></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T12:21:21.243",
"Id": "494931",
"Score": "0",
"body": "What is `getBooks`? Does the code work as you expect it to do?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T19:37:31.387",
"Id": "251352",
"Score": "2",
"Tags": [
"typescript",
"vue.js"
],
"Title": "Vue 3 composition API typescript using ref in Object"
}
|
251352
|
<p>I'm learning swift programming and i built a music trivia app for iOS that use firebase real time database.
I have a function that before the game start get the number of record for each category of the game and update a class variable that is a tuple called records.</p>
<pre><code>var records = (classical: 0, mix: 0, casual: 0)
private func getNumberOfRecords(category: String) {
var ref: DatabaseReference!
ref = Database.database().reference().child(category)
ref.observeSingleEvent(of: .value) { snapshot in
let enumerator = snapshot.children
while((enumerator.nextObject() as? DataSnapshot) != nil) {
switch category {
case "casual":
records.casual += 1
case "classical":
records.classical += 1
case "mix":
records.mix += 1
default: print("Error loading record from category \(category)")
}
}
}
}
</code></pre>
<p>Here is how I call the function and because it's asynchronous the response I receive from firebase and I need to know the number of records before call another function that will load the game data from the database i use DispatchQueue and wait 3 seconds.</p>
<pre><code>getNumberOfRecords(category: "classical")
getNumberOfRecords(category: "casual")
getNumberOfRecords(category: "mix")
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
loadDataFromDB(records: records.classical, category: "classical")
loadDataFromDB(records: records.casual, category: "casual")
loadDataFromDB(records: records.mix, category: "mix")
}
</code></pre>
<p>Now this is working but it's pretty ugly, especially using the function getNumberOfRecords to update the global tuple records. I don't know how can I rewrite this because if i make getNumberOfRecords return a tuple rather than update the global one is always 0 when i pass it as parameter of the function loadDataFromDB inside the DispatchQueue.</p>
<p>Thanks in advance to anyone will have time to read this.</p>
|
[] |
[
{
"body": "<p>A typical way to write an asynchronous function is to have it take a function as an argument that will be called with the results when they are ready. Such a function is often called a completion handler.</p>\n<pre><code>private func getNumberOfRecords(category: String, completion: (Int) -> Void) { \n ...\n default: print("Error loading record from category \\(category)")\n }\n }\n }\n completion(records.count)\n}\n</code></pre>\n<p>Then at the call site you can write:</p>\n<pre><code>getNumberOfRecords(category: "classical", completion: { count in ... })\n</code></pre>\n<p>or better written with trailing-closure syntax:</p>\n<pre><code>getNumberOfRecords(category: "classical") { count in ... }\n</code></pre>\n<p>You still have the problem of three asynchronous things, and instead of chaining them together, you can also avoid looping over the data 3 times, you can loop over the data once and remember the counts for each item, using a dictionary:</p>\n<pre><code>private func getNumberOfRecords(completion: ([String: Int] -> Void)) {\n var categoryCounts: [String: Int] = [:]\n\n {\n ... loop over the data here and instead of switch category ...\n categoryCounts[category] = (categoryCounts[category] ?? 0) + 1\n }\n\n completion(categoryCounts)\n}\n\ngetNumberOfRecords { categoryCounts in \n for (category, count) in categoryCounts {\n loadDataFromDB(records: count, category: category) \n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-06T19:54:57.477",
"Id": "495754",
"Score": "0",
"body": "Thank you! the completion handler is exactly what I was looking for. I was trying to solve this using promises but I think it's more important to learn how to write an asynchronous function without any external library first. Again thanks for your time!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T15:26:57.053",
"Id": "251548",
"ParentId": "251353",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "251548",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T19:54:01.683",
"Id": "251353",
"Score": "3",
"Tags": [
"swift",
"ios",
"firebase"
],
"Title": "Swift iOS rewrite a function that use Firebase database without updating a global variable"
}
|
251353
|
<p>I have an input checker class with some RegExes, and I have converted some of the loops to lambdas. Am I doing it right? They seem to work fine, but I'm new to Lambdas. Does this offer a performance benefit over the commented implementation? Should I try implementing the first one as a lambda, and if so, how? Thanks in advance!</p>
<pre><code>public static class DataChecker
{
public static bool IsGameInputDataValid(string[] dataFile)
{
if (dataFile.Length < 5)
{
return false;
}
var regexList = new List<Regex>();
regexList.Add(new Regex("^\\d\\s\\d$"));
regexList.Add(new Regex("^(\\d,\\d )*(\\d,\\d)$"));
regexList.Add(new Regex("^\\d\\s\\d$"));
regexList.Add(new Regex("^\\d \\d [NESW]{1}$"));
regexList.Add(new Regex("^[RLM]{1}( [RLM]{1})*$"));
//cant figure this one out as lambda... but should it even be converted for performance reasons?
for (int i = 0; i < 4; i++)
{
if (!regexList[i].IsMatch(dataFile[i]))
{
return false;
}
}
var listOfMoves = dataFile.Select(x => x).Skip(4).ToList();
//instead of:
// for (int i = 4; i<countOfLinesInInputFile; i++)
// {
// listOfMoves.Add(lines[i]);
// }
var areaAnyMoveSequencesInvalid =
listOfMoves.Select(x => regexList[4].IsMatch(x)).ToList()
.Any(y => y == false);
if (areaAnyMoveSequencesInvalid)
{
return false;
}
// instead of:
// foreach (var line in listOfMoves)
// {
// if (!regexList[4].IsMatch(line))
// {
// return false;
// }
// }
return true;
}
}
</code></pre>
<p>edit: Originally I wanted the question to only focus on the lambdas, but I got a lot of responses for the RegExes as well. Therefore I'll add the missing parts to make sense of that. It's a turtle-moving game in 2-dimensional x,y coordinates map.</p>
<p>Sample data file:</p>
<pre><code>5 4
1,1 1,3 3,3
4 2
0 1 N
R M L M M
R M M M
M R M M M M
M R M M
M M M
</code></pre>
<p>Rules:
The first line should define the board size
• The second line should contain a list of mines (i.e. list of co-ordinates separated by a space)
• The third line of the file should contain the exit point.
• The fourth line of the file should contain the starting position of the turtle.
• The fifth line to the end of the file should contain a series of moves.</p>
<p>Where:
R: Rotate right
L: Rotate left
M: Move
N,E,S,W: cardinal directions</p>
<p>I've updated the original with d+ instead of d, to allow for multiple digit coordinates:</p>
<pre><code> regexList.Add(new Regex("^\\d+\\s\\d+$"));
regexList.Add(new Regex("^(\\d+,\\d+ )*(\\d+,\\d+)$|^$"));
regexList.Add(new Regex("^\\d+\\s\\d+$"));
regexList.Add(new Regex("^\\d+ \\d+ [NESW]{1}$"));
regexList.Add(new Regex("^[RLM]{1}( [RLM]{1})*$"));
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T23:36:07.197",
"Id": "494786",
"Score": "1",
"body": "Welcome to the Code Review Site. The question title should tell us what the code does rather than what your concerns about the code are. It would also be helpful if there was a short paragraph explaining what the code does, this helps us provide a better review and better suggestions. Please read [How do I ask a good question](https://codereview.stackexchange.com/help/how-to-ask), it can give you some hints on the title and other good tips for getting up votes on your question. You might also want to remove any commented out code because that type of code makes us question if the code is ready"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T05:28:46.253",
"Id": "494792",
"Score": "0",
"body": "perhaps given us a sample of `dataFile` and explaination on what the expressions do and what data do you consider `Valid`. This would give us some idea on your question and we can help you with that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T06:34:33.590",
"Id": "495015",
"Score": "0",
"body": "Please don't ignore comments that advise you to improve your post in any way, @pacmaninbw suggested something because those are the traits of a good question. I have edited the title for you now"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T16:25:12.893",
"Id": "495397",
"Score": "0",
"body": "Hi! Sorry for getting back to the thread a little late and thanks so much for all the replies! The original idea was to not put the emphasis on reviewing the regexes for, but the lambdas -- I only included the regexes so you can see what I'm working with later on. However, I'll edit the post now because of the replies :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T16:28:15.740",
"Id": "495399",
"Score": "1",
"body": "Please do not update your question after you have received answers: https://codereview.stackexchange.com/help/someone-answers I've rolled back your edit. If you want to post a follow-up question, you can do so."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T16:41:30.580",
"Id": "495405",
"Score": "0",
"body": "@BCdotWEB The original post was still available after the edit, the edit only provided more information requested by the answers... I think it would be clearer for people coming to the thread with the edit approved, although true, that not necessary for the original question. However, someone also edited the original title, so now the answer to the original question is not easily findable (lambdas), because someone edited it out... I feel moderation is going too far with this one, but if you feel it's okay this way..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T16:44:22.523",
"Id": "495406",
"Score": "0",
"body": "@user3616457 I thought I saw your edit also updated some of the original code, if that isn't the case then you can re-apply your edit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T17:06:28.463",
"Id": "495409",
"Score": "0",
"body": "@BCdotWEB You are right, it did update the original RegExes, albeit in a very minor way, and not related to the main question. I've included it properly at the end now, instead of modifying the original one. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T17:26:15.197",
"Id": "495416",
"Score": "0",
"body": "You've added a lot to the question and it shows up on some monitoring tools. I don't see where you might have invalidated the answers which is what we worry about the most. It might be better in the future to ask a new question with a link to the old question."
}
] |
[
{
"body": "<h3>Disclaimer: Not a Code Reviewer</h3>\n<ul>\n<li><p>Just looking into the regular expressions here!</p>\n</li>\n<li><p>Not sure exactly what we are doing.</p>\n</li>\n<li><p>My guess is that:</p>\n</li>\n</ul>\n<p>We would probably want:</p>\n<pre><code> regexList.Add(new Regex("^(?:\\\\d,\\\\d )*(?:\\\\d,\\\\d)$"));\n</code></pre>\n<p>instead of</p>\n<pre><code> regexList.Add(new Regex("^(\\\\d,\\\\d )*(\\\\d,\\\\d)$"));\n</code></pre>\n<p>and we don't want the <code>{1}</code>:</p>\n<pre><code> regexList.Add(new Regex("^\\\\d \\\\d [NESW]$"));\n regexList.Add(new Regex("^[RLM]( [RLM])*$"));\n</code></pre>\n<p>and maybe we would want non-capturing groups here too, instead of capturing groups:</p>\n<pre><code> regexList.Add(new Regex("^\\\\d \\\\d [NESW]$"));\n regexList.Add(new Regex("^[RLM](?: [RLM])*$"));\n</code></pre>\n<p>and that'd a bit simplify the expressions.</p>\n<h3>Happy Coding! ( ˆ_ˆ )</h3>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T16:34:01.513",
"Id": "495401",
"Score": "1",
"body": "Thanks for reviewing the RegExes! :) I originally did not want to focus on the regexes much, but I have added some clarifications to the OP for them now. I agree about the non-capturing groups (According to StackOverflow, it should make a difference performance-wise (albeit small in this case)). The {1} is needed due to the rules I've just posted I believe."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T00:41:57.530",
"Id": "251362",
"ParentId": "251358",
"Score": "2"
}
},
{
"body": "<p>I would tackle this problem by not adding the last regex to the list but to have this as a separate regex. Using a little "trick" by using <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.range?view=netcore-3.1\" rel=\"nofollow noreferrer\"><code>Enumerable.Range()</code></a> you can replace the <code>for</code> with a linq expression like so</p>\n<pre><code>if (Enumerable.Range(0, 4).Any(i => !regexList[i].IsMatch(dataFile[i]))) { return false; }\n</code></pre>\n<p>After the loop you have this line</p>\n<pre><code>var listOfMoves = dataFile.Select(x => x).Skip(4).ToList(); \n</code></pre>\n<p>in which you neither need the call to <code>Select()</code> nor to <code>ToList()</code>.</p>\n<p>In the next line</p>\n<pre><code>var areaAnyMoveSequencesInvalid =\n listOfMoves.Select(x => regexList[4].IsMatch(x)).ToList()\n .Any(y => y == false); \n</code></pre>\n<p>A simple call to <code>Any()</code> would be sufficient but you could just return the value of a call to <code>All()</code> instead like shown below.</p>\n<p>If the method in question is called quite often you should consider to use compiled regex. They take a little bit more time to create them but executing them will become faster. If you take this way you should initialize the regexes in the static constructor.</p>\n<p>Summing this up will lead to</p>\n<pre><code>public static class DataChecker\n{\n static DataChecker()\n {\n regexList = new List<Regex>();\n regexList.Add(new Regex("^\\\\d\\\\s\\\\d$", RegexOptions.Compiled));\n regexList.Add(new Regex("^(\\\\d,\\\\d )*(\\\\d,\\\\d)$", RegexOptions.Compiled));\n regexList.Add(new Regex("^\\\\d\\\\s\\\\d$", RegexOptions.Compiled));\n regexList.Add(new Regex("^\\\\d \\\\d [NESW]{1}$", RegexOptions.Compiled));\n\n lastRegex = new Regex("^[RLM]{1}( [RLM]{1})*$", RegexOptions.Compiled);\n }\n private static readonly List<Regex> regexList;\n private static readonly Regex lastRegex;\n public static bool IsGameInputDataValid(string[] dataFile)\n {\n if (dataFile.Length < 5) { return false; }\n\n if (Enumerable.Range(0, 4).Any(i => !regexList[i].IsMatch(dataFile[i]))) { return false; }\n\n return dataFile.Skip(4).All(x => lastRegex.IsMatch(x));\n }\n}\n</code></pre>\n<p>Without knowing what the input looks like I can't come up with a better name for the last regex. In addition this isn't tested but should work like a charme.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T13:06:32.723",
"Id": "495054",
"Score": "0",
"body": "The first 4 Regex's are the mystery to me. The last one is a way to validate a \"move\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T16:26:49.200",
"Id": "495398",
"Score": "0",
"body": "This is exactly what I was looking for! Thanks so much! I've added a sample file and the rules for the regexes for more clarification."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T06:28:09.693",
"Id": "251455",
"ParentId": "251358",
"Score": "4"
}
},
{
"body": "<p>When working with the <code>Regex</code> pattern, you can benefit from the "<a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/verbatim\" rel=\"nofollow noreferrer\">verbatim string literal</a>" operator <code>@</code>:</p>\n<p>so that</p>\n<p><code>"^\\\\d\\\\s\\\\d$"</code> becomes <code>@"^\\d\\s\\d$"</code></p>\n<p>This is more readable and if you're using Visual Studio, you will get help from intellisense (a better coloring), when designing the pattern directly in place of <code>new Regex(pattern)</code></p>\n<hr />\n<p>Besides that, I'd go with the suggestions by Heslacher, but take it a step further:</p>\n<pre><code> public static class DataCheckerReview\n {\n static readonly List<Regex> headerPatterns;\n static readonly Regex movePattern;\n\n static DataCheckerReview()\n {\n headerPatterns = new List<Regex>\n {\n new Regex(@"^\\d\\s\\d$", RegexOptions.Compiled),\n new Regex(@"^(\\d,\\d )*(\\d,\\d)$", RegexOptions.Compiled),\n new Regex(@"^\\d\\s\\d$", RegexOptions.Compiled),\n new Regex(@"^\\d \\d [NESW]$", RegexOptions.Compiled)\n };\n\n movePattern = new Regex(@"^[RLM]( [RLM])*$", RegexOptions.Compiled);\n }\n\n static bool LinesEnough(string[] dataLines) => dataLines != null && dataLines.Length > 4;\n static bool CheckHeaders(string[] dataLines) => headerPatterns.Zip(dataLines).All(pair => pair.First.IsMatch(pair.Second));\n static bool CheckMoves(string[] dataLines) => dataLines.Skip(4).All(dl => movePattern.IsMatch(dl));\n\n public static bool IsGameInputDataValid(string[] dataLines)\n {\n return LinesEnough(dataLines) && CheckHeaders(dataLines) && CheckMoves(dataLines);\n }\n }\n</code></pre>\n<p>When initializing a list "statically" as you do, you can do it as shown above instead of calling <code>Add()</code> for each entry (You can use this approach for all objects that provides an <code>Add()</code> method and implements <code>IEnumerable</code>).\nIf you don't add or remove entries in the list, a plain array may be a better choice than a list?</p>\n<p>In <code>CheckHeaders()</code> the <code>Zip()</code> extension is used to pair each regex in the header patterns with the first four lines in the input lines. <code>Zip()</code> only pairs items in the sets for the count of items in the shortest set, so no need for <code>Take()</code> etc.</p>\n<p>By abstracting the validation of the input away in dedicated methods, you get a clean design, that is easy to maintain and the naming makes it easy to understand what each step does.</p>\n<p>The context is somewhat unclear, but just returning bool from a method that checks several properties is not very informative. I think, I'd throw a dedicated exception if a step fails or at least have some kind of logging. As a client of the method, it would be nice to know what went wrong.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T16:30:27.327",
"Id": "495400",
"Score": "1",
"body": "Thanks very much for the suggestions, sounds like some valid points there!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T07:47:40.683",
"Id": "251527",
"ParentId": "251358",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "251455",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T21:27:12.923",
"Id": "251358",
"Score": "5",
"Tags": [
"c#",
"regex",
"lambda"
],
"Title": "Regex - Input Checker Class - Lambda with two lists"
}
|
251358
|
<p>This code does parallel processing of files read from a directory. It divides the directory into 'core' number of file chunks and process those chunks in parallel. 'cores' is the number of cores in the linux system.</p>
<pre><code>from multiprocessing import Process
import os
from time import sleep
import multiprocessing
pros = []
def getFiles(directory):
'''returns the files from a directory'''
for dirpath,_,filenames in os.walk(directory):
for f in filenames:
yield os.path.abspath(os.path.join(dirpath, f))
def countFiles(directory):
return len([name for name in os.listdir(directory) if os.path.isfile(os.path.join(directory, name))])
def foo(fileList):
print(fileList)
def isCommon(a, b):
aSet = set(a)
bSet = set(b)
if len(aSet.intersection(bSet)) > 0:
return(True)
return(False)
if __name__ == "__main__":
'''get count of files in directory and split it in based on number of cores'''
directory = ""
noCores = multiprocessing.cpu_count()
totalFilesCount = countFiles(directory)
chunkSize = totalFilesCount/noCores
totalChunks = noCores
print("total files", totalFilesCount, "total chunks", totalChunks, "chunk size", chunkSize)
filesProcessed = 0
currentChunk = 0
fileObj = getFiles(directory)
listOFFiles = []
while filesProcessed < totalFilesCount:
filesList = []
# if it is last chunk and totalFilesCount can't be divided equally then put leftover files in last core to get processed
if currentChunk == totalChunks - 1 and totalFilesCount%noCores:
chunkSize += totalFilesCount%noCores
reached = 0
for f in fileObj:
filesList.append(f)
if chunkSize == reached:
break
reached += 1
listOFFiles.append(filesList)
p = Process(target=foo, args=(filesList,))
pros.append(p)
p.start()
currentChunk += 1
filesProcessed += chunkSize
for t in pros:
t.join()
for a, b in zip(listOFFiles, listOFFiles[1:]):
assert isCommon(a, b) == False
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T05:02:23.163",
"Id": "494893",
"Score": "1",
"body": "Did you look at [`multiprocessing.Pool`](https://docs.python.org/3.7/library/multiprocessing.html#using-a-pool-of-workers)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-06T01:27:31.550",
"Id": "495634",
"Score": "0",
"body": "@RootTwo: thanks, I looked into it and it is very easy to use."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-26T08:03:19.733",
"Id": "515486",
"Score": "0",
"body": "instead of ```reached``` you can do ```chunkSize == len(filesList)``` in your break statement, totalChunks can be omitted, just use noCores (matter of taste, totalChunks add some semantic information, but it's one more thing to remember (more complexity), ...)"
}
] |
[
{
"body": "<p>The python standard library offers two process pools to simplify what you're trying to achieve: <a href=\"https://docs.python.org/3.7/library/multiprocessing.html#using-a-pool-of-workers\" rel=\"nofollow noreferrer\"><code>multiprocessing.Pool</code></a> (as mentioned by @RootTwo) and <a href=\"https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ProcessPoolExecutor\" rel=\"nofollow noreferrer\"><code>concurrent.futures.ProcessPoolExecutor</code></a>.</p>\n<p>I personally like the second one (despite its more limited API) because you can replace it with a <code>ThreadPoolExecutor</code> without changing the rest of the code. Threads are better suited if your processing is I/O bound, because inter-process communication is slow and processes are slower to start (especially on Windows). With the <code>concurrent.futures</code> API, you can easily swap the two and test which one works better.</p>\n<p>There are some other ways you can improve the code, most notably:</p>\n<ol>\n<li>If you're on Python 3.x as you should be, I suggest the use of <code>pathlib</code> instead of <code>os.path</code>.</li>\n<li>Put code from the <code>if __name__ == "__main__":</code> into a "main" function to make automated testing easier.</li>\n<li>Use snake_case instead of camelCase as that's the accepted standard for Python.</li>\n<li>(Opinion) If you're on python 3.x, you could also use type annotations to improve the readability of the code.</li>\n</ol>\n<p>With this in mind, I would rewrite your code as:</p>\n<pre><code>from pathlib import Path\nfrom concurrent.futures import ProcessPoolExecutor, as_completed\nfrom typing import Iterable\n\ndef get_files(directory: Path) -> Iterable[Path]:\n # Using glob simplifies the code in these cases.\n return (file for file in directory.glob("**/*") if file.is_file())\n\ndef foo(file: Path):\n ...\n\n# This can be easily called from a test\ndef process_files(directory: Path):\n # I am using sum, so that the result is computed lazily and we\n # do not need to build a list of all files. If the directory is\n # very large, this could save a lot of memory.\n # Since get_files returns a one-shot generator, we cannot\n # save it to a variable and reuse it here and below.\n file_count = sum(1 for _ in get_files(directory))\n \n with concurrent.futures.ProcessPoolExecutor() as executor:\n futures = executor.map(foo, get_files(directory))\n # Reading the value returned by the executor is very\n # important, because exceptions happening in the `foo`\n # function will be captured and not be raised until the\n # value is read, thus obfuscating the errors.\n # \n # Another nice solution for the progress would be\n # using the library tqdm.\n for i, _ in enumerate(as_completed(futures)):\n print(f"Processed file {i+1} / {file_count}")\n\nif __name__ == "__main__":\n process_files(Path(""))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-17T08:36:04.257",
"Id": "264140",
"ParentId": "251359",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T22:07:46.310",
"Id": "251359",
"Score": "6",
"Tags": [
"python"
],
"Title": "parallel processing of files from a directory"
}
|
251359
|
<p>I wrote a silly Rust program inspired by a <a href="https://www.wolframalpha.com/input/?i=number%20of%20days%20since%20January%201%2C%201970" rel="nofollow noreferrer">WolframAlpha query</a>. I know, that's nothing serious, but if there's anything that could be made more, well, proper Rust-like, I'd love to know! Of course, general feedback is welcomed too.</p>
<p>For starters, here's my <code>Cargo.toml</code>:</p>
<pre><code>[package]
name = "rusted-days"
version = "0.1.0"
authors = ["baduker"]
edition = "2018"
[dependencies]
chrono = "0.4.19"
</code></pre>
<p>And the code:</p>
<pre><code>use std::io;
use std::io::Write;
use chrono::{NaiveDateTime, DateTime, Utc, Datelike};
fn main() {
let prompt = "What's your date (DD/MM/YYYY)?: ";
let date = input(prompt).expect("Something went wrong! o.O");
show_interpretation(parse_date(date));
}
fn input(user_input: &str) -> io::Result<String> {
print!("{}", user_input);
io::stdout().flush()?;
let mut buffer: String = String::new();
io::stdin().read_line(&mut buffer)?;
Ok(buffer.trim_end().to_owned())
}
fn parse_date(date: String) -> DateTime<Utc> {
let naive_date = chrono::NaiveDate::parse_from_str(
date.as_str(), "%d/%m/%Y"
).unwrap();
let naive_datetime: NaiveDateTime = naive_date
.and_hms(0, 0, 0);
DateTime::<Utc>::from_utc(naive_datetime, Utc)
}
fn show_interpretation(date: DateTime<Utc>) {
println!("Input interpretation: days since {}", date.format("%A, %B %d, %Y"));
let total_days = Utc::now() - date;
println!("Result:\n{} days have rusted away ¯\\_(ツ)_/¯", total_days.num_days());
let years = Utc::now().year() - date.year();
let months = Utc::now().month() - date.month();
let days = Utc::now().day() - date.day();
println!("Timespan:\n{} year(s), {} month(s), {} day(s)", years, months, days);
println!("{} weeks", total_days.num_weeks());
println!("{:.2} years", total_days.num_days() as f32 / 365_f32);
}
</code></pre>
<p>A sample output (you should get):</p>
<pre><code>What's your date (DD/MM/YYYY): 01/01/1970
Input interpretation: days since Thursday, January 01, 1970
Result:
18567 days have rusted away ¯\_(ツ)_/¯
Timespan:
50 years, 10 month(s), 0 days
2652 weeks
50.87 years
</code></pre>
|
[] |
[
{
"body": "<p>I can't see any issues in terms of making your code idiomatic; it looks very Rust-like! I did however notice a problem with your code's logic.</p>\n<h2>Integer overflow</h2>\n<p>I tried inputting 31/12/2019 and obtained a panic when I ran it today (07/11/2020). This was because <code>Utc::now().month()</code> is a <code>u32</code> equal to 11, and the code attempts to subtract 12:</p>\n<pre><code>let months = Utc::now().month() - date.month();\n</code></pre>\n<p>This leads to an overflow because we're using unsigned integers. The same story applies for the day, which is also a <code>u32</code>, but not the year, which is an <code>i32</code> and so functions fine.</p>\n<p>Even if we convert the relevant types to signed integers, the following isn't what you mean:</p>\n<pre><code>let years = Utc::now().year() - date.year();\n</code></pre>\n<p>This would tell you that 31/12/2019 and 1/1/2020 are a year apart, when in fact this isn't true. Even dividing the number of days by 365 isn't quite right because of leap years.</p>\n<p>Making the date logic work correctly is a lot more frustrating than it sounds: the number of months passed depends on the length of each month as well as the <code>Duration</code> instance. That's why <code>Duration</code> doesn't implement anything beyond <code>num_weeks()</code>: it's simply a difference between two dates, so it doesn't know how to account for the varying month lengths.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-07T19:04:48.237",
"Id": "495836",
"Score": "1",
"body": "Thanks for the feedback! Glad to hear the code is proper Rust-like. Not so great to learn I've missed a few things. Guess, it's time to learn writing tests in Rust. :) By the way, any tips on dealing with the overflow issue?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-07T19:25:11.993",
"Id": "495838",
"Score": "1",
"body": "No problem, @baduker. As far as stopping the overflows, you can just cast `Utc::now().month()` etc to `i64` and your code won't panic any more, for example `let month = Utc::now().month() as i64 - date.month()`. This doesn't solve your issue though, because then this says that the difference between 31/12/2019 and 31/10/2020 is 1 year, -2 months. I am not sure if the [relativedelta](https://docs.rs/relativedelta/0.2.2/relativedelta/) crate might be helpful? I've not used it and just reviewed the documentation, but it might be able to do what you need."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-07T19:38:25.870",
"Id": "495839",
"Score": "1",
"body": "Right, getting rid of overflow still doesn't remedy the date delta issue. I'll poke around the crate and if I can't find what I need, I'll take this to Stackoverflow."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-07T17:43:13.437",
"Id": "251768",
"ParentId": "251360",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "251768",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T22:29:50.393",
"Id": "251360",
"Score": "5",
"Tags": [
"rust"
],
"Title": "Rusted days - a WolframAlfa port"
}
|
251360
|
<p>This is a simple maze generator program. I didn't want to include header files and separate compilation because it was meant to be simple and straightforward. I also think the code is both readable and understandable, which is why I do not have many comments. I implemented an iterative version due to the function call overload of a recursive approach, though I felt a recursive approach might be cleaner.</p>
<p>The code works based on what I have tested so far.</p>
<p><strong>MAJOR CONCERNS</strong></p>
<ol>
<li>Readability</li>
<li>Potential pitfalls</li>
<li>General bad practice</li>
<li>Poor use of Data structures</li>
</ol>
<h1>maze_gen.cc</h1>
<pre><code>#include <iostream>
#include <array>
#include <string>
#include <vector>
#include <tuple>
#include <map>
#include <stack>
#define N 16
struct Cell
{
Cell() = default;
Cell( int i, int j );
const Cell &operator=( const Cell & );
std::string direction( const Cell & );
std::map< std::string, bool> walls;
std::map<std::string, std::string> mypairs;
int x;
int y;
bool visited;
std::stack<Cell> neighbors;
};
Cell::Cell( int i, int j )
: x( i ), y( j ), visited( false )
{
walls.insert( { "N", true } );
walls.insert( { "S", true } );
walls.insert( { "W", true } );
walls.insert( { "E", true } );
mypairs.insert( { "N", "S" } );
mypairs.insert( { "S", "N" } );
mypairs.insert( { "E", "W" } );
mypairs.insert( { "W", "E" } );
}
const Cell &Cell::operator=( const Cell &c )
{
x = c.x;
y = c.y;
visited = c.visited;
walls = c.walls;
mypairs = c.mypairs;
return *this;
}
std::string Cell::direction( const Cell &other )
{
if( x == other.x && y + 1 == other.y )
return "E";
if( x == other.x && y - 1 == other.y )
return "W";
if( x - 1 == other.x && y == other.y )
return "N";
if( x + 1 == other.x && y == other.y )
return "S";
return "";
}
struct Grid
{
Grid();
void print_grid();
std::vector<std::tuple< int, int> > get_all_neighbors( int i, int j );
std::string direction( Cell current, Cell other );
void generate_maze();
std::array<std::array< Cell, N >, N > grids;
};
Grid::Grid() {
for( int i = 0; i != N; ++i ) {
for( int j = 0; j != N; ++j ) {
grids[ i ][ j ] = Cell( i, j );
}
}
}
std::vector<std::tuple< int, int> > Grid::get_all_neighbors( int i, int j ) {
std::tuple< int, int> co_ordinates;
std::vector<std::tuple< int, int> > valid_neighbors;
if( ( i >= 0 && i < N ) && ( j + 1 >= 0 && j + 1 < N ) && ( grids[ i ][ j + 1 ].visited == false ) ) {
co_ordinates = std::make_tuple( i, j + 1 );
valid_neighbors.push_back( co_ordinates );
}
if( ( i >= 0 && i < N ) && ( j - 1 >= 0 && j - 1 < N ) && ( grids[ i ][ j - 1 ].visited == false ) ) {
co_ordinates = std::make_tuple( i, j - 1 );
valid_neighbors.push_back( co_ordinates );
}
if( ( i - 1 >= 0 && i - 1 < N ) && ( j >= 0 && j < N ) && ( grids[ i - 1 ][ j ].visited == false ) ) {
co_ordinates = std::make_tuple( i - 1 , j );
valid_neighbors.push_back( co_ordinates );
}
if( ( i + 1 >= 0 && i + 1 < N ) && ( j >= 0 && j < N ) && ( grids[ i + 1 ][ j ].visited == false ) ) {
co_ordinates = std::make_tuple( i + 1 , j );
valid_neighbors.push_back( co_ordinates );
}
return valid_neighbors;
}
void Grid::print_grid() {
std::cout << "+";
for( int i = 0; i != N; ++i )
std::cout << "----+";
std::cout << std::endl;
for( int i = 0; i != N; ++i ) {
std::string body = " ";
std::cout << "|";
for( int j = 0; j != N; ++j ) {
if( grids[i][j].walls.at( "E" ) )
std::cout << body << "|";
else
std::cout << body << " ";
}
std::cout << std::endl;
for( int j = 0; j != N; ++j ) {
std::cout << "+";
if( grids[i][j].walls.at( "S" ) ) {
std::cout << "----";
}
else {
std::cout << body;
}
}
std::cout << "+";
std::cout << std::endl;
}
}
void Grid::generate_maze()
{
Cell current_cell = grids[ 6 ][ 6 ];
std::stack<Cell> visited_cells;
grids[ current_cell.x ][ current_cell.y ].visited = true;
visited_cells.push( grids[ current_cell.x ][ current_cell.y ] );
while( visited_cells.empty() == false )
{
current_cell = visited_cells.top();
visited_cells.pop();
auto neighbors = get_all_neighbors( current_cell.x, current_cell.y );
int random_int = 0;
if ( neighbors.size() != 0 ) {
random_int = 0 + rand() % neighbors.size();
}
if( neighbors.empty() == false )
{
visited_cells.push( grids[ current_cell.x ][ current_cell.y ] );
int i = std::get<0>( neighbors[ random_int ] );
int j = std::get<1>( neighbors[ random_int ] );
Cell neighbor = grids[ i ][ j ];
std::string direction = grids[ current_cell.x ][ current_cell.y ].direction( neighbor );
grids[ current_cell.x ][ current_cell.y ].walls[ direction ] = false;
grids[ neighbor.x ][ neighbor.y ].walls[ grids[ current_cell.x ][ current_cell.y ].mypairs[ direction ] ] = false;
grids[ i ][ j ].visited = true;
visited_cells.push( grids[ i ][ j ] );
}
}
}
int main()
{
srand( static_cast<unsigned int> (time(0)) );
Grid grid;
grid.print_grid();
grid.generate_maze();
std::cout << "\nMaze generated\n";
grid.print_grid();
}
</code></pre>
|
[] |
[
{
"body": "<p>Avoid macros. Replace <code>#define N 6</code> with <code>constexpr int N = 6;</code>. <code>N</code> is not a very descriptive name; you should give it a better one (<code>MAZE_SIZE</code>). You're also using this for both dimensions of the maze, which limits you to square mazes.</p>\n<p><code>operator=</code> should not return a const reference.</p>\n<p>Since <code>Cell::walls</code> is a map that stores a <code>bool</code>, you could replace it with a <code>set</code>, and use the presence of the key in the set as the value.</p>\n<p>Rather than using short strings for things like direction, you could use an enum type. This would save space and improve performance.</p>\n<p><code>Cell::direction</code> can be a const function (<code>std::string Cell::direction( const Cell &other ) const</code>).</p>\n<p>You could add an <code>init</code> or <code>setxy</code> function to <code>Cell</code>, and use that in the <code>Grid</code> constructor (<code>grids[ i ][ j ].init(x, y);</code>).</p>\n<p><code>Grid::get_all_neighbors</code> can also be a const member function. You can get rid of <code>co_ordinates </code> by using <code>valid_neighbors.emplace_back(std::make_tuple(/*...*/))</code>.</p>\n<p>When checking a bool value, you don't need to use <code>==</code>, you can check it directly. To check for false, you can use the <code>!</code> operator: <code>!grids[ i ][ j - 1 ].visited</code>.</p>\n<p>There are a couple of duplicated conditions in <code>get_all_neighbors</code>. This function can be rewritten with nested <code>if</code> statements to remove them. This would also improve the readability just a bit.</p>\n<p>In a lot of your <code>for</code> loops, your comparison uses <code>!=</code>. While that works here, more common is to use <code><</code>. The <code><</code> comparison is essential when using something like OpenMP to add multithreading.</p>\n<p>In <code>print_grid</code>, the <code>body</code> variable can be moved outside of the for loop. This will avoid repeatedly creating and destroying it.</p>\n<p><code>generate_maze</code> uses a hardcoded <code>6</code> as a starting cell. This should be a constant somewhere (defined next to <code>N</code>), or should be some fraction of <code>N</code>. You seem to be using <code>current_cell</code> just to hold <code>x</code> and <code>y</code> values. You can use either a smaller coordinate class, or a pair, to manipulate these. By using the full <code>Cell</code> object you're copying around a lot of (empty) maps and stacks.</p>\n<p><code>rand</code> is not a very good source of random numbers. Look into the facilities provided by the <code><random></code> header.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T04:49:22.573",
"Id": "494791",
"Score": "0",
"body": "I found out that whenever i declare operator= without const, it resulted to weird things happening when I make a copy"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T17:32:12.880",
"Id": "494836",
"Score": "1",
"body": "@theProgrammer While in practice it usually doesn't matter, the compiler generated assignment operator returns a non-const reference, and there are some cases where the value returned by the assignment is immediately used or modified that would not compile if the returned reference was const."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T00:47:12.100",
"Id": "251363",
"ParentId": "251361",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "251363",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-30T23:21:34.927",
"Id": "251361",
"Score": "5",
"Tags": [
"c++"
],
"Title": "Maze Generator in C++ using iterative approach"
}
|
251361
|
<p>I want to split an integer of type <code>unsigned long long</code> to its digits.
Any comments and suggestions are always welcome.</p>
<pre><code>#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<unsigned short> IntegerDigits(unsigned long long input)
{
vector<unsigned short> output;
const unsigned short n = log10(ULLONG_MAX);
unsigned long long divisor = pow(10, n);
bool leadingZero = true;
for (int i = 0; i < n + 1; i++)
{
unsigned short digit = input / divisor % 10;
if (!leadingZero || digit != 0)
{
output.push_back(digit);
leadingZero = false;
}
divisor /= 10;
}
return output;
}
void main()
{
vector<unsigned short> output = IntegerDigits(ULLONG_MAX);
cout << ULLONG_MAX << ": [";
for (auto y : output)
cout << y << ", ";
cout << "\b\b]";
cout << ""<<endl;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T06:33:41.360",
"Id": "494794",
"Score": "1",
"body": "`short n = log10(ULLONG_MAX)` will this be rounded up or down? Why?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T06:40:04.660",
"Id": "494795",
"Score": "0",
"body": "@greybeard: Down. Because `log10(ULLONG_MAX) + 1` represents \"the max number of digits\" for `unsigned long long`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T06:44:17.623",
"Id": "494796",
"Score": "1",
"body": "What if `ULLONG_MAX` was 2⁶⁶ (2³³×2³³)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T06:51:38.107",
"Id": "494797",
"Score": "0",
"body": "@greybeard the max number of digits becomes 20. What is the problem?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T07:01:04.590",
"Id": "494798",
"Score": "0",
"body": "@greybeard `n+1` represents the max number of digits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T07:54:48.543",
"Id": "494809",
"Score": "2",
"body": "The problem is that a rounded up `pow(10, n)` may not be \"losslessly\" assignable to an `unsigned long long`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T10:28:14.443",
"Id": "494913",
"Score": "0",
"body": "I don't know why you choose to not add `#include <cmath>`. Produced `pow` not defined on my Computer, compiled with `c++14`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T10:34:33.060",
"Id": "494914",
"Score": "0",
"body": "@theProgrammer: I don't know why. In my machine it is available without `cmath`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T10:41:34.473",
"Id": "494916",
"Score": "0",
"body": "Perhaps, you compiler did some underground work, but it's good practice to explicitly include necessary headers. `explicit is better than implicit`"
}
] |
[
{
"body": "<h1>Avoid mixing floating point and integer arithmetic</h1>\n<p>As mentioned by greybeard, there is a potential problem here:</p>\n<pre><code>const unsigned short n = log10(ULLONG_MAX);\n</code></pre>\n<p><code>ULLONG_MAX</code> is larger than can be exactly represented by a <code>double</code>. This means the result might not be what you expect. The same goes for <code>pow(10, n)</code>. While you can compensate for it, it is better to find a way to calculate the length of a number without using floating point math.</p>\n<h1>Keep it simple</h1>\n<p>Unless performance is a big concern, keep it simple. You don't have to know the number of digits up front if you push trailing digits to the front of the vector, like so:</p>\n<pre><code>vector<unsigned short> IntegerDigits(unsigned long long input)\n{\n vector<unsigned short> output;\n\n while (input)\n {\n output.insert(output.begin(), input % 10);\n input /= 10;\n }\n\n // Handle input being equal to 0\n if (output.empty())\n {\n output.push_back(0);\n }\n\n return output;\n}\n</code></pre>\n<p>Pushing to the front of a <code>std::vector</code> is less efficient, but on the other hand you don't need the <code>double</code><-><code>int</code> conversions, and you don't need to handle the leading zeros inside the loop.</p>\n<h1>Avoid using <code>std::endl</code></h1>\n<p><a href=\"https://stackoverflow.com/questions/213907/stdendl-vs-n\">Prefer using <code>"\\n"</code> over <code>std::endl</code></a>, the latter is equivalent to the former, but also forces a flush of the output, which can be bad for performance.</p>\n<h1>Avoid backspaces in the output</h1>\n<p>You used a neat trick to get rid of the last comma without having to have extra logic inside the <code>for</code>-loop in <code>main()</code>. However, consider that the output might not just be for human consumption, but is written to a file and/or is parsed by another program. In that case, the <code>\\b</code> characters are probably unexpected and might cause problems.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T08:30:06.213",
"Id": "494811",
"Score": "1",
"body": "Where is `push_front` defined?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T08:51:51.760",
"Id": "494814",
"Score": "0",
"body": "I changed to `stack` instead of `vector` because `push_front` has not been defined in `vector`. :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T10:16:56.643",
"Id": "494815",
"Score": "0",
"body": "Ehr oops, I meant `insert(output.begin(), ...)`!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T19:43:42.443",
"Id": "494851",
"Score": "1",
"body": "Better to just append and then reverse in-place?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T21:03:22.443",
"Id": "494862",
"Score": "0",
"body": "Or use a `std::deque`. The are many ways one could do this, but since it's likely only a few digits will be stored, I don't think it's going to matter much. This is where I would just keep the simplest approach, and only change it when performance becomes a bottleneck and measurements have shown that this function is a big contributor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T10:24:13.577",
"Id": "494912",
"Score": "0",
"body": "Why don't you take each element individually, push into a `stack`. Nice and easy."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T14:31:31.673",
"Id": "494953",
"Score": "0",
"body": "@Deduplicator Even better: `return {std::rbegin(output), std::rend(output)};`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T14:33:46.310",
"Id": "494954",
"Score": "0",
"body": "@Casey That would be shorter, but means one more allocation. Probably sub-optimal, though the compiler might optimise it away."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T08:06:58.767",
"Id": "251370",
"ParentId": "251364",
"Score": "10"
}
},
{
"body": "<p>As @G. Sliepen said, I also want to reiterate, when performance isn't a problem, ensure to make the code as simple as possible.</p>\n<p>A modified version using <code>stack</code> might be written like this</p>\n<pre><code>void separate_digits( stack<int> &s, long long int digits )\n{\n while( digits != 0 ) \n {\n s.push( digits % 10 );\n digits /= 10;\n }\n}\n</code></pre>\n<p>Displaying the digit would just require you to <code>pop</code> the stack, which as we know takes constant time</p>\n<pre><code>void print_separated_digits( stack<int> &s ) \n{\n while( !s.empty( ) )\n {\n std::cout << s.top( ) << " ";\n s.pop( );\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T11:48:03.190",
"Id": "251418",
"ParentId": "251364",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "251370",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T01:43:26.903",
"Id": "251364",
"Score": "7",
"Tags": [
"c++",
"algorithm"
],
"Title": "Splitting an integer to its digits"
}
|
251364
|
<p>Based on the sample variants, I need to get all combinations of all variants. In the example I have 3x3x2=18 variants.</p>
<pre class="lang-rb prettyprint-override"><code>## SAMPLE VARIANTS
sizes = ['small', 'medium', 'large']
colors = ['red', 'green', 'blue']
materials = ['cotton', 'linen']
## ITERATE TO ALL VARIANTS
titles = []
sizes.each do |size|
colors.each do |color|
materials.each do |material|
## PUT THE VARIANT IN THE NEW ARRAY
titles.push("#{size} - #{color} - #{material}")
end
end
end
puts titles.inspect
</code></pre>
<p>Is my nested each loop preferred or there is some better implementation for this?</p>
|
[] |
[
{
"body": "<h1>Frozen string literals</h1>\n<p>Immutable data structures and purely functional code are always preferred, unless mutability and side-effects are required for clarity or performance. In Ruby, strings are always mutable, but there is a <a href=\"https://bugs.ruby-lang.org/issues/8976\" rel=\"nofollow noreferrer\">magic comment</a> you can add to your files (also available as a command-line option for the Ruby engine), which will automatically make all literal strings immutable:</p>\n<pre class=\"lang-rb prettyprint-override\"><code># frozen_string_literal: true\n</code></pre>\n<p>It is generally preferred to add this comment to all your files.</p>\n<h1>Word array "percent" literals</h1>\n<p>Ruby has <a href=\"https://ruby-doc.org/core/doc/syntax/literals_rdoc.html#label-Percent+Strings\" rel=\"nofollow noreferrer\">special array literals for arrays of single-word strings</a> that can make your code easier to read by reducing the amount of "syntax fluff" around the actual content.</p>\n<p>The literal starts with the sigils <code>%w</code> or <code>%W</code> (think "word" or "witespace-separated"). <code>%w</code> behaves like a single-quoted string, i.e. does not perform interpolation and supports no escape characters other than <code>\\'</code> and <code>\\\\</code>. <code>%W</code> behaves like a double-quoted string.</p>\n<p>So, the beginning of your script could look like this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code># frozen_string_literal: true\n\n## SAMPLE VARIANTS\nsizes = %w[small medium large]\ncolors = %w[red green blue]\nmaterials = %w[cotton linen]\n</code></pre>\n<p>As with all percent literals, you can freely choose the delimiter you want to use such that the delimiter does not occur inside the literal. For example, you can use <code>|</code> as the delimiter, <code>,</code>, <code>@</code> anything you want:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>sizes = %w@small medium large@\ncolors = %w@red green blue@\nmaterials = %w@cotton linen@\n</code></pre>\n<p>The first character after the <code>w</code> determines the delimiter. Delimiters come in two variants: paired and unpaired. With an unpaired delimiter, the same character ends the literal, as in the second example. With a paired delimiter, the corresponding closing delimiter ends the literal, e.g. when you start with <code><</code>, you close with <code>></code>, etc. See the first example.</p>\n<h1>Linting</h1>\n<p>You should run some sort of linter or static analyzer on your code. <a href=\"https://www.rubocop.org/\" rel=\"nofollow noreferrer\">Rubocop</a> is a popular one, but there are others.</p>\n<p>Rubocop was able to detect all of the style improvements I pointed out above, and also was able to autocorrect all of the ones I listed.</p>\n<p>I have set up my editor such that it automatically runs Rubocop with auto-fix as soon as I hit "save".</p>\n<p>Here's what the result of the auto-fix looks like:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code># frozen_string_literal: true\n\n## SAMPLE VARIANTS\nsizes = %w[small medium large]\ncolors = %w[red green blue]\nmaterials = %w[cotton linen]\n\n## ITERATE TO ALL VARIANTS\ntitles = []\nsizes.each do |size|\n colors.each do |color|\n materials.each do |material|\n ## PUT THE VARIANT IN THE NEW ARRAY\n titles.push("#{size} - #{color} - #{material}")\n end\n end\nend\n\nputs titles.inspect\n</code></pre>\n<h1><code>puts foo.inspect</code></h1>\n<p><a href=\"https://ruby-doc.org/core/Kernel.html#method-i-p\" rel=\"nofollow noreferrer\"><code>Kernel#p</code></a> is the preferred debugging method. It does the same thing, but is more idiomatic, and is specifically designed for quick debugging (hence the one-character name).</p>\n<p>So, the last line can simply be</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>p titles\n</code></pre>\n<p>Also, <a href=\"https://ruby-doc.org/core/Kernel.html#method-i-puts\" rel=\"nofollow noreferrer\"><code>Kernel#puts</code></a> returns <code>nil</code>, but <code>Kernel#p</code> returns its argument(s), so you can quickly chuck it into a long chain of expressions without changing the result.</p>\n<h1>Vertical whitespace</h1>\n<p>Your code could use some vertical whitespace to give the code more room to breathe. I would suggest at least separating the initialization at the beginning of the loop:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>titles = []\n\nsizes.each do |size|\n colors.each do |color|\n materials.each do |material|\n ## PUT THE VARIANT IN THE NEW ARRAY\n titles.push("#{size} - #{color} - #{material}")\n end\n end\nend\n</code></pre>\n<h1>The "shovel" operator <code><<</code></h1>\n<p><a href=\"https://ruby-doc.org/core/Array.html#method-i-push\" rel=\"nofollow noreferrer\"><code>Array#push</code></a> is not idiomatic. More precisely, it is <em>only</em> idiomatic if you are using the array as a <em>stack</em>, then you would use <code>Array#push</code> and <a href=\"https://ruby-doc.org/core/Array.html#method-i-pop\" rel=\"nofollow noreferrer\"><code>Array#pop</code></a>, since those are the standard names for the stack operations.</p>\n<p>The idiomatic way of appending something to something else is the shovel operator, in this case <a href=\"https://ruby-doc.org/core/Array.html#method-i-3C-3C\" rel=\"nofollow noreferrer\"><code>Array#<<</code></a>, so that should be</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>titles << "#{size} - #{color} - #{material}"\n</code></pre>\n<h1>Iterators</h1>\n<p>In Ruby, it is idiomatic to use high-level iterators. In your code, you are already using iterators instead of loops, so that is good. However, <a href=\"https://ruby-doc.org/core/Array.html#method-i-each\" rel=\"nofollow noreferrer\"><code>each</code></a> is really the lowest-level of all the iterators. It is essentially equivalent to a <code>FOREACH-OF</code> loop. It has no higher-level semantics, and it relies on mutation and side-effects.</p>\n<p>Whenever you have the pattern of "Initialize a result, loop over a collection appending to the result, return result", that is a <a href=\"https://wikipedia.org/wiki/Fold_(higher-order_function)\" rel=\"nofollow noreferrer\"><em>fold</em></a>. There are two implementations of <em>fold</em> in the Ruby core library, <a href=\"https://ruby-doc.org/core/Enumerable.html#method-i-inject\" rel=\"nofollow noreferrer\"><code>inject</code></a> and <a href=\"https://ruby-doc.org/core/Enumerable.html#method-i-each_with_object\" rel=\"nofollow noreferrer\"><code>each_with_object</code></a>. <code>inject</code> is the more functional one, <code>each_with_object</code> is the more imperative one. So, for now, we will use <code>each_with_object</code> here, since the code is still pretty imperative, and that makes the relationship between the old and new code more clear.</p>\n<p>As a general transformation,</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>accumulator = some_initial_value\n\ncollection.each do |element|\n accumulator = do_something_with(accumulator, element)\nend\n</code></pre>\n<p>becomes</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>accumulator = collection.inject(some_initial_value) do |accumulator, element|\n do_something_with(accumulator, element)\nend\n</code></pre>\n<p>or</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>collection.each_with_object(some_initial_value) do |element, accumulator|\n do_something_with(accumulator, element)\nend\n</code></pre>\n<p>In your case, it would look like this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>titles = []\n\nsizes.each do |size|\n colors.each do |color|\n materials.each do |material|\n ## PUT THE VARIANT IN THE NEW ARRAY\n titles << "#{size} - #{color} - #{material}"\n end\n end\nend\n</code></pre>\n<p>becomes</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>titles = []\n\nsizes.each_with_object(titles) do |size, titles|\n colors.each_with_object(titles) do |color, titles|\n materials.each_with_object(titles) do |material, titles|\n ## PUT THE VARIANT IN THE NEW ARRAY\n titles << "#{size} - #{color} - #{material}"\n end\n end\nend\n</code></pre>\n<p>Granted, this doesn't buy us much, actually the opposite. It starts to look slightly different though, when we move to a purely functional version without side-effects and mutation using <code>Enumerable#inject</code>:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>titles = sizes.inject([]) do |acc, size|\n colors.inject(acc) do |acc, color|\n materials.inject(acc) do |acc, material|\n ## PUT THE VARIANT IN THE NEW ARRAY\n acc + ["#{size} - #{color} - #{material}"]\n end\n end\nend\n</code></pre>\n<h1>Linter, revisited</h1>\n<p>Rubocop actually complains about my use of <em>shadowing</em> the outer <code>acc</code> with the inner <code>acc</code>.</p>\n<p>I disagree. You should not be afraid to disable or re-configure rules in your linter to fit your style.</p>\n<p>However, note that programming is a team sport. If you are <em>modifying</em> code, adopt the existing style. If you are part of a team, adopt the team's style. If you write open source code, adopt the project's style. If you start your own project, adopt the community's style (do <em>not</em> create your own style for your project, until your project is big and successful enough to have its own independent community).</p>\n<h1>Excursion: Generality of <em>fold</em> (<code>inject</code> / <code>each_with_object</code>)</h1>\n<p>When I wrote above that you can rewrite this iteration with <code>inject</code> or <code>each_with_object</code>, that was actually a tautological statement. I didn't even have to read the code to make this statement.</p>\n<p>It turns out that <em>fold</em> is "general". <a href=\"https://wikipedia.org/wiki/Fold_(higher-order_function)#Universality\" rel=\"nofollow noreferrer\"><em>Every</em> iteration over a collection can be expressed using <em>fold</em></a>. This means, if we were to delete <em>every method</em> from <code>Enumerable</code>, except <code>inject</code>, then we could re-implement the entire <code>Enumerable</code> module again, using nothing but <code>inject</code>. As long as we have <code>inject</code>, we can do anything.</p>\n<h1>Iterators, take 2</h1>\n<p>So, what we did until now was replace the low-level iterator with a higher-level iterator.</p>\n<p>However, we are still not done. What we are now doing is we take each three elements from our three collections, concatenating them, and putting it into a new collection. So, really, what we are doing is <em>transforming</em> each element (or triple of elements), or "mapping" each element to a new element.</p>\n<p>This is called <a href=\"https://wikipedia.org/wiki/Map_(higher-order_function)\" rel=\"nofollow noreferrer\"><em>map</em></a> and is also available in Ruby as <a href=\"https://ruby-doc.org/core/Enumerable.html#method-i-map\" rel=\"nofollow noreferrer\"><code>Enumerable#map</code></a>.</p>\n<p>So, finally, our code looks like this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>titles = sizes.map do |size|\n colors.map do |color|\n materials.map do | material|\n "#{size} - #{color} - #{material}"\n end\n end\nend\n</code></pre>\n<p>This result is actually not quite right: we get a triply-nested array, because we have a triply-nested <code>Enumerable#map</code>.</p>\n<p>We could <a href=\"https://ruby-doc.org/core/Array.html#method-i-flatten\" rel=\"nofollow noreferrer\"><code>Array#flatten</code></a> the result, but there is a better way: <a href=\"https://ruby-doc.org/core/Enumerable.html#method-i-flat_map\" rel=\"nofollow noreferrer\"><code>Enumerable#flat_map</code></a>:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>titles = sizes.flat_map do |size|\n colors.flat_map do |color|\n materials.map do | material|\n "#{size} - #{color} - #{material}"\n end\n end\nend\n</code></pre>\n<p>What we did here, was to replace the <em>general</em> high-level iterator <em>fold</em> (which can do <em>anything</em>) with a more restricted, more specialized high-level iterator <em>map</em>. By using a more specialized iterator, we are able to better convey our semantics to the reader. Instead of thinking "Okay, so here we have an accumulator, and an element, and we do something with the element, and then append it to the accumulator … ah, I see, we are transforming each element", the reader just sees <code>map</code> and instantly <em>knows</em> that <code>map</code> transforms the elements.</p>\n<h1>Array methods</h1>\n<p>There is not much we can improve in the code by using iterators. However, there are many more methods in both the <a href=\"https://ruby-doc.org/core/Enumerable.html\" rel=\"nofollow noreferrer\"><code>Enumerable</code> mixin</a> and the <a href=\"https://ruby-doc.org/core/Array.html\" rel=\"nofollow noreferrer\"><code>Array</code> class</a>.</p>\n<p>So, let's take a step back and think about what we are <em>actually</em> doing here: we are constructing the <a href=\"https://wikipedia.org/wiki/Cartesian_product\" rel=\"nofollow noreferrer\"><em>Cartesian Product</em></a> of the three arrays. And perhaps not surprisingly, there already is a method that computes a product of arrays, creatively named <a href=\"https://ruby-doc.org/core/Array.html#method-i-product\" rel=\"nofollow noreferrer\"><code>Array#product</code></a>:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>titles = sizes.product(colors, materials).map do |size, color, material|\n "#{size} - #{color} - #{material}"\nend\n</code></pre>\n<h1><code>Array#join</code></h1>\n<p>As a last improvement, let's look at what the block is doing: it is "joining" the three variants together. And again, there is already a method which does that: <a href=\"https://ruby-doc.org/core/Array.html#method-i-join\" rel=\"nofollow noreferrer\"><code>Array#join</code></a>:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>titles = sizes.product(colors, materials).map do |variant|\n variant.join(' - ')\nend\n</code></pre>\n<h1>Final result</h1>\n<p>So, in the end, the entire thing looks something like this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code># frozen_string_literal: true\n\n## SAMPLE VARIANTS\nsizes = %w[small medium large]\ncolors = %w[red green blue]\nmaterials = %w[cotton linen]\n\ntitles = sizes.product(colors, materials).map do |variant|\n variant.join(' - ')\nend\n\np titles\n</code></pre>\n<p>Which I think is some nice-looking, easy to read, easy to understand code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T10:22:52.643",
"Id": "251371",
"ParentId": "251366",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "251371",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T04:05:51.247",
"Id": "251366",
"Score": "4",
"Tags": [
"ruby"
],
"Title": "Generating product variants in Ruby"
}
|
251366
|
<p>For integer A, the base level of 1 is "XYZ"
For subsequent levels, the levels become "X" + Level (A - 1) + "Y" + Level (A - 1) + "Z".
So for level 2, the string would be "XXYZYXYZZ"</p>
<p>The objective is to return the substring from the Level string using the Start and End Index.</p>
<p>Example: If entering 2 3 7, it would Level 2, 3rd character to the 7th character and the result would be "YZYXY" from "XXYZYXYZZ"</p>
<p>The following constraints are given:</p>
<ul>
<li>1 ≦ Level K ≦ 50,</li>
<li>1 ≦ start ≦ end ≦ length of Level K String,</li>
<li>1 ≦ end - start + 1 ≦ 100.</li>
</ul>
<p>I have written a brute force approach for this problem in Python as follows</p>
<pre><code>def my_substring():
level = int(input())
start_index = int(input()) - 1
end_index = int(input())
strings_list = [None] * level
strings_list[0] = "XYZ"
for i in range(1, level):
strings_list[i] = "X" + strings_list[i - 1] + "Y" + strings_list[i - 1] + "Z"
return "".join(strings_list[-1])[start_index:end_index]
if __name__ == '__main__':
print(my_substring())
</code></pre>
<p>As shown, the length of the string will increase by (base string * 2) + 3 for each iteration. Past the 20th iteration, my program starts running into issues from having to deal with the enormous final string. I would like to learn how I can reduce my complexity from what I think is O(N^2).</p>
<p>What alternative approaches are there for me to handle/concatenate very long strings in Python? Is there a way for me to reduce the loading time/resources for doubling my strings?</p>
<p>Or is my current approach flawed and should I be approaching this issue from a different angle (one that I am so far unable to come up with an alternative for).</p>
<p>Edit: I have been told that this problem can be solved in O(1) - O(logn) time.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T07:45:01.623",
"Id": "494801",
"Score": "1",
"body": "what are `start_index` and `end_index` used for? your description missed that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T07:46:34.460",
"Id": "494802",
"Score": "0",
"body": "My apologies, they are used for retrieving the substring from the final string."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T07:48:02.287",
"Id": "494805",
"Score": "0",
"body": "My apologies, it was a typo. I used starter() for a stopwatch to confirm that my brute force approach is exponential."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T07:54:11.650",
"Id": "494808",
"Score": "0",
"body": "My apologies, I have accidentally mixed up parts from my different attempts. I have rectified the typos."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T11:36:45.313",
"Id": "494820",
"Score": "1",
"body": "Is this from from programming contest? If yes, can you provide a link? Are there any limits/constraints on the level or indices?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T11:49:58.457",
"Id": "494821",
"Score": "0",
"body": "It is from a problem sheet. The limits/constraints are 1 ≦ Level K ≦ 50, 1 ≦ start ≦ end ≦length of Level K String, and 1 ≦ end - start + 1 ≦ 100"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T16:53:33.473",
"Id": "494835",
"Score": "0",
"body": "A majority of time is consumed in the `.join`. If you just do `return strings_list[-1][start_index:end_index]`, it works fine for ~30 level. The generation from Martin's answer is obviously better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T21:11:23.740",
"Id": "494863",
"Score": "0",
"body": "Think of a tree where each node is `X{left_child}Y{right_child}Z`. The string is then an in-order traversal of the tree. You can calculate the length of a child tree from the formula given by Martin, so you know the index of X, Y, and Z. Only process a child node if it can overlap start_index to end_index.."
}
] |
[
{
"body": "<h2>User input</h2>\n<p>First of all, it's important to provide a prompt string every time that you <code>input</code>. Currently, the user is presented with a blank console - they don't even have an indication that you're waiting for them to type something; for all they know the program is just hung. Instead, do something like</p>\n<pre><code>level = int(input('Please enter the level.'))\n</code></pre>\n<p>These <code>input</code> calls should be at the same (outer) level as your <code>print</code>, not in the <code>my_substring</code> routine. <code>my_substring</code> should accept integer parameters.</p>\n<h2>String interpolation</h2>\n<p>Use an f-string; something like</p>\n<pre><code>strings[i] = f'X{strings[i - 1]}Y{strings[i - 1]Z'\n</code></pre>\n<h2>Naming</h2>\n<p>Generally instead of <code>strings_list</code>, you can just call it <code>strings</code> - the plural is a programmer hint that this is iterable, and you can add an actual <code>: List[str]</code> typehint to indicate that this is a string list.</p>\n<h2>Algorithm</h2>\n<p>Instead of doing string concatenation inside the loop (and instead of an f-string), see if your runtime improves by doing list insertion. You will still do a <code>join</code>, just over expanded indexes.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T11:54:45.643",
"Id": "251374",
"ParentId": "251369",
"Score": "3"
}
},
{
"body": "<p>The length of the string at level <span class=\"math-container\">\\$ K \\$</span> is <span class=\"math-container\">\\$ 3 (2^K -1) \\$</span>, which means that for <span class=\"math-container\">\\$ K = 50 \\$</span> a string with <span class=\"math-container\">\\$ 3377699720527869 \\$</span> characters is (recursively) built. That is about 3 <a href=\"https://en.wikipedia.org/wiki/Petabyte\" rel=\"nofollow noreferrer\">petabyte</a> (if you count one byte per character) and won't fit into the memory of your computer.</p>\n<p>On the other hand, only a small portion of that complete string is actually needed, because of the constraint <span class=\"math-container\">\\$ 1 \\le end - start + 1 \\le 100 \\$</span>. And in many cases, that substring is already contained in the string given by a previous, smaller level.</p>\n<p>Therefore I would prefer a recursive algorithm: Check the given start and end indices for the positions of "X", "Y" and "Z" from the current level, and recurse to the preceding level for the portions between those positions.</p>\n<p>Here is a possible implementation:</p>\n<pre><code>def substring(level, start_index, end_index):\n # Indices of "X", "Z", "Y" at the current level:\n low = 1\n high = 3 * (2 ** level - 1)\n mid = (low + high) // 2\n\n result = ""\n while start_index <= end_index:\n if start_index == low:\n result += "X"\n start_index += 1\n elif start_index < mid:\n e = min(end_index, mid - 1)\n result += substring(level - 1, start_index - low, e - low)\n start_index += e - start_index + 1\n elif start_index == mid:\n result += "Y"\n start_index += 1\n elif start_index < high:\n e = min(end_index, high - 1)\n result += substring(level - 1, start_index - mid, e - mid)\n start_index += e - start_index + 1\n else:\n result += "Z"\n start_index += 1\n\n return result\n</code></pre>\n<p>It computes</p>\n<pre><code>substring(50, 3377699720527869-200, 3377699720527869-100)\n</code></pre>\n<p>within fractions of a second.</p>\n<p>Further improvements are possible, e.g. by noting that the string on level K starts with K "X" characters and ends with K "Z" characters, or by handling the first level separately.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T13:28:11.283",
"Id": "251376",
"ParentId": "251369",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T07:28:26.343",
"Id": "251369",
"Score": "11",
"Tags": [
"python"
],
"Title": "Retrieving a substring from an exponentially growing string"
}
|
251369
|
<p>I was following Wes Bos JS 30-day challenge, so HTML and CSS are mostly are copy-paste,
I'd like feedback on JS (mostly).
Thanks.</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>const panels = document.querySelectorAll('.panel');
panels.forEach(panel => panel.addEventListener('click', () => {
const isOpen = panel.classList.contains('open');
panels.forEach(panel => panel.classList.remove('open'));
if(!isOpen) {
panel.classList.add('open');
}
}));
panels.forEach(panel => panel.addEventListener('transitionend', e => {
if(e.propertyName.includes('flex')) {
panels.forEach(panel => {
if(panel.classList.contains('open')) {
panel.classList.add('open-active');
} else {
panel.classList.remove('open-active');
}
});
}
}));</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
box-sizing: border-box;
background: #ffc600;
font-family: 'helvetica neue';
font-size: 20px;
font-weight: 200;
}
body {
margin: 0;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
.panels {
min-height: 100vh;
overflow: hidden;
display: flex;
}
.panel {
background: #6B0F9C;
box-shadow: inset 0 0 0 5px rgba(255, 255, 255, 0.1);
color: white;
text-align: center;
align-items: center;
/* Safari transitionend event.propertyName === flex */
/* Chrome + FF transitionend event.propertyName === flex-grow */
transition:
font-size 0.7s cubic-bezier(0.61, -0.19, 0.7, -0.11),
flex 0.7s cubic-bezier(0.61, -0.19, 0.7, -0.11), background 0.2s;
font-size: 20px;
background-size: cover;
background-position: center;
flex: 1;
display: flex;
justify-content: center;
flex-direction: column;
}
.panel1 {
background-image: url(https://source.unsplash.com/gYl-UtwNg_I/1500x1500);
}
.panel2 {
background-image: url(https://source.unsplash.com/rFKUFzjPYiQ/1500x1500);
}
.panel3 {
background-image: url(https://images.unsplash.com/photo-1465188162913-8fb5709d6d57?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&cs=tinysrgb&w=1500&h=1500&fit=crop&s=967e8a713a4e395260793fc8c802901d);
}
.panel4 {
background-image: url(https://source.unsplash.com/ITjiVXcwVng/1500x1500);
}
.panel5 {
background-image: url(https://source.unsplash.com/3MNzGlQM7qs/1500x1500);
}
/* Flex Children */
.panel>* {
margin: 0;
width: 100%;
transition: transform 0.5s;
flex: 1 0 auto;
display: flex;
align-items: center;
justify-content: center;
}
.panel *:first-child {
transform: translateY(-100%);
}
.panel *:last-child {
transform: translateY(100%);
}
.panel.open-active *:first-child,
.panel.open-active *:last-child {
transform: translateY(0);
}
.panel p {
text-transform: uppercase;
font-family: 'Amatic SC', cursive;
text-shadow: 0 0 4px rgba(0, 0, 0, 0.72), 0 0 14px rgba(0, 0, 0, 0.45);
font-size: 2em;
}
.panel p:nth-child(2) {
font-size: 4em;
}
.panel.open {
font-size: 40px;
flex: 5;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Flex Panels </title>
<link href="https://fonts.googleapis.com/css?family=Amatic+SC" rel="stylesheet" type="text/css">
</head>
<body>
<div class="panels">
<div class="panel panel1">
<p>Hey</p>
<p>Let's</p>
<p>Dance</p>
</div>
<div class="panel panel2">
<p>Give</p>
<p>Take</p>
<p>Receive</p>
</div>
<div class="panel panel3">
<p>Experience</p>
<p>It</p>
<p>Today</p>
</div>
<div class="panel panel4">
<p>Give</p>
<p>All</p>
<p>You can</p>
</div>
<div class="panel panel5">
<p>Life</p>
<p>In</p>
<p>Motion</p>
</div>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>It looks pretty good to me. I can only see a few things to consider:</p>\n<p><strong>More precise propertyName check</strong> You have <code>if(e.propertyName.includes('flex')) {</code> because Safari uses <code>flex</code> and others use <code>flex-grow</code>. Are you <em>sure</em> that the <code>flex</code> substring won't be present in any other possible CSS transitions? Even if you're sure, will readers of the code be sure? I'd change to an <code>===</code> test against both possibilities, or at least use <code>startsWith</code> (which is a bit more appropriate than <code>.includes</code> here, since both possibilities start with <code>flex</code>).</p>\n<p>You can also move the comment about the transition event name to the JS as well as the CSS.</p>\n<p><strong>Concise classList setting</strong> When you want to either add a class name, or remove a class name, based on a condition, you can condense an <code>if(...) classList.add(...) else(...) classList.remove</code> into a single <code>classList.toggle</code> with a second argument that indicates whether to add or remove the class. Your</p>\n<pre><code>if(panel.classList.contains('open')) {\n panel.classList.add('open-active');\n} else {\n panel.classList.remove('open-active');\n}\n</code></pre>\n<p>simplifies to</p>\n<pre><code>const { classList } = panel;\nclassList.toggle('open-active', classList.contains('open'));\n</code></pre>\n<p><strong>Browser compatibility</strong> Though, some ancient browsers don't support the 2nd argument, so consider what sort of browsers you need to support. If you only want to support reasonably up-to-date browsers, it's just fine. Another thing to keep in mind is that <code>NodeList.prototype.forEach</code> was only introduced a few years ago, around 2016 or 2017 IIRC; like <code>startsWith</code>, it's newer than ES6, so either use a polyfill or use iterators and Babel instead, eg:</p>\n<pre><code>for (const panel of panels) {\n // do stuff with panel\n</code></pre>\n<p>(if you want to support IE, you should be using Babel anyway, to transpile your code to ES5 syntax)</p>\n<p><strong>Void return?</strong> <code>panels.forEach(panel => panel.addEventListener</code> returns the value of calling <code>addEventListener</code> to the caller of <code>forEach</code>. Since <code>forEach</code> doesn't look at what its callbacks return, this doesn't do anything. It's not a real problem, but some might consider the code to make a bit more sense if the <code>forEach</code> callback returned void (no <code>return</code> statement or implicit return at all). (Described in TypeScript's TSLint <a href=\"https://palantir.github.io/tslint/rules/no-void-expression/\" rel=\"noreferrer\">here</a>)</p>\n<p><strong>Clickable panels</strong> Since the panels are clickable, maybe change from the default cursor to <code>cursor: pointer</code> to make it more obvious to the user that they're meant to be clicked?</p>\n<p><strong>Space between elements in selectors</strong> I'd change <code>.panel>*</code> to <code>.panel > *</code> - it makes it a bit easier to read when separate elements are separated by spaces.</p>\n<p><strong>Repetitive panels</strong> Rather than</p>\n<pre><code><div class="panel panel1">\n</div>\n<div class="panel panel2">\n</div>\n</code></pre>\n<pre><code>.panel1 {\n background-image: url(https://source.unsplash.com/gYl-UtwNg_I/1500x1500);\n}\n\n.panel2 {\n background-image: url(https://source.unsplash.com/rFKUFzjPYiQ/1500x1500);\n}\n</code></pre>\n<p>Consider using <code>:nth-child</code> instead, allowing you to remove the extra <code>panel#</code> classes entirely.</p>\n<pre><code>.panel:nth-child(1) {\n background-image: url(https://source.unsplash.com/gYl-UtwNg_I/1500x1500);\n}\n\n.panel:nth-child(2) {\n background-image: url(https://source.unsplash.com/rFKUFzjPYiQ/1500x1500);\n}\n</code></pre>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const panels = document.querySelectorAll('.panel');\n\npanels.forEach((panel) => {\n panel.addEventListener('click', () => {\n const isOpen = panel.classList.contains('open');\n panels.forEach(panel => panel.classList.remove('open'));\n if (!isOpen) {\n panel.classList.add('open');\n }\n });\n});\n\npanels.forEach((panel) => {\n panel.addEventListener('transitionend', e => {\n /* Safari transitionend event.propertyName === flex */\n /* Chrome + FF transitionend event.propertyName === flex-grow */\n if (e.propertyName === 'flex' || e.propertyName === 'flex-grow') {\n panels.forEach(panel => {\n const { classList } = panel;\n classList.toggle('open-active', classList.contains('open'));\n });\n }\n })\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>html {\n box-sizing: border-box;\n background: #ffc600;\n font-family: 'helvetica neue';\n font-size: 20px;\n font-weight: 200;\n}\n\nbody {\n margin: 0;\n}\n\n*,\n*:before,\n*:after {\n box-sizing: inherit;\n}\n\n.panels {\n min-height: 100vh;\n overflow: hidden;\n display: flex;\n}\n\n.panel {\n background: #6B0F9C;\n box-shadow: inset 0 0 0 5px rgba(255, 255, 255, 0.1);\n color: white;\n text-align: center;\n align-items: center;\n /* Safari transitionend event.propertyName === flex */\n /* Chrome + FF transitionend event.propertyName === flex-grow */\n transition:\n font-size 0.7s cubic-bezier(0.61, -0.19, 0.7, -0.11),\n flex 0.7s cubic-bezier(0.61, -0.19, 0.7, -0.11), background 0.2s;\n font-size: 20px;\n background-size: cover;\n background-position: center;\n\n flex: 1;\n display: flex;\n justify-content: center;\n flex-direction: column;\n \n cursor: pointer;\n}\n\n.panel:nth-child(1) {\n background-image: url(https://source.unsplash.com/gYl-UtwNg_I/1500x1500);\n}\n\n.panel:nth-child(2) {\n background-image: url(https://source.unsplash.com/rFKUFzjPYiQ/1500x1500);\n}\n\n.panel:nth-child(3) {\n background-image: url(https://images.unsplash.com/photo-1465188162913-8fb5709d6d57?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&cs=tinysrgb&w=1500&h=1500&fit=crop&s=967e8a713a4e395260793fc8c802901d);\n}\n\n.panel:nth-child(4) {\n background-image: url(https://source.unsplash.com/ITjiVXcwVng/1500x1500);\n}\n\n.panel:nth-child(5) {\n background-image: url(https://source.unsplash.com/3MNzGlQM7qs/1500x1500);\n}\n\n/* Flex Children */\n.panel > * {\n margin: 0;\n width: 100%;\n transition: transform 0.5s;\n flex: 1 0 auto;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\n.panel *:first-child {\n transform: translateY(-100%);\n}\n\n.panel *:last-child {\n transform: translateY(100%);\n}\n\n.panel.open-active *:first-child,\n.panel.open-active *:last-child {\n transform: translateY(0);\n}\n\n.panel p {\n text-transform: uppercase;\n font-family: 'Amatic SC', cursive;\n text-shadow: 0 0 4px rgba(0, 0, 0, 0.72), 0 0 14px rgba(0, 0, 0, 0.45);\n font-size: 2em;\n}\n\n.panel p:nth-child(2) {\n font-size: 4em;\n}\n\n.panel.open {\n font-size: 40px;\n flex: 5;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><link href=\"https://fonts.googleapis.com/css?family=Amatic+SC\" rel=\"stylesheet\" type=\"text/css\">\n<div class=\"panels\">\n <div class=\"panel\">\n <p>Hey</p>\n <p>Let's</p>\n <p>Dance</p>\n </div>\n <div class=\"panel\">\n <p>Give</p>\n <p>Take</p>\n <p>Receive</p>\n </div>\n <div class=\"panel\">\n <p>Experience</p>\n <p>It</p>\n <p>Today</p>\n </div>\n <div class=\"panel\">\n <p>Give</p>\n <p>All</p>\n <p>You can</p>\n </div>\n <div class=\"panel\">\n <p>Life</p>\n <p>In</p>\n <p>Motion</p>\n </div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T08:29:56.243",
"Id": "494903",
"Score": "0",
"body": "thanks for review and commets! i updated the code based on your comments, but i have questions.\n1. what dies this syntax do: `const { classList } = panel;`?\n2. i didn't quite get returning void. isn't it function's user fault to use value of functioning which doesn't return anything?\n3. `.panel>*` was formatted by vscode. how can i turn adding space?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T15:06:55.810",
"Id": "494960",
"Score": "1",
"body": "(1) That's destructuring: https://stackoverflow.com/questions/54605286/ Like `const classList = panel.classList` but more concise. (2) The problem is that it makes the code a tiny bit harder to understand at a glance. It's not `forEach`'s fault that the callback return isn't used, it's the callback's fault for returning something that isn't used anywhere. Not a big deal, just makes the code a bit clearer without returning something that will not be used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T21:52:56.117",
"Id": "494993",
"Score": "0",
"body": "You have got me on the Void return. The OPs code is JS not TypeScript., so the link did not help. I can not work out what you are saying here. Is it that the OP should add the function block delimiters? `=> {.p.addEv..` rather than `=> p.addEv..`. . All JS functions return a value, How do you not imply a return.? Surely you are not trying to say void the return of `addEventListener` `undefined` eg `panels.forEach(panel => void panel.addEv...` which would do nothing `(void undefined) === undefined` is true. Or am I missing something?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T22:07:35.880",
"Id": "494994",
"Score": "0",
"body": "@Blindman67 Yes, the idea is to add block delimiters so that nothing is returned, implicitly or explicitly. Consider the general case of `someFn(arg => someOtherFn(arg))`. Without looking at the implementation details, it's not clear whether `someFn` does something with the callback return value. Not returning anything by using block delimiters makes it clear that there is no link. Sure, most people probably know that `forEach`'s callback return value is ignored anyway, but it'll be a bit clearer to read without having to know that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T22:07:37.397",
"Id": "494995",
"Score": "0",
"body": "Although TS isn't JS, the rationale for the [linting rule](https://palantir.github.io/tslint/rules/no-void-expression/) still applies in JS: \"It’s misleading returning the results of an expression whose type is void\""
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T15:02:19.463",
"Id": "251380",
"ParentId": "251377",
"Score": "7"
}
},
{
"body": "<h1>Review</h1>\n<p>I agree with the answer by CertainPerformance: the code does look pretty good. Indentation seems consistent, variable names are appropriate and lines are terminated well. Readability is great.</p>\n<h2>Inefficient loops</h2>\n<p>The code in the event handlers loops over all panel elements, yet at most only two elements would have updates to their class list. See the suggestion below about ways to eliminate the loops.</p>\n<h2>Excess CSS rules</h2>\n<p>The style <code>font-size: 20px;</code> is not needed under <code>.panel</code> since the same rule is also specified on <code>html</code>, plus it gets overridden by more specific selectors.</p>\n<h1>Suggestion</h1>\n<h2>Remove loops by using <a href=\"https://davidwalsh.name/event-delegate\" rel=\"nofollow noreferrer\">Event delegation</a></h2>\n<p>Instead of adding event listeners to each panel element, event listeners can be added to the container element. This would require changing the event handlers to look at the event target and determining if the target matched a panel or child of a panel - can be done with the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/closest\" rel=\"nofollow noreferrer\"><code>.closest()</code></a> method. And a live <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection\" rel=\"nofollow noreferrer\">HTMLCollection</a> of elements with class name <code>open</code> can be fetched once using <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName\" rel=\"nofollow noreferrer\"><code>document.getElementsByClassName('open');</code></a>. Then if any elements have that class when the click handler is called the class name can be removed.</p>\n<p>This would allow adding and removing panels without needing to register the event handlers on them. While it may not make a noticable difference on a small page like this, it is wise to consider places where a loop can be avoided.</p>\n<p>In the code snippet below, the loops have been eliminated.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const panelsContainer = document.querySelector('.panels');\nconst openPanels = document.getElementsByClassName('open');\nconst openActivePanels = document.getElementsByClassName('open-active');\n\npanelsContainer.addEventListener('click', e => {\n const panel = e.target.closest('.panel');\n if (!panel) {\n return;\n }\n const isOpen = panel.classList.contains('open');\n if (openPanels.length) {\n openPanels[0].classList.remove('open');\n }\n panel.classList.toggle('open', !isOpen);\n});\npanelsContainer.addEventListener('transitionend', e => {\n /* Safari transitionend event.propertyName === flex */\n /* Chrome + FF transitionend event.propertyName === flex-grow */\n if (e.propertyName === 'flex' || e.propertyName === 'flex-grow') {\n if (openActivePanels.length) {\n openActivePanels[0].classList.toggle('open-active', openActivePanels[0].classList.contains('open'))\n }\n if (openPanels.length) {\n openPanels[0].classList.add('open-active')\n }\n }\n})</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>html {\n box-sizing: border-box;\n background: #ffc600;\n font-family: 'helvetica neue';\n font-size: 20px;\n font-weight: 200;\n}\n\nbody {\n margin: 0;\n}\n\n*,\n*:before,\n*:after {\n box-sizing: inherit;\n}\n\n.panels {\n min-height: 100vh;\n overflow: hidden;\n display: flex;\n}\n\n.panel {\n background: #6B0F9C;\n box-shadow: inset 0 0 0 5px rgba(255, 255, 255, 0.1);\n color: white;\n text-align: center;\n align-items: center;\n /* Safari transitionend event.propertyName === flex */\n /* Chrome + FF transitionend event.propertyName === flex-grow */\n transition: font-size 0.7s cubic-bezier(0.61, -0.19, 0.7, -0.11), flex 0.7s cubic-bezier(0.61, -0.19, 0.7, -0.11), background 0.2s;\n \n background-size: cover;\n background-position: center;\n flex: 1;\n display: flex;\n justify-content: center;\n flex-direction: column;\n}\n\n.panel1 {\n background-image: url(https://source.unsplash.com/gYl-UtwNg_I/1500x1500);\n}\n\n.panel2 {\n background-image: url(https://source.unsplash.com/rFKUFzjPYiQ/1500x1500);\n}\n\n.panel3 {\n background-image: url(https://images.unsplash.com/photo-1465188162913-8fb5709d6d57?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&cs=tinysrgb&w=1500&h=1500&fit=crop&s=967e8a713a4e395260793fc8c802901d);\n}\n\n.panel4 {\n background-image: url(https://source.unsplash.com/ITjiVXcwVng/1500x1500);\n}\n\n.panel5 {\n background-image: url(https://source.unsplash.com/3MNzGlQM7qs/1500x1500);\n}\n\n\n/* Flex Children */\n\n.panel>* {\n margin: 0;\n width: 100%;\n transition: transform 0.5s;\n flex: 1 0 auto;\n display: flex;\n align-items: center;\n justify-content: center;\n}\n\n.panel *:first-child {\n transform: translateY(-100%);\n}\n\n.panel *:last-child {\n transform: translateY(100%);\n}\n\n.panel.open-active *:first-child,\n.panel.open-active *:last-child {\n transform: translateY(0);\n}\n\n.panel p {\n text-transform: uppercase;\n font-family: 'Amatic SC', cursive;\n text-shadow: 0 0 4px rgba(0, 0, 0, 0.72), 0 0 14px rgba(0, 0, 0, 0.45);\n font-size: 2em;\n}\n\n.panel p:nth-child(2) {\n font-size: 4em;\n}\n\n.panel.open {\n font-size: 40px;\n flex: 5;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><!DOCTYPE html>\n<html lang=\"en\">\n\n<head>\n <meta charset=\"UTF-8\">\n <title>Flex Panels </title>\n <link href=\"https://fonts.googleapis.com/css?family=Amatic+SC\" rel=\"stylesheet\" type=\"text/css\">\n</head>\n\n<body>\n\n <div class=\"panels\">\n <div class=\"panel panel1\">\n <p>Hey</p>\n <p>Let's</p>\n <p>Dance</p>\n </div>\n <div class=\"panel panel2\">\n <p>Give</p>\n <p>Take</p>\n <p>Receive</p>\n </div>\n <div class=\"panel panel3\">\n <p>Experience</p>\n <p>It</p>\n <p>Today</p>\n </div>\n <div class=\"panel panel4\">\n <p>Give</p>\n <p>All</p>\n <p>You can</p>\n </div>\n <div class=\"panel panel5\">\n <p>Life</p>\n <p>In</p>\n <p>Motion</p>\n </div>\n </div>\n\n</body>\n\n</html></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T08:52:11.453",
"Id": "494906",
"Score": "0",
"body": "thanks for mentioning event delegation, i heard it's important best practice but had completely forgotten about it. just one question, why should i use `.closest()` instead of `e.target.classList.contains('panel')`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T11:42:27.847",
"Id": "494925",
"Score": "0",
"body": "That is a great question! It's due to [event bubbling](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_bubbling_and_capture) which might start at a [text node](https://developer.mozilla.org/en-US/docs/Web/API/Text) if the user clicks on text within an element."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T11:46:53.753",
"Id": "494926",
"Score": "1",
"body": "okay, thanks for clarification, i'll use `.closest()`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T22:50:50.980",
"Id": "251391",
"ParentId": "251377",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "251380",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T14:25:09.357",
"Id": "251377",
"Score": "8",
"Tags": [
"javascript",
"html",
"css",
"ecmascript-6",
"event-handling"
],
"Title": "Flex panels in CSS and JS"
}
|
251377
|
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/251336/231235">An element_wise_add Function For Boost.MultiArray in C++</a>. The following code is the improved version based on <a href="https://codereview.stackexchange.com/a/251348/231235">G. Sliepen's answer</a>. On the other hand, the built-in function <code>.num_dimensions()</code> I used here for the part of array dimension mismatch detection.</p>
<pre><code>template<typename T>
concept is_multi_array = requires(T x)
{
x.num_dimensions();
x.shape();
boost::multi_array(x);
};
// Add operator
template<class T1, class T2> requires (is_multi_array<T1>&& is_multi_array<T2>)
auto operator+(const T1& input1, const T2& input2)
{
if (input1.num_dimensions() != input2.num_dimensions()) // Dimensions are different, unable to perform element-wise add operation
{
throw std::logic_error("Array dimensions are different");
}
if (*input1.shape() != *input2.shape()) // Shapes are different, unable to perform element-wise add operation
{
throw std::logic_error("Array shapes are different");
}
boost::multi_array output(input1); // [ToDo] drawback to be improved: avoiding copying whole input1 array into output, but with appropriate memory allocation
for (decltype(+input1.shape()[0]) i = 0; i < input1.shape()[0]; i++)
{
output[i] = input1[i] + input2[i];
}
return output;
}
// Minus operator
template<class T1, class T2> requires (is_multi_array<T1>&& is_multi_array<T2>)
auto operator-(const T1& input1, const T2& input2)
{
if (input1.num_dimensions() != input2.num_dimensions()) // Dimensions are different, unable to perform element-wise add operation
{
throw std::logic_error("Array dimensions are different");
}
if (*input1.shape() != *input2.shape()) // Shapes are different, unable to perform element-wise add operation
{
throw std::logic_error("Array shapes are different");
}
boost::multi_array output(input1); // [ToDo] drawback to be improved: avoiding copying whole input1 array into output, but with appropriate memory allocation
for (decltype(+input1.shape()[0]) i = 0; i < input1.shape()[0]; i++)
{
output[i] = input1[i] - input2[i];
}
return output;
}
</code></pre>
<p>The test of the add/minus operator:</p>
<pre><code>int main()
{
// Create a 3D array that is 3 x 4 x 2
typedef boost::multi_array<double, 3> array_type;
typedef array_type::index index;
array_type A(boost::extents[3][4][2]);
// Assign values to the elements
int values = 0;
for (index i = 0; i != 3; ++i)
for (index j = 0; j != 4; ++j)
for (index k = 0; k != 2; ++k)
A[i][j][k] = values++;
for (index i = 0; i != 3; ++i)
for (index j = 0; j != 4; ++j)
for (index k = 0; k != 2; ++k)
std::cout << A[i][j][k] << std::endl;
auto sum_result = A;
for (size_t i = 0; i < 3; i++)
{
sum_result = sum_result + A;
}
sum_result = sum_result - A;
for (index i = 0; i != 3; ++i)
for (index j = 0; j != 4; ++j)
for (index k = 0; k != 2; ++k)
std::cout << sum_result[i][j][k] << std::endl;
return 0;
}
</code></pre>
<p>All suggestions are welcome.</p>
<ul>
<li><p>Which question it is a follow-up to?</p>
<p><a href="https://codereview.stackexchange.com/q/251336/231235">An element_wise_add Function For Boost.MultiArray in C++</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p>The previous question is the implementation of <code>element_wise_add</code> function for Boost.MultiArray. Based on <a href="https://codereview.stackexchange.com/a/251348/231235">G. Sliepen's suggestion</a>, this kind of element-wise operations could be implemented with C++ operator overloading. As the result, here comes the operator+ and operator- overload functions for Boost.MultiArray.</p>
</li>
<li><p>Why a new review is being asked for?</p>
<p>The operator+ and operator- overload functions here include the exception handling for the situation of different dimensions and shapes. Please check if this usage is appropriate. Moreover, I am still seeking another smarter method to improve the construction of <code>output</code> object. If there is any better idea for deducing the output structure from input without copying process, please let me know.</p>
</li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T14:59:20.470",
"Id": "251379",
"Score": "3",
"Tags": [
"c++",
"recursion",
"boost",
"c++20"
],
"Title": "An Add/Minus Operator For Boost.MultiArray in C++"
}
|
251379
|
<p>I have a legacy code in which <code>ids</code> List has some duplicate value coming and this method is being called from lot of difference places as of now -</p>
<pre><code>public async Task<List<T>> Execute<T>(IList<int> ids, Policy policy, Func<CancellationToken, int, Task<T>> mapperFunc) where T : class
{
var holder = new List<Task<T>>(ids.Count);
var removeNull = new List<T>(ids.Count);
for (int i = 0; i < ids.Count; i++)
{
var id = ids[i];
holder.Add(ProcessData(policy, ct => mapperFunc(ct, id)));
}
var responses = await Task.WhenAll(holder);
for (int i = 0; i < responses.Length; i++)
{
var response = responses[i];
if (response != null)
{
removeNull.Add(response);
}
}
return removeNull;
}
</code></pre>
<p>I am trying to change above method such that I can remove duplicate stuff from <code>ids</code> list so I came up with below code which does that but I wanted to see if there is any better way we can write below code?</p>
<pre><code>public async Task<List<T>> Execute<T>(IList<int> ids, Policy policy, Func<CancellationToken, int, Task<T>> mapperFunc) where T : class
{
var noDupsList = new HashSet<int>(ids).ToList();
var holder = new List<Task<T>>(noDupsList.Count);
var removeNull = new List<T>(noDupsList.Count);
for (int i = 0; i < noDupsList.Count; i++)
{
var id = noDupsList[i];
holder.Add(ProcessData(policy, ct => mapperFunc(ct, id)));
}
var responses = await Task.WhenAll(holder);
for (int i = 0; i < responses.Length; i++)
{
var response = responses[i];
if (response != null)
{
removeNull.Add(response);
}
}
return removeNull;
}
</code></pre>
<p><strong>Update</strong></p>
<p>Seeing the answer that came I thought it's good idea to mention how my actual code is - This is how my original code is :</p>
<pre><code>public async Task<List<T>> Execute<T>(IList<int> ids, Policy policy, Func<CancellationToken, int, Task<T>> mapperFunc, string logMessage) where T : class
{
var noDupsList = new HashSet<int>(ids).ToList();
var holder = new List<Task<T>>(noDupsList.Count);
var removeNull = new List<T>(noDupsList.Count);
using (var logMetric = new LogMetric(_logger, TITLE, "DatabaseCall"))
{
logMetric.Message = logMessage;
for (int i = 0; i < noDupsList.Count; i++)
{
var id = noDupsList[i];
holder.Add(ProcessData(policy, ct => mapperFunc(ct, id)));
}
var responses = await Task.WhenAll(holder);
for (int i = 0; i < responses.Length; i++)
{
var response = responses[i];
if (response != null)
{
removeNull.Add(response);
}
}
logMetric.StatusCode = (removeNull.Count == 0) ? 204 : 200;
}
return removeNull;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T18:38:17.773",
"Id": "494847",
"Score": "0",
"body": "Use `Linq` it will shorten your code and give you more readability to your code. For instance, `var uniqueIdsList = ids.Distinct().ToList();` would give you the unique ids directly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T18:46:24.113",
"Id": "494848",
"Score": "0",
"body": "Is `Linq` efficient here? I have been told its quite expensive and this method will be called at hight throughput so just wanted to make sure. But apart from that do you think we can rewrite this in better way to solve this problem or just change that one line to use linq instead of set?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T19:22:21.823",
"Id": "494849",
"Score": "0",
"body": "`Linq` is efficient in mostly, it would do the same thing, except it would be shorter, readable, and extendable. You can try to test it, and see how it would preform with the reset of the code. Compare, then decide."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T23:33:42.133",
"Id": "494870",
"Score": "0",
"body": "The problem of given you a decent answer here, is that I have no idea what `ProcessData` actually should do, neither do I know whether you can change the signature of your method. I would quite possibly keep the return type to `Task<IEnumerable<T>>` or `Task<IReadonlyList<T>>` if I have to, and the input type restricted to `IEnumerable<int> ids`. To be fair you can wrap the entire code in 1 somewhat long one liner with linq with using a `Select` (to get the tasks) and a `Where` (to filter out the nulls). Is performance a must here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T10:22:11.423",
"Id": "494911",
"Score": "0",
"body": "Where is `logMessage` coming? Do you really want to log a number here? If you really need to know if nulls got removed, I guess you could check the hashset length vs the filtered responses length, but I am not getting the logic here completely"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T22:14:54.943",
"Id": "494996",
"Score": "0",
"body": "sorry updated my code to add `logMessage`. I missed it earlier. It is just our own way of logging. I just want to wrap that in the same way it is there right now. @Icepickle"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T23:26:33.757",
"Id": "495001",
"Score": "0",
"body": "To be fair, I don't think logging should be part of this at all, couldn't this be done with a layer in between? I am assuming there is some dependency injection being done in this code (though the logging as it stands, might indicate there is not), so why not use something like a decorator/adapter pattern for the logging? That way, you can keep your efficient `Execute` method, but if you need logging, you could turn it on"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T23:38:33.747",
"Id": "495002",
"Score": "0",
"body": "That logging is our internal framework which calculates average latency and few other things on its own because that call is what we made to database so we are calculating it for metrics purpose. Also that logging does few other things that we can see like qps, latency and few other things."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T00:15:21.160",
"Id": "495004",
"Score": "0",
"body": "That should make a big difference, I believe, you could just make it so that you have an adapter that does the logging for you, but then calls your real Execute method before and after the logging (as you would have the ids & the responses, you could check in the adapter what the differences were afterwards) I am just trying to say that I can't see the logging as part of the responsibility of the Execute method"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T01:01:35.967",
"Id": "495006",
"Score": "0",
"body": "yeah make sense. I will look into that and see if I can refactor it in future release but for now what will be the best way to adapt to it with your current answer?"
}
] |
[
{
"body": "<p>I think you used a good way to filter out the duplicates, but I don't see why you feel the need to call <code>.ToList()</code> after that. A <code>HashSet</code> is perfectly iterable.</p>\n<p>As such, I believe I would write your lengthy code somewhat differently as:</p>\n<pre><code>public async Task<IReadonlyList<T>> Execute<T>(IEnumerable<int> ids, Policy policy, Func<CancellationToken, int, Task<T>> mapperFunc) where T : class \n{\n return (await Task.WhenAll(\n new HashSet<int>(ids).Select( id => ProcessData( policy, ct => mapperFunc( ct, id ) ) ) ) )\n .Where( response => response != null )\n .ToList();\n}\n</code></pre>\n<p>It will still remove all the duplicates, await all entries using the <code>Task.WhenAll</code> and remove the <code>null</code> values.</p>\n<p>As for knowing if it is more efficient I can't tell without testing. I think it is more readable, though to be fair, I would probably rather assign the results to a variable before filtering them out, saving you some brackets.</p>\n<pre><code>public async Task<IReadonlyList<T>> Execute<T>(IEnumerable<int> ids, Policy policy, Func<CancellationToken, int, Task<T>> mapperFunc) where T : class \n{\n var responses = await Task.WhenAll(\n new HashSet<int>(ids).Select( id => ProcessData( policy, ct => mapperFunc( ct, id ) ) ) );\n\n return responses\n .Where( response => response != null )\n .ToList();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T00:31:23.740",
"Id": "494871",
"Score": "0",
"body": "Thanks for your suggestion. I can update my question which has `ProcessData` method as well so that it can clear your confusion if needed but I have a question on your suggestion. Will this have any problem related to closure issue? Earlier I had closure issue with my original code so that's why I needed to initialize variable like this - `var id = ids[i];` to fix that so just making sure your suggestion will not have same problem?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T00:52:04.770",
"Id": "494874",
"Score": "0",
"body": "@AndyP, No you shouldn't have a problem there, `id` is already local because of the lambda in select"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T01:53:52.567",
"Id": "494876",
"Score": "0",
"body": "After checking your answer which I think is really good I was gonna try integrating in my solution but I realize one thing. I removed one thing from my original code which I thought is not relevant here but looking at your answer now I am confuse on how to have that in your suggestion. So I updated my question to provide my full code which has this line `using (var logMetric = new LogMetric(_logger, TITLE, \"DatabaseCall\"))` wrapped around my first for loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T01:54:45.673",
"Id": "494877",
"Score": "0",
"body": "I apologize about this as I should have added this in earlier. Now with that detail can we still use your suggestion or we need to change it? If yes, then how I can wrap around using block in your suggestion? Will it be wrapped around `var responses` block?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T01:57:28.850",
"Id": "494878",
"Score": "0",
"body": "@AndyP yes, wrap it inside the usings or use a local using statement"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T01:59:34.330",
"Id": "494879",
"Score": "0",
"body": "Can you update this in your answer as well please if possible?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T00:09:04.913",
"Id": "251394",
"ParentId": "251382",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "251394",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T17:16:02.780",
"Id": "251382",
"Score": "5",
"Tags": [
"c#"
],
"Title": "Efficiently remove duplicate elements from the list"
}
|
251382
|
<p><a href="https://i.stack.imgur.com/NmQ2g.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NmQ2g.png" alt="GUI" /></a>I have made part of a quiz game and realize that if I continue down this route my code could get huge, is there a way to simplify my code or make it more efficient?
The first couple of lines of MathsQuestions.txt are:</p>
<blockquote>
<p>1.Work out the value of 3 × 8? a)12, b)14, c)16, d)18,<br />
2.Work out the value of 4 × 2? a) 6, b) 8, c)12, d)14,<br />
3.Work out the value of 8 × 2? a) 6, b)12, c)14, d)16,</p>
</blockquote>
<pre><code>import tkinter
import tkinter as tk
from tkinter.ttk import *
from tkinter import *
class SampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self._frame = None
self.switch_frame(MainMenu)
def switch_frame(self, frame_class):
new_frame = frame_class(self)
if self._frame is not None:
self._frame.destroy()
self._frame = new_frame
self._frame.pack()
class MainMenu(tk.Frame):
def __init__(self, master):
global photo
global photo2
global photo3
global photo4
global photo5
global photo6
tk.Frame.__init__(self, master)
lbl = tk.Label(self, text="MainMenu", font=('Verdana', 40, "bold"))
lbl.grid(row=0, column=2)
#Maths Picture/Button
photo = PhotoImage(file = "MathsPicture.png")
photoimage = photo.subsample(3,3)
button = tk.Button(self, image = photo, command=lambda:[master.switch_frame(MathsQ1), MathsScoreUpdate()])
button.grid(row=1, column=1)
Mathsscore = 0
def MathsScoreUpdate(event=None):
global Mathsscore
Mathsscore += 5
x = open("MathsQuestions.txt", "r", errors = "ignore")
MathsQuestions = x.read()
MathsQ = MathsQuestions.split(",")
x.close()
#symbols
#r = row
#q = question
#a = answer
class MathsQ1(tk.Frame):
global Mathsscore
def __init__(self, master):
a = 2
r = 4
q = 0
tk.Frame.__init__(self, master)
self.pack(expand=True, anchor='n')
lbl = tk.Label(self, text=Mathsscore , font=("Verdana", 30, "bold"))
lbl.grid(row=1, column=1)
lbl = tk.Label(self, text="Score:" , font=("Verdana", 30, "bold"))
lbl.grid(row=1, column=0)
lbl = tk.Label(self, text="Q1/10", font=('Verdana', 30, "bold"))
lbl.grid(row=0, column=0)
lbl = tk.Label(self, text=MathsQ[q], font=('Verdana', 20, "bold"))
lbl.grid(row=2, column=3, columnspan=2)
btn = tk.Button(self, text=MathsQ[1] , font=("Verdana", 35, "bold"), height =1, width = 15, command=lambda:[master.switch_frame(MathsQ2), MathsScoreUpdate()])
btn.grid(row=3, column=3)
for i in range(3):
btn = tk.Button(self, text=MathsQ[a] , font=("Verdana", 35, "bold"), height =1, width = 15, command=lambda: master.switch_frame(MathsQ2))
btn.grid(row=r, column=3)
r = r + 1
a = a + 1
lbl = tk.Label(self, text="Maths Category", font=("Verdana", 25))
lbl.grid(row=0, column = 5, sticky="ne")
print(score)
print("Physics Question 1")
class MathsQ2(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.pack(expand=True, anchor='n')
a = 7
r = 4
q = 5
lbl = tk.Label(self, text=Mathsscore , font=("Verdana", 30, "bold"))
lbl.grid(row=1, column=1)
lbl = tk.Label(self, text="Score:" , font=("Verdana", 30, "bold"))
lbl.grid(row=1, column=0)
lbl = tk.Label(self, text="Q2/10", font=('Verdana', 30, "bold"))
lbl.grid(row=0, column=0)
lbl = tk.Label(self, text=MathsQ[q], font=('Verdana', 20, "bold"))
lbl.grid(row=2, column=3, columnspan=2)
btn = tk.Button(self, text=MathsQ[6] , font=("Verdana", 35, "bold"), height =1, width = 15, command=lambda:[master.switch_frame(MathsQ3), MathsScoreUpdate()])
btn.grid(row=3, column=3)
for i in range(3):
btn = tk.Button(self, text=MathsQ[a] , font=("Verdana", 35, "bold"), height =1, width = 15, command=lambda: master.switch_frame(MathsQ3))
btn.grid(row=r, column=3)
r = r + 1
a = a + 1
lbl = tk.Label(self, text="Maths Category", font=("Verdana", 25))
lbl.grid(row=0, column = 5, sticky="ne")
print(score)
class MathsQ3(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.pack(expand=True, anchor='n')
a = 12
r = 4
q = 10
lbl = tk.Label(self, text=Mathsscore , font=("Verdana", 30, "bold"))
lbl.grid(row=1, column=1)
lbl = tk.Label(self, text="Score:" , font=("Verdana", 30, "bold"))
lbl.grid(row=1, column=0)
lbl = tk.Label(self, text="Q2/10", font=('Verdana', 30, "bold"))
lbl.grid(row=0, column=0)
lbl = tk.Label(self, text=MathsQ[q], font=('Verdana', 20, "bold"))
lbl.grid(row=2, column=3, columnspan=2)
btn = tk.Button(self, text=MathsQ[11] , font=("Verdana", 35, "bold"), height =1, width = 15, command=lambda:[master.switch_frame(MathsQ4), MathsScoreUpdate()])
btn.grid(row=3, column=3)
for i in range(3):
btn = tk.Button(self, text=MathsQ[a] , font=("Verdana", 35, "bold"), height =1, width = 15, command=lambda: master.switch_frame(MathsQ4))
btn.grid(row=r, column=3)
r = r + 1
a = a + 1
lbl = tk.Label(self, text="Maths Category", font=("Verdana", 25))
lbl.grid(row=0, column = 5, sticky="ne")
print(score)
class MathsQ4(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.pack(expand=True, anchor='n')
a = 17
r = 4
q = 15
lbl = tk.Label(self, text=Mathsscore , font=("Verdana", 30, "bold"))
lbl.grid(row=1, column=1)
lbl = tk.Label(self, text="Score:" , font=("Verdana", 30, "bold"))
lbl.grid(row=1, column=0)
lbl = tk.Label(self, text="Q2/10", font=('Verdana', 30, "bold"))
lbl.grid(row=0, column=0)
lbl = tk.Label(self, text=MathsQ[q], font=('Verdana', 20, "bold"))
lbl.grid(row=2, column=3, columnspan=2)
btn = tk.Button(self, text=MathsQ[16] , font=("Verdana", 35, "bold"), height =1, width = 15, command=lambda:[master.switch_frame(MathsQ5), MathsScoreUpdate()])
btn.grid(row=3, column=3)
for i in range(3):
btn = tk.Button(self, text=MathsQ[a] , font=("Verdana", 35, "bold"), height =1, width = 15, command=lambda: master.switch_frame(MathsQ5))
btn.grid(row=r, column=3)
r = r + 1
a = a + 1
lbl = tk.Label(self, text="Maths Category", font=("Verdana", 25))
lbl.grid(row=0, column = 5, sticky="ne")
print(score)
class MathsQ5(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.pack(expand=True, anchor='n')
a = 22
r = 4
q = 20
lbl = tk.Label(self, text=Mathsscore , font=("Verdana", 30, "bold"))
lbl.grid(row=1, column=1)
lbl = tk.Label(self, text="Score:" , font=("Verdana", 30, "bold"))
lbl.grid(row=1, column=0)
lbl = tk.Label(self, text="Q2/10", font=('Verdana', 30, "bold"))
lbl.grid(row=0, column=0)
lbl = tk.Label(self, text=MathsQ[q], font=('Verdana', 20, "bold"))
lbl.grid(row=2, column=3, columnspan=2)
btn = tk.Button(self, text=MathsQ[21] , font=("Verdana", 35, "bold"), height =1, width = 15, command=lambda:[master.switch_frame(MathsQ6), MathsScoreUpdate()])
btn.grid(row=3, column=3)
for i in range(3):
btn = tk.Button(self, text=MathsQ[a] , font=("Verdana", 35, "bold"), height =1, width = 15, command=lambda: master.switch_frame(MathsQ6))
btn.grid(row=r, column=3)
r = r + 1
a = a + 1
lbl = tk.Label(self, text="Maths Category", font=("Verdana", 25))
lbl.grid(row=0, column = 5, sticky="ne")
print(score)
class MathsQ6(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.pack(expand=True, anchor='n')
a = 27
r = 4
q = 25
lbl = tk.Label(self, text=Mathsscore , font=("Verdana", 30, "bold"))
lbl.grid(row=1, column=1)
lbl = tk.Label(self, text="Score:" , font=("Verdana", 30, "bold"))
lbl.grid(row=1, column=0)
lbl = tk.Label(self, text="Q2/10", font=('Verdana', 30, "bold"))
lbl.grid(row=0, column=0)
lbl = tk.Label(self, text=MathsQ[q], font=('Verdana', 20, "bold"))
lbl.grid(row=2, column=3, columnspan=2)
btn = tk.Button(self, text=MathsQ[26] , font=("Verdana", 35, "bold"), height =1, width = 15, command=lambda:[master.switch_frame(MathsQ7), MathsScoreUpdate()])
btn.grid(row=3, column=3)
for i in range(3):
btn = tk.Button(self, text=MathsQ[a] , font=("Verdana", 35, "bold"), height =1, width = 15, command=lambda: master.switch_frame(MathsQ7))
btn.grid(row=r, column=3)
r = r + 1
a = a + 1
lbl = tk.Label(self, text="Maths Category", font=("Verdana", 25))
lbl.grid(row=0, column = 5, sticky="ne")
print(score)
class MathsQ7(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.pack(expand=True, anchor='n')
a = 32
r = 4
q = 30
lbl = tk.Label(self, text=Mathsscore , font=("Verdana", 30, "bold"))
lbl.grid(row=1, column=1)
lbl = tk.Label(self, text="Score:" , font=("Verdana", 30, "bold"))
lbl.grid(row=1, column=0)
lbl = tk.Label(self, text="Q2/10", font=('Verdana', 30, "bold"))
lbl.grid(row=0, column=0)
lbl = tk.Label(self, text=MathsQ[q], font=('Verdana', 20, "bold"))
lbl.grid(row=2, column=3, columnspan=2)
btn = tk.Button(self, text=MathsQ[31] , font=("Verdana", 35, "bold"), height =1, width = 15, command=lambda:[master.switch_frame(MathsQ8), MathsScoreUpdate()])
btn.grid(row=3, column=3)
for i in range(3):
btn = tk.Button(self, text=MathsQ[a] , font=("Verdana", 35, "bold"), height =1, width = 15, command=lambda: master.switch_frame(MathsQ8))
btn.grid(row=r, column=3)
r = r + 1
a = a + 1
lbl = tk.Label(self, text="Maths Category", font=("Verdana", 25))
lbl.grid(row=0, column = 5, sticky="ne")
print(score)
class MathsQ8(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.pack(expand=True, anchor='n')
a = 37
r = 4
q = 35
lbl = tk.Label(self, text=Mathsscore , font=("Verdana", 30, "bold"))
lbl.grid(row=1, column=1)
lbl = tk.Label(self, text="Score:" , font=("Verdana", 30, "bold"))
lbl.grid(row=1, column=0)
lbl = tk.Label(self, text="Q2/10", font=('Verdana', 30, "bold"))
lbl.grid(row=0, column=0)
lbl = tk.Label(self, text=MathsQ[q], font=('Verdana', 20, "bold"))
lbl.grid(row=2, column=3, columnspan=2)
btn = tk.Button(self, text=MathsQ[36] , font=("Verdana", 35, "bold"), height =1, width = 15, command=lambda:[master.switch_frame(MathsQ9), MathsScoreUpdate()])
btn.grid(row=3, column=3)
for i in range(3):
btn = tk.Button(self, text=MathsQ[a] , font=("Verdana", 35, "bold"), height =1, width = 15, command=lambda: master.switch_frame(MathsQ9))
btn.grid(row=r, column=3)
r = r + 1
a = a + 1
lbl = tk.Label(self, text="Maths Category", font=("Verdana", 25))
lbl.grid(row=0, column = 5, sticky="ne")
print(score)
class MathsQ9(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.pack(expand=True, anchor='n')
a = 42
r = 4
q = 40
lbl = tk.Label(self, text=Mathsscore , font=("Verdana", 30, "bold"))
lbl.grid(row=1, column=1)
lbl = tk.Label(self, text="Score:" , font=("Verdana", 30, "bold"))
lbl.grid(row=1, column=0)
lbl = tk.Label(self, text="Q2/10", font=('Verdana', 30, "bold"))
lbl.grid(row=0, column=0)
lbl = tk.Label(self, text=MathsQ[q], font=('Verdana', 20, "bold"))
lbl.grid(row=2, column=3, columnspan=2)
btn = tk.Button(self, text=MathsQ[41] , font=("Verdana", 35, "bold"), height =1, width = 15, command=lambda:[master.switch_frame(MathsQ10), MathsScoreUpdate()])
btn.grid(row=3, column=3)
for i in range(3):
btn = tk.Button(self, text=MathsQ[a] , font=("Verdana", 35, "bold"), height =1, width = 15, command=lambda: master.switch_frame(MathsQ10))
btn.grid(row=r, column=3)
r = r + 1
a = a + 1
lbl = tk.Label(self, text="Maths Category", font=("Verdana", 25))
lbl.grid(row=0, column = 5, sticky="ne")
print(score)
class MathsQ10(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.pack(expand=True, anchor='n')
a = 47
r = 4
q = 45
lbl = tk.Label(self, text=Mathsscore , font=("Verdana", 30, "bold"))
lbl.grid(row=1, column=1)
lbl = tk.Label(self, text="Score:" , font=("Verdana", 30, "bold"))
lbl.grid(row=1, column=0)
lbl = tk.Label(self, text="Q2/10", font=('Verdana', 30, "bold"))
lbl.grid(row=0, column=0)
lbl = tk.Label(self, text=MathsQ[q], font=('Verdana', 20, "bold"))
lbl.grid(row=2, column=3, columnspan=2)
btn = tk.Button(self, text=MathsQ[46] , font=("Verdana", 35, "bold"), height =1, width = 15, command=lambda:[master.switch_frame(MathsEnding), MathsScoreUpdate()])
btn.grid(row=3, column=3)
for i in range(3):
btn = tk.Button(self, text=MathsQ[a] , font=("Verdana", 35, "bold"), height =1, width = 15, command=lambda: master.switch_frame(MathsEnding))
btn.grid(row=r, column=3)
r = r + 1
a = a + 1
lbl = tk.Label(self, text="Maths Category", font=("Verdana", 25))
lbl.grid(row=0, column = 5, sticky="ne")
print(score)
class MathsEnding(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.pack(expand=True, anchor='center')
lbl = tk.Label(self, text="Congrats on completing the maths quiz, you can see you score below.\n You can either go back to the main menu or try the quiz again" , font=("Verdana", 15, "bold"))
lbl.grid(row=0, column=0, columnspan=2)
btn = tk.Button(self, text="Go back to MainMenu" , font=("Verdana", 20, "bold"), height =1, width = 18, command=lambda:master.switch_frame(MainMenu))
btn.grid(row=1, column=0)
btn = tk.Button(self, text="Restart the Quiz" , font=("Verdana", 20, "bold"), height =1, width = 15, command=lambda:master.switch_frame(MathsQ1))
btn.grid(row=1, column=1)
lbl = tk.Label(self, text=["Score", Mathsscore] , font=("Verdana", 30, "bold"))
lbl.grid(row=2, column=0)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T17:55:47.267",
"Id": "494838",
"Score": "0",
"body": "Why do you have all of the \"...\" at the end? If it's to circumvent restrictions on having more code than non-code, there's a reason for that restriction. This type of action goes against site policy."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T17:57:21.573",
"Id": "494839",
"Score": "0",
"body": "Welcome to code review! I have edited your title so that it only states what your code does. Anything else belongs in the body. Find more in [ask]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T18:05:12.407",
"Id": "494840",
"Score": "0",
"body": "Please provide us with an example of the first few lines of MathsQuestions.txt"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T18:07:24.153",
"Id": "494841",
"Score": "0",
"body": "@BryanOakley I believe this question is off-topic, since this is a \"part\" of his project which he hasn't finished yet"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T18:12:17.943",
"Id": "494843",
"Score": "0",
"body": "added the first couple of lines from MathsQuestions.txt"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T18:13:41.573",
"Id": "494845",
"Score": "0",
"body": "@WilliamG: in a technical forum, it's important to be accurate. Are you saying that the file only has a single very long line?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T18:16:52.043",
"Id": "494846",
"Score": "1",
"body": "@AryanParekh: I don't think it's off topic. While the OP says it's \"part of\" a program, I think they mean it's a complete program, except that they want to add more questions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T21:29:54.283",
"Id": "494864",
"Score": "0",
"body": "There is a question and then four possible answers, my bad for not specifying. This is a complete program but I want to add more category but i don't know if there is a better way of doing it instead of having a new class per page"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T03:56:19.733",
"Id": "494891",
"Score": "0",
"body": "@WilliamG A screenshot of the GUI would solve all the doubts!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T12:04:21.907",
"Id": "494927",
"Score": "0",
"body": "@AryanParekh I have added a picture of the GUI"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T17:32:31.873",
"Id": "495105",
"Score": "0",
"body": "(With question *1)*, how do you earn a score above 0?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-16T07:29:05.927",
"Id": "496738",
"Score": "0",
"body": "It would be quite useful to be able to run your app; as it stands all that repeated code is rather useless to work with."
}
] |
[
{
"body": "<p>Sure there are lots of ways to improve it! Let's begin with the small stuff and work our way up:</p>\n<h2>Undefined "score"</h2>\n<p>Either define it and then print it everywhere if you want, or just remove it. I removed it below.</p>\n<h2>General style</h2>\n<p>Have a look at <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> for a good start on Python code style. Use vertical spacing, separate comment text from the hash, no spaces in keyword arguments, name functions in snake case, that kind of stuff.</p>\n<h2>Imports</h2>\n<p>Discard the ones you don't use, and generally try to avoid star imports, because that can lead to name clashes and confusion. Let's just use a single import:</p>\n<pre><code>import tkinter as tk\n</code></pre>\n<h2>The big payoff: <em>don't repeat yourself</em></h2>\n<p>Keep it <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a>. When you see similar code twice, think about ways to write it only once. If you see it three times, you should definitely try to do something about that. Ten times? Boy oh boy. Fight that CTRL+C/CTRL+V instinct.</p>\n<p>By parameterising the frame creation as follows, we can <em>drastically</em> reduce the complexity of creating multiple question frames.</p>\n<pre><code>class Question(tk.Frame):\n def __init__(self, master, r, q, a, q_number, q_text, switch_to):\n super().__init__(master)\n\n self.pack(expand=True, anchor='n')\n\n lbl = tk.Label(self, text=Mathsscore, font=("Verdana", 30, "bold"))\n lbl.grid(row=1, column=1)\n lbl = tk.Label(self, text="Score:", font=("Verdana", 30, "bold"))\n lbl.grid(row=1, column=0)\n lbl = tk.Label(self, text=f"Q{q_number}/10", font=('Verdana', 30, "bold"))\n lbl.grid(row=0, column=0)\n lbl = tk.Label(self, text=MathsQ[q], font=('Verdana', 20, "bold"))\n lbl.grid(row=2, column=3, columnspan=2)\n btn = tk.Button(\n self,\n text=q_text,\n font=("Verdana", 35, "bold"),\n height=1,\n width=15,\n command=lambda: [self.master.switch_frame(switch_to), maths_score_update()]\n )\n btn.grid(row=3, column=3)\n for i in range(3):\n btn = tk.Button(\n self,\n text=MathsQ[a],\n font=("Verdana", 35, "bold"),\n height=1,\n width=15,\n command=lambda: self.master.switch_frame(switch_to)\n )\n btn.grid(row=r, column=3)\n r = r + 1\n a = a + 1\n lbl = tk.Label(self, text="Maths Category", font=("Verdana", 25))\n lbl.grid(row=0, column=5, sticky="ne")\n</code></pre>\n<p>Now creating frames is as easy as 1-2-3.</p>\n<pre><code>class MathsQ1(Question):\n def __init__(self, master):\n super().__init__(\n master, r=4, q=0, a=2, q_number=1, q_text=MathsQ[1], switch_to=MathsQ2\n )\n print("Physics Question 1")\n\n\nclass MathsQ2(Question):\n def __init__(self, master):\n super().__init__(\n master, r=4, q=5, a=7, q_number=2, q_text=MathsQ[6], switch_to=MathsQ3\n )\n\n\nclass MathsQ3(Question):\n def __init__(self, master):\n super().__init__(\n master, r=4, q=10, a=12, q_number=2, q_text=MathsQ[11], switch_to=MathsQ4\n )\n\n\nclass MathsQ4(Question):\n def __init__(self, master):\n super().__init__(\n master, r=4, q=15, a=17, q_number=2, q_text=MathsQ[16], switch_to=MathsQ5\n )\n\n\nclass MathsQ5(Question):\n def __init__(self, master):\n super().__init__(\n master, r=4, q=20, a=22, q_number=2, q_text=MathsQ[21], switch_to=MathsQ6\n )\n\n\nclass MathsQ6(Question):\n def __init__(self, master):\n super().__init__(\n master, r=4, q=25, a=27, q_number=2, q_text=MathsQ[26], switch_to=MathsQ7\n )\n\n\nclass MathsQ7(Question):\n def __init__(self, master):\n super().__init__(\n master, r=4, q=30, a=32, q_number=2, q_text=MathsQ[31], switch_to=MathsQ8\n )\n\n\nclass MathsQ8(Question):\n def __init__(self, master):\n super().__init__(\n master, r=4, q=35, a=37, q_number=2, q_text=MathsQ[36], switch_to=MathsQ9\n )\n\n\nclass MathsQ9(Question):\n def __init__(self, master):\n super().__init__(\n master, r=4, q=40, a=42, q_number=2, q_text=MathsQ[41], switch_to=MathsQ10\n )\n\n\nclass MathsQ10(Question):\n def __init__(self, master):\n super().__init__(\n master, r=4, q=45, a=47, q_number=2, q_text=MathsQ[46], switch_to=MathsEnding\n )\n</code></pre>\n<p>This should pretty much achieve the exact same functionality, but as we can see the question number stays the same across most questions. You should probably have it running from 1 to 10. You should also be able to abstract it some more yourself, maybe by extracting the font styles or creating and placing labels, but this is a start. Indeed I think the <code>switch_to</code> argument is not needed if you just pass the correct question number and use it as an index. And looks like the indices to <code>MathsQ</code> and <code>q</code> and <code>a</code> have patterns (<code>q = 5i</code>, <code>a = 5i + 2</code>, <code>qt = 5i + 1</code>), so they could be just calculated instead of inputting them by hand.</p>\n<p>Here's the final code dump just for completeness, but try changing the code yourself! Because the question and picture files were not provided, I can't promise this will run 100 %, but it should be ok at least with some debugging.</p>\n<pre><code>import tkinter as tk\n\n\nclass SampleApp(tk.Tk):\n def __init__(self):\n tk.Tk.__init__(self)\n self._frame = None\n self.switch_frame(MainMenu)\n\n def switch_frame(self, frame_class):\n new_frame = frame_class(self)\n if self._frame is not None:\n self._frame.destroy()\n self._frame = new_frame\n self._frame.pack()\n\n\nclass MainMenu(tk.Frame):\n def __init__(self, master):\n tk.Frame.__init__(self, master)\n lbl = tk.Label(self, text="MainMenu", font=('Verdana', 40, "bold"))\n lbl.grid(row=0, column=2)\n # Maths Picture/Button\n photo = tk.PhotoImage(file="MathsPicture.png")\n photoimage = photo.subsample(3, 3)\n button = tk.Button(\n self,\n image=photo,\n command=lambda: [master.switch_frame(MathsQ1), maths_score_update()]\n )\n button.grid(row=1, column=1)\n\n\nMathsscore = 0\n\n\ndef maths_score_update(event=None):\n global Mathsscore\n Mathsscore += 5\n\n\nx = open("MathsQuestions.txt", "r", errors="ignore")\nMathsQuestions = x.read()\nMathsQ = MathsQuestions.split(",")\nx.close()\n# symbols\n# r = row\n# q = question\n# a = answer\n\n\nclass Question(tk.Frame):\n def __init__(self, master, r, q, a, q_number, q_text, switch_to):\n super().__init__(master)\n\n self.pack(expand=True, anchor='n')\n\n lbl = tk.Label(self, text=Mathsscore, font=("Verdana", 30, "bold"))\n lbl.grid(row=1, column=1)\n lbl = tk.Label(self, text="Score:", font=("Verdana", 30, "bold"))\n lbl.grid(row=1, column=0)\n lbl = tk.Label(self, text=f"Q{q_number}/10", font=('Verdana', 30, "bold"))\n lbl.grid(row=0, column=0)\n lbl = tk.Label(self, text=MathsQ[q], font=('Verdana', 20, "bold"))\n lbl.grid(row=2, column=3, columnspan=2)\n btn = tk.Button(\n self,\n text=q_text,\n font=("Verdana", 35, "bold"),\n height=1,\n width=15,\n command=lambda: [self.master.switch_frame(switch_to), maths_score_update()]\n )\n btn.grid(row=3, column=3)\n for i in range(3):\n btn = tk.Button(\n self,\n text=MathsQ[a],\n font=("Verdana", 35, "bold"),\n height=1,\n width=15,\n command=lambda: self.master.switch_frame(switch_to)\n )\n btn.grid(row=r, column=3)\n r = r + 1\n a = a + 1\n lbl = tk.Label(self, text="Maths Category", font=("Verdana", 25))\n lbl.grid(row=0, column=5, sticky="ne")\n\n\nclass MathsQ1(Question):\n def __init__(self, master):\n super().__init__(\n master, r=4, q=0, a=2, q_number=1, q_text=MathsQ[1], switch_to=MathsQ2\n )\n print("Physics Question 1")\n\n\nclass MathsQ2(Question):\n def __init__(self, master):\n super().__init__(\n master, r=4, q=5, a=7, q_number=2, q_text=MathsQ[6], switch_to=MathsQ3\n )\n\n\nclass MathsQ3(Question):\n def __init__(self, master):\n super().__init__(\n master, r=4, q=10, a=12, q_number=2, q_text=MathsQ[11], switch_to=MathsQ4\n )\n\n\nclass MathsQ4(Question):\n def __init__(self, master):\n super().__init__(\n master, r=4, q=15, a=17, q_number=2, q_text=MathsQ[16], switch_to=MathsQ5\n )\n\n\nclass MathsQ5(Question):\n def __init__(self, master):\n super().__init__(\n master, r=4, q=20, a=22, q_number=2, q_text=MathsQ[21], switch_to=MathsQ6\n )\n\n\nclass MathsQ6(Question):\n def __init__(self, master):\n super().__init__(\n master, r=4, q=25, a=27, q_number=2, q_text=MathsQ[26], switch_to=MathsQ7\n )\n\n\nclass MathsQ7(Question):\n def __init__(self, master):\n super().__init__(\n master, r=4, q=30, a=32, q_number=2, q_text=MathsQ[31], switch_to=MathsQ8\n )\n\n\nclass MathsQ8(Question):\n def __init__(self, master):\n super().__init__(\n master, r=4, q=35, a=37, q_number=2, q_text=MathsQ[36], switch_to=MathsQ9\n )\n\n\nclass MathsQ9(Question):\n def __init__(self, master):\n super().__init__(\n master, r=4, q=40, a=42, q_number=2, q_text=MathsQ[41], switch_to=MathsQ10\n )\n\n\nclass MathsQ10(Question):\n def __init__(self, master):\n super().__init__(\n master, r=4, q=45, a=47, q_number=2, q_text=MathsQ[46], switch_to=MathsEnding\n )\n\n\nclass MathsEnding(tk.Frame):\n def __init__(self, master):\n tk.Frame.__init__(self, master)\n self.pack(expand=True, anchor='center')\n lbl = tk.Label(\n self,\n text=(\n "Congrats on completing the maths quiz, you can see you score below."\n "\\nYou can either go back to the main menu or try the quiz again"\n ),\n font=("Verdana", 15, "bold")\n )\n lbl.grid(row=0, column=0, columnspan=2)\n btn = tk.Button(\n self,\n text="Go back to MainMenu",\n font=("Verdana", 20, "bold"),\n height=1, width=18,\n command=lambda: master.switch_frame(MainMenu)\n )\n btn.grid(row=1, column=0)\n btn = tk.Button(\n self,\n text="Restart the Quiz",\n font=("Verdana", 20, "bold"),\n height=1,\n width=15,\n command=lambda: master.switch_frame(MathsQ1)\n )\n btn.grid(row=1, column=1)\n lbl = tk.Label(self, text=["Score", Mathsscore], font=("Verdana", 30, "bold"))\n lbl.grid(row=2, column=0)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-03T12:19:20.907",
"Id": "261576",
"ParentId": "251383",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T17:52:08.953",
"Id": "251383",
"Score": "5",
"Tags": [
"python",
"classes",
"tkinter"
],
"Title": "Quiz Game using Tkinter in Python"
}
|
251383
|
<p>I'm working on a list <strong>practice project</strong> from the book <em>"Automate the Boring Stuff with Python"</em> which asks for this:</p>
<blockquote>
<p>Write a function that takes a list value as an argument and returns a
string with all the items separated by a comma and a space, with <em>and</em>
inserted before the last item. For example, passing the previous spam
list to the function would return 'apples, bananas, tofu, and cats'.
But your function should be able to work with any list value passed to
it. Be sure to test the case where an empty list [] is passed to your
function.</p>
</blockquote>
<p>So far I've come up with this:</p>
<pre><code>def comma_code(iterable):
'''
Function that loops through every value in a list and prints it with a comma after it,
except for the last item, for which it adds an "and " at the beginning of it.
Each item is str() formatted in output to avoid concatenation issues.
'''
for i, item in enumerate(iterable):
if i == len(iterable)-1 and len(iterable) != 1: # Detect if the item is the last on the list and the list doesn't contain only 1 item (BONUS)
print('and ' + str(iterable[-1])) # Add 'and ' to the beginning
elif len(iterable) == 1: # BONUS: If list contains only 1 item,
print('Just ' + str(iterable[-1])) # replace 'and ' with 'Just '
else: # For all items other than the last one
print(str(iterable[i]) + ',', end=" ") # Add comma to the end and omit line break in print
</code></pre>
<p>There's heavy commenting because I'm fairly new and I'm trying to leave everything as clear as possible for my future self.</p>
<p>Now I wonder if there's a better way of doing this and also (subjective question) if there is something in my code that I should change for better readability and/or style. As I said, I'm fairly new and I would like to pick good coding practices from the beginning.</p>
<p>These are a couple of lists I ran through the function:</p>
<pre class="lang-py prettyprint-override"><code>spam = ['apples', 'bananas', 'tofu', 'cats']
bacon = [3.14, 'cat', 11, 'cat', True]
enty = [1]
</code></pre>
<p>And this is the working output:</p>
<pre><code>apples, bananas, tofu, and cats
3.14, cat, 11, cat, and True
Just 1
</code></pre>
<p>Thanks in advance.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T19:49:01.390",
"Id": "494852",
"Score": "7",
"body": "*\"returns a string\"* - You're not doing that at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T19:53:57.560",
"Id": "494853",
"Score": "0",
"body": "Care to explain? Is it because i'm printing the output rather than returning it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T19:56:54.273",
"Id": "494854",
"Score": "2",
"body": "Well... yeah..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T23:19:22.930",
"Id": "494869",
"Score": "0",
"body": "I fixed it, I just didn't know how to print a \"return\" value. Thanks for pointing it out, my logic was faulty."
}
] |
[
{
"body": "<h1>An alternate approach</h1>\n<ul>\n<li>The routine is same for <strong>all</strong> types of inputs, <strong>except</strong> for when the <code>len(list) == 1</code>. This is why we can use a <a href=\"https://wiki.python.org/moin/Generators\" rel=\"nofollow noreferrer\">generator function</a> to simplify the routine, and then a simple <code>if</code> statement to work with the exception</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>def comma_code(iterable):\n result = ', '.join(str(value) for value in iterable[:-1])\n return f"{result}, and {iterable[-1]}"\n</code></pre>\n<p>Now, since we have to deal with a special case, an if-statement can work</p>\n<pre class=\"lang-py prettyprint-override\"><code>def comma_code(iterable):\n if not iterable: return None\n if len(iterable) == 1: return f"Just {iterable[0]}"\n\n result = ', '.join(str(value) for value in iterable[:-1])\n return f"{result}, and {iterable[-1]}"\n</code></pre>\n<p>The question hasn't stated <strong>what</strong> to do if the size of the container is <code>0</code>, hence I have just returned <code>None</code>. As stated by @Stef in the comments, you can also return an empty string which is just <code>''</code>. <br>\nI would prefer <code>None</code> as it becomes easy to trace back if an issue occurred.<br> Moreover, you can also design a simple function that would check if the container is empty. If it is then the function can print a custom warning which can help you in debugging your code</p>\n<h1>Explanation</h1>\n<pre class=\"lang-py prettyprint-override\"><code>result = ', '.join(str(value) for value in iterable[:-1])\n</code></pre>\n<p>This is called a <a href=\"https://wiki.python.org/moin/Generators\" rel=\"nofollow noreferrer\">generator function</a>, we're basically appending <code>str(value) + ', '</code> for every <code>value</code> in <code>iterable</code>.<br> <code>iterable[:-1]</code> so that we only iterate till the second last element. <br>\nto be fully verbose, <code>:-1</code> says <em>everything in <code>iterable</code> up till the last element</em></p>\n<hr />\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T20:53:17.243",
"Id": "494861",
"Score": "3",
"body": "A gift introducing the _generator_ & _f-strings_ and explaining so gentle Applied **pythonic conciseness** like a pro."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T21:46:19.623",
"Id": "494866",
"Score": "0",
"body": "`result = ', '.join(str(value) for value in iterable[:-1])`\nIs this applying the concept of list comprehension? I'm familiar with f-string formatting and understand what generator code does for memory optimization, but i'm yet to recognize easily the format for list comprehensions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T22:46:55.107",
"Id": "494867",
"Score": "0",
"body": "I tried this, it works great and it's really compact. I only had to figure out how to print the function return values. Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T23:17:44.040",
"Id": "494868",
"Score": "0",
"body": "However, I just found an issue in the format. Output shows a comma after every item, including the next to last so it ends up looking like \"Item[1], Item[2], ... Item[-2] **,** and Item[-1]\". Simply removing the ',' after {result} in `return f\"{result}, and {iterable[-1]}\"` seems to fix the issue (In case you want to update your code)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T03:11:46.447",
"Id": "494880",
"Score": "1",
"body": "@VaneyRio Hey, sorry for the late reply, don't you need a `,` before `and`? That's how I remember my English to be, if not its simply to remove it, as you said just remove it from the f-string"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T03:13:27.587",
"Id": "494881",
"Score": "0",
"body": "@VaneyRio Do you still have any doubts? I can make a little chat room to clarify anything"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T11:04:47.663",
"Id": "494919",
"Score": "0",
"body": "Instead of `iterable[:-1]` which creates a copy, you could also call [`itertools.islice`](https://docs.python.org/3/library/itertools.html#itertools.islice) like this: `islice(iterable, len(iterable) - 1)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T11:12:07.697",
"Id": "494920",
"Score": "0",
"body": "@CristianCiupitu Never knew about that! Thanks for the suggestion, but wouldn't a simple `[]` be worth the cost for better readability?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T11:31:55.487",
"Id": "494922",
"Score": "0",
"body": "@AryanParekh indeed there's a trade-off of readability, memory and speed. Also a plain `[:-1]` slicing will be faster for small lists / tuples. There is also [`take_nth`](https://toolz.readthedocs.io/en/latest/api.html#toolz.itertoolz.take_nth) from the [pytoolz](https://pypi.python.org/pypi/toolz/) / [cytoolz](https://pypi.org/project/cytoolz/) package, which can be used like this: `take_nth(len(iterable) - 1, iterable)`. Anyway, changes like should be made only after some profiling / benchmarking."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T11:37:20.623",
"Id": "494924",
"Score": "0",
"body": "The text of the question says \"Be sure to test the case where an empty list [] is passed to your function.\" but this answer says \"Note that I am assuming len(iterable) is always >= 1\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T12:18:21.927",
"Id": "494930",
"Score": "0",
"body": "@Stef My bad, I didn't read it thoroughly, I will edit the answer now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T12:23:25.770",
"Id": "494932",
"Score": "0",
"body": "@CristianCiupitu I believe unless one is coding for something like an embedded system where memory is not free, it's not a problem! :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T13:15:44.510",
"Id": "494938",
"Score": "0",
"body": "`if len(iterable) == 0: return iterable` Why not return `\"\"` instead? The user might be surprised if the function returns something which isn't a string."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T13:28:10.390",
"Id": "494940",
"Score": "0",
"body": "@Stef Well, it wasn't mentioned in the question. I think it should just return `None`. But again, the question says nothing about handling the Exception, I edited it anyway"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T13:30:48.770",
"Id": "494942",
"Score": "0",
"body": "\"Write a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space, with *and* inserted before the last item.\" It's pretty explicit in that sentence that the return value should be a string. \"all the items\" if there are no items means no items. Thus an empty string. However, the python code showed as the answer adds the word \"Just\" in case of one element, which isn't mentioned in the text of the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T13:35:00.690",
"Id": "494943",
"Score": "0",
"body": "@VaneyRio Your question stipulates that there must be a comma \",\" before \"and\"... why are you making it an issue that this answer conforms with the task specification?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T16:06:39.817",
"Id": "494974",
"Score": "0",
"body": "@Stef I'm won't comment on that since that should be clarified by the OP. Otherwise, I would very much prefer returning `None` compared to an empty string. It's alright! There is absolutely no point in arguing further :)"
}
],
"meta_data": {
"CommentCount": "17",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T19:55:08.647",
"Id": "251386",
"ParentId": "251385",
"Score": "9"
}
},
{
"body": "<h3>Well done</h3>\n<p>First I like your attitude "for the future me". Keep that clean-coding practice. It will truely help.</p>\n<h3>Handle edge cases aside</h3>\n<p>I would extract the <em>junction-part</em> (", ", " and ") and particularly the single case ("Just "):</p>\n<pre class=\"lang-py prettyprint-override\"><code>def print_joined(iterable):\n # in unlikely case of nothing (fail-fast)\n if len(iterable) == 0:\n # raise an error or print sorry instead of returning silently\n return\n # special intro if single\n elif len(iterable) == 1:\n print('Just ' + str(iterable[0]))\n return\n\n ## multiples concatenated\n for i, item in enumerate(iterable):\n join = ', ' # default separator\n\n ## multiples concatenated\n joined_items = ''\n for i, item in enumerate(iterable):\n junction = ', ' # default separator\n\n if i == len(iterable)-2:\n junction = ' and ' # special separator before last\n elif i == len(iterable)-1:\n junction = '' # last item ends without separator\n\n joined_items += str(item) + junction # you defined item on loop, so use it\n\n print(joined_items)\n</code></pre>\n<p>This alternative is just making the different cases clear.\nAlthough a bit verbose and not very <em>pythonic</em> (no generator, no template based string-formatting used), it focuses on <strong>robustness</strong>.</p>\n<p>To give the lengthy method body structure and separate different parts for <strong>readability</strong> I inserted empty lines (vertical spacing) - individual preference of style.</p>\n<p>All edge-cases are caught in the beginning in order to <strong>return/fail fast</strong> (avoid obsolete loop). This is best-practice when it comes to validation.</p>\n<p>The <strong>core purpose</strong> can be <strong>easily read</strong> from the <strong>last line</strong> (the return line): printing items joined.\nThe side amenities like case-based junction strings are put <em>literally</em> as <strong>topping</strong>.\nRefinement can be introduced in later iterations (<strong>extensibility</strong>), depending on your experience, e.g.:</p>\n<ul>\n<li>enhanced formatting/printing (using Python's convenience functions)</li>\n<li>returning a string (making the function a formatter, independent from output interface)</li>\n<li>parameterize junction-strings (for customisation/localisation instead of hard-coded)</li>\n</ul>\n<h3>Usability: Grammar for using comma before <code>and</code> in lists</h3>\n<p>I wondered about the comma before <code>and</code> and did research.\nThe phenomenon called <a href=\"https://en.wikipedia.org/wiki/Serial_comma\" rel=\"nofollow noreferrer\"><em>serial comma</em> or <em>Oxford comma</em></a>, is described in the <em>Grammarly Blog</em> post <a href=\"https://www.grammarly.com/blog/comma-before-and/\" rel=\"nofollow noreferrer\">Comma Before And</a>. It essentially says:</p>\n<ul>\n<li>You usually put a comma before and when it’s connecting two independent clauses.</li>\n<li>It’s almost always optional to put a comma before and in a list.</li>\n<li>You should not use a comma before and if you’re only mentioning two qualities.</li>\n</ul>\n<p>Since I assume the function should <strong>list pure items</strong> (names, nouns, verbs) - not clauses - I implemented a simple <code>and</code> (without <em>serial comma</em>) to also handle 2 items grammatically correctly.</p>\n<p>Thus as long as the different junctions can't be parameterized yet, you should clarify (implicitly) applied junction-rules in a comment (doc-string).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T21:42:00.350",
"Id": "494865",
"Score": "0",
"body": "I tried this because I like the idea of testing for errors before computing anything else, however, there's a problem with this code.\nLast item (iterable[-1]) shows in the output as:\n'iterable[-1] and' rather than 'and iterable[-1]'.\n\nInverting the print statement also changes the order of the ',' to the beginning of every item printed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T14:41:19.653",
"Id": "494955",
"Score": "0",
"body": "@VaneyRio Thanks! I forgot to test my solution. Now fixed and updated the code. Note: comparison with 0-based index `i` to check for last `i == len(iterable)-1`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T15:21:00.000",
"Id": "494961",
"Score": "0",
"body": "Did some grammar research on _Oxford comma_ and SO suggests related review on [Refactor Oxford Comma function (and other functions)](https://codereview.stackexchange.com/questions/51238)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T19:57:14.203",
"Id": "251387",
"ParentId": "251385",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "251386",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T19:17:27.877",
"Id": "251385",
"Score": "9",
"Tags": [
"python",
"performance",
"formatting",
"iteration"
],
"Title": "Comma formatted list printer"
}
|
251385
|
<p>I whipped this up as an example of how infinite loops can often be used to great effect in golang, and also to discuss closing channels and worker communications. It was strictly off the cuff, but I was curious if anybody would like to offer a critique. In particular, I feel as though <code>inflight</code> is a crude implementation detail. I've done it many times, and looking at <a href="https://golang.org/src/sync/waitgroup.go?s=3500:3527#L93" rel="nofollow noreferrer">wait group implementation</a>, seems like it is a synchronized version of the same thing.</p>
<pre><code>package main
import (
"log"
)
func doStuff(datachan <-chan map[string]string, reschan chan<- int) {
for {
data, ok := <-datachan
if !ok {
log.Print("Channel closed.")
break
}
log.Printf("Data had %d length: %+v", len(data), data)
reschan<-len(data)
}
return
}
const workers = 3
func main() {
var datachan = make(chan map[string]string)
var reschan = make(chan int)
var inflight = 0
var inputs = []map[string]string {
map[string]string{ "hi": "world" },
map[string]string{ "bye": "space", "including": "moon" },
map[string]string{ "bye": "space", "including": "moon" },
map[string]string{ },
map[string]string{ },
}
// an inline funciton definition can change inflight within main()'s scope
processResults := func (res int) {
log.Printf("Main function got result %d", res)
inflight--
}
// start some workers
for i := 0; i < workers; i++{
go doStuff(datachan, reschan)
}
for _, data := range inputs {
//Select allows reading from reschan if datachan is not available for
// writing, thus freeing up a worker to read from datachan next loop
written := false
for written != true {
select {
case res := <-reschan:
processResults(res)
case datachan <- data:
inflight++
written = true
}
}
}
close(datachan)
for inflight > 0 {
processResults(<-reschan)
}
}
</code></pre>
|
[] |
[
{
"body": "<p>You wrote:</p>\n<pre><code>func doStuff(datachan <-chan map[string]string, reschan chan<- int) {\n for {\n data, ok := <-datachan\n if !ok {\n log.Print("Channel closed.")\n break\n }\n log.Printf("Data had %d length: %+v", len(data), data)\n reschan <- len(data)\n }\n return\n}\n</code></pre>\n<p>I don't understand why you didn't write:</p>\n<pre><code>func doStuff(datachan <-chan map[string]string, reschan chan<- int) {\n for data := range datachan {\n log.Printf("Data had %d length: %+v", len(data), data)\n reschan <- len(data)\n }\n log.Print("Channel closed.")\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T08:31:26.897",
"Id": "251408",
"ParentId": "251388",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T20:22:33.400",
"Id": "251388",
"Score": "1",
"Tags": [
"go",
"concurrency"
],
"Title": "SO golang example with infinite for / channel workers"
}
|
251388
|
<p>Inspired by dtolnay's procedural macro workshop (on <a href="https://github.com/dtolnay/proc-macro-workshop" rel="nofollow noreferrer">Github</a>), I have implemented a derive-macro to automatically implement the Builder pattern on a Rust struct, which allows a struct instance to be created using chained method calls on an intermediate object instead of having to provide all the required values at once. A more exact specification (along with a usage example) is given in the top-level doc comment in <code>lib.rs</code>.</p>
<p>This is my first "real" Rust project, so I'd be especially interested to hear about more idiomatic ways to approach this problem.</p>
<p><strong>lib.rs</strong></p>
<pre><code>extern crate proc_macro;
mod fields;
use proc_macro::TokenStream;
use proc_macro2::{self, Ident, Span};
use quote::{format_ident, quote};
use syn::{parse_macro_input, Data, DeriveInput, Field, Fields};
use fields::{AnalyzedField, MetaData};
/// Constructs an implementation of the builder pattern for the struct.
///
/// Generates a struct `{struct_name}Builder` that can be created using
/// the `builder()` method on the main struct.
///
/// Initialize fields of the builder using methods of the same name as
/// the fields. These can also be chained.
///
/// All fields must be set (see exceptions below) before the `build()` method
/// may be called, which will return an instance of the struct with the
/// values from the builder. If `build()` is called before all values have been set,
/// an `Incomplete{struct_name}Error` will be returned.
///
/// Fields of the form `Option<T>` in the struct do not have to be set before
/// calling `build()`.
///
/// Fields of the form `Vec<T>` can be annotated with `#[builder(each = "{arg}")]`
/// to generate a method `arg(T)` that will append its argument to the Vec.
/// A Vec that is annotated with `each` will be initialized to an empty Vec on
/// construction of the builder.
///
/// # Example
///
/// ```
/// use derive_builder::Builder;
///
/// #[derive(Builder)]
/// struct Thing {
/// num: usize,
/// name: String,
/// optional: Option<String>,
/// #[builder(each = "arg")]
/// args: Vec<i32>,
/// }
///
/// let instance = Thing::builder()
/// .num(25)
/// .name("John".to_owned())
/// .arg(5)
/// .arg(34)
/// .build()
/// .unwrap();
///
/// assert_eq!(instance.num, 25);
/// assert_eq!(instance.name, "John".to_owned());
/// assert_eq!(instance.optional, None);
/// assert_eq!(instance.args, vec![5, 34]);
/// ```
#[proc_macro_derive(Builder, attributes(builder))]
pub fn derive(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let name = &input.ident;
let fields = match input.data {
Data::Struct(syn::DataStruct {
fields: Fields::Named(fields),
..
}) => fields.named.into_iter().collect::<Vec<Field>>(),
_ => {
let e = syn::Error::new_spanned(
&input,
"the builder macro may only be used with named fields",
)
.to_compile_error();
return TokenStream::from(quote! {
fn err() { #e }
});
}
};
let mut analyzed_fields: Vec<AnalyzedField> = Vec::with_capacity(fields.len());
for field in fields {
match AnalyzedField::new(field) {
Ok(f) => analyzed_fields.push(f),
Err(e) => {
let e = e.to_compile_error();
return TokenStream::from(quote! {
fn err() { #e }
});
}
}
}
let builder_constructor = make_builder_constructor(name, &analyzed_fields);
let builder_struct = make_builder_struct(name, &analyzed_fields);
let builder_impl = make_builder_impl(name, &analyzed_fields);
let error_type = make_builder_error_type(name);
let tokens = TokenStream::from(quote! {
#builder_constructor
#builder_struct
#builder_impl
#error_type
});
tokens
}
fn make_builder_constructor(
type_name: &proc_macro2::Ident,
fields: &Vec<AnalyzedField>,
) -> proc_macro2::TokenStream {
let builder_initializers = fields.iter().map(|field| {
let ident = field.get_field().ident.as_ref().unwrap();
match field.get_meta_data() {
MetaData::Each(_, _) => quote! { #ident: std::option::Option::Some(Vec::new()) },
_ => quote! { #ident: std::option::Option::None },
}
});
let name_builder = get_builder_name(type_name);
quote! {
impl #type_name {
pub fn builder() -> #name_builder {
#name_builder {
#(#builder_initializers),*
}
}
}
}
}
fn make_builder_struct(
type_name: &proc_macro2::Ident,
fields: &Vec<AnalyzedField>,
) -> proc_macro2::TokenStream {
let option_fields = fields.iter().map(|field| {
let ident = field.get_field().ident.as_ref().unwrap();
let ty = field.get_setter_arg_type();
quote! { #ident: std::option::Option<#ty>}
});
let name_builder = get_builder_name(type_name);
quote! {
pub struct #name_builder {
#(#option_fields),*
}
}
}
fn make_builder_error_type(type_name: &proc_macro2::Ident) -> proc_macro2::TokenStream {
let error_type_name = get_error_type_name(type_name);
quote! {
#[derive(Debug)]
pub struct #error_type_name {
missing_field: &'static str,
}
impl std::fmt::Display for #error_type_name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Field {} is missing from builder.", self.missing_field)
}
}
impl std::error::Error for #error_type_name {}
}
}
fn make_builder_impl(
type_name: &proc_macro2::Ident,
fields: &Vec<AnalyzedField>,
) -> proc_macro2::TokenStream {
let methods = make_builder_methods(fields);
let error_type_name = get_error_type_name(type_name);
let name_builder = get_builder_name(type_name);
let checks = fields.iter().map(|field| {
let ident = field.get_field().ident.as_ref().unwrap();
match field.get_meta_data() {
MetaData::Optional(_) => {
quote! {
let #ident = self.#ident.take();
}
}
_ => {
let field_name = ident.to_string();
quote! {
let #ident = self.#ident.take()
.ok_or(#error_type_name { missing_field: #field_name })?;
}
}
}
});
let setters = fields.iter().map(|field| {
let ident = field.get_field().ident.as_ref().unwrap();
quote! {
#ident
}
});
quote! {
impl #name_builder {
#(#methods)*
pub fn build(&mut self) -> std::result::Result<#type_name, #error_type_name> {
#(#checks)*
Ok(#type_name {
#(#setters),*
})
}
}
}
}
fn make_builder_methods(fields: &Vec<AnalyzedField>) -> Vec<proc_macro2::TokenStream> {
fields
.iter()
.map(|field| {
let ident = field.get_field().ident.as_ref().unwrap();
let ty = field.get_setter_arg_type();
let mut setter = quote! {
pub fn #ident(&mut self, #ident: #ty) -> &mut Self {
self.#ident = std::option::Option::Some(#ident);
self
}
};
let mut appender = proc_macro2::TokenStream::new();
match field.get_meta_data() {
MetaData::Each(ref s, ref t) => {
let appender_ident = Ident::new(s, Span::call_site());
if &ident.to_string() == s {
setter = proc_macro2::TokenStream::new();
}
appender = quote! {
pub fn #appender_ident(&mut self, #appender_ident: #t) -> &mut Self {
self.#ident.as_mut().unwrap().push(#appender_ident);
self
}
};
}
_ => (),
};
quote! {
#setter
#appender
}
})
.collect()
}
fn get_builder_name(type_name: &proc_macro2::Ident) -> proc_macro2::Ident {
format_ident!("{}Builder", type_name)
}
fn get_error_type_name(type_name: &proc_macro2::Ident) -> proc_macro2::Ident {
format_ident!("Incomplete{}Error", type_name)
}
</code></pre>
<p><strong>fields.rs</strong></p>
<pre><code>use proc_macro2::{self, Ident};
use syn::Field;
/// A struct field that has been analyzed for
/// properties of interest to the Builder macro.
/// The results of the analysis are given as [`MetaData`].
pub struct AnalyzedField {
field: Field,
meta: MetaData,
}
/// Holds additional information on fields to be initialized
/// in the builder.
pub enum MetaData {
/// A field with no special treatment
Normal,
/// A field that is an [Option<T>] in the final struct
/// and is thus not obligatory to set in the builder.
/// The contained type is the `T` from the Option.
Optional(syn::Type),
/// A field that is a [Vec<T>] in the struct
/// and can be appended to in the builder using the method
/// with the name in the string.
/// The contained type is the `T` from the Vec.
Each(String, syn::Type),
}
const EACH_KEYWORD: &str = "each";
const ATTR_PATH: &str = "builder";
const EACH_REQ_TYPE: &str = "Vec";
const OPTIONAL_TYPE: &str = "Option";
impl AnalyzedField {
/// Analyzes the field and initializes the attached metadata.
/// Returns an error if one occured while parsing a builder attribute
/// or if there was a type mismatch between attribute requirements
/// and the given types in the struct (e.g. "each" requires a [Vec<T>]).
pub fn new(field: Field) -> Result<Self, syn::Error> {
let builder_attr = Self::get_builder_attr(&field);
if let Some(attr) = builder_attr {
let appender_name = Self::parse_each_attribute(attr)?;
match Self::get_generic_type(&field, EACH_REQ_TYPE) {
Some(t) => Ok(Self {
field,
meta: MetaData::Each(appender_name, t),
}),
None => Err(syn::Error::new_spanned(
field,
format!("`{}` requires type {}<T>", EACH_KEYWORD, EACH_REQ_TYPE),
)),
}
} else if let Some(t) = Self::get_generic_type(&field, OPTIONAL_TYPE) {
Ok(Self {
field,
meta: MetaData::Optional(t),
})
} else {
Ok(Self {
field,
meta: MetaData::Normal,
})
}
}
/// Returns the field this instance was initialized with.
pub fn get_field(&self) -> &Field {
&self.field
}
/// Returns the meta data associated with the field.
pub fn get_meta_data(&self) -> &MetaData {
&self.meta
}
/// If the field's type is of the form ty<T>, returns Some(T).
fn get_generic_type(field: &Field, ty: &str) -> Option<syn::Type> {
if let &syn::Type::Path(syn::TypePath {
qself: None,
ref path,
}) = &field.ty
{
if path.segments.len() != 1 {
return None;
}
let segment = path.segments.first().unwrap();
if segment.ident.to_string() != ty.to_owned() {
return None;
}
match segment.arguments {
syn::PathArguments::AngleBracketed(ref args) => {
Self::extract_generic_argument(args)
}
_ => None,
}
} else {
None
}
}
/// If there is exactly one generic arguments, returns it.
fn extract_generic_argument(args: &syn::AngleBracketedGenericArguments) -> Option<syn::Type> {
if args.args.len() == 1 {
match args.args.first().unwrap() {
syn::GenericArgument::Type(ref t) => Some(t.clone()),
_ => None,
}
} else {
None
}
}
/// Returns an attribute of the form #[builder(...)] if one exists on the field.
fn get_builder_attr(field: &Field) -> Option<&syn::Attribute> {
field
.attrs
.iter()
.find(|attr| attr.path.get_ident().map(Ident::to_string) == Some(ATTR_PATH.to_owned()))
}
/// Parses an attribute of the form #[builder(each = "...")] and returns
/// the literal string argument. Returns an error if the attribute cannot
/// be parsed in this manner.
fn parse_each_attribute(attr: &syn::Attribute) -> Result<String, syn::Error> {
let meta = attr.parse_meta()?;
let error = Err(syn::Error::new_spanned(
&meta,
format!("expected `{}({} = \"...\")`", ATTR_PATH, EACH_KEYWORD),
));
let args = if let syn::Meta::List(ref list) = meta {
&list.nested
} else {
return error;
};
if args.len() != 1 {
return error;
}
if let Some(&syn::NestedMeta::Meta(syn::Meta::NameValue(ref name))) = args.first() {
if name.path.get_ident().map(Ident::to_string) == Some(EACH_KEYWORD.to_owned()) {
match &name.lit {
&syn::Lit::Str(ref lit_str) => return Ok(lit_str.value()),
_ => return error,
}
} else {
return error;
}
} else {
return error;
}
}
/// Gets the type that should be used by a setter in the builder.
pub fn get_setter_arg_type(&self) -> &syn::Type {
match &self.meta {
&MetaData::Optional(ref t) => t,
_ => &self.field.ty,
}
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T21:59:31.010",
"Id": "251390",
"Score": "3",
"Tags": [
"beginner",
"rust",
"macros"
],
"Title": "Rust Builder pattern derive-macro"
}
|
251390
|
<p>I wrote a very simple implementation of cycle detection in an undirected graph; I'm not interested in applying it to any real-life case: it's just for explaining the basic idea behind cycle detection in a CS lesson.</p>
<p>I went for recursive DFS, and unlike other implementations I found on the internet, I used just one set for the visited nodes (instead of having a set for the visited nodes and another one for the ancestors):</p>
<pre><code>boolean hasCycleDfs(Node current, Set<Node> visited) {
if (visited.contains(current)) {
return true;
}
visited.add(current);
for (Node neighbour: current.neighbors) {
if (hasCycleDfs(neighbour, visited)) {
return true;
}
}
visited.remove(current);
return false;
}
</code></pre>
<p>I wrote a couple of tests and they're green:</p>
<pre><code> @Test
public void test() {
List<Node> nodes = IntStream
.range(1, 8)
.mapToObj(Node::new)
.collect(Collectors.toList());
Node n1 = nodes.get(0);
Node n2 = nodes.get(1);
Node n3 = nodes.get(2);
Node n4 = nodes.get(3);
Node n5 = nodes.get(4);
Node n6 = nodes.get(5);
Node n7 = nodes.get(6);
n1.add(n2).add(n3);
n2.add(n4);
n3.add(n4).add(n6);
n4.add(n6).add(n7);
n5.add(n1);
n6.add(n5);
assertTrue(hasCycleDfs(n1, new HashSet<>()));
cleanNodes(nodes);
n1.add(n2);
n2.add(n3);
n3.add(n4);
n4.add(n1);
assertTrue(hasCycleDfs(n1, new HashSet<>()));
cleanNodes(nodes);
n1.add(n2).add(n5).add(n3);
n2.add(n3).add(n5);
n3.add(n4).add(n5);
n4.add(n5);
assertFalse(hasCycleDfs(n1, new HashSet<>()));
cleanNodes(nodes);
n1.add(n2).add(n3);
n2.add(n3);
assertFalse(hasCycleDfs(n1, new HashSet<>()));
}
void cleanNodes(List<Node> nodes) {
nodes.forEach(Node::clearNeighbours);
}
</code></pre>
<p>This is the Node class:</p>
<pre><code>class Node {
int val;
Set<Node> neighbors = new HashSet<>();
Node(int val) {
this.val = val;
}
public Node add(Node child) {
neighbors.add(child);
return this;
}
public void clearNeighbours() {
neighbors.clear();
}
@Override
public String toString() {
return "[" + val + "]";
}
@Override
public boolean equals(Object o) {
Node node = (Node) o;
return val == node.val;
}
@Override
public int hashCode() {
return val * 31;
}
}
</code></pre>
<p>Do you see any edge case I didn't take into account that will give a wrong answer?</p>
|
[] |
[
{
"body": "<p>The code looks clean and organized, but there is an issue with the implementation.</p>\n<h2>Undirected graph</h2>\n<p>Consider an undirected graph <code>A - B</code>:</p>\n<ul>\n<li>B is neighbor of A</li>\n<li><strong>A is neighbor of B</strong></li>\n</ul>\n<p>Using the current implementation I would create the graph like this:</p>\n<pre><code>Node a = new Node(1);\nNode b = new Node(2);\n\na.add(b);\nb.add(a);\n</code></pre>\n<p>Such graph is not cyclic, but the method <code>hasCycleDfs</code> returns <code>true</code>.</p>\n<blockquote>\n<p>unlike other implementations I found on the internet, I used just one\nset for the visited nodes (instead of having a set for the visited\nnodes and another one for the ancestors)</p>\n</blockquote>\n<p>The reason for the set of ancestors is to handle this case.</p>\n<h2>Testing</h2>\n<ul>\n<li>Is good practice to have one method for test case, instead of a single method with all the tests. It will help you pinpoint the failing test quicker without having to look at the code.</li>\n<li>Once you have multiple <code>@Test</code> methods, you can clean the state in a method annotated with <code>@Before</code> (<code>@BeforeEach</code> in Junit5) or simply recreate the graph from scratch every time.</li>\n</ul>\n<h2>Minor improvements</h2>\n<ul>\n<li>The methods of <code>Node</code> are <code>public</code> unlike the class and instance variables. Use the access modifiers consistently.</li>\n<li>In a non‐academic context, the method <code>hasCycleDfs</code> should be <code>private</code> as it needs to be called with and empty set:\n<pre><code>boolean hasCycleDfs(Node current) {\n return hasCycleDfs(Node current, new HashSet<>());\n}\nprivate boolean hasCycleDfs(Node current, Set<Node> visited) {\n //...\n}\n</code></pre>\n</li>\n</ul>\n<h2>Rewrite</h2>\n<p>Actually, there is no need for a set of ancestors, a pointer to the parent is enough:</p>\n<pre><code>boolean hasCycleDfs(Node current, Set<Node> visited, Node parent) {\n visited.add(current);\n for (Node neighbour : current.neighbors) {\n if (!visited.contains(neighbour)) {\n if (hasCycleDfs(neighbour, visited, current)) {\n return true;\n }\n } else if (!neighbour.equals(parent)) {\n // If the node is visited and not parent of \n // the current node, then there is a cycle\n return true;\n }\n }\n return false;\n}\n</code></pre>\n<p>And you can use it like:</p>\n<pre><code>hasCycleDfs(n1, new HashSet<>(), null);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T08:39:24.163",
"Id": "496163",
"Score": "0",
"body": "Thanks Marc, super useful review!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T08:56:43.417",
"Id": "496164",
"Score": "0",
"body": "@AndreaIacono glad I could help. Any reason for the downvote?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T09:21:59.287",
"Id": "496165",
"Score": "0",
"body": "actually I pressed it by mistake while accepting your anwser, and now it doesn't allow me to edit anymore (unless you edit the answer). Can you edit it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T09:23:12.763",
"Id": "496166",
"Score": "0",
"body": "I also realized that my tests are incosistent with the title of the question: they build a directed graph instead of an undirected graph"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T09:36:36.360",
"Id": "496167",
"Score": "0",
"body": "@AndreaIacono edited the answer. Yeah, the tests seems to build a directed graph. An additional suggestion is to create a class `Graph` with a method `addEdge(a,b)` to simplify the graph creation."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-10T03:31:52.570",
"Id": "251885",
"ParentId": "251392",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "251885",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T23:21:17.083",
"Id": "251392",
"Score": "7",
"Tags": [
"java",
"graph"
],
"Title": "Cycle detection in undirected graphs with recursive DFS"
}
|
251392
|
<p>Exact problem statement:</p>
<blockquote>
<p>A main thread spawns 2 new threads, the main thread waits on this
threads with these conditions:</p>
<ol>
<li>if any of the threads returns True, then main thread moves on and prints the thread_id and timestamp of the thread.</li>
<li>if both threads return false, finish execution and don't print anything</li>
</ol>
</blockquote>
<p>My attempt:</p>
<pre><code>public static void main(String[] args) throws InterruptedException, ExecutionException{
FutureTask<Boolean> futureTask = new FutureTask<>(() -> {
System.out.println("Hello, World 1!");
return true;
});
FutureTask<Boolean> futureTask2 = new FutureTask<>(() -> {
System.out.println("Hello, World 2!");
return true;
});
Thread t1 = new Thread(futureTask);
Thread t2 = new Thread(futureTask2);
t1.start();
t2.start();
// Wait for either to be done.
while (!futureTask.isDone() && !futureTask2.isDone());
if (futureTask.isDone()) {
if (futureTask.get()) {
System.out.println("1 - " + t1.getId() + " " + System.currentTimeMillis());
return;
}
}
if (futureTask2.isDone()) {
if (futureTask2.get()) {
System.out.println("2 - " + t2.getId() + " " + System.currentTimeMillis());
return;
}
}
}
}
</code></pre>
<p>When I run this a few times, sometimes thread 1 wins, sometimes 2, which seems to make sense to me. Appreciate any room for improvement or advice.</p>
|
[] |
[
{
"body": "<p>Caveat: I don't know java. Since this site is pretty low volume, figured I'd offer some thoughts anyhow.</p>\n<p>The first function sleeps for 2 seconds, the other doesn't. How does <code>Hello, world 1!</code> ever get done first? Or is that not what "win" means?</p>\n<p>Looking at <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/FutureTask.html#isDone()\" rel=\"nofollow noreferrer\">some doc</a>, <code>isDone</code> doesn't appear to block. Thus, I don't see why your <code>while()</code> is blocking on any event. That means it's a loop of unbounded CPU cycles, and that's never good. At least, as I've seen some examples do, you should sleep a bit, perhaps some ms, before checking again. Otherwise, you're looping and checking the results as fast as you can. That seems less than optimal.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T05:02:34.313",
"Id": "494894",
"Score": "0",
"body": "I'm sorry, I added the sleep later on and forgot about it, fixed it now. But yes, if the sleep is there, this program prints ```Hello, world 1!``` deterministically and all the time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T05:03:17.640",
"Id": "494895",
"Score": "0",
"body": ">Otherwise, you're looping and checking the results as fast as you can. That seems less than optimal.\n\nVery interesting! Yes, a sleep of perhaps 300ms is a good idea at that check."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T01:57:23.567",
"Id": "251397",
"ParentId": "251393",
"Score": "1"
}
},
{
"body": "<p>In my opinion, there are one flaw in your current implementation.</p>\n<h3>You need to manually check if the threads are done executing manually (they are multiple ways to do that automatically).</h3>\n<p>At the moment, you need to manually check the state of the thread.</p>\n<p>For your code, I would suggest you to use the <a href=\"https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/concurrent/ExecutorService.html\" rel=\"nofollow noreferrer\"><code>java.util.concurrent.ExecutorService</code></a>, if you are allowed to use it.</p>\n<p>This service allows you to control the execution of the threads; they are multiple implementation of this service (each implementation run threads differently depending of the conditions).</p>\n<p>For your case, I would use the <code>FixedThreadPool</code>, that run a maximum number of threads at the same time.</p>\n<p>If you can use it, it will allow you to replace the <code>while</code> and the part where you start the threads manually.</p>\n<pre class=\"lang-java prettyprint-override\"><code>ExecutorService taskExecutor = Executors.newFixedThreadPool(2); // Two execution maximum at the same time\n\nThread t1 = new Thread(futureTask);\nThread t2 = new Thread(futureTask2);\n\ntaskExecutor.execute(t1); // Here, you could put directly the `FutureTask`, but since we need the id, we use the thread.\ntaskExecutor.execute(t2);\n\ntaskExecutor.shutdown(); // We close the executor, since if we don’t, the main thread will continue and not end even if the two other threads are done.\n\ntry {\n taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); // Here, we add a time limit on the execution, you can add any time.\n} catch (InterruptedException e) {\n System.out.println("One of the thread ran more than the allowed time!");\n}\n</code></pre>\n<p>This way if not optimal when executed multiple time, since you need to recreate a <code>java.util.concurrent.ExecutorService</code> on each execution, but is fine in this case, in my opinion.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T23:48:40.623",
"Id": "495003",
"Score": "0",
"body": "Great idea about the executors, I did not know that you could pass in a `Thread` to an executor. Another way to avoid using `Thread` is to make a simple nested class returned by the Future which includes both the boolean result and a string containing the threadID and timestamp."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T12:46:51.990",
"Id": "251421",
"ParentId": "251393",
"Score": "2"
}
},
{
"body": "<h3>Bug</h3>\n<p>I'd post this as a comment and a close vote, but you already have two answers.</p>\n<p>Your program does not actually fulfill the problem statement. If one thread quickly returns false and the other has not finished yet (but will return true eventually), your program halts and prints nothing. But instead, it should wait for the second thread to finish.</p>\n<h3>Testing</h3>\n<p>You could have found this yourself with a more robust testing framework. You should test all of the following situations:</p>\n<ol>\n<li>Both return true. Task 1 returns first.</li>\n<li>Both return true. Task 2 returns first.</li>\n<li>Task 1 returns true first and later task 2 would return false.</li>\n<li>Task 1 returns true but task 2 returns false later.</li>\n<li>Task 2 returns true first and later task 1 would return false.</li>\n<li>Task 2 returns true but task 1 returns false later.</li>\n<li>Both return false. Task 1 returns first.</li>\n<li>Both return false. Task 2 returns first.</li>\n</ol>\n<p>You might also want to check what happens when a task never returns. There may be other edge cases as well.</p>\n<h3>Numbered variables</h3>\n<p>Variables named 1 and 2 are a potential code smell. In general when you have this, you should consider if you could actually either name the variables better or switch to a collection (e.g. an array or something that implements the <code>Collection</code> interface).</p>\n<p>A side benefit of switching to a collection is that it frees you up in case the requirements change from two to another number.</p>\n<p>This is not to say that there are no circumstances under which numbered variables are OK. Only that when you consider using them, you should consider if they really make sense.</p>\n<h3>Modularization</h3>\n<p>To make testing easier, I would move the main code outside of the <code>main</code> method. So instead of editing the <code>main</code> method for each test, your tests would create the appropriate tasks and pass them to the task runner. The task runner could then enshrine the logic of</p>\n<ol>\n<li>Create threads.</li>\n<li>Launch them.</li>\n<li>Check if they are finished.</li>\n<li>If one is finished, check if its task returned true and produce the correct output.</li>\n<li>If both returned false, return.</li>\n</ol>\n<p>Note that this will be easier to test if the task runner method returns a string rather than printing output. You can leave the printing logic in your <code>main</code> method.</p>\n<h3>Test frameworks</h3>\n<p>Even better than putting your tests in your <code>main</code> method, put them into some kind of test framework. E.g. JUnit. With a testing framework, it is easy to run every test every time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T22:20:02.533",
"Id": "494997",
"Score": "0",
"body": "'Your program does not actually fulfill the problem statement. If one thread quickly returns false and the other has not finished yet (but will return true eventually), your program halts and prints nothing.'\n\nDarn, you're right. Thanks. Will re-write this. Modularization is also a good idea."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T16:25:35.553",
"Id": "251429",
"ParentId": "251393",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "251429",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-31T23:30:35.300",
"Id": "251393",
"Score": "3",
"Tags": [
"java",
"multithreading"
],
"Title": "Spawning two threads and if any of the threads returns true, let the main thread ignore the other and move on"
}
|
251393
|
<p>This is a programming question from <a href="https://leetcode.com/problems/longest-palindromic-substring/" rel="noreferrer">LeetCode</a>:</p>
<blockquote>
<p>Given a string s, return the longest palindromic substring in s.</p>
<p>Example 1:</p>
<p>Input: s = "babad" Output: "bab" Note: "aba" is also a valid answer.</p>
</blockquote>
<p>Below is my code that fails the following input because of "Time Limit Exceeded":</p>
<blockquote>
<p>"glwhcebdjbdroiurzfxxrbhzibilmcfasshhtyngwrsnbdpzgjphujzuawbebyhvxfhtoozcitaqibvvowyluvdbvoqikgojxcefzpdgahujuxpiclrrmalncdrotsgkpnfyujgvmhydrzdpiudkfchtklsaprptkzhwxsgafsvkahkbsighlyhjvbburdfjdfvjbaiivqxdqwivsjzztzkzygcsyxlvvwlckbsmvwjvrhvqfewjxgefeowfhrcturolvfgxilqdqvitbcebuooclugypurlsbdfquzsqngbscqwlrdpxeahricvtfqpnrfwbyjvahrtosovsbzhxtutyfjwjbpkfujeoueykmbcjtluuxvmffwgqjgrtsxtdimsescgahnudmsmyfijtfrcbkibbypenxnpiozzrnljazjgrftitldcueswqitrcvjzvlhionutppppzxoepvtzhkzjetpfqsuirdcyqfjsqhdewswldawhdyijhpqtrwgyfmmyhhkrafisicstqxokdmynnnqxaekzcgygsuzfiguujyxowqdfylesbzhnpznayzlinerzdqjrylyfzndgqokovabhzuskwozuxcsmyclvfwkbimhkdmjacesnvorrrvdwcgfewchbsyzrkktsjxgyybgwbvktvxyurufsrdufcunnfswqddukqrxyrueienhccpeuqbkbumlpxnudmwqdkzvsqsozkifpznwapxaxdclxjxuciyulsbxvwdoiolgxkhlrytiwrpvtjdwsssahupoyyjveedgqsthefdyxvjweaimadykubntfqcpbjyqbtnunuxzyytxfedrycsdhkfymaykeubowvkszzwmbbjezrphqildkmllskfawmcohdqalgccffxursvbyikjoglnillapcbcjuhaxukfhalcslemluvornmijbeawxzokgnlzugxkshrpojrwaasgfmjvkghpdyxt"</p>
</blockquote>
<pre><code>class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
if len(s) == 0:
return None
if len(s) == 1:
return s
P = [[False]*len(s) for i in range(len(s))]
for i in range(len(s)):
P[i][i] = True
for i in range(len(s)-1):
P[i][i+1] = (s[i]==s[i+1])
for s_len in range(3,len(s)+1):
for i in range(len(s)+1-s_len):
P[i][i+s_len-1] = P[i+1][i+s_len-2] and (s[i]==s[i+s_len-1])
ip = 0
jp = 0
max_len = 1
for i in range(len(s)):
for j in range(len(s)):
if P[i][j] and j+1-i > max_len:
max_len = j+1-i
ip = i
jp = j
continue
return s[ip:jp+1]
</code></pre>
<p>I was trying to follow the following approach described in the site solution. Could anyone help to see how to make my code more efficient?</p>
<hr />
<p><a href="https://i.stack.imgur.com/aYaos.png" rel="noreferrer"><img src="https://i.stack.imgur.com/aYaos.png" alt="enter image description here" /></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T03:20:42.060",
"Id": "494882",
"Score": "2",
"body": "Would you like to see other solutions too?"
}
] |
[
{
"body": "<h3>Disclaimer: Not a Code Reviewer</h3>\n<p>Here are some short comments though:</p>\n<ul>\n<li>You're looping though twice.</li>\n<li>That'd make it brute force.</li>\n<li>Brute force does usually fail for some medium and hard questions on LeetCode.</li>\n</ul>\n<h3>Alternative Solution</h3>\n<ul>\n<li>Here we'd loop through once:</li>\n</ul>\n<pre><code>class Solution:\n def longestPalindrome(self, s):\n if len(s) < 1:\n return s\n\n def isPalindrome(left, right):\n return s[left:right] == s[left:right][::-1]\n\n left, right = 0, 1\n for index in range(1, len(s)):\n if index - right > 0 and isPalindrome(index - right - 1, index + 1):\n left, right = index - right - 1, right + 2\n if index - right >= 0 and isPalindrome(index - right, index + 1):\n left, right = index - right, right + 1\n return s[left: left + right]\n\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/yCbfT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/yCbfT.png\" alt=\"enter image description here\" /></a></p>\n<h3>Your Solution</h3>\n<ul>\n<li>I just tested your solution (marginally passes):</li>\n</ul>\n<pre><code>class Solution(object):\n\n def longestPalindrome(self, s):\n """\n :type s: str\n :rtype: str\n """\n if len(s) < 1:\n return s\n\n P = [[False] * len(s) for i in range(len(s))]\n\n for i in range(len(s)):\n P[i][i] = True\n\n for i in range(len(s) - 1):\n P[i][i + 1] = (s[i] == s[i + 1])\n\n for s_len in range(3, len(s) + 1):\n for i in range(len(s) + 1 - s_len):\n P[i][i + s_len - 1] = P[i + 1][i + s_len - 2] and (s[i] == s[i + s_len - 1])\n\n ip = 0\n jp = 0\n max_len = 1\n\n for i in range(len(s)):\n for j in range(len(s)):\n if P[i][j] and j + 1 - i > max_len:\n max_len = j + 1 - i\n ip = i\n jp = j\n continue\n\n return s[ip:jp + 1]\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/TedP3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/TedP3.png\" alt=\"enter image description here\" /></a></p>\n<ul>\n<li><p>Since the runtimes is high, it's possible that it would fail sometimes.</p>\n</li>\n<li><p>I guess LeetCode has a time limit for each problem, maybe 10 seconds would be the limit for this specific problem.</p>\n</li>\n<li><p>Probably based on the geolocation/time, the runtime would be different also.</p>\n</li>\n</ul>\n<hr />\n<h3>Just a bit more optimization:</h3>\n<ul>\n<li>Please see this line <code>for j in range(i + 1, len(s)):</code>:</li>\n</ul>\n<pre><code>class Solution(object):\n\n def longestPalindrome(self, s):\n """\n :type s: str\n :rtype: str\n """\n if len(s) < 1:\n return s\n\n P = [[False] * len(s) for _ in range(len(s))]\n\n for i in range(len(s)):\n P[i][i] = True\n\n for i in range(len(s) - 1):\n P[i][i + 1] = (s[i] == s[i + 1])\n\n for s_len in range(3, len(s) + 1):\n for i in range(len(s) + 1 - s_len):\n P[i][i + s_len - 1] = P[i + 1][i + s_len - 2] and (s[i] == s[i + s_len - 1])\n\n ip = 0\n jp = 0\n max_len = 1\n\n for i in range(len(s)):\n for j in range(i + 1, len(s)):\n if P[i][j] and j + 1 - i > max_len:\n max_len = j + 1 - i\n ip = i\n jp = j\n continue\n\n return s[ip:jp + 1]\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/I9Ccz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/I9Ccz.png\" alt=\"enter image description here\" /></a></p>\n<ul>\n<li><p>It reduces about 1 second but still not good.</p>\n</li>\n<li><p>I'm sure there are more ways to optimize.</p>\n</li>\n<li><p>Wait a bit! There are good Python reviewers here. Would likely help you out.</p>\n</li>\n</ul>\n<hr />\n<h3>With some comments:</h3>\n<pre><code>class Solution:\n def longestPalindrome(self, s):\n if len(s) < 1:\n return s\n\n def isPalindrome(left, right):\n return s[left:right] == s[left:right][::-1]\n\n # We set the left pointer on the first index\n # We set the right pointer on the second index\n # That's the minimum true palindrome\n left, right = 0, 1\n\n # We visit the alphabets from the second index forward once\n for index in range(1, len(s)):\n # Here we move the right pointer twice and once checking for palindromeness\n # We boundary check using index - right, to remain positive\n if index - right > 0 and isPalindrome(index - right - 1, index + 1):\n print(f"Step {index - 1}: Left pointer is at {index - right - 1} and Right pointer is at {index + 1}")\n print(f"Palindromeness start: {index - right - 1} - Palindromeness end: {index + 1}")\n print(f"Window length: {right}")\n print(f"Before: Left is {left} and Right is {left + right}")\n left, right = index - right - 1, right + 2\n print(f"After: Left is {left} and Right is {left + right}")\n print(f"String: {s[left: left + right]}")\n print('#' * 50)\n if index - right >= 0 and isPalindrome(index - right, index + 1):\n print(f"Step {index - 1}: Left pointer is at {index - right} and Right pointer is at {index + 1}")\n print(f"Palindromeness start: {index - right - 1} - Palindromeness end: {index + 1}")\n print(f"Window length: {right + 1}")\n print(f"Before: Left is {left} and Right is {left + right}")\n left, right = index - right, right + 1\n print(f"After: Left is {left} and Right is {left + right}")\n print(f"String: {s[left: left + right]}")\n print('#' * 50)\n return s[left: left + right]\n\n\nSolution().longestPalindrome("glwhcebdjbdroiurzfxxrbhzibilmcfasshhtyngwrsnbdpzgjphujzuawbebyhvxfhtoozcitaqibvvowyluvdbvoqikgojxcefzpdgahujuxpiclrrmalncdrotsgkpnfyujgvmhydrzdpiudkfchtklsaprptkzhwxsgafsvkahkbsighlyhjvbburdfjdfvjbaiivqxdqwivsjzztzkzygcsyxlvvwlckbsmvwjvrhvqfewjxgefeowfhrcturolvfgxilqdqvitbcebuooclugypurlsbdfquzsqngbscqwlrdpxeahricvtfqpnrfwbyjvahrtosovsbzhxtutyfjwjbpkfujeoueykmbcjtluuxvmffwgqjgrtsxtdimsescgahnudmsmyfijtfrcbkibbypenxnpiozzrnljazjgrftitldcueswqitrcvjzvlhionutppppzxoepvtzhkzjetpfqsuirdcyqfjsqhdewswldawhdyijhpqtrwgyfmmyhhkrafisicstqxokdmynnnqxaekzcgygsuzfiguujyxowqdfylesbzhnpznayzlinerzdqjrylyfzndgqokovabhzuskwozuxcsmyclvfwkbimhkdmjacesnvorrrvdwcgfewchbsyzrkktsjxgyybgwbvktvxyurufsrdufcunnfswqddukqrxyrueienhccpeuqbkbumlpxnudmwqdkzvsqsozkifpznwapxaxdclxjxuciyulsbxvwdoiolgxkhlrytiwrpvtjdwsssahupoyyjveedgqsthefdyxvjweaimadykubntfqcpbjyqbtnunuxzyytxfedrycsdhkfymaykeubowvkszzwmbbjezrphqildkmllskfawmcohdqalgccffxursvbyikjoglnillapcbcjuhaxukfhalcslemluvornmijbeawxzokgnlzugxkshrpojrwaasgfmjvkghpdyxt")\n\n</code></pre>\n<h3>Prints:</h3>\n<pre><code>Step 18: Left pointer is at 18 and Right pointer is at 20\nPalindromeness start: 17 - Palindromeness end: 20\nWindow length: 2\nBefore: Left is 0 and Right is 1\nAfter: Left is 18 and Right is 20\nString: xx\n##################################################\nStep 25: Left pointer is at 24 and Right pointer is at 27\nPalindromeness start: 23 - Palindromeness end: 27\nWindow length: 3\nBefore: Left is 18 and Right is 20\nAfter: Left is 24 and Right is 27\nString: ibi\n##################################################\nStep 462: Left pointer is at 460 and Right pointer is at 464\nPalindromeness start: 459 - Palindromeness end: 464\nWindow length: 4\nBefore: Left is 24 and Right is 27\nAfter: Left is 460 and Right is 464\nString: pppp\n##################################################\n\n</code></pre>\n<h3>Happy Coding! ( ˆ_ˆ )</h3>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T03:51:10.167",
"Id": "494889",
"Score": "1",
"body": "better than 94%, that's nice!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T13:13:48.360",
"Id": "494937",
"Score": "1",
"body": "I believe `s[left:right][::-1]` can also be `s[right-1:left-1:-1]`. I presume that would save a bit of time as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T16:48:29.963",
"Id": "494977",
"Score": "1",
"body": "@Emma I agree that `s[left:right].reverse()` would be different (and possibly nonsensical). I'm not seeing how reversing the slice at the same time as slicing would be different than slicing and then reversing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T21:32:55.490",
"Id": "495134",
"Score": "1",
"body": "@Emma: +1. Many thanks for your insights. I'm still slowly reading your \"Alternative Solution\". That looks very smart. I have yet \"decipher\" the two \"if\" conditions. Could you say a few words about the underlying ideas?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T21:36:17.697",
"Id": "495136",
"Score": "1",
"body": "It is very interesting to see that my code could pass the tests in your snapshot. I have never seen it passed submitting it several times on my own."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T21:51:01.817",
"Id": "495141",
"Score": "1",
"body": "It seems that using the dynamical programming approach mentioned in my question is unlikely to pass the LeetCode tests."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T01:36:19.310",
"Id": "251396",
"ParentId": "251395",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "251396",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T01:27:28.217",
"Id": "251395",
"Score": "9",
"Tags": [
"python",
"programming-challenge",
"strings",
"dynamic-programming",
"palindrome"
],
"Title": "LeetCode on Longest Palindromic Substring in Python"
}
|
251395
|
<p>This C code is to print a triangle of stars.</p>
<p><a href="https://i.stack.imgur.com/hraai.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hraai.png" alt="enter image description here" /></a></p>
<pre><code>#include <stdio.h>
int main(){
for(int i=0;i<3;i++) {
for(int j=0;j<i*2+1;j++){
printf("*");
}
printf("\n");
}
}
</code></pre>
<p>which works well though, I'd like to know if there is a better way to do the job, as it's said 2 layers of loop is inefficient, compared to vectorization.</p>
|
[] |
[
{
"body": "<p>Due to the size of the program, I have only a few things to suggest</p>\n<ul>\n<li>Since you aren't returning anything from <code>main()</code>, use <code>int main(void)</code>.</li>\n<li>Use don't have to perform any arithmetic in the inner nested-loop, you only need to do <code>j <= i</code></li>\n<li><code>3</code> in the outer-loop is a <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)#:%7E:text=The%20term%20magic%20number%20or,1%20manuals%20of%20the%201960s.\" rel=\"nofollow noreferrer\">magic number</a> or, an <strong>unnamed numeric constant</strong>. I suggest you assign it to <code>const int rows</code>, to make it clear</li>\n</ul>\n<pre class=\"lang-c prettyprint-override\"><code>#include <stdio.h>\n\nint main(void)\n{\n const int rows = 3;\n\n for(int i = 0;i < rows; i++)\n {\n for(int j = 0; j <= i; j++)\n printf("*")\n\n printf("\\n");\n }\n}\n</code></pre>\n<p>I believe this will be the best, and easiest way to perform this task!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T05:30:56.317",
"Id": "251401",
"ParentId": "251400",
"Score": "2"
}
},
{
"body": "<p>I use a string to avoid the inner loop. The problem here is the <code>printf()</code> inside. A 3000-row triangle redirected to <code>/dev/null</code> takes 50ms, but now only 4ms.</p>\n<p>I reformatted the output. And I left dots as fillers to see what is going on.</p>\n<pre><code>$ ./a.out \n...*...\n..***..\n.*****.\n*******\n</code></pre>\n<p>It starts with one <code>*</code> in the so-called middle, and every row-iteration only sets two more bytes to <code>*</code> before it prints.</p>\n<p>The complicated part is preparing the string i.e. array of chars. You can use <code>calloc()</code> to clear the right side, but it still takes a step to put blanks on the left side.</p>\n<pre><code>#include <stdio.h>\n#include <string.h>\n\nint trihi = 4;\nchar PIX = '*';\n\nint main(void){\n\n int width = trihi * 2 - 1;\n char s[width + 1];\n memset(s, '.', width);\n s[width] = '\\0';\n\n int mid = trihi - 1;\n s[mid] = PIX;\n printf("%s\\n", s);\n\n for (int i = 1; i < trihi; i++) {\n\n s[mid - i] =\n s[mid + i] = PIX;\n printf("%s\\n", s);\n }\n}\n</code></pre>\n<p>This should add up. <code>s[mid + i]</code> runs up to <code>2*mid</code> = <code>2*(trihi-1)</code>.\nThe '\\0' sits at <code>width = 2*trihi - 1</code> which is one higher, and is the highest legal index for <code>s</code>.</p>\n<p>It is very easy to make a small mistake and not have the <code>\\0</code> at the correct place.</p>\n<p>It also works with a triangle height of 1:</p>\n<pre><code>$ ./a.out \n*\n</code></pre>\n<p>And by setting <code>... = --PIX;</code> in the loop:</p>\n<pre><code>$ ./a.out \n.....*.....\n....)*)....\n...()*)(...\n..'()*)('..\n.&'()*)('&.\n%&'()*)('&%\n</code></pre>\n<p><strong>The So-Called Middle</strong></p>\n<p>This is how a triangle of height 4 is laid out. Size is 8. The middle is s[3]; there are 3 spaces to the left.</p>\n<pre><code>01234567 --- "offset", "index"\n...*...0\n| | |\n| | +-- s[width] (width = 2*trihi - 1) \n| +------ s[mid] (mid = trihi - 1) \n+--------- s[0] \n</code></pre>\n<p>You start with trihi=4, but what you need is mostly 3 and 7...the geometrical base width is also 7.</p>\n<hr />\n<p><strong>Just any Triangle</strong></p>\n<p>If this is enough (with original height = 3):</p>\n<pre><code>$ ./a.out \n*\n**\n***\n</code></pre>\n<p>then the code gets much simpler:</p>\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n\nint trihi = 3;\nchar PIX = '*';\n\nint main(void){\n\n char *s = calloc(trihi+1, 1);\n\n for (int i = 0; i < trihi; i++) {\n s[i] = PIX;\n printf("%s\\n", s);\n }\n}\n</code></pre>\n<p>I kicked everything out except the basic idea: re-using a prepared string/array. Here the calloc-zeroes are only after the PIXes. No need for a filler like space or dots via memset() anymore. But it is also not the same user experience...and the triangle is half the size.</p>\n<p>Overiq.com has a double-loop version of a <em>C Program to print Half Pyramid pattern using *</em>. It takes much longer than the above (<em>tri2.c</em> below).</p>\n<pre><code>$ gcc -O2 over.c \n$ time ./a.out |wc -l\n3001\n\nreal 0m0.029s\nuser 0m0.020s\nsys 0m0.014s\n$ gcc -O2 tri2.c \n$ time ./a.out |wc -l\n3000\n\nreal 0m0.006s\nuser 0m0.000s\nsys 0m0.011s\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T16:44:30.190",
"Id": "494975",
"Score": "0",
"body": "Your answer is almost a good one. Currently your observation about the performance of the program is implied, if you actually mention it in the answer it would be better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T17:02:25.887",
"Id": "494979",
"Score": "0",
"body": "With redir to a tmpfs file it is 54ms vs. 11ms. I don't know what you mean with \"imply\" or \"mention\". I tested and mentioned it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T17:20:12.897",
"Id": "494980",
"Score": "0",
"body": "It is the OP who mentioned efficiency, and I think he is right to ask. His way would work well with curses, I guess, where you \"refresh\" when done modifying."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T15:07:26.633",
"Id": "251425",
"ParentId": "251400",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T04:41:28.057",
"Id": "251400",
"Score": "4",
"Tags": [
"beginner",
"c",
"iteration"
],
"Title": "C program to print a triangle of stars"
}
|
251400
|
<p>Hi I participated in Leetcode weekly contest 213 and am facing issue with submission for below question
<a href="https://leetcode.com/contest/weekly-contest-213/problems/kth-smallest-instructions/" rel="nofollow noreferrer">Kth Smallest Instructions</a></p>
<blockquote>
<p>Bob is standing at cell (0, 0), and he wants to reach destination:
(row, column). He can only travel right and down. You are going to
help Bob by providing instructions for him to reach destination.</p>
<p>The instructions are represented as a string, where each character is
either:</p>
<p>'H', meaning move horizontally (go right), or 'V', meaning move
vertically (go down). Multiple instructions will lead Bob to
destination. For example, if destination is (2, 3), both "HHHVV" and
"HVHVH" are valid instructions.</p>
<p>However, Bob is very picky. Bob has a lucky number k, and he wants the
kth lexicographically smallest instructions that will lead him to
destination. k is 1-indexed.</p>
<p>Given an integer array destination and an integer k, return the kth
lexicographically smallest instructions that will take Bob to
destination.</p>
<p><strong>Example 1</strong> :<br />
<strong>Input</strong>: destination = [2,3], k = 1<br />
<strong>Output</strong>: "HHHVV"<br />
<strong>Explanation</strong>: All the instructions that reach (2, 3) in lexicographic
order are as follows: ["HHHVV", "HHVHV", "HHVVH", "HVHHV", "HVHVH",
"HVVHH", "VHHHV", "VHHVH", "VHVHH", "VVHHH"].</p>
<p><strong>Constraints</strong>:<br />
destination.length == 2<br />
1 <= row, column <= 15<br />
1 <= k <= nCr(row + column, row), where nCr(a, b) denotes a choose b.</p>
</blockquote>
<p>I tried to create all the possible paths lexicographically and stop when count reached k, but it giving me TLE.</p>
<p>Below is my code :</p>
<pre><code>public class Solution {
String res = string.Empty;
int count = 0;
int K;
public string KthSmallestPath(int[] destination, int k) {
K=k;
this.FindAllPaths("", destination[1], destination[0]);
return res;
}
public void FindAllPaths(string currPath, int hRem, int vRem)
{
if(count == K) return;
if(hRem == 0 && vRem == 0)
{
res = currPath;
count++;
return;
}
if(hRem != 0)
{
this.FindAllPaths(currPath + 'H', hRem - 1, vRem);
}
if(vRem != 0)
{
this.FindAllPaths(currPath + 'V', hRem, vRem - 1);
}
}
}
</code></pre>
<p>Any idea on how can I optimize the code so that it passes all the test cases.</p>
|
[] |
[
{
"body": "<h3>A review of your current code</h3>\n<p><code>class Solution</code> uses the fields</p>\n<pre><code>String res = string.Empty;\nint count = 0;\nint K;\n</code></pre>\n<p>to pass information around between the “main” <code>KthSmallestPath()</code> function and the <code>FindAllPaths()</code> helper function. That makes the logic difficult to understand. Even worse, it causes wrong results if the function is called more than once:</p>\n<pre><code>String res1 = sol.KthSmallestPath(new int [] { 2, 3 }, 5);\n// HVHVH (correct)\nString res2 = sol.KthSmallestPath(new int [] { 2, 3 }, 1);\n// VVHHH (wrong)\n</code></pre>\n<p>Try to pass all information as function arguments. If that is not possible, make sure to reset all the commonly used fields at the start of the function.</p>\n<p>The horizontal and vertical spacing is not consistent: There should be spaces around the operator in</p>\n<pre><code>K=k;\n</code></pre>\n<p>and I suggest to always use curly braces with if-statements, e.g. here:</p>\n<pre><code>if(count == K) return;\n</code></pre>\n<p>Finally, I had to think twice about the element of the given <code>destination</code> array correspond to rows/columns and to horizontal/vertical steps. Assinging these values to local variables with an explaining comment can make this more clear:</p>\n<pre><code>int vRem = destination[0]; // destination row = # of vertical steps \nint hRem = destination[1]; // destination column = # of horizontal steps\n</code></pre>\n<h3>A better approach</h3>\n<p>In the “worst case”</p>\n<pre><code>String res = sol.KthSmallestPath(new int [] { 15, 15 }, 155117520);\n</code></pre>\n<p>your code builds recursively <span class=\"math-container\">\\$ \\binom{30}{15} = 155117520\\$</span> strings. This is a case where the “brute force” method simply does not work, and one has to find something more efficient.</p>\n<p>In fact it is possible to find the k-th smallest permutation of a string with N characters in O(N) time and with O(N) memory, see for example</p>\n<ul>\n<li><a href=\"https://math.stackexchange.com/q/60742/42969\">Finding the n-th lexicographic permutation of a string</a> on Mathematics Stack Exchange,</li>\n<li><a href=\"https://www.geeksforgeeks.org/find-n-th-lexicographically-permutation-string-set-2\" rel=\"nofollow noreferrer\">Find n-th lexicographically permutation of a string | Set 2</a> on GeeksforGeeks.</li>\n</ul>\n<p>The idea is to compute at every step how many permutations start with an <code>H</code> and how many start with a <code>V</code> and then choose the next letter accordingly.</p>\n<p>As an example, compute the 5-th permutation of <code>HHHVV</code>.</p>\n<ul>\n<li><p>There are <span class=\"math-container\">\\$ \\binom{5}{2} = 10 \\$</span> permutations, and <span class=\"math-container\">\\$ \\binom{4}{2} = 6 \\$</span> start with <code>H</code>. Since <span class=\"math-container\">\\$ 5 \\le 6 \\$</span> the first letter must be <code>H</code>, and it remains to compute the 5-th permutation of <code>HHVV</code>.</p>\n</li>\n<li><p>Next, there are <span class=\"math-container\">\\$ \\binom{4}{2} = 6 \\$</span> permutations of <code>HHVV</code>, and <span class=\"math-container\">\\$ \\binom{3}{2} = 3 \\$</span> start with <code>H</code>. Since <span class=\"math-container\">\\$ 5 > 3 \\$</span> the next letter must be <code>V</code>, and it remains to compute the second permutation of <code>HHV</code>.</p>\n</li>\n<li><p>This process is repeated until no <code>H</code>s are left, and the remaining positions are filled with <code>V</code>.</p>\n</li>\n</ul>\n<p>Here is a possible implementation, using a recursive helper function:</p>\n<pre><code>public class Solution {\n\n // From https://rosettacode.org/wiki/Evaluate_binomial_coefficients#C.23\n static int binomial(int n, int k)\n {\n if (k > n - k)\n {\n k = n - k;\n }\n\n int c = 1;\n for (int i = 0; i < k; i++)\n {\n c = c * (n - i);\n c = c / (i + 1);\n }\n return c;\n }\n\n /*\n * Returns the `k`-th permutation of a string with `numH` 'H's and\n * `numV` 'V's in lexicographic order.\n */\n static string KthPermutation(int numH, int numV, int k)\n {\n if (numH == 0)\n {\n return new String('V', numV);\n }\n else\n {\n // Number of permutations starting with 'H':\n int c = binomial(numH + numV - 1, numV);\n if (k <= c)\n {\n return 'H' + KthPermutation(numH - 1, numV, k);\n }\n else\n {\n return 'V' + KthPermutation(numH, numV - 1, k - c);\n }\n }\n }\n\n public string KthSmallestPath(int[] destination, int k)\n {\n int numV = destination[0]; // destination row = # of vertical steps \n int numH = destination[1]; // destination column = # of horizontal steps\n return KthPermutation(numH, numV, k);\n }\n}\n</code></pre>\n<p>It computes</p>\n<pre><code>String res = sol.KthSmallestPath(new int [] { 15, 15 }, 155117520);\n</code></pre>\n<p>in 0.6 milliseconds on my MacBook (using Mono).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T09:58:22.610",
"Id": "251412",
"ParentId": "251402",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "251412",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T06:17:16.250",
"Id": "251402",
"Score": "3",
"Tags": [
"c#",
"algorithm",
"recursion",
"time-limit-exceeded"
],
"Title": "LeetCode - Weekly Contest 213 - Kth Smallest Instructions"
}
|
251402
|
<p>I'm currently learning c++ coming from a python background, so I'll include a solution in python and in c++ for the following problem statement:</p>
<blockquote>
<p>Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.</p>
</blockquote>
<p><strong>Example 1:</strong></p>
<p>Input: nums = [2,7,11,15], target = 9</p>
<p>Output: [0,1]</p>
<p><strong>Example 2:</strong></p>
<p>Input: nums = [3,2,4], target = 6</p>
<p>Output: [1,2]</p>
<p>I would like to hear your feedback / suggestions for performance improvements / other suggestions. Here's the <a href="https://leetcode.com/problems/two-sum/" rel="nofollow noreferrer">link</a></p>
<p><code>two_sum.py</code></p>
<pre><code>def two_sum(nums: list, target: int):
for i, n in enumerate(nums):
match = target - n
if match in (rest := nums[i + 1:]):
match_at = rest.index(match)
return i, match_at + i + 1
if __name__ == '__main__':
if result := two_sum([2, 7, 11, 15], 22):
print(f'Indices:\n{result}')
else:
print('No matches found')
</code></pre>
<p>Leetcode stats:</p>
<blockquote>
<p>Runtime: 772 ms, faster than 36.98% of Python online submissions for Two Sum.
Memory Usage: 14.4 MB, less than 49.82% of Python online submissions for Two Sum.</p>
</blockquote>
<p><code>two_sum.h</code></p>
<pre><code>#ifndef LEETCODE_TWO_SUM_H
#define LEETCODE_TWO_SUM_H
#include <iostream>
#include <vector>
using std::vector;
using std::cout;
using std::endl;
vector<int> two_sum_solution(vector<int> &nums, int target) {
vector <int> results;
for (int i = 0; i < nums.size(); ++i) {
int match = target - nums[i];
for (int j = i + 1; j < nums.size(); ++j) {
if (nums[j] == match) {
for (int index_match : {
i, j
})
results.push_back(index_match);
}
}
}
return results;
}
#endif //LEETCODE_TWO_SUM_H
</code></pre>
<p><code>main.cpp</code></p>
<pre><code>#include <vector>
#include "two_sum.h"
using std::vector;
int main() {
vector<int> v1{2, 7, 11, 15};
vector<int> v = two_sum_solution(v1, 22);
if (!v.empty()) {
cout << "Indices:" << endl;
for (auto i: v)
cout << i << " ";
}
else (cout << "No matches found");
}
</code></pre>
<p>Leetcode stats:</p>
<blockquote>
<p>Runtime: 384 ms, faster than 34.03% of C++ online submissions for Two Sum.
Memory Usage: 9.3 MB, less than 12.99% of C++ online submissions for Two Sum.</p>
</blockquote>
|
[] |
[
{
"body": "<p>You can perhaps improve the performance by creating a map of value -> index in the first iteration over the given array.</p>\n<p>Currently, Your program does the following (time complexity):</p>\n<ol>\n<li>iterate over all <code>index, value</code> pairs of the array (<span class=\"math-container\">\\$ O(n) \\$</span>)</li>\n<li>search for <code>target - value</code> in the array (<span class=\"math-container\">\\$ O(n) \\$</span>)</li>\n<li>lookup index of <code>target - value</code> (<span class=\"math-container\">\\$ O(n) \\$</span>)</li>\n</ol>\n<p>And since these are all nested, you get to <span class=\"math-container\">\\$ O(n^2) \\$</span> (it isn't <span class=\"math-container\">\\$ n^3 \\$</span> because last lookup is not being done for each iteration).</p>\n<hr />\n<p>My proposed solution:</p>\n<ol>\n<li>Create a map/dict of <code>{value: index}</code> (<span class=\"math-container\">\\$ O(n) \\$</span>)</li>\n<li>Iterate over <code>index, value</code> of array (<span class=\"math-container\">\\$ O(n) \\$</span>)</li>\n<li>Lookup and return index from the map/dict (<span class=\"math-container\">\\$ O(1) \\$</span>)</li>\n</ol>\n<hr />\n<pre><code>def two_sum(numbers: list[int], target: int):\n lookup: dict = {\n value: index\n for index, value in enumerate(numbers)\n }\n for index, value in enumerate(numbers):\n match = target - value\n if search_index := lookup.get(match):\n return index, search_index\n return None\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T07:10:13.007",
"Id": "494900",
"Score": "1",
"body": "That would fail the cases where the target is double the number ex: `[1,3,4,2]` and `6`, will output (1, 1) which is incorrect"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T07:12:43.570",
"Id": "494901",
"Score": "1",
"body": "Adding another if-clause to verify `search_index != index` is still faster than iterating over the array again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T10:41:25.960",
"Id": "495040",
"Score": "0",
"body": "@HeapOverflow I was referring to the iteration in OP's code: `match in (rest := nums[i + 1:])` or `int j = i + 1; j < nums.size(); ++j`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T13:33:38.813",
"Id": "495055",
"Score": "0",
"body": "@HeapOverflow Marc's rewrite is obviously better. Although it uses the same style as my proposed solution above. Mine was a verbatim iteration of the 3 points."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T20:48:58.213",
"Id": "495124",
"Score": "0",
"body": "You can combine the two loops into one, which has the additional advantage of terminating as soon as the second item is found."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T07:01:54.947",
"Id": "251405",
"ParentId": "251403",
"Score": "5"
}
},
{
"body": "<p>I am not an expert in C++ but I can give a feedback about the Python solution.</p>\n<p>Your current solution runs in <span class=\"math-container\">\\$O(n^2)\\$</span>. Basically, for each number <code>n</code> of the input <code>nums</code>, find <code>target - n</code> in <code>nums</code>. How to improved it?</p>\n<p>The second part of the algorithm can be improved from <span class=\"math-container\">\\$O(n)\\$</span> to <span class=\"math-container\">\\$O(1)\\$</span>. Instead of looking up <code>target - n</code> in a list, you can use a dictionary:</p>\n<pre><code>def two_sum(nums: list, target: int):\n num_index = {}\n for i, n in enumerate(nums):\n match = target - n\n if match in num_index:\n return num_index[match], i\n num_index[n] = i\n return -1\n</code></pre>\n<p>Results:</p>\n<pre><code>Original: Runtime: 772 ms. Memory Usage: 14.4 MB\nImproved: Runtime: 48 ms. Memory Usage: 15.5 MB\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T12:58:35.617",
"Id": "495052",
"Score": "0",
"body": "If performance is of importance, I would suggest using `get()` to avoid duplicate dict-lookup. That is, replace `match = target - n` with `match = num_index.get(target - n)` , and then replace the `if`-statement with `if match is not None:` , and finally, `return match, i`. I believe there might be some gain here, if the `nums` param is a rather long list. Please let me know if you disagree or prove me wrong. Cheers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T14:28:58.103",
"Id": "495064",
"Score": "0",
"body": "@magnus I think that with your suggestion there should be a little improvement but LeetCode gives similar results. Maybe with a proper benchmark would be possible to notice the difference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T08:34:35.930",
"Id": "495516",
"Score": "0",
"body": "@magnus So you think making *every* check slower just to avoid *one* lookup will make it overall *faster*?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T09:17:25.717",
"Id": "495526",
"Score": "0",
"body": "@superbrain Yes, I believed so, at least for (very) large dicts. However, according to this SO post, it is not: https://stackoverflow.com/questions/39582115/python-dictionary-lookup-performance-get-vs-in . My assumption was based on the accepted answer of this CR post: https://codereview.stackexchange.com/questions/231409"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T11:42:44.733",
"Id": "495535",
"Score": "0",
"body": "@magnus Hmm, you said it's to avoid duplicate lookup, though. So the \"for large list/dict\" doesn't make sense, as the larger they get, the *less* that single avoided duplicate lookup matters."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T13:40:24.743",
"Id": "495546",
"Score": "0",
"body": "@superbrain I disagree. Please, feel free to enlighten me!:) By duplicate look-up, I mean that the alg first performs a `k in d`, then a `x = d[y]`. According to https://wiki.python.org/moin/TimeComplexity , they perform at **average** `O(1)`, but has amortized worst case `O(n)`, which is the same as for `d.get(y)`. Do I understand correctly that you claim that the overhead of `get()` is greater than dual lookup? You don't need to take my word for it, try it your self. My submission at LeetCode ran for 40ms, which is 16,7% faster than the solution posted here. I find that quite significant."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T14:25:34.633",
"Id": "495552",
"Score": "0",
"body": "@magnus submit the solution again, you'll get results from 30 to 50 ms. As already said, you cannot spot the difference with LeetCode."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T14:30:00.887",
"Id": "495553",
"Score": "0",
"body": "@magnus Sorry, but... the fact that you try to use such a LeetCode result as evidence only shows you don't know what you're doing :-P. Or rather, what LeetCode is doing. Namely an [egregiously bad job](https://codereview.stackexchange.com/a/246047/228314) at timing. And no, I'm not claiming that the `get()` takes longer than dual lookup. I'm stating that the `get()` takes longer than the **single** lookup using `in` (especially if you include the method lookup (as you do)). It seems you still don't see that the second lookup happens only **once**, regardless of how large the input is?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T16:53:31.993",
"Id": "495581",
"Score": "0",
"body": "@superbrain Yes, I see it now. This is hillarious actually. I'm sorry for wasting everyone's time. And yes, I was naive to think that LeetCode had a decent timing system. However, your condescendance gives you no credit, but I thank you regardless for correcting my poor suggestion."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T07:07:26.220",
"Id": "251406",
"ParentId": "251403",
"Score": "11"
}
},
{
"body": "<h1>Only include the header files that you need</h1>\n<p>In your <code>two_sum.h</code> file, you don't need <code>iostream</code>, since you're not using any of its functionality. Remember that <code>#include</code> literally copy-pastes the file, so if you're including this header file in multiple files, it might potentially slow down your compilation times.</p>\n<h1>Split declarations and definitions</h1>\n<p>Typically, you would split your files into two parts: the header file (normally ending with <code>*.h, *.hpp, *.hh</code>) and the source file (normally ending with <code>*.cpp, *.cc</code>). The header file only consists of the declarations and the source file contains the implementation.</p>\n<p>So in your case, your header file will look like this:</p>\n<h2>two_sum.h</h2>\n<pre><code>#ifndef LEETCODE_TWO_SUM_H\n#define LEETCODE_TWO_SUM_H\n\n#include <vector>\n\nstd::vector<int> two_sum_solution(std::vector<int> &nums, int target);\n\n#endif // LEETCODE_TWO_SUM_H\n</code></pre>\n<p>and your source file will look like this:</p>\n<h2>two_sum.cpp</h2>\n<pre><code>#include "two_sum.h"\nstd::vector<int> two_sum_solution(std::vector<int> &nums, int target)\n{\n ...\n}\n</code></pre>\n<p>In fact, if you try to include your <code>two_sum.h</code> (with the implementation) into multiple files, you would be breaking the <a href=\"https://stackoverflow.com/questions/4192170/what-exactly-is-one-definition-rule-in-c\">One-Definition Rule</a>. Your source files would contain multiple definitions of the same function, and the linker will spit out an error. One way to get around is to mark the functions <code>inline</code>, but you most likely want to do the former.</p>\n<h1>No <code>using namespace</code> in the header files</h1>\n<p>Don't do <code>using namespace</code> or any of its variant in a header file. Since the header file is copy pasted throughout multiple source files, it has a potential to cause annoying\nerrors. <a href=\"https://stackoverflow.com/questions/21423013/is-it-ok-to-have-using-namespace-statement-in-a-header-file?noredirect=1&lq=1\">See here</a></p>\n<h1>Use const reference</h1>\n<p>Since <code>two_sum_solution</code> is not modifying the <code>nums</code> vector, pass it by const reference.</p>\n<h1>size_t vs int for array indices</h1>\n<p><a href=\"https://stackoverflow.com/questions/1951519/when-to-use-stdsize-t\">Consider using size_t instead of int for array indices</a></p>\n<h1>Use <code>auto</code> as much as possible</h1>\n<p>There are a couple of instances in your code where you can use <code>auto</code> instead of specifying the type. Examples:</p>\n<p><code>auto match = target - nums[i];</code>\n<code>auto v = two_sum_solution(v1, 22);</code></p>\n<h1>The inner-most loop is pointless</h1>\n<p>Simply do</p>\n<pre><code>results.push_back(i);\nresults.push_back(j);\n</code></pre>\n<p>Also, once you've found the solution, you might want to return the result immediately.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T07:58:19.730",
"Id": "494902",
"Score": "0",
"body": "Thanks, that's very informative, i have a few questions: what if i'm going to include the header file that will only contain declarations, in which .cpp file should the definition be given that i need to include it in several files? And regarding using `const`, `auto` and `size_t` whenever relevant, does this improve performance? I'm asking because as you must know, in python these things do not exist so i'm learning the hows and whys"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T08:44:07.870",
"Id": "494905",
"Score": "0",
"body": "Your header file should be included in all the source files that will want to your functions (for e.g. your `main.cpp` will include `two_sum.h`). Your functions should be defined in a separate source file (`two_sum.cpp`). During compilation, the linker will resolve all references.\n\nThey don't improve performance. Since you're passing by reference, it makes sense to use `const` so you don't do anything that will accidentally modify the vector. `auto` is just a directive for the compiler to deduce the type, and `size_t` is the canonical type for array indices."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T07:14:30.040",
"Id": "251407",
"ParentId": "251403",
"Score": "6"
}
},
{
"body": "<p>This is interesting to me because I come from a C background and started using Python the past few years for work, so I've had the reverse path as you. When I started Python, I greatly preferred solutions like yours because looping through lists is so explicit and clear.</p>\n<p>However, I since learned that more proficient Python programmers at work understand my code better when I use the standard library. Once I began to invest in learning those tools, it had the double effect of 1) making my code more succinct and 2) being more efficient in time and/or space.</p>\n<p>In this case, I would solve the problem with <code>combinations</code> from the <code>itertools</code> package:</p>\n<pre><code>from itertools import combinations\n\ndef two_sum(nums, target):\n pairs_with_indices = combinations(enumerate(nums), 2)\n\n # result is a generator comprehension.\n winning_pairs = ((index_i, index_j)\n for (index_i, i), (index_j, j) in pairs_with_indices\n if sum((i, j)) == target)\n\n # Insert as much error checking as you need...\n return next(winning_pairs)\n</code></pre>\n<p>There's probably an even better more succinct and clear solution using Numpy, which is effectively standard library in my line of work (data science) but that's not true everywhere.</p>\n<p>One thing that's different than your code: there is no room for off-by-one-errors. In my experience, code like this</p>\n<pre><code>if match in (rest := nums[i + 1:]):\n match_at = rest.index(match)\n return i, match_at + i + 1\n</code></pre>\n<p>is easy for me to write, hard to read and maintainability spans the whole gambit from easy to impossible. In other words, managing indices manually in Python gives me just enough rope to hang myself with, and standard library functions have been a great alternative.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T18:01:56.460",
"Id": "494982",
"Score": "0",
"body": "I tried the very same solution at first and despite `itertools` being very efficient, the solution for some reason is rejected \"time limit exceeded\" but it's what i think is the most readable solution but may not scale well because it's `O(N^2)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T18:31:09.230",
"Id": "494984",
"Score": "0",
"body": "@bullseye, Good point. I made the list comprehension a generator comprehension and only return the first value, so we don't continue calculating after we find something. Out of curiosity, could you share the input nums/target so I could try the time test?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T18:34:04.820",
"Id": "494985",
"Score": "0",
"body": "The input nums are already provided on the leetcode platform, if you want you may test there directly. The examples were Input: nums = [2,7,11,15], target = 9 and Input: nums = [3,2,4], target = 6"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T20:47:54.760",
"Id": "495123",
"Score": "2",
"body": "This adds unnecessary complexity to the problem. A dictionary would be a much more useful tool here."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T17:49:45.707",
"Id": "251433",
"ParentId": "251403",
"Score": "3"
}
},
{
"body": "<h1>Know your containers</h1>\n<p><code>std::unordered_map</code> is your friend in this problem. Whenever you've never previously seen a number, simply use the <code>operator[]</code> or <code>insert</code> function to add the number and its index. When using <code>find</code>, it will return an iterator, which is a <code>key-value</code> pair.</p>\n<p>eg:\n<code>auto location = m.find(numToFind);</code></p>\n<p><code>location->first</code> is your key, and\n<code>location->second</code> is your value</p>\n<h1>When you return, don't use push_back</h1>\n<p>You can simply return an initializer list like: <code>{i,j}</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T11:27:23.177",
"Id": "251597",
"ParentId": "251403",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "251406",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T06:29:54.683",
"Id": "251403",
"Score": "9",
"Tags": [
"python",
"c++",
"programming-challenge"
],
"Title": "Leetcode two sum"
}
|
251403
|
<p>I am new to python, in .NET we use web.config to store environment specific variables... I want to achieve the same for my python program (scraper)</p>
<p>I have created .env file at the root of the project and added the following variable to it:</p>
<pre><code>CHROME_WEB_DRIVER=C:/webdrivers/chromedriver.exe
</code></pre>
<p><em>Note that I have added .env to gitignore as this file changes in different environments.</em></p>
<p>And I am using <code>decouple</code> package to use this setting from .env file in the constructor of the class:</p>
<pre class="lang-py prettyprint-override"><code>import scrapy
from decouple import config
from python_json_config import ConfigBuilder
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
class MySpider(scrapy.Spider):
name = 'my_spider'
def __init__(self):
# .env variables
self.CHROME_WEB_DRIVER = config('CHROME_WEB_DRIVER')
self.job_highlight_dict = {}
self.wanted_organisations_dict = {}
self.output_path = ""
self.start_urls = []
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
self.driver = webdriver.Chrome(self.CHROME_WEB_DRIVER, chrome_options=chrome_options)
builder = ConfigBuilder()
config_values = builder.parse_config('config/config.json')
self.start_urls = config_values.urls
for o in config_values.organisations:
self.wanted_organisations_dict[o["brandName"]] = o["organisationName"]
self.output_path = config_values.output
def start_requests(self):
for url in self.start_urls:
yield scrapy.Request(url=url, callback=self.parse)
def parse(self, response):
# parse response
</code></pre>
<p>Note that I also have a config.json file, but this file contains configuration variables which are consistent across all environments.</p>
<p>This is how the config.json file looks like:</p>
<pre class="lang-json prettyprint-override"><code>{
"urls": [
"https://www.site-to-scrape-1.com",
"https://www.site-to-scrape-2.com"
],
"organisations": [
{ "brandName" : "brand-1", "organisationName" : "organisation-1" },
{ "brandName" : "brand-2", "organisationName" : "organisation-2" }
],
"output": "../path/to/s3/bucket"
}
</code></pre>
<p>I have not included all of spider class, but it is the main class of this project which crawls the given urls and then parse them. I am not sure if the constructor of the spider is the best place to read config.json and .env files?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T01:35:01.337",
"Id": "495296",
"Score": "0",
"body": "Add more tags, ex. selenium"
}
] |
[
{
"body": "<ul>\n<li>Add a declarative format for the config file, possibly. If you encounter errors, the output will look messy today (KeyError is never fun for an end user)</li>\n<li>I would say <strong>init</strong> is a good time, but unclear if it's the right place. It's looking messy. I would either (1) split out parsing the config file into a helper method or (2) consolodate some lines. (1) is better if you expect to add more config.</li>\n<li>I would consider making the chrome driver at the start of 'parse', as this is more of a "can fail" type operation--it will make writing tests easier.</li>\n<li>Consolidating:\n<ul>\n<li>'builder' is used only once, don't declare it</li>\n<li>don't assign to self.wanted_organizations_dict, or self.output_path, and self.start_urls twice. just initialize them once, correctly, in one line each.</li>\n<li>self.job_highlight_dict is not initialized. i don't know what this is, but are you sure you want to declare it here?</li>\n<li>self.CHROME_WEB_DRIVER does not appear to be used outside this, change it to a local variable or inline it, unless you move driver init to parse time</li>\n<li>declare self.wanted_organisations_dict in a single-line dict comprehension, not 3 lines.</li>\n<li>Initialize chrome_options in a single line, not 4.</li>\n</ul>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T01:45:12.563",
"Id": "251573",
"ParentId": "251404",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "251573",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T06:34:15.350",
"Id": "251404",
"Score": "0",
"Tags": [
"python",
"selenium",
"configuration"
],
"Title": "Reading configuration variables in a Python project"
}
|
251404
|
<p>if I have a large 2D array let's call it a dataset and I want to divide it into a number of 2D array of equal size that is smaller and easy to processing it(let's treat it as chunks), by using PSO algorithm I take the best position values, utilize it as an index of the dataset then putting these value in the chunks..
this code gives me a number of repeated chunks that has the same value but I want different values for each chunk from all the dataset</p>
<pre><code>// partitioning the dataset
int k = 0;//chunks counter
double[][] ch = new double[125][14];
while(k!=dataset.length){
best = swarm.getBestPosition();
ch = DatasetChunks(best, dataset);
ChunksPrint(ch, k);
k++;
}
private static double[][] DatasetChunks(double[] best, double[][] dataset) {
dataset = LoadData();
int row = 125, col = 14;
double[][] ch1 = new double[row][col];
int[] s2 = new int[best.length];
//treat the negative and repeated value of best position
Set<Integer> st = new HashSet<>();
for (int i = 0; i < s2.length - 1; i++) {
s2[i] = (int) best[i];
if (s2[i] < 0) {
s2[i] *= -1;
}
}
for (int i = 0; i < s2.length; i++) {
// check whether the element is
// repeated or not
if (!st.contains(s2[i])) {
st.add(s2[i]);
} else {
// find the next greatest element
for (int j = (int)(s2[i] + Math.random()); j < Integer.MAX_VALUE; j++) {
if (!st.contains(j) ) {
s2[i] = j;
st.add(j);
break;
}
}
}
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
ch1[i][j] = dataset[s2[i]][j];
}
}
return ch1;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T13:22:42.100",
"Id": "494939",
"Score": "4",
"body": "`[... ]this code gives me a number of repeated chunks that has the same value but I want different values for each chunk from all the dataset` Hello, if the code doesn't give you the correct result, then the question is off-topic.\n\n[What topics can I ask about here?](https://codereview.stackexchange.com/help/on-topic) `Code Review aims to help improve working code. If you are trying to figure out why your program crashes or produces a wrong result, ask on Stack Overflow instead.`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T19:36:38.900",
"Id": "495119",
"Score": "0",
"body": "*Assuming* `swarm.getBestPosition()` to return the same result every time, what *do* you expect `DatasetChunks()` to return?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T08:03:19.210",
"Id": "495182",
"Score": "0",
"body": "@greybeard it must partition the whole dataset based on the best position without any repeat"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T09:04:00.677",
"Id": "251409",
"Score": "1",
"Tags": [
"java"
],
"Title": "particle swarm optimization algorithm and 2D array partitioning"
}
|
251409
|
<p>The original problem statement is <a href="https://leetcode.com/problems/binary-search-tree-iterator/" rel="nofollow noreferrer">here</a>, here is the super short summary:</p>
<blockquote>
<p>Your binary search tree iterator must implement the following interface:</p>
</blockquote>
<pre><code>pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}
struct BSTIterator {}
impl BSTIterator {
fn new(root: Option<Rc<RefCell<TreeNode>>>) -> Self {}
fn next(&mut self) -> i32 {}
fn has_next(&self) -> bool {}
}
</code></pre>
<blockquote>
<p>The binary search iterator must return the values of the binary search tree from smallest to largest. It must use <code>O(h)</code> memory, where <code>h</code> is the height of the tree. Both <code>next</code> and <code>has_next</code> must run in <code>O(1)</code> amortized time.</p>
</blockquote>
<p>My solution to this is gradual, controlled recursion:</p>
<ol>
<li>Given the root of the tree in constructor, traverse all the left children and remember them.</li>
<li>On each <code>next</code> call, pop the last remembered node and return it. If that node had a right child, traverse it and all of its left children, and remember them.</li>
</ol>
<p>The implementation:</p>
<pre><code>use std::cell::RefCell;
use std::rc::Rc;
// Definition for a binary tree node.
#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
pub val: i32,
pub left: Option<Rc<RefCell<TreeNode>>>,
pub right: Option<Rc<RefCell<TreeNode>>>,
}
impl TreeNode {
#[inline]
pub fn new(val: i32) -> Self {
TreeNode {
val,
left: None,
right: None,
}
}
}
struct BSTIterator {
nodes: Vec<Rc<RefCell<TreeNode>>>,
}
impl BSTIterator {
fn new(root: Option<Rc<RefCell<TreeNode>>>) -> Self {
let mut nodes = vec![];
if let Some(root) = root {
BSTIterator::insert(&mut nodes, root);
}
BSTIterator { nodes }
}
/// Return the next smallest number
fn next(&mut self) -> i32 {
let rc = self.nodes.pop().unwrap();
let node = (*rc).borrow();
if let Some(node) = &node.right {
BSTIterator::insert(&mut self.nodes, Rc::clone(node));
}
node.val
}
/// True if there is a next smallest number, false otherwise
fn has_next(&self) -> bool {
!self.nodes.is_empty()
}
fn insert(nodes: &mut Vec<Rc<RefCell<TreeNode>>>, node: Rc<RefCell<TreeNode>>) {
let mut node = Some(node);
while let Some(rc) = node {
nodes.push(Rc::clone(&rc));
node = (*rc)
.borrow()
.left
.as_ref()
.and_then(|lft| Some(Rc::clone(&lft)));
}
}
}
fn main() {
let mut node50 = TreeNode::new(50);
let mut node25 = TreeNode::new(25);
let mut node75 = TreeNode::new(75);
let mut node12 = TreeNode::new(12);
let mut node32 = TreeNode::new(32);
let mut node62 = TreeNode::new(62);
let mut node80 = TreeNode::new(80);
node25.left = Some(Rc::new(RefCell::new(node12)));
node25.right = Some(Rc::new(RefCell::new(node32)));
node75.left = Some(Rc::new(RefCell::new(node62)));
node75.right = Some(Rc::new(RefCell::new(node80)));
node50.left = Some(Rc::new(RefCell::new(node25)));
node50.right = Some(Rc::new(RefCell::new(node75)));
let mut it = BSTIterator::new(Some(Rc::new(RefCell::new(node50))));
while it.has_next() {
println!("{}", it.next());
}
}
</code></pre>
<p>The compiler kept screaming at me, and it was my first time working with <code>Rc</code> and <code>RefCell</code>. Which anti-patterns do I have here? Is <code>(*rc).borrow().left.as_ref().and_then(/*...*/)</code> a reasonable thing to write in <code>insert</code>?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T09:34:33.907",
"Id": "251410",
"Score": "3",
"Tags": [
"rust",
"binary-search-tree"
],
"Title": "LeetCode 173: Binary Search Tree Iterator"
}
|
251410
|
<p>I was asked the following question while trying to get a Hackerrank certificate. I couldn't solve on time but I now completed the solution. Can you please check if my solution seems good? Suggestions on improvement are appreciated.</p>
<p>Q: You have a rectangle of width w and height h. You will start to draw boundaries. The number of boundaries is given by the length of the given array, distance. isVertical[i] represents whether or not i-th boundary is vertical or not. 1 means vertical and 0 means horizontal. distance[i] tells the distance between your boundary and the rectangle. In case of a horizontal boundary, it represents the distance from the bottom of your rectangle, and in case of a vertical boundary, it represents the distance from the left of your rectangle.</p>
<p>You need to return the largest areas of your rectangle as an array after drawing each of your boundaries.</p>
<p>ex) w = 4, h = 4, isVertical = [0,1], distance = [3,1]
After drawing the first boundary, the largest possible rectangle area is 12.
After drawing the second boundary, the largest possible rectangle area is 9.
You are not given a new rectangle for each boundary. You draw boundaries on the same rectangle.</p>
<p>You should return [12, 9].</p>
<p>My solution:</p>
<ul>
<li>I created one grid using a 2d-array and computed the largest possible rectangle area after each boundary is drawn by choosing the larger between the area taken up by the boundary and the current largest rectangle area minus the boundary area. I used the same, one grid to do computation for every boundary.</li>
</ul>
<pre><code>function largestArea(w, h, isVertical, distance) {
if (isVertical.length !== distance.length) return null;
if (w == 0 || h == 0) return 0;
let grid = new Array(h).fill(0).map(() => new Array(w).fill()); // -1 represents areas of the original rectangle
let largestArea = w*h;
let areas = [];
for (let i = 0; i < isVertical.length; i++) {
let boundaryArea = 0;
if (isVertical[i] == 1) {
boundaryArea = drawVerticalBoundary(distance[i], grid); // distance[i] for vertical boundary is distance from the left
} else {
boundaryArea = drawHorizontalBoundary(h-distance[i], grid); // distance[i] for horizontal boundary is distance from the bottom
}
largestArea = Math.max(largestArea-boundaryArea, boundaryArea);
areas.push(largestArea);
}
return areas;
}
function drawVerticalBoundary(maxCol, grid) {
let area = 0;
for (let row = 0; row < grid.length; row++) {
for (let col = 0; col < maxCol; col++) { // area already taken by another boundary is not part of current boundary
if (!grid[row][col]) {
area++;
grid[row][col] = 1;
}
}
}
return area;
}
function drawHorizontalBoundary(maxRow, grid) {
let area = 0;
for (let row = 0; row < maxRow; row++) {
for (let col = 0; col < grid[0].length; col++) {
if (!grid[row][col]) { // area already taken by another boundary is not part of current boundary
area++;
grid[row][col] = 1;
}
}
}
return area;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T13:28:51.430",
"Id": "494941",
"Score": "1",
"body": "Hello, I highly suggest you to edit your question and add a language tag (javascript, ect) to your question; you will have more answers this way, in my opinion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T16:46:05.097",
"Id": "494976",
"Score": "0",
"body": "Did so! Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T04:39:00.487",
"Id": "495324",
"Score": "0",
"body": "Can you link to the original question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T04:42:25.253",
"Id": "495325",
"Score": "0",
"body": "Also, can you give a quick high-level explanation of how you are thinking about the problem, and how you solved it? I'm having trouble seeing how this code relates to the problem as I understand it.\nIf you haven't verified your solution is correct on hackerrank, please do so first. We can only comment on style and speed. You're expected to have a correct solution already."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T21:16:34.430",
"Id": "495449",
"Score": "0",
"body": "Oh, didn't know that. Which community should I go instead to ask such question? There is no link to the original question as the question came up while I was trying to earn a certificate. This solution definitely works but uses unnecessarily too much space. I have written a new solution here: https://github.com/hbjORbj/interview_prep/blob/master/Second%2099/q_a125.js"
}
] |
[
{
"body": "<p>I do have a solution for this question but apology because I am proficient in python\nplease add the answer who can write the same logic in JS also.\nThanks</p>\n<p>what I have done is maintain array of width and height and get amximum width difference and height difference between adjcent location of H and W. which leads to maxArea of rectangle</p>\n<p>This is not efficient solution as it was giving timelimit exceed on 3-4 test cases.so appreciate if anyone can optimize it.</p>\n<pre><code>def getMaxArea(w, h, isVertical, distance):\n # Write your code here\n def insort(test_list, k):\n for i in range(len(test_list)):\n if test_list[i] > k:\n break\n return test_list[:i] + [k] + test_list[i:]\n \n maxy = 0\n wline = [0,w]\n hline = [0,h]\n res = []\n for i in range(len(isVertical)):\n if isVertical[i]:\n wline = insort(wline, distance[i])\n else:\n hline = insort(hline, distance[i])\n wmax = 0\n hmax = 0\n for i in range(1,len(wline)):\n if wline[i] - wline[i-1] > wmax:\n wmax = wline[i] - wline[i-1]\n for i in range(1,len(hline)):\n if hline[i] - hline[i-1] > hmax:\n hmax = hline[i] - hline[i-1]\n \n res.append(hmax * wmax)\n return res\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T20:45:53.717",
"Id": "515137",
"Score": "0",
"body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-21T19:45:20.450",
"Id": "261045",
"ParentId": "251411",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T09:55:17.110",
"Id": "251411",
"Score": "3",
"Tags": [
"javascript",
"programming-challenge"
],
"Title": "Largest rectangle areas after drawing boundaries"
}
|
251411
|
<h1>Description</h1>
<p>A regex-based method of validating ISBN-10 as strings. Can be digits (or 'X' at the end) only, or with dashes, according to those of <em>English-speaking publications</em> (which are defined by the regular expressions contained in the code below).</p>
<p>The last digit, a check digit (unless it is an 'X'), is calculated in the following manner. Multiply each digit, starting from the leftmost digit, by a weight, and then sum the results. The check digit should be such that this sum is divisible by 11. The weight starts at 1, and increases by 1 for each digit. For example, consider the ISBN 0-306-40615-2. The sum is calculated as follows:</p>
<pre><code>sum = 0*1 + 3*2 + 0*3 + 6*4 + 4*5 + 0*6 + 6*7 + 1*8 + 5*9 + 2*10 = 165
165 mod 11 = 0 // the check digit, 2, is valid.
</code></pre>
<p>I am a .NET developer dabbling in C++ for fun. With this exercise, I have tried to hide certain things from anything outside the <code>namespace</code>, by creating an anonymous <code>namespace</code> inside it. Essentially, I have tried to achieve what the <code>private</code> keyword does in C#, in C++ semantics. I am curious if I have done anything "un C++ like" in this code. I envisage this code could be expanded to have a function that validates ISBN-13 numbers.</p>
<h1>Code</h1>
<pre><code>#include <iostream>
#include <string>
#include <vector>
#include <regex>
#include <algorithm>
namespace isbn_validation
{
namespace // anonymous namespace
{
// regex expressions
// dashless
const std::regex isbn10_no_dashes(R"((\d{9})[\d|\X])");
// with dashes
const std::regex isbn10_dashes1(R"((\d{1})\-(\d{5})\-(\d{3})\-[\d|\X])");
const std::regex isbn10_dashes2(R"((\d{1})\-(\d{3})\-(\d{5})\-[\d|\X])");
const std::regex isbn10_dashes3(R"((\d{1})\-(\d{4})\-(\d{4})\-[\d|\X])");
const std::regex isbn10_dashes4(R"((\d{1})\-(\d{5})\-(\d{3})\-[\d|\X])");
const std::regex isbn10_dashes5(R"((\d{2})\-(\d{5})\-(\d{2})\-[\d|\X])");
const std::regex isbn10_dashes6(R"((\d{1})\-(\d{6})\-(\d{2})\-[\d|\X])");
const std::regex isbn10_dashes7(R"((\d{1})\-(\d{7})\-(\d{1})\-[\d|\X])");
bool isbn10_check_digit_valid(std::string isbn10)
{
auto valid = false;
// split it
std::vector<char> split(isbn10.begin(), isbn10.end());
// if the very last character is an 'X', don't bother with it
if (split[9] == 'X')
{
return true;
}
// all digits
// validate the last digit (check digit)
int digit_sum = 0;
int digit_index = 1;
for (std::vector<char>::iterator it = split.begin(); it != split.end(); ++it)
{
digit_sum = digit_sum + ((*it - '0')*digit_index);
digit_index++;
}
valid = !(digit_sum%11);
return valid;
}
}
bool valid_isbn10(std::string isbn)
{
// can take ISBN-10, with or without dashes
auto valid = false;
// check if it is a valid ISBN-10 without dashes
if (std::regex_match(isbn, isbn10_no_dashes))
{
// validate the check digit
valid = isbn10_check_digit_valid(isbn);
}
// check if it is a valid ISBN-10 with dashes
if (std::regex_match(isbn, isbn10_dashes1) || std::regex_match(isbn, isbn10_dashes2) || std::regex_match(isbn, isbn10_dashes3) ||
std::regex_match(isbn, isbn10_dashes4) || std::regex_match(isbn, isbn10_dashes5) || std::regex_match(isbn, isbn10_dashes6) || std::regex_match(isbn, isbn10_dashes7))
{
// remove the dashes
isbn.erase(std::remove(isbn.begin(), isbn.end(), '-'), isbn.end());
// validate the check digit
valid = isbn10_check_digit_valid(isbn);
}
return valid;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T13:02:15.970",
"Id": "495053",
"Score": "0",
"body": "Are isbn10_dashes1 and isbn10_dashes4 identical? Maybe I got this wrong! But the mere difficulty in checking it comes from the redundancy in the regular expressions. You should at least consider whether to construct the strings from a template string by replacing the numeric values. That would emphasize the differences and make them easier verifiable. (As always, the flip side of abstraction is that spelling it out is trivial which has its merits as well.)"
}
] |
[
{
"body": "<p>When you're comparing against 8 different patterns, and then simply removing <code>-</code> for 7 of those validations, why not just remove <code>-</code> initially, and then validate against the only remaining pattern.</p>\n<p>Another thing to note is, in the patterns, at the end; you have a character set: <code>[\\d|\\X]</code>. This actually will match one of:</p>\n<ul>\n<li>a digit</li>\n<li>literal <code>|</code></li>\n<li>literal <code>X</code> characters (you don't need <code>\\X</code> though).</li>\n</ul>\n<p>This should instead be:</p>\n<pre><code>\\d{9}[\\dX]\n</code></pre>\n<hr />\n<p>A general outline of how the code should work:</p>\n<ul>\n<li>Remove all <code>-</code> from given string</li>\n<li>Check if length of string is exactly <span class=\"math-container\">\\$ 10 \\$</span></li>\n<li>Validate against the pattern rewritten above</li>\n<li>Check if last character is <code>X</code></li>\n<li>Validate individual digit sum and divisibility.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T12:41:02.103",
"Id": "494933",
"Score": "1",
"body": "I have no insight on the standard, but is it desirable or even correct to accept a string with 9+1 digits and an arbitrary number of dashes at any positions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T12:57:38.707",
"Id": "494936",
"Score": "0",
"body": "@BlameTheBits According to a cursory reading on wikipedia, it seems like different countries/publishers use different dash formatting, but generally splitting into 4-5 parts"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T21:52:23.637",
"Id": "494992",
"Score": "0",
"body": "They are split into several parts. I have considered only English publication ISNB formats in that regard. These ISBNs have specific digits that are valid for these parts, but I have not taken that into account, as that would have meant creating dozens more regexes."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T11:21:36.643",
"Id": "251417",
"ParentId": "251415",
"Score": "6"
}
},
{
"body": "<p><a href=\"/u/12240\">hjpotter92</a> starts with the right idea:<br />\nUnify and simplify.<br />\nYou just should go much further.</p>\n<p>Also, don't give up if the last digit is <code>X</code>, that's a perfectly fine digit for your code.</p>\n<p>You aren't (or shouldn't) be interested in all the dashes, so ignore them.<br />\nCould you even know that you have all the used patterns?</p>\n<p>Take a closer look at <a href=\"//de.wikipedia.org/wiki/Internationale_Standardbuchnummer#ISBN-10\" rel=\"noreferrer\">wikipedia on ISBN10</a>, and you will find that the pattern is completely regular. Every digit is multiplied by its position, even the last (which might be 10, represented by <code>X</code>).</p>\n<p>As there is no need to modify the string, you can use a <a href=\"https://en.cppreference.com/w/cpp/string/basic_string_view\" rel=\"noreferrer\"><code>std::string_view</code></a>, giving any caller maximum convenience <em>and</em> efficiency.<br />\nYes, it only came with C++17, if your library doesn't supply it either use a free implementation or at least fall back to <code>std::string const&</code> to hopefully avoid copies.</p>\n<p>Avoiding needless allocations (even though small-object-optimization probably saves your bacon for the string-argument to your helper-function) is a very C++ thing to do.</p>\n<p>Not that it can fix your creation of a perfectly superfluous <code>std::vector</code>.</p>\n<p>And now you can mark it <code>noexcept</code> and <code>constexpr</code>, giving the callers assurance it will always succeed and can even be done at compile-time.</p>\n<p>By the way, for-range is a thing in C++ since C++11, and much preferred over manual iterator-juggling.</p>\n<p>And if you do the same operation multiple times with different data, consider storing it in an array and looping, like you would also do in C#.</p>\n<pre><code>constexpr bool validate_isbn10(std::string_view s) noexcept {\n unsigned num = 0; // unsigned so overflow is harmless\n std::size_t found = 0; // std::size_t so cannot overflow at all\n for (auto c : s)\n if (c >= '0' && c <= '9')\n num += ++found * (c - '0');\n else if (c == 'X' && found == 9)\n num += ++found * 10;\n else if (c != '-')\n return false;\n return found == 10 && num % 11 == 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T22:51:58.423",
"Id": "251445",
"ParentId": "251415",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "251417",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T10:53:33.080",
"Id": "251415",
"Score": "6",
"Tags": [
"c++",
"c++11",
"regex"
],
"Title": "Validating ISBN-10s, with or without dashes in C++11"
}
|
251415
|
<p>I've been following Wes Bos challenge, I wrote the code myself then looked at his finished example.
Here's my code (I only wrote the JS):</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>const cities = [];
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
fetch(endpoint)
.then(blob => blob.json())
.then(json => cities.push(...json))
.catch(err => console.log(err.message));
const input = document.querySelector('.search');
const suggestions = document.querySelector('.suggestions');
function findMatches(word, cities) {
const regex = new RegExp(word, 'gi');
return cities.filter(city => city.city.match(regex) || city.state.match(regex));
}
function displayMatches(value) {
const matchingCities = findMatches(value, cities);
for (const city of matchingCities) {
const spanCity = document.createElement('span');
spanCity.setAttribute('class', 'name');
const regex = new RegExp(value, 'gi');
const cityName = `${city['city']}, ${city['state']}`.replace(regex, `<span class="hl">${value}</span>`);
spanCity.innerHTML = cityName;
const spanPopulation = document.createElement('span');
spanPopulation.setAttribute('class', 'population');
spanPopulation.textContent = numberWithCommas(city['population']);
const li = document.createElement('li');
li.appendChild(spanCity);
li.appendChild(spanPopulation);
suggestions.appendChild(li);
}
}
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
input.addEventListener('input', e => {
while (suggestions.lastChild) {
suggestions.removeChild(suggestions.lastChild);
}
const value = input.value.toLowerCase();
const isEmpty = value.length === 0;
if (isEmpty) {
const li1 = document.createElement('li');
li1.textContent = 'Filter for a city';
suggestions.appendChild(li1);
const li2 = document.createElement('li');
li2.textContent = 'or a state';
suggestions.appendChild(li2);
return;
}
displayMatches(value);
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
box-sizing: border-box;
background: #ffc600;
font-family: 'helvetica neue';
font-size: 20px;
font-weight: 200;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
input {
width: 100%;
padding: 20px;
}
.search-form {
max-width: 400px;
margin: 50px auto;
}
input.search {
margin: 0;
text-align: center;
outline: 0;
border: 10px solid #F7F7F7;
width: 120%;
left: -10%;
position: relative;
top: 10px;
z-index: 2;
border-radius: 5px;
font-size: 40px;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.12), inset 0 0 2px rgba(0, 0, 0, 0.19);
}
.suggestions {
margin: 0;
padding: 0;
position: relative;
}
.suggestions li {
background: white;
list-style: none;
border-bottom: 1px solid #D8D8D8;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.14);
margin: 0;
padding: 20px;
transition: background 0.2s;
display: flex;
justify-content: space-between;
text-transform: capitalize;
}
.suggestions li:nth-child(even) {
transform: perspective(100px) rotateX(3deg) translateY(2px) scale(1.001);
background: linear-gradient(to bottom, #ffffff 0%, #EFEFEF 100%);
}
.suggestions li:nth-child(odd) {
transform: perspective(100px) rotateX(-3deg) translateY(3px);
background: linear-gradient(to top, #ffffff 0%, #EFEFEF 100%);
}
span.population {
font-size: 15px;
}
.hl {
background: #ffc600;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><form class="search-form">
<input type="text" class="search" placeholder="City or State">
<ul class="suggestions">
<li>Filter for a city</li>
<li>or a state</li>
</ul>
</form></code></pre>
</div>
</div>
</p>
<p>Please review it.</p>
<p>And one question. In his finished code, <code>displayMatches()</code> function looks like this. I wonder which option is better (of course this one is shorter):</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function displayMatches() {
const matchArray = findMatches(this.value, cities);
const html = matchArray.map(place => {
const regex = new RegExp(this.value, 'gi');
const cityName = place.city.replace(regex, `<span class="hl">${this.value}</span>`);
const stateName = place.state.replace(regex, `<span class="hl">${this.value}</span>`);
return `
<li>
<span class="name">${cityName}, ${stateName}</span>
<span class="population">${numberWithCommas(place.population)}</span>
</li>
`;
}).join('');
suggestions.innerHTML = html;
}</code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p><strong>Asynchronous loading</strong> The population of the <code>cities</code> variable looks suspicious because all it does is push to an array after the request finishes. On seeing that, readers of the code could very easily worry that the script, once run, isn't going to run in the right order due to the <a href=\"https://stackoverflow.com/q/23667086\">extremely common bug</a> caused by a variable being populated asynchronously. Your code <em>happens to work</em> anyway, but it looks worrying on the first glance.</p>\n<p>That aside, what if the <code>githubusercontent</code> endpoint is not reachable? Then the script will appear to do nothing when stuff is typed in, and the user will be confused.</p>\n<p>Fix it by introducing something like a loading screen, which indicates to the user that data is being fetched, and display an error if fetching fails. (Maybe add a check to see if fetching takes an unexpectedly long amount of time and show an error in that case too.)</p>\n<p><strong>Responses aren't blobs</strong> You do <code>fetch(endpoint).then(blob => blob.json())</code>. The variable named <code>blob</code> is actually a <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Response\" rel=\"nofollow noreferrer\">Response object</a>. (You could get a Blob out of the Response stream if you called <code>.blob()</code> on it, but you're calling <code>.json()</code> on it.) Probably best to change the variable name to <code>response</code> or something like it.</p>\n<p><strong>JSON is a <em>string</em> format</strong> You do <code>.then(json => cities.push(...json))</code>. JSON is a way of representing data in string format. After deserialization, what you have is no longer JSON - it's just a plain array or object. This is a common issue. <a href=\"http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/\" rel=\"nofollow noreferrer\">There's no such thing as a JSON object</a>. I'd call it something like <code>responseCities</code> instead.</p>\n<p><strong>Regular expression special characters</strong> Some characters have a special meaning in regular expressions. For example, <code>.</code> will match any character, and <code>foo+</code> will not match <code>foo</code> followed by a literal plus, but <code>foo</code> followed by one or more <code>o</code>s. Whenever using <code>new RegExp</code>, make sure you're accounting for these sorts of cases, else you'll probably run into problems when unexpected characters are encountered. For example, someone searching for <code>st.</code> will see the following:</p>\n<p><a href=\"https://i.stack.imgur.com/MGG0j.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/MGG0j.png\" alt=\"enter image description here\" /></a></p>\n<p>To escape special characters, you can use <code>.replace</code> to escape the input before passing it to the RegExp constructor: <a href=\"https://stackoverflow.com/q/3561493\">https://stackoverflow.com/q/3561493</a></p>\n<p>If you were just just trying to see if one string exists inside another, without case sensitivity, I think the code would be easier to understand if you called <code>toLowerCase()</code> on both strings and then used <code>.includes</code>. But since you want to insert a <code><span></code> at certain points, there's no getting around a regular expression somewhere.</p>\n<p>To simplify it a bit, consider using a regular expression <em>just once</em>, rather than twice - take the value and try to replace it with the <code><span></code>s. If the resulting string is different from the original string, it's a match, so you can use the result; otherwise, if the resulting string is the same, it's not a match.</p>\n<p><strong>cityName?</strong> You concatenate the city and state together when creating the string to display to the user. Rather than call it <code>cityName</code>, consider calling it <code>locationName</code> - it's not just a city anymore, after all.</p>\n<pre><code>for (const city of cities) {\n const baseLocationName = `${city['city']}, ${city['state']}`;\n const highlightedLocationName = baseLocationName.replace(\n new RegExp(escapeRegex(value), 'gi'),\n `<span class="hl">${value}</span>`\n );\n if (highlightedLocationName !== baseLocationName) {\n insertLocation(highlightedLocationName, city);\n }\n}\n</code></pre>\n<p><strong>More concise object navigation</strong> You can change:</p>\n<p><code>spanCity.setAttribute('class', 'name')</code> to <code>spanCity.className = 'name';</code> (or remove this class entirely, since the class name isn't referenced anywhere else)</p>\n<p><code>city['population']</code> to <code>city.population</code> (dot notation looks nicer and is probably preferable when possible)</p>\n<p><strong>Clearing the HTML</strong> can be done easily by just setting the <code>textContent</code> of the container to the empty string - no need to iterate over the <code>lastChild</code>s until no more exist.</p>\n<p><strong>Placeholder text</strong> When you're waiting for the user to start typing, rather than inserting elements with <code>document.createElement</code> / <code>appendChild</code> / <code>textContent</code> and so on (which is a bit verbose), consider just setting the HTML content.</p>\n<pre><code>suggestions.innerHTML = `\n <li>Filter for a city</li>\n <li>or a state</li>\n`;\n</code></pre>\n<p><strong>Suggestion limit</strong> There are a lot of possible cities. If more than, say, 20 get rendered, the page gets quite large and can take a while to load. Consider rendering only 20 at most.</p>\n<p>Implementing all of these gives you:</p>\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 endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';\n\nconst setupListener = (cities) => {\n const escapeRegex = s => s.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&');\n const input = document.querySelector('.search');\n\n function displayMatches(value) {\n let matchCount = 0;\n for (const city of cities) {\n const baseLocationName = `${city['city']}, ${city['state']}`;\n const highlightedLocationName = baseLocationName.replace(\n new RegExp(escapeRegex(value), 'gi'),\n `<span class=\"hl\">${value}</span>`\n );\n if (highlightedLocationName !== baseLocationName) {\n insertLocation(highlightedLocationName, city);\n matchCount++;\n if (matchCount >= 20) {\n return;\n }\n }\n }\n }\n function insertLocation(locationNameHTML, city) {\n const li = suggestions.appendChild(document.createElement('li'));\n const locationSpan = li.appendChild(document.createElement('span'));\n locationSpan.innerHTML = locationNameHTML;\n const locationPopulationSpan = li.appendChild(document.createElement('span'));\n locationPopulationSpan.className = 'population';\n locationPopulationSpan.textContent = numberWithCommas(city.population);\n }\n\n function numberWithCommas(x) {\n return x.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\n }\n const handleInput = () => {\n suggestions.textContent = '';\n\n const value = input.value.toLowerCase();\n const isEmpty = value.length === 0;\n if (!isEmpty) {\n displayMatches(value);\n return;\n }\n suggestions.innerHTML = `\n <li>Filter for a city</li>\n <li>or a state</li>\n `;\n };\n input.addEventListener('input', handleInput);\n // Remove the loading screen:\n handleInput();\n};\n\n\nconst suggestions = document.querySelector('.suggestions');\nfetch(endpoint)\n .then(response => response.json())\n .then(setupListener)\n .catch(err => {\n suggestions.textContent = 'There was an unexpected error: ' + err.message;\n });</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>html {\n box-sizing: border-box;\n background: #ffc600;\n font-family: 'helvetica neue';\n font-size: 20px;\n font-weight: 200;\n}\n\n*,\n*:before,\n*:after {\n box-sizing: inherit;\n}\n\ninput {\n width: 100%;\n padding: 20px;\n}\n\n.search-form {\n max-width: 400px;\n margin: 50px auto;\n}\n\ninput.search {\n margin: 0;\n text-align: center;\n outline: 0;\n border: 10px solid #F7F7F7;\n width: 120%;\n left: -10%;\n position: relative;\n top: 10px;\n z-index: 2;\n border-radius: 5px;\n font-size: 40px;\n box-shadow: 0 0 5px rgba(0, 0, 0, 0.12), inset 0 0 2px rgba(0, 0, 0, 0.19);\n}\n\n.suggestions {\n margin: 0;\n padding: 0;\n position: relative;\n}\n\n.suggestions li {\n background: white;\n list-style: none;\n border-bottom: 1px solid #D8D8D8;\n box-shadow: 0 0 10px rgba(0, 0, 0, 0.14);\n margin: 0;\n padding: 20px;\n transition: background 0.2s;\n display: flex;\n justify-content: space-between;\n text-transform: capitalize;\n}\n\n.suggestions li:nth-child(even) {\n transform: perspective(100px) rotateX(3deg) translateY(2px) scale(1.001);\n background: linear-gradient(to bottom, #ffffff 0%, #EFEFEF 100%);\n}\n\n.suggestions li:nth-child(odd) {\n transform: perspective(100px) rotateX(-3deg) translateY(3px);\n background: linear-gradient(to top, #ffffff 0%, #EFEFEF 100%);\n}\n\nspan.population {\n font-size: 15px;\n}\n\n.hl {\n background: #ffc600;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><form class=\"search-form\">\n <input type=\"text\" class=\"search\" placeholder=\"City or State\">\n <ul class=\"suggestions\">App is loading...</ul>\n</form></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<blockquote>\n<p>And one question. In his finished code, <code>displayMatches()</code> function looks like this. I wonder which option is better (of course this one is shorter):</p>\n</blockquote>\n<p>I strongly prefer your version because it's <em>safer</em>. Direct concatenation of input to create an HTML string can result in arbitrary code execution, which is a security risk. If the data happened to come from an API, and you didn't trust the API 100%, there could be problems.</p>\n<p>His code could be fixed by assigning to the <code>.textContent</code> of the <code><span></code>s afterwards, instead of interpolating.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T16:38:32.273",
"Id": "495089",
"Score": "0",
"body": "thanks for valuable comments. i have a few questions: 1) i create `async function fetchData(endpoint) { const res = await fetch(endpoint); if(!res.ok) throw new error('Unable to fetch data.');`, and when endpoint is not reachable, why this error isn't returned? instead there's `TypeError: Failed to fetch` 2) i remember someone advised to never ever use `innerHTML`. how else can i bypass it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T16:46:14.343",
"Id": "495092",
"Score": "1",
"body": "`Failed to fetch` will be thrown if the request can't get started in the first place - the `await fetch(..)` threw, so it never got to the `res.ok` check. There is absolutely nothing wrong with `innerHTML` as long as the text is trustworthy and you don't interpolate (both of which are often easy to manage) - but if you really didn't want to use it for some reason, you could go back to the `createElement` / `appendChild` methods in your original code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T16:53:36.357",
"Id": "495094",
"Score": "0",
"body": "how should i catch `await fetch(..)` then?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T16:56:42.347",
"Id": "495095",
"Score": "1",
"body": "I wouldn't bother, I'd use `.then` instead of `await`, and put a `.catch` at the end of the Promise chain to handle any errors thrown above, like in my answer. (adding in the `res.ok` check too, if you want)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T16:59:03.357",
"Id": "495096",
"Score": "0",
"body": "how about this: https://hastebin.com/eqelifataz.js?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T17:23:31.447",
"Id": "495104",
"Score": "1",
"body": "Works, but it'd be better to initialize listeners once the response comes back instead of *just* pushing to the cities array, and described in the answer. Also `.then(arr => storeCities(arr))` simplifies to `.then(storeCities)`"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T00:42:55.787",
"Id": "251447",
"ParentId": "251416",
"Score": "4"
}
},
{
"body": "<p>Thank you for sharing your code. I have written an implementation of my own and I will comment below on the places where my design decisions diverged from yours.</p>\n<h2>Use Promises for Asynchronous Control Flow</h2>\n<p>When fetching data asynchronously - as <code>cities</code> is fetched - I would use a Promise object to handle the asynchronous flow. As your code is currently, there is technically a <a href=\"https://en.wikipedia.org/wiki/Race_condition\" rel=\"nofollow noreferrer\">race condition</a> because there is code that assumes that <code>cities</code> is fully-populated without checking if the <code>fetch</code> has actually completed.</p>\n<p>I would assign the Promise returned by <code>fetch</code> to a variable and then put any code that relies on the value of <code>cities</code> into a <code>.then</code> handler. In the case of this example, the change in application behavior may be negligible, but I still like this approach because it is more explicit and correct. It allows me, as a programmer reading the code, to know that <code>cities</code> is fetched asynchronously without my having to search through the code to see when/how the Array is populated.</p>\n<p>The code becomes:</p>\n<pre><code>const getCitiesPromise = fetch('https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json')\n .then(response => {\n if (!response.ok) { throw new Error('Failed to fetch cities'); }\n return response.json();\n })\n .catch(err => {\n console.error(err);\n });\n</code></pre>\n<p>Notice, also, that I omitted the <code>json => cities.push(...json)</code>. I find this to be unnecessary work to push each element of the <code>json</code> array onto the <code>cities</code> array. <code>json</code> is already the array of cities we want, so why not just point <code>cities</code> to it, as in: <code>cities = json</code>?</p>\n<h2>Decouple Functions</h2>\n<p>If I could change one thing about this code, I would take the <code>findMatches</code> call <em>out of</em> <code>displayMatches</code>. By having <code>displayMatches</code> call <code>findMatches</code>, it makes the application more difficult to debug. If, for some reason, we were not rendering any matches, it would be difficult to determine if the problem were with the finding or the displaying. Ideally, we would want to be able to feed a hard-coded list of <code>cities</code> to <code>displayMatches</code> so that we could quickly assess where our issue lay. Additionally, a separation would allow us to feed a hard-coded search term to <code>findMatches</code> and simply <code>console.log</code> the output without needing the DOM. This is <em>much</em> easier both to debug and to unit-test.</p>\n<p>In my implementation, I split these into functions called "findMatches" and "renderCitiesList", and they look like:</p>\n<pre><code>const findMatches = (cities, searchTerm) => {\n if (!searchTerm) { return []; }\n const regex = new RegExp(searchTerm, 'gi');\n return cities.filter(city => city.city.match(regex) || city.state.match(regex));\n};\n\nconst renderCitiesList = ($el, cities, searchTerm) => {\n const regex = new RegExp(`(${searchTerm})`, 'gi');\n const html = cities.map(city => {\n const formattedCity = formatCity(city).replace(regex, '<strong>$1</strong>');\n return `<li>${formattedCity} - ${formatPopulation(city.population)}</li>`;\n }).join('');\n \n $el.innerHTML = html || '';\n};\n</code></pre>\n<p>I decided to make these functions more "functional" by having them take <code>cities</code> as a parameter to facilitate the debugging and unit-testing as I mentioned above. My render function does, however, rely on some formatting functions, which I shall discuss later.</p>\n<h2>Avoid Unnecessary Loops</h2>\n<p>The most curious piece of the code to me was the <code>while</code> loop in the <code>input</code> event listener. There is no need to remove the child nodes of the <code>suggestions</code> element one at a time. <code>suggestions.innerHTML = ''</code> would do the trick in one fell swoop.</p>\n<p>In my implementation, I did not even include code to explicitly empty the <code>suggestions</code> element (which I called <code>$cities</code>). My <code>renderCitiesList</code> function (above) maps <code>cities</code> to formatted <code><li></code> strings and injects the concatenated result into the <code>$cities</code> element. If there are no <code>cities</code>, an empty string is injected.</p>\n<p>As the matching and rendering had already been decoupled into independent functions, the only duty left to my event listener was to invoke the find and pass the result to the render:</p>\n<pre><code>const $search = document.getElementById('Search');\n\n$search.addEventListener('input', () => {\n const searchTerm = ($search.value || '').toLowerCase();\n \n getCitiesPromise.then((cities) => {\n renderCitiesList($cities, findMatches(cities, searchTerm), searchTerm);\n });\n});\n</code></pre>\n<p>It is worth noting that I did not include the default messaging, "Filter for a city or a state", but, if I had, I would have done this in the <code>renderCitiesList</code> function as it is presentation logic.</p>\n<h2>Function Names should describe the What, Not the How</h2>\n<p>I did not like the name "numberWithCommas" for the function that formats the population number. If we ever wanted to change how we formatted this number - say, we wanted to use spaces instead of commas - then we would need to rename our function because it would become a lie. This is why we want to give our functions names that describe <em>what</em> they do, but not <em>how</em> they do it. A function name like "formatPopulation" could be repeatedly updated with new formatting rules and its name would remain honest and descriptive.</p>\n<p>Additionally, in my implementation I avoided the Regular Expression. I am not saying that the Regular Expression is bad, I just found it a little tricky for my tastes and I wanted to see if I could arrive at a solution that was succinct and simple. Basically, I used <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice\" rel=\"nofollow noreferrer\">String.prototype.slice</a> to get the parts of the value that needed to be separated into, pushed them to an Array, and then joined them with a ",".</p>\n<pre><code>const formatPopulation = population => {\n const parts = [];\n \n for (let i = population.length; i > 0; i -= 3) {\n parts.push(population.slice(Math.max(0, i - 3), i));\n }\n \n return parts.reverse().join(',');\n};\n</code></pre>\n<h2>Extra Credit</h2>\n<p>I thought it would improve the UI if the returned list of matched <code>cities</code> was sorted alphabetically. As I was already handling the <code>cities</code> with a Promise, this just required adding an extra <code>then</code> handler to do the sorting*:</p>\n<pre><code>const getCitiesPromise = fetch('https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json')\n .then(response => {\n if (!response.ok) { throw new Error('Failed to fetch cities'); }\n return response.json();\n })\n .then(cities => {\n return cities.sort((city1, city2) => {\n const formattedCity1 = formatCity(city1);\n const formattedCity2 = formatCity(city2);;\n \n if (formattedCity1 < formattedCity2) { return -1; }\n if (formattedCity1 > formattedCity2) { return 1; }\n \n return 0;\n });\n })\n .catch(err => {\n console.error(err);\n });\n</code></pre>\n<p>I wanted to ensure that the cities were rendered in sorted order (alphabetically, ascending). For this reason, I needed to make sure that the compare function was comparing cities in the same format as they were being rendered. For this reason, I created a <code>formatCity</code> function so that both the sort and the <code>renderCitiesList</code> functions could use the same logic without code duplication.</p>\n<h2>The Result</h2>\n<p>My completed solution is as follows. Note that I implemented only the JavaScript and did not concern myself with the styling.</p>\n<pre><code>const $cities = document.getElementById('Cities');\nconst $search = document.getElementById('Search');\n\nconst findMatches = (cities, searchTerm) => {\n if (!searchTerm) { return []; }\n const regex = new RegExp(searchTerm, 'gi');\n return cities.filter(city => city.city.match(regex) || city.state.match(regex));\n};\n\nconst formatCity = city => {\n return `${city.city}, ${city.state}`;\n};\n\nconst formatPopulation = population => {\n const parts = [];\n \n for (let i = population.length; i > 0; i -= 3) {\n parts.push(population.slice(Math.max(0, i - 3), i));\n }\n \n return parts.reverse().join(',');\n};\n\nconst renderCitiesList = ($el, cities, searchTerm) => {\n const regex = new RegExp(`(${searchTerm})`, 'gi');\n const html = cities.map(city => {\n const formattedCity = formatCity(city).replace(regex, '<strong>$1</strong>');\n return `<li>${formattedCity} - ${formatPopulation(city.population)}</li>`;\n }).join('');\n\n $el.innerHTML = html || '';\n};\n\nconst getCitiesPromise = fetch('https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json')\n .then(response => {\n if (!response.ok) { throw new Error('Failed to fetch cities'); }\n return response.json();\n })\n .then(cities => {\n return cities.sort((city1, city2) => {\n const formattedCity1 = formatCity(city1);\n const formattedCity2 = formatCity(city2);;\n \n if (formattedCity1 < formattedCity2) { return -1; }\n if (formattedCity1 > formattedCity2) { return 1; }\n\n return 0;\n });\n })\n .catch(err => {\n console.error(err);\n });\n\n$search.addEventListener('input', () => {\n const searchTerm = ($search.value || '').toLowerCase();\n \n getCitiesPromise.then((cities) => {\n renderCitiesList($cities, findMatches(cities, searchTerm), searchTerm);\n });\n});\n</code></pre>\n<p>I have created a <a href=\"https://jsfiddle.net/76484/jL9wh10u/\" rel=\"nofollow noreferrer\">fiddle</a> for reference.</p>\n<p>As to your question of whose implementation of <code>displayMatches</code> is better: Wes Bos's <code>displayMatches</code> is very similar to mine. Ours differ from yours in two ways. First, we use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow noreferrer\">Array.prototype.map</a> to map matched cities to HTML element strings whereas you use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\">for...of loop</a>. Array.prototype.map is a more "functional" way to produce the output and I prefer it for all the standard reasons the advocates of functional programming emphasize. What I particularly like about this implementation is that, as it just spits-out a String without manipulating the DOM, I can <code>console.log</code> the result to do my debugging and can completely ignore what is rendered to the page. The second difference is that Wes and I are creating an HTML string and using <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML\" rel=\"nofollow noreferrer\"><code>Element.innerHTML</code></a> whereas you are calling <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild\" rel=\"nofollow noreferrer\"><code>Node.appendChild</code></a> for each item in your for...of. I find the former cleaner for its lack of <code>.setAttribute</code>s and <code>.textContent</code>s. Also, as yours updates the DOM <em>twice for each match</em> (<code>.appendChild</code> is called twice in the loop body), it is possible that it is less performant. The performance impact is probably negligible (one would need to measure to be sure); it is the readability that guides my design decision.</p>\n<p>Frankly, it is the call to <code>findMatches</code> that I dislike most about yours and Wes's implementations. For the reasons I stated above, I think these actions are best left independent (decoupled). I think code is most comprehensible when it decisively separates the processing from the rendering.</p>\n<p>Thank you. I hope you are able to find something in my response that helps you.</p>\n<p>* I owe a Thank You to the author of this <a href=\"https://stackoverflow.com/a/6712080/3397771\">StackOverflow post</a> for a refresher on sorting Arrays of Strings in JavaScript.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T16:41:32.843",
"Id": "495090",
"Score": "0",
"body": "thanks for your helpful feedback."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T01:48:12.387",
"Id": "251449",
"ParentId": "251416",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "251447",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T11:12:20.157",
"Id": "251416",
"Score": "6",
"Tags": [
"javascript",
"html",
"css",
"ecmascript-6"
],
"Title": "Type ahead in JS"
}
|
251416
|
<p>I have an array of integers, I have to find all sub-arrays of different size from <code>1</code> to <code>len(array)</code>. In every sub-array, I have to find the minimum value in it, once done I have to find the maximum value between the minimum values of all the subarrays of the same size. Finally, I have to return these maximum values in a list.</p>
<p>So the first value in my list will always be the maximum integer in the array, the second value will be the maximum between the minimum values of the sub-arrays size 2, and so on; the last value in the list will always be the minimum integer of the array.
Original problem here: <a href="https://www.hackerrank.com/challenges/min-max-riddle/problem" rel="nofollow noreferrer">Min Max Riddle</a></p>
<pre class="lang-py prettyprint-override"><code>def min_max_subarrays(arr):
result = [max(arr), ]
w = 2
while w < len(arr):
temp = 0
for i, n in enumerate(arr[:-w+1]):
x = min(arr[i:i+w])
if x > temp:
temp = x
result.append(temp)
w += 1
result.append(min(arr))
return result
</code></pre>
<p>The function is correct but I'm sure there's a way to reduce time complexity. I feel one loop is unnecessary but I'm struggling to find a way to remove it.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T13:51:45.700",
"Id": "494947",
"Score": "0",
"body": "I corrected the indentation (It was a copy/paste error), yes it is online somewhere but I did it a while ago and don't remember where it is... If my explanation isn't clear I can search for the original."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T14:18:43.863",
"Id": "494950",
"Score": "0",
"body": "I found it: \"Min Max Riddle\" on Hackerrank"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T15:06:13.087",
"Id": "494959",
"Score": "2",
"body": "I see. So one important thing you omitted is the limits. n=10^6 rules out not only cubic time solutions like yours but also quadratic time ones."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T15:51:13.420",
"Id": "494968",
"Score": "2",
"body": "Perhaps add the link to hackerrank in question too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T15:55:07.797",
"Id": "494971",
"Score": "0",
"body": "also, check the discussions on the same for a hint on \\$ O(n) \\$ solution https://www.hackerrank.com/challenges/min-max-riddle/forum/comments/486316"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T02:05:37.773",
"Id": "495301",
"Score": "0",
"body": "By 'the maximum between' do you mean 'the maximum OF' or 'the maximum of the pairwise subtraction'?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T14:24:50.447",
"Id": "495379",
"Score": "0",
"body": "\"the maximum of\", also there's a link with all the details"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T12:09:45.507",
"Id": "251419",
"Score": "2",
"Tags": [
"python",
"array"
],
"Title": "Find the max value between minimum values in sub-arrays"
}
|
251419
|
<p>It could be a simple Fisher-Yates, but then if the number of participants is 1,000,000 and the number of winner is only 3, then we really don't need to shuffle the whole 1,000,000 numbers, so the following is to reduce the number of steps, written as a simpler case of drawing 9 winners out of 30 participants:</p>
<p>The following is to consider 30 participants, each numbered from 1 to 30, and take out 9 winners. One will be Grand Prize, and two will be Second Prizes, and 6 Third Prizes.</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>const NUM_PARTICIPANTS = 30;
const NUM_DRAWN = 9;
console.log(`run: ${NUM_PARTICIPANTS} draw ${NUM_DRAWN}`);
const arr = Array.from(new Array(NUM_PARTICIPANTS), (e, i) => i + 1);
for (let i = arr.length - 1; i >= NUM_PARTICIPANTS - NUM_DRAWN; --i) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
const results = arr.slice(NUM_PARTICIPANTS - NUM_DRAWN)
console.log(`Grand prize: ${results[0]}`);
console.log(`Second prize: ${results.slice(1,3).sort((a, b) => a - b).join(" ")}`);
console.log(`Other winners:\n ${results.slice(3).sort((a, b) => a - b).join("\n ")}`);</code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>You could use a loop to cycle through the total number of winners desired, then individually select a random winner and remove it from the array of participants.\nIf you don't want to modify the original array of participants, you can create a copy to work with.\nThis is a way to generate the results array that should scale better with a high number of participants with few winners. How you select the 1st place, 2nd place, and so on, works the same after this code snippet.</p>\n<pre><code>const participants = [...arr];\nlet results = [];\n\nfor (let i = 0; i < NUM_DRAWN; i++) {\n const choice = Math.floor(Math.random() * participants.length);\n results.push(participants[choice]);\n participants.splice(choice, 1);\n}\n</code></pre>\n<p>Edit: <code>arr.length</code> is now <code>participants.length</code>, since you want the upper range of the random number to match the adjusted size of <code>participants</code> as it loses people.</p>\n<p>Edit: Changed the temporary array into a set so that removing elements becomes O(1) instead of O(N). This works best when there are many more participants than winners (3/1,000,000 hell yea!, but 9/30 is not so great). Otherwise the while loop can end up doing many wasted iterations looking for participants not already in results. Notice that now I am dealing directly with the values of the participants, and not array indices. This wouldn't work as well if arr was filled with name strings instead of [1,2,3...,N].</p>\n<pre><code>const participants = new Set(arr);\nconst results = [];\n\nwhile (results.length < NUM_DRAWN)\n const choice = Math.ceil(Math.random() * NUM_PARTICIPANTS);\n if (participants.has(choice) {\n results.push(choice);\n participants.delete(choice);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T00:21:37.397",
"Id": "495005",
"Score": "0",
"body": "This method will not scale that well. If there is a high number of participants then splice will be an expensive operation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T01:16:05.760",
"Id": "495007",
"Score": "0",
"body": "You said \"You could use a loop to cycle through the total number of winners desired, then individually select a random winner and remove it from the array of participants\" but then if you even remove 1 element, you could be possibly dealing with O(N) where N is 1,000,000, and then when you remove another again, then another 1,000,000 steps, then why not just shuffle it once? Fisher-Yates is good because it doesn't \"shrink\" the array"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T04:28:41.390",
"Id": "495012",
"Score": "0",
"body": "I forgot that splicing out an element was O(N) because even though the index is known (finding it should be O(1)), everything after it needs to get shifted back by 1."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T20:12:51.140",
"Id": "251439",
"ParentId": "251420",
"Score": "3"
}
},
{
"body": "<h1>Simulating Random sequences</h1>\n<p>In games of chance we use random numbers not to simulate random outcomes, but rather to obscure results so that they can not be easily known in advance.</p>\n<h2>Why bother with random</h2>\n<p>As any sequence of independent random values is just as likely as any other we don't need to use a (pseudo) random number generator to simulate the generation the sequence.</p>\n<p>We can hard code it as follows</p>\n<pre><code> const NUM_DRAWN = 9;\n const results = [1,2,3,4,5,6,7,8,9];\n\n console.log(`Grand prize: ${results[0]}`);\n console.log(`Second prize: ${results.slice(1,3).sort((a, b) => a - b).join(" ")}`);\n console.log(`Other winners:\\n ${results.slice(3).sort((a, b) => a - b).join("\\n ")}`)\n</code></pre>\n<p>It would be statistically as robust as any other method (There are no logical or physical proofs of randomness). That does not mean it is random, it is not at all random, it is just statistically consistent with any other selection method.</p>\n<p>However we don't want people to cheat by knowing the outcome ahead of time</p>\n<h2>Non Trivial Determinism</h2>\n<p>Computers are deterministic and it is possible to know all winners ahead of time no matter what code you write.</p>\n<p>What we want is to make finding out who the winners will be ahead of time as non trivial as possible.</p>\n<p>JavaScript's pseudo random is seeded with the system clock. The pseudo random value is a Double (64 bit floating point). Checking if you guessed the correct seed and finding the correct spot in the sequence would require too much work to be worth the effort.</p>\n<h2>Only the winners</h2>\n<p>Rather than create an array of 30 (or 1,000,000) people, we need only the array for the winners.</p>\n<p>We pick a numbered person and check if that person is in the winning set or not. If not add the person to the set of winners. Do this until you have found all the winners.</p>\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 NUM_PARTICIPANTS = 30, NUM_DRAWN = 9;\nconst randomInt = range => Math.floor(Math.random() * range);\nconst results = createWinners(); \nconsole.log(`Draw ${NUM_DRAWN} from ${NUM_PARTICIPANTS}`);\nconsole.log(`Grand prize: ${results[0]}`);\nconsole.log(`Second prize: ${results.slice(1,3).sort((a, b) => a - b).join(\" \")}`);\nconsole.log(`Other winners:\\n ${results.slice(3).sort((a, b) => a - b).join(\"\\n \")}`);\n\nfunction createWinners() {\n var draw = randomInt(NUM_PARTICIPANTS);\n const winners = new Set([draw]); \n while (winners.size < NUM_DRAWN) {\n do {\n draw = randomInt(NUM_PARTICIPANTS);\n } while (winners.has(draw));\n winners.add(draw);\n }\n return [...winners.values()];\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><strong>Notes</strong></p>\n<ul>\n<li><p>To reduce the cost of checking if a winner has already been selected we use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set\" rel=\"nofollow noreferrer\">Set</a>.</p>\n<p><code>Set</code> uses a <a href=\"https://en.wikipedia.org/wiki/Hash_table#:%7E:text=In%20computing%2C%20a%20hash%20table,desired%20value%20can%20be%20found.\" rel=\"nofollow noreferrer\">hash table</a> when inserting <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/add\" rel=\"nofollow noreferrer\">Set.add</a> and searching <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/has\" rel=\"nofollow noreferrer\">Set.has</a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/get\" rel=\"nofollow noreferrer\">Set.get</a>. This reduces the seach complexity to <span class=\"math-container\">\\$O(1)\\$</span> rather than <span class=\"math-container\">\\$O(n)\\$</span> for searches like <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find\" rel=\"nofollow noreferrer\">Array.find</a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex\" rel=\"nofollow noreferrer\">Array.findIndex</a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes\" rel=\"nofollow noreferrer\">Array.includes</a> etc...</p>\n</li>\n<li><p><a href=\"https://en.wikipedia.org/wiki/Halting_problem\" rel=\"nofollow noreferrer\">Halting problem</a> Unfortunately whether this algorithm will finish is <em>"undecidable"</em> <sup>[*]</sup>. That is, we can not know in advance if the inner loop will exit (assuming <code>Math.random</code> is truly random or is <em>"undecidable"</em> ).</p>\n<p>Care must be taken to ensure you only use this method when selecting A of B (where A is draws B is participants) such that A < B and A / B is small as the complexity is as bad as it can get <span class=\"math-container\">\\$O(2^{2^n})\\$</span> where n represents A (closer to <span class=\"math-container\">\\$1 / (B / A)\\$</span>) and the second 2 represents B. Luckily for most real world uses, <span class=\"math-container\">\\$2^{2^n}\\$</span> is very close to <span class=\"math-container\">\\$n\\$</span> and not worth the concern.</p>\n</li>\n</ul>\n<p><sub> <strong>[*]</strong> Close to <em>"undecidable"</em> as <code>Math.random()</code>'s full sequence is knowable, just not practically accessible</sub></p>\n<p>For a given number of winners the algorithms performance increases as the number of participants increases. On average the results of the snippet bellow, 9 of 1 million, requires less work than the snippet above, 9 of 30.</p>\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 NUM_PARTICIPANTS = 1e6;\nconst NUM_DRAWN = 9;\nconst randomInt = range => Math.floor(Math.random() * range);\nconst results = createWinners(); \nconsole.log(`Draw ${NUM_DRAWN} from ${NUM_PARTICIPANTS}`);\nconsole.log(`Grand prize: ${results[0]}`);\nconsole.log(`Second prize: ${results.slice(1,3).sort((a, b) => a - b).join(\" \")}`);\nconsole.log(`Other winners:\\n ${results.slice(3).sort((a, b) => a - b).join(\"\\n \")}`);\n\nfunction createWinners() {\n var draw = randomInt(NUM_PARTICIPANTS);\n const winners = new Set([draw]); \n while (winners.size < NUM_DRAWN) {\n do {\n draw = randomInt(NUM_PARTICIPANTS);\n } while (winners.has(draw));\n winners.add(draw);\n }\n return [...winners.values()];\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-08T13:04:38.030",
"Id": "495918",
"Score": "0",
"body": "hm, I have read most of your answer, not all, but one thing: creating an array of 1,000,000 is cheap. It is O(n), and is considered \"not a big deal\". For your method, if it is 1 million and we draw out 6 or 30, then it is ok... but for situation such as, when the company or boss decided, \"ok, 500,000 people shall still get something, like 1 coin\". Well, then, your algorithm could be running again and again, often finding numbers that are already generated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-08T15:36:39.423",
"Id": "495937",
"Score": "0",
"body": "@deeper-understanding O(n) does not mean cheap. Big O represents complexity as n approaches infinity. Cheap (efficiency) is a comparison between available and required resources for which big O gives no insight. The method you use will depend on requirements of the function. If you need 500K of 1000K then you can use a partial Fisher-Yates shuffle. That is create the full array (1000K) and shuffle (as per Fisher-Yates) to the 500,000th item (no need to continue past draws required) returning the 500K as the winners"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T14:37:18.473",
"Id": "496183",
"Score": "0",
"body": "You said \"O(n) does not mean cheap. Big O represents complexity as n approaches infinity\" Do you even know what you are talking about? Do you understand what O(n) is. It is true that if the requirement is to draw 10 numbers from 1,000,000 numbers, maybe we don't have to go O(1,000,000) or 1,000,000 steps. But as soon as the boss or manager said, let's draw 500,000 out of 1,000,000 then the \"try and see already picked\" method is not good any more. We don't want to write programs that works well \"draw 3 out of 100 and it works well and now draw 50 out of 100 and it doesn't work well\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T14:38:04.630",
"Id": "496184",
"Score": "0",
"body": "O(n) is one of the cheapest solution already. If we could go O(1) or O(log n) of course it is even better, but O(n) is considered to be usually a viable solution"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T16:06:11.497",
"Id": "496190",
"Score": "0",
"body": "@deeper-understanding Big O is written as a limit. Specifically in CS it represents an asymptotic analysis of a function, There is only one asymptote (n = Infinity). This is why O(n) is equivalent to O(n * m) m = is ANY value > 0.and insignificant as n approaches infinity. Two functions, one needing n * m steps (where m=1) and another n * m (where m = 42 trillion zillion bigillion) have exactly the same complexity O(n). The SAME complexity, one done in a blink of an eye and the other is done some time around the heat death of the universe. Again!! O(n) does not mean cheap"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T18:33:38.170",
"Id": "496201",
"Score": "0",
"body": "if you are using some kind of `has_drawn()` look up table method, and if the manager said, ok, for 100,000 people, let's draw 90,000 people and some get prizes and some get coupons, then your method of \"trial and error\" is much more than O(n). It might be even O(n²) which is already a big no in CS. So I wonder why you say O(n) is \"so expensive\" and then present a O(n²) solution"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T04:08:10.167",
"Id": "496269",
"Score": "0",
"body": "@deeper-understanding MUCH worse than \\$O(n^2)\\$ it has the worst complexity possible \\$O(2^{2^n})\\$. Performance and complexity are not the same thing. as in this case the most complex function can easily out perform the least complex function when the ratio (winner over entrants) is small (read answer). At 50% (500K of 1000K) it still requires less iteration. There is no need to go over 50% as you can change the winning condition to not being drawn"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-12T13:46:11.127",
"Id": "496333",
"Score": "0",
"body": "so what if the company decides 10 winners, 10% of customers get 5 coupons, 20% get 2 coupons, and 35% get 1 coupon? Actually in most engineering tasks I have done, we were satisfied with n, and won't be obsessed about 0.5n, at the risk of complexity and possible rewrite"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T03:35:20.580",
"Id": "251451",
"ParentId": "251420",
"Score": "2"
}
},
{
"body": "<p>To pick <code>m</code> from a collection of size <code>n</code>, there are at least a couple of approaches:</p>\n<ul>\n<li><p>Randomly shuffle an array of numbers (<code>O(n)</code>), then pick the top few (<code>O(m)</code>), resulting in an overall complexity of <code>O(n + m)</code>. This is what you're doing currently, though it requires creating an array.</p>\n</li>\n<li><p>Repeatedly pick a random number from 0 to <code>n</code>. If a duplicate number is picked, pick again. Repeat <code>m</code> times. This has an overall complexity of around <code>O(m * C)</code>, where C is the average number of picks before finding a non-duplicate. It'll range from close to 1 (when <code>n</code> is significantly larger than <code>m</code>) to infinity (when <code>n</code> is equal to <code>m</code>).</p>\n</li>\n</ul>\n<p>If <code>m</code> is close to <code>n</code>, the first approach, that you're doing currently, is quickest, because the other approach results in lots of collisions. If <code>m</code> is significantly smaller than <code>n</code>, the second approach is quickest, because the collision chance C is low. So, where's the break-even point? It'll depend on the engine running the code, but we can do some basic performance tests. I'll use <a href=\"https://codereview.stackexchange.com/a/251451\">Blindman67's code</a> since it's pretty much exactly what I had in mind.</p>\n<p>The below tests aren't 100% reliable, but they'll give you an OK idea of the time required:</p>\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>// Array sort method:\n\n// Wait for the iframe to load completely\nsetTimeout(() => {\n \n const NUM_PARTICIPANTS = 1e7;\n const NUM_DRAWN = 3e6;\n\n const t0 = performance.now();\n // Make the array 0-indexed rather than 1-indexed\n // to avoid unnecessary addition for every element\n const arr = Array.from({ length: NUM_PARTICIPANTS }, (_, i) => i);\n const lowerLimit = NUM_PARTICIPANTS - NUM_DRAWN;\n for (let i = arr.length - 1; i >= lowerLimit; --i) {\n const j = Math.floor(Math.random() * (i + 1));\n // Use a temp variable instead of the destructuring trick, it's probably a bit faster:\n const temp = arr[i];\n arr[i] = arr[j];\n arr[j] = temp;\n }\n // Then slice the array and calculate the results\n console.log('Time taken:', performance.now() - t0);\n}, 1000);</code></pre>\r\n</div>\r\n</div>\r\n</p>\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>// Picking random numbers until enough non-duplicates are found:\n\n// Wait for the iframe to load completely\nsetTimeout(() => {\n \n const NUM_PARTICIPANTS = 1e7;\n const NUM_DRAWN = 3e6;\n\n const randomInt = range => Math.floor(Math.random() * range);\n const results = createWinners(); \n\n function createWinners() {\n const t0 = performance.now();\n var draw = randomInt(NUM_PARTICIPANTS);\n const winners = new Set([draw]); \n while (winners.size < NUM_DRAWN) {\n do {\n draw = randomInt(NUM_PARTICIPANTS);\n } while (winners.has(draw));\n winners.add(draw);\n }\n // Then slice the array and calculate the results\n console.log('Time taken:', performance.now() - t0);\n return [...winners.values()];\n }\n}, 1000);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>I tried a few different combinations of <code>NUM_PARTICIPANTS</code> and <code>NUM_DRAWN</code> numbers, and the ratio used above, 10 to 3, seems to be pretty close to the break-even point, when the numbers are large, at least on V8. (If the code runs in a different environment, the ideal ratio to use will likely be different.) At that point, both methods look to take a pretty similar amount of runtime. If you don't have a large number of participants, either approach will work just fine, since it won't take any noticeable amount of time to run the script regardless. But if you have a large number, check the ratio of participants to winners, then choose the appropriate method depending on the ratio.</p>\n<pre><code>const createWinners = (numParticipants, numWinners) => (\n numWinners / numParticipants < 0.3\n ? createWinnersWithSetPicking(numParticipants, numWinners)\n : createWinnersWithArraySort(numParticipants, numWinners)\n);\n</code></pre>\n<p>If you change the code, you might want to run a performance test again to see what works better, and you might want to adjust the magic ratio. Take into consideration the environment the code runs (or is most likely to run) on too - Node? Chrome? Firefox? Safari?</p>\n<p>That said, if your numbers are large enough that performance is an issue, this should almost certainly be done on the server (in Node), not on the client, so as not to be unrunnable on low-end devices.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-08T13:09:32.217",
"Id": "495921",
"Score": "0",
"body": "I can read your long note more, but at this point: my code is not any different from Fisher-Yates to shuffle the whole array and take what is needed. But jus that \"when the other numbers are not needed, why keep on shuffling them\"? My code is exactly this: place 1,000,000 cards out in pile 1, now take 6 cards out randomly from this pile 1, and place it in pile 2. And these are the winners. This procedure is perfect, evenly distributed. And I am doing exactly that, but just that I don't shrink pile 1, but just move the card some where, and that's it. My pile 2 is at the tail of the array."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-21T14:00:47.283",
"Id": "497414",
"Score": "0",
"body": "to put it simply, once Fisher-Yates has decided a card at the tail, it is never touched. So we could shuffle 1,000,000 cards, or we could shuffle 9, and the last 9 is never touched anyways, so why shuffle more than 9?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-21T19:24:18.457",
"Id": "497454",
"Score": "0",
"body": "Oops, you're right. What was throwing me was frequently seeing contiguous sequences like `22 23 24 25`, but that's not a result of a failure to randomly select, but a byproduct of having a large ratio of picks from available options, in combination with the sorting afterwards."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T03:58:38.843",
"Id": "251452",
"ParentId": "251420",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T12:46:49.770",
"Id": "251420",
"Score": "6",
"Tags": [
"javascript",
"shuffle"
],
"Title": "Out of N number of participants, draw out M winners"
}
|
251420
|
<p>I decided to modify <a href="https://codereview.stackexchange.com/questions/250511/double-ended-queue-for-embedded-systems">my last code</a> about a queue intended for embedded systems and make it accept different data types for multiple purposes.</p>
<p>It is a double-ended queue, the user can store and get elements to and from each end of the queue .
The queue uses a static allocated buffer - array. The user must pass the size of the array to the queue during the initialization and the size of each element.</p>
<p>My intention is to use the same piece of code for making queue that can hold bytes and structs too (not in the same queue!).</p>
<p>So here's the header file.</p>
<pre><code>#ifndef QUEUE_H
#define QUEUE_H
#include <inttypes.h>
#include <stdbool.h>
struct queue
{
void * data_buf;
void * front;
void * back;
const uint16_t elements_num_max;
const uint16_t elements_size;
uint16_t elements;
};
void queue_init(struct queue * queue);
bool queue_is_full(struct queue * queue);
bool queue_is_empty(struct queue * queue);
bool queue_add_front(struct queue * queue, void * data);
bool queue_add_back(struct queue * queue, void * data);
bool queue_get_front(struct queue * queue, void * data);
bool queue_get_back(struct queue * queue, void * data);
#endif
</code></pre>
<p>and the source code.</p>
<pre><code>/**
* \file queue.c
*
* \brief A double-ended queue (deque). Elements can be added or removed from
* either the front or the back side.
* \warning The current implementation is NOT interrupt safe. Make sure interrupts
* are disabled before access the QUEUE otherwise the program might yield
* unexpected results.
*/
#include "queue.h"
#define INCREASE_INDEX(queue, ptr) queue->ptr = (queue->ptr + queue->elements_size) >= (queue->data_buf + queue->elements_num_max * queue->elements_size) ? queue->data_buf : (queue->ptr + queue->elements_size)
#define DECREASE_INDEX(queue, ptr) queue->ptr = (queue->ptr - queue->elements_size) < queue->data_buf ? (queue->data_buf + (queue->elements_num_max - 1) * queue->elements_size) : (queue->ptr - queue->elements_size)
/**
* Initializes - resets the queue.
*/
void queue_init(struct queue * queue)
{
memset((uint8_t *)queue->data_buf, 0, queue->elements_num_max * queue->elements_size);
queue->back = queue->data_buf;
queue->front = queue->data_buf;
queue->elements = 0;
}
/**
* Checks if queue is full.
*
* \returns true if queue is full.
*/
bool queue_is_full(struct queue * queue)
{
return (queue->elements == queue->elements_num_max);
}
/**
* Checks if queue is empty
*
* \returns true if queue is empty.
*/
bool queue_is_empty(struct queue * queue)
{
return (queue->elements == 0);
}
/**
* Adds one element to the front of the queue.
*
* \returns false if the queue is full.
*/
bool queue_add_front(struct queue * queue,
void * data)
{
if (queue_is_full(queue))
{
return false;
}
if (queue_is_empty(queue) == false)
{
INCREASE_INDEX(queue, front);
}
memcpy((uint8_t *)queue->front, (uint8_t *)data, queue->elements_size);
queue->elements++;
return true;
}
/**
* Adds one element to the back of the queue.
*
* \returns false if the queue is full.
*/
bool queue_add_back(struct queue * queue,
void * data)
{
if (queue_is_full(queue))
{
return false;
}
if (queue_is_empty(queue) == false)
{
DECREASE_INDEX(queue, back);
}
memcpy((uint8_t *)queue->back, (uint8_t *)data, queue->elements_size);
queue->elements++;
return true;
}
/**
* Reads one element from the front of the queue.
*
* \returns false if the queue is empty.
*/
bool queue_get_front(struct queue * queue,
void * data)
{
if (queue_is_empty(queue))
{
return false;
}
memcpy((uint8_t *)data, (uint8_t *)queue->front, queue->elements_size);
if (queue->front != queue->back)
{
DECREASE_INDEX(queue, front);
}
queue->elements--;
return true;
}
/**
* Reads one element from the back of the queue.
*
* \returns false if the queue is empty.
*/
bool queue_get_back(struct queue * queue,
void * data)
{
if (queue_is_empty(queue))
{
return false;
}
memcpy((uint8_t *)data, (uint8_t *)queue->back, queue->elements_size);
if (queue->front != queue->back)
{
INCREASE_INDEX(queue, back);
}
queue->elements--;
return true;
}
</code></pre>
<p>How to use it:</p>
<pre><code>#define ELEMENTS 100
MyStruct_t struct_buff[ELEMENTS];
struct queue my_queue =
{
.data_buf = struct_buff,
.elements_num_max = ELEMENTS.
.elements_size = sizeof(MyStruct_t),
};
queue_init(&my_queue);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T14:05:14.313",
"Id": "494949",
"Score": "2",
"body": "_The current implementation is NOT interrupt safe_ - why not? Is there some global state I'm not seeing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T16:59:25.613",
"Id": "494978",
"Score": "0",
"body": "@Reinderien The code I posted is based on an old implementation I posted before. You can see the detailed explanation here https://codereview.stackexchange.com/a/245318/155837 about why it is not interrupt safe."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T17:33:15.190",
"Id": "494981",
"Score": "1",
"body": "@Reinderien The entire queue state is kind of global. Consider the mainline code and ISR try to operate on the same queue."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T02:16:18.723",
"Id": "495008",
"Score": "0",
"body": "I'm using the latest release of Visual Studio 2019, not the best C compiler in the world. To get the 2 macros in queue.c to compile I had to cast all of the `queue->front`, `queue->back` and `queue->data_buf` pointers to `unsigned`. Apparently the VC compiler doesn't think void pointers are complete objects."
}
] |
[
{
"body": "<p>In <code>queue_init</code>, there's no need to initialize all elements to zero. On the same note, the queue is being partially initialized outside <code>queue_init()</code> and partially within it. You might consider passing buffer, size and maximum elements as parameters to the function or getting rid of it altogether</p>\n<p>You can shorten <code>queue_is_full(queue)==false</code> to <code>!queue_is_full(queue)</code> and <code>return (queue->elements==0);</code> to <code>return !(queue->elements);</code></p>\n<p>Also, you could consider renaming the macro to something like <code>INCREASE_INDEX_CYCLICALLY</code> to indicate the two end of array are connected</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T07:24:59.310",
"Id": "251456",
"ParentId": "251422",
"Score": "1"
}
},
{
"body": "<p>Couple of bugs:</p>\n<ul>\n<li>queue.c doesn't <code>#include <string.h></code>.</li>\n<li>Casting the pointer parameters passed to <code>memset</code> and <code>memcpy</code> isn't necessary, but can hide bugs.</li>\n<li>Your macros do non-standard pointer arithmetic on void pointers. Don't do that, there's no need to use such pointless non-standard extensions and they are very unlikey to be supported by embedded systems compilers. Use <code>uint8_t*</code> instead.</li>\n</ul>\n<p>Overall, make sure you are compiling with a standard C compiler and not a non-standard C++ compiler.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T07:40:44.590",
"Id": "251588",
"ParentId": "251422",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "251588",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T12:58:32.067",
"Id": "251422",
"Score": "1",
"Tags": [
"c",
"queue",
"embedded"
],
"Title": "Double-ended queue for Embedded Systems with different data size"
}
|
251422
|
<p>I have written a code to solve the N-Queen problem for a 14 by 14 chessboard. There are preplaced queens (see below for the sample input and output). The lines of sample input (after the 3) represent the positions of the preplaced queens. For example, "1 1 2 9 3 6 4 10" refers to the 4 preplaced queens are at (1st row 1st column), (2nd row, 9th column), (3rd row 6th column), (4th row, 10th column).</p>
<p>I am hoping that it will return me the number of solutions. But when I tried running the code, I got time limit exceeded, even for the sample input.</p>
<p>I will try the list of tuples method, but let me know if there is a more efficient implementation. Thanks in advance</p>
<p>[![Question screenshot][1]][1]</p>
<pre><code>Sample Input
3
1 1 2 9 3 6 4 10
1 9 12 8 8 5 2 7
2 10 10 3
Sample Output
39
32
2414
</code></pre>
<pre><code>import sys
def nQueens(n, pre_placed_rows, pre_placed_cols, N, state=[], col=1):
if col > n: return [state]
res = []
for i in range(1, n+1):
if invalid(state, i): continue
for sol in nQueens(n, pre_placed_rows, pre_placed_cols, N, state + [i], col+1):
if N == 2: # 2 preplaced queens
if sol[pre_placed_cols[0]-1] == pre_placed_rows[0] and sol[pre_placed_cols[1]-1] == pre_placed_rows[1]:
res.append(sol) #[sol]
elif N == 3: # 3 preplaced queens
if sol[pre_placed_cols[0]-1] == pre_placed_rows[0] and sol[pre_placed_cols[1]-1] == pre_placed_rows[1] and sol[pre_placed_cols[2]-1] == pre_placed_rows[2]:
res.append(sol)
else: # 4 preplaced queens
if sol[pre_placed_cols[0]-1] == pre_placed_rows[0] and sol[pre_placed_cols[1]-1] == pre_placed_rows[1] and sol[pre_placed_cols[2]-1] == pre_placed_rows[2] and sol[pre_placed_cols[3]-1] == pre_placed_rows[3]:
res.append(sol)
return res
def invalid(s, r2): # is it safe to put the queen
if not s:
return False
if r2 in s:
return True
c2 = len(s) + 1
return any(abs(c1-c2) == abs(r1-r2) for c1, r1 in enumerate(s, 1))
num_case = int(sys.stdin.readline())
for _ in range(num_case):
s = sys.stdin.readline().split()
N = len(s) // 2
pre_placed_rows = []
pre_placed_cols = []
n = 14
for i in range(N):
pre_placed_rows.append(int(s[2*i]))
pre_placed_cols.append(int(s[2*i+1]))
print(len(nQueens(n, pre_placed_rows, pre_placed_cols, N)))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T14:56:40.547",
"Id": "494956",
"Score": "5",
"body": "Welcome to the Code Review site. Please add a link to the programming challenge."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T13:34:08.843",
"Id": "495056",
"Score": "1",
"body": "Hi pacman, I do not have the link, but I have attached the screenshot. The time allowed is 6000ms, 256MB memory. My current algo has taken more than a minute, but less than 10MB memory"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T18:34:11.323",
"Id": "495112",
"Score": "0",
"body": "How much more than a minute did it take? And did it produce the correct results?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T05:06:40.567",
"Id": "495170",
"Score": "0",
"body": "Hi superb, it is taking 20minutes for the sample input. It produced the correct results"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T00:26:27.863",
"Id": "495290",
"Score": "1",
"body": "It looks like `nQueens()` constructs all possible solutions but drops those that don't have a queen in the pre-placed squares. That's a lot of extra work. `state` should start with the pre-placed queens already filed in and `nQueens()` should try to fill in the rest."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T02:28:39.813",
"Id": "495478",
"Score": "0",
"body": "I tried. Not sure what I did wrong.\n\ndef nQueens(n, state=[], col=1):\n if col > n: return [state]\n res = []\n for i in range(1, n+1):\n if invalid(state, i): continue\n for sol in nQueens(n, state + [i], col+1): res += [sol]\n return res\n\ndef invalid(s, r2):\n if not s: return False\n if r2 in s: return True\n c2 = len(s) + 1\n return any(abs(c1-c2) == abs(r1-r2) for c1, r1 in enumerate(s, 1))\nstate = [1]\nprint(nQueens(14,state,col=1))"
}
] |
[
{
"body": "<p>Here's my take on it.</p>\n<p>Translate columns 1-14 to 0-13 for internal use and translate back on output.</p>\n<p><code>state</code> keeps track of where the queens are. <code>state[0]</code> is the row of the queen in column 0, etc. A None indicates the column is empty.</p>\n<p><code>nQueens()</code> searches <code>state</code> for an empty column and then checks each row in that column for a valid move. If a move is valid, <code>state</code> is updated and <code>nQueens()</code> is called with the new state. After the recursive call is made, revert the change in state. That avoids the need to make a copy of the state.</p>\n<p>The code <code>yield</code>s the solutions rather than keeping a list.</p>\n<p><code>printboard()</code> is just to help with visualizing what is going on. Uncomment some of the calls if you're curious...but only do one of the smaller test cases because there is a lot of output.</p>\n<p>I think your <code>imvalid()</code> might be off?</p>\n<p>Put the driver code in <code>main()</code>.</p>\n<pre><code>SIZE = 14\n\n\ndef nQueens(state):\n #printboard(state)\n \n # find an empty column (row==None)\n for col, row in enumerate(state):\n if row is None:\n break\n \n # all columns filled. so it is a solution\n else:\n yield state\n \n for row in range(SIZE):\n # check if row taken\n if not valid(state, row, col):\n continue\n\n # make the move\n #print(f"col[{col+1}] = {row+1}")\n state[col] = row\n yield from nQueens(state)\n \n # revert the move to continue the search\n state[col] = None\n \n\ndef valid(state, row, col):\n # is there a queen in this row\n if row in state: \n return False\n\n # is there a queen on a diagonal\n for c,r in enumerate(state):\n if r is None:\n continue\n \n if col-row == c-r or col+row == c+r:\n return False\n \n return True\n\n\ndef printboard(state):\n print(' '+' '.join(str(i%10) for i in range(1, SIZE+1)))\n for r in range(SIZE):\n print((r+1)%10, end=' ')\n for c in range(SIZE):\n if state[c] == r:\n print('Q', end=' ')\n else:\n print('.', end=' ')\n print()\n\n \ndef main(data):\n num_cases = int(data.readline())\n\n for case_num in range(num_cases):\n # initialize state to all Nones.\n # None means the corresponding column is empty\n state = [None]*SIZE\n\n # fill in the preset queens\n preset = data.readline().split()\n while preset:\n row = int(preset.pop(0)) - 1\n col = int(preset.pop(0)) - 1\n state[col] = row\n\n #printboard(state)\n\n # count the number of solutions\n for n,sol in enumerate(nQueens(state)):\n #printboard(sol)\n pass\n\n print(n+1)\n \n</code></pre>\n<p>Test it like so:</p>\n<pre><code>test = """\n3\n1 1 2 9 3 6 4 10\n1 9 12 8 8 5 2 7\n2 10 10 3\n""".strip()\n\nmain(io.StringIO(test))\n</code></pre>\n<p>Or call it like:</p>\n<pre><code>main(sys.stdin)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T06:18:59.047",
"Id": "496158",
"Score": "0",
"body": "Thanks RootTwo. Can I know which line will iterate all of the columns?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-11T20:51:39.617",
"Id": "496220",
"Score": "0",
"body": "The columns are iterated using recursion. `state` is a list of the position (row) of the queen in each column. That is, `state[0]` is the row of the queen in column 0, `state[1]` is the row of the queen in column 1, etc. The `for col, row in enumerate(state):` loop searches `state` to find an empty column. Just before each recursive call to `nQueens()`, that empty column of `state` is filled in. When `state` is full, that means every column has a queen. That should happen at the 10th, 11th, or 12th level of recursion depending on the number of preset queens."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-07T03:19:00.260",
"Id": "251743",
"ParentId": "251424",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T14:11:27.927",
"Id": "251424",
"Score": "5",
"Tags": [
"python",
"programming-challenge",
"n-queens"
],
"Title": "Finding number of solutions nqueens 14 by 14 chessboard"
}
|
251424
|
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/251336/231235">An element_wise_add Function For Boost.MultiArray in C++</a> and <a href="https://codereview.stackexchange.com/q/251379/231235">An Add/Minus Operator For Boost.MultiArray in C++</a>. Besides the basic element-wise add / minus operations, I am trying to implement an <code>element_wise_multiplication</code> function and an <code>element_wise_division</code> function here for Boost.MultiArray. The new concept <code>is_multiplicable</code> and <code>is_divisible</code> used here are as below.</p>
<pre><code>template<typename T>
concept is_multiplicable = requires(T x)
{
x * x;
};
template<typename T>
concept is_divisible = requires(T x)
{
x / x;
};
</code></pre>
<p>The another used concept <code>is_multi_array</code>:</p>
<pre><code>template<typename T>
concept is_multi_array = requires(T x)
{
x.num_dimensions();
x.shape();
boost::multi_array(x);
};
</code></pre>
<p>The implementation of <code>element_wise_multiplication</code> function and <code>element_wise_division</code> function:</p>
<pre><code>// Multiplication
template<class T1, class T2> requires (is_multiplicable<T1> && is_multiplicable<T2>)
auto element_wise_multiplication(const T1& input1, const T2& input2)
{
return input1 * input2;
}
template<class T1, class T2> requires (is_multi_array<T1> && is_multi_array<T2>)
auto element_wise_multiplication(const T1& input1, const T2& input2)
{
if (input1.num_dimensions() != input2.num_dimensions()) // Dimensions are different, unable to perform element-wise add operation
{
throw std::logic_error("Array dimensions are different");
}
if (*input1.shape() != *input2.shape()) // Shapes are different, unable to perform element-wise add operation
{
throw std::logic_error("Array shapes are different");
}
boost::multi_array output(input1); // drawback to be improved: avoiding copying whole input1 array into output, but with appropriate memory allocation
for (decltype(+input1.shape()[0]) i = 0; i < input1.shape()[0]; i++)
{
output[i] = element_wise_multiplication(input1[i], input2[i]);
}
return output;
}
// Division
template<class T1, class T2> requires (is_divisible<T1> && is_divisible<T2>)
auto element_wise_division(const T1& input1, const T2& input2)
{
if (input2 == 0)
{
throw std::logic_error("Divide by zero exception"); // Handle the case of dividing by zero exception
}
return input1 / input2;
}
template<class T1, class T2> requires (is_multi_array<T1> && is_multi_array<T2>)
auto element_wise_division(const T1& input1, const T2& input2)
{
if (input1.num_dimensions() != input2.num_dimensions()) // Dimensions are different, unable to perform element-wise add operation
{
throw std::logic_error("Array dimensions are different");
}
if (*input1.shape() != *input2.shape()) // Shapes are different, unable to perform element-wise add operation
{
throw std::logic_error("Array shapes are different");
}
boost::multi_array output(input1); // drawback to be improved: avoiding copying whole input1 array into output, but with appropriate memory allocation
for (decltype(+input1.shape()[0]) i = 0; i < input1.shape()[0]; i++)
{
output[i] = element_wise_division(input1[i], input2[i]);
}
return output;
}
</code></pre>
<p>The test for the <code>element_wise_multiplication</code> function and the <code>element_wise_division</code> function:</p>
<pre><code>int main()
{
// Create a 3D array that is 3 x 4 x 2
typedef boost::multi_array<double, 3> array_type;
typedef array_type::index index;
array_type A(boost::extents[3][4][2]);
// Assign values to the elements
int values = 1;
for (index i = 0; i != 3; ++i)
for (index j = 0; j != 4; ++j)
for (index k = 0; k != 2; ++k)
A[i][j][k] = values++;
for (index i = 0; i != 3; ++i)
for (index j = 0; j != 4; ++j)
for (index k = 0; k != 2; ++k)
std::cout << A[i][j][k] << std::endl;
auto test_result = A;
for (size_t i = 0; i < 3; i++)
{
test_result = element_wise_multiplication(test_result, A);
}
test_result = element_wise_division(test_result, A);
for (index i = 0; i != 3; ++i)
for (index j = 0; j != 4; ++j)
for (index k = 0; k != 2; ++k)
std::cout << test_result[i][j][k] << std::endl;
return 0;
}
</code></pre>
<p>All suggestions are welcome.</p>
<ul>
<li><p>Which question it is a follow-up to?</p>
<p><a href="https://codereview.stackexchange.com/q/251336/231235">An element_wise_add Function For Boost.MultiArray in C++</a> and
<a href="https://codereview.stackexchange.com/q/251379/231235">An Add/Minus Operator For Boost.MultiArray in C++</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p>The previous questions are the implementation of add / minus operations for Boost.MultiArray and I am trying to implement an <code>element_wise_multiplication</code> function and <code>element_wise_division</code> function here.</p>
</li>
<li><p>Why a new review is being asked for?</p>
<p>There are two new concepts <code>is_multiplicable</code> and <code>is_divisible</code> have been added here. I am not sure is this a good idea although it seems to work fine with the test example mentioned above. On the other hand, the reason for not overloading the operator* and operator/ directly is that the symbol <code>*</code> and <code>/</code> are hard to indicate element-wise multiplication and division clearly. There are some more complex high dimensional matrix multiplication calculations maybe like <a href="https://math.stackexchange.com/q/63074/819308">this one</a>. If there is any further suggestion about this idea, please let me know.</p>
</li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T15:24:37.583",
"Id": "251427",
"Score": "2",
"Tags": [
"c++",
"recursion",
"boost",
"c++20"
],
"Title": "An element_wise_multiplication and an element_wise_division Function For Boost.MultiArray in C++"
}
|
251427
|
<p>I'm trying to solve this problem <a href="https://www.codechef.com/problems/SEGTREES" rel="nofollow noreferrer">here</a>. The question is all about finding the shortest sub array inside an array that contains all the element from 1 to K.</p>
<p><strong>Input</strong>:</p>
<ul>
<li>The first line contains three space-separated integers N, K and Q. N is the length of actual Array, we need to find the shortest sub-array that contains all the element from 1 to K and Q is the number of queries.</li>
<li>The second line contains N space-separated integers A1,A2,…,AN (the content for actual array).</li>
</ul>
<p>There are two types of queries:</p>
<ul>
<li>Type 1 : 1 u v -> Update the value at position u to v.</li>
<li>Type 2 : 2 -> Find the length of the shortest contiguous subarray which contain all the integers from 1 to K.</li>
</ul>
<p>I wrote this code here, which I believe is efficient enough to be completed before desired time.</p>
<pre><code>/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef {
private static int findShortestContiguousSubArray(int[] array, int k) {
Map<Integer, Integer> mapElementAndCount = new HashMap<>();
for (int i = 1; i <= k; i++) {
mapElementAndCount.put(i, 1);
}
int count = k;
int cursor = 0;
int start = 0;
int minLength = Integer.MAX_VALUE;
while (cursor < array.length) {
if (mapElementAndCount.containsKey(array[cursor])) {
mapElementAndCount.put(array[cursor], mapElementAndCount.get(array[cursor]) - 1);
if(mapElementAndCount.get(array[cursor]) == 0) {
count--;
}
}
while (start < array.length && count == 0) {
if (minLength > cursor - start + 1) {
minLength = cursor - start + 1;
}
if(mapElementAndCount.keySet().contains(array[start])) {
mapElementAndCount.put(array[start], mapElementAndCount.get(array[start]) + 1);
if(mapElementAndCount.get(array[start]) == 1) {
count++;
}
}
start++;
}
cursor++;
}
return minLength == Integer.MAX_VALUE ? -1 : minLength;
}
public static void main (String[] args) throws java.lang.Exception {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String firstLine = input.readLine();
String[] instructions = firstLine.trim().split(" ");
int n = Integer.parseInt(instructions[0]);
int k = Integer.parseInt(instructions[1]);
int q = Integer.parseInt(instructions[2]);
String[] stringArray = input.readLine().trim().split(" ");
int[] array = new int[stringArray.length];
for (int i = 0; i < n; i++) {
array[i] = Integer.parseInt(stringArray[i]);
}
while (q > 0) {
Integer.parseInt(instructions[0]);
String query = input.readLine();
instructions = query.trim().split(" ");
if (instructions.length == 1) {
System.out.println(findShortestContiguousSubArray(array, k));
} else if (instructions.length == 3) {
int targetIndex = Integer.parseInt(instructions[1]) - 1;
if (targetIndex >= array.length || targetIndex < 0) {
q--;
continue;
}
array[targetIndex] = Integer.parseInt(instructions[2]);
System.out.println();
}
q--;
}
}
}
</code></pre>
<p><strong>Explanation</strong>:</p>
<p>I've created a map where I stored count 1 for each element in the range 1 to K (including K). After that I'm traversing the actual array and whenever I encounter an element which is there in the map, I reduce the value by 1 and reducing the count variable by 1 (I mean if the count of an element has become zero, I need to find K-1 rest elements in the range). And when the count variable becomes 0, which means I've found a sub array that contains all the element from 1 to K, then I compare it to the last encountered sub-array size (for the first time, I set it to Integer.MAX_VALUE) and I modify the size if I encounter small sub-array.</p>
<p><strong>PROBLEM</strong>:</p>
<p>After submitting the code, it's showing time limit exceeded.</p>
<p>If this algorithm is fine, what is the problem in the code?</p>
<p>If this algorithm is not the best way to solve this problem, what else could be done (A brief demonstration of the algorithm would be sufficient)?</p>
<p>I'm asking question on this platform for the first time, so may be I'm not doing this in the best possible way. Please suggest the edit, I'll fix it.</p>
<p>Thank you in advance!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T16:08:20.177",
"Id": "495081",
"Score": "1",
"body": "You are using a straightforward algorithm, and programming challenges are called \"challenges\" as typically you need to come up with a better approach than the straightforward one. Your `find()` algorithm is O(n²), and you're repeatedly doing that very same algorithm for every Type 2 query. There might be a better `find()` algorithm, and there might be an incremental approach, taking into account that the Type 1 queries only change a single array element, thus allowing the `find()` to re-use some partial results from previous runs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T16:36:30.837",
"Id": "495087",
"Score": "1",
"body": "You shoud, split the Python implementation into its own question, as giving an answer for Java *and* Python is a lot harder and much more code to look through."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T17:01:39.257",
"Id": "495097",
"Score": "0",
"body": "I have updated the question and removed the Python part of it. @hjpotter92"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T17:03:18.187",
"Id": "495098",
"Score": "0",
"body": "I'll think about your suggestion and it makes perfect sense to me. I think your comment deserve to be an answer. @RalfKleberhoff"
}
] |
[
{
"body": "<p>This is not a complete answer with an algorithm or an implementation solving the challenge, but a hint at where to improve the approach.</p>\n<h2>Algorithm</h2>\n<p>You are using a straightforward algorithm, and programming challenges are called "challenges" as typically you need to come up with a better approach than the straightforward one.</p>\n<p>Your <code>find()</code> algorithm is <code>O(n²)</code>, and you're repeatedly doing that very same algorithm for every Type 2 query. There might be a better <code>find()</code> algorithm in itself.</p>\n<p>And there might be an incremental approach, taking into account that the Type 1 queries only change a single array element, thus allowing the <code>find()</code> to re-use some partial results from previous runs.</p>\n<h2>Code Style</h2>\n<p>In addition, as this is Code Review, some hints on Java style (I know, programming challenges don't ask for production-quality code, but anyway...).</p>\n<pre><code> int cursor = 0;\n // ...\n while (cursor < array.length) {\n // ...\n cursor++;\n }\n</code></pre>\n<p>This is a simple loop counting from <code>0</code> up to <code>array.length</code>. That should be written as</p>\n<pre><code> for (int cursor = 0; cursor < array.length; cursor++) {\n // ...\n }\n</code></pre>\n<p>Although your version does exactly the same, by spreading the code parts that make up the loop over many lines of code, it's hard to see the "simple loop" structure. Similarly, in the <code>while (q > 0) { ... }</code> you even have multiple places where you decrement <code>q</code> (because of the <code>continue</code> statement). With a <code>for</code> loop, you'd avoid that as well.</p>\n<p>You can replace</p>\n<pre><code> if (minLength > cursor - start + 1) {\n minLength = cursor - start + 1;\n }\n</code></pre>\n<p>by</p>\n<pre><code> minLength = Math.max(minLength, cursor - start + 1);\n</code></pre>\n<p>The import staments should be changed.</p>\n<pre><code>import java.util.*;\nimport java.lang.*;\nimport java.io.*;\n</code></pre>\n<p>First of all, there's no need to import anything from the <code>java.lang</code> package, as classes from that package are always visible with their simple name (implicitly being imported).</p>\n<p>Then, I recommend not to use wildcard imports, but to import the classes you need individually.</p>\n<p>Why? Imagine, at Java 7 times you created a class <code>my.package.utils.IntStream</code> to read files of integers, and you used the wildcard import style:</p>\n<pre><code>import java.util.*;\nimport java.io.*;\nimport my.package.utils.*;\n</code></pre>\n<p>Before Java8, there was no <code>java.util.IntStream</code> interface, so your code compiled perfectly. But with the introduction of Java8, suddenly your <code>my.package.utils.IntStream</code> class collides with the <code>java.util.IntStream</code> interface, both wildcard-imported, and the compiler can't decide which one to choose if you write IntStream somewhere in your code. The introduction of a new interface into the Java library, an interface you never intended to use, suddenly breaks your code.</p>\n<p>Had you written individual imports for only the classes you really need, the <code>java.util.IntStream</code> wouldn't bother you.</p>\n<p>As a guideline for imports:</p>\n<ul>\n<li>Have your IDE manage the import statements for you.</li>\n<li>Make sure the IDE settings use individual imports, not wildcards.</li>\n<li>Import only the classes you really need.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T21:25:38.767",
"Id": "251508",
"ParentId": "251431",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "251508",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T17:24:09.923",
"Id": "251431",
"Score": "5",
"Tags": [
"java",
"programming-challenge",
"array",
"hash-map"
],
"Title": "Find the shortest sub array that contains all element from 1 to K"
}
|
251431
|
<p>I'd like to read a line from stdin, excluding the newline character. I've written the function:</p>
<pre><code>/* read in a line from stdin, NULL on failure
* does not include trailing newline
*/
char*
readStdinLine() {
char* buffer;
size_t bufsize = 32;
size_t characters;
buffer = (char *) malloc(bufsize * sizeof(char));
if (buffer == NULL)
return NULL;
characters = getline(&buffer, &bufsize, stdin);
buffer[--characters] = '\0';
char* text = (char *) malloc(characters);
for (int i = 0; i < characters + 1; i++) {
text[i] = buffer[i];
}
free(buffer);
return text;
}
</code></pre>
<p>This seems inneficient, I'm essentially reading in the line twice, once in getline and once to remove the trailing newline. That doesn't seem like the most memory-efficient algorithm, and I would like to remove the newline without copying, if that is at all possible.</p>
<p>I'm very new to C (have used C++, Java, etc, but never a systems language without objects) so I would appreciate learning all the code style things I've done wrong as well. Thanks!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T18:12:48.120",
"Id": "494983",
"Score": "1",
"body": "I don't see the need for this. `getline()` does all this automatically. If you want a version that removed the newline character then you simply remove it (if it exists (Note last line in a file may not have a new line))."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T06:43:02.750",
"Id": "495018",
"Score": "1",
"body": "Do note that `getline` isn't a standard C function and you should probably tag the question accordingly."
}
] |
[
{
"body": "<p>This function can be written like this:</p>\n<pre><code>char* readStdinLine()\n{\n char* buffer = NULL;\n size_t bufsize = 0;\n ssize_t characters = getline(&buffer, &bufsize, stdin);\n if (characters == -1) {\n free(buffer);\n buffer = NULL;\n }\n else if (buffer[characters-1] == '\\n') {\n buffer[characters-1] = '\\0';\n }\n return buffer;\n}\n</code></pre>\n<p>The <code>getline()</code> function does everything you need. You simply need to check for errors and remove the new line character)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T18:17:57.050",
"Id": "251434",
"ParentId": "251432",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "251434",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T17:25:51.957",
"Id": "251432",
"Score": "3",
"Tags": [
"performance",
"c"
],
"Title": "stdin getline wrapper"
}
|
251432
|
<p>I have a <code>TodoItem</code> component that looks like this:</p>
<pre><code>type Todo = {
id: string;
text: string;
isCompleted: boolean;
createdAt: string;
};
type TodoProps = {
todo: Todo;
removeTodo: (id: string) => void;
markCompletedTodo?: (id: string) => void;
};
const TodoItem = ({ todo, removeTodo, markCompletedTodo }: TodoProps) => {
return (
<div>
<h2>{todo.text}</h2>
<button type="button" onClick={() => removeTodo(todo.id)}>
Remove
</button>
{typeof markCompletedTodo === 'undefined' ? null : (
<button type="button" onClick={() => markCompletedTodo(todo.id)}>
Mark completed
</button>
)}
</div>
);
};
export default TodoItem;
</code></pre>
<p>As you can see, it gets a <code>todo</code> with a <code>isCompleted</code> property. I want to render the 'Mark completed' button only is the <code>isCompleted</code> property is <code>false</code>, but currently I'm checking for the optional <code>markCompletedTodo</code> prop. That works but I have the feeling this can be done in a better way.</p>
<p>I'm using it to create two lists of TODOS, one for incomplete TODOS and one for complete TODOS, so I'm using it like this in another component:</p>
<pre><code>return (
<h2>Incomplete TODOS</h2>
{incompleteTodos.map((todo) => (
<TodoItem
key={todo.text}
todo={todo}
removeTodo={removeTodoRequest}
markCompletedTodo={markCompletedTodoRequest}
/>
))}
<h2>Complete TODOS</h2>
{completeTodos.map((todo) => (
<TodoItem
key={todo.text}
todo={todo}
removeTodo={removeTodoRequest}
/>
))}
)
</code></pre>
<p>Is there a better approach to this regarding the type checking and the prop types in the <code>TodoItem</code> component, or any other aspect?</p>
|
[] |
[
{
"body": "<p><strong>Make the shapes the same</strong> In my experience, TypeScript is easiest when similar data has the same shape (type). Rather than conditionally passing a <code>markCompletedTodo</code>, consider passing that prop unconditionally, and in the child component, check <code>todo.isCompleted</code> when you need to identify whether to add the button or not.</p>\n<p><strong>Duplicate key bug</strong> You use:</p>\n<pre><code>{incompleteTodos.map((todo) => (\n <TodoItem\n key={todo.text}\n</code></pre>\n<p>What if the todo text is the same? Maybe someone adds "Get groceries" Tuesday, then comes back to the app on Thursday and adds "Get groceries" again for the next week. This means that you'll have duplicate mapped keys, which should not be done and will confuse React, possibly creating rendering problems.</p>\n<p>Since it looks like todos have IDs, use those IDs as keys instead.</p>\n<p><strong><code>&&</code> instead of conditional</strong> To conditionally render in React, you can use <code>&&</code> or <code>||</code> to test, and put the element to be rendered on the right-hand side - it's a bit more concise than the conditional operator.</p>\n<p>You could do something like:</p>\n<pre><code>// You could rename the definition of removeTodoRequest to removeTodo\n// and markCompletedTodoRequest to markCompletedTodo\n// so that you can use shorthand property names below:\nconst makeTodoItem = (todo: Todo) => (\n <TodoItem\n key={todo.id}\n {...{ todo, removeTodo, markCompletedTodo }}\n />\n);\nreturn (\n <h2>Incomplete TODOS</h2>\n {incompleteTodos.map(makeTodoItem)}\n <h2>Complete TODOS</h2>\n {completeTodos.map(makeTodoItem)}\n); // don't forget this semicolon\n</code></pre>\n<pre><code>type TodoProps = {\n todo: Todo;\n removeTodo: (id: string) => void;\n markCompletedTodo: (id: string) => void;\n};\n\nconst TodoItem = ({ todo, removeTodo, markCompletedTodo }: TodoProps) => {\n return (\n <div>\n <h2>{todo.text}</h2>\n <button type="button" onClick={() => removeTodo(todo.id)}>\n Remove\n </button>\n {!todo.isCompleted && (\n <button type="button" onClick={() => markCompletedTodo(todo.id)}>\n Mark completed\n </button>\n )}\n </div>\n );\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T03:16:02.270",
"Id": "251450",
"ParentId": "251435",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "251450",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T18:37:48.810",
"Id": "251435",
"Score": "1",
"Tags": [
"react.js",
"typescript"
],
"Title": "TodoItem component type checking for optional prop"
}
|
251435
|
<p>This is a simple machine language simulator that handles basic operations such as read, write, load, store, add, subtract, multiply, divide, modulus, branch, branch if negative, branch if zero.</p>
<p>Inputs are gotten from the user in hexadecimal, the memory is simulated as a built-in <code>array</code> of integers which can hold a maximum of 1 word.</p>
<p>A word consist of 4 digits, the first two represents the operand code (sml instruction code), the last two represents the operand (location in memory)
The simulator also reads and output string literals.</p>
<p>Here is the code.</p>
<h1>constants.h</h1>
<pre><code>constexpr unsigned read = 0xA; // Read a word(int) from the keyboard into a specific location in memory
constexpr unsigned write = 0xB; // Write a word(int) from a specific location in memory to the screen
constexpr unsigned read_str = 0xC; // Read a word(string) from the keyboard into a specific location in memory
constexpr unsigned write_str = 0xD; // Write a word(string) from a specific location in memory to the screen
constexpr unsigned load = 0x14; // Load a word from a specific location in memory to the accumulator
constexpr unsigned store = 0x15; // Store a word from the accumulator into a specific location in memory
constexpr unsigned add = 0x1E; /* Add a word from a specific location in memory to the word in the accumulator; store the
result in the accumulator */
constexpr unsigned subtract = 0x1F;
constexpr unsigned multiply = 0x20;
constexpr unsigned divide = 0x21;
constexpr unsigned modulo = 0x22;
constexpr unsigned branch = 0x28; // Branch to a specific location in the memory
constexpr unsigned branchneg = 0x29; // Branch if accumulator is negative
constexpr unsigned branchzero = 0x2A; // Branch if accumulator is zero
constexpr unsigned halt = 0x2B; // Halt the program when a task is completed
constexpr unsigned newline = 0x32; // Insert a new line
constexpr unsigned end = -0x1869F; // End the program execution
constexpr unsigned memory_size = 1000;
constexpr unsigned sml_debug = 0x2C; // SML debug
</code></pre>
<h1>registers.h</h1>
<pre><code>int accumulator = 0;
unsigned instruction_counter = 0;
unsigned instruction_register = 0;
unsigned operation_code = 0;
unsigned operand = 0;
</code></pre>
<h1>sml.h</h1>
<pre><code>#include "constants.h"
void memory_dump( int memory[memory_size], const unsigned &mem_size, const int &acc, const unsigned &ins_reg, \
const unsigned &ins_cnt, const unsigned &opr_code, const unsigned &opr );
void execute( int memory[memory_size], int &acc, unsigned &ins_reg, unsigned &ins_cnt, unsigned &opr_code, unsigned &opr ); // executes the statement in sequential manner
void evaluate( int memory[memory_size], int &acc, unsigned &ins_reg, unsigned &ins_cnt, unsigned &opr_code, unsigned &opr );
void display_welcome_message();
bool division_by_zero( int memory[ memory_size ], unsigned operand );
</code></pre>
<h1>sml.cpp</h1>
<pre><code>#include <iostream>
#include <iomanip>
#include <string>
#include "sml.h"
int temp_cnt = 0; // holds instruction_counter when performing branch operation
std::string temp_str; // holds the string before it is written into the memory
bool debug = false;
void memory_dump( int memory[memory_size], const unsigned &mem_size, const int &acc, const unsigned &ins_reg, \
const unsigned &ins_cnt, const unsigned &opr_code, const unsigned &opr )
{
std::cout << "\nREGISTERS:\n";
std::cout << std::setw( 25 ) << std::left << std::setfill( ' ' ) << "accumulator" << std::showpos
<< std::setw( 5 ) << std::setfill( '0' ) << std::internal << acc << '\n';
std::cout << std::setw( 28 ) << std::left << std::setfill( ' ' )
<< "instruction counter" << std::noshowpos << std::setfill( '0' )
<< std::right << std::setw( 2 ) << ins_cnt << '\n';
std::cout << std::setw( 25 ) << std::left << std::setfill( ' ' )
<< "instruction register" << std::showpos << std::setw( 5 ) << std::setfill( '0' )
<< std::internal << ins_reg << '\n';
std::cout << std::setw( 28 ) << std::left << std::setfill( ' ' )
<< "operation code" << std::noshowpos << std::setfill( '0' )
<< std::right << std::setw( 2 ) << opr_code << '\n';
std::cout << std::setw( 28 ) << std::left << std::setfill( ' ' )
<< "operand" << std::noshowpos << std::setfill( '0' )
<< std::right << std::setw( 2 ) << opr << '\n';
std::cout << "\n\nMEMORY:\n";
std::cout << " ";
for( int i = 0; i != 10; ++i )
std::cout << std::setw( 6 ) << std::setfill( ' ') << std::right << i;
for( size_t i = 0; i != mem_size; ++i )
{
if( i % 10 == 0 )
std::cout << "\n" << std::setw( 3 ) << std::setfill( ' ' ) << i << " ";
std::cout << std::setw( 5 ) << std::setfill( '0' ) << std::showpos << std::internal << memory[ i ] << " ";
}
std::cout << std::endl;
}
void execute( int memory[memory_size], int &acc, unsigned &ins_reg, \
unsigned &ins_cnt, unsigned &opr_code, unsigned &opr )
{
int divisor;
while( memory[ ins_cnt ] != 0 )
{
ins_reg = memory[ ins_cnt++ ];
if( ins_reg < 1000 ) divisor = 0x10;
else if( ins_reg >= 1000 && ins_reg < 10000 ) divisor = 0x100;
else if( ins_reg >= 10000 && ins_reg < 100000 ) divisor = 0x1000;
opr_code = ins_reg / divisor;
opr = ins_reg % divisor ;
if( opr_code == halt )
break;
evaluate( memory, acc, ins_reg, ins_cnt, opr_code, opr );
if( debug )
memory_dump( memory, memory_size, acc, ins_reg, ins_cnt, \
opr_code, opr );
}
}
void evaluate( int memory[memory_size], int &acc, unsigned &ins_reg, \
unsigned &ins_cnt, unsigned &opr_code, unsigned &opr )
{
switch ( opr_code )
{
case read:
std::cin >> memory[ opr ];
break;
case read_str:
std::cin >> temp_str;
memory[ opr ] = temp_str.size();
for( int i = 1; i != temp_str.size() + 1; ++i )
memory[ opr + i ] = int( temp_str[ i - 1 ] );
break;
case write:
std::cout << memory[ opr ] << " ";
break;
case write_str:
for( int i = 0; i != memory[ opr ] + 1; ++i ) {
std::cout << char( memory[ opr + i ]);
}
break;
case load:
acc = memory[ opr ];
break;
case store:
memory[ opr ] = acc;
break;
case add:
acc += memory[ opr ];
break;
case subtract:
acc -= memory[ opr ];
break;
case multiply:
acc *= memory[ opr ];
break;
case divide:
if ( division_by_zero( memory, opr ) )
{
memory_dump( memory, memory_size, acc, ins_reg, ins_cnt, opr_code, opr );
exit( EXIT_FAILURE );
}
else
{
acc /= memory[ opr ];
break;
}
case modulo:
if( division_by_zero( memory, opr ) )
{
memory_dump( memory, memory_size, acc, ins_reg, ins_cnt, opr_code, opr );
exit( EXIT_FAILURE );
}
else
{
acc %= memory[ opr ];
break;
}
case branch:
temp_cnt = ins_cnt;
ins_cnt = opr;
execute( memory, acc, ins_reg, ins_cnt, opr_code, opr );
ins_cnt = temp_cnt;
break;
case branchneg:
if( acc < 0 )
{
temp_cnt = ins_cnt;
ins_cnt = opr;
execute( memory, acc, ins_reg, ins_cnt, opr_code, opr );
ins_cnt = temp_cnt;
}
break;
case branchzero:
if( acc == 0 )
{
temp_cnt = ins_cnt;
ins_cnt = opr;
execute( memory, acc, ins_reg, ins_cnt, opr_code, opr );
ins_cnt = temp_cnt;
}
break;
case newline:
std::cout << '\n' << std::flush;
break;
case sml_debug:
if ( opr == 1 ) debug = true;
else if ( opr == 0 ) debug = false;
else
{
std::cout << std::setw( 5 ) << std::setfill( ' ') << std::left << "***"
<< "Invalid debug mode"
<< std::setw( 5 ) << std::right << "***\n";
}
break;
default:
break;
}
}
void display_welcome_message () {
std::cout << "***" << " WELCOME TO SIMPLETRON! " << "***\n\n";
std::cout << std::setw( 5 ) << std::left << "***"
<< "Please enter your program one instruction"
<< std::setw( 5 ) << std::right << "***\n";
std::cout << std::setw( 5 ) << std::left << "***"
<< "(or data word) at a time. I will type the"
<< std::setw( 5 ) << std::right << "***\n";
std::cout << std::setw( 5 ) << std::left << "***"
<< "location number and a question mark (?)."
<< std::setw( 6 ) << std::right << "***\n";
std::cout << std::setw( 5 ) << std::left << "***"
<< "You then type the word for that location"
<< std::setw( 6 ) << std::right << "***\n";
std::cout << std::setw( 5 ) << std::left << "***"
<< "Type the sentinel -0x1869F to stop entering"
<< std::setw( 5 ) << std::right << "***\n";
std::cout << std::setw( 5 ) << std::left << "***"
<< "your program"
<< std::setw( 5 ) << std::right << "***";
std::cout << "\n\n" << std::flush;
}
bool division_by_zero( int memory[ memory_size ], unsigned operand )
{
if ( memory[ operand ] == 0 )
{
std::cout << std::setw( 5 ) << std::left << "***"
<< "Attempting division by zero"
<< std::setw( 5 ) << std::right << "***\n";
std::cout << std::setw( 5 ) << std::left << "***"
<< "Program terminated abnormally"
<< std::setw( 5 ) << std::right << "***\n";
std::cout << "\n";
return true;
}
return false;
}
</code></pre>
<h1>main.cpp</h1>
<pre><code>#include <iostream>
#include <iomanip>
#include "registers.h"
#include "sml.h"
int main()
{
int memory[ memory_size ]{};
size_t memory_size = sizeof( memory )/ sizeof( memory[ 0 ] );
int temp;
display_welcome_message();
while( instruction_counter != memory_size )
{
std::cout << std::setw( 2 ) << std::setfill( '0' )
<< instruction_counter << " ? ";
std::cin >> std::hex >> temp;
if( temp == end ) {
break;
}
if( temp >= -0xB3E8 && temp < 0xB3E8 )
memory[ instruction_counter++ ] = temp;
else
continue;
}
instruction_counter = 0;
std::cout << std::setfill( ' ' );
std::cout << std::setw( 5 ) << std::left << "***"
<< "Program loaded into memory"
<< std::setw( 5 ) << std::right << "***\n";
std::cout << std::setw( 5 ) << std::left << "***"
<< "Program execution starts..."
<< std::setw( 5 ) << std::right << "***\n";
execute( memory, accumulator, instruction_register, instruction_counter, operation_code, operand );
std::cout << std::endl;
}
</code></pre>
|
[] |
[
{
"body": "<h1>Digits and word sizes</h1>\n<p>I see code like this in your code:</p>\n<pre><code>constexpr unsigned read = 0xA;\nint accumulator = 0;\n</code></pre>\n<p>This means you are tying word sizes to whatever the size of an <code>int</code> is on the machine you are compiling your code on. I would create new type aliases that explicitly defines the size of a signed and unsigned word in your simulated machine:</p>\n<pre><code>using sword = int32_t;\nusing uword = uint32_t;\n</code></pre>\n<p>Then there are the digits. You say that the input from the user is in hexadecimal, that words are 4 digits, but from the code it looks like those are decimal digits? That's not very consistent. Most computers would work with powers of two, and that also makes simulation much faster (division and modulo operations are quite expensive).</p>\n<h1>Create a <code>class</code> to hold the state of the machine</h1>\n<p>Instead of having lots of out-of-class functions to which you have to pass a lot of variables every time, it makes more sense to create a <code>class</code> that represents the simulated machine, and which contains member variables for the registers and the memory, like so:</p>\n<pre><code>class Machine {\n int accumulator = 0; \n unsigned instruction_counter = 0;\n ...\n std::vector<int> memory(memory_size);\n\n void memory_dump();\n void evaluate();\n\npublic:\n void load_program();\n void execute();\n};\n</code></pre>\n<p>You can also move all the constants inside <code>class Machine</code>, so they no longer pollute the global namespace, especially when you have names like <code>read</code> and <code>write</code> that shadow POSIX functions.</p>\n<p>I would move everything from <code>sml.cpp</code> into <code>class Machine</code>, except <code>display_welcome_message()</code>, which should probably just be in <code>main.cpp</code>, as it does not relate to the functioning of the machine.</p>\n<h1>Avoid magic constants</h1>\n<p>You have proper names for all the constants, except <code>-0xB3E8</code> and <code>0xB3E8</code>. What's up with those? Give those a name as well.</p>\n<h1>Consider using a formatting library</h1>\n<p>Creating nicely formatted output using <code>iostream</code> functionality in C++ is very annoying. It requires a lot of code, mistakes are easily made, and the source code looks terrible. If you can use C++20 already, I strongly suggest you start using <a href=\"https://en.cppreference.com/w/cpp/utility/format/format\" rel=\"nofollow noreferrer\"><code>std::format()</code></a>, but if you cannot, consider using <a href=\"https://github.com/fmtlib/fmt\" rel=\"nofollow noreferrer\">fmtlib</a>, which is the library that <code>std::format()</code> is based on, and will work with earlier versions of C++. This means you can rewrite your code like so:</p>\n<pre><code>std::cout << std::format("{:02} ? ", instruction_counter);\n...\nstd::cout << std::format("{:*^40}\\n", " Program loaded into memory ");\n...\nstd::cout << std::format("{:*^40}\\n", " Program execution starts... ");\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T20:52:09.310",
"Id": "494990",
"Score": "0",
"body": "Can you please elaborate on `Most computers would work with powers of two, and that also makes simulation much faster (division and modulo operations are quite expensive).`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T21:17:13.963",
"Id": "494991",
"Score": "0",
"body": "@theProgrammer See [this question](https://gamedev.stackexchange.com/questions/27196/which-opcodes-are-faster-at-the-cpu-level) for an overview of the speed of native CPU instructions. In general, integer division takes tens of clock cycles, whereas a simple bitwise AND or shift instruction takes less than a cycle on average. So if you encode your instructions such that the opcode is always in, for example, the high 16 bits, you have the lower 16 bits for the instruction operand. So then `opr_code = ins_reg >> 16; opr = ins_reg & 0xFFFF`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T23:23:42.580",
"Id": "495000",
"Score": "1",
"body": "Nitpick: `read` and `write` are from POSIX, not from the C Standard Library."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T16:10:22.247",
"Id": "495082",
"Score": "0",
"body": "Does any compiler implementation support `std::format` already? Last time I checked, it was in the standard but nowhere implemented."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T20:40:50.007",
"Id": "251440",
"ParentId": "251436",
"Score": "5"
}
},
{
"body": "<h2>General Observations</h2>\n<p>This particular kind of problem is always interesting to solve.</p>\n<p>Since your 4th question you seem to be avoiding classes. In C++ classes are your entryway to object oriented programming and class provide great tools. As @G.Sliepen stated in their review the simulator would be much better if it was a class. There wouldn't be any need for global variables if the simulator was implemented as a class. The public interfaces for <code>execute()</code>, <code>evaluate()</code>, and <code>memory_dump()</code> would be much simpler since the memory array and the registers would be private variables and there would be no need to pass them into the function.</p>\n<p>To make the program more friendly add a line editor that allows the user to modify the simulator program. That way the program doesn't need to exit if the simulator dumps memory. The execution of the simulator can stop, the user can edit the line and then start the simulation again. Use <a href=\"http://www.cplusplus.com/doc/tutorial/exceptions/\" rel=\"nofollow noreferrer\">exceptions</a> rather than <code>exit(EXIT_FAILURE);</code> to return the program to a known state.</p>\n<p>You might want to look at the <a href=\"https://codereview.stackexchange.com/questions/244566/an-attempt-at-a-toy-vm\">answers on this question</a> for more information.</p>\n<h2>Avoid Global Variables</h2>\n<p>Currently there are at least 8 global variables in the program, in <code>registers.h</code>:</p>\n<pre><code>int accumulator = 0;\nunsigned instruction_counter = 0;\nunsigned instruction_register = 0;\nunsigned operation_code = 0;\nunsigned operand = 0;\n</code></pre>\n<p>in sml.cpp:</p>\n<pre><code>int temp_cnt = 0; // holds instruction_counter when performing branch operation\nstd::string temp_str; // holds the string before it is written into the memory\nbool debug = false;\n</code></pre>\n<p>It is very difficult to read, write, debug and maintain programs that use global variables. Global variables can be modified by any function within the program and therefore require each function to be examined before making changes in the code. In C and C++ global variables impact the namespace and they can cause linking errors if they are defined in multiple files. The <a href=\"https://stackoverflow.com/questions/484635/are-global-variables-bad\">answers in this stackoverflow question</a> provide a fuller explanation.</p>\n<p>Most or all of these global variables could be private variables if the simulator was implemented as a class.</p>\n<p>The registers could be implemented as an array indexed by an enun.</p>\n<pre><code>typedef enum\n{\n ACCUMULATOR = 0,\n INSTRUCTION_COUNTER = 1,\n INSTRUCTION_REGISTER = 2,\n OPERATION_CODE = 3,\n OPERAND = 4,\n REGISTER_COUNT = 5\n} REGISTERS;\n\n unsigned registers[static_cast<unsigned>(REGISTER_COUNT)];\n registers[ACCUMULATOR] = 0;\n</code></pre>\n<p>If the code in sml.cpp isn't converted to a class, then it would be better to make each of those variable <code>static</code> so that their scope is only that of the sml.cpp file itself, right now they could be accessed in other <code>.cpp</code> files such as <code>main.cpp</code>.</p>\n<p>The registers global variables should be declared in <code>sml.cpp</code> since they aren't necessary to other parts of the program such as <code>main.cpp</code>.</p>\n<h2>Include Guards</h2>\n<p>In C++ as well as the C programming language the code import mechanism <code>#include FILE</code> actually copies the code into a temporary file generated by the compiler. Unlike some other modern languages C++ (and C) will include a file multiple times. To prevent this programmers use include guards which can have 2 forms:</p>\n<p>the more portable form is to embed the code in a pair of pre-processor statements</p>\n<pre><code>#ifndef SYMBOL\n#define SYMBOL\n// All other necessary code\n#endif // SYMBOL\n\nA popular form that is supported by most but not all C++ compilers is to put #pragma once at the top of the header file. \n</code></pre>\n<p>Using one of the 2 methods above to prevent the contents of a file from being included multiple times is a best practice for C++ programming. This can improve compile times if the file is included multiple times, it can also prevent compiler errors and linker errors.</p>\n<h2>Complexity</h2>\n<p>The function <code>evaluate()</code> is too complex <em>(does too much)</em> and the performance can be improved. If the opcode values defined <code>constants.h</code> were in order and starting at zero an array of functions could be used to implement each of the opcodes. Then each opcode can be evaluated by simplify indexing into that array by opcode. This would greatly reduce the amount of code in the function. It will perform faster because indexing into an array is faster than going through multiple if statements in the assembly code generated. This also makes it easier to expand the instruction set.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T04:13:15.260",
"Id": "495011",
"Score": "0",
"body": "@pacmanibw I have never seen `typedef enum { ... }` in C++, I have read that it makes somewhat a difference in C, what is the use here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T04:45:13.593",
"Id": "495013",
"Score": "0",
"body": "Great. Inasmuch as adding a vim-like interface would improve usability, I just want to keep it very simple now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T04:49:46.783",
"Id": "495014",
"Score": "0",
"body": "@pacmanibw. Correct me if am wrong, I think classes are meant to be used in scenarios where multiple instances of a class are needed. In this case, only one instance of a class would ever be needed at a time. I know classes would improves the structure and readability, what are the other gains? Can it be done clearly using a different approach aside classes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T07:04:02.737",
"Id": "495020",
"Score": "1",
"body": "@theProgrammer That's one of their uses, not the only use for classes. Once you start using classes and applying single-responsibility (1 function has 1 task and 1 task only), you'll see your code cleans up quite nicely. Your `registers.h` will become obsolete."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T14:45:48.143",
"Id": "495066",
"Score": "0",
"body": "@theProgrammer One of the more important usages of Object Oriented Program is reuse. Well written classes following the [SOLID programming principles](https://en.wikipedia.org/wiki/SOLID) can be used in other programs just by including the class files in a new program. That reduces development time and costs. Almost all programming in C++ is object oriented for this reason. The [single-responsibility principle](https://en.wikipedia.org/wiki/Single-responsibility_principle) mentioned by Mast is the S in SOLID."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T15:06:53.963",
"Id": "495069",
"Score": "0",
"body": "@AryanParekh there may be multiple enum declarations in a program that aren't protected by a class or a namespace, making it a type provides better type checking. My [question on a simple language lexical analyzer](https://codereview.stackexchange.com/questions/248559/hand-coded-state-driven-lexical-analyzer-in-c-with-unit-test-part-a) is an example in C."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T22:51:41.070",
"Id": "251444",
"ParentId": "251436",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "251444",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T19:47:25.320",
"Id": "251436",
"Score": "7",
"Tags": [
"c++"
],
"Title": "Simple Machine Language simulator"
}
|
251436
|
<p>I am refactoring a function that calculates how many days to add to a process based on destination country or state.</p>
<p>The original function called the database twice, even though the database table stored four values. My thought is to remove the database calls and use a config constant, or simply put the relevant ID numbers right in the code. Which of these methods do you think is best? Or should I do something different?</p>
<h1>Method 1</h1>
<pre><code>def get_transit_time(country, state=None):
if country.id in [1, 221]: # US, Puerto Rico
days = 7
elif country.id in [13, 138]: # Australia, New Zealand
days = 10
elif country.id == 37: # Canada
days = 12
else:
days = 14 # all others
if state and state.id in [2, 15]: # Hawaii, Alaska
days = 10
return days
</code></pre>
<h1>Method 2</h1>
<p>(allows for growth via config constant)</p>
<pre><code>SEND_DELAY_COUNTRIES = [
{'country_id': 1, 'delay': 7},
{'country_id': 221, 'delay': 7},
{'country_id': 13, 'delay': 10},
{'country_id': 138, 'delay': 10},
{'country_id': 37, 'delay': 12}
]
SEND_DELAY_STATES = [
{'state_id': 2, 'delay': 10},
{'state_id': 10, 'delay': 10}
]
def get_card_transit_time(country, state=None):
days = 14 # default if no result found
for country_config in SEND_DELAY_COUNTRIES:
if country_config['country_id'] == country.id:
days = country_config['delay']
if state:
for state_config in SEND_DELAY_STATES:
if state_config['state_id'] == state.id:
days = state_config['delay']
return days
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T18:19:23.873",
"Id": "495110",
"Score": "0",
"body": "It should go in the same place that the country/state_name to country/state_id mapping is stored. When country/state information needs to be changed, it's best if you only need to make changes in one place."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T01:50:46.340",
"Id": "495300",
"Score": "2",
"body": "First of all, if you have hardcoded numbers and have to add comments that it means Puerto Rico, you are probably doing something wrong. Define an enum for readability."
}
] |
[
{
"body": "<p>I would advise to use the second method for many reasons:</p>\n<ul>\n<li>It is more extensible, so you can add other country codes later easier.</li>\n<li>Avoids <code>if</code> <code>elif</code> chains.</li>\n<li>Avoids <a href=\"https://en.wikipedia.org/wiki/Magic_number_%28programming%29\" rel=\"nofollow noreferrer\">Magic Numbers</a>.</li>\n</ul>\n<p>I would also change the <code>dict</code> representation because you are iterating over it in <code>O(n)</code> linear time.</p>\n<p>While <code>dict</code>s are optimized for <code>O(1)</code> constant time.</p>\n<p>I would change it to the following:</p>\n<pre class=\"lang-py prettyprint-override\"><code>SEND_DELAY = {\n 'country_id': {\n 1: 7,\n 221: 7,\n 13: 10,\n 138: 10,\n 37: 12\n }\n 'state_id': {\n 2: 10,\n 10: 10\n }\n}\n</code></pre>\n<p>And access it like the following:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def get_card_transit_time(country, state=None):\n default = 14 # default if no result found\n days = (SEND_DELAY['state_id'][state.id]\n if state is not None\n else SEND_DELAY['country_id'].get(country.id, default))\n\n return days\n</code></pre>\n<p>This approach is very fast, works in <code>O(1)</code> constant time, extensible and abstracts chains of <code>if</code> <code>elif</code> chains.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-05T09:37:09.400",
"Id": "518440",
"Score": "0",
"body": "Given the comment in `days = 14 # default if no result found`, I'd recommend using [`dict.get()`](https://docs.python.org/3/library/stdtypes.html#dict.get) to fall back to the default."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-05T16:44:59.287",
"Id": "518468",
"Score": "0",
"body": "@TobySpeight I am actually using `dict.get(country.id, default)` but I left the default variable there for clarity sake."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-05T20:38:03.543",
"Id": "518491",
"Score": "0",
"body": "Ah yes, in the `else` branch. I was imagining the same for the first, but of course we're indexing with `state.id` and it's `state` that could be `None`. Sorry for my confusion!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-06T16:09:31.337",
"Id": "518559",
"Score": "0",
"body": "@TobySpeight No problem ;)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-05T04:43:22.537",
"Id": "262667",
"ParentId": "251437",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T19:58:27.747",
"Id": "251437",
"Score": "1",
"Tags": [
"python",
"comparative-review"
],
"Title": "Calculate how many days to add to a process based on destination country or state"
}
|
251437
|
<p>How can I improve this code? It renders a ML env with openAI gym and matplotlib. I am new to coding so not sure if my variables or format or any lines can be improved.</p>
<pre><code>def _render(self, obs):
"""Renders the environment.
"""
ball_loc = obs[1]
x, y = self.circle.center
new_y = math.tan(-math.radians(obs[3])) * (ball_loc - self.target_location)
self.circle.center = (ball_loc, 10 + new_y + 1)
t_start = self.ax.transData
coords = t_start.transform([self.target_location, 10])
t = mpl.transforms.Affine2D().rotate_deg_around(coords[0], coords[1], -obs[3])
t_end = t_start + t
self.rect.set_transform(t_end)
self.fig.canvas.draw()
plt.pause(0.05)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T09:41:59.220",
"Id": "495034",
"Score": "1",
"body": "Hi! Welcome to code review, Please add enough details about your code in the question body, anything that will be useful to people who'd want to review your code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T01:08:14.133",
"Id": "495158",
"Score": "1",
"body": "We need to see more of the code - at the very least, your `import` statements; but ideally the entire program."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-01T22:10:32.787",
"Id": "251443",
"Score": "2",
"Tags": [
"python-3.x",
"graph",
"mathematics",
"machine-learning",
"matplotlib"
],
"Title": "Data Visualization (rendering env)"
}
|
251443
|
<p>I'm still fairly new to Python and I'm trying to see if I've efficiently used modules, functions, etc or if there's another/easier way to do something.</p>
<p>This Python 3 Vigenere Cipher is a rebuild of a JavaScript-based cipher and based in Windows. It accepts any alphabet character, and has demo options built in. Cipher demo uses stage 1 of the CIA <a href="https://en.wikipedia.org/wiki/Kryptos" rel="noreferrer">Kryptos</a> cipher.</p>
<pre><code>#! python
import os
import re
## Initialize global variables
continue_cipher = ""
demo_alphabet = "KRYPTOSABCDEFGHIJLMNQUVWXZ"
demo_key = "PALIMPSEST"
demo_cipher_string = "EMUFPHZLRFAXYUSDJKZLDKRNSHGNFIVJYQTQUXQBQVYUVLLTREVJYQTMKYRDMFD"
demo_cipher_decoded = "BETWEENSUBTLESHADINGANDTHEABSENCEOFLIGHTLIESTHENUANCEOFIQLUSION"
## Visuals
def display_header():
print("################################################")
print("# #")
print("# --- VIGENERE CIPHER --- #")
print("# #")
print("# A simple Vigenere cipher decoder/encoder #")
print("# #")
print("################################################", end="\n\n")
return
def display_results(mode, cipher_vars):
# Clear screen for final results
os.system('cls')
# Display header
display_header()
# Decompose cipher_vars
(alphabet, key, cipher_string, results) = cipher_vars
print("Mode:", "Decrypt" if mode == "D" else "Encrypt", end="\n\n")
print("Alphabet:", alphabet)
print("Key:", key)
print("Cipher String:", cipher_string, end="\n\n")
print("Decoded string:" if mode == "D" else "Encoded string:", results, end="\n\n")
return
## Validations
def string_is_alpha(input_string):
return True if re.match("^[a-zA-Z_]*$", input_string) else False
## Cipher variables
def get_alphabet():
global demo_alphabet
while True:
alphabet = input("Enter cipher alphabet: ").upper()
if alphabet == "":
alphabet = demo_alphabet
break
elif string_is_alpha(alphabet) is False:
print("The alphabet is not valid. Alphabet should not contain spaces, digits or special characters.")
else:
break
return alphabet
def get_key():
global demo_key
while True:
key = input("Enter cipher key: ").upper()
if key == "":
key = demo_key
break
elif string_is_alpha(key) is False:
print("The key is not valid. Key should not contain spaces, digits or special characters.")
else:
break
return key
def get_cipher_string(mode):
global demo_cipher_string
global demo_cipher_decoded
while True:
cipher_string = input("Enter cipher string: ").upper()
if cipher_string == "":
cipher_string = demo_cipher_string if mode == "D" else demo_cipher_decoded
break
elif string_is_alpha(cipher_string) is False:
print("The cipher string is not valid. Cipher strings should not contain spaces, digits or special characters.")
else:
break
return cipher_string
## Cipher actions
def get_cipher_alphabets(alphabet, key):
cipher_alphabets = []
for char in key:
char_index = alphabet.find(char)
cipher_alphabet = alphabet[char_index:] + alphabet[:char_index]
cipher_alphabets.append(cipher_alphabet)
return cipher_alphabets
def start_cipher(mode, alphabet, key, cipher_string):
mode_string = ""
cipher_alphabets = get_cipher_alphabets(alphabet, key)
cipher_alphabet_index = 0
for char in cipher_string:
# Reset cipher_alphabet_index to 0 when at end of cipher alphabets
if cipher_alphabet_index == len(cipher_alphabets):
cipher_alphabet_index = 0
# Use appropriate alphabet based on mode
# Syntax: base_alphabet[mode_alphabet.find(char)]
if mode == "D":
mode_string += alphabet[cipher_alphabets[cipher_alphabet_index].find(char)]
else:
mode_string += cipher_alphabets[cipher_alphabet_index][alphabet.find(char)]
cipher_alphabet_index += 1
return mode_string
## Cipher Mode
def get_cipher_mode():
while True:
cipher_mode = input("Choose cipher mode - [D]ecrypt or [E]ncrypt: ").upper()
if cipher_mode != "D" and cipher_mode != "E":
print("That is not a valid option. Please enter 'D' for decrypt and 'E' for encrypt.")
else:
break
print("")
return cipher_mode
def start_cipher_mode(mode):
print("Press 'enter' to use demo options")
alphabet = get_alphabet()
key = get_key()
cipher_string = get_cipher_string(mode)
mode_string = start_cipher(mode, alphabet, key, cipher_string)
return alphabet, key, cipher_string, mode_string
## Loop cipher
def get_continue_cipher():
while True:
continue_cipher = input("Do you want to decode/encode more? [Y/N]: ").upper()
if continue_cipher != "Y" and continue_cipher != "N":
print("That is not a valid option. Please enter 'Y' to continue and 'N' to quit.")
else:
break
return continue_cipher
## Start vigenere cipher program
while continue_cipher != "N":
# Clear the screen after each operation
os.system('cls')
# Display header
display_header()
# Determine cipher mode
cipher_mode = get_cipher_mode()
cipher_vars = start_cipher_mode(cipher_mode)
# Display results
display_results(cipher_mode, cipher_vars)
continue_cipher = get_continue_cipher()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T06:36:12.930",
"Id": "495017",
"Score": "0",
"body": "Your title should state what your code does, and nothing else. Everything else belongs to the body of the question. [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask), also please explain further what your code does in the body, as of now it is a little unclear"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T06:52:38.460",
"Id": "495019",
"Score": "0",
"body": "It wouldn't let me put that in the first time. It kept sending me to the how do I ask a good question link, so I kept trying until the system accepted something. Perhaps there's an issue with the system because it now accepts my original title."
}
] |
[
{
"body": "<h2>shebang</h2>\n<p>The shebang should be generic. You are currently calling <code>python</code>, which might point to python 2 on certain systems.</p>\n<p>A generic, virtual environment friendly python shebang is:</p>\n<pre><code>#!/usr/bin/env python3\n</code></pre>\n<h2>PEP-8</h2>\n<p>Few points from <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8 guide</a>:</p>\n<ul>\n<li>Surround top-level function and class definitions with two blank lines.</li>\n<li>Use blank lines in functions, sparingly, to indicate logical sections.</li>\n<li>Constants are usually defined on a module level and written in all capital letters with underscores separating words.</li>\n</ul>\n<h2>PEP-484</h2>\n<p>Type hinting functions makes it easier to follow through your functions. Check out <a href=\"https://www.python.org/dev/peps/pep-0484/\" rel=\"nofollow noreferrer\">the PEP-484</a>.</p>\n<h2><code>if __name__</code> block</h2>\n<p>Put execution logic of your script inside the <code>if __name__ == "__main__"</code> block. A more descriptive explanation can be checked <a href=\"https://stackoverflow.com/a/419185/1190388\">on Stack Overflow</a>.</p>\n<h2>Redundant logic</h2>\n<p>In your code, you have 5 different functions, only to read user input. All of them have the same job of:</p>\n<ol>\n<li>infinite loop</li>\n<li>ask for user input</li>\n<li>convert to uppercase</li>\n<li>validate if input is empty (or in a set of valid values)</li>\n<li>in case of empty value, return a default</li>\n<li>return with the value</li>\n</ol>\n<p>All this could be handled by a single function:</p>\n<pre><code>def ask_user_input(message: str, options: List[str] = None, default: str = None, check_alpha: bool = False) -> str:\n if not any([options, default]):\n raise ValueError("Either a set of `options` for validation or a fallback `default` needed.")\n while True:\n value = input(message).upper()\n if options:\n if value in options:\n break\n else:\n print(f"Invalid value. Select one of {', '.join(options)}")\n continue\n if default is not None:\n if not value:\n value = default\n break\n elif not check_alpha:\n break\n elif not (value.isalpha() and value.isascii()):\n print("The input text should only consist of ascii alphabets.")\n continue\n else:\n break\n return value\n</code></pre>\n<h2>Regex/validation</h2>\n<p>The regex for validating input allows for <code>_</code>, whereas the error message explicitly says no special characters. The check in the rewrite above is done using (updated based on comment below):</p>\n<pre><code>value.isalpha() and value.isascii()\n</code></pre>\n<p>which will perform faster than regex (unless the user keeps inputting wrong values <span class=\"math-container\">\\$ 10^ n \\$</span> times, at which the precompiled pattern <em>might</em> perform slightly better).</p>\n<h2>Performance</h2>\n<p>A few things which can be changed to make the code more performant:</p>\n<ol>\n<li><p>Instead of concatenating (appending) to string <code>mode_string</code>, push to a list and at the end, use <code>"".join()</code>. More details <a href=\"https://stackoverflow.com/a/3055541/1190388\">on Stack Overflow</a>.</p>\n</li>\n<li><p>You can make your program support linux (*nix) systems too. The only dependency on windows is your system call to <code>cls</code>. Perhaps (<a href=\"https://stackoverflow.com/a/2084628/1190388\">taken from Stack Overflow</a>):</p>\n<pre><code>def clear():\n os.system("cls" if os.name == "nt" else "clear")\n</code></pre>\n</li>\n<li><p>There are 2 functions with very similar names: <code>start_cipher(mode...)</code> and <code>start_cipher_mode(mode)</code>. This makes it really difficult to know which one is truly <strong>starting the cipher</strong>. Perhaps, have 2 separate functions <code>encrypt</code> and <code>decrypt</code>?</p>\n</li>\n<li><p>Using modulo operation, you can remove the following conditional:</p>\n<pre><code>if cipher_alphabet_index == len(cipher_alphabets):\n cipher_alphabet_index = 0\n</code></pre>\n<p>and would look like:</p>\n<pre><code>result.append(alphabet[cipher_alphabets[cipher_alphabet_index % alphabets_length].find(char)]\n</code></pre>\n</li>\n<li><p>Since you only use the <code>alphabet</code> string to actually work with the index values of characters in it, make a dictionary. Lookups in dictionary is <span class=\"math-container\">\\$ O(1) \\$</span> compared to <span class=\"math-container\">\\$ O(n) \\$</span> for the <code>.find()</code>. This would be:</p>\n<pre><code>from itertools import count\nalphabet_map = dict(zip(alphabet, count()))\n</code></pre>\n</li>\n<li><p>From the above 2 points, it is clear that you don't really need characters/alphabets after the user input. Only the index value modulo matters. This might be difficult to understand/implement without a considerable mathematical understanding, so you can skip this for now.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T15:39:13.707",
"Id": "495073",
"Score": "0",
"body": "Amazing! I've learned so much from this. In Performance #3, I did have separate encrypt/decrypt functions but they did the same thing, so I combined into one. Since start_cipher_mode() is the function to get the cipher data, and start_cipher() is the actual encryption/decryption process, would it be better to change start_cipher_mode() to get_cipher_vars() and keep the en/decryption processes in one function?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T16:14:00.630",
"Id": "495083",
"Score": "0",
"body": "@Chimera.Zen encryption/decryption generally perform very similar mathematical operations. You should still split encrypt and decrypt, and call those accordingly in the `start_cipher` function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T18:30:40.293",
"Id": "495111",
"Score": "1",
"body": "I would argue it would be better to change `not all(char in ascii_uppercase for char in value)` into `value.isalpha() and value.isascii()`. Otherwise great answer!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T10:35:31.063",
"Id": "251467",
"ParentId": "251453",
"Score": "7"
}
},
{
"body": "<p>@hjpotter covered most of my comments.</p>\n<h2>Booleans</h2>\n<p>Python has a concept of <a href=\"https://www.freecodecamp.org/news/truthy-and-falsy-values-in-python/\" rel=\"nofollow noreferrer\">truthy and falsy</a> values, so it is preferable just to treat values as booleans directly, rather than comparing them to True or False.</p>\n<hr />\n<pre><code>return True if re.match("^[a-zA-Z_]*$", input_string) else False\n</code></pre>\n<p>can be simplified to:</p>\n<pre><code>return re.match("^[a-zA-Z_]*$", input_string)\n</code></pre>\n<hr />\n<pre><code> elif string_is_alpha(alphabet) is False:\n</code></pre>\n<p>This can be simplified to:</p>\n<pre><code> elif not string_is_alpha(alphabet):\n</code></pre>\n<p>If general, you rarely want to use "is" for comparison. (The main exception is comparing to <code>None</code>.)</p>\n<h2>Compiling regular expressions</h2>\n<p>This is almost certainly an unnecessary performance improvement, but might be useful to know for later:</p>\n<p>The call to <code>re.match</code> needs to compile the regexp every time it is called. You can precompile the regexp once, and then call <code>match</code> on the compiled object to speed it up.</p>\n<h2>Globals</h2>\n<p>Almost every time I reach for the <code>global</code> keyword, it turns out to be a mistake.</p>\n<p>I don't think you need to declare the demo identifiers as global; they should already be available to use (to read from only - if you attempt to write to them, you will define a new variable in the new scope, hiding the originals).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T18:36:07.297",
"Id": "495113",
"Score": "3",
"body": "In this case, precompiling the regexp wouldn't matter, as Python keeps a cache of the 512 most recently compiled regular expressions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T18:41:54.203",
"Id": "495115",
"Score": "0",
"body": "@Jasmijn: :-O I did not know that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T04:58:45.447",
"Id": "495169",
"Score": "0",
"body": "@Oddthinking source: https://github.com/python/cpython/blob/master/Lib/re.py#L288"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T17:52:58.073",
"Id": "251490",
"ParentId": "251453",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "251467",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T05:18:59.107",
"Id": "251453",
"Score": "6",
"Tags": [
"python",
"beginner",
"python-3.x",
"vigenere-cipher",
"encryption"
],
"Title": "Python 3 Vigenere Cipher"
}
|
251453
|
<p>I was directed here from Stack Overflow.</p>
<p>I completed my recent programming assignment for developing a substitution cipher in C. Below is what I came up with after reading many tutorials, googling many questions, watching many videos, etc. but I am happy with the result. I was just wondering if you know of a more efficient way to do it? Is this good code (for a beginner)? Is there something I overlooked? It should be noted that this is CS50 and I was using the CS50 library. If this isn't the place for this type of feedback, please delete! Thanks!</p>
<p>Here is my code:</p>
<pre><code>#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int validate(int c, string v[]); //prototpe validate function
int main(int argc, string argv[])
{
if (validate(argc, argv) == 0) //run validate for argc and argv and check its response
{
printf("Key is valid\n"); //if valid, print message
}
else
{
return 1; //Return error
}
string plaintext = get_string("plaintext: "); //Get user input
printf("ciphertext: "); //Output the cipher, using following algorithm
//Loop through each letter of inputed text
for (int t = 0, len = strlen(plaintext); t < len; t++)
{
//If not alphabetic character, print as entered
if (plaintext[t] < 'A' || (plaintext[t] > 'Z' && plaintext[t] < 'a') || plaintext[t] > 'z')
{
printf("%c", plaintext[t]);
}
//If alphabetic, encipher the input
else
{
for (int u = 0; u < 26; u++)
{
if (plaintext[t] == 65 + u) //check for uppercase alphabetic characters starting with ASCII 65
{
//Ensure outputed text maintains uppercase
char upper = argv[1][u];
int up = isupper(upper);
if (up == 0)
{
upper = toupper(upper);
printf("%c", upper);
}
if (up != 0)
{
printf("%c", upper);
}
}
if (plaintext[t] == 97 + u) //check for lowercase alphabetic characters starting with ASCII 97
{
//Ensure the outputed text maintains lowercase
char lower = argv[1][u];
int low = islower(lower);
if (low == 0)
{
lower = tolower(lower);
printf("%c", lower);
}
if (low != 0)
{
printf("%c", lower);
}
}
}
}
}
printf("\n"); //print newline for clean terminal
return 0; //Exit
}
//Key Validation function
int validate(int c, string v[])
{
//Validate that only one Command Line Argument was entered
if (c != 2) //Check the number if entered commands at execution
{
//If more than one, print error message
printf("Key must be the only Command Line Argument\n");
return 1; //Return error
}
//Validate that Key length is 26 characters
if (strlen(v[1]) != 26) //Don't forget null 0
{
printf("Key must contain exactly 26 characters\n");
return 1; //Return error
}
//Validate that all Key characters are alphabetic
for (int i = 0, n = strlen(v[1]); i < n; i++)
{
//Check each element of the array
if (isalpha(v[1][i]))
{
continue; //Continue if alphabetic
}
else
{
//if non-alphabetic, print error code
printf("Key must contain only alphabetic characters\n");
return 1; //Return error
}
}
//Validate that each Key character is unique
for (int x = 0, z = strlen(v[1]); x < z; x++)
{
//Create a second loop to compare every element to the first before incrementing the first
for (int y = x + 1; y < z; y++)
{
//Cast array elements to int, check if each element equals next element in array
if (v[1][x] == v[1][y])
{
printf("Key must contain exactly 26 unique characters\n");
return 1; //Return error
}
//also check if same character has been used in different case
if (v[1][x] == v[1][y] + 32)
{
printf("Key must contain exactly 26 unique characters\n");
return 1; //Return error
}
if (v[1][x] == v[1][y] - 32)
{
printf("Key must contain exactly 26 unique characters\n");
return 1; //Return error
}
}
}
return 0; //Key is valid, so return true
}
</code></pre>
|
[] |
[
{
"body": "<p><code>validate</code>:</p>\n<ul>\n<li><p>Once we've checked the number of command line arguments, we can use a named variable for the key, instead of referring to it as <code>v[1]</code> everywhere: <code>string key = v[1]</code>. We should do the same in the <code>main</code> function.</p>\n</li>\n<li><p>We can save the string length to another variable, instead of calling <code>strlen</code> multiple times.</p>\n</li>\n<li><p>The alphabet check contains an unnecessary branch that does nothing. We can simplify it to:</p>\n<pre><code> //Validate that all key characters are alphabetic\n for (int i = 0; i < key_len; i++)\n {\n if (!isalpha(key[i]))\n {\n printf("Key must contain only alphabetic characters\\n");\n return 1; //Return error\n }\n }\n</code></pre>\n</li>\n<li><p>The uniqueness check will compare the last non-null character in the key with the null character at the end. We need to limit <code>x</code> to the range <code>[0, key_len - 1)</code> to avoid that.</p>\n</li>\n<li><p><code>if (v[1][x] == v[1][y] + 32)</code>, <code>if (v[1][x] == v[1][y] - 32)</code>. We should use a named constant variable for <code>32</code> to make it clearer what this is doing.</p>\n<p>Note, however, that these checks don't do exactly what we want them to. They will also compare the letters with various punctuation characters.</p>\n<p>We can replace these 3 <code>if</code>s with a single one: <code>if (toupper(key[x]) == toupper(key[y]))</code></p>\n</li>\n</ul>\n<hr />\n<p><code>main</code>:</p>\n<ul>\n<li><p>We can use <code>isalpha</code> in our encoding loop, instead of custom range checking.</p>\n</li>\n<li><p>We don't need to loop over the alphabet to do the encoding. We can calculate the offset of our index character from <code>'a'</code> or <code>'A'</code>, and use that as the index into the key.</p>\n</li>\n<li><p>It looks like we're trying to maintain the case of the plaintext - which maybe isn't a sensible feature for a cryptographic system! Anyway... in that case, we need to use <code>isupper</code> on the <code>plaintext[t]</code>, not on the encoded value (which is what the original program seems to be doing).</p>\n<p>Note that since we don't know whether the key chars are uppercase or lowercase, we should always use <code>toupper</code> or <code>tolower</code> on the output.</p>\n</li>\n</ul>\n<p>So I think we can do something like:</p>\n<pre><code>for (int t = 0, len = strlen(plaintext); t < len; t++)\n{\n if (!isalpha(plaintext[t]))\n {\n printf("%c", plaintext[t]);\n continue;\n }\n\n char encoded = key[toupper(plaintext[t]) - 'A'];\n char output = isupper(plaintext[t]) ? toupper(encoded) : tolower(encoded);\n printf("%c", output);\n}\n</code></pre>\n<p>Some additional explanation:</p>\n<p>As I understand it, the <code>key</code> string (<code>argv[1]</code>) contains the character to be substituted for each letter of the alphabet. So <code>'a'</code> in the plaintext is replaced with <code>key[0]</code>, <code>'b'</code> with <code>key[1]</code>, etc.</p>\n<p>So to get the correct index in the <code>key</code> for a given character from <code>'A'</code> to <code>'Z'</code>, we need to get the distance of that character from <code>'A'</code>. Since <code>char</code> is an integer type, we can do this with some simple math: <code>plaintext[t] - 'A'</code></p>\n<p>Here <code>'A'</code> is simply another way of writing <code>65</code>. So if <code>plaintext[t]</code> is also <code>'A'</code>, we get <code>65 - 65</code>, or if <code>plaintext[t]</code> is <code>'B'</code> we get <code>66 - 65</code>. This gives us the index we need for the key.</p>\n<p><code>plaintext[t]</code> could be uppercase or lowercase. For lowercase we could get the distance from <code>'a'</code> instead, but it's easier to convert everything to uppercase and do a single comparison.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T09:31:59.750",
"Id": "495026",
"Score": "0",
"body": "Thanks for the feedback! Maintaining the case was indeed a part of the assignment and I did struggle with that. Just curious if you could explain a little more what this code is doing? Not fully wrapping my head around it (not sure if it's because i'm 11 hours into a night shift or not)\n char encoded = key[toupper(plaintext[t]) - 'A'];"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T10:30:53.723",
"Id": "495039",
"Score": "0",
"body": "Sure. Added a bit more explanation."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T08:14:57.687",
"Id": "251459",
"ParentId": "251454",
"Score": "2"
}
},
{
"body": "<p>My first suggestion is actually to remove most of the comments. Sometimes comments are useful, but when they are explaining obvious things, they just clutter the code. Also, since <code>validate</code> checks the command line arguments, I would rename it to <code>validate_args</code> and also name the arguments <code>argc</code> and <code>argv</code>.</p>\n<p>So assuming we have renamed those variables, let's continue on that function. The check for number of arguments and argument length are good as they are. So we jump to checking for only alpha characters. Your loop is too complicated. It does not need an if statement. Also, we could change the for loop a bit, since we already know that it has correct length.</p>\n<pre><code>for (int i = 0; argv[1][i] != '\\0'; i++)\n{\n if (!isalpha(v[1][i]))\n printf("Key must contain only alphabetic characters\\n");\n return 1;\n }\n}\n</code></pre>\n<p>The check for uniqueness could be made a lot simpler. I made the array bigger than 26 so that it works if you want to use more characters in future. Also changed the error message because of that.</p>\n<pre><code>int arr[256] = {0}; \nfor (int i = 0; argv[1][i] != '\\0'; i++)\n{\n if(arr[argv[1][i]] > 0)\n {\n printf("Key must contain unique characters\\n");\n return 1; \n }\n\n arr[argv[1][i]]++;\n}\n</code></pre>\n<p>You could make it shorter by removing the last line that increments the array and instead write the if statement like this: <code>if(arr[argv[1][i]]++ > 0)</code> but IMHO, that just makes it harder to read.</p>\n<p>To clarify, what's happening here is basically something that creates a histogram. You could write it like this instead:</p>\n<pre><code>int arr[256] = {0}; \nfor (int i = 0; argv[1][i] != '\\0'; i++) {\n arr[argv[1][i]]++;\n}\n\n// Now arr[n] indicates how many of character n the argument had\n\nfor(int i=0; i<sizeof arr; i++) {\n if(arr[i] > 1) {\n printf("Key must contain unique characters\\n");\n return 1; \n }\n}\n</code></pre>\n<p>And in general, avoid magic numbers. Instead of 26, declare a global constant, either with <code>#define</code> or <code>const int</code>. Sometimes you use <code>65</code> instead of <code>'A'</code>. Don't do that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T09:35:25.323",
"Id": "495030",
"Score": "0",
"body": "Thanks for the feedback! I definitely feel like I am over commenting at times but part of the assignments for CS50 is \"style\" and you get dinged for lack of comments so I often find myself just putting stuff in to make sure that doesn't happen, but I am aware that I am doing that so I guess that's a good thing? Could you explain the last part a little bit more? I'm just not fully understanding how \n\nif(arr[argv[1][i]] > 0)\n\nis checking for uniqueness"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T09:38:25.160",
"Id": "495031",
"Score": "0",
"body": "@apreynolds1989 Well, what should I say? Sometimes I am also forced to write crappy code just to meet requirements. ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T09:40:03.457",
"Id": "495032",
"Score": "0",
"body": "The `arr` is an array that counts the occurrences of characters. If you skip the return statement, you could use it to make a histogram. See my edit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T09:52:08.827",
"Id": "495035",
"Score": "0",
"body": "haha fair enough! What I am not seeing is how the arr is counting unique characters as opposed to just counting characters? If I am overlooking something plainly obvious, I blame the night shift :P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T09:55:46.087",
"Id": "495036",
"Score": "0",
"body": "@apreynolds1989 If `arr[n] > 1` that means that `n` occurs more than once. That's the definition of not unique."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T09:58:13.790",
"Id": "495037",
"Score": "0",
"body": "ooooohhh. yup, i see it now. And yup, blaming the night shift.. :P Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T10:56:04.157",
"Id": "495044",
"Score": "0",
"body": "@apreynolds1989 Hehe, no worries. Happens to me too sometimes."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T09:18:59.320",
"Id": "251462",
"ParentId": "251454",
"Score": "3"
}
},
{
"body": "<blockquote>\n<p>a more efficient way to do it?</p>\n</blockquote>\n<p><code>for</code> loop obliges 2 sequential trips through the string <code>plaintext</code>. Instead, consider one trip: iterate until the <em>null character</em> is found.</p>\n<pre><code>// for (int t = 0, len = strlen(plaintext); t < len; t++)\nfor (int t = 0); plaintext[t]; t++)\n</code></pre>\n<blockquote>\n<p>Is there something I overlooked?</p>\n</blockquote>\n<p><code>char</code> is <em>signed</em> or <em>unsigned</em>. When <em>signed</em>, it can have negatives values like -42. <code>isupper(int ch)</code> and other <code>is...()</code> functions are well defined for <code>ch</code> in the <code>unsigned char</code> range and <code>EOF</code>. Pedantic code insures the range.</p>\n<pre><code>char upper = argv[1][u];\n// int up = isupper(upper);\nint up = isupper((unsigned char) upper);\n</code></pre>\n<blockquote>\n<p>Is this good code (for a beginner)?</p>\n</blockquote>\n<p>Yes.</p>\n<p>Good use of local variables rather than all at the top of the function.</p>\n<hr />\n<p><strong>Use <code>if/else</code></strong></p>\n<pre><code> int up = isupper(upper);\n //if (up == 0) {\n // upper = toupper(upper);\n // printf("%c", upper);\n //}\n //if (up != 0) {\n // printf("%c", upper);\n //}\n if (up == 0) {\n upper = toupper(upper);\n printf("%c", upper);\n } else {\n printf("%c", upper);\n }\n</code></pre>\n<p>or</p>\n<pre><code> int up = isupper(upper);\n if (up == 0) {\n upper = toupper(upper);\n }\n printf("%c", upper);\n</code></pre>\n<p>or simply</p>\n<pre><code> // int up = isupper(upper);\n upper = toupper(upper);\n printf("%c", upper);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T00:23:45.957",
"Id": "251516",
"ParentId": "251454",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T05:53:38.177",
"Id": "251454",
"Score": "3",
"Tags": [
"c",
"encryption"
],
"Title": "Substitution Cipher in C"
}
|
251454
|
<p><a href="https://leetcode.com/problems/longest-substring-without-repeating-characters/" rel="noreferrer">Link here</a>
I'm currently learning c++ coming from a python background, so I'll include a solution in python and in c++ for the following problem statement and based on very helpful answers obtained on my previous <a href="https://codereview.stackexchange.com/questions/251403/leetcode-two-sum">question</a> I made some improvements in the c++ implementation:</p>
<blockquote>
<p>Given a string s, find the length of the longest substring without repeating characters.</p>
</blockquote>
<p><strong>Example 1:</strong></p>
<p>Input: s = "abcabcbb"
Output: 3</p>
<p><strong>Example 2:</strong></p>
<p>Input: s = "bbbbb"
Output: 1</p>
<p>I would like to improve speed for both python and c++ implementations, and I need to improve memory consumption in the c++ implementation since I got a very high figure (600+ MB) as well as the reasons for this high consumption (if the figure is accurate), and I would like general suggestions too.</p>
<p><code>longest_substring.py</code></p>
<pre><code>def get_longest(s: str):
possibilities = (s[i:] for i in range(len(s)))
maximum = 0
for possibility in possibilities:
end_idx = maximum
while end_idx <= len(possibility):
current_chunk = possibility[0:end_idx]
end_idx += 1
if not (current_size := len(current_chunk)) == len(set(current_chunk)):
break
maximum = max(current_size, maximum)
return maximum
if __name__ == '__main__':
print(f'Longest substring:\n{get_longest("abcabcbb")}')
</code></pre>
<p>Leetcode stats:</p>
<blockquote>
<p>Runtime: 260 ms, faster than 19.36% of Python3 online submissions for Longest Substring Without Repeating Characters.</p>
</blockquote>
<blockquote>
<p>Memory Usage: 14.4 MB, less than 100.00% of Python3 online submissions for Longest Substring Without Repeating Characters.</p>
</blockquote>
<p><code>longest_substring.h</code></p>
<pre><code>#ifndef LEETCODE_LONGEST_SUBSTRING_H
#define LEETCODE_LONGEST_SUBSTRING_H
#include <string>
int longest_sub(const std::string &s);
bool check_unique(const std::string &s);
#endif //LEETCODE_LONGEST_SUBSTRING_H
</code></pre>
<p><code>longest_substring.cpp</code></p>
<pre><code>#include "longest_substring.h"
#include <iostream>
using std::endl;
using std::cout;
using std::string;
bool check_unique(const string &s) {
for (size_t i = 0; i < s.size() - 1; ++i) {
for (size_t j = i + 1; j < s.size(); ++j) {
if (s[i] == s[j])
return false;
}
}
return true;
}
int longest_sub(const string &s) {
int maximum = 0;
for (size_t i = 0; i < s.size(); ++i) {
const string possibility = s.substr(i);
auto end_idx = maximum;
while (end_idx < possibility.size()) {
const string current_chunk = possibility.substr(0, ++end_idx);
if (!check_unique(current_chunk))
break;
auto current_size = current_chunk.size();
if (current_size > maximum)
maximum = current_size;
}
}
return maximum;
}
int main() {
cout << "Longest substring: " << endl;
cout << longest_sub("abcabcbb");
}
</code></pre>
<p>Leetcode stats:</p>
<blockquote>
<p>Runtime: 100 ms, faster than 14.88% of C++ online submissions for Longest Substring Without Repeating Characters.</p>
</blockquote>
<blockquote>
<p>Memory Usage: 604.2 MB, less than 5.02% of C++ online submissions for Longest Substring Without Repeating Characters.</p>
</blockquote>
|
[] |
[
{
"body": "<h1>Complexity</h1>\n<p>Your solution has <a href=\"https://en.wikipedia.org/wiki/Time_complexity\" rel=\"noreferrer\">time complexity</a> <span class=\"math-container\">\\$\\mathcal{O}(N^4)\\$</span>, which is very bad. There is a <span class=\"math-container\">\\$\\mathcal{O}(N)\\$</span> solution for this problem. Consider for example the string:</p>\n<pre><code>abcdecfghij\n</code></pre>\n<p>Instead of taking substrings and checking if the substring has duplicates, instead keep track of the last position seen for any possible character. This is basically an array of 256 ints, which you should initialize to -1 to indicate that you've never seen the character before. Then, iterate over the string character by character, and check if the character you look at has already been seen. If not, update its position in the array. So after processing <code>abcde</code>, you will have <code>a = 0, b = 1, c = 2, d = 3, e = 4</code> and the rest is still <code>-1</code>. Then when you encounter <code>c</code> again, you know you have a duplicate. But instead of starting over from the second character of the string, you should start instead from the character right after the first <code>c</code>, so at position 3. And you know you already have a valid substring up to and including the second <code>c</code>. So then you can continue from there. You continue until you find a character with a recorded position that is equal to or more than the starting position of the current substring. Here is a possible implementation in C++:</p>\n<pre><code>#include <array>\n#include <utility>\n\nint longest_sub(const std::string &s) {\n std::array<int, 256> last_positions;\n last_positions.fill(-1);\n\n int min_position = 0;\n int maximum_length = 0;\n\n for (size_t i = 0; i < s.size(); ++i) {\n int &last_position = last_positions[static_cast<unsigned char>(s[i])];\n\n if (last_position >= min_position) {\n // We encountered a duplicate\n min_position = last_position + 1;\n }\n\n maximum_length = std::max(maximum_length, int(i + 1 - min_position));\n last_position = i;\n }\n\n return maximum_length;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T10:20:13.040",
"Id": "495038",
"Score": "2",
"body": "I don't know how they calculate memory usage. I don't see your code having any memory leaks, so it shouldn't use that much."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T16:36:45.907",
"Id": "495088",
"Score": "2",
"body": "I think you mean `a = 0, b = 1, c = 2, d = 3, e = 4`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T20:49:01.220",
"Id": "495125",
"Score": "0",
"body": "Btw, you really should consider [`std::string_view`](https://en.cppreference.com/w/cpp/string/basic_string_view) for the argument."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T21:03:40.343",
"Id": "495126",
"Score": "1",
"body": "@Deduplicator The API is determined by LeetCode in this case, but otherwise you would be right."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T21:10:08.260",
"Id": "495127",
"Score": "2",
"body": "Those top-coder, elite-coder, coding-challenge and assorted sites really get on my nerves with all their ante-diluvian super-pessimized code which nobody in their right mind ever thought barely adequate. And it just keeps coming. Still, as you restricted yourself to the big picture, I took the litte details."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T21:12:58.080",
"Id": "495128",
"Score": "1",
"body": "@Deduplicator Thanks, you have some excellent additions! I'm already glad that no `<bits/stdc++.h>` were `#include`d in OP's post."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T21:48:49.670",
"Id": "495138",
"Score": "0",
"body": "@Deduplicator I don't like these coding challenges because they are not realistic and most of the questions are testing you for things that are not very useful in real life, I learned that one day when I was starting to learn python, I kept solving project Euler problems one by one, after a while specially when I started to write some useful code, I realized that you get the actual useful experience from practicing real world problems. However they are good when you're new to some language and you don't want to go hardcore on day1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T21:50:33.860",
"Id": "495140",
"Score": "0",
"body": "@G.Sliepen What does this expression do? `last_positions[static_cast<unsigned char>(s[i])]`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T22:14:40.040",
"Id": "495146",
"Score": "1",
"body": "@bullseye: it gets the element in the array `last_positions[]` at the index given by the character `s[i]`. You have to cast `s[i]` to an `unsigned char`, because a `char` might be signed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T11:49:04.100",
"Id": "495205",
"Score": "0",
"body": "Minor performance improvement: halve the memory usage of the `last_positions` array by using `uin16_t` elements instead of `int` (the linked problem assures that \"`0 <= s.length <= 5 * 10^4`\"). You'll then need an unsigned alternative for the -1 default, so just have the array hold 1-indexed positions instead of 0-indexed positions: that way you can just zero-initialize the array (`= {};`) instead of calling `.fill()` at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T12:14:58.857",
"Id": "495207",
"Score": "0",
"body": "@Will I'm not sure it will make much of a difference; even with `int`s the array only takes up 1 kilobyte, which should have no trouble fitting into the L1 cache of the CPU. Maybe you win some by using a zero-filled array, but lose some by having to add 1 to the indices. A micro-optimization like this should be benchmarked to see if it really helps."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T18:53:52.167",
"Id": "495244",
"Score": "0",
"body": "@G.Sliepen \"it gets the element in the array `last_positions[]` at the index given by the character `s[i]`\" I don't get the meaning of index given by a character, ex: `s[0]` for `s` being `\"abc\"` is `'a'` what I don't understand is that `last_positions[]` is indexed using normal indices (0, 1, 2 ...) as well as characters ('a') in that case, does this imply the ascii order? (97 for `'a'` respectively) or there is something I don't understand?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T21:19:08.693",
"Id": "495265",
"Score": "0",
"body": "@bullseye: each character has a numerical value. On almost all systems, they indeed follow the ASCII order, at least for values between 0 and 127."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T08:39:47.723",
"Id": "251460",
"ParentId": "251458",
"Score": "12"
}
},
{
"body": "<p><a href=\"/u/129343\">G. Sliepen</a> already took care of the big picture issues, where you get the most bang for the buck.</p>\n<p>Still, there are a few issues with the code aside from using a sub-optimal algorithm:</p>\n<ol>\n<li><p>You should consider <a href=\"https://en.cppreference.com/w/cpp/string/basic_string_view\" rel=\"nofollow noreferrer\"><code>std::string_view</code></a> for the string-argument, and for getting a temporary slice of a long-lived string.<br />\nDynamic allocation is pretty expensive, and best avoided, both on calling a function if the input might not be in the desired format, and in the function itself.<br />\nSee "<em><a href=\"//stackoverflow.com/questions/20803826/what-is-string-view\">What is <code>string_view</code>?</a></em>" and "<em><a href=\"//stackoverflow.com/questions/40127965/how-exactly-is-stdstring-view-faster-than-const-stdstring\">How exactly is <code>std::string_view</code> faster than <code>const std::string&</code>?</a></em>" for more details.</p>\n</li>\n<li><p>Now that the functions no longer allocate memory, or contain any other potential exception-thrower, mark them <code>noexcept</code> so everyone knows (and the compiler enforces) that it won't throw. It won't do much of anything here, but is good documentation, informs the compiler if it only knows the declaration, and can be important later with using templated code consuming it for best performance and highest exception-safety guarantees.</p>\n</li>\n<li><p>Also, mark them <code>constexpr</code> while you are at it, to allow use in constant expression, and encourage evaluation at compile-time. That is also a best-practice thing not actually changing much of anything for your example program itself.</p>\n</li>\n<li><p>You use <code>std::cout</code> twice (whyever you don't push all the output into it in a single expression escapes me there, but that can be argued either way), and <code>std::endl</code> once. Writing (and keeping in mind) those two using-declarations costs more than prefixing the uses with <code>std::</code>. Even if you really dislike writing <code>std::</code>, you don't write it less often.</p>\n</li>\n<li><p>Don't force flushing a stream unless you really mean it, as it flushes performance down the drain. <code>std::endl</code> outputs a newline and then flushes, <code>stream << std::endl</code> being exactly equivalent to <code>stream << '\\n' << std::flush</code>. Thus if you really have to, better be explicit and use <code>std::flush</code>.<br />\nSee "<em><a href=\"//stackoverflow.com/questions/5492380/what-is-the-c-iostream-endl-fiasco\">What is the C++ iostream <code>endl</code> fiasco?</a></em>" for more detail.</p>\n</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T21:07:19.643",
"Id": "251506",
"ParentId": "251458",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "251460",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T07:55:02.857",
"Id": "251458",
"Score": "8",
"Tags": [
"python",
"c++",
"programming-challenge"
],
"Title": "Leetcode longest substring without repeating characters"
}
|
251458
|
<p><a href="https://leetcode.com/problems/insert-delete-getrandom-o1/" rel="nofollow noreferrer">https://leetcode.com/problems/insert-delete-getrandom-o1/</a></p>
<p>please comment on performance</p>
<blockquote>
<p>Implement the RandomizedSet class:</p>
<p>bool insert(int val) Inserts an item val into the set if not present.
Returns true if the item was not present, false otherwise. bool
remove(int val) Removes an item val from the set if present. Returns
true if the item was present, false otherwise. int getRandom() Returns
a random element from the current set of elements (it's guaranteed
that at least one element exists when this method is called). Each
element must have the same probability of being returned. Follow up:
Could you implement the functions of the class with each function
works in average O(1) time?</p>
<p>Example 1:</p>
<p>Input ["RandomizedSet", "insert", "remove", "insert", "getRandom",
"remove", "insert", "getRandom"] [[], [1], [2], [2], [], [1], [2], []]
Output [null, true, false, true, 2, true, false, 2]</p>
<p>Explanation RandomizedSet randomizedSet = new RandomizedSet();
randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1
was inserted successfully. randomizedSet.remove(2); // Returns false
as 2 does not exist in the set. randomizedSet.insert(2); // Inserts 2
to the set, returns true. Set now contains [1,2].
randomizedSet.getRandom(); // getRandom() should return either 1 or 2
randomly. randomizedSet.remove(1); // Removes 1 from the set, returns
true. Set now contains [2]. randomizedSet.insert(2); // 2 was already
in the set, so return false. randomizedSet.getRandom(); // Since 2 is
the only number in the set, getRandom() will always return 2.</p>
<p>Constraints:</p>
<p><span class="math-container">\$-2^{31} <= val <= 2^{31} - 1\$</span>. At most <span class="math-container">\$10^5\$</span> calls will be made to insert, remove, and getRandom. There will be at least one element in the data
structure when getRandom is called.</p>
</blockquote>
<pre><code>public class RandomizedSet {
private HashSet<int> _set;
/** Initialize your data structure here. */
public RandomizedSet()
{
_set = new HashSet<int>();
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
public bool Insert(int val)
{
if (_set.Contains(val))
{
return false;
}
_set.Add(val);
return true;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
public bool Remove(int val)
{
if (_set.Contains(val))
{
_set.Remove(val);
return true;
}
return false;
}
/** Get a random element from the set. */
public int GetRandom()
{
Random rand = new Random();
int key = rand.Next(_set.Count);
return _set.ElementAt(key);
}
}
/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet obj = new RandomizedSet();
* bool param_1 = obj.Insert(val);
* bool param_2 = obj.Remove(val);
* int param_3 = obj.GetRandom();
*/
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>The <code>HashSet<int></code> won't be changed hence make it <code>readonly</code>.</li>\n<li>Instead of calling <code>Contains()</code> prior to the call to <code>Add()</code>, if this evaluates to <code>false</code>, can be simplified to just <code>return _set.Add(val);</code> because the <code>Add()</code> method returns <code>false</code> if the value is allready in the <code>HashSet</code>. <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1.add?view=netcore-3.1\" rel=\"noreferrer\">Reference</a></li>\n<li>Instead of calling <code>Contains()</code> prior to calling <code>Remove()</code> can be simplified as well to just <code>return _set.Remove(val);</code> because <code>Remove()</code> will return <code>false</code> if the item isn't in the <code>HashSet</code>. <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1.remove?view=netcore-3.1\" rel=\"noreferrer\">Reference</a></li>\n<li>Calling <code>GetRandom()</code> in repeatedly short order may result in the same element because the <code>Seed</code> of a created <code>Random</code> in .NET framework is based on the current timestamp. It is better to create a class-level <code>Random</code> to be used.</li>\n</ul>\n<p>Summing up leads to</p>\n<pre><code>public class RandomizedSet {\n \n private readonly HashSet<int> _set;\n /** Initialize your data structure here. */\n public RandomizedSet()\n {\n _set = new HashSet<int>();\n }\n\n /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */\n public bool Insert(int val)\n {\n return _set.Add(val);\n }\n\n /** Removes a value from the set. Returns true if the set contained the specified element. */\n public bool Remove(int val)\n {\n return _set.Remove(val);\n }\n\n private readonly Random rand = new Random();\n /** Get a random element from the set. */\n public int GetRandom()\n {\n int key = rand.Next(_set.Count);\n return _set.ElementAt(key);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T10:19:55.440",
"Id": "251466",
"ParentId": "251464",
"Score": "6"
}
},
{
"body": "<h2><code>GetRandom()</code> Complexity</h2>\n<p><code>HashSet<T></code> does not support lookup by index so <code>ElementAt</code> needs to iterate until the requested element is reached. That requires O(n) steps not O(1).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T10:09:24.077",
"Id": "251533",
"ParentId": "251464",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "251466",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T09:55:07.137",
"Id": "251464",
"Score": "4",
"Tags": [
"c#",
"interview-questions"
],
"Title": "LeetCode: Insert delete getrandom o1 C#"
}
|
251464
|
<p>I've been working on a little challenge in order to learn more.. I've written the following code, which works. I'm just concerned that there are several areas where my lack of in depth Python knowledge has forced me to 'go the long way around'. I'm really keep to learn more and learn in the correct way, so looking for areas I can improve the code & also shorten it where possible.</p>
<p>The idea is, we use a free API to obtain some JSON data containing a list of dates and stock price information. The JSON gives a 'refreshed date' which is the latest date the data has been obtained, I'm then calculating a list of <em>N</em> dates PRIOR to this date, and returning the stock close price for each of those past days, and then returning the average of those prices.</p>
<p>The code works, and I'm quite happy of that.. but I don't want to stop here. I want to make sure I'm learning the right way.</p>
<p>Since the stock market is closed on Sat/Sun, we need to avoid weekends when calculating the list of dates, so N=3 on a Monday, would be 3 'stock market' days prior to Monday, thus - Mon, Fri, Thu.</p>
<p>For anyone who is interested in looking at the format of data being read in there's a demo API key: <a href="https://www.alphavantage.co/query?apikey=demo&function=TIME_SERIES_DAILY_ADJUSTED&symbol=MSFT" rel="nofollow noreferrer">https://www.alphavantage.co/query?apikey=demo&function=TIME_SERIES_DAILY_ADJUSTED&symbol=MSFT</a></p>
<p>CODE:</p>
<pre><code>from datetime import date, timedelta, datetime
import json
from requests import Request, Session
from flask import Flask, make_response
app = Flask(__name__)
# To be passed in with ENV-Vars
SYMBOL='MSFT'
NDAYS = 3
api_key = 'apikey="XXXXXXXX"&'
function = 'function=TIME_SERIES_DAILY_ADJUSTED&'
symbol = f'symbol={SYMBOL}'
url = f'https://www.alphavantage.co/query?{api_key}{function}{symbol}'
session = Session()
output = session.get(url)
data = json.loads(output.text)
refreshed = datetime.strptime(str(data['Meta Data']['3. Last Refreshed']), '%Y-%m-%d').date()
dates = []
output = {}
def prev_days(rdate):
rdate -= timedelta(days=NDAYS)
while rdate.weekday() > 4:
rdate -= timedelta(days=1)
return rdate
past_date = prev_days(refreshed)
delta = refreshed - past_date
for i in range(delta.days + 1):
dates.append(refreshed - timedelta(days=i))
for date in dates:
close = data['Time Series (Daily)'][str(date)]['4. close']
output.update({str(date): float(close)})
avg = sum(list(output.values())) / len(list(output.values()))
def resp():
return f'{SYMBOL} data={list(output.values())}, average={avg}'
@app.route('/')
def main():
response = make_response(resp(), 200)
response.mimetype = "text/plain"
return response
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5000)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T11:09:10.567",
"Id": "495045",
"Score": "3",
"body": "Whoever thought of `\"1. open\"` as response structure is definitely not developer friendly."
}
] |
[
{
"body": "<h2>Relays</h2>\n<p>Your current design:</p>\n<ul>\n<li>fetches data from alphavantage once, on startup</li>\n<li>offers it to anyone who hits any of your interfaces on port 5000 (which, by the way, is already used by a <a href=\"https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Registered_ports\" rel=\"nofollow noreferrer\">large number of services</a> other than the default Flask development webserver)</li>\n</ul>\n<p>This seems unusual. Perhaps it's just to try out a random use of Flask for learning purposes, which is fine, but:</p>\n<p>If you really want to preserve this API as an effective relay, it should probably be authenticated. You can add that here, or in a frontend (nginx, etc). Also, just bind to 80 once you hit production. A frontend can do HTTPS termination effectively translating from 443 to 80.</p>\n<p>If all you want is code to conveniently get alphavantage data, don't make your own HTTP API; just make a <code>requests</code> wrapper library.</p>\n<h2>Globals</h2>\n<blockquote>\n<p>To be passed in with ENV-Vars</p>\n</blockquote>\n<p>should apply to <code>api_key</code>, as that's a secret that should not be hard-coded.</p>\n<p>Also, it's an odd choice to hard-code <code>symbol</code>. With very little introduced complexity, you can make your code parametric on symbol (and perhaps also <code>function</code>).</p>\n<p>Otherwise: <code>session</code>, <code>output</code>, <code>data</code>, etc. probably shouldn't be globals. Consider making an LRU cache for <code>data</code>, and taking advantage of Flask's <code>before_first_request</code>, and moving the great majority of your global code into functions.</p>\n<p>For <code>session</code> in particular, there's currently no advantage to having that - you might as well just <code>requests.get</code> since you only do it once.</p>\n<h2>Request formation</h2>\n<p>Don't pre-format key-value query parameter pairs. Instead,</p>\n<pre><code>session.get(\n 'https://www.alphavantage.co/query',\n params={\n 'apikey': API_KEY,\n 'function': 'TIME_SERIES_DAILY_ADJUSTED',\n 'symbol': 'MSFT',\n },\n)\n</code></pre>\n<h2>Response parsing</h2>\n<pre><code>json.loads(output.text)\n</code></pre>\n<p>is unnecessary. Just use <code>output.json</code>. Also, between <code>get()</code> and <code>.json</code>, call <code>output.raise_for_status</code>. This will increase the quality of error information when something goes wrong.</p>\n<h2>Sum over an iterable</h2>\n<pre><code>sum(list(output.values()))\n</code></pre>\n<p>should not use <code>list</code>. <code>sum</code> can operate on any iterable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T20:15:03.783",
"Id": "251498",
"ParentId": "251469",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "251498",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T10:58:35.073",
"Id": "251469",
"Score": "3",
"Tags": [
"python",
"flask"
],
"Title": "Flask app to return close prices & average"
}
|
251469
|
<p>I had an interview task which was the final stage, however, the feedback I got back for my solution was that it <em><code>lacked effort and structure</code></em>. I would be grateful to know how my solution could be improved. I used postcode.io to get the latitude and longitude from the post codes.</p>
<p>Here is the Description:</p>
<blockquote>
<p><strong>Brief:</strong> Create a server application that allows a user to input one or more postcodes, and then returns location-specific information
based on the postcode entered.</p>
<p><strong>Requirements:</strong> At least one of the external APIs made available to you should be used to retrieve the information that your API returns.
You are not limited to using only one, and are free to use as many of
them as you like (inc. any other external resources) in order to
provide useful data.</p>
</blockquote>
<p>Based on the above I made the following program.</p>
<p><strong>app.js</strong></p>
<pre><code>import * as express from "express";
import * as axios from "axios";
const app = express();
app.use(express.json());
app.get("/", (req, res) => {
res.send("Server is up and running ");
});
app.get("/postcode/:postcode", async (req, res) => {
const postcode = req.params.postcode;
await getLatlonFromPostcode(postcode).then((data) => {
res.send(data);
});
});
app.post("/postcodes", async (req, res) => {
const postCodes = req.body.postcodes;
const result = await getAdressForMultiplePostCodes(postCodes).then(
(response) => {
return returnLatLonObj(response.result);
}
);
res.json(result);
});
//Return the lat and lon for a single postcode
export async function getLatlonFromPostcode(postcode) {
try {
const res = await axios
.get(`https://api.postcodes.io/postcodes/${postcode}`)
.then((response) => {
const lat = response.data.result.latitude.toString();
const lon = response.data.result.longitude.toString();
return `${lat}, ${lon}`;
});
return res;
} catch (error) {
console.error(error);
}
}
//Return array of addresses from Postcode array
export async function getAdressForMultiplePostCodes(postcodes) {
try {
const res = await axios
.post("https://api.postcodes.io/postcodes", {
postcodes,
})
.then((response) => {
return response.data;
});
return res;
} catch (error) {
console.error(error);
}
}
//Grab Latitude and Longitude and convert Array to object
function returnLatLonObj(arr) {
return arr.reduce((prev, curr) => {
prev[curr.result.latitude] = curr.result.longitude;
return prev;
}, {});
}
export default app;
</code></pre>
<p>This is my <strong>index.js</strong></p>
<pre><code>import app from "./app";
app.listen(3000, () => {
console.log("server listening on port 3000");
})
</code></pre>
<p>This was my test file, which I used jest for.</p>
<pre><code>import { getLatlonFromPostcode } from "../app";
describe("getLatlonFromPostcode", () => {
test("it should return latlon for given postcode", async () => {
const latlon = await getLatlonFromPostcode("ox495nu");
expect(latlon).toEqual("51.655929, -1.069752");
});
});
describe("getLatlonFromPostcode in uppercase", () => {
test("it should return latlon for given postcode", async () => {
const latlon = await getLatlonFromPostcode("OX49 5NU");
expect(latlon).toEqual("51.655929, -1.069752");
});
});
describe("getLatlonFromPostcode with spaces between the postcode", () => {
test("it should return latlon for given postcode", async () => {
const latlon = await getLatlonFromPostcode("OX49 5NU");
expect(latlon).toEqual("51.655929, -1.069752");
});
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T13:48:48.517",
"Id": "495059",
"Score": "1",
"body": "The reasons given for not getting a job are seldom the reasons for not getting the job. \"lacked effort and structure\" is hog wash. You clearly put in effort. 50 line of working code a day is considered the mainstream average, Counting 82 lines is the better part of 2 days effort, And \"structured?\" without a design doc and code quality guides your code can not be judged on a subjective property like its structure. HR skills of most companies are poor to very poor. Unfortunately in the end you were likely but one of many forms with required fields.that needed submitting to complete a task."
}
] |
[
{
"body": "<h2>Test case structure</h2>\n<p>It doesn't seem like the code totally "<em>lacked effort and structure</em>" but the structure, at least of the test cases, could be better. Since all three <code>describe()</code> blocks contain a test that calls <code>getLatlonFromPostcode</code> so there could be a single <code>describe()</code> block with three <code>it()</code> blocks to test the various aspects of how the function should handle given postcodes.</p>\n<h2>Utilizing <code>await</code></h2>\n<p>One of the main benefits of using <code>await</code> is to eliminate the need for callbacks to <code>.then()</code>. Some code utilizes this benefit e.g. the test functions but the methods in app.js do not - e.g.</p>\n<blockquote>\n<pre><code>await getLatlonFromPostcode(postcode).then((data) => {\n res.send(data);\n});\n</code></pre>\n</blockquote>\n<p>Ideally, the <code>res.send()</code> call would be on a sequential line instead of in a <code>.then()</code> callback function:</p>\n<pre><code>const data = await getLatlonFromPostcode(postcode);\nres.send(data);\n</code></pre>\n<p>Or even simpler:</p>\n<pre><code>res.send(await getLatlonFromPostcode(postcode));\n</code></pre>\n<h2>Error handling</h2>\n<p>As an interviewer I would be checking to see how well the code handles edge cases. Obviously with promises comes rejection. The first couple methods don't appear to handle rejected promises at all.</p>\n<h2>Import Star</h2>\n<p>The two <code>import</code> statements import everything from the modules being imported. In the <a href=\"https://github.com/airbnb/javascript#modules--no-wildcard\" rel=\"nofollow noreferrer\">Airbnb style guide</a>, it recommends no wildcards:</p>\n<blockquote>\n<p>Why? This makes sure you have a single default export.<sup><a href=\"https://github.com/airbnb/javascript#modules--no-wildcard\" rel=\"nofollow noreferrer\">1</a></sup></p>\n</blockquote>\n<p>The import for <code>axios</code> could be simplified using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment\" rel=\"nofollow noreferrer\">destructuring assignment</a>:</p>\n<pre><code>import { get, post} from "axios";\n</code></pre>\n<p>That way the code can call <code>get()</code> and <code>post()</code> without needing to reference axios, and the other items exported from axios that are not needed are not imported.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T15:25:59.593",
"Id": "251477",
"ParentId": "251470",
"Score": "5"
}
},
{
"body": "<p>The code could be improved with a few tweaks, but it's not bad, and the overall structure looks just fine to me.</p>\n<p><strong>Error handling is in the wrong place</strong> Some of your route handler are <code>async</code>, and inside them you <code>await</code>. Whenever you have a Promise, make sure to handle possible errors properly. Although the functions outside of your router handlers handle errors - they'll never return Promises that reject - it's a bit of a code smell to rely on the called functions to never reject; if you accidentally use a function which <em>does</em> return a Promise that rejects, Express won't be able to handle the rejection inside the route handler, and you'll get an UnhandledRejection, which will either terminate the server process completely, or display a warning message that unhandled rejections are deprecated.</p>\n<p>When a Promise rejects, don't just log the error, but also send a response to the user indicating that there was an unexpected error. The error handling should be in the <em>route handlers</em>, not in the functions it's calling.</p>\n<p><strong><code>async</code> shines only with nested Promises</strong> On a similar note, <code>async</code> functions and the <code>try { await ... } catch(e) {}</code> they require for error handling is a reasonable amount of boilerplate. If all you have is a <em>single</em> Promise, consider just using <code>.then</code> and <code>.catch</code> instead.</p>\n<p>A rule of thumb I like: would an <code>async</code> function use at least two <code>await</code>s? Then it's probably worth it. Otherwise, it might not be.</p>\n<p>For example, <code>/postcode/:postcode</code> could be:</p>\n<pre><code>app.get("/postcode/:postcode", (req, res) => {\n // Destructure for conciseness:\n const { postcode } = req.params;\n // Changed name from Latlon to LatLon - "Latlon" is not a single word\n // so use proper CamelCase instead\n getLatLonFromPostcode(postcode)\n .then((data) => {\n res.send(data);\n })\n .catch((error) => {\n console.error(error);\n res.status(500).json({ error: error.message });\n });\n});\n</code></pre>\n<p>and <code>getLatLonFromPostcode</code> can be:</p>\n<pre><code>//Return the lat and lon for a single postcode\nexport function getLatLonFromPostcode(postcode) {\n return axios.get(`https://api.postcodes.io/postcodes/${postcode}`)\n .then((response) => {\n const { latitude, longitude } = response.data;\n return `${latitude}, ${longitude}`;\n });\n}\n</code></pre>\n<p>letting the <em>caller</em> handle possible errors. Also note the use of destructuring for conciseness, and since string interpolation with <code>${}</code> will automatically coerce the interpolated expressions to strings, there's no need to call <code>toString</code> explicitly.</p>\n<p>You can follow the same pattern for the <code>/postcodes</code> route.</p>\n<p><strong>Spelling</strong> Misspelled variables and properties, or inconsistent capitalization, are a frequent source of bugs. Change <code>getAdressForMultiplePostCodes</code> to <code>getAddressForMultiplePostcodes</code> (Since <code>postcodes</code> is one word in the request, it should also probably appear as one word here - if you use <code>PostCodes</code>, the inconsistent capitalization could make things harder than they should be)</p>\n<p><strong>Groupby into object with <code>Object.fromEntries</code></strong> Your <code>returnLatLonObj</code> can be improved:</p>\n<ul>\n<li>First, <code>.reduce</code> arguably isn't very appropriate when the accumulator is the same object across all iterations. It <em>works</em>, but it can be a bit verbose and confusing. See <a href=\"https://www.youtube.com/watch?v=qaGjS7-qWzg\" rel=\"nofollow noreferrer\">this video</a> by V8 developers on the subject.</li>\n<li>Second, if you want to turn an array into an object whose keys are properties of the array items, you can do it quite concisely with <code>Object.fromEntries</code>:</li>\n</ul>\n<pre><code>function returnLatLonObj(arr) {\n return Object.fromEntries(\n arr.map(({ result: { latitude, longitude }) => [latitude, longitude])\n );\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T15:42:21.950",
"Id": "251480",
"ParentId": "251470",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "251480",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T11:31:46.540",
"Id": "251470",
"Score": "7",
"Tags": [
"javascript",
"node.js",
"interview-questions",
"express.js",
"axios"
],
"Title": "Take postcodes and get the Lat long information from them"
}
|
251470
|
<h1><a href="https://github.com/Zoran-Jankov/File-Removal-PowerShell-Script" rel="nofollow noreferrer">File Removal PowerShell Script</a></h1>
<h2>Introduction</h2>
<p>I have created a <em>File Removal PowerShell Script</em> that can be configured to remove files on various ways. I would like your opinions an suggestion on my scrip so I can improve the script, and to improve my PowerShell skills. I will non post the whole code of my scrip in this post, just the main body of the script, and links to the function used by this script.</p>
<h2>Description</h2>
<p>This script removes defined files from targeted folders. It is meant to be used by System Administrators, because it has many options and settings that can be configured to remove files in multiple and various ways. All data regarding file removal, target folders, file names, optional number of days files must be older then to be removed, if files in subfolders should be removed, and if files should be force removed, are written by user in <a href="https://github.com/Zoran-Jankov/File-Removal-PowerShell-Script/blob/master/Data.csv" rel="nofollow noreferrer"><code>Data.csv</code></a> file. User can enter partial names of files in <code>FileName</code> column with a wildcard character, for example <code>*.dat</code> or <code>Backup*</code>. Script generates detailed log file, and report that is sent via email. In <a href="https://github.com/Zoran-Jankov/File-Removal-PowerShell-Script/blob/master/Settings.cfg" rel="nofollow noreferrer"><code>Settings.cfg</code></a> file parameters are stored for email settings, and options to turn on or off console writing, loging, and email report as the user requires them.</p>
<h2>Usage</h2>
<p>Before running <em>File Removal PowerShell Script</em> user must configure the script settings in <a href="https://github.com/Zoran-Jankov/File-Removal-PowerShell-Script/blob/master/Settings.cfg" rel="nofollow noreferrer"><code>Settings.cfg</code></a> file, and the data feeding the script must be entered in <a href="https://github.com/Zoran-Jankov/File-Removal-PowerShell-Script/blob/master/Data.csv" rel="nofollow noreferrer"><code>Data.csv</code></a> file.</p>
<h3>Settings</h3>
<p><em>File Removal PowerShell Script</em> can be configured in <a href="https://github.com/Zoran-Jankov/File-Removal-PowerShell-Script/blob/master/Settings.cfg" rel="nofollow noreferrer"><code>Settings.cfg</code></a> file to write output to console, write permanent log and to send email when it is finished running. Email settings, log title and log separator are also configured in <a href="https://github.com/Zoran-Jankov/File-Removal-PowerShell-Script/blob/master/Settings.cfg" rel="nofollow noreferrer"><code>Settings.cfg</code></a> file.</p>
Settings parameters
<ul>
<li><strong><code>LogTitle</code></strong> - Define a string to be a title in logs</li>
<li><strong><code>LogSeparator</code></strong> - Define a string to be a separator in logs for clearer visibility</li>
<li><strong><code>WriteTranscript</code></strong> - Set to <em><strong>true</strong></em> if writing transcript to console is wanted</li>
<li><strong><code>WriteLog</code></strong> - Set to <em><strong>true</strong></em> if writing a permanent log is wanted</li>
<li><strong><code>SendReport</code></strong> - Set to <em><strong>true</strong></em> if sending a report via email log is wanted</li>
<li><strong><code>LogFile</code></strong> - Relative path to permanent log file</li>
<li><strong><code>ReportFile</code></strong> - Relative path to report log file</li>
<li><strong><code>SmtpServer</code></strong> - SMPT server name</li>
<li><strong><code>Port</code></strong> - SMPT port (<em>25/465/587</em>)</li>
<li><strong><code>To</code></strong> - Email address to send report log to</li>
<li><strong><code>From</code></strong> - Email address to send report log form</li>
<li><strong><code>Subject</code></strong> - Subject of the report log email</li>
<li><strong><code>Body</code></strong> - Body of the report log email</li>
</ul>
<h3>Data</h3>
<p>In <a href="https://github.com/Zoran-Jankov/File-Removal-PowerShell-Script/blob/master/Data.csv" rel="nofollow noreferrer"><code>Data.csv</code></a> user enters target folders, target files and optionally number of days to remove files older than that.</p>
Data parameters
<ul>
<li><p><strong><code>FolderPath</code></strong> - In this column write the full path of the folder in which files are to be removed.</p>
<ul>
<li><em><strong>Example:</strong></em> <em>C:\Folder\Folder\Folder</em></li>
</ul>
</li>
<li><p><strong><code>FileName</code></strong> - In this column write the name of the file which is to be removed. It can include a wild card character <strong><code>*</code></strong> so multiple files can be affected.</p>
<ul>
<li><em><strong>Example:</strong></em> * (Remove all files in target folder)</li>
<li><em><strong>Example:</strong></em> <em>Cache.bat</em> (Remove only the file named "Cache.bat")</li>
<li><em><strong>Example:</strong></em> *<em>.bmp</em> (Remove all files with ".bmp" extension)</li>
<li><em><strong>Example:</strong></em> <em>Backup</em>* (Remove all files with name starting with "Backup")</li>
</ul>
</li>
<li><p><strong><code>OlderThen</code></strong> - In this column write the number of days to remove files older than that in integer format</p>
<ul>
<li><em><strong>Example:</strong></em> <em>180</em> (Remove all files older than six months)</li>
<li><em><strong>Example:</strong></em> <em>0</em> (Remove all files regardless of file creation time)</li>
</ul>
</li>
<li><p><strong><code>Recurse</code></strong> - In this column enter <em><strong>true</strong></em> if file removal in subfolders is required.</p>
<ul>
<li><em><strong>Example:</strong></em> <em>true</em> (Remove all files even in subfolders of the target folder)</li>
<li><em><strong>Example:</strong></em> <em>false</em> (No files in subfolders of the target folder will be removed)</li>
</ul>
</li>
<li><p><strong><code>Force</code></strong> - In this column enter <em><strong>true</strong></em> if force removal of files is required.</p>
<ul>
<li><em><strong>Example:</strong></em> <em>true</em> (Force remove all selected files)</li>
<li><em><strong>Example:</strong></em> <em>false</em> (Selected files will not be removed by force)</li>
</ul>
</li>
</ul>
<p>All of the data parameters are taken in account while script is calculating which files will be removed. This is very convenient because it is possible to target multiple folders with different rulers for file removal with a single script.</p>
<h2>The Script</h2>
<pre><code>#Loading script data and settings
$Data = Import-Csv -Path "$PSScriptRoot\Data.csv" -Delimiter ';'
$Settings = Get-Content -Path "$PSScriptRoot\Settings.cfg" | ConvertFrom-StringData
#File counters
$TotalSuccessfulRemovalsCounter = 0
$TotalFailedRemovalsCounter = 0
$TotalContentRemoved = 0
Import-Module "$PSScriptRoot\Modules\Get-FormattedFileSize.psm1"
Import-Module "$PSScriptRoot\Modules\Remove-Files.psm1"
Import-Module "$PSScriptRoot\Modules\Send-EmailReport.psm1"
Import-Module "$PSScriptRoot\Modules\Write-Log.psm1"
Write-Log -Message $Settings.LogTitle -NoTimestamp
Write-Log -Message $Settings.LogSeparator -NoTimestamp
#Formating data to fit expected parameters in `Remove-Files` function
$Data | ForEach-Object -Process {
if ($_.OlderThen -match "^\d+$") {
$_.OlderThen = [int]$_.OlderThen
}
else {
$_.OlderThen = [int]180
}
if ($_.Recurse -eq "true") {
$_.Recurse = $true
}
else {
$_.Recurse = $false
}
if ($_.Force -eq "true") {
$_.Force = $true
}
else {
$_.Force = $false
}
}
$Data | Remove-Files | ForEach-Object {
$TotalContentRemoved += $_.FolderSpaceFreed
$TotalSuccessfulRemovalsCounter += $_.FilesRemoved
$TotalFailedRemovalsCounter += $_.FailedRemovals
}
if ($TotalSuccessfulRemovalsCounter -gt 0) {
$SpaceFreed = Get-FormattedFileSize -Size $TotalContentRemoved
$Message = "Successfully removed " + $TotalSuccessfulRemovalsCounter + " files - removed " + $SpaceFreed
Write-Log -Message $Message
}
if ($TotalFailedRemovalsCounter -gt 0) {
$Message = "Failed to remove " + $TotalFailedRemovalsCounter + " files"
Write-Log -Message $Message
}
if (($TotalSuccessfulRemovalsCounter -gt 0) -and ($TotalFailedRemovalsCounter -eq 0)) {
$FinalMessage = "Successfully completed - File Removal PowerShell Script"
}
elseif (($TotalSuccessfulRemovalsCounter -gt 0) -and $TotalFailedRemovalsCounter -gt 0) {
$FinalMessage = "Successfully completed with some failed delitions - File Removal PowerShell Script"
}
else {
$FinalMessage = "Failed to remove any file - File Removal PowerShell Script"
}
Write-Log -Message $FinalMessage
Write-Log -Message $Settings.LogSeparator -NoTimestamp
#Sends email with detailed report and removes temporary "Report.log" file
Send-EmailReport -Settings $Settings -FinalMessage $FinalMessage
</code></pre>
<h2>The functions used</h2>
<ul>
<li><a href="https://github.com/Zoran-Jankov/File-Removal-PowerShell-Script/blob/master/Modules/Get-FormattedFileSize.psm1" rel="nofollow noreferrer"><em><strong>Get-FormattedFileSize</strong></em></a></li>
<li><a href="https://github.com/Zoran-Jankov/File-Removal-PowerShell-Script/blob/master/Modules/Remove-Files.psm1" rel="nofollow noreferrer"><em><strong>Remove-Files</strong></em></a></li>
<li><a href="https://github.com/Zoran-Jankov/File-Removal-PowerShell-Script/blob/master/Modules/Send-EmailReport.psm1" rel="nofollow noreferrer"><em><strong>Send-EmailReport</strong></em></a></li>
<li><a href="https://github.com/Zoran-Jankov/File-Removal-PowerShell-Script/blob/master/Modules/Write-Log.psm1" rel="nofollow noreferrer"><em><strong>Write-Log</strong></em></a></li>
</ul>
<h3>Report Log</h3>
<p><em>File Removal PowerShell Script</em> generates detailed log file and report, with timestamped log entry of every action and error, with files names which have been removed and disk space freed.</p>
<p><img src="https://raw.githubusercontent.com/Zoran-Jankov/File-Deletion/master/Images/Report%20Log.png" alt="Report Log" /></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T13:40:14.923",
"Id": "495057",
"Score": "1",
"body": "why do you have one-parameter-set-per-parameter in the `Remove-Files` function? your examples show you mixing them ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T13:47:27.823",
"Id": "495058",
"Score": "0",
"body": "@Lee_Dailey I don't understand the question. Can you tell me what you mean exactly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T13:51:33.377",
"Id": "495060",
"Score": "1",
"body": "each of the parameters in that function has `ParameterSetName = \"UniqueNameHere\"`. that is _supposed_ to mean that you cannot use them at the same time ... but you use them in your examples in many combos. i recommend you read up on what `Parameter Sets`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T16:05:21.700",
"Id": "495079",
"Score": "0",
"body": "@Lee_Dailey Oh I see what I did wrong."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T19:05:01.823",
"Id": "495117",
"Score": "1",
"body": "kool! glad to have helped a little bit ... [*grin*]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-14T05:05:03.093",
"Id": "496544",
"Score": "0",
"body": "@Zoran please stop making suggested edits that do not improve the clarity/searchability of posts. Adding hyperlinks to terms like Codeigniter is not valuable. Converting acronyms to uppercase like `html` to `HTML` is not valuable. Changing a title that does not express what the script in question does to a new title that does not describe the scripts functionality is not valuable. I don't take pleasure in Rejecting edits, but none of your recent edits have improved content or earned +2 rep."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T12:50:29.540",
"Id": "251472",
"Score": "1",
"Tags": [
"file",
"powershell"
],
"Title": "File Removal PowerShell Script"
}
|
251472
|
<p><strong>Program description:</strong></p>
<blockquote>
<p>Given an array of integers <code>nums</code> and an integer <code>target</code>, return indices of the two numbers such that they add up to <code>target</code>.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.</p>
</blockquote>
<p><strong>My solution:</strong></p>
<pre><code>/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function(nums, target) {
let N = nums.length;
for(i=0;i<=N-1;i++) {
for(j=i+1;j<=N;j++) {
if(nums[i] + nums[j] == target) {
return [i,j];
};
};
};
};
</code></pre>
<p><strong>Test input:</strong></p>
<pre><code>[2,7,11,15]
9
</code></pre>
<p><strong>Test output:</strong></p>
<pre><code>[0,1]
</code></pre>
<p><strong>Test summary:</strong></p>
<pre><code>Solution accepted.
Runtime: 84ms
</code></pre>
<p><strong>Question:</strong> is there a way to make this code look more neat using some comprehensions, maybe also improving its runtime? Thank you in advance.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T15:47:26.570",
"Id": "495074",
"Score": "2",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here, since most posts pos the question of how the code can be simplified. Please [edit] to the site standard, which is for the title to simply state the task accomplished by the code. Please see [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask), as well as [How to get the best value out of Code Review: Asking Questions](https://codereview.meta.stackexchange.com/q/2436/120114) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T05:43:24.240",
"Id": "495172",
"Score": "0",
"body": "There is a tag [tag:2sum] - and probably more questions tackling twosum without it than tagged."
}
] |
[
{
"body": "<p><strong>Performance</strong> The biggest issue with your current implementation is that it's <code>O(n ^ 2)</code>. You have to iterate through an array of length <code>N</code> <code>(N ^ 2) / 2</code> times in order to find matches. The algorithm can be improved by iterating only once, and by using a Set or an object when iterating to store which number the current number would have to be paired with in order to sum to the target.</p>\n<p>For example, when iterating over <code>1</code>, with a target of <code>5</code>, you could put <code>4</code> into the Set, because 1 + 4 === 5. On further iterations, check to see if the element being iterated over exists in the Set. If it does, it's a match: return the pair. See bottom of answer for an implementation.</p>\n<p><strong>Prefer <code>const</code> over <code>let</code></strong> Since <code>N</code> isn't being reassigned, declare it with <code>const</code>: <a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6</a></p>\n<p><strong>Don't create global variables</strong> Always declare variables before using them. Your current code with <code>for(i=0;i<=N-1;i++)</code> and <code>for(j=i+1;j<=N;j++) {</code> is implicitly creating global <code>i</code> and <code>j</code> variables. This is both inelegant and can lead to confusing bugs if the function gets called again before its first call completes. (Also consider adding spaces between operators for readability). You'd want to do:</p>\n<pre><code>for (let i = 0; i < N; i++) {\n</code></pre>\n<p>Note the use of <code>i < N</code>, not <code>i <= N</code>; since <code>N</code> is the length, <code>nums[N]</code> will be <code>undefined</code>, so you shouldn't iterate over it.</p>\n<p><strong>Use strict equality</strong> Don't use <code>==</code> - it has many <a href=\"https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons\">strange rules</a> with type coercion. Even if <em>you're</em> sure the types of the operands are the same, to make it clearer for readers at a glance, better to avoid it and use <code>===</code> or <code>!==</code> instead.</p>\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>/**\n * @param {number[]} nums\n * @param {number} target\n * @return {number[]}\n */\nconst twoSum = function(nums, target) {\n // Key: Number which, if found, matches the number at the index value\n // eg: { 3 => 6 }: if 3 is found later, it'll be a match with the number at index 6\n const indexByPair = new Map();\n const { length } = nums;\n for (let i = 0; i < length; i++) {\n if (indexByPair.has(nums[i])) {\n return [indexByPair.get(nums[i]), i];\n }\n indexByPair.set(target - nums[i], i);\n }\n};\nconsole.log(twoSum([2,7,11,15], 9));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T17:50:01.703",
"Id": "495107",
"Score": "0",
"body": "Thank you so much for the detailed answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-13T07:34:11.503",
"Id": "499724",
"Score": "0",
"body": "*Note the use of `i < N`, not `i <= N`* which doesn't occur in the question - you correctly quoted `i=0;i<=N-1`. Then again, your warning against accessing `nums[N]` is spot-on, and a measure against it has to be taken - the limit in the *nested* loop has to be lowered: `for (let j = i + 1; j < N; j++)`. (The outer loop doesn't need a limit at all: 1) it doesn't index `nums` (movement of code evaluating \"invariant expressions\" exempted - a beast to debug) 2) a value will be returned before `i` exceeds any promising limit given `You may assume that each input would have exactly one solution`.)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T16:00:25.973",
"Id": "251483",
"ParentId": "251479",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "251483",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T15:34:14.263",
"Id": "251479",
"Score": "3",
"Tags": [
"javascript",
"algorithm"
],
"Title": "Is there a way to make this code simplier?"
}
|
251479
|
<p>For the following question, does my JS Solution seem correct?</p>
<p>I'm looking for some peer review.</p>
<blockquote>
<p>Q: Given a string s containing only a and b, find longest substring of s such that s does not contain more than two contiguous occurrences of a and b.</p>
</blockquote>
<p>Examples: <br>
"aabbaaaaabb" => "aabbaa" <br>
"aabbaabbaabbaa" => "aabbaabbaabbaa"</p>
<pre><code>function maxLenSubStr(s) {
let start = 0, end = 0;
let numOfConsecutiveChars = 0;
let res = "";
while (end <= s.length) {
numOfConsecutiveChars++;
if (numOfConsecutiveChars > 2 || end == s.length) { // time to end our substring is these two cases
if (end-start > res.length) res = s.substring(start,end); // if it is not longer, there is no need to store it
start = end-1; // slide our window so we can look for a new valid substring
numOfConsecutiveChars--; // now we have a valid substring with two contiguous occurrences instead of three
}
if (s[end] !== s[end+1]) numOfConsecutiveChars = 0;
end++;
}
return res;
// Time Complexity: O(n)
// Space Complexity: O(1)
}
</code></pre>
|
[] |
[
{
"body": "<p>After some tests, the code does look correct, but the logic takes <em>some time</em> to parse and understand, which is a significant disadvantage; when writing good, maintainable code, readability is usually the most important factor to consider.</p>\n<p>If a script is running too slowly for your liking, you can run a performance test to identify the bottleneck(s) and then fix those bottlenecks (possibly with hard-to-read code like this), but before then, better to write easy-to-write, easy-to-understand code first.</p>\n<p>If it were me, I'd use a regular expression. It'll have many fewer "moving parts" than going through the string manually and counting up lengths, and REs are quite widely used for general string matching and manipulation across most programming languages; it's something a programmer will probably already be familiar with, so hopefully using them won't present a problem.</p>\n<p>The one complication with a regular expression is that when there may be overlapping matches, the code can get somewhat ugly, see <a href=\"https://stackoverflow.com/q/20833295\">here</a> for examples. Here, with a string of <code>abbba</code>, you'd have to consider both <code>abb</code> and <code>bba</code>, where the middle <code>b</code> is contained in both. Rather than deal with overlapping matches, I'll replace all 3+-contiguous-occurrences with 4-contiguous-occurrences beforehand. Then it's trivial to use <code>.split</code> to split along the middle of each 4-contiguous section, and then return the longest string in the resulting array:</p>\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 maxLenSubStr = s => s\n // Expand 3 or more contiguous occurrences to 4 contiguous occurrences\n // eg 'abbba' -> 'abbbba'\n .replace(/(.)\\1{2,}/g, '$&$1')\n // Split along the middle of each 4-contiguous subsequence\n // eg 'abbbba' -> ['abb', 'bba']\n .split(/(?<=\\1(.))(?=\\1{2})/)\n .reduce((a, b) => a.length > b.length ? a : b);\n\nconsole.log(maxLenSubStr(\"aabbaaaaabb\")); // => \"aabbaa\"\nconsole.log(maxLenSubStr(\"aabbaabbaabbaa\")); // => \"aabbaabbaabbaa\"\nconsole.log(maxLenSubStr(\"baaa\")); // => \"baa\"</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>For the regular expressions, the same technique is being used in both. Capture a character in a group, then backreference that group to match the same character again as many times as needed.</p>\n<ul>\n<li><code>(.)\\1{2,}</code> - <code>(.)</code> captures the character, <code>\\1{2,}</code> matches it again 2 or more times, then replaces with 4 occurrences of the character.</li>\n<li><code>(?<=\\1(.))(?=\\1{2})</code> - <code>(.)</code> captures the character in the lookbehind, <a href=\"https://stackoverflow.com/q/36047988\">preceded</a> by <code>\\1</code>, another occurrence of the character. Then <code>(?=\\1{2})</code> looks ahead for 2 more occurrences of the character.</li>\n</ul>\n<p>I'd consider this an order of magnitude easier to understand than your original code. It's much easier to see at a glance that it'll carry out the desired logic properly, at least for those with a bit of experience with regular expressions. Whether it's worth replacing your original code with it would depend on you and your team's familiarity with REs.</p>\n<p>If you had to do it without lookbehind (which is not supported on out-of-date browsers), then split with another capturing group around the whole left match, or use <code>.match</code> instead, to match characters until encountering 3 in a row:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const maxLenSubStr = s => s\n // Expand 3 or more contiguous occurrences to 4 contiguous occurrences\n // eg 'abbba' -> 'abbbba'\n .replace(/(.)\\1{2,}/g, '$&$1')\n // Split along the middle of each 4-contiguous subsequence\n // eg 'abbbba' -> ['abb', 'bba']\n // Lazily match characters until encountering the end of the string\n // or until 3 of the same character are in a row\n .match(/.*?(?:$|(.)\\1(?=\\1))/g)\n .reduce((a, b) => a.length > b.length ? a : b);\n\nconsole.log(maxLenSubStr(\"aabbaaaaabb\")); // => \"aabbaa\"\nconsole.log(maxLenSubStr(\"aabbaabbaabbaa\")); // => \"aabbaabbaabbaa\"\nconsole.log(maxLenSubStr(\"baaa\")); // => \"baa\"\nconsole.log(maxLenSubStr(\"aaab\")); // => \"aab\"</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>If you were to keep using your original code, I'd suggest:</p>\n<ul>\n<li><p>Use strict comparison <code>===</code> instead of sloppy comparison <code>==</code> (which has <a href=\"https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons\">weird coercion rules</a> a reader of the code shouldn't have to worry about)</p>\n</li>\n<li><p>Use spaces between non-unary operators and operands, for readability, eg <code>end - start > res.length</code> instead of <code>end-start > res.length</code></p>\n</li>\n<li><p>Rather than <code>numOfConsecutiveChars--;</code>, since the new consecutive count will always be 2, better to assign 2 to it directly: <code>numOfConsecutiveChars = 2</code></p>\n</li>\n<li><p>Increment <code>numOfConsecutiveChars</code> only when a subsequent consecutive character is found, and not unconditionally. (Your current logic works, it's just confusing)</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T21:18:09.647",
"Id": "495450",
"Score": "0",
"body": "You are a legend. Thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T17:56:51.933",
"Id": "251491",
"ParentId": "251484",
"Score": "4"
}
},
{
"body": "<p>If I saw this code in an interview I would want to look at multiple factors, including:</p>\n<ul>\n<li>how well the code works</li>\n<li>how readable the code is</li>\n</ul>\n<p>Obviously the code works for the given input. In terms of readability it seems the code has consistent indentation, though some of the lines are quite long and I have to scroll horizontally to read the entire contents.</p>\n<p>While it isn't wrong to use a <code>while</code> loop, it could be re-written using a <code>for</code> loop, since a <code>for</code> loop is a <code>while</code> loop with the initialization, condition and final-expression expressions contained in one line (though it could span multiple lines if necessary).</p>\n<pre><code>for (let start = 0, end = 0, numOfConsecutiveChars = 0; end <= s.length; end++) {\n</code></pre>\n<p>This will eliminate the need to have <code>end++</code> at the end of the loop block, and keep the iterator variables scoped to the block instead of the entire function.</p>\n<p>This line</p>\n<blockquote>\n<pre><code>numOfConsecutiveChars++;\n</code></pre>\n</blockquote>\n<p>could be removed if the conditional line that follows it is updated to include the increment in a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment#Prefix_increment\" rel=\"nofollow noreferrer\">pre-fix manner</a>:</p>\n<pre><code>if (++numOfConsecutiveChars > 2 || end == s.length) { \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T21:18:14.543",
"Id": "495451",
"Score": "0",
"body": "You are a legend. Thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T19:03:06.890",
"Id": "251495",
"ParentId": "251484",
"Score": "2"
}
},
{
"body": "<h1>Complexity and performance review</h1>\n<h2>JavaScript does not like strings.</h2>\n<p>It is always best to avoid direct string manipulation in JavaScript when compared to manipulating numbers.</p>\n<p>As the function involves stepping over each character you can get a lot of performance by converting characters to numbers using <code>String.charCodeAt</code>.</p>\n<p>Not all JavaScript numbers are equally as performant. Internally JavaScript has several different types of <code>Number</code> (depending on which JS engine is used). The simplest internal number type is 32bit Signed Integer (uint32) which CPUs can handle quicker than Doubles (64 bit floating point).</p>\n<p>You can force a number to be uint32 by performing a bit-wise operation on it. Thus <code>String.charCodeAt(index) | 0</code> will give you the most performant data from a string.</p>\n<h2>Complexity</h2>\n<p>You have commented in your code</p>\n<pre><code>// Space Complexity: O(1)\n// Time Complexity: O(n)\n</code></pre>\n<h3>Space</h3>\n<p>Your function is at least <span class=\"math-container\">\\$O(n)\\$</span> space if we ignore how the heap works and <span class=\"math-container\">\\$O(n*log(n))\\$</span> if we dont.</p>\n<p>The function returns a string, javascript does not use references for strings, it copies every character every time you move it. So a simple function</p>\n<pre><code>function giveBackStr(str) { return str }\nconst a = giveBackStr("1234567890"); \n</code></pre>\n<p>has a space complexity of <span class=\"math-container\">\\$O(n)\\$</span> as the string is first copied to argument <code>str</code> and then if return is assigned a second copy is created. So the above example will need RAM for 20 characters.</p>\n<p>If we don't ignore the way the JS heap works the space complexity gets worse as RAM assigned inside a function is not removed from the heap until all code has finished executing. Thus as with time complexity your length check is causing the function to use too much RAM (see next section)</p>\n<h3>Time</h3>\n<p>The way you track the max length of the found string means that the time complexity is greater that <span class=\"math-container\">\\$O(n)\\$</span></p>\n<pre><code>if (end-start > res.length) res = s.substring(start,end)\n</code></pre>\n<p>The best case for your code is <span class=\"math-container\">\\$O(n)\\$</span> however the worst is <span class=\"math-container\">\\$O(n.log(n))\\$</span></p>\n<p>For example the string <code>"ababab"</code>. Each iteration will get a longer string to return. Thus you will need to create <code>"a"</code>, then <code>"ab"</code>, <code>"aba"</code>, <code>"abab"</code>, ... to <code>"ababab"</code>.</p>\n<p>JaveScript copies strings one character at a time. So for the 6 characters <code>"ababab"</code> just to copy parts of the string 6 times requires the movement of 20 characters, meaning time complexity worst case is <span class=\"math-container\">\\$O(n.log(n))\\$</span></p>\n<h2>Rewrite</h2>\n<p>The next snippet is written to have</p>\n<ul>\n<li>a time complexity of <span class=\"math-container\">\\$O(n)\\$</span> which can not be improved,</li>\n<li>a space complexity of <span class=\"math-container\">\\$O(n)\\$</span> as the argument and returns are strings this can not be improved.</li>\n<li>and to be performant within the constraints of the above two points.</li>\n</ul>\n<p>Code</p>\n<pre><code>function maxLenSubStrB(str) {\n var i = 0, max = 0, from = 2, start, c1, c2;\n const nextChar = () => str.charCodeAt(i++) | 0;\n const checkMax = () => {\n const len = i - from;\n if (len > max) {\n start = from - 2;\n max = len;\n }\n from = i;\n }\n if (str.length > 2) { \n c1 = nextChar();\n c2 = nextChar(); \n while (i < str.length) {\n const c = nextChar();\n c2 === c && c2 === c1 && checkMax();\n c1 = c2;\n c2 = c;\n }\n i ++;\n checkMax();\n return str.slice(start, start + max + 1);\n }\n return str; \n}\n</code></pre>\n<p>This is may not be the most performant way.</p>\n<ul>\n<li>there can be an early exit by checking if the number of remain characters is less than max</li>\n<li>Using <code>String.indexOf</code> to locate triples</li>\n</ul>\n<p>However the gains would be small</p>\n<h2>Note on Strings and Number</h2>\n<p>To point out how bad JavaScript is at manipulating strings if we change the function <code>nextChar</code> from</p>\n<pre><code>const nextChar = () => str.charCodeAt(i++) | 0;\n</code></pre>\n<p>to</p>\n<pre><code>const nextChar = () => str[i++];\n</code></pre>\n<p>it takes twice as long to find a solution.</p>\n<p>Removing the bit-wise conversion to Uint32</p>\n<pre><code>const nextChar = () => str.charCodeAt(i++);\n</code></pre>\n<p>results in a small 4-5% slowdown.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T21:18:22.263",
"Id": "495452",
"Score": "0",
"body": "You are a legend. Thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T20:31:09.610",
"Id": "251565",
"ParentId": "251484",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T16:01:54.893",
"Id": "251484",
"Score": "4",
"Tags": [
"javascript",
"strings",
"interview-questions",
"ecmascript-6",
"iteration"
],
"Title": "Microsoft OA | Longest Substring Without 3 Contiguous Occurrences of Letter"
}
|
251484
|
<p>I have written this multithreaded program to download files from AWS S3. Kindly review if it is a correct approach.</p>
<p>Code works and downloads the files. But I see an issue occurring sometime (below is the error I see). According to me each file/object from S3 is download independently by one thread. Why would two thread try to access the same file?</p>
<p><strong>Log:</strong></p>
<pre><code>[WinError 32] The process cannot access the file because it is being used by another process: './Data/weblog_download/web_log_collector_to_s3-1-2020-10-31-10-09-31-cb1494d0-f739-4aa4-a685-9978e0bda090.77C419cA' -> './Data/weblog_download/web_log_collector_to_s3-1-2020-10-31-10-09-31-cb1494d0-f739-4aa4-a685-9978e0bda090'
[WinError 32] The process cannot access the file because it is being used by another process: './Data/weblog_download/web_log_collector_to_s3-1-2020-10-30-18-12-14-b8ec4e31-2509-4f16-b5dc-95d3052be92e.0eCEB7B4' -> './Data/weblog_download/web_log_collector_to_s3-1-2020-10-30-18-12-14-b8ec4e31-2509-4f16-b5dc-95d3052be92e'
</code></pre>
<p><strong>Code:</strong></p>
<pre><code>from datetime import datetime, timedelta
from AWSUtils import s3_utils
from pathlib import Path
import os, shutil, pprint
import boto3
import multiprocessing as mp
from multiprocessing import Pool
from functools import partial
import time
from threading import Thread
from multiprocessing.pool import ThreadPool
import threading
s3 = boto3.client("s3")
is_folder_cleanup = True
path_to_save = "./Data/weblog_download"
base_bucket = 'web-logs'
main_key = 'web_logs2020/{}'
def download_file(file_key):
try:
# getting file name out of the full key (web_log_collector_to_s3-1-2020-10-31-10-09-31-cb1494d0-f739-4aa4-a685-9978e0bda090)
file_name = file_key.split("/")[-1]
s3_utils.download_file(base_bucket, file_key, path_to_save + "/" + file_name)
except Exception as e:
print(e)
def download_files_from_s3(key):
print(f"{os.getpid()}:{threading.current_thread().ident}: Processing: {key}")
base_kwargs = {
'Bucket': base_bucket,
'Prefix': key
}
# querying AWS S3 to list all the files/object for the key and bucket.
response = s3.list_objects_v2(**base_kwargs)
pprint.pprint(response)
if response:
if 'Contents' in response:
all_files_to_download = []
# getting each files/object name from the response
for c in response['Contents']:
k = c['Key']
all_files_to_download.append(k)
# download_pool = Pool(processes=20)
# download_pool.map(download_file, all_files_to_download)
# download_pool.close()
# download_pool.join()
# using multiple threads to download multiple file/object
with Pool(processes=5) as pool_thread:
pool_thread.map(download_file, all_files_to_download)
if __name__ == '__main__':
today_date = datetime.now()
days = []
months = []
hours = list(range(0, 24))
keys = []
# getting day and month for last 7 days and storing into a list
for i in range(1, 8):
today_date_minus = today_date - timedelta(days=i)
day_end = today_date_minus.day
month = today_date_minus.month
days.append(day_end)
months.append(month)
print(days, months, hours)
# formatting to get the key/folder as in S3 (web_logs2020/10/26/7)
for month, day in zip(months, days):
print(month, day)
for hour in hours:
key = main_key.format(f"{month}/{day}/{hour}") # example key -> web_logs2020/10/26/7
keys.append(key)
print(f"All Keys: {keys}")
Path(path_to_save).mkdir(parents=True, exist_ok=True)
# cleaning up current folder to download new files.
if is_folder_cleanup:
for root, dirs, files in os.walk(path_to_save):
print(root, dirs, files)
for f in files:
os.unlink(os.path.join(root, f))
for d in dirs:
shutil.rmtree(os.path.join(root, d))
start_time = time.time()
threads = []
with ThreadPool(processes=15) as p:
p.map(download_files_from_s3, keys)
print(f"Total Time taken: {(time.time() - start_time) / 60}")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T17:18:44.820",
"Id": "495103",
"Score": "1",
"body": "`print(f\"{os.getpid()}:{threading.current_thread().ident}: Processing: {key}\")` look into the `logging` module"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T18:36:30.800",
"Id": "495114",
"Score": "0",
"body": "Sure, I always want to use the logger but end up using print."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T16:55:52.433",
"Id": "251487",
"Score": "2",
"Tags": [
"python-3.x",
"multithreading"
],
"Title": "Simple multithreading programing in Python to download file from AWS S3"
}
|
251487
|
<p>I've written a modern C++17 INI file reader to get access parameters values from an <a href="https://en.wikipedia.org/wiki/INI_file" rel="nofollow noreferrer">INI</a> configuration file anywhere in a source file by simply included <code>#include "Ini.hpp"</code> in the headers.</p>
<p>The file parsing is done once at first parameter request with a default file path. The parsing is done with REGEX I've written on this purpose.</p>
<p>I may went too far when checking the different number ranges depending on the C++ number type (<code>short, int, long, long long, ...</code>).</p>
<p>Let me know what you think.</p>
<p><strong>Ini.hpp</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#include <fstream>
#include <unordered_map>
#include <string>
#include <regex>
#include <cfloat>
#include <climits>
// PARAMETERS_INI_FILE_PATH is a constant defined in the CMake configuration project file
struct Ini
{
public:
typedef std::unordered_map<std::string, std::unordered_map<std::string, std::string>> IniStructure;
Ini() = delete;
static void parse(const std::string &filePath = PARAMETERS_INI_FILE_PATH);
template<typename T> static T get(const std::string &section, const std::string &key);
private:
static bool keyExists(const std::string &section, const std::string &key);
static long long extractIntegerNumber(const std::string &section, const std::string &key);
static long double extractFloatNumber(const std::string &section, const std::string &key);
// [section][parameter name][parameter value]
static inline IniStructure values;
static inline std::string iniPath;
};
</code></pre>
<p><strong>Ini.cpp</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#include "Ini.hpp"
// ------------------------------------------------- Static functions ------------------------------------------------ //
/**
* Parse the INI file located to the given file path and store the values in Ini::values
*
* @param filePath - The path of the INI file to parse
*/
void Ini::parse(const std::string &filePath)
{
std::ifstream fileReader(filePath, std::ifstream::in);
std::string fileContent((std::istreambuf_iterator<char>(fileReader)), std::istreambuf_iterator<char>());
std::regex sections(R"(\[([^\]\r\n]+)]((?:\r?\n(?:[^[\r\n].*)?)*))");
std::regex parameters(R"((\w+) ?= ?(\"([^\"]+)\"|([^\r\n\t\f\v;#]+)))");
std::smatch sectionMatch;
iniPath = filePath;
if (fileReader.fail()) {
throw std::runtime_error("The file " + Ini::iniPath + " could not be opened");
}
while (regex_search(fileContent, sectionMatch, sections)) {
std::unordered_map<std::string, std::string> sectionParameters;
std::string sectionString = sectionMatch[2].str();
for (std::sregex_iterator parameter(sectionString.begin(), sectionString.end(), parameters); parameter != std::sregex_iterator(); ++parameter) {
std::smatch parameterMatch = *parameter;
sectionParameters[parameterMatch[1].str()] = parameterMatch[3].matched ? parameterMatch[3].str() : parameterMatch[4].str();
// parameterMatch[1] is the key, parameterMatch[3] is a trim quoted string (string without double quotes)
// and parameterMatch[4] is a number
}
values[sectionMatch[1].str()] = sectionParameters;
fileContent = sectionMatch.suffix();
}
}
/**
* Tells if the parameter exists in the given section at the given key
*
* @param section - The INI section to get the parameter from
* @param key - The INI parameter key
*
* @return True if the parameter exists in the given section at the given key, false otherwise
*/
bool Ini::keyExists(const std::string &section, const std::string &key)
{
return values.find(section) != values.end() && values[section].find(key) != values[section].end();
}
/**
* Extract the integer number of the parameter in the given INI section at the given key
*
* @param section - The INI section to get the parameter from
* @param key - The INI parameter key
*
* @return The requested integer number value
*/
long long Ini::extractIntegerNumber(const std::string &section, const std::string &key)
{
std::smatch intNumberMatch;
std::regex intNumber(R"(^\s*(\-?\d+)\s*$)");
if (!keyExists(section, key)) {
throw std::runtime_error("The key " + key + " does not exist in section " + section + " in " + Ini::iniPath);
}
if (std::regex_match(values[section][key], intNumberMatch, intNumber)) {
return std::strtoll(intNumberMatch[1].str().c_str(), nullptr, 10);
} else {
throw std::runtime_error("The given parameter is not an integer number");
}
}
/**
* Extract the floating point number of the parameter in the given INI section at the given key
*
* @param section - The INI section to get the parameter from
* @param key - The INI parameter key
*
* @return The requested floating point number value
*/
long double Ini::extractFloatNumber(const std::string &section, const std::string &key)
{
std::smatch floatNumberMatch;
std::regex floatNumber(R"(^\s*(\-?(?:(?:\d+(?:\.\d*)?)|(?:\d+(?:\.\d+)?e(?:\+|\-)\d+))f?)\s*$)");
if (!keyExists(section, key)) {
throw std::runtime_error("The key " + key + " does not exist in section " + section + " in " + Ini::iniPath);
}
if (std::regex_match(values[section][key], floatNumberMatch, floatNumber)) {
return std::strtold(floatNumberMatch[1].str().c_str(), nullptr);
} else {
throw std::runtime_error("The given parameter is not a floating point number");
}
}
// ---------------------------------------------- Template specialisation -------------------------------------------- //
/**
* Throw an exception if the requested type is not defined
*/
template<typename T>
T Ini::get(const std::string &section, const std::string &key)
{
throw std::runtime_error("The type of the given parameter is not defined");
}
/**
* Get the boolean parameter in the given INI section at the given key
*
* @param section - The INI section to get the parameter from
* @param key - The INI parameter key
*
* @return The requested bool value
*/
template<>
bool Ini::get(const std::string &section, const std::string &key)
{
if (iniPath.empty()) { parse(); }
return values[section][key] == "true" || values[section][key] == "1";
}
/**
* Get the string parameter in the given INI section at the given key
*
* @param section - The INI section to get the parameter from
* @param key - The INI parameter key
*
* @return The requested string value
*/
template<>
std::string Ini::get(const std::string &section, const std::string &key)
{
if (iniPath.empty()) { parse(); }
return values[section][key];
}
/**
* Get the short number parameter in the given INI section at the given key
*
* @param section - The INI section to get the parameter from
* @param key - The INI parameter key
*
* @return The requested short number value
*/
template<>
short Ini::get(const std::string &section, const std::string &key)
{
if (iniPath.empty()) { parse(); }
auto number = extractIntegerNumber(section, key);
if (number >= -SHRT_MAX && number <= SHRT_MAX) {
return static_cast<short>(number);
} else {
throw std::runtime_error("The number is out of range of a short integer");
}
}
/**
* Get the int number parameter in the given INI section at the given key
*
* @param section - The INI section to get the parameter from
* @param key - The INI parameter key
*
* @return The requested int number value
*/
template<>
int Ini::get(const std::string &section, const std::string &key)
{
if (iniPath.empty()) { parse(); }
auto number = extractIntegerNumber(section, key);
if (number >= -INT_MAX && number <= INT_MAX) {
return static_cast<int>(number);
} else {
throw std::runtime_error("The number is out of range of a an integer");
}
}
/**
* Get the unsigned int number parameter in the given INI section at the given key
*
* @param section - The INI section to get the parameter from
* @param key - The INI parameter key
*
* @return The requested unsigned int number value
*/
template<>
unsigned int Ini::get(const std::string &section, const std::string &key)
{
if (iniPath.empty()) { parse(); }
auto number = extractIntegerNumber(section, key);
if (number < 0) {
throw std::runtime_error("The number is negative so it cannot be unsigned");
} else if (number <= UINT_MAX) {
return static_cast<unsigned int>(number);
} else {
throw std::runtime_error("The number is out of range of a an unsigned integer");
}
}
/**
* Get the long int number parameter in the given INI section at the given key
*
* @param section - The INI section to get the parameter from
* @param key - The INI parameter key
*
* @return The requested long int number value
*/
template<>
long Ini::get(const std::string &section, const std::string &key)
{
if (iniPath.empty()) { parse(); }
auto number = extractIntegerNumber(section, key);
if (number >= -LONG_MAX && number <= LONG_MAX) {
return number;
} else {
throw std::runtime_error("The number is out of range of a a long integer");
}
}
/**
* Get the long long int number parameter in the given INI section at the given key
*
* @param section - The INI section to get the parameter from
* @param key - The INI parameter key
*
* @return The requested long long int number value
*/
template<>
long long Ini::get(const std::string &section, const std::string &key)
{
if (iniPath.empty()) { parse(); }
return extractIntegerNumber(section, key);
}
/**
* Get the float number parameter in the given INI section at the given key
*
* @param section - The INI section to get the parameter from
* @param key - The INI parameter key
*
* @return The requested float number value
*/
template<>
float Ini::get(const std::string &section, const std::string &key)
{
if (iniPath.empty()) { parse(); }
auto number = extractFloatNumber(section, key);
if (number >= -FLT_MAX && number <= FLT_MAX) {
return static_cast<float>(number);
} else {
throw std::runtime_error("The number is out of range of a float");
}
}
/**
* Get the double number parameter in the given INI section at the given key
*
* @param section - The INI section to get the parameter from
* @param key - The INI parameter key
*
* @return The requested double number value
*/
template<>
double Ini::get(const std::string &section, const std::string &key)
{
if (iniPath.empty()) { parse(); }
auto number = extractFloatNumber(section, key);
if (number >= -DBL_MAX && number <= DBL_MAX) {
return static_cast<double>(number);
} else {
throw std::runtime_error("The number is out of range of a double");
}
}
/**
* Get the long double number parameter in the given INI section at the given key
*
* @param section - The INI section to get the parameter from
* @param key - The INI parameter key
*
* @return The requested long double number value
*/
template<>
long double Ini::get(const std::string &section, const std::string &key)
{
if (iniPath.empty()) { parse(); }
return extractFloatNumber(section, key);
}
</code></pre>
<p><strong>main.cpp</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include "Ini.hpp"
int main(int argc, char **argv)
{
try {
auto myNumber = Ini::get<int>("Section", "parameter1");
auto myString = Ini::get<std::string>("Section", "parameter2");
std::cout << "Get the string " << myString << " and the number " << myNumber << " from the INI config file." << std::endl;
} catch (const std::exception &e) {
std::cerr << e.what() << std::endl;
return 1;
}
return 0;
}
</code></pre>
<p><strong>example.ini</strong></p>
<pre><code>[Section]
parameter1 = 10
; comment
parameter2 = My string parameter ; comment
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T09:17:16.817",
"Id": "495194",
"Score": "1",
"body": "Yep I did couple of tests in a online regex tester, I'll put some demos. I didn't find a native C++ INI parser in the std like there is in PHP for example."
}
] |
[
{
"body": "<p>General issues to the whole concept:</p>\n<ul>\n<li>There is a reason why <code>ini</code> file format is considered deprecated by Microsoft.\nFile formats like <code>json</code> and <code>xml</code> have tree-like structure making them a lot more flexible that <code>ini</code> file format that has only single-depth sections.</li>\n</ul>\n<p>Suppose you want a class to obtain a value from the configuration file. Okay, that's simple just fix a section for the class and let it take value from a given key. But wait, what if you have more than a single instance of the class and you want different configurations for it? Do you want to manually decide the section for each class?</p>\n<p>With tree-like configuration file formats you can just go to a subsection and obtain values from there. And everything is organized automatically.</p>\n<p>If you still want to operate with INI file format you can just extend it by saying that <code>/</code> acts as a subsection. So,</p>\n<pre><code>[SECTION]\nSUBSECTION/KEY = VALUE\n</code></pre>\n<p>is equivalent to</p>\n<pre><code>[SECTION/SUBSECTION]\nKEY = VALUE\n</code></pre>\n<p>and both resulting in <code>SECTION/SUBSECTION/KEY = VALUE</code>.</p>\n<ul>\n<li>Making ini parser into a singleton creates a lot of issues.</li>\n</ul>\n<ol>\n<li><p>What do you think will happen if you parse several ini files and some of them share the same sections?</p>\n</li>\n<li><p>What will happen if in one thread you access data while another thread parses an ini file? You need to make the class thread-safe.</p>\n</li>\n<li><p>What if you don't want to expose all your ini files to every section in the code? Say you want to instantiate a class from a different version of a specific <code>ini</code> file that has same fields but different values as the one you work on currently?</p>\n</li>\n</ol>\n<p>I am a strong believer in Context Pattern - you create a class with some dynamic shared data and forward it to all necessary class instances (only slightly alter handles to it so they access information from the correct places). Singletons are fine for services/functions that require relatively long instantiation. Configuration file is more of a shared data and not a singleton.</p>\n<ul>\n<li>Okay, let's move to various technical issues:</li>\n</ul>\n<ol>\n<li><p>You define template method <code>get</code> in .cpp file. That's not gonna work. They must be defined in header else using it for new types causes compilation errors so the <code>throw</code> will never be triggered. Honestly, you want a compilation error instead of a runtime error but did you ever read a template error message? They are all incomprehensible.</p>\n<p>Instead you should write the unspecified <code>get</code> in header and put a <code>static_assert</code> inside.</p>\n</li>\n<li><p>The interface is very clunky. Frequently, people have default parameters and just want to see if the value was overridden in the configuration file and update it if necessary.\nThink how easy it would be with this interface. They will have to wrap every single call into try/catch. That's horrible.</p>\n<p>Why not simply return a <code>std::optional<T></code> instead of throwing for every little thing?\nCheck <code>boost::property_tree</code> how they have it. It is written a lot more sensibly.</p>\n</li>\n<li><p>The methods that just want to get values modify the data, e.g.,</p>\n<pre><code> bool Ini::get(const std::string &section, const std::string &key)\n {\n return values[section][key] == "true" || values[section][key] == "1";\n }\n</code></pre>\n<p>Here, if <code>values[section]</code> doesn't exist it will be created and same for <code>values[section][key]</code>. It is definitely not what you want with "get data" methods. In addition, it will cause data-races and UB issues when you try to get data from the ini class by different threads.</p>\n</li>\n<li><p>Since you want a modern C++ code, why do you use such outdated MACROS? for integer and float limits? There is <code>std::numeric_limits<T></code> for this purpose and you can write a single definition for all integral values instead of specializing it for each type.</p>\n</li>\n<li><p>Accessing keys of <code>unordered_map<string, unordered_map<string,string>></code> is inefficient and inconvenient. To access a single key you have to generate hash twice one for each map. Consider using <code>unordered_map<string,string></code> and store access keys in format <code>section/key</code> instead. This way you'll also be able to forward section + key in a single string instead of two. Furthermore, for input consider using <code>string_view</code> although, I am unsure if <code>unordered_map<string,string></code> can find elements directly from <code>string_view</code> keys.</p>\n</li>\n<li><p>I believe it will be more convenient if the default ini file wasn't a universal constant but instead depend on the name of the executable? no? Like you have two executables <code>A.exe</code> and <code>B.exe</code> then <code>A.exe</code> will automatically try to load <code>A.ini</code> and <code>B.exe</code> will automatically try to load <code>B.ini</code>. Isn't it better?</p>\n</li>\n<li><p><code>Ini::parse(const std::string &filePath)</code> If you already use <code>C++17</code> then please use dedicated class <code>std::filesystem::path</code> instead of <code>std::string</code>. Also the you should utilize <code>std::move</code> as <code>values[sectionMatch[1].str()] = sectionParameters;</code> will cause the unordered map <code>sectionParameters</code> to be copied which is slow for such a class. Furthermore, it is completely unnecessary as you could've just written <code>values[sectionMatch[1].str()] = std::move(sectionParameters);</code> which would steal all its content instead of copying.</p>\n</li>\n<li><p>Honestly, I don't understand the regular expressions and I have some doubts that it will properly parse <code>ini</code> files - you should add checks on this part and test it properly. Furthermore, you ought to put out warnings/errors when the file you read doesn't follow <code>ini</code> specification and I don't see it done.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T09:13:55.600",
"Id": "495192",
"Score": "0",
"body": "Thank you for this long and precise review.\nINI files intent to be simpler than verbose XML one, I really like JSON format since I was a web developer and used this format quite a lot in JS but JSON format lack of comments in it to describe what's going on.\nThis class is not TS, it should be you're right !\nUsing a static_assert would be better than error throwing that's a good point.\nThis code came from a C++14 CUDA project and the project can now handle C++17 with NVCC 11 so I will use the std::filesystem.\nI will get most of your recommendations and post a 2nd version today."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T11:15:52.147",
"Id": "495530",
"Score": "0",
"body": "I'm curious of one thing, I tried as you suggested to put a static assert in header to have compilation error when a type is not implemented with `std::is_same_v`. It works when I build in debug mode but not in release (-O3). I kept the template specialization in `.cpp` file. Must template specialization be located in header file ?\nTo be clear, if I put static_assert in header file in release mode, compilation warns about undefined specialization but fails to get the correct one in function call at execution. The unspecified template is called."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T12:01:48.217",
"Id": "495540",
"Score": "0",
"body": "@RomainLaneuville you need to either make definition in header or declare via `extern template` that there is a .cpp definition elsewhere. Generally, I thought to inform you later that you shouldn't write `get` like this. Instead, you should make `get` template from classes `T` and `Parser` (defaulted to some `default_parser<T>`) and let the `Parser` class convert from the string to `T`. It is much easier to specialise classes as opposed to functions."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T05:13:45.673",
"Id": "251522",
"ParentId": "251489",
"Score": "5"
}
},
{
"body": "<p>Based on <strong>ALX23z</strong> recommendations, I did the following changes :</p>\n<ul>\n<li>The class is now thread safe</li>\n<li>There is only one get method that parsing all the types</li>\n<li>The class is now using <code>std::numeric_limits<T></code> instead of old C style constants</li>\n<li>The class is now using <code>std::filesystem::path</code> instead of <code>std::string</code> for file path parameter</li>\n</ul>\n<p>I kept the <code>typedef std::unordered_map<std::string, std::unordered_map<std::string, std::string>> IniStructure</code> which I think is more readable when accessing parameter as <code>values[section][parameter]</code> and the parameter access time is not critical as it is not intended to be accessed multiple times like in a loop.</p>\n<p>This class does not handle multiple INI files parsing.</p>\n<p>I tried to use a <code>static_assert</code> to warn about undefined type at compilation time but the compilation fails before reaching the assertion.</p>\n<p>Here is the new version :</p>\n<p><strong>Ini.hpp</strong></p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <filesystem>\n#include <fstream>\n#include <string>\n#include <unordered_map>\n#include <regex>\n#include <type_traits>\n#include <limits>\n#include <mutex>\n\ntemplate<typename T> struct unsupportedType : std::false_type { };\n\nstruct Ini\n{\n public:\n typedef std::unordered_map<std::string, std::unordered_map<std::string, std::string>> IniStructure;\n\n Ini() = delete;\n\n static void parse(const std::filesystem::path &filePath = PARAMETERS_INI_FILE_PATH);\n\n template<typename T> static T get(const std::string &section, const std::string &key);\n\n private:\n static void checkParameter(const std::string &section, const std::string &key);\n static long long extractIntegerNumber(const std::string &section, const std::string &key);\n static long double extractFloatNumber(const std::string &section, const std::string &key);\n static void checkInit();\n\n // IniStructure[section][parameter name] = parameter value\n static inline IniStructure values;\n static inline std::filesystem::path iniPath;\n static inline std::mutex mutex;\n static inline bool initialized = false;\n};\n</code></pre>\n<p><strong>Ini.cpp</strong></p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include "Ini.hpp"\n\n// ------------------------------------------------- Static functions ------------------------------------------------ //\n\n/**\n * Parse the INI file located to the given file path and store the values in Ini::values\n *\n * @param filePath - The path of the INI file to parse\n */\nvoid Ini::parse(const std::filesystem::path &filePath)\n{\n std::ifstream fileReader(filePath, std::ifstream::in);\n std::string fileContent((std::istreambuf_iterator<char>(fileReader)), std::istreambuf_iterator<char>());\n std::regex sections(R"(\\[([^\\]\\r\\n]+)]((?:\\r?\\n(?:[^[\\r\\n].*)?)*))");\n std::regex parameters(R"((\\w+) ?= ?(\\"([^\\"]+)\\"|([^\\r\\n\\t\\f\\v;#]+)))");\n std::smatch sectionMatch;\n\n iniPath = filePath;\n\n if (fileReader.fail()) {\n throw std::runtime_error("The file " + Ini::iniPath.string() + " could not be opened");\n }\n\n while (regex_search(fileContent, sectionMatch, sections)) {\n std::unordered_map<std::string, std::string> sectionParameters;\n std::string sectionString = sectionMatch[2].str();\n\n for (std::sregex_iterator parameter(sectionString.begin(), sectionString.end(), parameters); parameter != std::sregex_iterator(); ++parameter) {\n std::smatch parameterMatch = *parameter;\n sectionParameters[parameterMatch[1].str()] = parameterMatch[3].matched ? parameterMatch[3].str() : parameterMatch[4].str();\n // parameterMatch[1] is the key, parameterMatch[3] is a trim quoted string (string without double quotes)\n // and parameterMatch[4] is a number\n }\n\n values[sectionMatch[1].str()] = std::move(sectionParameters);\n fileContent = sectionMatch.suffix();\n }\n\n initialized = true;\n}\n\n/**\n * Tells if the parameter exists in the given section at the given key\n *\n * @param section - The INI section to get the parameter from\n * @param key - The INI parameter key\n *\n * @throw Runtime exception if either the section does not exist or the key does not exists in the given section\n */\nvoid Ini::checkParameter(const std::string &section, const std::string &key)\n{\n if (values.find(section) == values.end()) {\n throw std::runtime_error("The section " + section + " does not exist in " + Ini::iniPath.string());\n }\n\n if (values[section].find(key) == values[section].end()) {\n throw std::runtime_error("The key " + key + " does not exist in section " + section + " in " + Ini::iniPath.string());\n }\n}\n\n/**\n * Extract the integer number of the parameter in the given INI section at the given key\n *\n * @param section - The INI section to get the parameter from\n * @param key - The INI parameter key\n *\n * @return The requested integer number value\n */\nlong long Ini::extractIntegerNumber(const std::string &section, const std::string &key)\n{\n std::smatch intNumberMatch;\n std::regex intNumber(R"(^\\s*(\\-?\\d+)\\s*$)");\n\n if (std::regex_match(values[section][key], intNumberMatch, intNumber)) {\n return std::strtoll(intNumberMatch[1].str().c_str(), nullptr, 10);\n } else {\n throw std::runtime_error("The given parameter is not an integer number");\n }\n}\n\n/**\n * Extract the floating point number of the parameter in the given INI section at the given key\n *\n * @param section - The INI section to get the parameter from\n * @param key - The INI parameter key\n *\n * @return The requested floating point number value\n */\nlong double Ini::extractFloatNumber(const std::string &section, const std::string &key)\n{\n std::smatch floatNumberMatch;\n std::regex floatNumber(R"(^\\s*(\\-?(?:(?:\\d+(?:\\.\\d*)?)|(?:\\d+(?:\\.\\d+)?e(?:\\+|\\-)\\d+))f?)\\s*$)");\n\n if (std::regex_match(values[section][key], floatNumberMatch, floatNumber)) {\n return std::strtold(floatNumberMatch[1].str().c_str(), nullptr);\n } else {\n throw std::runtime_error("The given parameter is not a floating point number");\n }\n}\n\n/**\n * Check if the INI file is already parsed, if not parse the INI file. This operation is thread safe.\n */\nvoid Ini::checkInit()\n{\n std::lock_guard<std::mutex> lock(mutex);\n\n if (!initialized) {\n parse();\n }\n}\n\n// ---------------------------------------------- Template specialisation -------------------------------------------- //\n\n/**\n * Get the parameter in the given INI section at the given key, extract the value depending on the given type\n *\n * @param section - The INI section to get the parameter from\n * @param key - The INI parameter key\n *\n * @return The requested parameter value\n */\ntemplate<typename T> T Ini::get(const std::string &section, const std::string &key) {\n checkInit();\n checkParameter(section, key);\n\n if constexpr (std::is_same_v<T, bool>) {\n return values[section][key] == "true" || values[section][key] == "1";\n } else if constexpr (std::is_same_v<T, std::string>) {\n return values[section][key];\n } else if constexpr (std::is_same_v<T, short> || std::is_same_v<T, int> || std::is_same_v<T, unsigned int>\n || std::is_same_v<T, long> || std::is_same_v<T, long long>\n ) {\n auto number = extractIntegerNumber(section, key);\n\n if (std::is_same_v<T, unsigned int> && number < 0) {\n throw std::runtime_error("The number is negative so it cannot be unsigned");\n } else if (number >= std::numeric_limits<T>::lowest() && number <= std::numeric_limits<T>::max()) {\n return static_cast<T>(number);\n } else {\n throw std::runtime_error("The number is out of range of the given integral type");\n }\n } else if constexpr (std::is_same_v<T, float> || std::is_same_v<T, double> || std::is_same_v<T, long double>) {\n auto number = extractFloatNumber(section, key);\n\n if (number >= std::numeric_limits<T>::lowest() && number <= std::numeric_limits<T>::max()) {\n return static_cast<T>(number);\n } else {\n throw std::runtime_error("The number is out of range of the given floating type");\n }\n } else {\n // @todo This does not warn at compile, compilation fails before reaching this\n static_assert(unsupportedType<T>::value, "The INI parser cannot read parameter of the given C++ type");\n }\n}\n\n// Forward template declarations\ntemplate bool Ini::get<bool>(const std::string &section, const std::string &key);\ntemplate std::string Ini::get<std::string>(const std::string &section, const std::string &key);\ntemplate short Ini::get<short>(const std::string &section, const std::string &key);\ntemplate int Ini::get<int>(const std::string &section, const std::string &key);\ntemplate unsigned int Ini::get<unsigned int>(const std::string &section, const std::string &key);\ntemplate long Ini::get<long>(const std::string &section, const std::string &key);\ntemplate long long Ini::get<long long>(const std::string &section, const std::string &key);\ntemplate float Ini::get<float>(const std::string &section, const std::string &key);\ntemplate double Ini::get<double>(const std::string &section, const std::string &key);\ntemplate long double Ini::get<long double>(const std::string &section, const std::string &key);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T19:50:03.153",
"Id": "495599",
"Score": "0",
"body": "Hi, if you want the new code reviewed, you should create a new question on this site."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T21:22:48.743",
"Id": "495617",
"Score": "0",
"body": "I just posted the new \"solution\" after taking some reviews into consideration, i'm not going to post the code x times after each iteration."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T21:42:01.057",
"Id": "495621",
"Score": "4",
"body": "Ok, that's fine. However, would you consider marking the answer from @ALX23z as the accepted answer? That is a real review after all, and allowed you to create the revised code you posted here."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T17:17:09.390",
"Id": "251669",
"ParentId": "251489",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "251522",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T17:36:24.177",
"Id": "251489",
"Score": "5",
"Tags": [
"c++",
"regex",
"c++17",
"template"
],
"Title": "C++17 static templated ini file reader"
}
|
251489
|
<p>I implemented a Queue using linked list data structure. This is also my first time using templates in C++.</p>
<h1>OVERVIEW</h1>
<p>Queue is a <code>data-structure</code> that supports only minimal functionalites such as <code>push</code>, <code>pop</code>, <code>front</code>, <code>back</code>, <code>empty</code> and <code>size</code>.</p>
<h1>PURPOSE</h1>
<ol>
<li>I aim to have a deeper understanding of templates in C++</li>
<li>I aim to make it look and feel close to the standard library's implementation in terms of memory usage, speed and readability</li>
</ol>
<h1>MAJOR CONCERNS</h1>
<ol>
<li>I initially didn't want to write the implementation of <code>Queue</code> in its header files, but it resulted to all sort of errors. <code>Can Implementation be seprated from its interface whilst using templates?</code></li>
<li>The standard library performance was twice as better as mine. <code>What may be reasons?</code></li>
</ol>
<h2>ListNode.h</h2>
<pre><code>#ifndef LINKEDQUEUE_LISTNODE_H_
#define LINKEDQUEUE_LISTNODE_H_
template< typename T > struct ListNode
{
ListNode() : next_ptr( nullptr ) {}
T data;
ListNode *next_ptr;
};
#endif
</code></pre>
<h2>LinkedQueue.h</h2>
<pre><code>#ifndef LINKEDQUEUE_QUEUE_H_
#define LINKEDQUEUE_QUEUE_H_
#include "ListNode.h"
#include <iostream>
#include <initializer_list>
template<typename T> class Queue
{
friend std::ostream &operator<<( std::ostream &os, const Queue &q )
{
ListNode<T> *temp = q.head;
while( temp != nullptr )
{
os << temp->data << " ";
temp = temp->next_ptr;
}
return os;
}
private:
ListNode<T> node;
ListNode<T> *head, *tail;
size_t queue_size;
public:
Queue() : head( nullptr ), tail( nullptr ), queue_size( 0 ) {}
Queue( std::initializer_list< T > list ) : Queue()
{
for( const T &item : list )
push( item );
}
~Queue()
{
delete head, tail;
}
inline void push( T x )
{
ListNode<T> *new_node = new ListNode<T>;
new_node->data = x;
if( head == nullptr ) head = tail = new_node;
else
{
tail->next_ptr = new_node;
tail = new_node;
}
++queue_size;
}
inline void pop()
{
if( head == nullptr ) throw std::out_of_range( "Queue is empty" );
ListNode<T> *temp = head;
if( head == tail ) head = tail = nullptr;
else head = head->next_ptr;
delete temp;
--queue_size;
}
inline T& front()
{
if( head != nullptr ) return head->data;
else throw std::out_of_range( "Queue is empty" );
}
inline T& back()
{
if( tail != nullptr ) return tail->data;
else throw std::out_of_range( "Queue is empty" );
}
inline bool empty()
{
if( head == nullptr ) return true;
return false;
}
inline size_t size() { return queue_size; }
};
#endif
</code></pre>
<h2>main.cpp</h2>
<pre><code>#include "LinkedQueue.h"
#include <iostream>
#include <chrono>
#include <string>
#include <queue>
int main()
{
auto start = std::chrono::high_resolution_clock::now();
Queue< int > q;
for( int i = 0; i != 1000000; ++i )
q.push( i );
std::cout << "Size of queue is " << q.size() << "\n";
std::cout << "Front of queue: " << q.front() << "\n";
std::cout << "Back of queue: " << q.back() << "\n";
std::cout << "Queue is empty: " << std::boolalpha << q.empty() << "\n";
for( int i = 0; i != 1000000; ++i )
q.pop();
std::cout << "Queue is empty: " << std::boolalpha << q.empty() << "\n";
auto end = std::chrono::high_resolution_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>( end - start );
std::cout << "\nMy runtime : " << elapsed.count() << "ms";
std::cout << "\n\n";
start = std::chrono::high_resolution_clock::now();
std::queue<int> q2;
for( int i = 0; i != 1000000; ++i )
q2.push( i );
std::cout << "Size of queue is " << q2.size() << "\n";
std::cout << "Front of queue: " << q2.front() << "\n";
std::cout << "Back of queue: " << q2.back() << "\n";
std::cout << "Queue is empty: " << std::boolalpha << q2.empty() << "\n";
for( int i = 0; i != 1000000; ++i )
q2.pop();
std::cout << "Queue is empty: " << std::boolalpha << q2.empty() << "\n";
end = std::chrono::high_resolution_clock::now();
elapsed = std::chrono::duration_cast<std::chrono::microseconds>( end - start );
std::cout << "\nStandard library runtime : " << elapsed.count() << "ms";
std::cout << "\n\n";
}
</code></pre>
<p>On executing main, the following output were produced</p>
<pre><code>Size of queue is 1000000
Front of queue: 0
Back of queue: 999999
Queue is empty: false
Queue is empty: true
My runtime : 75378ms
Size of queue is 1000000
Front of queue: 0
Back of queue: 999999
Queue is empty: false
Queue is empty: true
Standard library runtime : 55720ms
</code></pre>
<p>Compiled and executed using <code>std=c++14</code> on a unix operating system</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T21:28:16.160",
"Id": "495271",
"Score": "0",
"body": "More importantly than C++ version did you do timings with optimized builds?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T10:01:26.533",
"Id": "495346",
"Score": "0",
"body": "No, I didn't use optimized builds."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T18:21:51.907",
"Id": "495422",
"Score": "1",
"body": "Then the numbers are not really useful to make a comparison with."
}
] |
[
{
"body": "<p>First of all, this is well-written code.</p>\n<h1>Ordering members of a class</h1>\n<p>Currently, your <code>Queue</code> class has the following order</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>class Queue\n{\n private:\n // private stuff\n \n public:\n // public stuff\n \n};\n</code></pre>\n<p>A lot of C++ programmers, including me, like to have public declarations first. <br>To quote from <a href=\"https://stackoverflow.com/questions/308581/how-should-i-order-the-members-of-a-c-class\">this thread on Stack Overflow</a></p>\n<blockquote>\n<p>It's my opinion, and I would wager a guess that most people would\nagree, that public methods should go first. One of the core principles\nof OO is that you shouldn't have to care about the implementation. Just\nlooking at the public methods should tell you everything you need to\nknow to use the class.</p>\n</blockquote>\n<pre class=\"lang-cpp prettyprint-override\"><code>class Queue \n{\n\n public:\n //...\n\n private:\n //...\n\n}\n</code></pre>\n<hr />\n<h1>Use a constant reference</h1>\n<p>take your <code>push()</code> function as an example</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>inline void push(T x);\n</code></pre>\n<p>Me, a random C++ developer decides to use your library and creates a queue in the following manner</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>class My_HUGE_class\n{\n // ...\n};\n\n\nint main()\n{\n Queue < My_Huge_class > foo;\n\n My_Huge_class x;\n foo.push(x);\n}\n</code></pre>\n<p>Look at what you've done! You have just copied the whole <code>x</code> object when the user merely tried to append something. A really expensive operation!</p>\n<p>If you had a doubt whether inlining the function would change that, <a href=\"https://stackoverflow.com/questions/722257/should-i-take-arguments-to-inline-functions-by-reference-or-value#:%7E:text=Yes%2C%20it%20will%20create%20a,the%20behavior%20of%20a%20function.\">no it won't</a>. You should always pass by a constant reference.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>void push(const T& x);\n</code></pre>\n<p>This will avoid any unnecessary copies.</p>\n<hr />\n<h1>Delete your linked list</h1>\n<p>This one is important</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>~Queue()\n{\n delete head;\n delete tail;\n}\n</code></pre>\n<ul>\n<li>Edit: As pointed out by @1201ProgramAlarm in the comments, you can't use a single delete keyword for multiple pointers - <code>delete x,y</code>, you will have to use one for each.</li>\n</ul>\n<p>There is a problem here, assume you have a <code>Queue<int> x</code></p>\n<p>After deletion, look at what happens</p>\n<p><a href=\"https://i.stack.imgur.com/GjGpr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/GjGpr.png\" alt=\"ll\" /></a></p>\n<p>You deleted the head and tail, everything else is floating around since it doesn't get deleted automatically.<br><You need to traverse through the list, and delete the nodes one by one. Here is the implementation</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>void deleteList() \n{ \n ListNode<T> * current = head; \n ListNode<T> * next; \n\n while (current != NULL) \n { \n next = current->next; \n delete current;\n current = next; \n } \n head = NULL; \n tail = NULL;\n} \n</code></pre>\n<hr />\n<h1>Should you overload the <code><<</code> operator?</h1>\n<p>I strongly believe that this is a bad idea. I can explain in a very simple manner</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>\nQueue < int > a{1,2,3,4,5};\nQueue < int > b{5,4,3,2,1};\n\nstd::cout << a; // valid!\n\nQueue < Queue < int > > c{a,b};\n\nstd::cout << b; // illegal `<<` operator for class!\n</code></pre>\n<p>Your overload will only work for types that can be printed using <code><<</code>, nothing else at all.</p>\n<hr />\n<h1>Nitpicks</h1>\n<pre class=\"lang-cpp prettyprint-override\"><code>inline T& front()\n{\n if (head != nullptr) return head->data;\n else throw std::out_of_range("Queue is empty");\n}\n\ninline T& back()\n{\n if (tail != nullptr) return tail->data;\n else throw std::out_of_range("Queue is empty");\n}\n</code></pre>\n<p>The <code>else</code> isn't necessary here, because if the previous condition is true, the control never reaches the front.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>inline T& front()\n{\n if (head != nullptr) return head->data;\n throw std::out_of_range("Queue is empty");\n}\n\ninline T& back()\n{\n if (tail != nullptr) return tail->data;\n throw std::out_of_range("Queue is empty");\n}\n</code></pre>\n<ul>\n<li><p>consider using <code>const</code> - <code>inline bool empty() const</code> if you aren't modifying any member variables</p>\n</li>\n<li><p>it is always good practice to have a comment after your <code>endif</code> to state which <em>if</em> it <em>ends</em></p>\n</li>\n</ul>\n<hr />\n<h1>Copy constructor</h1>\n<p>consider this scenario</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>Queue < int > a{1, 2, 3, 4, 5};\nQueue < int > b(a);\n\nstd::cout << b;\n</code></pre>\n<p>On my visual c++ compiler, this directly triggers an assertion and <strong>fails</strong>. You haven't declared a constructor in <code>Queue</code> that takes in another <code>Queue</code>, so C++ did that for you. But this performs a <a href=\"https://www.learncpp.com/cpp-tutorial/915-shallow-vs-deep-copying/\" rel=\"nofollow noreferrer\">shallow copy</a>. Very bad for these kinds of classes</p>\n<blockquote>\n<p>This is because shallow copies of a pointer just copy the address of\nthe pointer -- it does not allocate any memory or copies the contents\nbeing pointed to!</p>\n</blockquote>\n<p>You <em><strong>must</strong></em> define your own <a href=\"https://en.cppreference.com/w/cpp/language/copy_constructor\" rel=\"nofollow noreferrer\">copy constructor</a></p>\n<hr />\n<h1>More functionality</h1>\n<p>A few things I would like to see</p>\n<ul>\n<li>Overload of the equality operators to compare two lists</li>\n<li>Ability to delete a single node</li>\n</ul>\n<h1>Regarding splitting into a <code>.cpp</code> file</h1>\n<p>You have defined all the functions in your header file, after reading your question</p>\n<blockquote>\n<p>Can Implementation be separated from its interface whilst using templates?<br></p>\n</blockquote>\n<p><a href=\"https://stackoverflow.com/questions/1724036/splitting-templated-c-classes-into-hpp-cpp-files-is-it-possible\"><strong>No :(</strong></a>, not neatly at least. Do read the link I cited.</p>\n<p>That is the price you pay with templates,</p>\n<hr />\n<h1>Comparing to the STL library</h1>\n<p><sup> all code here is from the Standard Template library </sup></p>\n<p>Let's see what actually happens when you create a <code>std::queue</code> in your tests.</p>\n<p>if you see the constructor of <code>queue</code></p>\n<pre class=\"lang-cpp prettyprint-override\"><code>template <class _Ty, class _Container = deque<_Ty>>\nclass queue;\n\n///\n\ntemplate <class _Ty, class _Container>\nclass queue {\n\n};\n</code></pre>\n<p>This means that when you created your <code>queue<int></code>, you just created a new <code>deque</code>. So when you do <code>.push()</code> in a <code>queue</code>, whats really happening is\njust <code>push_back()</code>, which is defined in <code>class deque</code>. If you have a look at those functions</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> void push_front(_Ty&& _Val) {\n _Orphan_all();\n _PUSH_FRONT_BEGIN;\n _Alty_traits::construct(_Getal(), _Unfancy(_Map()[_Block] + _Newoff % _DEQUESIZ), _STD move(_Val));\n _PUSH_FRONT_END;\n }\n\n void push_back(_Ty&& _Val) {\n _Orphan_all();\n _Emplace_back_internal(_STD move(_Val));\n }\n</code></pre>\n<p>The code is already getting out of control. Time to stop<br></p>\n<p><code>std::deque</code> is <strong>not</strong> a linked list. It is a <a href=\"https://en.wikipedia.org/wiki/Circular_buffer#:%7E:text=In%20computer%20science%2C%20a%20circular,easily%20to%20buffering%20data%20streams.\" rel=\"nofollow noreferrer\">circular buffer</a>, which is very different from a linked list, which is already extremely <a href=\"https://stackoverflow.com/questions/45717938/efficient-linked-list-in-c/45718641#:%7E:text=std%3A%3Alist%20is%20an,particularly%20for%20small%20data%20types.\">in-efficient</a></p>\n<p>Hence, it is not a fair comparison. A deque is more like a vector. Both of them are fundamentally very different.</p>\n<p><a href=\"https://stackoverflow.com/questions/1436020/whats-the-difference-between-deque-and-list-stl-containers\"><code>std::deque vs std::list</code> in C++</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T21:17:06.547",
"Id": "495261",
"Score": "0",
"body": "`It's my opinion, and I would wager a guess that most people would agree`. I disagree: Private members first. Public methods. Private methods. Is the best order. There should be very few private members so putting them at the top is not an issue and they are easily ignored it you just want the public interface (for why see below). Then public methods as this is what most people want to read. Private methods last as they may be large and inconsequential to a lot of readers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T21:17:09.123",
"Id": "495262",
"Score": "0",
"body": "The reason to put private members first is to make the job of code review and validation easy for reviewers and people that are interested in how the code works. The first thing I check is that the constructors/destructors and assignment operators all work correctly with the members and the object is initialized correctly. Having to scroll to the bottom then scroll to the top and jump backwards and forwards to validate these is harder when they are not next to the initialization routines (which are usually the first public methods)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T21:22:49.633",
"Id": "495267",
"Score": "0",
"body": "Don't agree with your logic for not overloading the output operator. Its pretty standard. Just because you may not always be able to print out members does not mean I don't want to be able to print out a container."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T21:24:28.023",
"Id": "495268",
"Score": "0",
"body": "When mentioning the issue with the copy constructor (self copy and shallow copy). You should talk about the rule of three."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T21:26:08.350",
"Id": "495270",
"Score": "0",
"body": "`Can Implementation be separated from its interface whilst using templates?` Yes. Easily. Just use a *.tpp file for the implementation. This is included by the header file. Relatively common for non trivial templates. In this case its not worth it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T22:21:43.213",
"Id": "495275",
"Score": "0",
"body": "Good review. Like all the points."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T03:32:13.993",
"Id": "495315",
"Score": "0",
"body": "@MartinYork I would disagree with the operator overloadig point, since if it was \" pretty standard \", then the STL containers would have it too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T03:33:14.377",
"Id": "495316",
"Score": "0",
"body": "@MartinYork Sorry about the `//private function` thing though, that was really stupid."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T03:41:16.420",
"Id": "495317",
"Score": "0",
"body": "@MartinYork Some programmers might want to split the values using commas, some might want to print each on a new line. For those reasons, I would leave overloading the `<<` operator to be the programmers choice"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T03:42:23.190",
"Id": "495318",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/115825/discussion-between-aryan-parekh-and-martin-york)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T03:49:05.433",
"Id": "495319",
"Score": "0",
"body": "`delete head, tail` will delete head and do nothing to tail. Why are you using `free` in your `deleteList` implementation? It should probably set `tail = NULL` as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T03:59:29.680",
"Id": "495320",
"Score": "0",
"body": "@1201ProgramAlarm Sorry about all of that, I have fixed that now."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T19:20:08.923",
"Id": "251496",
"ParentId": "251492",
"Score": "4"
}
},
{
"body": "<h2>Comments:</h2>\n<blockquote>\n<p>I aim to have a deeper understanding of templates in C++</p>\n</blockquote>\n<p>Good example to use to develop these skills:</p>\n<hr />\n<blockquote>\n<p>I aim to make it look and feel close to the standard library's implementation in terms of memory usage, speed and readability.</p>\n</blockquote>\n<p>That will be harder. You have the same characteristics as <code>std::list</code> while the standard version <code>std::queue</code> uses a <code>std::deque</code> as the underlying container that has very different characteristcs.</p>\n<p>See this question for the differences: <a href=\"https://stackoverflow.com/q/181693/14065\">What are the complexity guarantees of the standard containers?</a></p>\n<blockquote>\n<p>The standard library performance was twice as better as mine. What may be reasons?</p>\n</blockquote>\n<p>Though they will look very similar. The technique of creating a new node dynamically for every push (std::list) is relatively expensive. This cost is amortized by allocating space for a bunch of objects (std::dequeue) in one go and then using them up as you need them.</p>\n<p>The other benefit is locality of reference. In a (std::deque) objects are close to each other and thus likely to more efficiently accessed because of hardware caching that will make sure objects close to each other become available quicker.</p>\n<hr />\n<blockquote>\n<p>I initially didn't want to write the implementation of Queue in its header files, but it resulted to all sort of errors. Can Implementation be seprated from its interface whilst using templates?</p>\n</blockquote>\n<p>It can. But for such a simple class I would not bother.</p>\n<pre><code>// LinkeddList.h\n#ifndef INCLUDE_GUARD\n#define INCLUDE_GUARD\nnamespace Stuff\n{\n class LinkedList\n {\n // STUFF\n public:\n void push(int);\n };\n}\n#include "LinkedList.tpp"\n#endif\n\n// LinkedList.tpp\n#ifndef INCLUDE_GUARD\n#error "You should include LinkedList.h" not this file.\n#endif\ninline void Stuff::LinkedList::push(int x)\n{\n // STUFF\n}\n....\n</code></pre>\n<hr />\n<h2>Overview</h2>\n<p>You have missed the rule of three.<br />\ni.e. CopyConstruction and Copy Assignment does not work.</p>\n<p>You have not considered move semantics. Big objects are copied into your queue. You could make this a lot more efficient by moving objects into your queue.</p>\n<p>Once you have added move semantics you need to remember the rule of five.</p>\n<p>The <code>ListNode</code> type is tightly coupled to the <code>Queue</code> type. There is no benifit to exposing the <code>ListNode</code> to users of your class as this simply locks you into maintaining for all future versions (what happens if you want to change it to doubly linked at some future time). Make this a private member of the <code>Queue</code> class so that your implementation details don't leak.</p>\n<h2>Code Review</h2>\n<p>Please add a namespace to wrap your personal stuff.</p>\n<hr />\n<p>That is a long line with lots of data:</p>\n<pre><code>template< typename T > struct ListNode\n</code></pre>\n<p>Normally I would see this:</p>\n<pre><code>template<typename T>\nstruct ListNode\n</code></pre>\n<hr />\n<p>Sure that's a constructor:</p>\n<pre><code> ListNode() : next_ptr( nullptr ) {}\n</code></pre>\n<p>But why not initialize all members?</p>\n<p>The problem this causes is that if <code>T</code> does not have a default constructor (A constructor that takes no arguments) you can not create objects of <code>ListNode</code>. So I would add a constructor that allows you to pass the data object.</p>\n<p>So you should do:</p>\n<pre><code> ListNode(T const& data): data(data), next_ptr( nullptr ) {}\n ListNode(T&& data): data(std::move(data), next_ptr( nullptr ) {}\n</code></pre>\n<p>But looking at your code you always set <code>next_ptr</code> just after creating the node. Why not then pass the next pointer as an argument to the constructor to simplify this processes.</p>\n<pre><code> ListNode(T const& data, ListNode* next): data(data), next_ptr( next ) {}\n ListNode(T&& data, ListNode* next): data(std::move(data), next_ptr( next ) {}\n</code></pre>\n<p>That's great. It now does everything you need. But there is already a constructor that does this that is implemented automatically by the compiler. So why have a constructor. Just use the default implementation and it will do all the work for you.</p>\n<pre><code>struct ListNode\n{\n T data;\n ListNode *next_ptr;\n};\n</code></pre>\n<hr />\n<p>What is this used for?</p>\n<pre><code> ListNode<T> node; // Were you planning on using a sentinel?\n</code></pre>\n<hr />\n<p>OK. head and tail.</p>\n<pre><code> ListNode<T> *head, *tail;\n</code></pre>\n<p>Why be lazy and squeeze this on one line. Make it easy to read put it on two. All coding standards you find will also specify the same thing. There is no reason to do this and make it hard to read.</p>\n<hr />\n<p>Is <code>size_t</code> always in the global namespace?</p>\n<pre><code> size_t queue_size;\n</code></pre>\n<p>Nope. You can force that by including certain headers. But do you want to do that with C++ code where all the other types are in the <code>std</code> namespace? Use <code>std::size_t</code>.</p>\n<hr />\n<p>This doe's not delete the queue.</p>\n<pre><code> ~Queue() \n {\n delete head, tail;\n }\n</code></pre>\n<p>You are missing all elements that are not head/tail.</p>\n<hr />\n<p>Don't use <code>inline</code> here.</p>\n<pre><code> inline void push( T x )\n</code></pre>\n<p>All method declarations in a class are already <code>inline</code> by default. And <code>inline</code> does not mean <code>inline the code</code> it tells the linker there may be multiple definitions in object files for this function it they can safely be ignored.</p>\n<p>The use of <code>inline</code> for inline-ing code is redundant. The compiler already makes the best choices and does it automatically (better than us puny humans). People may argue that there are other keywords for forcing inlining sure. But don't think humans make the choice of adding those compiler specific commands (unless your an idiot human). These are added once you have proved the compiler is making an non optimal choice you want to force it one way or another (that is hard work).</p>\n<hr />\n<p>As noted before you should probably pass by const reference or r-value reference for efficiency.</p>\n<pre><code> void push(T x) // The parameter is copied here.\n\n\n // use\n void push(T const& x) // pass a reference remvoe one copy. \n void push(T&& x) // pass by r-value ref allow move.\n</code></pre>\n<hr />\n<p>I would simplify your push to:</p>\n<pre><code> void push(T const& x)\n {\n head = new ListNode<T>(x, head);\n if (tail == nullptr) {\n tail = head;\n }\n ++queue_size;\n }\n void push(T&& x)\n {\n head = new ListNode<T>(std::move(x), head);\n if (tail == nullptr) {\n tail = head;\n }\n ++queue_size;\n }\n</code></pre>\n<hr />\n<p>Sure you can check the operation is valid.</p>\n<pre><code> inline void pop()\n {\n if( head == nullptr ) throw std::out_of_range( "Queue is empty" );\n</code></pre>\n<p>But the standard libraries don't. They allow you to break the users code here. The logic is there is a a way for them to check externally <code>empty()</code> and they should be using this. Its their fault if they are bad programmers.</p>\n<p>In C++ the standard behavior is that code should be optimal in all situations. Consider this situation:</p>\n<pre><code> while(!queue.empty()) {\n queue.pop();\n }\n</code></pre>\n<p>Why are you making me pay the price of a check inside <code>pop()</code> when I have already payed the price externally. Its twice as expensive as it needs to be.</p>\n<p>Now we do understand there are beginners out there. So we also provide methods that do check for situations where it would be nice for the interface to perform the check:</p>\n<p>Example:</p>\n<pre><code> for(int loop = 0;loop < vec.size(); ++loop)\n std::cout << "Loop: " << loop << " " << vec[loop] << "\\n"; // No check on accesses.\n\n\n std::cout << "Loop: " << loop << " " << vec.at(15) << "\\n"; // Checked accesses.\n</code></pre>\n<p>The <code>std::vector</code> provides two methods to accesses elements. Once is checked you can use this in situations where you have not done the check externally. While the other is not checked and can be used when you know the input is always in range.</p>\n<pre><code> T& operator[](int index);\n T& at(int index);\n</code></pre>\n<hr />\n<hr />\n<p>Same argument on checking here:</p>\n<pre><code> inline T& front()\n {\n if( head != nullptr ) return head->data;\n else throw std::out_of_range( "Queue is empty" );\n }\n\n inline T& back()\n {\n if( tail != nullptr ) return tail->data;\n else throw std::out_of_range( "Queue is empty" );\n }\n</code></pre>\n<hr />\n<p>Functions that do not change the state of an object should be marked const. Thus when you pass the Queue by const reference to a function you can still accesses functions that don't mutate the object.</p>\n<p>The obvious functions here are:</p>\n<pre><code> std::size_t size() const { return queue_size;} // No change in state.\n\n bool empty() const; // This never mutates the object.\n //\n // Should be able to tell if a Queue is empty and \n // its size even when you only have a const reference\n // to the obejct\n</code></pre>\n<p>Less obvious are the <code>front()</code> and <code>back()</code> methods. Here you can have two modes. There can be a mutating version that allows you to mutate the members in the queue (if you want that functionality (not sure you do in a queue)).</p>\n<pre><code> // Mutatable accesses\n T& front() {return head->data;}\n T& back() {return tail->data;}\n\n // Non Mutatable accesses\n T const& front() const {return head->data;}\n T const& back() const {return tail->data;}\n</code></pre>\n<hr />\n<p>This is an anti pattern:</p>\n<pre><code> if (test) {\n return true;\n }\n else {\n return false;\n }\n</code></pre>\n<p>You can simplify it to:</p>\n<pre><code> return test;\n</code></pre>\n<p>So lets look at <code>empty()</code>:</p>\n<pre><code> bool empty()\n {\n if( head == nullptr ) return true;\n return false;\n }\n\n // Simplify to:\n bool empty() const\n {\n return head == nullptr;\n }\n</code></pre>\n<h2>HowTo</h2>\n<h3>Queue.h</h3>\n<pre><code>#ifndef THORSANVIL_QUEUE_H\n#define THORSANVIL_QUEUE_H\n \n\n#include <iostream>\n#include <initializer_list>\n\nnamespace ThorsAnvilExamples\n{\n\ntemplate<typename T>\nclass Queue\n{\n struct ListNode\n {\n T data;\n ListNode *next_ptr;\n };\n template<typename E>\n class iteratorBase\n {\n ListNode* data;\n public:\n iteratorBase(ListNode* d): data(d) {}\n E& operator*() {return data->data;}\n E* operator->() {return &data->data;}\n iteratorBase& operator++() {data = data->next_ptr;return *this;}\n iteratorBase operator++(int) {iterator tmp(*this);++(*this);return tmp;}\n bool operator==(iteratorBase const& rhs) {return data == rhs.data;}\n bool operator!=(iteratorBase const& rhs) {return data != rhs.data;}\n };\n\n\n private:\n ListNode* head = nullptr;\n ListNode* tail = nullptr;\n std::size_t qsize = 0;\n public:\n Queue()\n {}\n Queue(std::initializer_list<T> list)\n {\n for(T const& item: list) {\n push(item);\n }\n }\n Queue(Queue const& copy)\n {\n for(T const& item: copy) { // Add begin() and end()\n push(item);\n }\n }\n Queue& operator=(Queue const& copy)\n {\n Queue tmp(copy);\n swap(tmp);\n return *this;\n }\n Queue(Queue&& move) noexcept\n {\n swap(move);\n }\n Queue& operator=(Queue&& copy) noexcept\n {\n swap(copy);\n return *this;\n }\n void swap(Queue& other) noexcept\n {\n using std::swap;\n swap(head, other.head);\n swap(tail, other.tail);\n swap(qsize, other.qsize);\n }\n ~Queue() \n {\n ListNode* old;\n while(head != nullptr) {\n old = head;\n head = head->next_ptr;\n delete old;\n }\n }\n friend void swap(Queue& lhs, Queue& rhs)\n {\n lhs.swap(rhs);\n }\n\n using iterator = iteratorBase<T>;\n using const_iterator = iteratorBase<T const>;\n iterator begin() {return iterator{head};}\n const_iterator begin() const {return const_iterator{head};}\n const_iterator cbegin()const {return const_iterator{head};}\n iterator end() {return iterator{nullptr};}\n const_iterator end() const {return const_iterator{nullptr};}\n const_iterator cend() const {return const_iterator{nullptr};}\n\n void push(T const& x) {add(new ListNode{x, head});}\n void push(T&& x) {add(new ListNode{std::move(x), head});}\n template<typename... Args>\n void push(Args&&... args) {add(new ListNode{T(std::move(args)...), head});}\n\n void pop()\n {\n ListNode* old = head;\n head = head->next_ptr;\n delete old;\n --qsize;\n }\n T const& front() const {return head->data;}\n T const& back() const {return tail->data;}\n bool empty() const {return head == nullptr;}\n std::size_t size() const {return qsize;}\n\n void print(std::ostream& str = std::cout) const\n {\n if (head) {\n str << head->data;\n for(ListNode* temp = head->next_ptr; temp != nullptr; temp = temp->next_ptr) {\n str << " " << temp->data;\n }\n }\n }\n friend std::ostream &operator<<(std::ostream &str, const Queue &q)\n {\n q.print(str);\n return str;\n }\n private:\n void add(ListNode* newhead)\n {\n head = newhead;\n if( tail == nullptr ) {\n tail = head;\n }\n ++qsize;\n }\n\n};\n\n}\n\n#endif\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T22:21:09.617",
"Id": "251569",
"ParentId": "251492",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "251496",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T18:03:30.570",
"Id": "251492",
"Score": "2",
"Tags": [
"c++",
"performance",
"linked-list",
"reinventing-the-wheel",
"template"
],
"Title": "Linked List Queue Implementation"
}
|
251492
|
<p>I have this class that's meant to represent a binary expression. The immediate improvement I'd like to make is to not have to declare the intermediate type of the operands; when declaring the expression, I'd like only to have to give it an input and an output. But output type of the 2 operands must match for compatibility sake. Let me demonstrate:</p>
<pre class="lang-csharp prettyprint-override"><code> var gt = new GreaterThanOperator();
var input = new BookingState();
var left = new ConstantOperand<BookingState,double>(10d);
var right = new ConstantOperand<BookingState,double>(20d);
var leftExpression = new Expression<BookingState, double, bool>(left, gt, right);
</code></pre>
<p>I would ideally like to reduce the code to be more inline with:</p>
<pre class="lang-csharp prettyprint-override"><code> var gt = new GreaterThanOperator();
var input = new BookingState();
// remove 'double' because it's redundant with the constructor param
var left = new ConstantOperand<BookingState>(10d);
var right = new ConstantOperand<BookingState>(20d);
// remove 'double' because it's derived from operand, and 'bool' because it's derived from the
// operator return type
var leftExpression = new Expression<BookingState>(left, gt, right);
</code></pre>
<p>I think, but I am not sure (and hence why I am here), that I could get there with the usage of factory methods (since I will want all expressions unique and shared as they are stateless; however, that's for another post)</p>
<pre class="lang-csharp prettyprint-override"><code> public class Expression<T,M,TOutput> : AbstractOperand<T,TOutput>
{
private readonly IOperand<T, M> left;
private readonly IOperator<M, TOutput> op;
private readonly IOperand<T, M> right;
public Expression(IOperand<T, M> left, IOperator<M, TOutput> op, IOperand<T, M> right): base(input => op.Apply(left.GetValue(input), right.GetValue(input)))
{
this.left = left;
this.op = op;
this.right = right;
}
public TOutput Evaluate(T input) => base.GetValue(input);
public override string ToString() => $"({left} {op} {right})";
}
</code></pre>
<p>IOperand</p>
<pre><code>
public interface IOperand<T,TResult> : IEquatable<IOperand<T,TResult>>
{
int Id { get; }
TResult GetValue(T input);
}
</code></pre>
<p>IOperator</p>
<pre><code> public interface IOperator<in T, out TResult>
{
int Id { get; }
ISet<string> Registrations { get; }
TResult Apply(T left, T right);
}
</code></pre>
<p>AbstractOperator</p>
<pre><code> public abstract class AbstractOperator<T, TOutput> : IOperator<T, TOutput>
{
private static int idCounter = 0;
private readonly Func<T,T, TOutput> f;
public AbstractOperator(ISet<string> registrations,Func<T,T, TOutput> f)
{
this.Id = idCounter++;
this.f = f;
this.Registrations = registrations;
}
public int Id {
get;
private set;
}
public ISet<string> Registrations {
get;
private set;
}
public TOutput Apply(T left, T right) => f(left,right);
}
</code></pre>
<p>LogicalOperator</p>
<pre><code> public abstract class LogicalOperator<T> : AbstractOperator<T,bool>
{
public LogicalOperator(ISet<string> registrations, Func<T, T, bool> f) : base(registrations, f) { }
}
</code></pre>
<p>GreaterThanOperator</p>
<pre><code> public class GreaterThanOperator : LogicalOperator<double>
{
public GreaterThanOperator() : base(registrations,(left, right) => left > right) { }
private static ISet<string> registrations = new HashSet<String>{"gt", ">"};
public override string ToString() => ">";
}
</code></pre>
<p><strong>UPDATE</strong></p>
<p>I have since updated it to use factory methods and it doesn't help (or at least I can't figure out how):</p>
<pre><code>var rightExpression = Expression<BookingState, double, bool>.GetInstance(left, gt, right, "50 is greater than Foo.Bar");
</code></pre>
<p>It's <em>more</em> verbose now</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T13:44:59.960",
"Id": "495217",
"Score": "0",
"body": "Is having them as non static classes required? Cause as you mentioned the only way to make this work is with the builder pattern. Kinda like `var left = BookingState.ApplyOperand(ConstantOperand, 20d)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T16:48:03.673",
"Id": "495229",
"Score": "0",
"body": "Yeah, I was thinking so - I started implementing something similar. But, I wasn't sure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T09:13:23.533",
"Id": "495342",
"Score": "0",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T18:12:18.040",
"Id": "251493",
"Score": "1",
"Tags": [
"c#"
],
"Title": "C# : Can I simplify the generics here"
}
|
251493
|
<p>I want to test the performance for various types of containers in Haskell. So far I got Vector and List. My goal is to learn how to use typeclass, how to use containers etc. Could anyone point out suggestions of below code?</p>
<pre><code>module Lib where
import Data.Array
import Data.List
import qualified Data.Vector.Algorithms.Radix as R
import qualified Data.Vector.Unboxed as V
import System.CPUTime
import System.Random
import Text.Printf
class TestSTL t where
stlGenerate ::(Random a, V.Unbox a) => Int -> IO (t a) --generate random number of t a
stlSort :: (Ord a, V.Unbox a, R.Radix a) => t a -> t a
stlSearchIndex :: (Ord a, V.Unbox a) => a -> t a -> Maybe Int
instance TestSTL [] where
stlGenerate i = take i . randoms <$> getStdGen
stlSort l = sort l
stlSearchIndex = elemIndex
instance TestSTL V.Vector where
stlGenerate i = V.replicateM i randomIO
stlSort = V.modify R.sort
stlSearchIndex = V.elemIndex
-- instance (Ix ix) => TestSTL (Array ix) where
-- stlGenerate i = take i . randoms <$> getStdGen
-- stlSort l = sort l
-- stlSearchIndex = elemIndex
time :: IO a -> IO a
time action = do
t0 <- getCPUTime
r <- action
t1 <- getCPUTime
let tm :: Double
tm = fromInteger (t1 - t0) * 1e-9
printf "%.3f ms\n" tm
return r
test :: IO ()
test = do
-- preparation
putStrLn "Please input an Int:"
e <- readLn :: IO Int
-- test list
putStrLn "Testing List:"
r <- time
$ stlSearchIndex e . stlSort
<$> (stlGenerate 1000000 :: IO [Int])
case r of
Just i -> putStrLn $ "Found at " ++ show i
Nothing -> putStrLn "Not found"
-- test vector
putStrLn "Testing Vector:"
r' <- time
$ stlSearchIndex e . stlSort
<$> (stlGenerate 1000000 :: IO (V.Vector Int))
case r' of
Just i -> putStrLn $ "Found at " ++ show i
Nothing -> putStrLn "Not found"
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T19:00:52.200",
"Id": "251494",
"Score": "3",
"Tags": [
"haskell"
],
"Title": "Haskell test performance for different container types"
}
|
251494
|
<p>Below is a (very) simplified version of a function I made that creates multiple REST requests to gather needed information.</p>
<p>Things to note:</p>
<ul>
<li>One of the REST calls is dependent upon the output of another.</li>
<li>I want to send off multiple requests at the same time when possible</li>
<li>If any rest responses inform us that the user is logged out, null should be returned.</li>
</ul>
<pre class="lang-javascript prettyprint-override"><code>async function gatherUserInfo(userId) {
try {
// Don't await yet, so this request can be sent at the same time as future requests.
const groupsRequest = getGroups(userId)
const {username, name} = await getProfile(userId)
return {
username,
name,
statusText: await getStatusText(username),
groups: await groupsRequest,
}
} catch (err) {
if (err instanceof NotLoggedInError) {
return null
}
throw err
}
}
</code></pre>
<p>I found the above code to be a very elegant solution to the problem. However, I recently realized that it won't actually work in node, because node will give warning or stop execution (depending on version) if an uncaught error happens in a promise. In the example above, the getGroups() call would send off a request (but not await it). Then, this function execution will pause on getProfile(). In the meantime, getGroups() will come back with the NotLoggedInError, which will result in the process being terminated, because that promise has not been awaited yet, (the try-catch can't catch the error until the await happens, which does happen later in the function execution).</p>
<p>So, I reluctantly trashed my old design and coded this up instead:</p>
<pre class="lang-javascript prettyprint-override"><code>async function gatherUserInfo(userId) {
const requests = [];
requests.push(
getGroups(userId)
.then(groups => ({groups}))
)
requests.push(
getProfile(userId)
.then(async ({username, name}) => {
const statusText = await getStatusText(username)
return {username, name, statusText}
})
)
let responses
try {
responses = await Promise.all(requests)
} catch (err) {
if (err instanceof NotLoggedInError) {
return null
}
throw err
}
return Object.assign({}, ...responses)
}
</code></pre>
<p>This is much harder to follow or understand, but it's the best I could come up with. How can this code be improved?</p>
<p>Here's some stub methods and test cases that can be paired with the examples above to execute them:</p>
<pre><code>// Mocks //
async function getGroups(userid) {
await wait(50)
if (userid !== 12) throw new NotLoggedInError('User not logged in')
return ['group A', 'group B'];
}
async function getProfile(userid) {
await wait(30)
if (userid !== 12) throw new NotLoggedInError('User not logged in')
return { username: 'grinchMaster135', name: 'The Grinch' };
}
async function getStatusText(username) {
await wait(30)
return 'away'
}
class NotLoggedInError extends Error {}
const wait = ms => new Promise(resolve => setTimeout(resolve, ms))
// TEST //
;(async function() {
console.log('Grinch info:', await gatherUserInfo(12)) // Grinch info: { username: 'grinchMaster135', name: 'The Grinch', groups: [ 'group A', 'group B' ], statusText: 'away' }
console.log('Non-logged in user info:', await gatherUserInfo(13)) // Non-logged in user info: null
})()
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>When you have multiple asynchronous requests to make, and you want them to operate in parallel, usually the appropriate tool to use is <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all\" rel=\"noreferrer\"><code>Promise.all</code></a>. You can use it here to wait for the groups and the profile data at once, despite the fact that the two requests are pretty distinct from each other:</p>\n<pre><code>async function gatherUserInfo(userId) {\n try {\n const [groups, {username, name}] = await Promise.all([\n getGroups(userId),\n getProfile(userId),\n ])\n return {\n username,\n name,\n groups,\n statusText: await getStatusText(username),\n }\n } catch (err) {\n if (err instanceof NotLoggedInError) {\n return null\n }\n throw err\n }\n}\n</code></pre>\n<p>This way, if any one of the Promises rejects, it will be being <code>await</code>ed at that time, so it'll be caught properly.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>async function gatherUserInfo(userId) {\n try {\n const [groups, {username, name}] = await Promise.all([\n getGroups(userId),\n getProfile(userId),\n ])\n return {\n username,\n name,\n groups,\n statusText: await getStatusText(username),\n }\n } catch (err) {\n if (err instanceof NotLoggedInError) {\n return null\n }\n throw err\n }\n}\n\n\n\nasync function getGroups(userid) {\n await wait(50)\n if (userid !== 12) throw new NotLoggedInError('User not logged in')\n return ['group A', 'group B'];\n}\n\nasync function getProfile(userid) {\n await wait(30)\n if (userid !== 12) throw new NotLoggedInError('User not logged in')\n return { username: 'grinchMaster135', name: 'The Grinch' };\n}\n\nasync function getStatusText(username) {\n await wait(30)\n return 'away'\n}\n\nclass NotLoggedInError extends Error {}\n\nconst wait = ms => new Promise(resolve => setTimeout(resolve, ms))\n\n\n// TEST //\n\n;(async function() {\n console.log('Grinch info:', await gatherUserInfo(12)) // Grinch info: { username: 'grinchMaster135', name: 'The Grinch', groups: [ 'group A', 'group B' ], statusText: 'away' }\n console.log('Non-logged in user info:', await gatherUserInfo(13)) // Non-logged in user info: null\n})()</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>You could also have fixed the unhandled rejection by adding a no-op <code>.catch</code> handler to the Promise that was created before <code>await</code>ing the other Promise:</p>\n<pre><code>groupsRequest.catch(() => void 0);\n</code></pre>\n<p>But that makes the code less elegant - I think the <code>Promise.all</code> version is better.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>async function gatherUserInfo(userId) {\n try {\n // Don't await yet, so this request can be sent at the same time as future requests.\n const groupsRequest = getGroups(userId)\n groupsRequest.catch(() => void 0);\n\n const {username, name} = await getProfile(userId)\n return {\n username,\n name,\n groups: await groupsRequest,\n statusText: await getStatusText(username),\n }\n } catch (err) {\n if (err instanceof NotLoggedInError) {\n return null\n }\n throw err\n }\n}\n\n\n\nasync function getGroups(userid) {\n await wait(50)\n if (userid !== 12) throw new NotLoggedInError('User not logged in')\n return ['group A', 'group B'];\n}\n\nasync function getProfile(userid) {\n await wait(30)\n if (userid !== 12) throw new NotLoggedInError('User not logged in')\n return { username: 'grinchMaster135', name: 'The Grinch' };\n}\n\nasync function getStatusText(username) {\n await wait(30)\n return 'away'\n}\n\nclass NotLoggedInError extends Error {}\n\nconst wait = ms => new Promise(resolve => setTimeout(resolve, ms))\n\n\n// TEST //\n\n;(async function() {\n console.log('Grinch info:', await gatherUserInfo(12)) // Grinch info: { username: 'grinchMaster135', name: 'The Grinch', groups: [ 'group A', 'group B' ], statusText: 'away' }\n console.log('Non-logged in user info:', await gatherUserInfo(13)) // Non-logged in user info: null\n})()</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T20:39:32.043",
"Id": "495122",
"Score": "0",
"body": "Both yours and @joseph's contributions were similar, but unique and helpful. Thanks! (if only I could accept both).\n\nI don't think adding the .catch() would work, because that would cause the error to be silently ignored, instead of being caught by the try-catch. Which, I guess shouldn't really be an issue because other endpoints would return the same logged-out error, and it'll get caught anyways. But yes, Promise.all would be better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T21:15:08.150",
"Id": "495130",
"Score": "0",
"body": "The no-op `catch` does work, you can run the second snippet to see - just because a Promise is being caught in one place doesn't stop it from being able to be caught in the other place. `await somePromiseThatHasAlreadyRejected` will properly reject the containing `async` function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T22:41:06.370",
"Id": "495150",
"Score": "0",
"body": "aah, I should have looked closer. I read it as `groupRequest = getGroups(...).catch(...)` but you were doing `groupRequest = getGroups(...); groupRequest.catch(...)`, which are two very different things."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T20:21:14.663",
"Id": "251500",
"ParentId": "251497",
"Score": "5"
}
},
{
"body": "<p>Your code boils down to just executing <code>getGroups()</code> in parallel with the <code>getProfile()</code>-<code>getStatusText()</code> sequence.</p>\n<p>You might want to extract that sequence out to a separate function. This way, it's obvious that they're treated as one thing (two async calls build one object). You can then <code>Promise.all()</code> the return of this new function (<code>getStatus()</code> in the following example) and <code>getGroups()</code>. This way, you also make it obvious that the two calls are async and independent of each other.</p>\n<pre><code>// getProfile and getStatusText synchronous to each other.\nconst getStatus = async id => {\n const {username, name} = await getProfile(id)\n const statusText = await getStatusText(username)\n return { username, name, statusText }\n}\n\nconst gatherUserInfo = async userId => {\n try {\n\n // getStatus and getGroups will run asynchronous to each other.\n const [{ username, name, statusText }, groups] = await Promise.all([\n getStatus(userId),\n getGroups(userId)\n ])\n\n return { username, name, statusText, groups }\n\n } catch(e) {\n if (e instanceof NotLoggedInError) {\n return null\n }\n throw err\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T20:21:47.340",
"Id": "251501",
"ParentId": "251497",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "251501",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T19:21:40.047",
"Id": "251497",
"Score": "3",
"Tags": [
"javascript",
"node.js",
"asynchronous"
],
"Title": "Send multiple REST requests at the same time. (node)"
}
|
251497
|
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/251336/231235">An element_wise_add Function For Boost.MultiArray in C++</a>. Besides the basic add operation applying onto each element, I am trying to implement a sine template function which can apply <code>std::sin()</code> on each element. A new concept <code>with_std_sin</code> is created as below.</p>
<pre><code>template<typename T>
concept with_std_sin = requires(T x)
{
std::sin(x);
};
</code></pre>
<p>The main body of this <code>sin</code> template function is here. The similar recursive technique is also used in order to go through all elements.</p>
<pre><code>template<class T> requires (with_std_sin<T>)
auto sin(const T& input)
{
return std::sin(input);
}
template<class T> requires (is_multi_array<T>)
auto sin(const T& input)
{
boost::multi_array output(input);
for (decltype(+input.shape()[0]) i = 0; i < input.shape()[0]; i++)
{
output[i] = sin(input[i]);
}
return output;
}
</code></pre>
<p>The test of this <code>sin</code> template function:</p>
<pre><code>// Create a 3D array that is 3 x 4 x 2
typedef boost::multi_array<double, 3> array_type;
typedef array_type::index index;
array_type A(boost::extents[3][4][2]);
// Assign values to the elements
int values = 1;
for (index i = 0; i != 3; ++i)
for (index j = 0; j != 4; ++j)
for (index k = 0; k != 2; ++k)
A[i][j][k] = values++;
for (index i = 0; i != 3; ++i)
for (index j = 0; j != 4; ++j)
for (index k = 0; k != 2; ++k)
std::cout << A[i][j][k] << std::endl;
auto test_result = sin(A);
for (index i = 0; i != 3; ++i)
for (index j = 0; j != 4; ++j)
for (index k = 0; k != 2; ++k)
std::cout << test_result[i][j][k] << std::endl;
</code></pre>
<p>All suggestions are welcome.</p>
<ul>
<li><p>Which question it is a follow-up to?</p>
<p><a href="https://codereview.stackexchange.com/q/251336/231235">An element_wise_add Function For Boost.MultiArray in C++</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p>The previous question is the implementation of applying add operation onto each element in Boost.MultiArray. The main idea in this question is to implement a <code>sin</code> template function for calculating trigonometric sine value of each element.</p>
</li>
<li><p>Why a new review is being asked for?</p>
<p>In my opinion, I am not sure is this a good idea about the implementation and the usage of the <code>with_std_sin</code> concept here. If there is any possible improvement, please let me know.</p>
</li>
</ul>
|
[] |
[
{
"body": "<p>It looks very simple and clean. I would change the name of <code>with_std_sin</code> though. There are some <a href=\"http://open-std.org/JTC1/SC22/WG21/docs/papers/2019/p1851r0.html#proposal\" rel=\"nofollow noreferrer\">guidelines for naming concepts</a> that suggest that it should be named <code>sinable</code>. That looks a bit weird, but everything I can think of to describe "something that std::sin supports" looks weird in some way, so it is as good as any name.</p>\n<p>However, consider that you might want to apply many other functions to the contents of a <code>boost::multi_array</code> as well, not just <code>std::sin</code>. In that case, a <code>recursive_transform()</code> that handles <code>multi_array</code>s is the way to go, so you could "just" write:</p>\n<pre><code>auto test_result = recursive_transform(A, [](auto &x){return std::sin(x);});\n</code></pre>\n<p>Or at least use that to define <code>sin()</code>, <code>cos()</code> and so on in therms of <code>recursive_transform()</code> without having to duplicate code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T21:01:12.813",
"Id": "251504",
"ParentId": "251499",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "251504",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T20:19:00.957",
"Id": "251499",
"Score": "2",
"Tags": [
"c++",
"recursion",
"boost",
"c++20"
],
"Title": "A Sine Template Function For Boost.MultiArray in C++"
}
|
251499
|
<p>I'm currently learning C# so that I can do some projects with the language.
To provide some fun learning I'm also learning the Unity engine at the same time.
Currently I'm following a tutorial for making a rail shooter, however the tutorial is a bit dated so I'm taking it as a personal challenge to handle the tutorial while updating parts of it to current tech.</p>
<p>I'd appreciate a quick code review of my player ship movement logic:
In particular, is there any ways I can clean this up and be more performant while still being readable for a novice?</p>
<p>I'm using the Unity Input System and have coded a state controller for my player.</p>
<pre><code>public class PlayerState
{
protected PlayerShip player;
protected PlayerStateMachine stateMachine;
protected PlayerData playerData;
protected float startTime;
private string stateName;
public PlayerState(PlayerShip player, PlayerStateMachine stateMachine, PlayerData playerData, string stateName)
{
this.player = player;
this.stateMachine = stateMachine;
this.playerData = playerData;
this.stateName = stateName;
}
// Called when entering a state
public virtual void Enter()
{
DoChecks();
startTime = Time.time;
//Debug.Log("Entered State: " + stateName);
}
// Called every fixed update
public virtual void PhysicsUpdate()
{
DoChecks();
}
</code></pre>
<p>And here is the child states, PlayerFlyingState is the "Super" state that isn't directly used, PlayerMoveState is the child state that is called when input is provided. It toggles state with an "idle":</p>
<pre><code>public class PlayerFlyingState : PlayerState // Inherits from PlayerState
{
protected Vector2 input;
public PlayerFlyingState(PlayerShip player, PlayerStateMachine stateMachine, PlayerData playerData, string stateName) : base(player, stateMachine, playerData, stateName)
{
}
public override void LogicUpdate()
{
base.LogicUpdate();
input = player.InputHandler.MovementInput;
}
public class PlayerMoveState : PlayerFlyingState
{
public PlayerMoveState(PlayerShip player, PlayerStateMachine stateMachine, PlayerData playerData, string stateName) : base(player, stateMachine, playerData, stateName)
{
}
public override void LogicUpdate()
{
base.LogicUpdate();
if (input.x == 0f && input.y == 0f)
{
player.setPosition(new Vector3(0f, 0f, 0f));
stateMachine.ChangeState(player.IdleState);
}
else
{
player.ProcessTranslation(input);
player.ProcessRotation(input);
}
}
</code></pre>
<p>And here is the ProcessTranslation method that is where the main portion of the movement logic is handled.</p>
<pre><code> public void ProcessTranslation(Vector2 inputAxis)
{
// Clamp player ship movement
float positionX = Mathf.Clamp(transform.localPosition.x, playerData.xLimitLeft, playerData.xLimitRight);
float positionY = Mathf.Clamp(transform.localPosition.y, playerData.yLimitDown, playerData.yLimitUp);
float moveX = 0f;
float moveY = 0f;
float tempX = (inputAxis.x * (playerData.moveSpeed * Time.deltaTime));
float tempY = (transform.up * inputAxis.y * (playerData.moveSpeed * Time.deltaTime)).y;
//////////////////////////////////////////////////////////////////////////////////////////
//! If ship is within limits, take temp value as input. Else set input velocity to 0 if the player moves the ship to the limit edges, allow them to input away from the limit direction.
/////////////////////////////////////////////////////////////////////////////////////////
if ( (positionX > playerData.xLimitLeft) && (positionX < playerData.xLimitRight))
{
moveX = tempX;
}
else
{
if (positionX <= playerData.xLimitLeft)
{
moveX = (Mathf.Clamp(inputAxis.x, 0f, System.Math.Abs(tempX)) * (playerData.moveSpeed * Time.deltaTime));
}
if (positionX >= playerData.xLimitRight)
{
moveX = (Mathf.Clamp(inputAxis.x, -System.Math.Abs(tempX), 0f) * (playerData.moveSpeed * Time.deltaTime));
}
}
if ( (positionY > playerData.yLimitDown) && (positionY < playerData.yLimitUp))
{
moveY = tempY;
}
else
{
if (positionY <= playerData.yLimitDown)
{
moveY = (transform.up * Mathf.Clamp(inputAxis.y, 0f, System.Math.Abs(tempY)) * (playerData.moveSpeed * Time.deltaTime)).y;
}
if (positionY >= playerData.yLimitUp)
{
moveY = (transform.up * Mathf.Clamp(inputAxis.y, -System.Math.Abs(tempY), 0f) * (playerData.moveSpeed * Time.deltaTime)).y;
}
}
tempShipPositionProcessed.Set(moveX, moveY, 0f);
setPosition(tempShipPositionProcessed);
}
public void setPosition(Vector3 inputVector)
{
//! To get reversed input, subtract inputVector instead of adding it.
rbody.transform.localPosition = transform.localPosition + inputVector;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T00:51:01.667",
"Id": "495154",
"Score": "1",
"body": "Did you write the `PlayerFlyingState`? If so, please include it in the question, so that we can do a better review and provide better answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T01:03:31.507",
"Id": "495157",
"Score": "0",
"body": "Added `PlayerFlyingState` and `PlayerState` to code block."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T20:25:21.727",
"Id": "251502",
"Score": "1",
"Tags": [
"c#",
"performance",
"unity3d"
],
"Title": "Unity - Rail Shooter Player Ship Movement Handler"
}
|
251502
|
<p>I am working on a portfolio project that deals with creating a Netflix-style recommendation engine for movies. This code is currently ran locally but I will need to upload it into Jupyter Notebooks and implement it with Amazon SageMaker. The .tsv files are imported from <a href="https://www.imdb.com/interfaces/" rel="nofollow noreferrer">IMDb Datasets</a>.</p>
<p>The code below is working code created by myself. Is there any room for improvement from an efficiency/cleanliness aspect?</p>
<pre><code>import pandas as pd
import numpy as np
basics = pd.read_table('basics.tsv')
origin = pd.read_table('akas.tsv')
ratings = pd.read_table('ratings.tsv')
#setting 'basics' columns
basics.drop(basics.columns[[3,4,6,7]], axis=1, inplace=True)
basics.columns = ['tconst','type','title','year','genre']
#removing all non-movies from index
cond1 = basics['type'].isin(['movie','tvMovie'])
#setting new 'basics' variable
basics2 = basics[cond1]
#setting 'origin' columns
origin.drop(origin.columns[[1,2,5,6,7]], axis = 1, inplace = True)
origin.columns = ['tconst','region','language']
#removing non-english movies from index
cond2 = origin['region'].isin(['US','GB'])
cond3 = origin['language'] == 'en'
#setting new 'origin' variable
origin2 = origin[cond2 | cond3]
#setting 'ratings' columns
ratings.columns = ['tconst','rating','votecount']
#converting strings to integers
ratings.rating = pd.to_numeric(ratings.rating, errors='coerce').astype(np.int64)
ratings.votecount = pd.to_numeric(ratings.votecount, errors='coerce').astype(np.int64)
#setting new 'ratings' variable
ratings2 = ratings[(ratings['rating'] >= 5) & (ratings['votecount'] >= 50)]
#finalizing movie recommendation list
rcmd = basics2.merge(origin2,on='tconst').merge(ratings2,on='tconst')
rcmd.drop_duplicates(subset = 'tconst', keep ="first", inplace = True)
print(rcmd)
</code></pre>
<p>Thanks in advance.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T21:32:57.397",
"Id": "495135",
"Score": "0",
"body": "Do your tsv files not have a heading row?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T21:37:52.553",
"Id": "495137",
"Score": "0",
"body": "Oh, they do. So I'm not sure why you're setting your col names explicitly."
}
] |
[
{
"body": "<h2>The usual</h2>\n<p>Use a PEP8 linter; move global code into functions; use type hints; use a <code>__main__</code> guard.</p>\n<h2>Column use</h2>\n<pre><code>basics.drop(basics.columns[[3,4,6,7]], axis=1, inplace=True)\nbasics.columns = ['tconst','type','title','year','genre']\n</code></pre>\n<p>really shouldn't be necessary. Use the <code>usecols</code> kwarg of <code>read_table</code> instead; the col names are a loose guess from the IMDB documentation:</p>\n<pre><code>basics = pd.read_table(\n 'basics.tsv',\n usecols=(\n 'tconst', 'titleType', 'primaryTitle', 'startYear', 'genres',\n ),\n)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T22:00:51.340",
"Id": "495144",
"Score": "0",
"body": "I set the columns for organization and aesthetic purposes. I did not like the default values provided, no other reason in particular."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T22:22:06.287",
"Id": "495149",
"Score": "0",
"body": "Aesthetics is not a convincing argument to rename columns. You're hindering your code's ability to correspond with the IMDB documentation."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T21:44:57.210",
"Id": "251511",
"ParentId": "251505",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T21:05:08.697",
"Id": "251505",
"Score": "1",
"Tags": [
"python",
"numpy",
"pandas",
"amazon-web-services"
],
"Title": "Cleaning Netflix-style recommendation engine datasets"
}
|
251505
|
<p>I'd like to get some expert's view on this first piece of code especially in the area of</p>
<ul>
<li>performance - (e.g. avoidable copies)</li>
<li>good practice (e.g. static members?)</li>
</ul>
<p>The final goal is the provide some abstractions for text manipulation like cleansing, stop-word removal and tokenization. The code base should grow substantially in the future so a lot more string manipulation methods should be supported. I understand that this should be bundled in a library in the end, however, I'd like to get feedback on the general code style first.</p>
<pre><code>#include <fstream>
#include <iostream>
#include <regex>
#include <sstream>
#include <string>
#include <vector>
class TextManipulator {
public:
static std::string replace(std::string &string, const std::string pattern,
const std::string toreplace) {
return std::regex_replace(string, std::regex(pattern), toreplace);
}
static std::string toLowerCase(std::string &string) {
std::locale loc;
std::string res;
for (auto elem : string) {
res += std::tolower(elem, loc);
}
return res;
}
static std::vector<std::string> split(const std::string &text,
char seperator) {
std::vector<std::string> tokens;
std::size_t start = 0, end = 0;
while ((end = text.find(seperator, start)) != std::string::npos) {
std::string extr = text.substr(start, end - start);
if (!extr.empty()) {
tokens.push_back(extr);
}
start = end + 1;
}
tokens.push_back(text.substr(start));
return tokens;
}
};
int main() {
std::ifstream input(
"/example_docs/Pride_and_Prejudice.txt");
std::stringstream buffer;
buffer << input.rdbuf();
std::string text = buffer.str();
text = TextManipulator::replace(text, "\r\n", " ");
text = TextManipulator::replace(text, ",", "");
text = TextManipulator::replace(text, ":", "");
text = TextManipulator::replace(text, ".", "");
text = TextManipulator::toLowerCase(text);
std::vector<std::string> tokens = TextManipulator::split(text, ' ');
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<h1>Don't use a <code>class</code></h1>\n<p>There is no need to create a <code>class</code> just to hold a collection of <code>static</code> functions. Instead, just declare the functions in the global namespace. If you want to avoid polluting the global namespace, consider putting them in a <code>namespace</code> instead, like so:</p>\n<pre><code>namespace TextManipulation {\n\nstd::string replace(...) {\n ...\n};\n\n...\n}\n</code></pre>\n<h1>Don't write unnecessary trivial wrapper functions</h1>\n<p>There is no need to create <code>TextManipulator::replace()</code>, when all it does is call <code>std::regex_replace</code> with almost exactly the same arguments. Why not call <code>std::regex_replace()</code> directly instead?</p>\n<p>The name <code>replace()</code> also hides the fact that <code>pattern</code> is a regular expression.</p>\n<h1>Consider renaming <code>toLowerCase()</code> to <code>tolower()</code></h1>\n<p>It's a bit annoying to have different naming conventions in one program, and since you already have <code>tolower()</code> for single characters, it would be very convenient to reuse that for whole strings as well. So:</p>\n<pre><code>std::string tolower(const std::string &str) {\n ...\n}\n</code></pre>\n<p>Note: you forget to add <code>const</code> to the function parameter here, as well as for the first parameter of <code>replace()</code>, but you did it correctly for the other string parameters.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T21:28:04.037",
"Id": "251509",
"ParentId": "251507",
"Score": "7"
}
},
{
"body": "<p>Whenever possible, use <a href=\"https://www.boost.org/doc/libs/1_53_0/libs/utility/doc/html/string_ref.html\" rel=\"nofollow noreferrer\">boost::string_ref</a> in your code, this will reduce the number of copy operations with <code>std::string</code>. Check the places where you have copy operations and replace them with <code>boost::string_ref</code> operations if possible.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T09:10:56.537",
"Id": "495191",
"Score": "0",
"body": "There's `string_view` in c++17"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T09:52:44.897",
"Id": "495196",
"Score": "0",
"body": "Yes you are right if you are in standard 17 or higher"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T22:30:59.290",
"Id": "251514",
"ParentId": "251507",
"Score": "-3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T21:11:35.733",
"Id": "251507",
"Score": "5",
"Tags": [
"c++",
"performance",
"object-oriented",
"strings"
],
"Title": "String/text manipulation utility class"
}
|
251507
|
<h1> Objective</h1>
<blockquote>
<p>Write a recursive method for generating all permutations of an input string. Return them as a set.</p>
</blockquote>
<p><em>See: <a href="https://www.interviewcake.com/question/java/recursive-string-permutations" rel="nofollow noreferrer">Recursive String Permutations</a> - Interview Cake</em></p>
<h1> Questions</h1>
<h3>1: How does the problem change if the string can have duplicate characters?</h3>
<ul>
<li>The solution below works with duplicate characters because the index of the original input is used to generate unique combinations of the original input minus the character at the given index. Therefore, there may be duplicate characters, however, their unique indexes will generate the correct solution.</li>
</ul>
<h3>2: What is the space and time complexity?</h3>
<ul>
<li><p><em>Time Complexity:</em> <span class="math-container">\$O(n^2)\$</span> because there is one iteration through the input for which index to examine, and a second iteration, placing the character at each position of the input to generate various combinations. Therefore, <span class="math-container">\$n x n\$</span>. This follows the rule, do X for each time of Y. <em>See: <a href="https://www.geeksforgeeks.org/time-complexity-permutations-string/" rel="nofollow noreferrer">Time complexity of all permutations of a string</a> - GeeksforGeeks</em></p>
</li>
<li><p><em>Space Complexity:</em> <strong>Is the space complexity also quadratic <span class="math-container">\$O(n^2)\$</span> because the unique permutations stored in a Set would grow quickly based on the size of the initial input?</strong></p>
</li>
</ul>
<h3>3: How to optimize the time and space complexity?</h3>
<ul>
<li><p><em>Time Complexity:</em> I do not see further time complexity optimizations.</p>
</li>
<li><p><em>Space Complexity:</em> I do not see further space complexity optimizations because the solution syntactically is recursive, but performs iteratively. The recursive part of the code, <code>allPerm</code> performs after each iteration through the input. Therefore, there are no methods saved onto the JVM's call stack.</p>
</li>
</ul>
<h1> Code</h1>
<ol>
<li>Iterate through each char and move the char to each position of the input String.</li>
<li>Add each version to a Set.</li>
</ol>
<pre><code>fun allPerm(input: String, lookAtIndex: Int, set: HashSet<String>): HashSet<String> {
if (lookAtIndex <= input.length - 1) {
for (i in 0 .. input.length - 1) {
val combo = input.substring(0, lookAtIndex) +
input.substring(lookAtIndex + 1)
set.add(combo.substring(0, i) + input.get(lookAtIndex) +
combo.substring(i))
}
allPerm(input, lookAtIndex + 1, set)
}
return set
}
</code></pre>
<p><em>See: <a href="https://github.com/AdamSHurwitz/RecursiveStringPermutations" rel="nofollow noreferrer">GitHub</a></em></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T22:20:12.700",
"Id": "495147",
"Score": "1",
"body": "Consider the input `abcdefghijklmnopqrstuvwxyz` and think about how many different combinations that will return. Then consider if this is more than, less than, or equal to `O(n^2)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T22:21:01.203",
"Id": "495148",
"Score": "1",
"body": "Also consider the input `aaaaaaaaaaaaaaaaaaaaaa` and think about how many different combinations that will return. Now consider if you can make any performance improvement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T01:32:59.387",
"Id": "495159",
"Score": "0",
"body": "Have you tested your code, e.g. on a simple exam like `abc`? Does it add the permutation `cba` to the set for that input?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T20:24:51.140",
"Id": "495447",
"Score": "0",
"body": "Here is the original test, @M.Doerner, [_TestSolve.kt_](https://github.com/AdamSHurwitz/RecursiveStringPermutations/blob/root/src/test/TestSolve.kt). I'm missing the permutation `cba`. I'll add that to the test and begin debugging to understand why `cba` is not covered in the algorithm."
}
] |
[
{
"body": "<h1>✅ Solution</h1>\n<h2> Fix - Missing Combinations</h2>\n<ol>\n<li>Recursively generate each permutation of characters.</li>\n<li>For every permutation, iterate through each index and move the last character to each position of the permutation.</li>\n<li>Add each permutation to the Set.</li>\n</ol>\n<pre><code>fun getPerms(input: String): HashSet<String> {\n val perms = hashSetOf<String>()\n if (input.length <= 1)\n return hashSetOf(input)\n val allCharsExceptLast = input.substring(0, input.length - 1)\n val permsOfAllCharsExceptLast = getPerms(allCharsExceptLast)\n val lastChar = input.substring(input.length - 1)\n for (s in permsOfAllCharsExceptLast) {\n for (i in 0.. allCharsExceptLast.length) {\n perms.add(s.substring(0, i) + lastChar + s.substring(i))\n }\n }\n return perms\n}\n</code></pre>\n<h2> Questions</h2>\n<h3>1: How does the problem change if the string can have duplicate characters?</h3>\n<p>Considering the input <code>aaaaaaaaaaaaaaaaaaaaaa</code>, it would return one combination. However, the algorithm would check each possible combination at every index which is highly inefficient. For example, with input <code>aaa</code>, the algorithm would run 9 times for the character at index 0, 1, and 2 for all 3 positions, so 3 x 3 iterations.</p>\n<h3>2: What is the space and time complexity?</h3>\n<p>Considering the input <code>abcdefghijklmnopqrstuvwxyz</code>, it seems like the space complexity grows larger than <code>O(n^2)</code> and closer to <code>O(n^n)</code>, exponential growth.</p>\n<h3>3: How to optimize the time complexity?</h3>\n<p>If we take a simple example with one repeated character, <code>a</code>, in the input <code>abac</code>, the second combinations of <code>a</code> at index 2 are entirely repeated throughout the rest of the iterations.</p>\n<p>Therefore, if a character value is a repeat value the iterations for the repeated value should be skipped. The algorithm may be adjusted to store an instance variable set of characters already searched for to improve the time efficiency.</p>\n<p><strong>Index 0</strong></p>\n<p><strong>a</strong>bac<br />\nb<strong>a</strong>ac<br />\nba<strong>a</strong>c<br />\nbac<strong>a</strong></p>\n<p><strong>Index 1</strong></p>\n<p><strong>b</strong>aac<br />\na<strong>b</strong>ac<br />\naa<strong>b</strong>c<br />\naac<strong>b</strong></p>\n<p><strong>Index 2</strong>: <em>This is the second time using character <code>a</code>, therefore, we can skip these iterations.</em></p>\n<p><strong>a</strong>abc<br />\na<strong>a</strong>bc<br />\nab<strong>a</strong>c<br />\nabc<strong>a</strong></p>\n<p><strong>Index 3</strong></p>\n<p><strong>c</strong>aba<br />\na<strong>c</strong>ba<br />\nab<strong>c</strong>a<br />\naba<strong>c</strong></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T13:33:52.880",
"Id": "495215",
"Score": "1",
"body": "It looks like my comments above (on your question) helped out?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T22:38:52.803",
"Id": "495280",
"Score": "2",
"body": "Under 3, you show the entire output of your code for the input `abac`. Note that this does not contain the permutation `caab`. You might want to reconsider your original algorithm and actually test that it is a solution to the base question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T20:16:34.047",
"Id": "495445",
"Score": "1",
"body": "Thank you @SimonForsberg! Your comments on the space complexity and how to think about duplicates inspired the answer above. Now I need to debug my current solution as it is missing a permutation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T21:12:33.010",
"Id": "495448",
"Score": "0",
"body": "Great find @M.Doerner! Thank you. I'll update the existing test under _[src/test/TestSolve.kt](https://github.com/AdamSHurwitz/RecursiveStringPermutations)_ to debug the algorithm."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T01:13:45.783",
"Id": "251518",
"ParentId": "251510",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T21:41:35.353",
"Id": "251510",
"Score": "0",
"Tags": [
"strings",
"recursion",
"complexity",
"dynamic-programming",
"kotlin"
],
"Title": "Generate unique string permutations recursively"
}
|
251510
|
<p>I am making a river crossing puzzle app using Pygame. Did I implement the conditions optimally?</p>
<p>The <code>Person</code> class arguments for the conditions as to when or not a person will cross a river are these:</p>
<ul>
<li><p><code>hate=[]</code>: If any of the names in the list are the names of any people in <code>boat.aboard</code>, don't cross.</p>
</li>
<li><p><code>like=[]</code>: If none of the names in the list are the names of any people in <code>boat.aboard</code>, don't cross.</p>
</li>
<li><p><code>alone=True</code>: If there is anyone in <code>boat.aboard</code> besides himself in the boat, don't cross.</p>
</li>
<li><p><code>alone=False</code>: If there is no one in <code>boat.aboard</code> besides himself in the boat, don't cross.</p>
</li>
</ul>
<p>Here is where I implemented the conditions:</p>
<pre><code> def go(self):
hated = [name for person in self.aboard for name in person.hate]
liked = [name for person in self.aboard for name in person.like]
no = False
if any(person.alone == True for person in self.aboard) and len(self.aboard) > 1:
no = True
elif any(person.alone == False for person in self.aboard) and len(self.aboard) == 1:
no = True
elif any(person.name == name for person in self.aboard for name in hated):
no = True
elif liked:
if any(person.name == name for person in self.aboard for name in liked):
no = False
else:
no = True
else:
no = False
if not no:
if self.side == 'UP':
self.y += 300
self.side = 'DOWN'
else:
self.y -= 300
self.side = 'UP'
self.obj.y = self.y
</code></pre>
<h3>I want to know if I implemented the conditions above ^ optimally, or even correctly.</h3>
<p>Here is when I run the entire code, and the conditions seem fine:</p>
<p><a href="https://i.stack.imgur.com/GDAxZ.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GDAxZ.gif" alt="enter image description here" /></a></p>
<p>And here is my entire code:</p>
<pre><code>import pygame
import random
pygame.init()
wn = pygame.display.set_mode((600, 600))
font = pygame.font.SysFont('Arial', 25)
people = []
class Person():
def __init__(self, name, x, y, color, side='UP', w=20, h=20, hate=[], like=[], alone=None):
self.name = name
self.color = color
self.x = x
self.y = y
self.w = w
self.h = h
self.alone = alone
self.hate = hate
self.like = like
self.side = side
self.obj = pygame.Rect(x, y, w, h)
people.append(self)
conditions = []
if alone == False:
conditions.append("won't go alone")
elif alone == True:
conditions.append("will only go alone")
if len(hate) > 1:
conditions.append(f"won't go with any of: {', '.join(hate)}")
elif len(hate) == 1:
conditions.append(f"won't go with {hate[0]}")
if len(like) > 1:
conditions.append(f"will only go if any of: {', '.join(like)} are going")
elif len(like) == 1:
conditions.append(f"will only go if {like[0]} is going")
self.conditions = conditions
def draw(self):
self.obj = pygame.Rect(self.x, self.y, self.w, self.h)
pygame.draw.rect(wn, self.color, self.obj)
def get_on_boat(self, boat):
self.x = random.randint(boat.x, boat.x+boat.w-self.w)
self.y = random.randint(boat.y, boat.y+boat.h-self.h)
self.side = boat.side
def write_conditions(self, x, y):
text = font.render(f"{self.name} {'; '.join(self.conditions)}", True, (0, 0, 0))
wn.blit(text, (x, y))
def get_off_boat(self, boat):
self.x += random.randint(50, 200)
def on_boat(self, boat):
return boat.x+boat.w-self.w >= self.x >= boat.x and boat.y+boat.h-self.h >= self.y >= boat.y
class Boat():
def __init__(self, room, x=280, y=200, color=(140, 140, 140), w=40, h=60, side='UP'):
self.room = room
self.x = x
self.y = y
self.w = w
self.h = h
self.trips = 0
self.color = color
self.obj = pygame.Rect(x, y, w, h)
self.side = side
self.aboard = []
def go(self):
hated = [name for person in boat.aboard for name in person.hate]
liked = [name for person in boat.aboard for name in person.like]
no = False
if any(person.alone == True for person in self.aboard) and len(self.aboard) > 1:
no = True
elif any(person.alone == False for person in self.aboard) and len(self.aboard) == 1:
no = True
elif any(person.name == name for person in self.aboard for name in hated):
no = True
elif liked:
if any(person.name == name for person in self.aboard for name in liked):
no = False
else:
no = True
else:
no = False
if not no:
if self.side == 'UP':
self.y += 300
self.side = 'DOWN'
else:
self.y -= 300
self.side = 'UP'
self.obj.y = self.y
def draw(self):
pygame.draw.rect(wn, self.color, self.obj)
boat = Boat(2)
Yel = Person('Yel', boat.x+100, boat.y, (255, 255, 0), hate=['Red']) # yellow
Red = Person('Red', boat.x-100, boat.y, (255, 0, 0), alone=True) # red
Pin = Person('Pin', boat.x+200, boat.y, (255, 0, 255), like=['Yel']) # pink
Blu = Person('Blu', boat.x+250, boat.y, (0, 0, 255), like=['Yel'], hate=['Gre']) # blue
Gre = Person('Gre', boat.x+280, boat.y, (0, 255, 0)) # green
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
elif event.type == pygame.MOUSEBUTTONDOWN:
for person in people:
if person.obj.collidepoint(pygame.mouse.get_pos()):
if person in boat.aboard:
person.get_off_boat(boat)
boat.aboard.remove(person)
boat.room += 1
else:
if boat.room and person.side == boat.side:
person.get_on_boat(boat)
boat.aboard.append(person)
boat.room -= 1
if not any(person.obj.collidepoint(pygame.mouse.get_pos()) for person in people):
if boat.obj.collidepoint(pygame.mouse.get_pos()):
if boat.aboard and boat.room >= 0:
boat.go()
for person in boat.aboard:
person.get_on_boat(boat)
boat.trips += 1
wn.fill((255, 255, 255))
pygame.draw.rect(wn, (100, 200, 255), (0, 290, 600, 180))
boat.draw()
for i, person in enumerate(people):
person.draw()
person.write_conditions(0, i*25)
pygame.display.update()
</code></pre>
<h3>Also, I want some suggestions to clean up my messy code.</h3>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T05:12:51.023",
"Id": "495329",
"Score": "0",
"body": "In the `Person` class, I would. move those `if/elif` statements out into either a separate method (maybe an `@staticmethod`), or to a standalone function (if you don't like static methods). This might also be a good case for using `dataclasses`."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T22:15:40.280",
"Id": "251513",
"Score": "4",
"Tags": [
"python",
"pygame"
],
"Title": "River crossing puzzle app using Pygame"
}
|
251513
|
<p>Find junk values in all tables and columns:</p>
<ol>
<li>Loop through all tables in a schema (Oracle 18c)</li>
<li>Loop through each number and text column</li>
<li>If columns have values that are junk, then add a statistic/record to a log table:
<ul>
<li><code>0</code> (number)</li>
<li><code> </code> (text; single space)</li>
<li><code> </code> (text; double space)</li>
<li><code>0</code> (text)</li>
<li><code>-</code> (text)</li>
<li><code>NULL</code> (text; not a true null)</li>
<li><code><NULL></code> (text; not a true null)</li>
</ul>
</li>
<li>Get the data custodian to review the issue and correct it if applicable.</li>
</ol>
<hr />
<pre><code>--TRUNCATE TABLE incorrect_value_results;
--CREATE TABLE incorrect_value_results (id NUMBER, table_name VARCHAR2(30), column_name VARCHAR2(30), val_count NUMBER);
DECLARE
l_count NUMBER;
l_index NUMBER;
BEGIN
l_index := 0;
-- Loop through each table in the schema
FOR i IN (SELECT table_name
FROM user_tables) LOOP
-- Loop through each relevant column for this table
FOR j IN (SELECT column_name, data_type
FROM user_tab_cols
WHERE table_name = i.table_name
AND data_type IN ('VARCHAR2', 'CHAR', 'NCHAR', 'NVARCHAR2', 'NUMBER')) LOOP
IF j.data_type IN ('VARCHAR2', 'CHAR', 'NCHAR', 'NVARCHAR2') THEN
EXECUTE IMMEDIATE 'SELECT COUNT(1) FROM '||i.table_name||' WHERE UPPER('||j.column_name||') IN('' '', '' '', ''0'', ''-'', ''NULL'', ''<NULL>'' )' INTO l_count;
ELSIF j.data_type = 'NUMBER' THEN
EXECUTE IMMEDIATE 'SELECT COUNT(1) FROM '||i.table_name||' WHERE '||j.column_name||' <= 0' INTO l_count ;
END IF;
-- If there are results then log them
IF l_count > 0 THEN
l_index := l_index + 1;
INSERT INTO incorrect_value_results (id, table_name, column_name, val_count)
VALUES (l_index,
i.table_name,
j.column_name,
l_count);
END IF;
END LOOP;
END LOOP;
END;
COMMIT;
</code></pre>
<hr />
<p>I'm relatively new to PL/SQL. How can the script be improved?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T18:22:10.780",
"Id": "495240",
"Score": "1",
"body": "Relevant thread: https://chat.stackexchange.com/rooms/179/conversation/gis-junk-values"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T18:24:03.167",
"Id": "495241",
"Score": "1",
"body": "Given your requirements (see above thread) and your work here, it seems like it's good enough to get the job done. Unfortunately I'm not a whiz-bang on Oracle's PLSQL so I can't give much advice there, but what I can say is that without us knowing a few more details, predicting the serviceability of SQL is gonna require some magical forward knowing. Like what's indexed vs what isn't, that sort of thing. - Overall this looks straightforward and reasonable. - You might consider an auditing service instead of a query and do this offline?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T18:25:19.337",
"Id": "495242",
"Score": "1",
"body": "By \"auditing service\" I just mean \"a piece of software that you write that is not a query in the database that can be run on a remote machine that 1) asks for a slot of data and 2) runs analysis on that slot of data\". Benefits being that you being in program land and not query land means logging, flat file output, better potential for formatting, etc. Downsides are network transit and two codebases."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-02T23:02:14.977",
"Id": "251515",
"Score": "1",
"Tags": [
"oracle",
"plsql"
],
"Title": "Find junk values in all tables and columns"
}
|
251515
|
<p>Good night. It is me again (<a href="https://codereview.stackexchange.com/questions/250759/animated-calendar-using-html-css-js/250778#250778" title="last post">last post about this code</a>).</p>
<p><strong>Summary:</strong> This project is meant to be a mobile calendar made with HTML, CSS and JS. I'm using a <code><table></code> to show all the days of the month. And each one of the days are off course a <code><td></code>. Currently they all receive an eventListener, that open a pop_up when clicked. The problem I believe is that I'm using they wrongly. More details below.</p>
<p><strong>Main issue:</strong> After the last post here, regarding this code, many improvements were made. Now, I'm facing a hard time dealing with event listeners. I have:</p>
<p>A 7x7 <code><table></code>. The first <code><tr></code> contains the <code><th></code>, in conclusion I have a 6x7 <code><table></code> containing my days of the month. Each one of these days are a <code><td></code>. I added an eventListener to each one of this days. This event triggers a pop-up div that contains a form to add a new schedule event. Once its form is filled, and the 'Confirm' button is clicked, again, by another eventListener, I create a div within the display_data div. So, each time an event is added, this div receives a new item.
The problem in here is the amount of times the parameter 'day' is being changed/runned, as you can see in the script, I ended up having to get the value in other way, not directly from the function.</p>
<p><strong>In Conclusion:</strong> I'm not finished with all the verifications yet, I plan to only show the scheduled events on the month that they belong to, etc... However, I've been burning my midnight oil trying to solve this issue with no success at all. If you have any suggestion on how to improve the code in general, fell free to do so!</p>
<p>I'll be posting the code below, also the git link in the correct branch if you rather it.</p>
<p><a href="https://github.com/LucasBiazi/Mobile_Calendar_HTML_CSS_JS/tree/notes_system" rel="nofollow noreferrer" title="git link">Github project link</a></p>
<p><strong>HTML:</strong></p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Calendar</title>
<script src="../script/script.js"></script>
<link rel="stylesheet" href="../css/style.css" />
</head>
<body>
<div id="add_schedule" class="hide_pop_up">
<div class="close_button">
<span id="schedule_day"></span>
<span id="close_pop_up">X</span>
</div>
<form id="pop_up">
<div class="schedule_time_div">
<div class="schedule_time_div_2">
<label for="schedule_initial_time">Starting at:</label>
<input id="schedule_initial_time" type="time" value="00:00" />
</div>
<div class="schedule_time_div_2">
<label for="schedule_final_time">Ending at:</label>
<input id="schedule_final_time" type="time" value="23:59" />
</div>
</div>
<div class="schedule_title_div">
<label for="schedule_title">Title</label>
<input
id="schedule_title"
placeholder="My title..."
type="text"
required
/>
</div>
<div class="schedule_description_div">
<label for="schedule_description">Description</label>
<input
id="schedule_description"
placeholder="My description..."
type="text"
/>
</div>
<div class="schedule_button_div">
<button id="save_schedule" form="pop_up" type="button">
Confirm
</button>
</div>
</form>
</div>
<div class="main">
<div class="title">
<span class="year_title" id="year_title"></span>
<span class="month_title" id="month_title"></span>
</div>
<div class="calendar">
<div id="month_days" class="month_days">
<table id="days">
<tr>
<th>Sun</th>
<th class="even">Mon</th>
<th>Tue</th>
<th class="even">Wed</th>
<th>Thu</th>
<th class="even">Fri</th>
<th>Sat</th>
</tr>
</table>
</div>
<div id="data_display" class="data_display"></div>
</div>
<div class="buttons">
<button id="back_button">
<img class="arrow_img" alt="back" />
</button>
<button id="t_button">T</button>
<button id="next_button">
<img class="arrow_img" alt="next" />
</button>
</div>
</div>
</body>
</html>
</code></pre>
<p><strong>CSS:</strong></p>
<pre><code>* {
padding: 0px;
margin: 0px;
font-family: Verdana, Geneva, Tahoma, sans-serif;
font-weight: lighter;
}
body {
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
background-image: url(../../media/grass.jpg);
/* Blurring the background. Applies behind the element... */
backdrop-filter: blur(9px);
background-size: cover;
}
@keyframes display_data {
0% {
transform: scale3d(0, 1, 1);
}
100% {
transform: scale3d(1, 1, 1);
}
}
@keyframes opacity {
from {
opacity: 0%;
}
to {
opacity: 100%;
}
}
@keyframes display_button_back {
0% {
right: 25px;
transform: scale3d(0.75, 0.75, 1);
}
100% {
right: 0px;
transform: scale3d(1, 1, 1);
}
}
@keyframes display_button_next {
0% {
left: 25px;
transform: scale3d(0.75, 0.75, 1);
}
100% {
left: 0px;
transform: scale3d(1, 1, 1);
}
}
@keyframes display_opacity_zoom {
from {
opacity: 0%;
transform: scale3d(0.5, 0.5, 1);
}
to {
opacity: 100%;
transform: scale3d(1, 1, 1);
}
}
@keyframes display_schedule {
from{
opacity: 0%;
transform: scale3d(.25,1,1);
}
to{
opacity: 100%;
transform: scale3d(1,1,1);
}
}
@keyframes close_schedule {
from{
opacity: 100%;
transform: scale3d(1,1,1);
}
to{
opacity: 0%;
transform: scale3d(.25,1,1);
}
}
.main {
width: 100vw;
height: 100vh;
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: flex-start;
color: white;
background-color: rgba(0, 0, 0, 0.65);
}
.title {
margin-top: 7%;
height: 80px;
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-evenly;
/* animation: display_opacity_zoom 1s ease-out; */
}
.year_title {
margin-left: 5px;
font-size: 40px;
letter-spacing: 5px;
color: lightsalmon;
text-align: center;
}
.month_title {
margin-left: 15px;
font-size: 25px;
letter-spacing: 15px;
text-align: center;
}
.calendar {
height: 75%;
width: 100vw;
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
}
.month_days {
margin-top: 10px;
width: 100%;
height: 50%;
/* animation: opacity 1s ease-in-out; */
}
table {
margin-top: 20px;
width: 100%;
font-size: 22px;
}
tr,
th,
td {
background-color: none;
}
th {
width: 14%;
text-align: center;
color: white;
}
th:first-child,
th:last-child {
color: lightsalmon;
}
td {
width: 2.38em;
height: 2.38em;
color: white;
text-align: center;
border-radius: 50%;
}
td:hover {
background-color: rgba(112, 203, 255, 0.349);
}
.data_display {
width: 95%;
height: 30%;
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
background-color: white;
border: none;
border-radius: 5px;
overflow-y: scroll;
/* animation: display_data 2s ease; */
}
.data_display_item{
width: 100%;
}
.data_display_div_title{
display: flex;
width: 100%;
justify-content: space-between;
align-items: center;
color: black;
margin-top: 5px;
margin-bottom: 5px;
font-size: 20px;
}
.data_display_div_title :first-child{
margin-left: 5px;
}
.data_display_div_title :last-child{
margin-right: 10px;
background-color: lightsalmon;
border-radius: 5px;
}
.data_display_div_description {
display: flex;
width: 100%;
flex-wrap: wrap;
font-size: 17px;
color: black;
}
.data_display_div_description span{
margin-left: 10px;
}
.schedule_day{
background-color: rgba(112, 203, 255, 0.349);
}
.other_month {
background: none;
color: rgba(175, 175, 175, 0.45);
}
.buttons {
width: 100vw;
height: 70px;
display: flex;
justify-content: space-around;
align-items: flex-start;
}
button {
width: 60px;
height: 60px;
display: flex;
justify-content: center;
align-items: center;
background: none;
border: none;
font-size: 35px;
font-weight: 400;
color: white;
}
button:hover{
cursor: pointer;
}
button:first-child{
/* animation: display_button_back 1s ease; */
position: relative;
}
button:first-child img{
content: url(../../media/left-arrow-line-symbol.svg);
}
/*
button:not(:first-child):not(:last-child){
animation: display_opacity_zoom 1s ease-out;
} */
button:last-child{
/* animation: display_button_next 1s ease; */
position: relative;
}
button:last-child img{
content: url(../../media/right-arrow-angle.svg);
}
.arrow_img{
width: 35px;
height: 35px"
}
.hide_pop_up{
display: none;
}
.schedule_display{
display: flex;
width: 97vw;
height: 80vh;
position: absolute;
display: flex;
flex-direction: column;
border-radius: 5px;
background: white;
justify-content: space-between;
align-items: flex-start;
/* animation: display_schedule .3s ease; */
}
/* .schedule_close{
animation: close_schedule .3s ease;
animation-fill-mode: forwards;
#87FFA7 <= Color for schedules
} */
.close_button{
width: 100%;
height: 40px;
display: flex;
align-items: center;
justify-content: space-between;
}
.close_button span{
font-size: 25px;
margin-right: 10px;
}
.close_button span:hover{
cursor: pointer;
}
form{
width: 100%;
height: 100%;
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
font-size: 25px;
}
.schedule_button_div, .schedule_time_div, .schedule_title_div, .schedule_description_div {
width: 100%;
height: 50px;
padding: 20px;
display: flex;
flex-direction: column;
justify-content: space-evenly;
align-items: flex-start;
}
input{
width: 100%;
font-size: 22px;
border: 2px black solid;
border-top: none;
border-right: none;
border-left: none;
}
.schedule_time_div{
height: 15%;
flex-direction: row;
}
.schedule_time_div input{
width: 150px;
height: 50px;
}
.schedule_time_div_2{
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: flex-start;
}
.schedule_button_div{
justify-content: center;
align-items: center;
}
.schedule_button_div button{
font-size: 20px;
color: black;
border: 2px black solid;
width: 30%;
}
@media only screen and (min-width: 1279px){
.title{
margin-top: 2%;
}
.data_display{
margin-top: 35px;
height: 70vh;
}
.calendar{
width: 97vw;
flex-direction: row;
align-items: flex-start;
}
.month_days{
height: fit-content;
}
td{
border-radius: 0%;
}
.buttons{
width: 50vw;
}
}
</code></pre>
<p><strong>JS:</strong></p>
<pre><code>// Returns the amount of days in a month.
const amount_of_days = (year, month) => new Date(year, month + 1, 0).getDate();
// Returns the day of the week in which the month starts.
const first_day_week_for_month = (year, month) =>
new Date(year, month, 1).getDay();
// When given the name, it returns the month number (0-11).
function month_name_in_number(month_name) {
const month_names = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
for (let i = 0; i < 12; i++) {
return month_names.indexOf(month_name);
}
}
// Returns a date object, with more properties.
const date_object = (date_year, date_month) => {
const month_names = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
const date_object = new Date(date_year, date_month);
const date = {
year: date_object.getFullYear(),
month: date_object.getMonth(),
month_name: month_names[date_object.getMonth()],
amount_of_days: amount_of_days(
date_object.getFullYear(),
date_object.getMonth()
),
get_first_Day: first_day_week_for_month(
date_object.getFullYear(),
date_object.getMonth()
),
};
return date;
};
// Returns a date object based on the table data.
function get_table_date() {
const table_year = parseInt(document.getElementById("year_title").innerText);
const table_month = month_name_in_number(
document.getElementById("month_title").innerText
);
return date_object(table_year, table_month);
}
// Prints year + month on the html.
function print_year_and_month(date_year, date_month) {
const date = date_object(date_year, date_month);
document.getElementById("year_title").innerText = date.year;
document.getElementById("month_title").innerText = date.month_name;
}
// Creates the table.
function create_table() {
const table = document.getElementById("days");
// Creates 6 rows.
for (let i = 0; i < 6; i++) {
let current_row = table.insertRow(1 + i);
// Creates 7 cells.
for (let x = 0; x < 7; x++) {
current_row.insertCell(x);
}
}
}
// Resets the 'td' data style properties.
function reset_table_data_style() {
const table = document.getElementById("days");
for (let i = 1; i < 7; i++) {
for (let x = 0; x < 7; x++) {
table.rows[i].cells[x].style.color = "";
table.rows[i].cells[x].style.background = "";
table.rows[i].cells[x].classList.remove("td");
table.rows[i].cells[x].classList.remove("other_month");
}
}
}
// Changes the background color of the current month cell if it is a weekend.
const change_background_color_if_weekend = (row_number) => {
const table = document.getElementById("days");
if (table.rows[row_number].cells[6].classList == "td") {
table.rows[row_number].cells[6].style.color = "lightsalmon";
}
if (table.rows[row_number].cells[0].classList == "td") {
table.rows[row_number].cells[0].style.color = "lightsalmon";
}
};
// Changes the background color of the current month cell if it is today's day.
const change_background_color_if_today = (row_number) => {
const table = document.getElementById("days");
const table_date_object = get_table_date();
if (
table_date_object.year === new Date().getFullYear() &&
table_date_object.month === new Date().getMonth()
) {
for (let i = 0; i < 7; i++) {
if (
table.rows[row_number].cells[i].innerText == new Date().getDate() &&
table.rows[row_number].cells[i].className === "td"
) {
table.rows[row_number].cells[i].style.background = "black";
}
}
} else {
return;
}
};
// Applies the background + today style. + loads schedules
function load_table_style() {
for (let x = 1; x < 7; x++) {
change_background_color_if_weekend(x);
change_background_color_if_today(x);
}
}
// Populates a row.
function populate_row(
execution_number,
row_number,
first_cell,
first_value,
cell_class
) {
if (execution_number <= 7) {
var table = document.getElementById("days");
for (let i = 0; i < execution_number; i++) {
table.rows[row_number].cells[first_cell + i].innerText = first_value + i;
table.rows[row_number].cells[first_cell + i].classList.add(cell_class);
}
} else {
console.log("Alert on populate_row function.");
}
}
// Populates the table.
function populate_table(date_year, date_month) {
// AD = Amount of Days. AC = Amount of cells. CM = Current Month.
const date = date_object(date_year, date_month);
const AC_CM_1_row = 7 - date.get_first_Day;
const AC_last_month = 7 - AC_CM_1_row;
const AD_last_month = amount_of_days(date.year, date.month - 1);
let AD_next_month = 42 - date.amount_of_days - AC_last_month;
let day_counter = AC_CM_1_row;
let lasting_days = date.amount_of_days - day_counter;
// Populates the first row.
if (AC_CM_1_row < 7) {
populate_row(
7 - AC_CM_1_row,
1,
0,
AD_last_month - (7 - AC_CM_1_row) + 1,
"other_month"
);
}
populate_row(AC_CM_1_row, 1, date.get_first_Day, 1, "td");
// Populates the other rows.
let i = 2;
while (day_counter < date.amount_of_days) {
populate_row(7, i, 0, day_counter + 1, "td");
day_counter += 7;
lasting_days = date.amount_of_days - day_counter;
i++;
// If lasting days won't fill a whole row, fill the rest of the table.
if (lasting_days <= 7 && lasting_days !== 0) {
populate_row(lasting_days, i, 0, day_counter + 1, "td");
while (AD_next_month !== 0) {
populate_row(7 - lasting_days, i, lasting_days, 1, "other_month");
AD_next_month -= 7 - lasting_days;
if (AD_next_month > 0) {
populate_row(7, i + 1, 0, 1 + (7 - lasting_days), "other_month");
AD_next_month -= 7;
}
}
day_counter = date.amount_of_days;
}
}
load_table_style();
}
function open_pop_up() {
const pop_up = document.getElementById("add_schedule");
pop_up.classList.remove("schedule_close");
pop_up.classList.add("schedule_display");
}
function close_pop_up() {
const pop_up = document.getElementById("add_schedule");
pop_up.classList.add("schedule_close");
pop_up.classList.remove("schedule_display");
}
function add_schedule_event_to_cells() {
const table = document.getElementById("days");
for (let i = 1; i < 7; i++) {
for (let x = 0; x < 7; x++) {
table.rows[i].cells[x].addEventListener("click", () => {
add_new_schedule_event(table.rows[i].cells[x].innerText);
});
}
}
}
function add_new_schedule_event(day) {
open_pop_up();
const confirm_button = document.getElementById("save_schedule");
const exit_button = document.getElementById("close_pop_up");
const date = document.getElementById("schedule_day");
date.innerText = day;
// ADD a list system that starts in the smallest day, and shows the irformation of the
// current month.
confirm_button.addEventListener("click", () => {
console.log(this.schedule_day.innerText);
const input_title = document.getElementById("schedule_title");
if (input_title.value !== "") {
// Create
const data_display = document.getElementById("data_display");
const input_init_time = document.getElementById("schedule_initial_time");
const input_final_time = document.getElementById("schedule_final_time");
const input_description = document.getElementById("schedule_description");
const data_item = document.createElement("div");
const title_div = document.createElement("div");
const span_title = document.createElement("span");
const span_time = document.createElement("span");
const description_div = document.createElement("div");
const span_description = document.createElement("span");
// Add class
data_item.classList.add("data_display_item");
title_div.classList.add("data_display_div_title");
description_div.classList.add("data_display_div_description");
// Append child
data_display.appendChild(data_item);
data_item.appendChild(title_div);
data_item.appendChild(description_div);
title_div.appendChild(span_title);
title_div.appendChild(span_time);
description_div.appendChild(span_description);
// Values
span_title.innerText = "⬤ " + this.schedule_day.innerText + ": " + input_title.value;
span_time.innerText =
input_init_time.value + " - " + input_final_time.value;
span_description.innerText = input_description.value;
// Clean fields
input_title.value = "";
input_init_time.value = "00:00";
input_final_time.value = "23:59";
input_description.value = "";
close_pop_up();
return;
}
input_title.style.borderBottom = "2px red solid";
});
exit_button.addEventListener("click", () => {
close_pop_up();
return;
});
}
// Loads today's data.
function main() {
print_year_and_month(new Date().getFullYear(), new Date().getMonth());
create_table();
populate_table(new Date().getFullYear(), new Date().getMonth());
add_schedule_event_to_cells();
}
// Loads buttons.
function load_buttons() {
const back_button = document.getElementById("back_button");
const t_button = document.getElementById("t_button");
const next_button = document.getElementById("next_button");
let table_date = get_table_date();
back_button.addEventListener("click", () => {
reset_table_data_style();
table_date.month -= 1;
print_year_and_month(table_date.year, table_date.month);
populate_table(table_date.year, table_date.month);
});
t_button.addEventListener("click", () => {
reset_table_data_style();
table_date = date_object(new Date().getFullYear(), new Date().getMonth());
print_year_and_month(new Date().getFullYear(), new Date().getMonth());
populate_table(new Date().getFullYear(), new Date().getMonth());
});
next_button.addEventListener("click", () => {
reset_table_data_style();
table_date.month += 1;
print_year_and_month(table_date.year, table_date.month);
populate_table(table_date.year, table_date.month);
});
}
// Loads main function as soon as the raw html loads.
function trigger_script() {
document.addEventListener("DOMContentLoaded", () => {
main();
load_buttons();
});
}
// Triggers the code.
trigger_script();
</code></pre>
<p><strong>Thanks in advance, all help is welcome!</strong></p>
|
[] |
[
{
"body": "<p>Found a solution.</p>\n<p>It may have been obvious all along, but, at least now I see it. Every time that I triggered the function <code>add_new_schedule_event()</code>, I was adding a new eventListener, hence I would have multiple values.</p>\n<p><strong>My solution:</strong>\nDivided the main function into sub-functions:</p>\n<pre><code>open_pop_up() // Display pop up\nclose_pop_up() // Hide pop up\nload_button_close_pop_up()\nload_button_confirm_pop_up()\n</code></pre>\n<p>The last two functions go on the <code>load_buttons()</code> function. By doing so, the events now are only generated once.</p>\n<p><strong>Edit:</strong> I was also adding eventListeners by passing function executions instead of just the functions names, and sometimes, I'd be even putting them on anonymous functions for some sort of reason. Now, a better fix would be:</p>\n<pre><code>Once the form is opened: Add the listeners.\nOnce the form is closed: Remove the listeners.\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T17:26:18.873",
"Id": "251554",
"ParentId": "251519",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "251554",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T02:31:45.143",
"Id": "251519",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Handling EventListeners in JS - Calendar in JS"
}
|
251519
|
<p>Befunge is an esoteric language designed with the goal of being as diffcuat to compile <a href="https://esolangs.org/wiki/Befunge" rel="nofollow noreferrer">https://esolangs.org/wiki/Befunge</a>. I have attempted multiple times in the past to make a befunge interpreter in C++ and have failed each time due to me not fully understanding the language. However recently decided to finally fully learn Befunge and make an interpreter for it in C++ and as result I was able to make a complete Befunge-93 interpter.</p>
<p><code>b93.cc</code>:</p>
<pre><code>#include <cstdio>
#include <cinttypes>
#include <string_view>
#include <array>
#include <vector>
#include <random>
namespace
{
constexpr std::size_t max_row_size = 25;
constexpr std::size_t max_col_size = 80;
struct grid_t
{
std::array<char, max_row_size * (max_col_size + 1)> data;
std::size_t rows = max_row_size;
std::size_t cols = max_col_size + 1;
};
grid_t readfile(std::string_view filepath)
{
grid_t result = {};
/* open a file for reading */
if(std::FILE * const file = std::fopen(filepath.data(), "r"); file != nullptr)
{
/* read the file into a buffer */
std::array<char, max_row_size * max_col_size> data = {};
std::size_t const bytes_read = std::fread(data.data(), 1, data.size(), file);
/* copy the buffer to the result */
for(std::size_t i = 0, j = 0, cols = 0; i < bytes_read; ++i, ++j)
{
/* skip charecters that are not a unicode code point */
if((reinterpret_cast<unsigned char*>(data.data())[i] & 0xC0u) == 0x80u)
{
--j;
continue;
}
/* for every newline increase the row count */
if(data[i] == '\n')
{
j += result.cols - cols - 1;
cols = 0;
continue;
}
++cols;
result.data[j] = data[i];
}
/* close the file */
std::fclose(file);
return result;
}
else
{
std::fprintf(stderr, "Error: could not open %s", filepath.data());
std::exit(EXIT_FAILURE);
}
}
}
int main(int argc, char **argv)
{
for (int i = 0; i + 1 < argc; ++i)
{
bool extensions = false;
if(std::string_view argv_sv = std::string_view{argv[i + 1]}; argv_sv.substr(0, 12) == "--extensions")
{
if (argv_sv.find("true", 12) != std::string_view::npos)
{
extensions = true;
}
else if (argv_sv.find("false", 12) != std::string_view::npos)
{
extensions = false;
}
else
{
std::fprintf(stderr, "Error: invalid arguments\n");
return EXIT_FAILURE;
}
i += 1;
if(i + 1 >= argc)
{
std::fprintf(stderr, "Error: exptected a file\n");
return EXIT_FAILURE;
}
}
auto[data, rows, cols] = readfile(argv[i + 1]);
/* create a stack */
std::vector<std::int32_t> stack;
auto push = [&](std::int32_t value) -> void { stack.push_back(value); };
auto pop = [&]() -> std::int32_t
{
if (stack.empty())
{
return 0;
}
else
{
std::int32_t temp = stack.back();
stack.pop_back();
return temp;
}
};
/* hold the position of the cursor and the direction of it */
std::array<std::ptrdiff_t, 2> pos = {}, dir = {1, 0};
auto move = [&, cols = cols, rows = rows]() -> void
{
pos[0] = ((pos[0] + dir[0]) % cols + cols) % cols;
pos[1] = ((pos[1] + dir[1]) % rows + rows) % rows;
};
/* setup an prng */
std::mt19937 engine{std::random_device{}()};
std::uniform_int_distribution <std::int32_t> dist{0, 3};
for (;;)
{
/* see https://catseye.tc/view/Befunge-93/doc/Befunge-93.markdown for what every instruction means */
switch (char ins = data[pos[1] * cols + pos[0]])
{
case '+':
{
push(pop() + pop());
} break;
case '-':
{
std::int32_t const a = pop();
std::int32_t const b = pop();
push(b - a);
} break;
case '/':
{
std::int32_t const a = pop();
std::int32_t const b = pop();
push(b / a);
} break;
case '*':
{
push(pop() * pop());
} break;
case '%':
{
std::int32_t const a = pop();
std::int32_t const b = pop();
push(b % a);
} break;
case '!':
{
if (stack.empty())
{
/* 0 == 0 is true */
push(1);
}
else
{
stack.back() = stack.back() == 0;
}
} break;
case '`':
{
std::int32_t a = pop();
std::int32_t b = pop();
push(b > a);
} break;
case '^':
{
north:
dir[1] = -1;
dir[0] = 0;
} break;
case 'v':
{
south:
dir[1] = 1;
dir[0] = 0;
} break;
case '>':
{
east:
dir[1] = 0;
dir[0] = 1;
} break;
case '<':
{
west:
dir[1] = 0;
dir[0] = -1;
} break;
case '_':
{
bool const value = pop() != 0;
if (value) goto west;
else goto east;
} break;
case '|':
{
bool const value = pop() != 0;
if (value) goto north;
else goto south;
} break;
case '"':
{
move();
/* while the current ch is not a quote push its ascii value */
for (;;)
{
if (char const ch = data[pos[1] * cols + pos[0]]; ch != '"')
{
push(ch);
move();
}
else
{
break;
}
}
} break;
case ':':
{
push(stack.empty() ? 0 : stack.back());
} break;
case '\\':
{
/* NOTE: this is needed because the \ op
* is the same as:
* a = pop()
* b = pop()
* push(a)
* push(b)
*/
switch (stack.size())
{
default:
{
std::swap(stack.end()[-1], stack.end()[-2]);
} break;
case 0: break;
case 1:
{
push(0);
} break;
}
} break;
case '$':
{
pop();
} break;
case '.':
{
std::int32_t value = pop();
std::printf("%" PRId32 " ", value);
} break;
case ',':
{
char value = static_cast<char>(pop());
std::printf("%c", value);
} break;
case '#':
{
move();
} break;
case 'g':
{
std::ptrdiff_t y = static_cast<std::ptrdiff_t>(pop());
std::ptrdiff_t x = static_cast<std::ptrdiff_t>(pop());
push(x >= 0 && x < static_cast<std::ptrdiff_t>(max_col_size) &&
y >= 0 && y < static_cast<std::ptrdiff_t>(max_row_size)
? data[y * cols + x] : 0);
} break;
case 'p':
{
std::ptrdiff_t y = (static_cast<std::ptrdiff_t>(pop()));
std::ptrdiff_t x = (static_cast<std::ptrdiff_t>(pop()));
std::int32_t value = pop();
/* check for out of bounds */
if(x >= 0 && x < static_cast<std::ptrdiff_t>(max_col_size) &&
y >= 0 && y < static_cast<std::ptrdiff_t>(max_row_size))
{
data[y * cols + x] = value;
}
} break;
case '&':
{
std::int32_t value;
std::scanf("%" SCNi32, &value);
push(value);
} break;
case '~':
{
char value;
std::scanf("%c", &value);
push(value);
} break;
/* exit the program */
case '@': goto end_of_loop;
/* for a number push its numeric value onto the stack */
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
push(ins - '0');
} break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
{
if (!extensions) break;
push(ins - 'a' + 10);
} break;
case '?':
{
switch (dist(engine))
{
case 0: goto north;
case 1: goto south;
case 2: goto east;
case 3: goto west;
}
} break;
case '\'':
{
if (!extensions) break;
move();
push(data[pos[1] * cols + pos[0]]);
} break;
}
move();
}
end_of_loop:;
}
}
</code></pre>
<p>to compile use:</p>
<p><code>Makefile</code></p>
<pre><code>cxx = clang++
flags = -Ofast -march=native -s -Wall -Wextra -pedantic -std=c++17
all: b93.cc
$(cxx) $(flags) b93.cc -o b93
clean:
rm b93
</code></pre>
|
[] |
[
{
"body": "<h1>Use <code>iostream</code> for file input/output</h1>\n<p>The C++ way of doing file I/O is by using <code>iostream</code> instead of <code>stdio</code>. I recommend you use this, as it integrates more easily with C++ types like <code>std::string</code> and so on, and provides RAII semantics.</p>\n<p>For formatted output, consider using <a href=\"https://github.com/fmtlib/fmt\" rel=\"nofollow noreferrer\">fmtlib</a>. C++20's <a href=\"https://en.cppreference.com/w/cpp/utility/format/format\" rel=\"nofollow noreferrer\"><code>std::format()</code></a> is based on that library. For scanning integers, you can use <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/stol\" rel=\"nofollow noreferrer\"><code>std::stoi()</code></a>.</p>\n<h1>Avoid passing <code>std::string_view</code>s to functions that do not expect them</h1>\n<p>In the following code:</p>\n<pre><code>grid_t readfile(std::string_view filepath)\n{\n ...\n std::FILE * const file = std::fopen(filepath.data(), "r");\n ...\n}\n</code></pre>\n<p>You have created the possibility for reading past the end of the string <code>filepath</code>. The reason is that a <code>std::string_view</code> does not guarantee that the string pointed to is terminated by a NUL byte. And even if the original string is, the part that the <code>std::string_view</code> points to might not, leading to unexpected behaviour. You have to either create a regular <code>std::string</code> from it first:</p>\n<pre><code>grid_t readfile(std::string_view filepath_view)\n{\n ...\n std::string filepath(filepath_view);\n std::FILE * const file = std::fopen(filepath.data(), "r");\n ...\n}\n</code></pre>\n<p>Or just make the argument a regular <code>std::string</code>:</p>\n<pre><code>grid_t readfile(const std::string &filepath_view)\n{\n ...\n</code></pre>\n<p>I would use the latter. Alternatively:</p>\n<h1>Use <code>std::filesystem::path</code> for paths</h1>\n<p>Consider using <code>std::filesystem::path</code>. Typically, you would create an alias for <code>std::filesystem</code> to avoid typing a lot of characters each time, so:</p>\n<pre><code>using fs = std::filsystem;\n</code></pre>\n<p>And then you could write:</p>\n<pre><code>grid_t readfile(const fs::path &filepath)\n{\n grid_t result;\n ifstream file(filepath);\n\n std::array<char, max_row_size * max_col_size> data;\n if (file.read(data.data(), data.size())) {\n const auto bytes_read = file.gcount();\n ...\n }\n else\n {\n // handle error\n }\n}\n</code></pre>\n<p>This makes it more explicit what kind of argument <code>readfile()</code> expects.</p>\n<h1>Separate parsing arguments from interpreting the input</h1>\n<p>The function <code>main()</code> is too big and cluttered, it is doing too much. Try to simplify it. Parsing the input should be done in its own function. So:</p>\n<pre><code>int main(int argc, char *argv[])\n{\n for (int i = 1; i < argc; ++i)\n {\n bool extensions = false;\n\n if (/* argv[i] is an option */)\n {\n // parse the option\n }\n\n auto grid = readfile(argv[i]);\n interpret(grid, extensions);\n }\n}\n</code></pre>\n<p>And possibly, if parsing options gets more complicated, you want to move that out of <code>main()</code> as well if possible.</p>\n<p>Note that once the interpreter itself is in its own function, you no longer need the ugly <code>goto end_of_loop</code>.</p>\n<h1>Beware of narrowing casts</h1>\n<pre><code>std::ptrdiff_t y = static_cast<std::ptrdiff_t>(pop());\n</code></pre>\n<p>Why is <code>y</code> a <code>ptrdiff_t</code>, when the stack has <code>int32_t</code>'s? This means that if you really have a very large grid, some programs will not run correctly. I don't know what the Befunge language standard says about this, but if the assumption is that grids are never larger than a 32-bit integer can hold, then maybe <code>pos</code> and <code>dir</code> should use <code>int32_t</code> instead of <code>ptrdiff_t</code>. That will also get rid of the casts.</p>\n<h1>Avoid unnecessary trailing return types</h1>\n<p>In most cases the return type of a lambda will be automatically deduced, so you can omit it. Why specify the return type explicitly, but use <code>auto</code> in lots of other places?</p>\n<h1>Avoid <code>goto</code>s</h1>\n<p>Most of the <code>goto</code>s you have in your code are unnecessary. Instead of writing <code>goto north</code>, why not create a few constants for that:</p>\n<pre><code>constexpr decltype(dir) north = {0, -1};\nconstexpr decltype(dir) south = {0, 1};\nconstexpr decltype(dir) east = {-1, 0};\nconstexpr decltype(dir) west = {1, 0};\n</code></pre>\n<p>And then you can write:</p>\n<pre><code>case '<':\n{\n dir = west;\n} break;\n\ncase '_':\n{\n dir = pop() ? west : east;\n} break;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T17:57:15.930",
"Id": "495239",
"Score": "0",
"body": "Wish I could up vote twice just for this statement `Note that once the interpreter itself is in its own function, you no longer need the ugly goto end_of_loop.`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T20:14:11.673",
"Id": "495253",
"Score": "0",
"body": "why should I use `std::filesystem::path` over `std::string_view`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T21:06:38.570",
"Id": "495260",
"Score": "0",
"body": "You should use `std::filesystem::path` for paths. That's what its for, and will make it easier to do path manipulation, and the `std::ifstream` constructor has an overload for it. Also, using a `std::string_view` like you do is asking for trouble, since there is no guarantee that a `std::string_view` has a terminating NUL byte. I'll add that to the answer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T17:52:36.717",
"Id": "251557",
"ParentId": "251521",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "251557",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T03:39:36.567",
"Id": "251521",
"Score": "4",
"Tags": [
"c++"
],
"Title": "Befunge-93 interpreter"
}
|
251521
|
<p>The question is - Write a program to remove the duplicates in a list</p>
<p>Here's how I did it-</p>
<pre><code>numbers = [1, 1, 1, 3, 3, 7, 7]
for i in numbers:
while numbers.count(i) > 1:
numbers.pop(numbers.index(i))
print(numbers)
</code></pre>
<p>Here's how the teacher in the youtube video did it-</p>
<pre><code>numbers = [2, 2, 4, 4, 6, 6]
uniques = []
for number in numbers:
if number not in uniques:
uniques.append(number)
print(uniques)
</code></pre>
<p>I know both the programs are objectively different in terms of how they do the task and the second program will I reckon consume more memory to create the new list however given the question which is the better approach and for what reasons?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T06:27:32.193",
"Id": "495173",
"Score": "3",
"body": "Too short for an answer, so: `numbers = list(set(numbers))`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T06:34:21.870",
"Id": "495174",
"Score": "1",
"body": "If you don't care about the order then just using `set(numbers)` will do the job"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T22:07:28.353",
"Id": "495457",
"Score": "0",
"body": "@FoundABetterNamd OMG! Was it Mosh Hamedani’s tutorial? I watched the same one!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T04:50:02.713",
"Id": "495502",
"Score": "0",
"body": "yup :) @fartgeek"
}
] |
[
{
"body": "<p>The teacher is obviously using a better way. Check/read more about time complexity for lists in python <a href=\"https://wiki.python.org/moin/TimeComplexity#list\" rel=\"nofollow noreferrer\">here (python wiki)</a>.</p>\n<p>In your case, you are going for a time complexity:</p>\n<ul>\n<li><span class=\"math-container\">\\$ O(n) \\$</span> for iteration</li>\n<li><span class=\"math-container\">\\$ O(n) \\$</span> for <code>.count()</code></li>\n<li><span class=\"math-container\">\\$ O(n) \\$</span> for intermediate pop</li>\n<li><span class=\"math-container\">\\$ O(n) \\$</span> for <code>.index</code></li>\n</ul>\n<p>for a final (worst case) time: <span class=\"math-container\">\\$ O(n^2) \\$</span> (see explanation <a href=\"https://codereview.stackexchange.com/questions/251523/two-ways-to-remove-duplicates-from-a-list/251524?noredirect=1#comment495269_251524\">in comments from superb rain</a>).</p>\n<p>In case of the tutorial:</p>\n<ul>\n<li><span class=\"math-container\">\\$ O(n) \\$</span> for iteration</li>\n<li><span class=\"math-container\">\\$ O(k) \\$</span> for <code>not in</code> check (using <span class=\"math-container\">\\$ k \\$</span> since the list is different now.</li>\n<li><span class=\"math-container\">\\$ O(1) \\$</span> for append</li>\n</ul>\n<p>generating a worst case performance of <span class=\"math-container\">\\$ O(n \\cdot k) \\$</span>.</p>\n<hr />\n<p>A more efficient solution, disregarding the order of elements would be the call:</p>\n<pre><code>uniques = list(set(numbers))\n</code></pre>\n<p>as suggested in comments. This would have <span class=\"math-container\">\\$ O(n) \\$</span> time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T07:21:24.963",
"Id": "495178",
"Score": "0",
"body": "If you do care about the order, you can still use a `set`, at the cost of O(k) additional memory, by keeping an additional `seen` set around."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T07:38:46.907",
"Id": "495179",
"Score": "0",
"body": "Thanks for the explanation"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T13:44:31.617",
"Id": "495216",
"Score": "3",
"body": "Theirs is O(n^2), not just O(n^3)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T15:09:13.033",
"Id": "495222",
"Score": "1",
"body": "Improvement on `uniques = list(set(numbers))` would be `uniques = list(dict.fromkeys(numbers))`; on modern Python (CPython/PyPy 3.6+, all Python 3.7+) `dict`s are insertion ordered, so the unique elements will remain in order of first appearance in the input, where `set` would apply a quasi-randomized order."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T16:48:26.743",
"Id": "495230",
"Score": "0",
"body": "@superbrain \"worst case\" being all the numbers are the same. the outer loop would run once, but the while loop and pop+index get n^3"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T16:49:38.023",
"Id": "495232",
"Score": "0",
"body": "@ShadowRanger there was recently another post on code review, where it was seen that dict allocation takes a lot longer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T17:53:20.147",
"Id": "495237",
"Score": "0",
"body": "@hjpotter92: Longer sure (`set` and `dict` are optimized for different use cases, `dict` has to have an unused value store `set` avoids, and certain resizing operations on `dict`s are more expensive due to variable width elements in the key array). But a *lot* longer? Depends on your idea of \"a lot\" I guess. In local tests, it looks like the worst case scenario has `list(dict.fromkeys(someiterable))` take twice as long as `list(set(someiterable))` (50-100% longer was typical). So sure, it's slower to use `dict.fromkeys`, but it's also the simplest way to preserve order to match OP's code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T21:26:02.063",
"Id": "495269",
"Score": "1",
"body": "@hjpotter92 I have no idea why you think they take n^3. They don't. Only n^2. In that \"worst case\", you have n count, n-1 index and n-1 pop, each of which takes time O(n). So ~3n\\*O(n) = O(n^2)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T01:44:20.173",
"Id": "495298",
"Score": "1",
"body": "@hjpotter92 Actually that's a best case. Someone sadly deleted the explanation I posted earlier, but here's a [benchmark](https://repl.it/repls/QuizzicalMeagerRectangle#main.py) now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T09:11:44.440",
"Id": "495341",
"Score": "0",
"body": "@superbrain updated my post above. not sure why i multiplied for `.pop` and `.index`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T09:13:36.067",
"Id": "495343",
"Score": "0",
"body": "@ShadowRanger https://codereview.stackexchange.com/a/250682/12240"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T11:52:25.280",
"Id": "495353",
"Score": "0",
"body": "@hjpotter92: Yeah, the conditions there are significantly different (implementation as Python code, not built-ins, where the Python bytecode differs a lot more, and `defaultdict(bool)` adds extra overhead to the addition of every new key). And in that solution, order is irrelevant, so `dict` doesn't provide any benefits \"for free\". Both conditions don't apply here; the incremental overhead for `dict.fromkeys` is less (though still non-zero) and preserving order is a meaningful benefit that `set` doesn't provide."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T13:02:46.363",
"Id": "495365",
"Score": "0",
"body": "Both the teacher's and the student's codes are O(n^2). The teacher's code could easily be improved to O(n) by replacing the list `unique` by a python `set`. I wouldn't say the teacher's code is \"obviously a better way\" when they both have approximately the same complexity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T13:34:55.887",
"Id": "495372",
"Score": "0",
"body": "@Stef https://tinyurl.com/codereview-251523 check the timings, hence _obviously_."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T13:52:59.687",
"Id": "495376",
"Score": "1",
"body": "@hjpotter92 The example you gave contains only duplicates of a single number. Nice way to choose an example so the numbers tell what you want them to tell!"
}
],
"meta_data": {
"CommentCount": "15",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T06:47:06.457",
"Id": "251524",
"ParentId": "251523",
"Score": "11"
}
},
{
"body": "<p>Your teacher's approach is better than yours, the main reason is the one noted in <a href=\"https://codereview.stackexchange.com/a/251524/98493\">the answer</a> by @hjpotter92.</p>\n<p>However, their approach can be optimized even more. Note that there is the <span class=\"math-container\">\\$O(k)\\$</span> check from <code>not in</code>. This is because when you check if an element is <code>in</code> a list, it goes through the whole list and tries to find it.</p>\n<p>A <code>set</code> on the other hand stores elements via their hashes, giving you <span class=\"math-container\">\\$O(1)\\$</span> <code>in</code> performance.</p>\n<p>If you don't care about the order of elements, you can just pass the input directly to <code>set</code>:</p>\n<pre><code>numbers = [2, 2, 4, 4, 6, 6]\nuniques = list(set(numbers))\n</code></pre>\n<p>If you do, however, care about maintaining the order of elements (and always using the position of where the element <em>first</em> appeared), you have to fill both a <code>list</code> and a <code>set</code>:</p>\n<pre><code>uniques = []\nseen = set()\nfor number in numbers:\n if number not in seen:\n uniques.append(number)\n seen.add(number)\nprint(uniques)\n</code></pre>\n<p>There are two caveats here, though:</p>\n<ul>\n<li>This takes additional memory, specifically <span class=\"math-container\">\\$O(k)\\$</span>, where <span class=\"math-container\">\\$k\\$</span> is the number of unique elements.</li>\n<li>This only works if all elements of the input list are "hashable". This basically boils down to them being not mutable, i.e. you can't use it with a list of lists or dicts. Numbers and strings are perfectly fine, though.</li>\n</ul>\n<p>Another thing you will probably learn about, if you haven't already, are functions. They allow you to encapsulate some functionality in one place, give it a name and reuse it:</p>\n<pre><code>def unique(x):\n uniques = []\n seen = set()\n for number in numbers:\n if number not in seen:\n uniques.append(number)\n seen.add(number)\n return uniques\n\nnumbers = [2, 2, 4, 4, 6, 6]\nprint(unique (numbers))\n</code></pre>\n<p>Actually, there are two more reasons why your teacher's solution is better:</p>\n<ul>\n<li>You mutate the input list when you do <code>pop</code>. This means that you would have to make a copy if you need the original list afterwards.</li>\n<li>Your teacher's code works as long as <code>numbers</code> is iterable, i.e. you can do <code>for x in numbers</code>. Your code relies on less universal methods like <code>pop</code>, <code>count</code> and <code>index</code> which are not implemented by all data structures. Being able to be iterated over is very common, though.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T07:38:55.997",
"Id": "495180",
"Score": "0",
"body": "Thanks for the explanation"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T13:05:40.513",
"Id": "495367",
"Score": "0",
"body": "It appears the two variables `seen` and `uniques` play the exact same role. You could simplify the code further: `uniques = list(set(numbers))`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T13:09:51.930",
"Id": "495369",
"Score": "0",
"body": "@Stef They do not. `uniques` is the output, which preserves the input order because it is a `list`. `seen` provides fast `in` comparisons, but no order information, since it is a `set`. Your approach is perfectly fine if the order does not matter (I forgot to add that as a note in my answer, though!)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T13:10:43.403",
"Id": "495370",
"Score": "0",
"body": "Oops, you're right."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T07:36:48.073",
"Id": "251526",
"ParentId": "251523",
"Score": "9"
}
},
{
"body": "<p><code>numbers.pop(numbers.index(i))</code> is equivalent to <code>numbers.remove(i)</code>.</p>\n<p>Given that your example lists are sorted and that your solution would fail for example <code>[1, 3, 1, 2, 3, 2]</code> (which it turns into <code>[3, 1, 3, 2]</code>, not removing the duplicate <code>3</code>), I'm going to assume that the input being sorted is part of the task specification. In which case that should be taken advantage of. Neither of the two solutions does.</p>\n<p>The teacher's can take advantage of it simply by checking <code>if number not in uniques[-1:]</code> instead of <code>if number not in uniques:</code>. Then it's O(n) instead of O(n^2) time.</p>\n<p>An alternative with <a href=\"https://docs.python.org/3/library/itertools.html#itertools.groupby\" rel=\"noreferrer\"><code>itertools.groupby</code></a>:</p>\n<pre><code>unique = [k for k, _ in groupby(numbers)]\n</code></pre>\n<p>Or in-place with just a counter of the unique values so far:</p>\n<pre><code>u = 0\nfor x in numbers:\n if u == 0 or x > numbers[u - 1]:\n numbers[u] = x\n u += 1\ndel numbers[u:]\n</code></pre>\n<p>Both take O(n) time. The latter is O(1) space if the final deletion doesn't reallocate or reallocates in place.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T16:46:28.377",
"Id": "495228",
"Score": "1",
"body": "`not in uniques [-1:]` is equivalent to `!= uniques [-1]`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T22:48:13.837",
"Id": "495282",
"Score": "3",
"body": "@hjpotter92 No, the latter would crash with an IndexError, as `uniques` starts empty."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T12:05:50.880",
"Id": "251537",
"ParentId": "251523",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "251524",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T06:13:36.060",
"Id": "251523",
"Score": "9",
"Tags": [
"python",
"comparative-review"
],
"Title": "Two ways to remove duplicates from a list"
}
|
251523
|
<p>I can feel the following is definitely not the optimal nor the cleanest way to do this. But I'm not quite sure how to refactor this.</p>
<pre><code>const formatBtnText = (txt, color, image) => {
const regex = /{image[\d]*}/g;
const matches = [...txt.matchAll(regex)];
if (!matches) {
return <Text style={[styles.buttonText, { color }]}>{txt}</Text>;
}
const strings = txt.split(regex);
let strIndex = 0;
let matchIndex = 0;
const res = [];
for (let i = 0; i < strings.length + matches.length; i++) {
if (i % 2 === 0) {
// every even is string
if (strings[strIndex] !== '') {
res.push(
<Text key={`${strIndex}_string`} style={[styles.buttonText, { color }]}>
{strings[strIndex]}
</Text>
);
}
strIndex++;
} else {
// every other is match
res.push(
<Image
key={`${matchIndex}_image`}
source={{ uri: image.uri }}
style={[styles.buttonImage, { width: (12 * image.width) / image.height }]}
/>
);
matchIndex++;
}
}
return res;
};
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T07:50:31.337",
"Id": "251528",
"Score": "1",
"Tags": [
"react-native"
],
"Title": "react string replace {image0} with actual image ramda?"
}
|
251528
|
<h2>About this exercise</h2>
<p>I found out there is a form of strict types in PHP 7.4, so I freshened up my PHP coding with this simple <code>Address</code> class. I did not use PHP since forever. So, any and all answers and comments highly appreciated. (This question is an update on <a href="https://codereview.stackexchange.com/q/251517/104270">its deleted version</a>; <sub>only users with reputation above 10k threshold can see deleted questions</sub>)</p>
<p>I still do not know exactly how the exceptions are to be used. If I made some sort of error in this area, please excuse me, but this code is working on my webserver without much testing.</p>
<p><strong>Additional Note (EDIT)</strong>: This class is culturally specific to the Czech Republic, where, just to clarify:</p>
<ul>
<li><p>Street and City have a minimum of 2 characters.</p>
</li>
<li><p>All of the following must be integers: House number / Orientation number, and the Zip code. There can be no letters to the House number for example, nor in the other two.</p>
</li>
</ul>
<hr />
<h2>Code</h2>
<pre class="lang-php prettyprint-override"><code><?php
// independent class
declare(strict_types=1);
class Address
{
private string $street = "";
private int $houseNumber = 0;
private int $orientationNumber = 0;
private string $city = "";
private int $zip = 0;
public function setStreet(string $newStreet): void
{
if (strlen($newStreet) >= 2)
{
$this->street = $newStreet;
}
else
{
throw new Exception("Street needs to be of length 2 or more.");
}
}
public function setHouseNumber(int $newHouseNumber): void
{
if (is_int($newHouseNumber) && $newHouseNumber > 0)
{
$this->houseNumber = $newHouseNumber;
}
else
{
throw new Exception('House number needs to have a value greater than 0.');
}
}
public function setOrientationNumber(int $newOrientationNumber): void
{
if (is_int($newOrientationNumber) && $newOrientationNumber >= 0)
{
$this->orientationNumber = $newOrientationNumber;
}
else
{
throw new Exception("Orientation number needs to have a value greater than 0; Can be equal to 0, in which case it won't be visible in full address.");
}
}
public function setCity(string $newCity): void
{
if (strlen($newCity) >= 2)
{
$this->city = $newCity;
}
else
{
throw new Exception("City needs to be of length 2 or more.");
}
}
public function setZip(int $newZip): void
{
if (is_integer($newZip) && $newZip >= 10000 && $newZip <= 99999 )
{
$this->zip = $newZip;
}
else
{
throw new Exception("Czech postal code must be integer in hypothetical range <10000;99999>.");
}
}
public function __construct(
string $initStreet,
int $initHouseNumber,
int $initOrientationNumber,
string $initCity,
int $initZip)
{
$this->setStreet($initStreet);
$this->setHouseNumber($initHouseNumber);
$this->setOrientationNumber($initOrientationNumber);
$this->setCity($initCity);
$this->setZip($initZip);
}
public function getStreet(): string
{
return $this->street;
}
public function getHouseNumber(): int
{
return $this->houseNumber;
}
public function getOrientationNumber(): int
{
return $this->orientationNumber;
}
public function getCity(): string
{
return $this->city;
}
public function getZip(): int
{
return $this->zip;
}
public function getFullAddress(): string
{
$fullAddress = $this->street . " " . $this->houseNumber;
if ($this->orientationNumber !== 0)
{
$fullAddress .= "/" . $this->orientationNumber;
}
$fullAddress .= ", " . $this->zip . " " . $this->city;
return $fullAddress;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T08:12:46.460",
"Id": "495183",
"Score": "1",
"body": "I would use strings everywhere for addresses. For example, ZIP codes can start with a zero. I don't think there's much to review here, unless you actually plan to use this class for something."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T08:29:35.327",
"Id": "495184",
"Score": "2",
"body": "If you are coercing `int` with `int $newHouseNumber`, then the `is_int($newHouseNumber)` check is useless."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T08:30:11.840",
"Id": "495185",
"Score": "0",
"body": "@KIKOSoftware Deployed already on my company's web, but not of much use since I store only my address there. Anyway, if there is a space to improve, then improve it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T08:30:49.720",
"Id": "495186",
"Score": "0",
"body": "@mickmackusa I see. So, basically, I don't need to check it. Ok."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T08:33:46.807",
"Id": "495187",
"Score": "0",
"body": "@mickmackusa _Coercing_ means what exactly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T11:27:24.463",
"Id": "495200",
"Score": "0",
"body": "There might be an argument for using your own getters in `getFullAddress()`, just like you use your own setters in your constructor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T11:32:09.293",
"Id": "495201",
"Score": "0",
"body": "@KIKOSoftware Already implemented as it was pointed out to me under the below answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T11:36:05.377",
"Id": "495202",
"Score": "0",
"body": "Ah, I missed that. You're not planning to work international?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T11:57:15.037",
"Id": "495206",
"Score": "0",
"body": "@KIKOSoftware Not on this particular class, I'm having some other projects, mostly unfinished business, in POSIX shell, which are international. This web site PHP code is for my address from the Czech republic only, however. Sorry, it took so many words to answer you. Thank you anyway. "
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T20:36:41.300",
"Id": "495255",
"Score": "0",
"body": "Is there a use-case for the setters beyond the constructor? If not could they be made private or the logic moved into the constructor? I don't want to go down the rabbit hole about immutable objects, but unless you have a need to create an object with all required fields, and then allow for changing those, you could reduce your surface area. I also wanted to point out that PHP 8 is around the corner which you might want to look into, specifically [constructor property promotion](https://stitcher.io/blog/constructor-promotion-in-php-8). I'm not saying it is good or bad, just that it exists."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T20:52:29.300",
"Id": "495257",
"Score": "0",
"body": "@ChrisHaas I will have to think about it, but thank you for the link to the new feature in any case. "
}
] |
[
{
"body": "<p>I was able to come up with two suggestions so far</p>\n<p>Using a generic exception is definitely not the way to go. Ask yourself a question, what your code is supposed to do when such an exception is thrown? displaying it to a user? but what if an exception was not a validation error at all but some serious system error, such as "class not found" for example? You don't want to show such errors to a site user.</p>\n<p>At least make it InvalidArgumentException, which is better suited for this kind of error.</p>\n<p>Better yet, create a custom InvalidAddressArgumentException and throw this one, so you will be able to catch only Address validation errors and leave all other errors alone.</p>\n<p>And a petty issue, using is_int() for an argument that is already typehinted makes no sense. It will never return false.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T09:07:48.617",
"Id": "495189",
"Score": "1",
"body": "Additionally, since you do have `getVar()` system in place, use those methods in the `getFullAddress` as well @LinuxSecurityFreak"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T09:17:06.517",
"Id": "495193",
"Score": "0",
"body": "@LinuxSecurityFreak that's actually a different question: *why* did you make all those getters? For which purpose? Probably an answer to this will lead you to the answer to yours"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T10:06:37.647",
"Id": "495197",
"Score": "0",
"body": "\"petty\" ...I'm heartbroken. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T20:44:01.377",
"Id": "495256",
"Score": "0",
"body": "The second answer seems more in-depth. However, thank you for your time and those two good suggestions! "
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T08:33:29.987",
"Id": "251531",
"ParentId": "251529",
"Score": "5"
}
},
{
"body": "<p>I saw your post yesterday before it was deleted. I didn’t have much to suggest but after seeing this code there are a few things I would change.</p>\n<p>The suggestions by YourCommonSense are great:</p>\n<ul>\n<li>Specific exception sub-classes (which can be custom) can help determine how edge cases should be handled by code that calls your code.</li>\n<li>With strict typing enabled, a non-integer passed to a function that expects an integer would lead to a TypeError<sup><a href=\"https://www.php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration.strict\" rel=\"nofollow noreferrer\">1</a></sup> so the calls to <code>is_int()</code> in the methods that expect integers for parameters is superfluous.</li>\n</ul>\n<h1>Suggestions</h1>\n<h2>Constructor placement</h2>\n<p>Many developers writing OOP code will place the constructor before all other methods in the class definitions, like the code in your previous post contained. This is not required and many IDEs would have a quick way to find it but it helps you (or a teammate) find it quicker than hunting through the source.</p>\n<h2>Default values for member/instance variables</h2>\n<p>The default values are great, though given that the constructor requires all to be passed (which then get passed to the setters) it makes the default values superfluous.</p>\n<h2>Docblocks</h2>\n<p><a href=\"https://github.com/php-fig/fig-standards/blob/master/proposed/phpdoc.md\" rel=\"nofollow noreferrer\">PSR-5</a> is in draft status currently but is commonly followed amongst PHP developers. It recommends adding docblocks above structural elements like classes, methods, properties, etc. Many popular IDEs will index the docblocks and use them to suggest parameter names when using code that has been documented. At least do it for the methods like the constructor, in case you forget which order the parameters are in.</p>\n<h2>Avoiding <code>else</code> when possible</h2>\n<p>In <a href=\"https://www.youtube.com/watch?v=GtB5DAfOWMQ\" rel=\"nofollow noreferrer\">this presentation about cleaning up code</a> Rafael Dohms talks about <code>return</code>ing early, limiting the indentation level to one per method and avoiding the <code>else</code> keyword. (<a href=\"https://www.slideshare.net/rdohms/bettercode-phpbenelux212alternate/11-OC_1Only_one_indentation_level\" rel=\"nofollow noreferrer\">see the slides here</a>).</p>\n<p>Most of the setter methods have a validation check with an <code>else</code> block. If the logic was flipped - i.e. when validation fails then throw the exception, then the <code>else</code> keyword could be eliminated. This will keep indentation levels at a minimum. For small methods like these it likely won’t make a big difference but in larger methods it would be significant.</p>\n<p>Let’s look at one setter:</p>\n<blockquote>\n<pre><code>public function setStreet(string $newStreet): void\n{\n if (strlen($newStreet) >= 2)\n {\n $this->street = $newStreet;\n }\n else\n {\n throw new Exception("Street needs to be of length 2 or more.");\n }\n }\n</code></pre>\n</blockquote>\n<p>Moving the <code>throw</code> statement up will allow the method to be shortened and indentation levels decreased:</p>\n<pre><code>public function setStreet(string $newStreet): void\n{\n if (strlen($newStreet) < 2)\n {\n throw new Exception("Street needs to be of length 2 or more.");\n }\n $this->street = $newStreet;\n}\n</code></pre>\n<p>The <code>else</code> is not needed, since “<em>code following the [<code>throw</code>] statement will not be executed, and PHP will attempt to find the first matching catch block</em>”<sup><a href=\"https://www.php.net/manual/en/language.exceptions.php\" rel=\"nofollow noreferrer\">2</a></sup></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T20:59:50.847",
"Id": "495258",
"Score": "1",
"body": "Did you not mention those two very good suggestions from the other answer intentionally. They are definitely a thing to implement for me. Anyway, thanks for the further hints! "
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T21:19:07.980",
"Id": "495264",
"Score": "0",
"body": "I agree with the suggestions in the answer by YourCommonSense, and I often state that though I neglected to do so initially. After reading [this meta](https://codereview.meta.stackexchange.com/q/2473/120114) perhaps I should make it a habit."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T14:18:48.757",
"Id": "251543",
"ParentId": "251529",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "251543",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T07:52:59.390",
"Id": "251529",
"Score": "2",
"Tags": [
"php",
"object-oriented",
"classes",
"type-safety"
],
"Title": "Address class in PHP 7.4 with types"
}
|
251529
|
<p>I have this challange that I finished which asked to print out a string according to the provided schedule. Here is an example:</p>
<pre><code>var restaurant = new Restaurant(
new OpeningHour(8,16), // Sunday
new OpeningHour(8,17), // Monday
new OpeningHour(8,17), // Tuesday
new OpeningHour(8,17), // Wednesday
new OpeningHour(8,16), // Thursday
new OpeningHour(8,16), // Friday
new OpeningHour(8,16) // Saturday
);
</code></pre>
<p><strong>expected output result</strong> = "Sun, Thu - Sat: 8-16, Mon - Wed: 8-17"</p>
<p>What I did was essentially:</p>
<ul>
<li>Create a List of Days, OpenHours, and CloseHours</li>
<li>Create a HashSet of the days so that I can compare the days</li>
<li>Create a for loop according to HashSet and Days</li>
<li>Seperate the Start, Middle, and Ending</li>
<li>Concatenate the result according to the open and close hours as well as the gap between days</li>
</ul>
<p>I have tried my best but I know for a fact that my code is not efficient at all, instead messy. I am trying to improve my C# skills please help. Here is my messy code:</p>
<pre><code>namespace Livit
{
using System;
using System.Collections.Generic;
using System.Linq;
public class Restaurant
{
public WeekCollection<OpeningHour> OpeningHours { get; private set; }
public Restaurant() {
// No opening hours available for restaurant
}
public Restaurant(OpeningHour monday, OpeningHour tuesday, OpeningHour wednesday, OpeningHour thursday, OpeningHour friday, OpeningHour saturday, OpeningHour sunday)
{
OpeningHours = new WeekCollection<OpeningHour>(monday, tuesday, wednesday, thursday, friday, saturday, sunday);
}
// THE EMPHASIS OF THE CHALLANGE IS THIS FUNCTION RIGHT HERE!!!
// Parse the date into desired format
public string DateParser(List<DayOfWeek> days, List<TimeSpan> openHours, List<TimeSpan> closeHours)
{
HashSet<string> availableRanges = new HashSet<string>();
List<string> timeRanges = new List<string>();
DayOfWeek current = DayOfWeek.Sunday;
string result = "";
for (int i = 0 ; i < days.Count; i++){
string timeRange = openHours[i].ToString().Substring(1,1)+'-'+closeHours[i].ToString().Substring(0,2);
availableRanges.Add(timeRange);
timeRanges.Add(timeRange);
}
List<string> arToList= availableRanges.ToList();
for (int i = 0 ; i < arToList.Count; i++)
{
for (int j = 0 ; j < timeRanges.Count; j++){
if(timeRanges[j] == arToList[i]){
// First Item
if(j==0 ){
result += days[j].ToString().Substring(0,3);
}
// Last Item
else if(j==timeRanges.Count-1){
char last = result.Last();
if(last != ' '){
result += " - ";
}
result += days[j].ToString().Substring(0,3);
}
// Everything in the middle
else{
if(days[j]-current > 1){
result += ", ";
}
if(timeRanges[j] != timeRanges[j-1] ){
result += days[j].ToString().Substring(0,3);
} else if (timeRanges[j] == timeRanges[j-1]){
char last = result.Last();
if(last != ' '){
result += " - ";
}
if(timeRanges[j] != timeRanges[j+1]){
result += days[j].ToString().Substring(0,3);
}
}
}
current = days[j];
}
}
result += ": " + arToList[i];
if(i!=arToList.Count-1){
result += ", ";
}
}
Console.WriteLine(result);
return result;
}
public string GetOpeningHours()
{
// Declare List for each attribute
List<DayOfWeek> days = new List<DayOfWeek>();
List<TimeSpan> openHours = new List<TimeSpan>();
List<TimeSpan> closeHours = new List<TimeSpan>();
// Call the opening and closing hours from each day and feed into new array
foreach (DayOfWeek day in Enum.GetValues(typeof(DayOfWeek)).OfType<DayOfWeek>().ToList()) {
TimeSpan openHour = OpeningHours.Get(day).OpeningTime;
TimeSpan closeHour = OpeningHours.Get(day).ClosingTime;
days.Add(day);
openHours.Add(openHour);
closeHours.Add(closeHour);
}
return DateParser(days,openHours,closeHours);
throw new NotImplementedException();
}
}
public class OpeningHour
{
public TimeSpan OpeningTime { get; private set; }
public TimeSpan ClosingTime { get; private set; }
public OpeningHour(TimeSpan openingTime, TimeSpan closingTime)
{
OpeningTime = openingTime;
ClosingTime = closingTime;
}
public OpeningHour(int openingHour, int closingHour)
{
OpeningTime = TimeSpan.FromHours(openingHour);
ClosingTime = TimeSpan.FromHours(closingHour);
}
}
public class WeekCollection<T>
{
private Dictionary<DayOfWeek, T> _collection;
public WeekCollection(T sunday, T monday, T tuesday, T wednesday, T thursday, T friday, T saturday)
{
_collection = new Dictionary<DayOfWeek, T>();
_collection.Add(DayOfWeek.Sunday, sunday);
_collection.Add(DayOfWeek.Monday, monday);
_collection.Add(DayOfWeek.Tuesday, tuesday);
_collection.Add(DayOfWeek.Wednesday, wednesday);
_collection.Add(DayOfWeek.Thursday, thursday);
_collection.Add(DayOfWeek.Friday, friday);
_collection.Add(DayOfWeek.Saturday, saturday);
}
public T Get(DayOfWeek dayOfWeek)
{
return _collection[dayOfWeek];
}
}
}
</code></pre>
<p><strong>Currently, I am still trying to find a better way in doing this challange. Any help would be appriciated.</strong></p>
<p>P.S. I highlighted the part where my concatenation is occuring, this part is basically the emphasis of the whole challange</p>
|
[] |
[
{
"body": "<p>The biggest improvement regarding performance would be to use a <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.text.stringbuilder?view=netcore-3.1\" rel=\"nofollow noreferrer\"><code>StringBuilder</code></a> instead of concatinating strings by the meaning of <code>result += ...</code> because the later will create a new <code>string</code> each time.</p>\n<blockquote>\n<p>Hi I am new to this StringBuilder, could you show me the right way to do it?</p>\n</blockquote>\n<p>As an example based on your code:</p>\n<pre><code>StringBuilder stringBuilder = new StringBuilder();\nfor (int i = 0; i < arToList.Count; i++)\n{\n for (int j = 0; j < timeRanges.Count; j++)\n {\n if (timeRanges[j] == arToList[i])\n {\n // First Item\n if (j == 0)\n {\n stringBuilder.Append(days[j].ToString().Substring(0, 3));\n }\n // Last Item\n else if (j == timeRanges.Count - 1)\n {\n char last = result.Last();\n if (last != ' ')\n {\n stringBuilder.Append(" - ");\n }\n stringBuilder.Append(days[j].ToString().Substring(0, 3));\n }\n</code></pre>\n<p>When you need the content of the <code>StringBuilder</code> you just use the <code>ToString()</code> method.</p>\n<hr />\n<ul>\n<li><p>To show correct results you will need to force the restaurant to open before 10. Thats because for openinghours you take the second char. A better way would be to correctly use the <code>TimeSpan</code> objects by accessing the <code>Hours</code> property.</p>\n</li>\n<li><p>You could use <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated\" rel=\"nofollow noreferrer\"><code>String interpolation</code></a> instead of doing e.g <code>string + " - " + string</code> which would look for the first loop like so</p>\n<pre><code>string timeRange = $"{openHours[i].Hours}-{closeHours[i].Hours}";\n</code></pre>\n</li>\n<li><p>The most inner loop doesn't need to iterate each time over all the <code>timeRanges</code>. Each seen item can be skipped. This can be done by using <code>(int)current</code> as the initial value for <code>j</code>.</p>\n</li>\n<li><p>There is some discrepancy regarding the constructor of the <code>Restaurant</code> and the constructor of the <code>WeekCollection</code>. The first parameter of <code>Restaurant</code>'s constructor is <code>monday</code> which is passed to the <code>WeekCollection<></code>'s constructor as parameter <code>sunday</code>. If one sees only the constructor of <code>Restaurant</code> the expected results won't match.</p>\n</li>\n<li><p>"//Everything in the middle": at least with the provided test-data you can safely remove this:</p>\n<pre><code>if (days[j] - current > 1)\n{\n stringBuilder.Append(", ");\n}\n</code></pre>\n<p>and change the <code>else if</code> to an <code>else</code>.</p>\n</li>\n</ul>\n<p>Summing up the <code>DateParser()</code> method, which by the way shouldn't be named like a noun but rather like a verb or verb-phrase would look like this:</p>\n<pre><code>public string DateParser(List<DayOfWeek> days, List<TimeSpan> openHours, List<TimeSpan> closeHours)\n{\n HashSet<string> availableRanges = new HashSet<string>();\n List<string> timeRanges = new List<string>();\n DayOfWeek current = DayOfWeek.Sunday;\n\n for (int i = 0; i < days.Count; i++)\n {\n string timeRange = $"{openHours[i].Hours}-{closeHours[i].Hours}";\n availableRanges.Add(timeRange);\n timeRanges.Add(timeRange);\n }\n StringBuilder stringBuilder = new StringBuilder();\n \n List<string> arToList = availableRanges.ToList();\n for (int i = 0; i < arToList.Count; i++)\n {\n for (int j = (int)current; j < timeRanges.Count; j++)\n {\n if (timeRanges[j] == arToList[i])\n {\n // First Item\n if (j == 0)\n {\n stringBuilder.Append(days[j].ToString().Substring(0, 3));\n }\n // Last Item\n else if (j == timeRanges.Count - 1)\n {\n char last = stringBuilder[stringBuilder.Length - 1];\n if (last != ' ')\n {\n stringBuilder.Append(" - ");\n }\n stringBuilder.Append(days[j].ToString().Substring(0, 3));\n }\n // Everything in the middle\n else\n {\n if (timeRanges[j] != timeRanges[j - 1])\n {\n stringBuilder.Append(days[j].ToString().Substring(0, 3));\n }\n else\n {\n char last = stringBuilder[stringBuilder.Length - 1];\n if (last != ' ')\n {\n stringBuilder.Append(" - ");\n }\n if (timeRanges[j] != timeRanges[j + 1])\n {\n stringBuilder.Append(days[j].ToString().Substring(0, 3));\n }\n }\n }\n current = days[j];\n }\n }\n\n stringBuilder.Append(": " + arToList[i]);\n if (i != arToList.Count - 1)\n {\n stringBuilder.Append(", ");\n }\n }\n return stringBuilder.ToString();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T12:25:05.423",
"Id": "495208",
"Score": "0",
"body": "Hi I am new to this StringBuilder, could you show me the right way to do it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T07:26:33.697",
"Id": "495335",
"Score": "0",
"body": "Wow this is awesome, does this mean that StringBuilder takes inputs just like an List does and automatically append it afterwards?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T07:38:57.863",
"Id": "495337",
"Score": "1",
"body": "Just read through the provided link."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T07:43:33.087",
"Id": "495338",
"Score": "0",
"body": "I see... this really improved performance wise. How about algorithm wise? Is there a better way to approach this challange?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T23:29:48.993",
"Id": "495467",
"Score": "0",
"body": "I wanted to ask you about the usage of availableRange.ToList(). I did this because i wanted to use the index in my loop but it probably cost me some performance since it create new memory allocation does it not? Is there any better way to directly do it with the HashSet so that I don't have to create another List?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T09:50:55.287",
"Id": "251532",
"ParentId": "251530",
"Score": "3"
}
},
{
"body": "<h3>There is a bug in your code</h3>\n<p>Your example and your code do not correspond. Your example starts with Sunday, yet the first parameter of your constructor is Monday, which then uses <code>WeekCollection</code> which starts with... Sunday!</p>\n<h3>A suggestion</h3>\n<p>IMHO <code>OpeningHour</code> should contain a parameter to indicate the day of the week, so you can pass a collection of <code>OpeningHour</code> to the constructor which should then check for duplicates. That way you can also have days where the restaurant is closed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T23:01:53.390",
"Id": "495464",
"Score": "0",
"body": "Thank you for this insight, I did'nt even realize this"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T16:53:54.700",
"Id": "251605",
"ParentId": "251530",
"Score": "3"
}
},
{
"body": "<p>When you initialize the dictionary in <code>WeekCollection<T></code> you could/should do it like this:</p>\n<pre><code> _collection = new Dictionary<DayOfWeek, T>\n {\n { DayOfWeek.Sunday, sunday },\n { DayOfWeek.Monday, monday },\n { DayOfWeek.Tuesday, tuesday },\n { DayOfWeek.Wednesday, wednesday },\n { DayOfWeek.Thursday, thursday },\n { DayOfWeek.Friday, friday },\n { DayOfWeek.Saturday, saturday }\n };\n</code></pre>\n<p>Personally I think that <code>WeekCollection<T></code> is superfluous. It doesn't really help to solve the problem, nor does it make the code more clear. So I would use its incapsulated dictionary directly in <code>Restaurant</code>:</p>\n<pre><code>public class Restaurant\n{\n public Dictionary<DayOfWeek, OpeningHour> OpeningHours { get; }\n\n public Restaurant(OpeningHour sunday, OpeningHour monday, OpeningHour tuesday, OpeningHour wednesday, OpeningHour thursday, OpeningHour friday, OpeningHour saturday)\n {\n OpeningHours = new Dictionary<DayOfWeek, OpeningHour>\n {\n { DayOfWeek.Sunday, sunday },\n { DayOfWeek.Monday, monday },\n { DayOfWeek.Tuesday, tuesday },\n { DayOfWeek.Wednesday, wednesday },\n { DayOfWeek.Thursday, thursday },\n { DayOfWeek.Friday, friday },\n { DayOfWeek.Saturday, saturday }\n };\n }\n\n ...\n}\n</code></pre>\n<hr />\n<p>A little about naming:</p>\n<blockquote>\n<pre><code>public class OpeningHour\n{\n public TimeSpan OpeningTime { get; private set; }\n public TimeSpan ClosingTime { get; private set; }\n</code></pre>\n</blockquote>\n<p>Descriptive names is a must and good, but IMO they should be as short as possible:</p>\n<pre><code>public class OpeningHour\n{\n public TimeSpan Open { get; }\n public TimeSpan Close { get; }\n</code></pre>\n<p>It's obvious from the context, that <code>OpeningTime</code> is a time object, so <code>Open</code> is precise and descriptive enough.</p>\n<hr />\n<p>But the major problem with the code in <code>DateParser()</code> is that you do many of the "computation" on the output strings. You compose the output and select from the days/opening hours via the built strings. This is error prone and makes the code unnecessary complex and hard to read.</p>\n<p>Instead you should group and select by the numeric values of the <code>OpeningHour</code> and <code>DayOfWeek</code> objects and from that result format the resulting string output.</p>\n<p>Below is a complete take on that - with some inline comments, that you maybe can find inspiration in:</p>\n<pre><code>public class Restaurant\n{\n // The WeekCollection is replaced with a plain dictionary\n private readonly Dictionary<DayOfWeek, OpeningHour> openingHours;\n public IReadOnlyDictionary<DayOfWeek, OpeningHour> OpeningHours => openingHours;\n\n public Restaurant(OpeningHour sunday, OpeningHour monday, OpeningHour tuesday, OpeningHour wednesday, OpeningHour thursday, OpeningHour friday, OpeningHour saturday)\n {\n openingHours = new Dictionary<DayOfWeek, OpeningHour>\n {\n { DayOfWeek.Sunday, sunday },\n { DayOfWeek.Monday, monday },\n { DayOfWeek.Tuesday, tuesday },\n { DayOfWeek.Wednesday, wednesday },\n { DayOfWeek.Thursday, thursday },\n { DayOfWeek.Friday, friday },\n { DayOfWeek.Saturday, saturday }\n };\n }\n\n public string GetOpeningHours()\n {\n var intervals = GroupByOpeningIntervals();\n\n StringBuilder builder = new StringBuilder();\n\n foreach (((var open, var close), var days) in intervals)\n {\n FormatInterval(builder, open, close, days);\n }\n\n builder.Length -= 2; // The last comma and space (", ")\n\n return builder.ToString();\n }\n\n // Format the result string according to your requirements\n private void FormatInterval(StringBuilder builder, TimeSpan open, TimeSpan close, List<DayOfWeek> days)\n {\n days.Sort();\n\n DayOfWeek firstDay = days[0];\n DayOfWeek lastDay = days[0];\n\n for (int i = 1; i < days.Count; i++)\n {\n DayOfWeek currDay = days[i];\n // If the current day isn't the next day from lastDay, then the current day interval ends, and a new begins with currDay as firstDay\n if (currDay != lastDay + 1)\n {\n AppendDayInterval(builder, firstDay, lastDay);\n firstDay = lastDay = currDay;\n }\n else\n {\n lastDay = currDay;\n }\n }\n\n AppendDayInterval(builder, firstDay, lastDay);\n builder.Length -= 2; // The last comma and space (", ")\n\n builder.AppendFormat(@": {0:hh\\:mm}-{1:hh\\:mm}, ", open, close);\n }\n\n // A helper function that format a DayOfWeekInterval\n private void AppendDayInterval(StringBuilder builder, DayOfWeek first, DayOfWeek last)\n {\n if (first == last)\n builder.AppendFormat("{0}, ", first.ToString().Substring(0, 3));\n else\n builder.AppendFormat("{0} - {1}, ", first.ToString().Substring(0, 3), last.ToString().Substring(0, 3));\n }\n\n // Grouping the OpeningHours into a dictionary having the open/close interval as key and a list of DayOfWeek values as value\n private Dictionary<(TimeSpan open, TimeSpan close), List<DayOfWeek>> GroupByOpeningIntervals()\n {\n Dictionary<(TimeSpan open, TimeSpan close), List<DayOfWeek>> intervals = new Dictionary<(TimeSpan open, TimeSpan close), List<DayOfWeek>>();\n\n // Each entry in OpeningHours is a KeyValuePair<K, V> which implements a Deconstruct(...) method and can therefore be decomposed into a tuple:\n foreach ((var day, var openingHour) in openingHours)\n {\n if (!intervals.TryGetValue(openingHour.Interval, out var set))\n intervals[openingHour.Interval] = set = new List<DayOfWeek>();\n set.Add(day);\n }\n\n return intervals;\n }\n}\n\npublic class OpeningHour\n{\n public TimeSpan Open { get; }\n public TimeSpan Close { get; }\n\n public OpeningHour(TimeSpan open, TimeSpan close)\n {\n Open = open;\n Close = close;\n }\n\n public OpeningHour(int open, int close) :\n this(TimeSpan.FromHours(open), TimeSpan.FromHours(close))\n {\n }\n\n // Just a convenient property.\n public (TimeSpan open, TimeSpan close) Interval => (Open, Close);\n\n public override string ToString()\n {\n return $"{Open.TotalHours} - {Close.TotalHours}";\n }\n}\n</code></pre>\n<p>As seen, there is very few comparison statements and all comparison is done on numeric values instead of on strings.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T23:16:07.803",
"Id": "495465",
"Score": "0",
"body": "Thank you for the correction. I really appreciate the effort you put into this answer. I am currently still reading about the comparison statements based on the numerical values and yes I am guilty as charged for using string as comparison. I have a question about the dictionary though, is it just good manner to put it directly inside the class or does it affect the performance as well?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T07:08:40.837",
"Id": "495511",
"Score": "1",
"body": "@Squish: How to use a dictionary (or any other type) depends on the context, so good manner or best practice isn't to define conclusively. In this context, it's IMO safe to use a dictionary directly, because you explicitly define the seven weekdays as arguments to the constructor of `Restaurant`. I think though that I should have made it a private field instead of a public property, and then provide some public IEnumerable, if needed. I have updated `Restaurant`..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T16:58:56.973",
"Id": "251606",
"ParentId": "251530",
"Score": "3"
}
},
{
"body": "<h3>Notes</h3>\n<ul>\n<li><p><strong>constructor</strong>:</p>\n<ul>\n<li>Not fully utilizing the <code>WeekCollection<T></code>, which is why it has too many arguments for one constructor.</li>\n<li>no validations</li>\n<li><code>default</code> constructor is not <code>private</code> to enforce using the custom constructor, which adds more unneeded validation requirements to the <code>OpeningHours</code>.</li>\n<li><code>OpeningHours</code> is not fully immutable, you can still modify the collection.</li>\n</ul>\n</li>\n<li><p>The implementation of <code>WeekCollection<T></code> is not needed, since it only restricted the underlying dictionary to 7 elements in week day order, which you can do in one line of code!.</p>\n</li>\n<li><p>The implementation of <code>OpeningHour</code> is good, but short! it would be better if you add <code>DayOfWeek</code> property to it, and use it in any array or collection as an object-model would be better.</p>\n</li>\n<li><p><strong>DateParser</strong>:</p>\n<ul>\n<li>arguments are un-chained, which either adds more complexity or invalidate the results.</li>\n<li>misleading method name, <code>Parser</code> supposed to parse it to some system or custom type, not getting the string representation of the date.</li>\n<li>Not utilizing or using the <code>OpeningHours</code>, which means, you're throwing away your efforts of implementing <code>OpeningHours</code> including <code>WeekCollection<T></code>!</li>\n</ul>\n</li>\n</ul>\n<h3>Moreover</h3>\n<p>because of your enormous constructor, it would be a good practice to consider using object modeling technique to minimize the arguments, and have a better control on it. So, you can modify your <code>OpeningHour</code> to something like this :</p>\n<pre><code>public class WorkDay\n{\n public DayOfWeek Day { get; set; }\n\n public TimeSpan OpenHour { get; set; }\n\n public TimeSpan CloseHour { get; set; }\n}\n\npublic class Restaurant\n{\n public List<WorkDay> WorkDays { get; }\n\n public Restaurant(List<WorkDay> workDays)\n {\n WorkDays = workDays;\n }\n}\n</code></pre>\n<p>Now, it's much simplified and easier to handle, as we avoided extra work, which disposed the need of <code>WeekCollection<T></code>. The rest can be handled from the constructor (like validating the object, order of elements ..etc.).</p>\n<h2>For the <code>DateParser</code></h2>\n<p>Almost all collections types have a constructor that takes <code>IEnumerable<T></code>, even if the collection doesn't have that constructor, it would have a method that takes a collection to be added like <code>AddRange</code> for instance. So, this :</p>\n<pre><code>HashSet<string> availableRanges = new HashSet<string>();\nList<string> timeRanges = new List<string>();\nfor (int i = 0 ; i < days.Count; i++){\n string timeRange = openHours[i].ToString().Substring(1,1)+'-' + closeHours[i].ToString().Substring(0,2);\n availableRanges.Add(timeRange);\n timeRanges.Add(timeRange);\n}\n</code></pre>\n<p>is not necessary, as you can do this :</p>\n<pre><code>var timeRanges = new List<string>();\n\nfor (int i = 0 ; i < days.Count; i++){ \n timeRanges.Add($"{{openHours[i]:%h}-{closeHours[i]:%h}");\n}\n\nvar availableRanges = new HashSet<string>(timeRanges);\n</code></pre>\n<p>though, when converting <code>TimeSpan</code> or <code>DateTime</code> you should always use <code>IFormatProvider</code> instead of <code>Substring</code> to specifiy the format you need (like <code>{openHours[i]:%h}</code> I specified the hour part only. The other bad practice is that you already have <code>TimeSpan</code> and you then converted to string, then used string comparison. This is bad, because you're changing the object type which loses its mutability, and preferences. Plus, it's another extra work. Why not just work the current object as is, and take advantage of its its benefits?.</p>\n<p>I think the reason behind the conversion to string is that you needed to put both <code>TimeSpan</code> to be compared, as the current solution is dealing with them separately. So, converting it to string would solve this issue, which is a <code>ghetto</code> solution.</p>\n<p>A proper solution is to use either <code>Object Modeling</code> (like <code>WorkDay</code> example above) or <code>Tuple</code> or <code>Dictionary</code> or a <code>KeyPairValue</code> or even creating anonymous type. Which would chain both objects. This way, you will still keep the object to its original state, and can be managed properly.</p>\n<p>Also, string is <code>immutable</code> so, when concatenating string, it would recreate a new string, and not appending to the current one. This would be really bad to the memory with large strings. Instead, use <code>StringBuilder</code>, as*@Heslacher mentioned in his answer.</p>\n<p>The loop itself can be simplified though, however, you've missed the order of days! because you're not using <code>WeekCollection<OpeningHour></code> which you've already ordered!</p>\n<p>P.S. <code>DayOfWeek</code> it's <code>enum</code> it can be cast to <code>int</code> value, which is an <code>int</code> representation of that day (0 = Sunday, and 6 = Saturday). So, why not just use it instead ?.</p>\n<h2>Example :</h2>\n<pre><code>public class WorkDay\n{\n public DayOfWeek Day { get; set; }\n\n public TimeSpan OpenHour { get; set; }\n\n public TimeSpan CloseHour { get; set; }\n\n public WorkDay(DayOfWeek day , TimeSpan openTime , TimeSpan closeTime)\n {\n Day = day;\n OpenHour = openTime;\n CloseHour = closeTime;\n }\n\n public WorkDay(DayOfWeek day , int openHour , int closeHour)\n {\n if(openHour > 24 || openHour < 0) { throw new ArgumentOutOfRangeException(nameof(openHour)); }\n\n if(closeHour > 24 || closeHour < 0) { throw new ArgumentOutOfRangeException(nameof(closeHour)); }\n\n OpenHour = new TimeSpan(openHour , 0 , 0);\n \n CloseHour = new TimeSpan(closeHour , 0 , 0);\n\n Day = day;\n }\n \n public string GetOpenCloseTimeAsString()\n {\n return $"{OpenHour:%h}-{CloseHour:%h}";\n }\n \n public override string ToString()\n {\n return $"{Day.ToString().Substring(0,3)}: {OpenHour:%h}-{CloseHour:%h}";\n }\n\n}\n \n \npublic class Restaurant\n{\n /// <summary>\n /// Enforced immutability, no changes on the list once the list is assigned. \n /// </summary>\n public IReadOnlyList<WorkDay> WorkDays { get; }\n\n /// <summary>\n /// Enforced constructor initiailization, always initiate with a IEnumerable<WorkDay>\n /// </summary>\n /// <param name="openHours"></param>\n public Restaurant(IEnumerable<WorkDay> workDays)\n {\n if(workDays == null)\n { throw new ArgumentNullException(nameof(workDays)); }\n\n // only seven days are allowed. \n var count = workDays.Count();\n \n if(count == 0 || count > 7) \n { throw new ArgumentOutOfRangeException(nameof(workDays)); }\n \n // forget the user order, just reorder the list before assign.\n // to ensure it'll be always in the given order\n WorkDays = workDays\n .OrderBy(x => x.OpenHour)\n .ThenBy(x => x.CloseHour)\n .ThenBy(x => (int) x.Day)\n .ToList();\n }\n\n\n /// <summary>\n /// If you need to return a HashSet or the list.\n /// </summary>\n /// <returns></returns>\n public HashSet<string> GetUniqueTimes()\n {\n return new HashSet<string>(WorkDays.Select(x => x.GetOpenCloseTimeAsString()));\n }\n\n public string GetWorkdaysAsString()\n {\n // The expected results can be acheived using Linq \n\n var result = WorkDays.GroupBy(x => new { x.OpenHour , x.CloseHour }\n , (key , values) => new\n {\n Time = key ,\n Days = values.Select(x => x.Day)\n .OrderBy(x => (int) x) // re-enforces the order by week days\n .Select(d => d.ToString().Substring(0 , 3))\n .ToList()\n })\n .Select(x =>\n {\n if (x.Days.Count == 1)\n {\n return new\n {\n StartDay = x.Days.First() ,\n Schedule = $"{x.Days.First()} : {x.Time.OpenHour:%h}-{x.Time.CloseHour:%h}"\n };\n }\n\n return new\n {\n StartDay = x.Days.First() ,\n Schedule = $"{x.Days.Skip(1).DefaultIfEmpty().First()} - {x.Days.Skip(1).DefaultIfEmpty().Last()}: {x.Time.OpenHour:%h}-{x.Time.CloseHour:%h}"\n };\n\n })\n .ToList();\n\n var open = result.First();\n var close = result.Last();\n\n return result.Count > 2 ? $"{open.StartDay}, {string.Join(", " , result.Select(x => x.Schedule))}" : $"{open.StartDay}, {open.Schedule}, {close.Schedule}";\n }\n}\n</code></pre>\n<p>Usage :</p>\n<pre><code> // since the constructor accepts IEnumerable<WorkDay>\n // I can pass List, Array, or any other collection that implements `IEnumerable`\nvar resturant = new Restaurant(new List<WorkDay>\n{\n new WorkDay(DayOfWeek.Sunday, 8, 16),\n new WorkDay(DayOfWeek.Monday, 8, 17),\n new WorkDay(DayOfWeek.Tuesday, 8, 17),\n new WorkDay(DayOfWeek.Wednesday, 8, 17),\n new WorkDay(DayOfWeek.Thursday, 8, 16),\n new WorkDay(DayOfWeek.Friday, 8, 16),\n new WorkDay(DayOfWeek.Saturday, 8, 16)\n});\n\n\nvar results = resturant.GetWorkdaysAsString();\n\n// in case you need to return the hashset of the times\nvar unique = resturant.GetUniqueTimes();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T09:15:12.150",
"Id": "495525",
"Score": "0",
"body": "you explained this really well... I really thank you for this, I learned a lot from what you have written here and most of my blunders are because of my inexperience in writing C# code. I have a question though regarding if I change the schedule of the dates. If i were to change the input to 8-16, 8,17, 8-19, 8-20, 8-21, 8-22 consequently from Sunday - Saturday, it throws a System.InvalidOperationException. Why is this? Does this mean I have to make a new sequence for each date pattern?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T11:29:02.977",
"Id": "495533",
"Score": "1",
"body": "@Squish this is a bug, because I don't have the full challenge requirements to cover all possible scenarios. However, you can work around it using `DefaultIfEmpty()` like this `x.Days.Skip(1).DefaultIfEmpty().First()`. But still, it needs to be handled correctly. Just for your learning, I have updated the code to cover that, which will help to understand the exception reason. Though, even my modification still lakes some other scenarios, which needs your magic ;)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T01:58:18.980",
"Id": "251631",
"ParentId": "251530",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "251631",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T08:17:49.013",
"Id": "251530",
"Score": "5",
"Tags": [
"c#",
"performance",
"beginner",
"algorithm",
"strings"
],
"Title": "String concatenation challange to be more efficient with DayOfWeek and Lists"
}
|
251530
|
<p>The task is to make a list of every lotto row if in a lotto, seven numbers are chosen from 39 numbers. Is there more elegant way to do this than my solution:</p>
<pre><code>rows = []
for a in range(1,40):
for b in range(a+1,40):
for c in range(b+1,40):
for d in range(c+1,40):
for e in range(d+1,40):
for f in range(e+1,40):
for g in range(f+1,40):
rows.append([a,b,c,d,e,f,g])
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T22:00:30.167",
"Id": "495272",
"Score": "1",
"body": "Regardless of the style of code, you will wait quite a lot its execution :)"
}
] |
[
{
"body": "<p>You could use <a href=\"https://docs.python.org/3/library/itertools.html#itertools.combinations\" rel=\"noreferrer\">itertools.combinations</a></p>\n<pre><code>import itertools\n\nrows = list(itertools.combinations(range(1, 40), 7))\n</code></pre>\n<p>If you want to know how to implement this without using a built-in, just read the sample implementation of <code>itertools.combinations</code> in the document.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T13:53:59.300",
"Id": "495218",
"Score": "0",
"body": "I'd go even further and use a `set` instead of a `list` just to be sure you have unique elements."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T15:37:31.423",
"Id": "495225",
"Score": "0",
"body": "@GrajdeanuAlex. The returned elements are guaranteed to be unique as long as the iterable (`range(1, 40)` here) itself has no duplicates."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T10:59:07.487",
"Id": "251536",
"ParentId": "251535",
"Score": "14"
}
},
{
"body": "<p>Code with this much indentation is never elegant, and it is very hard to maintain.</p>\n<p>There is a programming principle called the <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">Don't Repeat Yourself Principle</a> sometimes referred to as DRY code. If you find yourself repeating the same code multiple times it is better to encapsulate it in a function. If it is possible to loop through the code that can reduce repetition as well.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T12:50:33.433",
"Id": "495209",
"Score": "6",
"body": "I'm not sure how you'd do the DRY thing like that here. Rather sounds like you copied&pasted that paragraph from somewhere where that made more sense."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T12:23:56.530",
"Id": "251539",
"ParentId": "251535",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "251536",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T10:52:16.417",
"Id": "251535",
"Score": "12",
"Tags": [
"python"
],
"Title": "List lotto rows"
}
|
251535
|
<p>I have built a "mega menu" that is working, but I would appreciate some advice on how my javascript can be improved.</p>
<p><strong>Step 1</strong> is looping through the top level menu items and applying the correct megamenu class names where necessary:</p>
<pre><code>const megamenu = document.getElementById('megamenu');
let megamenuChildren = megamenu.children;
let megamenuChildrenArray = Array.from(megamenuChildren);
for (let i = 0; i < megamenuChildrenArray.length; i++) {
let sub = megamenuChildrenArray[i].children;
// if the nav li contains x1 children it is a regular link
// if the nav li contains x2 children it is a megamenu item and we add the classes
if (sub.length === 2) {
let subArray = Array.from(sub);
subArray[0].classList.add('megamenu-trigger-' + i);
subArray[1].classList.add('megamenu-sub-' + i);
}
}
</code></pre>
<p><strong>Step 2</strong> Earlier in my development I learned that we shouldn't add eventListener inside a loop! So instead I am adding an eventListener to the document to listen for all clicks.</p>
<p>There are only ever a maximum of x5 li's in the top level menu, so I am checking each one for a click and swapping the class <code>'dn'</code> (display: none;) for <code>'db'</code> (display: block;). I am also adding the class <code>'megamenu-sub-triggered'</code>:</p>
<pre><code>document.addEventListener('click', function(event) {
if (event.target.matches('.megamenu-trigger-0')) {
console.log('trigger 0 clicked!');
event.preventDefault();
let subZero = document.getElementsByClassName('megamenu-sub-0')[0];
subZero.classList.remove('dn');
subZero.classList.add('db', 'megamenu-sub-triggered');
}
if (event.target.matches('.megamenu-trigger-1')) {
console.log('trigger 1 clicked!');
event.preventDefault();
let subOne = document.getElementsByClassName('megamenu-sub-1')[0];
subOne.classList.remove('dn');
subOne.classList.add('db', 'megamenu-sub-triggered');
}
if (event.target.matches('.megamenu-trigger-2')) {
console.log('trigger 2 clicked!');
event.preventDefault();
let subTwo = document.getElementsByClassName('megamenu-sub-2')[0];
subTwo.classList.remove('dn');
subTwo.classList.add('db', 'megamenu-sub-triggered');
}
if (event.target.matches('.megamenu-trigger-3')) {
console.log('trigger 3 clicked!');
event.preventDefault();
let subThree = document.getElementsByClassName('megamenu-sub-3')[0];
subThree.classList.remove('dn');
subThree.classList.add('db', 'megamenu-sub-triggered');
}
if (event.target.matches('.megamenu-trigger-4')) {
console.log('trigger 4 clicked!');
event.preventDefault();
let subFour = document.getElementsByClassName('megamenu-sub-4')[0];
subFour.classList.remove('dn');
subFour.classList.add('db', 'megamenu-sub-triggered');
}
}
</code></pre>
<p><strong>Step 3</strong> Finally, <strong>inside the same document.addEventListener above</strong>, I am listening for clicks outside of the <code>'.megamenu-sub-triggered'</code> element, and checking each possible megamenu to see (a) if it exists, and (b) if it contains the triggered class.</p>
<p>If conditions (a) and (b) are met, I am putting the classes back to their original state:</p>
<pre><code>if (document.getElementsByClassName('megamenu-sub-triggered')) {
if (!event.target.closest('.megamenu-sub-triggered')) {
var subZero = document.getElementsByClassName('megamenu-sub-0')[0];
if (subZero && subZero.matches('.megamenu-sub-0.megamenu-sub-triggered')) {
subZero.classList.remove('db', 'megamenu-sub-triggered');
subZero.classList.add('dn');
}
var subOne = document.getElementsByClassName('megamenu-sub-1')[0];
if (subOne && subOne.matches('.megamenu-sub-1.megamenu-sub-triggered')) {
subOne.classList.remove('db', 'megamenu-sub-triggered');
subOne.classList.add('dn');
}
var subTwo = document.getElementsByClassName('megamenu-sub-2')[0];
if (subTwo && subTwo.matches('.megamenu-sub-2.megamenu-sub-triggered')) {
subTwo.classList.remove('db', 'megamenu-sub-triggered');
subTwo.classList.add('dn');
}
var subThree = document.getElementsByClassName('megamenu-sub-3')[0];
if (subThree && subThree.matches('.megamenu-sub-3.megamenu-sub-triggered')) {
subThree.classList.remove('db', 'megamenu-sub-triggered');
subThree.classList.add('dn');
}
var subFour = document.getElementsByClassName('megamenu-sub-4')[0];
if (subFour && subFour.matches('.megamenu-sub-4.megamenu-sub-triggered')) {
subFour.classList.remove('db', 'megamenu-sub-triggered');
subFour.classList.add('dn');
}
}
}
</code></pre>
<p>Any help improving this code, and my own javascript knowledge, is very much appreciated!</p>
<p>Many thanks</p>
|
[] |
[
{
"body": "<h3>Step 1</h3>\n<p><strong>Concise iteration and selectors</strong></p>\n<p><code>.children</code> returns an array-like collection of elements. While the collection isn't actually an array, it still has elements at numeric indicies and has a <code>.length</code>. So, there's no need to convert it into an actual array first if you're iterating over it with a <code>for (let i = 0; i < collection.length; ...)</code> loop. So, with:</p>\n<pre><code>let megamenuChildren = megamenu.children;\nlet megamenuChildrenArray = Array.from(megamenuChildren);\nfor (let i = 0; i < megamenuChildrenArray.length; i++) {\n</code></pre>\n<p>you can instead use:</p>\n<pre><code>let megamenuChildren = megamenu.children;\nfor (let i = 0; i < megamenuChildren.length; i++) {\n</code></pre>\n<p><em>But there's a better option</em>. Since you don't really care about the <em>index</em> being iterated over, you just care about the <em>elements</em> in the collection, how about iterating through only the elements, instead of the indicies? Use <code>for..of</code> instead:</p>\n<pre><code>for (const child of megamenuChildren) {\n</code></pre>\n<p><em>But there's a better option</em>. Rather than selecting the <code>#megamenu</code> element, and then using <code>.children</code> to get to its children, then iterating over the children, you can use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors\" rel=\"nofollow noreferrer\">selector string instead</a> to get to the children immediately:</p>\n<pre><code>for (const child of document.querySelectorAll('#megamenu > *')) {\n</code></pre>\n<p>The selector sting <code>#megamenu > *</code> means: select all children of elements with an ID of <code>megamenu</code>.</p>\n<p><em>But there's a better option</em>. You could add these classes to the HTML instead of through the JS, or you could not add these classes or anything like them at all - see below, at the bottom of Step 2.</p>\n<p><strong>Checking children length is weird</strong> Once the children are selected, doing this:</p>\n<pre><code>// if the nav li contains x1 children it is a regular link\n// if the nav li contains x2 children it is a megamenu item and we add the classes\n\nif (sub.length === 2) {\n</code></pre>\n<p>is pretty strange. I think it would be much more natural for the parent elements to distinguish <em>themselves</em> by whether they're a container for more items or just contain a plain link. Maybe use a class name of <code>subgroup</code> for such parents. Then, rather than checking the length of the children, you could just change the selector string above to:</p>\n<pre><code>for (const child of document.querySelectorAll('#megamenu > .subgroup')) {\n</code></pre>\n<p>in order to iterate over the subgroups.</p>\n<h3>Step 2</h3>\n<blockquote>\n<p>Earlier in my development I learned that we shouldn't add eventListener inside a loop!</p>\n</blockquote>\n<p><strong>Listeners in a loop are just fine</strong> as long as you use modern syntax, usually. There is only <em>one</em> situation where adding listeners in a loop will fundamentally fail, which is if you're using <code>var</code>, which has unintuitive function scope instead of block scope:</p>\n<pre><code>// Bad:\nfor (var i = 0; i < elms.length; i++) {\n var elm = elms[i];\n elm.addEventListener('click', () => {\n console.log(elm, 'clicked');\n });\n}\n</code></pre>\n<pre><code>// Fix:\nfor (let i = 0 // ...\n</code></pre>\n<p>One should never be using <code>var</code> in source code anyway, nowadays, due in part to problems like this. Always use <code>const</code> or <code>let</code> instead. (Prefer <code>const</code> when possible, since it indicates reassignment will not occur.)</p>\n<p>There is one situation in which adding listeners inside a loop can lead to difficult-to-manage code, which is if elements that need listeners are added <em>dynamically</em>. See <a href=\"https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements\">https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements</a>. In such a case, it's often more manageable to add a single listener to the parent instead of adding listeners to the children <em>on pageload</em> and adding listeners to each <em>dynamically created</em> child on creation.</p>\n<p>But your situation does not fall into either of the above 2 categories. There's nothing wrong with adding lots of listeners (except, maybe, if you have 1000+ of them, or something like that - that might have a performance impact, I'm not sure). If you can change your Step 2 code so that it adds listeners in a loop instead of the repetitive <code>if (event.target.matches('.megamenu-trigger-1')) {</code> blocks, feel free to do that. Or, you could continue on with your event delegation approach, but with some improvements:</p>\n<p><strong>Use querySelector to select a single element</strong> instead of <code>getElementsByClassName(..)[0]</code>. For example, you can replace these:</p>\n<pre><code>document.getElementsByClassName('megamenu-sub-1')[0]\n</code></pre>\n<p>with</p>\n<pre><code>document.querySelector('.megamenu-sub-1')\n</code></pre>\n<p>Another benefit of <code>querySelector</code> is that it accepts a selector string, and selector strings are far more flexible than plain classes are tag names.</p>\n<p>Or, rather than all of these classes, you could <strong>navigate from the clicked element instead</strong>. You could remove Step 1's code completely, only keeping the <code>subgroup</code> class name for menu parents. Then, on click, check to see if the target is the first child of a <code>.subgroup</code> - if it is, this is the equivalent of the <code>trigger</code> being clicked, so you can dynamically navigate to its next sibling and change its class. Replace <em>all</em> of Step 2's code with the following:</p>\n<pre><code>document.addEventListener('click', (e) => {\n const { target } = e;\n if (!target.matches('.subgroup > :first-child')) {\n return;\n }\n // A trigger element was clicked, so:\n e.preventDefault();\n const submenu = target.nextElementSibling;\n submenu.classList.remove('dn');\n submenu.classList.add('db', 'megamenu-sub-triggered');\n});\n</code></pre>\n<p>The most important part is using <code>.nextElementSibling</code> to get to the clicked element's next sibling, instead of using all those classes.</p>\n<h3>Step 3</h3>\n<p><strong>Collections are truthy</strong>. You have <code>if (document.getElementsByClassName('megamenu-sub-triggered')) {</code>, but <code>getElementsByClassName</code> returns a collection, and not a possibly falsey value, so the <code>if</code> check is redundant. If you want to check if any elements match the class, check the collection's <code>length >= 1</code> instead. Or, even better...</p>\n<p><strong>Iteration is overkill.</strong> Instead, you can select the currently opened submenu element which has the <code>db</code> class with a single selector string. If it exists, and if the clicked element was not inside it, then reset its classes:</p>\n<pre><code>document.addEventListener('click', (event) => {\n const openSubmenu = document.querySelector('megamenu-sub-triggered');\n if (openSubmenu && !openSubmenu.contains(event.target)) {\n openSubmenu.classList.remove('db', 'megamenu-sub-triggered');\n openSubmenu.classList.add('dn');\n }\n});\n</code></pre>\n<p><strong>Multiple classes?</strong> It's odd to have 3 separate classes that get added or removed together. It would make more sense to change your CSS rules so that you can have just a <em>single</em> class instead, that gets toggled on or off. For example, you could have a <code>submenu-open</code> class, and then do:</p>\n<pre><code>submenu.classList.add('submenu-open');\n</code></pre>\n<p>or</p>\n<pre><code>openSubmenu.classList.remove('submenu-open');\n</code></pre>\n<p>without the classes of <code>db</code>, <code>megamenu-sub-triggered</code>, or <code>dn</code> at all.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T19:05:22.980",
"Id": "251561",
"ParentId": "251541",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "251561",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T13:56:34.953",
"Id": "251541",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "vanilla js eventListener on navigation"
}
|
251541
|
<p>I have a python flask app that waits for requests from user app and than spawns a process with job based on the request it receives.
It keeps the status and queue of the jobs in memory.
The requests to this service will always have this pattern:</p>
<ol>
<li>Submit job</li>
<li>(optional) upload additional data</li>
<li>check every 5 seconds if the job is finished</li>
<li>download results</li>
<li>delete job data</li>
</ol>
<p>I have simply created lists and dicts for the queue, running and finished jobs.
The logic is that first submit request is called with information if it needs to wait for additional data or not. If no data is needed, it will put it in the queue or spawn a process if there is any CPU free.</p>
<p>If additional data was needed, it will be put into separate queue and once the request with additional data is completed, it will spawn the job (or put it into queue).
Since every user app that has submitted a submit request will check every few seconds if their job is done, I have used this to check if any job is done and move it to finished and spawn another job from the queue.</p>
<p>Once the check request returns that it is done, the user app will download the results and than call for termination of the job data.</p>
<p>What surprised me, was that the flask app would spawn together with each thread if it is not protected by <code>if __name__ == '__main__':</code> even when the spawned job was in different file and is not referencing anything from the flask app file.</p>
<p>Since I'm relatively new to flask and multiprocessing, is there anything else I should be worrying about?</p>
<p>This is the code:</p>
<pre><code>import os
import uuid
from os.path import isfile, isdir
from flask import Flask, request, Response, send_from_directory
from multiprocessing import Process
from werkzeug.utils import secure_filename
from helpers import str2bool
from temporary_test_task import run_task
if __name__ == '__main__':
app = Flask(__name__)
running = {}
finished = []
queue = []
waiting_for_data = {}
queue_list = set()
@app.route('/status', methods=['GET', 'POST'])
def status():
return "OK", 200
def finish_job(job_id):
finished.append(job_id)
last = running.pop(job_id)
last.close()
if len(queue) > 0:
next_job = queue.pop()
queue_list.remove(next_job[0])
start_job(next_job)
def start_job(job=None):
if job is None:
job = queue.pop()
queue_list.remove(job[0])
task_cb = Process(target=run_task, args=(job[0], job[1]))
task_cb.start()
print('started thread')
running[job[0]] = task_cb
def remove_finished():
for j in list(running.keys()):
if not running[j].is_alive():
finish_job(j)
@app.route("/Simulation", methods=['POST'])
def submit_job():
# create id
job_id = str(uuid.uuid4())
job_data = request.data.decode('utf-8')
# check if waiting for data
if str2bool(request.headers.get('UseMlData', False)):
waiting_for_data[str(job_id)] = job_data
status = 'WAITING_FOR_DATA'
else:
status = submit_job_local(job_id, job_data)
return status, 200
def submit_job_local(job_id, job_data):
# check not too many processing jobs
if len(running) >= config.threads:
queue.append((job_id, job_data))
queue_list.add(job_id)
status = 'QUEUED'
else:
start_job((job_id, job_data))
status = 'RUNNING'
return status
@app.route("/Simulation/<uuid:job_id>", methods=['GET'])
def check_status(job_id: uuid):
job_id = str(job_id)
remove_finished()
if job_id in running:
r = 'RUNNING'
elif job_id in queue_list:
r = 'QUEUED'
elif job_id in finished:
r = 'COMPLETED'
else:
r = 'FAILED'
return r, 200
@app.route('/Simulation/<uuid:job_id>/UploadData', methods=['POST'])
def upload_file(job_id):
job_id = str(job_id)
if job_id not in waiting_for_data:
return 'uuid not in waiting for data mode', 400
number_of_files = 0
base_path = os.path.join('uploadedData', job_id)
if not os.path.exists(base_path):
os.makedirs(base_path)
for file in request.files.values():
if file.filename == '':
return 'no file name', 400
if file:
filename = secure_filename(file.filename)
path = os.path.join(base_path, filename)
file.save(path)
number_of_files += 1
submit_job_local(job_id, waiting_for_data.pop(job_id))
return str(number_of_files) + ' files uploaded', 200
@app.route('/Simulation/<uuid:job_id>/Results', methods=['GET'])
def download_results(job_id):
if str(job_id) not in finished:
return 'job id not found', 404
base_path = os.path.join('results', str(job_id))
file_path = os.path.join(base_path, 'result.xml')
if not isfile(file_path):
return 'file not found', 404
return send_from_directory(base_path, 'result.xml')
app.run()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T09:36:07.700",
"Id": "495344",
"Score": "0",
"body": "Any reason for not using something like celery to do the processing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T11:52:23.943",
"Id": "495536",
"Score": "0",
"body": "I have never worked with that and from the documentation I have read it looked way too complicated for such a simple task. I also wanted to keep it as simple as possible as it must be maintainable by people not so proficient in python."
}
] |
[
{
"body": "<h2>Main guards</h2>\n<p>You have a kind of anti-guard for <code>__main__</code>. The purpose of such a guard is to define - but not run - symbols like constants, classes and functions if someone wants to import them. Due to your additional indentation, you've actually prevented this altogether.</p>\n<p>To fix this, move your <code>if __name__ == '__main__':</code> block to the bottom of your file and de-indent everything else.</p>\n<h2>Globals</h2>\n<p>Due to the way that Flask declarations work, <code>app</code> should stay as a global, as it is now. <code>running</code>, etc. should not be.</p>\n<p>If you make <code>finish_job</code> (for instance) a method on a class that has members for <code>finished</code>, <code>running</code>, etc., that's one relatively easy way to get to something that's more easily testable, modular and re-entrant.</p>\n<h2>RESTful responses</h2>\n<p>About</p>\n<pre><code>@app.route('/status', methods=['GET', 'POST'])\ndef status():\n return "OK", 200\n</code></pre>\n<p>it's unusual to return 200 for a <code>POST</code>. Why does <code>status</code> accept <code>POST</code> at all? <code>POST</code> usually implies the creation of a new resource.</p>\n<p>For <code>submit_job</code>, it's good that it accepts <code>POST</code>, but it still shouldn't return <code>200 OK</code> - it should probably return <code>201 CREATED</code>.</p>\n<h2>String interpolation</h2>\n<pre><code>str(number_of_files) + ' files uploaded'\n</code></pre>\n<p>can be</p>\n<pre><code>f'{number_of_files} files uploaded'\n</code></pre>\n<h2>Is it your fault or mine?</h2>\n<p>This:</p>\n<pre><code> if str(job_id) not in finished:\n return 'job id not found', 404\n</code></pre>\n<p>makes sense. The job is not in the list of finished jobs, so kick out the request with a 404. This:</p>\n<pre><code> if not isfile(file_path):\n return 'file not found', 404\n</code></pre>\n<p>is a little more dubious. If the job is in the list of finished jobs, but is not on the filesystem, is the error really the client's fault? I would sooner guess that this is an erroneous server state, i.e. a 500.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-06T19:43:21.677",
"Id": "251730",
"ParentId": "251542",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T14:12:35.593",
"Id": "251542",
"Score": "3",
"Tags": [
"python",
"multithreading",
"flask",
"multiprocessing"
],
"Title": "python flask spawn jobs with multiprocessing"
}
|
251542
|
<p>This is my first attempt in converting a pure javascript to typescript. Any comment?</p>
<pre><code>const apiUrl = 'https://localhost:123'
export function webApiUrl() {
return apiUrl;
}
export function downloadPdf(id : number, fileName: string) {
const spinner: HTMLElement = document.getElementById('spinner') as HTMLImageElement
spinner.style.display = 'block'
fetch(`${apiUrl}/api/file/download?fileDocumentId=${id}`).then(resp => resp.arrayBuffer()).then(resp => {
// set the blog type to final pdf
const file = new Blob([resp], { type: 'application/pdf' });
// process to auto download it
const fileURL: string = URL.createObjectURL(file);
const link: HTMLAnchorElement = document.createElement('a');
link.href = fileURL;
link.download = fileName;
link.click();
spinner.style.display = 'none'
});
}
</code></pre>
<p>I think the only code I can't figure out how to convert over is the blob type.</p>
|
[] |
[
{
"body": "<p><strong>Use explicit type annotation only when necessary</strong> In the vast majority of cases, TypeScript can infer the type of an expression automatically, without you having to note it manually. It's probably better and easier to let TS take care of it - it makes for less code to read and write. If you're ever not sure what sort of type an expression is, use an IDE which can tell you (like VSCode, which works really well with TypeScript - just hover over an expression and it'll tell you what type TypeScript has inferred for it).</p>\n<p>For example:</p>\n<pre><code>const fileURL: string = URL.createObjectURL(file);\nconst link: HTMLAnchorElement = document.createElement('a');\n</code></pre>\n<p>can be</p>\n<pre><code>const fileURL = URL.createObjectURL(file);\nconst link = document.createElement('a');\n</code></pre>\n<p>IMO, TypeScript shines most when it looks almost identical to JavaScript, with the added bonus of warning you when you're doing something that's type-unsafe.</p>\n<blockquote>\n<p>I think the only code I can't figure out how to convert over is the blob type.</p>\n</blockquote>\n<p>Its type is a Blob, which you can see in VSCode (or any other good TS-aware IDE):</p>\n<p><a href=\"https://i.stack.imgur.com/lkQtr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lkQtr.png\" alt=\"enter image description here\" /></a></p>\n<p>But, as said, better to let TS infer it automatically; no need for <code>const file: Blob =</code>.</p>\n<p><strong>Prefer generics over type assertion</strong> <a href=\"https://www.typescriptlang.org/docs/handbook/generics.html\" rel=\"nofollow noreferrer\">Generics</a> are the most elegant way to denote the type of a particular expression, when the type isn't set in stone by the function signature. The <code>as</code> keyword, in contrast, is less type-safe: <code>as</code> tells TypeScript "I know exactly what I'm doing, ignore whatever type this value was determined to be previously and assume that it's of THIS type instead".</p>\n<p>For example, the following code does not throw a TS error, despite the <code>as</code> clearly being nonsensical:</p>\n<pre><code>const foo = {\n bar: 'bar'\n} as {\n fn?: () => Promise<Array<string>>\n};\n</code></pre>\n<p><code>as</code> isn't as bad as <code>any</code>, but they both should be avoided when possible.</p>\n<p>In your case, <code>getElementById</code> is not generic, unfortunately, but <code>querySelector</code> is. You can change:</p>\n<pre><code>const spinner: HTMLElement = document.getElementById('spinner') as HTMLImageElement\n</code></pre>\n<p>to</p>\n<pre><code>const spinner = document.querySelector<HTMLElement>('#spinner')!;\n// you could also use <HTMLImageElement> if you needed image element specific types\n</code></pre>\n<p>Generics are essentially <em>type arguments</em> that come in <code><></code> brackets, before the <em>expression arguments</em> inside the parentheses of the function call. Above, <code><HTMLImageElement></code> tells <code>querySelector</code>: "This selector, if it matches, will match an HTMLImageElement." This is preferable to <code>as</code> because only the types that extend Element can be passed to <code>querySelector</code>.</p>\n<p><strong>Function name</strong> Functions should describe <em>actions</em>, or what they do. <code>webApiUrl</code> might be more precisely named <code>getApiUrl</code>. (Or, just export the URL string alone: <code>export const apiUrl = '...';</code>, there doesn't seem to be any need for the function)</p>\n<p><strong>Error handling</strong> If the <code>fetch</code> fails, no indication is given to the user or to other parts of the program. Whenever you have a Promise, you should almost always make sure that possible errors inside it get handled. TSLint rule: <a href=\"https://palantir.github.io/tslint/rules/no-floating-promises/\" rel=\"nofollow noreferrer\"><code>no-floating-promises</code></a>.</p>\n<p>While you could add a <code>.catch</code> onto the <code>fetch</code> Promise chain:</p>\n<pre><code> spinner.style.display = 'none'\n})\n.catch((error) => {\n // handle errors\n});\n</code></pre>\n<p>It might be better to let the <em>caller</em> handle errors as needed. Change:</p>\n<pre><code>fetch(`${apiUrl}/api/...\n</code></pre>\n<p>to</p>\n<pre><code>return fetch(`${apiUrl}/api/...\n</code></pre>\n<p>so that each caller can do <code>downloadPdf(id, fileName).catch(handleErrors)</code> individually.</p>\n<p><strong>Semicolons</strong> Some of your lines are missing semicolons. This is stylistically inconsistent and can lead to <a href=\"https://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi\">odd bugs</a> if you forget a semicolon where it's required. Add the missing semicolons, and consider using <a href=\"https://eslint.org/docs/rules/semi\" rel=\"nofollow noreferrer\">a linter which warns you</a> when they're missing. (The rationale behind using a linter is similar to the rationale behind using TypeScript - turn annoying, hard-to-encounter, sometimes-hard-to-debug runtime errors into trivially fixable compile-time errors.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T02:19:05.777",
"Id": "495303",
"Score": "0",
"body": "Thanks a lot for the comprehensive code review. May I know what is the purpose of the last symbol `!` in `const spinner = document.querySelector<HTMLElement>('#spinner')!;`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T02:21:45.783",
"Id": "495304",
"Score": "1",
"body": "That tells TS that the expression definitely isn't null nor undefined."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-19T19:48:12.367",
"Id": "497235",
"Score": "0",
"body": "It's not a good practice using `!`, you can't be sure that the spinner element always exists in the HTML (what if something else changed HTML?). So you should always check if it is defined. If you wish to have a nice TS code, you can use Optional Chaining."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-19T19:53:50.703",
"Id": "497238",
"Score": "0",
"body": "@KiraLT If the script writer has every reason to believe that the element absolutely should exist when the script runs, using `!` should be fine. If there's really a possibility that the element wouldn't exist, then yes, you'd want to check that it does first (but there's no indication that this is one of those situations). Ideally, an even better approach would be a framework like React that tightly couples the DOM elements with the state of the application, so that the existence of one without the other is inconceivable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-19T20:02:51.487",
"Id": "497242",
"Score": "0",
"body": "From my experience, I can say that even if you think that at the moment it should always exist, the future can prove you wrong and for a simple mistake, your whole app will crash instead of just a loader. In very rare cases maybe you can use it, but it would be best to always handle all edge cases, especially if it won't cause inconvenience. As for react, life is not always is so nice, that you can choose which technology you can use."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T16:39:58.250",
"Id": "251551",
"ParentId": "251547",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "251551",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T15:08:53.403",
"Id": "251547",
"Score": "3",
"Tags": [
"typescript"
],
"Title": "Conversion to typescript from javascript"
}
|
251547
|
<p>Changed Program based on suggestions. New Code: <a href="https://codereview.stackexchange.com/questions/251558/job-scheduling-algorithm-2">Job Scheduling Algorithm 2</a></p>
<p>I have created an algorithm for job scheduling. <br>The algorithm goes through sub-lists in order with two nested for loops. Inside the nested for loops, the algorithm counts how many tasks for each job are completed. If this is equal to the number of tasks, then the profit for that job is added to the total profit.</p>
<p>Item start to Item end is an item using that machine from start to end. Machine start to Machine end is when the machines can process the items. A single task is a single machine doing items. The number required for a job is tasks to be completed while done tasks are tasks that will finish in the schedule. If those two counts are equal then the job is done, and profit is added to the profit var.</p>
<p>Here is the code</p>
<pre><code>def output_profit(profit:int)->None:
print("profit: " + str(profit), end = "\n")
def output_subset(subset:[str])->None:
for item in subset:
print(str(item), end = " ")
def main():
items = ["a", "b"]
items_starts = [0, 3]
items_ends = [2, 4]
#total number of tasks that are needed for job i
tasks_to_complete = [1,1]
#tasks that are done for job i
done_tasks = [0, 0]
machine_starts = [0, 0]
machine_ends = [1, 7]
profits_for_job = [10, 12]
profit = 0
for row in range(0, len(items)):
for col in range(0, len(items) + 1):
subset = items[row:col]
for job_index in range(0, len(subset)):
if items_starts[job_index] >= machine_starts[job_index]:
if items_ends[job_index] <= machine_ends[job_index]:
done_tasks[job_index] = done_tasks[job_index] + 1
profit = 0
for job_index in range(0, len(subset)):
if tasks_to_complete[job_index] == done_tasks[job_index]:
profit = profit + profits_for_job[job_index]
output_profit(profit)
output_subset(subset)
if __name__ == "__main__":
main()
</code></pre>
<p>I am looking for ways to improve the code readability and improve the algorithm's efficiency.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T16:58:26.080",
"Id": "495234",
"Score": "0",
"body": "What do `item_starts` and `item_ends` do? I'd also appreciate if you thoroughly explained the purpose of all variables in `main()`, since a first glance it's very difficult to identify their purpose :)"
}
] |
[
{
"body": "<h2>Functions</h2>\n<p>It's good that you're thinking about how to capture code in functions, but you haven't particularly chosen the right code to move into functions.</p>\n<p>This is somewhat trivial:</p>\n<pre><code>print("profit: " + str(profit), end = "\\n")\n</code></pre>\n<p>and does not deserve its own function; simply write</p>\n<pre><code>print(f'profit: {profit}')\n</code></pre>\n<p>at the outer level. The same applies for <code>output_subset</code>, which does not need a loop and can be</p>\n<pre><code> print(' '.join(item for item in subset))\n</code></pre>\n<p>Instead, something that <em>does</em> deserve to be in a separate function is your set of loops starting at <code>for row</code>, which can be translated into a generator; also note that 0 is the default start for <code>range</code>:</p>\n<pre><code>ProfitPair = Tuple[\n int,\n List[str],\n]\n\n\ndef get_profits( ... variables needed for iteration ...) -> Iterable[ProfitPair]:\n for row in range(len(items)):\n for col in range(len(items) + 1):\n subset = items[row:col]\n for job_index in range(len(subset)):\n if items_starts[job_index] >= machine_starts[job_index]:\n if items_ends[job_index] <= machine_ends[job_index]:\n done_tasks[job_index] = done_tasks[job_index] + 1\n profit = 0 \n for job_index in range(len(subset)):\n if tasks_to_complete[job_index] == done_tasks[job_index]:\n profit += profits_for_job[job_index]\n \n yield (profit, subset)\n</code></pre>\n<h2>Type hints</h2>\n<p>It's good that you've tried this out. <code>subset:[str]</code> should be <code>subset: List[str]</code>.</p>\n<h2>Indexing</h2>\n<pre><code>for row in range(0, len(items)):\n for col in range(0, len(items) + 1):\n subset = items[row:col]\n</code></pre>\n<p>seems strange to me. Based on your initialization, <code>items</code> is not a two-dimensional (nested) list - unless you count string indexing as the second dimension. <code>row</code> and <code>col</code> are thus somewhat misnamed, and are basically <code>start</code> and <code>end</code>.</p>\n<h2>In-place addition</h2>\n<pre><code>done_tasks[job_index] = done_tasks[job_index] + 1\n</code></pre>\n<p>should be</p>\n<pre><code>done_tasks[job_index] += 1\n</code></pre>\n<h2>Summation with generators</h2>\n<pre><code> profit = 0 \n for job_index in range(0, len(subset)):\n if tasks_to_complete[job_index] == done_tasks[job_index]:\n profit = profit + profits_for_job[job_index]\n \n</code></pre>\n<p>can be</p>\n<pre><code>profit = sum(\n profits_for_job[job_index]\n for job_index in range(len(subset))\n if tasks_to_complete[job_index] == done_tasks[job_index]\n)\n</code></pre>\n<p>This raises another point, though. Consider "rotating" your data structure so that, instead of multiple sequences where the same index in each correspond to a description of the same thing, e.g.</p>\n<pre><code>profits_for_job[job_index]\ntasks_to_complete[job_index]\ndone_tasks[job_index]\n</code></pre>\n<p>instead have a sequence of <code>@dataclass</code>es with attributes:</p>\n<pre><code>job[job_index].profits\njob[job_index].tasks_to_complete\njob[job_index].tasks_done\n</code></pre>\n<h2>Predicate combination</h2>\n<pre><code> if items_starts[job_index] >= machine_starts[job_index]:\n if items_ends[job_index] <= machine_ends[job_index]:\n done_tasks[job_index] = done_tasks[job_index] + 1\n</code></pre>\n<p>can just be</p>\n<pre><code>if (\n items_starts[job_index] >= machine_starts[job_index] and\n items_ends[job_index] <= machine_ends[job_index]\n):\n done_tasks[job_index] += 1\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T16:49:10.977",
"Id": "495231",
"Score": "0",
"body": "The indexing is based on getting a ordered list into subsets of the list."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T16:51:50.713",
"Id": "495233",
"Score": "0",
"body": "That's fine; I still think the variable names could be changed to be less misleading."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T16:59:34.417",
"Id": "495235",
"Score": "0",
"body": "I'm in the process of writing a review, I see this, and I realize almost all of my points are mentioned here "
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T16:45:46.653",
"Id": "251552",
"ParentId": "251549",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "251552",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T15:49:31.323",
"Id": "251549",
"Score": "4",
"Tags": [
"performance",
"algorithm",
"python-3.x"
],
"Title": "Job Scheduling Algorithm"
}
|
251549
|
<p>I want to create two classes, one for attributes and one for functional behaviors. The point of the attributes class was to hold all of the attributes along with property methods (setters/getters), and I wanted to split the classes up this way so that everything related to the attributes would not fill up the entire other class.</p>
<p>Due to the way python handles <a href="https://stackoverflow.com/q/4841782">mutable default arguments</a>, I have to handle the attributes using <code>None</code> for default arguments, but I have a very large number of parameters. This has caused the code to become unnecessarily long when passing arguments around on the initialization:</p>
<pre class="lang-py prettyprint-override"><code>class Attributes:
def __init__(self,
arg1,
arg2,
arg3,
arg4,
arg5):
self.arg1 = default_arg1 if arg1 is None else arg1
self.arg2 = default_arg2 if arg2 is None else arg2
self.arg3 = default_arg3 if arg3 is None else arg3
self.arg4 = default_arg4 if arg4 is None else arg4
self.arg5 = default_arg5 if arg5 is None else arg5
# attribute methods like getters and setters
class Functionality(Attributes):
def __init__(self,
arg1 = None,
arg2 = None,
arg3 = None,
arg4 = None,
arg5 = None):
super(Functionality, self).__init__(
arg1,
arg2,
arg3,
arg4,
arg5
)
# Methods that give functionality to the class
</code></pre>
<p>I want to be able to use this class as follows:</p>
<pre class="lang-py prettyprint-override"><code>example_obj = Functionality(
arg1 = example_arg1,
arg4 = example_arg4
)
</code></pre>
<p>Is there any cleaner way to do this? I want to add more attributes (more than 20 attributes instead of 5), but the above code involves writing basically the same thing way too many times.</p>
|
[] |
[
{
"body": "<p>By passing all of the arguments inside of a dictionary one avoids a lengthy <code>__init__</code> in <code>Functionality</code> and also allows setting all default arguments in 3 lines without causing issues with mutable arguments.</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Attributes:\n def __init__(self, attributes):\n \n default_attributes = {\n 'arg1' : default_arg1,\n 'arg2' : default_arg2,\n 'arg3' : default_arg3,\n 'arg4' : default_arg4,\n 'arg5' : default_arg5\n }\n \n for attribute in default_attributes.keys():\n if attribute not in attributes:\n attributes[attribute] = default_attributes[attribute]\n \n arg1 = attributes['arg1']\n arg2 = attributes['arg2']\n arg3 = attributes['arg3']\n arg4 = attributes['arg4']\n arg5 = attributes['arg5']\n</code></pre>\n<pre class=\"lang-py prettyprint-override\"><code>class Functionality(Attributes):\n def __init__(self, attributes = None):\n super(Functionality, self).__init__({} if attributes is None else attributes)\n</code></pre>\n<p>The only difference in usage is it now has to be used with a dictionary.</p>\n<pre class=\"lang-py prettyprint-override\"><code>example_obj = Functionality({\n 'arg1' : example_arg1,\n 'arg2' : example_arg2\n})\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T18:27:50.583",
"Id": "251559",
"ParentId": "251553",
"Score": "0"
}
},
{
"body": "<p>I'm going to address your existing code in a manner that generally goes from most minimal to most significant changes. I'd strongly recommend actually using the solution at the very bottom of this post; the minimal changes are more useful:</p>\n<ol>\n<li>From a historical (pre-<code>dataclasses</code>) perspective</li>\n<li>For understanding how classes and inheritance work</li>\n</ol>\n<p>but there's no reason to torture yourself hand-writing all of this when <code>dataclasses</code> will do the work for you.</p>\n<h2>Delegating to defaults of super class</h2>\n<p>When you're inheriting <code>__init__</code> from another class, you typically <em>don't</em> want to reproduce their parameters explicitly; it creates too much confusion and too much interdependency (making more opportunities for code to get out of sync). There are two standard solutions here:</p>\n<h3>Option 1: Explicitly delegate via <code>**kwargs</code></h3>\n<p>When <code>Functionality</code> doesn't make direct use of any parameter, don't accept it by name. Just accept <code>**kwargs</code> (when you're talking about this many defaulted parameters, no one should be passing arguments positionally anyway; it's a nightmare for readability/maintainability) and pass it along. So <code>Functionality</code> would look like:</p>\n<pre><code>class Functionality(Attributes):\n def __init__(self, **kwargs):\n # Other stuff required for initialization\n super().__init__(**kwargs) # Python 3.x doesn't require you to pass args to super in most cases\n # Other stuff required for initialization\n\n # Methods that give functionality to the class\n</code></pre>\n<h3>Option 2: Inherit <code>__init__</code> implicitly</h3>\n<p>In this case, it might be even simpler though; the <code>__init__</code> of <code>Functionality</code> doesn't do anything beyond delegate to <code>Attributes</code>. If your real code is the same (nothing but a <code>super().__init__</code> call), you'd just omit the definition of <code>__init__</code> on <code>Functionality</code> and let it inherit <code>Attributes</code>'s <code>__init__</code> directly.</p>\n<pre><code>class Functionality(Attributes):\n # No __init__ defined at all; uses Attributes.__init__ automatically\n\n # Methods that give functionality to the class\n</code></pre>\n<p>Either way, you're no longer using separate defaults for each class.</p>\n<p>Note: If the parent class must <em>not</em> accept default arguments, but the child class should, see the end of this answer for <strong>Preferred solution (especially if the child must not have defaults, and the parent class should): <code>dataclasses</code> everywhere</strong> (not described here since it relies on techniques for solving your mutable defaults problem, which I haven't gotten to yet).</p>\n<hr />\n<h2>Avoid problems with mutable defaults</h2>\n<p>There are two simple solutions for avoiding the problems with mutable defaults.</p>\n<h3>Option 1: <a href=\"https://docs.python.org/3/library/copy.html#copy.deepcopy\" rel=\"noreferrer\">Deep copy</a> unconditionally</h3>\n<p>For the defaulted class itself, go ahead and use mutable arguments as defaults, but the safe way, making deep copies. This is often safer even when not passed as defaults, since without copying, you'd be aliasing values from the caller, and changes made by either you or the caller would affect the other.</p>\n<p>Adding explicit mutable defaults, you end up with:</p>\n<pre><code>from copy import deepcopy\n\nclass Attributes:\n def __init__(self, arg1=[], arg2={}, arg3=set(), arg4=MyMutable(), arg5=OtherMutable()):\n self.arg1 = deepcopy(arg1)\n self.arg2 = deepcopy(arg2)\n self.arg3 = deepcopy(arg3)\n self.arg4 = deepcopy(arg4)\n self.arg5 = deepcopy(arg5)\n\n # attribute methods like getters and setters\n</code></pre>\n<h3>Option 2: <a href=\"https://docs.python.org/3/library/dataclasses.html\" rel=\"noreferrer\">Let <code>dataclasses</code> do your work for you</a></h3>\n<p>As an alternative to hand-writing all of <code>Attributes</code>, I'd suggest making it a <code>dataclass</code>, which means you don't need to repeat the names, and allows you to <a href=\"https://docs.python.org/3/library/dataclasses.html#dataclasses.field\" rel=\"noreferrer\">define <code>default_factory</code>s for each <code>field</code></a> to generate default values on demand. That would allow you to write a simpler <code>Attributes</code> (with far less name repetition) matching what I wrote above like so:</p>\n<pre><code>from dataclasses import dataclass, field\n\n@dataclass\nclass Attributes:\n arg1: list = field(default_factory=list)\n arg2: dict = field(default_factory=dict)\n arg3: set = field(default_factory=set)\n arg4: MyMutable = field(default_factory=MyMutable)\n arg5: OtherMutable = field(default_factory=OtherMutable)\n\n # attribute methods like getters and setters\n</code></pre>\n<p>and it will generate <code>__init__</code> (as well as <code>__repr__</code> and <code>__eq__</code> for good measure; you can turn them off, or other features on, by parameterizing the <code>@dataclass</code> decorator) for you, including automatically calling your <code>default_factory</code> to initialize the field if and only if the caller did not provide the parameter.</p>\n<p>Note: Unlike the other solution, this <em>doesn't</em> ensure caller-provided arguments are copied, so the risk of aliasing would remain. You could always <a href=\"https://docs.python.org/3/library/dataclasses.html#post-init-processing\" rel=\"noreferrer\">define a <code>__post_init__</code></a> to copy any fields you think this is likely to be a problem for.</p>\n<p>Side-note: For my example, I just annotated the types as <code>list</code>, <code>dict</code>, and <code>set</code>; to annotate properly, you'd usually the <code>typing</code> classes (<code>List</code>, <code>Dict</code>, <code>Set</code>) and annotate with the types the containers are expected to hold, e.g. <code>arg1: List[int] = field(default_factory=list)</code> if <code>arg1</code> is expected to be a <code>list</code> of <code>int</code>s.</p>\n<h2>Preferred solution (especially if the child must not have defaults, and the parent class should): <code>dataclasses</code> everywhere</h2>\n<p>In your example, <code>Attributes()</code> fails for lack of arguments, while <code>Functionality()</code> does not (substituting defaults),</p>\n<p><code>dataclasses</code> still cover that case adequately. You'd define both parent and child as dataclasses, but not provide defaults for the fields on the parent:</p>\n<pre><code>from dataclasses import dataclass, field\n\n@dataclass\nclass Attributes:\n arg1: list\n arg2: dict\n arg3: set\n arg4: MyMutable\n arg5: OtherMutable\n\n # Optionally define __post_init__ to modify arguments, perform other work\n\n # attribute methods like getters and setters\n\n@dataclass\nclass Functionality(Attributes):\n arg1: list = field(default_factory=list)\n arg2: dict = field(default_factory=dict)\n arg3: set = field(default_factory=set)\n arg4: MyMutable = field(default_factory=MyMutable)\n arg5: OtherMutable = field(default_factory=OtherMutable)\n\n # Optionally define __post_init__ to modify arguments, perform other work\n\n # Methods that give functionality to the class\n</code></pre>\n<p>Since no defaults are set on <code>Attributes</code>, direct use of <code>Attributes</code> will require you all arguments to be provided. But <code>dataclasses</code> are helpful again here; the fields of a child class of a dataclass are:</p>\n<ol>\n<li>All of the fields of the parent(s)</li>\n<li>Plus all of the fields of the child</li>\n<li>When a given field is defined in both, the child's definition wins</li>\n</ol>\n<p>So we can provide <code>default_factory</code>s solely on the child (and get defaulting behavior), but not on the parent (so it never defaults).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T19:44:38.940",
"Id": "495247",
"Score": "1",
"body": "Works wonderfully! Will have to try looking more into dataclasses but for now using everything else suffices for me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T20:08:19.610",
"Id": "495251",
"Score": "0",
"body": "@SimplyBeautifulArt: Glad it helps. `dataclasses` is one of those things where, technically, everything it does could be written by hand (by definition; the module is written in Python), but it would be a royal pain to handle all the corner cases (e.g. your scenario where `Attributes` lacks default arguments, while `Functionality` takes mutable default arguments). What would otherwise be substantial changes often just means flipping a flag (e.g. if the class should be immutable/hashable, you just use `@dataclass(frozen=True)` and it generates `__hash__` and protects against instance mutation)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T20:15:39.040",
"Id": "495254",
"Score": "0",
"body": "I see. Good to know if I ever want a more general use of a class for handling data."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T18:28:00.273",
"Id": "251560",
"ParentId": "251553",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "251560",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T17:00:58.297",
"Id": "251553",
"Score": "7",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"template",
"classes"
],
"Title": "Cleanly passing in a large number of mutable parameters through a python class"
}
|
251553
|
<p>I'm posting a solution for LeetCode's "Count Substrings That Differ by One Character". If you'd like to review, please do. Thank you!</p>
<h3><a href="https://leetcode.com/problems/count-substrings-that-differ-by-one-character/" rel="nofollow noreferrer">Problem</a></h3>
<blockquote>
<p>Given two strings s and t, find the number of ways you can choose a
non-empty substring of s and replace a single character by a different
character such that the resulting substring is a substring of t. In
other words, find the number of substrings in s that differ from some
substring in t by exactly one character.</p>
<p>For example, the underlined substrings in "<a href="http:///" rel="nofollow noreferrer">compute</a>r" and "<a href="http:///" rel="nofollow noreferrer">computa</a>tion"
only differ by the 'e'/'a', so this is a valid way.</p>
<p>Return the number of substrings that satisfy the condition above.</p>
<p>A substring is a contiguous sequence of characters within a string.</p>
</blockquote>
<h3>Example 1:</h3>
<p><a href="https://i.stack.imgur.com/3PUQN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3PUQN.png" alt="enter image description here" /></a></p>
<h3>Example 2:</h3>
<p><a href="https://i.stack.imgur.com/S5MSv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/S5MSv.png" alt="enter image description here" /></a></p>
<h3>Constraints:</h3>
<ul>
<li>1 <= s.length, t.length <= 100</li>
<li>s and t consist of lowercase English letters only.</li>
</ul>
<h3>Code</h3>
<pre><code>#include <stdio.h>
#include <string.h>
static const size_t getCounts(
const char *source,
const char *target,
size_t s_index,
size_t t_index
) {
size_t counter = 0;
size_t prev = 0;
size_t curr = 0;
while (s_index < strlen(source) && t_index < strlen(target)) {
++curr;
if (source[s_index] != target[t_index]) {
prev = curr;
curr = 0;
}
counter += prev;
++s_index;
++t_index;
}
return counter;
}
static const int countSubstrings(
const char *source,
const char *target
) {
size_t counters = 0;
for (size_t s_index = 0; s_index < strlen(source); ++s_index) {
counters += getCounts(source, target, s_index, 0);
}
for (size_t t_index = 1; t_index < strlen(target); ++t_index) {
counters += getCounts(source, target, 0, t_index);
}
return counters;
}
int main() {
printf ("%i \n", countSubstrings("aba", "baba"));
printf ("%i \n", countSubstrings("ab", "bb"));
printf ("%i \n", countSubstrings("a", "a"));
printf ("%i \n", countSubstrings("abe", "bbc"));
printf ("%i \n", countSubstrings("abeaskdfjpoirgfjifjwkdafjaksld",
"fqowuerflqfdjcasdjkvlfkjqheofkjsdjfasldkf"));
return 0;
}
</code></pre>
<h3>Outputs:</h3>
<pre><code>6
3
0
10
1314
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T20:07:27.590",
"Id": "495250",
"Score": "1",
"body": "Your examples do not really help because the underlines are not visible (at least not in my browser)."
}
] |
[
{
"body": "<p>It looks nice, and you got the right algorithm.</p>\n<p>Still, there are problems and additional ideas:</p>\n<ol>\n<li><p>The <code>const</code>-qualifier on the two functions return-value is ignored. Didn't your compiler warn?</p>\n</li>\n<li><p>Denoting the start of a string-slice by pointer to start of the whole string and offset into it is cumbersome and inefficient. Just give a pointer to the start of the slice.</p>\n</li>\n<li><p>You are playing <a href=\"http://wiki.c2.com/?ShlemielThePainter\" rel=\"nofollow noreferrer\">Shlemiel The Painter</a> with all four <code>strlen()</code>-calls in your loops. The compiler might be able to hoist it four you, or it might not.</p>\n<p>If it cannot, at least those in <code>countSubstrings()</code> are cheaper by some constant factor than the calls to a fixed <code>getCounts()</code>, and thus don't influence your codes big-oh.<br />\nBut those in <code>getCounts()</code> turn the function from linear to quadratic, and thus the algorithm from quadratic to cubic.</p>\n<p>What I don't get is why you ask for the strings length at all.<br />\nJust substitute <code>!s[n]</code> for <code>strlen(s) == n</code>.</p>\n</li>\n<li><p>Either <code>int</code> is always big enough, and should be used throughout, or it isn't,\nand you have to play it safe by using <code>size_t</code>.</p>\n</li>\n<li><p>By the way, the problem is symmetric in its two arguments. That can be used.</p>\n</li>\n</ol>\n<p>And that was all I found.</p>\n<pre><code>static int getCounts(const char* a, const char* b) {\n int prev = 0;\n int curr = 0;\n int r = 0;\n for (; *a && *b; r += prev) {\n ++curr;\n if (*a++ != *b++) {\n prev = curr;\n curr = 0;\n }\n }\n return r;\n}\n\nstatic int manyCounts(const char* a, const char* b) {\n int r = 0;\n while (*a)\n r += getCounts(a++, b);\n return r;\n}\n\nint countSubstrings(const char * a, const char * b) {\n return !*a ? 0 : manyCounts(a + 1, b) + manyCounts(b, a);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T21:17:15.483",
"Id": "251566",
"ParentId": "251555",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "251566",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T17:39:29.780",
"Id": "251555",
"Score": "5",
"Tags": [
"beginner",
"algorithm",
"c",
"programming-challenge",
"strings"
],
"Title": "LeetCode 1638: Count Substrings That Differ by One Character"
}
|
251555
|
<p>I am looking for feedback to improve code readability and improve the algorithm's efficiency. I have already posted a question on code review about this. The feedback was helpful, and I did rethink the data structures.</p>
<p>Link to the previous question: <a href="https://codereview.stackexchange.com/questions/251549/job-scheduling-algorithm">Job Scheduling Algorithm</a></p>
<p>Info about classes:</p>
<p>Item is the item the machines work on.
Machine is a single machine that can be used from start time to end time.
A single task is a single item on a machine.
Job is a complete job, and can have more than one task.</p>
<p>The algorithm schedules the tasks, re-orders them for the specific machine, and adds to total profit is a job is finished within the schedule.</p>
<pre><code>
class ItemModel:
def __init__(self, name:str, starts:int, ends:int)->None:
self.name = name
self.start = start
self.ends = ends
class JobModel:
def __init__(self, tasks_needed:int, tasks_done:int, profit:int)->None:
self.tasks_needed = tasks_needed
self.tasks_done = tasks_done
self.profit = profit
class MachineModel:
def __init__(self, starts:int, ends:int)->None:
self.starts = starts
self.ends = ends
class View:
def output_profit(profit:int)->None:
print("profit: " + str(profit), end = "\n")
def output_sublist(sublist:[int])->None:
for item in sublist:
print(str(item), end = " ")
print('\n')
def algorithm(items:[ItemModel], jobs:[JobModel], machines:[MachineModel])->(int, [ItemModel]):
total_profit = 0
for start in range(len(items)):
for end in range(len(items)):
for job_row in range(len(jobs)):
if (time >= jobs[job_row].start_time) and (time <= jobs[job_row].end_time):
jobs[job_row].task_done += 1
profit = 0
for job_row in range(len(jobs)):
if jobs[row].tasks_needed == jobs[row].tasks_done:
profit += jobs[row].profit
yield (profit, sublist)
def main():
items = [ItemModel("a", 0, 2), ItemModel("b", 3, 4)]
jobs = [JobModel(0, 0, 12), JobModel(0, 0, 10)]
machines = [MachineModel(0, 1), MachineModel(0, 7)]
View view = View()
for pair in algorithm(items, jobs, machines):
view.output_profit(pair[0])
view.output_sublist(pair[1])
if __name__ == "__main__":
main()
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>'algorithm' is not correct at all and will fail at runtime. please make sure your code works before posting it. <code>start</code> and <code>end</code> are never read. <code>time</code> is never defined. 'row' is never defined--it is typo-d as 'job_row' the second time. use 'for job in robs', not 'for job_row in <code>range(len(jobs))</code> together with 'jobs[job_row]'. I would generally recommend a linter, which should catch all these errors.</p>\n</li>\n<li><p>Add a docstring to "algorithm", describing what its inputs are, and what it returns. Make sure to describe what it returns in terms of MEANING, and not what the algorithm does. ("returns the best way to schedule..." and not "loops through...")\nChange the name of 'algorithm' to reflect what it does (ex. 'schedule').</p>\n</li>\n<li><p>I personally think it's fine to put the contents of 'main' directly in the <code>if __name__ == "__main__"</code> block, but I've seen it both ways.</p>\n</li>\n<li><p>For the output_ methods, consider returning a string, and printing the string, as two steps. <code>" ".join()</code> may help.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T02:03:30.603",
"Id": "251575",
"ParentId": "251558",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T18:07:41.553",
"Id": "251558",
"Score": "1",
"Tags": [
"python"
],
"Title": "Job Scheduling Algorithm 2"
}
|
251558
|
<p>I am trying to learn recursion and have a question involving an array that needs to be reversed. I am focusing on c# but the language probably doesn't matter a whole lot because my function is not using any libraries.</p>
<p>Here is my code:</p>
<pre><code>char[] ReverseString(char[] s, int i = 0)
{
char[] x = s;
char temp = s[i];
s[i] = s[s.Length - (i + 1)];
s[s.Length - (i + 1)] = temp;
i++;
if (i < (s.Length) / 2)
{
ReverseString(s, i);
}
return x;
}
</code></pre>
<p>Any suggestions on how I should improve my function (maybe time complexity or using libraries (nuget packages)) is appreciated as well.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T09:51:40.203",
"Id": "495345",
"Score": "0",
"body": "The same problem has been address many times: [1](https://stackoverflow.com/questions/49930296/recursively-reverse-an-array), [2](https://codereview.stackexchange.com/questions/66773/reversing-an-array-recursively), [3](https://www.youtube.com/watch?v=ICFLUX8Y73Y), etc..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-06T18:40:55.013",
"Id": "495745",
"Score": "0",
"body": "Tip: `System.Linq` is great when you want to do something with arrays or collections `string hello = \"Hello World!\"; string olleh = new string(hello.Reverse().ToArray());` Output: `!dlroW olleH`."
}
] |
[
{
"body": "<p>Honestly, this is not a very good problem to do recursively, just pick another problem. Here's a better one: take in an integer, and print the sum of the digits.</p>\n<p>Some general feedback:</p>\n<ul>\n<li>ReverseString returns something, but you ignore its return value</li>\n<li>You make x, but it's a shallow copy of s -- modifying x and s do the same thing, and returning them would do the same thing. Just don't declare 'x' at all.</li>\n<li>See how short you can make this. It's not good general advice, but it can be good advice when learning recursion.</li>\n</ul>\n<p>One last tip when learning recursion: next time, try to do it without modifying a single variable. Just use expressions and return values. Again, it's not always how you should write real code, but it will help you learn faster.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T17:33:23.483",
"Id": "495418",
"Score": "0",
"body": "Thanks I am following a guide on LeetCode and this was the first problem they gave but I will try printing the amount of digits in an int. (I have done this but not recursively). But could you explain your first point about ignoring the return value?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-06T02:44:55.087",
"Id": "495637",
"Score": "0",
"body": "Print the SUM of the digits, not the NUMBER of digits"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T04:34:08.103",
"Id": "251582",
"ParentId": "251564",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T20:30:26.430",
"Id": "251564",
"Score": "1",
"Tags": [
"c#",
"array",
"recursion"
],
"Title": "Recursion with char[] in c#"
}
|
251564
|
<p>I made a program that lets the user input text into a text box.
The user can choose a number to rotate each alphabetical character by that number,
and the output box will diplay the converted text.</p>
<p>Here is how it runs:</p>
<p><a href="https://i.stack.imgur.com/8qIcy.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/8qIcy.gif" alt="enter image description here" /></a></p>
<p>Among the code is</p>
<pre><code># if event.key == pygame.K_RETURN:
# print('\n'.join([''.join(row) for row in rot_box.text])+'\n--------------------')
</code></pre>
<p>If you remove the hashtags, the converted text will be printed whenever you press Enter.</p>
<p>Here is my entire code:</p>
<pre><code>import pygame
pygame.font.init()
wn = pygame.display.set_mode((600, 600))
font = pygame.font.Font(None, 32)
class TextBox():
def __init__(self, x, y, w, h, title='Text Box', color=(0, 0, 0), default=''):
self.input_box = pygame.Rect(x, y, w, h)
self.w = w
self.h = h
self.color_inactive = color
self.color_active = pygame.Color('purple')
self.color = self.color_inactive
self.default = default
self.text = ['']
self.active = False
self.title = title
def draw(self):
title = font.render(self.title, True, self.color)
wn.blit(title, (self.input_box.x+5, self.input_box.y-self.h))
txts = [font.render(''.join(t), True, self.color) for t in self.text]
width = max(self.w, max(txts, key=lambda x:x.get_width()).get_width()+10)
height = self.h * len(txts)
self.input_box.w = width
self.input_box.h = height
if len(txts) == 1 and txts[0].get_width() == 1:
wn.blit(font.render(self.default, True, self.color), (self.input_box.x+5, self.input_box.y+5))
else:
for i, txt in enumerate(txts):
wn.blit(txt, (self.input_box.x+5, self.input_box.y+5+i*self.h))
pygame.draw.rect(wn, self.color, self.input_box, 2)
def check_status(self, pos):
if self.input_box.collidepoint(pos):
self.active = not self.active
else:
self.active = False
self.color = self.color_active if self.active else self.color_inactive
def type(self, event):
if self.active:
if event.key == pygame.K_RETURN:
self.text.append('')
elif event.key == pygame.K_BACKSPACE:
if self.text[-1]:
self.text[-1] = self.text[-1][:-1]
else:
if len(self.text) > 1:
self.text = self.text[:-1]
else:
self.text[-1] += event.unicode
def rot(alp, num):
while num >= 26:
num -= 26
if alp in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ':
n = ord(alp) + num
if n > 122 or 97 > n > 90:
n -= 26
alp = chr(n)
return alp
box = TextBox(110, 60, 140, 32, 'Input Text')
rot_num = TextBox(10, 60, 50, 32, 'Rot', default='0')
rot_box = TextBox(110, 300, 140, 32, 'Output Text')
while True:
rt = int(rot_num.text[0]) if rot_num.text[0] else 0
rot_box.text = [[rot(char, rt) for char in row] for row in box.text]
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.MOUSEBUTTONDOWN:
box.check_status(event.pos)
rot_num.check_status(event.pos)
if event.type == pygame.KEYDOWN:
box.type(event)
if (event.unicode.isdigit() or event.key == pygame.K_BACKSPACE) and len(rot_num.text[0]) < 6 or event.key == pygame.K_BACKSPACE:
rot_num.type(event)
# if event.key == pygame.K_RETURN:
# print('\n'.join([''.join(row) for row in rot_box.text])+'\n--------------------')
wn.fill((255, 255, 200))
box.draw()
rot_num.draw()
rot_box.draw()
pygame.display.flip()
</code></pre>
<h3>Can you show me how to clean up my messy code?</h3>
<h3>Can also you point me at the parts of my code that should've been in a class or function, and the parts that shouldn't have been?</h3>
|
[] |
[
{
"body": "<p>Your ROT algorithm is slightly wrong. The real ROT returns The alphabet rotated in the corresponding case. But in yours, even if you give Uppercase(TUVWXYZ), it returns lowercase for large rotations. That is not exact ROT.</p>\n<p>This can be seen from this screenshot <a href=\"https://i.stack.imgur.com/CkD1Q.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/CkD1Q.png\" alt=\"enter image description here\" /></a></p>\n<p>This may be helpful: <a href=\"https://www.geeksforgeeks.org/rot13-cipher/\" rel=\"nofollow noreferrer\">https://www.geeksforgeeks.org/rot13-cipher/</a>. Here instead of <code>chr()</code> and <code>ord()</code> <strong>Dictionaries</strong> are used which is very efficient and less error prone.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T22:36:26.927",
"Id": "495461",
"Score": "0",
"body": "Thanks for pointing that out!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T04:33:14.933",
"Id": "251581",
"ParentId": "251568",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "251581",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T22:01:33.960",
"Id": "251568",
"Score": "4",
"Tags": [
"python",
"classes",
"pygame"
],
"Title": "Rot13 app - How to tidy up code?"
}
|
251568
|
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/250418/231235">Generic Two Dimensional Data Plane with Manipulation Methods For C#</a>. Thanks to <a href="https://codereview.stackexchange.com/a/250439/231235">cliesens's</a> and <a href="https://codereview.stackexchange.com/a/250546/231235">Rick Davin's detailed answer</a>. Moreover, the mentioned <code>PlaneV2</code> example is very clear to let me realize how to improve my code. Based on Rick Davin's <code>PlaneV2</code> example, I am trying to implement a <code>SubPlane</code> method which can extract a specific region data block by given parameters. The experimental code is as follows.</p>
<pre><code>public PlaneV2<T> SubPlane(int locationX, int locationY, int newWidth, int newHeight)
{
if (this.Grid == null)
{
return null;
}
PlaneV2<T> outputPlaneV2 = new PlaneV2<T>(newWidth, newHeight);
for (int y = 0; y < newHeight; y++)
{
for (int x = 0; x < newWidth; x++)
{
outputPlaneV2[x, y] = this.Grid[locationX + x, locationY + y];
}
}
return outputPlaneV2;
}
</code></pre>
<p>As you can see, there are four parameters in this <code>SubPlane</code> method, The first and second parameter represents the top-left location in the origin plane, and the third and forth parameter represents the size of the extracted sub-plane. The usage of this <code>SubPlane</code> method is as below.</p>
<pre><code>var width = 3;
var height = 5;
var plane = new PlaneV2<int>(width, height);
for (var x = 0; x < width; x++)
for (var y = 0; y < height; y++)
plane[x, y] = ((x + 1) * 100) + y;
var newSubPlane = plane.SubPlane(1, 1, 2, 2); // For example
Console.WriteLine("ToString() Example: " + newSubPlane.ToString());
Console.WriteLine("\nTAB DELIMITED BY X THEN Y");
Console.WriteLine(plane.ToDelimitedStringByWidthThenHeight());
Console.WriteLine(newSubPlane.ToDelimitedStringByWidthThenHeight());
Console.WriteLine("\nSEMI-COLON DELIMITED BY Y THEN X");
Console.WriteLine(plane.ToDelimitedStringByHeightThenWidth(" ; "));
Console.WriteLine(newSubPlane.ToDelimitedStringByHeightThenWidth(" ; "));
</code></pre>
<p>The whole <code>PlaneV2<T></code> class with <code>SubPlane</code> method implementation:</p>
<pre><code>public class PlaneV2<T>
{
public int Width { get; } = 0;
public int Height { get; } = 0;
private T[,] Grid = null;
public int Length => Width * Height;
public PlaneV2() : this(1, 1) { }
public PlaneV2(int width, int height)
{
Width = Math.Max(width, 0);
Height = Math.Max(height, 0);
Grid = new T[width, height];
}
public PlaneV2(PlaneV2<T> plane) : this(plane?.Grid) { }
public PlaneV2(T[,] sourceGrid)
{
if (sourceGrid == null)
{
return;
}
Width = sourceGrid.GetLength(0);
Height = sourceGrid.GetLength(1);
Grid = new T[Width, Height];
Array.Copy(sourceGrid, Grid, sourceGrid.Length);
}
public T this[int x, int y]
{
get
{
if (x < 0 || x >= Width)
{
throw new ArgumentOutOfRangeException(nameof(x));
}
if (y < 0 || y >= Height)
{
throw new ArgumentOutOfRangeException(nameof(y));
}
return Grid[x, y];
}
set
{
if (x < 0 || x >= Width)
{
throw new ArgumentOutOfRangeException(nameof(x));
}
if (y < 0 || y >= Height)
{
throw new ArgumentOutOfRangeException(nameof(y));
}
Grid[x, y] = value;
}
}
public PlaneV2<T> SubPlane(int locationX, int locationY, int newWidth, int newHeight)
{
if (this.Grid == null)
{
return null;
}
PlaneV2<T> outputPlaneV2 = new PlaneV2<T>(newWidth, newHeight);
for (int y = 0; y < newHeight; y++)
{
for (int x = 0; x < newWidth; x++)
{
outputPlaneV2[x, y] = this.Grid[locationX + x, locationY + y];
}
}
return outputPlaneV2;
}
public override string ToString() => $"{nameof(PlaneV2<T>)}<{typeof(T).Name}>[{Width}, {Height}]";
public string ToDelimitedStringByHeightThenWidth(string separator = "\t")
{
StringBuilder lines = new StringBuilder();
for (int y = 0; y < Height; y++)
{
StringBuilder columns = new StringBuilder();
string columnDelimiter = "";
for (int x = 0; x < Width; x++)
{
columns.Append(columnDelimiter + Grid[x, y].ToString());
if (columnDelimiter == "")
{
columnDelimiter = separator;
}
}
lines.AppendLine(columns.ToString());
}
return lines.ToString();
}
public string ToDelimitedStringByWidthThenHeight(string separator = "\t")
{
StringBuilder lines = new StringBuilder();
for (int x = 0; x < Width; x++)
{
StringBuilder columns = new StringBuilder();
string columnDelimiter = "";
for (int y = 0; y < Height; y++)
{
columns.Append(columnDelimiter + Grid[x, y].ToString());
if (columnDelimiter == "")
{
columnDelimiter = separator;
}
}
lines.AppendLine(columns.ToString());
}
return lines.ToString();
}
} // class
</code></pre>
<p>All suggestions are welcome.</p>
<ul>
<li><p>Which question it is a follow-up to?</p>
<p><a href="https://codereview.stackexchange.com/q/250418/231235">Generic Two Dimensional Data Plane with Manipulation Methods For C#</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p>The previous question focused on the concatenation methods, and the main idea here is to implement a <code>SubPlane</code> method which can extract a specific region data block by given parameters.</p>
</li>
<li><p>Why a new review is being asked for?</p>
<p>Although it seems that the above version of this <code>SubPlane</code> method works well, I am not sure is it efficient with copying data element-by element using <code>for</code> loop. I am not sure how to construct the output sub-plane with <code>Array.Copy</code> in this situation. If there is any better idea, please let me know.</p>
</li>
</ul>
|
[] |
[
{
"body": "<p>Only focusing on <code>ToDelimitedStringByHeightThenWidth()</code> and <code>ToDelimitedStringByWidthThenHeight()</code></p>\n<p>By extracting the methods <code>IEnumerable<string> TopDown(int y)</code> and <code>IEnumerable<string> TopDown(int y)</code> like so:</p>\n<pre><code>private IEnumerable<string> TopDown(int y)\n{\n for (int x = 0; x < Width; x++)\n {\n yield return Grid[x, y].ToString();\n }\n} \nprivate IEnumerable<string> LeftRight(int x)\n{\n for (int y = 0; y < Height; y++)\n {\n yield return Grid[x, y].ToString();\n }\n} \n</code></pre>\n<p>you can take advantage of the <code>string.Join(separator, IEnumerable<string>)</code> and remove the <code>StringBuilder columns</code> and the <code>if</code> inside the most inner loops, leading to:</p>\n<pre><code>public string ToDelimitedStringByHeightThenWidth(string separator = "\\t")\n{\n StringBuilder lines = new StringBuilder();\n for (int y = 0; y < Height; y++)\n {\n lines.AppendLine(string.Join(separator, TopDown(y)));\n }\n return lines.ToString();\n} \npublic string ToDelimitedStringByWidthThenHeight(string separator = "\\t")\n{\n StringBuilder lines = new StringBuilder();\n for (int x = 0; x < Width; x++)\n {\n lines.AppendLine(string.Join(separator, LeftRight(x)));\n }\n return lines.ToString();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T09:00:12.537",
"Id": "251592",
"ParentId": "251570",
"Score": "1"
}
},
{
"body": "<p>A few points :</p>\n<ul>\n<li><p>The default value of <code>int</code> is zero, so <code>public int Width { get; } = 0;</code> is unnecessary.</p>\n</li>\n<li><p><code>Width = Math.Max(width, 0);</code> what is the reason of doing this ? isn't going to give you the same as <code>Width = width;</code> or is there is some cases where the values would differ ?</p>\n</li>\n<li><p>In the third constructor <code>if (sourceGrid == null) { return; }</code>, not recommended, either throw <code>ArguementNullException</code> or you could initiate the default instructor would be better.</p>\n<pre><code> public T this[int x, int y]\n {\n get\n {\n if (x < 0 || x >= Width)\n {\n throw new ArgumentOutOfRangeException(nameof(x));\n }\n if (y < 0 || y >= Height)\n {\n throw new ArgumentOutOfRangeException(nameof(y));\n }\n return Grid[x, y];\n }\n set\n {\n if (x < 0 || x >= Width)\n {\n throw new ArgumentOutOfRangeException(nameof(x));\n }\n if (y < 0 || y >= Height)\n {\n throw new ArgumentOutOfRangeException(nameof(y));\n }\n Grid[x, y] = value;\n }\n }\n</code></pre>\n</li>\n</ul>\n<p>is equal to this :</p>\n<pre><code>public T this[int x, int y] { get; set; }\n</code></pre>\n<p>Unless you implement a custom validation, your current indexer will be redundant, because it replicates the indexer default behavior. Mostly, you need to implement your requirements within the setter, but the getter in most cases doesn't need more than default behavior. As you're required to handle what's going inside your class (setter), but not what goes out of it (getter).</p>\n<ul>\n<li>Combine : <code>ToDelimitedStringByHeightThenWidth</code> and <code>ToDelimitedStringByWidthThenHeight</code> code into one <code>private</code> method and just recall it from other methods.</li>\n</ul>\n<p>Example :</p>\n<pre><code>public string ToDelimitedStringByHeightThenWidth(string separator = "\\t")\n{\n return ToDelimitedString(Height, Width, separator);\n}\n\npublic string ToDelimitedStringByWidthThenHeight(string separator = "\\t")\n{\n return ToDelimitedString(Width, Height, separator);\n}\n\nprivate string ToDelimitedString(int outterCounter, int innerCounter, string separator)\n{\n var lines = new StringBuilder();\n var columns = new StringBuilder();\n var columnDelimiter = string.IsNullOrWhiteSpace(separator) ? "" : separator;\n \n for (int x = 0; x < outterCounter; x++)\n {\n for (int y = 0; y < innerCounter; y++)\n {\n columns.Append(columnDelimiter + Grid[x, y].ToString());\n \n if (columnDelimiter == string.Empty) // more readability \n {\n columnDelimiter = string.IsNullOrWhiteSpace(separator) ? "\\t" : separator;\n }\n }\n \n lines.AppendLine(columns.ToString());\n columns.Clear(); // Clear and reuse it instead of initiating a new object.\n }\n \n return lines.ToString();\n}\n</code></pre>\n<p>For <code>SubPlane</code>, you should not use the regular <code>for</code> loop to copy arrays unless if you're sure that it won't be a big arrays (large arrays = 2000+ elements). The reason behind that is the more elements that array has, the more performance you lose when copying using the <code>for</code> loop. So, to gain more performance, you need to use <code>Array.Copy</code> for large arrays, which is a native function that would copy the array with bypassing some of <code>CLR</code> checks. This would eventually add some extra boost to the overall performance.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T12:17:09.353",
"Id": "495355",
"Score": "1",
"body": "The part about the getter is not correct. Assume setting I first set `plane[1, 1] = 1` and want to read (assuming T is int) `int value = plane[-1, 1]`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T12:27:09.733",
"Id": "495356",
"Score": "0",
"body": "@Heslacher by default, it would throw an index out of range exception, which I think it's redundant."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T12:35:53.593",
"Id": "495359",
"Score": "0",
"body": "Well, my bad you are right ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T12:53:41.377",
"Id": "495362",
"Score": "0",
"body": "@Heslacher nope, I'm the one who needs to apology, I read my lines, and it felt misleading, so I updated that line to be more clear. Accept my apologies again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T12:58:54.077",
"Id": "495364",
"Score": "0",
"body": "no problem, no need to apologize"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T10:00:58.150",
"Id": "251594",
"ParentId": "251570",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "251594",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-03T22:57:00.047",
"Id": "251570",
"Score": "3",
"Tags": [
"c#",
"object-oriented",
"generics",
"classes"
],
"Title": "A SubPlane Method for Generic Two Dimensional Data Plane in C#"
}
|
251570
|
<p>I am completing a simple but tedious program in C++. I have a function that must find the minimum value in an array. Here is the code:</p>
<pre><code>double min(double x[], int total)
{
for (int i = 0; i < total; i++)
{
x[0] = (x[i] < x[0]) ? x[i] : x[0];
}
return x[0];
}
</code></pre>
<p>And a different approach, using a nested <code>for</code> loop and an <code>if</code> statement inside:</p>
<pre><code>double min(double x[], int total)
{
for (int i = 0; i < total; i++)
{
for (int j = i + 1; j < total; j++)
{
if (x[j] > x[i])
{
double temp = x[i];
x[i] = x[j];
x[j] = temp;
}
}
}
return x[0];
}
</code></pre>
<p>I have a few questions here:</p>
<ol>
<li>Is the first code really any more efficient than the second? I'm sure that as the array grows then time complexity will too <code>0(n)</code>. So maybe with arrays this is better?</li>
<li>Is there any other way that I could improve this further? I'm sure it would be far more efficient to use a library, I just don't know many C++ libraries.</li>
</ol>
<p>Assuming that the data is not needed after this function call, how much more practical would my first option be? Would it only make a noticeable difference where <code>num_elements > 10000</code>?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T14:40:14.370",
"Id": "495383",
"Score": "1",
"body": "For all new users when you down vote a question, please add a comment explaining what is wrong with the question. Down voting without commenting is somewhat rude and doesn't help the person that asked the question improve the question. It is not clear why this question has 3 down votes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T17:18:09.770",
"Id": "495413",
"Score": "0",
"body": "@TobySpeight Welcome back, missed you these last few months."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T17:20:56.150",
"Id": "495414",
"Score": "0",
"body": "Thanks @pacmaninbw. Was unexpectedly out of the office for a few weeks. :-( I have equipment at home now and catching up; lots of comments to answer!"
}
] |
[
{
"body": "<ul>\n<li>The biggest issue I see with this code, is that it destroys data. It does not return the min--it OVERWRITES the first array value with the min, and then returns the min. You should try to write correct code before writing fast code.</li>\n<li>Rename 'total' to 'num_elements' or something. 'total' sounds like it's the sum of the values.</li>\n</ul>\n<ol>\n<li><p>I don't know what you mean by your suggestion around a "nested for loop". Include code if you want an opinion about that. An if-statement inside a for-loop, is not called a "nested for loop". A "nested for loop" means a for-loop inside a for-loop.</p>\n<p>This is the same efficiency as an if statement. The ternary operator and an if statement will compile to the same thing. A ternary operator only affects readability.</p>\n</li>\n<li><p>You could use std::min. <a href=\"https://en.cppreference.com/w/cpp/algorithm/min\" rel=\"noreferrer\">https://en.cppreference.com/w/cpp/algorithm/min</a></p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T01:23:33.017",
"Id": "495295",
"Score": "0",
"body": "The std::min suggestion is very good. If the OP stays with their loop they should use iterators and can use a ranged for loop as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T01:40:30.850",
"Id": "495297",
"Score": "0",
"body": "I can edit my post to be more specific, but when I say nested for loop and if statement, I mean `for (int i = 0; ...) {for (int j = i + 1; ...) { if (x[i] < x[j] ) { //temp variable... }}}`. And this is all assuming that the array can be destroyed and won't be needed after the function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T01:47:07.433",
"Id": "495299",
"Score": "2",
"body": "That explains a lot. The second example sorts the list (using bubble sort, which you should not do--use std::sort if you ever need to sort something). Just finding a minimum is more efficient than sorting a list, yes. As a rule of thumb, the number of nested loops and the efficiency are almost the same, as long as you're not accessing files or the internet, etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T17:29:20.437",
"Id": "495417",
"Score": "0",
"body": "Thanks, I learned a lot. (Avoid bubble sort because of `0(n^2)`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T23:19:04.577",
"Id": "525200",
"Score": "0",
"body": "Avoid bubble sort because you shouldn't implement things yourself that are in standard libraries, not because it's inefficient. The standard library will be correct, fast, and readable (`std::sort(s.begin(), s.end());` is immediately understandable to anyone who knows the standard library, which should be everyone)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T01:21:07.683",
"Id": "251572",
"ParentId": "251571",
"Score": "6"
}
},
{
"body": "<p>Depends on what you're trying to do.</p>\n<p>The STL Algorithm library has <code>std::min</code> which will give you the result; you'll still need to compare every item though, and that achieves O(N) time complexity.</p>\n<pre><code>#include <algorithm>\ndouble min(double x[], int total){ // There's a subtle chance for bugs right here\n ASSERT(total >= 1); // An ugly fix\n auto res = x[0];\n for (int i = 1; i < total; i++)\n res = std::min(res, x[i]);\n return res;\n}\n\n</code></pre>\n<p>then there's the STL algorithm min_element which returns an iterator to the smallest element. As it's a full blown function, you don't need to declare your own. It too, is a O(N) algorithm.</p>\n<pre><code>#include <algorithm>\n\nint main(){\ndouble x[total]; // total defined elsewhere, maybe as macro or constexpr\n// Your code\nauto min_number = *std::min_element(std::cbegin(x),std::cend(x));\n//more code\n</code></pre>\n<p>Sorting the array won't provide you with a speedup, because unless the array is already sorted, then the Average Time Complexity will be O(N * log(N)), and a worst case O(N²).</p>\n<p>As a final note: if you use the first method, like in your code, you're opening yourself up to issues where total <strong>could</strong> be zero or negative, giving your access issues.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T13:42:07.230",
"Id": "495374",
"Score": "2",
"body": "In the last case, prefer `std::begin(x)` and `std::end(x)`, as `&x[size]` is only really applicable to native arrays, and has too many moving parts."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T13:51:37.663",
"Id": "495375",
"Score": "0",
"body": "True, given the initial state of the question, I was under the impression that OP might be passing c-arrays around instead of standard containers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T17:21:45.773",
"Id": "495415",
"Score": "0",
"body": "Thanks for the answer. It helps."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T10:34:05.557",
"Id": "251596",
"ParentId": "251571",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "251572",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T01:10:11.953",
"Id": "251571",
"Score": "-2",
"Tags": [
"c++",
"algorithm",
"array"
],
"Title": "Find the minimum value in an array"
}
|
251571
|
<p>I'm trying to implement a queue data structure in C++ using a circular array.</p>
<p>Please give recommendations on how I can improve this code.
Also, is my array growth strategy good? I'm doubling the array when the buffer is full.
(Try to remain in C++ 11 because, well that's a restriction I have to follow atm).</p>
<p>Sorry for the lack of comments in advance LoL (this is a rushed implementation).</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <utility>
template <typename T>
class Queue {
public:
Queue() : data(nullptr), len(0), front(0), cap(0)
{
}
~Queue()
{
this->Clear();
}
Queue(const Queue& rhs) : Queue()
{
if (rhs.data) {
this->data = new T[rhs.cap];
this->cap = rhs.cap;
this->len = rhs.len;
this->front = rhs.front;
for (size_t i = 0; i < len; ++i) {
this->data[i] = rhs.data[i];
}
}
}
Queue(Queue&& rhs) : data(rhs.data), cap(rhs.cap), len(rhs.len), front(rhs.front)
{
rhs.data = nullptr;
}
Queue& operator=(Queue rhs)
{
swap(*this, rhs);
return *this;
}
size_t GetLength() const { return len; }
const T& GetFront() const { return data[front]; }
void Enqueue(const T& val)
{
if (len == cap) {
size_t oldCap = cap;
if (cap == 0) cap = 1;
cap *= 2;
T* newBuff = new T[cap];
for (size_t i = 0; i < len; ++i) {
size_t idx = (front + i) % oldCap;
newBuff[i] = data[idx];
}
front = 0;
data = newBuff;
}
data[(front + len) % cap] = val;
++len;
}
T Dequeue()
{
T val = std::move(data[front]);
front = (front + 1) % cap;
--len;
return val;
}
void Clear()
{
delete[] data;
data = nullptr;
this->cap = this->len = this->front = 0;
}
friend
std::ostream& operator<< (std::ostream& out, const Queue& q)
{
out << "Queue{";
for (size_t i = 0; i < q.len; ++i) {
size_t idx = (q.front + i) % q.cap;
out << q.data[idx];
if (i < q.len - 1) out << ", ";
}
out << "}";
return out;
}
friend
void swap(Queue& lhs, Queue& rhs)
{
std::swap(lhs.data, rhs.data);
std::swap(lhs.len, rhs.len);
std::swap(lhs.cap, rhs.cap);
std::swap(lhs.front, rhs.front);
}
private:
T* data;
size_t len;
size_t cap;
size_t front;
};
int main()
{
Queue < int > a;
a.Enqueue( 5 ); // add 5
a.Enqueue ( 6 ); // add 6
std::cout << a; // prints Queue{5, 6}
a.Clear(); // empties the Queue
std::cout << a; // prints Queue{}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T05:12:47.983",
"Id": "495328",
"Score": "0",
"body": "Can you give a basic example of how this class can be used?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T05:22:23.567",
"Id": "495330",
"Score": "0",
"body": "@Aryan Parekh this is a Queue (First-In First-Out) data structure. I'm a CS student so I'm just learning about Data structures so I don't know about many applications of the Queue. However it is used for simulating a real-life Queue in programming."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T05:27:04.053",
"Id": "495331",
"Score": "0",
"body": "You misunderstood me :), I added a `main()` function in your code showing how this class can be used. You can [edit] it further to show the use of the rest of the functions"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T05:28:18.147",
"Id": "495332",
"Score": "0",
"body": "@Aryan Parekh ok"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T05:38:48.877",
"Id": "495333",
"Score": "0",
"body": "A circular array is rough to resize correctly. Can you avoid doing that, and instead throw an error, ha? Doubling is fine, yes. Definitely pull it out of Enqueue. It can be made much more efficient--should just be 'memcpy' twice. Also, you have a memory leak there now. I would allow setting capacity on create (either empty or from another queue) if you want to be extra professional."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T02:28:57.943",
"Id": "495479",
"Score": "0",
"body": "@Zachary Vance using a fixed size array has a lot of problems. Also since my implementation is already working with a resizable buffer (minus the memory leak which I fixed), why should I settle for a fixed size buffer ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T04:19:56.907",
"Id": "495494",
"Score": "0",
"body": "@GuyontheInternet \"Circular\" array implies a fixed size"
}
] |
[
{
"body": "<p>This is quite a decent implementation of a C++ container! Some minor improvements are possible though:</p>\n<h1>Prefer using default member initialization</h1>\n<p>Especially when you have multiple constructors, <a href=\"https://en.cppreference.com/w/cpp/language/data_members#Member_initialization\" rel=\"nofollow noreferrer\">default member initialization</a> saves typing and reduces the chance of accidentily not initializing a variable. So:</p>\n<pre><code>class Queue {\npublic:\n Queue() = default;\n\n Queue(const Queue &rhs)\n {\n ...\n }\n\n ...\nprivate:\n T* data = nullptr; // or {} works as well\n size_t len = 0;\n size_t cap = 0;\n size_t front = 0;\n};\n</code></pre>\n<h1>Use bitwise AND instead of modulo operations</h1>\n<p>Calculating the modulus of an integer is very slow compared to doing a bitwise AND (tens of CPU cycles vs. a fraction of a cycle). Since your capacity is always a power of two, you can use bitwise AND, like so:</p>\n<pre><code>data[(front + len) & (cap - 1)] = val;\n</code></pre>\n<p>You can get rid of the <code>- 1</code> if you really want, that means storing the capacity minus one in <code>cap</code>. This will speed up the common case where you don't need to reallocate a tiny bit.</p>\n<p>Note that the compiler probably won't be able to optimize the modulo to a bitwise AND by itself, because <code>cap</code> is not a constant.</p>\n<h1>Consider following the naming conventions of the standard library</h1>\n<p>It would be nice if your container has the same interface as other STL containers. That makes it easier for a programmer to remember the names of the member functions, but also makes it more likely that your container can be used as a drop-in replacement for other STL containers, and that algorithms that work with a <code>std::queue</code> can also work with your container. So consider renaming these member functions:</p>\n<ul>\n<li><code>GetLength()</code> -> <code>size()</code></li>\n<li><code>GetFront()</code> -> <code>front()</code></li>\n<li><code>Enqueue()</code> -> <code>push()</code></li>\n<li><code>Dequeue()</code> -> <code>pop()</code> (althought the STL's <code>pop()</code> doesn't return any value)</li>\n<li><code>Clear()</code> -> <code>clear()</code></li>\n</ul>\n<p>The reason the STL doesn't return a value for <code>pop()</code> is so that it doesn't require <code>T</code> to be movable, instead you use <code>front()</code> to read the value, then <code>pop()</code> to discard it.</p>\n<h1>Unnecessary use of <code>this-></code></h1>\n<p>There are a few places where you use <code>this-></code> where it isn't necessary. In the copy constructor it makes a bit of sense since this emphasizes the contrast with <code>rhs.</code>, but in <code>~Queue()</code> and <code>Clear()</code> you don't need it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T02:26:40.257",
"Id": "495477",
"Score": "0",
"body": "Thanks for the detailed answer . Can you tell me how that bitwise trick works, I can't quite wrap my head around it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T04:12:03.450",
"Id": "495491",
"Score": "1",
"body": "@GuyontheInternet You can read [this](https://mziccard.me/2015/05/08/modulo-and-division-vs-bitwise-operations/#:~:text=Modulo%20can%20be%20easily%20translated,is%20a%20power%20of%20two.&text=In%20general%2C%20if%20divisor%20is,positions%3A%20value%20%3E%3E%20n%20.), it will help :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T19:37:26.203",
"Id": "251615",
"ParentId": "251583",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "251615",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T05:07:24.117",
"Id": "251583",
"Score": "4",
"Tags": [
"c++",
"c++11",
"queue",
"classes"
],
"Title": "C++ Queue Circular Array Implementation"
}
|
251583
|
<p>I am making this React Component for an interactive eye that moves and tracks the user's mouse cursor wherever it goes to in the webpage. However, I faced 3 problems while doing so.</p>
<ol>
<li><p>The eye moves as if the eye is in the middle of the webpage, so that when I place the eye somewhere other than the center of the webpage, it does not look at the cursor, only follow its movements.</p>
</li>
<li><p>Everytime I move my mouse in the webpage vigorously, my CPU usage rose to about 10% and my GPU rose 30%. Is this normal for interactive websites?</p>
</li>
<li><p>The image blurs sometimes after, when, and before moving.</p>
</li>
</ol>
<p>Here is my Eye Component:</p>
<pre><code>import React, { Component } from "react";
import "./Eye.css";
import pupil from "../assets/images/pupil.png";
import eyelid from "../assets/images/eye.png";
class Eye extends Component {
componentDidMount() {
window.addEventListener("mousemove", this._onMouseMove);
window.addEventListener("mouseout", this._onMouseLeave);
}
_onMouseMove = (e) => {
var balls = document.getElementsByClassName("ball");
var x = (e.clientX * 100) / window.innerWidth + "%";
var y = (e.clientY * 100) / window.innerHeight + "%";
console.log(e.clientX, e.clientX);
balls[0].style.left = x;
balls[0].style.top = y;
balls[0].style.transform = "translate(-" + x + ",-" + y + ")";
balls[0].style.transitionDuration = "0s";
};
_onMouseLeave = (e) => {
var balls = document.getElementsByClassName("ball");
var x = "50%";
var y = "50%";
balls[0].style.left = x;
balls[0].style.top = y;
balls[0].style.transform = "translate(-" + x + ",-" + y + ")";
balls[0].style.transitionDuration = ".5s";
};
render() {
return (
<div className='eyes'>
<img className='eyelid' src={eyelid} />
<div className='eye'>
<div className='ball'>
<img className='pupil' src={pupil} />
</div>
</div>
</div>
);
}
}
export default Eye;
</code></pre>
<p><a href="https://eunicocornelius.github.io/infographics/" rel="nofollow noreferrer">The Demo Problem HERE</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T03:58:24.870",
"Id": "495486",
"Score": "1",
"body": "@CertainPerformance I have deployed a demo on my gh-pages, can you take a look at it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T13:54:46.467",
"Id": "495547",
"Score": "0",
"body": "Yep, that'll do, thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-08T07:34:51.697",
"Id": "495898",
"Score": "0",
"body": "@CertainPerformance Any progress? I'm still stuck on finding a solution..."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T07:38:38.800",
"Id": "251587",
"Score": "1",
"Tags": [
"performance",
"beginner",
"css",
"react.js",
"memory-optimization"
],
"Title": "Improving interactive component performance with constant image translation"
}
|
251587
|
<p>I have created a Path finder.<br />
The aim is to find ALL paths that join a Point A to a Point B.<br />
I have defined an object <code>Segment</code> which is a link between two assets.<br />
It is readable in both directions.</p>
<pre><code>==> Segment(A->B) === Segment(B<-A)
</code></pre>
<p>Here is my code:</p>
<pre><code># Exemple Path finder
class Segment:
# A segment is a link (physical, radio, logical) beetween two assets
def __init__(self, sku, e1, e2, re1, re2):
# The SKU is the unique ID of the segment
# A segment as two endpoint that can be inversable
self.sku = sku
self.sku_endpoint_1 = e1
self.sku_endpoint_2 = e2
self.reverse_sku_endpoint_1 = re1
self.reverse_sku_endpoint_2 = re2
# We can instanciante a segment like that
seg1 = Segment("SEGMENT1","A", "B", "B", "A")
seg2 = Segment("SEGMENT2","B", "C", "C", "B")
seg3 = Segment("SEGMENT3","C", "D", "D", "C")
seg4 = Segment("SEGMENT4","C", "E", "E", "C")
seg5 = Segment("SEGMENT5","E", "A", "A", "E")
seg6 = Segment("SEGMENT6","E", "D", "D", "E")
# Then create a liste of segment
liste_segments = [seg1, seg2, seg3, seg4, seg5, seg6]
</code></pre>
<p>--</p>
<pre><code># The function below allow to find neibhors of a segment
def neighbors(liste_segments, node):
for segment in liste_segments:
if node == segment.sku_endpoint_1:
yield segment
</code></pre>
<p>--</p>
<pre><code># And the function below solve all paths existing beetween an start et end.
def solve(liste_segments, s, e, current_path=None, nb_call=0):
nb_call += 1
if nb_call == 1:
# We create a new liste with the inversable values to have all possibility of linking
liste_segments = clone(liste_segments)
if current_path is None:
current_path = []
if s == e:
# Here, we end the function because we found the end.
yield current_path
else:
# Else we call recursively the solve function on each neibhors
for node in neighbors(liste_segments, s):
print(node.sku_endpoint_1, node.sku_endpoint_2)
if node not in current_path:
for result in solve(liste_segments, node.sku_endpoint_2 , e, current_path + [node], nb_call):
yield result
</code></pre>
<p>--</p>
<pre><code># The yield function return a generator
# The function here create a dictionnary of all paths found.
# On all paths we check if the paths is meaningful.
# Ex: if a segment is found twice on the same path...this is not meaningful.
# So we delete the entry from the dict to keep only understanding paths.
def list_to_dict(paths):
d = {}
index = 0
for path in paths:
index+=1
d[index] = []
for segment in path:
d[index].append(segment.sku)
to_del = []
for k, v in d.items():
temp = []
for seg in v:
if seg not in temp:
temp.append(seg)
else:
if k not in to_del:
to_del.append(k)
for i in to_del:
del d[i]
return d
</code></pre>
<p>--</p>
<pre><code># The clone function create a new list of segment with all possibility.
def clone(liste_segments):
new_list_segments = []
for seg in liste_segments:
new_list_segments.append(Segment(seg.sku, seg.sku_endpoint_1, seg.sku_endpoint_2, "", ""))
new_list_segments.append(Segment(seg.sku, seg.reverse_sku_endpoint_1, seg.reverse_sku_endpoint_2, "", ""))
return new_list_segments
</code></pre>
<p>Is my code pythonic? What could be changed?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T10:31:41.843",
"Id": "495347",
"Score": "0",
"body": "Welcome to Code Review! What prompted you to write this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T13:08:06.573",
"Id": "495368",
"Score": "1",
"body": "Hello, I am creating a microservice that manage wiring over a datacenter, based on the layer 1 of OSI Model. The goal of this \"path finder\" is to permit an user to design a link beetween two assets. The link consists of N segments"
}
] |
[
{
"body": "<p>If you want to work with graphs in Python, you should have a look at the excellent module <a href=\"https://networkx.org/documentation/stable/index.html\" rel=\"nofollow noreferrer\"><code>networkx</code></a>. It has (usually fast) implementations of the most common (and many not so common) operations on directed and undirected graphs.</p>\n<p>Your case in particular, finding all simple paths (i.e. paths without repeating nodes) between two nodes, <a href=\"https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.simple_paths.all_simple_paths.html?highlight=all_simple_paths#networkx-algorithms-simple-paths-all-simple-paths\" rel=\"nofollow noreferrer\">is already implemented</a>:</p>\n<pre><code>import networkx as nx\n\ng = nx.Graph() # bi-directional edges. Use nx.DiGraph() if you want to explicitly specify directions\ng.add_edges_from([("A", "B"), ("B", "C"), ("C", "D"), ("C", "E"), ("E", "A")])\ng.add_edge("E", "D") # can also add individual edges\n\nfor path in nx.all_simple_paths(g, source="A", target="B"):\n print(path)\n\n# ['A', 'B']\n# ['A', 'E', 'C', 'B']\n# ['A', 'E', 'D', 'C', 'B']\n</code></pre>\n<p>If you want to associate data with each edge and get back only this data, this is also possible:</p>\n<pre><code>g = nx.Graph() # bi-directional edges. Use nx.DiGraph() if you want to explicitly specify directions\ng.add_edges_from([("A", "B", {"sku": "SEGMENT1"}),\n ("B", "C", {"sku": "SEGMENT2"}),\n ("C", "D", {"sku": "SEGMENT3"}),\n ("C", "E", {"sku": "SEGMENT4"}),\n ("E", "A", {"sku": "SEGMENT5"})])\ng.add_edge("E", "D", sku="SEGMENT6") # can also add individual edges\n\npaths = nx.all_simple_paths(g, source="A", target="B")\nfor path in map(nx.utils.pairwise, paths):\n for edge in path:\n print(edge, g.edges[edge]["sku"])\n print()\n\n# ('A', 'B') SEGMENT1\n# \n# ('A', 'E') SEGMENT5\n# ('E', 'C') SEGMENT4\n# ('C', 'B') SEGMENT2\n# \n# ('A', 'E') SEGMENT5\n# ('E', 'D') SEGMENT6\n# ('D', 'C') SEGMENT3\n# ('C', 'B') SEGMENT2\n</code></pre>\n<p>It even allows you to easily visualize the graph:</p>\n<pre><code>import matplotlib.pyplot as plt\n\nnx.draw(g, with_labels=True, node_color="white")\nplt.show()\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/IBpKgm.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IBpKgm.png\" alt=\"enter image description here\" /></a></p>\n<p>Or, more fancy:</p>\n<pre><code>pos = nx.spring_layout(g)\nlabels = dict(zip(g.edges, [g.edges[e]["sku"] for e in g.edges]))\nnx.draw(g, with_labels=True, node_color="white", pos=pos)\nnx.draw_networkx_edge_labels(g, pos=pos, edge_labels=labels)\nplt.show()\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/6QW8rl.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/6QW8rl.png\" alt=\"enter image description here\" /></a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T15:44:35.143",
"Id": "495391",
"Score": "1",
"body": "Amazing ! Thanks for this sharing :)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T16:01:32.447",
"Id": "495392",
"Score": "0",
"body": "But in my case I wanted to get the SKU of the segment...and not the tuple (end-->start)..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T16:03:59.183",
"Id": "495393",
"Score": "2",
"body": "@AchrafBentabib That was not obvious from your question, because you did not show us the part where you actually use your functions. This is definitely also possible, give me a few minutes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T16:14:52.007",
"Id": "495396",
"Score": "1",
"body": "@AchrafBentabib Added how you can add information to the edges and get back this information instead of the names of the nodes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T18:57:29.287",
"Id": "495427",
"Score": "0",
"body": "Thanks you very much, that match exactly what I wanted in few lines ! Compare to my code it's definitly much radier, thx"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T19:10:59.367",
"Id": "495428",
"Score": "0",
"body": "Finally I have one other question. What about finding all path with repeated nodes, but without repeating the same segment ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T11:20:36.327",
"Id": "495532",
"Score": "0",
"body": "See the new post : https://codereview.stackexchange.com/questions/251648/path-finder-for-network-link-wiring-improvment"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T13:33:51.133",
"Id": "251599",
"ParentId": "251589",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "251599",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T07:42:06.500",
"Id": "251589",
"Score": "7",
"Tags": [
"python",
"graph"
],
"Title": "Path finder for network link wiring"
}
|
251589
|
<p>I was asked to write a program that sorts three strings alphabetically using <strong>only if-else</strong> (no sorting algorithms, usage of arrays whatsover). I'm fairly new to C++ programming but I've come up with this program and would like to know if there's any way to make this more efficient while only using if-else? Any help or suggestions would be appreciated. Thank you!</p>
<pre><code>#include <iostream>
using namespace std;
int main()
{
string word1, word2, word3;
string temp;
cout << "Enter three words separated by a space: ";
cin >> word1 >> word2 >> word3;
if (word1 > word2 && word1 > word3 && word3 > word2)
{
temp = word1;
word1 = word2;
word2 = word3;
word3 = temp;
}
else if (word1 > word2 && word1 > word3 && word2 > word3)
{
temp = word1;
word1 = word3;
word3 = temp;
}
else if (word2 > word1 && word2 > word3 && word1 > word3)
{
temp = word2;
word1 = word3;
word2 = word1;
word3 = temp;
}
else if (word2 > word1 && word2 > word3 && word3 > word1)
{
temp = word2;
word2 = word3;
word3 = temp;
}
else if (word3 > word1 && word3 > word2 && word1 > word2)
{
temp = word1;
word1 = word2;
word2 = temp;
}
cout << "The correct sort is " << word1 << ", " << word2 << ", " << word3 << endl;
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T09:04:38.593",
"Id": "495340",
"Score": "0",
"body": "This code does run, I've already tested it. And this code works perfectly fine, as mentioned it's supposed to sort the strings in alphabetical order. What my lecturer showed as an example was using if-else to sort 2 strings and we were then tasked to use the same concept to sort 3 strings. But I want to know if there's any way to improve this code to make it less bulky."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T11:03:32.450",
"Id": "495348",
"Score": "0",
"body": "@Wale c++ string class has an overload for comparison operators that internally call the `compare` method of that class which performs a lexicographical compare on the strings."
}
] |
[
{
"body": "<p>You could create a function that automatically places two of the strings.</p>\n<pre><code>#include <iostream>\nusing namespace std;\n\n//returns true if correction was needed\nbool correctArrange(string& a, string& b){\n if (a <= b) return false;\n auto temp = a;\n a = b;\n b = temp;\n return true;\n}\n\nint main()\n{\n string word1, word2, word3;\n string temp;\n \n cout << "Enter three words separated by a space: ";\n cin >> word1 >> word2 >> word3; \n\n for (bool changed = true;changed;){\n changed = correctArrange(word1, word2) | correctArrange(word2, word3);\n }\n \n cout << "The correct sort is " << word1 << ", " << word2 << ", " << word3 << endl;\n}\n</code></pre>\n<p>Basically implementing bubble-sort algorithm.</p>\n<p>If you're not allowed even the lowly for-loop, then you can unroll it.</p>\n<pre><code>int main()\n{\n string word1, word2, word3;\n string temp;\n \n cout << "Enter three words separated by a space: ";\n cin >> word1 >> word2 >> word3; \n\n correctArrange(word1, word2);\n if (correctArrange(word2, word3))\n correctArrange(word1, word2);\n \n cout << "The correct sort is " << word1 << ", " << word2 << ", " << word3 << endl;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T11:30:03.750",
"Id": "495350",
"Score": "0",
"body": "I'm not even sure that OP is allowed to use functions, but sure I can add that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T11:34:23.380",
"Id": "495351",
"Score": "0",
"body": "Welcome to CodeReview@SE. Your *correct arrangement* primitive looks much like the one used in [sorting networks](https://en.m.wikipedia.org/wiki/Sorting_network). (*correctly arrange*?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T12:44:10.030",
"Id": "495361",
"Score": "0",
"body": "Hello, thank you for your response! However I'm a newbie in this so there's some parts I don't really understand, for instance can I know why the bitwise operator | is used here? And why is changed set to false in the if statement? Thanks again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T12:54:16.800",
"Id": "495363",
"Score": "0",
"body": "In the function: think of the return-value as \"if correct\", if the function is already correct, you don't need to do anything else. This additional information can then be used elsewhere! Since the return is a boolean you can use either the bitwise or word-wise `or` - either will work here. `0x01 | 0x01 == 0x01 || 0x00`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T13:02:52.877",
"Id": "495366",
"Score": "1",
"body": "@AlexShirley `main()` is special in C++ and C99+: `return 0;` is implicit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T13:22:38.493",
"Id": "495371",
"Score": "0",
"body": "@AlexShirley Ahh I see. Thank you for your explanation! :)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T10:08:33.170",
"Id": "251595",
"ParentId": "251590",
"Score": "0"
}
},
{
"body": "<ol>\n<li><p>Your indentation is off. <code>if</code> should be at the same level as the corresponding <code>else</code> or <code>else if</code>, their bodies being indented once. Don't wander all the way to the right.</p>\n</li>\n<li><p>You are missing the include for <code>std::string</code>, <code><string></code>.</p>\n</li>\n<li><p><code>using namespace std;</code> seems convenient, right? Unfortunately, throwing everything and the kitchen sink into the global namespace and praying it works is error-prone.<br />\nSee "<em><a href=\"//stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Why is “using namespace std;” considered bad practice?</a></em>".</p>\n<p>I wouldn't even use a using-declaration here, though that would be unproblematic at least.</p>\n</li>\n<li><p><code>return 0;</code> is implicit for <code>main()</code>. (And only for that function.)</p>\n</li>\n<li><p>You never test whether reading (and/or writing) succeeds. At least that's pretty harmless in your program. Still, consider ending with:</p>\n<pre><code> return !!std::cin || !!std::cout;\n</code></pre>\n</li>\n<li><p>Swapping is often far more efficient than copying. Consider using <code>a.swap(b)</code> or the more generic <code>using std::swap; swap(a, b);</code> two-step, the latter is in <code><utility></code>.</p>\n</li>\n<li><p>Only use <code>std::endl</code> when you need to flush the stream. Actually, belay that, be explicit and use <code>std::flush</code>.<br />\nHint: <code>std::cin</code> and <code>std::cout</code> are tied, which you already take advantage of with your prompt. Also, when the program ends the standard streams are flushed.<br />\nSee "<em><a href=\"//stackoverflow.com/questions/5492380/what-is-the-c-iostream-endl-fiasco\">What is the C++ iostream <code>endl</code> fiasco?</a></em>".</p>\n</li>\n<li><p>Comparing strings is likely to be comparatively expensive. Thus, compare two strings, and then make different decisions depending on the outcome.</p>\n</li>\n<li><p>An alternative to considering each case separately is writing a <a href=\"//en.wikipedia.org/wiki/Sorting_network\" rel=\"nofollow noreferrer\">sorting-network</a>.<br />\nYou would be well-advised to abstract a conditional swap into its own function if you go that way:</p>\n<pre><code>void sort2(std::string& a, std::string& b) noexcept {\n if (b < a)\n b.swap(a);\n}\n</code></pre>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T14:30:33.150",
"Id": "495381",
"Score": "0",
"body": "Hi! Thanks for your response.\n2. Can I know when should I use #include <string>? Because my program ran normally without this header... \n4. Does this mean I don't need to write return 0 for my main function?\n5. Can I know how the testing reading (and/or writing) works?\n6. Unfortunately I'm not allowed to use anything other than if-else, oof. But thanks for letting me know about the swap!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T15:15:20.010",
"Id": "495388",
"Score": "0",
"body": "re2: Whenever you use something from a header, include it. Don't depend on your implementation today recursively including header X when you include Y unless contractual, that's brittle. re4: Yes. re5: [See a reference on streams](https://en.cppreference.com/w/cpp/io/basic_ios/operator_bool). re6: You are using plenty more. Anyway, how about keeping strictly to those handicaps for one version, and doing it right for another. Whether to submit both depends on the teacher."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T06:21:16.593",
"Id": "495510",
"Score": "0",
"body": "thanks for your explanations, I really appreciate it :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T13:33:23.423",
"Id": "251598",
"ParentId": "251590",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "251595",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T07:44:37.117",
"Id": "251590",
"Score": "1",
"Tags": [
"c++",
"strings",
"sorting"
],
"Title": "Sorting string with if-else"
}
|
251590
|
<p><strong>Context</strong>: I want to check if notice of assessment are valid.
<strong>What I did</strong>: I wrote some code to extract textual information from PDF (with OCR on image contained in the PDF): <code>numfiscal</code> and <code>refavis</code></p>
<p>What I expose in this code: based on the website of government I check validity of my notice of assessment doing a post request with relatives numfiscal and refavis.</p>
<p>What are your recommendations for this code ? (Any advice will be good since I am mainly autodidact with really little experience in coding practices).</p>
<pre><code>import requests
import lxml.html
from pprint import pprint
import re
from ..config import myconfig # My config for proxy,
from ..utilities.utils import normalize_text,lazyproperty,write_csv,timer #See the end i put the functions
class ForbiddenAccess(Exception):
pass
class IMPOTCrawler():
impot_url = 'https://cfsmsp.impots.gouv.fr/secavis/faces/commun/index.jsf'
def __init__(self,numfiscal,refavis):
self.numfiscal = numfiscal
self.refavis = refavis
self.data = {'numfiscal':self.numfiscal,'refavis':self.refavis}
def _request(self):
proxies = {"http": myconfig.PROXY_HTTP,"https": myconfig.PROXY_HTTPS}
data = {'j_id_7:spi':self.numfiscal,'j_id_7:num_facture':self.refavis,'j_id_7_SUBMIT':'1','javax.faces.ViewState':'RxJe/1JKTJSr3aiM3H9DqZq0DrwqEXsY7Rw4eLRgEBsCF1IALJGqVgWTaQkiKbbdcGDWW774BWUCa/+j2CDznhw1/3bxJteY6ZCui66yNevhkej4xuyrFMte5KQnKORt9JZrOQ==','j_id_7:j_id_l':'Valider'}
req = requests.post(IMPOTCrawler.impot_url,data=data,proxies=proxies)
html = req.text
self.req_ok = req.ok
self.data.update({'req_ok':self.req_ok})
return req.ok, html
@lazyproperty
def html_content(self):
_, html = self._request()
return html
def is_valid(self):
if re.findall("Adresse déclarée au",self.html_content):
self.data.update({"is_valid__online":True,"Request_message":None})
return True
elif re.findall("La référence saisie ne correspond pas à un avis présent dans la base.",self.html_content):
self.data.update({"is_valid__online":False,"Request_message":"Avis non présent dans la base gouvernementale"})
return False
elif re.findall("Vous devez vérifier les identifiants saisis.",self.html_content):
self.data.update({"is_valid__online":False,"Request_message":"Mauvais identifiants"})
return False
elif re.findall("Accès Interdit",self.html_content):
raise ForbiddenAccess("Accès interdit: trop de requêtes")
def parse_info(self):
valid = self.is_valid()
if not valid:
return
tree = lxml.html.fromstring(self.html_content)
xpath = "//div[@id='conteneur']//div[@id='principal']//table"
tab = tree.xpath(xpath)[0]
tbody = tab.find('tbody')
rows = tbody.findall("tr")
infos = []
infosdic = {}
#Retrieve informations
for i,row in enumerate(rows):
cols = row.findall("td")
for j,col in enumerate(cols):
text = col.text
if text:
normtext = re.sub('[\n|\t]','',normalize_text(text).lower())
text = re.sub('[\n|\t]','',text)
infos.append(text)
infosdic[(i,j)]=text
schema = {'NOM_DECL_1':(1,1),'NOM_NAIS_DECL_1':(2,1),'PRENOM_DECL_1':(3,1),'DATE_NAIS_DECL_1':(4,1),
'NOM_DECL_2':(1,2),'NOM_NAIS_DECL_2':(2,2),'PRENOM_DECL_2':(3,2),'DATE_NAIS_DECL_2':(4,2)}
parsed_infos = {key:infosdic[value] for key,value in schema.items()}
for i,elt in enumerate(infos):
if "Adresse déclarée au" in elt:
if "Date de mise en recouvrement de " in infos[i+5]:
parsed_infos['ADRESSE'] = "{}, {}".format(infos[i+1],infos[i+4])
else:
parsed_infos['ADRESSE'] = "{}, {}".format(infos[i+1],infos[i+4],infos[i+6])
if "Revenu fiscal de référence" in elt:
parsed_infos['REV_FISC'] = normalize_text(infos[i+1])
self.data.update(parsed_infos)
return parsed_infos
</code></pre>
<h2><code>utilities.utils</code></h2>
<pre><code>def normalize_text(input_str):
import unicodedata
nfd_form = unicodedata.normalize('NFD', input_str)
return nfd_form.encode('ascii','ignore').decode('ascii')
def write_csv(filepath,dic):
headers = list(dic.keys())
with open(filepath,'a',newline='') as f:
f_csv = csv.DictWriter(f,headers)
if f.tell()==0:
f_csv.writeheader()
f_csv.writerow(dic)
def read_csv(filepath,colname=None):
with open(filepath) as f:
f_csv =csv.DictReader(f)
res = []
if colname:
for row in f_csv:
res.append(row[colname])
else:
for row in f_csv:
res.append(row)
return res
def timer(method):
import time
def wrapper(*args, **kwargs):
start = time.time()
result = method(*args, **kwargs) # note the function call!
end = time.time()
print('Elapsed time for: {} is: {} s'.format(method.__name__,(end-start)))
return result
return wrapper
Edit: Project on: https://github.com/laurent-pincemaille/Impots-ocr
</code></pre>
|
[] |
[
{
"body": "<h2>Error checking</h2>\n<pre><code> req = requests.post(IMPOTCrawler.impot_url,data=data,proxies=proxies)\n self.req_ok = req.ok\n self.data.update({'req_ok':self.req_ok})\n return req.ok, html\n</code></pre>\n<p>First of all, you're passing around <code>ok</code> in at least three places: <code>self.data</code>, the first element of the return tuple, and <code>self.req_ok</code>. That "three" should go down to "zero". It's not a great idea to make a surprise side-effect of <code>_request</code> that modifies <code>self</code>, and it's generally a better idea to use the Python exception-handling system instead of passing around error values. To this end, rather than paying attention to <code>req.ok</code>, simply call <code>req.raise_for_status()</code>. If you need to handle an exception that results, then do so with a <code>try / except</code>.</p>\n<p>Second of all, you're actually just dropping your error status:</p>\n<pre><code> _, html = self._request()\n</code></pre>\n<p>which you shouldn't. Errors matter, particularly with network operations.</p>\n<h2>data</h2>\n<p>What is <code>self.data</code>? So far it looks like a random grab-bag of unrelated things that you write to and never read from. Can this just go away?</p>\n<h2>Proxies</h2>\n<p>Consider saving a <code>requests.session</code> to your crawler object, and setting its proxies only once via its <code>proxies</code> attribute during your <code>__init__</code>.</p>\n<h2>Silent failure</h2>\n<p>Are you <em>sure</em> that</p>\n<pre><code>def parse_info(self):\n valid = self.is_valid()\n if not valid:\n return \n</code></pre>\n<p>should silently fail, without logging anything or even returning a boolean?</p>\n<h2>Regular expression precompilation</h2>\n<p>You use</p>\n<pre><code>re.sub('[\\n|\\t]'\n</code></pre>\n<p>in a method, in a doubly-nested loop. This is a good candidate for <code>re.compile</code> in static class scope.</p>\n<h2>Formatting</h2>\n<p>Is this:</p>\n<pre><code>parsed_infos['ADRESSE'] = "{}, {}".format(infos[i+1],infos[i+4],infos[i+6])\n</code></pre>\n<p>correct? It looks like you have one too few fields in your format string.</p>\n<h2>Generators</h2>\n<pre><code>def read_csv(filepath,colname=None):\n with open(filepath) as f:\n f_csv =csv.DictReader(f)\n res = []\n if colname:\n for row in f_csv:\n res.append(row[colname])\n else:\n for row in f_csv:\n res.append(row)\n\n return res \n</code></pre>\n<p>can become</p>\n<pre><code>def read_csv(filepath, colname=None):\n with open(filepath) as f:\n f_csv = csv.DictReader(f)\n if colname:\n yield from (row[colname] for row in f_csv)\n else:\n yield from f_csv\n</code></pre>\n<h2>Parens</h2>\n<pre><code>format(method.__name__,(end-start)))\n</code></pre>\n<p>can lose the inner-most parens.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-09T12:37:49.580",
"Id": "495999",
"Score": "0",
"body": "Thank you a lot for your advices, it is very valuable for me!\n My self.data register all informations that i get after doing the \"post\" request (data retrieved from the request (like fiscal revenue etc...), as metadata about success/failure of the request with the reasons ) like this i can retrieve and analyze later the informations (from the object). So i do need to store rhis req.ok. I will put a link of my github project to clear some points! However i will integrate the other corrections you pointed out :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T02:17:33.030",
"Id": "251633",
"ParentId": "251591",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T08:37:36.760",
"Id": "251591",
"Score": "5",
"Tags": [
"python",
"python-3.x"
],
"Title": "Web Crawler for notice of assessment retrieval"
}
|
251591
|
<p>I currently have the following piece of code in place that attempts to find matches within a list, based on a priority system:</p>
<pre><code>possible_combinations = ["ABC", "AB", "A", "D"]
if len(possible_combinations) >= 1:
chosen_combination = [comb for comb in possible_combinations if ("A" in comb) and ("C" in comb)]
if (len(chosen_combination) == 0):
chosen_combination = [comb for comb in possible_combinations if ("A" in comb)]
if (len(chosen_combination) == 0):
chosen_combination = [comb for comb in possible_combinations if ("C" in comb)]
if (len(chosen_combination) == 0):
raise ValueError(f"No match found.")
print(chosen_combination)
['ABC']
</code></pre>
<p>Is there any way I could refactor this code to get rid of these if-statements, and thereby make my code look nicer?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T17:48:44.013",
"Id": "495420",
"Score": "1",
"body": "perhaps explain why/what, there might be completely different way to solve the problem"
}
] |
[
{
"body": "<p>You could do something like this:</p>\n<pre><code>possible_combinations = ["ABC", "AB", "A", "D"]\ncombs = [("A","C"),("A",),("C",)]\n\nfor comb in combs:\n chosen_comb = [x for x in possible_combinations if all([y in x for y in comb])]\n if len(chosen_comb) > 0:\n break\n\nprint(chosen_comb)\n \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T18:33:01.487",
"Id": "495423",
"Score": "4",
"body": "Are you sure that this: `(\"A\",\"C\"),(\"A\"),(\"C\")` is your intent? The first parens make a tuple, and the second and third do not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T19:37:16.993",
"Id": "495434",
"Score": "0",
"body": "It doesn't really matter here, but you are right. What I meant was ```[(\"A\",\"C\"),(\"A\",),(\"C\",)]```. I corrected it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T08:39:59.283",
"Id": "495517",
"Score": "0",
"body": "Looks quite nice. Thx!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T18:01:27.587",
"Id": "251608",
"ParentId": "251607",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "251608",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T17:22:53.927",
"Id": "251607",
"Score": "2",
"Tags": [
"python",
"python-3.x"
],
"Title": "Multiple if-statements with overwriting lists"
}
|
251607
|
<p>I did another challenge by from Wes Bos JS course. This is my version, and I'll also post his version. Please let me know which one you think is better, thanks.</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>const inbox = document.querySelector('.inbox');
let firstIndex = -1;
let shiftPressed = false;
function getIndex(parent, child) {
return Array.from(parent.children).indexOf(child);
}
inbox.addEventListener('change', e => {
const checkbox = e.target.closest('input[type="checkbox"]');
if (!checkbox) return;
const parent = checkbox.parentNode;
const grandParent = parent.parentNode;
if (!shiftPressed) {
firstIndex = getIndex(grandParent, parent);
} else {
const secondIndex = getIndex(grandParent, parent);
const grandChildren = grandParent.children;
const [minIdx, maxIdx] = [Math.min(firstIndex, secondIndex), Math.max(firstIndex, secondIndex)];
for (let idx = minIdx + 1; idx < maxIdx; idx++) {
const itemDiv = grandChildren.item(idx);
const itemCheckbox = itemDiv.querySelector('input[type="checkbox"]');
itemCheckbox.checked = true;
}
firstIndex = -1;
shiftPressed = false;
}
});
window.addEventListener('keydown', e => {
if (e.shiftKey && firstIndex !== -1) {
shiftPressed = true;
}
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
font-family: sans-serif;
background: #ffc600;
}
.inbox {
max-width: 400px;
margin: 50px auto;
background: white;
border-radius: 5px;
box-shadow: 10px 10px 0 rgba(0, 0, 0, 0.1);
}
.item {
display: flex;
align-items: center;
border-bottom: 1px solid #F1F1F1;
}
.item:last-child {
border-bottom: 0;
}
input:checked+p {
background: #F9F9F9;
text-decoration: line-through;
}
input[type="checkbox"] {
margin: 20px;
}
p {
margin: 0;
padding: 20px;
transition: background 0.2s;
flex: 1;
font-family: 'helvetica neue';
font-size: 20px;
font-weight: 200;
border-left: 1px solid #D1E2FF;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="inbox">
<div class="item">
<input type="checkbox">
<p>This is an inbox layout.</p>
</div>
<div class="item">
<input type="checkbox">
<p>Check one item</p>
</div>
<div class="item">
<input type="checkbox">
<p>Hold down your Shift key</p>
</div>
<div class="item">
<input type="checkbox">
<p>Check a lower item</p>
</div>
<div class="item">
<input type="checkbox">
<p>Everything in between should also be set to checked</p>
</div>
<div class="item">
<input type="checkbox">
<p>Try to do it without any libraries</p>
</div>
<div class="item">
<input type="checkbox">
<p>Just regular JavaScript</p>
</div>
<div class="item">
<input type="checkbox">
<p>Good Luck!</p>
</div>
<div class="item">
<input type="checkbox">
<p>Don't forget to tweet your result!</p>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>And this is his JS code:</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>const checkboxes = document.querySelectorAll('.inbox input[type="checkbox"]');
let lastChecked;
function handleCheck(e) {
// Check if they had the shift key down
// AND check that they are checking it
let inBetween = false;
if (e.shiftKey && this.checked) {
// go ahead and do what we please
// loop over every single checkbox
checkboxes.forEach(checkbox => {
console.log(checkbox);
if (checkbox === this || checkbox === lastChecked) {
inBetween = !inBetween;
console.log('Starting to check them in between!');
}
if (inBetween) {
checkbox.checked = true;
}
});
}
lastChecked = this;
}
checkboxes.forEach(checkbox => checkbox.addEventListener('click', handleCheck));</code></pre>
</div>
</div>
</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T18:03:42.160",
"Id": "251609",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Holding shift to check multiple items in JS"
}
|
251609
|
<p>I am new to Python and tkinter and I made software which checks Windows computer's usage of: CPU, RAM, Storage, Upload Speed, Download Speed, Latency and Ping. If the output exceeds the input, an automated email will be sent. All tasks are scheduled in minute(s).</p>
<p>Actually, the software is running and doing its job but once I clicked <strong>Start Task</strong> the GUI will be unresponsive and it's showing <strong>Not Responding</strong> because of <strong>schedule while loop</strong>, while the code is perfectly running in the background. I know it because during the test, I am receiving warning emails as expected. I even tested it using one button which should print <strong>Hello World</strong> each 1 minute , again <strong>schedule while loop</strong> is freezing the GUI while its outputting Hello World.</p>
<p>Any hints and suggestions would be very kind and precious.</p>
<p>Thank you very much.</p>
<h1>Code</h1>
<p>This uses Python 3.8.5.</p>
<p>The GUI was generated using PAGE RAD with a few modifications I made.</p>
<p>To send an automated email, you should not use 2-Factor Authentication or it will fail to send.</p>
<p><strong>Usage</strong> : Simply input 1 in all fields of <strong>System Preferences</strong> and in <strong>Email Preferences</strong> input your SMTP, email address, password and again your email address or any other one to receive alert or warning emails.</p>
<pre><code>import sys
import tkinter as tk
from tkinter import DoubleVar, IntVar, StringVar
import tkinter.ttk as ttk
import schedule
import time
import psutil, shutil
from win10toast import ToastNotifier
import speedtest
from pythonping import ping
import email.message
import smtplib
import webbrowser
def vp_start_gui():
global val, w, root
root = tk.Tk()
top = Toplevel1 (root)
init(root, top)
root.mainloop()
w = None
def init(top, gui, *args, **kwargs):
global w, top_level, root
w = gui
top_level = top
root = top
def destroy_window():
global top_level
top_level.destroy()
top_level = None
def create_Toplevel1(rt, *args, **kwargs):
global w, w_win, root
root = rt
w = tk.Toplevel(root)
top = Toplevel1(w)
init(w, top, *args, **kwargs)
return (w, top)
def destroy_Toplevel1():
global w
w.destroy()
w = None
class Toplevel1:
def __init__(self, top=None):
_bgcolor = '#d9d9d9' # X11 color: 'gray85'
_fgcolor = '#000000' # X11 color: 'black'
_compcolor = '#d9d9d9' # X11 color: 'gray85'
_ana1color = '#d9d9d9' # X11 color: 'gray85'
_ana2color = '#ececec' # Closest X11 color: 'gray92'
self.style = ttk.Style()
if sys.platform == "win32":
self.style.theme_use('winnative')
self.style.configure('.',background=_bgcolor)
self.style.configure('.',foreground=_fgcolor)
self.style.configure('.',font="TkDefaultFont")
self.style.map('.',background=
[('selected', _compcolor), ('active',_ana2color)])
top.geometry("500x620+359+59")
top.minsize(120, 1)
top.maxsize(1370, 749)
top.resizable(0, 0)
top.title("System Watchdog")
top.configure(background="#d9d9d9")
top.configure(highlightbackground="#d9d9d9")
top.configure(highlightcolor="black")
cpu = IntVar()
ram = DoubleVar()
storage = IntVar()
Ping = StringVar()
upload_sp = DoubleVar()
download_sp = DoubleVar()
latency = DoubleVar()
task_timer = IntVar()
smtp = StringVar()
sender_email = StringVar()
sender_pwd = StringVar()
receiver_email = StringVar()
n = ToastNotifier()
def cpu_check():
cpu_usage = psutil.cpu_percent()
return cpu_usage < cpu.get()
def disc_space_check():
disk_usage = shutil.disk_usage("/")
disk_total = disk_usage.total
disk_free = disk_usage.used
threshold = disk_free / disk_total * 100
return threshold > storage.get()
def available_memory_check():
available = psutil.virtual_memory().available
available_in_GB = available / 1000000000
return available_in_GB >= ram.get()
def upload_speed():
st = speedtest.Speedtest()
upload_s = round(st.upload()/1000000, 2)
return upload_s >= upload_sp.get()
def download_speed():
st = speedtest.Speedtest()
download_s = round(st.download()/1000000, 2)
return download_s >= download_sp.get()
def latency_check():
st = speedtest.Speedtest()
st.get_best_server()
return st.results.ping <= latency.get()
def ping_ip():
p = Ping.get()
l = list(ping(p))
return str(l[0]).startswith('Reply')
def generate_email(sender, receiver, subject, body):
message = email.message.EmailMessage()
message['Subject'] = subject
message['From'] = sender
message['To'] = receiver
message.set_content(body)
return message
def send_email(package):
mail_server = smtplib.SMTP(smtp.get())
mail_server.starttls()
mail_server.login(sender_email.get(), sender_pwd.get())
mail_server.send_message(package)
mail_server.quit()
def email_warning(warning):
sender = sender_email.get()
receiver = receiver_email.get()
subject = warning
body = "Alert! Check Your System ASAP!"
message = generate_email(sender, receiver, subject, body)
send_email(message)
def mailing():
if not cpu_check():
n.show_toast("Warning!", "CPU Usage is greater than " + " " + str(cpu.get()), duration = 10)
subject = 'Alert! - CPU Usage is greater than ' + ' ' + str(cpu.get())
email_warning(subject)
if not disc_space_check():
n.show_toast("Warning!", "Available disk space is less than " + ' ' + str(storage.get()) + '!', duration = 10)
subject = "Alert! - Available disk space is less than " + ' ' + str(storage.get()) + '!'
email_warning(subject)
if not available_memory_check():
n.show_toast("Warning!", "Available memory is less than " + ' ' + str(ram.get()) + '!', duration = 10)
subject = "Alert! - Available memory is less than " + ' ' + str(ram.get()) + '!'
email_warning(subject)
if not upload_speed():
n.show_toast("Warning!", "Low upload speed! Upload speed is less than " + ' ' + str(upload_sp.get()))
subject = "Alert! - Low upload speed! Upload speed is less than " + ' ' + str(upload_sp.get())
email_warning(subject)
if not download_speed():
n.show_toast("Warning!", "Low download speed! Download speed is less than " + ' ' + str(download_sp.get()))
subject = "Alert! - Low download speed! Download speed is less than " + ' ' + str(download_sp.get())
email_warning(subject)
if not latency_check():
n.show_toast("Warning!", "High Latency! Latency is higher than " + ' ' + str(latency.get()))
subject = "Alert! - High Latency! Latency is higher than " + ' ' + str(latency.get())
email_warning(subject)
if not ping_ip():
n.show_toast("Warning!", "Unreachable IP, Request timed out!")
subject = "Alert! - Unreachable IP, Request timed out!"
email_warning(subject)
def linked_in():
url='https://linkedin.com/in/cyber-services'
webbrowser.open_new_tab(url)
def git_hub():
url='https://github.com/IT-Support-L2'
webbrowser.open_new_tab(url)
def paypal():
url='https://www.paypal.com/paypalme/HamdiBouaskar'
webbrowser.open_new_tab(url)
def StartTask():
schedule.every(task_timer.get()).minutes.do(cpu_check)
schedule.every(task_timer.get()).minutes.do(disc_space_check)
schedule.every(task_timer.get()).minutes.do(available_memory_check)
schedule.every(task_timer.get()).minutes.do(upload_speed)
schedule.every(task_timer.get()).minutes.do(download_speed)
schedule.every(task_timer.get()).minutes.do(latency_check)
schedule.every(task_timer.get()).minutes.do(ping_ip)
schedule.every(task_timer.get()).minutes.do(mailing)
while True:
schedule.run_pending()
time.sleep(1)
def StopTask():
schedule.cancel_job(StartTask)
self.TSeparator1 = ttk.Separator(top)
self.TSeparator1.place(x=30, y=40, width=442)
self.style.configure('TNotebook.Tab', background=_bgcolor)
self.style.configure('TNotebook.Tab', foreground=_fgcolor)
self.style.map('TNotebook.Tab', background=
[('selected', _compcolor), ('active',_ana2color)])
self.TNotebook1 = ttk.Notebook(top)
self.TNotebook1.place(x=25, y=53, height=526, width=450)
self.TNotebook1_t1_1 = tk.Frame(self.TNotebook1)
self.TNotebook1.add(self.TNotebook1_t1_1, padding=3)
self.TNotebook1.tab(0, text="System Preferences", compound="left"
,underline="-1", )
self.TNotebook1_t1_1.configure(borderwidth="1")
self.TNotebook1_t1_1.configure(relief="sunken")
self.TNotebook1_t1_1.configure(background="#353535")
self.TNotebook1_t1_1.configure(highlightbackground="#d9d9d9")
self.TNotebook1_t1_1.configure(highlightcolor="black")
self.TNotebook1_t2_1 = tk.Frame(self.TNotebook1)
self.TNotebook1.add(self.TNotebook1_t2_1, padding=3)
self.TNotebook1.tab(1, text="Email Preferences", compound="left"
,underline="-1", )
self.TNotebook1_t2_1.configure(borderwidth="1")
self.TNotebook1_t2_1.configure(background="#000000")
self.TNotebook1_t2_1.configure(highlightbackground="#d9d9d9")
self.TNotebook1_t2_1.configure(highlightcolor="black")
self.TNotebook1_t3_1 = tk.Frame(self.TNotebook1)
self.TNotebook1.add(self.TNotebook1_t3_1, padding=3)
self.TNotebook1.tab(2, text="Help",compound="left",underline="-1",)
self.TNotebook1_t3_1.configure(background="#d9d9d9")
self.TNotebook1_t3_1.configure(highlightbackground="#d9d9d9")
self.TNotebook1_t3_1.configure(highlightcolor="black")
self.TNotebook1_t4_1 = tk.Frame(self.TNotebook1)
self.TNotebook1.add(self.TNotebook1_t4_1, padding=3)
self.TNotebook1.tab(3, text="Follow me", compound="left", underline="-1")
self.TNotebook1_t4_1.configure(background="#d9d9d9")
self.TNotebook1_t4_1.configure(highlightbackground="#d9d9d9")
self.TNotebook1_t4_1.configure(highlightcolor="black")
self.Labelframe1 = tk.LabelFrame(self.TNotebook1_t1_1)
self.Labelframe1.place(x=10, y=10, height=48, width=421)
self.Labelframe1.configure(relief='ridge')
self.Labelframe1.configure(font="-family {Segoe UI} -size 9 -weight bold")
self.Labelframe1.configure(foreground="black")
self.Labelframe1.configure(relief="ridge")
self.Labelframe1.configure(text='''CPU Check''')
self.Labelframe1.configure(background="#d9d9d9")
self.Labelframe1.configure(highlightbackground="#d9d9d9")
self.Labelframe1.configure(highlightcolor="black")
self.CPU_Entry = tk.Entry(self.Labelframe1)
self.CPU_Entry.place(x=290, y=15, height=27, width=104
, bordermode='ignore')
self.CPU_Entry.configure(background="#c1ffc1")
self.CPU_Entry.configure(cursor="")
self.CPU_Entry.configure(disabledforeground="#a3a3a3")
self.CPU_Entry.configure(font="TkFixedFont")
self.CPU_Entry.configure(foreground="#000000")
self.CPU_Entry.configure(highlightbackground="#d9d9d9")
self.CPU_Entry.configure(highlightcolor="black")
self.CPU_Entry.configure(insertbackground="black")
self.CPU_Entry.configure(justify='center')
self.CPU_Entry.configure(selectbackground="blue")
self.CPU_Entry.configure(selectforeground="white")
self.CPU_Entry.configure(textvariable=cpu)
self.Label4 = tk.Label(self.Labelframe1)
self.Label4.place(x=60, y=20, height=14, width=93, bordermode='ignore')
self.Label4.configure(activebackground="#f9f9f9")
self.Label4.configure(activeforeground="black")
self.Label4.configure(background="#d9d9d9")
self.Label4.configure(disabledforeground="#a3a3a3")
self.Label4.configure(foreground="#000000")
self.Label4.configure(highlightbackground="#d9d9d9")
self.Label4.configure(highlightcolor="black")
self.Label4.configure(text='''Enter CPU''')
self.Labelframe2 = tk.LabelFrame(self.TNotebook1_t1_1)
self.Labelframe2.place(x=10, y=70, height=48, width=421)
self.Labelframe2.configure(relief='ridge')
self.Labelframe2.configure(font="-family {Segoe UI} -size 9 -weight bold")
self.Labelframe2.configure(foreground="black")
self.Labelframe2.configure(relief="ridge")
self.Labelframe2.configure(text='''RAM Check''')
self.Labelframe2.configure(background="#d9d9d9")
self.Labelframe2.configure(highlightbackground="#d9d9d9")
self.Labelframe2.configure(highlightcolor="black")
self.Label5 = tk.Label(self.Labelframe2)
self.Label5.place(x=60, y=20, height=14, width=93, bordermode='ignore')
self.Label5.configure(activebackground="#f9f9f9")
self.Label5.configure(activeforeground="black")
self.Label5.configure(background="#d9d9d9")
self.Label5.configure(disabledforeground="#a3a3a3")
self.Label5.configure(foreground="#000000")
self.Label5.configure(highlightbackground="#d9d9d9")
self.Label5.configure(highlightcolor="black")
self.Label5.configure(text='''Enter RAM''')
self.RAM_Entry = tk.Entry(self.Labelframe2)
self.RAM_Entry.place(x=287, y=16, height=27, width=104, bordermode='ignore')
self.RAM_Entry.configure(background="#c1ffc1")
self.RAM_Entry.configure(disabledforeground="#a3a3a3")
self.RAM_Entry.configure(font="TkFixedFont")
self.RAM_Entry.configure(foreground="#000000")
self.RAM_Entry.configure(highlightbackground="#d9d9d9")
self.RAM_Entry.configure(highlightcolor="black")
self.RAM_Entry.configure(insertbackground="black")
self.RAM_Entry.configure(justify='center')
self.RAM_Entry.configure(selectbackground="blue")
self.RAM_Entry.configure(selectforeground="white")
self.RAM_Entry.configure(textvariable=ram)
self.Labelframe3 = tk.LabelFrame(self.TNotebook1_t1_1)
self.Labelframe3.place(x=10, y=130, height=48, width=420)
self.Labelframe3.configure(relief='ridge')
self.Labelframe3.configure(font="-family {Segoe UI} -size 9 -weight bold")
self.Labelframe3.configure(foreground="black")
self.Labelframe3.configure(relief="ridge")
self.Labelframe3.configure(text='''Storage Check''')
self.Labelframe3.configure(background="#d9d9d9")
self.Labelframe3.configure(highlightbackground="#d9d9d9")
self.Labelframe3.configure(highlightcolor="black")
self.Label6 = tk.Label(self.Labelframe3)
self.Label6.place(x=60, y=20, height=14, width=103, bordermode='ignore')
self.Label6.configure(activebackground="#f9f9f9")
self.Label6.configure(activeforeground="black")
self.Label6.configure(background="#d9d9d9")
self.Label6.configure(disabledforeground="#a3a3a3")
self.Label6.configure(foreground="#000000")
self.Label6.configure(highlightbackground="#d9d9d9")
self.Label6.configure(highlightcolor="black")
self.Label6.configure(text='''Enter Storage''')
self.STORAGE_Entry = tk.Entry(self.Labelframe3)
self.STORAGE_Entry.place(x=287, y=16, height=27, width=104
, bordermode='ignore')
self.STORAGE_Entry.configure(background="#c1ffc1")
self.STORAGE_Entry.configure(disabledforeground="#a3a3a3")
self.STORAGE_Entry.configure(font="TkFixedFont")
self.STORAGE_Entry.configure(foreground="#000000")
self.STORAGE_Entry.configure(highlightbackground="#d9d9d9")
self.STORAGE_Entry.configure(highlightcolor="black")
self.STORAGE_Entry.configure(insertbackground="black")
self.STORAGE_Entry.configure(justify='center')
self.STORAGE_Entry.configure(selectbackground="blue")
self.STORAGE_Entry.configure(selectforeground="white")
self.STORAGE_Entry.configure(textvariable=storage)
self.Labelframe4 = tk.LabelFrame(self.TNotebook1_t1_1)
self.Labelframe4.place(x=10, y=190, height=48, width=420)
self.Labelframe4.configure(relief='ridge')
self.Labelframe4.configure(font="-family {Segoe UI} -size 9 -weight bold")
self.Labelframe4.configure(foreground="black")
self.Labelframe4.configure(relief="ridge")
self.Labelframe4.configure(text='''Ping / Reachability Check''')
self.Labelframe4.configure(background="#d9d9d9")
self.Labelframe4.configure(highlightbackground="#d9d9d9")
self.Labelframe4.configure(highlightcolor="black")
self.PING_Entry = tk.Entry(self.Labelframe4)
self.PING_Entry.place(x=160, y=16, height=27, width=234
, bordermode='ignore')
self.PING_Entry.configure(background="#c1ffc1")
self.PING_Entry.configure(disabledforeground="#a3a3a3")
self.PING_Entry.configure(font="TkFixedFont")
self.PING_Entry.configure(foreground="#000000")
self.PING_Entry.configure(highlightbackground="#d9d9d9")
self.PING_Entry.configure(highlightcolor="black")
self.PING_Entry.configure(insertbackground="black")
self.PING_Entry.configure(justify='center')
self.PING_Entry.configure(selectbackground="blue")
self.PING_Entry.configure(selectforeground="white")
self.PING_Entry.configure(textvariable=Ping)
self.Label12 = tk.Label(self.Labelframe4)
self.Label12.place(x=40, y=20, height=16, width=94, bordermode='ignore')
self.Label12.configure(activebackground="#f9f9f9")
self.Label12.configure(activeforeground="black")
self.Label12.configure(background="#d9d9d9")
self.Label12.configure(disabledforeground="#a3a3a3")
self.Label12.configure(foreground="#000000")
self.Label12.configure(highlightbackground="#d9d9d9")
self.Label12.configure(highlightcolor="black")
self.Label12.configure(text='''Enter IP Address''')
self.Labelframe5 = tk.LabelFrame(self.TNotebook1_t1_1)
self.Labelframe5.place(x=10, y=250, height=48, width=420)
self.Labelframe5.configure(relief='ridge')
self.Labelframe5.configure(font="-family {Segoe UI} -size 9 -weight bold")
self.Labelframe5.configure(foreground="black")
self.Labelframe5.configure(relief="ridge")
self.Labelframe5.configure(text='''Upload Speed Check''')
self.Labelframe5.configure(background="#d9d9d9")
self.Labelframe5.configure(highlightbackground="#d9d9d9")
self.Labelframe5.configure(highlightcolor="black")
self.UPLOAD_Entry = tk.Entry(self.Labelframe5)
self.UPLOAD_Entry.place(x=287, y=16, height=27, width=104
, bordermode='ignore')
self.UPLOAD_Entry.configure(background="#c1ffc1")
self.UPLOAD_Entry.configure(disabledforeground="#a3a3a3")
self.UPLOAD_Entry.configure(font="TkFixedFont")
self.UPLOAD_Entry.configure(foreground="#000000")
self.UPLOAD_Entry.configure(highlightbackground="#d9d9d9")
self.UPLOAD_Entry.configure(highlightcolor="black")
self.UPLOAD_Entry.configure(insertbackground="black")
self.UPLOAD_Entry.configure(justify='center')
self.UPLOAD_Entry.configure(selectbackground="blue")
self.UPLOAD_Entry.configure(selectforeground="white")
self.UPLOAD_Entry.configure(textvariable=upload_sp)
self.Label7 = tk.Label(self.Labelframe5)
self.Label7.place(x=30, y=20, height=14, width=133, bordermode='ignore')
self.Label7.configure(activebackground="#f9f9f9")
self.Label7.configure(activeforeground="black")
self.Label7.configure(background="#d9d9d9")
self.Label7.configure(disabledforeground="#a3a3a3")
self.Label7.configure(foreground="#000000")
self.Label7.configure(highlightbackground="#d9d9d9")
self.Label7.configure(highlightcolor="black")
self.Label7.configure(text='''Enter Upload Speed''')
self.Labelframe6 = tk.LabelFrame(self.TNotebook1_t1_1)
self.Labelframe6.place(x=10, y=370, height=48, width=420)
self.Labelframe6.configure(relief='ridge')
self.Labelframe6.configure(font="-family {Segoe UI} -size 9 -weight bold")
self.Labelframe6.configure(foreground="black")
self.Labelframe6.configure(relief="ridge")
self.Labelframe6.configure(text='''Latency Check''')
self.Labelframe6.configure(background="#d9d9d9")
self.Labelframe6.configure(highlightbackground="#d9d9d9")
self.Labelframe6.configure(highlightcolor="black")
self.Label8 = tk.Label(self.Labelframe6)
self.Label8.place(x=40, y=20, height=14, width=83, bordermode='ignore')
self.Label8.configure(activebackground="#f9f9f9")
self.Label8.configure(activeforeground="black")
self.Label8.configure(background="#d9d9d9")
self.Label8.configure(disabledforeground="#a3a3a3")
self.Label8.configure(foreground="#000000")
self.Label8.configure(highlightbackground="#d9d9d9")
self.Label8.configure(highlightcolor="black")
self.Label8.configure(text='''Enter Latency''')
self.LATENCY_Entry = tk.Entry(self.Labelframe6)
self.LATENCY_Entry.place(x=287, y=16, height=27, width=104
, bordermode='ignore')
self.LATENCY_Entry.configure(background="#c1ffc1")
self.LATENCY_Entry.configure(disabledforeground="#a3a3a3")
self.LATENCY_Entry.configure(font="TkFixedFont")
self.LATENCY_Entry.configure(foreground="#000000")
self.LATENCY_Entry.configure(highlightbackground="#d9d9d9")
self.LATENCY_Entry.configure(highlightcolor="black")
self.LATENCY_Entry.configure(insertbackground="black")
self.LATENCY_Entry.configure(justify='center')
self.LATENCY_Entry.configure(selectbackground="blue")
self.LATENCY_Entry.configure(selectforeground="white")
self.LATENCY_Entry.configure(textvariable=latency)
self.Labelframe11 = tk.LabelFrame(self.TNotebook1_t1_1)
self.Labelframe11.place(x=10, y=430, height=48, width=420)
self.Labelframe11.configure(relief='ridge')
self.Labelframe11.configure(font="-family {Segoe UI} -size 9 -weight bold")
self.Labelframe11.configure(foreground="black")
self.Labelframe11.configure(relief="ridge")
self.Labelframe11.configure(text='''Task Scheduler''')
self.Labelframe11.configure(background="#d9d9d9")
self.Labelframe11.configure(highlightbackground="#d9d9d9")
self.Labelframe11.configure(highlightcolor="black")
self.Label3 = tk.Label(self.Labelframe11)
self.Label3.place(x=40, y=20, height=17, width=203, bordermode='ignore')
self.Label3.configure(activebackground="#f9f9f9")
self.Label3.configure(activeforeground="black")
self.Label3.configure(background="#d9d9d9")
self.Label3.configure(disabledforeground="#a3a3a3")
self.Label3.configure(foreground="#000000")
self.Label3.configure(highlightbackground="#d9d9d9")
self.Label3.configure(highlightcolor="black")
self.Label3.configure(text='''Enter Check Time Interval in minute-s''')
self.SCHEDULER_Entry = tk.Entry(self.Labelframe11)
self.SCHEDULER_Entry.place(x=287, y=15, height=27, width=104
, bordermode='ignore')
self.SCHEDULER_Entry.configure(background="#c1ffc1")
self.SCHEDULER_Entry.configure(disabledforeground="#a3a3a3")
self.SCHEDULER_Entry.configure(font="TkFixedFont")
self.SCHEDULER_Entry.configure(foreground="#000000")
self.SCHEDULER_Entry.configure(highlightbackground="#d9d9d9")
self.SCHEDULER_Entry.configure(highlightcolor="black")
self.SCHEDULER_Entry.configure(insertbackground="black")
self.SCHEDULER_Entry.configure(justify='center')
self.SCHEDULER_Entry.configure(selectbackground="blue")
self.SCHEDULER_Entry.configure(selectforeground="white")
self.SCHEDULER_Entry.configure(textvariable=task_timer)
self.Labelframe12 = tk.LabelFrame(self.TNotebook1_t1_1)
self.Labelframe12.place(x=10, y=310, height=48, width=420)
self.Labelframe12.configure(relief='groove')
self.Labelframe12.configure(font="-family {Segoe UI} -size 9 -weight bold")
self.Labelframe12.configure(foreground="black")
self.Labelframe12.configure(text='''Download Speed Check''')
self.Labelframe12.configure(background="#d9d9d9")
self.Labelframe12.configure(highlightbackground="#d9d9d9")
self.Labelframe12.configure(highlightcolor="black")
self.Label13 = tk.Label(self.Labelframe12)
self.Label13.place(x=40, y=20, height=14, width=133, bordermode='ignore')
self.Label13.configure(activebackground="#f9f9f9")
self.Label13.configure(activeforeground="black")
self.Label13.configure(background="#d9d9d9")
self.Label13.configure(disabledforeground="#a3a3a3")
self.Label13.configure(foreground="#000000")
self.Label13.configure(highlightbackground="#d9d9d9")
self.Label13.configure(highlightcolor="black")
self.Label13.configure(text='''Enter Download Speed''')
self.DWONLOAD_Entry = tk.Entry(self.Labelframe12)
self.DWONLOAD_Entry.place(x=287, y=16, height=27, width=104
, bordermode='ignore')
self.DWONLOAD_Entry.configure(background="#c1ffc1")
self.DWONLOAD_Entry.configure(disabledforeground="#a3a3a3")
self.DWONLOAD_Entry.configure(font="TkFixedFont")
self.DWONLOAD_Entry.configure(foreground="#000000")
self.DWONLOAD_Entry.configure(highlightbackground="#d9d9d9")
self.DWONLOAD_Entry.configure(highlightcolor="black")
self.DWONLOAD_Entry.configure(insertbackground="black")
self.DWONLOAD_Entry.configure(justify='center')
self.DWONLOAD_Entry.configure(selectbackground="blue")
self.DWONLOAD_Entry.configure(selectforeground="white")
self.DWONLOAD_Entry.configure(textvariable=download_sp)
self.Labelframe7 = tk.LabelFrame(self.TNotebook1_t2_1)
self.Labelframe7.place(x=10, y=30, height=64, width=426)
self.Labelframe7.configure(relief='ridge')
self.Labelframe7.configure(font="-family {Segoe UI} -size 9 -weight bold")
self.Labelframe7.configure(foreground="black")
self.Labelframe7.configure(relief="ridge")
self.Labelframe7.configure(text='''SMTP''')
self.Labelframe7.configure(background="#d9d9d9")
self.Labelframe7.configure(highlightbackground="#d9d9d9")
self.Labelframe7.configure(highlightcolor="black")
self.SMTP_Entry = tk.Entry(self.Labelframe7)
self.SMTP_Entry.place(x=79, y=19, height=30, width=294
, bordermode='ignore')
self.SMTP_Entry.configure(background="#c1ffc1")
self.SMTP_Entry.configure(disabledforeground="#a3a3a3")
self.SMTP_Entry.configure(font="TkFixedFont")
self.SMTP_Entry.configure(foreground="#000000")
self.SMTP_Entry.configure(highlightbackground="#d9d9d9")
self.SMTP_Entry.configure(highlightcolor="black")
self.SMTP_Entry.configure(insertbackground="black")
self.SMTP_Entry.configure(justify='center')
self.SMTP_Entry.configure(selectbackground="blue")
self.SMTP_Entry.configure(selectforeground="white")
self.SMTP_Entry.configure(textvariable=smtp)
self.Labelframe8 = tk.LabelFrame(self.TNotebook1_t2_1)
self.Labelframe8.place(x=10, y=120, height=64, width=426)
self.Labelframe8.configure(relief='ridge')
self.Labelframe8.configure(font="-family {Segoe UI} -size 9 -weight bold")
self.Labelframe8.configure(foreground="black")
self.Labelframe8.configure(relief="ridge")
self.Labelframe8.configure(text='''Sender email address''')
self.Labelframe8.configure(background="#d9d9d9")
self.Labelframe8.configure(highlightbackground="#d9d9d9")
self.Labelframe8.configure(highlightcolor="black")
self.SenderEmailAdres_Entry = tk.Entry(self.Labelframe8)
self.SenderEmailAdres_Entry.place(x=79, y=19, height=30, width=294
, bordermode='ignore')
self.SenderEmailAdres_Entry.configure(background="#c1ffc1")
self.SenderEmailAdres_Entry.configure(cursor="")
self.SenderEmailAdres_Entry.configure(disabledforeground="#a3a3a3")
self.SenderEmailAdres_Entry.configure(exportselection="0")
self.SenderEmailAdres_Entry.configure(font="TkFixedFont")
self.SenderEmailAdres_Entry.configure(foreground="#000000")
self.SenderEmailAdres_Entry.configure(highlightbackground="#a4ffa4")
self.SenderEmailAdres_Entry.configure(highlightcolor="#bfffbf")
self.SenderEmailAdres_Entry.configure(insertbackground="#000000")
self.SenderEmailAdres_Entry.configure(justify='center')
self.SenderEmailAdres_Entry.configure(selectbackground="blue")
self.SenderEmailAdres_Entry.configure(selectforeground="white")
self.SenderEmailAdres_Entry.configure(textvariable=sender_email)
self.Labelframe9 = tk.LabelFrame(self.TNotebook1_t2_1)
self.Labelframe9.place(x=10, y=210, height=64, width=426)
self.Labelframe9.configure(relief='ridge')
self.Labelframe9.configure(font="-family {Segoe UI} -size 9 -weight bold")
self.Labelframe9.configure(foreground="black")
self.Labelframe9.configure(relief="ridge")
self.Labelframe9.configure(text='''Sender's Password''')
self.Labelframe9.configure(background="#d9d9d9")
self.Labelframe9.configure(highlightbackground="#d9d9d9")
self.Labelframe9.configure(highlightcolor="black")
self.SenderPWD_Entry = tk.Entry(self.Labelframe9)
self.SenderPWD_Entry.place(x=79, y=19, height=30, width=294
, bordermode='ignore')
self.SenderPWD_Entry.configure(background="#c1ffc1")
self.SenderPWD_Entry.configure(cursor="")
self.SenderPWD_Entry.configure(disabledforeground="#a3a3a3")
self.SenderPWD_Entry.configure(exportselection="0")
self.SenderPWD_Entry.configure(font="TkFixedFont")
self.SenderPWD_Entry.configure(foreground="#000000")
self.SenderPWD_Entry.configure(highlightbackground="#a4ffa4")
self.SenderPWD_Entry.configure(highlightcolor="#bfffbf")
self.SenderPWD_Entry.configure(insertbackground="#000000")
self.SenderPWD_Entry.configure(justify='center')
self.SenderPWD_Entry.configure(selectbackground="blue")
self.SenderPWD_Entry.configure(selectforeground="white")
self.SenderPWD_Entry.configure(show="*")
self.SenderPWD_Entry.configure(textvariable=sender_pwd)
self.Labelframe10 = tk.LabelFrame(self.TNotebook1_t2_1)
self.Labelframe10.place(x=10, y=300, height=64, width=426)
self.Labelframe10.configure(relief='ridge')
self.Labelframe10.configure(font="-family {Segoe UI} -size 9 -weight bold")
self.Labelframe10.configure(foreground="black")
self.Labelframe10.configure(relief="ridge")
self.Labelframe10.configure(text='''Receiver email address''')
self.Labelframe10.configure(background="#d9d9d9")
self.Labelframe10.configure(highlightbackground="#d9d9d9")
self.Labelframe10.configure(highlightcolor="black")
self.ReceiverEmailAdres_Entry = tk.Entry(self.Labelframe10)
self.ReceiverEmailAdres_Entry.place(x=79, y=19, height=30, width=294
, bordermode='ignore')
self.ReceiverEmailAdres_Entry.configure(background="#c1ffc1")
self.ReceiverEmailAdres_Entry.configure(cursor="")
self.ReceiverEmailAdres_Entry.configure(disabledforeground="#a3a3a3")
self.ReceiverEmailAdres_Entry.configure(exportselection="0")
self.ReceiverEmailAdres_Entry.configure(font="TkFixedFont")
self.ReceiverEmailAdres_Entry.configure(foreground="#000000")
self.ReceiverEmailAdres_Entry.configure(highlightbackground="#a4ffa4")
self.ReceiverEmailAdres_Entry.configure(highlightcolor="#bfffbf")
self.ReceiverEmailAdres_Entry.configure(insertbackground="#000000")
self.ReceiverEmailAdres_Entry.configure(justify='center')
self.ReceiverEmailAdres_Entry.configure(selectbackground="blue")
self.ReceiverEmailAdres_Entry.configure(selectforeground="white")
self.ReceiverEmailAdres_Entry.configure(textvariable=receiver_email)
self.StartTask_Button = tk.Button(self.TNotebook1_t2_1)
self.StartTask_Button.place(x=40, y=390, height=34, width=356)
self.StartTask_Button.configure(activebackground="#bfffbf")
self.StartTask_Button.configure(activeforeground="#000000")
self.StartTask_Button.configure(background="#d9d9d9")
self.StartTask_Button.configure(disabledforeground="#a3a3a3")
self.StartTask_Button.configure(font="-family {Segoe UI} -size 9 -weight bold")
self.StartTask_Button.configure(foreground="#000000")
self.StartTask_Button.configure(highlightbackground="#d9d9d9")
self.StartTask_Button.configure(highlightcolor="black")
self.StartTask_Button.configure(pady="0")
self.StartTask_Button.configure(text='''Start Task''')
self.StartTask_Button.configure(command=StartTask)
self.Stop_Task = tk.Button(self.TNotebook1_t2_1)
self.Stop_Task.place(x=40, y=450, height=34, width=356)
self.Stop_Task.configure(activebackground="#bfffbf")
self.Stop_Task.configure(activeforeground="#000000")
self.Stop_Task.configure(background="#d9d9d9")
self.Stop_Task.configure(disabledforeground="#a3a3a3")
self.Stop_Task.configure(font="-family {Segoe UI} -size 9 -weight bold")
self.Stop_Task.configure(foreground="#000000")
self.Stop_Task.configure(highlightbackground="#d9d9d9")
self.Stop_Task.configure(highlightcolor="black")
self.Stop_Task.configure(pady="0")
self.Stop_Task.configure(text='''Stop Task''')
self.Stop_Task.configure(command=StopTask)
self.TNotebook2 = ttk.Notebook(self.TNotebook1_t3_1)
self.TNotebook2.place(x=0, y=10, height=475, width=420)
self.TNotebook2.configure(takefocus="")
self.TNotebook2_t1_1 = tk.Frame(self.TNotebook2)
self.TNotebook2.add(self.TNotebook2_t1_1, padding=3)
self.TNotebook2.tab(0, text="System Preferences", compound="left", underline="-1")
self.TNotebook2_t1_1.configure(background="#d9d9d9")
self.TNotebook2_t1_1.configure(highlightbackground="#d9d9d9")
self.TNotebook2_t1_1.configure(highlightcolor="black")
self.TNotebook2_t2_1 = tk.Frame(self.TNotebook2)
self.TNotebook2.add(self.TNotebook2_t2_1, padding=3)
self.TNotebook2.tab(1, text="Email Preferences", compound="left", underline="-1")
self.TNotebook2_t2_1.configure(background="#d9d9d9")
self.TNotebook2_t2_1.configure(highlightbackground="#d9d9d9")
self.TNotebook2_t2_1.configure(highlightcolor="black")
self.TNotebook2_t3_1 = tk.Frame(self.TNotebook2)
self.TNotebook2.add(self.TNotebook2_t3_1, padding=3)
self.TNotebook2.tab(2, text="License",compound="left",underline="-1",)
self.TNotebook2_t3_1.configure(background="#d9d9d9")
self.TNotebook2_t3_1.configure(highlightbackground="#d9d9d9")
self.TNotebook2_t3_1.configure(highlightcolor="black")
self.SysPref_Scrolledtext = ScrolledText(self.TNotebook2_t1_1)
self.SysPref_Scrolledtext.place(x=0, y=19, height=423, width=405)
self.SysPref_Scrolledtext.configure(background="white")
self.SysPref_Scrolledtext.configure(font="TkTextFont")
self.SysPref_Scrolledtext.configure(foreground="black")
self.SysPref_Scrolledtext.configure(highlightbackground="#d9d9d9")
self.SysPref_Scrolledtext.configure(highlightcolor="black")
self.SysPref_Scrolledtext.configure(insertbackground="black")
self.SysPref_Scrolledtext.configure(insertborderwidth="3")
self.SysPref_Scrolledtext.configure(selectbackground="blue")
self.SysPref_Scrolledtext.configure(selectforeground="white")
self.SysPref_Scrolledtext.configure(wrap="none")
self.EmailPref_Scrolledtext = ScrolledText(self.TNotebook2_t2_1)
self.EmailPref_Scrolledtext.place(x=0, y=19, height=423, width=405)
self.EmailPref_Scrolledtext.configure(background="white")
self.EmailPref_Scrolledtext.configure(font="TkTextFont")
self.EmailPref_Scrolledtext.configure(foreground="black")
self.EmailPref_Scrolledtext.configure(highlightbackground="#d9d9d9")
self.EmailPref_Scrolledtext.configure(highlightcolor="black")
self.EmailPref_Scrolledtext.configure(insertbackground="black")
self.EmailPref_Scrolledtext.configure(insertborderwidth="3")
self.EmailPref_Scrolledtext.configure(selectbackground="blue")
self.EmailPref_Scrolledtext.configure(selectforeground="white")
self.EmailPref_Scrolledtext.configure(wrap="none")
self.License_Scrolledtext = ScrolledText(self.TNotebook2_t3_1)
self.License_Scrolledtext.place(x=0, y=19, height=423, width=405)
self.License_Scrolledtext.configure(background="white")
self.License_Scrolledtext.configure(font="TkTextFont")
self.License_Scrolledtext.configure(foreground="black")
self.License_Scrolledtext.configure(highlightbackground="#d9d9d9")
self.License_Scrolledtext.configure(highlightcolor="black")
self.License_Scrolledtext.configure(insertbackground="black")
self.License_Scrolledtext.configure(insertborderwidth="3")
self.License_Scrolledtext.configure(selectbackground="blue")
self.License_Scrolledtext.configure(selectforeground="white")
self.License_Scrolledtext.configure(wrap="none")
self.Label1 = tk.Label(self.TNotebook1_t4_1)
self.Label1.place(x=30, y=45, height=23, width=162)
self.Label1.configure(activebackground="#f9f9f9")
self.Label1.configure(activeforeground="black")
self.Label1.configure(background="#d9d9d9")
self.Label1.configure(disabledforeground="#a3a3a3")
self.Label1.configure(font="-family {Segoe UI} -size 9 -weight bold")
self.Label1.configure(foreground="#000000")
self.Label1.configure(highlightbackground="#d9d9d9")
self.Label1.configure(highlightcolor="black")
self.Label1.configure(text='''Follow me in Linkedin''')
self.LINKEDIN_Button = tk.Button(self.TNotebook1_t4_1)
self.LINKEDIN_Button.place(x=268, y=45, height=24, width=157)
self.LINKEDIN_Button.configure(activebackground="#bfffbf")
self.LINKEDIN_Button.configure(activeforeground="#000000")
self.LINKEDIN_Button.configure(background="#d9d9d9")
self.LINKEDIN_Button.configure(disabledforeground="#a3a3a3")
self.LINKEDIN_Button.configure(foreground="#000000")
self.LINKEDIN_Button.configure(highlightbackground="#d9d9d9")
self.LINKEDIN_Button.configure(highlightcolor="black")
self.LINKEDIN_Button.configure(pady="0")
self.LINKEDIN_Button.configure(text='''Linkedin''')
self.LINKEDIN_Button.configure(command=linked_in)
self.Label2 = tk.Label(self.TNotebook1_t4_1)
self.Label2.place(x=30, y=157, height=23, width=162)
self.Label2.configure(activebackground="#f9f9f9")
self.Label2.configure(activeforeground="black")
self.Label2.configure(background="#d9d9d9")
self.Label2.configure(disabledforeground="#a3a3a3")
self.Label2.configure(font="-family {Segoe UI} -size 9 -weight bold")
self.Label2.configure(foreground="#000000")
self.Label2.configure(highlightbackground="#d9d9d9")
self.Label2.configure(highlightcolor="black")
self.Label2.configure(text='''Follow me in Github''')
self.GITHUB_Button = tk.Button(self.TNotebook1_t4_1)
self.GITHUB_Button.place(x=268, y=157, height=24, width=157)
self.GITHUB_Button.configure(activebackground="#bfffbf")
self.GITHUB_Button.configure(activeforeground="#000000")
self.GITHUB_Button.configure(background="#d9d9d9")
self.GITHUB_Button.configure(disabledforeground="#a3a3a3")
self.GITHUB_Button.configure(foreground="#000000")
self.GITHUB_Button.configure(highlightbackground="#d9d9d9")
self.GITHUB_Button.configure(highlightcolor="black")
self.GITHUB_Button.configure(pady="0")
self.GITHUB_Button.configure(text='''Github''')
self.GITHUB_Button.configure(command=git_hub)
self.DONATE_Button = tk.Button(self.TNotebook1_t4_1)
self.DONATE_Button.place(x=20, y=267, height=24, width=407)
self.DONATE_Button.configure(activebackground="#bfffbf")
self.DONATE_Button.configure(activeforeground="#000000")
self.DONATE_Button.configure(background="#d9d9d9")
self.DONATE_Button.configure(disabledforeground="#a3a3a3")
self.DONATE_Button.configure(foreground="#000000")
self.DONATE_Button.configure(highlightbackground="#d9d9d9")
self.DONATE_Button.configure(highlightcolor="black")
self.DONATE_Button.configure(pady="0")
self.DONATE_Button.configure(text='''Donate PayPal''')
self.DONATE_Button.configure(command=paypal)
self.Label11 = tk.Label(self.TNotebook1_t4_1)
self.Label11.place(x=10, y=350, height=49, width=424)
self.Label11.configure(activebackground="#f9f9f9")
self.Label11.configure(activeforeground="black")
self.Label11.configure(background="#d9d9d9")
self.Label11.configure(disabledforeground="#a3a3a3")
self.Label11.configure(foreground="#000000")
self.Label11.configure(highlightbackground="#d9d9d9")
self.Label11.configure(highlightcolor="black")
self.Label11.configure(text='''To report a bug or to suggest a feature, feel free to contact me on Github.''')
self.Label14 = tk.Label(self.TNotebook1_t4_1)
self.Label14.place(x=40, y=420, height=31, width=364)
self.Label14.configure(activebackground="#f9f9f9")
self.Label14.configure(activeforeground="black")
self.Label14.configure(background="#d9d9d9")
self.Label14.configure(disabledforeground="#a3a3a3")
self.Label14.configure(foreground="#000000")
self.Label14.configure(highlightbackground="#d9d9d9")
self.Label14.configure(highlightcolor="black")
self.Label14.configure(justify='left')
self.Label14.configure(text='''For professional inquiry, contact me at cyber-tech@keemail.me''')
self.Label10 = tk.Label(top)
self.Label10.place(x=40, y=10, height=21, width=424)
self.Label10.configure(activebackground="#f9f9f9")
self.Label10.configure(activeforeground="black")
self.Label10.configure(background="#d9d9d9")
self.Label10.configure(disabledforeground="#a3a3a3")
self.Label10.configure(font="-family {Segoe UI Black} -size 12 -weight bold")
self.Label10.configure(foreground="#000000")
self.Label10.configure(highlightbackground="#d9d9d9")
self.Label10.configure(highlightcolor="black")
self.Label10.configure(text='''SYSTEM WATCHDOG''')
self.menubar = tk.Menu(top,font="TkMenuFont",bg=_bgcolor,fg=_fgcolor)
top.configure(menu = self.menubar)
self.Label9 = tk.Label(top)
self.Label9.place(x=90, y=590, height=21, width=304)
self.Label9.configure(activebackground="#f9f9f9")
self.Label9.configure(activeforeground="black")
self.Label9.configure(background="#d9d9d9")
self.Label9.configure(disabledforeground="#a3a3a3")
self.Label9.configure(font="-family {Segoe UI} -size 10 -weight bold")
self.Label9.configure(foreground="#000000")
self.Label9.configure(highlightbackground="#d9d9d9")
self.Label9.configure(highlightcolor="black")
self.Label9.configure(text='''By Cyber-Tech ® 2020''')
class AutoScroll(object):
def __init__(self, master):
try:
vsb = ttk.Scrollbar(master, orient='vertical', command=self.yview)
except:
pass
hsb = ttk.Scrollbar(master, orient='horizontal', command=self.xview)
try:
self.configure(yscrollcommand=self._autoscroll(vsb))
except:
pass
self.configure(xscrollcommand=self._autoscroll(hsb))
self.grid(column=0, row=0, sticky='nsew')
try:
vsb.grid(column=1, row=0, sticky='ns')
except:
pass
hsb.grid(column=0, row=1, sticky='ew')
master.grid_columnconfigure(0, weight=1)
master.grid_rowconfigure(0, weight=1)
methods = tk.Pack.__dict__.keys() | tk.Grid.__dict__.keys() \
| tk.Place.__dict__.keys()
for meth in methods:
if meth[0] != '_' and meth not in ('config', 'configure'):
setattr(self, meth, getattr(master, meth))
@staticmethod
def _autoscroll(sbar):
def wrapped(first, last):
first, last = float(first), float(last)
if first <= 0 and last >= 1:
sbar.grid_remove()
else:
sbar.grid()
sbar.set(first, last)
return wrapped
def __str__(self):
return str(self.master)
def _create_container(func):
def wrapped(cls, master, **kw):
container = ttk.Frame(master)
container.bind('<Enter>', lambda e: _bound_to_mousewheel(e, container))
container.bind('<Leave>', lambda e: _unbound_to_mousewheel(e, container))
return func(cls, container, **kw)
return wrapped
class ScrolledText(AutoScroll, tk.Text):
@_create_container
def __init__(self, master, **kw):
tk.Text.__init__(self, master, **kw)
AutoScroll.__init__(self, master)
import platform
def _bound_to_mousewheel(event, widget):
child = widget.winfo_children()[0]
if platform.system() == 'Windows':
child.bind_all('<MouseWheel>', lambda e: _on_mousewheel(e, child))
child.bind_all('<Shift-MouseWheel>', lambda e: _on_shiftmouse(e, child))
else:
child.bind_all('<Button-4>', lambda e: _on_mousewheel(e, child))
child.bind_all('<Button-5>', lambda e: _on_mousewheel(e, child))
child.bind_all('<Shift-Button-4>', lambda e: _on_shiftmouse(e, child))
child.bind_all('<Shift-Button-5>', lambda e: _on_shiftmouse(e, child))
def _unbound_to_mousewheel(event, widget):
if platform.system() == 'Windows':
widget.unbind_all('<MouseWheel>')
widget.unbind_all('<Shift-MouseWheel>')
else:
widget.unbind_all('<Button-4>')
widget.unbind_all('<Button-5>')
widget.unbind_all('<Shift-Button-4>')
widget.unbind_all('<Shift-Button-5>')
def _on_mousewheel(event, widget):
if platform.system() == 'Windows':
widget.yview_scroll(-1*int(event.delta/120),'units')
else:
if event.num == 4:
widget.yview_scroll(-1, 'units')
elif event.num == 5:
widget.yview_scroll(1, 'units')
def _on_shiftmouse(event, widget):
if platform.system() == 'Windows':
widget.xview_scroll(-1*int(event.delta/120), 'units')
else:
if event.num == 4:
widget.xview_scroll(-1, 'units')
elif event.num == 5:
widget.xview_scroll(1, 'units')
if __name__ == '__main__':
vp_start_gui()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T19:28:56.733",
"Id": "495432",
"Score": "0",
"body": "Code not working as expected is off-topic on code review"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T19:38:31.413",
"Id": "495435",
"Score": "0",
"body": "Actually the code is working, it is showing **Not Responding** due to several functions running at the same time but its successfully working"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T19:39:58.543",
"Id": "495436",
"Score": "0",
"body": "My bad, I will remove my downvote"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T19:40:02.320",
"Id": "495437",
"Score": "1",
"body": "I somewhat doubt that you desire this not-responding state. As such, the code isn't working as you intend, and this question is indeed off-topic. Please consider posting this on Stack Overflow instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T19:41:58.153",
"Id": "495439",
"Score": "1",
"body": "@Reinderien The Not responding is just the GUI freezing due to calculations, is that off-topic?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T19:42:56.180",
"Id": "495441",
"Score": "2",
"body": "It depends on the focus of the question. It could be edited to emphasize the desire for a general review, but if the main thrust of the question is to fix the not-responding issue then it's off-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T20:08:15.310",
"Id": "495443",
"Score": "0",
"body": "exactly, code is running in background and executing all functionalities but the GUI is showing **Not Responding** which means its freezes due instant computations or instant calculations but it's working!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T21:39:50.750",
"Id": "495454",
"Score": "0",
"body": "Probably **while True:\n schedule.run_pending()\n time.sleep(1)** is blocking entire thread and its causing to have **Not Responding** and GUI Freeze while the code is executed in the background. I tried the same with one button GUI and it has same effect."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T23:32:37.433",
"Id": "495470",
"Score": "0",
"body": "I think using **while loop** with **schedule** in **tkinter** is a bad idea, any other alternatives?"
}
] |
[
{
"body": "<p>I'm going to give you the benefit of the doubt that you actually are just looking for a general review. There's a lot to cover here.</p>\n<h2>Variable naming</h2>\n<p>Particularly for a variable as important as <code>w</code>, it really does need a better name. I have no idea what it is. The same is true of <code>val</code>.</p>\n<h2>Globals</h2>\n<p>Avoid them. Attempt to pass <code>val</code>, <code>w</code>, <code>root</code>, <code>top_level</code> etc. as parameters; or make a class that holds them, where (for instance) <code>destroy_window</code> would become a class method instead of a global function.</p>\n<h2>Constants</h2>\n<p>Move <code>_bgcolor</code> and values like it to "static" scope (within <code>Toplevel1</code>, outside of any method).</p>\n<h2>RAD isolation</h2>\n<p>This code is really verbose. It's important to come up with a strategy that isolates the output of your designer tool from code that you've actually written. Currently it's a big crazy mix of both. There are many ways to do this, including subclassing, or simple instantiation.</p>\n<p>If you had to re-run your designer, what would happen? Could you trust that it would leave all of your custom code alone in its current state? I wouldn't.</p>\n<h2>Except / pass</h2>\n<p>Never do this. Bare <code>except</code> interferes with some signalling exceptions whose absence will surprise you. If you expect that (for instance) <code>ttk.Scrollbar()</code> is going to fail in some way, then catch the specific exception - not every single exception that could ever exist.</p>\n<h2>Subclassing the strangest way possible</h2>\n<pre><code> methods = tk.Pack.__dict__.keys() | tk.Grid.__dict__.keys() \\\n | tk.Place.__dict__.keys()\n\n for meth in methods:\n if meth[0] != '_' and meth not in ('config', 'configure'):\n setattr(self, meth, getattr(master, meth))\n</code></pre>\n<p>is spooky and almost definitely a bad idea. From the looks of it, you're accepting a <code>master</code> (whatever that is - you're missing all type hints), applying a shotgun-approach loop over a handful of predicted attribute names, and setting them as attributes on your own <code>AutoScroll</code> class to basically make it a proxy object.</p>\n<p>First of all, this doesn't do what you think. <code>__dict__</code> does <em>not</em> only return methods - it also returns any static variables set on those three classes.</p>\n<p>Second, why the acrobatics? Why not just make <code>AutoScroll</code> a subclass of whatever <code>master</code> is? You further subclass it as <code>ScrolledText</code> anyway, and instantiate it via</p>\n<pre><code> self.SysPref_Scrolledtext = ScrolledText(self.TNotebook2_t1_1)\n</code></pre>\n<p>where <code>TNotebook2_t1_1</code> is a <code>tk.Frame</code>. So why not just make <code>ScrolledText</code> a subclass of <code>tk.Frame</code>, and instantiate <code>TNotebook2_t1_1</code> as a <code>ScrolledText</code> directly?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T11:02:16.003",
"Id": "495528",
"Score": "0",
"body": "thank you. As I said the GUI code is generated using PAGE, it's true there is some missings but its not my actual intention. My actual needs is how to fix **schedule while loop** because its the one behind getting freezed GUI while code successfully running in background. I made a test of a GUI with one button and one function and I confirm **schedule while loop** is behind freezed GUI."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T14:23:48.863",
"Id": "495550",
"Score": "0",
"body": "We've been over this: if you need to fix something, then it's broken, and if it's broken, it does not belong on Code Review Stack Exchange."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T15:17:34.197",
"Id": "495557",
"Score": "0",
"body": "Everything is working as expected except **GUI FREEZE**, else If you think that my question does not belong to this page, I have to kindly follow your decision. Regards."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T01:47:47.817",
"Id": "251630",
"ParentId": "251612",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T18:54:27.290",
"Id": "251612",
"Score": "1",
"Tags": [
"performance",
"python-3.x",
"tkinter"
],
"Title": "Check Windows computer's usage of CPU and other resources"
}
|
251612
|
<p>I'm posting a solution for LeetCode's "Non-decreasing Array". If you'd like to review, please do. Thank you!</p>
<h3><a href="https://leetcode.com/problems/non-decreasing-array/" rel="nofollow noreferrer">Problem</a></h3>
<p>Given an array <code>nums</code> with <code>n</code> integers, your task is to check if it could become non-decreasing by modifying at most 1 element.</p>
<p>We define an array is non-decreasing if <code>nums[i] <= nums[i + 1]</code> holds for every i (0-based) such that (<code>0 <= i <= n - 2</code>).</p>
<h3>Example 1:</h3>
<ul>
<li>Input: nums = [4,2,3]</li>
<li>Output: true</li>
<li>Explanation: You could modify the first 4 to 1 to get a non-decreasing array.</li>
</ul>
<h3>Example 2:</h3>
<ul>
<li>Input: nums = [4,2,1]</li>
<li>Output: false</li>
<li>Explanation: You can't get a non-decreasing array by modify at most one element.</li>
</ul>
<h3>Constraints:</h3>
<ul>
<li><code>1 <= n <= 10 ^ 4</code></li>
<li><code>-10 ^ 5 <= nums[i] <= 10 ^ 5</code></li>
</ul>
<h3>Code</h3>
<pre><code>// Most of headers are already included;
// Can be removed;
#include <iostream>
#include <cstdint>
#include <vector>
// The following block might slightly improve the execution time;
// Can be removed;
static const auto __optimize__ = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
return 0;
}();
struct Solution {
using ValueType = std::int_fast32_t;
static const bool checkPossibility(
std::vector<int>& nums
) {
if (std::size(nums) < 3) {
return true;
}
ValueType max_changes = 0;
for (ValueType index = 1; max_changes < 2 && index < std::size(nums); ++index) {
if (nums[index - 1] > nums[index]) {
++max_changes;
if (index - 2 < 0 || nums[index - 2] <= nums[index]) {
nums[index - 1] = nums[index];
} else {
nums[index] = nums[index - 1];
}
}
}
return max_changes < 2;
}
};
int main() {
std::vector<int> nums = {3, 4, 2, 3};
std::cout << std::to_string(Solution().checkPossibility(nums) == false) << "\n";
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<h1>Avoid unnecessary special case handling</h1>\n<p>You exit early if the size of the array is less than 3, but this is unnecessary: the rest of the code already handles arrays of size 0, 1 and 2 correctly. You might save a cycle if you feed it a small array, but you pay for this check with a cycle or two for every time the function is called with <code>std::size(nums)</code> > 2.</p>\n<h1>Use <code>std::size_t</code> for indices</h1>\n<p>You made <code>index</code> a <code>std::int_fast32_t</code>, but this has a different size (likely) and a different signedness than the result of <code>std::size(nums)</code>. This means the compiler should have warned you about a comparison between signed and unsigned integers. While things work out here, since you know the size of the input array is constrained, it is best to use <code>std::size_t</code> here to avoid the compiler warning. Performance is likely not going to differ one bit, since <code>index</code> can be kept in a CPU register at all times.</p>\n<h1>There is no need to use <code>std::to_string()</code> when using <code><<</code> on a <code>std::ostream</code></h1>\n<p>When writing to a <code>std::ostream</code>, <code>operator<<</code> will already cause the argument to be formatted, so there is no need to call <code>std::to_string()</code>. In fact, you can tell the stream to format a <code>bool</code> as text:</p>\n<pre><code>int main() {\n std::vector<int> nums = {3, 4, 2, 3};\n std::cout << std::boolalpha << Solution().checkPossibility(nums) << "\\n";\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T22:34:14.597",
"Id": "251623",
"ParentId": "251617",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "251623",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T21:43:21.623",
"Id": "251617",
"Score": "2",
"Tags": [
"c++",
"beginner",
"algorithm",
"programming-challenge",
"c++17"
],
"Title": "LeetCode 665: Non-decreasing Array"
}
|
251617
|
<p>I'm posting a solution for LeetCode's "Non-decreasing Array". If you'd like to review, please do. Thank you!</p>
<h3><a href="https://leetcode.com/problems/non-decreasing-array/" rel="nofollow noreferrer">Problem</a></h3>
<p>Given an array <code>nums</code> with <code>n</code> integers, your task is to check if it could become non-decreasing by modifying at most 1 element.</p>
<p>We define an array is non-decreasing if <code>nums[i] <= nums[i + 1]</code> holds for every i (0-based) such that (<code>0 <= i <= n - 2</code>).</p>
<h3>Example 1:</h3>
<ul>
<li>Input: nums = [4,2,3]</li>
<li>Output: true</li>
<li>Explanation: You could modify the first 4 to 1 to get a non-decreasing array.</li>
</ul>
<h3>Example 2:</h3>
<ul>
<li>Input: nums = [4,2,1]</li>
<li>Output: false</li>
<li>Explanation: You can't get a non-decreasing array by modify at most one element.</li>
</ul>
<h3>Constraints:</h3>
<ul>
<li><code>1 <= n <= 10 ^ 4</code></li>
<li><code>-10 ^ 5 <= nums[i] <= 10 ^ 5</code></li>
</ul>
<h3>Code</h3>
<pre><code>// Since the relevant headers are already included on the LeetCode platform,
// the headers can be removed;
#include <stdio.h>
#include <stdbool.h>
static const bool checkPossibility(
int *nums,
const int nums_size
) {
if (nums_size < 3) {
return true;
}
int max_changes = 0;
for (int index = 1; index < nums_size - 1; ++index) {
if (!(nums[index] >= nums[index - 1] && nums[index + 1] >= nums[index])) {
if (nums[index + 1] >= nums[index - 1]) {
++max_changes;
nums[index] = nums[index - 1];
} else {
if (nums[index] < nums[index - 1] && nums[index + 1] < nums[index]) {
return false;
} else if (nums[index] <= nums[index + 1]) {
nums[index - 1] = nums[index];
if (!(index - 1) || nums[index - 2] <= nums[index - 1]) {
++max_changes;
} else {
return false;
}
} else {
nums[index + 1] = nums[index];
++max_changes;
}
}
}
}
return max_changes < 2;
}
int main() {
static const int nums_size = 3;
int nums_array[nums_size] = {4, 2, 1};
int (*nums)[nums_size] = &nums_array;
fputs(checkPossibility(*nums, nums_size) ? "true" : "false", stdout);
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<h1>Simplify the logic</h1>\n<p>Why does this solution look more complicated than the <a href=\"https://codereview.stackexchange.com/questions/251617/leetcode-665-non-decreasing-array#251617\">C++ version you posted</a>? It seems like you can use exactly the same logic as in the C++ version.</p>\n<h1>Don't return <code>const</code> values</h1>\n<p>Declaring the return value to be <code>const</code> is not doing anything unless you return a pointer.</p>\n<h1>Avoid unnecessary special case handling</h1>\n<p>You exit early if the size of the array is less than 3, but this is unnecessary: the rest of the code already handles arrays of size 0, 1 and 2 correctly. You might save a cycle if you feed it a small array, but you pay for this check with a cycle or two for every time the function is called with <code>nums_size > 2</code>.</p>\n<h1>Simplify your <code>main()</code></h1>\n<p>You do a lot of unnecessary things in <code>main()</code>:</p>\n<ul>\n<li>There's no need to have a constant for the array up front, as you can use <code>sizeof</code> to get the size of the array, and divide it by the size of one element to get the number of elements.</li>\n<li>There is no need to declare a pointer to the array, the array itself can be used as a pointer.</li>\n<li><code>puts()</code> is like <code>fputs()</code>, but always writes to <code>stdout</code>, and adds a newline for you.</li>\n<li>The <code>return 0</code> is not necessary in <code>main()</code>.</li>\n</ul>\n<p>So you can simplify it as follows:</p>\n<pre><code>int main() {\n int array[] = {4, 2, 1};\n puts(checkPossibility(array, sizeof array / sizeof *array) ? "true" : "false");\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T22:25:33.153",
"Id": "251621",
"ParentId": "251618",
"Score": "2"
}
},
{
"body": "<p><strong>The code mutates an array</strong>. It is not good.</p>\n<p><strong>The code does too much</strong>. You may <code>return false</code> as soon as <code>max_changes</code> reaches 2 (no need to examine the rest).</p>\n<p><strong>More functions please</strong>. It is very hard to follow the complicated decision making. Consider</p>\n<pre><code>int find_first_violation(int * nums, int size)\n{\n int i = 0;\n for (; i < size; i++) {\n if (nums[i] < nums[i-1]) {\n break;\n }\n }\n return i;\n}\n</code></pre>\n<p>Then the business logic would be:</p>\n<pre><code> int violation = find_first_violation(nums, size);\n\n if (violation == size) {\n // array is already non-decreasing\n return true;\n }\n if (violation == size - 1) {\n // easily fixable: increase nums[size - 1]\n return true;\n }\n\n // Now fix the violation\n // violation == 1 is fixable by decreasing nums[0]. No action needed.\n // Otherwise, we only care about the case where nums[violation] is too\n // small - less than two preceding numbers. It is only fixable by\n // increasing it, effectively setting it equal to nums[violation - 1].\n\n if ((violation > 1) && (nums[violation] < nums[violation - 2])) {\n nums[violation] = nums[violation - 1];\n }\n\n // Finally, the core argument to have more functions: there\n // must be no more violations.\n\n return find_first_violation(nums + violation, size - violation) == size - violation;\n</code></pre>\n<p>Of course the first two conditions can be combined into <code>violation >= size - 1</code>. Of course increasing of <code>nums[violation]</code> can be virtual, without mutating the array (if <code>nums[violation - 1] > nums[violation + 1]</code> we may immediately <code>return false;</code>).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T23:21:08.620",
"Id": "251624",
"ParentId": "251618",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "251621",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T21:47:12.860",
"Id": "251618",
"Score": "3",
"Tags": [
"performance",
"beginner",
"algorithm",
"c",
"programming-challenge"
],
"Title": "LeetCode 665: Non-decreasing Array (C)"
}
|
251618
|
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/251499/231235">A Sine Template Function For Boost.MultiArray in C++</a>, <a href="https://codereview.stackexchange.com/q/251171/231235">A recursive_transform for std::array with various return type</a>, <a href="https://codereview.stackexchange.com/q/251132/231235">A recursive_transform for std::vector with various return type</a> and <a href="https://codereview.stackexchange.com/q/251060/231235">A recursive_transform Function For Various Type Nested Iterable With std::variant Implementation in C++</a>.</p>
<p>In the previous question <a href="https://codereview.stackexchange.com/q/251499/231235">A Sine Template Function For Boost.MultiArray in C++</a>, there is a suggestion which is to use <code>recursive_transform</code> function to handle <code>multi_array</code>s in <a href="https://codereview.stackexchange.com/a/251504/231235">G. Sliepen's answer</a>. However, I found that the existed version of <code>recursive_transform</code> couldn't handle <code>multi_array</code>s well. In other words, another version of <code>recursive_transform</code> function which can be capable of <code>multi_array</code> structure is needed. I am trying to implement this as below. First, some concepts including <code>is_multi_array</code>, <code>is_sub_array</code> and <code>is_const_sub_array</code> are created.</p>
<pre><code>template<typename T>
concept is_multi_array = requires(T x)
{
x.num_dimensions();
x.shape();
boost::multi_array(x);
};
template<typename T>
concept is_sub_array = requires(T x)
{
x.num_dimensions();
x.shape();
boost::detail::multi_array::sub_array(x);
};
template<typename T>
concept is_const_sub_array = requires(T x)
{
x.num_dimensions();
x.shape();
boost::detail::multi_array::const_sub_array(x);
};
</code></pre>
<p>The main part of the <code>recursive_transform</code> function:</p>
<pre><code>template<class T, class F>
auto recursive_transform(const T& input, const F& f)
{
return f(input);
}
template<class T, std::size_t S, class F>
auto recursive_transform(const std::array<T, S>& input, const F& f)
{
using TransformedValueType = decltype(recursive_transform(*input.cbegin(), f));
std::array<TransformedValueType, S> output;
std::transform(input.cbegin(), input.cend(), output.begin(),
[f](auto& element)
{
return recursive_transform(element, f);
}
);
return output;
}
template<template<class...> class Container, class Function, class... Ts>
// non-recursive version
auto recursive_transform(const Container<Ts...>& input, const Function& f)
{
using TransformedValueType = decltype(f(*input.cbegin()));
Container<TransformedValueType> output;
std::transform(input.cbegin(), input.cend(), std::back_inserter(output), f);
return output;
}
template<template<class...> class Container, class Function, class... Ts>
requires is_elements_iterable<Container<Ts...>>
auto recursive_transform(const Container<Ts...>& input, const Function& f)
{
using TransformedValueType = decltype(recursive_transform(*input.cbegin(), f));
Container<TransformedValueType> output;
std::transform(input.cbegin(), input.cend(), std::back_inserter(output),
[&](auto& element)
{
return recursive_transform(element, f);
}
);
return output;
}
template<class T, class F> requires (is_multi_array<T> || is_sub_array<T> || is_const_sub_array<T>)
auto recursive_transform(const T& input, const F& f)
{
boost::multi_array output(input);
for (decltype(+input.shape()[0]) i = 0; i < input.shape()[0]; i++)
{
output[i] = recursive_transform(input[i], f);
}
return output;
}
</code></pre>
<p>Moreover, the used <code>is_elements_iterable</code> concept:</p>
<pre><code>template<typename T>
concept is_elements_iterable = requires(T x)
{
std::begin(x)->begin();
std::end(x)->end();
};
</code></pre>
<p>Finally, the test of this <code>recursive_transform</code> with Boost.MultiArray is as follows.</p>
<pre><code>// Create a 3D array that is 3 x 4 x 2
typedef boost::multi_array<double, 3> array_type;
typedef array_type::index index;
array_type A(boost::extents[3][4][2]);
// Assign values to the elements
int values = 1;
for (index i = 0; i != 3; ++i)
for (index j = 0; j != 4; ++j)
for (index k = 0; k != 2; ++k)
A[i][j][k] = values++;
for (index i = 0; i != 3; ++i)
for (index j = 0; j != 4; ++j)
for (index k = 0; k != 2; ++k)
std::cout << A[i][j][k] << std::endl;
auto test_result = recursive_transform(A, [](auto& x) {return std::sin(x); });
for (index i = 0; i != 3; ++i)
for (index j = 0; j != 4; ++j)
for (index k = 0; k != 2; ++k)
std::cout << test_result[i][j][k] << std::endl;
</code></pre>
<p>The whole test of this <code>recursive_transform</code> can be checked at <a href="https://gist.github.com/Jimmy-Hu/bf1c54b54c492ce0562b15228d67beef" rel="nofollow noreferrer">here</a>.</p>
<p>All suggestions are welcome.</p>
<p>The summary information:</p>
<ul>
<li><p>Which question it is a follow-up to?</p>
<p><a href="https://codereview.stackexchange.com/q/251499/231235">A Sine Template Function For Boost.MultiArray in C++</a>,</p>
<p><a href="https://codereview.stackexchange.com/q/251171/231235">A recursive_transform for std::array with various return type</a>,</p>
<p><a href="https://codereview.stackexchange.com/q/251132/231235">A recursive_transform for std::vector with various return type</a> and</p>
<p><a href="https://codereview.stackexchange.com/q/251060/231235">A recursive_transform Function For Various Type Nested Iterable With std::variant Implementation in C++</a>.</p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p>Improving the capability of <code>recursive_transform</code> function with <code>multi_array</code> structure.</p>
</li>
<li><p>Why a new review is being asked for?</p>
<p>All suggestions about this <code>recursive_transform</code> function are welcome.</p>
</li>
</ul>
|
[] |
[
{
"body": "<h1>Only one <code>concept</code> is necessary for <code>boost::multi_array</code> types</h1>\n<p>The concepts <code>is_sub_array</code> and <code>is_const_sub_array</code> are redundant, since <code>is_multi_array</code> will match the first two ones as well. That is because of:</p>\n<pre><code>boost::multi_array(x);\n</code></pre>\n<p>The constructor of <code>boost::multi_array</code> has overloads for <code>sub_array</code>s and <code>const_sub_array</code>s.</p>\n<h1>Restrict the overload for non-recursive containers</h1>\n<p>In this overload:</p>\n<pre><code>template<template<class...> class Container, class Function, class... Ts>\n// non-recursive version\nauto recursive_transform(const Container<Ts...>& input, const Function& f)\n{\n ...\n</code></pre>\n<p>You should require that <code>Container<Ts...></code> is a non-recursive container, otherwise it could match types that are not containers as well.</p>\n<h1>Make sure your concepts check everything that is used</h1>\n<p>I did mention this before, but I missed it myself in an earlier review when I gave an example for the <code>is_iterable</code> concept. But since you use <code>std::back_inserter()</code>, you should check for that in the relevant concepts as well, since not all containers support inserting to the back. If you don't check it in the concept, compilation will still fail but the error message will be very hard to understand.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T02:38:56.700",
"Id": "495481",
"Score": "0",
"body": "Thank you for the answer. About the \"Restrict the overload for non-recursive containers\" part, is there any further example or hint can help me know how to do that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T07:16:39.713",
"Id": "495512",
"Score": "2",
"body": "@JimmyHu `requires (is_iterable(Container<Ts....>) && !is_element_iterable(Container<Ts...>))`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T00:06:05.557",
"Id": "251627",
"ParentId": "251620",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "251627",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T22:19:25.250",
"Id": "251620",
"Score": "2",
"Tags": [
"c++",
"recursion",
"lambda",
"boost",
"c++20"
],
"Title": "A recursive_transform Template Function for BoostMultiArray"
}
|
251620
|
<p>I wanted a simple thing: being able to override a base class and just add one single getter. The bad thing is the base class does override some operators and will return the wrong type. I, therefore, came across the curiously recurring template pattern which helped me to write the following.</p>
<p>However, I am still not very satisfied. I wrote a very similar question <a href="https://stackoverflow.com/q/64623306/2612235">here</a> which helped me to learn about CRTP.</p>
<pre><code>#include <algorithm>
#include <array>
#include <iostream>
using namespace std;
template <typename C, typename T, int N>
class PointCRTP
{
protected:
array<T, N> elements;
public:
PointCRTP() = default;
PointCRTP(array<T, N> el) : elements(el) {}
C operator+(C& other)
{
C c;
transform(elements.begin(), elements.end(), other.elements.begin(),
c.elements.begin(), plus<int>());
return c;
}
T operator[](int k) { return elements[k]; }
friend std::ostream& operator<<(std::ostream& os, C const& x)
{
os << "P(";
for (auto k : x.elements) os << k << ", ";
return os << "\b\b" << ')';
}
};
template <typename T, int N>
struct Point : public PointCRTP<Point<T, N>, T, N> {
using PointCRTP<Point<T, N>, T, N>::PointCRTP;
};
template <typename T>
struct Point2D : public PointCRTP<Point2D<T>, T, 2> {
Point2D() = default;
Point2D(T x, T y) : PointCRTP<Point2D<T>, T, 2>({x, y}) {}
T getX() { return PointCRTP<Point2D<T>, T, 2>::elements[0]; }
T getY() { return PointCRTP<Point2D<T>, T, 2>::elements[1]; }
};
int main()
{
Point<int, 3> p({1, 2, 3});
Point<int, 3> q({3, 4, 2});
Point<int, 3> c = p + q;
std::cout << c << " = " << p << " + " << q << endl;
Point2D<int> r(1, 2);
Point2D<int> s(3, 4);
Point2D<int> t = r + s;
std::cout << t << " = " << r << " + " << s << endl;
}
</code></pre>
<p>Is there a way to make this example simpler (shorter)?</p>
|
[] |
[
{
"body": "<h1>Avoid special cases</h1>\n<p>A lot of problems come from the fact that you have slightly different ways to construct a 2D point and to get its elements than you have for an arbitrary dimensional point. You should avoid that first, this will make your life much easier.</p>\n<p>Here is a <code>class Point</code> that supports <code>getX()</code> and <code>getY()</code> with compile-time checking that the size of <code>elements</code> is large enough, and a constructor that takes a variable number of arguments, so you don't need to use braces when constructing a <code>Point</code>:</p>\n<pre><code>template <typename T, int N>\nclass Point\n{\n std::array<T, N> elements;\n\npublic:\n template<typename... E>\n Point(E&&...e): elements({std::forward<E>(e)...}) {}\n\n Point operator+(const Point& other)\n {\n Point c;\n std::transform(elements.begin(), elements.end(), other.elements.begin(),\n c.elements.begin(), plus<T>());\n return c;\n }\n\n const T& operator[](size_t k) const\n {\n return elements[k];\n }\n\n friend std::ostream& operator<<(std::ostream& os, Point const& x)\n {\n os << "P(";\n for (auto& k : x.elements) os << k << ", ";\n return os << "\\b\\b" << ')';\n }\n\n template<std::enable_if_t<(N > 0), int> = 0>\n const T& getX() const {\n return elements[0];\n }\n\n template<std::enable_if_t<(N > 1), int> = 0>\n const T& getY() const {\n return elements[1];\n }\n};\n</code></pre>\n<p>There are various ways to enable/disable member functions at compile time, the above uses <a href=\"https://en.cppreference.com/w/cpp/types/enable_if\" rel=\"nofollow noreferrer\"><code>std::enable_if_t</code></a> which completely disables a function. You can also use a compile-time assert, like so:</p>\n<pre><code>T getY() const {\n static_assert(N > 1, "this point doesn't have a y coordinate");\n return elements[1];\n}\n</code></pre>\n<p>Although as pointed out in the comments, this has the drawback that you cannot check at compile time if a given <code>Point</code> type supports <code>getX()</code>, <code>getY()</code>.</p>\n<p>To make a <code>Point2D</code> convenience class, use <code>using</code>:</p>\n<pre><code>template<typename T>\nusing Point2D = Point<T, 2>;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T00:04:53.690",
"Id": "495471",
"Score": "2",
"body": "Alternative to the `static_assert()`s: `template <int X= 0> std::enable_if_t<(X == 0 && X < N), T> getX() ...` dito for `getY()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T00:11:05.503",
"Id": "495472",
"Score": "1",
"body": "Personally I think the `static_assert()` makes the code look nicer, plus you get to define a custom error message. Although disabling the function entirely is also not bad."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T08:21:02.303",
"Id": "495514",
"Score": "2",
"body": "Using SFINAE instead of `static_assert` has the advantage of being compile-time checkable using traits (e.g. `supports_getX<T>`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T10:08:48.637",
"Id": "495527",
"Score": "1",
"body": "@AngewisnolongerproudofSO You convinced me :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T23:45:49.307",
"Id": "251626",
"ParentId": "251622",
"Score": "7"
}
},
{
"body": "<h1>Assignment using <code>[]</code> operator</h1>\n<p>If you have a look at your overload of <code>[]</code></p>\n<pre class=\"lang-cpp prettyprint-override\"><code> T operator[](size_t k) const\n {\n return elements[k];\n }\n</code></pre>\n<p>You are creating a <strong>copy</strong>. What you should do is returning a reference - <code>&</code> otherwise, you can't do something like</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>Point< int, 3 > p({1,2,3});\np[0] = 5; // Erorr: Expression must be a modifiable value\n</code></pre>\n<p>Simply solve it by returning a reference</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> T& operator[](size_t k)\n {\n return elements[k];\n }\n</code></pre>\n<p>As pointed at by @AI0867 in the comments, since we're returning a modifiable value we need to remove <code>const</code>.</p>\n<hr />\n<h1>Avoid copies</h1>\n<p>From your overload of the <code><<</code> operator</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>for (auto k : x.elements) os << k << ", ";\n</code></pre>\n<p><code>auto k</code> performs a <strong>deep copy</strong>, which would be fine if you had a primitive type like <code>int, double</code>. But anything large, like <code>std::string</code> will make things slow.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>for(auto& k : x.elements)\n</code></pre>\n<p>The same goes for</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>Point2D(T x, T y) : PointCRTP<Point2D<T>, T, 2>({ x, y }) {}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T13:11:48.430",
"Id": "495544",
"Score": "0",
"body": "You've just made operator[] return a modifiable reference while keeping it const. You probably want to remove the const, or make both a const and a non-const version, one of which returns a const-ref and the other a modifable reference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T14:08:46.727",
"Id": "495548",
"Score": "1",
"body": "@AI0867 Thank you for pointing that out!, it should be alright now"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-05T03:42:11.710",
"Id": "251637",
"ParentId": "251622",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "251626",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T22:30:56.490",
"Id": "251622",
"Score": "9",
"Tags": [
"c++",
"template-meta-programming"
],
"Title": "How to simplify this C++ CRTP example?"
}
|
251622
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.