body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>basically I'm learning Java Swing by myself and I'm wondering what is the correct way to wrote code for it?
I don't want to have a big class with everything in it and I want to do in the most "correct" way.
For example, I have this program right there that it is supposed to paint N rectangles, where N is given in input by the user using a JTextField. Basically you enter the number of rectangles that you want, you click "Ok" and it is supposed to draw that amount of rectangles in a random place into another JPanel that is under the input area by repainting that area. It doesn't really work as intended because the rectangles aren't the same size (as I wanted to) and the repaint method only works when I resize the window. </p>
<blockquote>
<p>MainFrame.java</p>
</blockquote>
<pre><code>//This is just a class that I use to create the JFrame in the main class, so I can work directly on the JFrame just here
public class MainFrame extends JFrame
{
public MainFrame(String title, int width, int height)
{
super(title);
this.setSize(width, height);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
</code></pre>
<blockquote>
<p>MainWindow.java</p>
</blockquote>
<pre><code>//This is the main class where I'm trying to have as little code as possible
public class MainWindow
{
public static void main(String[] args)
{
MainFrame frame = new MainFrame("RandomRectangles", 500, 500);
RectanglesPanel rectangles = new RectanglesPanel(frame);
JPanel mainPanel = new JPanel(new BorderLayout());
InputPanel inputPanel = new InputPanel();
//Is adding the listener here a "good practice" or not?
inputPanel.getButton().addActionListener(e ->
{
//adds all the rectangles in the JPanel
for(int c = 0; c < Integer.parseInt(inputPanel.getTextField().getText()); c++)
{
RectangleComponent box = new RectangleComponent();
rectangles.add(box);
}
mainPanel.repaint();
});
mainPanel.add(inputPanel, BorderLayout.NORTH);
mainPanel.add(rectangles, BorderLayout.CENTER);
frame.add(mainPanel);
frame.setVisible(true);
}
}
</code></pre>
<blockquote>
<p>RectanglesPanel.java</p>
</blockquote>
<pre><code>//This is the panel that I use as a "canvas" to paint the rectangles
public class RectanglesPanel extends JPanel
{
public RectanglesPanel(MainFrame frame)
{
super(new GridLayout());
this.setPreferredSize(new Dimension(frame.getWidth() - 100, frame.getHeight() - 100));
this.setBackground(Color.BLACK);
}
}
</code></pre>
<blockquote>
<p>InputPanel.java</p>
</blockquote>
<pre><code>//The panel where the input stuff happens, I added those methods because I needed them where I added the listener to the button, but again I don't know if this is a "good practice" or not
public class InputPanel extends JPanel
{
private JButton button;
private JLabel label;
private JTextField text;
public InputPanel()
{
super(new FlowLayout());
button = new JButton("Ok");
label = new JLabel("How many rectangles?");
text = new JTextField(10);
this.add(label);
this.add(text);
this.add(button);
}
public JButton getButton()
{
return this.button;
}
public JTextField getTextField()
{
return this.text;
}
}
</code></pre>
<blockquote>
<p>RectangleComponent.java</p>
</blockquote>
<pre><code>//Here's the rectangles that are a JComponent
public class RectangleComponent extends JComponent
{
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
Random random = new Random();
//I draw them in a random location every time, but supposedly with the same dimensions
Rectangle box = new Rectangle(random.nextInt(getWidth()), random.nextInt(getHeight()), 30, 20);
g2.setColor(Color.RED);
g2.fill(box);
g2.draw(box);
}
@Override
public Dimension getPreferredSize()
{
return new Dimension(30, 20);
}
@Override
public Dimension getMaximumSize()
{
return new Dimension(30, 20);
}
@Override
public Dimension getMinimumSize()
{
return new Dimension(30, 20);
}
}
</code></pre>
<p>Is there something I can improve in the way I'm writing this code?
Also, this is my first question here so let me know if I've done something wrong with the post, I'll edit it.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-19T18:18:34.943",
"Id": "454414",
"Score": "1",
"body": "It's because I first posted this question on stackoverflow, but they told me to ask here and I just copy and pasted what I wrote there, my bad. Anyway you're right, I'll edit the post trying to explain myself better"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-19T20:17:24.910",
"Id": "454422",
"Score": "0",
"body": "Haven't read all your code yet but be aware there's no one single \"right way\" to write code, including Swing. Often it depends (heavily) on the problem. Just wanted to address that one point."
}
] |
[
{
"body": "<p>Swing code is generally appalling, and that includes the tutorials.</p>\n\n<p>As always in Java, don't go around subclassing classes you don't need to. You wouldn't dare subclass <code>Thread</code> (any more), so don't subclass <code>JFrame</code> or <code>JPanel</code>. However, for <code>JComponent.paintComponent</code> methods is being overridden sensibly, the <code>get</code> method should be replaced by calling the appropriate <code>set</code>s.</p>\n\n<p>What appear to be \"objects\" in naïve object orientation, should really be just plain functions. However, often processes should be object - think of them of processors.</p>\n\n<p>Classes that are just a collection of fields with get (and possibly set) method, are probably a bad idea. You'll also see <code>get</code> followed only by an action on the gotten value.</p>\n\n<p>Swing (and in practice AWT) should only be used from the AWT Event Dispatch Thread (EDT). <code>main</code> executes in a different thread. So you need to switch threads.</p>\n\n<pre><code>public static void main(String[] args) {\n java.awt.EventQueue.invokeLater(MyApp::swingGo);\n}\nprivate static void swingGo() {\n</code></pre>\n\n<p>Your <code>RectanglePanel</code> attempts to derive its preferred size from the size of a <code>JFrame</code>. That wont update when the window is resized, and looks to be attempting to do something a <code>LayoutManager</code> should be doing.</p>\n\n<p>That <code>repaint</code> should be a <code>revalidate</code> as you are adding components.</p>\n\n<p>I don't think you don't need to both <code>fill</code> and <code>draw</code> the rectangle in the same colour.</p>\n\n<p><code>Integer.parseInt</code> may throw an exception, so that should be caught rather than thrown (no need to dump the stack tract).</p>\n\n<p>In terms of style: In Java open braces are usually on the same line as the statement they belong to. <code>parseInt</code> could be stored in a local variable, rather than living within the <code>for</code> statement.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T10:44:07.540",
"Id": "454733",
"Score": "2",
"body": "I have a gut feeling that Swing code is apalling because the tutorials try to cram everything needed in the case into a single class and programmers just follow the instructions. Doing a proper MVC would take too much \"blog space\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T13:17:38.200",
"Id": "454748",
"Score": "1",
"body": "@TorbenPutkonen Proper MVC? Have you seen the arrows if you image google MVC? https://www.google.co.uk/search?tbm=isch&q=mvc I'm happy with the new development with some diagrams having four boxes."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-19T19:05:12.167",
"Id": "232654",
"ParentId": "232649",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-19T17:00:41.503",
"Id": "232649",
"Score": "2",
"Tags": [
"java",
"swing",
"gui",
"user-interface"
],
"Title": "How to properly write code for Java Swing"
}
|
232649
|
<p>A month ago I reviewed the code in <a href="https://codereview.stackexchange.com/q/230486/120114">Resizable split DIVs Vue.js</a>, suggesting that the OP use computed properties and bound styles to simplify the code (at least reducing the need to use <code>$refs</code> to access DOM elements). Below are two variations I devised. They are very similar. The main difference is that the second uses <code>-1</code> for the initial values and ternary operators to check if the data values are set. Are those good improvements? What else would you change?</p>
<p>The user can drag the vertical bar, as well as the two horizontal bars, to resize the containers.</p>
<p>There are two approaches below. In the first one the position data properties are initialized to empty strings, whereas in the second they are initialized to <code>-1</code>. This affects the logic within the computed property methods.</p>
<p>Note: this appears to only work with Chrome, Opera, IE and Edge. There is something with the OPs original code that doesn't allow the dragging to work with FF or Safari. It appears <code>clientX</code> and <code>clientY</code> values are not set in those browsers, which maybe the same as <a href="https://stackoverflow.com/questions/11656061/event-clientx-showing-as-0-in-firefox-for-dragend-event">this issue</a>.</p>
<p><a href="https://i.stack.imgur.com/dCpkz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dCpkz.png" alt="sample screenshot" /></a></p>
<h2>Non-ternary approach with empty strings as initial values</h2>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const app = new Vue({
el: '#app',
data: {
lrDividerPos: '',
rtbDividerPos: '',
ltbDividerPos: '',
},
computed: {
bottomLeftStyle: function() {
const style = {};
if (this.lrDividerPos) {
style.width = this.lrDividerPos + 'px';
}
if (this.ltbDividerPos) {
style.height = (window.innerHeight - this.ltbDividerPos) + 'px';
style.top = this.ltbDividerPos + 'px';
}
return style;
},
bottomRightStyle: function() {
const style = {};
if (this.lrDividerPos) {
style.left = this.lrDividerPos + 'px';
style.width = (window.innerWidth - this.lrDividerPos + 2) + 'px';
}
if (this.rtbDividerPos) {
style.top = this.rtbDividerPos + 'px';
style.height = (window.innerHeight - this.rtbDividerPos) + 'px';
}
return style;
},
leftDividerStyles: function() {
if (this.lrDividerPos) {
return {
width: (this.lrDividerPos + 2) + 'px'
};
}
return {};
},
ltbDividerStyles: function() {
const style = {};
if (this.lrDividerPos) {
style.width = this.lrDividerPos + 2 + 'px';
}
if (this.ltbDividerPos) {
style.top = this.ltbDividerPos + 'px';
}
return style;
},
lrDividerStyles: function() {
if (this.lrDividerPos) {
return {
left: this.lrDividerPos + 'px'
};
}
return {};
},
rtbDividerStyles: function() {
const style = {};
if (this.lrDividerPos) {
style.left = this.lrDividerPos + 'px';
style.width = (window.innerWidth - this.lrDividerPos + 2) + 'px';
}
if (this.rtbDividerPos) {
style.top = this.rtbDividerPos + 'px';
}
return style;
},
topLeftStyle: function() {
const style = {};
if (this.ltbDividerPos) {
style.height = this.ltbDividerPos + 'px';
}
if (this.lrDividerPos) {
style.width = this.lrDividerPos + 'px';
}
return style;
},
topRightStyle: function() {
const style = {};
if (this.lrDividerPos) {
style.left = this.lrDividerPos + 'px';
style.width = (window.innerWidth - this.lrDividerPos + 2) + 'px';
}
if (this.rtbDividerPos) {
style.height = this.rtbDividerPos + 'px';
}
return style;
}
},
methods: {
lrDividerDrag: function(e) {
if (e.clientX) {
this.lrDividerPos = e.clientX;
}
},
ltbDividerDrag: function(e) {
if (e.clientY) {
this.ltbDividerPos = e.clientY;
}
},
rtbDividerDrag: function(e) {
if (e.clientY) {
this.rtbDividerPos = e.clientY;
}
},
dividerDragStart: function(e) {
e.dataTransfer.setDragImage(new Image, 0, 0);
}
}
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.text-area {
margin: 10px;
}
.container {
position: absolute;
overflow: scroll;
top: 0;
left: 0;
height: 50%;
width: 50%;
}
.top-left {
background-color: pink;
}
.top-right {
background-color: lightgreen;
left: 50%;
}
.bottom-left {
background-color: lightblue;
top: 50%;
}
.bottom-right {
background-color: lightyellow;
top: 50%;
left: 50%;
}
.divider {
position: absolute;
background-color: black;
}
.left-right {
width: 4px;
height: 100%;
top: 0;
left: calc(50% - 4px / 2);
}
.right-top-bottom {
width: 50%;
height: 4px;
top: calc(50% - 4px / 2);
left: 50%;
}
.left-top-bottom {
width: 50%;
height: 4px;
top: calc(50% - 4px / 2);
left: 0;
}
.left-right:hover {
cursor: col-resize;
}
.left-top-bottom:hover,
.right-top-bottom:hover {
cursor: row-resize;
}
::-webkit-scrollbar {
height: 0;
width: 0;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
<div>
<div class="top-left container" :style="topLeftStyle">
<div class="text-area">
<h3>Resize me using the black bars</h3>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
</div>
<div class="top-right container" :style="topRightStyle">
<div class="text-area">
<h3>Resize me using the black bars</h3>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
</div>
<div class="bottom-left container" :style="bottomLeftStyle">
<div class="text-area">
<h3>Resize me using the black bars</h3>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
</div>
<div class="bottom-right container" :style="bottomRightStyle">
<div class="text-area">
<h3>Resize me using the black bars</h3>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
</div>
<div class="left-right divider" draggable="true" @dragstart="dividerDragStart" @drag="lrDividerDrag" :style="lrDividerStyles"></div>
<div class="right-top-bottom divider" draggable="true" @drag="rtbDividerDrag" @dragstart="dividerDragStart" :style="rtbDividerStyles"></div>
<div class="left-top-bottom divider" draggable="true" @drag="ltbDividerDrag" @dragstart="dividerDragStart" :style="ltbDividerStyles"></div>
</div>
</div></code></pre>
</div>
</div>
</p>
<h2>Ternary approach with negative initial values</h2>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const app = new Vue({
el: '#app',
data: {
lrDividerPos: -1,
rtbDividerPos: -1,
ltbDividerPos: -1,
},
computed: {
bottomLeftStyle: function() {
return {
height: this.ltbDividerPos > -1 ? (window.innerHeight - this.ltbDividerPos) + 'px' : '',
top: this.ltbDividerPos > -1 ? this.ltbDividerPos + 'px' : '',
width: this.lrDividerPos > -1 ? this.lrDividerPos + 'px' : ''
};
},
bottomRightStyle: function() {
return {
height: this.rtbDividerPos > -1 ? (window.innerHeight - this.rtbDividerPos) + 'px' : '',
left: this.lrDividerPos > -1 ? this.lrDividerPos + 'px' : '',
top: this.rtbDividerPos > -1 ? this.rtbDividerPos + 'px' : '',
width: this.lrDividerPos > -1 ? (window.innerWidth - this.lrDividerPos + 2) + 'px' : ''
};
},
leftDividerStyles: function() {
return {
width: this.lrDividerPos > -1 ? (this.lrDividerPos + 2) + 'px' : ''
};
},
ltbDividerStyles: function() {
return {
top: this.ltbDividerPos > -1 ? this.ltbDividerPos + 'px' : '',
width: this.lrDividerPos > -1 ? this.lrDividerPos + 2 + 'px' : ''
};
},
lrDividerStyles: function() {
return {
left: this.lrDividerPos > -1 ? this.lrDividerPos + 'px' : ''
};
},
rtbDividerStyles: function() {
return {
left: this.lrDividerPos > -1 ? this.lrDividerPos + 'px' : '',
top: this.rtbDividerPos > -1 ? this.rtbDividerPos + 'px' : '',
width: this.lrDividerPos > -1 ? (window.innerWidth - this.lrDividerPos + 2) + 'px' : ''
};
},
topLeftStyle: function() {
return {
height: this.ltbDividerPos > -1 ? this.ltbDividerPos + 'px' : '',
width: this.lrDividerPos > -1 ? this.lrDividerPos + 'px' : ''
};
},
topRightStyle: function() {
return {
height: this.rtbDividerPos > -1 ? this.rtbDividerPos + 'px' : '',
left: this.lrDividerPos > -1 ? this.lrDividerPos + 'px' : '',
width: this.lrDividerPos > -1 ? (window.innerWidth - this.lrDividerPos + 2) + 'px' : ''
};
}
},
methods: {
lrDividerDrag: function(e) {
if (e.clientX) {
this.lrDividerPos = e.clientX;
}
},
ltbDividerDrag: function(e) {
if (e.clientY) {
this.ltbDividerPos = e.clientY;
}
},
rtbDividerDrag: function(e) {
if (e.clientY) {
this.rtbDividerPos = e.clientY;
}
},
dividerDragStart: function(e) {
e.dataTransfer.setDragImage(new Image, 0, 0);
}
}
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.text-area {
margin: 10px;
}
.container {
position: absolute;
overflow: scroll;
top: 0;
left: 0;
height: 50%;
width: 50%;
}
.top-left {
background-color: pink;
}
.top-right {
background-color: lightgreen;
left: 50%;
}
.bottom-left {
background-color: lightblue;
top: 50%;
}
.bottom-right {
background-color: lightyellow;
top: 50%;
left: 50%;
}
.divider {
position: absolute;
background-color: black;
}
.left-right {
width: 4px;
height: 100%;
top: 0;
left: calc(50% - 4px / 2);
}
.right-top-bottom {
width: 50%;
height: 4px;
top: calc(50% - 4px / 2);
left: 50%;
}
.left-top-bottom {
width: 50%;
height: 4px;
top: calc(50% - 4px / 2);
left: 0;
}
.left-right:hover {
cursor: col-resize;
}
.left-top-bottom:hover,
.right-top-bottom:hover {
cursor: row-resize;
}
::-webkit-scrollbar {
height: 0;
width: 0;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
<div>
<div class="top-left container" :style="topLeftStyle">
<div class="text-area">
<h3>Resize me using the black bars</h3>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
</div>
<div class="top-right container" :style="topRightStyle">
<div class="text-area">
<h3>Resize me using the black bars</h3>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
</div>
<div class="bottom-left container" :style="bottomLeftStyle">
<div class="text-area">
<h3>Resize me using the black bars</h3>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
</div>
<div class="bottom-right container" :style="bottomRightStyle">
<div class="text-area">
<h3>Resize me using the black bars</h3>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
</div>
<div class="left-right divider" draggable="true" @dragstart="dividerDragStart" @drag="lrDividerDrag" :style="lrDividerStyles"></div>
<div class="right-top-bottom divider" draggable="true" @drag="rtbDividerDrag" @dragstart="dividerDragStart" :style="rtbDividerStyles"></div>
<div class="left-top-bottom divider" draggable="true" @drag="ltbDividerDrag" @dragstart="dividerDragStart" :style="ltbDividerStyles"></div>
</div>
</div></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>In accordance with the D.R.Y. principle: the markup can be simplified by registering a <a href=\"https://vuejs.org/v2/guide/components.html\" rel=\"nofollow noreferrer\">component</a> - and a template can be used with an <a href=\"https://vuejs.org/v2/guide/components-edge-cases.html#X-Templates\" rel=\"nofollow noreferrer\">X-Template</a>. For example - add a <code><script></code> tag like this:</p>\n<pre><code><script type="text/x-template" id="text-container-template">\n <div class="container">\n <div class="text-area">\n <h3>Resize me using the black bars</h3>\n\n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor\n in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n </div>\n </div>\n</script>\n</code></pre>\n<p>And then register that component before the Vue app instance is created:</p>\n<pre><code>Vue.component('text-container', {\n template: '#text-container-template'\n});\n</code></pre>\n<p>Then the markup for the main application can be simplified to just the following:</p>\n<pre><code><div id="app">\n <div>\n <text-container class="top-left" :style="topLeftStyle">\n </text-container>\n <text-container class="top-right" :style="topRightStyle">\n </text-container>\n <text-container class="bottom-left" :style="bottomLeftStyle">\n </text-container>\n <text-container class="bottom-right" :style="bottomRightStyle">\n </text-container>\n <div class="left-right divider" draggable="true" @dragstart="dividerDragStart" \n @drag="lrDividerDrag" :style="lrDividerStyles"></div>\n <div class="right-top-bottom divider" draggable="true" @drag="rtbDividerDrag" \n @dragstart="dividerDragStart" :style="rtbDividerStyles"></div>\n <div class="left-top-bottom divider" draggable="true" @drag="ltbDividerDrag" \n @dragstart="dividerDragStart" :style="ltbDividerStyles"></div>\n </div>\n</div>\n</code></pre>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>Vue.component('text-container', {\n template: '#text-container-template'\n});\nconst app = new Vue({\n el: '#app',\n data: {\n lrDividerPos: '',\n rtbDividerPos: '',\n ltbDividerPos: '',\n },\n computed: {\n bottomLeftStyle: function() {\n const style = {};\n if (this.lrDividerPos) {\n style.width = this.lrDividerPos + 'px';\n }\n if (this.ltbDividerPos) {\n style.height = (window.innerHeight - this.ltbDividerPos) + 'px';\n style.top = this.ltbDividerPos + 'px';\n }\n return style;\n },\n bottomRightStyle: function() {\n const style = {};\n if (this.lrDividerPos) {\n style.left = this.lrDividerPos + 'px';\n style.width = (window.innerWidth - this.lrDividerPos + 2) + 'px';\n }\n if (this.rtbDividerPos) {\n style.top = this.rtbDividerPos + 'px';\n style.height = (window.innerHeight - this.rtbDividerPos) + 'px';\n }\n return style;\n },\n leftDividerStyles: function() {\n if (this.lrDividerPos) {\n return {\n width: (this.lrDividerPos + 2) + 'px'\n };\n }\n return {};\n },\n ltbDividerStyles: function() {\n const style = {};\n if (this.lrDividerPos) {\n style.width = this.lrDividerPos + 2 + 'px';\n }\n if (this.ltbDividerPos) {\n style.top = this.ltbDividerPos + 'px';\n }\n return style;\n },\n lrDividerStyles: function() {\n if (this.lrDividerPos) {\n return {\n left: this.lrDividerPos + 'px'\n };\n }\n return {};\n },\n rtbDividerStyles: function() {\n const style = {};\n if (this.lrDividerPos) {\n style.left = this.lrDividerPos + 'px';\n style.width = (window.innerWidth - this.lrDividerPos + 2) + 'px';\n }\n if (this.rtbDividerPos) {\n style.top = this.rtbDividerPos + 'px';\n }\n return style;\n },\n topLeftStyle: function() {\n const style = {};\n if (this.ltbDividerPos) {\n style.height = this.ltbDividerPos + 'px';\n }\n if (this.lrDividerPos) {\n style.width = this.lrDividerPos + 'px';\n }\n return style;\n },\n topRightStyle: function() {\n const style = {};\n if (this.lrDividerPos) {\n style.left = this.lrDividerPos + 'px';\n style.width = (window.innerWidth - this.lrDividerPos + 2) + 'px';\n }\n if (this.rtbDividerPos) {\n style.height = this.rtbDividerPos + 'px';\n }\n return style;\n }\n },\n methods: {\n lrDividerDrag: function(e) {\n if (e.clientX) {\n this.lrDividerPos = e.clientX;\n }\n },\n ltbDividerDrag: function(e) {\n if (e.clientY) {\n this.ltbDividerPos = e.clientY;\n }\n },\n rtbDividerDrag: function(e) {\n if (e.clientY) {\n this.rtbDividerPos = e.clientY;\n }\n },\n dividerDragStart: function(e) {\n e.dataTransfer.setDragImage(new Image, 0, 0);\n }\n }\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.text-area {\n margin: 10px;\n}\n.container {\n position: absolute;\n overflow: scroll;\n top: 0;\n left: 0;\n height: 50%;\n width: 50%;\n}\n.top-left {\n background-color: pink;\n}\n\n.top-right {\n background-color: lightgreen;\n left: 50%;\n}\n\n.bottom-left {\n background-color: lightblue;\n top: 50%;\n}\n\n.bottom-right {\n background-color: lightyellow;\n top: 50%;\n left: 50%;\n}\n\n.divider {\n position: absolute;\n background-color: black;\n}\n\n.left-right {\n width: 4px;\n height: 100%;\n top: 0;\n left: calc(50% - 4px / 2);\n}\n\n.right-top-bottom {\n width: 50%;\n height: 4px;\n top: calc(50% - 4px / 2);\n left: 50%;\n}\n\n.left-top-bottom {\n width: 50%;\n height: 4px;\n top: calc(50% - 4px / 2);\n left: 0;\n}\n\n.left-right:hover {\n cursor: col-resize;\n}\n\n.left-top-bottom:hover,\n.right-top-bottom:hover {\n cursor: row-resize;\n}\n\n::-webkit-scrollbar {\n height: 0;\n width: 0;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><script src=\"https://cdn.jsdelivr.net/npm/vue/dist/vue.js\"></script>\n<script type=\"text/x-template\" id=\"text-container-template\">\n <div class=\"container\">\n <div class=\"text-area\">\n <h3>Resize me using the black bars</h3>\n\n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor\n in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n </div>\n </div>\n</script>\n<div id=\"app\">\n <div>\n <text-container class=\"top-left\" :style=\"topLeftStyle\">\n </text-container>\n <text-container class=\"top-right\" :style=\"topRightStyle\">\n </text-container>\n <text-container class=\"bottom-left\" :style=\"bottomLeftStyle\">\n </text-container>\n <text-container class=\"bottom-right\" :style=\"bottomRightStyle\">\n </text-container>\n <div class=\"left-right divider\" draggable=\"true\" @dragstart=\"dividerDragStart\" @drag=\"lrDividerDrag\" :style=\"lrDividerStyles\"></div>\n <div class=\"right-top-bottom divider\" draggable=\"true\" @drag=\"rtbDividerDrag\" @dragstart=\"dividerDragStart\" :style=\"rtbDividerStyles\"></div>\n <div class=\"left-top-bottom divider\" draggable=\"true\" @drag=\"ltbDividerDrag\" @dragstart=\"dividerDragStart\" :style=\"ltbDividerStyles\"></div>\n </div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-28T21:18:14.670",
"Id": "263565",
"ParentId": "232651",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-19T17:39:57.150",
"Id": "232651",
"Score": "11",
"Tags": [
"javascript",
"comparative-review",
"event-handling",
"rags-to-riches",
"vue.js"
],
"Title": "Resizable containers with VueJS"
}
|
232651
|
<p>This is the first time I‘ve used Rust, and I'd like to have some feedback on this project. The <code>Grid</code> class should be able to store objects of any type; it's a simple 2D grid that implements the bare minimum of interfaces. Only the <code>copy_sub_grid</code> function is a bit fancy here, nothing else is too crazy.</p>
<pre><code>pub type Coordinate = (usize, usize);
pub type Dimension = (usize, usize);
pub type GridAction<T> = fn(target: &mut T);
pub struct Grid<T> {
column_count: usize,
row_count: usize,
data: Vec<T>
}
impl<T> Grid<T>
where
T: Copy,
{
pub fn new(column_count: usize, row_count: usize, default: T) -> Self
{
let capacity = row_count * column_count;
Self {
column_count: column_count,
row_count: row_count,
data: vec![default; capacity],
}
}
pub fn get_capacity(&self) -> usize {
return self.row_count * self.column_count;
}
pub fn height(&self) -> usize {
return self.row_count;
}
pub fn width(&self) -> usize {
return self.column_count;
}
pub fn get_mut(&mut self, position: Coordinate) -> Option<&mut T> {
if self.in_grid(position) {
let i = self.get_index(position);
return Some(&mut self.data[i]);
} else {
return None
}
}
pub fn get(&self, position: Coordinate) -> Option<&T> {
if self.in_grid(position) {
return Some(&self.data[self.get_index(position)]);
} else {
None
}
}
pub fn set(&mut self, position: Coordinate, new_value: T) {
match self.get_mut(position) {
Some(value) => {
*value = new_value;
}
None => ()
}
}
pub fn map(&mut self, func: GridAction<T>) {
for element in &mut self.data {
func(element);
}
}
pub fn swap(&mut self, position1: Coordinate, position2: Coordinate) {
let index1 = self.get_index(position1);
let index2 = self.get_index(position2);
self.data.swap(index1, index2);
}
pub fn copy_sub_grid(&self, (x, y): Coordinate, (w, h): Dimension, default: T) -> Option<Grid<T>> {
if self.in_grid((x + w, y + h)) {
let mut new_grid = Grid::new(w, h, default);
for row_i in y .. y + h {
for col_i in x .. x + w {
let flat_i = self.get_index((col_i, row_i));
let value = self.data[flat_i];
new_grid.set((col_i - x, row_i - y), value);
}
}
return Some(new_grid);
} else {
return None;
}
}
fn get_index(&self, (x, y): Coordinate) -> usize {
return x + y * self.column_count;
}
fn in_grid(&self, (x, y): Coordinate) -> bool {
return x < self.column_count && y < self.row_count;
}
}
#[test]
fn test_new() {
let mut _grid = Grid::new(10, 15, 0);
assert_eq!(150, _grid.get_capacity());
assert_eq!(15, _grid.height());
assert_eq!(10, _grid.width());
}
#[test]
fn test_get_set() {
let mut _grid = Grid::new(10, 15, 0);
_grid.set((5, 5), 10);
let _value = _grid.get_mut((5,5)).unwrap();
assert_eq!(&10, _value);
*_value = 11;
assert_eq!(&11, _value);
assert_eq!(&11, _grid.get((5,5)).unwrap());
}
#[test]
fn test_swap() {
let mut _grid = Grid::new(10, 15, 0);
_grid.set((5, 5), 10);
_grid.swap((5,5), (1,2));
assert_eq!(&0, _grid.get((5,5)).unwrap());
assert_eq!(&10, _grid.get((1,2)).unwrap());
}
#[test]
fn test_map() {
let mut _grid = Grid::new(10, 15, 1);
_grid.map(|x| *x = *x * 2);
assert_eq!(&2, _grid.get((5,5)).unwrap());
}
#[test]
fn test_sub_grid() {
let mut _grid = Grid::new(10, 15, 1);
_grid.set((5, 5), 10);
let new_grid = _grid.copy_sub_grid((2,2), (6, 6), 1).unwrap();
assert_eq!(36, new_grid.get_capacity());
assert_eq!(6, new_grid.height());
assert_eq!(6, new_grid.width());
assert_eq!(&10, new_grid.get((3,3)).unwrap());
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-19T20:42:13.207",
"Id": "454424",
"Score": "2",
"body": "This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you. [Questions should include a description of what the code does](//codereview.meta.stackexchange.com/q/1226)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T13:39:38.333",
"Id": "454615",
"Score": "0",
"body": "@EthanBierlein What context is missing? It's a 2D grid, with basic grid functions, there even are unit tests at the bottom to explain what the code does. I really don't believe this is incomplete."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T17:39:41.663",
"Id": "454671",
"Score": "1",
"body": "I think some description was missing in the initial message. I edited it so that readers can grasp what the code does without reading it."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-19T20:27:58.227",
"Id": "232659",
"Score": "3",
"Tags": [
"rust"
],
"Title": "Rust 2D grid class"
}
|
232659
|
<p><a href="https://codereview.stackexchange.com/questions/231141/implementing-simplified-jaipur-board-game">Link to my previous question.</a></p>
<p>I've implemented the other features of the <a href="https://boardgamegeek.com/boardgame/54043/jaipur" rel="nofollow noreferrer">board game</a>, and made a simple learning method that stores state values and makes optimal moves based on that. </p>
<p>I've used some OOP concepts, but I'm not sure if I've used them appropriately.</p>
<p><strong>Edit:</strong></p>
<p>I'm mainly interested in a review of the system design, the way objects are structured & handled, the way <code>Jaipur</code> object is modified from within <code>Player</code> class (in the <code>make_optimal_move</code> method) when <code>Jaipur</code> itself contains <code>Player</code> objects. </p>
<p><strong>agent_jaipur.py</strong></p>
<pre><code>import random
from enum import Enum, IntEnum, unique
from itertools import cycle, combinations, product
from collections import Counter
import numpy as np
import copy
import pickle
state_values = dict()
@unique
class Commodity(IntEnum):
CAMEL = 0
LEATHER = 1
SPICE = 2
SILK = 3
SILVER = 4
GOLD = 5
DIAMOND = 6
@classmethod
def is_costly(self, commodity):
return commodity in [self.DIAMOND, self.GOLD, self.SILVER]
class Jaipur:
def __init__(self, player1_type, player2_type, muted=False):
self.muted = muted
self.price_tokens = {
Commodity.DIAMOND: [5, 5, 5, 7, 7],
Commodity.GOLD: [5, 5, 5, 6, 6],
Commodity.SILVER: [5, 5, 5, 5, 5],
Commodity.SILK: [1, 1, 2, 2, 3, 3, 5],
Commodity.SPICE: [1, 1, 2, 2, 3, 3, 5],
Commodity.LEATHER: [1, 1, 1, 1, 1, 1, 2, 3, 4],
}
self._pile = [Commodity.DIAMOND] * 6 + [Commodity.GOLD] * 6 + [Commodity.SILVER] * 6 + \
[Commodity.SILK] * 8 + [Commodity.SPICE] * 8 + [Commodity.LEATHER] * 10 + \
[Commodity.CAMEL] * 8
random.shuffle(self._pile)
self.market = Counter()
for i in Commodity:
self.market[i] = 0
self.market[Commodity.CAMEL] = 3
for i in range(2):
self.market[self._pile.pop()] += 1
self._player1 = player1_type(tag='P1', game=self)
self._player2 = player2_type(tag='P2', game=self)
for i in range(5):
for _player in self._player1, self._player2:
commodity = self._pile.pop()
if commodity == Commodity.CAMEL:
_player.camel_count += 1
else:
_player.hand[commodity] += 1
self.winner = None
self._players_gen = cycle([self._player1, self._player2])
self.player_turn = next(self._players_gen)
def pile_size(self):
return len(self._pile)
def pick_commodity(self, commodity=None):
if sum(self.market.values()) == 0:
return (None, 0)
if commodity is not None and self.market[commodity] > 0:
picked_commodity = commodity
else:
market_list = []
for c in self.market:
if self.market[c] > 0:
market_list += [c] * self.market[c]
picked_commodity = random.choice(market_list)
pick_count = 0
# When player takes camel, all camels in market must be taken
if picked_commodity == Commodity.CAMEL:
market_camels = self.market[Commodity.CAMEL]
pick_count = market_camels
self.market[Commodity.CAMEL] = 0
for i in range(market_camels):
if self._pile:
self.market[self._pile.pop()] += 1
else:
pick_count = 1
self.market[picked_commodity] -= 1
if self._pile:
self.market[self._pile.pop()] += 1
return (picked_commodity, pick_count)
def pprint(self, s, c):
print(s, end=' ')
for i in c.keys():
if c[i] > 0:
print('%s: %d,'%(i, c[i]), end=' ')
print()
def print_game(self):
if self.muted:
return
print('price_tokens: ', self.price_tokens.values())
print('pile size:', self.pile_size())
self.pprint('market: ', self.market)
self.pprint('P1 hand: ', self._player1.hand)
self.pprint('P2 hand: ', self._player2.hand)
print('P1 camels:', self._player1.camel_count)
print('P2 camels:', self._player2.camel_count)
print('P1 tokens: ', self._player1.tokens)
print('P2 tokens: ', self._player2.tokens)
print('P1 score:', self._player1.score())
print('P2 score:', self._player2.score())
print('Winner is', self.winner)
print()
def play_game(self, learn, muted=False):
self.muted = muted
print('----------------- GAME STARTED -------------------')
self.print_game()
while self.winner is None:
if not self.muted:
print('---------------------', self.player_turn.tag, ' turn', '---------------------')
self.print_game()
self = self.switch_player(learn)
self.game_winner()
else:
print('----------------- GAME ENDED -------------------')
self.print_game()
print('P1 final score:', self._player1.final_score)
print('P2 final score:', self._player2.final_score)
print()
if isinstance(self._player1, Agent):
self._player1.learn_state(self._player1.get_state(), self.winner)
if isinstance(self._player2, Agent):
self._player2.learn_state(self._player2.get_state(), self.winner)
return self.winner
def switch_player(self, learn):
self = self.player_turn.make_move(self.winner, learn)
self.player_turn = next(self._players_gen)
return self
def game_winner(self):
# End game if 3 resources are sold completely
# Or if market goes less than 5
if len(['empty' for i in self.price_tokens.values() if not i]) >= 3 or (sum(self.market.values()) < 5):
self._player1.final_score = self._player1.score()
self._player2.final_score = self._player2.score()
if self._player1.camel_count > self._player2.camel_count:
self._player1.final_score += 5
elif self._player1.camel_count < self._player2.camel_count:
self._player2.final_score += 5
if self._player1.final_score > self._player2.final_score:
self.winner = self._player1.tag
elif self._player1.final_score < self._player2.final_score:
self.winner = self._player2.tag
else:
self.winner = self._player2.tag #TODO
return self.winner
class Player:
def __init__(self, tag, game):
self.tag = tag
self.camel_count = 0
self.hand = Counter()
for i in Commodity:
self.hand[i] = 0
self.tokens = []
self.final_score = 0
self._game = game
self.prev_state = self.get_state()
def hand_size(self):
return sum(self.hand.values())
def score(self):
return sum(self.tokens)
def get_state(self): #TODO
#return tuple((self.hand_size(), self.camel_count))
score = self.score() // 10
pile_size = self._game.pile_size() // 5
camel = self.camel_count // 4
# hand = tuple(self.hand.items())
hand = tuple(self.hand[i] for i in Commodity)
hand_size = self.hand_size()
# market = tuple(self._game.market.items())
market_costly = sum([self._game.market[i] for i in Commodity if Commodity.is_costly(i)])
market_non_costly = sum([self._game.market[i] for i in Commodity if (not Commodity.is_costly(i)) and (not i == Commodity.CAMEL)])
market_camel = sum([self._game.market[i] for i in Commodity if i == Commodity.CAMEL])
market = (market_costly, market_non_costly, market_camel)
state = tuple((score, pile_size, hand_size, camel, market))
return state
def get_possible_trades(self, give_commodities, take_commodities):
# print('give commodities', give_commodities)
# print('take commodities', take_commodities)
if len(give_commodities) < 2 or len(take_commodities) < 2:
return []
give_commodities = sorted(give_commodities)
take_commodities = sorted(take_commodities)
possible_trades = []
for trade_size in range(2, min(len(give_commodities), len(take_commodities)) + 1):
give_subsets = set(combinations(give_commodities, trade_size))
take_subsets = set(combinations(take_commodities, trade_size))
all_combinations = product(give_subsets, take_subsets)
for give, take in all_combinations:
if len(set(give).intersection(set(take))) == 0:
possible_trades += [(give, take)]
# print('possible trades')
# for i in possible_trades:
# print(i[0])
# print(i[1])
# print()
return possible_trades
def get_all_moves(self):
moves = [0, 1, 2] # TAKE, SELL, TRADE
take_commodities = [i for i in self._game.market if self._game.market[i] > 0]
sell_commodities = [i for i in self.hand if (self.hand[i] > 1) or (not Commodity.is_costly(i) and self.hand[i] > 0)]
all_moves = []
if self.hand_size() < 7:
all_moves += [(moves[0], i) for i in take_commodities]
all_moves += [(moves[1], i) for i in sell_commodities]
trade_give_commodities = []
for i in self.hand:
trade_give_commodities += [i] * self.hand[i]
trade_give_commodities += [Commodity.CAMEL] * self.camel_count
trade_take_commodities = []
for i in self._game.market:
if i != Commodity.CAMEL:
trade_take_commodities += [i] * self._game.market[i]
# TODO Enable trading
# possible_trades = self.get_possible_trades(trade_give_commodities, trade_take_commodities)
# all_moves += [(moves[2], i) for i in possible_trades]
return all_moves
def take(self, commodity=None):
# self._game.pprint('before taking:', self.hand)
if not self._game.muted:
print('taking..', commodity)
if self.hand_size() < 7:
taken, take_count = self._game.pick_commodity(commodity)
if taken == Commodity.CAMEL:
self.camel_count += take_count
else:
self.hand[taken] += take_count
# self._game.pprint('after taking:', self.hand)
def sell(self, commodity=None, count=0):
# print('before selling..', self.tokens)
if not self._game.muted:
print('selling..', commodity)
if commodity is None:
commodity = self.hand.most_common(1)[0][0]
if ((not Commodity.is_costly(commodity)) and self.hand[commodity] > 0) or self.hand[commodity] > 1:
count = self.hand[commodity] # TODO As of now sell all cards of this type
for i in range(count):
if self._game.price_tokens[commodity]:
self.tokens.append(self._game.price_tokens[commodity].pop())
self.hand[commodity] -= count
if count == 3:
self.tokens.append(random.randint(1, 4))
elif count == 4:
self.tokens.append(random.randint(4, 7))
elif count >= 5:
self.tokens.append(random.randint(7, 11))
# print('after selling...', self.tokens)
def trade(self, give=None, take=None):
# if not self._game.muted:
# print('trading..', (give, take))
if give == None or take == None:
return
if len(give) != len(take):
return
if len(give) < 2:
return
if(set(give).intersection(set(take))):
return
give = Counter(give)
take = Counter(take)
self.hand -= give
self._game.market += give
self._game.market -= take
self.hand += take
self.camel_count -= give[Commodity.CAMEL]
def make_move(self, winner, learn=False):
all_moves = self.get_all_moves()
# for i, move in enumerate(all_moves):
# print(i, move)
# move = int(input('Choose move..'))
move = random.choice(all_moves)
if move[0] == 0:
self.take(move[1])
elif move[0] == 1:
self.sell(move[1])
elif move[0] == 2:
self.trade(move[1][0], move[1][1])
return self._game
class Agent(Player):
def __init__(self, tag, game):
super().__init__(tag, game)
def make_move(self, winner, learn):
if learn:
self.learn_state(self.get_state(), winner)
if learn:
epsilon = 0.8
else:
epsilon = 1
p = random.uniform(0, 1)
if p < epsilon:
self._game = self.make_optimal_move()
else:
super().make_move(winner, learn)
return self._game
def make_optimal_move(self):
opt_self = None
v = -float('Inf')
all_moves = self.get_all_moves()
# print('all_moves')
# for i in all_moves:
# print(i)
for m, c in all_moves:
temp_self = copy.deepcopy(self)
if m == 0:
temp_self.take(c)
elif m == 1:
temp_self.sell(c)
elif m == 2:
temp_self.trade(c[0], c[1])
# print('after making move', m, c)
# temp_self._game.print_game()
# print()
temp_state = self.get_state()
v_temp = self.calc_value(temp_state)
# Encourage exploration
if v_temp is None:
v_temp = 1
if v_temp > v:
opt_self = copy.deepcopy(temp_self)
v = v_temp
elif v_temp == v:
toss = random.randint(0, 1)
if toss == 1:
opt_self = copy.deepcopy(temp_self)
self = copy.deepcopy(opt_self)
# print('Optimal self')
# opt_self._game.print_game()
# print()
# print('After making optimal move')
# self._game.print_game()
return self._game
def calc_value(self, state):
global state_values
if state in state_values.keys():
return state_values[state]
def learn_state(self, state, winner):
global state_values
# if winner is not None:
# state_values[state] = self.reward(winner)
if self.prev_state in state_values.keys():
v_s = state_values[self.prev_state]
else:
v_s = int(0)
R = self.reward(winner)
if state in state_values.keys() and winner is None:
v_s_tag = state_values[state]
else:
v_s_tag = int(0)
state_values[self.prev_state] = v_s + 0.5 * (R + v_s_tag - v_s)
self.prev_state = state
def reward(self, winner):
if winner is self.tag:
R = 1
elif winner is None:
R = 0
else:
R = -1
return R
def load_values():
global state_values
try:
f = open('state_values.pickle', 'rb')
state_values = pickle.load(f)
except:
state_values = dict()
def save_values():
global state_values
f = open('state_values.pickle', 'wb')
try:
os.remove(f)
except:
pass
pickle.dump(state_values, f)
def play_to_learn(episodes, muted=True):
load_values()
print(len(state_values))
for i in range(episodes):
print('Episode', i)
game = Jaipur(Agent, Player)
game.play_game(learn=True, muted=muted)
game = Jaipur(Player, Agent)
game.play_game(learn=True, muted=muted)
if i % 1000 == 0:
save_values()
save_values()
print(len(state_values))
count = 0
for i in state_values:
if state_values[i] not in (-0.5, 0, 0.5):
print(i, state_values[i])
count += 1
print(count)
# print(state_values)
def test(n=100):
load_values()
# print('----------------------------------------------------------------- Agent vs Agent')
# ava_p1_wins = 0
# for i in range(n):
# game = Jaipur(Agent, Agent)
# winner = game.play_game(learn=False, muted=True)
# if winner == 'P1':
# ava_p1_wins += 1
print('----------------------------------------------------------------- Agent vs Player')
avp_p1_wins = 0
for i in range(n):
game = Jaipur(Agent, Player)
winner = game.play_game(learn=False, muted=True)
if winner == 'P1':
avp_p1_wins += 1
print('----------------------------------------------------------------- Player vs Agent')
pva_p1_wins = 0
for i in range(n):
game = Jaipur(Player, Agent)
winner = game.play_game(learn=False, muted=True)
if winner == 'P1':
pva_p1_wins += 1
print('----------------------------------------------------------------- Player vs Player')
pvp_p1_wins = 0
for i in range(n):
game = Jaipur(Player, Player)
winner = game.play_game(learn=False, muted=True)
if winner == 'P1':
pvp_p1_wins += 1
print('----------------------------------------------------------------- Result')
# print('----------------------------------------------------------------- Agent vs Agent')
# print('Total:', n)
# print('P1:', ava_p1_wins)
# print('P2:', n - ava_p1_wins)
print('----------------------------------------------------------------- Agent vs Player')
print('Total:', n)
print('P1:', avp_p1_wins)
print('P2:', n - avp_p1_wins)
print('----------------------------------------------------------------- Player vs Agent')
print('Total:', n)
print('P1:', pva_p1_wins)
print('P2:', n - pva_p1_wins)
print('----------------------------------------------------------------- Player vs Player')
print('Total:', n)
print('P1:', pvp_p1_wins)
print('P2:', n - pvp_p1_wins)
def play():
# play_to_learn(10000, muted=True)
game = Jaipur(Player, Agent)
game.play_game(learn=False, muted=False)
test()
if __name__ == "__main__":
play()
</code></pre>
<p>The GitHub repository can be found <a href="https://github.com/t-thirupathi/jaipur-board-game" rel="nofollow noreferrer">here</a>.</p>
|
[] |
[
{
"body": "<p>I think your code too good to be True! I hope to code like you one day! </p>\n\n<p>Even so, there always exists improvements, no matter how few.</p>\n\n<h1>Bug</h1>\n\n<p>In the <code>save_values</code> function, there is a line <code>os.remove(f)</code> which raises an error, but is caught by the <code>except</code> statement, which just moves on to the next line of the code. Is <code>import os</code> statement missing? I believe so.</p>\n\n<h1>Improvements</h1>\n\n<p>I don't believe there are any improvements for <code>make_optimal_move</code>, but I will add them if I find any.</p>\n\n<hr>\n\n<p><code>from enum import Enum, IntEnum, unique</code><br>\n<code>import numpy as np</code></p>\n\n<p><code>Enum</code> and <code>np</code> is not used. Do you plan to use them later? Removing it is your wish.</p>\n\n<hr>\n\n<p>In <code>class Agent</code>, signature of method 'Agent.make_move()' doesn't match the signature of base method in the class 'Player'. </p>\n\n<p>The signature of <code>Agent.make_move()</code> is <code>make_move(self, winner, learn)</code> while the signature of <code>class Player</code> is <code>make_move(self, winner, learn=False)</code>. </p>\n\n<p>The signatures should always be the same.</p>\n\n<hr>\n\n<p>Use ternary operators.</p>\n\n<p>In the <code>Agent.make_move</code> function</p>\n\n<pre><code>if learn:\n epsilon = 0.8\nelse:\n epsilon = 1\n</code></pre>\n\n<p>can be replaced with </p>\n\n<pre><code>epsilon = 0.8 if learn else 1\n</code></pre>\n\n<p>and in <code>Agent.reward</code> function</p>\n\n<pre><code>if winner is self.tag:\n R = 1\nelif winner is None:\n R = 0\nelse:\n R = -1\n</code></pre>\n\n<p>can be replaced with</p>\n\n<pre><code>return 0 if winner is None else 1 if winner is self.tag else -1\n</code></pre>\n\n<hr>\n\n<p>According to <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> rules, variables in functions should be lower case.</p>\n\n<hr>\n\n<p>In <code>Jaipur.pick_commodity</code>,<br>\n<code>if sum(self.market.values()) == 0</code> can be replaced with <code>if not sum(self.market.values())</code></p>\n\n<p>and you can remove the redundant parenthesis in <code>return (None, 0)</code> and <code>return (picked_commodity, pick_count)</code></p>\n\n<p>See <a href=\"https://medium.com/the-andela-way/idiomatic-python-coding-the-smart-way-cc560fa5f1d6\" rel=\"nofollow noreferrer\">idiomatic</a> coding.</p>\n\n<p>Also, <code>pick_count = 0</code> can be removed. It is changed in the <code>if</code> statement or <code>else</code> statement anyway.</p>\n\n<hr>\n\n<p>In the <code>Player.get_state</code> method, <code>hand</code> is not used, so you can remove it.</p>\n\n<hr>\n\n<p>Define static methods with <code>@staticmethod</code></p>\n\n<p><code>Player.get_possible_trades</code>, <code>Agent.calc_value</code>, and <code>Jaipur.pprint</code> are static.</p>\n\n<hr>\n\n<p>In <code>Player.trade</code>, you are using <code>==</code> to compare <code>give</code> and <code>take</code> to <code>None</code>. You should always use <code>is</code> instead of <code>==</code> to compare a value and <code>None</code></p>\n\n<p>Remove the redundant parenthesis in the line <code>if(set(give).intersection(set(take))):</code></p>\n\n<p>Now, </p>\n\n<pre><code>if len(give) != len(take):\n return \n\nif len(give) < 2:\n return \n\nif set(give).intersection(set(take)):\n return\n</code></pre>\n\n<p>can be replaced with </p>\n\n<pre><code>if len(give) != len(take) or len(give) < 2 or set(give).intersection(set(take)):\n return\n</code></pre>\n\n<hr>\n\n<p>If I get more improvements, I'll be sure to edit them in!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T13:35:21.377",
"Id": "232798",
"ParentId": "232662",
"Score": "4"
}
},
{
"body": "<p>You code looks mostly good to me. Adding docstrings to it would definitly make it even better.</p>\n\n<hr>\n\n<p><em>Comments about the Jaipur class</em></p>\n\n<p><strong>Smaller functions</strong></p>\n\n<p>It could be a good idea to write small functions to have a higher level of abstractions without any consideration for the implementation details.</p>\n\n<p>For instance, you have <code>self._pile.pop()</code> in various places. It may be easier to understand if it was moved in a <code>def draw_card()</code> method (an additional idea could be to add an optional argument for the number of cards). That method could be called in the initialisation step as well.</p>\n\n<p>Also, the <code>if self._pile: self.market[self.draw_card()] += 1</code> could be moved in a <code>add_card_to_market()</code> method.</p>\n\n<p><strong>Duplicated code</strong></p>\n\n<p>Another way to remove duplicated code could be to consider what is actually different from one situation to another.\nIn the case \"when player takes camel\", only the way to get the number of cards picked is different. For every other aspect, the logic is the same. We could write:</p>\n\n<pre><code> # When player takes camel, all camels in market must be taken\n pick_count = self.market[picked_commodity] if picked_commodity == Commodity.CAMEL else 1\n self.market[picked_commodity] -= pick_count\n for i in range(pick_count):\n self.add_card_to_marker()\n\n return (picked_commodity, pick_count)\n</code></pre>\n\n<p><strong>Using the Python tools</strong></p>\n\n<p>In <code>pick_commodity</code>, you iterate over the <code>self.market</code> keys and then retrieve the associated values.\nYou could use <a href=\"https://docs.python.org/3.8/library/stdtypes.html#dict.items\" rel=\"noreferrer\">https://docs.python.org/3.8/library/stdtypes.html#dict.items</a> to iterate over both keys and values.</p>\n\n<pre><code> market_list = []\n for c, n in self.market.items():\n if n > 0:\n market_list += [c] * n\n</code></pre>\n\n<p>Also, another aspect of the Counter class you are using is that you do not need to initialise things to 0.</p>\n\n<p><strong>The part with 'empty'</strong></p>\n\n<p>I must confess that the part <code>len(['empty' for i in self.price_tokens.values() if not i]) >= 3</code> got me really puzzled. Where is this <code>'empty'</code> string coming from ?</p>\n\n<p>Here, you build a list where only the length will be relevant, not its content. You could use <code>None</code> as the content.</p>\n\n<pre><code>`len([None for i in self.price_tokens.values() if not i]) >= 3`\n</code></pre>\n\n<p>Another option would be to just use sum to get the same value:</p>\n\n<pre><code>`sum(not i for i in self.price_tokens.values()) >= 3`\n</code></pre>\n\n<hr>\n\n<p><em>Comments about the Player class</em></p>\n\n<p><strong>Iterating over a different object</strong></p>\n\n<p>In <code>get_state</code>, you use <code>for i in Commodity</code> in various places.</p>\n\n<p>I think it would be more natural to iterate over the other object you are considering (<code>self.hand</code> or <code>self._game.market</code>).</p>\n\n<p>For instance:</p>\n\n<pre><code> market_costly = sum([self._game.market[i] for i in Commodity if Commodity.is_costly(i)])\n market_non_costly = sum([self._game.market[i] for i in Commodity if (not Commodity.is_costly(i)) and (not i == Commodity.CAMEL)])\n market_camel = sum([self._game.market[i] for i in Commodity if i == Commodity.CAMEL])\n</code></pre>\n\n<p>would become</p>\n\n<pre><code> market_costly = sum(n for c, n in self._game.market.items() if Commodity.is_costly(c))\n market_non_costly = sum(n for c, n in self._game.market.items() if not Commodity.is_costly(c) and i != Commodity.CAMEL)\n market_camel = sum(n for c, n in self._game.market.items() if i == Commodity.CAMEL)\n</code></pre>\n\n<p>Even though that last line can be simplified considerably:</p>\n\n<pre><code> market_camel = self._game.market[Commodity.CAMEL]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T13:32:43.607",
"Id": "232857",
"ParentId": "232662",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-19T21:43:55.303",
"Id": "232662",
"Score": "10",
"Tags": [
"python",
"object-oriented",
"game",
"design-patterns"
],
"Title": "System design - Jaipur board game learning agent"
}
|
232662
|
<p>I am trying to automate this portion of code in python (code shown for 2 polygons, I am trying to do the same for 10 000 polygons). Any ideas on how to implement this using <code>for</code> loop or whichever fastest way you recommend.</p>
<pre><code>### Polygon 1
def checkPolygon1(row):
point = Point((row['X']), (row['Y']))
return polygon1.contains(point)
#Apply fn to each row of dataframe (datacopy)
datacopy.apply(checkPolygon1, axis=1)
#Create new variable InPolygon1 in data if X, Y in shapely file
datacopy['InPolygon1'] = datacopy.apply(checkPolygon1, axis=1)
### Polygon 2
def checkPolygon2(row):
point = Point((row['X']), (row['Y']))
return polygon2.contains(point)
datacopy.apply(checkPolygon2, axis=1)
#Create new variable InPolygon2 in data if X, Y in shapely file
datacopy['InPolygon2'] = datacopy.apply(checkPolygon2, axis=1)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T01:47:24.783",
"Id": "454449",
"Score": "3",
"body": "Your description is missing the _purpose_ of the code. You say the code does something \"for two polygons\", but you didn't say what this \"something\" is."
}
] |
[
{
"body": "<p>Both functions <code>checkPolygon1</code> and <code>checkPolygon2</code> perform essentially the same actions and only differ in specific <em>polygon</em> instance. <br>That's an appropriate case for <a href=\"https://refactoring.com/catalog/parameterizeFunction.html\" rel=\"nofollow noreferrer\"><em>Parameterize Function</em></a> refactoring technique where <em>polygon</em> instance can serve as a <em>factor</em>. </p>\n\n<p>Define a unified function <strong><code>point_in_polygon</code></strong> (don't forget about Python naming conventions):</p>\n\n<pre><code>def point_in_polygon(row, polygon):\n return polygon.contains(Point(row['X'], row['Y']))\n</code></pre>\n\n<p>Then, assuming that you already have a <em>list</em> or <em>generator</em> of polygons <code>polygons</code>:</p>\n\n<pre><code>for i, polygon in enumerate(polygons, 1):\n datacopy[f'InPolygon{i}'] = datacopy.apply(point_in_polygon, axis=1, polygon=polygon)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-19T22:49:39.823",
"Id": "232667",
"ParentId": "232666",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-19T22:16:47.887",
"Id": "232666",
"Score": "2",
"Tags": [
"python",
"pandas"
],
"Title": "Python - Automate code involving suffix"
}
|
232666
|
<p>The 'friendly form' of a number is written as a sum of reciprocals of distinct positive integers. eg. <span class="math-container">$$\frac{4}{5} = \frac{1}{2} + \frac{1}{4} +\frac{1}{20}$$</span></p>
<p>I have written a python program that calculates the friendly form of an inputted fraction.</p>
<pre><code>import math
from fractions import Fraction
def decompose(x):
if x.numerator == 1:
return [x]
# Finds the largest fraction m = 1/p which is less than or equal to x
m = Fraction(1, math.ceil(float(1 / x)))
x = x - m
#Recursively returns a chain of fractions
return decompose(x) + [m]
def main():
inp = input("Enter positive fraction in form \"a/b\": ")
try:
x = Fraction(inp)
except ValueError:
print("Invalid input.")
return
if float(x) == 0:
print("Enter non-zero value.")
return
if float(x) < 0:
print("Converting to positive value.")
x = -x
if float(x) >= 1:
print("Enter valid fraction")
return
answer = decompose(x)
for a in answer:
print(a)
if __name__ == "__main__":
main()
</code></pre>
|
[] |
[
{
"body": "<p>Overall, the code is very good, but a few tiny improvements can be made:</p>\n\n<ul>\n<li><p>In the decompose function <code>x = x - m</code> can be replaced with <code>x -= m</code></p></li>\n<li><p>Instead of <code>return decompose(x) + [m]</code> and such, use <code>yield</code></p></li>\n<li><p>Instead of <code>for a in answer ...</code>, use <code>print(*answer, sep='\\n')</code></p></li>\n<li><p>In the decompose function, <code>math.ceil(float(1 / x))</code> can be changed to <code>math.ceil(1 / x)</code>. <strong>Python 3.x</strong> automatically interprets <code>/</code> as a float operator</p></li>\n<li><p>As only <code>math.ceil</code> is used, you could just do <code>from math import ceil</code></p></li>\n</ul>\n\n<p>Here's the final code:</p>\n\n<pre><code>from math import ceil\nfrom fractions import Fraction\n\ndef decompose(x):\n if x.numerator == 1:\n yield x\n return \n\n m = Fraction(1, ceil(1 / x))\n x -= m\n\n yield m\n yield from decompose(x)\n\ndef main():\n inp = input(\"Enter positive fraction in form 'a/b': \")\n\n try:\n x = Fraction(inp)\n\n except ValueError:\n print(\"Invalid input.\")\n return\n\n if float(x) == 0:\n print(\"Enter non-zero value.\")\n return\n\n if float(x) < 0:\n print(\"Converting to positive value.\")\n x = -x\n\n if float(x) >= 1:\n print(\"Enter valid fraction\")\n return\n\n print(*decompose(x), sep='\\n')\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n\n<p>Hope this helps!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T05:10:14.403",
"Id": "232676",
"ParentId": "232668",
"Score": "4"
}
},
{
"body": "<p>Every recursive algorithm can be rewritten without recursion. In worst case, using one stack.</p>\n\n<p>I'm not a pythonist, so instead I will write in pseudocode:</p>\n\n<pre><code>def decompose(x)\n result = []\n while x.numerator != 1:\n m = Fraction(1, ceil(1/x))\n x -= m\n result.append(m)\n\n result.append(x)\n return result\n</code></pre>\n\n<p>Now using yield as suggested by @Srivaths it gets simpler:</p>\n\n<pre><code>def decompose(x)\n while x.numerator != 1:\n m = Fraction(1, ceil(1/x))\n x -= m\n yield m\n\n yield x\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T11:13:42.217",
"Id": "232695",
"ParentId": "232668",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-19T23:04:52.483",
"Id": "232668",
"Score": "4",
"Tags": [
"python",
"algorithm",
"python-3.x"
],
"Title": "Python Friendly Form"
}
|
232668
|
<p>I made this Scrabble with care since it will be mainly used by family that will not understand the error codes so that is why I catch basically every possible error, to make it user friendly. I have revised this based on <a href="https://codereview.stackexchange.com/q/232083/100620">an earlier post</a> and hope to improve its efficiency even more now that I have basically redone the code.</p>
<pre><code>
letter_val = {" ": 0, "A": 1, "B": 3, "C": 3, "D": 2, "E": 1, "F": 4, "G": 2, "H": 4, "I": 1, "J": 8, "K": 5, "L": 1, "M": 3, "N": 1, "O": 1, "P": 3, "Q": 10, "R": 1, "S": 1, "T": 1, "U": 1, "V": 4, "W": 4, "X": 8, "Y": 4, "Z": 10}
print("""
___| | | |
\___ \ __| __| _` | __ \ __ \ | _ \ __|
| ( | ( | | | | | | __/ |
_____/ \___|_| \__,_|_.__/ _.__/ _|\___|_|
""")
players = []
def add_players():
print("If amount of players is less than 4, press enter after all players are entered.")
while len(players) < 4:
new_player = input("Enter player to add>>> ")
if new_player:
if new_player not in (stats[0] for stats in players):
players.append([new_player, 0])
print("Player {} added.".format(new_player))
else:
print("Player already in player list.")
else:
break
add_players()
def home():
option = input('Would you like to [A]dd a score, [V]iew scores, [U]ndo the last change, or [End] the game? > ')
return option
def add_score():
score = 0
global temp_value, temp_player, undo_ind
player = temp_player = input("Enter player to score>>> ")
if player:
if player in (stats[0] for stats in players):
try:
word = input("Enter word to score(Enter a space for blank tiles)>>> ")
if word:
value = temp_value = sum(letter_val[i.upper()] for i in word)
else:
add_score()
except KeyError:
print("Word must consist of letters only.")
add_score()
dbl_or_trip = input("Is word [D]ouble or [T]riple or [N]either?> ")
if dbl_or_trip.lower() == "d":
score += value * 2
elif dbl_or_trip.lower() == "t":
score += value * 3
elif dbl_or_trip.lower() == "n":
score += value
else:
print("Please enter a valid option.")
add_score()
print("Are there any double or triple letters?(For example, if the letter \"b\" is doubled and \"t\" is tripled, it is entered like this> b2 t3)")
mult_letters = input("Enter any double or triple letters in the above format or press enter to skip> ")
spl_mult_letters = mult_letters.split()
try:
for letter, multiplier in spl_mult_letters:
for stats in players:
if stats[0] == player:
if 4 > int(multiplier) > 1:
stats[1] += letter_val[letter.upper()] * (int(multiplier) - 1) + score
break
else:
print("The multiplier must be either 2 or 3.")
except ValueError:
print("Please enter multiplied letters in the above format.")
else:
print("Player entered is not in player list.")
add_score()
undo_ind = False
main()
def view_scores():
for i in players:
print("Player %s has a score of %d" % (i[0], i[1]))
main()
def undo():
global undo_ind
no_change = "No changes have been made."
try:
if temp_value and temp_player and undo_ind is False:
for stats in players:
if stats[0] == temp_player:
stats[1] -= temp_value
else:
print(no_change)
except NameError:
print(no_change)
home()
undo_ind = True
main()
def end_game():
for name, score in players:
print("Player %s has a score of %d" % (name, score))
__name__ = "end"
def main():
option = home()
if option.lower() == "a":
add_score()
elif option.lower() == "v":
view_scores()
elif option.lower() == "u":
undo()
elif option.lower() == "end":
end_game()
else:
print("Please enter a valid option.")
main()
if __name__ == "__main__":
main()
</code></pre>
<p>I know I have recursion in the <code>main()</code> function and I would like someone to provide an example specific to this scenario for me to use, as I can't figure out a working solution. Also the reason I set <code>__name__</code> to "end" in the <code>end_game()</code> function is because if I did not, end game would run the if statement at the end of the code and then repeat <code>main()</code> putting the user in an endless loop that can only be escaped by CTRL+C. If anyone has a better way of the interaction between <code>end_game()</code> and <code>main()</code> I would like to hear and improve on it. I am fairly new to Python, and examples do help a lot for this program and future references. Thanks.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T13:18:30.983",
"Id": "455250",
"Score": "0",
"body": "I tested the code and it does not seem to fit the condition \"Your question must contain code that is already working correctly\". Trying to add a score without any double or or triple letters fails (nothing is added to the player score), and I sometimes get stuck in an infinite loop with no possibility to exit. Also, it doesn't follow Scrabble's rules, as it is impossible to score a double double word (or triple triple word), and letters should be doubled/tripled before the word, and this code goes the other way around."
}
] |
[
{
"body": "<h2>Style</h2>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(\"\"\"\n___| | | | \n\\___ \\ __| __| _` | __ \\ __ \\ | _ \\ __| \n | ( | ( | | | | | | __/ | \n_____/ \\___|_| \\__,_|_.__/ _.__/ _|\\___|_| \n\"\"\")\n</code></pre>\n\n<p>What does that even mean? Scrabble?</p>\n\n<p>There are many possible replacements.</p>\n\n<p>For example:</p>\n\n<pre><code>print(\"\"\"\n\n _/_/_/_/ _/_/_/_/ _/_/_/_/ _/ _/_/_/_/ _/_/_/_/ _/ _/_/_/_/\n _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/ _/\n _/_/_/_/ _/ _/_/_/_/ _/ _/ _/_/_/_/ _/_/_/_/ _/ _/_/_/_/\n _/ _/ _/ _/ _/_/_/_/ _/ _/ _/ _/ _/ _/\n _/_/_/_/ _/_/_/_/ _/ _/ _/ _/ _/_/_/_/ _/_/_/_/ _/_/_/_/ _/_/_/_/\n\n\n\"\"\")\n</code></pre>\n\n<p>But it's your wish if you don't want to change it!</p>\n\n<hr>\n\n<h2>add_scores</h2>\n\n<p><strong>Always</strong> add a return statement when you don't want the upcoming code to be executed</p>\n\n<pre><code>except KeyError:\n print(\"Word must consist of letters only.\")\n add_score()\n\ndbl_or_trip = input(\"Is word [D]ouble or [T]riple or [N]either?> \")\n</code></pre>\n\n<p>Regardless of whether there was <code>KeyError</code> or not, <code>dbl_or_trip = input(...</code> is executed.<br>\nIf there was a <code>KeyError</code>, then after <code>add_score()</code> was executed, it moves on to the next line.</p>\n\n<p><code>value</code> is declared inside the scope of <code>try</code>. That's bound to create some errors. declare <code>value = None</code> before executing the <code>try</code> statement</p>\n\n<hr>\n\n<h2>add_players</h2>\n\n<p>There's not much improvement here, except that you can use<br>\n<code>print(\"Player {} added.\".format(new_player))</code> instead of <code>print(f\"Player {new_player} added.\")</code></p>\n\n<p>Also, you can add <code>print()</code> statement after taking the input to make the text easier to read.</p>\n\n<hr>\n\n<h2>view_scores</h2>\n\n<p>Again, you can use <code>print(f'{something}')</code> instead of <code>print('%s' % 'something')</code></p>\n\n<hr>\n\n<h2>end_game</h2>\n\n<p>And yet again, you can use <code>f'{something}'</code></p>\n\n<p>Also, why do you do <code>__name__ = \"end\"</code>? It works even if you remove that.</p>\n\n<blockquote>\n <p>Also the reason I set <strong>name</strong> to \"end\" in the end_game() function is because if I did not, end game would run the if statement at the end of the code and then repeat main() putting the user in an endless loop that can only be escaped by CTRL+C.</p>\n</blockquote>\n\n<p>That is not true. After <code>end_game()</code> is called, the code automatically returns to the line that was being run.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def foo(): # Line 1\n return 'bar' # Line 2\n # Line 3\nfoo() # Line 4\nprint('1') # Line 5\n</code></pre>\n\n<p>This does not create an endless recursion. After <code>'bar'</code> was returned, The function ends, but the code does not continue from line 3. It goes on to the next line that was being run while calling the function which was line 4. So the code proceeds to line 5. In other words, functions are not a part of the executing code.</p>\n\n<hr>\n\n<h2>undo</h2>\n\n<p>Again, <strong>always</strong> add a return statement when you don't want the upcoming code to be executed</p>\n\n<pre><code> except NameError:\n print(no_change)\n home()\n\n undo_ind = True\n main()\n</code></pre>\n\n<p>After <code>home()</code> is executed, the code will proceed to execute <code>undo_ind = True</code> and <code>main()</code>, which we don't want to happen.</p>\n\n<p><code>undo_ind is False</code> <em>should always</em> be replaced with <code>not undo_ind</code>.</p>\n\n<hr>\n\n<h2>Misc</h2>\n\n<ul>\n<li><p>You should not run <code>add_players()</code> outside <code>if __name__ == '__main__'</code>. If the module was imported, It would automatically ask for player names.</p></li>\n<li><p>Also, you can create a function <code>begin</code> which calls <code>add_players()</code> and then <code>main()</code></p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T16:45:42.150",
"Id": "454652",
"Score": "2",
"body": "That \"Scrabble\" ascii art looks amazing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T17:07:57.973",
"Id": "454661",
"Score": "2",
"body": "@Linny Thank you so much! My family said I were just wasting my time, but I was sure someone would appreciate it! :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T22:37:20.250",
"Id": "454695",
"Score": "0",
"body": "@Srivaths also, when I add the score to `stats[1]` it's in the for loop that each list in the format of `[player_name, score]` is represented by stats, so it is updating the score in player, I just don't get how the way you did it is much different than mine. But then again, maybe I need some more explanation of what your code is doing better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T22:53:41.727",
"Id": "454699",
"Score": "0",
"body": "@Srivaths For the points for the letters, I have to make a custom dictionary because there is no pattern in the points for each letter, unless I do some webscraping or something along the lines to retrieve point values, which is needless to say unnecessary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T06:43:05.810",
"Id": "454716",
"Score": "0",
"body": "@pythonier500 Sorry. Both of your points are correct. It was wrong on my part. I have edited my answer accordingly"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T03:50:33.540",
"Id": "454981",
"Score": "1",
"body": "@Srivaths it is quite alright, I was wrong about the `end_game` function as I had an invalid placement of code, thank you for all the help. I took your advice for a `begin` function that works quite well."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T04:27:36.050",
"Id": "232675",
"ParentId": "232673",
"Score": "5"
}
},
{
"body": "<h1>Bugs</h1>\n<p>I think the calculation is incorrect when there's both letter multipliers and word multipliers in play - the letter multipliers should be computed first, so that they get multiplied up by the word multiplier, too.</p>\n<p>It also doesn't handle words that span more than one double-word or triple-word square, or claiming the 50-point bonus for playing all tiles.</p>\n<h1>Improvements</h1>\n<p>This line, as well as being unwieldy (use some line breaks!) restricts this program to English scrabble:</p>\n<blockquote>\n<pre><code>letter_val = {" ": 0, "A": 1, "B": 3, "C": 3, "D": 2, "E": 1, "F": 4, "G": 2, "H": 4, "I": 1, "J": 8, "K": 5, "L": 1, "M": 3, "N": 1, "O": 1, "P": 3, "Q": 10, "R": 1, "S": 1, "T": 1, "U": 1, "V": 4, "W": 4, "X": 8, "Y": 4, "Z": 10}\n</code></pre>\n</blockquote>\n<p>If you want to be useful to all players of the game, it would be worth loading the points values from a config file.</p>\n<p>The current code is going to have problems in languages where not all tiles are single letters (e.g. <kbd>DD₁</kbd> or <kbd>LL₅</kbd> in a Welsh set).</p>\n<p>If you ever try Super Scrabble, you'll find that there are quad-letter and quad-word spaces, too; it would be a nice enhancement to support those, and not too difficult to implement.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T16:05:40.470",
"Id": "455278",
"Score": "0",
"body": "Thank you for that feedback, I will try to implement the 50 point bonus and words that span more than one double-word or triple-word. I do not plan to spend too much more time on this project so I may keep it restricted to the English language since this is more of a project for my family and we only play the English version."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T16:28:27.863",
"Id": "455285",
"Score": "0",
"body": "You might be able to implement extra word-multipliers by allowing the user to provide a string of multipliers (e.g. 'dd' for two double-word scores) and parsing with a loop. That might be a good way to handle the bonus, too (e.g. enter an `x` in that input to indicate all tiles played)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T10:16:38.653",
"Id": "232986",
"ParentId": "232673",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T02:36:23.107",
"Id": "232673",
"Score": "5",
"Tags": [
"python",
"beginner",
"python-3.x",
"game"
],
"Title": "Scrabble Scorer in Python"
}
|
232673
|
<p>I have some questions about best practices to apply in JavaScript. I would like to ask about my code and how I could improve.</p>
<p>Starting with an example, I have 2 functions with different ways of handling promises</p>
<p>Here I have a route to add a user:</p>
<pre><code> addUsers(req,res,next) {
try {
const {name,email,login} = req.body;
User.existLogin(req.body.login)
.then(async result => {
if(!result){
const password = await bcrypt.hashSync(req.body.password, 10);
User.create({
name, email, login, password }).then(result => {
res.status(201).json({Results: result.dataValues})
})
}else{
return res.status(409).json({message: 'Login already exists'});
}
})
} catch (error) {
res.status(500).json({error: error})
}
}
</code></pre>
<p>And here I have another function to login:</p>
<pre><code>async login(req,res){
const user = await User.existLogin(req.body.login);
if (!user) { return res.status(400).json({result: 'Login is wrong '});}
const isPassword = await User.isPassword(user.dataValues.password, req.body.password);
if (!isPassword) { return res.status(400).json({result: 'Password is wrong '}); }
const jwt = auth.signjwt(auth.payload(user));
console.log(jwt);
res.status(200);
res.json(jwt);
}
</code></pre>
<p>Looking at this the login function seems to me to be cleaner, but I have doubts if really yours I could improve in one of two (I follow different logics to do both).</p>
<p>I have an auth folder, where I export functions, such as my payload, my sign, my middleware to validate my jwt, but I don't know if this is a correct decision.</p>
<pre><code>const jwt = require('jsonwebtoken');
const User = require('../models/User')
const config= require('../config/dbconfig');
const moment = require('moment');
module.exports = {
signjwt (payload) {
return jwt.sign(payload,
config.secretToken
)
},
payload (usuario) {
return {
sub: usuario.id,
name: usuario.nome,
email: usuario.email,
login: usuario.username,
admin: true,
iat: Math.floor(moment.now()/1000), // Timestamp de hoje
exp: moment().add(10, 'minutes').unix() // Validade de 2 dias
}
},
async auth(req,res,next){
const token = req.header('Authorization');
console.log(token);
if(!token) return res.status(401).json('Unauthorized');
try{
const decoded = jwt.verify(token,config.secretToken);
const user = await User.findByPk(decoded.sub);
console.log(user);
if(!user){
return res.status(404).json('User not Found');
}
res.json(user);
next();
}catch(error){
console.error(error);
res.status(400).json('Invalid Token');
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-19T00:06:51.923",
"Id": "454464",
"Score": "1",
"body": "\"*with different ways of handling promises*\" - avoid [mixing `await` and `.then(…)` syntax](https://stackoverflow.com/a/54387912/1048572), yes. Don't pass `async` functions as callbacks. Btw, one mistake that probably stems from this confusion is that you're not handling rejections from `User.existLogin`."
}
] |
[
{
"body": "<p>Follow some standards, use code linting <em>(for example ESLint)</em> and code formatting <em>(for example Prettier)</em>, try to prevent code duplication as much as possible, \nuse design patterns and don't complex things. Those things will make your code more readable for others.</p>\n\n<p>There is no right or wrong while the code works and it's easy to read.</p>\n\n<hr>\n\n<p><em>Martin Fowler.</em> </p>\n\n<blockquote>\n <p>Any fool can write code that a computer can understand. Good\n programmers write code that humans can understand.</p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-18T23:46:23.063",
"Id": "232679",
"ParentId": "232678",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "232679",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-18T20:31:37.580",
"Id": "232678",
"Score": "5",
"Tags": [
"javascript",
"node.js"
],
"Title": "Adding users for login"
}
|
232678
|
<p>I created this morse code encoder and decoder.</p>
<pre class="lang-py prettyprint-override"><code>class DecodeError(BaseException):
__module__ = Exception.__module__
class EncodeError(BaseException):
__module__ = Exception.__module__
code_letter = {
'.-': 'A', '-...': 'B', '-.-.': 'C', '-..': 'D', '.': 'E', '..-.': 'F', '--.': 'G',
'....': 'H', '..': 'I', '.---': 'J', '-.-': 'K', '.-..': 'L', '--': 'M', '-.': 'N',
'---': 'O', '.--.': 'P', '--.-': 'Q', '.-.': 'R', '...': 'S', '-': 'T', '..-': 'U',
'...-': 'V', '.--': 'W', '-..-': 'X', '-.--': 'Y', '--..': 'Z',
'.----': '1', '..---': '2', '...--': '3', '....-': '4', '.....': '5',
'-....': '6', '--...': '7', '---..': '8', '----.': '9', '-----': '0',
'--..--': ', ', '.-.-.-': '.', '..--..': '?', '-..-.': '/',
'-....-': '-', '-.--.': '(', '-.--.-': ')', '/': ' '
}
letter_code = {value: key for key, value in zip(code_letter.keys(), code_letter.values())}
def morse_encode(string: str) -> str:
try:
return ' '.join(letter_code[i.upper()] for i in string)
except:
raise EncodeError('Unknown value in string')
def morse_decode(string: str) -> str:
try:
return ''.join(code_letter[i] for i in string.split())
except:
raise DecodeError('Unknown value in string')
if __name__ == '__main__':
string = input()
print(morse_encode(string))
</code></pre>
<p>Is it possible to make the code shorter while maintaining neatness?</p>
<p>Thanks!</p>
|
[] |
[
{
"body": "<p>Some suggestions:</p>\n\n<ol>\n<li>I believe <a href=\"https://stackoverflow.com/a/1319675/96588\">the idiomatic way to declare custom exceptions</a> is to inherit from <code>Exception</code> rather than <code>BaseException</code>, and to just use the no-op <code>pass</code> as the class body. I've not seen the <code>__module__ = Exception.__module__</code> pattern before, but if that does what it looks like (making the class effectively part of the exceptions module) that's probably going to be misleading. It's not a generic error, after all.</li>\n<li>It <em>might</em> be faster to put both upper and lower case characters in the dict than to use <code>upper()</code>. You could test this with <a href=\"https://docs.python.org/3/library/timeit.html\" rel=\"noreferrer\"><code>timeit</code></a>.</li>\n<li>If you're processing a big string of Morse code you might want to use an <a href=\"https://stackoverflow.com/a/4586073/96588\">iterator</a>. That way the string is processed one word at a time, rather than having to split the entire text into a list in memory before starting to output anything.</li>\n<li>Rather than parsing <code>input()</code> I would expect this sort of script to either read standard input or to accept a list of file path <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"noreferrer\">arguments</a> which would each be read and converted.</li>\n<li>If the script also accepted <code>--encode</code> and <code>--decode</code> parameters (possibly with <code>--encode</code> as the default) it could easily be used to script a conversion of any text.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T08:45:32.440",
"Id": "454479",
"Score": "0",
"body": "For the first point, if `__module__ = Exception.__module__` is removed, the exception is shown as `__main__.(something)`. Else it is shown as `(somthing)`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T07:56:44.927",
"Id": "232689",
"ParentId": "232681",
"Score": "4"
}
},
{
"body": "<p>@l0b0 is right for (1.). The <a href=\"https://docs.python.org/3/library/exceptions.html#BaseException\" rel=\"nofollow noreferrer\">docs</a> say to inherit from <code>Exception</code> instead:</p>\n\n<blockquote>\n <p>The base class for all built-in exceptions. It is not meant to be directly inherited by user-defined classes (for that, use Exception)</p>\n</blockquote>\n\n<p>I've also never seen <code>__module__</code> used in that case, but if you like to output better, I guess it works fine.</p>\n\n<hr>\n\n<p><code>letter_code</code> can make use of dictionary's <a href=\"https://docs.python.org/3/library/stdtypes.html?highlight=dict%20items#dict.items\" rel=\"nofollow noreferrer\"><code>items</code></a> method.</p>\n\n<pre><code>zip(code_letter.keys(), code_letter.values())\n</code></pre>\n\n<p>Is roughly equivalent to</p>\n\n<pre><code>code_letter.items()\n</code></pre>\n\n<p>And just to make it a little clearer what the dictionary comprehension is doing, I might also rename loop variables:</p>\n\n<pre><code>letter_code = {letter: morse for morse, letter in code_letter.items()}\n</code></pre>\n\n<hr>\n\n<p>You're using bare <code>except</code>s, which is generally a bad idea. If you accidentally typo some other catchable error into the <code>try</code>, you'll get <code>'Unknown value in string'</code> messages instead of a real error. Specify what exact error you want to catch. I'd also make use of the fact that stringifying a <code>KeyError</code> exception tells you what the bad key was. You can print out the exception to tell the user what went wrong exactly</p>\n\n<pre><code>def morse_encode(string: str) -> str:\n try:\n return ' '.join(letter_code[i.upper()] for i in string)\n\n except KeyError as e:\n raise EncodeError(f'Unknown value in string: {e}')\n\n>>> morse_encode(\"]\")\nEncodeError: Unknown value in string: ']'\n</code></pre>\n\n<p>And of course, <code>i</code> is a bad name for that loop variable. <code>i</code> suggests an index, but that's a letter, not an index. This reads much better</p>\n\n<pre><code>' '.join(letter_code[char.upper()] for char in string)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T17:31:20.403",
"Id": "232710",
"ParentId": "232681",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "232710",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T06:11:07.040",
"Id": "232681",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"morse-code"
],
"Title": "Morse code encoder decoder"
}
|
232681
|
<p>The code works not only as a normal <a href="https://en.wikipedia.org/wiki/Run-length_encoding" rel="nofollow noreferrer">run length</a> encoder and decoder, but it also works for values like <code>3ABC</code> (Prints <code>ABCABCABC</code>), but the same doesn't happen for encoding</p>
<pre class="lang-py prettyprint-override"><code>class DecodeError(BaseException):
__module__ = Exception.__module__
class EncodeError(BaseException):
__module__ = Exception.__module__
def run_length_encode(string: str) -> str:
if any(not i.isalpha() for i in string):
raise EncodeError('String must contain only alphabets')
final_string = ''
number = 1
character = string[0]
for i in string[1:]:
if i != character:
final_string += str(number) + character
number = 0
number += 1
character = i
final_string += str(number) + character
return final_string
def run_length_decode(encoded_string: str) -> str:
if not encoded_string:
return ''
if encoded_string[-1].isnumeric():
raise DecodeError('Ending character must not be an integer')
if not encoded_string[0].isnumeric():
raise DecodeError('Starting character must be an integer')
number = character = ''
final_string = ''
for c in encoded_string:
if c.isnumeric():
if character:
final_string += int(number) * character
number = character = ''
number += c
if number == '0':
raise DecodeError('Number cannot start with 0')
else:
if not c.isalpha():
raise DecodeError('String must contain only alphabets')
character += c
final_string += int(number) * character
return final_string
if __name__ == '__main__':
t = int(input('Enter if you want to encode(1) or decode(2): '))
string = input('Enter string: ')
if t == 1: print(run_length_encode(string))
elif t == 2: print(run_length_decode(string))
else: raise ValueError('Value must be 1 or 2')
</code></pre>
<p>Is it possible make this code shorter, neater, and faster?</p>
<h1>A few testcases:</h1>
<h2>For encode:</h2>
<pre><code>Enter if you want to encode(1) or decode(2): 1
Enter string: AABBCCDD
2A2B2C2D
</code></pre>
<pre><code>Enter if you want to encode(1) or decode(2): 1
Enter string: AB1
Traceback (most recent call last):
File "C:/Users/Administrator/.PyCharmCE2018.3/config/scratches/scratch_62.py", line 67, in <module>
if t == 1: print(run_length_encode(string))
File "C:/Users/Administrator/.PyCharmCE2018.3/config/scratches/scratch_62.py", line 9, in run_length_encode
raise EncodeError('String must contain only alphabets')
EncodeError: String must contain only alphabets
</code></pre>
<pre><code>Enter if you want to encode(1) or decode(2): 1
Enter string: AAABBcCCddee
3A2B1c2C2d2e
</code></pre>
<pre><code>Enter if you want to encode(1) or decode(2): 1
Enter string: AAABBCC.
Traceback (most recent call last):
File "C:/Users/Administrator/.PyCharmCE2018.3/config/scratches/scratch_62.py", line 67, in <module>
if t == 1: print(run_length_encode(string))
File "C:/Users/Administrator/.PyCharmCE2018.3/config/scratches/scratch_62.py", line 9, in run_length_encode
raise EncodeError('String must contain only alphabets')
EncodeError: String must contain only alphabets
</code></pre>
<h2>For decode:</h2>
<pre><code>Enter if you want to encode(1) or decode(2): 2
Enter string: 2A3C4D
AACCCDDDD
</code></pre>
<pre><code>Enter if you want to encode(1) or decode(2): 2
Enter string: 1ABC
ABC
</code></pre>
<pre><code>Enter if you want to encode(1) or decode(2): 2
Enter string: 2A3B1ABC
AABBBABC
</code></pre>
<pre><code>Enter if you want to encode(1) or decode(2): 2
Enter string: 0X
Traceback (most recent call last):
File "C:/Users/Administrator/.PyCharmCE2018.3/config/scratches/scratch_62.py", line 68, in <module>
elif t == 2: print(run_length_decode(string))
File "C:/Users/Administrator/.PyCharmCE2018.3/config/scratches/scratch_62.py", line 50, in run_length_decode
raise DecodeError('Number cannot start with 0')
DecodeError: Number cannot start with 0
</code></pre>
<pre><code>Enter if you want to encode(1) or decode(2): 2
Enter string: 0123A
Traceback (most recent call last):
File "C:/Users/Administrator/.PyCharmCE2018.3/config/scratches/scratch_62.py", line 68, in <module>
elif t == 2: print(run_length_decode(string))
File "C:/Users/Administrator/.PyCharmCE2018.3/config/scratches/scratch_62.py", line 50, in run_length_decode
raise DecodeError('Number cannot start with 0')
DecodeError: Number cannot start with 0
</code></pre>
<pre><code>Enter if you want to encode(1) or decode(2): 2
Enter string: 2A3#
Traceback (most recent call last):
File "C:/Users/Administrator/.PyCharmCE2018.3/config/scratches/scratch_62.py", line 68, in <module>
elif t == 2: print(run_length_decode(string))
File "C:/Users/Administrator/.PyCharmCE2018.3/config/scratches/scratch_62.py", line 54, in run_length_decode
raise DecodeError('String must contain only alphabets')
DecodeError: String must contain only alphabets
</code></pre>
<pre><code>Enter if you want to encode(1) or decode(2): 2
Enter string: A2A
Traceback (most recent call last):
File "C:/Users/Administrator/.PyCharmCE2018.3/config/scratches/scratch_62.py", line 68, in <module>
elif t == 2: print(run_length_decode(string))
File "C:/Users/Administrator/.PyCharmCE2018.3/config/scratches/scratch_62.py", line 36, in run_length_decode
raise DecodeError('Starting character must be an integer')
DecodeError: Starting character must be an integer
</code></pre>
<pre><code>Enter if you want to encode(1) or decode(2): 2
Enter string: 1A2
Traceback (most recent call last):
File "C:/Users/Administrator/.PyCharmCE2018.3/config/scratches/scratch_62.py", line 68, in <module>
elif t == 2: print(run_length_decode(string))
File "C:/Users/Administrator/.PyCharmCE2018.3/config/scratches/scratch_62.py", line 33, in run_length_decode
raise DecodeError('Ending character must not be an integer')
DecodeError: Ending character must not be an integer
</code></pre>
<p>If you want more testcases, say so in the comments and I'll add them!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T09:27:42.747",
"Id": "454486",
"Score": "0",
"body": "Consider the following actual test: `run_length_decode(\"10abc2err3.0bbc\")` gives `abcabcabcabcabcabcabcabcabcabcerrerr...`. Is that expected? 1) sequence of chars 2) float numbers 3) `0` digit before a letter ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T11:02:45.413",
"Id": "454498",
"Score": "0",
"body": "`abcabcabc...` was expected, but the others were not. Thanks for pointing that out!. I'll edit my code soon"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T12:40:55.053",
"Id": "454504",
"Score": "0",
"body": "It would be helpful to describe the intended behavior, with examples of inputs and expected outputs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T13:32:52.777",
"Id": "454510",
"Score": "0",
"body": "@RomanPerekhrest Yes"
}
] |
[
{
"body": "<h3>Improvements and corrections:</h3>\n\n<p><strong><code>run_length_encode</code></strong> function. <br>The responsibility is <em>\"encoding\"</em> the input string basing on <em>counting</em> consecutive characters (including repetitive characters) and returning the resulting string in format <code><count><char(s)>...</code>.<br>Instead of relying on a verbose and noisy <code>for</code> loop, <a href=\"https://docs.python.org/3/library/re.html#re.sub\" rel=\"nofollow noreferrer\"><strong><code>re.sub</code></strong></a> function with <a href=\"https://www.regular-expressions.info/backref.html\" rel=\"nofollow noreferrer\">regex <em>backreferences</em></a> and extended (but simple) substitution allow to succeed the job in just one line. (Add <strong><code>import re</code></strong> at top level)</p>\n\n<p>The new version of <code>run_length_encode</code> function:</p>\n\n<pre><code>def run_length_encode(string: str) -> str:\n if not string.isalpha():\n raise EncodeError('Input string must contain only alphabetic chars')\n\n encoded = re.sub(r'(.)(\\1+)?', \n lambda m: f\"{len(m.group(2) or '') + 1}{m.group(1)}\", string)\n return encoded\n</code></pre>\n\n<hr>\n\n<p><strong><code>run_length_decode</code></strong> function.</p>\n\n<ul>\n<li><p><code>encoded_string</code> is shortened to <strong><code>encoded_str</code></strong> and <em>stripped</em> at the very start:</p>\n\n<pre><code>encoded_str = encoded_str.strip()\n</code></pre></li>\n<li><p><code>if encoded_string[-1].isnumeric()</code>. The <code>DecodeError</code> for this check is rephrased to get a more consistent description:</p>\n\n<pre><code>if encoded_str[-1].isnumeric():\n raise DecodeError('Ending character must be an alphabetic char')\n</code></pre></li>\n<li><p><code>if not encoded_string[0].isnumeric()</code>. The validation for starting char is extended to also cover prohibited <code>0</code> digit at the start of the input string:</p>\n\n<pre><code>if not encoded_str[0].isnumeric() or encoded_str[0] == '0':\n raise DecodeError('Starting character must be an integer (except 0)')\n</code></pre></li>\n<li><p>the crucial <strong><code>for</code></strong> loop gets even worse with inner validations:</p>\n\n<pre><code>if number == '0':\n raise DecodeError('Number cannot start with 0')\n</code></pre>\n\n<p>and</p>\n\n<pre><code>if not c.isalpha():\n raise DecodeError('String must contain only alphabets')\n</code></pre>\n\n<p>The error message <code>'Number cannot start with 0'</code> sounds too generic and is better expressed as <code>'Input string cannot contain letter(s) with zero counts'</code>.<br>Those 2 validations can be effectively moved <strong>out</strong> from the loop and run just once (powered by <a href=\"https://docs.python.org/3/library/re.html#re.search\" rel=\"nofollow noreferrer\"><code>re.search</code></a> check) before the main processing. </p></li>\n</ul>\n\n<p>If sacrificing concrete descriptive error messages - all validations can be handled with a single regex pattern and <em>collapsed</em>, but that, of course, would require a more generic error message.<br></p>\n\n<p>But finally, the entire loop is replaced with similar short <em>regex magic</em> based on pattern <strong><code>r'(\\d+)(\\D+)'</code></strong> and string <em>multiplication</em>:</p>\n\n<pre><code> def run_length_decode(encoded_str: str) -> str:\n encoded_str = encoded_str.strip()\n if not encoded_str:\n return ''\n\n if encoded_str[-1].isnumeric():\n raise DecodeError('Ending character must be an alphabetic char')\n\n if not encoded_str[0].isnumeric() or encoded_str[0] == '0':\n raise DecodeError('Starting character must be an integer (except 0)')\n\n if re.search(r'[^\\da-zA-Z]', encoded_str):\n raise DecodeError('Input string must contain only alphanumeric chars')\n\n if re.search(r'\\D0', encoded_str):\n raise DecodeError('Input string cannot contain letter(s) with zero counts')\n\n decoded = re.sub(r'(\\d+)(\\D+)', \n lambda m: f\"{m.group(2) * int(m.group(1))}\", encoded_str)\n return decoded\n</code></pre>\n\n<hr>\n\n<p>Quick test of <em>new</em> versions:</p>\n\n<pre><code>print(run_length_encode('AABBCCDDDD')) # \"2A2B2C4D\"\nprint(run_length_encode('aaaa3')) # EncodeError \"Input string must contain only alphabetic chars\"\nprint(run_length_encode('AAABBcCCddee')) # \"3A2B1c2C2d2e\"\n\nprint(run_length_decode(\"2A3#\")) # DecodeError \"Input string must contain only alphanumeric chars\"\nprint(run_length_decode(\"1a2N030c\")) # DecodeError \"Input string cannot contain letter(s) with zero counts\"\nprint(run_length_decode(\"1a2\")) # DecodeError \"Ending character must be an alphabetic char\"\nprint(run_length_decode(\"a23b\")) # DecodeError \"Starting character must be an integer (except 0)\"\nprint(run_length_decode(\"10abC2err10b3B\")) # \"abCabCabCabCabCabCabCabCabCabCerrerrbbbbbbbbbbBBB\"\nprint(run_length_decode(\"4abc1Arr3bbB\")) # \"abcabcabcabcArrbbBbbBbbB\"\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T17:42:08.013",
"Id": "232711",
"ParentId": "232682",
"Score": "5"
}
},
{
"body": "<p>In order to give an alternative to the <a href=\"https://codereview.stackexchange.com/a/232711/98493\">excellent RegEx answer</a> by <a href=\"https://codereview.stackexchange.com/users/95789/romanperekhrest\">@RomanPerekhrest</a>, here is one using <a href=\"https://docs.python.org/3/library/itertools.html#itertools.groupby\" rel=\"nofollow noreferrer\"><code>itertools.groupby</code></a>. This way you can eliminate your manual <code>for</code> loops and counting for the <code>run_length_encode</code> function.</p>\n\n<pre><code>from itertools import groupby\n\ndef run_length_encode(s):\n \"\"\"Returns a RLE string like this:\n 'ABBCC' -> '1A2B3C'\n \"\"\"\n if not s.isalpha():\n raise EncodeError('Input string must contain only alphabetic chars')\n\n return \"\".join(f\"{len(list(g))}{c}\" for c, g in groupby(s))\n</code></pre>\n\n<p>For the decoding I would also use a RegEx, but maybe using <a href=\"https://docs.python.org/3/library/re.html#re.findall\" rel=\"nofollow noreferrer\"><code>re.findall</code></a>:</p>\n\n<pre><code>def run_length_decode(s):\n \"\"\"Take a RLE from `run_length_encode` and decompress it:\n '1A2B3C' -> 'ABBCC'\n \"\"\"\n return \"\".join(c * int(n) for n, c in re.findall(r'(\\d)([a-zA-Z])', s))\n</code></pre>\n\n<p>Of course you would have to add all the sanity checks back again to this. Doing that will make it less neat and short. The current code will raise some exceptions (e.g. for the empty string), but skip malformed parts of the string (check out <code>run_length_decode(\"a2b\") -> \"bb\"</code>).</p>\n\n<p>In addition, you should probably also document your functions, ideally using a <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\"><code>docstring</code></a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T13:50:14.683",
"Id": "232738",
"ParentId": "232682",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "232711",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T06:17:58.560",
"Id": "232682",
"Score": "4",
"Tags": [
"python",
"python-3.x"
],
"Title": "Run length encoder decoder"
}
|
232682
|
<p>I took this as a challenge and implemented linked list data structure in python</p>
<pre class="lang-py prettyprint-override"><code>class Node:
def __init__(self, data, nxt=None):
self.data = data
self.next = nxt
class LinkedList:
def __init__(self, arr=None):
if arr in [None, []]:
self.head = None
else:
self.arrayToLinked(arr)
def arrayToLinked(self, arr):
self.head = Node(arr[0])
temp = self.head
for i in range(1, len(arr)):
temp.next = Node(arr[i])
temp = temp.next
def append(self, new_val):
new_node = Node(new_val)
if self.head is None:
self.head = new_node
return
last = self.head
while last.next is not None:
last = last.next
last.next = new_node
def linkedToArray(self):
arr = []
temp = self.head
while temp is not None:
arr.append(temp.data)
temp = temp.next
return arr
def removeDuplicates(self):
pass
def sort(self):
arr = []
temp = self.head
while temp is not None:
arr.append(temp.data)
temp = temp.next
self.arrayToLinked(sorted(arr))
def index(self, val):
temp = self.head
i = 0
while temp is not None:
if temp.data == val: return i
i += 1
return -1
def min(self):
mini = self.head.data
temp = self.head
while temp is not None:
if mini > temp.data:
mini = temp.data
return mini
def max(self):
maxi = self.head.data
temp = self.head
while temp is not None:
if maxi < temp.data:
maxi = temp.data
return maxi
def push(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
@staticmethod
def insertNode(prev_node, new_val):
new_node = Node(new_val)
new_node.next = prev_node.next
prev_node.next = new_node
def insertIndex(self, pos, data):
data = Node(data)
i = 0
temp = self.head
while i < pos:
if temp is None or temp.next is None:
return
temp = temp.next
i += 1
dum = temp
temp = data
temp.next = dum
self.head = temp
def delete(self, key):
temp = self.head
if temp is not None and temp.data == key:
self.head = temp.next
return
prev = None
while temp is not None:
if temp.data == key:
break
prev = temp
temp = temp.next
if temp is None:
return
prev.next = temp.next
def deleteIndex(self, pos):
if self.head is None:
return
temp = self.head
if pos == 0:
self.head = temp.next
return
for i in range(pos - 1):
temp = temp.next
if temp is None:
break
if temp is None or temp.next is None:
return
val = temp.next.next
temp.next = None
temp.next = val
def pop(self, pos):
if self.head is None:
return
temp = self.head
if pos == 0:
self.head = temp.next
return
for i in range(pos - 1):
temp = temp.next
if temp is None:
break
if temp is None or temp.next is None:
return
val = temp.next.next
pop_val = temp.next
temp.next = None
temp.next = val
return pop_val
def count(self, element):
temp = self.head
count = 0
while temp is not None:
if temp.data == element:
count += 1
temp = temp.next
return count
def remove(self, element):
temp = self.head
while temp is not None:
if temp.next is not None and temp.next.data == element:
dum = temp.next.next
temp.next = None
temp.next = dum
temp = temp.next
def isLoop(self):
s = set()
temp = self.head
while temp:
if temp in s:
return True
s.add(temp)
temp = temp.next
return False
def findLoop(self):
s = set()
temp = self.head
while temp:
if temp in s:
return temp
s.add(temp)
temp = temp.next
def createLoop(self, data):
ind = self.index(data)
last = self.head
while last.next is not None:
last = last.next
last.next = self[ind]
def reverse(self):
result = None
temp = self.head
while temp:
result = Node(temp.data, temp)
temp = temp.next
self.head = result
def len(self):
c = 0
temp = self.head
while temp is not None:
c += 1
temp = temp.next
return c
def clear(self):
self.head = None
def copy(self):
return self.arrayToLinked(self.linkedToArray())
def __getitem__(self, index):
arr = []
temp = self.head
while temp is not None:
arr.append(temp)
temp = temp.next
return arr[index]
def getValues(self, index):
arr = []
temp = self.head
while temp is not None:
arr.append(temp.data)
temp = temp.next
return arr[index]
def print(self):
arr = []
m = self.head
while m is not None:
arr.append(str(m.data))
m = m.next
print(' -> '.join(arr))
</code></pre>
<p>I want to make the code as short as possible, while maintaining neatness.</p>
<p>Thanks!</p>
|
[] |
[
{
"body": "<p>This code is pretty neat. One major improvement would be the addition of some <em>magic</em> methods, like <code>__iter__</code>, <code>__getitem__</code>, <code>__setitem__</code> and <code>__str__</code>.</p>\n\n<h1><strong>iter</strong></h1>\n\n<p>The magic method you'll use the most wil be <code>__iter__</code>. It will allow you to do <code>for node in linked_list</code></p>\n\n<pre><code>def __iter__(self):\n current = self.head\n while current:\n yield current\n current = current.next\n</code></pre>\n\n<p>If there is the possibility for loops in the linked list, this will go on forever. In that case, it might be best to raise a specific exception</p>\n\n<pre><code>class LoopListError(Exception): pass\n...\ndef __iter__(self):\n current = self.head\n visited = set()\n while current:\n if current in visited:\n raise LoopListError(\"f{current} is part of a loop\")\n set.add(current)\n yield current\n current = current.next\n</code></pre>\n\n<p>Make sure never to change the list while iterating over it. This might lead to strange errors.</p>\n\n<h1><code>__len__</code></h1>\n\n<p>len(self) can be renamed to <code>__len_</code>, so you can do <code>len(linked_list)</code> . It can also be implemented like this:</p>\n\n<pre><code>def __len__(self):\n return sum(1 for _ in self)\n</code></pre>\n\n<p>If there is a loop in the list, this wil raise the <code>LoopListError</code>. If, in that case, you want the length of the non-looped part of the list, then you can do:</p>\n\n<pre><code>def __len__(self):\n count = 0\n try:\n for _ in self:\n count += 1\n except LoopListError:\n pass\n return count\n</code></pre>\n\n<p>If you want it to iterate over the nodes values instead of the nodes themselves, you can just change the <code>yield current</code> to <code>yield current.data</code>. Whichever option is best depends on the design of the rest and the use of this list.</p>\n\n<p>I think it's cleaner to provide a separate <code>iter_values</code> method:</p>\n\n<pre><code>def iter_values(self):\n return (node.data for node in self)\n</code></pre>\n\n<p>You don't need a specific <code>min</code> and <code>max</code> method any more, but can use the builtins</p>\n\n<h1><code>__getitem__</code></h1>\n\n<p>In your implementation, you load the complete linked list into a builtin <code>list</code>. This is not needed. You can use <code>enumerate</code> to loop over the elements, and keep track of the index</p>\n\n<pre><code>def __getitem__(self, index):\n for i, node in enumerate(self):\n if i == index:\n return node\n raise IndexError(f\"{index} not found\")\n</code></pre>\n\n<p>This works for positive indices. If you also want to accept negative indices, you need to convert the negative index to a positive one:</p>\n\n<pre><code>def __getitem__(self, index):\n if index < 0:\n l = len(self)\n if abs(index) > l:\n raise IndexError(f\"{index} out of range\")\n index = l - index\n\n for i, node in enumerate(self):\n if i == index:\n return node\n raise IndexError(f\"{index} out of range\")\n</code></pre>\n\n<h1><code>__bool__</code></h1>\n\n<p>In python, by convention, empty containers are <em>falsey</em>. Their <code>__bool__</code> function returns <code>False</code>.</p>\n\n<pre><code>def __bool__(self):\n return self.head is not None\n</code></pre>\n\n<h1><code>arrayToLinked</code></h1>\n\n<p>In python, it's seldomly necessary to loop over an index. Instead of <code>for i in range(1, len(arr))</code>, you can use <code>for value in arr:</code>. This only needs a bit of special handling for the head of the list. </p>\n\n<p>Your <code>arrayToLinked</code> method corresponds to <code>list.extend(iterable)</code> on an ordinary list. I only clears the list first. My suggestion would be to skip the clearing of the list. If the user wants a fresh list, he can either explicitly clear it himself, or call the constructor while providing the iterable:</p>\n\n<pre><code>def extend(self, iterable):\n it = iter(iterable)\n if not self:\n try:\n self.head = Node(next(it))\n except StopIteration:\n self.head = None\n\n for value in it:\n self.append(Node(value))\n\ndef __init__(self, iterable=None):\n self.head = None\n if iterable is not None:\n self.extend(iterable)\n</code></pre>\n\n<hr>\n\n<p>As409_conflict noted in the comments, this might not be the most performant method to use</p>\n\n<p>if you provide a <code>tail</code> method,</p>\n\n<pre><code>def tail(self):\n \"\"\"\n returns the last element in the linked list. \n \"\"\"\n\n if self.head is None:\n return None\n for current in self:\n pass\n return current\n\n\ndef extend(self, iterable):\n it = iter(iterable)\n if not self:\n try:\n self.head = Node(next(it))\n except StopIteration:\n return\n current = self.tail()\n\n for value in it:\n current.next = current = Node(value)\n</code></pre>\n\n<h1><code>copy</code></h1>\n\n<p>The copy then becomes as simple as</p>\n\n<pre><code>def copy(self):\n return type(self)(self.iter_values())\n</code></pre>\n\n<h1><code>sort</code></h1>\n\n<pre><code>def sort(self):\n sorted_values = sorted(self.iter_values())\n self.clear()\n self.extend(sorted_values )\n</code></pre>\n\n<p>Or, If you want to return a new instance</p>\n\n<pre><code>def sort(self):\n return type(self)(sorted(self.iter_values()))\n</code></pre>\n\n<hr>\n\n<p>In general, I suggest you take a look at the <a href=\"https://docs.python.org/3/reference/datamodel.html\" rel=\"nofollow noreferrer\">Python data model</a>, and what methods a standard <code>list</code> provides, and thy to mimic those behaviours</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T11:54:30.530",
"Id": "454740",
"Score": "0",
"body": "Due to the linear complexity of append, your extend complexity is squared. Better incorporate the looping there or introduce `self._last`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T11:01:22.500",
"Id": "232694",
"ParentId": "232690",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "232694",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T09:07:01.753",
"Id": "232690",
"Score": "3",
"Tags": [
"python",
"algorithm",
"python-3.x",
"linked-list"
],
"Title": "Linked List implementation in python 3.x"
}
|
232690
|
<p>I'm new to JavaScript and came across classes in ES6. Though they are great, I don't want to learn something that can be done in other ways. So, I created this code that does somehow similar job to what classes in JS do. Please give me feedback on whether classes does more than what I think they can do and whether my code is missing something that classes can do.
This is the JS code:</p>
<pre><code><script>
const person = function(first, second, age, sex){
return {
firstName:first,
lastName:second,
age:age,
gender:sex,
fullName:function(){
return this.firstName + " " + this.lastName;
}
}
}
var John = person("John", "Anderson", 21, "Male");
var Mary = person("Mary", "Smith", 32, "Female");
document.getElementById("demo1").innerHTML = John.firstName;
document.getElementById("demo2").innerHTML = Mary.fullName();
</script>
</code></pre>
<p>And the output of the code is: </p>
<pre><code>John
Mary Smith
</code></pre>
|
[] |
[
{
"body": "<p>A short review;</p>\n\n<ul>\n<li>In stacktraces, <code>person</code> will be a nameless function, use <code>function person(){}</code> instead</li>\n<li>There is no good reason to have different names (<code>first</code>-><code>firstName</code>) for your attributes. Using the same name allows you to use some nifty JS syntax</li>\n<li>Your code will create a new function for each instance of <code>person</code>, unless you have a smart VM, that could be heavy on memory</li>\n<li>I would extend the <code>.prototype</code> of <code>person</code> for <code>fullName</code> to prevent that memory issue</li>\n<li>I also strive to name functions with a <code><verb><thing></code> scheme so I would call it <code>getFullName()</code></li>\n<li>Ideally functions that are akin to a class are capitalized, so <code>person</code> -> <code>Person</code></li>\n</ul>\n\n<p>So, all in all, this is my counter proposal:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code> function Person(firstName, lastName, age, gender){\n Object.assign(this, {firstName, lastName, age, gender});\n }\n\n Person.prototype.getFullName = function personGetFullName(){\n return this.firstName + \" \" + this.lastName;\n }\n\n const John = new Person(\"John\", \"Anderson\", 21, \"Male\");\n const Mary = new Person(\"Mary\", \"Smith\", 32, \"Female\");\n console.log(John.firstName);\n console.log(Mary.getFullName());</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-29T04:47:40.787",
"Id": "459195",
"Score": "0",
"body": "Thank you for the explanation. I'll further study javascript classes and object in more depth to understand them more"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T11:17:41.193",
"Id": "232696",
"ParentId": "232691",
"Score": "6"
}
},
{
"body": "<p>This style is the best for encapsulation as it can use closure to protect the objects state. However if you expose all the properties without getters and setters you destroy the encapsulation.</p>\n\n<h2>Exposed example</h2>\n\n<ul>\n<li>This exposes all the properties.</li>\n<li>Uses property shorthand to assign properties.</li>\n<li>Uses function shorthand to define the function.</li>\n</ul>\n\n<p>Code</p>\n\n<pre><code>function person(firstName, lastName, age, gender) {\n return {\n firstName, lastName, age, gender,\n fullName() { return this.firstName + \" \" + this.lastName },\n };\n}\n\n// or with getter\n\nfunction person(firstName, lastName, age, gender) {\n return {\n firstName, lastName, age, gender,\n get fullName() { return this.firstName + \" \" + this.lastName },\n };\n}\n\n// or compact form\n\nfunction fullName() { return this.firstName + \" \" + this.lastName }\nconst person=(firstName, lastName, age, gender)=>({firstName, lastName, age, gender, fullName});\n</code></pre>\n\n<h2>Encapsulated example</h2>\n\n<ul>\n<li><p>Protects state via closure, using getters and setters to vet properties and maintain trusted state.</p></li>\n<li><p>Object is frozen so that the existing properties can not be changed or new ones added. As setters are used the object though frozen can still change state.</p></li>\n</ul>\n\n<p>Code</p>\n\n<pre><code>function person(firstName, lastName, age, gender) {\n return Object.freeze({\n get firstName() { return firstName },\n get lastName() { return lastName }, \n get age() { return age }, \n get gender() { return gender },\n get fullName() { return this.firstName + \" \" + this.lastName },\n\n set firstName(str) { firstName = str.toString() },\n set lastName(str) { lastName = str.toString() }, \n set age(num) { age = num >= 0 && num <= 130 ? Math.floor(Number(num)) : \"NA\" }, \n set gender(str) { gender = str === \"Male\" || str === \"Female\" ? str : \"NA\" },\n });\n}\n</code></pre>\n\n<p>Note that age and genders vet the values using the setters. However if the object is created with bad age or gender values the values remain invalid.</p>\n\n<p>To avoid the this you can either have the getters vet the state and return the correct state or not return the object immediately and assign the properties within the function. Personally I use <code>API</code> to hold the closure copy, but what ever suits your style is ok.</p>\n\n<pre><code>function person(firstName, lastName, age, gender) {\n const API = {\n get firstName() { return firstName },\n get lastName() { return lastName }, \n get age() { return age }, \n get gender() { return gender },\n get fullName() { return this.firstName + \" \" + this.lastName },\n\n set firstName(str) { firstName = str.toString() },\n set lastName(str) { lastName = str.toString() }, \n set age(num) { age = num >= 0 && num <= 130 ? Math.floor(Number(num)) : \"NA\" }, \n set gender(str) { gender = str === \"Male\" || str === \"Female\" ? str : \"NA\" },\n };\n\n API.age = age;\n API.gender = gender;\n API.firstName = firstName; // ensures these are not objects that can change\n API.lastName = lastName; // the toString in the setter makes a copy\n return Object.freeze(API);\n}\n</code></pre>\n\n<h2>Object's <code>prototype</code></h2>\n\n<p>For modern browsers the functions are cached and copies are references so prototypes do not give any advantage in terms of memory and performance.</p>\n\n<p>In older browsers (> 3 years approx) this style has an overhead when creating a new instance. Each function within the function person needs to be evaluated and instantiated as a new instance of that function thus using more memory and CPU cycles at instantiation.</p>\n\n<p>This overhead is not large but if you are creating many 1000s that have lives longer than the current execution but quickly released, this becomes a noticeable problem. Example may be a particle system with each particle being a short lived object.</p>\n\n<p>If performance is important use the prototype as follows. You could also reuse objects by keeping a pool of unused objects.</p>\n\n<p>Notes </p>\n\n<ul>\n<li>You will lose encapsulation.</li>\n<li>The object name is changed to \"Person\" and though not required should be instantiated with <code>new</code></li>\n<li>Can not use setters for the properties assign at instantiation so the object state remains untrust-able.</li>\n<li>Freeze the prototype as that should not be changed (if that is a priority)</li>\n<li>Adds <code>toString</code> which will be called automatically as needed for type coercion. Can also be done with the above versions.</li>\n<li>Adds <code>valueOf</code> as handy way to copy object without having to deal with <code>fullName</code> as a getter. Can also be done with the above versions.</li>\n</ul>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function Person(firstName, lastName, age, gender) {\n return Object.assign(this, {firstName, lastName, age, gender});\n}\n// or but MUST use new to create\nfunction Person(firstName, lastName, age, gender) {\n this.firstName = firstName; \n this.lastName = lastName; \n this.age = age >= 0 && age <= 130 ? Math.floor(Number(age)) : \"NA\";\n this.gender = typeof gender === \"string\" && gender.toLowerCase() === \"male\" ? \"Male\" : \"Female\";\n // without the return this will return undefined if called as Person()\n // but will return this if called with new Person();\n}\n\nPerson.prototype = Object.freeze({\n get fullName() { return (this.gender === \"Male\" ? \"Mr \" : \"Miss \") + this.firstName + \" \" + this.lastName },\n toString() { return this.fullName + \" \" + this.age + \"y \" + this.gender },\n get valueOf() { return [this.firstName, this.lastName, this.age, this.gender] },\n});\n\nconst foo = new Person(\"Foo\", \"Bar\", 20, \"Male\");\nconsole.log(\"Object foo: \" + foo); // auto toString\nconst boo = new Person(...foo.valueOf);\nboo.firstName = \"Boo\";\nboo.gender = \"Female\";\nconsole.log(\"Object boo: \" + boo); \nconsole.log(boo);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-29T04:51:03.743",
"Id": "459197",
"Score": "0",
"body": "This was super helpful. Thank you. I need to further study javascript classes and objects to understand all concepts around them"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T22:34:20.633",
"Id": "232718",
"ParentId": "232691",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T09:14:19.920",
"Id": "232691",
"Score": "4",
"Tags": [
"javascript",
"object-oriented",
"ecmascript-6"
],
"Title": "Alternative code to classes in Javascript?"
}
|
232691
|
<p>Part 1: <a href="https://codereview.stackexchange.com/questions/217767/tic-tac-toe-with-changeable-board-size-part-1">Tic-Tac-Toe with changeable board size (Part 1)</a></p>
<p>I just revisited all my previous questions and saw that I hadn't updated my Tic-Tac-Toe code. So, I improvised my code as per @Austin Hastings suggestions</p>
<p>Here's the updated code:</p>
<pre class="lang-py prettyprint-override"><code>import os
from random import randint
from textwrap import dedent
cls = lambda: os.system('CLS') # Works only in command console.
# Random names
names = [
'Jacob', 'Michael',
'Joshua', 'Ethan', 'Matthew', 'Daniel',
'Christopher', 'Andrew', 'Anthony', 'William',
'Joseph', 'Alexander', 'David', 'Ryan',
'Noah', 'James', 'Nicholas', 'Tyler',
'Logan', 'John', 'Christian', 'Jonathan',
'Nathan', 'Benjamin', 'Samuel', 'Dylan',
'Brandon', 'Gabriel', 'Elijah', 'Aiden',
'Angel', 'Jose', 'Zachary', 'Caleb',
'Jack', 'Jackson', 'Kevin', 'Gavin',
'Mason', 'Isaiah', 'Austin', 'Evan',
'Luke', 'Aidan', 'Justin', 'Jordan',
'Robert', 'Isaac', 'Landon', 'Jayden',
'Thomas', 'Cameron', 'Connor', 'Hunter',
'Jason', 'Diego', 'Aaron', 'Bryan',
'Owen', 'Lucas', 'Charles', 'Juan',
'Luis', 'Adrian', 'Adam', 'Julian',
'Alex', 'Sean', 'Nathaniel', 'Carlos',
'Jeremiah', 'Brian', 'Hayden', 'Jesus',
'Carter', 'Sebastian', 'Eric', 'Xavier',
'Brayden', 'Kyle', 'Ian', 'Wyatt',
'Chase', 'Cole', 'Dominic', 'Tristan',
'Carson', 'Jaden', 'Miguel', 'Steven',
'Caden', 'Kaden', 'Antonio', 'Timothy',
'Henry', 'Alejandro', 'Blake', 'Liam',
'Richard', 'Devin', 'Riley', 'Jesse',
'Seth', 'Victor', 'Brady', 'Cody',
'Jake', 'Vincent', 'Bryce', 'Patrick',
'Colin', 'Marcus', 'Cooper', 'Preston',
'Kaleb', 'Parker', 'Josiah', 'Oscar',
'Ayden', 'Jorge', 'Ashton', 'Alan',
'Jeremy', 'Joel', 'Trevor', 'Eduardo',
'Ivan', 'Kenneth', 'Mark', 'Alexis',
'Omar', 'Cristian', 'Colton', 'Paul',
'Levi', 'Damian', 'Jared', 'Garrett',
'Eli', 'Nicolas', 'Braden', 'Tanner',
'Edward', 'Conner', 'Nolan', 'Giovanni',
'Brody', 'Micah', 'Maxwell', 'Malachi',
'Fernando', 'Ricardo', 'George', 'Peyton',
'Grant', 'Gage', 'Francisco', 'Edwin',
'Derek', 'Max', 'Andres', 'Javier',
'Travis', 'Manuel', 'Stephen', 'Emmanuel',
'Peter', 'Cesar', 'Shawn', 'Jonah',
'Edgar', 'Dakota', 'Oliver', 'Erick',
'Hector', 'Bryson', 'Johnathan', 'Mario',
'Shane', 'Jeffrey', 'Collin', 'Spencer',
'Abraham', 'Leonardo', 'Brendan', 'Elias',
'Jace', 'Bradley', 'Erik', 'Wesley',
'Jaylen', 'Trenton', 'Josue', 'Raymond',
'Sergio', 'Damien', 'Devon', 'Donovan',
'Dalton', 'Martin', 'Landen', 'Miles',
'Israel', 'Andy', 'Drew', 'Marco',
'Andre', 'Gregory', 'Roman', 'Ty',
'Jaxon', 'Avery', 'Cayden', 'Jaiden',
'Roberto', 'Dominick', 'Rafael', 'Grayson',
'Pedro', 'Calvin', 'Camden', 'Taylor',
'Dillon', 'Braxton', 'Keegan', 'Clayton',
'Ruben', 'Jalen', 'Troy', 'Kayden',
'Santiago', 'Harrison', 'Dawson', 'Corey',
'Maddox', 'Leo', 'Johnny', 'Kai',
'Drake', 'Julio', 'Lukas', 'Kaiden',
'Zane', 'Aden', 'Frank', 'Simon',
'Sawyer', 'Marcos', 'Hudson', 'Trey'
]
# Dummy Variable
start = 0
# Essential Variables:
player = 'Player' # Player name
board_type = 2 # Board Type (1 or 2)
board = [['', '', ''], ['', '', ''], ['', '', '']] # The TicTacToe board
win_board = [['', '', ''], ['', '', ''], ['', '', '']] # Traces the win (if any) of 'board'
X = 'X'
O = 'O'
size = 3
def empty_cells():
empty = []
for i in range(size):
for j in range(size):
if board[i][j] != X and board[i][j] != O:
empty.append((i, j))
return empty
def countWins(p):
"""
Counts the wins possible in the current move for player 'p'
"""
count = 0
empty = empty_cells()
for i, j in empty:
copy = board[i][j]
board[i][j] = p
count += win(p)
board[i][j] = copy
return count
def get_insane_AI_move(ai, pl, x=0, name=''):
"""
ai: ai character
pl: player character
x: dummy variable
name: ai name
The best AI
Follows all the tips and checks for moves leading to multiple wins constantly
"""
empty = empty_cells()
length = len(empty)
if length == 1:
i, j = empty[0]
if x:
print(name + ' Moved To Grid', i * size + j + 1)
return
for i, j in empty:
copy = board[i][j]
board[i][j] = ai
if win(ai):
if x:
print(name + ' Moved To Grid', i * size + j + 1)
return
board[i][j] = copy
for i, j in empty:
copy = board[i][j]
board[i][j] = pl
if win(pl) or length == 1:
board[i][j] = ai
if x:
print(name + ' Moved To Grid', i * size + j + 1)
return
board[i][j] = copy
wins2 = []
l = 0
for i, j in empty:
copy = board[i][j]
board[i][j] = ai
if countWins(ai) > 1:
l += 1
r = [i, j]
wins2.append(r)
board[i][j] = copy
if l:
m = wins2[randint(0, 1000) % l]
board[m[0]][m[1]] = ai
if x:
print(name + ' Moved To Grid', m[0] * size + m[1] + 1)
return
l = 0
pos_centers = [[i, j] for i in range(size) for j in range(size)
if (i in [0, size - 1]) == (j in [0, size - 1]) == False]
centers = []
for i in range(len(pos_centers)):
x = pos_centers[i][0]
y = pos_centers[i][1]
if board[x][y] != ai and board[x][y] != pl:
centers.append(pos_centers[i])
l += 1
if l:
r = centers[randint(1, 1000) % l]
board[r[0]][r[1]] = ai
if x:
print(name + ' Moved To Grid', r[0] * size + r[1] + 1)
return
l1 = l2 = 0
pos_edges = [[0, 0], [0, size - 1], [size - 1, 0], [size - 1, size - 1]]
edges = []
for i in range(len(pos_edges)):
x = pos_edges[i][0]
y = pos_edges[i][1]
if board[x][y] != ai and board[x][y] != pl:
edges.append(pos_edges[i])
l1 += 1
if l1:
r = edges[randint(1, 1000) % l1]
board[r[0]][r[1]] = ai
if x:
print(name + ' Moved To Grid', r[0] * size + r[1] + 1)
return
pos_middles = [[i, j] for i in range(size) for j in range(size)
if (i in [0, size - 1]) != (j in [0, size - 1])]
middles = []
for i in range(len(pos_middles)):
x = pos_middles[i][0]
y = pos_middles[i][1]
if board[x][y] != ai and board[x][y] != pl:
middles.append(pos_middles[i])
l2 += 1
r = middles[randint(1, 1000) % l2]
board[r[0]][r[1]] = ai
if x:
print(name + ' Moved To Grid', r[0] * size + r[1] + 1)
return
def get_hard_AI_move(ai, pl, x=0, name=''):
"""
A medium AI
Can only look ahead 1 move
"""
empty = empty_cells()
length = len(empty)
if length == 1:
i, j = empty[0]
if x:
print(name + ' Moved To Grid', i * size + j + 1)
return
for i, j in empty:
copy = board[i][j]
board[i][j] = ai
if win(ai) == 1:
if x:
print(name + ' Moved To Grid', i * size + j + 1)
return
board[i][j] = copy
for i, j in empty:
copy = board[i][j]
board[i][j] = pl
if win(pl) == 1:
board[i][j] = ai
if x:
print(name + ' Moved To Grid', i * size + j + 1)
return
board[i][j] = copy
l = 0
possible = [[i, j] for i in range(size) for j in range(size)]
available = []
for i in range(len(possible)):
x = possible[i][0]
y = possible[i][1]
if board[x][y] != ai and board[x][y] != pl:
available.append(possible[i])
l += 1
r = available[randint(1, 1000) % l]
board[r[0]][r[1]] = ai
if x:
print(name + ' Moved To Grid', r[0] * size + r[1] + 1)
return
def get_easy_AI_move(ai, pl, x=0, name=''):
"""
An easy AI
Moves randomly
"""
l = 0
available = []
for x, y in empty_cells():
if board[x][y] != ai and board[x][y] != pl:
available.append((x, y))
l += 1
r = available[randint(1, 1000) % l]
board[r[0]][r[1]] = ai
if x:
print(name + ' Moved To Grid', r[0] * size + r[1] + 1)
return
def get_user_move(p1, p2):
""" Gets user input and processes it """
g = int(input(f'Please Enter Grid Number (1 ~ {size * size}): ')) - 1
x = g // size
y = g % size
if x >= size or y >= size or board[x][y] == p1 or board[x][y] == p2:
print('Please Enter A Valid Move')
get_user_move(p1, p2)
return
print(player + ' Moved To Grid', g + 1)
board[x][y] = p1
print()
def get_win(p):
""" Traces the win into 'win_board' """
for i in range(size):
# Rows
if all(board[i][j] == p for j in range(size)):
for j in range(size):
win_board[i][j] = p
return
# Columns
if all(board[j][i] == p for j in range(size)):
for j in range(size):
win_board[j][i] = p
return
# Diagonals
if all(board[i][i] == p for i in range(size)):
for i in range(size):
win_board[i][i] = p
return
if all(board[i][-(i + 1)] == p for i in range(size)):
for i in range(size):
win_board[i][-(i + 1)] = p
return
## Returns in every case as multiple wins might be traced out
def printBoard1():
""" Prints board type 1 """
for i in range(size - 1):
print(' ' + '| ' * (size - 1))
print(end=' ')
for j in range(size - 1):
print(board[i][j], end=' | ')
print(board[i][-1])
print(' ' + '| ' * (size - 1))
print('------' + '--------' * (size - 1))
' | '
print(' ' + '| ' * (size - 1))
print(end=' ')
for j in range(size - 1):
print(board[-1][j], end=' | ')
print(board[-1][-1])
print(' ' + '| ' * (size - 1))
print()
def printBoard2():
""" Prints board type 2 """
for i in range(size - 1):
for j in range(size - 1):
print(board[i][j], end=' | ')
print(board[i][-1])
print('---' * size + '-' * (size - 3))
for j in range(size - 1):
print(board[-1][j], end=' | ')
print(board[-1][-1])
print()
def printWin(p):
""" Prints 'win_board' at board type 2"""
get_win(p)
for i in range(size - 1):
for j in range(size - 1):
print(win_board[i][j], end=' | ')
print(win_board[i][-1])
print('---' * size + '-' * (size - 2))
for j in range(size - 1):
print(win_board[-1][j], end=' | ')
print(win_board[-1][-1])
print()
def getRandomName():
""" Gets random names from 'names' """
name = names[randint(1, 1000) % 250]
return name
def helper():
""" Help section containing Rules, Tips and Credits """
print()
print('B for Back\n')
print('1. Rules')
print('2. Tips')
print('3. Credits')
option = input('\nPlease Enter Your Option: ').lower()
print()
if option == 'b': return
if option == '1': rules()
if option == '2': tips()
if option == '3': about()
input('Enter To Continue . . . ')
print()
helper()
def about():
print('This Game Of Tic-Tac-Toe Is Created By Srivaths')
print('If You Are Unfamiliar With This Game, Please Read The Rules And Tips')
print('Enjoy!!\n')
def changeName():
""" Changes player name: 'player' """
global player
player = input('Please Enter Your Name: ')
def changeBoard():
""" Changes board type: 'board_type' """
global board_type
print()
print('B for Back\n')
print('1.')
printBoard1()
print('2.\n')
printBoard2()
print()
option = input('\nPlease Enter Your Option: ')
if option == 'b' or option == 'B':
return
if option == '1': board_type = 1
if option == '2': board_type = 2
def changeCharacters():
""" Changes characters: 'X', 'O' """
global X, O
print()
X = input('Please Enter Character For Player 1 (currently ' + X + '): ')
O = input('Please Enter Character For Player 2 (currently ' + O + '): ')
def changeSize():
""" Changes board size: 'size' """
global size
size = int(input('Please Enter Size: '))
initialize()
def settings():
""" Settings """
print()
print('B for Back\n')
print('1. Change Name')
print('2. Change Size')
print('3. Change Board')
print('4. Change Characters')
option = input('\nPlease Enter Your Option: ').lower()
if option == 'b':
return
if option == '1': changeName()
if option == '2': changeSize()
if option == '3': changeBoard()
if option == '4': changeCharacters()
print()
settings()
def main_menu():
""" The main menu """
global start
# cls()
print()
if start == 0:
intro()
start = 1
main_menu()
return
print('Hello ' + player)
print('\nQ for Quit\n')
print('1. Help')
print('2. Settings')
print('3. Play')
option = input('\nPlease Enter Your Option: ')
if option == '1':
helper()
if option == '2':
settings()
if option == '3':
initialize()
play('X', 'O')
if option == 'q' or option == 'Q':
print('Thanks For Playing!\n')
return
print()
main_menu()
def rules():
""" Basic rules """
print(
dedent('''
1. In Tic-Tac-Toe, there are 2 players and their characters are X and O respectively
2. Any row or column or diagonal filled the same character is a win
3. A board where there are no moves left is a tie
4. You are not allowed to place characters over another
5. The playes must play in alternate turns, starting with X
''')
)
def tips():
""" Basic tips """
print(
dedent(
'''
1. Always try and capture the center
2. Next try to capture the edges
3. Occupy the edges only if necessary
4. Be aware of immediate moves
5. Try the easy bot to get the hang of the game
'''
)
)
def intro():
""" Introduction """
global board_type
initialize()
print('Hello Player', end=', ')
changeName()
print('\nHello ' + player + ', Welcome To The Game Of Tic-Tac-Toe!!')
know = input('Are You Familiar With The Game? (y / n): ').lower()
if know == 'n':
print('\nFirst A Little Introduction To The Rules: \n')
rules()
print('\nNext A Few Tips: \n')
tips()
print('\nAnd That\'s ALL!!!\n')
input('Enter To Continue . . . ')
print('\n')
print('\nPlease Pick Your Board Preference: \n')
print('1.')
printBoard1()
print('2.\n')
printBoard2()
print()
option = input('Please Enter Your Option: ')
if option == '1': board_type = 1
if option == '2': board_type = 2
print(
dedent('''
Change Characters Via [Main Menu -> Settings -> Change Characters]
Here You Must Try Your Luck Against Three Levels!!
1. Easy
2. Hard
3. Insane
Can YOU Beat Them ALL????
Let's See....
''')
)
input('Enter To Continue . . . ')
def play(p1, p2):
"""
The play area
p1: Player 1
p2: Player 2
"""
print()
initialize()
computer = getRandomName()
print('1. Easy')
print('2. Hard')
print('3. Insane')
print()
level = int(input('Please Enter Level: '))
print()
while computer == player:
computer = getRandomName()
print('\t\t' + player + ' VS ' + computer + '\n\n')
c = randint(0, 1)
pl = p1
ai = p2
if c == 0:
ai = p1
pl = p2
print('\n' + computer + ' Goes First!\n\n')
else:
print('\n' + player + ' Goes First!\n\n')
if board_type == 1:
printBoard1()
else:
printBoard2()
d = 0
while True:
t = d % 2
if t == c:
if level == 1: get_easy_AI_move(ai, pl, 1, computer)
if level == 2: get_hard_AI_move(ai, pl, 1, computer)
if level == 3: get_insane_AI_move(ai, pl, 1, computer)
if board_type == 1:
printBoard1()
else:
printBoard2()
if win(ai):
print(computer + ' Wins!\n')
print('Below Is How ' + computer + ' Won\n\n')
printWin(ai)
break
else:
get_user_move(pl, ai)
if board_type == 1:
printBoard1()
else:
printBoard2()
if win(pl):
print(player + ' Wins!')
print('Below Is How ' + player + ' Won\n')
printWin(pl)
break
if len(empty_cells()) == 0:
print('Tie!')
break
d += 1
play_again(p1, p2)
def initialize():
""" Resets the board """
global board, win_board
board = [[' ' for _ in range(size)] for __ in range(size)]
win_board = [[' ' for _ in range(size)] for __ in range(size)]
def play_again(p1, p2):
""" Gets input from the player asking if they want to play again """
option = input('Would You Like To Play Again? (y(yes) / n(no) / m(Main Menu): ').lower()
if option == 'y':
play(p1, p2)
elif option == 'n':
return
elif option == 'm':
return
else:
print('\nPlease Enter a Valid Option')
play_again(p1, p2)
def win(p):
""" Checks for win """
if any(all(board[i][j] == p for j in range(size)) for i in range(size)):
return True
if any(all(board[j][i] == p for j in range(size)) for i in range(size)):
return True
if all(board[i][i] == p for i in range(size)):
return True
if all(board[i][-(i + 1)] == p for i in range(size)):
return True
return False
main_menu()
</code></pre>
<p>Hope @Austin Hastings will answer this question too!</p>
|
[] |
[
{
"body": "<h1>Winning Bug</h1>\n<p>When the board is at this stage and the user gets the next move:</p>\n<pre><code> | | \n X | O | X\n | | \n----------------------\n | | \n | O | \n | | \n----------------------\n | | \n O | X | X\n | | \n</code></pre>\n<p>And the user enters <strong>5</strong>, the game bugs and will let the user enter again and win the game, instead of the AI placing an X at position 4 resulting in a draw.</p>\n<h1>Start Game Bug</h1>\n<p>When first prompted to select a difficulty, you enter a number (lets say <strong>1</strong>). Then it asks you what you want to do. You enter <strong>3</strong> to play. It then asks you what difficulty <em>again</em>. I would remove the first prompt of difficulty, since it's kinda weird you ask for the difficulty <em>before</em> seeing if the user wants to play at all.</p>\n<h1><code>win</code></h1>\n<p>When returning <code>True</code> or <code>False</code>, 90% of the time you can instead return the expression that would result in those values. Observe:</p>\n<pre><code>def win(p):\n """ Checks for win """\n\n return any([\n any(all(board[i][j] == p for j in range(size)) for i in range(size)),\n any(all(board[j][i] == p for j in range(size)) for i in range(size)),\n all(board[i][i] == p for i in range(size)),\n all(board[i][-(i + 1)] == p for i in range(size))\n ])\n</code></pre>\n<p>This erases the need of any <code>return True</code> statements as returning the <em>expression</em> will result in a boolean value itself.</p>\n<h1>Ternary Operators</h1>\n<p>This</p>\n<pre><code>if board_type == 1:\n printBoard1()\nelse:\n printBoard2()\n</code></pre>\n<p>can be simplified to this using a <a href=\"https://book.pythontips.com/en/latest/ternary_operators.html\" rel=\"nofollow noreferrer\">ternary operator</a>:</p>\n<pre><code>printBoard1() if board_type == 1 else printBoard2()\n</code></pre>\n<h1>Method Naming</h1>\n<p>Method and variable names should <strong>both</strong> be <code>snake_case</code>.</p>\n<pre><code>printBoard1() -> print_board_one()\n</code></pre>\n<p>I would also use "one" instead of "1", but that's a personal preference.</p>\n<h1>That big list of names</h1>\n<p>Time to address the elephant in the room. I would put the names in a separate file, like <code>names.txt</code>, and extrapolate the information from there. It clears up a bunch of bulk from your code. Here's how this method might look like:</p>\n<p><strong>names.txt</strong></p>\n<pre><code>Ben,David,Hannah,Max,Sarah,William\n</code></pre>\n<pre><code>def get_names():\n with open("names.txt", "r") as file:\n return ''.join(file.readlines()).split(",")\n</code></pre>\n<p>It will return</p>\n<pre><code>["Ben", "David", "Hannah", "Max", "Sarah", "William"]\n</code></pre>\n<p>What this does is reads every line in the file, converts that list into a string, then returns a list of each word split by a comma. It's a simple way to access and get data from the names file. It also significantly reduces the clutter in your code.</p>\n<p>If you don't want to go through the trouble of putting each name in the file, that's understandable. What you can do is create another python module <code>names.py</code>, put the list in that file, and import from that file. Take a look:</p>\n<pre><code>from names import NAMES # NAMES is the list of names\n</code></pre>\n<p>Now you can operate on this <code>NAMES</code> list.</p>\n<h1>String Formatting</h1>\n<p>This</p>\n<pre><code>print(name + ' Moved To Grid', r[0] * size + r[1] + 1)\n</code></pre>\n<p>can be written like this:</p>\n<pre><code>print(f"{names} Moved To Grid {r[0] * size + r[1] + 1}")\n</code></pre>\n<p>The same with these input statements</p>\n<pre><code>X = input(f"Please Enter Character For Player 1 (currently {X}): ")\nO = input(f"Please Enter Character For Player 2 (currently {O}): ")\n</code></pre>\n<h1>Type Hints</h1>\n<p>Lets take a look at this method header:</p>\n<pre><code>def play_again(p1, p2):\n</code></pre>\n<p>Now, consider this:</p>\n<pre><code>def play_again(p1: str, p2: str) -> None:\n</code></pre>\n<p>These can help you and other people using your program identify what types to pass into the method, as well as what values could be returned.</p>\n<h1>If Statement Formatting</h1>\n<p>This</p>\n<pre><code>if level == 1: get_easy_AI_move(ai, pl, 1, computer)\nif level == 2: get_hard_AI_move(ai, pl, 1, computer)\nif level == 3: get_insane_AI_move(ai, pl, 1, computer)\n</code></pre>\n<p>should really be this</p>\n<pre><code>if level == 1:\n get_easy_AI_move(ai, pl, 1, computer)\nif level == 2:\n get_hard_AI_move(ai, pl, 1, computer)\nif level == 3:\n get_insane_AI_move(ai, pl, 1, computer)\n</code></pre>\n<h1>Main Guard</h1>\n<p>You should wrap all initialization code in a main guard. This will allow you to import this module without having the code run. Take a look:</p>\n<pre><code>if __name__ == '__main__':\n main_menu()\n</code></pre>\n<p>It's not very conventional to have an if statement on one line.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T16:17:01.590",
"Id": "454534",
"Score": "1",
"body": "`board = [['' * 3] * 3]` will lead to some pretty strange errors"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T16:35:19.987",
"Id": "454535",
"Score": "0",
"body": "@MaartenFabré Do you mind describing a couple so that I might reevaluate that portion of my answer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T19:14:45.887",
"Id": "454552",
"Score": "0",
"body": "@Carcigenicate I see that I have a lot of misconceptions when it comes to working with lists. I've removed that part of the answer because it is so flawed. I'll have to take some time to relearn what I thought I knew about lists. Thanks for the explanation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T05:33:02.113",
"Id": "454572",
"Score": "0",
"body": "@Linny, it doesn't ask for the difficulty level, it displays that there are 3 types of AI and prompts the user to `Enter To Continue . . . `.\n\nAlso, can you please explain what the first bug did in more detail?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T15:41:52.097",
"Id": "232707",
"ParentId": "232698",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "232707",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T11:44:16.720",
"Id": "232698",
"Score": "2",
"Tags": [
"python",
"algorithm",
"python-3.x",
"linked-list"
],
"Title": "Tic-Tac-Toe with changeable board size (Part 2)"
}
|
232698
|
<p>I have an Excel file and each row within the sheet represents an employee's data.</p>
<p>I am trying to find a cleaner way to map each row to a <code>model</code> object:</p>
<pre><code>public IList<Employee> ReadEmployees(byte[] file, string companyId)
{
var employees = new List<Employee>();
using (var stream = new MemoryStream(file))
{
using (var package = new ExcelPackage(stream))
{
var worksheet = package.Workbook.Worksheets[0];
for (var rowNumber = 3; rowNumber <= worksheet.Dimension.End.Row; rowNumber++)
{
//---- Trying to retrieve the row data in an elegant way----
var employee = GetEmployeeRowSummary(worksheet, rowNumber, companyId);
employees.Add(employee);
}
}
}
return employees;
}
</code></pre>
<p>I was kind of hoping to use something like <code>auto-mapper</code> but don't know if that would be the best way (maybe create a Custom Resolver).</p>
<p>Is there a better way of mapping excel rows to an model? The way I am doing it currently seems like a maintenance issue.</p>
<pre><code>private static Employee GetEmployeeRowSummary(ExcelWorksheet worksheet, int rowNumber, string companyId)
{
var employeeId = Guid.NewGuid().ToString();
return new Employee
{
CompanyId = companyId,
EmployeeId = employeeId,
EmployeeNumber = worksheet.Cells[rowNumber, 1].GetValue<string>(),
FirstName = worksheet.Cells[rowNumber, 2].GetValue<string>(),
LastName = worksheet.Cells[rowNumber, 3].GetValue<string>(),
BirthDate = worksheet.Cells[rowNumber, 4].GetValue<DateTime>(),
AppointmentDate = worksheet.Cells[rowNumber, 5].GetValue<DateTime>(),
CompanyRunFrequencyId = 9,
JobTitle = worksheet.Cells[rowNumber, 8].GetValue<string>(),
DateCreated = DateTime.Now,
EmployeeAddress = new List<EmployeeAddress>
{
new EmployeeAddress
{
EmployeeId = employeeId,
StreetNumber = worksheet.Cells[rowNumber, 9].GetValue<int>(),
Suburb = worksheet.Cells[rowNumber, 11].GetValue<string>(),
City = worksheet.Cells[rowNumber, 12].GetValue<string>(),
PostalCode = worksheet.Cells[rowNumber, 13].GetValue<int>()
}
}
};
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T13:21:45.300",
"Id": "454505",
"Score": "0",
"body": "Is this the code as you currently use it? Maintenance issues aside, does it work to your satisfaction?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T13:23:02.280",
"Id": "454506",
"Score": "1",
"body": "Yes this is my current code, and working"
}
] |
[
{
"body": "<p>The indentation needs to be mentioned. Hopefully it's just an accidental tabs vs spaces issue that caused it to render this way, ...but I'm not seeing the <kbd>Tab</kbd> characters, so... the indentation needs to be mentioned, becauase this is not normal:</p>\n\n<blockquote>\n<pre><code>public IList<Employee> ReadEmployees(byte[] file, string companyId)\n {\n</code></pre>\n</blockquote>\n\n<p>Expected:</p>\n\n<pre><code>public IList<Employee> ReadEmployees(byte[] file, string companyId)\n{\n</code></pre>\n\n<p>Just like you have here:</p>\n\n<blockquote>\n<pre><code> using (var stream = new MemoryStream(file))\n {\n</code></pre>\n</blockquote>\n\n<p>And here:</p>\n\n<blockquote>\n<pre><code> for (var rowNumber = 3; rowNumber <= worksheet.Dimension.End.Row; rowNumber++)\n {\n</code></pre>\n</blockquote>\n\n<p>Now, with that cleared, the <code>GetEmployeeRowSummary</code> method looks much cleaner already:</p>\n\n<pre><code>private static Employee GetEmployeeRowSummary(ExcelWorksheet worksheet, int rowNumber, string companyId)\n\n{\n var employeeId = Guid.NewGuid().ToString();\n return new Employee\n {\n CompanyId = companyId,\n EmployeeId = employeeId,\n EmployeeNumber = worksheet.Cells[rowNumber, 1].GetValue<string>(),\n FirstName = worksheet.Cells[rowNumber, 2].GetValue<string>(),\n LastName = worksheet.Cells[rowNumber, 3].GetValue<string>(),\n BirthDate = worksheet.Cells[rowNumber, 4].GetValue<DateTime>(),\n AppointmentDate = worksheet.Cells[rowNumber, 5].GetValue<DateTime>(),\n CompanyRunFrequencyId = 9,\n JobTitle = worksheet.Cells[rowNumber, 8].GetValue<string>(),\n DateCreated = DateTime.Now,\n EmployeeAddress = new List<EmployeeAddress>\n {\n new EmployeeAddress\n {\n EmployeeId = employeeId,\n StreetNumber = worksheet.Cells[rowNumber, 9].GetValue<int>(),\n Suburb = worksheet.Cells[rowNumber, 11].GetValue<string>(),\n City = worksheet.Cells[rowNumber, 12].GetValue<string>(),\n PostalCode = worksheet.Cells[rowNumber, 13].GetValue<int>()\n }\n }\n };\n}\n</code></pre>\n\n<p>Consistent indentation is fundamental for clean, readable code.</p>\n\n<p>But readability isn't the biggest problem here: the repeated calls to <code>worksheet.Cells</code> and <code>{Range?}.GetValue</code> are.</p>\n\n<p>I'm not sure what <code>ExcelPackage</code> is, but it's definitely not VSTO, so <em>maybe</em> this isn't as much of a problem, but invoking <code>worksheet.Cells[...].GetValue<...>()</code> is spawning a RCW (Runtime Callable Wrapper - a .NET wrapper object to access a COM object) whose reference isn't captured, and thus could be leaking the object reference. If you were using VSTO, there would very likely be a \"ghost\" EXCEL.EXE process lingering in <em>Task Manager</em> forever, well after your application happily terminated.</p>\n\n<p>In any case, working directly with worksheet cells is THE slowest thing you can do, whether in VBA or C# through COM interop, whether it be through VSTO or any other library.</p>\n\n<p>Again I don't know what <code>ExcelPackage</code> is nor what this API has to offer, but in the native Excel object model <code>Range.Value</code>, when the <code>Range</code> object represents multiple cells, gives you a 2D variant array (<code>object[,]</code> in .NET) - if all you're ever interested in is the values that are in the cells (as seems to be the case), then you don't need to deal with worksheets and cells and <code>.GetValue<T>()</code>.</p>\n\n<p>So instead of looping through rows:</p>\n\n<blockquote>\n<pre><code>for (var rowNumber = 3; rowNumber <= worksheet.Dimension.End.Row; rowNumber++)\n</code></pre>\n</blockquote>\n\n<p>Grab the values array (not sure what the syntax would be with this API - if your library doesn't allow you to grab a 2D array of values, drop that library and use VSTO):</p>\n\n<pre><code>var values = worksheet.Range(worksheet.Cells[3, 1], worksheet.Cells[lastRow, 13]).Value;\n</code></pre>\n\n<p>The idea is to get a <code>Range</code> object that encompasses all the cells you're interested in. Maybe that's everything from row 3 to <code>worksheet.Dimension.End.Row</code>, but even without knowing the slightest thing about this particular API I would fear that <code>worksheet.Dimension.End.Row</code> yields something like 1,048,576 - which is very very very unlikely the <em>actual</em> number of rows you need to care about.</p>\n\n<p>With the Excel object model, you'd do something like <code>sheet.Range(\"A\" & sheet.Rows.Count).End(xlUp).Row</code> to get the last interesting row (aka <code>lastRow</code>), and use that row number to make the \"interesting range\" from which to read the values.</p>\n\n<p>Now that you have a 2D array that contains all the values, <code>GetEmployeeRowSummary</code> doesn't make much sense anymore: we don't care for a <code>rowNumber</code>, and we don't need a <code>ExcelWorksheet</code> reference anymore.</p>\n\n<p>In fact all we need is a \"row slice\" of the 2D array, by copying the row to a new array (<a href=\"https://stackoverflow.com/a/51241629/1188513\">this code</a> looks like it):</p>\n\n<pre><code>public T[] GetRow(T[,] matrix, int rowNumber)\n{\n return Enumerable.Range(0, matrix.GetLength(1))\n .Select(x => matrix[rowNumber, x])\n .ToArray();\n}\n\nprivate static Employee ReadEmployee(object[] row, string companyId)\n{\n var id = Guid.NewGuid().ToString();\n return new Employee\n {\n CompanyId = companyId,\n EmployeeId = id,\n EmployeeNumber = (string)row[1],\n FirstName = (string)row[2],\n LastName = (string)row[3],\n BirthDate = (DateTime)row[4],\n //...\n };\n}\n</code></pre>\n\n<p>As for mapping the properties automatically, I'm not a fan. <em>Something, somewhere</em> needs to do the mapping, and I'd much rather it be explicit in the code. Automatic mapping would need more metadata than just column indices - you'd likely need column names and data types, so instead of copying the cells to an array you'd be copying the cells to some <code>DataTable</code>, or have the mapper understand what an Excel <code>Range</code> or <code>ListObject</code> is... all of which sound like quite a lot of effort for an error-prone way to just list the properties at the left of an <code>=</code> operator. If your explicit casts blow up, you'll know why. If the automagic mapping blows up, pray the library throws meaningful exceptions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T18:24:19.377",
"Id": "454681",
"Score": "1",
"body": "Hi thanks for your reply, going to go through it now, but just to start the indentation was just a pasting issue. And the ExcelPackage is from a library called EPPlus, https://www.nuget.org/packages/EPPlus/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T19:37:42.063",
"Id": "454684",
"Score": "0",
"body": "Ah, so there's no COM interop going on then, the package works directly with the OpenXML... which has pros ...and cons. Everything one knows about the Excel object model goes out the window, basically."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T17:09:24.290",
"Id": "232752",
"ParentId": "232699",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T12:45:36.323",
"Id": "232699",
"Score": "5",
"Tags": [
"c#",
"excel"
],
"Title": "Mapping Excel rows to model"
}
|
232699
|
<p>I use the following code to filter data from <code>SQL</code> and it works fine. However, below code is vulnerable to SQL injection, but all the <code>$post</code> values are checkbox value (it's not user input). So can I use below code?</p>
<p>Or do I need to use "prepared statement" as per <a href="https://stackoverflow.com/a/14767651/4826112">this answer</a>? I can only send number in array. </p>
<p><strong>Conn.php</strong></p>
<pre><code> try {
//create PDO connection
$conn = new PDO("mysql:host=" . DBHOST . ";port=3306;dbname=" . DBNAME, DBUSER, DBPASS);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET CHARACTER SET utf8");
} catch (PDOException $e) {
//show error
echo '<p class="bg-danger">' . $e->getMessage() . '</p>';
exit;
}
</code></pre>
<p><strong>INDEX</strong></p>
<pre><code><div class="md-radio my-1">
<input type="radio" class="filter_all cate" name="cate" id="car" value="Car">
<label for="car">Car</label>
</div>
</code></pre>
<p><strong>script</strong></p>
<pre><code>$(document).ready(function () {
filter_data();
function filter_data() {
$('.filter_data');
var action = 'fetch_data';
var cate = get_filter('cate');
$.ajax({
url: "fetch.php",
method: "POST",
data: {
action: action,
cate: cate
},
success: function (data) {
$('.filter_data').html(data);
}
});
}
function get_filter(class_name) {
var filter = [];
$('.' + class_name + ':checked').each(function () {
filter.push($(this).val());
});
return filter;
}
$('.filter_all').click(function () {
filter_data();
});
});
</code></pre>
<p><strong>fetch.php</strong></p>
<pre><code>if (isset($_POST["action"])) {
$query = "SELECT * FROM allpostdata WHERE sts = '1'";
if (isset($_POST["cate"])) {
$cate = implode("','", $_POST["cate"]);
$query .= "AND sca IN('" . $cate . "')";
}
$stmt = $conn->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll();
$total_row = $stmt->rowCount();
$output = '';
if ($total_row > 0) {
foreach ($result as $row) {
$output .= '<a href="/single_view.php?p=' . $row['link'] . '>' . $row['link']. '</a>
}
} else {
$output = '<h3>No Data Found</h3>';
}
echo $output;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T14:05:42.673",
"Id": "454511",
"Score": "4",
"body": "This question is off topic and \" all the $post values are checkbox value(its not user input)\" is a grave delusion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T14:26:28.840",
"Id": "454512",
"Score": "0",
"body": "@YourCommonSense any solution? as per your answer how do i use word in `array`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T14:27:40.353",
"Id": "454513",
"Score": "0",
"body": "Just exactly as shown in the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T14:31:56.353",
"Id": "454516",
"Score": "0",
"body": "@YourCommonSense i tried but it does nothing no error it triggers `else {\n $output = '<h3>No Data Found</h3>';\n}`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T14:41:01.817",
"Id": "454518",
"Score": "1",
"body": "Here is my instruction on [how to debug your database interactions](https://phpdelusions.net/pdo/mcve). Please follow it to find out why doesn't your query find the data"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T15:04:08.287",
"Id": "454523",
"Score": "0",
"body": "@YourCommonSense i tried https://phpdelusions.net/pdo#in and couldn't get can make a short example with it, what should i replace in above code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T15:30:59.647",
"Id": "454528",
"Score": "0",
"body": "This question is off-topic because of the use of variables that are not defined within the code, examples are `$conn` and `$query`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T04:34:26.997",
"Id": "454707",
"Score": "0",
"body": "@pacmaninbw have look at code added `$conn` and `$query`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T22:25:21.157",
"Id": "454972",
"Score": "0",
"body": "How can this possibly be working as intended? `$parameter` and `$hashed` aren't ever declared. We don't fix broken code here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T11:20:13.890",
"Id": "455007",
"Score": "0",
"body": "@mickmackusa `$parameter` and `$hashed` are just link for page. and i have updated my question have a look at it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T12:14:51.787",
"Id": "455008",
"Score": "0",
"body": "@mickmackusa this is what i did there i get `id` and follewed this https://stackoverflow.com/a/12102882/3836908"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T16:45:20.663",
"Id": "455019",
"Score": "1",
"body": "Please do not update questions after they have been answered, especially please do not update code after the question has been answered. Please see https://codereview.stackexchange.com/help/someone-answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T16:47:53.833",
"Id": "455020",
"Score": "0",
"body": "@pacmaninbw it says `Do not change the code in the question` i have just added a`if` statement in question."
}
] |
[
{
"body": "<p>Applying YCS's tutorial can't be dumbed down any further, so I suppose I'll write it out.</p>\n\n<pre><code>if (isset($_POST[\"action\"])) {\n $query = \"SELECT link FROM allpostdata WHERE sts = '1'\";\n\n if (!empty($_POST[\"cate\"])) {\n $query .= \" AND sca IN (\" . str_repeat(\"?,\", count($_POST[\"cate\"]) - 1) . \"?)\";\n } else {\n $_POST[\"cate\"] = []; // in case it is not set \n }\n\n $stmt = $conn->prepare($query);\n $stmt->execute($_POST[\"cate\"]);\n $result = $stmt->fetchAll();\n if (!$result) {\n exit('<h3>No Data Found</h3>');\n }\n foreach ($result as $row) {\n echo \"<a href=\\\"/single_view.php?p={$row['link']}\\\">{$row['link']}</a>\";\n }\n}\n</code></pre>\n\n<p>I assume this will display your links side by side. You may want to style them a bit to position the links in a user friendly fashion.</p>\n\n<p>Additionally, <code>$('.filter_data');</code> is doing nothing and can be removed.</p>\n\n<p>I'd probably change the <code>filter_data()</code> declaration to something more brief:</p>\n\n<pre><code>function filter_data() {\n $.post(\n \"fetch.php\",\n {action: 'fetch_data', cate: get_filter('cate')}\n )\n .done(function(data) {\n $('.filter_data').html(data);\n });\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T16:49:40.540",
"Id": "455022",
"Score": "0",
"body": "a small change in question what if i have multiple `if` statement in `query`, and what about `SQL injection` there is no need of using `prepared statement`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T12:44:42.683",
"Id": "232892",
"ParentId": "232702",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T14:01:41.580",
"Id": "232702",
"Score": "1",
"Tags": [
"javascript",
"php",
"sql"
],
"Title": "Returning search results based off checkboxes"
}
|
232702
|
<p>I am studying socket.io and ended up making a connection using react as front end
js and how to back end node js</p>
<p>I was successful but I have a question as to how I made my code I don't know if it's "safe" or if I could improve on something</p>
<p>in my back end i have this on my app.js:</p>
<p>Here I call my router and pass my io / socket</p>
<pre><code>const express = require('express');
const bodyParser = require('body-parser');
const port = 8080;
const cors = require('cors');
require('./database/index')
const socketRouter = require('./routes/socket');
const usersRouter = require('./routes/userRoutes');
const postRouter = require('./routes/post');
const matchRouter = require('./routes/matchRoutes');
const app = express();
const router = express.Router();
const socket = require('socket.io');
const server = app.listen(
port,
console.log(`Server running in ${process.env.NODE_ENV} mode on port ${port}`)
);
let io = require('socket.io')(server);
app.set("io", io);
socketRouter.configuration(io,socket);
</code></pre>
<p>e em meu arquivo de router:</p>
<pre><code>const socketController = require ('../controllers/SocketController');
const verify = require('../auth/index');
module.exports = {
configuration: (io,socket) => {
io.on('connection', (socket) => {
socket.on('test', async (token,message) => {
const tokenVerify = await verify.authSocket(token);
if(tokenVerify){
console.log(message);
console.log(`Socket id: ${socket.id}`)
socket.emit('myevent', {message: 'OK'});
}
})
})
}
}
</code></pre>
<p>And on my router I get the socket and the io
I take my token / message that I send through my front end and do a verification</p>
<p>with this function :</p>
<pre><code>async authSocket(token){
if(!token) return res.status(401).json('Unauthorized');
try{
const decoded = jwt.verify(token,config.secretToken);
if(decoded){
return true;
}
}catch(error){
console.error(error);
}
}
</code></pre>
<p>in my front end i have this:</p>
<pre><code>verify = () => {
let socket = null;
socket = io.connect('http://localhost:8080/');
const message = {
nome: 'testando',
message: 'dasuidhjasu'
}
socket.emit('test',JSON.parse(sessionStorage.getItem('token')), message)
}
</code></pre>
<p>And as a result I get it</p>
<p><a href="https://i.stack.imgur.com/AcEZv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AcEZv.png" alt="enter image description here"></a></p>
<p>But as I said I don't know if my code is correct or if I could improve on something, I would be happy if they could help me</p>
<p>and I also have a question:</p>
<p>I wish this was my socket connection method (ie if my jwt is not valid, don't open a connection)</p>
<p>But if it is valid and I want to send new issues as I would so that no longer need to be authenticated</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T18:27:09.803",
"Id": "454542",
"Score": "0",
"body": "You say you don't know if your code is correct. Did you test the output? What did you want it to be? Regarding whether your code is safe or not, well, it's not doing much of anything at the moment. What attacks are you concerned about?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T18:44:08.493",
"Id": "454545",
"Score": "0",
"body": "I don't know very well, it's more to know if I had a good logic doing this or if I can improve, I wanted to authenticate my jwt when I use io.on ('connection', (socket) => {\n\nand not when I use the event test\nbut I am wondering how I will pass my token to the connection so I only need to authenticate once"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T18:46:29.100",
"Id": "454546",
"Score": "0",
"body": "Because this way I think I would have to do an authentication every event I have and not just when I connect"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T17:49:50.780",
"Id": "232712",
"Score": "2",
"Tags": [
"node.js",
"react.js",
"socket.io"
],
"Title": "socket.io / jwt"
}
|
232712
|
<p>I wanted to write a C function C99/POSIX compliant that read an integer from the user input. I wanted this function to be safe and robust but I feel it is way too complex for such simple task. </p>
<p>I am wondering whether this code is optimal.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
/**
* Read an integer from `stdin`.
* @param min Minimum accepted value
* @param max Maximum accepted value
* @param nom Default value
* @return captured integer
*/
int read_integer(char *text, int min, int max, int nom) {
int n = nom;
bool failure = false;
do {
printf("%s [%d] ? : ", text, nom);
// Read user input
char line[24];
do {
if (fgets(line, sizeof(line), stdin) != line || feof(stdin)) {
exit(EXIT_FAILURE);
break;
}
} while (strchr(line, '\n') == NULL);
// Default value?
{
char *cursor = line;
while ((*cursor == ' ' || *cursor == '\t') && *cursor != '\0') {
cursor++;
}
if (*cursor == '\n') {
return n;
}
}
// Not a number ?
if (sscanf(line, "%d", &n) != 1) {
printf("Error: this is not valid entry!\n\n");
continue;
}
// Not in the range ?
if (n < min || n > max) {
printf("Error: value should be between %d and %d!\n\n", min, max);
continue;
}
return n;
} while(true);
}
int main() {
do {
printf("You said %d\n",
read_integer("What's the answer", 10, 50, 42));
} while(!feof(stdin));
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T20:59:54.893",
"Id": "454557",
"Score": "1",
"body": "That code doesn't look to be working like intended."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T21:00:22.217",
"Id": "454558",
"Score": "0",
"body": "Could you be more explicit?"
}
] |
[
{
"body": "<p>regarding: </p>\n\n<pre><code>if (fgets(line, sizeof(line), stdin) != line || feof(stdin)) \n</code></pre>\n\n<p>This is unnecessary messy. Suggest: </p>\n\n<pre><code>if( fgets( line, sizeof( line ), stdin )\n</code></pre>\n\n<p>If any error occurs, the returned value is <code>NULL</code> so the body of the <code>if()</code> will not be entered.</p>\n\n<p>regarding:</p>\n\n<pre><code>if (fgets(line, sizeof(line), stdin) != line || feof(stdin)) {\n exit(EXIT_FAILURE);\n break;\n</code></pre>\n\n<p>the <code>break;</code> will never be executed because the call to <code>exit()</code> will have already exited the program.</p>\n\n<p>regarding:</p>\n\n<pre><code>while(!feof(stdin));\n</code></pre>\n\n<p>please read: <a href=\"https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong\">while(!feof()) is always wrong</a></p>\n\n<p>regarding:</p>\n\n<pre><code> return n;\n} while(true);\n</code></pre>\n\n<p>The <code>return</code> is always executed, so this loop will never iterate, looking for a valid input.</p>\n\n<p>regarding:</p>\n\n<pre><code>char *cursor = line;\n while ((*cursor == ' ' || *cursor == '\\t') && *cursor != '\\0') {\n cursor++;\n } \n if (*cursor == '\\n') {\n return n;\n }\n</code></pre>\n\n<p>This <code>while()</code> code block will iterate to the end of the array <code>line[]</code>, most of the time. the result will be no number will be extracted. Suggest, starting at <code>line[0]</code> to check for <code>isdigit( line[i] )</code> and if true, then extract the number, perhaps using something like: <code>strtol()</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T16:51:44.840",
"Id": "454654",
"Score": "0",
"body": "We generally prefer not to answer questions that contain code that is not working. I would suggested that you should have picked the part of the code that is not working and comment on that. `(return n; } while(true)`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T21:27:54.197",
"Id": "232716",
"ParentId": "232714",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T19:20:02.660",
"Id": "232714",
"Score": "4",
"Tags": [
"c"
],
"Title": "Properly read integer in a range in C"
}
|
232714
|
<p>I have written a solution to the blood-type matching problem, as described at <a href="https://projectlovelace.net/problems/blood-types/" rel="noreferrer">https://projectlovelace.net/problems/blood-types/</a>. The problem is to determine whether a given recipient (in this case, <code>argv[1]</code>) will find a match for a blood transfusion in an array of available donors (<code>argv + 2</code>).</p>
<ul>
<li><strong>Input blood type:</strong> <code>B+</code></li>
<li><strong>Input list of available blood types:</strong> <code>A- B+ AB+ O+ B+ B-</code></li>
<li><strong>Output:</strong> <code>match</code></li>
</ul>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <err.h>
typedef struct {
enum { O, A, B, AB } abo;
enum { P, M } rh;
} Blood;
const int abo[4][4] = {
{ O, O, O, O }, // O
{ O, A, O, A }, // A // *
{ O, B, O, B }, // B // *
{ O, A, B, AB }, // AB
};
const int rh[2][2] = {
{ P, M }, // P
{ M, M }, // M // *
};
Blood
parse(char *s){
char rh0 = s[strlen(s)-1];
char *abo0 = strdup(s);
abo0[strlen(s)-1] = '\0';
Blood b = {
!strncmp(abo0, "O", 1) ? O
: !strncmp(abo0, "A", 1) ? A
: !strncmp(abo0, "B", 1) ? B
: !strncmp(abo0, "AB", 2) ? AB
: -1,
rh0 == '+' ? P
: rh0 == '-' ? M
: -1,
};
return b;
}
int
main(int argc, char *argv[]) {
if(argc < 3)
err(1, "no arguments given\n");
int n = argc - 2;
char *a0 = argv[1];
char **as = argv + 2;
Blood b0 = parse(a0);
Blood *bs = malloc(sizeof(Blood) * n);
for(int i = 0; i < n; i++)
bs[i] = parse(as[i]);
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 2; j++) {
for(int k = 0; k < n; k++) {
if(abo[b0.abo][i] == bs[k].abo && rh[b0.rh][j] == bs[k].rh) {
printf("match\n");
return 0;
}
}
}
}
printf("no match\n");
return 1;
}
</code></pre>
<p>which works correctly in my tests, but uses some hacks. Specifically, lines marked with <code>// *</code> have repeated values of enums, since I couldn't find a way to make loop sizes conditional on blood types.</p>
<p>What would be a better way, without forcing the blood type enums to be the same size? And more generally, is there a simpler version of the blood-type matching algorithm?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T00:21:56.557",
"Id": "454568",
"Score": "3",
"body": "Bug: if s has len 0, your parse function invokes undefined behavior."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T13:06:29.817",
"Id": "454745",
"Score": "1",
"body": "@D.BenKnoble A bug is when a program behaves badly on a valid input. As far as I can see it is not stated anywhere that an empty string given as a parameter is a _valid_ input for the program. You might as well complain that the `malloc` may fail if `argc` is too large. I wouldn't expect an excersise program to be nuke-proof. IMHO this is at most a potential weaknes (if the `parse()` routine is ever used outside tis application), not a _bug_... :) There are more serious problems with the code than proper handling an improper input!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T13:27:11.750",
"Id": "454749",
"Score": "5",
"body": "@CiaPan I mostly agree in theory—but not paying attention to these kinds of bugs (yes, bug: the type and docs impose no limitations on the length, so its not stated not to be a valid input; worse, it could very well become an issue)—not paying attention to these kinds of bugs is a dangerous hubris that assumes « proper » input (which is a bad idea) and assumes the access will fail a particular way (eg, segfault). Bad idea. If one writes it here, lets learn not to before we get to larger systems!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T18:16:06.520",
"Id": "454828",
"Score": "0",
"body": "You said the code 'works correctly' in you tests. Can you, please, show them? I suspect your program would not pass some. Did you test, for example, a recipient with blood type A+ and an AB+ donor?"
}
] |
[
{
"body": "<p>Each blood factor can be present or not present. The blood types can be bit-encoded using one bit for the <code>A</code> factor, one bit for the <code>B</code> factor, and one bit for the <code>Rh</code> factor.</p>\n<pre><code>enum { A=1, B=2, Rh=4 };\n</code></pre>\n<p>You would parse the blood type <code>"AB+"</code> as <code>A + B + Rh == 7</code>, and <code>"O-"</code> as <code>0</code> because it does not contain any <code>A</code> factor, <code>B</code> factor, or <code>Rh</code> factor.</p>\n<p>Survival requires the donor's blood not contain any factors missing in the recipient's blood type. Complement the recipient's blood type to get the bad factors, and use a bit-wise <code>and</code> operation to test that all of the factors are not present in the donor's blood.</p>\n<pre><code>bool donor_matches = (donor & ~recipient) == 0;\n</code></pre>\n<hr />\n<p>If you want to leave you enum's as encoding the 4 blood types, and the Rh factor separately, you can get to a similar coding.</p>\n<p>Note that:</p>\n<pre><code>enum { O, A, B, AB } abo;\n</code></pre>\n<p>will define <code>O=0, A=1, B=2, AB=3</code>, so you have a similar bit assignment as above. The <code>Rh</code> factor on the other hand would be better to reverse the order:</p>\n<pre><code>enum { M, P } rh;\n</code></pre>\n<p>so that <code>M=0, P=1</code>. Now you could express the match condition:</p>\n<pre><code>bool donor_match = (donor_abo & ~recipient_abo) == 0 && (donor_rh & ~recipient_rh) == 0;\n</code></pre>\n<hr />\n<p>Finally, if you want to leave the <code>rh</code> enum as you have originally defined it:</p>\n<pre><code>enum { P, M } rh;\n</code></pre>\n<p>then note that <code>donor_rh >= recipient_rh</code> would express that the rh factors match, or the donor has a less-restrictive (numerically higher) rh factor.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T21:56:04.230",
"Id": "454691",
"Score": "6",
"body": "I suggest to write `0b001`, `0b010`, `0b100` for the bit encoding instead of decimal numbers in `enum { A=1, B=2, Rh=4 };`. This would express your idea in the code better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T22:45:53.177",
"Id": "454696",
"Score": "2",
"body": "@JonasStein I like the idea, but as of [C11](https://en.cppreference.com/w/c/language/integer_constant), it looks like only decimal, hexadecimal and octal constants are standard."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T23:51:26.970",
"Id": "454701",
"Score": "0",
"body": "You may also consider a bitfield struct instead of enum."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T08:29:15.713",
"Id": "454720",
"Score": "0",
"body": "@AJNeufeld Interesting. I was not aware, that it is not standard C11 (see also https://stackoverflow.com/questions/9014958/how-do-i-use-a-binary-prefix-in-accordance-with-c11). Can you use binary constants? http://gcc.gnu.org/onlinedocs/gcc/Binary-constants.html Or define own constant `my0b100` and fix it in future."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T15:56:15.387",
"Id": "454783",
"Score": "3",
"body": "Not as elegant as @JonasStein's suggestion, but you could use bit-shifting: `enum { A = 1 << 0, B = 1 << 1, C = 1 << 2 }`, though it might be overkill for such a small enum (I've used this before when dealing with a large bitfield to ensure I didn't make a silly mistake defining my constants by hand)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T15:58:59.550",
"Id": "454786",
"Score": "3",
"body": "@Wasabi Perhaps not as elegant, but standard compliant. I approve (except for that weird `C` blood type)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-27T21:58:14.893",
"Id": "455478",
"Score": "1",
"body": "Brilliant example of how domain knowledge can help with elegant implementation. You knew what the underlying logic was. OP (and me) probably thought the pairings were random."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T23:40:19.500",
"Id": "232719",
"ParentId": "232715",
"Score": "56"
}
},
{
"body": "<p>Your code is way too complicated. If any of <code>A</code>, <code>B</code>, or <code>+</code> is present in the donor, it must also be present in the recipient. That's all you need.</p>\n\n<pre><code>bool is_compatible(const char* donor, const char* recipient)\n{\n if(strstr(donor, \"A\") != NULL && strstr(recipient, \"A\") == NULL)\n return false;\n if(strstr(donor, \"B\") != NULL && strstr(recipient, \"B\") == NULL)\n return false;\n if(strstr(donor, \"+\") != NULL && strstr(recipient, \"+\") == NULL)\n return false;\n return true;\n}\n\nint main(int argc, char *argv[])\n{\n for (int i = 2; i < argc; i++)\n {\n if (is_compatible(argv[i], argv[1]))\n {\n printf(\"match: %s\\n\", argv[i]);\n return 0;\n }\n }\n printf(\"no match\\n\");\n return 1;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T23:54:07.393",
"Id": "454702",
"Score": "9",
"body": "A model for blood type, even as simple as enumeration, I think, is required. Because blood models do change, and there are alternate representations. While this is certainly smaller and simpler, it hard codes blood typing logic into the source code and not into the data (of valid blood types). This is not necessarily the best approach for software intended for medical use, of course this is just an exercise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T16:21:55.173",
"Id": "455283",
"Score": "1",
"body": "@crasic, the test function could follow your suggestion *and* be shorter, with a simple loop on `if (strstr(donor,types[index]) && !strstr(recipient,types[index])) return false;`, with `types=\"AB+\"`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T00:13:25.713",
"Id": "232720",
"ParentId": "232715",
"Score": "28"
}
},
{
"body": "<p>Forget about what they asked for, and think about what it really means.</p>\n\n<p>Having a match means that at least one of the donor strings contains no characters that aren't in the recipient string, except for possibly the placeholders \"O\" and \"-\".</p>\n\n<p>So check for that:</p>\n\n<pre><code>#include <malloc.h>\n#include <stdio.h>\n#include <string.h>\n\n int\nmain(int argc, char **argv) {\n if (argc>2) {\n auto int index;\n auto char **donor;\n auto char *donee = strcat(strcpy(malloc(3+strlen(argv[1])), argv[1]), \"-O\");\n for (donor=&argv[2]; *donor; ++donor) {\n for (index=0; index[*donor]; ++index)\n if (!strchr(donee, index[*donor])) break;\n if (!index[*donor]) return puts(\"Match\"), 0;\n }\n }\n return puts(\"No match\\n\"), 1;\n}\n</code></pre>\n\n<p>The unnecessary placeholders, \"O\" and \"-\", should have been stripped from the donor strings, but in this case it was easier to add them to the recipient string.</p>\n\n<p>Note that except for that special case, this code has nothing specific to human blood types. The same program will work for Vulcans too (Spok is \"T-\").</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T21:41:19.007",
"Id": "233022",
"ParentId": "232715",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T21:07:49.090",
"Id": "232715",
"Score": "33",
"Tags": [
"c"
],
"Title": "Match blood types in C"
}
|
232715
|
<p>I'm trying to create a separate package in a monorepo to handle <code>TypeORM</code> functions. So if I have two APIs (User API, Admin API), both can refer to the same package to talk to the database. I have written a class which takes all the TypeORM entities, create a connection and export them. Please let me know whether I can further refactor this:</p>
<pre><code>import { createConnection, Connection, Repository, getConnectionOptions } from 'typeorm';
import { User } from './entity/User';
class Store {
private dbConnection: Connection | undefined;
private userRepository: Repository<User> | undefined;
/**
* Create a new DB connection and set repositories
*/
createDBConnection = async (): Promise<void> => {
const connectionOptions = await getConnectionOptions();
this.dbConnection = await createConnection({
...connectionOptions,
entities: [User],
});
this.userRepository = await this.dbConnection.getRepository(User);
};
/**
* Throw an error if the repository is not available
*/
private connectionNotCreatedError = (): never => {
throw new Error('Repository not available. Please check whether you created the connection first.');
};
/**
* Get the user repository
*/
getUserRepository = (): Repository<User> => {
return this.userRepository || this.connectionNotCreatedError();
};
}
export const store = new Store();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T06:47:09.560",
"Id": "454575",
"Score": "0",
"body": "IMHO, it makes no sense. You should obtain the repository asynchronously."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T08:22:46.307",
"Id": "454577",
"Score": "0",
"body": "@slepic Didn't get you. I created this part will be replicated in both the repos. Trying to take it into one place."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T08:46:19.347",
"Id": "454578",
"Score": "1",
"body": "I mean why not just have `async getUserRepository(): Promise<Repository<User>>`? You can even implement it in a way that it is only loaded once and on consecutive calls, the already fulfilled promise is returned."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T09:13:52.703",
"Id": "454579",
"Score": "0",
"body": "@slepic Awesome so that means it remembers the result and won't call the function all the time? Do we have to implement it in a special way for that to work?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T13:57:25.240",
"Id": "455259",
"Score": "0",
"body": "Ah sry, I missed that. I'm not really working with typescript daily, so I'm not sure how to do it from scratch. But I'm pretty sure it is possible..."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T01:48:34.023",
"Id": "232722",
"Score": "3",
"Tags": [
"typescript"
],
"Title": "Create one class to perform all type orm functionalities"
}
|
232722
|
<p>database relations can be found here <a href="http://www.tpc.org/tpc_documents_current_versions/pdf/tpc-h_v2.18.0.pdf" rel="nofollow noreferrer">http://www.tpc.org/tpc_documents_current_versions/pdf/tpc-h_v2.18.0.pdf</a></p>
<pre><code>SELECT l_orderkey, sum(l_extendedpriced * (1 - l_discount)) as revenue, o_orderdate, o_shippriority
FROM customer, orders, lineitem
WHERE c_mktsegment = 'BUILDING' -- '[SEGMENT]'
and c_custkey = o_custkey
and l_orderkey = o_orderkey
and o_orderdate < "1995-03-15" -- '[DATE]'
and l_shipdate > "1995-03-15" -- '[DATE]'
GROUP BY l_orderkey, o_orderdate, o_shippriority
ORDER BY revenue desc, o_orderdate;
</code></pre>
<p>I was planning on optimizing this query by using joins like so </p>
<pre><code>SELECT l_orderkey, sum(l_extendedpriced * (1 - l_discount)) as revenue, o_orderdate, o_shippriority
FROM customer
JOIN orders ON c_custkey = o_custkey
JOIN lineitem ON o_orderkey = l_orderkey
WHERE c_mktsegment = 'BUILDING' --'[SEGMENT]'
AND o_orderdate < "1995-03-15" -- '[DATE]'
AND l_shipdate > "1995-03-15" -- '[DATE]'
GROUP BY l_orderkey, o_orderdate, o_shippriority
ORDER BY revenue desc, o_orderdate;
</code></pre>
<p>Now all I have to do is create indexes for the tables. For this problem, a maximum of 3 indexes per table can be created with its primary key being 1 of them.</p>
<p>The indexes that I came up with are (these are the columns used in the GROUP BY and ORDER BY clauses)</p>
<pre><code>CREATE INDEX idx_l_orderkey ON lineitem(l_orderkey);
CREATE INDEX idx_o_orderdate_shippriority ON orders(o_orderdate, o_shippriority);
</code></pre>
<p>Are there any more indexes that I can put in to further optimize this query? I feel like I need to make another index for the customer table for the c_mktsegment. Also, if there's any other strategies that I forgot, could you please enlighten me. Thank you.</p>
|
[] |
[
{
"body": "<p>You can ask SQL Server to recommend the indexes that might improve performance of your query by selecting the query and clicking on this <strong>Display Estimated Execution Plan</strong> button on the taskbar (or simply <strong>Ctrl+L</strong>):</p>\n\n<p><a href=\"https://i.stack.imgur.com/U859f.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/U859f.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>This will analyze the query and it will show you the query cost of the operations required to retrieve the data, and eventually propose which indexes might be useful.</p>\n\n<p>Btw, using the joins (as on your 2nd example) should be more efficient indeed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T16:37:16.683",
"Id": "232751",
"ParentId": "232725",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T05:43:37.363",
"Id": "232725",
"Score": "1",
"Tags": [
"performance",
"sql",
"indexeddb"
],
"Title": "query optimization and indexing"
}
|
232725
|
<p>I'm building a simple Django app for reviews of different objects (restaurants, car services, car wash etc).</p>
<p>I started with the app, but soon I faced first problem. Every object has features (but every type of object has different features).</p>
<p>For example:</p>
<p>Restaurants have garden, playground, seats, type of kitchen, etc.
car washes have external cleaning, internal cleaning etc.
So I started to build a typical DB implementation with ManyToMany tables, but then I found Django Model Inheritance, so I implement it in my APP. After that I faced other problem, about getting all objects from some category (only restaurants, only car services etc..). So I changed model logic from Django Model Inheritance to PolymorphicModel, the core of the object is almost ready, but I have some doubts, I will post the code, then few words about my doubts:</p>
<p><strong>models.py:</strong></p>
<pre><code>from django.db import models
from users.models import ProfileUser
from django.utils import timezone
from polymorphic.models import PolymorphicModel
# Create your models here.
class City(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return f"{self.name}"
class Object(PolymorphicModel):
author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE, db_column='author')
title = models.CharField(max_length=300)
city = models.ForeignKey(City, on_delete=models.CASCADE)
address = models.CharField(max_length=300)
phone = models.CharField(max_length=20, default='')
email = models.CharField(max_length=100, default='')
site = models.CharField(max_length=100, default='')
facebook = models.CharField(max_length=100, default='')
instagram = models.CharField(max_length=100, default='')
content = models.TextField()
rating = models.IntegerField(default=10)
created_date = models.DateTimeField(default=timezone.now)
approved_object = models.BooleanField(default=False)
admin_seen = models.BooleanField(default=False)
def __str__(self):
return f"{self.title}"
class Restaurant(Object):
seats = models.IntegerField()
bulgarian_kitchen = models.BooleanField(default=False)
italian_kitchen = models.BooleanField(default=False)
french_kitchen = models.BooleanField(default=False)
category_en_name = models.CharField(max_length=100, default='restaurants')
category_bg_name = models.CharField(max_length=100, default='Ресторанти')
bg_name = models.CharField(max_length=100, default='Ресторант')
is_garden = models.BooleanField(default=False)
is_playground = models.BooleanField(default=False)
class SportFitness(Object):
is_fitness_trainer = models.BooleanField(default=False)
category_en_name = models.CharField(max_length=100, default='sportfitness')
category_bg_name = models.CharField(max_length=100, default='Спорт и фитнес')
bg_name = models.CharField(max_length=100, default='Спорт и фитнес')
class CarService(Object):
is_parts_clients = models.BooleanField(default=False)
category_en_name = models.CharField(max_length=100, default='carservice')
category_bg_name = models.CharField(max_length=100, default='Автосервизи')
bg_name = models.CharField(max_length=100, default='Автосервиз')
class BeautySalon(Object):
is_hair_salon = models.BooleanField(default=False)
is_laser_epilation = models.BooleanField(default=False)
category_en_name = models.CharField(max_length=100, default='beautysalon')
category_bg_name = models.CharField(max_length=100, default='Салони за красота')
bg_name = models.CharField(max_length=100, default='Салон за красота')
class FastFood(Object):
is_pizza = models.BooleanField(default=False)
is_duner = models.BooleanField(default=False)
is_seats = models.BooleanField(default=False)
category_en_name = models.CharField(max_length=100, default='fastfood')
category_bg_name = models.CharField(max_length=100, default='Бързо хранене')
bg_name = models.CharField(max_length=100, default='Бързо хранене')
</code></pre>
<p><strong>urls.py:</strong></p>
<pre><code>from django.urls import path
from . import views
urlpatterns = [
path('user/<int:pk>/', views.UserObjectsView.as_view(), name='user-objects'),
path('add/<str:category>/', views.add_object, name='add-object'),
path('<str:category>/<int:pk>/<int:page_num>/', views.show_object, name='show-object'),
path('all/<str:category>/', views.show_all_objects, name="show-all-objects"),
]
</code></pre>
<p><strong>views.py:</strong></p>
<pre><code>from django.shortcuts import render, redirect
from django.views import generic
from objects.models import Object, ProfileUser, Comment, Restaurant, SportFitness, CarService, BeautySalon, FastFood, CarWash, Fun, Other
from .forms import RestaurantForm, SportFitnessForm, BeautySalonForm, CarServiceForm, CarWashForm, FastFoodForm, FunForm, OtherForm, CommentForm, UploadForm
from django.contrib import messages
from django.db.models import Avg
from django.apps import apps
from django.core.paginator import Paginator
from django.http import JsonResponse
class AllObjects(generic.ListView):
queryset = Object.objects.all()
template_name = 'show_all_objects.html'
class UserObjectsView(generic.ListView):
template_name = 'user_objects.html'
def get_queryset(self):
user_id = self.kwargs['pk']
return Object.objects.filter(author = user_id)
def add_object(request, category):
if not request.user.is_authenticated:
messages.info(request, 'За да добавите нов Обект, трябва да сте регистриран потребител!')
return redirect('account_login')
if category == 'restaurants':
form = RestaurantForm(request.POST or None)
elif category == 'sportfitness':
form = SportFitnessForm(request.POST or None)
elif category == 'carservice':
form = CarServiceForm(request.POST or None)
elif category == 'beautysalon':
form = BeautySalonForm(request.POST or None)
elif category == 'fastfood':
form = FastFoodForm(request.POST or None)
elif category == 'carwash':
form = CarWashForm(request.POST or None)
elif category == 'fun':
form = FunForm(request.POST or None)
elif category == 'other':
form = OtherForm(request.POST or None)
upload_form = UploadForm(request.POST or None)
if form.is_valid():
obj = form.save(commit=False)
obj.author = ProfileUser.objects.get(user=request.user)
obj.save()
messages.success(request, 'Успешно добавихте нов Обект, може да видите вашите обекти във вашия профил!')
return redirect('home')
context = {
'form': form,
'upload_form': upload_form
}
return render(request, "add_object.html", context)
def show_object(request, category, pk, page_num):
categories = {'restaurants' : 'Restaurant', 'sportfitness' : 'SportFitness', 'carservice' : 'CarService', 'beautysalon' : 'BeautySalon', 'fastfood' : 'FastFood', 'carwash' : 'CarWash', 'fun' : 'Fun', 'other' : 'Other'}
obj = apps.get_model('objects', categories[category]).objects.get(id=pk)
if request.method == 'POST':
data = {'error': False, 'error_message': ''}
user = request.user
author = ProfileUser.objects.get(user=user)
comment = Comment()
object = Object.objects.get(id=pk)
comment.object = obj
comment.author = author
comment.content = request.POST.get('content')
comment.rating = request.POST.get('rating')
rating = Comment.objects.filter(object_id=pk).aggregate(Avg('rating'))['rating__avg']
object.rating = rating
data['rating'] = rating
comment.save()
object.save()
return JsonResponse(data)
form = CommentForm()
reviews_count = Comment.objects.filter(object_id=pk).count()
rating = Comment.objects.filter(object_id=pk).aggregate(Avg('rating'))['rating__avg']
comments_list = Comment.objects.all()
paginator = Paginator(comments_list, 2)
comments = paginator.get_page(page_num)
context = {
'form': form,
'object': obj,
'reviews_count': reviews_count,
'rating': rating,
'category': category,
'comments': comments,
'page_num': page_num,
}
return render(request, "show_object.html", context)
def show_all_objects(request, category):
categories = {'restaurants' : 'Restaurant', 'sportfitness' : 'SportFitness', 'carservice' : 'CarService', 'beautysalon' : 'BeautySalon', 'fastfood' : 'FastFood', 'carwash' : 'CarWash', 'fun' : 'Fun', 'other' : 'Other'}
if category == 'restaurants':
objects = Object.objects.instance_of(Restaurant)
elif category == 'sportfitness':
objects = Object.objects.instance_of(SportFitness)
elif category == 'carservice':
objects = Object.objects.instance_of(CarService)
elif category == 'beautysalon':
objects = Object.objects.instance_of(BeautySalon)
elif category == 'fastfood':
objects = Object.objects.instance_of(FastFood)
elif category == 'carwash':
objects = Object.objects.instance_of(CarWash)
elif category == 'fun':
objects = Object.objects.instance_of(Fun)
elif category == 'other':
objects = Object.objects.instance_of(Other)
context = {
'object_list': objects,
'category': category,
}
return render(request, 'show_all_objects.html', context)
</code></pre>
<p><strong>Template, where List all category and client can choose a category:</strong></p>
<pre><code><div class="container_categories_box margin-top-5 margin-bottom-30">
<a href="{% url 'show-all-objects' category='restaurants' %}" class="utf_category_small_box_part"> <i class="im im-icon-Chef"></i>
<h4>Ресторантии</h4>
<span>22</span>
</a>
<a href="{% url 'show-all-objects' category='sportfitness' %}" class="utf_category_small_box_part"> <i class="im im-icon-Dumbbell"></i>
<h4>Спортни и фитнес</h4>
<span>15</span>
</a>
<a href="{% url 'show-all-objects' category='carservice' %}" class="utf_category_small_box_part"> <i class="im im-icon-Car-Wheel"></i>
<h4>Автосервизи</h4>
<span>05</span>
</a>
<a href="{% url 'show-all-objects' category='beautysalon' %}" class="utf_category_small_box_part"> <i class="im im-icon-Gemini-2"></i>
<h4>Салони за красота</h4>
<span>12</span>
</a>
<a href="{% url 'show-all-objects' category='fastfood' %}" class="utf_category_small_box_part"> <i class="im im-icon-Hamburger"></i>
<h4>Бързо хранене</h4>
<span>08</span>
</a>
</div>
</code></pre>
<p>Okay, this is the most important part from the code, My doubts are:</p>
<ol>
<li><p>Templates: category this is hardcoded: </p>
<ul>
<li><code>{% url 'show-all-objects' category='restaurants' %}</code> - restaurants</li>
<li><code>{% url 'show-all-objects' category='sportfitness' %}</code> - sportfitness (etc..)</li>
</ul></li>
<li><p>These if else in <strong>views.py</strong>:</p>
<p><code>if category == 'restaurants':
form = RestaurantForm(request.POST or None)
elif category == 'sportfitness':
form = SportFitnessForm(request.POST or None)
elif category == 'carservice':
form = CarServiceForm(request.POST or None)
elif category == 'beautysalon':
form = BeautySalonForm(request.POST or None)
elif category == 'fastfood':
form = FastFoodForm(request.POST or None)
elif category == 'carwash':
form = CarWashForm(request.POST or None)
elif category == 'fun':
form = FunForm(request.POST or None)
elif category == 'other':
form = OtherForm(request.POST or None)</code></p></li>
</ol>
<p><strong>and this one:</strong></p>
<pre><code>if category == 'restaurants':
objects = Object.objects.instance_of(Restaurant)
elif category == 'sportfitness':
objects = Object.objects.instance_of(SportFitness)
elif category == 'carservice':
objects = Object.objects.instance_of(CarService)
elif category == 'beautysalon':
objects = Object.objects.instance_of(BeautySalon)
elif category == 'fastfood':
objects = Object.objects.instance_of(FastFood)
elif category == 'carwash':
objects = Object.objects.instance_of(CarWash)
elif category == 'fun':
objects = Object.objects.instance_of(Fun)
elif category == 'other':
objects = Object.objects.instance_of(Other)
</code></pre>
<p>Generally I'm not quite sure, that this is the "right way" to implement this app. I'm open to any questions.</p>
|
[] |
[
{
"body": "<p>Please, for the love of goodness, don't create your own superclass named <code>Object</code>, be more specific. The lower-case <code>object</code> is already a defined type and this is just confusing.</p>\n\n<p>The multi-language name and category approach isn't scalable. I needed a similar solution recently, and what I tried was something like the following:</p>\n\n<pre><code>class Language(models.Model):\n name = models.CharField(max_length=2) # Create one \"en\" instance and one \"bg\" instance\n\nclass Text(models.Model):\n text = models.TextField()\n language = models.ForeignKey('Language', on_delete=models.CASCADE)\n\nclass Category(models.Model):\n names = models.ManyToManyField('Text')\n\n def name(self, language='en'):\n try:\n return self.names.get(language=language).text\n except Text.DoesNotExist:\n return self.names.get(language__name='en').text # or whatever your default language is\n</code></pre>\n\n<p>You can then keep a language for each user, and when you want to look up the name, just do <code>category.name(request.user.language)</code>. You can thus easily add new languages and tweak translations in the future just by altering the database.</p>\n\n<p>Anyway, back to reviewing your actual code. Since all your tags are simple boolean fields, it would have been much cleaner to keep these categories in their own table, create a many-to-many mapping, and simply do existence checks into your database. To make the types of businesses easily editable and addable, you could create a type system in your database itself, creating a kind of \"virtual\" inheritance system.</p>\n\n<pre><code>class Business(models.Model):\n name = models.ManyToManyField('Text')\n author = ...\n ...\n kind = models.ForeignKey('BusinessType', null=True, on_delete=models.SET_NULL)\n tags = models.ManyToManyField('Tag')\n\nclass BusinessType(models.Model):\n name = models.CharField(max_length=100) # e.g., 'Restaurant' or 'Sport Fitness'\n possible_tags = models.ManyToManyField('Tag')\n\nclass Tag(models.Model):\n base_name = models.CharField(max_length=100) # e.g. 'bulgarian_kitchen'\n description = models.ManyToManyField('Text')\n</code></pre>\n\n<p>You still have access to all the same information, but it's all configurable through the database rather than through your code. E.g., to get a restaurant and check if it has an Italian kitchen,</p>\n\n<pre><code>restaurant = Business.objects.get(name__language='en', name__text='YumBob', kind__name='Restaurant')\nhas_italian_kitchen = restaurant.tags.filter(base_name='italian_kitchen').exists()\n</code></pre>\n\n<p>or to find all beauty salons that offer laser epilation,</p>\n\n<pre><code>epilators = Business.objects.filter(kind__name='Beauty Salon', tags__name='laser_epilation')\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/5478432/making-a-django-form-class-with-a-dynamic-number-of-fields\">You can also</a> <a href=\"https://jacobian.org/2010/feb/28/dynamic-form-generation/\" rel=\"nofollow noreferrer\">dynamically create forms</a>, etc. for each business type by instantiating a base Form and then adding boolean fields to it for each tag in <code>my_business.kind.possible_tags</code>. And, of course, you could create sidecar tables for particular business types to store additional, non-boolean fields. E.g.,</p>\n\n<pre><code>class RestaurantExtraData(models.Model):\n business = models.OneToOneField('Business', primary_key=True, on_delete=models.CASCADE)\n num_seats = models.IntegerField()\n</code></pre>\n\n<p>This way, you minimize the amount of special code required for different businesses, but retain the ability to add extra information where necessary. All of this together avoids your need for the stacked if/else statements and the large quantities of hard-coded strings in your views and templates, and allows you to configure everything using data rather than code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T14:51:27.230",
"Id": "454629",
"Score": "0",
"body": "I will rename it :) \"Since all your tags are simple boolean fields, it would have been much cleaner to keep these categories in their own table\" well seats are not boolean field, probably in near future there will be and others non boolean fields features."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T14:57:35.770",
"Id": "454632",
"Score": "1",
"body": "@MorganFreeFarm hence my last suggestion about using one-to-one relationship tables to tag information onto specific rows in the main table, rather than fragmenting the data across a bunch of very similar tables. You could, in theory, hide some of this fragmentation, say by creating a dictionary of models so you can use a string key to get the appropriate model, but the more you can centralize your logic and apply the [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) principle, the more busy-work and hassle you can save yourself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T15:02:53.137",
"Id": "454634",
"Score": "0",
"body": "I see. Based on your opinion, current solution doesn't look so bad at all :D"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T14:40:21.850",
"Id": "232744",
"ParentId": "232727",
"Score": "2"
}
},
{
"body": "<p>I found a pythonic way to use dictonary, instead of if else:</p>\n\n<pre><code>params_map = {\n 'restaurants': Restaurant,\n 'sportfitness': SportFitness,\n 'carservice': CarService,\n 'beautysalon': BeautySalon,\n 'fastfood': FastFood,\n 'carwash': CarWash,\n 'fun': Fun,\n 'other': Other,\n}\n\nobjects = Object.objects.instance_of(params_map.get(category))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T12:14:24.963",
"Id": "232940",
"ParentId": "232727",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "232744",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T08:28:52.533",
"Id": "232727",
"Score": "1",
"Tags": [
"python",
"django"
],
"Title": "Django: App based at PolymorphicModel"
}
|
232727
|
<p>I'm reasonably new to <code>D3</code>, and I've put together a class based <code>React</code> component which outputs a genomic alignment visually. The result looks like this:</p>
<p><a href="https://i.stack.imgur.com/hyQOZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hyQOZ.png" alt="enter image description here"></a></p>
<p>The component is as follows: </p>
<pre><code>import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import * as d3 from 'd3';
const StyledSVG = styled.svg`
rect {
fill: steelblue;
shape-rendering: crispEdges;
}
text {
fill: black;
font: 10px sans-serif;
text-anchor: middle;
font-weight: bold;
}
.start, .note {
text-anchor: start;
}
`
let height = 150;
let width = 700;
const maxDepthVal = 35;
class Alignment extends React.Component{
constructor(props){
super(props);
if(props.height){
height = props.height;
}
if(props.width){
width = props.width;
}
}
findMax = (data, key) => {
return Math.max.apply(Math, data.map(o => o[key]))
}
renderAlignmentComponent = (arr, y, ref, barWidth, leftPadding) => {
d3.select(ref).selectAll('text')
.data(arr, d => d.key)
.join(
enter => enter.append('text')
.attr('transform', (d, i) => `translate(${leftPadding + (i * (barWidth)) }, 0)`)
.attr('x', (d, i) => barWidth/2)
.attr('y', y)
.text(d => d.base),
update => update
.attr('transform', (d, i) => `translate(${leftPadding + i * barWidth}, 0)`)
.attr('x', (d, i) => barWidth/2)
)
}
renderMarker = (data, ref, y ) => {
d3.select(ref).selectAll('text').data(data)
.join('text')
.attr('x', 10)
.attr('y', y)
.attr('class', 'start')
.attr('dy', '.75em')
.text(d => d)
}
renderLabel = (data, ref, y) => {
d3.select(ref)
.selectAll('text')
.data(data)
.join(
enter => enter.append('text')
.attr('x', 10)
.attr('y', y)
.attr('class', 'note')
.attr('dy', '.75em')
.text(d => d),
update => update,
exit => exit.remove()
)
}
componentDidUpdate = () => {
const { reference, alignment, depth, start } = this.props;
const leftPadding = 40 + start.toString().length * 4.5;
const topPadding = reference.length > 0 ? 38 : 0;
const barWidth = (width - leftPadding) / depth.length;
let i;
const chart = d3.select(this.refs.chart)
.attr('width', width)
.attr('height', height + topPadding + 5)
const unencodedDepths = []
const alArr = [];
const refArr = [];
const seps = [];
let max = 0;
for(i = 0; i < depth.length; i+=1){
const key = i + start;
if(reference.length > 0){
alArr.push({
base: alignment[i],
key
})
refArr.push({
base: reference[i],
key
})
seps.push({
base: reference[i] === alignment[i] ? '|' : '',
key
});
}
let depthVal;
if(depth[i].match(/[a-z]/i)){
depthVal = depth[i].charCodeAt(0) - 87; //so that a = 10
}else{
depthVal = +depth[i];
}
max = max > depthVal ? max : depthVal;
unencodedDepths.push({
depth: depthVal,
key
});
}
const y = d3.scaleLinear()
.range([height, 0])
.domain([0, max]);
//start pos marker
this.renderMarker([start], this.refs.startPos, topPadding + 7);
this.renderMarker([max], this.refs.height, height + topPadding - 10);
if(reference.length > 0){
this.renderAlignmentComponent(refArr, 10, this.refs.reference, barWidth, leftPadding);
this.renderAlignmentComponent(alArr, 38, this.refs.alignEl, barWidth, leftPadding);
this.renderAlignmentComponent(seps, 23, this.refs.sepEl, barWidth, leftPadding);
}
//histogram
d3.select(this.refs.hist).selectAll('rect')
.attr('height', height)
.data(unencodedDepths, d => d.key)
.join(
enter => enter.append('rect')
.attr('transform', (d, i) => `translate(${leftPadding + (i * barWidth) - barWidth/2}, 0)`)
.attr('y', topPadding + 5)
.attr('x', barWidth/2)
.attr('height', d => height - y(d.depth))
.attr('width', barWidth),
update => update
.attr('transform', (d, i) => `translate(${leftPadding + (i * barWidth) - barWidth/2}, 0)`)
.attr('height', d => height - y(d.depth))
.attr('x', (d, i) => barWidth/2)
)
this.renderLabel(reference.length > 0 ? ['Sbject'] : '', this.refs.refNote, 2);
this.renderLabel(reference.length > 0 ? ['Query'] : '', this.refs.alNote, 30);
}
componentDidMount = () => {
this.componentDidUpdate();
}
render(){
return (
<StyledSVG ref="chart">
<StyledSVG ref="refNote" />
<StyledSVG ref="alNote" />
<StyledSVG ref="startPos" />
<StyledSVG ref="height" />
<StyledSVG ref="reference" />
<StyledSVG ref="sepEl" />
<StyledSVG ref="alignEl" />
<StyledSVG ref="hist" />
</StyledSVG >
)
}
}
Alignment.propTypes = {
reference: PropTypes.string.isRequired,
alignment: PropTypes.string.isRequired,
start: PropTypes.number.isRequired,
depth: PropTypes.string.isRequired
}
export default Alignment;
</code></pre>
<p>The code works well, and re-renders correctly when I change the props to show the next bit of the alignment. </p>
<p>To me, however, it seems excessive with the d3 select calls - but i'm not sure if there's a better way here. </p>
<p>Any suggestions are appreciated! </p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T08:29:48.693",
"Id": "232728",
"Score": "3",
"Tags": [
"javascript",
"react.js",
"d3.js"
],
"Title": "React and D3 Alignment Histogram"
}
|
232728
|
<p>I have the following code which works perfectly fine. I am using the dial pad to set the number and also to send the DTMF tones. But I find the code to bit more repitive. Is there any better way to optimize the code or the approach I have is good enough ?
Thank you in advance for your valuable suggestions. Cheers :)</p>
<pre><code>public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button btnZero, btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btnAsh, btnHash;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Buttons
btn1 = findViewById(R.id.btnOne);
btn2 = findViewById(R.id.btnTwo);
btn3 = findViewById(R.id.btnThree);
btn4 = findViewById(R.id.btnFour);
btn5 = findViewById(R.id.btnFive);
btn6 = findViewById(R.id.btnSix);
btn7 = findViewById(R.id.btnSeven);
btn8 = findViewById(R.id.btnEight);
btn9 = findViewById(R.id.btnNine);
btnZero = findViewById(R.id.btnZero);
btnAsh = findViewById(R.id.btnAsterisk);
btnHash = findViewById(R.id.btnHash);
dialPadTone();
}
public dialPadTone() {
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
btn5.setOnClickListener(this);
btn6.setOnClickListener(this);
btn7.setOnClickListener(this);
btn8.setOnClickListener(this);
btn9.setOnClickListener(this);
btnZero.setOnClickListener(this);
btnAsh.setOnClickListener(this);
btnHash.setOnClickListener(this);
}
@Override
public void onClick(View view) {
// Read current phone dialPadnumber
String phoneNo = dialPadnumber.getText().toString();
int value;
if (btnZero.equals(view)) {
value = 48;
phoneNo += btnZero.getText();
} else if (btn1.equals(view)) {
value = 49;
phoneNo += btn1.getText();
} else if (btn2.equals(view)) {
value = 50;
phoneNo += btn2.getText();
} else if (btn3.equals(view)) {
value = 51;
phoneNo += btn3.getText();
} else if (btn4.equals(view)) {
value = 52;
phoneNo += btn4.getText();
} else if (btn5.equals(view)) {
value = 53;
phoneNo += btn5.getText();
} else if (btn6.equals(view)) {
value = 54;
phoneNo += btn6.getText();
} else if (btn7.equals(view)) {
value = 55;
phoneNo += btn7.getText();
} else if (btn8.equals(view)) {
value = 56;
phoneNo += btn8.getText();
} else if (btn9.equals(view)) {
value = 57;
phoneNo += btn9.getText();
} else if (btnAsh.equals(view)) {
value = 42;
} else if (btnHash.equals(view)) {
value = 35;
} else {
throw new IllegalStateException("Unexpected value: " + view.getId());
}
setPhoneNum(phoneNo);
Intent intent = new Intent("send_dtmf_tones");
Message message = new DTMFtones(
value
);
sendBroadcast(intent);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Use the <a href=\"https://www.geeksforgeeks.org/handling-click-events-button-android/\" rel=\"nofollow noreferrer\">android:onClick</a> attribute to get rid of the boilerplate calls to <code>setOnClickListener</code> and <code>findViewById</code>.</p>\n\n<p>The giant if-else statement is very repetitive. The actions taken in all branches are assigning a value to the <code>value</code> variable and appending a digit to the phone number. You could convert the code to data by mapping the button label to a value and a string.</p>\n\n<pre><code>final String label = ((Button) view).getText();\nfinal int value = buttonLabelToValue.get(label);\nphoneNo += buttonLabelToPhoneNumberDigit.get(label);\n</code></pre>\n\n<p>Handle the two special cases '#' and '*' by mapping the PhoneNumberDigit to an empty string.</p>\n\n<p>I never write code to prepare for an UI component calling a wrong listener method. I define the UI and the listeners and if my UI calls the wrong method then it's a bug. My tests must be good enough to catch such scenarios. In this example, not checking the return value of <code>buttonLabelToValue.get(...)</code> for nulls results in <code>NullPointerException</code> instead of the <code>IllegalStateException</code> thrown in your version. Not much difference for the user as the app crashes in both cases.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T11:22:08.377",
"Id": "454586",
"Score": "0",
"body": "Thanks for your suggestion. I will rework it :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T10:21:27.257",
"Id": "232731",
"ParentId": "232729",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T08:33:16.330",
"Id": "232729",
"Score": "1",
"Tags": [
"java",
"android"
],
"Title": "Sending DTMF tones from dialpad"
}
|
232729
|
<pre><code>NOTES=[]
hadm=[]
for i in sorted(list(notes_df.SUBJECT_ID.unique())):
#print(i)
NOTES.append(list(notes_df[notes_df.SUBJECT_ID == i].TEXT))
hadm.append(list(notes_df[notes_df.SUBJECT_ID == i].HADM_ID.astype(float)))
notes_1_df = pd.DataFrame(list(zip(sorted(list(notes_df.SUBJECT_ID.unique())),hadm,[item for sublist in NOTES for item in sublist])), columns =['SUBJECT_ID','HADM_ID','NOTES'])
notes_1_df.HADM_ID=notes_1_df.HADM_ID.astype(str)
</code></pre>
<p>The above code works fine to generate a new <code>Dataframe</code> with sorted values of subject ID and its corresponding values of other column. I used lists to store values and then used them to create a <code>Dataframe</code>.</p>
<p>But it is slow. How to make it fast?</p>
<p><code>notes_df</code> structure:</p>
<pre><code>ROW_ID|SUBJECT_ID|HADM_ID|TEXT
1 4 89 Here is the text
2 23 433 Here is the text,and so on
3 65 1212 Here is the text,and
4 914 2212 Here is the text,and so on
5 23 112 Here is the text,and so on
6 23 773 Here is the text,and so on
7 65 1210 Here is the text,and so
8 23 1212 Here is the text,and so on
</code></pre>
|
[] |
[
{
"body": "<p>What makes your code slow is the repeated calls to <code>unique</code>, and manually shunting all entries into lists repeatedly. Ideally you want to do it all in <code>pandas</code> for the most speed.</p>\n\n<p>If I understand it correctly, you want to group by the subject ID, collect all hadm IDs and texts. In that case, you can just use <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.groupby.html\" rel=\"nofollow noreferrer\"><code>pandas.DataFrame.groupby</code></a> and <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.aggregate.html\" rel=\"nofollow noreferrer\"><code>pandas.DataFrame.aggregate</code></a> to achieve (almost) the same result:</p>\n\n<pre><code>notes_1_df = notes_df.drop(columns=[\"ROW_ID\"]) \\\n .groupby(\"SUBJECT_ID\") \\\n .aggregate(list) \\\n .reset_index()\n</code></pre>\n\n<p>Which directly produces this output:</p>\n\n<pre><code> SUBJECT_ID HADM_ID TEXT\n0 4 [89] [Here is the text]\n1 23 [433, 112, 773, 1212] [Here is the text,and so on, Here is the text,...\n2 65 [1212, 1210] [Here is the text,and, Here is the text,and so]\n3 914 [2212] [Here is the text,and so on]\n</code></pre>\n\n<p>Whereas your code produces:</p>\n\n<pre><code> SUBJECT_ID HADM_ID NOTES\n0 4 [89.0] Here is the text\n1 23 [433.0, 112.0, 773.0, 1212.0] Here is the text,and so on\n2 65 [1212.0, 1210.0] Here is the text,and so on\n3 914 [2212.0] Here is the text,and so on\n</code></pre>\n\n<p>This differs mainly in the notes. Here your code is a bit weird. Instead of doing what you did, let's just pick the first text from each subject for now.</p>\n\n<p>I am assuming that having integers for the hadm ID is fine, otherwise you can be more specific and supply two different functions to <code>aggregate</code>, in which case you don't even need the <code>drop</code> anymore:</p>\n\n<pre><code>notes_1_df = notes_df.groupby(\"SUBJECT_ID\") \\\n .aggregate({\"HADM_ID\": lambda x: list(map(float, x)),\n \"TEXT\": \"first\"}) \\\n .rename(columns={\"TEXT\": \"NOTES\"}) \\\n .reset_index()\n</code></pre>\n\n\n\n<pre><code> SUBJECT_ID HADM_ID NOTES\n0 4 [89.0] Here is the text\n1 23 [433.0, 112.0, 773.0, 1212.0] Here is the text,and so on\n2 65 [1212.0, 1210.0] Here is the text,and\n3 914 [2212.0] Here is the text,and so on\n</code></pre>\n\n<hr>\n\n<p>To see why I think your code produces weird results, let's replace the text with unique texts:</p>\n\n<pre><code>df[\"TEXT\"] = \"Text from subject \" + df.SUBJECT_ID.astype(str) + \", hadm \" + df.HADM_ID.astype(str)\n</code></pre>\n\n<p>Then my (last) code produces:</p>\n\n<pre><code> SUBJECT_ID HADM_ID NOTES\n0 4 [89.0] Text from subject 4, hadm 89\n1 23 [433.0, 112.0, 773.0, 1212.0] Text from subject 23, hadm 433\n2 65 [1212.0, 1210.0] Text from subject 65, hadm 1212\n3 914 [2212.0] Text from subject 914, hadm 2212\n</code></pre>\n\n<p>Where each text is the first text from that actual subject. In contrast, your code produces:</p>\n\n<pre><code> SUBJECT_ID HADM_ID NOTES\n0 4 [89.0] Text from subject 4, hadm 89\n1 23 [433.0, 112.0, 773.0, 1212.0] Text from subject 23, hadm 433\n2 65 [1212.0, 1210.0] Text from subject 23, hadm 112\n3 914 [2212.0] Text from subject 23, hadm 773\n</code></pre>\n\n<p>Note how the texts do not correspond to the same subjects anymore!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T11:25:46.840",
"Id": "454587",
"Score": "0",
"body": "what does `'TEXT':'first'` do? also on my side, My NOTES column collects all notes under same Subject_ID in a list ,Unlike what is specified in answer. I also didnt understand this \"The first text (which is implicitly selected in your code by using zip, which clips at the end of the shortest iterable) can be selected using notes_1_df.TEXT.str[0] or using the first function\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T11:29:44.650",
"Id": "454589",
"Score": "0",
"body": "@AdityaVartak: It applies the function [`first`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.first.html), which takes the first element in the group. It's a pandas specialty that you can pass a string instead of the function, it only works for some. Your code is a bit weird, you collect the notes per subject ID (as does my first code), but then you do `[item for sublist in NOTES for item in sublist]`, which means you loose the connection between the text and the subject/hadm ID. Try it with unique texts for each row to see the difference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T11:34:19.150",
"Id": "454590",
"Score": "0",
"body": "yeah i just tried out your code on the data and i see the notes in the beginning are properly coming as expected. but the notes near the end are all jumbled"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T11:36:48.493",
"Id": "454591",
"Score": "0",
"body": "for `[item for sublist in NOTES for item in sublist]` I was trying to pick up a subnote list from list of notes then pick the note from the sublist as notes are inside lists which are collected together as a single list for single subject ID"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T11:41:08.450",
"Id": "454594",
"Score": "0",
"body": "@AdityaVartak: Added an example with more easily identified texts."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T11:46:20.207",
"Id": "454595",
"Score": "0",
"body": "what if i want to collect all texts and not just the first. I mean that I want to make a list of list for all texts of that subject(similar to way it is done for hadm id) ,Order is not compulsorily important but better if it is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T11:46:55.197",
"Id": "454596",
"Score": "1",
"body": "@AdityaVartak: See my first code block, that is exactly what that code is doing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T11:48:43.187",
"Id": "454597",
"Score": "0",
"body": "Ok i get it now.So i should execute it in 2 steps first the above code then the below one?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T11:50:10.793",
"Id": "454598",
"Score": "0",
"body": "@AdityaVartak: No, they are two slightly different ways. The first one just collates both hadm IDs and texts into lists each, per subject. The second one was me trying to more closely emulate the behavior of your code and discovering that your code is a bit weird :). They are completely independent."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T11:52:02.620",
"Id": "454599",
"Score": "0",
"body": "okay so what shall i change in 2nd code to make sure i can collect list of lists of the note and in proper order as you talked about"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T11:58:56.833",
"Id": "454600",
"Score": "0",
"body": "@AdityaVartak Nothing, just use the first, adding the `rename` from the second."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T12:07:29.353",
"Id": "454601",
"Score": "0",
"body": "I was asking regarding `'first'` arguement.I dont need only the 1st note, need all notes for subject ID. So should i delete the ` \"TEXT\": \"first\"` or any other way?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T12:32:38.373",
"Id": "454603",
"Score": "0",
"body": "@AdityaVartak Again, just use the first code block. It puts both the hadm IDs and the texts in lists. The only real difference is in how I used the `aggreggate` method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T13:37:24.970",
"Id": "454613",
"Score": "1",
"body": "Thanks a lot @Graipher I am accepting the solution"
}
],
"meta_data": {
"CommentCount": "14",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T11:14:06.737",
"Id": "232734",
"ParentId": "232730",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "232734",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T09:37:58.517",
"Id": "232730",
"Score": "2",
"Tags": [
"python",
"performance",
"pandas"
],
"Title": "Sort pandas DataFrame first by subject ID then pick their corresponding values from other columns"
}
|
232730
|
<p>I have a <code>Singleton</code> manager class for managing request model and its attributes.</p>
<p>My main aim is update object observers when some of the object attributes changes.</p>
<pre><code>class FlightSearchManager {
private val _flightSearchRequestModelLiveData : MutableLiveData<FlightSearchRequestModel> = MutableLiveData()
val flightSearchRequestModelLiveData : LiveData<FlightSearchRequestModel> get() = _flightSearchRequestModelLiveData
var flightSearchRequestModel : FlightSearchRequestModel
init {
flightSearchRequestModel =
FlightSearchRequestModel(
null,
null,
null,
null,
null,
null,
null,
null,
null)
}
fun updateFlightSearchRequestModel(_arriveAirport : String? = null,
_arriveAirportId: Int? = null,
_departureAirport : String? = null,
_departureAirportId: Int? = null,
_departureDate : String? = null,
_isRoundTrip : Boolean? = false,
_paxTypeCount : List<PaxTypeCount>? = null,
_returnDate : String? = null,
_seatClass : String? = null) {
flightSearchRequestModel.apply {
arriveAirport = _arriveAirport ?: arriveAirport
arriveAirportId = _arriveAirportId ?: arriveAirportId
departureAirport = _departureAirport ?: departureAirport
departureAirportId = _departureAirportId ?: departureAirportId
departureDate = _departureDate ?: departureDate
isRoundTrip = _isRoundTrip ?: isRoundTrip
paxTypeCount = _paxTypeCount ?: paxTypeCount
returnDate = _returnDate ?: returnDate
seatClass = _seatClass ?: seatClass
// Notify all listeners of live data
_flightSearchRequestModelLiveData.value = this
}
}
}
</code></pre>
<p>When I want to notify observers I call:</p>
<pre><code>flightSearchManager.updateFlightSearchRequestModel(_seatClass = "1")
</code></pre>
<p>This solution does not seem good solution. How can I write it more intelligently?</p>
|
[] |
[
{
"body": "<p>To give you valuable feedback on your usecase, I would need more information, like: How do listeners listen? How does the caller look like? </p>\n\n<p>How exactly does <code>_flightSearchRequestModelLiveData.value = this</code> notify all listeners of live data? Its not a function call, so how is an event created and pushed?!</p>\n\n<p>Instead I will give some pattern advices you may need.</p>\n\n<h2>Use constructor initialisation</h2>\n\n<ol>\n<li>Kotlin enables you to set fields over constructors. Even if your class is a singleton and all values are default - creating a constructor will enable to test your class easily (and other benefits).</li>\n</ol>\n\n<p>So instead of:</p>\n\n<pre><code>class FlightSearchManager {\n\n private val _flightSearchRequestModelLiveData : MutableLiveData<FlightSearchRequestModel> = MutableLiveData()\n val flightSearchRequestModelLiveData : LiveData<FlightSearchRequestModel> get() = _flightSearchRequestModelLiveData\n\n var flightSearchRequestModel : FlightSearchRequestModel\n</code></pre>\n\n<p>try to go for:</p>\n\n<pre><code>class FlightSearchManager(\n val flightSearchRequestModelLiveData : MutableLiveData<FlightSearchRequestModel> = MutableLiveData(),\n var flightSearchRequestModel : FlightSearchRequestModel = FlightSearchRequestModel()\n) {\n</code></pre>\n\n<ol start=\"2\">\n<li>If you already have a constructor for a class and it is valid to have all fields to have default values - don't force the caller to set them!</li>\n</ol>\n\n<p>This code is an anti-pattern:</p>\n\n<pre><code>flightSearchRequestModel =\n FlightSearchRequestModel(\n null,\n null,\n null,\n null,\n null,\n null,\n null,\n null,\n null)\n</code></pre>\n\n<p>What you should go for would be:</p>\n\n<pre><code>data class FlightSearchRequestModel(\n val propertyOne : String? = null, \n val propertyTwo: Int? = null,\n ...\n)\n\nFlightSearchManager {\n val model = FlightSearchRequestModel()\n}\n</code></pre>\n\n<h2>Parameters</h2>\n\n<p>It is seen as code smell, when your method has too many parameters, so I would recommend to reduce the number of those in <code>fun updateFlightSearchRequestModel</code>.</p>\n\n<p>You could create a single function for every parameter change. Of course it means more lines to write, but is cleaner, straight forward and not as error-prone to side effects since you don't change ~20 things in one method.</p>\n\n<h2>Naming convetions</h2>\n\n<p>I would guess that you coded with something like <em>C#</em> before, because of the usage of underscores <code>_</code> in variable names. Please try to follow the appropreate convetion for this language (Kotlin), as well as in Java:</p>\n\n<blockquote>\n <p>Local variables, instance variables, and class variables are also written in lowerCamelCase. Variable names should not start with underscore (_) or dollar sign ($) characters, even though both are allowed. This is in contrast to other coding conventions that state that underscores should be used to prefix all instance variables.</p>\n</blockquote>\n\n<p>Constants: </p>\n\n<blockquote>\n <p>Constants should be written in uppercase characters separated by underscores. Constant names may also contain digits if appropriate, but not as the first character.</p>\n</blockquote>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Naming_convention_(programming)\" rel=\"nofollow noreferrer\">Source</a></p>\n\n<p>Fields like this:</p>\n\n<pre><code>private val _flightSearchRequestModelLiveData : MutableLiveData<FlightSearchRequestModel> = MutableLiveData()\n</code></pre>\n\n<p>would become:</p>\n\n<pre><code>private val flightSearchRequestModelLiveData : MutableLiveData<FlightSearchRequestModel> = MutableLiveData()\n</code></pre>\n\n<hr>\n\n<p>Functions like this</p>\n\n<pre><code>fun updateFlightSearchRequestModel(_arriveAirport : String? = null,\n _arriveAirportId: Int? = null,\n</code></pre>\n\n<p>would become:</p>\n\n<pre><code>fun updateFlightSearchRequestModel(arriveAirport : String? = null,\n arriveAirportId: Int? = null,\n</code></pre>\n\n<h2>Immutability</h2>\n\n<p>Immutable code is easier to debug, to understand and to test. Favor <code>val</code> over <code>var</code> in (almost) every case.</p>\n\n<p>If you really need to change something by reference, at least create a completely new immutable object. Example:</p>\n\n<p>This </p>\n\n<pre><code>flightSearchRequestModel.apply {\n arriveAirport = _arriveAirport ?: arriveAirport\n arriveAirportId = _arriveAirportId ?: arriveAirportId\n ...\n}\n</code></pre>\n\n<p>could become this:</p>\n\n<pre><code>flightSearchRequestModel = copy(arriveAirport = arriveAirport, arriveAirportId = arriveAirportId, ...)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-27T08:57:52.730",
"Id": "233050",
"ParentId": "232732",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "233050",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T10:36:05.923",
"Id": "232732",
"Score": "1",
"Tags": [
"android",
"kotlin",
"observer-pattern"
],
"Title": "Notify observers when object attributes update"
}
|
232732
|
<p>I have written this code for crawling and scraping search results from Google. But it's super slow when I run it.</p>
<p>What it does: read a pandas column, search values in Google and take the first result link then extract the siret number in link
Ex.</p>
<blockquote>
<p><a href="https://www.infogreffe.fr/entreprise-societe/380760702-entreprise-de-decoration-et-d-innovation-sarl-340591B001420000.html" rel="nofollow noreferrer">https://www.infogreffe.fr/entreprise-societe/380760702-entreprise-de-decoration-et-d-innovation-sarl-340591B001420000.html</a>
the siret is 380760702. In every iteration I save this number in <code>found_results</code>.</p>
</blockquote>
<p>To do that, there are three functions:</p>
<ul>
<li><code>rechercher_google()</code> to get the html</li>
<li><code>parse_results()</code> to parse the url where the digit is</li>
<li><code>recherche_google()</code> to wrap to these two functions above.</li>
</ul>
<p>Could it be less greedy in complexity or be better?</p>
<pre><code># Function pour recupere la html
USER_AGENT = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'}
def rechercher_google(search_term, number_results, language_code):
'''
input: Nom de l'entreprise à siretiser, le nombre de page et la langue
output: La page resultat dde google en html stocker au format raw html
'''
assert isinstance(search_term, str), 'Il doit etre en string'
assert isinstance(number_results, int), 'DOit etre en chiffre'
escaped_search_term = search_term.replace(' ', '+')
g_url = 'https://www.google.fr/search?q={}&num={}&hl={}'.format(escaped_search_term, number_results, language_code)
response = requests.get(g_url, headers = USER_AGENT)
response.raise_for_status()
return response.text, search_term
# function pour recuperer ce qu'on a besoin dans la page
def parse_results(html, keyword):
'''
Input: la sortie de la fortion fetch_results()
output: le nom de l'entreprise et le siret
'''
soup = bs(html, 'html.parser')
found_results = []
rank = 1
result_block = soup.find_all('div', attrs={'class': 'g'}) # g indique q'on est bien dans un resultat normal
for result in result_block:
link = result.find('a', href=True)
title = result.find('h3')
if link and title:
link = link['href']
title = title.get_text()
if link != '#':
try:
found_results.append({'siret':link.split('/')[4].split('-')[0]})
except Exception as list_error:
print('error in fund_results {}'.format(list_error))
rank += 1
return found_results
# wrap up, le tout dans un global function qui appelle les deux premiere.
def scrape_google(search_term, number_results, language_code):
'''
input: il mange les deux premier functions
output: une liste de dict des nom d'entreprise avec leur siret et club
'''
try:
html, keyword = rechercher_google(search_term, number_results, language_code)
results = parse_results(html, keyword)
return results
except AssertionError:
raise Exception("Probleme d'argument")
except requests.HTTPError:
raise Exception(" :/ Google a bloqué le ip")
except requests.RequestException:
raise Exception(" :/ Probleme de connexion/proxy")
</code></pre>
<p>To run it</p>
<pre><code># Siret à partir de google
start_time = time.time()
data = []
for keyword in liste_partenaire.Partenaire:
keyword = keyword+ ' ' + 'infogreffe Montpellier'
name.append(keyword)
try:
results = scrape_google(keyword, 1, "fr")
for result in results:
data.append(results[0]['siret'])
except Exception as e:
print(' :( Error in results:: [ {} ]'. format(e))
finally:
time.sleep(11)
print("--- %s seconds d'éxecution ---" % (time.time() - start_time)) # 48 minutes
# save
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T11:27:50.493",
"Id": "454588",
"Score": "1",
"body": "Welcome to Code Review! Seems like you have missed the hint to *\"State the task that your code accomplishes. Make your title distinctive.\"* in the question template. Please also have a look at our [ask] page to get a few more hints how to write an interesting title for your question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T11:40:20.490",
"Id": "454592",
"Score": "0",
"body": "Ok thanks let le review it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T11:40:51.470",
"Id": "454593",
"Score": "2",
"body": "You said *it's super slow*, then why are you waiting for **11** seconds on each iteration with `time.sleep(11)` ?!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T12:35:02.863",
"Id": "454604",
"Score": "0",
"body": "This is to avoid google bot, can I make it 5s or less?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T12:35:42.663",
"Id": "454605",
"Score": "0",
"body": "So my code is in complexity (in for loop) is ok?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T12:36:13.913",
"Id": "454606",
"Score": "1",
"body": "I have rephrased your question and your title to the best of my knowledge to make it more readable. Since I don't speak French, there might be errors. Please have a look at the rephrased version, and especially check *\"to grape a siret\"*, which I could not understand."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T12:40:20.400",
"Id": "454607",
"Score": "0",
"body": "Sorry I chnaged, I'm french. I meant to extract the siret. siret is unique company id here in France. I have edited the post again."
}
] |
[
{
"body": "<p>Your escaping for the search term is not sufficient. Other characters than spaces might be in the user entered string, which also need to be escaped. Luckily, <code>requests</code> can do it all for you:</p>\n\n<pre><code>def rechercher_google(search_term, number_results, language_code):\n '''\n input: Nom de l'entreprise à siretiser, le nombre de page et la langue\n output: La page resultat dde google en html stocker au format raw html\n '''\n assert isinstance(search_term, str), 'Il doit etre en string'\n assert isinstance(number_results, int), 'DOit etre en chiffre'\n\n g_url = 'https://www.google.fr/search'\n params = {\"q\": search_term, \"num\": number_results, \"hl\": language_code}\n response = requests.get(g_url, params=params, headers=USER_AGENT)\n response.raise_for_status()\n return response.text, search_term\n</code></pre>\n\n<p>Note that I also followed Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, and did not use spaces around the <code>=</code> for keyword arguments.</p>\n\n<p>But the obvious improvement is not to parse the Google search results at all, but directly query the website you are interested in. If I understand it correctly, what you actually want to parse is:</p>\n\n<pre><code>url = \"https://www.infogreffe.fr/recherche-entreprise-dirigeants/resultats-entreprise-dirigeants.html\"\nparams = {\"ga_cat\": \"globale\", \"ga_q\"=search_term}\nresponse = requests.get(url, params=params, header=USER_AGENT)\n</code></pre>\n\n<p>That website is not particularly fast either (some pages take 5s to load). But they will probably have worse bot protection than Google, which is a bit evil, but if your scraping is evil, you should not be doing it in the first place. Always read the terms & conditions of websites you want to scrape, so at least you know what you are doing. The Wikipedia page <a href=\"https://en.wikipedia.org/wiki/Search_engine_scraping\" rel=\"nofollow noreferrer\">Search engine scraping</a> has quite a lot of information about what Google is doing to prevent you from scraping their search result page too aggressively. In the same vein, you could try optimizing the wait time between the queries, which is currently 11 seconds. With some trial & error you might find a shorter time that also works.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T13:33:27.233",
"Id": "454610",
"Score": "0",
"body": "Thanks lot I'll change this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T13:34:49.747",
"Id": "454611",
"Score": "2",
"body": "@abdoulsn: Glad it helped. But please don't update the code in the question. If you feel like you need more review, either un-accept my answer and wait for more answers, or ask a new question with updated code. Have a look at our [help center](https://codereview.stackexchange.com/help/someone-answers) for more information on what to do after you have received an answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T13:29:15.593",
"Id": "232737",
"ParentId": "232733",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "232737",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T11:09:52.513",
"Id": "232733",
"Score": "2",
"Tags": [
"python",
"performance",
"web-scraping",
"beautifulsoup"
],
"Title": "Scrape company data from Google search"
}
|
232733
|
<p>I have different set of objects where I have to show <strong>Name UI</strong> and <strong>Menu UI</strong> using <code>OnMouseDown</code> and on <code>OnMouseEnter</code> Events. Remember Both are optional, the one object may contain(attach) both option(script) or maybe one option(script).</p>
<p>Currently I have manage to write two separate scripts like this, that include <code>input</code> + <code>action</code>:</p>
<p><em>For Menu UI Handling :</em></p>
<pre><code> /// <summary>
/// It will shown the three button menu on mouse click.
/// </summary>
public class DisplayMenu : MonoBehaviour
{
public GameObject canvasMenuNavigation;
public Image panelNavigation;
public float machineNameYPosition = 0f;
[SerializeField]
BtnFurtherExplosionAnimationDeactive btnFurtherExplosionAnimationDeactive;
public void Reset()
{
canvasMenuNavigation = GameObject.Find("Canvas_MenuNavigation");
panelNavigation = canvasMenuNavigation.GetComponentInChildren<Image>();
btnFurtherExplosionAnimationDeactive = canvasMenuNavigation.GetComponentInChildren<BtnFurtherExplosionAnimationDeactive>();
}
private void OnMouseDown()
{
if (AnimationStateManager.currentAnimationState != AnimationStates.None)
{
Debug.Log("onmousedown");
DisplayMenueCanvas(true);
panelNavigation.transform.position = new Vector3(
this.transform.position.x,
this.transform.position.y + machineNameYPosition,
this.transform.position.z);
string currentAnimatioType = this.name.Split('_')[3];
Debug.Log(currentAnimatioType);
AnimationStates selectedState = (AnimationStates)System.Enum.Parse(typeof(AnimationStates), currentAnimatioType, true);
FindObjectOfType<SelectedAnimationType>().selectedAnimationType = selectedState;
btnFurtherExplosionAnimationDeactive.ButtonActive();
}
}
void DisplayMenueCanvas(bool isActive)
{
canvasMenuNavigation.SetActive(isActive);
}
}
</code></pre>
<p><em>AND The below script will mange to show <code>Name UI</code>:</em></p>
<pre><code>/// <summary>
/// Display Name UI on mouse Enter event and hide on mouse exit
/// </summary>
public class DisplayMachinePartNameOnMouseOver : MonoBehaviour
{
public GameObject machinePartNameShow;
public Canvas partNameCavnas;
public Image partNameImage;
public LineDrawer lineDrawer;
public Text txtMachinePartName;
public float machineNameYPosition = 5f;
public void Reset()
{
machinePartNameShow = GameObject.Find("MachinePartNameShow");
partNameCavnas = machinePartNameShow.GetComponentInChildren<Canvas>();
partNameImage = machinePartNameShow.GetComponentInChildren<Image>();
lineDrawer = machinePartNameShow.GetComponentInChildren<LineDrawer>();
txtMachinePartName = machinePartNameShow.GetComponentInChildren<Text>();
}
private void OnMouseEnter()
{
if (!EventSystem.current.IsPointerOverGameObject())
{
//Position the UI
partNameImage.transform.position = new Vector3(
this.transform.position.x,
this.transform.position.y + machineNameYPosition,
this.transform.position.z);
//Set line between Name and Object
lineDrawer.SetLine(this.transform.position, partNameImage.transform.position);
//Get the name
string machinePartName = MachinePartNames.MachinePartName(this.name);
Debug.Log(machinePartName);
if (machinePartName != null)
{
//show the name
txtMachinePartName.text = machinePartName;
//activate the name UI
DisplayMachinePartName(true);
}
}
}
private void OnMouseExit()
{
//Deactive the part name UI
DisplayMachinePartName(false);
}
void DisplayMachinePartName(bool isActive)
{
machinePartNameShow.SetActive(isActive);
}
}
</code></pre>
<p>How can I improve this code? So that the input class and other (action) functionality handle separately. As you can see, currently I am doing input and functionality/Action in the same class. I am willing to convert it to independent components scripts. So that I able to apply the SOLID principle. </p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T12:26:44.307",
"Id": "232735",
"Score": "3",
"Tags": [
"c#",
"unity3d"
],
"Title": "Manage independent script component architecture in unity"
}
|
232735
|
<p>The end goal of my program is to use a non-linear solver to fit a set of parameters to my data set. I pull the data set from a database into a list <code>sprays</code>, then instantiate a list of <code>Strip</code> objects which parse that data for further processing.</p>
<pre><code>strips = [Strip(spray) for spray in sprays]
</code></pre>
<p><code>Spray.cool(hw, ha, coef, units)</code> is a class function which returns a 2-tuple <code>(err1, err2)</code> of errors. My goal is to minimize the mean-square error of this call for the entire data set. The total list of errors is generated by the following function:</p>
<pre><code>def search(h):
errors = []
for strip in strips:
errors += strip.cool(h[0], h[1], list(h[2:]), units)
return errors
</code></pre>
<p>I have a preset parameter <code>units</code> which is a list of 6 floats.</p>
<p><b>I have a few parameters I wish to fit:</b><br/>
<code>hw</code> and <code>ha</code> are both floats.<br/>
<code>coef</code> is a list of six floats which will affect their corresponding elements in <code>units</code>.<br/></p>
<p>I fit these parameters through the following function call from <code>scipy.optimize</code></p>
<pre><code>leastsq(search, (hw, ha, *coef))
</code></pre>
<p>Each individual call of <code>Strip.cool</code> takes ~10ms to execute, which is plenty fast for applications I am looking into. However, <code>strips</code> contains 1000s of elements, each calling <code>Strip.cool</code>, which adds up. It's bearable for a single call of <code>search</code>, but <code>leastsq</code> calls <code>search</code> numerous times to converge on a solution which adds up to hours of computation.</p>
<p><b>How can improve the performance of this program?</b><br/>
Ideally, I would make a change to <code>search</code> which would allow all elements of <code>strips</code> to call <code>cool</code> at once, in a sort of parallel call that I think I see in <code>numpy</code> array operations a lot. Also possible would be to change my approach to a non-linear fit, either by using a different solver or different method entirely (one that doesn't require calling <code>cool</code> for every instance in <code>strips</code> every iteration). I would prefer to steer away from editing <code>cool</code>, as I feel it is fairly optimized and a small increase in performance there will not greatly improve the overall performance (again, calling <code>cool</code> millions of times), but I have included it for the curious souls.</p>
<p><b>What I have tried:</b><br/>
<code>threading</code> and <code>multiprocessing</code> both require a bit of overhead to spin up a new routine. This overhead is greater than the execution time for a single call, and from what I've found using these methods results in a call to <code>search</code> actually taking longer.<br/>
<code>map</code> looked promising at first, as I hope that there was some parallel processing trickery going on under the hood. By defining</p>
<pre><code>def run_strip(strip, *args):
return strip.cool(args[0], args[1], args[2], args[3])
</code></pre>
<p>a call of <code>map(lambda s: run_strip(s, h[0], h[1], list(h[2:]), units), strips)</code> produces the same results, but unfortunately with comparable processing time.</p>
<p><b>Function definition</b></p>
<pre><code>def cool(self, hw, ha, coef, units):
bw = 2 * self.dy / self.k * hw
ba = 2 * self.dy / self.k * ha
atemp = 70
Uwt = np.zeros_like(self.Matrix)
Uwb = np.zeros_like(self.Matrix)
Uwt[1,0] = Uwb[-2,-1] = self.alpha * bw * self.wtemp
Uwt[1,1] = Uwb[-2,-2] = -self.alpha * bw
Uat = np.zeros_like(self.Matrix)
Uab = np.zeros_like(self.Matrix)
Uat[1,0] = Uab[-2,-1] = self.alpha * ba * atemp
Uat[1,1] = Uab[-2,-2] = -self.alpha * ba
temperature = np.ones((int(self.y / self.dy) + 1)) * self.ftemp
temps = np.empty((len(self.iterations), int(self.y / self.dy) + 1))
for n, i, t, b in zip(range(len(rot.RegionLengths)), self.iterations, self.topSprays, self.botSprays):
if t == 1:
tunit = rot.TopSprayRegionUnits[n] * coef[:3][units[:3].index(tunit)]
Ut = Uwt * tunit
else:
tunit = 1
Ut = Uat
if b == 1:
bunit = rot.BottomSprayRegionUnits[n] * coef[3:][units[3:].index(bunit)]
Ub = Uwb * bunit
else:
bunit = 1
Ub = Uab
temperature = np.matmul(np.linalg.matrix_power(self.Matrix+Ut+Ub, i), np.pad(temperature, (1, 1), 'constant', constant_values=((1,1),)))[1:-1]
temps[n] = np.reshape(temperature, (1,-1))
return temperature[0] - self.ctemp
</code></pre>
<p>Personal note:<br/>
Sorry for the problems with posing this question. The balance between too much detail and too much abstraction can be difficult. Hopefully this provides enough information now to point towards a solution.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T13:11:01.890",
"Id": "454608",
"Score": "0",
"body": "I think this code is too general to be reviewed. We require concrete code with sufficient context to understand it. Otherwise the review would consist entirely of \"Use [`multiprocessing`](https://docs.python.org/3/library/multiprocessing.html).\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T13:22:32.717",
"Id": "454609",
"Score": "0",
"body": "@Graipher What seems too general about it? `Foo` is an object which has a function `dofoo` that takes several parameters. In this case `dofoo` returns a number. `func` returns the results of `dofoo` for all `Foo` instances in `foos`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T13:42:25.377",
"Id": "454618",
"Score": "0",
"body": "Using `foo` and `bar` is the epitome of stub code. And we dont review stub code on CR."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T13:50:14.823",
"Id": "454619",
"Score": "0",
"body": "Edited to be less general."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T13:56:30.373",
"Id": "454620",
"Score": "0",
"body": "Groger, to clarify @konijn's statement, it's not that your code looks too vague, it's that the purpose of Code Review is to review the quality, performance, etc. of actual, working code. It's supposed to be the exact code you're running because we're here to critique things like style, function layout, documentation, etc. If you don't know how to accomplish something or your code doesn't work the way you want it to, that's what Stack Overflow is for. I've flagged your question to request that the moderators migrate it there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T14:43:20.413",
"Id": "454626",
"Score": "1",
"body": "@Groger, when you saying \"*perhaps calling in parallel*\" - you'd need to understand that all your options are limited to `threading` or `multiprocessing` or `asyncio`. No need to invent/seek something \"unearthly\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T14:53:00.020",
"Id": "454630",
"Score": "0",
"body": "@RomanPerekhrest I second your remark, but would clarify that ```asyncio``` does not technically run code *in parallel*, it allows multiple pieces of code to trade off running in the same thread when one of them is waiting on I/O, a system call, or something else that isn't directly running Python code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T15:01:03.440",
"Id": "454633",
"Score": "0",
"body": "Another point is you saying \"Each call of cool takes ~10 ms, which is pretty fast and cannot be further optimized\". That might be true, but is not necessarily so. Supplying the actual method would allow us to check it and determine it ourselves. Maybe there is some way to do it better in `numpy`/`pandas`, although it might only be worth copying data if you do the whole process many times. Something else we don't know without seeing how the code is actually used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T15:21:43.103",
"Id": "454635",
"Score": "0",
"body": "@Graipher added code for the function."
}
] |
[
{
"body": "<p>As @Graipher says: Use <a href=\"https://docs.python.org/3/library/multiprocessing.html\" rel=\"nofollow noreferrer\">multiprocessing</a>.</p>\n\n<p>You say </p>\n\n<blockquote>\n <p>Each call of dofoo takes ~10 ms, which is pretty fast and cannot be further optimized</p>\n</blockquote>\n\n<p>which implies that your function is CPU bound, or at least that you're not spending the entire time waiting on disk or network I/O... if so, use asyncronous programming like <a href=\"http://www.gevent.org/\" rel=\"nofollow noreferrer\">gevent</a> or just regular old threads (the overhead would be small compared to your 10ms function). <a href=\"https://wiki.python.org/moin/GlobalInterpreterLock\" rel=\"nofollow noreferrer\">If you read up on the GIL</a>, you'll find that the Python interpreter is itself not thread-safe (and for good reasons, there are several great talks, articles, and projects that explore the costs of removing this global lock), hence why you need multiple processes to get proper parallelism.</p>\n\n<p>That said, this is a really common problem and easily handled. The most obvious solution is <a href=\"https://docs.python.org/3.8/library/multiprocessing.html\" rel=\"nofollow noreferrer\"><code>multiprocessing.Pool.map</code></a>, which would make your code look like:</p>\n\n<pre><code>import multiprocessing as mp\n\ndef run_strip(strip, *args):\n return strip.cool(args)\n\ndef all_the_strips(x, y):\n with mp.Pool() as pool:\n z = pool.starmap(run_strip, [(strip, x, y, a, b) for strip in strips])\n return [x for lst in z for x in lst]\n</code></pre>\n\n<p>There are more complicated ways of accomplishing the same task (e.g. setting up a <code>mp.Queue</code> and launching your own processes to consume it) if this solution doesn't fit your need.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T15:35:03.103",
"Id": "454638",
"Score": "0",
"body": "This actually ends up being slower than my original code, likely due to the additional overhead required to set this up."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T18:02:29.127",
"Id": "454827",
"Score": "0",
"body": "@Groger how many CPU cores do you have? And is your code CPU-bound, or limited by something else (network, disk, etc.)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T18:50:54.050",
"Id": "454835",
"Score": "0",
"body": "2 cores. The actual code crunching doesn't require any network communciation, memory is fine, CPU usage is pretty normal."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T13:53:26.263",
"Id": "232739",
"ParentId": "232736",
"Score": "-2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T12:37:34.773",
"Id": "232736",
"Score": "-2",
"Tags": [
"python",
"performance"
],
"Title": "Parallel Calling of Function for Non-linear Solving"
}
|
232736
|
<p>I am working on a <strong><a href="https://github.com/Ajax30/ciapi" rel="nofollow noreferrer">blog application</a></strong> with <strong>Codeigniter 3.1.8</strong> and <strong>AngularJS v1.7.8</strong>.</p>
<p>The Dashboard of the application is "pure" Codeigniter, with Models, Controllers, and views, while the fronted is made up of JSONs managed and displayed by AngularJS.</p>
<p>I operated this clear <em>separation</em> between back-end and front-end in order to enable "themeing". </p>
<p>My <strong>app.js</strong> file:</p>
<pre><code>angular.module('app', [
'ngRoute',
'app.controllers',
'ngSanitize'
]).config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider){
$routeProvider.when('/', {
templateUrl: 'themes/caminar/templates/posts.html',
controller: 'PostsController'
}).when('/posts/byauthor/:author_id', {
templateUrl: 'themes/caminar/templates/posts.html',
controller: 'PostsByAurhorController'
}).when('/categories/posts/:cat_id', {
templateUrl: 'themes/caminar/templates/posts.html',
controller: 'PostsByCategoryController'
}).when('/posts/search', {
templateUrl: 'themes/caminar/templates/posts.html',
controller: 'PostsSearchController'
}).when('/:slug', {
templateUrl: 'themes/caminar/templates/singlepost.html',
controller: 'SinglePostController'
}).when('/comments/create/', {
templateUrl: 'themes/caminar/templates/singlepost.html',
controller: 'PostCommentController'
}).when('/pages/page/:id', {
templateUrl: 'themes/caminar/templates/page.html',
controller: 'PageController'
}).otherwise({
redirectTo: '/'
})
// Enable HTML5 mode
$locationProvider.html5Mode({
enabled: true,
requireBase: true
});
}])
// Date parser filter
.filter('dateParse', function() {
return function(date) {
return Date.parse(date);
};
});
</code></pre>
<p>The <strong>controllers.js</strong> file contains <em>all</em> the front-end controllers:</p>
<pre><code>angular.module('app.controllers', [])
.controller('MainController', ['$scope', '$http', function($scope, $http) {
$http.get('api').then(function(response) {
//Site name
$scope.siteTitle = response.data.site_title;
// Tagline
$scope.tagline = response.data.tagline;
//Company name
$scope.companyName = response.data.company_name;
//Company email
$scope.company_email = response.data.company_email;
//Facebook
$scope.facebook = response.data.facebook;
//Instagram
$scope.instagram = response.data.instagram;
//Twitter
$scope.twitter = response.data.twitter;
// Pages
$scope.pages = response.data.pages;
});
}])
// All posts
.controller('PostsController', ['$scope', '$http', function($scope, $http) {
//Get current page (?page=2, ?page=3 etc)
const currPage = window.location.search;
// Get all the posts on the current page
$http.get('api/' + currPage).then(function(response) {
//Categories
$scope.categories = response.data.categories;
// Posts
$scope.posts = response.data.posts;
// posts pagination
$scope.pagination = response.data.pagination;
});
}])
// Search posts
.controller('PostsSearchController', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {
//Get search term
const searchTerm = window.location.search;
$http.get('api/posts/search' + searchTerm).then(function(response) {
//Categories
$scope.categories = response.data.categories;
// Posts
$scope.posts = response.data.posts;
// posts pagination
$scope.pagination = response.data.pagination;
});
}])
// Posts by Category
.controller('PostsByCategoryController', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {
//Get Category id
const cat_id = $routeParams.cat_id;
//Get current page (?page=2, ?page=3 etc)
const currPage = window.location.search;
$http.get('api/categories/posts/' + cat_id + currPage).then(function(response) {
//Categories
$scope.categories = response.data.categories;
// Posts
$scope.posts = response.data.posts;
// posts pagination
$scope.pagination = response.data.pagination;
});
}])
// Posts by author
.controller('PostsByAurhorController', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {
//Get author id
const author_id = $routeParams.author_id;
//Get current page (?page=2, ?page=3 etc)
const currPage = window.location.search;
$http.get('api/posts/byauthor/' + author_id + currPage).then(function(response) {
//Categories
$scope.categories = response.data.categories;
// Posts
$scope.posts = response.data.posts;
// posts pagination
$scope.pagination = response.data.pagination;
});
}])
// Single post
.controller('SinglePostController', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {
const slug = $routeParams.slug;
$http.get('api/' + slug).then(function(response) {
//Single post
$scope.post = response.data.post;
//Comments
$scope.comments = response.data.comments;
});
}])
// Post comment
.controller('PostCommentController', ['$scope', '$http', '$routeParams', '$timeout', function($scope, $http, $routeParams, $timeout) {
const slug = $routeParams.slug;
$http.get('api/' + slug).then(function(response) {
//Current post id
let post_id = response.data.post.id;
$scope.commentSubmitted = false;
$scope.newComment = {
slug: slug,
post_id: post_id,
name: $scope.name,
email: $scope.email,
comment: $scope.comment
};
$scope.createComment = function() {
if ($scope.newComment.name !== undefined && $scope.newComment.email !== undefined && $scope.newComment.comment !== undefined) {
$http.post('api/comments/create/' + post_id, $scope.newComment)
.then(() => {
$scope.newComment = {};
$scope.commentForm.$setPristine();
$scope.commentForm.$setUntouched();
$scope.commentSuccessMsg = "Your comment was submitted. It will be published after aproval";
$scope.commentSubmitted = true;
$timeout(function() {
$scope.fadeout = "fadeout";
}, 3000);
});
}
};
});
}])
// Page
.controller('PageController', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {
const pageId = $routeParams.id;
$http.get('api/pages/page/' + pageId).then(function(response) {
// Page
$scope.page = response.data.page;
//Categories
$scope.categories = response.data.categories;
// Posts
$scope.posts = response.data.posts;
});
}])
</code></pre>
<p>There is a <code>themes</code> directory with each theme in its own directory, each theme directory containing the necessary assets and templates, like, for instance: <code>mytheme/templates/singlepost.html</code>:</p>
<pre><code><div class="wrapper style1">
<div class="content">
<h2>{{post.title}}</h2>
<p class="meta clearfix">
<span class="pull-left">By <a href="posts/byauthor/{{post.author_id}}" title="All posts by {{post.first_name}} {{post.last_name}}">{{post.first_name}} {{post.last_name}}</a></span>
<span class="pull-right">Published on {{post.created_at | dateParse | date : "MMMM dd y"}} in <a href="categories/posts/{{post.cat_id}}" title="All posts in {{post.category_name}}">{{post.category_name}}</a></span>
</p>
<div class="image fit">
<img ng-src="api/assets/img/posts/{{post.post_image}}" alt="{{post.title}}">
</div>
<div class="post-content" ng-bind-html="post.content"></div>
<div class="comments-form" ng-controller="PostCommentController">
<h3>Leave a comment</h3>
<form name="commentForm" novalidate>
<div class="row uniform">
<div class="form-controll 6u 12u$(xsmall)">
<input type="text" name="name" id="name" ng-model="newComment.name" placeholder="Name" ng-required="true" />
<span class="error" ng-show="(commentForm.name.$touched && commentForm.name.$invalid) || (commentForm.$submitted && commentForm.name.$invalid)">This field can not be empty</span>
</div>
<div class="form-controll 6u$ 12u$(xsmall)">
<input type="email" name="email" id="email" ng-model="newComment.email" placeholder="Email" ng-required="true" />
<span class="error" ng-show="(commentForm.email.$touched && commentForm.email.$invalid) || (commentForm.$submitted && commentForm.email.$invalid)">Enter a valid email address</span>
</div>
<div class="form-controll 12u$">
<textarea name="comment" rows="6" id="message" ng-model="newComment.comment" placeholder="Comment" ng-required="true"></textarea>
<span class="error" ng-show="(commentForm.comment.$touched && commentForm.comment.$invalid) || (commentForm.$submitted && commentForm.comment.$invalid)">This field can not be empty</span>
</div>
<!-- Break -->
<div class="12u$">
<input type="submit" value="Add comment" ng-click="createComment()" class="button special fit" />
</div>
</div>
</form>
<div class="alert alert-success {{fadeout}}" ng-show="commentSubmitted == true">
{{commentSuccessMsg}}
</div>
</div>
<div ng-if="comments.length > 0" class="comments">
<h3>Comments</h3>
<div ng-repeat="comment in comments" class="comment">
<h4>On {{comment.created_at | dateParse | date : "MMMM dd y"}}, {{comment.name}} wrote:</h4>
<p>{{comment.comment}}</p>
</div>
</div>
</div>
</div>
</code></pre>
<p>Thee AngularJS app entry point - index.html - has all the paths to the aforementioned theme assets:</p>
<pre><code><!DOCTYPE html>
<html ng-app="app" ng-controller="MainController">
<head>
<title>{{siteTitle}} | {{tagline}}</title>
<base href="/">
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="js/vendor/angular.min.js"></script>
<script src="js/vendor/angular-route.min.js"></script>
<script src="js/vendor/angular-sanitize.js"></script>
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<link rel="stylesheet" href="themes/caminar/assets/css/main.css" />
</head>
<body>
<!-- Header -->
<header id="header">
<div class="logo"><a href="/">{{siteTitle}}</a></div>
</header>
<!-- Main -->
<section id="main">
<div class="inner" ng-view></div>
</section>
<!-- Footer -->
<footer id="footer">
<div class="container">
<ul class="icons">
<li><a href="{{twitter}}" target="_blank" class="icon fa-twitter"><span class="label">Twitter</span></a></li>
<li><a href="{{facebook}}" target="_blank" class="icon fa-facebook"><span class="label">Facebook</span></a></li>
<li><a href="{{instagram}}" target="_blank" class="icon fa-instagram"><span class="label">Instagram</span></a></li>
<li><a href="mailto:{{company_email}}" class="icon fa-envelope-o"><span class="label">Email</span></a></li>
</ul>
<ul class="icons">
<li ng-repeat="page in pages">
<a href="pages/page/{{page.id}}">{{page.title}}</a>
</li>
</ul>
</div>
<div class="copyright">
&copy; {{companyName}}. All rights reserved. Design by <a href="https://templated.co" target="_blank">TEMPLATED</a>
</div>
</footer>
</body>
</html>
</code></pre>
<p>The obvious shortcoming of this application is: you are not able top see the templates (HTML) with [CTRL] + [U], which is bad for SEO.</p>
<p>Any constructive <strong>criticism</strong> and/or <strong>suggestions</strong> is welcomed. </p>
|
[] |
[
{
"body": "<p>The code looks decent, though it would be better if it had more code for handling errors. </p>\n\n<p>Indentation is very uniform throughout the code. There is some repeated code in the promise callbacks to some of the API endpoint requests in the controller functions (e.g. to set the <code>categories</code>, <code>posts</code> and <code>pagination</code> properties on <code>$scope</code>) that could be abstracted to a named function in order to DRY out that code. That function could also loop over the properties to set from <code>response.data</code> and assign them to <code>$scope</code>.</p>\n\n<p>Some <a href=\"/questions/tagged/ecmascript-6\" class=\"post-tag\" title=\"show questions tagged 'ecmascript-6'\" rel=\"tag\">ecmascript-6</a> features like arrow functions are used, and thus <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Property_definitions\" rel=\"nofollow noreferrer\">the shorthand property definition notation</a> could simplify object initialization - e.g. This block in the <code>PostCommentController</code> code:</p>\n\n<blockquote>\n<pre><code> $scope.newComment = {\n slug: slug,\n post_id: post_id,\n name: $scope.name,\n email: $scope.email,\n comment: $scope.comment\n };\n</code></pre>\n</blockquote>\n\n<p>could be simplified to:</p>\n\n<pre><code> $scope.newComment = {\n slug,\n post_id,\n name: $scope.name,\n email: $scope.email,\n comment: $scope.comment\n };\n</code></pre>\n\n<p>Also, in that function for the <code>PostCommentController</code> there is variable declared with <code>let</code>:</p>\n\n<blockquote>\n<pre><code> //Current post id\n let post_id = response.data.post.id;\n</code></pre>\n</blockquote>\n\n<p>This variable never gets reassigned, and to prevent accidental reassignment <code>const</code> can be used instead of <code>let</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T08:09:21.967",
"Id": "455219",
"Score": "0",
"body": "There is also an obvious shortcoming of this application: no server-side rendering (have a look at the **[page](http://code-love.tk/apiblog/metamorphosis-book-review)** source). Any suggestions for this issue? Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T22:37:21.083",
"Id": "455333",
"Score": "0",
"body": "Hmm... I did note there wasn't really any server-side code included in your post. I tried the URL in your comment but it shows a 404 message: \"_404 Not Found The resource requested could not be found on this server!_\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-27T05:52:05.113",
"Id": "455358",
"Score": "0",
"body": "Then please try **[this one](http://code-love.tk/apiblog/)**. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-29T20:40:49.267",
"Id": "467100",
"Score": "0",
"body": "Does this application qualify as a REST application?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T21:12:08.033",
"Id": "232969",
"ParentId": "232741",
"Score": "1"
}
},
{
"body": "<p>Regarding your comment about SEO:</p>\n<blockquote>\n<p>The obvious shortcoming of this application is: you are not able top see the templates (HTML) with [CTRL] + [U], which is bad for SEO.</p>\n</blockquote>\n<p>I did a search on the web for "angularJS SEO" and found quite a few results. The majority of posts on the topic suggest considering the use of pre-rendering services:</p>\n<blockquote>\n<p>Search engines still need to see the content and elements of the page in the source code to guarantee that it will be indexed correctly. One current solution is to consider using a pre-rendering platform, such as Prerender.io. This is middleware that will crawl your web page, execute all javascript files, and host a cached version of your Angular pages on their content delivery network (CDN). When a request is received from a search engine bot it will show them the cached version, while the non-bot visitor will be shown the Angular page.</p>\n<p>This may sound like <a href=\"https://en.wikipedia.org/wiki/Cloaking\" rel=\"nofollow noreferrer\">cloaking</a>, but Google has confirmed that it is <strong>not</strong>. It has also been stated by Google that as long as your intent is to improve user experience, and the content that’s available to the visitors is the same as what’s presented to Googlebot, you will not be penalized.<sup><a href=\"https://www.verticalmeasures.com/blog/search-optimization/overcoming-angular-seo-issues-associated-with-angularjs-framework/\" rel=\"nofollow noreferrer\">1</a></sup></p>\n</blockquote>\n<p>Another post suggests the following:</p>\n<blockquote>\n<p>There are three ways to do this.</p>\n<p><strong>The first one is to use a pre-rendering platform</strong>. Prerender.io, for example. Such a service would create cached versions of the content and render it in a form a Googlebot can crawl and index.</p>\n<p>Unfortunately, it could prove a short-lived solution. Google can depreciate it easily, leaving the site without an indexable solution again.</p>\n<p>The second solution is to modify SPA elements to render it as a hybrid between client- and server-side. <strong>Developers refer to this method as Initial Static Rendering</strong>.</p>\n<p>In this method, you can leave certain elements, critical for SEO – title, meta description, headers, somebody copy and so on – on the server-side. As a result, those elements appear in the source code and Google can crawl them.</p>\n<p>Unfortunately, once again, the solution might prove insufficient at times.</p>\n<p><strong>There is a viable option, however. It involves using Angular Universal extension</strong> to create static versions of pages to be rendered server-side Needless to say, these are indexable by Google fully, and there’s little chance that the technology will be depreciated any time soon.<sup><a href=\"https://www.seoclarity.net/blog/angularjs-seo\" rel=\"nofollow noreferrer\">2</a></sup></p>\n</blockquote>\n<p>So consider options like those.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T19:52:18.980",
"Id": "233290",
"ParentId": "232741",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "232969",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T14:05:12.977",
"Id": "232741",
"Score": "4",
"Tags": [
"javascript",
"html",
"ecmascript-6",
"angular.js",
"codeigniter"
],
"Title": "Blogging application with Codeigniter back-end and AngularJS front-end"
}
|
232741
|
<p>I have working code for this project, but I am now in need of some help to create a dynamic ordered list within Outlook from Excel.</p>
<p>I am trying to format comments that a user will enter into a UserForm in Excel and pass those comments into an ordered list via a collection; the issue I run into is that the number of comments can vary and I need to account for that when it comes to setting up the ordered list. I know I cannot create dynamic variables, so right now I am stuck on how to loop through the collection and adjust the size of the ordered list dynamically.</p>
<p>Below is the code that is working outside of the fact that the ordered list is not dynamic. Im wondering if maybe passing that Collection into a Class Module would be beneficial, but I am not really proficient with those yet. Please note that <code>Option Explicit</code> is defined in this module.</p>
<pre><code>Dim strComment As String, commentColl As Collection
Dim arr As Variant
strComment = SheetData.Range("Notes_For_Doc_Reviewer")
arr = Split(strComment, ",")
Set commentColl = New Collection
Dim a
For Each a In arr
commentColl.Add Trim(a)
Next a
'Dim x As Variant, i As Long
'For Each x In commentColl
' Debug.Print CStr(x)
'Next x
Count = commentColl.Count
Application.ScreenUpdating = False
Application.DisplayAlerts = False
ZackEmail = "ZackE@nothing.com"
currDir = MLAChecklist.path
hyperlink = "<a href=""" & Replace(currDir, " ", "%20") & """>" & currDir & "</a>"
strBody = "<BODY style=font-size:11pt;font-family:Calibri>Hello Zack," & _
"<p>Please complete the closing document review for the following file:" & "&nbsp" & "&nbsp" & hyperlink & "<br><br>" & vbCrLf & _
"Items to make note of in the file." & _
"<ol>" & _
"<li>" & commentColl(1) & "</li>" & _
"<li>" & commentColl(2) & "</li>" & _
"<li>" & commentColl(3) & "</li>" & _
"<li>" & commentColl(4) & "</li>" & _
"<li>" & commentColl(5) & "</li>" & _
"</ol>" & _
"</p></BODY>"
</code></pre>
<p><a href="https://i.stack.imgur.com/LZRS3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LZRS3.png" alt="Locals Window for Items in Collection"></a></p>
<p><strong>EDIT: Output of <code>getCheckListHTML</code> per request</strong></p>
<pre><code><html>
<body style=font-size:11pt;font-family:Calibri>
Hello Zack,
<p>Please complete the closing document review for the following file:
&nbsp&nbsp
<a href="Z:\Projects\Excel%20Projects\MLA%20UserForm%20Checklist">Z:\Projects\Excel Projects\MLA UserForm Checklist</a>
<br><br>
Items to make note of in the file.
<ol>
<li>Test run</li>
<li>items list</li>
<li>run through things</li>
<li>test number</li>
<li>blah blah<li>
</ol>
<br>
Thank You,
</p>
</body>
</html>
</code></pre>
<p><a href="https://i.stack.imgur.com/HkIqE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HkIqE.png" alt="OUtlook Body Output"></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T14:41:56.603",
"Id": "454625",
"Score": "0",
"body": "You should include the mechanism that creates `arr`. Is `arr` an 1 dimensional array?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T14:47:47.597",
"Id": "454628",
"Score": "0",
"body": "correct, it is a dynamic one dimensional array that is being stored in a collection."
}
] |
[
{
"body": "<p>There is no reason to convert <code>arr</code> to a collection. <code>Join()</code> can quickly build a tag list from a 1 Dimensional array. The trick is to have <code>Join()</code> insert a closing tag + open tag between each element.</p>\n\n<blockquote>\n<pre><code>\"<li>\" & Join(arr, \"</li><li>\") & \"</li>\"\n</code></pre>\n</blockquote>\n\n<h2>Join Demo</h2>\n\n<pre><code>Dim arr As Variant\nDim n As Long\nReDim arr(6)\nFor n = 1 To 7\n arr(n - 1) = WeekdayName(n)\nNext\n\nDebug.Print \"<li>\" & Join(arr, \"</li><li>\") & \"</li>\"\nDebug.Print \"<li>\" & Join(arr, \"</li>\" & vbNewLine & \"<li>\") & \"</li>\"\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/TFKvR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/TFKvR.png\" alt=\"Immediate Window Results\"></a></p>\n\n<p>You could also avoid creating the array in the first using the same tring to replace the commas with a close tag + an open tag:</p>\n\n<p><a href=\"https://i.stack.imgur.com/eTR0q.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/eTR0q.png\" alt=\"Immediate Window Results\"></a></p>\n\n<p>Your code is building a hyperlink, filling an ordered list, and creating the message htmlBody and will probably do several other tasks before it is complete. There is no way to test any single process without running the entire code. The fewer tasks that a method performs the easier it is to modify and debug.</p>\n\n<p><a href=\"https://i.stack.imgur.com/5Jc5L.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/5Jc5L.png\" alt=\"Immediate Window Results\"></a></p>\n\n<p>Notice how easy it was to test my Refactored Code in the immediate window.</p>\n\n<h2>Refactored Code</h2>\n\n<p>Note: I find that using an ArrayList is the easiest way to create and modify dynamic html.</p>\n\n<pre><code>Function getCheckListItems() As String\n getCheckListItems = \"<li>\" & Replace(SheetData.Range(\"Notes_For_Doc_Reviewer\").Value, \",\", \"</li>\" & vbNewLine & \"<li>\") & \"</li>\"\nEnd Function\n\nFunction getChecklistHTML(HyperlinkTag As String, CheckListItems As String) As String\n Const Delimiter As String = vbNewLine\n Dim list As Object\n Set list = CreateObject(\"System.Collections.ArrayList\")\n list.Add \"<html>\"\n list.Add \"<body style=font-size:11pt;font-family:Calibri>\"\n list.Add \"Hello Zack\"\n list.Add \"<p>Please complete the closing document review for the following file:\"\n list.Add \"&nbsp&nbsp\"\n list.Add HyperlinkTag\n list.Add \"<br><br>\"\n list.Add \"Items to make note of in the file.\"\n list.Add \"<ol>\"\n list.Add CheckListItems\n list.Add \"</ol>\"\n list.Add \"</body>\"\n list.Add \"</html>\"\n\n getChecklistHTML = Join(list.ToArray, Delimiter)\n\nEnd Function\n\nFunction getCurrentPathHyperlink(Wb As Workbook)\n Const DefaultLink As String = \"<a href='@currDir'>@currDir</a>\"\n\n Dim currDir As String\n currDir = Replace(Wb.Path, \" \", \"%20\")\n\n getCurrentPathHyperlink = Replace(DefaultLink, \"@currDir\", currDir)\nEnd Function\n</code></pre>\n\n<h2>Edit:</h2>\n\n<p>My original post was using an open tag instead of a closing tag in <code>getCheckListItems()</code>. Many thanks to Ryan Wildry!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T16:22:09.190",
"Id": "454644",
"Score": "0",
"body": "Thank you. I still have a lot to learn about programming in VBA, but I really appreciate your time. This works amazingly, but it does add an extra `<li></li>` in the body of the email that is blank. Lets say I only have 5 items to list it will list a blank 6th item."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T16:28:14.600",
"Id": "454645",
"Score": "0",
"body": "Does `SheetData.Range(\"Notes_For_Doc_Reviewer\").Value` have an extra comma in it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T16:30:04.420",
"Id": "454646",
"Score": "0",
"body": "No, it only has 4 commas in it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T16:40:12.603",
"Id": "454649",
"Score": "0",
"body": "Very strange. Did you examine the html in the Immediate Window?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T16:44:20.370",
"Id": "454651",
"Score": "0",
"body": "yes i did and it only shows the 5 items. Im wondering if its because of `getChecklistHTML = Join(list.ToArray, Delimiter)` adding in a `vbNewLine` automatically, but whats strange is that when I look at `getChecklistHTML` in the immediate window it only has the 5 items in the list."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T16:51:01.080",
"Id": "454653",
"Score": "0",
"body": "The extra `vbNewLine` does not add any extra tags. You can change `vbNewLine` to `vbNullString` to test it.. What is the output of `getCheckListItems()`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T16:52:46.847",
"Id": "454655",
"Score": "0",
"body": "The output of `getCheckListItems()` is just the 5 items as expected."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T16:59:58.327",
"Id": "454657",
"Score": "0",
"body": "Can you link me the html `getChecklistHTML` output?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T17:05:07.930",
"Id": "454658",
"Score": "2",
"body": "`getCurrentPathHyperlink` should have a strongly typed return value. Also, each function should have an explicit scope too. Also, depending on the size of the HTML you need to create, writing it all in code may become harder to maintain. If the HTML grows too much larger, I find it easier to keep an HTML fragment saved to named range someplace with placeholder values e.g. `{0}` or similar, then simply replace in the string. Still, a good overall approach. +1 for using Join."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T17:07:49.270",
"Id": "454660",
"Score": "0",
"body": "@TinMan not sure what you mean by link the output to you. I can add the output as part of the question if that would help?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T17:08:27.490",
"Id": "454662",
"Score": "0",
"body": "@ZackE that will work"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T17:11:47.753",
"Id": "454663",
"Score": "0",
"body": "@TinMan added. It doesnt make any sense on why Outlook is adding that additional list item in the body of the email. Added a picture of that too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T17:18:18.187",
"Id": "454665",
"Score": "0",
"body": "The last `<li>` isn't closed. There is another `<li>` at the end, which is creating the new item."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T17:19:15.897",
"Id": "454666",
"Score": "0",
"body": "@RyanWildry I agree with everything that you said. For larger documents I store the base document in Shapes or text-boxes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T17:20:00.333",
"Id": "454667",
"Score": "0",
"body": "@RyanWildry you're are a genius!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T17:21:23.507",
"Id": "454668",
"Score": "0",
"body": "@RyanWildry i see it now too. Thanks for the extra set of eyes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T17:26:43.560",
"Id": "454669",
"Score": "0",
"body": "@TinMan I wouldn't go that far! Spent far too much time looking at HTML than I care to admit :-P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T17:30:03.017",
"Id": "454670",
"Score": "0",
"body": "@RyanWildry I've spent more time looking at code and html with my eyes glazed over than I care to admit. :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T17:39:58.273",
"Id": "454672",
"Score": "1",
"body": "Thank you both for your assistance. I learned a lot with this one."
}
],
"meta_data": {
"CommentCount": "19",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T15:53:33.103",
"Id": "232748",
"ParentId": "232742",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "232748",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T14:14:29.477",
"Id": "232742",
"Score": "3",
"Tags": [
"vba",
"excel"
],
"Title": "Dynamically create ordered list in outlook from Excel"
}
|
232742
|
<p>I'm a beginner in Java, and this is the first time I have written a program from scratch without a guide explaining how and where to create classes etc. Please review my code to see whether the program has been written in a logical way.</p>
<p>The program is a very basic FruitMachine. The user clicks on "spin", and three cards are drawn. Depending on what these 3 cards are the user either wins or loses points. The game continues until a certain threshold is met. </p>
<p><strong>FruitMachine Class</strong> - Main class, creates a UserInterFaceFrame</p>
<pre><code> public class FruitMachine {
public static void main(String[] args) {
UserInterfaceFrame userInterface = new UserInterfaceFrame("Fruitmachine");
}
}
</code></pre>
<p><strong>GameLogic class</strong> - Controls the functioning of the game </p>
<pre><code>import java.beans.PropertyChangeSupport;
import java.util.Random;
public class GameLogic {
private String[] cards;
private String[] drawnCards;
private int balance;
public GameLogic() {
cards = new String[]{"Ace", "King", "Queen", "Jack", "Joker"};
drawnCards = new String[3];
this.balance = 100;
}
public String[] getCards() {
return cards;
}
public int getBalance() {
return balance;
}
public String getDrawnCardAtX(int x) {
return drawnCards[x];
}
public void setBalance(int newBalance) {
balance = newBalance;
}
public String spin() {
Random random = new Random();
int count = 0;
for (int i = 0; i < 3; i++) {
drawnCards[i] = cards[random.nextInt(cards.length)];
System.out.println(drawnCards[i]);
if (drawnCards[i].equals("Joker")) {
balance -= 25;
count++;
}
}
if (count > 1) {
return count + " jokers: you lose " + (25 * count) + " points";
}
if (count != 0) {
return count + " joker: you lose " + (25 * count) + " points";
}
if (drawnCards[0].equals(drawnCards[1]) && drawnCards[1].equals(drawnCards[2])) {
balance += 50;
return "Three of a kind - you win 50 points";
} else if (drawnCards[0].equals(drawnCards[1]) || drawnCards[0].equals(drawnCards[2])
|| drawnCards[1].equals(drawnCards[2])) {
balance += 20;
return "Two of a kind - you win 20 points";
}
return null;
}
}
</code></pre>
<p><strong>UserInterFace class</strong> - Creates a JFrame and fills it with JPanels for the user interface. </p>
<pre><code>import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class UserInterfaceFrame extends JFrame implements ActionListener {
private GameLogic gamelogic;
;
public UserInterfaceFrame(String title) {
super(title);
setSize(600, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setLayout(new GridLayout(2, 0));
this.gamelogic = new GameLogic();
JPanel labelsBorder = new JPanel();
labelsBorder.setBorder(BorderFactory.createLoweredBevelBorder());
JPanel labels = new JPanel();
labels.setLayout(new BoxLayout(labels, BoxLayout.Y_AXIS));
DataLabel balanceLabel = new DataLabel("Balance is " + gamelogic.getBalance());
labels.add(balanceLabel);
DataLabel cards = new DataLabel("Welcome");
labels.add(cards);
DataLabel winLose = new DataLabel("");
labels.add(winLose);
labelsBorder.add(labels);
JPanel lowerFrame = new JPanel();
lowerFrame.setLayout(new GridLayout(0, 2));
JPanel lowerRightFrame = new JPanel();
lowerRightFrame.setLayout(new GridLayout(2, 0));
lowerRightFrame.setBorder(BorderFactory.createEmptyBorder(60, 60, 60, 60));
JPanel lowerLeftFrame = new JPanel();
lowerLeftFrame.setLayout(new GridLayout(0, 3, 30, 0));
lowerLeftFrame.setBorder(BorderFactory.createEmptyBorder(50, 50, 50, 50));
JPanel card1 = new CardPanel();
JLabel card1Label = new JLabel("", SwingConstants.CENTER);
card1.add(card1Label);
JPanel card2 = new CardPanel();
JLabel card2Label = new JLabel("", SwingConstants.CENTER);
card2.add(card2Label);
JPanel card3 = new CardPanel();
JLabel card3Label = new JLabel("", SwingConstants.CENTER);
card3.add(card3Label);
lowerLeftFrame.add(card1);
lowerLeftFrame.add(card2);
lowerLeftFrame.add(card3);
JButton spin = new JButton("Spin");
spin.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cards.setText(gamelogic.spin());
balanceLabel.setText("Balance is " + gamelogic.getBalance());
card1Label.setText(gamelogic.getDrawnCardAtX(0));
card2Label.setText(gamelogic.getDrawnCardAtX(1));
card3Label.setText(gamelogic.getDrawnCardAtX(2));
}
});
JButton reset = new JButton("New game");
reset.setEnabled(false);
reset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
gamelogic.setBalance(100);
reset.setEnabled(false);
spin.setEnabled(true);
winLose.setText("");
balanceLabel.setText("Balance is: " + gamelogic.getBalance());
}
});
balanceLabel.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent event) {
if (gamelogic.getBalance() < 0) {
winLose.setText("You lose!");
reset.setEnabled(true);
spin.setEnabled(false);
}
if (gamelogic.getBalance() > 150) {
winLose.setText("You win!");
reset.setEnabled(true);
spin.setEnabled(false);
}
}
});
lowerRightFrame.add(spin);
lowerRightFrame.add(reset);
lowerFrame.add(lowerLeftFrame);
lowerFrame.add(lowerRightFrame);
add(labelsBorder);
add(lowerFrame);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
</code></pre>
<p><strong>DataLabel Class</strong> - Extends JPanel to overwrite some of the default behaviour</p>
<pre><code> import javax.swing.BorderFactory;
import javax.swing.JLabel;
public class DataLabel extends JLabel {
public DataLabel(String setString) {
super(setString);
setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
}
}
</code></pre>
<p><strong>Card Panel Class</strong> </p>
<pre><code>import java.awt.Color;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
public class CardPanel extends JPanel {
public CardPanel() {
setBorder(BorderFactory.createRaisedBevelBorder()); // Creates a raised border around the edge of the cards to make them "pop".
setBackground(Color.yellow); // Sets the colour of the cards to yellow
setLayout(new GridBagLayout()); // GridBagLayout with out any constraints will always centre a JLabel.
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T19:27:21.557",
"Id": "454683",
"Score": "2",
"body": "Hello sepalous, could you maybe explain in more detail what your code does?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T22:31:00.500",
"Id": "454693",
"Score": "2",
"body": "Please [edit] your post and make the title describe/summarize the purpose of the code, and take a few minutes to better describe the components and their purpose. Thanks!"
}
] |
[
{
"body": "<p><strong>'Card' could be an ENUM.</strong>\nThis should also be a static final class variable, for example:</p>\n\n<pre><code>private static final Card[] CARDS = new Card[]{Card.ACE, Card.KING, Card.QUEEN, Card.JACK, Card.JOKER};\n</code></pre>\n\n<p><strong>Avoid magic numbers</strong>, the '3' here should be declared, same for the starting balance</p>\n\n<pre><code>private static final int NUMBER_OF_CARDS_DRAWN = 3;\nprivate static final int STARTING_BALANCE = 100;\n</code></pre>\n\n<p>Here you use the magic number '3' again, which should be changed to variable</p>\n\n<pre><code>// Changed '3' to 'NUMBER_OF_CARDS_DRAWN'\ndrawnCards = new String[NUMBER_OF_CARDS_DRAWN];\n...\nfor (int i = 0; i < NUMBER_OF_CARDS_DRAWN; i++) {\n</code></pre>\n\n<p>This does not make sense. Count is never decremented so the second if statement will never be reached. You can remove it.</p>\n\n<pre><code>if (count > 1) {\n return count + \" jokers: you lose \" + (25 * count) + \" points\";\n}\n// You can remove this.\nif (count != 0) {\n return count + \" joker: you lose \" + (25 * count) + \" points\";\n}\n</code></pre>\n\n<p>Remove magic numbers '25, '50', '20'. <strong>Use static variables</strong></p>\n\n<p><strong>Avoid having game logic inside your UI.</strong></p>\n\n<p>The number of cards should be retrieved from the GameLogic, then add that number of cards.</p>\n\n<pre><code>// Needs to be refactored into a for-loop, given the NumberOfCards is a variable.\nlowerLeftFrame.add(card1);\nlowerLeftFrame.add(card2);\nlowerLeftFrame.add(card3);\n</code></pre>\n\n<p>Same here, if you have an ArrayList of labels, you'll need to refactor this into a for-loop.</p>\n\n<pre><code>// Needs to be refactored into a for-loop, given the NumberOfCards is a variable.\ncard1Label.setText(gamelogic.getDrawnCardAtX(0));\ncard2Label.setText(gamelogic.getDrawnCardAtX(1));\ncard3Label.setText(gamelogic.getDrawnCardAtX(2));\n</code></pre>\n\n<p>This should not be in the UI. It's definetly GameLogic. Consider moving to constructor of GameLogic</p>\n\n<pre><code>// Doesn't belong in UI. Consider putting it in the constructor of GameLogic\ngamelogic.setBalance(100);\nreset.setEnabled(false);\nspin.setEnabled(true);\n</code></pre>\n\n<p>This is very much GameLogic and does not belong in the UI</p>\n\n<pre><code>// This is very much GameLogic, doesn't belong in UI\nif (gamelogic.getBalance() < 0) {\n winLose.setText(\"You lose!\");\n reset.setEnabled(true);\n spin.setEnabled(false);\n}\nif (gamelogic.getBalance() > 150) {\n winLose.setText(\"You win!\");\n reset.setEnabled(true);\n spin.setEnabled(false);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-01T16:54:21.503",
"Id": "233231",
"ParentId": "232750",
"Score": "3"
}
},
{
"body": "<p>Let's show how to split the model up and remove all the UI elements.</p>\n\n<p>First of all, we want to play a card game, so let's define the cards:</p>\n\n<pre><code>public enum Card {\n ACE, KING, QUEEN, JACK, JOKER;\n}\n</code></pre>\n\n<hr>\n\n<p>We have some kind of account with points:</p>\n\n<pre><code>\nimport java.util.function.Predicate;\n\npublic final class Account {\n private int balance;\n\n public Account(int startingBalance) {\n this.balance = startingBalance;\n }\n\n public int getBalance() {\n return balance;\n }\n\n public void withdraw(int loss) {\n balance -= loss;\n }\n\n public void deposit(int gain) {\n balance += gain;\n }\n\n public boolean test(Predicate<Integer> test) {\n return test.test(balance);\n }\n\n @Override\n public String toString() {\n return String.format(\"Account has %d points\", balance);\n }\n}\n</code></pre>\n\n<p>So that god rid of that part of the equations, we don't want anything in the machine description itself if we can separate it out. Note that we don't supply a \"setter\".</p>\n\n<hr>\n\n<p>Now we have multiple things resulting from a single spin. Somehow we must present them in the GUI, but without directly calling the GUI. Tricky? Not that tricky, just use a <em>listener</em> interface that the GUI classes can implement:</p>\n\n<pre><code>import java.util.List;\n\npublic interface SpinListener {\n void showCardSpin(List<Card> cards);\n void showResult(String result);\n}\n</code></pre>\n\n<hr>\n\n<p>Fine, now let's implement the game:</p>\n\n<pre><code>import java.security.SecureRandom;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.EnumSet;\nimport java.util.List;\nimport java.util.Random;\n\npublic final class FruityMacFruitMachine {\n // in the end just a list of all the cards as an unmodifiable constant value\n private final static List<Card> CARDS =\n Collections.unmodifiableList(new ArrayList<Card>(EnumSet.allOf(Card.class)));\n private static final int CARD_COUNT = 3;\n\n private static final int LOSS_PER_JOKER = 25;\n private static final int WINNINGS_FOR_THREE_OF_A_KIND = 50;\n private static final int WINNINGS_FOR_TWO_OF_A_KIND = 20;\n\n // I'm a security buff, secure randoms are *more* random than Random\n private final Random random = new SecureRandom();\n private final Account account;\n private SpinListener listener;\n\n // we create the machine with an account and a listener for the results\n public FruityMacFruitMachine(Account account, SpinListener listener) {\n this.account = account;\n this.listener = listener;\n }\n\n // create a card spin, clearly a separate method\n private List<Card> cardSpin(int amountOfCards) {\n List<Card> drawnCards = new ArrayList<Card>(amountOfCards);\n for (int i = 0; i < amountOfCards; i++) {\n drawnCards.add(CARDS.get(random.nextInt(CARDS.size())));\n }\n return drawnCards;\n }\n\n // the spin and all the followup moves\n public void spin() {\n // take a spin\n List<Card> draw = cardSpin(CARD_COUNT);\n // the GUI should not change the draw, right?\n listener.showCardSpin(Collections.unmodifiableList(draw));\n\n // check for jokers by iterating over the cards,\n // filtering out the jokers and then counting them\n int jokers = (int) draw.stream().filter(card -> card == Card.JOKER).count();\n if (jokers >= 1) {\n // we reuse the loss, no need to calculate twice!\n int loss = LOSS_PER_JOKER * jokers;\n account.withdraw(loss);\n listener.showResult(String.format(\"%d joker(s): you lose %d points\", jokers, loss));\n return;\n }\n\n // we now count the distinct cards\n int distinctCards = (int) draw.stream().distinct().count();\n\n // all cards are distinct -> no luck\n if (distinctCards == CARD_COUNT) {\n listener.showResult(\"No luck, draw again\");\n return;\n }\n\n // we just declare the variables in advance\n // and then initialize them in the if / else code blocks\n int gain;\n String result;\n if (distinctCards == 1) {\n gain = WINNINGS_FOR_THREE_OF_A_KIND;\n result = \"Three of a kind\";\n } else if (distinctCards == 2) {\n gain = WINNINGS_FOR_TWO_OF_A_KIND;\n result = \"Two of a kind\";\n } else {\n throw new IllegalStateException();\n }\n account.deposit(gain);\n listener.showResult(String.format(\"%s: you win %d points\", result, gain));\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Now here is a console implementation of the game:</p>\n\n<pre><code>\npublic static void main(String[] args) {\n Account account = new Account(100);\n FruityMacFruitMachine game = new FruityMacFruitMachine(account, new SpinListener() {\n @Override\n public void showCardSpin(List<Card> cards) {\n System.out.println(cards);\n }\n\n @Override\n public void showResult(String result) {\n System.out.println(result);\n }\n });\n while (account.test(x -> x >= 50 && x < 200)) {\n game.spin();\n System.out.println(account);\n System.out.println();\n }\n System.out.println(\"Thank you for playing, come again\");\n}\n\n</code></pre>\n\n<p>Up to you go create a GUI around it by implementing the listener and some model / view for the <code>Account</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T01:16:26.087",
"Id": "238075",
"ParentId": "232750",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T16:17:38.803",
"Id": "232750",
"Score": "1",
"Tags": [
"java",
"game",
"swing"
],
"Title": "Fruit machine game"
}
|
232750
|
<p>For my programming class, we have been tasked with creating a Sudoku solver; the first step of the project was to create a program which would display the game board based on input provided by the user. </p>
<pre class="lang-py prettyprint-override"><code>import math #To be used later
def board_filler():
"""Creates the sudoku board from user input"""
board = [[], [], [], [], [], [], [], [], [], [], []]
for x in enumerate(board):
#If it is one of the rows that have lines, add them
if ((x[0] + 1) % 4) == 0:
for y in range(11):
board[x[0]].append("-")
else:
for y in range(11):
#If it is a column that has lines in it, add them
if ((y + 1) % 4) == 0:
board[x[0]].append("|")
else:
#Repeat until an inout has been entered
z = True
while z:
z = False
if x[0] > 7:
xRead = x[0] - 1
elif x[0] > 3:
xRead = x[0]
else:
xRead = x[0] + 1
if y > 7:
yRead = y - 1
elif y > 3:
yRead = y
else:
yRead = y + 1
number = input("Please enter a number for the square in column %s and in row %s, if there is no number, just hit enter:" %(xRead, yRead))
#Trys to make it a number, then checks to see if it is a number 1 to 9
try:
number = int(number)
if number > 9 or number < 1:
z = True
print("Please enter a number between 1 and 9")
else:
board[x[0]].append(number)
#If it is not a number, check if its empty
except (TypeError, ValueError):
#If its empty, add a space
if len(number) == 0:
board[x[0]].append(" ")
#If not ask for a number
else:
z = True
print("Please enter a number")
return board
def board_printer(board):
"""Prints the sudoku board"""
#Turns board into str to make the .join work
for x in enumerate(board):
for y in enumerate(board):
board[x[0]][y[0]] = str(board[x[0]][y[0]])
#Prints the board
for x in enumerate(board):
print(" ".join(board[x[0]]))
board_printer(board_filler())
</code></pre>
<p>A few notes for review:</p>
<ul>
<li>The <code>board_filler</code> function feels quite bloated.</li>
<li>I don't like the way I implemented <code>xRead</code> and <code>yRead</code>.</li>
</ul>
<p>How can I improve my code?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T17:47:12.557",
"Id": "454674",
"Score": "2",
"body": "Poor user of this program, he/she would need to enter input number/press `Enter` **80** times"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T18:12:53.657",
"Id": "454680",
"Score": "0",
"body": "@RomanPerekhrest Yeah! I can't even test the code properly"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T19:49:13.077",
"Id": "454685",
"Score": "0",
"body": "@K00lman, can you please explain why and how you are using `xRead` and `yRead`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T20:41:33.687",
"Id": "454690",
"Score": "0",
"body": "@Srivaths I am using them to make it so that the input does not skip numbers and prevent it from going to 11. Removing it makes it count 1, 2, 3, 5, 6, 7, 9, 10, 11 instead of the 1, 2, 3, 4, 5, 6, 7, 8, 9 I want."
}
] |
[
{
"body": "<p>First of all, let the code speak! Don't unnecessarily add comments unless they are explaining a really complicated piece of code.</p>\n\n<h2>Basic definitions:</h2>\n\n<p>A magic number is defined to be:</p>\n\n<blockquote>\n <p>Unique values with unexplained meaning or multiple occurrences which could (preferably) be replaced with named constants</p>\n</blockquote>\n\n<p>Can you find the magic numbers in your code?<br>\nYes that's right, the culprits are <code>11</code> and <code>4</code>.</p>\n\n<p>Let's just define variables for those!</p>\n\n<pre><code>ROWS = 11\nCOLS = 11\nGRID_ROWS = 4\nGRID_COLS = 4\n</code></pre>\n\n<p>Next, let's replace every magic number with the appropriate variable!</p>\n\n<h1>Making the code shorter!</h1>\n\n<h2>Function <code>board_printer</code></h2>\n\n<p>Why use <code>enumerate</code>? Why make everything a <code>str</code>?</p>\n\n<p>Your whole function can just be rewritten as the following:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def board_printer(board):\n \"\"\"Prints the sudoku board\"\"\"\n\n for row in board:\n print(*row)\n</code></pre>\n\n<h2>Function <code>board_filler</code></h2>\n\n<p>You don't need to use <code>for x in enumerate(board)</code> at all!<br>\nJust use <code>for x in range(ROWS)</code> and change every instance of <code>x[0]</code> to <code>x</code> accordingly</p>\n\n<hr>\n\n<p>Instead of </p>\n\n<pre><code>if ((x[0] + 1) % GRID_ROWS) == 0:\n for y in range(11):\n board[x].append(\"-\")\n</code></pre>\n\n<p>Use</p>\n\n<pre><code>if ((x[0] + 1) % GRID_ROWS) == 0:\n board[x] = [\"-\"] * COLS\n</code></pre>\n\n<hr>\n\n<p>Use formatting! </p>\n\n<p>for taking input of number, use <code>number = input(\"Please enter a number for the square in row {xRead} and in column {yRead} (hit enter for no number): \")</code> instead of using <code>%s</code></p>\n\n<hr>\n\n<p>Why use a dummy variable <code>z</code>?</p>\n\n<p>Just do:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>while True:\n number = input(\"Please enter a number for the square in column {x[0] + 1} and in row {y + 1} (hit enter for no number): \")\n\n try:\n number = int(number)\n\n if number > 9 or number < 1:\n raise ValueError\n else:\n board[x].append(number)\n\n break\n\n except (TypeError, ValueError):\n if not number:\n board[x].append(\" \")\n else:\n print(\"Please enter an integer between 1 and 9\")\n</code></pre>\n\n<p>Essentially, it tries to take an input, check if the value is an <strong><em>integer between 1 and 9</em></strong>, else raises an exception. If the number was indeed valid, it makes it to the end of the <code>try</code> statement, which causes the loop to break</p>\n\n<h2>Misc</h2>\n\n<ul>\n<li><p>Run <code>board_printer(board_filler())</code> inside <code>if __name__ == __main__:</code>. This causes <code>board_printer(board_filler())</code> not to run if it was imported from another module.</p></li>\n<li><p>Try using <code>list(map(int, input(f'Enter {COLS - (COLS // GRID_COLS)} space separated integers: ').split()))</code> for each row. It is tiring to fill every single cell by hand! So ask input for a whole row. It's your personal preference though!</p></li>\n</ul>\n\n<p>Hope this helps!</p>\n\n<h1>EDIT:</h1>\n\n<p><strong>This part is to solely dedicated to removing <code>xRead</code> and <code>yRead</code> and is not related to the above improvements</strong></p>\n\n<p>First we have to change<br>\n<code>ROWS = COLS = 11</code> to <code>ROWS = COLS = 9</code> and\n<code>GRID_ROWS = GRID_COLS = 4</code> to <code>GRID_ROWS = GRID_COLS = 3</code></p>\n\n<p><strong>Do not</strong> append <code>-</code> or <code>|</code> to board at all!</p>\n\n<p>Just remove all statements that append <code>-</code> or <code>|</code> and also remove <code>xRead</code> and <code>yRead</code>. Now, the board would look like a sudoku board without <code>-</code> or <code>|</code></p>\n\n<hr>\n\n<p>In the <code>board_filler</code> use</p>\n\n<pre><code>def board_printer(board):\n \"\"\"Prints the sudoku board\"\"\"\n\n for row in range(ROWS):\n s = ''\n\n for col in range(COLS):\n s += str(board[row][col]) + ' '\n\n if not (col + 1) % GRID_COLS:\n s += '| '\n\n print(s)\n\n if not (row + 1) % GRID_ROWS:\n print('-' * len(s))\n</code></pre>\n\n<p>This will print <code>-</code> or <code>|</code> according to the row or column!</p>\n\n<hr>\n\n<h1>Final code including all above mentioned improvements</h1>\n\n<pre><code>\nROWS = COLS = 9\nGRID_ROWS = GRID_COLS = 3\n\ndef board_filler():\n \"\"\"Creates the sudoku board from user input\"\"\"\n\n board = [[] for _ in range(ROWS)]\n\n for x in range(ROWS):\n for y in range(COLS):\n while True:\n number = input(f\"Please enter an integer for the square in column {x + 1} and in row {y + 1} (hit enter for no number): \")\n\n try:\n number = int(number)\n\n if number > 9 or number < 1:\n raise ValueError\n else:\n board[x].append(number)\n\n break\n\n except (TypeError, ValueError):\n if not number:\n board[x].append(\" \")\n else:\n print(\"Please enter an integer between 1 and 9\")\n\n return board\n\ndef board_printer(board):\n \"\"\"Prints the sudoku board\"\"\"\n\n print()\n\n for row in range(ROWS):\n s = ''\n\n for col in range(COLS):\n s += str(board[row][col]) + ' '\n\n if not (col + 1) % GRID_COLS:\n s += '| '\n\n s = s[:-1] # Removes trailing space\n\n print(s)\n\n if not (row + 1) % GRID_ROWS:\n print('-' * len(s))\n\nif __name__ == '__main__':\n board_printer(board_filler())\n</code></pre>\n\n<p><strong>NOTE:</strong> <code>board_filler</code> doesn't look as bloated either! The code kills 2 birds with one stone!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T22:27:36.753",
"Id": "454692",
"Score": "0",
"body": "Very helpful, but I would just like to say it was a part of my project to put so many comments. Otherwise, I would have used less."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T05:23:52.880",
"Id": "454708",
"Score": "0",
"body": "If you want, you can add them back anytime! Also, I've updated my answer as per `I don't like the way I implemented xRead and yRead.` too! Take a look at the `EDIT` section"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T15:58:01.510",
"Id": "455114",
"Score": "0",
"body": "I just tried all of the changes you said in the idle editor, and the {} don't work. What am I missing? Also, you forgot to include the break after you hit enter and enter the empty space."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T16:16:31.560",
"Id": "455122",
"Score": "1",
"body": "Yes, I had made a minor bug and forgot to update the code. I've updated my code accordingly. Also the `f{something}` (Notice the `f`) just means [formatting](https://realpython.com/python-f-strings/)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T19:25:19.540",
"Id": "232758",
"ParentId": "232753",
"Score": "6"
}
},
{
"body": "<p>I'm going to take a pass through <code>board_filler</code> as if I were cleaning up my own code, take notes on everything I changed, and share the final result.</p>\n\n<ol>\n<li>Adding type hints so mypy will tell me if I mess up during any of this refactoring.</li>\n<li>Oh weird, my <code>board</code> isn't a list of list of <code>int</code>s like I thought, it's also got strings in it? I'll go ahead and add the typing, but I should come back to that because it feels like it might be a clue the data model is a little confused.</li>\n<li>Reassigning <code>number</code>(string) to <code>number</code>(int) is making mypy complain, so I'll just move that <code>input</code> inside the <code>int</code> cast for now and take a closer look later at whether that makes sense.</li>\n<li>No point using <code>enumerate</code> if I'm only interested in the index; I'll change it so I'm just iterating over the range of indices. Oh look, mypy helps me catch all the places I need to change <code>x[0]</code> to just <code>x</code>!</li>\n<li>Looks like we have the length of <code>board</code> hardcoded in a couple of places; I'm just going to change those to <code>len(board)</code> so that if we adjust <code>board</code> the rest of the code will just magically work.</li>\n<li>This <code>% 4</code> is troubling. Let's just define <code>GRID = 4</code> and use that.</li>\n<li>Wow, I'm not even sure what the rest of this code is doing. Let's see if cutting down the indentation and adding linebreaks between \"paragraphs\" helps make it easier to follow...</li>\n</ol>\n\n<p>At this point my code looks like:</p>\n\n<pre><code>from typing import List, Union\n\nGRID = 4 # draw a grid line every 4 rows/cols\n\ndef board_filler() -> List[List[Union[int, str]]]:\n \"\"\"Creates the sudoku board from user input\"\"\"\n board: List[List[Union[int, str]]] = [[], [], [], [], [], [], [], [], [], [], []]\n for x in range(len(board)):\n\n #If it is one of the rows that have lines, add them\n if ((x + 1) % GRID) == 0:\n for y in range(len(board)):\n board[x].append(\"-\")\n continue\n\n for y in range(len(board)):\n\n #If it is a column that has lines in it, add them\n if ((y + 1) % GRID) == 0:\n board[x].append(\"|\")\n continue\n\n #Repeat until an input has been entered\n z = True\n while z:\n z = False\n\n if x > 7:\n xRead = x - 1\n elif x > 3:\n xRead = x\n else:\n xRead = x + 1\n\n if y > 7:\n yRead = y - 1\n elif y > 3:\n yRead = y\n else:\n yRead = y + 1\n\n #Tries to make it a number, then checks to see if it is a number 1 to 9\n try:\n number = int(input(\n \"Please enter a number for the square in column %s and in row %s, if there is no number, just hit enter:\" \n % (xRead, yRead)\n ))\n if number > 9 or number < 1:\n z = True\n print(\"Please enter a number between 1 and 9\")\n else:\n board[x].append(number)\n #If it is not a number, check if its empty\n except (TypeError, ValueError):\n #If its empty, add a space\n if not number:\n board[x].append(\" \")\n #If not ask for a number\n else:\n z = True\n print(\"Please enter a number\")\n return board\n</code></pre>\n\n<p>It is now apparent to me that a <em>huge</em> part of the complexity of this function is due to the fact that we're mixing our actual data (the numbers) with the display logistics (drawing the grid lines). That's going to be a continuous source of pain (what we call in the biz \"technical debt\"), especially if we plan to write code later that tries to actually solve the puzzle. What if we just took all that grid stuff out and let <code>board_filler</code> return a <code>List[List[int]]</code>?</p>\n\n<p>It turns out that that makes the code a LOT simpler, and now all the complexity of <code>board_filler</code> is very clearly in getting the user input. Let's just break that out into its own function...</p>\n\n<pre><code>def get_number_for_square(x: int, y: int, max: int) -> Optional[int]:\n \"\"\"Prompt the user for a number between 1 and max until they give\n us one or just give us a blank line (in which case return None).\"\"\"\n choice = input(\n (\"Please enter a number for the square in column %s and in row %s\" +\n \"; if there is no number, just hit enter: \") % (x, y)\n )\n if len(choice) == 0:\n return None\n try:\n number = int(choice)\n assert 1 <= number <= max\n return number\n except:\n print(\"Please enter a number between 1 and %d.\" % max)\n return get_number_for_square(x, y, max)\n</code></pre>\n\n<p>Between that and getting rid of the grid stuff, <code>board_filler</code> is suddenly quite a bit smaller. Using <code>len(board)</code> everywhere is starting to bother me; since we're constructing the board inside this function, let's just take the size as a parameter and construct the board to match the size, rather than building it the other way around.</p>\n\n<pre><code>def board_filler(size: int = 9) -> List[List[Optional[int]]]:\n \"\"\"Creates the sudoku board from user input\"\"\"\n board: List[List[Optional[int]]] = []\n for x in range(size):\n board.append([])\n for y in range(size):\n board[x].append(get_number_for_square(x, y, size))\n return board\n</code></pre>\n\n<p>Now all I need to do is replace the grid drawing logic that I chopped out. Since that has to do with how we're displaying the board, not the value of the board itself, it belongs in my <code>board_printer</code> function. As with the <code>size</code> magic number, let's make that a parameter, because why not:</p>\n\n<pre><code>def board_printer(board: List[List[Optional[int]]], grid_size: int = 3) -> None:\n \"\"\"Pretty-prints the board, with grid lines every grid_size squares.\"\"\"\n for y in range(len(board)):\n if y % grid_size == 0 and y > 0:\n print(\"-\" * (len(board) + (math.ceil(len(board) / grid_size)) - 1))\n for x in range(len(board)):\n if x == len(board) - 1:\n end = \"\\n\"\n elif (x + 1) % grid_size == 0:\n end = \"|\"\n else:\n end = \"\"\n print(board[y][x] if board[y][x] else \" \", end=end)\n</code></pre>\n\n<p>There are probably more graceful ways of doing that printing, but it's nice and flexible if we decide we want to change up how the grid is printed. At the end of it, I can still do:</p>\n\n<pre><code>board_printer(board_filler())\n</code></pre>\n\n<p>and I think it still does about what the original code did, but hopefully this version is easier to follow (and it's <em>much</em> more flexible now)!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T11:34:06.617",
"Id": "454738",
"Score": "0",
"body": "In `board_filler`, instead of using the bad habbit of `[]` + `for` + `append`, you could use `return [[get_number_for_square(x, y, size) for x in range(size)] for y in range(size)]`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T05:23:34.617",
"Id": "232773",
"ParentId": "232753",
"Score": "4"
}
},
{
"body": "<p><code>board_filler()</code> feels bloated, because it is trying to do 2 unrelated things: 1) building some of the graphics for displaying the board, and 2) getting input for the numbers in the board. These should be split into separate functions.</p>\n\n<p>Asking the user to enter 81 values or blank lines is a poor user experience. It would be easy to loose their place and enter the wrong data. Consider letting the user enter the data a row at a time, using a '-' for blank spaces in the game board (and ignore blanks in the input). All of these would be valid:</p>\n\n<pre><code>Enter row 1: --89-1---\nEnter row 2: 19- 2-- ---\nEnter row 3: - 5 - - 7 - - - 8\netc.\n</code></pre>\n\n<p>The code would look something like:</p>\n\n<pre><code>def get_board(nrows):\n print(\"Enter the grid one row at a time. Use '-' for blank spaces.\\n\")\n\n rows = []\n for n in range(nrows):\n row = input(f\"Enter row {n}: \")\n rows.append(row.replace(' ', '')\n\n return rows\n</code></pre>\n\n<p>A function like <code>board_filler()</code> could then take the list of strings returned by <code>get_board()</code> to fill up the sudoku grid. This separation of concerns (one function to get input and another to fill the grid) makes it easy to make changes. For example, <code>board_filler()</code> wouldn't care where the grid data came from as long as it was a list of strings. It could easily be function that read a grid from a file or scraped it from a web site. </p>\n\n<p>There isn't any reason to convert the numbers in the grid into int's. They aren't be used for their numerical value (they aren't being added or anything). They are just unique symbols. That way everything in the grid is a character.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T06:36:03.480",
"Id": "232776",
"ParentId": "232753",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "232758",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T17:16:17.237",
"Id": "232753",
"Score": "7",
"Tags": [
"python",
"beginner",
"python-3.x",
"sudoku"
],
"Title": "Displaying a Sudoku Board"
}
|
232753
|
<p>I was just trying Project Euler <a href="https://projecteuler.net/problem=50" rel="noreferrer">problem 50</a>.</p>
<blockquote>
<p>The prime 41, can be written as the sum of six consecutive primes: 41
= 2 + 3 + 5 + 7 + 11 + 13</p>
<p>This is the longest sum of consecutive primes that adds to a prime
below one-hundred.</p>
<p>The longest sum of consecutive primes below one-thousand that adds to
a prime, contains 21 terms, and is equal to 953.</p>
<p>Which prime, below one-million, can be written as the sum of the most
consecutive primes?</p>
</blockquote>
<p>Here's my code for the same in <strong>Python</strong>:</p>
<pre class="lang-py prettyprint-override"><code>LIMIT = 1000000
x = [1] * (LIMIT + 1)
x[0] = x[1] = 0
primes = []
length = 0
for i in range(2, LIMIT):
if x[i]:
primes.append(i)
length += 1
for j in range(i * i, LIMIT + 1, i):
x[j] = 0
s = 0
prev = -1
cnt = -1
for i in range(length):
s = 0
for j in range(i, length):
s += primes[j]
if s > LIMIT:
break
if x[s] and cnt < j - i + 1:
cnt = j - i + 1
prev = s
print(prev)
</code></pre>
<p>I just create a list of primes using Sieve of Eratosthenes. For each prime, I'm just finding all the consecutive primes and their sums to get the answer.</p>
<p>This currently takes about one second to run.</p>
<p>Is there a faster, better, and neater way to solve this?</p>
<p>Thank you for your help!</p>
<p><strong>EDIT:</strong></p>
<p>I see there are 2 votes to close my program as it <code>Lacks concrete context</code>. Can you please explain what I should do to add concrete context?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T22:01:44.607",
"Id": "454859",
"Score": "1",
"body": "Yeah, don't vote to close this question without an explanation. The context is crystal clear."
}
] |
[
{
"body": "<p>Often on project Euler, it is useful to solve a problem \"backwards\". What do I mean by this? Well, \"forwards\" would be to generate a list of primes, and check all consecutive sums for primality and length, a \"bottom up\" approach. This takes a very long time and is rather undirected. </p>\n\n<p>Because you're building <em>up</em> from the smallest length, you need to keep building your consecutive sums, even when you've found potential answers!</p>\n\n<hr>\n\n<p>A better solution would be to start with an ordered list of primes whose sum is below <code>10**6</code> (which can easily be generated with a sieve as you have done). Then, put them <em>all</em> together in a list and find the sum. Then, do the following:</p>\n\n<ul>\n<li>Remove a prime from the beginning</li>\n<li>Check the sum for primality</li>\n<li>Add it back and remove a prime from the end </li>\n<li>Check the sum for primality</li>\n<li>Remove both</li>\n<li>Check the sum for primality</li>\n<li>...</li>\n</ul>\n\n<p>This means as soon as you find a prime from those sums, you have guaranteed it is the largest, simply by working backwards.</p>\n\n<hr>\n\n<p>Now that you have the basic algorithm, you can start making efficiency improvements. Things like improving your initial sieve; or making optimisations to your python code using generators, fewer function calls etc.</p>\n\n<p>Finally, there are all sorts of great answers on the project Euler forums which you have access to if you submit a correct answer. It's always worth skimming them having completed a problem; there's always someone with a better way of doing it!</p>\n\n<hr>\n\n<h3>Pseudocode of example:</h3>\n\n<p>I'll show how this algorithm could be used to generate the answer 41 for the largest prime below 100 constructed from consecutive primes.</p>\n\n<p>Using a sieve, generate a list of primes, <code>p</code> whose sum is <code><= 100</code>: <code>p = [2, 3, 5, 7, 11, 13, 17, 19, 23]</code></p>\n\n<p>Remove the largest prime from the list and evaluate if the sum is prime:</p>\n\n<pre><code>p -> p = [2, 3, 5, 7, 11, 13, 17, 19]\nsum = 77\nis_prime(sum) >>> False\n</code></pre>\n\n<p>Add the largest prime (<code>23</code>) back to the list, remove the smallest prime (<code>2</code>) and try again:</p>\n\n<pre><code>p -> p = [3, 5, 7, 11, 13, 17, 19, 23]\nsum = 98\nis_prime(sum) >>> False\n</code></pre>\n\n<p>Add the smallest prime (<code>2</code>) back, then remove the <em>two</em> largest primes (<code>19, 23</code>):</p>\n\n<pre><code>p -> p = [2, 3, 5, 7, 11, 13, 17]\nsum = 58\nis_prime(sum) >>> False\n</code></pre>\n\n<p>Add back the largest prime, remove the smallest:</p>\n\n<pre><code>p -> p = [3, 5, 7, 11, 13, 17, 19]\nsum = 75\nis_prime(sum) >>> False\n</code></pre>\n\n<p>Add back the smallest, remove the two largest:</p>\n\n<pre><code>p -> p = [2, 3, 5, 7, 11, 13]\nsum = 41\nis_prime(sum) >>> True\n# Success!\nreturn sum\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T10:57:48.013",
"Id": "454736",
"Score": "0",
"body": "Can you please add a pseudocode for the algorithm? It would be really helpful!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T11:07:35.797",
"Id": "454737",
"Score": "0",
"body": "Sure, I'll edit some in"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T11:56:58.757",
"Id": "454741",
"Score": "0",
"body": "I believe what you have provided is examples. Pseudocode is `a notation resembling a simplified programming language, used in program design`. Please correct me if I am wrong"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T11:22:13.757",
"Id": "454906",
"Score": "0",
"body": "@Srivaths, you are correct, but bearing in mind that this is a site for code review rather than code production it's perfectly reasonable for an answer to give clear examples instead of (pseudo)code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T11:40:52.273",
"Id": "454908",
"Score": "0",
"body": "Yes, I agree. But still, I did ask if you could provide me a pseudocode! :-) But still, no problem. I've implemented your algorithm!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T10:50:05.757",
"Id": "232789",
"ParentId": "232754",
"Score": "4"
}
},
{
"body": "<blockquote>\n<pre><code>for i in range(2, LIMIT):\n if x[i]:\n primes.append(i)\n length += 1\n\n for j in range(i * i, LIMIT + 1, i):\n x[j] = 0\n</code></pre>\n</blockquote>\n\n<p>This is inconsistent: either <code>i</code> should range up to <code>LIMIT</code> inclusive, or there's no need for <code>j</code> to range up to <code>LIMIT</code> inclusive.</p>\n\n<p>Also, updating <code>length</code> in the loop is overkill. <code>len(primes)</code> outside the loop works just as well and doesn't distract.</p>\n\n<p>There are more advanced ways of doing the sieve with range updates, but that's already covered in dozens if not thousands of answers on this site, so I'll leave it as an exercise to search for one of them.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>s = 0\nprev = -1\ncnt = -1\n</code></pre>\n</blockquote>\n\n<p>It's not immediately clear what any of those variable names mean.</p>\n\n<blockquote>\n<pre><code> if x[s] and cnt < j - i + 1:\n cnt = j - i + 1\n prev = s\n</code></pre>\n</blockquote>\n\n<p>This could be done more elegantly by folding <code>cnt</code> and <code>prev</code> into a tuple:</p>\n\n<pre><code>width_sum = (-1, -1)\n\n...\n if x[s]:\n width_sum = max(width_sum, (j - i + 1, s))\n</code></pre>\n\n<hr>\n\n<p>You want the longest, so the fastest approach will usually be to search in decreasing order of length. To keep the bookkeeping simple it may be worth aggregating partial sums:</p>\n\n<pre><code>primes = []\naccum = [0]\n\nfor i in range(2, LIMIT):\n if x[i]:\n primes.append(i)\n accum.append(accum[-1] + i)\n\n for j in range(i * i, LIMIT + 1, i):\n x[j] = 0\n\nprimes = set(primes)\nfor width in range(len(primes), 0, -1):\n for off in range(width, len(accum)):\n partial_sum = accum[off] - accum[off - width]\n if partial_sum > LIMIT:\n break\n if partial_sum in primes:\n print(partial_sum)\n exit(0)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T10:54:15.617",
"Id": "232790",
"ParentId": "232754",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "232790",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T17:23:33.700",
"Id": "232754",
"Score": "7",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"primes",
"sieve-of-eratosthenes"
],
"Title": "Project Euler problem 50"
}
|
232754
|
<p>I implemented this console application that generates Fibonacci and Lucas sequence numbers using boost and GMP for multiprecision.</p>
<p>There is an iterator-like class which can do any sequence based on the recursive rule <code>F(n) = F(n-1) + F(n-2)</code>.</p>
<p>Then there are two functions which can compute Fibonacci and Lucas numbers given their position as for random access of the sequences.</p>
<p>I am using <code>operator<<</code> to feed the iterator with one of these functions so it can align itself with given start position in the given sequence.</p>
<p>The iterator can actually iterate backwards, because there is nothing that prevents it. You can invoke the behaviour by passing negative limit to the console app. This actually allows to go below zeroth element of the sequences.</p>
<p>I welcome any constructive criticism on my code and also suggestions how to make it more general in terms providing potentialy more sequences, using different number representations and having the iterator actualy do the random access (+=,-=,...) using those functions without loosing the ability to act on them and not knowing which function is used for the random access... And of course whatever other improvement comes to your mind :)</p>
<p>I am not sure whether I am using anything C++17 specific, but that is as high as I can go.</p>
<pre><code>#include <iostream>
#include <algorithm>
#include <boost/multiprecision/gmp.hpp>
/**
* Provides iterator over fibonacci family sequences.
* That is those sequences generated by recursive formula:
* F(n) = F(n-1) + F(n-2)
*/
template <class T = long, class TIndex = T>
struct pair_sum_iterator
{
public:
typedef std::bidirectional_iterator_tag iterator_category;
typedef T value_type;
typedef TIndex difference_type;
typedef T* pointer;
typedef T& reference;
T current, next;
TIndex index;
pair_sum_iterator()
: current(0), next(0), index(0)
{}
pair_sum_iterator(const TIndex& index)
: current(0), next(0), index(index)
{}
pair_sum_iterator(const T& first, const T& second)
: current(first), next(second), index(0)
{}
pair_sum_iterator(const T& first, const T& second, const TIndex& index)
: current(first), next(second), index(index)
{}
const T& operator*() const
{
return current;
}
pair_sum_iterator & operator++()
{
++index;
T tmp = current;
current = next;
next += tmp;;
return *this;
}
pair_sum_iterator operator++(int)
{
pair_sum_iterator old(*this);
++(*this);
return old;
}
pair_sum_iterator & operator--()
{
--index;
T tmp = current;
current = next - current;
next = tmp;
return *this;
};
pair_sum_iterator operator--(int)
{
pair_sum_iterator old(*this);
--(*this);
return old;
}
pair_sum_iterator & operator+=(const TIndex& diff)
{
TIndex d(diff);
while (d > 0) {
++(*this);
--d;
}
while (d < 0) {
--(*this);
d += 1; //bug in boost - cannot use ++d
}
return *this;
}
pair_sum_iterator & operator-=(const TIndex& diff)
{
return *this += -diff;
}
pair_sum_iterator operator+(const TIndex& diff) const
{
pair_sum_iterator result(*this);
return result += diff;
}
pair_sum_iterator operator-(const TIndex& diff) const
{
pair_sum_iterator result(*this);
return result -= diff;
}
pair_sum_iterator& operator<<(T (*f)(const TIndex&))
{
current = f(index);
next = f(index + 1);
return *this;
}
};
template <class T, class TIndex>
bool operator==(const pair_sum_iterator<T, TIndex> & a, const pair_sum_iterator<T, TIndex> & b)
{
return a.index == b.index;
}
template <class T, class TIndex>
bool operator!=(const pair_sum_iterator<T, TIndex> & a, const pair_sum_iterator<T, TIndex> & b)
{
return a.index != b.index;
}
template <class T, class TIndex>
bool operator<(const pair_sum_iterator<T, TIndex> & a, const pair_sum_iterator<T, TIndex> & b)
{
return a.index < b.index;
}
template <class T, class TIndex>
bool operator<=(const pair_sum_iterator<T, TIndex> & a, const pair_sum_iterator<T, TIndex> & b)
{
return a.index <= b.index;
}
template <class T, class TIndex>
bool operator>(const pair_sum_iterator<T, TIndex> & a, const pair_sum_iterator<T, TIndex> & b)
{
return a.index > b.index;
}
template <class T, class TIndex>
bool operator>=(const pair_sum_iterator<T, TIndex> & a, const pair_sum_iterator<T, TIndex> & b)
{
return a.index >= b.index;
}
template <class T, class TIndex>
TIndex operator-(const pair_sum_iterator<T, TIndex> & a, const pair_sum_iterator<T, TIndex> & b)
{
return a.index - b.index;
}
/**
* Fibonacci and lucas sequence random accessors and related stuff
*/
typedef boost::multiprecision::mpz_int app_int;
typedef boost::multiprecision::mpf_float_500 app_float;
const app_float sqrt5 = boost::multiprecision::sqrt(app_float(5));
const app_float phi = (app_float(1) + sqrt5) / app_float(2);
const app_float nphi = app_float(1) - phi;
app_int fibonacci(const app_int & n)
{
app_float n_f(n);
return boost::multiprecision::round(((boost::multiprecision::pow(phi,n_f) - boost::multiprecision::pow(nphi, n_f)) / sqrt5)).convert_to<app_int>();
}
app_int lucas(const app_int & n)
{
app_float n_f(n);
return boost::multiprecision::round(boost::multiprecision::pow(nphi, n_f) + boost::multiprecision::pow(phi, n_f)).convert_to<app_int>();
}
/**
* Console application parameters
*/
struct app_params
{
public:
app_int start;
app_int limit;
app_int (*sequence)(const app_int &);
bool show_usage;
bool success;
app_params()
: start(0), limit(10), sequence(fibonacci), show_usage(false), success(true)
{}
void usage(bool success)
{
show_usage = true;
this->success = success;
}
static app_params parse(int argc, char* argv[])
{
unsigned int arg_offset = 1;
app_params params;
try {
if (argc > 1) {
std::string arg1(argv[1]);
if (arg1 == "-h" || arg1 == "--help") {
params.usage(argc == 2);
} else {
if (arg1 == "lucas") {
++arg_offset;
params.sequence = lucas;
}
if (argc == 1 + arg_offset) { // custom limit
params.limit = app_int(argv[arg_offset]);
} else if (argc == 2 + arg_offset) { // custom limit and offset
params.start = app_int(argv[arg_offset]);
params.limit = app_int(argv[arg_offset + 1]);
} else if (argc > arg_offset) { //argc==arg_offset -> default limit and offest for lucas, otherwise invalid params
params.usage(false);
}
}
}
} catch (std::runtime_error error) {
params.usage(false);
}
return params;
}
};
/**
* Displays application usage information
*/
void print_usage(std::ostream & stream)
{
stream << "Usage:\n";
stream << "\tfibonacci [lucas] [[<start=0>] <limit=10>]\n";
}
/**
* Application entry point
*/
int main(int argc, char* argv[])
{
auto params = app_params::parse(argc, argv);
if (params.show_usage) {
print_usage(params.success ? std::cout : std::cerr);
return params.success ? EXIT_SUCCESS : EXIT_FAILURE;
}
pair_sum_iterator<app_int> f(params.start);
pair_sum_iterator<app_int> end(params.start + params.limit);
f << params.sequence;
std::ostream_iterator<app_int> out(std::cout, "\n");
if (params.limit.sign() < 0) {
std::reverse_copy(end, f, out);
} else {
std::copy(f, end, out);
}
return EXIT_SUCCESS;
}
</code></pre>
<h3>To Compile:</h3>
<pre><code>g++ -std=c++17 -g main.cc -lboost_math_c99 -lgmp -o fibonacci
</code></pre>
<pre><code>$g++ --version
g++ (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0
</code></pre>
<h3>To Run:</h3>
<pre><code>fibonacci [lucas] [[<start=0>] <limit=10>]
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T18:06:06.523",
"Id": "232757",
"Score": "3",
"Tags": [
"c++",
"c++17",
"fibonacci-sequence",
"boost",
"gmp"
],
"Title": "Fibonacci and Lucas sequence generator using Boost and GMP"
}
|
232757
|
<p>I'm trying to improve my interview skills so I wrote one of the typical assignments - tic-tac-toe game. The main goals are:</p>
<ul>
<li>time limit: 30 minutes - 1h</li>
<li>use only vanilla js</li>
</ul>
<p>I'll attach source but I created PR in dedicated repo as I think it'd easier to comment for reviewers.</p>
<p>Repo: <a href="https://github.com/makbol/tictactoe/pull/2" rel="nofollow noreferrer">https://github.com/makbol/tictactoe/pull/2</a></p>
<p>index.html</p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="./style.css" >
</head>
<body>
<div id="game" class="game"></div>
<script src="./player.js"></script>
<script src="./cell.js"></script>
<script src="./board.js"></script>
<script src="./game.js"></script>
<script src="./main.js"></script>
</body>
</code></pre>
<p>main.js</p>
<pre><code>const playerA = new Player({
sign: 'X',
name: 'Adrian'
});
const playerB = new Player({
sign: 'O',
name: 'Ben'
});
const game = new Game({
root: document.getElementById('game'),
size: 3,
players: [
playerA, playerB
]
});
</code></pre>
<p>game.js</p>
<pre><code>const DEFAULT_SIZE = 3;
class Game {
constructor({ size = DEFAULT_SIZE, root, players }) {
this.state = [];
this.size = size;
this.root = root;
this.board = new Board({
root: this.root,
size: this.size,
updateState: this.updateState.bind(this),
getCurrentPlayer: this.getCurrentPlayer.bind(this)
});
this.maxMoves = this.size * this.size;
this.numMoves = 0;
this.players = players
this.playersQueue = [...this.players];
this.currentPlayer = null;
this.setCurrentPlayer();
this.buildState();
}
buildState() {
for(let i = 0; i < this.size; i++) {
this.state.push(new Array(this.size).fill(0));
}
}
updateState({row, column}) {
this.state[row][column] = this.currentPlayer.sign;
this.numMoves++;
this.setCurrentPlayer();
this.checkWinner();
}
setCurrentPlayer() {
const player = this.playersQueue.shift();
this.currentPlayer = player
this.playersQueue.push(player);
}
getCurrentPlayer() {
return this.currentPlayer;
}
checkWinner() {
const winner = this.getResult();
if(winner) {
setTimeout(() => {
alert('Winner: ' + winner.name);
this.reset();
}, 0);
}
if (this.numMoves === this.maxMoves) {
setTimeout(() => {
alert('Game end');
this.reset();
}, 0);
}
}
getResult() {
const [ winner ] = this.players.filter(player =>
this.getRowResult(player) ||
this.getColumnResult(player) ||
this.getDiagonalResult(player)
);
return winner;
}
getRowResult(player) {
return this.state.filter((row) => {
return row.join('') === player.sign.repeat(row.length);
}).length
}
getColumnResult(player) {
return this.state[0].filter((column, index) => {
return this.getColumn(index) === player.sign.repeat(this.size);
}).length;
}
getDiagonalResult(player) {
let resultLeft = '';
let resultRight = '';
let expected = player.sign.repeat(this.size);
for(let i = 0; i < this.size; i++) {
resultLeft += this.state[i][i];
}
for(let i = this.size - 1; i === 0; i--) {
resultRight += this.state[i][i];
}
return resultLeft === expected || resultRight === expected;
}
getColumn(n) {
let result = '';
for(let i = 0; i < this.size; i++) {
result += this.state[i][n];
}
return result;
}
reset() {
this.board.clear();
this.numMoves = 0;
this.clearState();
}
clearState() {
this.state = [];
this.buildState();
}
}
</code></pre>
<p>board.js</p>
<pre><code>class Board {
constructor({size, root, updateState, getCurrentPlayer}) {
this.size = size;
this.cells = [];
this.root = root;
this.updateState = updateState;
this.getCurrentPlayer = getCurrentPlayer
this.buildBoard();
}
buildBoard() {
const board = [];
for(let i = 0; i < this.size; i++) {
const row = [];
for(let j = 0; j < this.size; j++) {
const cell = new Cell({
row: i,
column: j,
updateState: this.updateState,
getCurrentPlayer: this.getCurrentPlayer
});
this.cells.push(cell);
row.push(cell);
}
board.push(this.addRowElement(row));
}
board.forEach(rows => {
this.root.appendChild(rows);
});
}
addRowElement(cells) {
const rowElement = document.createElement('div');
rowElement.className = 'row';
cells.forEach((cell) => {
rowElement.appendChild(cell.element);
});
return rowElement;
}
clear() {
this.cells.forEach(cell => cell.clear());
}
}
</code></pre>
<p>cell.js</p>
<pre><code>class Cell {
constructor({row, column, updateState, getCurrentPlayer}) {
this.row = row;
this.column = column;
this.marked = false;
this.updateState = updateState;
this.getCurrentPlayer = getCurrentPlayer;
this.element = this.getElement();
}
onClick() {
if(this.canClick()) {
const player = this.getCurrentPlayer();
this.sign = player.sign;
this.marked = true;
this.render();
this.updateState({
row: this.row,
column: this.column
});
}
}
canClick() {
return !this.marked;
}
clear() {
this.sign = '';
this.marked = false;
this.render();
}
getElement() {
const element = document.createElement('div');
element.className = 'cell';
element.addEventListener('click', this.onClick.bind(this));
return element;
}
render() {
this.element.textContent = this.sign;
}
}
</code></pre>
<p>player.js</p>
<pre><code>class Player {
constructor({ sign, name }) {
this.sign = sign;
this.name = name;
}
}
</code></pre>
<p>My main considerations:</p>
<ul>
<li>Passing all the way down to <code>Cell</code> method <code>updateState</code> seems a bit unfortunate
<ul>
<li>Create general <code>State</code> class and reuse it among classes?</li>
<li>Events? Not big fan - hard to track changes</li>
</ul></li>
<li>Re-render whole board every time something changes or mutate state of each cell?</li>
</ul>
<p>My biggest concern is about architecture since it's interview assignment.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T15:43:22.450",
"Id": "454777",
"Score": "0",
"body": "You did all this in under an hour? That's impressive! This looks like an extremely well designed tic tac toe game. I personally would go with cell mutation, a full render would require listeners to be re-attached manually."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T10:47:33.813",
"Id": "454902",
"Score": "0",
"body": "Well part of that and general concept I did on interview. Afterwards I decided to finish that so I think it took around 1 hour primarily bc I needed to consider. If I'd have good concept in mind then writing this would take less then 30 minutes. That's why I'm asking for review. I know that kind of assignments repeats on interviews so I want to have basic concept in mind."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T10:57:35.867",
"Id": "454904",
"Score": "1",
"body": "The perfect way would be to write some simple diffing algo but I think there's no time for that on interview (and I don't know how ;)). For full render there's no need to reattach listeners bc they are attached while new instance of 'Cell' is initiated (full render would require to all initiate Cells again). For that case both approaches are fine but imagine if there would be board with 10^6 cells."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T16:31:01.203",
"Id": "455126",
"Score": "0",
"body": "Yes interesting. I will have to try this exercise for myself sometime."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T19:55:42.703",
"Id": "232760",
"Score": "1",
"Tags": [
"javascript",
"interview-questions"
],
"Title": "Tic-tac-toe vanilla js"
}
|
232760
|
<p>I have made my first little project using C#/WPF - a simple rock, paper, scissors game. I am happy with the functionality and look but I would love to know how a more experienced programmer would refactor the code I have to bring the size down and make it more readable. Many thanks.</p>
<p><strong>MainWindow.xaml</strong></p>
<pre><code><Window x:Class="Rock_Paper_Scissors.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Rock_Paper_Scissors"
mc:Ignorable="d"
Title="Rck/Ppr/Scsr" Height="805.5" Width="612">
<Grid>
<Grid Margin="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Button x:Name="btnRock" FontSize="35" Content="ROCK" HorizontalAlignment="Left" Margin="10,570,0,0" VerticalAlignment="Top" Width="175" Height="175" Click="Player_Choice"/>
<Button x:Name="btnPaper" FontSize="35" Content="PAPER" HorizontalAlignment="Left" Margin="9,570,0,0" VerticalAlignment="Top" Width="175" Height="175" Grid.Column="1" Click="Player_Choice"/>
<Button x:Name="btnScissors" FontSize="35" Content="SCISSORS" HorizontalAlignment="Left" Margin="10,570,0,0" VerticalAlignment="Top" Width="175" Height="175" Grid.Column="2" Click="Player_Choice"/>
<TextBox Name="txbxPlayersChoice" BorderBrush="Black" TextAlignment="Center" Padding="0, 35" FontSize="35" Grid.Column="1" HorizontalAlignment="Left" Height="126" Margin="10,394,0,0"
TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="174"/>
<TextBox x:Name="txbxPlayerScore" FontSize="23" FontWeight="Bold" TextAlignment="Center" Padding="0 -6 0 0" BorderBrush="Black" Grid.Column="1" HorizontalAlignment="Left" Height="24" Margin="10,520,0,0"
TextWrapping="Wrap" VerticalAlignment="Top" Width="174"/>
<TextBox IsEnabled="False" BorderBrush="Black" TextAlignment="Center" FontSize="15" Grid.Column="1" HorizontalAlignment="Left" Height="24" Margin="10,370,0,0" TextWrapping="Wrap"
Text="Player" VerticalAlignment="Top" Width="174"/>
<TextBox Name="txbxCompsChoice" BorderBrush="Black" TextAlignment="Center" Padding="0, 35" FontSize="35" Grid.Column="1" HorizontalAlignment="Left" Height="126" Margin="10,46,0,0"
TextWrapping="Wrap" Text="?" VerticalAlignment="Top" Width="174"/>
<TextBox IsEnabled="False" BorderBrush="Black" TextAlignment="Center" FontSize="15" Grid.Column="1" HorizontalAlignment="Left" Height="24" Margin="10,22,0,0" TextWrapping="Wrap"
Text="Computer" VerticalAlignment="Top" Width="174"/>
<TextBox x:Name="txbxCompScore" FontSize="23" FontWeight="Bold" TextAlignment="Center" Padding="0 -6 0 0" BorderBrush="Black" Grid.Column="1" HorizontalAlignment="Left" Height="24" Margin="10,172,0,0"
TextWrapping="Wrap" VerticalAlignment="Top" Width="174"/>
<Button x:Name="btnCountdown" Content="PLAY" Margin="10,201,10,390" Grid.Column="1" Click="BtnCountdown_Click" FontSize="55">
<Button.Template>
<ControlTemplate TargetType="Button">
<Grid>
<Ellipse Fill="MediumTurquoise"/>
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Button.Template>
</Button>
<TextBox IsEnabled="False" Name="txbxLeft" TextAlignment="Center" Padding="0, 260, 0, 0" HorizontalAlignment="Left" Height="534" Margin="10,10,0,0" TextWrapping="Wrap"
Text="Pick Rock, Paper or Scissors" VerticalAlignment="Top" Width="175"/>
<TextBox IsEnabled="False" Name="txbxRight" TextAlignment="Center" Padding="0, 260, 0, 0" HorizontalAlignment="Left" Height="534" Margin="10,10,0,0" TextWrapping="Wrap"
Text="Press play to start.
First to 3 wins. " VerticalAlignment="Top" Width="175" Grid.Column="2"/>
</Grid>
</Grid>
</Window>
</code></pre>
<p><strong>MainWindow.xaml.cs</strong></p>
<pre><code>using System;
using System.Windows;
using System.Windows.Controls;
namespace Rock_Paper_Scissors
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private System.Windows.Forms.Timer timer1;
private int counter = 7;
string ROCK = "ROCK";
string PAPER = "PAPER";
string SCISSORS = "SCISSORS";
private void The_Game(object sender, EventArgs e)
{
counter--;
if (counter == 6)
{
btnCountdown.FontSize = 95; btnCountdown.Content = "3";
}
if (counter == 5)
{
btnCountdown.Content = "2";
}
if (counter == 4)
{
btnCountdown.Content = "1";
}
if (counter == 3)
{
btnCountdown.FontSize = 55; btnCountdown.Content = "SHOW";
Comp_Choice();
btnRock.IsEnabled = btnPaper.IsEnabled = btnScissors.IsEnabled = false;
if ((txbxPlayersChoice.Text == ROCK && txbxCompsChoice.Text == PAPER)
|| (txbxPlayersChoice.Text == PAPER && txbxCompsChoice.Text == SCISSORS)
|| (txbxPlayersChoice.Text == SCISSORS && txbxCompsChoice.Text == ROCK))
{
txbxLeft.Text = txbxRight.Text = "You Lose"; txbxCompScore.Text = txbxCompScore.Text + "X";
}
if ((txbxPlayersChoice.Text == PAPER && txbxCompsChoice.Text == ROCK)
|| (txbxPlayersChoice.Text == ROCK && txbxCompsChoice.Text == SCISSORS)
|| (txbxPlayersChoice.Text == SCISSORS && txbxCompsChoice.Text == PAPER))
{
txbxLeft.Text = txbxRight.Text = "You Win"; txbxPlayerScore.Text = txbxPlayerScore.Text + "X";
}
if ((txbxPlayersChoice.Text == ROCK && txbxCompsChoice.Text == ROCK)
|| (txbxPlayersChoice.Text == PAPER && txbxCompsChoice.Text == PAPER)
|| (txbxPlayersChoice.Text == SCISSORS && txbxCompsChoice.Text == SCISSORS))
{
txbxLeft.Text = txbxRight.Text = "DRAW";
}
}
if (counter == 0)
{
timer1.Stop();
btnCountdown.FontSize = 25; btnCountdown.Content = "PLAY AGAIN";
txbxCompsChoice.Text = "?"; txbxPlayersChoice.Text = "";
txbxLeft.Text = "Pick Rock, Paper or Scissors"; txbxRight.Text = "Click Play Again to start";
btnCountdown.IsEnabled = true;
counter = 7;
if (txbxPlayerScore.Text == "XXX")
{
txbxLeft.Text = "GAME OVER"; txbxRight.Text = "YOU WIN!";
btnCountdown.Content = " YOU WIN\nPLAY AGAIN";
}
if(txbxCompScore.Text == "XXX")
{
txbxLeft.Text = "GAME OVER"; txbxRight.Text = "YOU LOSE!";
btnCountdown.Content = " YOU LOSE\nPLAY AGAIN";
}
btnRock.IsEnabled = btnPaper.IsEnabled = btnScissors.IsEnabled = true;
}
}
private void BtnCountdown_Click(object sender, RoutedEventArgs e)
{
if(btnCountdown.IsPressed == true)
{
btnCountdown.FontSize = 32;
}
timer1 = new System.Windows.Forms.Timer();
timer1.Tick += new EventHandler(The_Game);
timer1.Interval = 1000; timer1.Start();
btnCountdown.IsEnabled = false;
if (txbxLeft.Text == "GAME OVER")
{
txbxPlayerScore.Text = ""; txbxCompScore.Text = "";
}
}
public void Comp_Choice()
{
string[] comp_choices = { ROCK, PAPER, SCISSORS };
Random rand = new Random();
int rand_index = rand.Next(comp_choices.Length);
txbxCompsChoice.Text = comp_choices[rand_index];
}
private void Player_Choice(object sender, RoutedEventArgs e)
{
Button clicked = (Button)sender;
txbxPlayersChoice.Text = clicked.Content.ToString();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T10:45:55.900",
"Id": "454735",
"Score": "0",
"body": "Do you wanna go the MVVM way?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T14:10:47.697",
"Id": "454754",
"Score": "0",
"body": "Sure thing - I'd like to see how that would look at least"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T20:44:24.257",
"Id": "454840",
"Score": "4",
"body": "Number one piece of advice here is **do not put multiple short statements on one line**. That is not idiomatic in C# and it is hard to read."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T20:48:17.840",
"Id": "454842",
"Score": "3",
"body": "Number two piece of advice is: keep the game logic and the UI logic separate. That's what Dbuggy is getting at; the model -- the state of the game -- and the user interface -- the view -- are logically separate but you've rolled them all up together."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T21:23:27.227",
"Id": "454850",
"Score": "0",
"body": "Thanks for your reply Eric. I had a feeling the multiple short statements on one line would be a no, but wanted to test the water.\nI understand what you're saying about breaking it up into more logical classes/methods but can't see how to approach that, can you briefly advise please?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T02:48:39.597",
"Id": "455055",
"Score": "0",
"body": "Is there any specific reason as to why you start `counter` at `7` but immediately decrement in `The_Game`?"
}
] |
[
{
"body": "<p>Just moving Eric's comments to an actual answer.</p>\n\n<ol>\n<li><blockquote>\n <p>Number one piece of advice here is do not put multiple short statements on one line. That is not idiomatic in C# and it is hard to read.</p>\n</blockquote></li>\n<li><blockquote>\n <p>Number two piece of advice is: keep the game logic and the UI logic\n separate. That's what Dbuggy is getting at; the model -- the state of\n the game -- and the user interface -- the view -- are logically\n separate but you've rolled them all up together.</p>\n</blockquote></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-16T14:58:21.450",
"Id": "234120",
"ParentId": "232763",
"Score": "1"
}
},
{
"body": "<pre><code>string ROCK = \"ROCK\";\nstring PAPER = \"PAPER\";\nstring SCISSORS = \"SCISSORS\"; \n</code></pre>\n\n<p>These should be constants because the values won't change. You have some more magic strings which should be converted to constants as well. </p>\n\n<p>Well, naming things is hard but one should stick to some guidelines. If you don't have guidelines I would suggest using the <a href=\"https://msdn.microsoft.com/en-us/library/ms229002.aspx\" rel=\"nofollow noreferrer\">.NET Naming Guidelines</a>. What really is important about naming is that one can grasp at first glance what the code is about. Think about if you or <strong>Sam the maintainer</strong> is looking at the code in a few months, do you still know what the abbreviations are meant for? </p>\n\n<p>E.g here </p>\n\n<pre><code>public void Comp_Choice()\n{\n string[] comp_choices = { ROCK, PAPER, SCISSORS };\n Random rand = new Random();\n int rand_index = rand.Next(comp_choices.Length);\n txbxCompsChoice.Text = comp_choices[rand_index];\n} \n</code></pre>\n\n<p>you have at least 4 times used abbreviations for naming things. But this method has some more issues. Each time this method is called you are creating <code>string[] comp_choices</code> which could be done at class-level and used each time. </p>\n\n<p><code>Random</code> isn't really random and if not using .NET Core one should make it a class-level variable which is intialized inside the constructor or at class intialization, because it is initialized using the current time as seed. Meaning if e.g this method is called very fast in a row it would produce the same values. </p>\n\n<p>Based on the mentione naming guidelines methdos should be named using <code>PascalCase</code> casing and fields should be named using <code>camelCase</code> casing. <code>Snake_case</code> casing usually isn't used in .NET development. </p>\n\n<p>I would prefer the method in question returning a <code>string</code> than beeing <code>void</code>. </p>\n\n<hr>\n\n<p>Checking for a Draw could be made first because it is the easiest and can be the shortest piece of code. In addition if a Draw happens you only need to check if either the user <strong>or</strong> the computer has won. Hence I suggest to change the logic like so </p>\n\n<pre><code>if ((txbxPlayersChoice.Text == txbxCompsChoice.Text )\n{\n txbxLeft.Text = txbxRight.Text = \"DRAW\";\n}\nelse if ((txbxPlayersChoice.Text == ROCK && txbxCompsChoice.Text == PAPER)\n || (txbxPlayersChoice.Text == PAPER && txbxCompsChoice.Text == SCISSORS)\n || (txbxPlayersChoice.Text == SCISSORS && txbxCompsChoice.Text == ROCK))\n{\n txbxLeft.Text = txbxRight.Text = \"You Lose\"; \n txbxCompScore.Text = txbxCompScore.Text + \"X\";\n}\nelse \n{\n txbxLeft.Text = txbxRight.Text = \"You Win\"; \n txbxPlayerScore.Text = txbxPlayerScore.Text + \"X\";\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-27T10:04:28.767",
"Id": "234691",
"ParentId": "232763",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T23:02:48.950",
"Id": "232763",
"Score": "5",
"Tags": [
"c#",
"wpf"
],
"Title": "WPF/C# - Rock, Paper, Scissors Game"
}
|
232763
|
<p>I have a java project that I'm working on and I'm trying to implement in my application role-based authentication.
So for example when a user is logging and he is an admin he will have access to some extra methods then a normal user has access to.</p>
<p>In order to do that I've mapped my database in the following way.</p>
<pre><code>SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
--
-- Table structure for table `data`
--
USE DB;
DROP TABLE IF EXISTS `data`;
CREATE TABLE IF NOT EXISTS `data` (
`id_u` int(11) NOT NULL AUTO_INCREMENT,
`Username` varchar(30) NOT NULL,
`Password` varchar(64) NOT NULL,
`Salt` varchar(64) NOT NULL,
`Role` int(30) NOT NULL,
PRIMARY KEY (`id_u`)
);
--
-- Dumping data for table `data`
--
INSERT INTO `data` (`id_u`,`Username`, `Password`, `Salt`,`Role`) VALUES
(1,'Mike', 'TzBql1WR9wZjN0LoKr2OBk2majc=', '4NWwJULan8U=','1'),
(2,'John', 'JcQnEVl0af8EwrPkmc6EGG+fLfs=', '2MWwJULan8U=','1'),
(3,'Alice', 'BaN+yn8W0SYZiUkaOHSZxDKTLMg=', '4NWSJULgn8U=','2'),
(4,'Bob', 'V1TtSe0GFYuHFJrA1l1lDIwdfKA=', '4NWwJILan9U=','2'),
(5,'Charlie', 'X40Xv/MntGoeqwif8hhFEOIrK8Q=', '4NWwFULan8X=','2');
COMMIT;
--
-- Table structure for table `Roles`
--
DROP TABLE IF EXISTS `Roles`;
CREATE TABLE IF NOT EXISTS `Roles` (
`id_r` int(11) NOT NULL AUTO_INCREMENT,
`Role_type` varchar(30) NOT NULL,
`Role_code` int(30) NOT NULL,
PRIMARY KEY (`id_r`),
CONSTRAINT FK_UsersRoles FOREIGN KEY (Role_code)
REFERENCES Roles(Role),
CONSTRAINT FK_PermissionsRoles FOREIGN KEY (Role_code)
REFERENCES Permissions(Permission)
)ENGINE=MyISAM AUTO_INCREMENT=22 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `Roles`
--
INSERT INTO `Roles` (`id_r`, `Role_type`, `Role_code`) VALUES
(1, 'admin', 1),
(2, 'normaluser', 2),
(3, 'guest', 3);
COMMIT;
--
-- Table structure for table `Permissions`
--
DROP TABLE IF EXISTS `Permissions`;
CREATE TABLE IF NOT EXISTS `Permissions` (
`id_p` int(11) NOT NULL AUTO_INCREMENT,
`Function` varchar(30) NOT NULL,
`Permission` int(30) NOT NULL,
PRIMARY KEY (`id_p`)
) ENGINE=MyISAM AUTO_INCREMENT=22 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `Permissions`
--
INSERT INTO `Permissions` (`id_p`, `Function`, `Permission`) VALUES
(1, 'newPrintJob', 0),
(2, 'print', 3),
(3, 'start', 3),
(4, 'read config', 2),
(5, 'set config', 1),
(6, 'queue', 2),
(7, 'top queue',2 ),
(8, 'stop', 2),
(9, 'restart', 2),
(10, 'status', 3),
(11, 'createUser', 1);
(12, 'createUser', 2);
</code></pre>
<p>Now my questions are, does the database have the correct structure in order to retrieve the name of the function in the Permission table?</p>
<p>How can I write a select statement that will retrieve a list of the certain functions from table Permission that a certain user has?
Any other feedback would be much appreciated. </p>
<p>Thank you!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T05:51:29.617",
"Id": "454711",
"Score": "0",
"body": "*How can I write a select statement that will retrieve a list of the certain functions* - this is out of scope"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T23:18:53.563",
"Id": "232764",
"Score": "1",
"Tags": [
"sql",
"mysql",
"database",
"query-selector"
],
"Title": "MySQL select statement for retrieving user role permissions"
}
|
232764
|
<p>I have multiple onEdit app script functions in my Google Spreadsheet which work individually but I cannot work out where to put the brackets to nest them. This is my code which is a little messy and probably needs a tidy up.</p>
<pre><code>// Cut Employees Left from Unit Standards sheet and paste in Unit Standards - Employees Left sheet
function onEdit(e) {
var ss = e.source;
var sheet = ss.getActiveSheet();
var sheetName = "Unit Standards"
var range = e.range;
var editedColumn = range.getColumn();
var editedRow = range.getRow();
var column = 2;
var date = range.getValue();
// Object.prototype.toString.call(date) === '[object Date]' --> checks if value is date
// editedColumn == column && editedRow > 4 --> checks if edited cell is from 'Date Left'
// sheet.getName() == sheetName --> checks if edited sheet is 'Unit Standards'
if(Object.prototype.toString.call(date) === '[object Date]' && editedColumn == column && editedRow > 4 && sheet.getName() == sheetName) {
var numCols = sheet.getLastColumn();
var row = sheet.getRange(editedRow, 1, 1, numCols).getValues();
var destinationSheet = ss.getSheetByName("Unit Standards - Employees Left");
// Get first empty row:
var emptyRow = destinationSheet.getLastRow() + 1;
// Copy values from 'Unit Standards'
destinationSheet.getRange(emptyRow, 1, 1, numCols).setValues(row);
sheet.deleteRow(editedRow);
sheet.hideColumns(column);
}
//Dependent Dropdowns for Event/Incidents Sheet
{
var range = e.range;
var editedRow = range.getRow();
var spreadsheet = SpreadsheetApp.getActive();
var dropdownSheet = spreadsheet.getSheetByName("Dropdown Lists");
var eventsSheet = spreadsheet.getSheetByName("Events/Incidents");
var baseSelected = eventsSheet.getRange('C' + editedRow).getValue();
var column;
switch (baseSelected) {
case 'EBOP': column = 'A'; break;
case 'Tauranga': column = 'B'; break;
case 'Palmerston North': column = 'C'; break;
case 'Kapiti': column = 'D';
}
var startCell = dropdownSheet.getRange( column +'4');
var endCellNotation = startCell.getNextDataCell(SpreadsheetApp.Direction.DOWN).getA1Notation();
var ruleRange = dropdownSheet.getRange(startCell.getA1Notation() + ':' + endCellNotation);
var dropdown1 = eventsSheet.getRange('D' + editedRow);
var dropdown2 = eventsSheet.getRange('E' + editedRow);
var rule1 = SpreadsheetApp.newDataValidation().requireValueInRange(ruleRange).build();
var rule2 = SpreadsheetApp.newDataValidation().requireValueInRange(ruleRange).build();
dropdown1.setDataValidation(rule1);
dropdown2.setDataValidation(rule2);
}
}
if (ss.getSheetName() == tabValidation) {
var lock = LockService.getScriptLock();
if (lock.tryLock(0)) {
autoid_(ss);
lock.releaseLock();
}
}
}
}
// Auto ID for Event/Incident Sheet
function autoid_(sheet) {
var data = sheet.getDataRange().getValues();
if (data.length < 2) return;
var indexId = data[1].indexOf('ID');
var indexDate = data[1].indexOf('Event/Incident Date');
if (indexId < 0 || indexDate < 0) return;
var id = data.reduce(
function(p, row) {
var year =
row[indexDate] && row[indexDate].getTime
? row[indexDate].getFullYear() % 100
: '-';
if (!Object.prototype.hasOwnProperty.call(p.indexByGroup, year)) {
p.indexByGroup[year] = [];
}
var match = ('' + row[indexId]).match(/(\d+)-(\d+)/);
var idVal = row[indexId];
if (match && match.length > 1) {
idVal = match[2];
p.indexByGroup[year].push(+idVal);
}
p.ids.push(idVal);
p.years.push(year);
return p;
},
{ indexByGroup: {}, ids: [], years: [] }
);
// Logger.log(JSON.stringify(id, null, ' '));
var newId = data
.map(function(row, i) {
if (row[indexId] !== '') return [row[indexId]];
if (isNumeric(id.years[i])) {
var lastId = Math.max.apply(
null,
id.indexByGroup[id.years[i]].filter(function(e) {
return isNumeric(e);
})
);
lastId = lastId === -Infinity ? 1 : lastId + 1;
id.indexByGroup[id.years[i]].push(lastId);
return [
Utilities.formatString(
'%s-%s',
id.years[i],
('000000000' + lastId).slice(-3)
)
];
}
return [''];
})
.slice(1);
sheet.getRange(2, indexId + 1, newId.length).setValues(newId);
}
/**
*
* @param {any} n
* @return {boolean}
*/
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
</code></pre>
|
[] |
[
{
"body": "<p>To put together "multiple onEdit" functions consider to have one function with a descriptive name for each of them, then call them from the actual onEdit function</p>\n<pre><code>function onEdit(e){\n copyRow(e);\n setDataValidations(e);\n}\n</code></pre>\n<p>Also you could save some code lines by removing lines like</p>\n<ol>\n<li><code>var ss = e.source</code> and <code>var spreadsheet = e.source;</code>. Instead of <code>ss</code> and <code>spreadsheet</code> use <code>e.source</code>.</li>\n<li><code>var range = e.range;</code>. Instead of <code>range</code> use <code>e.range</code>.</li>\n<li><code>var editedColumn = range.getColumn();</code>. Instead of <code>editedColumn</code> use <code>e.range.columnStart</code>.</li>\n<li><code>var editedRow = range.getRow();</code>. Instead of <code>editedRow</code> use <code>e.range.rowStart</code>.</li>\n<li><code>var date = range.getValue();</code> Instead of <code>date</code> use <code>e.value</code></li>\n</ol>\n<p>Bear in mind that if multiple cells are edited</p>\n<ul>\n<li><code>e.value</code> will return <code>undefined</code></li>\n<li><code>e.range.getValue()</code> will return the value of the to top-left cell.</li>\n<li><code>e.range.getColumn()</code> will return the column number of the to top-left cell.</li>\n<li><code>e.range.getRow()</code> will return the row number of the to top-left cell.</li>\n</ul>\n<p>Considering the above you might want to include some validations before calling / executing changes to your spreadsheet.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-25T04:38:29.313",
"Id": "479954",
"Score": "0",
"body": "Valid advice, but on [a question that should not have been answered here](https://codereview.stackexchange.com/help/how-to-answer)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-23T16:42:12.297",
"Id": "244392",
"ParentId": "232765",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-21T23:36:59.313",
"Id": "232765",
"Score": "3",
"Tags": [
"javascript",
"google-apps-script"
],
"Title": "Bracketing multiple onEdit functions"
}
|
232765
|
<p>[This is my first question to Code Review and it might be a bit too much.]</p>
<p>I want to give users the means to draw a simple diagram in the browser, and because it is partly a self-education project about the low-level entities and relationships in the browser, I haven't used one of the bigger frameworks that might perhaps have helped more. </p>
<p>My goal here is to prepare a diagram and be able to submit (save) to a server, then have the server return the diagram and reconstitute the entities and links. At the moment, this is done with data-* attributes.</p>
<p>My questions:</p>
<ul>
<li><p>There are a lot of global variables (<code>draw.state</code>, <code>draw.docKeyListenerCount</code> etc are contained only inside the 'onload'-equivalent function) that I address from different eventListeners, and I recall that shared mutable state is evil. I found this (and having the listeners at the top scope) necessary because the user can move the mouse faster than my script can update the location of objects.</p></li>
<li><p>To complete one action (e.g. attach a free link to an entity) involves a sequence of mousedown, mouseout, mouseover and mouseup events. It's very confusingly organised, and to add new actions I'll have to think really hard about where the fall in the flow of possible responses to each event.</p></li>
<li><p>Changes to the entity types or action possibilities would have to be added in on each of those (e.g. if I want to be able to drop an entity into another entity to represent a sub-component, how can I introduce that in a nice modular way). </p></li>
</ul>
<pre><code> SVG.on(document, 'DOMContentLoaded', function() {
//=================
//set up drawing
//=================
var draw = SVG('diagram-0').size(1200,700).attr({"class": "graphics"});
draw.state = 'rest';
draw.docKeyListenerCount = 0;
draw.fE = null;
draw.originX = undefined;
draw.originY = undefined;
draw.clientX = undefined;
draw.clientY = undefined;
draw.newX = undefined;
draw.newY = undefined;
draw.labelTextbuffer = [];
let tools = draw.nested().size(200, 700);
draw.tools = tools;
tools.attr({"class": "tools"});
let diagram = draw.nested().size(1000, 700).move(200, 0);
draw.diagram = diagram; //expose diagram
diagram.attr({"class": "diagram"});
tools.toolarea = tools.rect(200, 700).attr({fill: "#ddd", strokeWidth: 1}).radius(5);
tools.title = tools.text("Tools").move(0, 0);
let entity_tool = moveableEntity(draw, 'new entity');
entity_tool.addTo(tools);
entity_tool.update = entityUpdate;
entity_tool.update(25, 25);
entity_tool.update();
let link_tool = newLink(draw, 25, 80, 60, 80);
link_tool.update = lineUpdate;
link_tool.addTo(tools);
link_tool.update();
entity_tool.data('grouptype', 'entity');
link_tool.data('grouptype', 'linker');
diagram.workarea = diagram.rect(1000, 700).radius(5).attr({fill: "#ddd", strokeWidth: 3});
diagram.title = diagram.text("Diagram").move(0, 0);
// ---------------
// E V E N T S
// ---------------
function ancestralGroup(svg_element) {
if (svg_element.type === 'g') {
return svg_element;}
else if (svg_element.type === 'svg') {return svg_element;}
else {
let parent = svg_element.parent();
return ancestralGroup(parent); // Watch Out: Recursion
};
};
function toolAct(e) {
let item = SVG.get(e.target.id);
let groupToCopy = ancestralGroup(item);
console.log('at ', groupToCopy);
if (groupToCopy.type === 'svg') { return; }; // user has clicked the background panel or a label
let copied = groupToCopy.clone();
console.log('copy made: ', copied.node)
diagram.add(copied); };
tools.on('click', toolAct);
diagram.on('mouseout', function (e) {
e.preventDefault();
if ((draw.state==='move')&&(draw.fE.type === 'circle')) {
let rings = ((10 - draw.fE.collocates.length*2) > 2) ? (10 - draw.fE.collocates.length*2) : 2;
draw.fE.attr({fill: "none", r: rings});
let thisring = rings;
for (const collocate of draw.fE.collocates) {
thisring = thisring + 2;
collocate.attr({fill: "none", r: thisring})
};
};
});
diagram.on('mouseover', function (e) {
e.preventDefault();
if (draw.state === 'move') {
let attachment = SVG.get(e.target.id);
if (attachment.type !== 'circle') {return;}
if ((draw.fE === attachment)||(draw.fE.collocates.indexOf(attachment)) > -1) {return;}
else {
draw.fE.collocates.push(attachment);
attachment.collocates.push(draw.fE);
};
};
return;
});
diagram.on('mouseup', function (e) {
if (draw.state !== 'edit') {
draw.state = 'rest';
if (draw.docKeyListenerCount === 1) {
SVG.off(document, 'keydown', edit);
draw.docKeyListenerCount = 0;};
if (draw.fE) {
if (draw.fE.attr("fill") === 'none') { unsticky(draw.fE);}
else {};
draw.fE = undefined;
};
}
else {
};
});
diagram.on('mousemove', function (e) {
if (draw.state === 'move') {
draw.newX = draw.originX + (e.clientX - draw.clickX);
draw.newY = draw.originY + (e.clientY - draw.clickY);
let parentGroup = ancestralGroup(draw.fE);
// console.log('MOUSEMOVE - draw.fE was: ', draw.fE, draw.state, parentGroup);
if (draw.fE.type === 'circle') { // then its a moveablePoint
draw.fE.cx(draw.newX).cy(draw.newY);
console.log('an immovable circle?', draw.fE.cx(), draw.fE.cy());
parentGroup.update();
if (draw.fE.collocates) { update_collocates(draw.fE); }}
else if ((draw.fE.type === 'rect')||(draw.fE.type=== 'tspan')) { // then it's an entity
parentGroup.from.cx(draw.newX).cy(draw.newY);
if (parentGroup.from.collocates) { update_collocates(parentGroup.from); }
parentGroup.to.cx((draw.newX + parentGroup.panel.width())).cy((draw.newY + parentGroup.panel.height()));
if (parentGroup.to.collocates) { update_collocates(parentGroup.to); }
parentGroup.label.x(draw.newX).y(draw.newY);
parentGroup.panel.x(draw.newX).y(draw.newY);
parentGroup.update();
}
}
else {}; // if draw.state not 'move', do nothing
});
diagram.on('mousedown', function (e) {
draw.fE = SVG.get(e.target.id); // reaches out to drawing scope
let parentGroup = ancestralGroup(draw.fE);
if (!parentGroup.to) { // this should be a 'take up group' function
let children = parentGroup.children();
if (parentGroup.data('grouptype') === 'entity') {
parentGroup.update = entityUpdate;
}
else if (parentGroup.data('grouptype') === 'linker') {
parentGroup.update = lineUpdate;
};
children.forEach(function (child) {
let partIndicator = child.data('part');
switch (partIndicator) {
case 'to':
parentGroup.to = child;
parentGroup.to.collocates = [];
break;
case 'from':
parentGroup.from = child;
parentGroup.from.collocates = [];
break;
case 'straight':
parentGroup.straight = child;
break;
case 'panel':
parentGroup.panel = child;
break;
case 'label':
parentGroup.label = child;
break; }
console.log('parent', parentGroup);
}
);
};
if (draw.fE.type === 'tspan') {
draw.state = 'edit';
draw.labelTextbuffer = draw.fE.text().split("");
if (draw.docKeyListenerCount <= 0) {
SVG.on(document, 'keydown', edit);
draw.docKeyListenerCount = 1; };
return;
}
else {if ((draw.fE.type !== 'tspan')&&(draw.state === 'edit')) {
draw.state = 'rest';
for (let i=0; i < draw.docKeyListenerCount; i++) {
SVG.off(document, 'keydown', edit);
draw.docKeyListenerCount--;
console.log('key listener off', draw.docKeyListenerCount)};
};
};
if (e.button === 0) {
draw.state = 'move';
draw.originX = ((draw.fE.type === 'circle') ? draw.fE.cx() : draw.fE.x());
draw.originY = ((draw.fE.type === 'circle') ? draw.fE.cy() : draw.fE.y());
draw.clickX = e.clientX;
draw.clickY = e.clientY;
}
else { // to detach
draw.state = 'detach';
if ((draw.fE.collocates)&&(draw.fE.collocates.length > 0)) {
for (const collocate of draw.fE.collocates) {
let idx = collocate.collocates.indexOf(draw.fE);
if (idx > -1) {collocate.collocates.splice(idx,1)};
}
draw.fE.collocates.length = 0;
draw.fE.attr({fill: 'red'});
}
draw.fE.dx(30);
parentGroup.update();
};
return;
});
function edit(e) {
e.preventDefault();
if (e.key === "Escape") { draw.state = 'rest'; draw.fE = undefined; return;}
if (draw.state === 'edit') {
if (e.key === "Backspace"){
draw.labelTextbuffer.pop();
draw.fE.node.innerHTML = draw.labelTextbuffer.join('');}
else if ((e.key === "Shift")||(e.key === "Alt")||(e.key=== "Control")||(e.key === "Delete")) { return;}
else if ((e.key !== "Enter")&&(e.key !== "Escape")) {
draw.labelTextbuffer.push(e.key);
draw.fE.node.innerHTML = draw.labelTextbuffer.join('');
}
else { // e.key === Enter or Escape
draw.labelTextbuffer = [];
draw.focusGroup = null;
draw.state = 'rest';
SVG.off(document, 'keydown', edit);
draw.docKeyListenerCount = 0; }
};
};
}); // close of the "onload" function
// ---------------
// SVG Objects
// --------------
function moveableEntity(draw, label='new E') {
let newE = draw.group();
newE.attr({"class": "entity"});
newE.height = 25;
newE.width = 90;
newE.panel = newE.rect(newE.width, newE.height);
newE.panel.data('part', 'panel');
newE.from = newE.put(moveablePoint(draw).cx(0).cy(0));
newE.from.data('part', 'from');
newE.to = newE.put(moveablePoint(draw).cx(newE.width).cy(newE.height));
newE.to.data('part', 'to');
newE.label = newE.text(label).attr({"font-size":"8"});
newE.label.data('part', 'label');
return newE;
};
function moveablePoint(draw) {
let pt = draw.circle(6);
pt.attr({"class": "moveablePoint"});
// pt.attr({class:"handle", 'pointer-events':"all"});
pt.collocates = [];
return pt;
}; // return type: SVG circle with event handlers and event emitters
function newLink(diagram, x1=10, y1=10, x2=50, y2=10) {
// return type: SVG group
let linker = diagram.group().attr({class: "graphics"});
linker.attr({"class": "linker"});
linker.straight = linker.put(diagram.line());
linker.straight.data('part', 'straight');
linker.straight.marker('end', 10,10, function(add){
add.polygon('0,2 0,8 10,5');});
linker.from = linker.put(moveablePoint(diagram).cx(x1).cy(y1));
linker.from.data('part', 'from');
linker.to = linker.put(moveablePoint(diagram).cx(x2).cy(y2));
linker.to.data('part', 'to');
return linker;
}
// Update functions
function entityUpdate(x1=undefined, y1 = undefined) {
let x2 = this.to.cx();
let y2 = this.to.cy();
let txtBBox = this.label.bbox();
if ((x1===undefined)||(y1===undefined)) { // if the points have moved, adjust the box
x1 = this.from.cx();
y1 = this.from.cy();
this.panel.x(x1).y(y1);
this.label.x(x1).y(y1);
this.panel.width(this.to.cx()-this.from.cx());
this.panel.height(this.to.cy()-this.from.cy());
this.to.cx(x2).cy(y2);
}
else { // if the box is moved, adjust the points
this.panel.x(x1).y(y1);
this.label.x(x1).y(y1);
this.from.cx(x1).cy(y1);
let width = (this.panel.width() < txtBBox.width) ? txtBBox.width : this.panel.width(); // size to fit width
this.panel.width(width);
this.to.cx(x1+this.panel.width()).cy(y1+this.panel.height());
};
}
function lineUpdate() { // return line from 'from' to 'to'.
return this.straight.plot(this.from.cx(), this.from.cy(),this.to.cx(),this.to.cy())
};
function sticky(draw) {
if (draw.state === 'grab') {
let rings = ((10 - draw.fE.collocates.length*2) > 2) ? (10 - draw.fE.collocates.length*2) : 2;
draw.fE.attr({fill: "none", r: rings});
let thisring = rings;
for (const collocate of draw.fE.collocates) {
thisring = thisring + 2;
collocate.attr({fill: "none", r: thisring})
};
draw.state = 'move';
};
}
function unsticky(focusElement) {
focusElement.attr({fill: "#0e84b5", r: "3"});
focusElement.parent().update();
for (const collocate of focusElement.collocates)
{collocate.attr({fill: "#0e84b5", r: "3"});};
}
function update_collocates(amoveablepoint) {
let x = amoveablepoint.cx();
let y = amoveablepoint.cy();
for (const joint of amoveablepoint.collocates) {
if (joint.type === 'circle') {
joint.cx(x).cy(y);
joint.parent().update(); }
else {
joint.parent().update();
};
}
}
</code></pre>
<p>I tried to make a jsfiddle but got a lot of errors. This script just expects a <code><div></code> labeled "diagram-0", and there are some styles, but nothing essential.</p>
<p>I also tried to make a jsfiddle but it only rendered the button. I looked at the console and there were a number of errors that made little sense to me.</p>
<p>Finally, its friday afternoon here, so I may be slow to respond.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T04:12:07.847",
"Id": "232770",
"Score": "3",
"Tags": [
"javascript",
"data-visualization",
"svg"
],
"Title": "Browser-editable SVG diagrams using JS & SVG.js"
}
|
232770
|
<p>I wrote a function which takes a byte and shifts the bits around. That is, there shall be the same number of 1 bits and 0 bits in the output but the bits will be shifted in position:</p>
<pre><code>global _main
default rel
section .text
_main:
; Given 1 byte, shift the positions of the bits in the form 74652103
mov bl, 0x5A
; 0101 1010
shift_bits:
; 1. bit 7 stays same
; 2. bit 4 (0x10) gets shifted left by 2 - and with 0001 0000, shift left by 2, or with result
; 3. bit 6 (0x40) gets shifted right by 1
; 4. bit 5 (0x20) gets shifted right by 1
; 5. bit 2 (0x4) gets shifted left by 1
; 6. bit 1 (0x2) gets shifted left by 1
; 7. bit 0 (0x1) gets shifted left by 1
; 8. bit 3 (0x8) gets shifted right by 3
; begin 0101 1010
; expect: 0110 0101
; end 0110 0101
mov al, bl
mov cl, 0
and al, 0x80
or cl, al
mov al, bl
and al, 0x10
shl al, 2
or cl, al
mov al, bl
and al, 0x4
shl al, 1
or cl, al
mov al, bl
and al, 0x2
shl al, 1
or cl, al
mov al, bl
and al, 0x1
shl al, 1
or cl, al
mov al, bl
and al, 0x8
shr al, 3
or cl, al
mov al, bl
and al, 0x2
shl al, 1
mov al, bl
and al, 0x40
shr al, 1
or cl, al
mov byte [A], cl ; Store result in A
go_out:
mov rax, 0x2000001 ; exit - macOS specific!
mov rdi, 0
syscall
section .data
A: db 0
</code></pre>
<p>Is there a more efficient way to do this with fewer instructions or more performant ones?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-13T14:07:29.067",
"Id": "457527",
"Score": "0",
"body": "as long as only 8 bit values are involved, you can also use look-up-table (LUT) with size 256B, then the conversion is basically single `mov` from memory, but I guess you are for some reason trying to avoid this (kinda \"cheat\", but often used in 8b/16b CPU emulators, etc.. to make the processing speed predictable across different types of calculations and also the LUTs are often 10..20 bits to account not only for the source 8b value, but also the \"flag\" register and calculating in single `mov` results of both together)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-13T14:12:49.060",
"Id": "457528",
"Score": "0",
"body": "and about actually doing the calculation with instructions, which instructions you are willing to accept? The example seems to be x86_64, so you would accept also `shrx` and similar? (didn't really try, but I would guess it may be favourable for certain intermediate steps, not affecting flags and specifying both source + destination registers saving a copy instruction)."
}
] |
[
{
"body": "<p>The operation count can be reduced, by using that some bits are moved by the same distance. Bits 0, 1 and 2 can be shifted left in one go. 5 and 6 can be shifted right in one go.</p>\n\n<p>Some shift/bitwise-OR combinations can be written as <code>lea</code>, that would be bad for Pentium 4 but very good on Ryzen and Ice Lake and fine on Haswell/Skylake. Since this is 64bit code it is best to use <code>lea</code> with a 64bit address and then implicitly discard the top half of the result by writing it to a 32bit destination, explicitly using a 32bit address would generate a useless address size override prefix.</p>\n\n<p>The 8 bit operations have a disadvantage on several CPUs that limits their efficiency, they're usually not inherently slow per-se but the problem is that writing to the \"low\" 8 bit register may <a href=\"https://stackoverflow.com/a/45660140/555045\">have a dependency on the whole register</a> (the \"high\" registers are an other story and have their own issues), something like <code>mov al, bl</code> doesn't \"decouple\" the new <code>al</code> from the old <code>al</code> on such CPUs because the write is merged into <code>rax</code>. So unless there is a good reason for writing to an 8 bit register, I would recommend avoiding it, to avoid such odd edge cases of the microarchitecture.</p>\n\n<p>Here is a possible implementation:</p>\n\n<pre><code> ; keep bit 7 at bit 7\n mov eax, ebx\n and eax, 128\n ; shift bits 0, 1, 2 left by 1 and combine\n mov ecx, ebx\n and ecx, 7\n lea eax, [rax + 2*rcx]\n ; shift bit 4 left by 2 and combine\n mov ecx, ebx\n and ecx, 0x10\n lea eax, [rax + 4*rcx]\n ; shift bit 3 right by 3 and combine\n mov ecx, ebx\n and ecx, 8\n shr ecx, 3\n or eax, ecx\n ; shift bits 5 and 6 right by 1 and combine\n shr ebx\n and ebx, 0x30\n or eax, ebx\n ; store result\n mov [A], al\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T07:36:55.377",
"Id": "232780",
"ParentId": "232771",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T04:55:07.103",
"Id": "232771",
"Score": "1",
"Tags": [
"assembly",
"x86"
],
"Title": "Shifting bits in assembly (nasm)"
}
|
232771
|
<p>I have a list like this:</p>
<pre><code>seq = [-2,3,-2,3,5,3,7,1,4,-5,1,4,-5,1,4,-5]
</code></pre>
<p>I want to get all the sequential recurrences and where it happens, I feel the way I'm doing its too brute force and in reality I want this for several lists each with length of about 300.</p>
<pre><code>dic = {}
for p1 in range(len(seq)):
for p2 in range(p1+1,len(seq)):
dic.setdefault(tuple(seq[p1:p2]), []).append((p1,p2))
</code></pre>
<p>which results in all unique sequences of numbers as keys and their positions as values, for example:</p>
<pre><code>#-2,3: [(0,2),(2,4)]
</code></pre>
<p>But also results in a lot of entries that occur only once that don't interest me, I'm 'cleaning' these after by taking only values that have more than 1 entry:</p>
<pre><code>def clean(dic):
cleandic = {}
for key, value in dic.items():
if len(value) > 1:
cleandic.setdefault(key,value)
return cleandic
cleandic = clean(dic)
</code></pre>
<p>Now for the last step I'm trying to get rid of the occurrences that happens inside the bigger ones, so I sorted the dict by reverse len of keys (bigger keys comes first), for example:</p>
<pre><code>#(1,4,-5,1,4,-5) : ([7,13),(10,16)]
#...
#(1,4,-5) : [(7,10),(10,13)]
</code></pre>
<p>The best I came up with to take out the small ones:</p>
<pre><code>sorteddic = dict(sorted(cleandic.items(), key=lambda item: len(item[0]), reverse=True))
onlybigs = {}
while len(sorteddic) > 0:
for key1, values1 in sorteddic.items():
for key2, values2 in sorteddic.copy().items():
if len(key2) == len(key1):
continue
for value1 in values1: #ex: (7,13)
for value2 in values2: #ex: (7,10)
if value2[0] >= value1[0] and value2[1] <= value1[1]:
sorteddic[key2].pop(sorteddic[key2].index(value2))
onlybigs.setdefault(key1, sorteddic.pop(key1))
break
#and a second clean in the end
readydic = clean(onlybigs)
</code></pre>
<p>This last step especially is taking too long because it compares each value for each key and my guess is the whole process can be done more efficiently somehow. </p>
<p>Any insights?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T05:34:31.050",
"Id": "454709",
"Score": "0",
"body": "You have `3-2` in your `seq` list. Is this a subtraction, or are you missing a comma?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T05:42:16.163",
"Id": "454710",
"Score": "0",
"body": "corrected it and some other mistakes in the code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T06:06:05.827",
"Id": "454712",
"Score": "0",
"body": "@ThiagoLuiz, the final `readydict` have lost indexes for the most items `{(1, 4, -5, 1, 4): [(7, 12), (10, 15)], (1, 4, -5, 1): [], (4, -5, 1, 4): [], (1, 4, -5): [], (4, -5, 1): [], (-5, 1, 4): [], (-2, 3): [(0, 2), (2, 4)], (1, 4): [(13, 15)], (4, -5): [], (-5, 1): [], (-2,): [], (3,): [(5, 6)], (1,): [], (4,): [], (-5,): []}` <-- empty lists. Is it not working as expected yet?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T06:09:11.460",
"Id": "454713",
"Score": "0",
"body": "sorry, i just did ```cleandic = {}\nfor key, value in dic.items():\n if len(value) > 1:\n cleandic.setdefault(key,value)``` again at the end"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T06:10:56.037",
"Id": "454714",
"Score": "0",
"body": "@ThiagoLuiz, but you have `readydic`, not `dic` at the end. Please fix and update your code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T06:19:35.333",
"Id": "454715",
"Score": "0",
"body": "Already did it, sorry for that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T07:55:07.777",
"Id": "454718",
"Score": "0",
"body": "@ok, the final `readydic` above contains `{(1, 4, -5, 1, 4): [(7, 12), (10, 15)], (-2, 3): [(0, 2), (2, 4)]}`. Is that intended? i.e. should the result be \"the farthest longest sequence\" and \"the earliest 2-number sequence\" ? Can you clarify ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T10:05:59.797",
"Id": "454729",
"Score": "0",
"body": "Result should be any segment of the initial list that repeats at least once and it's not inside a bigger segment that also repeats. It's also sorted by the size of the segments (reversed)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T05:03:33.843",
"Id": "454877",
"Score": "0",
"body": "Welcome to Code Review! I have rolled back your last edit. Please don't change or add to the code in your question after you have received answers. See [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) Thank you."
}
] |
[
{
"body": "<p>You're doing things the hard way.</p>\n\n<pre><code>dic = {}\nfor p1 in range(len(seq)):\n for p2 in range(p1+1,len(seq)):\n dic.setdefault(tuple(seq[p1:p2]), []).append((p1,p2))\n</code></pre>\n\n<p>For each range, you are calling <code>.setdefault()</code>. You should just use a default dictionary, which can automatically create a list for any unseen keys:</p>\n\n<pre><code>from collections import defaultdict\n\ndic = defaultdict(list)\n\nfor p1 in range(len(seq)):\n for p2 in range(p1 + 1, len(seq)):\n dic[tuple(seq[p1:p2])].append((p1, p2))\n</code></pre>\n\n<hr>\n\n<p>Next, you're filtering the dictionary the hard way.</p>\n\n<pre><code>cleandic = {}\nfor key, value in dic.items():\n if len(value) > 1:\n cleandic.setdefault(key,value)\n</code></pre>\n\n<p>This can be expressed in one line, using list comprehension:</p>\n\n<pre><code>cleandic = { key: val for key, val in dic.items() if len(val) > 1 }\n</code></pre>\n\n<hr>\n\n<p>The next improvement comes from noting that the key portion of <code>(-2, 3): [(0, 2), (2, 4)]}</code> is completely recoverable from the value portion; using <code>(0, 2)</code> or <code>(2, 4)</code> as a slice of <code>seq</code> will return the appropriate sequence. You do not need to maintain a dictionary; a list of lists is sufficient and less complex. Instead of <code>cleandic</code>, you can have:</p>\n\n<pre><code>groups = [ val for val in dic.values() if len(val) > 1 ]\n</code></pre>\n\n<p>Instead of removing the second of these two dictionary values:</p>\n\n<blockquote>\n <p>#(1,4,-5,1,4,-5) : [(7,13),(10,16)]<br>\n #(1,4,-5) : [(7,10),(10,13)] </p>\n</blockquote>\n\n<p>You now just need to remove the second of these two list entries:</p>\n\n<blockquote>\n <p>[(7,13),(10,16)]<br>\n [(7,10),(10,13)] </p>\n</blockquote>\n\n<hr>\n\n<p>You can still sort this by noting that <code>(7,13)</code> represents a sequence of length 6.</p>\n\n<pre><code>groups = sorted(groups, key=lambda item: item[0][1] - item[0][0], reverse=True)\n</code></pre>\n\n<hr>\n\n<p>Any time you have to <code>.copy()</code> is good time to stop and think if there is another way to solve the problem.</p>\n\n<pre><code> for key2, values2 in sorteddic.copy().items():\n ...\n sorteddic[key2].pop(sorteddic[key2].index(value2))\n</code></pre>\n\n<p>Here, you are modifying <code>sorteddic</code> inside the loop, so you clearly can't loop on the <code>sorteddic</code> itself, which explains the need to copy the dictionary first. Since the copy is itself in another loop, you are doing a lot of copies!</p>\n\n<p>Moreover, this isn't even a loop! It is just a way to extract the first item from the dictionary.</p>\n\n<pre><code>for key1, values1 in sorteddic.items():\n ...\n break\n</code></pre>\n\n<p>Rework the algorithm to not modify the container you're looping over:</p>\n\n<pre><code>def subset_of(long_groups, group):\n return any(lg[0] <= g[0] and g[1] <= lg[1] for long_group in long_groups\n for lg in long_group for g in group)\n\n...\n\nlongest_groups = []\nfor group in groups:\n if not subset_of(longest_groups, group):\n longest_group.append(group)\n</code></pre>\n\n<p>Finally, you can rebuild your dictionary with the sequence tuples as keys:</p>\n\n<pre><code>readydic = { tuple(seq[group[0][0]:group[0][1]]): group for group in longest_groups }\n</code></pre>\n\n<p>Since all the dictionary copying has been removed, this should be significantly faster.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T15:25:08.077",
"Id": "454919",
"Score": "0",
"body": "I don't think my example ```seq``` was great, because I have to keep smallers that happens outsite the biggers even if they same the same numbers. So here ```seq = [1,2,3,4,5,6,0,1,2,3,4,5,6,1,2,3,1,2,3,0]``` the ```(1,2,3)``` in the end has to be in readydic. I adapted your code to do this, is it ok if I answer my question with that? And one more question, turning values to list and back do dict doesn't become a time problem with biggers dicts?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T20:50:02.177",
"Id": "454965",
"Score": "0",
"body": "From [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers), in particular the **Posting a self-answer** section, you are allowed to post a self answer, but it \"_must meet the standards of a Code Review answer, just like any other answer. Describe what you changed, and why. Code-only answers that don't actually review the code are insufficient and are subject to deletion_\". Alternately, you could post a new follow-up question, cross-linking one to the other, showing what you've done and why, inviting addition code review feedback."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T21:06:47.367",
"Id": "454967",
"Score": "0",
"body": "There is a performance impact with converting dictionary values to a list, and later turning the list back into a dictionary. However, there is a much, much larger impact repeatedly copying the dictionary once for every entry in the dictionary. A dictionary is a more complex data structure than a list; if you are merely iterating over all entries in the container, using a list instead of a dictionary will not be slower and might be slightly faster. If you want to leave the container as a dictionary, that can work; the important aspect is removing the repeated copies."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T06:16:08.977",
"Id": "232775",
"ParentId": "232772",
"Score": "4"
}
},
{
"body": "<h3>Optimized version</h3>\n<p>The crucial function can be thought through 3 phases:</p>\n<p><em>Aggregating <strong>dictionary of sequential recurrences</strong></em></p>\n<p>As was correctly mentioned <strong><code>defaultdict(list)</code></strong> is a more performant alternative to <code>dic.setdefault</code>.<br>Besides of that, as you've mentioned, input list could be of length <code>300</code>. In that case the initial approach will evaluate <code>len(seq)</code> 44850 times.<br>To optimize that we'll store the size of the input sequence in a separate variable <strong><code>seq_size = len(seq)</code></strong> and refer it in subsequent loops.</p>\n<hr />\n<p><em>Filtering out entries that weren't recurred (occurred once) with ordering</em></p>\n<p>Instead of defining <code>clean</code> inner function and generating a redundant dictionary <code>cleandic</code> - both filtering and sorting can be performed in one pass:</p>\n<pre><code>d = dict(sorted(((k, v) for k, v in d.items() if len(v) > 1),\n key=lambda x: len(x[0]), reverse=True))\n</code></pre>\n<hr />\n<p><em>Filtering out entries that are part (included) of other longer sequences</em></p>\n<p>Instead of falling into a numerous noisy loops - a <em>string membership</em> trick can be applied. It's based on the idea of presenting string representations of <em>short</em> and <em>long</em> sequences as a <em>"needle"</em> and <em>"haystack"</em>.<br>It looks as:\n<code>" 1 4 -5 "</code> <strong>in</strong> <code>" 1 4 -5 1 4 -5 "</code>.<br>Trailing spaces prevent incorrect matches like <code>"1 4 -5"</code> <strong>in</strong> <code>"1 4 -55 11 4 -5"</code> (which would be <em>truthy</em>)</p>\n<hr />\n<p>The new implementation is placed into a function called <strong><code>find_recurrences</code></strong>.<br>(I've moved the old implementation into function <code>find_recurrences_old</code> for comparison)</p>\n<pre><code>from collections import defaultdict\n\n\ndef find_recurrences(seq):\n seq_size = len(seq)\n d = defaultdict(list)\n\n for i in range(0, seq_size):\n for j in range(i + 1, seq_size):\n d[tuple(seq[i:j])].append((i, j))\n\n d = dict(sorted(((k, v) for k, v in d.items() if len(v) > 1),\n key=lambda x: len(x[0]), reverse=True))\n d_copy = d.copy()\n\n for k, v in d_copy.items():\n if k not in d:\n continue\n k_str = f" {' '.join(map(str, k))} "\n for k_ in d.keys() - set([k]):\n if f" {' '.join(map(str, k_))} " in k_str:\n del d[k_]\n\n return d\n</code></pre>\n<hr />\n<p>Ensuring that both functions return the same result:</p>\n<pre><code>In [79]: seq = [-2, 3, -2, 3, 5, 3, 7, 1, 4, -5, 1, 4, -5, 1, 4, -5] \n\nIn [80]: find_recurrences_old(seq) \nOut[80]: {(1, 4, -5, 1, 4): [(7, 12), (10, 15)], (-2, 3): [(0, 2), (2, 4)]}\n\nIn [81]: find_recurrences(seq) \nOut[81]: {(1, 4, -5, 1, 4): [(7, 12), (10, 15)], (-2, 3): [(0, 2), (2, 4)]}\n</code></pre>\n<hr />\n<p>But the <strong>new</strong> version has <em>time performance</em> advantage:</p>\n<pre><code>In [84]: %timeit find_recurrences_old(seq) \n97.3 µs ± 212 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n\nIn [85]: %timeit find_recurrences(seq) \n80.5 µs ± 154 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T02:16:24.177",
"Id": "454872",
"Score": "0",
"body": "checking your answer I found a +1 mistake in my code that got into yours. Edit was to short, in the first loop should be ```for j in range(i + 1, seq_size+1):``` Your code is a big improvement on mine but it gives a different result, the list i gave as exemple just doesn't show it. Try this: ```seq2 = [1,2,3,4,5,6,0,1,2,3,4,5,6,1,2,3,1,2,3]```\nmy code results:\n```{(1, 2, 3, 4, 5, 6): [(0, 6), (7, 13)], (1, 2, 3): [(13, 16), (16, 19)]}```\nyour code results:\n```{(1, 2, 3, 4, 5, 6): [(0, 6), (7, 13)]}```\nThe cause is the \"needle\" and \"haystack\" part.\nAgain, big improvement"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T20:13:43.373",
"Id": "232831",
"ParentId": "232772",
"Score": "3"
}
},
{
"body": "<p>Use <code>collections.defaultdict()</code> rather than <code>dict.setdefault()</code>.</p>\n\n<p>Instead of nested loops to find subsequence, keep a dict mapping items to their positions. For each item in the sequence check if that item was in the sequence before. If it is, only check for subsequences starting at those positions. I think on average, this will do better than the nest loops:</p>\n\n<pre><code>seen_items = defaultdict(list)\n\nfor pos, item in enumerate(sequence):\n if item in seen_items:\n for other_pos in seen_items[item]:\n ...check for matching subsequences starting at pos and other_pos\n ...and add them to the dict of sequences...\n\n seen_items[item].append(pos)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T07:14:12.570",
"Id": "232847",
"ParentId": "232772",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "232775",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T05:02:41.460",
"Id": "232772",
"Score": "4",
"Tags": [
"python",
"algorithm",
"python-3.x",
"sorting"
],
"Title": "Finding sequential recurrences in a list of numbers"
}
|
232772
|
<p><em>Preface: I am learning Rust through the Advent of Code</em></p>
<p>The task is to read lines from a file, parse each as an integer, then provide a summation of all the numbers. My solution looks like this:</p>
<pre class="lang-rust prettyprint-override"><code>use std::fs::File;
use std::io::{self, prelude::*, BufReader};
fn main() -> io::Result<()> {
let file = File::open("day01.txt")?;
let reader = BufReader::new(file);
let mut sum: i32 = 0;
for line in reader.lines() {
let value: i32 = line.unwrap().parse().unwrap();
sum += value
}
println!("{}", sum);
Ok(())
}
</code></pre>
<p>I'd like to use the iterator methods <code>map</code> and <code>sum</code> in my solution, but I haven't figured out how to do so with the type checker. Suggestions?</p>
|
[] |
[
{
"body": "<p>That's how you use <code>Iterator::sum</code>:</p>\n\n<pre><code>use std::fs::File;\nuse std::io::{self, prelude::*, BufReader};\n\nfn main() -> io::Result<()> {\n let file = File::open(\"day01.txt\")?;\n let reader = BufReader::new(file);\n let sum: i32 = reader\n .lines()\n .map(|line| line.unwrap().parse::<i32>().unwrap())\n .sum();\n\n println!(\"{}\", sum);\n\n Ok(())\n}\n</code></pre>\n\n<p>You must first say to what type the line must be parsed: <code>parse::<i32>()</code> and then, you must give the sum a type because the output of the <code>Add</code> trait is not the same as <code>self</code> and <code>other</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T09:59:07.347",
"Id": "232787",
"ParentId": "232774",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "232787",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T05:35:36.590",
"Id": "232774",
"Score": "4",
"Tags": [
"beginner",
"rust",
"iterator"
],
"Title": "Summation Over Lines in a File (Advent of Code 2018 Day 1)"
}
|
232774
|
<p>I have been assigned to implement the morphological dilation operation without using MATLAB's imdilate, and I came up with the following solution:</p>
<pre><code>% -------------------------------------------------------------------------
% -> Morphological Operations
% -> Image Dilation
% -------------------------------------------------------------------------
% -------------------------------------------------------------------------
% - [Pre-Operation Code: Getting Everything Ready] -
% -------------------------------------------------------------------------
% Starting With A Clean (Workspace) And (Command Window)
clear;
clc;
% Creating A Matrix Consisting Of 0s And 1s Representing A Binary Image.
binaryImage = [ ...
0 0 0 0 0 0
0 0 1 1 0 0
0 0 1 1 0 0
0 0 0 0 0 0];
% Creating A Matrix Representing Our Structuring Element
structuringElement = [ ...
0 1 0
1 1 1
0 1 0];
% Getting The Number Of Rows (Height) And The Number Of Columns (Width) Of The Binary Image
[imageRows, imageColumns] = size(binaryImage);
% Getting The Number Of Rows (Height) And The Number Of Columns (Width) Of The Structuring Element
[structuringRows, structuringColumns] = size(structuringElement);
% Creating An Empty Matrix That Will Be Used To Store The Final Processed Image
dilatedImage = zeros(imageRows, imageColumns);
ref = imdilate(binaryImage, structuringElement);
% -------------------------------------------------------------------------
% - [Dilation Operation] -
% -------------------------------------------------------------------------
% Going Over Each Row In The Binary Image
for i = 1:imageRows
% Going Over Each Column In The Binary Image
for j = 1:imageColumns
% If The Current Pixel Is A Foreground Pixel (1)
if (binaryImage(i, j) == 1)
% Going Over Each Row In The Structuring Element
for k = 1:structuringRows
% Going Over Each Column In The Structuring Element
for l = 1:structuringColumns
% If The Current Pixel In The Structuring Element Is A Foreground Pixel (1)
if (structuringElement(k, l) == 1)
dilatedImage(i + k - 2, j + l - 2) = 1;
end
end
end
end
end
end
subplot(1, 3, 1), imshow(binaryImage), title('Original Image');
subplot(1, 3, 2), imshow(dilatedImage), title('Dilated Image');
subplot(1, 3, 3), imshow(ref), title('MATLAB imdilate');
</code></pre>
<p>I am open to any suggestions! Thank you in advance.</p>
|
[] |
[
{
"body": "<p>I have a few different comments.</p>\n\n<p>Firstly, for 2D arrays like in your example, you can simply do <code>conv2(binaryImage,structuringElement,'same')</code>, it's equivalent to <code>imdilate</code> (and about 4 times faster). That might not be acceptable for your case if you are supposed to write the code yourself though. </p>\n\n<p>Next, and importantly, your code has a logic error. If your binary image has a white pixel along any edge, the results are incorrect or you get an error (if it's in the top row). This is due to your indexing into <code>dilatedImage</code> where <code>i+k-2</code> can be less than 1, or can be larger than the number of rows in <code>dilatedImage</code>.</p>\n\n<p>You have a lot of comments, which is better than none, but I think it's excessive here. It is very clear what this line of code does <code>[imageRows, imageColumns] = size(binaryImage);</code>, for example, even for people who don't know Matlab. Some of your comments make the lines very long as well.</p>\n\n<p>A minor issue, I'd move the <code>imdilate</code> command somewhere else, that part of the code is where you are re-creating <code>imdilate</code>, I think it's nicer to separate the verification part.</p>\n\n<p>Another minor issue is in using <code>i</code> and <code>j</code> as loop indices. Since <code>i</code> and <code>j</code> can be used for complex numbers in Matlab, by convention they are avoided as loop indices (although I do not usually worry about this).</p>\n\n<p>I would put the code that does the work into its own function that takes <code>binaryImage</code> and <code>structuringElement</code> as inputs and returns <code>dilatedImage</code>.</p>\n\n<p>The big thing here is you 6 nested <code>for</code>/<code>if</code> statements, which is hard to read and hard to code. Historically, such nested loops would have been very slow in Matlab, but nowadays it's not such a concern. One thing you should do is swap the order of the first two <code>for</code> loops. Matlab stores arrays in a column major format, so loop over the columns first, then the rows. This gives roughly a 20-25% speedup in my tests. Additionally, checking to remove the out-of-bounds error is also a speedup, since we only set pixels to one if they are inside the image, irregardless of the value of the structuring array. Check out this version of your loop:</p>\n\n<pre><code>for j = 1:imageColumns\n for i = 1:imageRows\n if binaryImage(i, j) == 1\n % Loop through the entries of the structuring element\n for l = 1:structuringColumns\n for k = 1:structuringRows\n % make sure the new pixel is inside the image\n if i+k-2>0 && j+l-2>0 && i+k-2<=imageRows && j+l-2<=imageColumns\n % make a white pixel if necessary\n if structuringElement(k, l)==1\n dilatedImage(i + k - 2, j + l - 2) = 1;\n end\n end\n end\n end\n end\n end\nend\n</code></pre>\n\n<p>Of course it would be nice to avoid writing all these loops, and that can be done. This next method is only slightly faster, but to me is cleaner. The idea is to first find the white pixels, and just loop over them, for each one working out which surrounding pixels should be changed.</p>\n\n<pre><code>[rowIdx,colIdx] = find(binaryImage); % the indices of white pixels in the image\n[maskRowIdx,maskColIdx] = find(structuringElement); % indices of structuring elements\n\n% now get indices of structuring elements relative to the centre of the array\nmaskRowIdx = maskRowIdx - floor(structuringRows/2) - 1;\nmaskColIdx = maskColIdx - floor(structuringColumns/2) - 1;\n\ndilatedImage = zeros(imageRows, imageColumns);\n\n% loop over each white pixel in the image\nfor i = 1:numel(rowIdx)\n % these are just the indices of the pixel\n rI = rowIdx(i);\n cI = colIdx(i);\n\n % now loop over each non-zero element of the structuring array\n for j = 1:numel(maskRowIdx)\n % the position of the pixel to change is (r,c)\n r = rI+maskRowIdx(j);\n c = cI+maskColIdx(j);\n\n % if the pixel is inside the image, we make it a 1\n if r>0 && c>0 && r<=imageRows && c<=imageColumns\n dilatedImage(r,c) = 1;\n end\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-01T16:13:47.910",
"Id": "455788",
"Score": "0",
"body": "Thank you a lot for the tips! By the way, what about the erosion operation implementation? Is it possible to implement it following the same code you provided just with some modifications? And what will I modify?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-01T22:24:34.580",
"Id": "455824",
"Score": "0",
"body": "The simplest thing to do is just use the same code but operate on `~binaryImage` instead of `binaryImage`, that is, swap the black and white pixels, do a dilation, swap the pixels back again."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-29T04:01:45.587",
"Id": "233140",
"ParentId": "232777",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "233140",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T07:06:31.953",
"Id": "232777",
"Score": "2",
"Tags": [
"image",
"matrix",
"matlab"
],
"Title": "My custom implementation of MATLAB's imdilate"
}
|
232777
|
<p>I've already created a code in <strong>python</strong> here with <em>almost</em> the same logic:<br>
<a href="https://codereview.stackexchange.com/questions/217767/tic-tac-toe-with-changeable-board-size-part-1">Tic-Tac-Toe with changeable board size (Part 1)</a><br>
<a href="https://codereview.stackexchange.com/questions/232698/tic-tac-toe-with-changeable-board-size-part-2">Tic-Tac-Toe with changeable board size (Part 2)</a></p>
<p>Here's the code in C++. As I'm still a beginner in C++, I don't know many of the STL functions or such. Please help me on improving the code</p>
<pre><code>#include <bits/stdc++.h>
#include <string.h>
#include <stdlib.h>
#include <vector>
using namespace std;
class TicTacToe{
public:
vector<vector<char>> board{{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};
vector<vector<char>> s_board{{' ', ' ', ' '}, {' ', ' ', ' '}, {' ', ' ', ' '}};
string player = "Player";
int s;
int start = 0;
char X = 'X';
char O = 'O';
int countWins(char p1, char p2){
int count = 0;
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
if(board[i][j] != p1 && board[i][j] != p2){
char c = board[i][j];
board[i][j] = p1;
if(win(p1) == 1)
count++;
board[i][j] = c;
}
}
}
return count;
}
void getInsaneAIMove(char ai, char pl, int x = 0, string name = ""){
srand(time(NULL));
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
if(board[i][j] != ai && board[i][j] != pl){
char c = board[i][j];
board[i][j] = ai;
if(win(ai) == 1 || tie() == 1){
if(x) cout << name << " Moved To Grid " << i * 3 + j + 1 << endl;
return ;
}
board[i][j] = c;
}
}
}
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
if(board[i][j] != ai && board[i][j] != pl){
char c = board[i][j];
board[i][j] = pl;
if(win(pl) == 1 || tie() == 1){
board[i][j] = ai;
if(x) cout << name << " Moved To Grid " << i * 3 + j + 1 << endl;
return ;
}
board[i][j] = c;
}
}
}
vector<vector<int>> wins2;
int l = 0;
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
if(board[i][j] != ai && board[i][j] != pl){
char c = board[i][j];
board[i][j] = ai;
if(countWins(ai, pl) > 1){
l++;
vector<int> r{i, j};
wins2.push_back(r);
}
board[i][j] = c;
}
}
}
if(l){
vector<int> m = wins2[rand() % l];
board[m[0]][m[1]] = ai;
if(x) cout << name << " Moved To Grid " << m[0] * 3 + m[1] + 1 << endl;
return ;
}
if(board[1][1] == '5'){
board[1][1] = ai;
if(x) cout << name << " Moved To Grid 5\n";
return ;
}
int l1 = 0, l2 = 0;
vector<vector<int>> pos_edges{{0, 0}, {0, 2}, {2, 0}, {2, 2}};
vector<vector<int>> edges;
for(int i = 0; i < 4; i++){
int x = pos_edges[i][0], y = pos_edges[i][1];
if(board[x][y] != ai && board[x][y] != pl){
edges.push_back(pos_edges[i]);
l1++;
}
}
if(l1){
vector<int> r = edges[rand() % l1];
board[r[0]][r[1]] = ai;
if(x) cout << name << " Moved To Grid " << r[0] * 3 + r[1] + 1 << endl;
return ;
}
vector<vector<int>> pos_middles{{0, 1}, {1, 0}, {1, 2}, {2, 1}};
vector<vector<int>> middles;
for(int i = 0; i < 4; i++){
int x = pos_middles[i][0], y = pos_middles[i][1];
if(board[x][y] != ai && board[x][y] != pl){
middles.push_back(pos_middles[i]);
l2++;
}
}
vector<int> r = middles[rand() % l2];
board[r[0]][r[1]] = ai;
if(x) cout << name << " Moved To Grid " << r[0] * 3 + r[1] + 1 << endl;
return ;
}
void getHardAIMove(char ai, char pl, int x = 0, string name = ""){
srand(time(NULL));
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
if(board[i][j] != ai && board[i][j] != pl){
char c = board[i][j];
board[i][j] = ai;
if(win(ai) == 1 || tie() == 1){
if(x) cout << name << " Moved To Grid " << i * 3 + j + 1 << endl;
return ;
}
board[i][j] = c;
}
}
}
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
if(board[i][j] != ai && board[i][j] != pl){
char c = board[i][j];
board[i][j] = pl;
if(win(pl) == 1 || tie() == 1){
board[i][j] = ai;
if(x) cout << name << " Moved To Grid " << i * 3 + j + 1 << endl;
return ;
}
board[i][j] = c;
}
}
}
int l = 0;
vector<vector<int>> possible{{0, 0}, {0, 2}, {2, 0}, {2, 2},
{0, 1}, {1, 0}, {1, 2}, {2, 1}};
vector<vector<int>> available;
for(int i = 0; i < 8; i++){
int x = possible[i][0], y = possible[i][1];
if(board[x][y] != ai && board[x][y] != pl){
available.push_back(possible[i]);
l++;
}
}
vector<int> r = available[rand() % l];
board[r[0]][r[1]] = ai;
if(x) cout << name << " Moved To Grid " << r[0] * 3 + r[1] + 1 << endl;
return ;
}
void getEasyAIMove(char ai, char pl, int x = 0, string name = ""){
srand(time(NULL));
int l = 0;
vector<vector<int>> possible{{0, 0}, {0, 2}, {2, 0}, {2, 2},
{0, 1}, {1, 0}, {1, 2}, {2, 1}};
vector<vector<int>> available;
for(int i = 0; i < 8; i++){
int x = possible[i][0], y = possible[i][1];
if(board[x][y] != ai && board[x][y] != pl){
available.push_back(possible[i]);
l++;
}
}
vector<int> r = available[rand() % l];
board[r[0]][r[1]] = ai;
if(x) cout << name << " Moved To Grid " << r[0] * 3 + r[1] + 1 << endl;
return ;
}
void getUserMove(char p1, char p2){
int g;
cout << "Please Enter Grid Number (1 - 9) : ";
cin >> g;
g -= 1;
int x = g / 3;
int y = g % 3;
if(board[x][y] == p1 || board[x][y] == p2){
cout << "Please Enter A Valid Move\n" << endl;
getUserMove(p1, p2);
return ;
}
cout << endl << player << " Moved To Grid " << g + 1;
board[x][y] = p1;
cout << "\n";
}
void getWin(char p){
bool r1 = board[0][0] == board[0][1] && board[0][1] == board[0][2] && board[0][0] == p;
bool r2 = board[1][0] == board[1][1] && board[1][1] == board[1][2] && board[1][0] == p;
bool r3 = board[2][0] == board[2][1] && board[2][1] == board[2][2] && board[2][0] == p;
bool c1 = board[0][0] == board[1][0] && board[1][0] == board[2][0] && board[0][0] == p;
bool c2 = board[0][1] == board[1][1] && board[1][1] == board[2][1] && board[0][1] == p;
bool c3 = board[0][2] == board[1][2] && board[1][2] == board[2][2] && board[0][2] == p;
bool d1 = board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] == p;
bool d2 = board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[0][2] == p;
if(r1 == 1) {s_board[0][0] = p; s_board[0][1] = p; s_board[0][2] = p;}
if(r2 == 1) {s_board[1][0] = p; s_board[1][1] = p; s_board[1][2] = p;}
if(r3 == 1) {s_board[2][0] = p; s_board[2][1] = p; s_board[2][2] = p;}
if(c1 == 1) {s_board[0][0] = p; s_board[1][0] = p; s_board[2][0] = p;}
if(c2 == 1) {s_board[0][1] = p; s_board[1][1] = p; s_board[2][1] = p;}
if(c3 == 1) {s_board[0][2] = p; s_board[1][2] = p; s_board[2][2] = p;}
if(d1 == 1) {s_board[0][0] = p; s_board[1][1] = p; s_board[2][2] = p;}
if(d2 == 1) {s_board[0][2] = p; s_board[1][1] = p; s_board[2][0] = p;}
}
void print1(){
cout << " | |\n";
cout << " " << board[0][0] << " | " << board[0][1] << " | " << board[0][2] << "\n";
cout << " | |\n";
cout << "---------------------\n";
cout << " | |\n";
cout << " " << board[1][0] << " | " << board[1][1] << " | " << board[1][2] << "\n";
cout << " | |\n";
cout << "---------------------\n";
cout << " | |\n";
cout << " " << board[2][0] << " | " << board[2][1] << " | " << board[2][2] << "\n";
cout << " | |\n";
cout << "\n";
}
void print2(){
cout << board[0][0] << " | " << board[0][1] << " | " << board[0][2] << "\n";
cout << "---------\n";
cout << board[1][0] << " | " << board[1][1] << " | " << board[1][2] << "\n";
cout << "---------\n";
cout << board[2][0] << " | " << board[2][1] << " | " << board[2][2] << "\n";
cout << "\n";
}
void printWin(char p){
getWin(p);
cout << s_board[0][0] << " | " << s_board[0][1] << " | " << s_board[0][2] << endl;
cout << "---------\n";
cout << s_board[1][0] << " | " << s_board[1][1] << " | " << s_board[1][2] << endl;
cout << "---------\n";
cout << s_board[2][0] << " | " << s_board[2][1] << " | " << s_board[2][2] << endl;
cout << endl;
}
string getRandomName(){
srand(time(NULL));
string names[250] = {
"Jacob", "Michael",
"Joshua", "Ethan", "Matthew", "Daniel",
"Christopher", "Andrew", "Anthony", "William",
"Joseph", "Alexander", "David", "Ryan",
"Noah", "James", "Nicholas", "Tyler",
"Logan", "John", "Christian", "Jonathan",
"Nathan", "Benjamin", "Samuel", "Dylan",
"Brandon", "Gabriel", "Elijah", "Aiden",
"Angel", "Jose", "Zachary", "Caleb",
"Jack", "Jackson", "Kevin", "Gavin",
"Mason", "Isaiah", "Austin", "Evan",
"Luke", "Aidan", "Justin", "Jordan",
"Robert", "Isaac", "Landon", "Jayden",
"Thomas", "Cameron", "Connor", "Hunter",
"Jason", "Diego", "Aaron", "Bryan",
"Owen", "Lucas", "Charles", "Juan",
"Luis", "Adrian", "Adam", "Julian",
"Alex", "Sean", "Nathaniel", "Carlos",
"Jeremiah", "Brian", "Hayden", "Jesus",
"Carter", "Sebastian", "Eric", "Xavier",
"Brayden", "Kyle", "Ian", "Wyatt",
"Chase", "Cole", "Dominic", "Tristan",
"Carson", "Jaden", "Miguel", "Steven",
"Caden", "Kaden", "Antonio", "Timothy",
"Henry", "Alejandro", "Blake", "Liam",
"Richard", "Devin", "Riley", "Jesse",
"Seth", "Victor", "Brady", "Cody",
"Jake", "Vincent", "Bryce", "Patrick",
"Colin", "Marcus", "Cooper", "Preston",
"Kaleb", "Parker", "Josiah", "Oscar",
"Ayden", "Jorge", "Ashton", "Alan",
"Jeremy", "Joel", "Trevor", "Eduardo",
"Ivan", "Kenneth", "Mark", "Alexis",
"Omar", "Cristian", "Colton", "Paul",
"Levi", "Damian", "Jared", "Garrett",
"Eli", "Nicolas", "Braden", "Tanner",
"Edward", "Conner", "Nolan", "Giovanni",
"Brody", "Micah", "Maxwell", "Malachi",
"Fernando", "Ricardo", "George", "Peyton",
"Grant", "Gage", "Francisco", "Edwin",
"Derek", "Max", "Andres", "Javier",
"Travis", "Manuel", "Stephen", "Emmanuel",
"Peter", "Cesar", "Shawn", "Jonah",
"Edgar", "Dakota", "Oliver", "Erick",
"Hector", "Bryson", "Johnathan", "Mario",
"Shane", "Jeffrey", "Collin", "Spencer",
"Abraham", "Leonardo", "Brendan", "Elias",
"Jace", "Bradley", "Erik", "Wesley",
"Jaylen", "Trenton", "Josue", "Raymond",
"Sergio", "Damien", "Devon", "Donovan",
"Dalton", "Martin", "Landen", "Miles",
"Israel", "Andy", "Drew", "Marco",
"Andre", "Gregory", "Roman", "Ty",
"Jaxon", "Avery", "Cayden", "Jaiden",
"Roberto", "Dominick", "Rafael", "Grayson",
"Pedro", "Calvin", "Camden", "Taylor",
"Dillon", "Braxton", "Keegan", "Clayton",
"Ruben", "Jalen", "Troy", "Kayden",
"Santiago", "Harrison", "Dawson", "Corey",
"Maddox", "Leo", "Johnny", "Kai",
"Drake", "Julio", "Lukas", "Kaiden",
"Zane", "Aden", "Frank", "Simon",
"Sawyer", "Marcos", "Hudson", "Trey"
};
string name = names[rand() % 250];
return name;
}
void help(){
system("CLS");
string option;
cout << "B for Back\n\n";
cout << "1.) Rules\n";
cout << "2.) Tips\n";
cout << "3.) About\n";
cout << "\nPlease Enter Your Option : "; cin >> option;
cout << endl;
system("CLS");
if(option == "b" || option == "B")
return ;
if(option == "1")
rules();
if(option == "2")
tips();
if(option == "3")
about();
system("pause");
system("CLS");
help();
}
void about(){
cout << "This Game Of Tic-Tac-Toe Is Created By Srivaths\n";
cout << "If You Are Unfamiliar With This Game, Please Read The Rules And Tips\n";
cout << "Enjoy!!\n\n";
}
void changeName(){
cout << "Please Enter Your Name : "; cin >> player;
}
void changeBoard(){
system("CLS");
cout << "B for Back\n\n";
cout << "1.)\n\n";
print1();
cout << "2.)\n\n";
print2();
cout << endl;
string option;
cout << "\nPlease Enter Your Option : "; cin >> option;
if(option == "b" || option == "B")
return ;
if(option == "1") s = 1;
if(option == "2") s = 2;
}
void changeColor(){
system("CLS");
string c = "color ";
string option;
cout << "B for Back\n\n";
cout << "1 = Blue\n";
cout << "2 = Green\n";
cout << "3 = Aqua\n";
cout << "4 = Red\n";
cout << "5 = Purple\n";
cout << "6 = Yellow\n";
cout << "7 = White\n";
cout << "8 = Gray\n";
cout << "9 = Light Blue\n";
cout << "A = Light Green\n";
cout << "B = Light Aqua\n";
cout << "C = Light Red\n";
cout << "D = Light Purple\n";
cout << "E = Light Yellow\n";
cout << "F = Bright White\n";
cout << "\nPlease Enter Your Option : "; cin >> option;
if(option == "b" || option == "B")
return ;
const char* x = (c + option).c_str();
system(x);
}
void changeCharacters(){
system("CLS");
cout << "Please Enter Character For Player 1 (currently " << X << ") : "; cin >> X;
cout << "Please Enter Character For Player 2 (currently " << O << ") : "; cin >> O;
}
void settings(){
system("CLS");
string option;
cout << "B for Back\n\n";
cout << "1.) Change Name\n";
cout << "2.) Change Board\n";
cout << "3.) Change Color\n";
cout << "4.) Change Characters\n";
cout << "\nPlease Enter Your Option : "; cin >> option;
if(option == "b" || option == "B")
return ;
if(option == "1") changeName();
if(option == "2") changeBoard();
if(option == "3") changeColor();
if(option == "4") changeCharacters();
system("CLS");
settings();
}
void main_menu(){
system("CLS");
string option;
if(start == 0){
intro();
start = 1;
main_menu();
return ;
}
cout << "Hello " << player << endl;
cout << "\nQ for Quit\n\n";
cout << "1.) Help\n";
cout << "2.) Settings\n";
cout << "3.) Play\n";
cout << "\nPlease Enter Your Option : "; cin >> option;
if(option == "1")
help();
if(option == "2")
settings();
if(option == "3"){
initialize();
play('X', 'O');
}
if(option == "q" || option == "Q"){
cout << "Thanks For Playing!\n";
return ;
}
system("CLS");
main_menu();
}
void rules(){
cout << "1.) In Tic-Tac-Toe, There Are 2 Players \n\tAnd Their Characters Are X and O respectively\n";
cout << "2.) Any Row Or Column or Diagonal Filled With The Same Characters Is A Win\n";
cout << "3.) A Board Where There Are No Moves Left Is A Tie Or Draw\n";
cout << "4.) You Are Not Allowed To Place Characters Over Another\n";
cout << endl;
}
void tips(){
cout << "1.) Always Try To Capture The Center\n";
cout << "2.) Next Try To Capture The Edges\n";
cout << "3.) Be Aware Of Instant Moves\n";
cout << "4.) Always Try To Think A Move Ahead\n";
cout << "5.) Try The Easy Bot To Get The Hang Of The Game\n";
cout << endl;
}
void intro(){
initialize();
cout << "Hello Player, ";
changeName();
cout << "\nHello " << player << ", ";
cout << "Welcome To The Game Of Tic-Tac-Toe!!\n";
string know;
cout << "Are You Familiar With The Game? (y / n) : "; cin >> know;
if(know == "n" || know == "N"){
cout << "\nFirst A Little Introduction To The Rules : \n\n";
rules();
cout << "\nNext A Few Tips : \n\n";
tips();
cout << "\nAnd That's ALL!!!\n\n";
system("pause");
cout << "\n\n";
}
cout << "\nPlease Pick Your Board Preference : \n\n";
cout << "1.)\n";
print1();
cout << "2.)\n\n";
print2();
cout << endl;
string option;
cout << "Please Enter Your Option : "; cin >> option;
if(option == "1") s = 1;
if(option == "2") s = 2;
cout << endl;
cout << "Change Characters Via [Main Menu -> Settings -> Change Characters]\n";
cout << endl;
cout << "Here You Must Try Your Luck Against Three Levels!!\n\n";
cout << "1.) Easy\n";
cout << "2.) Hard\n";
cout << "3.) Insane\n";
cout << endl;
cout << "Can YOU Beat Them ALL????\n";
cout << "Let's See....\n\n";
system("pause");
system("CLS");
}
void play(char p1, char p2){
system("CLS");
initialize();
srand(time(NULL));
string computer = getRandomName();
int level;
cout << "1.) Easy\n";
cout << "2.) Hard\n";
cout << "3.) Insane\n";
cout << endl;
cout << "Please Enter Level : "; cin >> level;
system("CLS");
while(computer == player){
computer = getRandomName();
}
cout << "\t\t" << player << " VS " << computer << "\n\n\n";
int c = rand() % 2;
char pl = p1, ai = p2;
if(c == 0){
ai = p1;
pl = p2;
cout << "\n" << computer << " Goes First!\n\n\n";
}
else {
cout << "\n" << player << " Goes First!\n\n\n";
if(s == 1) print1();
else print2();
}
int d = 0;
while(true){
int t = d % 2;
if(t == c){
if(level == 1) getEasyAIMove(ai, pl, 1, computer);
if(level == 2) getHardAIMove(ai, pl, 1, computer);
if(level == 3) getInsaneAIMove(ai, pl, 1, computer);
if(s == 1) print1();
else print2();
if(win(ai)){
cout << computer << " Wins!\n" << endl;
cout << "Below Is How " << computer << " Won\n\n";
printWin(ai);
break;
}
}
else {
getUserMove(pl, ai);
if(s == 1) print1();
else print2();
if(win(pl)){
cout << player << " Wins!\n";
cout << "Below Is How " << player << " Won\n\n";
printWin(pl);
break;
}
}
if(tie()){
cout << "Tie!\n";
break;
}
d += 1;
}
playAgain(p1, p2);
}
void initialize(){
board[0][0] = '1'; s_board[0][0] = ' ';
board[0][1] = '2'; s_board[0][1] = ' ';
board[0][2] = '3'; s_board[0][2] = ' ';
board[1][0] = '4'; s_board[1][0] = ' ';
board[1][1] = '5'; s_board[1][1] = ' ';
board[1][2] = '6'; s_board[1][2] = ' ';
board[2][0] = '7'; s_board[2][0] = ' ';
board[2][1] = '8'; s_board[2][1] = ' ';
board[2][2] = '9'; s_board[2][2] = ' ';
}
void playAgain(char p1, char p2){
cout << "\n";
string option;
cout << "Would You Like To Play Again? (y(yes) / n(no) / m(Main Menu) : "; cin >> option;
if(option == "y" || option == "Y")
play(p1, p2);
else if(option == "n" || option == "N")
return ;
else if(option == "m" || option == "M")
return ;
else {
cout << "\nPlease Enter a Valid Option";
playAgain(p1, p2);
}
}
bool win(char p){
bool r1 = board[0][0] == board[0][1] && board[0][1] == board[0][2] && board[0][0] == p;
bool r2 = board[1][0] == board[1][1] && board[1][1] == board[1][2] && board[1][0] == p;
bool r3 = board[2][0] == board[2][1] && board[2][1] == board[2][2] && board[2][0] == p;
bool c1 = board[0][0] == board[1][0] && board[1][0] == board[2][0] && board[0][0] == p;
bool c2 = board[0][1] == board[1][1] && board[1][1] == board[2][1] && board[0][1] == p;
bool c3 = board[0][2] == board[1][2] && board[1][2] == board[2][2] && board[0][2] == p;
bool d1 = board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[0][0] == p;
bool d2 = board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[0][2] == p;
return r1 || r2 || r3 || c1 || c2 || c3 || d1 || d2;
}
bool tie(){
bool c1 = board[0][0] != '1';
bool c2 = board[0][1] != '2';
bool c3 = board[0][2] != '3';
bool c4 = board[1][0] != '4';
bool c5 = board[1][1] != '5';
bool c6 = board[1][2] != '6';
bool c7 = board[2][0] != '7';
bool c8 = board[2][1] != '8';
bool c9 = board[2][2] != '9';
return c1 && c2 && c3 && c4 && c5 && c6 && c7 && c8 && c9;
}
};
int main()
{
TicTacToe game;
game.main_menu();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T13:36:51.677",
"Id": "454750",
"Score": "0",
"body": "The code is either \"almost the same\", or it is \"similar\". \"Almost similar\" sounds like \"totally different\" :) Anyway, avoid one letter variables, or at least the small \"L\", I keep reading it as \"one\", In either case i don't know what it is for..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T13:45:54.567",
"Id": "454751",
"Score": "0",
"body": "@slepic Yes, I will edit my question fixing it. And `l` is for the length"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T07:09:56.310",
"Id": "232778",
"Score": "4",
"Tags": [
"c++",
"c++11",
"tic-tac-toe",
"c++14"
],
"Title": "Tic Tac Toe with different level AI"
}
|
232778
|
<p>I am creating routes from an array of menuItems. I have written a recursive function, which works fine but I think the code can be improved. So, I need you guys to review my code and suggest me some changes.</p>
<p>Here is the code:</p>
<pre><code>const accumulator = [];
const renderRoutes = (_menuItems) => {
_menuItems.forEach((menuItem) => {
accumulator.push(
<Route
exact
path={menuItem.path}
render={props => (
<Scene
{...props}
menuItem={menuItem}
/>
)}
/>,
);
if (menuItem.children) {
renderRoutes(menuItem.children);
}
});
return accumulator;
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T07:43:42.733",
"Id": "454717",
"Score": "0",
"body": "One simple recommendation would be to not use recursion."
}
] |
[
{
"body": "<p>Avoid recursion, avoid putting the accumulator out of the function that fills it.</p>\n\n<p>My favourite phrase: Every recursive algorithm can be rewritten without recursion. In worst case, using one (extra) stack.</p>\n\n<pre><code>function renderRoutes(menuItems) {\n let accumulator = [];\n let queue = [];\n queue.concat(menuItems);\n while (queue.length > 0) {\n const item = queue.shift();\n accumulator.push(route(item))\n queue.concat(item.children);\n }\n return accumulator;\n}\n</code></pre>\n\n<p>The <code>route(item)</code> is the same as your <code><Route....</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T08:16:56.573",
"Id": "454719",
"Score": "0",
"body": "Thank for suggesting the solution. I took a look at your solution. I will implement it. But a question: Why should we avoid recursion?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T08:42:48.040",
"Id": "454721",
"Score": "1",
"body": "@Vishal Recursion puts all stuff onto the implicit stack.Usualy at least some of the data is not necesary to be there.And in most cases you cannot change the size of implicit stack.While you can allow explicit stack to have size whatever you have memory for. In general (not sure in js) recursion deepening may be restricted to some level. Also every call introduces a jump, which is (minor) performance drop. Explicit stack will often reduce the memory consumption greatly and improve performance slightly. Some recursive algorithms can even be implemented entirely without stack (but not your case)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T09:00:16.387",
"Id": "454723",
"Score": "1",
"body": "@Vishal the only advantage of recursive algorithms is that they are intuitively easy to write and understand. But nonrecursive variant will always be better in terms of memory and time complexity. (Well you can Always screw up but if everything Is done properly, it Will be better)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T09:28:46.070",
"Id": "454724",
"Score": "0",
"body": "Got it! Thank you for the explanation."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T07:53:01.407",
"Id": "232781",
"ParentId": "232779",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "232781",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T07:34:58.237",
"Id": "232779",
"Score": "2",
"Tags": [
"javascript",
"recursion",
"react.js"
],
"Title": "recursive function improvement"
}
|
232779
|
<p>I am trying to make an IOS tool similar to Android's ValueAnimator... <em>more or less</em></p>
<p>This is useful for situations where you simply want a value to "animate" over time, but rather than necessarily attaching that value to some view property, it is available to use as you wish. Imagine applying it to an audio filter, for example.</p>
<p>It works like a Timer/NSTimer except that is passes a value back to the selector which behaves differently depending on the arguments sent to the initializer.</p>
<p><strong>Concerns:</strong></p>
<p>Is there a way to tidy up the numerous functions into something like a dictionary? (I'm not that advanced at Swift)</p>
<p>Is there a way of accomplishing the same functionality -- passing a "listener" function in on initialization which will be called back with the animated value as an argument -- but <em>without using a selector?</em> ... I ask because of the nasty "MyNSDoubleObject" workaround.</p>
<p>Any other improvements... this is my first question on here.</p>
<p><strong>Code:</strong></p>
<pre><code>import Foundation
// this class is a work-around for the fact that we can't pass a raw value (int, double, etc.) through a selector -- must be object
class MyNSDoubleObject: NSObject {
var val: Double
init(val: Double) {
self.val = val
}
}
class ValueAnimator : NSObject {
// args
private let sampleRate: Int
private let functionType: FunctionType
private let selector: Selector
private let target: AnyObject
// computed from args
private let maxIterations: Int
private let timeInterval: Double
private var X_currentRepIndex: Int = 0 // domain
private var F_of_X = MyNSDoubleObject(val: 0.0) // range
// other
private var timer = Timer()
enum FunctionType {
case SINE_WAVE_FROM_0_TO_1_TO_0
case SINE_WAVE_FROM_0_TO_1
case SINE_WAVE_FROM_1_TO_0
}
// Public functions
init(durationInSeconds: Int, sampleRate: Int, functionType: FunctionType, selector: Selector, target: AnyObject) {
self.sampleRate = sampleRate
self.maxIterations = durationInSeconds * sampleRate
self.timeInterval = 1.0/Double(sampleRate)
self.functionType = functionType
self.selector = selector
self.target = target
}
func start() {
timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: (#selector(timerCallback)), userInfo: nil, repeats: true)
}
// "Private" functions
@objc func timerCallback() {
switch functionType {
case .SINE_WAVE_FROM_0_TO_1_TO_0:
F_of_X.val = sine010(x: X_currentRepIndex)
case .SINE_WAVE_FROM_0_TO_1:
F_of_X.val = sine01(x: X_currentRepIndex)
case .SINE_WAVE_FROM_1_TO_0:
F_of_X.val = sine10(x: X_currentRepIndex)
}
X_currentRepIndex += 1
_ = target.perform(selector, with: F_of_X)
if X_currentRepIndex == (maxIterations+1) {
timer.invalidate()
}
}
private func sine010(x: Int) -> Double {
return (-cos(2*Double.pi * (Double(x)/Double(maxIterations)))+1)/2
}
private func sine01(x: Int) -> Double {
return (-cos(Double.pi * (Double(x)/Double(maxIterations)))+1)/2
}
private func sine10(x: Int) -> Double {
return (cos(Double.pi * (Double(x)/Double(maxIterations)))+1)/2
}
}
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n <p>Is there a way to tidy up the numerous functions into something like a dictionary? </p>\n</blockquote>\n\n<p>Sure, there are various options. But first the functions should be made independent of <code>maxIterations</code>, i.e. the computation </p>\n\n<pre><code>Double(currentIteration) / Double(maxIterations)\n</code></pre>\n\n<p>should be done in the <em>caller</em> so that the functions simplify to</p>\n\n<pre><code>private func sine010(x: Double) -> Double {\n return (-cos(2 * .pi * x) + 1)/2\n}\n</code></pre>\n\n<p>thus avoiding code duplication. Note also the use of the “implicit member expression” <code>.pi</code> – the type <code>Double</code> is automatically inferred from the context.</p>\n\n<p>Now you could define a dictionary mapping a function types to functions. The functions can be embedded directly as closures instead of defining global functions:</p>\n\n<pre><code>let functionDict : [FunctionType: (Double) -> Double] = [\n .SINE_WAVE_FROM_0_TO_1_TO_0: { (1 - cos(2 * .pi * $0)) / 2 },\n .SINE_WAVE_FROM_0_TO_1: { (1 - cos(.pi * $0)) / 2 },\n .SINE_WAVE_FROM_1_TO_0: { (1 + cos(.pi * $0)) / 2 },\n]\n</code></pre>\n\n<p>The disadvantage is that <em>you</em> are now responsible to update the dictionary if new function types are added.</p>\n\n<p>A perhaps better alternative is to make the function a <em>computed property</em> of the function type enumeration:</p>\n\n<pre><code>enum FunctionType {\n case SINE_WAVE_FROM_0_TO_1_TO_0\n case SINE_WAVE_FROM_0_TO_1\n case SINE_WAVE_FROM_1_TO_0\n\n var f: (Double) -> Double {\n switch self {\n case .SINE_WAVE_FROM_0_TO_1_TO_0: return { (1 - cos(2 * .pi * $0)) / 2 }\n case .SINE_WAVE_FROM_0_TO_1: return { (1 - cos(.pi * $0)) / 2 }\n case .SINE_WAVE_FROM_1_TO_0: return { (1 + cos(.pi * $0)) / 2 }\n }\n }\n}\n</code></pre>\n\n<p>Now everything is in “one place” and the compiler can check the exhaustiveness of the switch statement.</p>\n\n<p>A disadvantage of all the above definitions is that they can not be extended: There is no way that a user can define its own interpolation function and pass it to the value animator.</p>\n\n<p>So what I would really do is to define a <code>struct</code> as the function wrapper, with static properties for predefined functions. I am calling it <code>Interpolator</code> now (resembling the Android <code>TimeInterpolator</code>). </p>\n\n<pre><code>class ValueAnimator {\n\n struct Interpolator {\n // A function mapping [0, 1] to [0, 1].\n let f: (Double) -> Double\n\n // Predefined interpolation functions\n static let sineWaveFrom0To1To0 = Interpolator(f: { (1 - cos(2 * .pi * $0)) / 2 } )\n static let sineWaveFrom0To1 = Interpolator(f: { (1 - cos(.pi * $0)) / 2 } )\n static let sineWaveFrom1To0 = Interpolator(f: { (1 + cos(.pi * $0)) / 2 } )\n }\n\n // ...\n}\n</code></pre>\n\n<p>Note also that I switched to lower camel case for the property names, which is the standard for all Swift identifiers except for types.</p>\n\n<p>Now a user can easily add more interpolation functions, e.g.</p>\n\n<pre><code>extension ValueAnimator.Interpolator {\n static let linear = ValueAnimator.Interpolator(f: { $0 } )\n}\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p>Is there a way of accomplishing the same functionality ... but without using a selector? ... I ask because of the nasty \"MyNSDoubleObject\" workaround.</p>\n</blockquote>\n\n<p>First: The wrapper object is not needed even if you use selectors: Swift automatically wraps values in Objective-C compatible types if necessary. Which means that you <em>can</em> pass a floating point value through the selector:</p>\n\n<pre><code>let value: Double = ...\ntarget.perform(selector, with: value)\n</code></pre>\n\n<p>and the receive can (conditionally) cast it back to a <code>Double</code>:</p>\n\n<pre><code>@objc func animate(obj: AnyObject) {\n guard let value = obj as? Double else { return }\n print(value)\n}\n</code></pre>\n\n<p>So the <code>MyNSDoubleObject</code> workaround is not needed.</p>\n\n<p>But it becomes much simpler if you replace the target/selector method by a simpler <em>callback</em> with a closure. Similarly for the local timer: With a block-based timer, the timer callback need not be Objective-C compatible, and the <code>ValueAnimator</code> class does not have to subclass <code>NSObject</code> anymore.</p>\n\n<hr>\n\n<p><em>Some minor remarks:</em> The </p>\n\n<pre><code>private let sampleRate: Int\n</code></pre>\n\n<p>property is not needed. Instead of initializing with an (inactive) timer</p>\n\n<pre><code>private var timer = Timer()\n</code></pre>\n\n<p>I would use an optional:</p>\n\n<pre><code>private var timer: Timer?\n</code></pre>\n\n<p><code>X_currentRepIndex</code> and <code>F_of_X</code> to not follow the Swift naming conventions, the latter name is quite non-descriptive.</p>\n\n<hr>\n\n<p><em>Putting it all together,</em> the <code>ValueAnimator</code> class could look like this:</p>\n\n<pre><code>class ValueAnimator {\n\n struct Interpolator {\n // A function mapping [0, 1] to [0, 1].\n let f: (Double) -> Double\n\n // Predefined interpolation functions\n static let sineWaveFrom0To1To0 = Interpolator(f: { (1 - cos(2 * .pi * $0)) / 2 } )\n static let sineWaveFrom0To1 = Interpolator(f: { (1 - cos(.pi * $0)) / 2 } )\n static let sineWaveFrom1To0 = Interpolator(f: { (1 + cos(.pi * $0)) / 2 } )\n }\n\n // args\n private let interpolation: Interpolator\n private let callback: (Double) -> Void\n\n // computed from args\n private let maxIterations: Int\n private let timeInterval: Double\n private var currentIteration: Int = 0\n\n // Other properties\n private var timer: Timer?\n\n init(durationInSeconds: Int, sampleRate: Int, interpolation: Interpolator,\n callback: @escaping (Double) -> Void) {\n self.maxIterations = durationInSeconds * sampleRate\n self.timeInterval = 1.0 / Double(sampleRate)\n self.interpolation = interpolation\n self.callback = callback\n }\n\n func start() {\n timer = Timer.scheduledTimer(withTimeInterval: timeInterval, repeats: true) { (timer) in\n let val = Double(self.currentIteration)/Double(self.maxIterations)\n self.callback(self.interpolation.f(val))\n self.currentIteration += 1\n if self.currentIteration > self.maxIterations {\n self.stop()\n }\n }\n }\n\n func stop() {\n timer?.invalidate()\n timer = nil\n }\n}\n</code></pre>\n\n<p>and a sample usage could look like this:</p>\n\n<pre><code>class ViewController: ViewController {\n\n var valueAnimator: ValueAnimator?\n\n override func viewDidLoad() {\n valueAnimator = ValueAnimator(durationInSeconds: 2, sampleRate: 2,\n interpolation: .sineWaveFrom0To1To0)\n { [weak self] value in\n guard let self = self else { return }\n\n // Do something with value ...\n }\n valueAnimator?.start()\n }\n\n}\n</code></pre>\n\n<p>Note the use of <code>weak self</code> in the closure to avoid a reference cycle.</p>\n\n<hr>\n\n<p><em>Further thoughts:</em></p>\n\n<ul>\n<li><p>Since <code>ValueAnimator</code> is a “pure Swift” class now it can be made <em>generic</em> to support other value types, such as integers.</p></li>\n<li><p>Finally: If the goal is to animate <em>visual elements:</em> don't reinvent the wheel, use <a href=\"https://developer.apple.com/documentation/quartzcore\" rel=\"nofollow noreferrer\">Core Animation</a>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T22:20:42.500",
"Id": "454863",
"Score": "0",
"body": "Appreciate your answer. Thanks for taking the time! Learned a lot there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T06:35:46.383",
"Id": "455057",
"Score": "0",
"body": "This is my first codereview. If I were to upload this to GitHub would that be bad etiquette / frowned upon? It seems weird."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T07:59:26.613",
"Id": "455064",
"Score": "0",
"body": "@BooberBunz: I don't see a problem there. A link to the Stack Exchange license terms is at the bottom of each page. I am not a lawyer and not a license expert, but as I understand it, you can republish any content as long as you properly attribute it."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T19:06:53.237",
"Id": "232825",
"ParentId": "232782",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "232825",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T07:59:08.687",
"Id": "232782",
"Score": "3",
"Tags": [
"swift",
"ios",
"animation",
"timer"
],
"Title": "ValueAnimator for IOS - Did I butcher it up?"
}
|
232782
|
<p>I have the following query: </p>
<pre><code>SELECT * FROM "topic"
WHERE "is_deleted" = 0
AND "topic_type" IN ('19','15','27','13','1','7','25','4','6','3','2','9','26','23','24','22')
AND "id" IN
(SELECT "record_id" FROM "notes"
WHERE
"record_id" IN (select "id" FROM "topic"
WHERE "is_deleted" = 0
AND "topic_type" IN ('19','15','27','13','1','7','25','4','6','3','2','9','26','23','24','22')
)
AND "record_model" = 'Topic'
AND "record_backend" = 'Sql'
AND "created_by" = 'acd2a9e61371f1fa51a59c52b2d6c2855423638b'
);
</code></pre>
<p>The idea is to get topic ID's that belong to a user with hash ID given in <code>created_by</code> clause. <code>notes</code> table is huge and I would like to of course limit the execution time as much as I can. </p>
<p>However I am using the topic part twice and I feel as there could be a better solution to it. Any ideas?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T09:32:22.810",
"Id": "454725",
"Score": "0",
"body": "It's hard to comment on efficiency in databases without seeing the schema. In particular whether `notes.record_id` and `topic.id` are indexed/primary keys. Could you provide that information?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T09:50:51.650",
"Id": "454726",
"Score": "0",
"body": "Efficiency at this point is maybe secondary to the question itself. I would like to see if an SQL construct is possible in a way to avoid duplication of the clauses. But to answer your question: `notes.record_id` is MUL VARCHAR indexed key to `topic` table. `topic.id` is indexed PRI INT"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T10:01:37.523",
"Id": "454727",
"Score": "1",
"body": "As far as I can tell, the innermost select is redundant in terms of what is returned in the query. All the filtering you do in the inner, you do again in the outer. The only consideration then becomes whether the premature filtering of the inner clause helps with the `in` statement one level up."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T10:08:53.003",
"Id": "454730",
"Score": "2",
"body": "A good database question would provide the schema, sample data, and wanted results. Here we have to guess what it all means. To be honest, I cannot make sense of it. However, as @JAD says: It seems that a simple join between `notes` and `topic` would do. PS: Either use singular or plural table names, not both."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T10:19:45.247",
"Id": "454731",
"Score": "0",
"body": "@KIKOSoftware `join`, or `exists`, or `in`. That depends a bit on the interpreter as well, and I'm not familiar with MySQL in that regard."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T15:11:06.443",
"Id": "454769",
"Score": "1",
"body": "can you provide the table structures?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T09:04:03.610",
"Id": "232783",
"Score": "0",
"Tags": [
"sql",
"mysql",
"oracle"
],
"Title": "Redundant query?"
}
|
232783
|
<p>I have a stream of stock prices and I want to design indicators calculation for them. Indicator can be imagined as an additional chart displayed next to the prices chart. More specifically, it is usually a function that takes current price and some prices berfore that and applies some function to the resulting array. The most simple example of an indicator is a simple moving average - for any given point <code>X</code> and window size <code>W</code> simple moving average is <code>(Y(X - W) + Y(X - W + 1) + ... + Y(X)) / W</code>. (<a href="https://www.investopedia.com/thmb/l-ky83gugyn-46tqvJezaZsAte4=/1543x0/filters:no_upscale():max_bytes(150000):strip_icc():format(webp)/SMA-5c535f2846e0fb00012b9825.png" rel="nofollow noreferrer">example chart</a>). One important thing is that an indicator can actually be calculated from another indicator values. Another important thing is that an indicator can actually produce multiple values as with <a href="https://en.wikipedia.org/wiki/Bollinger_Bands" rel="nofollow noreferrer">Bollinger Bands</a>.</p>
<p>So I want to design indicators in C# so that they meet the following conditions:</p>
<ol>
<li>I probably want an indicator object to be stateless and manage state in a functional programming way (meaning explicit immutable state passing) because I want to be able to lazy load historical market data for a longer period and apply the same indicator object to the new data without stopping calculating new values from new real-time data.</li>
<li>I want to give users an ability to write their own indicators and the code should be "UI-friendly" (meaning that defining parameters and data sources that will appear on a UI form should be as easy as possible). I want to achieve this via defining indicator parameters and data sources as fields marked with corresponding attributes, getting them via reflection and translating into UI input elements (like number input for <code>int</code> paramter and data source drop down selector for <code>IDataSource<double></code> data source).</li>
</ol>
<p>Soo at this point I have something like this:</p>
<pre><code>public interface IDataSource<TEntry>
{
// TODO.
}
public interface IIndicatorInput
{
TEntry GetSourceEntry<TEntry>(IDataSource<TEntry> source);
}
public interface IIndicatorState<out TEntry>
{
TEntry GetCurrent();
}
public struct SimpleIndicatorState<T> : IIndicatorState<T>
{
public T Current;
public T GetCurrent() => Current;
}
public interface IIndicator<TState, TEntry> : IDataSource<TEntry>
where TState : IIndicatorState<TEntry>
{
TState Init();
TState Reduce(TState state, IIndicatorInput input);
}
public abstract class Indicator<TState, TEntry> : IIndicator<TState, TEntry>, IEquatable<Indicator<TState, TEntry>>
where TState : IIndicatorState<TEntry>
{
public abstract TState Init();
public abstract TState Reduce(TState state, IIndicatorInput input);
#region Equality members
public bool Equals(Indicator<TState, TEntry> other)
{
var fields = GetType().GetFields().Where(f =>
f.GetCustomAttributes(true).Any(a => a.GetType() == typeof(IndicatorParamAttribute)
|| a.GetType() == typeof(IndicatorSourceAttribute)));
var properties = GetType().GetProperties().Where(p =>
p.GetCustomAttributes(true).Any(a => a.GetType() == typeof(IndicatorParamAttribute)
|| a.GetType() == typeof(IndicatorSourceAttribute)));
return fields.All(field => field.GetValue(this) == field.GetValue(other)) &&
properties.All(property => property.GetValue(this) == property.GetValue(other));
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return Equals((Indicator<TState, TEntry>) obj);
}
public override int GetHashCode()
{
var typeName = GetType().FullName;
var hashCode = typeName != null ? typeName.GetHashCode() : 0;
var fields = GetType().GetFields().Where(f =>
f.GetCustomAttributes(true).Any(a => a.GetType() == typeof(IndicatorParamAttribute)
|| a.GetType() == typeof(IndicatorSourceAttribute)));
var properties = GetType().GetProperties().Where(p =>
p.GetCustomAttributes(true).Any(a => a.GetType() == typeof(IndicatorParamAttribute)
|| a.GetType() == typeof(IndicatorSourceAttribute)));
foreach (var field in fields)
{
var fieldValue = field.GetValue(this);
hashCode = (hashCode * 397) ^ fieldValue.GetHashCode();
}
foreach (var property in properties)
{
var propertyValue = property.GetValue(this);
hashCode = (hashCode * 397) ^ propertyValue.GetHashCode();
}
return hashCode;
}
#endregion
}
public abstract class StatelessIndicator<T> : Indicator<SimpleIndicatorState<T>, T>
{
protected abstract T GetCurrent(IIndicatorInput input);
public override SimpleIndicatorState<T> Init() => new SimpleIndicatorState<T>();
public override SimpleIndicatorState<T> Reduce(SimpleIndicatorState<T> state, IIndicatorInput input) =>
new SimpleIndicatorState<T> { Current = GetCurrent(input) };
}
public struct WindowState<TInput, TOutput> : IIndicatorState<TOutput>
{
public TInput[] Buffer;
public int CurrentIndex;
public TOutput Current;
public TOutput GetCurrent() => Current;
}
public abstract class WindowIndicator<TInput, TOutput> : Indicator<WindowState<TInput, TOutput>, TOutput>
{
[IndicatorParam]
public int WindowSize;
[IndicatorSource]
public IDataSource<TInput> Source;
public WindowIndicator(int windowSize, IDataSource<TInput> source = null)
{
if (windowSize < 1)
throw new Exception("Window size should be an integer greater than zero.");
WindowSize = windowSize;
Source = source;
}
protected abstract TOutput Aggregate(TInput[] values);
protected abstract TOutput Default();
public override WindowState<TInput, TOutput> Init() => new WindowState<TInput, TOutput>
{
Buffer = new TInput[WindowSize],
CurrentIndex = -1,
Current = Default(),
};
public override WindowState<TInput, TOutput> Reduce(WindowState<TInput, TOutput> state, IIndicatorInput input)
{
var buffer = new TInput[WindowSize];
state.Buffer.CopyTo(buffer, 0);
var currentIndex = state.CurrentIndex + 1;
buffer[currentIndex % WindowSize] = input.GetSourceEntry<TInput>(Source);
return new WindowState<TInput, TOutput>
{
Buffer = buffer,
CurrentIndex = currentIndex,
Current = currentIndex < WindowSize - 1 ? Default() : Aggregate(buffer),
};
}
}
public class Sma : WindowIndicator<double, double?>
{
protected override double? Aggregate(double[] values) => values.Sum() / WindowSize;
protected override double? Default() => null;
public Sma(int windowSize, IDataSource<double> source = null) : base(windowSize, source)
{
}
}
public class Macd : StatelessIndicator<double>
{
[IndicatorSource]
public Sma SmaShort = new Sma(12);
[IndicatorSource]
public Sma SmaLong = new Sma(26);
protected override double GetCurrent(IIndicatorInput input) =>
input.GetSourceEntry(SmaShort).Value - input.GetSourceEntry(SmaLong).Value;
}
</code></pre>
<p>I think there should be like a graph of data sources and a check for cycle dependencies in this graph before calculation. A simple graph could look like this:</p>
<pre><code> PRICES [root - origininal prices]
| |
V V
SMA(12) SMA(26) [these two indicators depend on original prices]
| |
V V
MACD [this indicator depends on the two SMA's]
</code></pre>
<p>Oh and also I decided to allow <code>null</code> as data source param value so I don't have to actually pass something when I define default data source values (like in <code>public Sma SmaShort = new Sma(12);</code>. So I think that I could just replace <code>null</code> with root data source (i.e. original prices).</p>
<p>So the question is basically am I overcomplicating things? I think I could implement it simpler if not the "UI friendliness" requirement.</p>
<p>And also any thoughts on actually passing data sources, storing them in a graph etc?</p>
<p>P.S. You may notice that it should be EMA's as MACD sources, not SMA's. Ignore that, it's only for an example purposes.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T15:30:42.813",
"Id": "454772",
"Score": "0",
"body": "I'll be honest, I did not carefully look through all your code and your requirements, but it does seem like you may be overcomplicating it. Shooting from the hip, I might just have different interfaces for the different types of indicators, e.g. make a IIndicator<InType,OutType> and then just implement an indicator in a simple class that contains whatever code it needs to do its magic. My question to you is this: would doing it that way introduce problems immediately, or are you trying to anticipate trying to solve a problem you don't yet have?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T09:32:40.117",
"Id": "232784",
"Score": "1",
"Tags": [
"c#"
],
"Title": "C# trading indicators calculation"
}
|
232784
|
<p>So I'm using the event emitter as some sort of an event bus(If I'm allowed to call it that).</p>
<p>The problem I've stumbled upon is that my listeners might want different data than another listener. Since I don't want to add too much and listener specific information where things get emitted. I'm using this solution, but it feels very repetitive and not too clean. </p>
<p><strong>My service function</strong></p>
<pre><code>async function updateUserStatus(userId, action) {
const [ updatedUser ] = await User.update({ id: userId }, { status: userActions[action] });
switch (action) {
case actions.activate:
UserEventEmitter.emit('user:activated', updatedUser.id);
break;
case actions.reject:
UserEventEmitter.emit('user:rejected', updatedUser.id );
break;
}
return updatedUser;
}
</code></pre>
<p><strong>The event dispatcher/configurator</strong></p>
<pre><code>UserEventEmitter.on('user:activated', sendWelcomeMailToUser);
UserEventEmitter.on('user:activated', addActivatedComment);
UserEventEmitter.on('user:rejected', addRejectedComment);
</code></pre>
<p><strong>The event listeners/handlers</strong></p>
<pre><code>async function addActivatedComment({ userId }) {
try {
await addComment({
userId,
translationKey: Enums.TIMELINE_USER_ACTIVATED
});
} catch (error) {
throw new SomeGoodError(error)
}
}
async function addRejectedComment({ userId }) {
try {
await addComment({
userId,
translationKey: Enums.TIMELINE_USER_REJECTED
});
} catch (error) {
throw new SomeGoodError(error)
}
}
function addComment({ supplierSupplierId, translationKey }) {
return Timeline.create({
user_id: userId,
status: translationKey
});
}
</code></pre>
<p>The <code>addRejectedComment</code> and <code>addActivatedComment</code> basically does the same thing with one different property. I don't want to send that property from the service because then my other listeners would get that property too.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T09:44:01.550",
"Id": "232785",
"Score": "1",
"Tags": [
"javascript",
"node.js",
"event-handling"
],
"Title": "Repetitive code for an event listener"
}
|
232785
|
<p>I'm trying to develop a c++ library that provide two kind of times:</p>
<ol>
<li>UTC time(self explainitory)</li>
<li>System time(time since the system has went on)</li>
</ol>
<p>I have looked into the <a href="https://en.cppreference.com/w/cpp/chrono" rel="nofollow noreferrer"><code>chrono</code></a> library in cpp and im trying to implement my library, more of the same like <code>chrono</code>. the implementation is very complicated for me right now.</p>
<p>I'll post the complete code I have later on, but so far I support only UTC time. I have few problems in my code that I want to improve but I don't know how exactly.</p>
<pre><code>#include "atltime.h"
#include "mmsystem.h"
namespace tc{
typedef struct date{
unsigned int day;
unsigned int month;
unsigned year;
date(unsigned int _day, unsigned int _month, unsigned int _year)
{
day = _day;
month = _month;
year = _year;
}
date() :day(0), month(0), year(0){}
}date;
template <class _Clock,
class _Time = typename _Clock::time,
class _Date = typename _Clock::date>
class time_point
{
public:
typedef _Clock clock;
typedef _Time time;
typedef _Date date;
time_point(const time& otherTime, const date& otherDate)
{
_MyTime = otherTime;
_MyDate = otherDate;
}
time get_time() const
{
return (_MyTime);
}
date get_date() const
{
return (_MyDate);
}
private:
_Time _MyTime;
_Date _MyDate;
};
}
struct utc_clock
{
typedef unsigned long long time;
typedef tc::date date;
typedef tc::time_point<utc_clock> time_point;
public:
static time_point now()
{
SYSTEMTIME systime;
GetSystemTime(&systime);
time_t cur_time = time(0);
struct tm *time_buf = localtime(&cur_time);
time t = (((time_buf->tm_sec + (time_buf->tm_min * 60) + (time_buf->tm_hour * 3600)) * 1000) + systime.wMilliseconds) * 1000ULL;
tc::date d((unsigned int)systime.wDay, (unsigned int)systime.wMonth, (unsigned int)systime.wYear);
return time_point(t, d);
}
static time to_micro(const time_point& t)
{
return t.get_time();
}
static time to_mili(const time_point& t)
{
return to_micro(t) / 1000;
}
static time to_sec(const time_point& t)
{
return to_mili(t) / 1000;
}
static time to_min(const time_point& t)
{
return to_sec(t) / 60;
}
static time to_hour(const time_point& t)
{
return to_min(t) / 60;
}
static char * to_utc_time_str(const time_point& t)
{
char *str = new char[100];
sprintf(str, "%02d:%02d:%02d:%03d:%03d", to_hour(t), to_min(t), to_sec(t), to_mili(t), to_micro(t));
return str;
}
static char * to_utc_date_str(const time_point& t)
{
char *str = new char[100];
sprintf(str, "%02d.%02d.%04d", t.get_date().day, t.get_date().month, t.get_date().year);
return str;
}
};
</code></pre>
<p>The usage goes like that:</p>
<pre><code>int main()
{
tc::time_point<utc_clock> t = utc_clock::now();
char * str = utc_clock::to_utc_date_str(t);
unsigned long long micro, mili, second;
unsigned long long s;
micro = utc_clock::to_micro(t);
mili = utc_clock::to_mili(t);
second = utc_clock::to_sec(t);
s = micro + mili; // this is not good, need to use type-safe
//handler on return time, or have a converter to allow it.
cout << "Micro: " << micro << endl;
cout << "Mili: " << mili << endl;
cout << "Seconds: " << second << endl;
cout << "UTC Date is: " << str << endl;
getchar();
}
</code></pre>
<p>There are few things I think I can improve in my code, but don't know how to implement it.</p>
<ol>
<li><p>all the function in <code>to_micro</code>, <code>to_mili</code>, <code>to_sec</code> ... etc can be written
in otherway using operator overloading maybe? for example I can have <code>'sc'</code> operator that can convert to seconds based on the received time. <code>sc(1000)</code> // 1000 is in mili, will convert it automatically to 1.</p></li>
<li><p>I want to make sure that doing arithmetical operation on different kind of times(mili/seconds/micro) is avoided. I'd be happy to get a direction over it.</p></li>
</ol>
<p>Any other suggestions/idea will be greatly welcomed</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T14:22:32.507",
"Id": "454759",
"Score": "0",
"body": "Welcome to code review. Does the code to be reviewed work as expected? You indicate that there are issues, Do these issue affect how the code runs?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T14:56:23.507",
"Id": "454768",
"Score": "0",
"body": "@pacmaninbw thank you. The code runs without bugs. I have issued all the problem that might occur and that I want to avoid. which of them was not clear? maybe I need to explain better"
}
] |
[
{
"body": "<h2>Fix all Warnings and Errors</h2>\n\n<p>During development it is a best practice to get all warning messages as well as all error messages. Warning messages can indicate hidden bugs in the code. For most C++ compilers the <code>-wall</code> switch will provide all warnings. I am building using Visual Studio 2019 Professional and there are many warnings presented during the build:</p>\n\n<blockquote>\n <p>1>------ Build started: Project: timelibrary2, Configuration: Debug Win32 ------<br>\n 1>timelibrary2.cpp<br>\n 1>D:\\ProjectsNfwsi\\CodeReview\\timelibrary2\\timelibrary2\\timelibrary2.cpp(107,16): warning C4477: 'sprintf' : format string '%02d' requires an argument of type 'int', but variadic argument 1 has type 'utc_clock::time'<br>\n 1>D:\\ProjectsNfwsi\\CodeReview\\timelibrary2\\timelibrary2\\timelibrary2.cpp(107,16): message : consider using '%lld' in the format string<br>\n 1>D:\\ProjectsNfwsi\\CodeReview\\timelibrary2\\timelibrary2\\timelibrary2.cpp(107,16): message : consider using '%I64d' in the format string<br>\n 1>D:\\ProjectsNfwsi\\CodeReview\\timelibrary2\\timelibrary2\\timelibrary2.cpp(107,16): warning C4477: 'sprintf' : format string '%02d' requires an argument of type 'int', but variadic argument 2 has type 'utc_clock::time'<br>\n 1>D:\\ProjectsNfwsi\\CodeReview\\timelibrary2\\timelibrary2\\timelibrary2.cpp(107,16): message : consider using '%lld' in the format string<br>\n 1>D:\\ProjectsNfwsi\\CodeReview\\timelibrary2\\timelibrary2\\timelibrary2.cpp(107,16): message : consider using '%I64d' in the format string<br>\n 1>D:\\ProjectsNfwsi\\CodeReview\\timelibrary2\\timelibrary2\\timelibrary2.cpp(107,16): warning C4477: 'sprintf' : format string '%02d' requires an argument of type 'int', but variadic argument 3 has type 'utc_clock::time'<br>\n 1>D:\\ProjectsNfwsi\\CodeReview\\timelibrary2\\timelibrary2\\timelibrary2.cpp(107,16): message : consider using '%lld' in the format string<br>\n 1>D:\\ProjectsNfwsi\\CodeReview\\timelibrary2\\timelibrary2\\timelibrary2.cpp(107,16): message : consider using '%I64d' in the format string<br>\n 1>D:\\ProjectsNfwsi\\CodeReview\\timelibrary2\\timelibrary2\\timelibrary2.cpp(107,16): warning C4477: 'sprintf' : format string '%03d' requires an argument of type 'int', but variadic argument 4 has type 'utc_clock::time'<br>\n 1>D:\\ProjectsNfwsi\\CodeReview\\timelibrary2\\timelibrary2\\timelibrary2.cpp(107,16): message : consider using '%lld' in the format string<br>\n 1>D:\\ProjectsNfwsi\\CodeReview\\timelibrary2\\timelibrary2\\timelibrary2.cpp(107,16): message : consider using '%I64d' in the format string<br>\n 1>D:\\ProjectsNfwsi\\CodeReview\\timelibrary2\\timelibrary2\\timelibrary2.cpp(107,16): warning C4477: 'sprintf' : format string '%03d' requires an argument of type 'int', but variadic argument 5 has type 'utc_clock::time'<br>\n 1>D:\\ProjectsNfwsi\\CodeReview\\timelibrary2\\timelibrary2\\timelibrary2.cpp(107,16): message : consider using '%lld' in the format string<br>\n 1>D:\\ProjectsNfwsi\\CodeReview\\timelibrary2\\timelibrary2\\timelibrary2.cpp(107,16): message : consider using '%I64d' in the format string<br>\n 1>timelibrary2.vcxproj -> D:\\ProjectsNfwsi\\CodeReview\\timelibrary2\\Debug\\timelibrary2.exe<br>\n 1>Done building project \"timelibrary2.vcxproj\".<br>\n ========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ========== </p>\n</blockquote>\n\n<p>The above warnings are all on line 107 which is this line:</p>\n\n<pre><code> sprintf(str, \"%02d:%02d:%02d:%03d:%03d\", to_hour(t), to_min(t), to_sec(t), to_mili(t), to_micro(t));\n</code></pre>\n\n<p>There is also a warning in the IDE about this line: </p>\n\n<pre><code> time t = (((time_buf->tm_sec + (time_buf->tm_min * 60) + (time_buf->tm_hour * 3600)) * 1000) + systime.wMilliseconds) * 1000ULL;\n</code></pre>\n\n<p>This warning is <code>Arithmetic Overflow</code>, which can indeed create errors or bugs.</p>\n\n<h2>Avoid <code>using namespace std;</code></h2>\n\n<p>While it is not in the code under review, it is apparent from the code in <code>main()</code> that the <code>using namespace std;</code> is in the code.</p>\n\n<p>If you are coding professionally you probably should get out of the habit of using the <code>using namespace std;</code> statement. The code will more clearly define where <code>cout</code> and other identifiers are coming from (<code>std::cin</code>, <code>std::cout</code>). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The identifier<code>cout</code> you may override within your own classes, and you may override the operator <code><<</code> in your own classes as well. This <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">stack overflow question</a> discusses this in more detail.</p>\n\n<h2>struct utc_clock</h2>\n\n<p>In the declaration of <code>struct utc_clock</code> there is the <code>public:</code> declaration, this is not necessary since by default all contents of a struct are public.</p>\n\n<p>It is not clear why all the functions in the struct are declared as <code>static</code>. It means while many instances of the utc_clock struct may be instantiated, they all refer to one instance of each function.</p>\n\n<p>If the utc_clock struct is being use to convert the system up time to utc, it might be good to add a function <code>to_days</code> as well, since some systems may be up for days, weeks or months.</p>\n\n<h2>Declare and Initialize Variables at the Same Time</h2>\n\n<p>A good practice in C++ is to initialize the variables when they are declared. C++ does not automatically initialize variables as some other languages do. Each declaration and initialization should be in it's own statement, on its own line, this makes it easier to find and edit the variable declaration and initialization.</p>\n\n<p>Instead of </p>\n\n<pre><code> unsigned long long micro, mili, second;\n\n micro = utc_clock::to_micro(t);\n mili = utc_clock::to_mili(t);\n second = utc_clock::to_sec(t);\n</code></pre>\n\n<p>it would be better to declare and initialize like this</p>\n\n<pre><code> unsigned long long micro = utc_clock::to_micro(t);\n unsigned long long mili = utc_clock::to_mili(t);\n unsigned long long second = utc_clock::to_sec(t);\n\n unsigned long long s = micro + mili;\n</code></pre>\n\n<h2>Unused Variables</h2>\n\n<p>In the <code>main()</code> function, the variable <code>s</code> is declared and assigned a value but it is never referenced. It would better if the variable <code>s</code> wasn't declared or initialized.</p>\n\n<h2>Initialization of Private Variables in a Constructor</h2>\n\n<p>It is possible and generally desired to private variables in a class outside the body of the constructor. This can be accomplished using the <code>{}</code> operator, so instead of </p>\n\n<pre><code> time_point(const time& otherTime, const date& otherDate)\n {\n _MyTime = otherTime;\n _MyDate = otherDate;\n } \n</code></pre>\n\n<p>use </p>\n\n<pre><code> time_point(const time& otherTime, const date& otherDate)\n : _MyTime{otherTime}, _MyDate{otherDate}\n {\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T17:24:17.153",
"Id": "454807",
"Score": "0",
"body": "Thank you for your comment. noted everything. what about the type-safety issue regarding the returned type?(to_sec/to_micro etc..) how can I solve this?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T16:42:57.443",
"Id": "232812",
"ParentId": "232788",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T10:30:32.063",
"Id": "232788",
"Score": "3",
"Tags": [
"c++",
"type-safety"
],
"Title": "Time provider library using type safe handler - like chrono CPP"
}
|
232788
|
<p>I have made a simple <code>Timer</code> class used for scheduling tasks. While defining the interface, I have followed the interface of a <code>java.util.Timer</code> class. The class is being written by using only C++11.</p>
<p>C++17 version is provided <a href="https://github.com/m-peko/timer" rel="nofollow noreferrer"><strong>here</strong></a></p>
<p><strong>timer.hpp</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#include <atomic>
#include <chrono>
#include <future>
#include <utility>
template<typename F, typename... Args>
inline auto invoke(F f, Args&&... args)
-> decltype(std::ref(f)(std::forward<Args>(args)...)) {
return std::ref(f)(std::forward<Args>(args)...);
}
class Timer {
public:
using Timestamp = std::chrono::time_point<
std::chrono::system_clock,
std::chrono::microseconds
>;
using Delay = std::chrono::milliseconds;
using Period = std::chrono::milliseconds;
public:
Timer() = delete;
Timer(std::atomic<bool>& is_running) : is_running_(is_running) {}
Timer(Timer const& other) = default;
Timer(Timer&& other) = default;
Timer& operator=(Timer const& other) = default;
Timer& operator=(Timer&& other) = default;
~Timer() = default;
template <typename TimerTask, typename ... Args>
std::future<void> schedule(TimerTask task, Timestamp const& time, Args... args) {
using namespace std::chrono;
return std::async(std::launch::async, [=]() {
while (time_point_cast<Timestamp::duration>(system_clock::now()) < time) {
// wait for the time
}
invoke(task, args...);
});
}
template <typename TimerTask, typename Period, typename ... Args>
std::future<void> schedule(TimerTask task, Timestamp const& time, Period const& period, Args... args) {
using namespace std::chrono;
return std::async(std::launch::async, [=]() {
while (time_point_cast<Timestamp::duration>(system_clock::now()) < time) {
// wait for the time
}
while (is_running_) {
invoke(task, args...);
std::this_thread::sleep_for(period);
}
});
}
template <typename TimerTask, typename ... Args>
std::future<void> schedule(TimerTask task, Delay const& delay, Args... args) {
using namespace std::chrono;
return std::async(std::launch::async, [=]() {
auto start = system_clock::now();
while (duration_cast<Delay>(system_clock::now() - start) < delay) {
// wait for the delay
}
invoke(task, args...);
});
}
template <typename TimerTask, typename ... Args>
std::future<void> schedule(TimerTask task, Delay const& delay, Period const& period, Args... args) {
using namespace std::chrono;
return std::async(std::launch::async, [=]() {
auto start = system_clock::now();
while (duration_cast<Delay>(system_clock::now() - start) < delay) {
// wait for the delay
}
while (is_running_) {
invoke(task, args...);
std::this_thread::sleep_for(period);
}
});
}
void cancel() {
is_running_ = false;
}
private:
std::atomic<bool>& is_running_;
};
</code></pre>
<p><strong>main.cpp</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include "timer.hpp"
int main() {
std::atomic<bool> is_running{true};
Timer timer(std::ref(is_running));
Timer::Timestamp ts = std::chrono::time_point_cast<Timer::Timestamp::duration>(
std::chrono::system_clock::now()
);
ts = ts + std::chrono::milliseconds{10000};
auto future = timer.schedule([] {
std::cout << "." << std::endl;
}, ts, Timer::Period{5000});
std::cout << "... in main ..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds{20});
std::cout << "... cancel ..." << std::endl;
timer.cancel();
return 0;
}
</code></pre>
<p>Let me hear your opinion about this implementation, code style, performance, possible improvements or possible pitfalls etc.</p>
<p>You may also note all the things that can be simplified or changed by using C++17 or even C++20.</p>
|
[] |
[
{
"body": "<p>Your usage of <code>std::ref</code> is unnecessary (both in <code>main</code> and <code>invoke</code>). It is only needed when you are passing arguments to a templated function that would normally throw away the reference qualifier, but this is not the case where you are using it.</p>\n\n<hr>\n\n<p>You are storing an external reference to a <code>std::atomic<bool></code>. This seems very bizarre to me because you are forcing the user of the <code>Timer</code> to (1) create it and (2) ensure that the reference stays valid for the life of the <code>Timer</code> instance. That can certainly be an annoyance with seemingly no benefit. You already have <code>cancel()</code> and if you want to see if it is running, just add a function for getting it.</p>\n\n<p>Just make <code>is_running_</code> a non-reference. (You did this in your linked version but not here)</p>\n\n<hr>\n\n<pre><code>while (time_point_cast<Timestamp::duration>(system_clock::now()) < time) {\n // wait for the time\n}\n</code></pre>\n\n<p>This will pin the thread at 100% utilization until the condition is met. This is very bad since it could be waiting for a long time, whatever the user wants. A hot loop like this you could cool down by adding micro-sleeps <code>while (condition) { // sleep for a few milliseconds }</code>.</p>\n\n<p>You're already using <code>sleep_for()</code> but there's also <a href=\"https://en.cppreference.com/w/cpp/thread/sleep_until\" rel=\"nofollow noreferrer\"><code>sleep_until()</code></a>. So your while loop can be replaced with:</p>\n\n<pre><code>std::this_thread::sleep_until(time);\n</code></pre>\n\n<p>and your timer will consume much fewer resources. (You updated your linked version so I'm guessing you already knew this)</p>\n\n<hr>\n\n<p>You should rethink your design.</p>\n\n<p>Returning a <code>std::future<void></code> is probably a bad idea. The destructor of <code>std::future</code> (when created from <code>std::async</code>) will block execution until the function ends. This would not allow for <em>fire-and-forget</em> calls, the caller has to wait for the function to be called. In a different situation you might use a future like this to return a value from the async function, but you aren't doing that here.</p>\n\n<p>However, <em>not</em> returning it has the same problem, it just moves the waiting into <code>schedule()</code>. What you would need to do is hold a <code>std::vector</code> of <code>std::future<void></code>s. This would give perspective for what all functions the <code>Timer</code> is juggling and forces the <code>Timer</code>'s destructor to wait for any outstanding functions to finish.</p>\n\n<p>However, that's not a good idea either; the internal list would grow for the life of the <code>Timer</code> with no way to purge completed functions (at least not cleanly). Instead lets look at your source of inspiration: the <code>java.util.Timer</code> documentation says it is:</p>\n\n<blockquote>\n <p>A facility for threads to schedule tasks for future execution in a background thread...</p>\n \n <p>Corresponding to each Timer object is a single background thread that is used to execute all of the timer's tasks, sequentially.</p>\n</blockquote>\n\n<p>You should follow their lead. Instead of juggling multiple handles to asynchronous functions, you should have one <code>std::thread</code> ready to do the work, hold a queue of functions-with-times that need to be called (a <code>std::priority_queue</code> perhaps), and probably a <code>std::mutex</code> for synchronize adding and removing stuff from the queue.</p>\n\n<hr>\n\n<p>This detracts from the Java version, but if you want to pass arguments to the function through additional arguments to <code>schedule()</code>, I'd recommend moving the <code>task</code> argument towards the end. This keeps the function call closer to the arguments in the parameter list.</p>\n\n<hr>\n\n<p>You have no mechanism for stopping a periodic function besides stopping the whole timer. The Java version accomplishes this by using a special <code>TimerTask</code> type that serves as a wrapper around a <code>Callable</code> that adds a <code>cancel()</code> function. For C++ however, I'd recommend implementing <em>cancellation tokens</em> that a user can use to stop a periodic function, should they wish to.</p>\n\n<hr>\n\n<p>Your code was very easy to review: good code style, good names, good use of <code>using</code>, good organization</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-09T10:04:06.527",
"Id": "233673",
"ParentId": "232791",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T11:29:11.750",
"Id": "232791",
"Score": "3",
"Tags": [
"c++",
"c++11",
"timer",
"scheduled-tasks"
],
"Title": "Timer for scheduling tasks in C++11"
}
|
232791
|
<p><a href="https://projecteuler.net/problem=5" rel="nofollow noreferrer">What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?</a></p>
<p>Is there a more elegant solution in C++?</p>
<pre><code>#include <iostream>
using namespace std;
int main(){
long long num = 1;
int divMin = 1;
int divMax = 20;
int tempDivMax = divMax;
while(true){
if(num % tempDivMax == 0)
{
tempDivMax--;
if(tempDivMax == divMin){
cout << num << endl;
break;
}
}else{
tempDivMax = divMax;
num++;
}
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T11:53:12.020",
"Id": "454739",
"Score": "2",
"body": "Did you look at the solution provided by project Euler themselves? Algorihmically, that's a good place to start. Once you entered the solution on their website, it can be found here: https://projecteuler.net/overview=005"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T11:59:19.370",
"Id": "454742",
"Score": "1",
"body": "There are far more efficient ways to get the result. I would suggest to have a look at earlier questions about this problem, such as https://codereview.stackexchange.com/q/80500/35991 or https://codereview.stackexchange.com/q/202307/35991, where better approaches are explained."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T13:14:08.750",
"Id": "454747",
"Score": "0",
"body": "The smallest positive number evenly divisible by numbers 1 to 20 is a constant and the fastest solution would be to print the constant. cheers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T15:50:55.947",
"Id": "454781",
"Score": "0",
"body": "Find all the primes between one and twenty."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T07:10:02.857",
"Id": "456543",
"Score": "0",
"body": "The answer is `LCM([1,2,...., 20]) = 2*3*2*5*7*2*3*11*13*2*17*19 = 232792560`"
}
] |
[
{
"body": "<h2>Code review</h2>\n\n<p>To start with, some points about your code:</p>\n\n<ul>\n<li><p><code>using namespace std;</code> is something I consider a code smell. It doesn't save much time and I find it clearer to see exactly where <code>cout</code> etc. are coming from. Additionally, it clutters your namespace although I myself haven't run into name collisions with the STL being an issue before.</p></li>\n<li><p>It looks like your condition to exit the <code>while</code> loop is <code>tempDivMax == divMin</code>. Use this rather than <code>while (true)</code> to make it clearer what behaviour is intended.</p></li>\n<li><p>You are also performing two iterations inside a single loop: num is being incremented from 1 until it succeeds and tempDivMax is being decremented until it equals divMin. Split these into separate loops! The code will be clearer to read and will be just as fast. The outer loop I would turn completely into a for loop <code>for (; tempDivMax != divMin; ++num) { ... }</code> and but the inner one I would make a while loop <code>while (tempDivMax > divMin && num % tempDivMax == 0) { ... }</code> since the long condition expression makes for some rough reading when condensed into a for loop.</p></li>\n<li><p>Finally, define your constants before your working variables and declare them as <code>const</code>. I would even do this outside of the main function.</p></li>\n</ul>\n\n<p>This leaves you with:</p>\n\n<pre><code>#include <iostream>\n\nconst int DIV_MIN = 1;\nconst int DIV_MAX = 20;\n\nint main() {\n long long num = 1;\n int tempDivMax = DIV_MAX;\n for (; tempDivMax > DIV_MIN; ++num) {\n tempDivMax = DIV_MAX;\n while (tempDivMax > DIV_MIN && num % tempDivMax == 0) {\n --tempDivMax;\n }\n }\n\n std::cout << num << std::endl;\n return 0;\n}\n</code></pre>\n\n<h2>A \"more elegant\" solution...</h2>\n\n<p>== Obligatory code below is untested ==</p>\n\n<p>I'd imagine they're looking for something like this?</p>\n\n<p>For something to be divisible by a number, it must have at least that number's prime factors. Furthermore, in any given number below 20, there can be a maximum of <span class=\"math-container\">$$\\lfloor{log_p(20)}\\rfloor$$</span> copies of the prime factor <span class=\"math-container\">$$p$$</span></p>\n\n<p>The following snippet calculates the product of these.</p>\n\n<pre><code>#include <iostream>\n\nconst int DIV_MAX = 20;\nconst int[] PRIMES = {2, 3, 5, 7, 11, 13, 17};\n\nint main() {\n int result = 1;\n for (int p : PRIMES) {\n int tmp = 1;\n while (tmp < DIV_MAX) tmp *= p;\n result *= tmp;\n }\n\n std::cout << result << std::endl;\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T07:16:05.490",
"Id": "456545",
"Score": "0",
"body": "Your untested solution is wrong. Firstly, 19 is also a prime. Secondly it produces 1418659424 which is obviously not divisible at least by 10. If I added 19 to the set of primes it produced 1034943840 which is not the smallest solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T07:23:17.760",
"Id": "456548",
"Score": "0",
"body": "Aha sry, the numbers are fake because it overflown 32 bit int. It produces much greater numbers with long. 6254891042400 without 19, and 2258015666306400 with 19, they both are evenly divisible by 1 to 20 but they are far more than the smallest solution. Smallest solution is 232792560."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T07:30:33.787",
"Id": "456549",
"Score": "0",
"body": "Actually 6254891042400 even cannot be divisble by 19 because that prime was not used for multiplication."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T02:45:51.063",
"Id": "232923",
"ParentId": "232792",
"Score": "2"
}
},
{
"body": "<h1>Avoid <code>using namespace std</code></h1>\n\n<p>The <code>std</code> namespace isn't designed for wholesale importation into the global namespace like that, and it contains lots of names that are likely to disagree with your own identifiers (possibly leading to unexpected overloads, and thus a different to expected behaviour). Leave the standard library identifiers where they belong, and enjoy clearer and more reliable code.</p>\n\n<h1>Avoid the infinite loop</h1>\n\n<p>Sometimes there's really a need for an infinite loop, but this doesn't appear to be one of those. What we have here looks like two loops, with the <code>if</code> switching between states. It's more honest and easier to read if we show the two loops clearly:</p>\n\n<pre><code>for (num = 1; num < LLONG_MAX; ++num) {\n bool dividesAll = true;\n for (int i = divMin; i < divMax; ++i) {\n if (num % i) {\n dividesAll = false;\n break;\n }\n if (dividesAll) {\n std::cout << num << '\\n';\n return 0;\n }\n}\n</code></pre>\n\n<p>It becomes clearer again if we refactor a function:</p>\n\n<pre><code>bool dividesAll(long long n, int min, int max) {\n for (int i = min; i < max; ++i) {\n if (n % i) {\n return false;\n }\n return true;\n}\n</code></pre>\n\n<p>and use it:</p>\n\n<pre><code>for (num = 1; !dividesAll(num, divMin, divMax); ++num) {\n // empty body\n}\nstd::cout << num << '\\n';\nreturn 0;\n</code></pre>\n\n<h1>Use unsigned types</h1>\n\n<p>There's no use of negative numbers, so we can stick to unsigned integer types here.</p>\n\n<h1>Improve the algorithm</h1>\n\n<p>Brute-force search is a poor choice of technique for this problem. Like all Project Euler challenges, you should be able to use some mathematical reasoning to produce much more efficient code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T06:54:57.080",
"Id": "456540",
"Score": "0",
"body": "Mathematic reasoning in this case can easily produce the answer itself. Getting the answer with a program is an overkill. If it was asking for 1 to N then it would be a differrent thing. The problem can be rephrased as finding LCM of the numbers 1 to 20. I can do this with a calculator just hitting multiplication button several times. Or even on paper quite easily..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T14:58:04.863",
"Id": "232948",
"ParentId": "232792",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T11:35:35.013",
"Id": "232792",
"Score": "1",
"Tags": [
"c++",
"programming-challenge"
],
"Title": "C++ Solution for ProjectEuler Problem #5"
}
|
232792
|
<p>Code works fine.
What I'm looking for is C# syntax to make the <strong><code>foreach</code> loop below</strong> more elegant, compact and readable. The foreach with the multiple if's takes up too much space and looks too ugly. I'm thinking LINQ syntax maybe?</p>
<p>(Assume all the variables are strings. The final version will have better variable naming)</p>
<pre><code>public static warMod Gen ( List<AtMap> atMaps ) {
List<AtMap> atMapList = new List<AtMap>();
foreach(var a in atMaps)
{
AtMap atMap = new AtMap();
if (!string.IsNullOrEmpty(a.srSys))
{
atMap.srSys = a.srSys;
}
if (!string.IsNullOrEmpty(a.desSys))
{
atMap.desSys = a.desSys;
}
if (a.srFl != null)
{
atMap.srFl = a.srFl;
}
if (a.desFl != null)
{
atMap.desFl = a.desFl;
}
atMapList.Add(atMap);
}
return new warMod {AtMapArr = atMapList}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T12:24:54.483",
"Id": "454743",
"Score": "1",
"body": "I think that the code is too simple to be provided a proper review!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T12:56:30.097",
"Id": "454744",
"Score": "1",
"body": "Welcome to Code Review! Please add more context about what the code in question is trying to accomplish to your question. Without seeing the `AtMap` class you won't get much help either, not because we don't want to but because wa can't help you without this class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T13:08:28.353",
"Id": "454746",
"Score": "0",
"body": "How about moving the body of the foreach (excluding the last line - Add()) to a function, respectively to a method of the AtMap. A static factory method, something like `static AtMap createCopyWithoutEmptyProperties(AtMap atMap)`. I dont see anything wrong with those ifs anyway, you can remove the braces and put the assignment on the same line with the if, but some might consider it bad code style..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T13:48:52.203",
"Id": "454752",
"Score": "1",
"body": "Why not start with good and useful names from the start. Furthermore i agree with @slepic about using a factory method. As you stated you then could simply write `return new WarMod { AtMapArr = atMaps.Select(CreateAtMapForWarMod).ToList()};`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T15:17:37.357",
"Id": "454771",
"Score": "0",
"body": "Innat3's answer of creating a custom constructor seems pretty good, but if you posted more context it seems like you might not even need to copy the AtMap list to a new AtMap list at all. I've learned with a bit of experience that the real benefits don't come from making code look cleaner, they come from using the correct data structures that convey the true intent of the code. In the past I was far too concerned with \"cleanness\" and I did not understand enough about what actually makes code maintainable (and a little bit of strategic messiness in places is not the end of the world)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T20:33:04.463",
"Id": "454838",
"Score": "0",
"body": "The number one thing that would make this code 1000x more readable is stp w/ abbrvs. I read this and I cannot easily tell the difference between srsys, dessys, srfl, desfl, and so on. Follow good naming conventions; use full words."
}
] |
[
{
"body": "<p>You could declare another constructor in your <code>AtMap</code> class which initializes the default parameterless constructor, and receiving another <code>AtMap</code> as input, performs the value-checking.</p>\n\n<pre><code>public class AtMap\n{\n public AtMap(AtMap a) : this()\n {\n if (!string.IsNullOrEmpty(a.srSys))\n srSys = a.srSys;\n\n if (!string.IsNullOrEmpty(a.desSys))\n desSys = a.desSys;\n\n if(a.srFl != null)\n srFl = a.srFl;\n\n if (a.desFl != null)\n desFl = a.desFl;\n }\n}\n</code></pre>\n\n<p>Then, all you'd have to do is</p>\n\n<pre><code>public static warMod Gen(List<AtMap> atMaps) \n => new warMod { AtMapArr = atMaps.Select(x => new AtMap(x)).ToList() };\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T20:41:33.853",
"Id": "454839",
"Score": "0",
"body": "This is a good solution. You could make it even shorter if you make a static factory method that calls the constructor, and then it becomes `atMaps.Select(AtMap.Factory).ToList()`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T22:19:42.303",
"Id": "454862",
"Score": "0",
"body": "@OP: If the default values of `srFl` or `desFl` are null, you can remove the conditional from the assignments. If the default values are not null, you could rewrite `if(a.srFl != null) srFl = a.srFl;` as `srFl = a.srFl ?? srFl;`. Honestly not sure whether null-coalescing makes it more readable, though."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T14:16:17.517",
"Id": "232801",
"ParentId": "232794",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T12:08:41.933",
"Id": "232794",
"Score": "-2",
"Tags": [
"c#"
],
"Title": "Make foreach with nested-if's more compact and readable"
}
|
232794
|
<p>I just tried to create a program for the <a href="https://en.wikipedia.org/wiki/Eight_queens_puzzle" rel="nofollow noreferrer">N queens</a> problem.</p>
<pre><code>def print_board() -> None:
""" Prints the board """
length = 3 * (SIZE - 1) + SIZE + 4
print()
print('-' * length)
for row in board:
print('| ' + ' | '.join(row) + ' |')
print('-' * length)
print()
def isValid(row: int, col: int) -> bool:
""" Returns if a cell index is valid """
return 0 <= row < SIZE and 0 <= col < SIZE
def isSafe(row: int, col: int) -> bool:
""" Checks if the given index position is safe """
# Checks if the column is safe
for i in range(SIZE):
if i != row and board[i][col] != ' ':
return False
# Checks if the row is safe
for j in range(SIZE):
if j != col and board[row][j] != ' ':
return False
# Checks if the diagonals are safe
for k in range(SIZE):
if isValid(row + k, col + k) and board[row + k][col + k] != ' ' or \
isValid(row - k, col + k) and board[row - k][col + k] != ' ' or \
isValid(row + k, col - k) and board[row + k][col - k] != ' ' or \
isValid(row - k, col - k) and board[row - k][col - k] != ' ':
return False
return True
def backtrack(row=0, total=0) -> bool:
""" Backtracks and fills chacks for every possible combination """
# If all rows are safely filled with queens
if row == SIZE:
# print_board() # Uncomment the code to print the current solution
# input('Enter to continue... ')
return 1
for col in range(SIZE):
# If the current index is safe, check for the next row
if isSafe(row, col):
board[row][col] = 'Q'
total += backtrack(row + 1)
board[row][col] = ' '
return total
def solve() -> None:
""" Calls backtrack and prints number of solutions """
total = backtrack()
print()
if not total:
print('No possible solution was found')
elif total == 1:
print('There is a total of 1 solution')
else:
print(f'There are a total of {total} solutions')
if __name__ == '__main__':
SIZE = int(input('Enter the size of the board: '))
board = [[' '] * SIZE for row in range(SIZE)]
solve()
</code></pre>
<p>Though it does work, I'm not satisfied yet. </p>
<p>I want to make this code as short as possible while also following <a href="https://www.python.org/dev/peps/pep-0008/" rel="nofollow noreferrer">Pep8</a> rules.</p>
<p>I believe there isn't a faster approach, but if there are any, please enlighten me!</p>
<p>Thank you!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T15:12:14.837",
"Id": "454770",
"Score": "1",
"body": "Did you notice Naming conventions in PEP8?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T18:35:49.250",
"Id": "454833",
"Score": "0",
"body": "@RomanPerekhrest *facepalms* I knew I was doing something wrong, this was it."
}
] |
[
{
"body": "<p>This isn't bad looking code. It's formatted nicely, and I think this is a good use of type hints.</p>\n\n<p>My two main concerns are your naming, and your use of <code>print</code>.</p>\n\n<hr>\n\n<p>Names should be snake_case according to <a href=\"https://www.python.org/dev/peps/pep-0008/#introduction\" rel=\"nofollow noreferrer\">PEP8</a>. You started adhering to it, then reverted back to camelCase later. It can be a hard change to make if you're used to other languages, but it's proper for Python, and studies have shown that it's easier to read anyways. </p>\n\n<hr>\n\n<p>I think you're \"abusing\" <code>print</code> here.</p>\n\n<p><code>print_board</code> is printing the board instead of returning a representation that can be used elsewhere. I'd change it to <code>format_board</code> (or <code>stringify_board</code> or something similar), and have it return a string instead of forcibly printing the board. It would be a fairly trivial change too. Just concatenate the different printed strings together, replace the <code>print()</code> calls with a <code>\"\\n\"</code>, and change your imperative <code>for</code> loop to a list comprehension that you give to <code>join</code> after. It would honestly probably be shorter and cleaner after those changes anyways. </p>\n\n<p>Then elsewhere, like in <code>solve</code>, you're printing the results. I would instead return some kind of indicator value, like an <code>Enum</code> instead of printing there. </p>\n\n<p>Why bother with limiting <code>print</code>? Testing and portability. Say you wanted to programmatically test <code>print_board</code>. You would need to intercept <code>sys.stdin</code> to get the printed text to compare it against a known string. This is both slower and more complicated than just having a function that returns a string in the first place. The same goes for <code>solve</code>. To test that's its operating correctly, you need to verify what it's printing instead of just checking the return value. </p>\n\n<p>Forcing use of <code>print</code> also prevents you from using these function in any other context, like a Tkinter UI.</p>\n\n<p>Return the data and let the caller decide how they want to use it.</p>\n\n<p>If you really want a <code>print_board</code> function for convenience, just make a wrapper:</p>\n\n<pre><code>def print_board() -> None:\n print(format_board())\n</code></pre>\n\n<hr>\n\n<p>Lastly, instead of using strings to indicate piece types, I'd use an <code>Enum</code>. Right now, you have a strong \"Q\" to indicate a queen on the board. Strings can be easily typo'd though; enums can't. If the only two valid board piece options are an empty space and a queen, you should use an enum to not only make that explicitly stated, but to enforce it. Entering an invalid enum invalid enum value will lead to an error instead of code-dependant effects that may end lead to silent failures.</p>\n\n<hr>\n\n<p>I also realized just as I was about to submit this that your <code>print_board</code> and <code>backtrack</code> functions are relying on the global <code>board</code> defined in the \"main\". Don't do this! If those functions require data like <code>board</code>, that data should be explicitly passed in as arguments. If you wanted to test those functions, you wouldn't be able to just generate a dummy board in the console and pass it in. You would need to modify the global, run the function, then remember to modify to global again before further testing. The less relience you have on global variables, the easier your code will be to test and comprehend. Ideally, functions should accept as arguments all the data that they require, and return all data that they produce. This isn't always feasible, but it's a good design choice to pick unless you have a good reason to rely on globals (like <code>board</code>) and side-effects (like <code>print</code>).</p>\n\n<hr>\n\n<hr>\n\n<p>Now that I'm on my full computer, I'm able to take a better look at the code and play with it a little more.</p>\n\n<p>First, here's the enum usage that I was referring to. Ignore my previous suggestion for <code>solve</code>. I realized that an enum wasn't really appropriate there (I'll show my alternate suggestion after). Basically, <code>BoardSquare</code> represents the total possible states of each square on the board, along with the string representations that they have:</p>\n\n<pre><code>from enum import Enum\n\nclass BoardSquare(Enum): # A square on the board can either be a queen, or an empty space\n QUEEN = \"Q\"\n EMPTY = \" \"\n</code></pre>\n\n<p>With that, I decided to use some <em>slightly</em> more advanced type hinting and created an alias for the board:</p>\n\n<pre><code>from typing import List\n\nBoard = List[List[BoardSquare]] # A Board is a list of lists of board squares\n</code></pre>\n\n<p>This, combined with the enum ensures that nothing except a <code>QUEEN</code> or <code>EMPTY</code> is ever put into a board. Attempting to do so will cause a warning. This helps prevent typos:</p>\n\n<pre><code>board: Board = [[BoardSquare.EMPTY] * side_length for _ in range(side_length)]\nboard[1][2] = \"SOME INVALID DATA\" # Causes an \"Unexpected types\" warning\n</code></pre>\n\n<p>And here's my <code>format_board</code> that I came up with:</p>\n\n<pre><code># A helper to neaten up format_board\ndef _format_row(row: List[BoardSquare]) -> str:\n return '| ' + ' | '.join(square.value for square in row) + ' |' # .value is the string defined in the enum\n\n\ndef format_board(board: Board) -> str:\n \"\"\" Formats the board as a string \"\"\"\n board_length = len(board) # Instead of relying on the global SIZE, I'd just compute it\n print_side_length = 3 * (board_length - 1) + board_length + 4\n\n top_bottom_str = '-' * print_side_length # Might as well save this instead of writing the same thing twice.\n\n # I'll admit, this got a little more convoluted than I thought it would. It's just nested called to `join `though.\n return top_bottom_str + \"\\n\" \\\n + '\\n'.join(_format_row(row) + '\\n' + top_bottom_str for row in board)\n</code></pre>\n\n<p>Yes, as the comments note, this got a little longer than I though it would. The need to translate the enum into a string using the generator expression necessitated breaking off the formatting of each row into its own function for readability.</p>\n\n<p>After going around and touching up some other stuff (see the comments), here's the full code that I ended up with:</p>\n\n<pre><code>from typing import List\nfrom enum import Enum\n\n\nclass BoardSquare(Enum): # A square on the board can either be a queen, or an empty space\n QUEEN = \"Q\"\n EMPTY = \" \"\n\n\nBoard = List[List[BoardSquare]] # A Board is a list of lists of board squares\n\n\n# Make it easier to create a new board for testing purposes\ndef new_board(side_length: int) -> Board:\n return [[BoardSquare.EMPTY] * side_length for _ in range(side_length)]\n\n\n# A helper to neaten up format_board\ndef _format_row(row: List[BoardSquare]) -> str:\n return '| ' + ' | '.join(square.value for square in row) + ' |' # .value is the string defined in the enum\n\n\ndef format_board(board: Board) -> str:\n \"\"\" Formats the board as a string \"\"\"\n board_length = len(board) # Instead of relying on the global SIZE, I'd just compute it\n print_side_length = 3 * (board_length - 1) + board_length + 4\n\n top_bottom_str = '-' * print_side_length # Might as well save this instead of writing the same thing twice.\n\n # I'll admit, this got a little more convoluted than I thought it would. It's just nested called to `join `though.\n return top_bottom_str + \"\\n\" \\\n + '\\n'.join(_format_row(row) + '\\n' + top_bottom_str for row in board)\n\n\ndef print_board(board: Board) -> None:\n \"\"\" Prints the board \"\"\"\n print(format_board(board))\n\n\ndef is_valid(row: int, col: int) -> bool:\n \"\"\" Returns if a cell index is valid \"\"\"\n return 0 <= row < GLOBAL_SIZE and 0 <= col < GLOBAL_SIZE\n\n\ndef is_safe(row: int, col: int) -> bool:\n \"\"\" Checks if the given index position is safe \"\"\"\n # Checks if the column is safe\n for i in range(GLOBAL_SIZE):\n if i != row and global_board[i][col] != BoardSquare.EMPTY:\n return False\n\n # Checks if the row is safe\n for j in range(GLOBAL_SIZE):\n if j != col and global_board[row][j] != BoardSquare.EMPTY:\n return False\n\n # Checks if the diagonals are safe\n for k in range(GLOBAL_SIZE):\n if is_valid(row + k, col + k) and global_board[row + k][col + k] != BoardSquare.EMPTY or \\\n is_valid(row - k, col + k) and global_board[row - k][col + k] != BoardSquare.EMPTY or \\\n is_valid(row + k, col - k) and global_board[row + k][col - k] != BoardSquare.EMPTY or \\\n is_valid(row - k, col - k) and global_board[row - k][col - k] != BoardSquare.EMPTY:\n\n return False\n\n return True\n\n\ndef backtrack(row=0, total=0) -> int: # I changed this to int. It was bool before, but that was wrong\n \"\"\" Backtracks and fills checks for every possible combination \"\"\"\n # If all rows are safely filled with queens\n if row == GLOBAL_SIZE:\n # print_board(global_board) # Uncomment the code to print the current solution\n # input('Enter to continue... ')\n return 1\n\n for col in range(GLOBAL_SIZE):\n # If the current index is safe, check for the next row\n if is_safe(row, col):\n global_board[row][col] = BoardSquare.QUEEN # Use the enums values here instead\n total += backtrack(row + 1)\n global_board[row][col] = BoardSquare.EMPTY\n\n return total\n\n\ndef report_solution() -> None:\n \"\"\" Calls backtrack and prints number of solutions \"\"\"\n total = backtrack()\n\n print()\n\n if not total:\n print('No possible solution was found')\n\n elif total == 1:\n print('There is a total of 1 solution')\n\n else:\n print(f'There are a total of {total} solutions')\n\n\nif __name__ == '__main__':\n GLOBAL_SIZE = int(input('Enter the size of the board: '))\n\n global_board = new_board(GLOBAL_SIZE)\n\n report_solution()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T05:52:19.807",
"Id": "454880",
"Score": "0",
"body": "`I'm on my phone, so this is going to be a relatively poor review`. Not at all! This is one of the best reviews I've ever gotten! But, could you please explain how to use `Enum` here? I don't quite understand how to use them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T06:11:05.930",
"Id": "454883",
"Score": "1",
"body": "Just search for \"Python enum\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T06:35:36.413",
"Id": "454884",
"Score": "0",
"body": "@RolandIllig I did, but I'm not quite sure how to use it here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T06:38:54.013",
"Id": "454885",
"Score": "0",
"body": "Ah, ok, you should always tell from the beginning when you did search, and what you found, and what you didn't understand. Otherwise we assume (by experience) that you are too lazy to search. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T13:52:31.850",
"Id": "454910",
"Score": "0",
"body": "@Srivaths This afternoon (I just woke up), I'm going to fix this review up a bit, including some examples. I'll message you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T14:32:01.123",
"Id": "454912",
"Score": "0",
"body": "Thank you. Ut means a lot when someone is working so hard just to help me!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T17:31:44.023",
"Id": "454930",
"Score": "0",
"body": "@Srivaths No problem. And see my edit at the bottom under the double line-separation"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T18:40:59.793",
"Id": "454946",
"Score": "0",
"body": "@RolandIllig Oh! I didn't know that! I'll be sure to keep it in mind from now on!"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T17:37:57.207",
"Id": "232816",
"ParentId": "232795",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "232816",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T12:21:40.750",
"Id": "232795",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"chess",
"n-queens"
],
"Title": "N queens problem in python"
}
|
232795
|
<p>Below is a code to update a google sheet using the database values. The script is working fine but it is rather slow because of the sleep function which I have to put because of the "Quota exceeding error" below. If I remove the sleep time it would work much faster but after a certain number of rows get updated it will throw the below error.</p>
<p>I have to update three columns namely A,B & C of which the value start row is from 4th row onwards. So basically I need advise/recommendations to improve this code on the below points:</p>
<ol>
<li>To make the query execution faster without getting the below error.</li>
<li>Is there a way to generalise this script, means without hardcoding the spreadsheet name (DB details I can get in a generalised way and read from config, for testing purpose only hardcoded the values)</li>
</ol>
<pre class="lang-none prettyprint-override"><code>gspread.exceptions.APIError: { "error": {
"code": 429,
"message": "Insufficient tokens for quota 'ReadGroup' and limit 'USER-100s' of service 'sheets.googleapis.com' for consumer 'project_number:*******'.",
"status": "RESOURCE_EXHAUSTED",
"details": [
{
"@type": "type.googleapis.com/google.rpc.Help",
"links": [
{
"description": "Google developer console API key",
"url": "https://console.developers.google.com/project/***/apiui/credential"
}
]
}
] } }
</code></pre>
<p><strong>Python Code:</strong></p>
<pre><code>import psycopg2
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from time import sleep
import datetime
def update_sheet(sheet, table, rangeStart='A', rangeEnd='C'):
for index, row in enumerate(table):
range = '{start}{i}:{end}{i}'.format(start=rangeStart, end=rangeEnd, i=index+4)
cell_list = sheet.range(range)
for i, cell in enumerate(cell_list):
start_time = datetime.datetime.now()
cell.value = row[i]
sheet.update_cells(cell_list)
end_time = datetime.datetime.now()
if (end_time - start_time).total_seconds() < 1:
sleep(1.01 - (end_time - start_time).total_seconds())
cnx_psql = psycopg2.connect(host="xxx.xxx.xxx.xx", database="postgres", user="postgres",password="******", port="5432")
print('DB connected')
psql_cursor = cnx_psql.cursor()
METADATA_QUERY = '''select product_id,CAST(low_stock_date as TEXT) low_stock_date,sku from test.low_stock_date;'''
psql_cursor.execute(METADATA_QUERY)
results = psql_cursor.fetchall()
cell_values = (results)
scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('/Users/lins/Documents/GS_secret/secret_key.json',scope)
client = gspread.authorize(creds)
sheet = client.open_by_url('https://docs.google.com/spreadsheets/d/1****zQ/edit#gid=0').sheet1
#Function Call
update_sheet(sheet, cell_values)
psql_curso.close()
cnx_psql.close()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T13:57:22.740",
"Id": "454753",
"Score": "0",
"body": "Is there an indentation error or do you really call `sheet.update_cells` every iteration of the `for` loop?"
}
] |
[
{
"body": "<p>The <a href=\"https://gspread.readthedocs.io/en/latest/api.html#gspread.models.Worksheet.update_cells\" rel=\"nofollow noreferrer\"><code>update_cells</code> call can update multiple cells at once</a>. So you should calculate all new values locally and push the changes in one update. This should use only one token, instead of one per cell (untested code): </p>\n\n<pre><code>def update_sheet(sheet, table, start='A', end='C'):\n to_update = []\n for i, row in enumerate(table):\n cells = sheet.range(f'{start}{i+4}:{end}{i+4}')\n for cell, value in zip(cells, row):\n cell.value = value\n to_update.extend(cells)\n sheet.update_cells(to_update)\n</code></pre>\n\n<p>I also changed the names and indentation to follow Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, and used an <a href=\"https://www.python.org/dev/peps/pep-0498/\" rel=\"nofollow noreferrer\"><code>f-string</code></a> for easier string formatting.</p>\n\n<p>This still has the problem that it needs to get each row from the sheet, each of which does an API call. Instead you can get each column as a range and update one column at a time, which saves calls if your table has less columns than rows. For this we need to transpose the table first, though:</p>\n\n<pre><code>def update_sheet(sheet, table, columns=\"ABC\", header=4):\n to_update = []\n table = list(zip(*table)) # transpose the table\n for col_name, col in zip(columns, table): # iterating over columns now\n r = f\"{col_name}{header}:{col_name}{len(col)+header}\" # changed range\n print(r) # for debugging\n cells = sheet.range(r)\n for cell, value in zip(cells, col):\n cell.value = value\n to_update.extend(cells)\n sheet.update_cells(to_update)\n</code></pre>\n\n<p>With this it is no problem to use e.g. this table of size 2500 x 3:</p>\n\n<pre><code>import numpy as np\n\n...\ntable = list(map(list, np.arange(2500*3).reshape(-1, 3).astype(str)))\nupdate_sheet(sheet, table)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T14:19:55.410",
"Id": "454757",
"Score": "0",
"body": "@Linu: How large is your table? It worked for me for a small test example (100 rows, 3 columns). If you have many more rows than columns, transposing the table first might gain you some less calls."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T14:21:35.440",
"Id": "454758",
"Score": "0",
"body": "@GraipherThe table has a max rows of 2500.Any other way to deal with this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T14:32:41.473",
"Id": "454765",
"Score": "0",
"body": "@Linu: No need to change your SQL, just transpose your list of lists (using e.g. the common Python idiom `list(zip(*table))`. I added it in the second function. The only other difference is that the range gets the whole column now, so we need all column names instead of start and end. But for that you could also write a convenience function that gives you all column names between start and end. Possibly even using [this recent answer of mine](https://codereview.stackexchange.com/a/232635/98493)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T14:03:34.700",
"Id": "232799",
"ParentId": "232796",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "232799",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T13:06:19.043",
"Id": "232796",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"google-sheets"
],
"Title": "Update Google Sheet with Python"
}
|
232796
|
<p>Say you have two strings: exp->aaccbb comp-> aa2bb</p>
<p>This example will return true as there are 2 chars between aa and bb. I have written this code snippet and am wondering if there is a better way do solve this problem and if I am missing any edge cases.</p>
<p>Also, what would be the fastest way to solve this problem with respect to time/place complexity? The solution is a 2 pointer approach with linear complexity. Follow up -> either side can have compressions or both at the same time.</p>
<pre><code>const isNumber = (ch)=>{
return Number(ch) == ch
}
const isExp = (exp, comp)=>{
let i=j=0;
while(i<exp.length && j<comp.length){
if(comp[j] !== exp[i] && !isNumber(comp[j])){
return false
}
else if(isNumber(comp[j])){
let currentCompIdx = j;
/*Find consexutive numbers*/
while(isNumber(comp[currentCompIdx+1]))currentCompIdx++;
/*Get Number from the compressed string*/
const moveIndexBy = Number(comp.slice(j,currentCompIdx+1));
/*set j pointer to index after the number*/
j=currentCompIdx+1;
/*Check if the letters after number is same*/
if(comp[j] !== exp[i+moveIndexBy]){
return false
}
i++;
j++;
}
else{
i++;
j++;
}
}
return true
}
/*Returns true as it has 2 chars between aa and cc*/
alert(isExp("aaccbb", "aa2bb"))
/*Returns true as it has 2 chars between aa and cc and 4 chars between bb and cc*/
alert(isExp("aaccbbqqqqcc", "aa2bb4cc"))
/*Returns true as it has 10 chars between aa and cc */
alert(isExp("aaccbbqqqqsacc", "aa10cc"))
/*Returns false as the exp string as only 1 char between aa and bb */
alert(isExp("aacbb", "aa2bb"))
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T17:21:20.867",
"Id": "454804",
"Score": "1",
"body": "Your first two test cases are returning false and your last two test cases are not returning anything! Also, I'm not super clear on what scenarios you are trying to test for. Could you elaborate your question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T17:01:45.530",
"Id": "454926",
"Score": "0",
"body": "Hey Rager, Thanks for responding. The Question is you are given two strings expanded and compressed. Compressed string will have numbers in the string. Compressed string should have the same character left and right of the number. For Eg . \nSay expanded str = aabbcc and compressed str = aa2cc. These two strings should should result as true as there are 2 characters (bb) between aa and cc.\nExample2- \nif expStr = aabbbcc and compStr = aa2cc will return false as exp str has 3 characters between aa and cc."
}
] |
[
{
"body": "<p>Notice how close the syntax of your compressed strings resemble that of a regular expression:</p>\n\n<pre><code> aa2bb => aa.{2}bb\naa2bb4cc => aa.{2}bb.{4}cc\n aa10cc => aa.{10}cc\n</code></pre>\n\n<p>Therefore you can easily create a regexp from your compressed string and test the expanded string against it:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function isExp(exp, comp) {\n const regexp = RegExp(`^${comp.replace(/\\d+/g, '.{$&}')}$`)\n return regexp.test(exp);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T17:02:16.097",
"Id": "454927",
"Score": "0",
"body": "Wow! Thats amazing. What will be the time/space complexity of this approach?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T18:04:03.877",
"Id": "454932",
"Score": "0",
"body": "@RamaM I would think using regular expressions would be slower. Are you trying to get the fastest execution without caring much about readability? If so you should state that & maybe mention why (E.g part of a contest/challenge)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T20:59:02.340",
"Id": "454966",
"Score": "0",
"body": "Agreed. I want to know what is fastest and the best strategy to approach this problem. The solution i came up with is a linear solution O(n) with two pointer approach one for expanded string and one for compressed."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T10:21:16.017",
"Id": "232853",
"ParentId": "232802",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T14:24:54.707",
"Id": "232802",
"Score": "1",
"Tags": [
"javascript",
"strings"
],
"Title": "Expand compressed string range"
}
|
232802
|
<p>I wrote this singly linked list and it worked fine,Now can anyone review my code. I want to do some more clean my delete and add function. And some abstraction.</p>
<pre><code>#include<stdio.h>
#include<stdlib.h>
typedef struct q_9
{
int data;
struct q_9 *link;
}*node;
node head=NULL;
node tail=NULL;
node newnode(int x);
void node_add(int x);
void delete_front();
void count();
void display();
void delete_last();
int main() {
int choice,element;
while (1)
{
printf("\n\t 1-->for add data:");
printf("\n\t 2-->for delete data:");
printf("\n\t 3-->for count node:");
printf("\n\t 4-->for delete from last data:");
printf("\n\t 5-->for display data:");
printf("\n please enter a choice:");
scanf("%d",&choice);
switch (choice)
{
case 1: printf("enter the element:\t------->");
scanf("%d",&element);
node_add(element);
break;
case 2:delete_front();
break;
case 3: count();
break;
case 4: delete_last();
break;
case 5:display();
break;
default:
break;
}
if (choice==6)
{
printf("you are exited from loop:\n");
break;
}
}
}
node newnode(int x)
{
node temp=(node)malloc(sizeof(node));
temp->data=x;
temp->link=NULL;
return temp;
}
void node_add(int x)
{
node temp=newnode(x);
if(head==NULL)
{
head=temp;
tail=temp;
temp=NULL;
return;
}
else
{
tail->link=temp;
tail=temp;
}
}
void display()
{
node p=head;
while (p!=NULL)
{
printf("%d\t",p->data);
p=p->link;
}
}
void count()
{
node p=head;
if (p==NULL)
{
printf("no element present here\n");
}
int i=0;
while(p!=NULL)
{
i++;
p=p->link;
}
printf("here is %d nodes are present\n",i);
}
void delete_front()
{
node temp=head;
head=head->link;
free(temp);
printf("\n memory freed");
}
void delete_last()
{
node temp=tail;
node p=head;
while(p->link->link!=NULL)p=p->link;
tail=p->link;
free(temp);
printf("memory freed\n");
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T15:45:22.847",
"Id": "454778",
"Score": "0",
"body": "\"I want to do some more clean my delete and add function.\" Is there a reason you want to \"clean\" the delete and add functions specifically? Wouldn't you want to \"clean\" all of your code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-01T14:15:49.813",
"Id": "455780",
"Score": "0",
"body": "@Linny Did you just accidentally remove a header include?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-01T16:04:43.627",
"Id": "455786",
"Score": "0",
"body": "@Mast Yeah, my mistake."
}
] |
[
{
"body": "<p>If one wants abstraction, then the interface (the menu) should be in a different file then the linked-list implementation, and should expose only function prototypes which are necessary in a header file, (the rest can be <a href=\"https://stackoverflow.com/questions/572547/what-does-static-mean-in-c\">static</a>.) The one with <code>main</code> should drive your linked list; the linked list should have no <code>main</code>. That way, code would be interchangeable into other, more complicated programmes. In practice, one should do an <a href=\"https://en.wikipedia.org/wiki/Software_testing\" rel=\"nofollow noreferrer\">automated test</a> in another file to see if the, edge cases in particular, (<em>eg</em>, empty list, which is not robust,) do what one expects them to.</p>\n\n<p>I would question this use as a <a href=\"https://en.wikipedia.org/wiki/Singleton_pattern\" rel=\"nofollow noreferrer\">singleton</a>, but maybe it's the way it's supposed to work. To break out of this pattern, I would accept another parameter to all functions, (except the constructor, in this case <code>newnode</code>.) In a sense, a linked-list is a tricky thing to abstract because, by definition, it's a recursive data structure, so how can one tell the middle of a list from the head? I suggest the looking at <a href=\"https://en.wikipedia.org/wiki/Linked_list\" rel=\"nofollow noreferrer\">Wikipedia</a>, <a href=\"https://en.cppreference.com/w/cpp/container/forward_list\" rel=\"nofollow noreferrer\">C++</a>, <a href=\"https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/LinkedList.html\" rel=\"nofollow noreferrer\">Java</a>, and <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.linkedlist-1?view=netframework-4.8\" rel=\"nofollow noreferrer\">C#</a> for existing implementations.</p>\n\n<p>One should turn up the warnings on ones compiler: in particular, <code>#include <stdio.h></code> is necessary for <code>printf</code>. (However, one should consider not using this function to make it more abstract.)</p>\n\n<p>Beware of the effects of <code>typedef</code> on <a href=\"https://www.codeproject.com/Tips/1172783/Gems-for-typedef-and-namespace-in-C\" rel=\"nofollow noreferrer\">namespace</a>; the <a href=\"https://www.kernel.org/doc/html/v4.10/process/coding-style.html#typedefs\" rel=\"nofollow noreferrer\">Linux kernel coding style</a> would frown upon such usage. In particular, the naming of <code>q_9</code> and <code>node</code> is problematic when one gets into more complex programmes. Maybe <code>struct int_node</code> or even <code>struct int_list_node</code>?</p>\n\n<p>When using, eg, <code>int main()</code>, beware that one is <a href=\"https://stackoverflow.com/questions/41803937/func-vs-funcvoid-in-c99\">not using prototypes</a> and subverting the compiler's ability to type-check. One should really use <code>int main(void)</code>.</p>\n\n<p>One doesn't check the return value of <a href=\"https://pubs.opengroup.org/onlinepubs/009695399/functions/malloc.html\" rel=\"nofollow noreferrer\">malloc</a>. This is bad because the function can return null and then the code has <code>temp->null=x</code>, which is potentially dereferencing a null pointer.</p>\n\n<p>For example, <code>void count()</code> is fine for printing out the lists count on <code>stdout</code>, but maybe this should be <code>int count(void)</code>, (or even <code>size_t count(void)</code>,) the user, (of the abstract file, probably yourself,) should be able to decide what they want to do with this information. Same with the print memory freed, one doesn't want to do this all the time.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T03:25:53.393",
"Id": "232842",
"ParentId": "232803",
"Score": "2"
}
},
{
"body": "<p><strong>Design: OK initial attempt at abstraction</strong></p>\n\n<p><code>main()</code> does not expose <code>struct q_9</code> members.</p>\n\n<p><strong>Design: <code>.tail</code> is not needed</strong></p>\n\n<p>Present function set has no benefit from the <code>tail</code> member. It is removable. Even <code>delete_last()</code> walks down the list.</p>\n\n<p><strong>Design: Global variables not needed</strong></p>\n\n<p>This is a major change, so will assume this code is using the simple one linked-list as an exercise.</p>\n\n<p><strong>Design: Consider common naming prefix (and avoid type-defining a pointer)</strong></p>\n\n<p>Example: </p>\n\n<pre><code>typedef struct q9 {\n struct q9 *link;\n int data;\n} q9_T;\n\nq9_T *q9_newnode(int x);\nint q9_count(const q9_T *node);\nvoid q9_display(const q9_T *node);\nvoid q9_add(q9_T *node, int x);\nvoid q9_delete_front(q9_T *node);\nvoid q9_delete_last(q9_T *node);\n// new ideas\nint q9_pop(q9_T *node);\nint q9_top(const q9_T *node);\nint q9_end(const q9_T *node); // Potential real use of .tail\nbool q9_empty(const q9_T *node);\n</code></pre>\n\n<p><strong>Bug: Wrong allocation size</strong></p>\n\n<p>Code allocates enough for a pointer rather than enough for the <code>struct</code>.</p>\n\n<p>Cast not needed. Better to allocate to the de-referenced object than type.</p>\n\n<pre><code>// node temp=(node)malloc(sizeof(node));\nnode temp = malloc(sizeof *temp);\n</code></pre>\n\n<p><strong>Function declarations say nothing about signature</strong></p>\n\n<p><code>void foo();</code> allows later calls like <code>foo(1), foo(\"hello\", 5.0)</code> to pass undetected as errors.</p>\n\n<pre><code>// void delete_front();\n// void count();\n// void display();\n// void delete_last();\nvoid delete_front(void);\nvoid count(void);\nvoid display(void);\nvoid delete_last(void);\n</code></pre>\n\n<p><strong>Inconsistent spacing</strong></p>\n\n<p>Use an auto-formatter - life is too short for manual formatting.</p>\n\n<p><strong>Lack of error checking</strong></p>\n\n<p>No checking if <code>scanf(\"%d\",&choice);</code> succeeded, nor <code>malloc()</code>.</p>\n\n<p><strong>Unneeded code</strong></p>\n\n<p><code>temp=NULL;</code> serves nor purpose in <code>node_add(int x)</code></p>\n\n<p><strong>Bug: de-referencing of <code>NULL</code></strong></p>\n\n<p><code>delete_front()</code> does not check if <code>head == NULL</code> before <code>head->link</code>. <code>tail</code> is not updated to <code>NULL</code> when last link deleted.</p>\n\n<p><strong>Bug: de-referencing of <code>NULL</code></strong></p>\n\n<p><code>delete_last()</code> does not check if <code>p->link == NULL</code> before <code>p->link->link</code>. Also expect <code>head</code> to be updated to <code>NULL</code> if last node deleted.</p>\n\n<p><strong>Prompts use lower case rather than sentence case.</strong></p>\n\n<p>Unless you are <a href=\"https://en.wikipedia.org/wiki/E._E._Cummings\" rel=\"nofollow noreferrer\">E. E. Cummings</a>, use sentence case for prompts.</p>\n\n<pre><code>// printf(\"\\n please enter a choice:\");\nprintf(\"\\n Please enter a choice:\");\n</code></pre>\n\n<p><strong>Insure output is seen before input</strong></p>\n\n<p>Due to various buffer modes of <code>stdout</code>, best to flush output before input, especially if the prior output does not in with a <code>'\\n'</code>.</p>\n\n<pre><code> printf(\"\\n please enter a choice:\");\n fflush(stdout); // add\n scanf(\"%d\",&choice);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T09:31:39.163",
"Id": "232933",
"ParentId": "232803",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "232933",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T15:10:56.047",
"Id": "232803",
"Score": "4",
"Tags": [
"c",
"linked-list",
"c99"
],
"Title": "Link list working"
}
|
232803
|
<p>One operation of my Android project is to decrypt one file (chosen in a set of ~30 files for pagination<sup>1</sup>) of ~10 Mb each and I do this with the following:</p>
<pre><code>fun InputStream.cipherDecryptWithSessionPwd(password: String): String {
var payloadArray: List<Byte>? = this.readBytes().toList()
var salt = payloadArray?.subList(0,32)
var spec: Rfc2898DeriveBytes? = Rfc2898DeriveBytes(password, salt?.toByteArray(), 50000)
var realData = payloadArray?.subList(32, payloadArray.size)
val keyBytes = spec?.getBytes(256 / 8)
val ivBytes = spec?.getBytes(128 / 8)
var cipher: Cipher? = Cipher.getInstance("AES/CFB/PKCS7Padding")
var secretKey: SecretKeySpec? = SecretKeySpec(keyBytes, "AES")
var ivSpec: IvParameterSpec? = IvParameterSpec(ivBytes)
cipher?.init(Cipher.DECRYPT_MODE, secretKey, ivSpec)
var byteArrayInputStream: ByteArrayInputStream? = ByteArrayInputStream(realData?.toByteArray())
var decipherStream: CipherInputStream? = CipherInputStream(byteArrayInputStream, cipher)
val d = BufferedReader(InputStreamReader(decipherStream, Charsets.UTF_8), 0xFFFF)
return d.readLine()
}
</code></pre>
<p>The problem with this is that at around the 72nd time<sup>2</sup> I repeat the operation Android kills my application because it runs out of memory<sup>3</sup>.</p>
<p>This is the second version of the decryption function, the first one caused the OOM error around the 25th time the operation was made. The problem here clearly is the number of conversions done (<code>InputStream</code> -> <code>ByteArray</code> -> <code>List<Byte></code> and others).</p>
<p>I don't know how to optimize more, the first version of the method was not mine and I never did encryption (and optimization) before.</p>
<p><strong>Scenario</strong> (and what have been tried):<br>
1 - Files are stored encrypted on the device, can't have them decrypted but at runtime<br>
2 - With the decrypted result (JSON) I fill a model using [Gson] (<a href="https://github.com/google/gson" rel="nofollow noreferrer">https://github.com/google/gson</a>), but the OOME seem to be thrown when my function is running (the exception points at the first line of the function)<br>
3 - Calculations are done and the model is disposed of when the next page is shown, then the whole operation has to be repeated
# - We tried reducing the number of JSON "records" inside each file from 5000 per file to 1000 per file reducing the file size to 2 Mb but the problem persists</p>
<p><strong>Notes</strong>:<br>
1 - We event tried reducing the pagination reaching files size to 2 Mb but the problem persists<br>
2 - This has to be done at least 130 times per session<br>
3 - With, <a href="https://partner.samsungknox.com/" rel="nofollow noreferrer">Knox</a> my application is the only one allowed to run on the device</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T15:36:27.433",
"Id": "454774",
"Score": "0",
"body": "Well, if it kills it the 72nd time it runs, doesn't that mean that the function you posted has enough memory to run, but there's something else going on outside of the snippet? Are you storing all the results in memory for each file? In normal applications I might say just your results to disk, but since the data seems to be sensitive, maybe not. You might have to limit the amount of results you keep in memory and re-calculate them when you want to view them again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T15:52:21.757",
"Id": "454782",
"Score": "0",
"body": "@Slothario - I've edited the question with more details"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T15:58:15.803",
"Id": "454785",
"Score": "0",
"body": "Are you sure the results are fully disposed of, though? Have you tried profiling it for memory leaks, or data that's still hanging around that isn't needed?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T16:05:02.360",
"Id": "454787",
"Score": "0",
"body": "Yep, I profiled the whole operation (it has been a looong week), I set to `null` each object when no more needed and nothing worked, I think that asking here is the last resort. One option would drastically change the whole project causing a seatback of months"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T16:06:12.763",
"Id": "454788",
"Score": "0",
"body": "@Slothario - are you asking these questions because the function is good for you?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T16:49:19.773",
"Id": "454790",
"Score": "0",
"body": "No, I haven't programmed with Android in a while and don't have an environment to test it in. However it would help if you made the smallest possible example that still produces the out-of-memory example. At the very least, you should post how you're storing the results of this function in memory, and how you're trying to remove them from memory, as I suspect that's where the problem lies."
}
] |
[
{
"body": "<p>I can't help too much as I don't have running code, but I can at least get rid of all <code>List</code> and <code>Array</code> conversions, that will make it run faster and reduce lot of memory garbage. I also removed all the optionals as immutability is our best friend :)</p>\n\n<p>Is it ran once per stream and then it is closed or more than once per stream? There is no information about how stream is being handled and if it is closed properly. That can be issue.</p>\n\n<pre><code>fun InputStream.cipherDecryptWithSessionPwd(password: String): String {\n val payloadArray: ByteArray = this.readBytes()\n val salt = payloadArray.sliceArray(0 until 32)\n val spec = Rfc2898DeriveBytes(password, salt, 50000)\n val realData = payloadArray.sliceArray(32 until payloadArray.size)\n\n val keyBytes = spec.getBytes(256 / 8)\n val ivBytes = spec.getBytes(128 / 8)\n\n val cipher = Cipher.getInstance(\"AES/CFB/PKCS7Padding\")\n val secretKey: SecretKeySpec? = SecretKeySpec(keyBytes, \"AES\")\n val ivSpec: IvParameterSpec? = IvParameterSpec(ivBytes)\n cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec)\n val byteArrayInputStream = ByteArrayInputStream(realData)\n val decipherStream = CipherInputStream(byteArrayInputStream, cipher)\n\n val d = BufferedReader(InputStreamReader(decipherStream, Charsets.UTF_8), 0xFFFF)\n return d.readLine()\n}\n</code></pre>\n\n<p>Edit:</p>\n\n<p>I was thinking what you could cache and only possible variable is I guess cipher:</p>\n\n<p><code>val cipher = Cipher.getInstance(\"AES/CFB/PKCS7Padding\")</code></p>\n\n<p>It probably won't speed up performance as I expect it to be cached factory method, but you can try putting variable outside of function anyway :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-09T11:30:55.693",
"Id": "233678",
"ParentId": "232805",
"Score": "1"
}
},
{
"body": "<p>Let's take a look line per line.</p>\n\n<pre><code>var payloadArray: List<Byte>? = this.readBytes().toList()\n</code></pre>\n\n<p>That's a really terrible idea. Generally you stream files using <code>FileInputStream</code>, or you can <em>map</em> files using the NIO (new I/O) interface of Java. Then you can read the bytes piecemeal.</p>\n\n<pre><code>val salt = payloadArray.sliceArray(0 until 32)\n</code></pre>\n\n<p>* Salts only have to be 128 bits maximum, 256 bits is complete overkill. You can slice or cut bytes from arrays just as well, or from a stream of course. No need for the salt and <code>realData</code> as <code>List</code>.</p>\n\n<pre><code>val cipher = Cipher.getInstance(\"AES/CFB/PKCS7Padding\")\n</code></pre>\n\n<p>* CFB mode with PKCS#7 doesn't make any sense; CFB is a streaming mode of operation, so padding the plaintext makes no sense whatsoever. Try <code>NoPadding</code> for future encryptions.</p>\n\n<pre><code>val secretKey: SecretKeySpec? = SecretKeySpec(keyBytes, \"AES\")\n</code></pre>\n\n<p>You expect <code>secretKey</code> to become <code>null</code>? </p>\n\n<pre><code>return d.readLine()\n</code></pre>\n\n<p>Wait, what? Single line string of 10 MB? Somebody needs to learn how to end lines I think. Generally such large strings are not useful, think of a way to split them up. Are you sure you need it all in one go? If not, keep it on disk.</p>\n\n<p><em>Note that it is perfectly possible to decrypt CFB ciphertext from on any position, as long as the starting position is a multiple of the block size (16 for AES) and the previous ciphertext block is known.</em></p>\n\n<hr>\n\n<p>The ones with the * are issues with the protocol, and those cannot be changed without re-encrypting the plaintext.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-14T19:03:28.750",
"Id": "234041",
"ParentId": "232805",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T15:31:16.083",
"Id": "232805",
"Score": "1",
"Tags": [
"android",
"cryptography",
"memory-optimization",
"kotlin",
"aes"
],
"Title": "Decrypt multiple 10Mb files with defined password"
}
|
232805
|
<p>How would you review this way of implementing a std::static_cast </p>
<pre><code>template <typename ToType, typename FromType>
ToType safe_static_cast( const FromType &from )
{
assert( from <= std::numeric_limits<ToType>::max() );
assert( from >= std::numeric_limits<ToType>::min() );
return static_cast<ToType>(from);
}
</code></pre>
<p>Is assertions on the limits a good way?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T15:47:46.513",
"Id": "454780",
"Score": "4",
"body": "The `assert()` don't do anything in production. So there is no actual checking here. So all you are doing is removing a compiler warning. Sure if that's what you want but best option is to make sure you are suing the correct types."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T16:50:57.883",
"Id": "454791",
"Score": "1",
"body": "While this is a very interesting question, it might be considered off-topic because it is hypothetical in nature, or a little to general."
}
] |
[
{
"body": "<p>This is a very interesting question.</p>\n\n<p>First, I would reconsider the name. <code>safe_static_cast</code> implies that it is more general than it is. The types must have <code>std::numeric_limits</code> specializations in your implementation, so clearly you are thinking of numeric types. Maybe <code>safe_numeric_cast</code> or even <code>numeric_cast</code> would be a better name.</p>\n\n<p>Secondly, <code>assert</code> is too often compiled out, so I would ask to consider alternatives which aren't. One alternative is throwing <code>std::out_of_range</code>. Another alternative is to saturate the destination type: if the source value is larger than the largest destination value, return the largest destination value.</p>\n\n<p>Consider <code>FromType</code> = <code>int</code>, <code>from</code> = <code>-1</code>, <code>ToType</code> = <code>unsigned int</code>. Note that <code>-1 >= 0u</code> is <code>true</code>.</p>\n\n<p>Consider the range of floating point types: <code>min()</code> is the lowest <strong>positive</strong> floating point value.</p>\n\n<p>Consider floating point infinities: <code>numeric_cast<double, double></code> should always be fine, right? But the comparison will fail for infinity.</p>\n\n<p>Consider floating point nans: similarly, all comparisons fail for nans.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T17:12:52.043",
"Id": "232814",
"ParentId": "232806",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "232814",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T15:40:37.380",
"Id": "232806",
"Score": "0",
"Tags": [
"c++"
],
"Title": "Safe static_cast in C++ in a codebase"
}
|
232806
|
<p>I have the following code for reading a json file into pandas dataframe and parsing the fields, but it is too slow for large files. Is there a way to make the code more efficient?</p>
<pre><code>def extract_text(json_train_path):
with open(json_train_path, 'r') as json_file:
train = {'example_id':[],
'question':[],
'text':[],
'long_answer':[],
'long_answer_text':[],
'short_answer':[],
'short_answer_text':[],
'yes_no_answer':[]}
# extract files
for line in tqdm(json_file):
data = json.loads(line)
example_id = str(data['example_id'])
question = data['question_text']
# clean text
text = data['document_text']
text = BeautifulSoup(text, "lxml").text
#text = text.lower()
long_start = data['annotations'][0]['long_answer']['start_token']
long_end = data['annotations'][0]['long_answer']['end_token']
long_answer_text = text.split(' ')[long_start:long_end]
long_answer_text = ' '.join(long_answer_text)
yes_no_answer = data['annotations'][0]['yes_no_answer']
if yes_no_answer == 'NONE':
yes_no_answer = ''
if data['annotations'][0]['short_answers']:
short_start = data['annotations'][0]['short_answers'][0]['start_token']
short_end = data['annotations'][0]['short_answers'][0]['end_token']
short_answer = (f'{short_start}:{short_end}')
short_answer_text = text.split(' ')[short_start:short_end]
short_answer_text = ' '.join(short_answer_text)
else:
short_start = ''
short_end = ''
short_answer_text = ''
short_answer = ''
# construct the DataFrame
train['example_id'].append(example_id)
train['question'].append(question)
train['text'].append(text)
train['long_answer'].append(f'{long_start}:{long_end}')
train['long_answer_text'].append(long_answer_text)
train['short_answer'].append(short_answer)
train['short_answer_text'].append(short_answer_text)
train['yes_no_answer'].append(yes_no_answer)
return train
</code></pre>
<p>This is an example of a line of json being parsed</p>
<pre><code>document_text long_answer_candidates question_text annotations document_url example_id
0 Email marketing - Wikipedia <H1> Email marketi... [{'start_token': 14, 'top_level': True, 'end_t... which is the most common use of opt-in e-mail ... [{'yes_no_answer': 'NONE', 'long_answer': {'st... https://en.wikipedia.org//w/index.php?title=Em... 5655493461695504401
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T16:44:39.050",
"Id": "454789",
"Score": "3",
"body": "The posted sample does not look valid. Post a testable valid fragment that comes to `data = json.loads(line)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T19:15:39.733",
"Id": "455036",
"Score": "0",
"body": "Also, how large is large? Is your JSON file GBs, TBs?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T17:13:27.283",
"Id": "455139",
"Score": "1",
"body": "@Graipher It is about 5 GB"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T15:44:38.427",
"Id": "232807",
"Score": "1",
"Tags": [
"python",
"pandas"
],
"Title": "Parsing large JSON files"
}
|
232807
|
<p>I'm writing a Scheme interpreter in Rust, and the first step is the parser. I've finished the lexer, and would like to see what people think of it before I go any further.</p>
<pre class="lang-rust prettyprint-override"><code>#[derive(Debug, PartialEq)]
enum LexToken {
Num(f64),
Symbol(String),
String(String),
LeftBracket,
RightBracket,
}
fn lex_input(input: &str) -> Result<Vec<LexToken>, &'static str> {
let mut output = Vec::new();
let input_length = input.len();
let mut current_idx = 0;
while current_idx < input_length {
if let Some((lexed_string, new_idx)) = lex_string(&input, current_idx) {
output.push(lexed_string);
current_idx = new_idx;
continue;
}
if let Some((lexed_number, new_idx)) = lex_number(&input, current_idx) {
output.push(lexed_number);
current_idx = new_idx;
continue;
}
if let Some((lexed_left_bracket, new_idx)) = lex_left_bracket(&input, current_idx) {
output.push(lexed_left_bracket);
current_idx = new_idx;
continue;
}
if let Some((lexed_right_bracket, new_idx)) = lex_right_bracket(&input, current_idx) {
output.push(lexed_right_bracket);
current_idx = new_idx;
continue;
}
if let Some(new_idx) = lex_whitespace(&input, current_idx) {
current_idx = new_idx;
continue;
}
if let Some((lexed_symbol, new_idx)) = lex_symbol(&input, current_idx) {
output.push(lexed_symbol);
current_idx = new_idx;
continue;
}
}
Ok(output)
}
fn lex_string(input: &str, from_idx: usize) -> Option<(LexToken, usize)> {
if input
.chars()
.nth(from_idx)
.expect("Lexxer skipped past the end of the input")
!= '"'
{
return None;
}
let output = input
.chars()
.skip(from_idx + 1)
.take_while(|&char| char != '"')
.collect::<String>();
Some((
LexToken::String(output.to_string()),
from_idx + output.len() + 2,
))
}
fn lex_left_bracket(input: &str, from_idx: usize) -> Option<(LexToken, usize)> {
if input
.chars()
.nth(from_idx)
.expect("Lexxer skipped past the end of the input")
!= '('
{
return None;
}
Some((LexToken::LeftBracket, from_idx + 1))
}
fn lex_right_bracket(input: &str, from_idx: usize) -> Option<(LexToken, usize)> {
if input
.chars()
.nth(from_idx)
.expect("Lexxer skipped past the end of the input")
!= ')'
{
return None;
}
Some((LexToken::RightBracket, from_idx + 1))
}
fn lex_whitespace(input: &str, from_idx: usize) -> Option<usize> {
if input
.chars()
.nth(from_idx)
.expect("Lexxer skipped past the end of the input")
.is_whitespace()
{
return Some(from_idx + 1);
}
None
}
fn lex_number(input: &str, from_idx: usize) -> Option<(LexToken, usize)> {
let next_char = input
.chars()
.nth(from_idx)
.expect("Lexxer skipped past the end of the input");
if !next_char.is_numeric() && next_char != '-' && next_char != '.' {
return None;
}
let num_as_string = input
.chars()
.skip(from_idx)
.take_while(|&char| char.is_numeric() || char == '.' || char == 'e' || char == '-')
.collect::<String>();
match num_as_string.parse::<f64>() {
Ok(num) => Some((LexToken::Num(num), from_idx + num_as_string.len())),
Err(_) => None,
}
}
fn lex_symbol(input: &str, from_idx: usize) -> Option<(LexToken, usize)> {
let output = input
.chars()
.skip(from_idx)
.take_while(|&char| !char.is_whitespace() && char != '(' && char != ')')
.collect::<String>();
Some((
LexToken::Symbol(output.to_string()),
from_idx + output.len(),
))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lex_brackets() {
let input = "()";
let expected_output = vec![LexToken::LeftBracket, LexToken::RightBracket];
compare(input, expected_output);
}
#[test]
fn lex_string() {
let input = "\"scheme\"";
let expected_output = vec![LexToken::String("scheme".to_string())];
compare(input, expected_output);
}
#[test]
fn lex_list_of_strings() {
let input = "(\"little\" \"scheme\")";
let expected_output = vec![
LexToken::LeftBracket,
LexToken::String("little".to_string()),
LexToken::String("scheme".to_string()),
LexToken::RightBracket,
];
compare(input, expected_output);
}
#[test]
fn lex_list_of_strings_with_whitespace() {
let input = " ( \"little\" \"scheme\" ) ";
let expected_output = vec![
LexToken::LeftBracket,
LexToken::String("little".to_string()),
LexToken::String("scheme".to_string()),
LexToken::RightBracket,
];
compare(input, expected_output);
}
#[test]
fn lex_number() {
let tests = vec![
("123", LexToken::Num(123f64)),
("0.123", LexToken::Num(0.123f64)),
("-0.1e-5", LexToken::Num(-0.1e-5f64)),
];
for (input, expect) in tests {
compare(input, vec![expect]);
}
}
#[test]
fn lex_list_of_numbers() {
let input = "(123 0.123 -0.1e-5)";
let expected_output = vec![
LexToken::LeftBracket,
LexToken::Num(123f64),
LexToken::Num(0.123f64),
LexToken::Num(-0.1e-5f64),
LexToken::RightBracket,
];
compare(input, expected_output);
}
#[test]
fn lex_symbol() {
let tests = vec![
("some_func", LexToken::Symbol("some_func".to_string())),
("-", LexToken::Symbol("-".to_string())),
("e", LexToken::Symbol("e".to_string())),
];
for (input, expect) in tests {
compare(input, vec![expect]);
}
}
#[test]
fn lex_list_of_symbols() {
let input = "(somefunc #some_symbol -)";
let expected_output = vec![
LexToken::LeftBracket,
LexToken::Symbol("somefunc".to_string()),
LexToken::Symbol("#some_symbol".to_string()),
LexToken::Symbol("-".to_string()),
LexToken::RightBracket,
];
compare(input, expected_output);
}
fn compare(input: &str, expected_output: Vec<LexToken>) {
let actual_output = lex_input(input).unwrap();
assert_eq!(actual_output, expected_output);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T18:18:00.367",
"Id": "454830",
"Score": "0",
"body": "Recommend using raw string literals to avoid so much manual escaping https://doc.rust-lang.org/reference/tokens.html#raw-string-literals"
}
] |
[
{
"body": "<p>You have several variations on this in your code:</p>\n\n<pre><code> if input\n .chars()\n .nth(from_idx)\n .expect(\"Lexxer skipped past the end of the input\")\n != '\"'\n {\n return None;\n }\n</code></pre>\n\n<p>This is problematic. In general, taking <code>nth</code> item in an iterator isn't going to be very efficient, since it has to iterate through all the previous elements in the iterator to get there. Some iterators may override this with a fast implementation, but <code>str.chars()</code> because the string is UTF-8 which has variable length characters. So it has to read through the string counting up the characters. Because you do this in a loop, you are going through the input string over and over and over again.</p>\n\n<p>A possible alternative is to pass around a mutable reference to the <code>std::char::Chars</code> object returned by <code>str.chars()</code>. Then you can have each lexing function move the iterator forward as it consume characters. This approach can be helped by using <code>.peekable()</code> to create an iterator with a <code>peek()</code> method that lets you look at the next item in the iterator without consuming it. Also, you can <code>clone()</code> this iterator to remember a particular position in the string, and assign to an iterator to reset it to a previous position.</p>\n\n<p>But what I'd actually do is define a struct, something like</p>\n\n<pre><code>struct Reader {\n currentLine: u32,\n currentColumn: u32,\n buffer: String,\n source: std::io::Read\n}\n</code></pre>\n\n<p>This struct:</p>\n\n<ol>\n<li>Reads from a std::io::Read, so it can be used with files/in memory data/whatever.</li>\n<li>Keeps track of the current line and column, probably quite useful for reporting errors.</li>\n<li>Provides utility functions to peek/consume data from the stream in a way conducive to implementing the lexer.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T01:14:23.677",
"Id": "233246",
"ParentId": "232808",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "233246",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T15:50:44.987",
"Id": "232808",
"Score": "2",
"Tags": [
"rust",
"scheme",
"lexer"
],
"Title": "Lex Scheme in Rust"
}
|
232808
|
<p>Recently I started looking and refreshing about algorithms and decided to try to do the 3 sum algorithm. I did the code below:</p>
<pre><code>public static int[] tripletSum(int[] A, int sum) {
HashMap<Integer, Boolean> data = new HashMap<>();
for (int i = 0; i < A.length; i++) {
data.put(A[i], true);
}
int i = 0;
int j = 1;
while (i < A.length && j < A.length) {
Integer a = A[i];
Integer b = A[j];
Integer delta = sum - (a + b);
if (data.containsKey(delta) && a != delta && b != delta && (a + b + delta) == sum) {
int[] result = {a, b, delta};
return result;
}
i++;
j++;
}
return null;
}
</code></pre>
<p>I'd like opinions about if it is good logic, time complexity, improvements. Any tips and comments will be great. </p>
<p>The piece of code below:</p>
<pre><code>if (data.containsKey(remainder) && a != remainder && b != remainder && (a + b + remainder) == sum) {
</code></pre>
<p>is included to avoid to repeat values in a and b, and to guarantee the sum result as expected.</p>
<p>Thanks</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T17:05:58.760",
"Id": "454798",
"Score": "0",
"body": "This 3sum algorithm: https://en.wikipedia.org/wiki/3SUM ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T17:13:41.793",
"Id": "454802",
"Score": "0",
"body": "I hope yes. A long time ago in a technical interview asked me to create an algorithm used to find three values in an array where the sum equals a sum parameter, like [5,1,2,1,8] and the sum expected is 15, interact in the loop finding the values where the sum equals 15."
}
] |
[
{
"body": "<p>There is no reason to use <code>HashMap</code>, you are not using the bools anywhere. So I think You could just use <code>HashSet</code>. Which you don't need to feed in foreach, instead simply pass the integers as constructor parameter.</p>\n\n<pre><code>var set = new HashSet(A);\n</code></pre>\n\n<p>You don't have to compare both <code>i</code> and <code>j</code></p>\n\n<pre><code>i < A.length && j < A.length\n</code></pre>\n\n<p>if <code>j</code> is always one larger then <code>i</code>, just compare with <code>j</code>.</p>\n\n<p>This condition is always true:</p>\n\n<pre><code>(a + b + delta) == sum\n</code></pre>\n\n<p>since that is the way it was obtained in the first place:</p>\n\n<pre><code>Integer delta = sum - (a + b);\n</code></pre>\n\n<p>This:</p>\n\n<pre><code>int[] result = {a, b, delta};\nreturn result;\n</code></pre>\n\n<p>could be just</p>\n\n<pre><code>return {a, b, delta};\n</code></pre>\n\n<p>You are returning <code>null</code> where you claim to return <code>int[]</code>, not sure if that's correct.</p>\n\n<p>Anyway I think your implementation does not work as intended, because it only looks for sums of two consecutive and third anywhere. It fails for example on [5,1,2,1,8] looking for 15=5+2+8.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T17:01:32.033",
"Id": "454794",
"Score": "0",
"body": "Thanks @slepic, but I tried using the [5,1,2,1,8], and got the result 5 2 8. If I get the sum result expected less every 2 elements from the array, the result will be a key found in the Hash.\nFor example: If the array is [5,1,2,1,8] and looking to find three values inside where is the sum is equal to 15, when interacting in the loop I'll get the first and second element(A[0] and A[1]), 1 + 2 (array sorted) and 15 - 3 = 12. Is it 12 a key? not.\nNow we'll interact again, and so on :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T17:04:30.223",
"Id": "454797",
"Score": "0",
"body": "@EdsonMartins hehe ok I guess I will have to actually run it :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T17:14:28.343",
"Id": "454803",
"Score": "0",
"body": "Thanks again @slepic, I changed to HashSet, the loop with j variable, etc Perfectly heheh."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T17:22:23.740",
"Id": "454806",
"Score": "0",
"body": "@EdsonMartins well, first I realized this is not C# as I thought :D But nevertheless with only few little changes it works in C# too :) Anyway it does not find solution for [5,1,2,1,8]=15, but it finds it for [5,1,2,8]=15. And going through the code logicaly leads me to conclusion that this should be the case in java as well, as I already wrote in my answer. I understand how you implemented it and that exactly makes me think it should not find solution [5,1,2,1,8]=15. No idea how it did, unless you changed the code already.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T17:25:06.893",
"Id": "454808",
"Score": "0",
"body": "@EdsonMartins cause 15-(5+1)=9 -> not in the set; 15-(1+2)=12 -> not in the set; 15-(2+1)=12 -> not in the set; 15-(1+8)=6 -> not in the set; the end."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T17:28:02.893",
"Id": "454810",
"Score": "0",
"body": "strange, but it's working in my idea. This is a Java code.\nThe initial logic, I'm sorting first and then calling the method.\nThe code is:\nint[] arr = {5,1,2,1,8};\n \n Arrays.sort(arr);\n int[] values = tripletSum(arr, 15);"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T17:28:41.453",
"Id": "454811",
"Score": "0",
"body": "Another point, I changed the code only to use HashSet.\nHashSet<Integer> data = new HashSet<>();\n \n for (int i = 0; i < A.length; i++) {\n data.add(A[i]);\n }\n \n int i = 0;\n int j = 1;"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T17:29:34.333",
"Id": "454812",
"Score": "0",
"body": "I didn't try to use the method addAll because I need to rewrite the logic used to find the delta, instead of using the array like A[index]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T17:29:43.470",
"Id": "454814",
"Score": "0",
"body": "Hmm but then of course it works, because if it is sorted then it is different sequence and I intentionaly picked one that will fail and you changed it :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T17:31:06.673",
"Id": "454815",
"Score": "0",
"body": "wow. I see :-D. Yes, I sorted first"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T17:31:52.200",
"Id": "454816",
"Score": "0",
"body": "maybe now is a good challenge to modify and use logic without sort method :-D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T17:32:39.790",
"Id": "454817",
"Score": "0",
"body": "But then your implementation only works because you sort first. I think you can still find a sequence that will fail even sorted, though it is hard to think of one... Anyway in that case the sort is basicaly part of your algorithm and as such increases time complexity of the implementation. And not by a small amount."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T17:34:14.700",
"Id": "454819",
"Score": "0",
"body": "@EdsonMartins Yeah, definitely look on the wikipedia linked in comments under your question. That looks like something I could have imagined as natural way to solve it..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T17:34:29.490",
"Id": "454820",
"Score": "0",
"body": "I hope if asking the interviewer about how the data will come (sorted or not). If sorted my algorithm will work, right? :-D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T17:36:27.503",
"Id": "454821",
"Score": "0",
"body": "I'll take a look again the wiki. Cheers"
}
],
"meta_data": {
"CommentCount": "15",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T16:54:25.900",
"Id": "232813",
"ParentId": "232809",
"Score": "1"
}
},
{
"body": "<p>According to the comment by @konijn and your answer to his comment below your question you tried to implement a variant of the algorithm <a href=\"https://en.wikipedia.org/wiki/3SUM\" rel=\"nofollow noreferrer\">3SUM</a> but your implementation is <strong>totally wrong</strong>.</p>\n\n<p>Let's start again: given an array and a value k you want to find three elements a, b, c in the array that satisfy the condition a + b + c = k. To obtain a complexity of O(n2) you have to use an hashtable to store values already checked in the array so if you have a and b and the hashtable contains the value c = k - (a + b) the algorithm ends. In this case instead of an hashtable I will use an <code>hashset</code> like I explain later.\nThe initial implementation of your method will be like this:</p>\n\n<pre><code>public static int[] tripletSum(int[] arr, int k) { \n final int n = arr.length;\n\n if (n < 3) { return null; }\n\n int[] numbers = Arrays.copyOf(arr, n);\n Arrays.sort(numbers);\n ...omitted\n}\n</code></pre>\n\n<p>You have chosen to return the triplet (a, b, c) if a + b + c = k, otherwise you return the <code>null</code> triplet if the length of the array if less than 3 or none triplet (a, b, c) satisfies the sum condition a + b + c = k.\nNow add the logic of algorithm to the body of method like below:</p>\n\n<pre><code>public static int[] tripletSum(int[] arr, int k) { \n final int n = arr.length;\n\n if (n < 3) { return null; }\n\n int[] numbers = Arrays.copyOf(arr, n);\n Arrays.sort(numbers);\n\n for (int i = 0; i < n - 1; ++i) {\n if (i > 0 && numbers[i] == numbers[i - 1]) { continue; } \n Set<Integer> set = new HashSet<>();\n int a = numbers[i];\n for (int j = i + 1; j < n; ++j) {\n int b = numbers[j];\n int c = k - (a + b);\n if (set.contains(c)) {\n return new int[] {a, b, c};\n }\n set.add(b);\n }\n }\n return null;\n}\n</code></pre>\n\n<p>I made a copy of the original array and sorted it so all duplicate numbers are consecutive : in this way in the loop once for a number a the there are no b and c that satisfy the condition a + b + c = k, the loop ignore all equal numbers to n with instruction <code>continue</code>. </p>\n\n<p>I use the <code>HashSet</code> to store the c values, so in every cycle of the loop I have a and b and I check if the hashset contains the value c = k - (a + b). If yes, the function returns the triplet (a, b, c) otherwise the value b is stored in the hashset if not already present as a c value for next iterations.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T12:03:21.160",
"Id": "232939",
"ParentId": "232809",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "232939",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T16:11:05.417",
"Id": "232809",
"Score": "1",
"Tags": [
"java",
"algorithm",
"mathematics"
],
"Title": "3 sum algorithm - Trying"
}
|
232809
|
<p>I was wondering if anyone could make any suggestions to how I could write the following more concisely and reduce the number of IF statements? If possible, I would also like to simultaneously assign values to variables and calculate the score.</p>
<p>I will eventually have multiple rule sets and formula scores for other question sets.</p>
<pre class="lang-py prettyprint-override"><code># q001 is multiple choice with three choices - q001_a01, q001_a02 & q001_a03 - only one selection can be made
# q002 is the first part of a two part question. It has two options = q002_a01 & q002_a02 - again, only one selection can be made
# q003 is only answered if q002_a01 is selected in q002 and also has two choices - q003_a01 & q003_a02
# q004 is a multiple choice question with 5 options - q004_a01, q004_a02, q004_a03, q004_a04 & q004_a05 - multiple selections can be made, q004_a05 answer is 'none of the above'
# q005 is a simple Yes/No (True/False) question
# q006 is multiple choice with three choices - q006_a01, q006_a02, q006_a03 & q006_a004 - only one selection can be made
# q007 is multiple choice with three choices - q007_a01, q007_a02 & q007_a03 - only one selection can be made
# q008 requires an input of an integer from 1-5
# all questions require a response (except q003)
# dictionary containing question and answer codes for a single individuals response
data = {'q001': 'q001_a01',
'q002': 'q002_a01',
'q003': 'q003_a02',
'q004': ['q004_a01', 'q004_a02', 'q004_a04'],
'q005': False,
'q006': 'q006_a03',
'q007': 'q007_a01',
'q008': 3}
# rules which define the values of the different variables
var1 = 2 if 'q001_a01' in data['q001'] else 0
var1 = 5 if 'q001_a02' in data['q001'] or 'q001_a03' in data['q001'] else var1
var2 = -2 if 'q002_a01' in data['q002'] and 'q003_a01' in data['q003'] else 0
var2 = 2 if 'q002_a01' in data['q002'] and 'q003_a02' in data['q003'] else var2
var3 = 2 if 'q004_a01' in data['q004'] else 0
var3 = var3 + 2 if 'q004_a02' in data['q004'] else var3
var3 = var3 - 1 if 'q004_a03' in data['q004'] else var3
var3 = var3 + 1 if 'q004_a04' in data['q004'] else var3
var3 = 5 if 'q004_a05' in data['q004'] else var3
var4 = 4 if True is data['q005'] else 0
var5 = 1 if 'q006_a01' in data['q006'] else 0
var5 = 2 if 'q006_a02' in data['q006'] else var5
var5 = -10 if 'q006_a03' in data['q006'] else var5
var5 = -2 if 'q006_a04' in data['q006'] else var5
var6 = 2 if 'q007_a01' in data['q007'] else 0
var6 = 1 if 'q007_a02' in data['q007'] or 'q007_a03' in data['q007'] else var6
var7 = data['q008']
# formula to calculate score from variables
score = var1 + var2 + var3 + var4 + ((var5 + var6) * var7)
</code></pre>
<p>I would like to make the code as neat and fast as possible.<br>
Also, could someone point me towards some python literature which would help me improve this myself?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T16:53:32.607",
"Id": "454792",
"Score": "0",
"body": "Can you share the *prototype* (origin) of that formula? where did you get the idea?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T17:01:59.257",
"Id": "454796",
"Score": "0",
"body": "The rules don't really seem to have much consistency that could be taken advantage of. I think the best you could do is construct some structure that holds the different data associated with each var, then iterate over it. That would still be difficult though as they \"q\" key strings aren't entirely consistent either."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T17:22:13.830",
"Id": "454805",
"Score": "0",
"body": "@Carcigenicate I will try and construct some structure as there is only a finite number of different question types (single answer from a list, multiple selection from a list, Yes/No or True/False, input a numerical value)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T17:27:46.560",
"Id": "454809",
"Score": "0",
"body": "@RomanPerekhrest unfortunately I cannot share the origin of that formula. However, the basic idea is that combined answers from specific sets of questions and according to the prescribed rules will be used to generate scores for different formulas which can then be used in downstream processes to help make some form of decision."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T17:40:30.793",
"Id": "454822",
"Score": "0",
"body": "Since nothing has descriptive names it's hard to discern the underlying logic. Is the idea that your `data` represents a sample \"test\" (with answers that may or may not be right), and the correct answers plus the scoring weights are encoded in the rest of the code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T17:53:04.670",
"Id": "454824",
"Score": "0",
"body": "Are answers expected to have a certain type (e.g. `str` vs `List` vs `bool`) based on the question, or could I (for example) pass a giant list of responses for `q002` since if I hit the right ones it'll override the negative score for all the wrong ones? The use of `in` for most of the checks implies that a list is acceptable input, but that doesn't match the data so I'm not sure if it's intentional or a coding error."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T17:55:56.650",
"Id": "454825",
"Score": "0",
"body": "@SamStafford I'm sorry if it is all a bit vague/unclear, there is only so much information I can divulge. The `data` represents the answers to a set of questions, there are no correct/incorrect answers but the combined answers given will be used to calculate a score which would then be used to make a decision downstream. For example another set of questions for an individual to answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T17:59:44.860",
"Id": "454826",
"Score": "0",
"body": "If the only information you can divulge about what you're trying to accomplish is the code itself it's not really possible to suggest a way to write it to better accomplish your intent. It *looks* like there might be some generalizable patterns in there for certain types of questions -- there are multiple-answer questions where the score is a weighted sum, and single-answer questions where each possible answer maps to a score, and it'd be possible to implement those patterns much more elegantly, but that implementation wouldn't be bug-for-bug compatible so with no \"spec\"... ¯\\_(ツ)_/¯"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T12:07:39.310",
"Id": "455087",
"Score": "0",
"body": "@SamStafford ok I can see how the question as it doesn't give enough info to really help too much. I will add more info regarding the questions to improve it."
}
] |
[
{
"body": "<p>Since everything in this code is defined statically rather than as a function input (and your comments indicate that there is no way to vary any part of how this code functions), there is no possibility allowed within the parameters of this question for the score to ever vary. You can therefore make this code significantly more concise and efficient by simply computing the score statically:</p>\n\n<pre><code>score = -15\n</code></pre>\n\n<p>This will produce the same score result as your original code with a significantly smaller footprint.</p>\n\n<p>If this doesn't seem right, the question to ask yourself (and then answer for the benefit of your code reviewers) is: which constants in this code can vary, and what types/values are permissible for them?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T18:06:11.913",
"Id": "232819",
"ParentId": "232811",
"Score": "4"
}
},
{
"body": "<h3>Restructuring and optimization</h3>\n\n<p>The initial approach is totally relies on <em>if-else ternary</em> conditions, supposedly attempting to make the code compact.<br> But in this case it was overused and comes to negative effects in readability and redundant reassignment to the same variable multiple times (all those numerous <code>var = ... else var</code>)</p>\n\n<p>One subtle detail that might be unnoticed at 1st glance is that all conditions for variables <strong><code>var1</code></strong>, <strong><code>var2</code></strong>, <strong><code>var3</code></strong>(partially), <strong><code>var5</code></strong> and <strong><code>var6</code></strong> are checked with <em>precedence</em> in relation to the final value assigned to a related variable.<br>Let's look at the sequence of conditions for <strong><code>var5</code></strong>:</p>\n\n<pre><code>var5 = 1 if 'q006_a01' in data['q006'] else 0\nvar5 = 2 if 'q006_a02' in data['q006'] else var5\nvar5 = -10 if 'q006_a03' in data['q006'] else var5\nvar5 = -2 if 'q006_a04' in data['q006'] else var5\n</code></pre>\n\n<p>if <code>'q006_a04' in data['q006']</code> is <em>truthy</em> then <code>var5</code> is just assigned with <code>-2</code> and <strong>all</strong> previous conditions become redundant. The same applies for other variables mentioned above. <br>That means that the optimal way is to build the conditional flow in <em>\"upstream\"</em> manner (basing on precedence).</p>\n\n<p>The intermediate optimizations include:</p>\n\n<ul>\n<li><p>all variables (except <code>var7</code>) is initialized at once:</p>\n\n<pre><code>var1 = var2 = var3 = var4 = var5 = var6 = 0\n</code></pre></li>\n<li><p><code>var2</code> block has a common condition <code>'q002_a01' in data['q002']</code>. <em>Consolidate conditional expression</em> technique is applied (see below)</p></li>\n<li><p><code>4 if True is data['q005'] else 0</code> is simply the same as <strong><code>4 if questionnaire['q005'] else 0</code></strong></p></li>\n</ul>\n\n<p>Considering the above conception and optimizations the restructured version is below (defined as <strong><code>calc_score</code></strong> function):</p>\n\n<pre><code>def calc_score(questionnaire):\n # rules which define the values of the different variables\n var1 = var2 = var3 = var4 = var5 = var6 = 0\n\n if 'q001_a02' in questionnaire['q001'] or 'q001_a03' in questionnaire['q001']:\n var1 = 5\n elif 'q001_a01' in questionnaire['q001']:\n var1 = 2\n\n if 'q002_a01' in questionnaire['q002']:\n if 'q003_a02' in questionnaire['q003']:\n var2 = 2\n elif 'q003_a01' in questionnaire['q003']:\n var2 = -2\n\n if 'q004_a05' in questionnaire['q004']:\n var3 = 5\n else:\n if 'q004_a01' in questionnaire['q004']:\n var3 = 2\n if 'q004_a02' in questionnaire['q004']:\n var3 += 2\n if 'q004_a03' in questionnaire['q004']:\n var3 -= 1\n if 'q004_a04' in questionnaire['q004']:\n var3 += 1\n\n var4 = 4 if questionnaire['q005'] else 0\n\n if 'q006_a04' in questionnaire['q006']:\n var5 = -2\n elif 'q006_a03' in questionnaire['q006']:\n var5 = -10\n elif 'q006_a02' in questionnaire['q006']:\n var5 = 2\n elif 'q006_a01' in questionnaire['q006']:\n var5 = 1\n\n if 'q007_a02' in questionnaire['q007'] or 'q007_a03' in questionnaire['q007']:\n var6 = 1\n elif 'q007_a01' in questionnaire['q007']:\n var6 = 2\n\n var7 = questionnaire['q008']\n\n # formula to calculate score from variables\n score = var1 + var2 + var3 + var4 + ((var5 + var6) * var7)\n return score\n\n\n# dictionary containing question and answer codes for an individual\ndata = {'q001': 'q001_a01',\n 'q002': 'q002_a01',\n 'q003': 'q003_a02',\n 'q004': ['q004_a01', 'q004_a02', 'q004_a04'],\n 'q005': False,\n 'q006': 'q006_a03',\n 'q007': 'q007_a01',\n 'q008': 3}\n\nprint(calc_score(data)) # -15\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T18:45:52.877",
"Id": "232822",
"ParentId": "232811",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T16:23:34.053",
"Id": "232811",
"Score": "2",
"Tags": [
"python",
"python-3.x"
],
"Title": "Assign values to answers from a questionnaire, input into a formula and calculate score"
}
|
232811
|
<p>Need to merge data per column if records in the first column are the same.</p>
<p>I wrote a VBA code and it works but it works very slow as it executes "merge" function per each row no matter if consequent cells are the same or different.</p>
<pre><code>Sub DuplicateValues()
'Declare All Variables:
Dim myCell As Range
Dim myRow As Integer
Dim myRange As Range
Dim myCol As Integer
Dim i As Integer
Dim k As Integer
Dim myFirstRow As Long
Dim myFirstColumn As Long
Dim rngCopy As Range, rngPaste As Range
'Count Number of Rows and Columns:
Application.DisplayAlerts = False
myRow = Range(Cells(3, 1), Cells(3, 1).End(xlDown)).Count + 2 'first two rows are headers
myCol = Range(Cells(2, 1), Cells(2, 1).End(xlToRight)).Count
'Apply formatting to the end of the table:
With ActiveSheet
Set rngCopy = .Range(.Range("A3"), .Cells(myRow, myCol))
With rngCopy.Borders
.LineStyle = xlContinuous
.ColorIndex = 0
.Weight = xlThin
End With
End With
'Merge duplicated cells per Row:
myFirstRow = 3
myFirstColumn = 1
Set iRow = Cells(myFirstRow, myFirstColumn)
Set n = Cells(myFirstRow + 1, myFirstColumn)
For i = 1 To myRow
If iRow <> n Then
Range(Cells(myFirstRow, 1), Cells(myFirstRow, myCol - 3)).HorizontalAlignment = xlCenter
Range(Cells(myFirstRow, 1), Cells(myFirstRow, myCol - 3)).VerticalAlignment = xlCenter
Range(Cells(myFirstRow, 8), Cells(myFirstRow, 8)).WrapText = True
Range(Cells(myFirstRow, 1), Cells(myFirstRow, myCol - 3)).EntireRow.AutoFit
iRow = Cells(myFirstRow + i, myFirstColumn)
n = Cells(myFirstRow + i + 1, myFirstColumn)
Else
n = Cells(myFirstRow + i + 1, myFirstColumn)
For k = 1 To myCol - 3 'need to merge data per column but don't need to merge data in the last 3 columns
Range(Cells(myFirstRow + i - 1, k), Cells(myFirstRow + i, k)).Merge
Range(Cells(myFirstRow + i - 1, k), Cells(myFirstRow + i, k)).HorizontalAlignment = xlCenter
Range(Cells(myFirstRow + i - 1, k), Cells(myFirstRow + i, k)).VerticalAlignment = xlCenter
Range(Cells(myFirstRow + i - 1, 8), Cells(myFirstRow + i, 8)).WrapText = True
Range(Cells(myFirstRow + i - 1, k), Cells(myFirstRow + i, k)).EntireRow.AutoFit
Next
End If
Next
End Sub
</code></pre>
<p>I tried to create a different logic to initiate "merge" by blocks (skip merging the same value cells in the first column right away):<br>
merging only when the "base/initial" cell is not the same as a "check" cell and merge all appropriate cells all together (not by each row), but I can't find a way to make it work.</p>
<p>Would be very grateful for any code optimizations!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T17:29:37.197",
"Id": "454813",
"Score": "0",
"body": "Unrelated for performance, but avoid using `With`, it just obfuscates code and makes it less readable."
}
] |
[
{
"body": "<blockquote>\n<pre><code>'Declare All Variables:\n\nDim myCell As Range\nDim myRow As Integer\nDim myRange As Range\nDim myCol As Integer\nDim i As Integer\nDim k As Integer\n\nDim myFirstRow As Long\nDim myFirstColumn As Long\n\nDim rngCopy As Range, rngPaste As Range\n</code></pre>\n</blockquote>\n\n<p>Don't do this. This procedure is somewhere between 2 and 3 screens high on my laptop: when I'm at the bottom of the procedure, I don't know what I'm looking at, so I scroll back up to this <em>wall of declarations</em>, parse the chunk of code, locate the variable I'm looking for, then scroll back down to where I was, ...and that gets very annoying, very fast.</p>\n\n<p>People defending this \"declare everything at the top of the procedure\" habit usually defend it pretty hard, and they're wrong. \"I can see everything that's used in the procedure at once\" sounds great on paper. Truth is, it only makes you scroll back and forth all the time for no reason, <em>and</em> makes it much harder than it should be, to know whether or not a variable is used, let alone <em>where</em> it's used.</p>\n\n<p>If you declare variables where you first assign them, as you need to introduce them, then you simply <em>can't</em> miss the fact that <code>myCell</code>, <code>myRange</code>, <code>rngPaste</code> are never assigned or referenced anywhere... and that <code>iRow</code> and <code>n</code> aren't declared at all. This is extremely bug-prone, you don't want to allow VBA code to run with undeclared variables. Fortunately you can completely prevent this, by simply specifying <code>Option Explicit</code> at the very top of every module you ever write any VBA code in.</p>\n\n<p>Proper indentation also helps, massively. It started well:</p>\n\n<pre><code>For i = 1 To myRow\n\n If iRow <> n Then\n</code></pre>\n\n<p>...and then suddenly went <em>way out there</em>:</p>\n\n<pre><code> Range(Cells(myFirstRow, 1), Cells(myFirstRow, myCol - 3)).HorizontalAlignment = xlCenter\n</code></pre>\n\n<p>...to seemingly random:</p>\n\n<pre><code> Else\n n = Cells(myFirstRow + i + 1, myFirstColumn)\n\n For k = 1 To myCol - 3 'need to merge data per column but don't need to merge data in the last 3 columns\n</code></pre>\n\n<p>Use an <a href=\"http://rubberduckvba.com/indentation\" rel=\"nofollow noreferrer\">indenter</a> if you're unsure how to keep indentation consistent.</p>\n\n<p>Row numbers should always be <code>As Long</code>. An <code>Integer</code> is a 16-bit signed integer type, so its maximum possible value is 32,767. This means as soon as your data involves row 32,768 and beyond, your code breaks with an \"Overflow\" run-time error. In fact, there's little to no reason at all to ever declare anything <code>As Integer</code> in 2019: processors are optimized to deal with 32-bit integer types, and that's a <code>Long</code> in VBA.</p>\n\n<p>I like this:</p>\n\n<blockquote>\n<pre><code>With ActiveSheet\n</code></pre>\n</blockquote>\n\n<p>I makes <code>ActiveSheet</code> references explicit, and that's very good.</p>\n\n<p>However you're <em>implicitly</em> referring to whatever the <code>ActiveSheet</code> is everywhere else outside this <code>With</code> block.</p>\n\n<blockquote>\n<pre><code>myRow = Range(Cells(3, 1), Cells(3, 1).End(xlDown)).Count + 2 'first two rows are headers\nmyCol = Range(Cells(2, 1), Cells(2, 1).End(xlToRight)).Count\n</code></pre>\n</blockquote>\n\n<p>Unqualified like this, <code>Range</code> and <code>Cells</code> are implicitly referring to the <code>ActiveSheet</code>: the <code>With ActiveSheet</code> block is therefore redundant, and makes accesses to that active sheet inconsistent: some are explicit, some are implicit - and that's very bug-prone.</p>\n\n<p>A note about this:</p>\n\n<pre><code>myRow = Range(Cells(3, 1), Cells(3, 1).End(xlDown)).Count + 2 'first two rows are headers\n</code></pre>\n\n<p>Looks like you're trying to get the last used row; this is not a reliable way to do it. Consider flipping the logic around and going <em>up</em> from the last row on the sheet to get the <code>.Row</code> of that specific cell, rather than the <code>Count</code> of cells in a range:</p>\n\n<pre><code>myRow = ws.Range(\"A\" & ws.Rows.Count).End(xlUp).Row\n</code></pre>\n\n<p>Note how the fist two rows being headers, doesn't matter any more.</p>\n\n<p>I'd strongly advise <em>against</em> using <code>my</code> as a prefix for anything, regardless of how often you see it in documentation. Same goes for <code>rng</code> and <code>o</code> and whatever other prefixing scheme you might read anywhere. Use meaningful names instead. \"myRow\" doesn't say what's important about it: it's the last row with data. <code>lastRow</code> would already be a much better name for it.</p>\n\n<p><code>rngCopy</code> is assigned, its borders are formatted, ...but it's not being <em>copied</em> anywhere. The name strongly suggests it's a <code>source</code>, especially since it's declared right next to the unused <code>rngPaste</code>, which strongly suggests that would be a <code>destination</code> for an operation involving the clipboard. Pretty misleading, since none of that is happening anywhere in the procedure.</p>\n\n<p>I already mentioned <code>n</code> isn't declared. Its usage is a problem.</p>\n\n<pre><code>Set n = Cells(myFirstRow + 1, myFirstColumn)\n</code></pre>\n\n<p>It's <code>Set</code>-assigned to a <code>Range</code>. Thus, its runtime type at that point is <code>Variant/Range</code>.</p>\n\n<pre><code>If iRow <> n Then\n</code></pre>\n\n<p>Now it's being compared to <code>iRow</code>, which is another undeclared <code>Variant/Range</code> variable, and the two objects are only comparable through implicit let-coercion involving hidden default member calls - making it all explicit would look like this:</p>\n\n<pre><code>If iRow.Value <> n.Value Then\n</code></pre>\n\n<p>And while that's now explicit, it's wrong. It's wrong, because they shouldn't be <code>Range</code> objects. They shouldn't be <code>Range</code> objects, because they're later being <code>Let</code>-assigned to plain values:</p>\n\n<pre><code> iRow = Cells(myFirstRow + i, myFirstColumn)\n n = Cells(myFirstRow + i + 1, myFirstColumn)\n</code></pre>\n\n<p>Beyond that point, the data type of <code>iRow</code> and <code>n</code> is up in the air. If you're lucky, you're looking at two <code>Variant/Double</code> values. Otherwise, you're looking at one or more <code>Variant/Error</code> values (that would be the case if the worksheet contains error values), and everything blows up with a <em>type mismatch</em> error.</p>\n\n<p>Not declaring variables is one thing, reusing variables is another, but reusing undeclared variables and assigning them a new runtime type, makes everything very hard to follow. Declare them with an explicit data type, and let them <em>be</em> values, instead of <em>objects that behave like values</em> thanks to implicit hidden code.</p>\n\n<p>As for performance, the reason it's slow is because it's doing the single slowest thing any code can do: interact with worksheet cells directly, in a loop.</p>\n\n<p>You can't help it, interacting with worksheet cells is <em>precisely</em> what this macro needs to do. All you <em>can</em> do is tell Excel to stop trying to keep up as you modify the worksheet.</p>\n\n<p>Every time a cell is modified, Excel evaluates whether a recalc is needed, and will perform it if it has to. Switch calculation to manual before you start manipulating the worksheet, and toggle it back to automatic when you're done: Excel will only recalculate once. That's <code>Application.Calculation</code> (set to <code>xlCalculationManual</code>, then back to <code>xlCalculationAutomatic</code> when you're ready).</p>\n\n<p>Every time a cell is modified, Excel fires worksheet events (e.g. <code>Worksheet.Change</code>), and if there's a handler procedure for that event, then that code will run before the next instruction does. Turn off application events before you start manipulating the worksheet, and toggle it back on when you're done: no worksheet events will be fired; that's <code>Application.EnableEvents</code> (set to <code>False</code>, then back to <code>True</code> when you're ready).</p>\n\n<p>Every time a cell is modified, Excel tries to repaint itself. While that's normally pretty fast, when you're modifying cells in a loop you don't want Excel to even try to keep up - you want to make your changes, and have Excel repaint itself when you're done. Do that by toggling <code>Application.ScreenUpdating</code> (set to <code>False</code>, then back to <code>True</code> when you're ready).</p>\n\n<p>Whenever you toggle this global <code>Application</code> state, make sure you handle runtime errors, and have your error-handling subroutine ensure that the global state gets properly reset whether the procedure succeeds or fails, whatever the reason for failing might be.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T20:46:26.393",
"Id": "454841",
"Score": "0",
"body": "Thanks for the detailed explanations on my errors, I just started writing codes on VBA and this is very helpful! Regarding performance, don't you think that if other logic was used, like merging only duplicated cells that are following each other (skipping merging every row) would increase the speed? I just don't know how to make it works that way..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T21:11:04.913",
"Id": "454844",
"Score": "0",
"body": "It probably would, but I'm pretty sure the overhead of Excel recalculating and redrawing stuff *every time* dwarfs any algorithmic tweaks - best do *both* (turn off recalcs & repaints *and* review the algorithm)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T21:13:50.090",
"Id": "454845",
"Score": "0",
"body": "Another question is about `myRow = ws.Range(\"A\" & ws.Rows.Count).End(xlUp).Row` that's a great way of getting the last row but I'm now getting an error: Object variable or With block variable not set"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T21:14:11.217",
"Id": "454846",
"Score": "0",
"body": "Is `ws` defined? I only put it there to emphasize that `Range` is a member call that needs to be qualified with a proper `Worksheet` object."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T21:19:58.447",
"Id": "454848",
"Score": "0",
"body": "Yes, I defined `ws`: `Dim ws As Worksheet`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T21:20:26.627",
"Id": "454849",
"Score": "0",
"body": "And it's `Set`-assigned? ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T21:28:42.400",
"Id": "454851",
"Score": "0",
"body": "If I do it `Set`-assigned, I'm getting another error: Object required. Also, after I changed my code using your suggestions, it doesn't perform as it used to, maybe because I didn't assign `n` and `iRow` correctly (I assigned them `As Objects`).."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T21:32:06.840",
"Id": "454853",
"Score": "0",
"body": "Not sure what state your code is in now... [Rubberduck](http://rubberduckvba.com) should help you clean everything up (confession: I used it to clean up the indentation, identify unused variables, and other issues; full disclaimer: I manage this VBIDE add-in open-source project). `n` and `iRow` need to be `Long` integers, not objects,"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T21:39:58.787",
"Id": "454855",
"Score": "0",
"body": "I tried assigning `Long` before but I got the same error: Object required but now for the first row with `iRow`. I've already cleaned the indentation but overall can't really figure out why the code doesn't work anymore after just making a couple of alterations you suggested. I feel that in order to have the code aligned with the suggestions above I have to re-write/update lots of other things as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T21:43:49.893",
"Id": "454856",
"Score": "0",
"body": "You'd get \"Object Required\" with a `Long` on the instructions where you're trying to `Set`-assign it. The changes I've suggested can't really be cherry-picked, it's all or none :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T22:02:10.297",
"Id": "454860",
"Score": "0",
"body": "Yep, that worked, thanks. I will try to figure out why I can't merge rows per column, something wrong with the loop `For k = 1 To myCol - 3` now"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T19:06:05.203",
"Id": "232824",
"ParentId": "232815",
"Score": "4"
}
},
{
"body": "<blockquote>\n <p>I tried to create a different logic to initiate \"merge\" by blocks (skip merging the same value cells in the first column right away):</p>\n</blockquote>\n\n<p>The best way to do this is count the number of duplicates and then define your range as <code>current row to (current row - (number of duplicates + 1))</code> (note: you add 1 because the original value is not a duplicate).</p>\n\n<blockquote>\n<pre><code>Range(Cells(i - (countDups + 1), k), Cells(i, k))\n</code></pre>\n</blockquote>\n\n<p>Hard coded values that may change in the future are called Magic Numbers. Replacing these values with an enumeration or constants will make you code easier to read and modify.</p>\n\n<p>For example the number 3 appears appears 4 times in code. Each occurrence is being used to determine the number of columns to exclude. If you later decide that you only need to exclude a 2 columns, you could just change all the 3's to 2. No problem, ease pease. So let's say we did that but decided to we did indeed need the to exclude the 3rd column, no problem just replace the 2's with 3's. But wait there are 2 header rows, now there is a problem.</p>\n\n<p>Before</p>\n\n<blockquote>\n<pre><code>Cells(myFirstRow, myCol - 3)\n</code></pre>\n</blockquote>\n\n<p>After</p>\n\n<blockquote>\n<pre><code>Cells(myFirstRow, myCol - ColumnOffset)\n</code></pre>\n</blockquote>\n\n<p>Anything that is in going to happen <code>If</code> or <code>Else</code> does not belong in an <code>If</code> statement.</p>\n\n<pre><code>If iRow <> n Then\n\n Range(Cells(myFirstRow, 1), Cells(myFirstRow, myCol - 3)).HorizontalAlignment = xlCenter\n Range(Cells(myFirstRow, 1), Cells(myFirstRow, myCol - 3)).VerticalAlignment = xlCenter\n Range(Cells(myFirstRow, 8), Cells(myFirstRow, 8)).WrapText = True\n Range(Cells(myFirstRow, 1), Cells(myFirstRow, myCol - 3)).EntireRow.AutoFit\n\n iRow = Cells(myFirstRow + i, myFirstColumn)\n n = Cells(myFirstRow + i + 1, myFirstColumn)\n\nElse\n n = Cells(myFirstRow + i + 1, myFirstColumn)\n\n For k = 1 To myCol - 3 'need to merge data per column but don't need to merge data in the last 3 columns\n\n Range(Cells(myFirstRow + i - 1, k), Cells(myFirstRow + i, k)).Merge\n Range(Cells(myFirstRow + i - 1, k), Cells(myFirstRow + i, k)).HorizontalAlignment = xlCenter\n Range(Cells(myFirstRow + i - 1, k), Cells(myFirstRow + i, k)).VerticalAlignment = xlCenter\n Range(Cells(myFirstRow + i - 1, 8), Cells(myFirstRow + i, 8)).WrapText = True\n Range(Cells(myFirstRow + i - 1, k), Cells(myFirstRow + i, k)).EntireRow.AutoFit\n\n Next\n\nEnd If\n</code></pre>\n\n<p>The <code>k</code> loop is disguising the fact that the <code>HorizontalAlignment</code>, <code>VerticalAlignment</code> and row height are being adjusted whether <code>iRow <> n</code> or not. Knowing this we can move these operations outside the scope of the <code>If</code> statement. This will make it much easier to focus on the <code>if...Else</code> logic.</p>\n\n<blockquote>\n<pre><code>If iRow <> n Then\n iRow = Cells(myFirstRow + i, myFirstColumn)\nElse\n For k = 1 To myCol - 3\n Range(Cells(myFirstRow + i - 1, k), Cells(myFirstRow + i, k)).Merge\n Next\nEnd If\n\nn = Cells(myFirstRow + i + 1, myFirstColumn)\nRange(Cells(myFirstRow, 8), Cells(myFirstRow, 8)).WrapText = True\nWith Range(Cells(myFirstRow, 1), Cells(myFirstRow, myCol - 3))\n .HorizontalAlignment = xlCenter\n .VerticalAlignment = xlCenter\n .EntireRow.AutoFit\nEnd With\n</code></pre>\n</blockquote>\n\n<p>If we think about it a little deeper, these formats are being applied to all cells in our target area. The formatting isn't even essential to merging the cells, which is what we are really trying to do. So we could simply pass the area to be formatted to another subroutine (see code below). This will simplify the main code and make it much easier to focus on the task at hand.</p>\n\n<h2>Refactored Code</h2>\n\n<pre><code>Sub MergeDuplicateValues()\n Const DebugMode As Boolean = True\n\n Dim Target As Range\n Dim ws As Worksheet\n\n Set ws = ThisWorkbook.Worksheets(\"Data\")\n\n If DebugMode Then\n Rem Close previous test workbook\n CloseTestWorkbooks\n Rem Copy the worksheet to a new workbook\n ws.Copy\n Set ws = ActiveSheet\n End If\n\n Rem Define the Target Range\n Set Target = getMergeRange(ws.Range(\"A1\"))\n Rem Add breakpoint here and use Target.Select in the Immediate Window to test the range\n\n If Target Is Nothing Then Exit Sub\n\n Application.ScreenUpdating = False\n MergeDuplicates Target\n ApplyBorders Target.CurrentRegion\n ApplyFormatsToMergeArea Target\n\nEnd Sub\n\nPrivate Sub MergeDuplicates(Target As Range)\n Application.DisplayAlerts = False\n Dim r As Long, countDups As Long\n\n With Target\n For r = 1 To .Rows.Count\n If .Cells(r, 1).Value = .Cells(r + 1, 1).Value Then\n countDups = countDups + 1\n Else\n If Count > 0 Then\n Dim Column As Range\n\n Rem Iterate over each column of the Target Range\n For Each Column In .Columns\n Dim section As Range\n Set section = Column.Cells(r - countDups, 1).Resize(countDups + 1)\n\n Rem Add breakpoint here and use section.Select in the Immediate Window to test the range\n section.Merge\n Next\n Count = 0\n End If\n End If\n Next\n End With\n Application.DisplayAlerts = True\nEnd Sub\n\nPrivate Function getMergeRange(Target As Range) As Range\n Const LastColumnOffset As Long = -3\n Const FirstRowOffset As Long = 2\n\n Dim newTarget As Range\n With Target.CurrentRegion\n\n Rem An error handler is needed when setting a range using negative offsets\n On Error Resume Next\n\n Rem Define the actual Target range\n Set newTarget = .Offset(FirstRowOffset).Resize(.Rows.Count - FirstRowOffset, .Columns.Count + LastColumnOffset)\n\n Rem Add breakpoint here and use newTarget.Select in the Immediate Window to test the range\n\n If Err.Number <> 0 Then\n Err.Raise Number:=vbObjectError + 513, Description:=\"Unable to create Merged Range\"\n Exit Function\n End If\n On Error GoTo 0\n End With\n\n Set getMergeRange = newTarget\nEnd Function\n\nPrivate Sub ApplyBorders(Target As Range)\n With Target.Borders\n .LineStyle = xlContinuous\n .ColorIndex = 0\n .Weight = xlThin\n End With\nEnd Sub\n\nPrivate Sub ApplyFormatsToMergeArea(Target As Range)\n Const NumberOfColumns As Long = 8\n\n With Target\n .HorizontalAlignment = xlCenter\n .VerticalAlignment = xlCenter\n .Resize(, NumberOfColumns).WrapText = True\n .Rows.EntireRow.AutoFit\n End With\nEnd Sub\n\nPrivate Sub CloseTestWorkbooks()\n Dim wb As Workbook\n For Each wb In Workbooks\n If Len(wb.Path) = 0 Then wb.Close 0\n Next\nEnd Sub\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T19:07:19.820",
"Id": "232964",
"ParentId": "232815",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T17:26:43.370",
"Id": "232815",
"Score": "4",
"Tags": [
"performance",
"vba"
],
"Title": "Merge duplicated cells in bulk per each column VBA"
}
|
232815
|
<p>I wanted to implement a <a href="https://en.wikipedia.org/wiki/Timsort" rel="nofollow noreferrer">Timsort</a> in python.</p>
<p>Here's what I've come up with:</p>
<pre><code>from typing import List
RUN = 32
def insertionSort(unsorted: List[int], left: int, right: int) -> None:
""" Sorts the array using insertion sort """
for i in range(left + 1, right + 1):
temp = unsorted[i]
j = i-1
while unsorted[j] > temp and j >= left:
unsorted[j+1] = unsorted[j]
j -= 1
unsorted[j+1] = temp
def merge(unsorted: List[int], left: int, middle: int, right: int) -> None:
""" Merges two sorted arrays """
len1 = middle - left + 1
len2 = right - middle
left_side = unsorted[left : left + len1]
right_side = unsorted[middle + 1 : middle + len2 + 1]
i = j = 0
k = left
while i < len1 and j < len2:
if left_side[i] <= right_side[j]:
unsorted[k] = left_side[i]
i += 1
else:
unsorted[k] = right_side[j]
j += 1
k += 1
while i < len1:
unsorted[k] = left_side[i]
i += 1
k += 1
while j < len2:
unsorted[k] = right_side[j]
j += 1
k += 1
def timSort(unsorted: List[int], length: int) -> None:
"""
Sorts every 'RUN' elements by insertion sort as
insertion sort is faster for smaller array lengths
"""
# Sorts every RUN elements using insertion sort
for i in range(0, length, RUN):
insertionSort(unsorted, i, min(i + 31, length - 1))
size = RUN
# Merges every sorted subarray using Merge Sort
while size < length:
left = 0
while left < length:
mid = min(left + size - 1, length - 1)
right = min(left + 2 * size - 1, length - 1)
merge(unsorted, left, mid, right)
left += size * 2
size *= 2
if __name__ == '__main__':
unsorted = list(map(int, input('Enter space seperated elements: ').split()))
n = len(unsorted)
timSort(unsorted, n)
print('Here\'s the sorted array: ')
print(*unsorted)
</code></pre>
<p>I think it looks good, but I want to make it even better.</p>
<p>PS: What would be the optimal length for <code>RUN</code>?</p>
|
[] |
[
{
"body": "<p>The easiest way to implement Timsort in Python is of course to use the built-in version:</p>\n<pre><code>def timsort(x):\n return sorted(x)\n</code></pre>\n<p>Since you don't learn anything from that, implementing it yourself is of course nice.</p>\n<p>First, some general comments.</p>\n<ul>\n<li>Python has an official style-guide, PEP8. It recommends using <code>lower_case</code> for variables and functions. It also recommends using empty lines sparingly.</li>\n<li>You don't need to pass the length to the algorithm. Every indexable Python object has a length, so just use <code>len(unsorted)</code>.</li>\n<li>Your type hints say that this function can only take lists of integers. It works perfectly fine with lists of any comparable type, just like the built-in <code>sorted</code>.</li>\n<li>Choosing to modify the input list in-place is perfectly fine for lists (after all, <code>list.sort</code> does the same thing). But if you do that, it should be noted in the <code>docstring</code>. You could, however, also choose to conform closer to <code>sorted</code> and first copy the iterable into a list (simply copying if it already is a list), sorting it in-place and returning it. This would change the signature to <code>tim_sort(x: Iterable[Any]) -> List[Any]</code>.</li>\n<li>The built-in sorting functions all take a <code>key</code> argument, which is called once per argument. This results in effectively sorting <code>[key(element) for element in x]</code> and afterwards returning only the second element from each inner tuple.</li>\n</ul>\n<p>Now, let's take a closer look at your actual code.</p>\n<p>You use <code>while</code> loops quite a lot. While (pun intended) they almost always work, they are not always the most efficient (in readability) way to accomplish your goal. In the <code>merge</code> function you can replace the last two <code>while</code> loops with list slice assignments. I would also simplify the setting of <code>left_side</code> and <code>right_side</code> by using <code>left</code>, <code>middle</code> and <code>right</code> instead of <code>left</code>, <code>middle</code>, <code>len1</code> and <code>len2</code>.</p>\n<pre><code>def merge(unsorted: List[int], left: int, middle: int, right: int) -> None:\n """ Merges two sorted arrays """\n len1 = middle - left + 1\n len2 = right - middle\n left_side = unsorted[left:middle + 1]\n right_side = unsorted[middle + 1:right + 1]\n \n i = j = 0\n k = left\n while i < len1 and j < len2:\n if left_side[i] <= right_side[j]:\n unsorted[k] = left_side[i]\n i += 1\n else:\n unsorted[k] = right_side[j]\n j += 1\n k += 1\n\n unsorted[k:] = left_side[i:]\n unsorted[k + len1 - i:] = right_side[j:]\n</code></pre>\n<p>Instead of slices, you can also create a new list and use <code>extend</code>:</p>\n<pre><code>def merge(unsorted: List[int], left: int, middle: int, right: int) -> None:\n """ Merges two sorted arrays """\n len1 = middle - left + 1\n len2 = right - middle\n left_side = unsorted[left:middle + 1]\n right_side = unsorted[middle + 1:right + 1]\n \n i = j = 0\n k = left\n out = []\n while i < len1 and j < len2:\n if left_side[i] <= right_side[j]:\n out.append(left_side[i])\n i += 1\n else:\n out.append(right_side[j])\n j += 1\n k += 1\n out.extend(left_side[i:])\n out.extend(right_side[j:])\n unsorted[:] = out\n</code></pre>\n<p>The first <code>while</code> loop could also use iterators instead of indices, but that is left as an exercise for now.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-05T09:52:45.183",
"Id": "490879",
"Score": "1",
"body": "That's not the easiest way, easiest way is `timsort = sorted` :-P (then you even get its parameters for free)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-05T09:55:30.733",
"Id": "490880",
"Score": "0",
"body": "@superbrain: I would argue that \"The easiest way to implement Timsort in Python is of course to use the built-in version\" is still true, but I did not give the simplest possible implementation of that :D And you are right, getting the options for free without having to do `*args, **kwargs` is nice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-05T10:10:51.980",
"Id": "490881",
"Score": "0",
"body": "`[(key(element), element) for element in x]` isn't quite right, since the element itself is *not* used in the comparisons then, only the key is. More seriously: Your merge functions don't work, cause `TypeError: 'list_iterator' object is not subscriptable`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-05T10:15:25.577",
"Id": "490882",
"Score": "0",
"body": "Plus your first `merge` would remove everything right of `right` and your second `merge` would also remove everything left of `left`. The slice assignments need to take those bounds into account."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-05T10:17:21.107",
"Id": "490883",
"Score": "0",
"body": "@superbrain: Looks like somebody didn't test their code...I'll see if I can fix it up."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-05T10:18:37.097",
"Id": "490884",
"Score": "0",
"body": "Maybe you did test, but only with an input shorter than `RUN`, in which case `merge` is never used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-05T12:03:44.520",
"Id": "490892",
"Score": "0",
"body": "The updated versions both cause IndexError for example on `unsorted = [13] * 666`."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T14:33:00.513",
"Id": "232859",
"ParentId": "232826",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "232859",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T19:17:50.500",
"Id": "232826",
"Score": "3",
"Tags": [
"python",
"algorithm",
"python-3.x",
"sorting",
"timsort"
],
"Title": "Timsort implementation in Python"
}
|
232826
|
<p>At our company we use an SQLite Database to manage our Drawing IDs (CAD Drawings). The code is written in Python and I need to update it. I think the code I have has some problems, but I am quite unsure so I hope to get feedback and criticism from you all!</p>
<h1>1. What my code does:</h1>
<ul>
<li>It saves the ID, Title and Project Number of the Drawing in a SQLite Database</li>
<li>Therefore it has a function <code>GetID</code> to get the latest ID and create a new one from it</li>
</ul>
<p>Our Drawing IDs look like this <code>"DR0000001"</code>. So I need to split the string, convert it to an Integer and add +1. Then rebuild the ID and return it to the <code>OnSave</code> function.</p>
<p>Then if false is not returned I start the save process.</p>
<h1>2. Problems I think I have with this code:</h1>
<ul>
<li>I think the time between getting the recent ID and saving the new one to the DB is susceptible to errors like double usage of IDs.</li>
<li>I really think this isn't a professional way to do this and I want to learn the correct way.</li>
</ul>
<h2>3. Here is the Code we used up to this point:</h2>
<pre><code>def GetID(self):
try:
conn = sqlite3.connect(SQL_PATH)
c = conn.cursor()
c.execute("SELECT DrawingID FROM Drawing LIMIT 1 OFFSET (SELECT COUNT(*) FROM Drawing)-1")
recent_drawing_id = c.fetchall()
new_drawing_id = "DR"+str(int(recent_drawing_id[0][0][2:])+1).zfill(len(recent_drawing_id[0][0][2:]))
return new_drawing_id
except:
wx.MessageBox("Couldn't get new Drawing ID!", "Info", wx.OK | wx.ICON_INFORMATION)
return False
def OnSave(self, event, mode):
drawingID = self.GetID()
if drawingID != False:
conn = sqlite3.connect(SQL_PATH)
c = conn.cursor()
titel = self.tc2.GetValue()
project_number = self.tc3.GetValue()
try:
c.execute("INSERT into Drawing (DrawingID,Titel,ProjectNumber) values (?,?,?)", (userID,titel,project_number))
conn.commit()
c.close()
return
except:
wx.MessageBox("Couldn't create new Drawing entry!", "Info", wx.OK | wx.ICON_INFORMATION)
return
else:
return
</code></pre>
|
[] |
[
{
"body": "<h1>cursor.lastrowid</h1>\n\n<p>I'm not a SQLite expert, but I think you could INSERT the row then UPDATE the row to add a DrawingID based on the automatically inserted/incremented rowid.</p>\n\n<pre><code># choose a value for OFFSET to make sure that DrawingIDs generated using this\n# method don't collide with those made by the old method\nOFFSET = 0\n\ndef OnSave(self, event, mode):\n conn = sqlite3.connect(SQL_PATH)\n c = conn.cursor()\n\n titel = self.tc2.GetValue()\n project_number = self.tc3.GetValue()\n\n try:\n # insert the row without a DrawingID\n c.execute(\"INSERT into Drawing (Titel,ProjectNumber) values (?,?)\",\n (titel,project_number))\n\n conn.commit() \n\n # calculate the drawingid based on the rowid of the just added row\n drawingid = f'DR{cursor.lastrowid + OFFSET:07d}'\n\n # update that row with the drawingid\n c.execute('UPDATE foo SET DrawingID=? WHERE rowid=?', \n (drawingid, cursor.lastrowid))\n\n conn.close()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-10T05:59:06.647",
"Id": "233752",
"ParentId": "232827",
"Score": "2"
}
},
{
"body": "<p>Really you don't need DR to be stored as it's a user convenience. That is you can add DR when extracting the value. You also don't need to check calculate the next number as SQlite can do this on your behalf.</p>\n\n<p>To further elaborate if DrawingID is defined using <code>INTEGER PRIMARY KEY</code> the column is then an alias of the normally hidden <strong>rowid</strong> (if not a WITHOUT ROWID table (rarely used)). </p>\n\n<p>When inserting a row and you don't sepcify a value for the column then a <strong>unique</strong> value is supplied. This is typically 1 greater than the highest with the first value as 1. </p>\n\n<ul>\n<li>However, there is no guarantee that the unique value will be 1 greater or that if when (if) you reached the maximum number of 9223372036854775807 (basically impossible due to storage device capacity) that a lower (but still unique) number will be assigned.</li>\n</ul>\n\n<p>Using an alias of the <strong>rowid</strong> will be more efficient not only as the value stored is shorter (maximum of 8 bytes), it is stored in the most efficient (up to twice as fast as other indexes) index. Of course you then don't have the additional inefficiency of trying to replicate this inbuilt behaviour by <em>So I need to split the string, convert it to an Integer and add +1. Then rebuild the ID and return it to the OnSave function.</em></p>\n\n<p>As an example consider the following :-</p>\n\n<pre><code>/* Cleanup in case existing Environment exists */\nDROP TABLE IF EXISTS Drawing;\n/* The suggested Schema */\nCREATE TABLE IF NOT EXISTS Drawing (DrawingID INTEGER PRIMARY KEY, Title TEXT, ProjectNumber INTEGER);\n\n/* Add various drawings */\nINSERT INTO Drawing (Title,ProjectNumber) VALUES\n ('Room1',1),('Room2',1),('Room1',3),('Room3',3),('Room3',1),('Room2',3),('Room1',2);\n/* Extracting Project, Drawing Title and Drawing ID */\nSELECT 'Project - '||ProjectNumber AS ProjectNumber, Title, 'DR'||printf('%07d',DrawingID) AS DrawingID FROM Drawing ORDER BY ProjectNumber,DrawingId; \n/* Cleanup testing Environment */\nDROP TABLE IF EXISTS Drawing;\n</code></pre>\n\n<p>The above results in :-</p>\n\n<p><a href=\"https://i.stack.imgur.com/UvCDm.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/UvCDm.png\" alt=\"enter image description here\"></a></p>\n\n<p>The actual data in the table being </p>\n\n<ul>\n<li>sorted as above i.e. extracted using <code>SELECT * FROM Drawing ORDER BY ProjectNumber,DrawingId;</code>) :-</li>\n</ul>\n\n<p><a href=\"https://i.stack.imgur.com/qs6WK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/qs6WK.png\" alt=\"enter image description here\"></a></p>\n\n<p>You may wish to have a read of </p>\n\n<ul>\n<li><a href=\"https://www.sqlite.org/lang_createtable.html#rowid\" rel=\"nofollow noreferrer\">SQL As Understood By SQLite - CREATE TABLE - ROWIDs and the INTEGER PRIMARY KEY</a></li>\n<li><a href=\"https://www.sqlite.org/autoinc.html\" rel=\"nofollow noreferrer\">SQLite Autoincrement</a> \n\n<ul>\n<li><em>(Noting that althogh this is a link to AUTOINCREMENT it explains why AUTOINCREMENT is best not used in addition to adding information)</em></li>\n</ul></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-18T20:47:07.227",
"Id": "234289",
"ParentId": "232827",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "234289",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T19:32:05.267",
"Id": "232827",
"Score": "5",
"Tags": [
"python",
"beginner",
"python-3.x",
"sql",
"sqlite"
],
"Title": "Add as newest ID to SQLite Database"
}
|
232827
|
<p>C++17 have <code><charconv></code>. However this header does not work on MacOS - It compiles, but can not link. Same header is not present in <code>MSVS</code>. The header also missing from my Arm Linux, even my gcc compiler there supports C++17 as well.</p>
<p>Following is a take to convert non terminated char array (e.g. buffer, string_view etc) into signed or unsigned integer.</p>
<p>I probably will use the code in production, once I do some more tests.</p>
<pre><code>#include <limits>
#include <type_traits>
#include <string_view>
#include <utility>
namespace impl{
template<typename T>
T x10(T a){
return a * 10;
}
inline char digit(char c){
return c - '0';
}
inline bool is_space(char c){
return c == ' ' || c == '\t' || c == '\r' || c == '\n';
}
inline bool is_sign(char c){
return c == '+' || c == '-';
}
inline bool is_digit(char c){
return c >= '0' && c <= '9';
}
template<typename T>
std::pair<bool,T> convert_unsigned(const char *c, const char *e){
T num = 0;
while(c != e && is_digit(*c)){
T tmp = x10(num) + digit(*c);
if (tmp < num)
return { false, num };
num = tmp;
++c;
}
return { true, num };
}
template<typename T>
std::pair<bool,T> convert(const char *c, const char *e, std::true_type /* unsigned */){
if (c != e && *c == '+')
++c;
return convert_unsigned<T>(c, e);
}
template<typename T>
std::pair<bool,T> convert(const char *c, const char *e, std::false_type /* unsigned */){
using U = std::make_unsigned_t<T>;
T sign = +1;
U max = std::numeric_limits<T>::max();
if (c != e && is_sign(*c)){
if (*c == '-'){
sign = -1;
max = - (U) std::numeric_limits<T>::min();
}
++c;
}
// std::cout << ">>> " << sign << ' ' << max << ' ' << '\n';
auto [ ok, result ] = convert_unsigned<U>(c, e);
if (result > max)
return { false, (T) result };
if (result == max)
return { true, (T) result };
return { ok, sign * (T) result };
}
}
template<typename T>
std::pair<bool,T> convert(std::string_view const s){
static_assert(std::is_integral_v<T>);
return impl::convert<T>(std::begin(s), std::end(s), std::is_unsigned<T>{});
}
#include <cstdint>
#include <iostream>
template<typename T>
void test(const char *s, T correct){
auto [ok, i] = convert<T>(s);
if (!ok)
std::cout << "Err" << '\n';
std::cout << ( i == correct ? "OK" : "NO") << ' ' << i << '\n';
}
int main(){
test<uint16_t> ("-0", std::numeric_limits<uint16_t>::min() );
test<uint16_t> ("65535", std::numeric_limits<uint16_t>::max() );
test<int16_t> ("+32767", std::numeric_limits<int16_t>::max() );
test<int16_t> ("-32768", std::numeric_limits<int16_t>::min() );
test<int16_t> ("+0", 0 );
test<int16_t> ("-0", 0 );
test<int16_t> ("+10", +10 );
test<int16_t> ("-10", -10 );
test<uint64_t> ("+0", std::numeric_limits<uint64_t>::min() );
test<uint64_t> ("+18446744073709551615", std::numeric_limits<uint64_t>::max() );
test<int64_t> ("+9223372036854775807", std::numeric_limits<int64_t>::max() );
test<int64_t> ("-9223372036854775808", std::numeric_limits<int64_t>::min() );
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T21:14:56.153",
"Id": "454847",
"Score": "0",
"body": "Added some nodes why someone needs these functions."
}
] |
[
{
"body": "<p>We're missing any documentation or template constraints, but it appears that this code parses only decimal integers, and silently ignores anything after the first non-digit. There are other departures from the interface of the functions provided in <code><charconv></code>:</p>\n\n<ul>\n<li>a leading <code>+</code> is accepted and ignored</li>\n<li><del>not all out-of-range values are detected</del>.</li>\n</ul>\n\n<p><del>Worse, there's no prevention of signed integer overflow, so there's undefined behaviour on certain inputs.</del><br>\nThe avoidance of signed overflow is fragile and could be made clearer to the reader (with suitable <code>static_assert()</code> if <code>requires</code> isn't palatable, for instance).</p>\n\n<p>I think that writing a function to multiply by 10 is taking functional decomposition a step too far. I would say the same for subtracting <code>'0'</code>, but that could be arguable if it were home for a comment explaining how C++ guarantees that the characters <code>'0'</code>..<code>'9'</code> are encoded as contiguous values.</p>\n\n<p>There are no tests for any of the failure cases, and all the tests have to be checked externally. It's better to make <code>main()</code> return an error status unless all the tests pass (and diagnostic output should go to <code>std::clog</code> or <code>std::cerr</code> as appropriate, rather than <code>std::cout</code>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T16:15:58.023",
"Id": "455121",
"Score": "0",
"body": "show me input where i have UB"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T16:49:42.087",
"Id": "455133",
"Score": "0",
"body": "`T tmp = x10(num) + digit(*c);` - (...time passes...) ah, that's unreachable with signed `T` - but not obviously so, and it's fragile (signedness passed in a bool)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T18:25:01.090",
"Id": "455146",
"Score": "0",
"body": ">> if it were home for a comment explaining how C++ guarantees that the characters '0'..'9' are encoded as contiguous values.\n\nthis is guaranteed from ASCII. also lowest 3 bits is the number."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T18:26:53.323",
"Id": "455147",
"Score": "0",
"body": "I know it's guaranteed by ASCII, but there's nothing that forces C++ implementations to use ASCII. That's why the comment explaining that C++ _does_ require contiguous digits is valuable."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T14:28:13.057",
"Id": "232945",
"ParentId": "232828",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "232945",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T19:34:34.247",
"Id": "232828",
"Score": "2",
"Tags": [
"c++",
"algorithm",
"reinventing-the-wheel",
"converting"
],
"Title": "Convert char array to number"
}
|
232828
|
<p>Here's how I'm using my location component:</p>
<pre><code><LocationContainer opts={{timeout: 5000}}>
{(address, error) => {
if (error) {
return <div>Could not determine address (why...? <span style={{color: 'red'}}>{error.message}</span>)</div>
} else if (address) {
return <div>{address.neighbourhood}, {address.city}</div>
} else {
return <div>loading...</div>
}
}}
</LocationContainer>
</code></pre>
<p>And here is the component itself:</p>
<pre><code>import { Component } from 'react';
import axios from 'axios';
class LocationContainer extends Component {
constructor(props) {
super(props);
this.state = {
address: null,
error: null,
};
}
getLocation(opts) {
return new Promise((resolve, reject) => {
if ('geolocation' in navigator) {
navigator.geolocation.getCurrentPosition(resolve, reject, opts);
} else {
reject('geolocation not supported');
}
});
}
async getAddress(opts) {
let location = await this.getLocation(opts);
let resp = await axios.get('https://nominatim.openstreetmap.org/reverse', {
params: {
lat: location.coords.latitude,
lon: location.coords.longitude,
format: 'json',
},
});
return resp.data.address;
}
async componentDidMount() {
try {
let address = await this.getAddress(this.props.opts);
this.setState({address: address});
} catch (error) {
this.setState({error: error})
}
}
render() {
return this.props.children(this.state.address, this.state.error);
}
}
export default LocationContainer;
</code></pre>
<p>The code renders the location of the client, or an error message is displayed if it can't be found.</p>
<p>I have two main questions: </p>
<ul>
<li><p>Is what I've done a sensible way to integrate the geolocation API into a react website?</p></li>
<li><p>Does the usage of <code>LocationContainer</code> make sense to an experienced react developer?</p></li>
</ul>
<p>Would love feedback on any anti-patterns or general react coding style.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T12:28:07.057",
"Id": "455090",
"Score": "0",
"body": "Hi Ferguzz, welcome to CodeReview. To Close Voters, please comment as to why."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T19:36:21.323",
"Id": "232829",
"Score": "2",
"Tags": [
"javascript",
"react.js"
],
"Title": "Patterns used for accessing geolocation API"
}
|
232829
|
<p>I have made a class which is a thread-safe implementation supporting Deposit, Withdrawal, Check Balance Querying and Transferring of money.
I have a class Account:</p>
<pre class="lang-java prettyprint-override"><code>public class Account {
private int balance;
private String address;
private String userId;
final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
Lock transferLock = new ReentrantLock();
public Account(String userId){
this.userId = userId;
}
public void add(int amount){
balance += amount;
}
public void sub(int amount){
this.balance -= amount;
}
public int getBalance(){
return balance;
}
}
</code></pre>
<p>I use a ReentrantReadWriteLock for Depositing and Withdrawing which acquires a Write Lock.
Read lock is acquired when checking an Account's balance.
A 'transferLock' is used to lock the transferring of funds from Account A to Account B.</p>
<p>Here are the main functions:</p>
<pre class="lang-java prettyprint-override"><code> public boolean deposit(String userId, int amount){
Account account = getUserAccount(userId);
Lock accountWriteLock = account.lock.writeLock();
accountWriteLock.lock();
account.add(amount);
accountWriteLock.unlock();
return true;
}
public boolean withdraw(String userId, int amount){
Account account = getUserAccount(userId);
Lock accountWriteLock = account.lock.writeLock();
accountWriteLock.lock();
if(account.getBalance() < amount){
accountWriteLock.unlock();
return false;
}
account.sub(amount);
accountWriteLock.unlock();
return true;
}
public int checkBalance(String userId){
Account account = getUserAccount(userId);
Lock accountReadLock = account.lock.readLock();
accountReadLock.lock();
int balance = account.getBalance();
accountReadLock.unlock();
return balance;
}
public boolean transfer(String fromAccountUserId, int amount, String toAccountUserId) throws Exception {
Account fromAccount = getUserAccount(fromAccountUserId);
Account toAccount = getUserAccount(toAccountUserId);
Random rand = new Random();
Lock fromAccountTransferLock = fromAccount.transferLock;
Lock toAccountTransferLock = toAccount.transferLock;
while (true) {
if (fromAccountTransferLock.tryLock()) {
fromAccount.lock.writeLock();
if (toAccountTransferLock.tryLock()) {
try {
withdraw(fromAccountUserId, amount);
deposit(toAccountUserId, amount);
break;
} catch (Exception e) {
return false;
} finally {
toAccountTransferLock.unlock();
}
}
fromAccountTransferLock.unlock();
Thread.sleep(rand.nextInt(1001));
}
}
return true;
}
</code></pre>
<p>Assume that getUserAccount(String userId) retrieves the appropriate Account object.</p>
<p><em>What I Would Like Reviewed</em><br>
1. Is my code thread-safe?<br>
2. Any improvements you think would be good? </p>
<p><em>Notes</em><br>
1. I prevent Deadlock in Transferring from Account A to Account B by allowing the holding thread to release its lock.<br>
2. I prevent LiveLock in transfer(...) by sleeping the thread for a random number of milliseconds between [0,1000] ms.</p>
<p>EDIT:
Here is the getUserAccount() code:</p>
<pre class="lang-java prettyprint-override"><code>public Account getUserAccount(String userId){
return new Account(userId);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T01:00:44.823",
"Id": "454867",
"Score": "1",
"body": "Hey Jim, could you add the full class where the method `getUserAccount` is defined, for example. Otherwise without the full code it's difficult to provide a good review :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T11:21:17.637",
"Id": "454905",
"Score": "0",
"body": "Hi IEatBagels, thanks for the reply. I have added the getUserAccount() function. As you can see right now it just returns a new Account() object. I am just testing the other functions first. I hope this is okay for you to still review. I appreciate the help :) Currently I am not communicating with any kind of database."
}
] |
[
{
"body": "<p>Let's break this down.</p>\n<ol>\n<li>You have two locks for single object that guarding same fields.</li>\n</ol>\n<p>It's generally bad practice, and it doesn't make sense as second lock(transferLock) is used only in single operation. It won't guard for other operations.</p>\n<p>It could possibly work if you have a static read-only lock for transfer with the following semantics: add/sub/get are global read lock and transfer is global write lock, then yu should acquire read lock on transfer on regular operations and write-lock on transfer op, but that would allow on;y single transfer at a time, and that's definitely not what you are trying to achieve.</p>\n<ol start=\"2\">\n<li>Your locks leak outside of your main class (reed aren't private/protected).</li>\n</ol>\n<p>This could lead to uncontrolled use from outside, say future versions of code could misuse locks. I can see that they have package level visibility, that's semi ok, but Account#add,Accound#sub, Account#getBallance are public and not guarded by locks, so that destroys the purpose of haveing locks package-private.</p>\n<p>I'd suggest put all usage of locks inside instance methods mentioned above, and add another method:</p>\n<pre><code>class Account{\npublic void transfer(Account other, int amount) { ... }\n}\n</code></pre>\n<p>Then all logic related to locking would be in a single, controlled place.</p>\n<ol start=\"3\">\n<li>Lock ordering. If you are using granular locks, so no single lock for all accounts and you need to lock several objects you should have STRICT lock order.</li>\n</ol>\n<p>You are trying to achieve this with <code>tryLock</code> and while loop, this COULD actually work if you have used your rw <code>lock</code>, but it would be possible to deadlock as you are acquiring other locks then. And it's not really performant to wait in spin-loop here, you can wait forever.</p>\n<p>I'd suggest to user your rw-lock but first, sort two accounts by accountId, then take write locks in order of account ids from lower to higher.</p>\n<pre><code>//pseudocode\nif (acc1.id<acc2.id) {\n acc1.lock.writeLock().lock()\n acc2.lock.writeLock().lock()\n}else{\n acc2.lock.writeLock().lock()\n acc1.lock.writeLock().lock()\n}\n</code></pre>\n<p>It could be actually combined with tryLock, but it could take a while to acquire such locks.</p>\n<ol start=\"4\">\n<li>Minor thing, it's preferable to call <code>unlock()</code> inside <strong>finally</strong> block, so no objects would stick in a locked state.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-13T09:22:20.763",
"Id": "245401",
"ParentId": "232830",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T19:59:04.607",
"Id": "232830",
"Score": "1",
"Tags": [
"java",
"thread-safety",
"concurrency",
"transactions"
],
"Title": "Thread Safe Bank Transaction: Deposit, Withdrawal, Check Balance and Transfer in Java"
}
|
232830
|
<p>I am writing a program to compress an image using Huffman encoding and I need to write the data structure and the byte file. After that, I have to read/decode it. I realize that my read and write is very slow.</p>
<p>I think in <code>writetree()</code> I need to write either <code>width</code>, <code>height</code>, <code>compress</code> bits and the <code>tree</code> data structure. I am not sure we can combine it or not.</p>
<p>And another part, I think I use too many for loop so it is very slow in a very long string</p>
<pre><code>from PIL import Image
import numpy as np
import json
import sys, string
trim = ('0', ('127', '255'))
width = 4
height = 4
longstring = "1100100111001101011110010011010110101111001001101011010111100100110101101011"
def decode (tree, str) :
output = ""
list = []
p = tree
count = 0
for bit in str :
if bit == '0' : p = p[0] # Head up the left branch
else : p = p[1] # or up the right branch
if type(p) == type("") :
output += p # found a character. Add to output
list.append(int(p))
p = tree # and restart for next character
return list
def writetree(tree,height, width,compress):
with open('structure.txt', 'w') as outfile:
json.dump(trim, outfile)
outfile.close()
f = open("info.txt", "w")
f.write(str(height)+"\n")
f.write(str(width)+"\n")
f.write(str(compress)+"\n")
f.close()
def readtree():
with open('structure.txt') as json_file:
data = json.load(json_file)
k = open("info.txt", "r")
heightread = k.readline().strip("\n")
widthread = k.readline().strip("\n")
compressread = k.readline().strip("\n")
json_file.close()
k.close()
return tuple(data), int(heightread), int(widthread), int(compressread)
def writefile():
print("Write file")
with open('file', 'wb') as f:
bit_strings = [longstring[i:i + 8] for i in range(0, len(longstring), 8)]
byte_list = [int(b, 2) for b in bit_strings]
print(byte_list)
realsize = len(bytearray(byte_list))
print('Compress number of bits: ', len(longstring))
writetree(trim,height,width,len(longstring))
f.write(bytearray(byte_list))
f.close()
def readfile():
print("Read file")
byte_list = []
longbin = ""
with open('file', 'rb') as f:
value = f.read(1)
while value != b'':
byte_list.append(ord(value))
value = f.read(1)
print(byte_list)
for a in byte_list[:-1]:
longbin = longbin + '{0:08b}'.format(a)
trim_read, height_read, width_read , compress_read = readtree()
sodu = compress_read%8
'''
because the this string is split 8 bits at the time, and the current compress_read is 76
so the sodu is 4. I have to convert the last byte_list into 4bits not 8 bits
'''
if sodu == 0:
longbin = longbin + '{0:08b}'.format(byte_list[-1])
elif sodu == 1:
longbin = longbin + '{0:01b}'.format(byte_list[-1])
elif sodu == 2:
longbin = longbin + '{0:02b}'.format(byte_list[-1])
elif sodu == 3:
longbin = longbin + '{0:03b}'.format(byte_list[-1])
elif sodu == 4:
longbin = longbin + '{0:04b}'.format(byte_list[-1])
elif sodu == 5:
longbin = longbin + '{0:05b}'.format(byte_list[-1])
elif sodu == 6:
longbin = longbin + '{0:06b}'.format(byte_list[-1])
elif sodu == 7:
longbin = longbin + '{0:07b}'.format(byte_list[-1])
print(longbin)
print("Decode/ show image:")
pixels = decode(trim_read, longbin)
it = iter(pixels)
pixels = list(zip(it,it,it))
#print(pixels)
image_out = Image.new("RGB", (width_read, height_read))
image_out.putdata(pixels)
#image_out.show()
writefile()
readfile()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T00:59:21.357",
"Id": "454866",
"Score": "0",
"body": "Hello! I think you have a great first post, could you maybe explain quickly how your algorithm works? I think your question might draw more attention, but anyways I think you've done a good job."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T05:50:54.223",
"Id": "454879",
"Score": "1",
"body": "I am using the Huffman encoding, It is quite long to explain in here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T05:52:53.373",
"Id": "454881",
"Score": "0",
"body": "for now, i need to write file, save the data structure ( trim ) also save the height and width and compress bit of the image. I think I make it loop over and over again so It much slower in longwer string"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T05:55:18.350",
"Id": "454882",
"Score": "0",
"body": "You can see in readfile function, I read the file and and append to the list, and loop it again to convert '{0:08b}'.format(a)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-16T02:51:38.370",
"Id": "457793",
"Score": "0",
"body": "Are you still looking for answers to this? :)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T20:31:03.323",
"Id": "232832",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"image"
],
"Title": "Better performance in read/write data structure + byte"
}
|
232832
|
<p>I have been working on Project Euler <a href="https://projecteuler.net/problem=12" rel="nofollow noreferrer">problem number 12</a>. I have code that will get me the right answer, however it takes too long. I know the code works because I have tested it multiple times with numbers that are smaller and take much less time to iterate through. I first wrote essentially the same thing in python, but I know C is faster so I gave it a shot in C, but my solution is just not efficient. Here is the code (in C):</p>
<pre><code>#include <stdio.h>
int main(void) {
int num = 0;
int i;
int j;
int divisors = 0;
for (i=1; i<10000; i++){
num += i;
for (j=1; j<=num; j++) {
if (num % j == 0) {
divisors += 1;
}
}
if (divisors > 500) {
printf("Num is %d\n", num);
printf("Divs are %d\n", divisors);
}
divisors = 0;
}
}
</code></pre>
<p>Project Euler problems are supposed to be solved in under a minute of run-time anyways, so this isn't a great solution even if I let it run until I got an answer. </p>
<p><strong>Any suggestions on ways to do this faster would be much appreciated!</strong></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T04:52:03.537",
"Id": "454874",
"Score": "2",
"body": "Welcome to Code Review! This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question (not behind a link). The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you. [Questions should include a description of what the code does](https://codereview.meta.stackexchange.com/a/1231)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T14:56:00.993",
"Id": "454915",
"Score": "1",
"body": "Please add the text of the Project Euler problem to the question before the code."
}
] |
[
{
"body": "<p><strong>Iterating [1...num] is too slow</strong><br>\n<strong>Only [1...sqrt(num)] needed</strong> </p>\n\n<p>Instead of </p>\n\n<pre><code>for (j=1; j<=num; j++) {\n if (num % j == 0) {\n divisors += 1;\n }\n}\n</code></pre>\n\n<p>Go to the root of <code>num</code> (when <code>j*j <= num</code>) and get 2 or 1 divisors.</p>\n\n<pre><code>for (j=1; j*j <= num; j++) {\n if (num % j == 0) {\n divisors += 1;\n if (j*j < num) divisors += 1;\n }\n}\n</code></pre>\n\n<p>Re-formulate to avoid <code>j*j</code> overflow</p>\n\n<pre><code>for (j=1; j < num/j; j++) {\n if (num % j == 0) {\n divisors += 2;\n }\n}\nif (j == num/j) {\n divisors += 1;\n}\n</code></pre>\n\n<p>Note: Many compilers with recognize the nearby <code>num/j</code> and <code>num % j</code> and perform the operation for the time cost one of one.</p>\n\n<p><strong>Example</strong></p>\n\n<p>Consider <code>num == 36</code>. Original code tries 36 numbers with the starred ones having an exact division.</p>\n\n<p>1*,2*,3*,4*,5,6*,7,8,9*,10,11,12*,13,14,15,16,17,18*,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36*.</p>\n\n<p>Notice that when <code>num%j == 0</code>, both <code>j</code> and <code>num/j</code> are divisors. Except when <code>j == num/j</code>, that discovers two unique divisors at once. Code only needs to iterate to 6.</p>\n\n<p>j=1, divisors: 1 & 36<br>\nj=2, divisors: 2 & 18<br>\nj=3, divisors: 3 & 12<br>\nj=4, divisors: 4 & 9<br>\nj=5, divisors: none<br>\nj=6, divisor: 6 </p>\n\n<p>6 iterations faster than 36.</p>\n\n<p>With a <code>num = 1,000,000</code>, new code will iterate to 1000 rather than 1,000,000 - a thousand times faster.</p>\n\n<hr>\n\n<p><strong>Detail on overflow possibility.</strong></p>\n\n<p>Consider <code>num</code> is at or near <code>INT_MAX</code>:</p>\n\n<p>With <code>for (j=1; j<=INT_MAX; j++) {</code>, <code>j</code> will attempt to increment beyond <code>INT_MAX</code> resulting in <em>undefined behavior</em>. </p>\n\n<p>With <code>for (j=1; j*j < near_INT_MAX; j++) {</code>, Unless <code>near_INT_MAX</code> is a perfect square, <code>j*j</code> will overflow. Again <em>undefined behavior</em>.</p>\n\n<p>With <code>for (j=1; j < num/j; j++) {</code>, <code>j</code> never overflow for all <code>num</code>.</p>\n\n<p>====</p>\n\n<p>There are many more advance techniques for faster code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T00:14:03.970",
"Id": "454865",
"Score": "0",
"body": "Code works great but could you go back and explain it all a little more? I'm trying to understand why this works so well so I can use things like this in the future."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T01:54:21.543",
"Id": "454870",
"Score": "0",
"body": "@joelanbanks3 OK"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T05:06:44.467",
"Id": "454878",
"Score": "0",
"body": "That's super cool! Thank you so much!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T23:49:24.150",
"Id": "232835",
"ParentId": "232834",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "232835",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-22T23:20:53.587",
"Id": "232834",
"Score": "0",
"Tags": [
"c",
"programming-challenge"
],
"Title": "Optimizing code that needs to run through a lot of different numbers for Project Euler"
}
|
232834
|
<p>I have a <code>HashMap</code> and I want to convert data in it to a <code>Response</code> object, but I do not find it clean and optimized. Is there a better way to achieve this?</p>
<pre><code>class Converter{
public static void main(String[] args) {
Map<String, Long> map = new HashMap<String, Long>();
map.put("111", 80) // first
map.put("1A9|ppp", 190) // second
map.put("98U|6765", 900) // third
map.put("999|aa|local", 95) // fourth
List<Response> responses = new ArrayList<>();
for(String key : map.keySet()){
Response response = new Response();
String[] str = key.split("\\|");
response.id = str[0] //id is always present in key i.e 111, 1A9, 98U,999
if(str.length == 2) {
if(str.matches("-?\\d+(\\.\\d+)?");){ // check if is numeric
response.code = str[1]; // 6765
}
else{
response.city = str[1]; //ppp
}
}
if(str.length == 3){
response.client = str[1]; //aa
response.type = str[2]; // local
}
response.qty = map.get[key];
responses.add(response);
}
}
}
class Response{
String id;
String city;
Long code;
String client;
String type;
Long qty;
// getters and setters
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T04:41:09.447",
"Id": "454873",
"Score": "0",
"body": "Why are you using a String to represent the response? Why not have a `HashMap<Response, Long>`"
}
] |
[
{
"body": "<p>As dustytrash already mentioned in a comment, it would be much more sensible to simply use the <code>Response</code> object as the map key and be done.</p>\n\n<p>If this is not possible due to unknown external constraints, move the translation to and from <code>String</code> into the <code>Response</code> object.</p>\n\n<pre><code>class Response {\n public static Response fromString(String s) {\n // ... do the parsing here\n }\n\n @Override\n public String toString() {\n // generate \"98U|6765\" or whatever\n // debatable: maybe don't use the overridden toString for the technical representation\n }\n}\n</code></pre>\n\n<p>This encapsulates the nitty-gritty details of conversion in the class itself.</p>\n\n<p>The converson then boils down to</p>\n\n<pre><code>map.keySet().stream()\n .map(Response::fromString)\n .collect(Collectors.toList());\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T18:30:28.800",
"Id": "455033",
"Score": "0",
"body": "Thank you. But i also wanted to know if there a way to improve parsing"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T18:44:36.177",
"Id": "455034",
"Score": "0",
"body": "And how to set the qty ?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T06:36:14.717",
"Id": "232845",
"ParentId": "232840",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "232845",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T02:11:23.327",
"Id": "232840",
"Score": "2",
"Tags": [
"java",
"stream"
],
"Title": "Converts data in a HashMap to a custom object"
}
|
232840
|
<p>Writing game engine as a hobby, I've come across many situations where I need a container like a map, but searchable by different keys: a block allocator where a block needs to be searched by either offset or size, or resources searchable by either name or file.</p>
<p>Having multiple maps for each of those keys is ugly and pain in the ass to erase an entry, so I came up with the following.</p>
<h2>Implementation:</h2>
<pre><code>template <typename... T>
class omni_map
{
static constexpr size_t num_element = sizeof...(T);
using tuple_t = std::tuple<T...>;
template <size_t I>
using element_t = typename std::tuple_element_t<I, tuple_t>;
struct node;
struct branch {
branch() :
left(nullptr),
right(nullptr) {}
node* left;
node* right;
};
struct node {
node(T&&... t) :
values(t...) {}
tuple_t values;
branch branches[num_element];
};
public:
template <size_t I>
class iterator {
friend class omni_map<T...>;
public:
iterator(node* n = nullptr) :
curr(n) {}
const tuple_t& operator*() {
return curr->values;
}
const tuple_t& operator->() {
return curr->values;
}
bool operator==(const iterator<I>& r) {
return curr == r.curr;
}
bool operator!=(const iterator<I>& r) {
return curr != r.curr;
}
private:
node* curr;
};
public:
omni_map() :
m_roots{ nullptr } {}
void emplace(T&&... t) {
node* n = m_nodepool.construct(std::forward<T>(t)...);
insert_node<0>(n);
}
template <size_t I>
iterator<I> find(const element_t<I>& value) {
node* curr = m_roots[I];
while (curr)
if (value < std::get<I>(curr->values))
curr = curr->branches[I].left;
else if (value > std::get<I>(curr->values))
curr = curr->branches[I].right;
else
return iterator<I>(curr);
return iterator<I>();
}
template <size_t I>
void erase(iterator<I> it) {
remove_node<0>(it.curr);
m_nodepool.destroy(it.curr);
}
template <size_t I>
iterator<I> begin() {
node* curr = m_roots[I];
while (curr->branches[I].left)
curr = curr->branches[I].left;
return iterator<I>(curr);
}
template <size_t I>
iterator<I> end() {
return iterator<I>();
}
private:
template <size_t I>
void insert_node(node* n) {
node** curr = &m_roots[I];
while (*curr) {
if (std::get<I>(n->values) <= std::get<I>((*curr)->values))
curr = &(*curr)->branches[I].left;
else
curr = &(*curr)->branches[I].right;
}
*curr = n;
insert_node<I + 1>(n);
}
template <>
void insert_node<num_element>(node* n) {}
template <size_t I>
void remove_node(node* n) {
node** curr = &m_roots[I];
while (*curr != n)
if (std::get<I>(n->values) <= std::get<I>((*curr)->values))
curr = &(*curr)->branches[I].left;
else
curr = &(*curr)->branches[I].right;
if (n->branches[I].left)
if (n->branches[I].right) {
node* left = n->branches[I].left;
node* max_left = n->branches[I].left;
while (max_left->branches[I].right)
max_left = max_left->branches[I].right;
*curr = max_left;
while (max_left->branches[I].left)
max_left = max_left->branches[I].left;
max_left->branches[I].left = left;
}
else
*curr = n->branches[I].left;
else
if (n->branches[I].right)
*curr = n->branches[I].right;
else
*curr = nullptr;
remove_node<I + 1>(n);
}
template <>
void remove_node<num_element>(node* n) {}
private:
mem_pool<node> m_nodepool;
node* m_roots[num_element];
};
</code></pre>
<p><code>mem_pool</code> is my implementation of free list memory pool allocator for data locality and fast allocation.</p>
<p>This implementation is basically a one big graph where each element has a binary search tree structure. A node has an left/right child node for each of the element. The values of each entry are stored as a tuple in each node. </p>
<p><code>emplace</code> function creates a node with a tuple constructed with given arguments, and calls <code>insert_node<0></code> which will insert the newly created node in the binary tree structure of the first element, then call <code>insert_node<1></code> for second element, and so on recursively until <code>insert_node<num_element></code>. The container accepts duplicate entries, which will be placed as the left child of already existing entry.</p>
<p><code>find<0></code> searches by the first element(<code>int</code> in the example code's case), <code>find<1></code> searches by the second element(<code>std::string</code> in the example code's case) and so on; returning <code>iterator<I></code> that points to the found entry.</p>
<p><code>erase</code> function takes said <code>iterator<I></code> to removes the node it points to.
The function does so by calling <code>remove_node<I></code> recursively before destroying the node, which will, for each element:</p>
<ol>
<li>find parent node.</li>
<li>if one child, replace self with said child from parent.</li>
<li>if two child, replace self with maximum value node from left branch (has to be maximum from left if duplicates are passed to the left, minimum from right if otherwise).</li>
</ol>
<p>I gave the iterator an index template argument, so that it could iterate based on given <code>I</code>th element. But I might not implement that feature since I won't ever have to iterate in my use cases.</p>
<h2>Example Code:</h2>
<pre><code>#include <iostream>
#include "omni_map.h"
int main()
{
util::omni_map<int, std::string> test_map;
test_map.emplace(3, "three");
test_map.emplace(2, "two");
test_map.emplace(7, "seven");
test_map.emplace(1, "one");
test_map.emplace(6, "six");
test_map.emplace(4, "four");
test_map.emplace(5, "five");
auto it0 = test_map.find<0>(4);
auto it1 = test_map.find<1>("seven");
std::cout << std::get<0>(*it0) << " " << std::get<1>(*it0) << std::endl;
std::cout << std::get<0>(*it1) << " " << std::get<1>(*it1) << std::endl;
test_map.emplace(25, "twenty-five");
test_map.emplace(16, "sixteen");
test_map.emplace(18, "eighteen");
test_map.emplace(17, "seventeen");
test_map.emplace(23, "twenty-three");
test_map.emplace(21, "twenty_one");
test_map.emplace(21, "twenty_one(1)");
it0 = test_map.find<0>(25);
std::cout << (it0 == test_map.end<0>() ? "true" : "false") << std::endl;
test_map.erase(it0);
it0 = test_map.find<0>(25);
std::cout << (it0 == test_map.end<0>() ? "true" : "false") << std::endl;
it0 = test_map.find<0>(21);
it1 = test_map.find<1>("sixteen");
std::cout << std::get<0>(*it0) << " " << std::get<1>(*it0) << std::endl;
std::cout << std::get<0>(*it1) << " " << std::get<1>(*it1) << std::endl;
}
</code></pre>
<p>Above test code outputs as follows:</p>
<pre class="lang-none prettyprint-override"><code>4 four
7 seven
false
true
21 twenty_one
16 sixteen
</code></pre>
<p>I have published the solution to my GitHub <a href="https://github.com/Wulfhart/omni_map" rel="nofollow noreferrer">here</a> to show the entire code.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T05:02:06.857",
"Id": "454876",
"Score": "2",
"body": "Welcome to Code Review! Can you show a complete test program (with the needed `#include`s and the main function) and the command you use to compile the code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T07:54:38.470",
"Id": "454886",
"Score": "0",
"body": "`std::iterator` is deprecated, anyway you have no iterator there..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T09:23:09.000",
"Id": "454893",
"Score": "1",
"body": "@L.F. I published my solution to github [here](https://github.com/Wulfhart/omni_reflection)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T08:29:50.820",
"Id": "455001",
"Score": "0",
"body": "@JoonghoLee: Why your rolled out your own alignment functions? Doesn't standard std::aligned_storage_t is enough for your purposes? Also, aligned_alloc and aligned_free is not used in alignment.h."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T09:19:53.203",
"Id": "455004",
"Score": "0",
"body": "@nomanpouigt Dynamically allocating with new operator doesn't seem to align the data, and std::aligned_new is not supported in MSVC, so I am using a code I copied from [here](https://stackoverflow.com/a/32133912). No good reason as to why I am not using the already declared aligned_alloc and aligned_free in the aligned_ptr implementation. As you can see from the commented out block of code below, I was experimenting with the allocation method, then didn't bother to change back after I decided to go with the original method."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T02:21:34.460",
"Id": "232841",
"Score": "6",
"Tags": [
"c++",
"graph",
"template",
"c++17",
"binary-search"
],
"Title": "Implementation of container searchable by any element"
}
|
232841
|
<p>I wrote a simple function that converts an array of words into proper case (using bitwise operations) and returns the array. I performed a simple test using <code>std::chrono</code> to check how fast it was able to perform the conversion. Using a vector of <strong>1000 words</strong> the function was able to do it in an average of <strong>27 microseconds</strong>.</p>
<p>My question is, if there is a faster way of doing this or if there is anything that I have missed that may be detrimental to the performance of the function. In addition, if there is any syntactical issues or changes that you would recommend that would be greatly appreciated.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <vector>
#include <string>
std::vector<std::string> ToProperCase(std::vector<std::string>& array)
{
if (array.empty())
return array;
// Loop through each word
for (std::string& value : array)
{
// Loop through each character in the word
for (unsigned int i = 0; i < value.size(); ++i)
{
// Capitalise first character
value[0] &= (~(1 << 5));
// Convert character to lower case
if (i > 0)
value[i] |= (1 << 5);
}
}
return array;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T14:26:45.577",
"Id": "454911",
"Score": "1",
"body": "Fast, but it's not unicode-aware, so what's the point?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T17:49:33.777",
"Id": "454931",
"Score": "4",
"body": "@Alexander We get users from various backgrounds; some beginners, some pros. Ridiculing users for not solving challenges you think are 'hard enough' isn't helpful. Please keep your elitism out of Code Review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T18:24:25.753",
"Id": "454938",
"Score": "1",
"body": "@Alexander I wrote this function fully aware that it will not be compatible for all characters and instead could have used the ```toupper()``` and ```tolower()``` functions. I am mainly interested in the performance of using bit shifting directly as well as my coding methodologies such as if I should be checking if an array is empty or simply the naming conventions and style. I do 100% agree that it would be easier to use the functions mentioned above."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T18:28:10.610",
"Id": "454939",
"Score": "3",
"body": "@Peilonrayz Wasn't elitism, though I was quite blunt, which I would edit if I could. IMO, beginner materials gloss too much over unicode correctness (read: supporting anything that isn't english, which is most of the world)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T16:43:23.293",
"Id": "455018",
"Score": "1",
"body": "I wouldn't call what you're doing \"bit shifting\". There a shift operator `<<` used with a constant, so it doesn't count. I guess the right name is \"bitwise\" operations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T17:24:19.963",
"Id": "455031",
"Score": "0",
"body": "@maaartinus Thinking about it now, I agree since I am not really shifting any bits as you mentioned. Thanks for the heads up."
}
] |
[
{
"body": "<p>You code is pretty nice, but still, there are improvements.</p>\n\n<p>Each time in the inner loop, your code unnecessarily runs <code>value[0] &= (~(1 << 5));</code> for <code>value.size()</code> times. That would take unnecessary time. Running it once should be enough. </p>\n\n<p>This would be the code after the improvements. </p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>vector<string> ToProperCase(vector<string>& array)\n{\n if (array.empty())\n return array;\n\n for (string& value : array)\n {\n if(value == \"\")\n continue;\n\n value[0] &= ~(1 << 5);\n\n for (unsigned int i = 1; i < value.size(); ++i)\n value[i] |= (1 << 5);\n }\n\n return array;\n}\n</code></pre>\n\n<p>Also, you can use <code>toupper()</code> and <code>tolower()</code> instead, though I'm not sure if they are faster.</p>\n\n<p>If I find anymore improvements, I'll be sure to edit them in!</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>If you want your code to be really fast, you can use map to store all the alphabets, but that would reduce the neatness of the code. It's your wish!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T08:02:22.720",
"Id": "454887",
"Score": "4",
"body": "You migth use range based for in the second loop as well. toupper/tolower are probably not faster, but that's because they are actually handling all cases properly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T10:46:38.310",
"Id": "454901",
"Score": "0",
"body": "Thank you for review. In regards to the toupper() and tolower(), I didn't use them intentionally as I wanted to implement the conversion without the use of a function and at the same time get a better idea of how they bit shifting works. In addition, as @slepic mentioned, the functions take into account all types of variables such as characters form different languages and I would not be surprised if they were slower."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T10:55:54.523",
"Id": "454903",
"Score": "1",
"body": "Just out of curiosity, but if possible, can you please tell me what the average time taken now? Thanks :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T18:33:07.573",
"Id": "454942",
"Score": "0",
"body": "@Srivaths The same exact code replaced with the functions is an average of 80 microseconds which around 60 more than by simply using bit shifting on my system. A slight increase but still fast considering that it supports international characters."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T18:38:26.467",
"Id": "454944",
"Score": "0",
"body": "Oh, but what if `toupper` and `tolower` is not used, but the code is replaced with mine. How much timw does it take then? (Sorry to nag, but my PC is slow, so the time might not be accurate)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T18:56:21.697",
"Id": "454948",
"Score": "0",
"body": "@Srivaths With the changes you recommended, around 2-3 microsecond quicker for sure since it does not have to evaluate ```value[0] &= ~(1 << 5)``` for every character."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T05:21:59.103",
"Id": "232844",
"ParentId": "232843",
"Score": "6"
}
},
{
"body": "<pre><code>std::vector<std::string> ToProperCase(std::vector<std::string>& array)\n{\n // ...\n return array;\n}\n</code></pre>\n\n<p><strike>There are many styles when it comes to capitalization. <code>ToProperCase</code> should have a better name to indicate what the function does, which is to capitalize the first letter of each word.</strike></p>\n\n<p><code>array</code> is a non-local reference being returned by value. Is this intended?</p>\n\n<hr>\n\n<pre><code> if (array.empty())\n return array;\n\n // Loop through each word\n for (std::string& value : array)\n</code></pre>\n\n<p>While compilers will optimize it, the early <code>return</code> is unnecessary. The range-based <code>for</code> will check to see if <code>array</code> is empty. If it is, the function will <code>return array</code>.</p>\n\n<p>Don't say in comments what can be clearly stated in code. Rather than using variable names like <code>array</code> and <code>value</code>, omit the comment and use <code>words</code> and <code>word</code> respectively. Reserve comments to concisely state intent and keep them crisp.</p>\n\n<pre><code> // Loop through each character in the word\n for (unsigned int i = 0; i < value.size(); ++i)\n {\n // Capitalise first character\n value[0] &= (~(1 << 5));\n\n // Convert character to lower case\n if (i > 0)\n value[i] |= (1 << 5);\n }\n }\n</code></pre>\n\n<p>What is the proper case of a digit? Punctuation? Control characters? Should you be mutating non-alpha characters?</p>\n\n<p>You do more work than necessary here. For every character in the word, you bitwise-and the first character then bitwise-or the current character. You can unswitch the body of the innermost loop by handling the first character before every subsequent character.</p>\n\n<pre><code> for (auto& word : words)\n {\n if (word.empty()) continue;\n\n word[0] = std::toupper(static_cast<unsigned char>(word[0]));\n\n for (auto i = 1u; i < word.size(); ++i) \n {\n word[i] = std::tolower(static_cast<unsigned char>(word[i]));\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T19:18:49.800",
"Id": "454952",
"Score": "0",
"body": "Thanks for the review. One question I wanted to ask is although there are many different capitalisations, doesn't 'proper case' indicated by default that the first letter in each word will be capitalised?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T19:26:13.013",
"Id": "454956",
"Score": "3",
"body": "@ZOulhad I don't think what you're doing here is any kind of actual, real-world capitalization, it's certainly not one I would call \"proper\". I assume what you actually want to implement would be [title case](https://apastyle.apa.org/style-grammar-guidelines/capitalization/title-case), which capitalizes more words than your normal sentence casing but by no means all. Might make a good next training program."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T19:50:39.360",
"Id": "454958",
"Score": "0",
"body": "I went ahead and striked the naming of the function. Apparently \"proper case\" is an appropriate variation of title casing. TIL."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T19:53:59.943",
"Id": "454959",
"Score": "0",
"body": "@Snowhawk Wouldn't that make it worse since the implemented function is not any form of title case I'm aware of? (There are variations of title case with everybody and their dog using slightly different versions, but \"capitalize every word\" is not one I can imagine anyone's using)\\"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T20:00:17.513",
"Id": "454960",
"Score": "2",
"body": "@Voo I asked a friend about it right before I struck it and she mentioned that Oracle refers to the action as proper casing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T20:04:28.550",
"Id": "454961",
"Score": "0",
"body": "@Snowhawk Indeed: [Reference I found online](https://www.oracle.com/webfolder/technetwork/data-quality/edqhelp/Content/processor_library/transformation/proper_case.htm). Nothing new under the sun."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T11:23:58.327",
"Id": "232855",
"ParentId": "232843",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "232855",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T05:00:02.550",
"Id": "232843",
"Score": "9",
"Tags": [
"c++",
"performance",
"bitwise",
"vectors"
],
"Title": "Proper Case Conversion (Performance)"
}
|
232843
|
<p>The following code is of a quiz. Is there any way to generalize the code further?</p>
<p>Example: If lifelines are used once, I've to a copy the code check the correct user each time. the same is for skipping. Is there any way to improve it?</p>
<pre><code>instructions = ''' Welcome to Py Quiz\n
1. Each Question Carries 25k Rupees.Totally 11 questions\n
2. One lifeline is allotted for the entire quiz.Lifelines and be used by entering 'help'\n
a) Double Dip [ Player will be given a second chance for answering ]\n
Important Note:Please DO NOT USE ANY OTHER KEYS OTHER THAN SPECIFIED\n
3. Incorrect answer in any question will lead to losing the entire game\n
4. Enjoy The Game\n'''
print(instructions)
name = input("Enter your name\n")
print(f"\n\nHi {name}!! Welcome to Py Quiz\nBest of Luck!!\n")
d = {}
points = 0
count=1
quiz = [
{
"question": "Which one of these is floor division?",
"options": ["//", "%", "/", "None of the above"],
},
{
"question": "Who played the role of 'Iron Man' in The Avengers series ?",
"options": ['Robert Downey,Jr', "Chris Evans", "Chris Hemsworth", "Brie Larson"],
},
{
"question": "Of the 26 World Heritage Sites identified by UNESCO in India, how many are in Karnataka?",
"options": ['2', "5", "3", "1"],
},
{
"question": "Which of these is India’s only supersonic cruise missile?",
"options": ['BrahMos', "Agni V", "Prithvi II", "Chandrayaan"],
},
{
"question": "Which of these scientists was inspired to make his famous discovery while on a sea voyage, in 1921?",
"options": ['C V Raman', "Srinivasa Ramanujan", "Albert Einstien", "Nikola Tesla"],
},
{
"question": "Which team won the first IPL(Indian Premier League) title in the year 2008?",
"options": ['Rajasthan Royals', "Chennai Super Kings", "Mumbai Indians", "Deccan Chargers"],
},
{
"question": "By which other name do we popularly know the Hertzian wave as?",
"options": ['Radio Waves', "Sound Waves", "Matter Waves", "Light Waves"],
},
{
"question": "What is the shape of the pupil of a goat’s eye?",
"options": ['Rectangular', 'V-Shaped', "Elliptical", "Circular"],
},
{
"question": "Who was the first actor to get Oscar Award",
"options": ['Janet Gayner', "Charlie Chaplin", "Fairbanks", "Montgomery"],
},
{
"question": "Beighton cup is associated with",
"options": ['Hockey', "Volly Ball", "Rugby", "Baseball"],
},
{
"question": "The Paithan (Jayakwadi) Hydro-electric project, completed with the help of Japan, is on the river",
"options": ['Godavari', "Narmada", "Kaveri", "Ganga"],
},
]
def double_dip():
limit=1
global points
while limit < 2:
user_input = input("Enter the option\n> ")
if options[int(user_input) - 1] == d["options"][0]:
# Answer is correct
points += 25000
print(f"Correct\n{name} has scored: {points} Rupees")
else:
# Answer is incorrect
print(f"Wrong\n")
limit += 1
print("Enter 1 to Start the quiz")
start = input()
Wrong = False
while start != '1':
print(f"Invalid input: {start}")
print("Enter 1 to Start the quiz")
start = input()
if start == '1':
for question_number, d in enumerate(quiz, 1):
question = d["question"]
options = sorted(d["options"])
print(f"\n#{question_number}: {question}")
for option_no, o in enumerate(options, 1):
print(f"{option_no}: {o}")
while True:
user_input = input("Enter the option\n> ")
# Valid input
if user_input.isdecimal() and int(user_input) in list(range(1, len(options) + 1)):
# Check answer
if options[int(user_input) - 1] == d["options"][0]:
# Answer is correct
points += 25000
print(f"Correct\n{name} has scored: {points} Rupees")
break
else:
# Answer is incorrect
print(f"Wrong\n{name} has scored: {points} Rupees")
Wrong = True
break
elif user_input == 'help':
print(f"Double Dip Activated")
if count==1:
a = double_dip()
elif count!=1:
print(f"No Lifelines available")
user_input = input("Enter the option\n> ")
# Valid input
if user_input.isdecimal() and int(user_input) in list(range(1, len(options) + 1)):
# Check answer
if options[int(user_input) - 1] == d["options"][0]:
# Answer is correct
points += 25000
print(f"Correct\n{name} has scored: {points} Rupees")
break
else:
# Answer is incorrect
print(f"Wrong\n{name} has scored: {points} Rupees")
Wrong = True
break
break
count += 1
elif user_input== 'skip':
print(f"{name} Are you sure you want to skip a Question\n")
q_input=input(f"Press Y for Yes\nPress N for No\n")
if q_input=='Y'or 'y':
print(f"{name} has scored: {points} Rupees\n")
break
elif q_input=='N'or 'n':
user_input = input("Enter the option\n> ")
# Valid input
if user_input.isdecimal() and int(user_input) in list(range(1, len(options) + 1)):
# Check answer
if options[int(user_input) - 1] == d["options"][0]:
# Answer is correct
points += 25000
print(f"Correct\n{name} has scored: {points} Rupees")
break
else:
# Answer is incorrect
print(f"Wrong\n{name} has scored: {points} Rupees")
Wrong = True
break
else:
print(f"Invalid User input {q_input}\n")
else:
print(f"Invalid input: {user_input}\n{name} has scored: {points} Rupees")
Wrong = True
break
# Breaking loop if answer is incorrect
if Wrong:
break
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T09:59:52.513",
"Id": "454895",
"Score": "0",
"body": "Why should any other option be compared with the 1st one: `if options[int(user_input) - 1] == d[\"options\"][0]:` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T11:25:30.553",
"Id": "454907",
"Score": "0",
"body": "Because d['options'][0] is the correct answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T15:08:01.000",
"Id": "454917",
"Score": "0",
"body": "For future questions, the title should indicate what the code does, and not what you want to get out of the question. A good title might be `Quiz`."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T06:58:15.917",
"Id": "232846",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"quiz"
],
"Title": "Quiz with lifelines"
}
|
232846
|
<p>My first Elm program.</p>
<p>Nineagram is a puzzle that appears in the local newspaper. Given the nine letters for the day, the task is to come up with two five-letter words that share the same middle letter.</p>
<p>Example: <code>efiimlrtu</code> has at least one solution of...</p>
<pre class="lang-none prettyprint-override"><code> f
e
l i m i t
u
r
</code></pre>
<p>This program is an aid to the solver - you can enter guesses at the first word one at a time. The program will display the remaining letters that would be used for the second word. If a guess could form a solution with one or more of the previous guesses, the guess is displayed in the solutions list along with the other matching word(s).</p>
<p>Example of a players guesses and final program output:</p>
<pre class="lang-none prettyprint-override"><code>Guesses:
lemur - fiit
mitre - filu
unlit - Invalid guess!
rifle - imtu
limit - efru
mufti - eilr
femur - iilt
Solutions:
rifle (mufti)
limit (femur)
mufti (rifle)
femur (limit)
</code></pre>
<pre class="lang-hs prettyprint-override"><code>module Main exposing (Guess, Model, Msg(..), Nineagram, init, main, update, view)
import Browser
import Html exposing (Attribute, Html, button, div, input, li, text, ul)
import Html.Attributes exposing (..)
import Html.Events exposing (onClick, onInput)
-- MAIN
main =
Browser.sandbox { init = init, update = update, view = view }
-- MODEL
type alias Model =
{ nineagram : Nineagram
, guesses : List Guess
, newguess : Guess
, newLetters : String
}
type alias Nineagram =
{ letters : List Char
}
type alias Guess =
String
init : Model
init =
{ nineagram = { letters = [] }
, guesses = []
, newguess = ""
, newLetters = ""
}
remainingLetters : Nineagram -> Guess -> Maybe (List Char)
remainingLetters nineagram guess =
removeLetters (String.toList guess) nineagram.letters
removeLetters : List Char -> List Char -> Maybe (List Char)
removeLetters lettersToRemove input =
case lettersToRemove of
[] ->
Just input
letterToRemove :: remainingLettersToRemove ->
case removeLetter letterToRemove input of
Nothing ->
Nothing
Just inputWithLetterRemoved ->
removeLetters remainingLettersToRemove inputWithLetterRemoved
removeLetter : Char -> List Char -> Maybe (List Char)
removeLetter letter input =
case input of
[] ->
Nothing
x :: rest ->
if letter == x then
Just rest
else
case removeLetter letter rest of
Nothing ->
Nothing
Just remainingInput ->
Just ([ x ] ++ remainingInput)
type ValidatedGuess
= ValidGuess Guess (List Char)
| InvalidGuess Guess
validateGuess : Guess -> Nineagram -> ValidatedGuess
validateGuess guess nineagram =
if List.length (String.toList guess) /= 5 then
InvalidGuess guess
else
case remainingLetters nineagram guess of
Nothing ->
InvalidGuess guess
Just letters ->
ValidGuess guess letters
hasSolutions : Nineagram -> List Guess -> Guess -> Bool
hasSolutions nineagram guesses guess =
guesses |> List.any (\otherguess -> guess |> isSolution nineagram otherguess)
solutions : Nineagram -> List Guess -> Guess -> List Guess
solutions nineagram guesses guess =
guesses |> List.filter (\otherguess -> guess |> isSolution nineagram otherguess)
isSolution : Nineagram -> Guess -> Guess -> Bool
isSolution nineagram guess otherguess =
if guess == otherguess || getMiddleLetter guess /= getMiddleLetter otherguess then
False
else
case nineagram.letters |> removeLetters (String.toList guess) of
Nothing ->
False
Just letters ->
case letters |> removeLetters (removeMiddleLetter (String.toList otherguess)) of
Nothing ->
False
Just [] ->
True
Just _ ->
False
getMiddleLetter : Guess -> List Char
getMiddleLetter guess =
guess
|> String.toList
|> List.take 3
|> List.drop 2
removeMiddleLetter : List Char -> List Char
removeMiddleLetter guess =
(guess |> List.take 2) ++ (guess |> List.drop 3)
-- UPDATE
type Msg
= TypingGuess String
| SubmitGuess String
| TypingLetters String
| SubmitLetters String
update : Msg -> Model -> Model
update msg model =
case msg of
SubmitGuess newGuess ->
{ model | guesses = model.guesses ++ [ newGuess ] }
TypingGuess typing ->
{ model | newguess = typing }
TypingLetters typing ->
{ model | newLetters = typing }
SubmitLetters newLetters ->
{ model | nineagram = { letters = String.toList newLetters } }
-- VIEW
view : Model -> Html Msg
view model =
case model.nineagram.letters of
[] ->
div []
[ div []
[ input [ placeholder "Nineagram letters", onInput TypingLetters ] []
, button [ onClick (SubmitLetters model.newLetters) ] [ text "Submit" ]
]
]
_ ->
div []
[ div []
[ text (String.fromList model.nineagram.letters)
, input [ placeholder "Guess", value model.newguess, onInput TypingGuess ] []
, button [ onClick (SubmitGuess model.newguess) ] [ text "Submit" ]
]
, div []
[ text "Guesses:"
, ul [] (List.map (\guess -> li [] [ viewGuess model.nineagram guess ]) model.guesses)
]
, div []
[ text "Solutions:"
, viewSolutions model.nineagram model.guesses
]
]
viewSolutions : Nineagram -> List Guess -> Html Msg
viewSolutions nineagram guesses =
ul []
(guesses
|> List.map
(\guess ->
case validateGuess guess nineagram of
ValidGuess _ _ ->
if guess |> hasSolutions nineagram guesses then
li [] [ text (guess ++ " (" ++ (guess |> solutions nineagram guesses |> String.join ", ") ++ ")") ]
else
text ""
InvalidGuess _ ->
text ""
)
)
viewGuess : Nineagram -> Guess -> Html msg
viewGuess nineagram guess =
case validateGuess guess nineagram of
InvalidGuess invalidGuess ->
div [] [ text (invalidGuess ++ " - " ++ "Invalid guess!") ]
ValidGuess validGuess letters ->
div [] [ text (validGuess ++ " - " ++ String.fromList letters) ]
</code></pre>
<p>I'm looking for advice on how to make it more idiomatic.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T08:45:00.627",
"Id": "232851",
"Score": "1",
"Tags": [
"elm"
],
"Title": "Nineagram puzzle aid in Elm"
}
|
232851
|
<p>I've created a program for Banking System in C++14.</p>
<p>You are given 9 options:</p>
<ol>
<li>Open Account</li>
<li>Close Account</li>
<li>Show All Accounts</li>
<li>Deposit in Account</li>
<li>Withdraw from Account</li>
<li>Transfer to an Account</li>
<li>Show Balance</li>
<li>Show All Transactions</li>
<li>Quit</li>
</ol>
<p>My program stores the deposits, and withdrawals, and transfers in a a file and uses them when the program is run again.</p>
<p><strong><em>Note:</em></strong> The currency is in Indian rupees.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <string>
#include <vector>
#include <fstream>
#include <iostream>
using namespace std;
int MAX = 9999999999;
class Account
{
private:
static int CurAccNo;
bool open = true;
int AccNo = ++CurAccNo;
double balance = 0;
string gender = "N/A";
string first_name, second_name;
public:
Account(){}
Account(string, string, int);
void deposit(double);
void withdraw(double);
void transfer(Account, double);
static void setCurAccNo(int No){
if(No > 0)
CurAccNo = No;
}
int getAccNo();
double getBalance();
string getGender();
string getFirstName();
string getSecondName();
void setBalance(double);
void setGender(string);
void setFirstName(string);
void setSecondName(string);
void close();
bool isOpen();
friend istream& operator >> (istream& in, Account &acc);
friend ostream& operator << (ostream& out, Account &acc);
friend ifstream& operator >> (ifstream& in, Account &acc);
friend ofstream& operator << (ofstream& out, Account &acc);
};
int Account::CurAccNo = 0;
Account::Account(string first_name, string second_name, int initial_balance)
{
setFirstName(first_name);
setSecondName(second_name);
balance = initial_balance;
}
void Account::deposit(double value){balance += value;}
void Account::withdraw(double value){balance -= value;}
void Account::transfer(Account other, double value){balance -= value ;other.balance += value;}
int Account::getAccNo(){return AccNo;}
double Account::getBalance(){return balance;}
string Account::getGender(){return gender;}
string Account::getFirstName(){return first_name;}
string Account::getSecondName(){return second_name;}
void Account::setBalance(double balance){if(balance >= 0) this -> balance = balance;}
void Account::setGender(string gender){if(gender == "M" || gender == "F") this -> gender = gender;}
void Account::setFirstName(string first_name){if(first_name != "") this -> first_name = first_name;}
void Account::setSecondName(string second_name){if(second_name != "") this -> second_name = second_name;}
void Account::close(){open = false;}
bool Account::isOpen(){return open;}
istream& operator >> (istream& in, Account &acc){
string first_name, second_name;
string gender;
double balance;
cout << "Enter First Name: "; cin >> first_name;
cout << "Enter Second Name: "; cin >> second_name;
cout << "Enter Gender (M / F): "; cin >> gender;
cout << "Enter Initial Balance: "; cin >> balance;
acc.setFirstName(first_name);
acc.setSecondName(second_name);
acc.setGender(gender);
acc.setBalance(balance);
return in;
}
ostream& operator << (ostream& out, Account &acc){
out << "First Name: " << acc.getFirstName() << endl;
out << "Second Name: " << acc.getSecondName() << endl;
out << "Gender: " << acc.getGender() << endl;
out << "Current Balance: " << acc.getBalance() << endl;
out << "Account Number: " << acc.getAccNo() << endl;
out << "Status: " << (acc.isOpen()? "Open" : "Closed") << endl;
return out;
}
ifstream& operator >> (ifstream& in, Account &acc){
string first_name, second_name;
string gender;
int AccNo; bool open;
double balance;
in >> first_name >> second_name;
in >> gender;
in >> balance >> AccNo;
in >> open;
acc.setFirstName(first_name);
acc.setSecondName(second_name);
acc.setGender(gender);
acc.setBalance(balance);
acc.open = open;
acc.AccNo = AccNo;
return in;
}
ofstream& operator << (ofstream& out, Account &acc){
out << acc.getFirstName() << endl;
out << acc.getSecondName() << endl;
out << acc.getGender() << endl;
out << acc.getBalance() << endl;
out << acc.getAccNo() << endl;
out << acc.isOpen();
return out;
}
bool isEmpty(ifstream& pFile)
{
return pFile.peek() == ifstream::traits_type::eof();
}
bool Valid(unsigned int AccNo, vector<Account> Accounts){
if(AccNo <= Accounts.size() && AccNo > 0 && Accounts[AccNo].isOpen())
return true;
return false;
}
int main()
{
vector<Account> Accounts;
ofstream otrans("Transactions.txt", ios::app);
ofstream ofs("BankingSystem.txt", ios::app);
ifstream ifs("BankingSystem.txt");
vector<int> AccNos;
vector<string> types;
vector<double> values;
while(!ifs.eof() && !isEmpty(ifs)){
Account acc;
ifs >> acc;
Accounts.push_back(acc);
}
Account::setCurAccNo(Accounts.size());
while(true){
cout << "|=============================|" << endl;
cout << "| WELCOME TO |" << endl;
cout << "| RANDOM BANK |" << endl;
cout << "|=============================|" << endl;
cout << endl;
cout << "What Would You Like To Do?:" << endl;
cout << " 1. Open Account" << endl;
cout << " 2. Close Account" << endl;
cout << " 3. Show All Accounts" << endl;
cout << " 4. Deposit in Account" << endl;
cout << " 5. Withdraw in Account" << endl;
cout << " 6. Transfer to an Account" << endl;
cout << " 7. Show Balance" << endl;
cout << " 8. Show All Transactions" << endl;
cout << " 9. Quit" << endl;
cout << endl;
string option;
cout << "Please Enter Your Option: "; cin >> option;
if(option == "1"){
Account acc;
cin >> acc;
if(Accounts.size() != 0)
ofs << endl;
Accounts.push_back(acc);
ofs << acc;
cout << "Account Opened Successfully!" << endl;
cout << "Your Account Number is " << acc.getAccNo() << endl;
}
else if(option == "2"){
int AccNo;
cout << "Enter Account Number: "; cin >> AccNo;
AccNo--;
if(Valid(AccNo, Accounts)){
cout << "Account Closed Successfully!" << endl;
Accounts[AccNo].close();
}
else
cout << "There Was an Error, Please Try Again!" << endl;
}
else if(option == "3"){
cout << endl;
for(unsigned int i = 0; i < Accounts.size(); i++)
cout << Accounts[i] << endl;
}
else if(option == "4"){
int AccNo;
double value;
cout << "Enter Account Number: "; cin >> AccNo;
cout << "Enter Deposit Amount: "; cin >> value;
AccNo--;
if(Valid(AccNo, Accounts)){
if(value < MAX){
cout << value << " Deposited to " << Accounts[AccNo].getFirstName() << "'s Account Successfully!" << endl;
Accounts[AccNo].deposit(value);
cout << "Balance is " << Accounts[AccNo].getBalance() << endl;
AccNos.push_back(AccNo);
types.push_back("Deposit");
values.push_back(value);
}
else
cout << "Overflow!" << endl;
}
else
cout << "There Was an Error, Please Try Again!" << endl;
}
else if(option == "5"){
int AccNo;
double value;
cout << "Enter Account Number: "; cin >> AccNo;
cout << "Enter Withdrawal Amount: "; cin >> value;
AccNo--;
if(Valid(AccNo, Accounts)){
if(Accounts[AccNo].getBalance() - value >= 0){
cout << value << " Withdrawn from " << Accounts[AccNo].getFirstName() << "'s Account Successfully!" << endl;
Accounts[AccNo].withdraw(value);
cout << "Balance is " << Accounts[AccNo].getBalance() << endl;
AccNos.push_back(AccNo);
types.push_back("Withdrawal");
values.push_back(value);
}
else
cout << "Not Enough Balance" << endl;
}
else
cout << "There Was an Error, Please Try Again!" << endl;
}
else if(option == "6"){
int AccNo, AccNoOther;
double value;
cout << "Enter Account Number: "; cin >> AccNo;
cout << "Enter Other Account Number: "; cin >> AccNoOther;
cout << "Enter Transfer Amount: "; cin >> value;
AccNo--;
if(Valid(AccNo, Accounts) && Valid(AccNoOther, Accounts)){
if(Accounts[AccNoOther].getBalance() + value > MAX)
cout << "Overflow" << endl;
else {
if(Accounts[AccNo].getBalance() - value >= 0){
cout << value << " Transfer to " << Accounts[AccNoOther].getFirstName() << "'s Account Successfully!" << endl;
Accounts[AccNo].transfer(Accounts[AccNoOther], value);
cout << Accounts[AccNo].getFirstName() << "'s Balance is " << Accounts[AccNo].getBalance() << endl;
cout << Accounts[AccNoOther].getFirstName() << "'s Balance is " << Accounts[AccNo].getBalance() << endl;
}
else
cout << "Not Enough Balance" << endl;
}
}
else
cout << "There Was an Error, Please Try Again!" << endl;
}
else if(option == "7"){
int AccNo;
cout << "Enter Account Number: "; cin >> AccNo;
AccNo--;
cout << endl;
if(Valid(AccNo, Accounts))
cout << Accounts[AccNo];
else
cout << "There Was an Error, Please Try Again!" << endl;
}
else if(option == "8"){
int AccNo;
cout << "Enter Account Number: "; cin >> AccNo;
AccNo--;
if(Valid(AccNo, Accounts)){
ifstream itrans("Transactions.txt");
vector<double> deposits;
vector<double> withdrawals;
string x = "Deposits";
while(!itrans.eof() && !isEmpty(itrans)){
int TransAcc;
string type;
double value;
itrans >> TransAcc >> type >> value;
if(TransAcc == AccNo){
if(type == "Deposit")
deposits.push_back(value);
if(type == "Withdrawal")
withdrawals.push_back(value);
}
}
for(unsigned int i = 0; i < AccNos.size(); i++){
int TransAcc = AccNos[i];
string type = types[i];
double value = values[i];
if(TransAcc == AccNo){
if(type == "Deposit")
deposits.push_back(value);
if(type == "Withdrawal")
withdrawals.push_back(value);
}
}
cout << "=======================================" << endl;
cout << "Withdrawal | Deposits" << endl;
cout << "=======================================" << endl;
cout << endl;
for(unsigned int i = 0; i < max(deposits.size(), withdrawals.size()); i++){
int s = 0;
if(i < withdrawals.size()){
string x = to_string(withdrawals[i]);
cout << x;
s = x.size();
}
string x = "Deposits ";
for(unsigned int _ = 0; _ < x.size() - s; _++)
cout << " ";
cout << "| ";
if(i < deposits.size()){
string x = to_string(deposits[i]);
cout << x;
}
cout << endl;
}
}
else
cout << "There Was an Error, Please Try Again!" << endl;
}
else if(option == "9"){
break;
}
else {
cout << "Please Enter a Valid Option" << endl;
}
cout << endl;
system("pause");
system("cls");
}
ofstream ofsn("BankingSystem.txt");
for(unsigned int i = 0; i < Accounts.size(); i++){
if(i != 0)
ofsn << "\n";
ofsn << Accounts[i];
}
for(unsigned int i = 0; i < AccNos.size(); i++){
if(i != 0)
otrans << "\n";
otrans << AccNos[i] << " " << types[i] << " " << values[i] << endl;
}
}
</code></pre>
<p>It works as expected to my knowledge. I would like to improve this as much as possible. Also, tips for adding more functions to the System are welcome.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T10:20:12.913",
"Id": "454896",
"Score": "4",
"body": "Maybe unrelated, but why would an (banking) `Account` need information about `gender`??"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T10:22:00.603",
"Id": "454897",
"Score": "0",
"body": "@πάνταῥεῖ Actually, this was an exercise by an online tutor. He gave this as a challenge. Don't know why, but `gender` was also asked to be taken as an input."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T01:06:54.377",
"Id": "455052",
"Score": "0",
"body": "At least in some countries every person is assigned a personal identification number where some part of it is actually a checksum making it harder to make up a fake one. And gender is part of this checksum calculation at least in Poland. The banking system needs the information about gender to detect invalid personal identification number."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T09:19:37.227",
"Id": "455071",
"Score": "0",
"body": "What about the currency? So if amount is displayed \"11.20\" means 11$ and 20 cents? What prevents people to withdraw less than/fractions of a cent in e.g. case 5?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T16:59:39.753",
"Id": "455135",
"Score": "1",
"body": "@lalala Actually, this is based on Indian rupees. You don't have denominations < `0.1`. Sorry to have confused you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T18:21:57.033",
"Id": "455145",
"Score": "0",
"body": "No worries. So what prevents people from withdrawing 0.5 in your software?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T19:37:40.127",
"Id": "455157",
"Score": "0",
"body": "If this is going to be run concurrently that's going to cause some problems."
}
] |
[
{
"body": "<h3>Don't abuse <code>using namespace std</code></h3>\n<p>Putting <code>using namespace std</code> at the top of every program is <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">a bad habit</a> that you'd do well to avoid.</p>\n<h3>Implement <code>operator<<</code> and <code>operator>></code> regardless of terminal or file input</h3>\n<p>The only implementations you should have are</p>\n<pre><code>friend istream& operator >> (istream& in, Account &acc);\nfriend ostream& operator << (ostream& out, const Account &acc);\n // ^^^^^ Note the const here\n</code></pre>\n<p>Mixing the text extraction operators with <code>std::cin</code> as you do here</p>\n<pre><code>istream& operator >> (istream& in, Account &acc){\n string first_name, second_name;\n string gender;\n double balance;\n\n cout << "Enter First Name: "; cin >> first_name;\n cout << "Enter Second Name: "; cin >> second_name;\n cout << "Enter Gender (M / F): "; cin >> gender;\n cout << "Enter Initial Balance: "; cin >> balance;\n\n acc.setFirstName(first_name);\n acc.setSecondName(second_name);\n acc.setGender(gender);\n acc.setBalance(balance);\n\n return in;\n}\n</code></pre>\n<p>restricts reusability and is a bad implementation.</p>\n<p>Rather use the setters, or appropriate constructors for such case.</p>\n<p>Also the implementation of <code>friend ofstream& operator << (ofstream& out, const Account &acc);</code></p>\n<p>is redundant. <code>friend ostream& operator << (ostream& out, const Account &acc);</code> will already work for any kinf of <code>std::ostream</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T10:41:27.230",
"Id": "232854",
"ParentId": "232852",
"Score": "6"
}
},
{
"body": "<h2>Missing Header Include</h2>\n<p>This code should have</p>\n<pre><code>#include <algorithm>\n</code></pre>\n<p>So that the call to <code>max()</code> will compile.</p>\n<h2>Symbolic Constants</h2>\n<p>The declaration for MAX makes it a variable rather than a constant, that means that it could be changed within the code. It might be better if it was declared as a constant</p>\n<pre><code>constexpr int MAX = 9999999999;\n</code></pre>\n<p>so that the code can't change it.</p>\n<h2>Avoid <code>using namespace </code>std`</h2>\n<p>As stated in another review if you are coding professionally you should get out of the habit of using the <code>using namespace std;</code> statement. The code will more clearly define where <code>cout</code> and other identifiers are coming from (<code>std::cin</code>, <code>std::cout</code>). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The identifier<code>cout</code> you may override within your own classes, and you may override the operator <code><<</code> in your own classes as well.</p>\n<h2>Put Classes in Their Own Files</h2>\n<p>One of the basic reasons for Object Oriented Programming is that objects are reusable, however, if the object is defined in the same file as <code>main()</code> it can't be reused or shared between modules. Most C++ editors (IDEs) have a way to create classes that generate both a header file and a C++ source file for the class. Another reason for doing separating classes into their own files is that it makes building, writing, debugging, reading, maintaining and testing code easier. During build only files that have been edited will recompile.</p>\n<h2>Complexity</h2>\n<p>The function <code>main()</code> is too complex (does too much). As programs grow in size the use of <code>main()</code> should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.</p>\n<p>There is also a programming principle called the Single Responsibility Principle that applies here. The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"noreferrer\">Single Responsibility Principle</a> states:</p>\n<blockquote>\n<p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n<p>There are at least 10 possible functions in <code>main()</code>.</p>\n<ul>\n<li>Show Menu</li>\n<li>Get Option (calls show menu and returns the option)</li>\n<li>Open Account</li>\n<li>Close Account</li>\n<li>Deposit in Account</li>\n<li>Withdraw from Account</li>\n<li>Show All Accounts</li>\n<li>Transfer to an Account</li>\n<li>Show Balance</li>\n<li>Show All Transactions</li>\n</ul>\n<p>Quit is not a function because it only indicates that the while loop should end.</p>\n<p>Rather than use multiple <code>else if</code> to process the options, use a switch statement:</p>\n<pre><code> int option;\n cout << "Please Enter Your Option Number: "; cin >> option;\n\n switch (option)\n {\n case 1: \n OpenAccount();\n continue;\n case 2:\n CloseAccount();\n continue;\n case 3:\n ShowAllAccounts();\n continue;\n ...\n default:\n cerr << "Invalid option " << option << "please enter a valid option\\n";\n continue;\n }\n</code></pre>\n<p>There are conceptually other classes that could help implement the program, such as class <code>Bank</code> which would contain the accounts and the current account number to assign to an account. The current account number to assign does not belong in the Account class. The list of transactions belongs in the Account class because the user should not see any transactions that do not belong to them. There should also be a <code>Customer</code> class that contains the customer data name and gender. A customer may have several accounts.</p>\n<h2>Default Constructors</h2>\n<p>Rather than creating the default constructor as <code>Account(){}</code>, C++ allows you to assign a default constructor <code>Account() = default;</code> This is more readable.</p>\n<h2>Readability</h2>\n<p>There are a number of this that would improve the readability of the code, which would not only make it easier to review, but easier to maintain the code as well.</p>\n<ul>\n<li>Put all declarations on separate lines.</li>\n<li>Horizontal spacing.</li>\n<li>Use code blocks even for single statements within <code>if</code> statements, <code>then</code> clauses and loops.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T16:33:05.327",
"Id": "455128",
"Score": "0",
"body": "What is the proper way to store gender in 2019 actually would be an interesting discussion on its own. I am not sure the proper place to have it though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T16:36:22.757",
"Id": "455130",
"Score": "0",
"body": "@Chuu Gender would best be an enum, I think I mentioned that you need a customer class as well, and that would be where it belongs. A customer might also have a list of their accounts."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T17:20:22.070",
"Id": "232863",
"ParentId": "232852",
"Score": "6"
}
},
{
"body": "<h2>Overview</h2>\n\n<p>The code is OK.</p>\n\n<p>I found 1 bug.</p>\n\n<p>The encapsulation is slightly lacking. You have Account as a class, which is good, but the getters/setters are not required and you have better methods to interact with it.</p>\n\n<p>On encapsulation, you need to encapsulate a set of accounts and the \"next account number\" into a class (maybe Bank). Currently, you set up a vector of accounts and then have to remember to set the next highest account number back in Account.</p>\n\n<p>I dislike the way you get user interaction inside a stream operator (input). I would change that and use stream operators simply for that.</p>\n\n<p>Your main() needs to be broken up a bit to make the code a bit more self-documenting.</p>\n\n<p>I dislike how user input of the account number requires you to then subtract one from the account number before you can use it. This is going to lead to a maintainability error where somebody forgets to subtract one before using the value entered by the user.</p>\n\n<h2>Code Review</h2>\n\n<h3>Using namespace std is bad practice.</h3>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>See: <a href=\"https://stackoverflow.com/q/1452721/14065\">Why is “using namespace std;” considered bad practice?</a> </p>\n\n<p>The answers to this question go into a lot of detail about the subject. It is definitely a habit that is hard to break. But one that you should (as detailed in the answers to the above question).</p>\n\n<p>But I hear you ask \"Why do all books/articles always start with: <code>using namespace std;</code>?</p>\n\n<p>The answer is context. In a book and/or magazine article the primary purpose is not maintainability but space (or the lack of it). They are prioritizing for space while in real life (or a professional setting) we are prioritizing for maintainability.</p>\n\n<hr>\n\n<h3>Using Global Constant rather than define</h3>\n\n<p>This is a good start.</p>\n\n<pre><code>int MAX = 9999999999;\n</code></pre>\n\n<p>But from the context, it also looks like it should be const. Or if you have a C compiler that supports more modern language, <code>constexpr</code>.</p>\n\n<pre><code>int constexpr MAX = 9999999999;\n</code></pre>\n\n<p>In general, any globally accessible state should be non-mutable (unless you have a very good reason for it not to be).</p>\n\n<hr>\n\n<h3>Readability:</h3>\n\n<pre><code> string first_name, second_name;\n</code></pre>\n\n<p>Please, one variable per line. I have not come across a coding standard that does not emphasize this. We are not trying to win competitions on the least vertical space we can use. The whole point of using a high-level language is easier maintainability. One variable per line will help with that.</p>\n\n<pre><code> std::string first_name;\n std::string second_name;\n</code></pre>\n\n<hr>\n\n<h3>Avoid getter/setter</h3>\n\n<pre><code> int getAccNo();\n double getBalance();\n string getGender();\n string getFirstName();\n string getSecondName();\n\n void setBalance(double);\n void setGender(string);\n void setFirstName(string);\n void setSecondName(string);\n</code></pre>\n\n<p>These break encapsulation.</p>\n\n<p>Yes sure, it is better than making the variables public. But what are you trying to archive? Getters and setters are good for property bags (property bag => your class is just a set of unrelated objects being transported together) not for class objects where the state represents a thing.</p>\n\n<pre><code> a.setName(a.getName() + \" Tool\"); // Is this a valid use case?\n</code></pre>\n\n<p>If you have a function that retrieves the state, modifies the state, then puts the new state back, should that functionality not be a part of the class? This is why methods tend to be actions that are applied to the object.</p>\n\n<p>Like these methods:</p>\n\n<pre><code> void deposit(double);\n void withdraw(double);\n void transfer(Account, double);\n</code></pre>\n\n<p>These methods are great.</p>\n\n<p>If we analyze why you have getters and setters:</p>\n\n<p>Methods used for printing:</p>\n\n<pre><code> getBalance\n getGender\n getFirstName\n getSecondName\n</code></pre>\n\n<p>Methods used for passing in data:</p>\n\n<pre><code> setBalance\n setGender\n setFirstName\n setSecondName\n</code></pre>\n\n<p>Validating that an amount can be added/withdrawn:</p>\n\n<pre><code> getBalance\n</code></pre>\n\n<p>Used in constructor to validate input:</p>\n\n<pre><code> setBalance\n setFirstName\n setSecondName\n</code></pre>\n\n<p>So you have 8 functions but only 4 primary use cases. The validation done by the constructor is a bit primitive and may as well be done by the constructor. The output operator (printing should be a friend anyway) is part of the public API for the Account class. The input operator similarly should be part of the public API but can more efficiently use the constructor and a swap operator to achieve the same results.</p>\n\n<p>So I think the only valid use case is 'Validating that an amount can be added/withdrawn', which deserves its own method to make it clear what you are doing and the result of the action.</p>\n\n<p>I'll go into more detail below when I re-design the class. See below.</p>\n\n<hr>\n\n<h3>Avoid silently failing checks</h3>\n\n<p>The following appears to fail if no valid number is passed in:</p>\n\n<pre><code> static void setCurAccNo(int No){\n if(No > 0)\n CurAccNo = No;\n }\n</code></pre>\n\n<p>Silent failure is the enemy of all coders. Make this scream and holler on failure as something has gone wrong. I would throw an exception on failure to make the application quit.</p>\n\n<hr>\n\n<h3>Currency should be integers</h3>\n\n<p>When talking about representing money, doubles are a terrible way to go.</p>\n\n<pre><code> double getBalance();\n</code></pre>\n\n<p>The trouble is that they have rounding errors. You should use an integer value. If this is for American currency with dollars and cents then record the number of cents. When you display it you can convert to dollars by dividing by 100. But never store currency in a double.</p>\n\n<hr>\n\n<h3>Enum when you have a small subset of valid values</h3>\n\n<p>Is a gender a string?</p>\n\n<pre><code> string getGender();\n</code></pre>\n\n<p>Maybe this is my old world bias showing here. I am assuming a small number of known versions.</p>\n\n<p>What are you trying to store and why? Is it to help with fraud detection?</p>\n\n<p>The reason I would not use a string is that it allows too many variants which could look valid under programmer scrutiny but are not actually valid inputs for the system.</p>\n\n<pre><code> \"f\" or \"F\" or \"Female\" or \"female\" or \"FEMALE\"\n \"m\" or \"M\" or \"Male\" or \"male\" or \"MALE\" or \n etc\n</code></pre>\n\n<p>These would all look valid to casual inspection. I think a better option would be an enum.</p>\n\n<p>On the counter side of the argument would be the ability of the system to adapt to alternative gender types that had not been considered at the time the application was first written.</p>\n\n<hr>\n\n<h3>Stream formatting</h3>\n\n<p>You want a different type of streaming to normal streaming when printing to a file.</p>\n\n<pre><code> friend istream& operator >> (istream& in, Account &acc);\n friend ostream& operator << (ostream& out, Account &acc);\n\n friend ifstream& operator >> (ifstream& in, Account &acc);\n friend ofstream& operator << (ofstream& out, Account &acc);\n</code></pre>\n\n<p>This effect is normally achieved with formatters. The account object would always be treated the same when printed to a stream. <strong>Because</strong> just because what you have locally is a reference to a stream does not mean it is not a file stream. This decision is made at compile time (not runtime). So you can definitely get different behaviors than expected.</p>\n\n<p>To solve for this, you create \"Format\" objects which know how to format an account for a stream. You may have a \"pretty print\" format or a \"pine print\" format for printing to different types of forms, etc.</p>\n\n<pre><code> std::cout << PrettyPrintFormat(acc) << \"\\n\";\n file << LinePrintFormat(acc) << \"\\n\";\n</code></pre>\n\n<hr>\n\n<h3>Bug</h3>\n\n<p>Bug:</p>\n\n<pre><code>void Account::transfer(Account other, double value)\n{\n balance -= value ;\n other.balance += value;\n}\n</code></pre>\n\n<p>You are passing the account by value.<br>\nYou have modified the copy of the account, not the original account.</p>\n\n<hr>\n\n<h3>Don't use interactions when streaming.</h3>\n\n<p>Asking for user interaction as part of the streaming processes?</p>\n\n<pre><code>istream& operator >> (istream& in, Account &acc){\n string first_name, second_name;\n string gender;\n double balance;\n\n cout << \"Enter First Name: \"; cin >> first_name;\n cout << \"Enter Second Name: \"; cin >> second_name;\n cout << \"Enter Gender (M / F): \"; cin >> gender;\n cout << \"Enter Initial Balance: \"; cin >> balance;\n\n acc.setFirstName(first_name);\n acc.setSecondName(second_name);\n acc.setGender(gender);\n acc.setBalance(balance);\n\n return in;\n}\n</code></pre>\n\n<hr>\n\n<h3>Evil</h3>\n\n<p>Dastardly</p>\n\n<pre><code>bool isEmpty(ifstream& pFile)\n{\n return pFile.peek() == ifstream::traits_type::eof();\n}\n</code></pre>\n\n<p>You are subverting the primary pattern used by all other developers. This is going to lead to errors in the long run. Please stick to established patterns.</p>\n\n<p>This is where your dastardly pattern is used.</p>\n\n<pre><code> while(!ifs.eof() && !isEmpty(ifs)){\n Account acc;\n ifs >> acc;\n\n Accounts.push_back(acc);\n }\n</code></pre>\n\n<p>It doesn't read that poorly, but it still makes it look wrong as most people are not expecting <code>isEmpty()</code> to peek. As such, you are going to go make them check. But it still looks better if you use the normal pattern:</p>\n\n<pre><code> Account acc;\n while(ifs >> acc) {\n Accounts.push_back(acc);\n }\n</code></pre>\n\n<p>Also you can take this a step further. You don't even need the loop. Just initialize the account vector with iterators:</p>\n\n<pre><code> std::ifstream ifs(\"BankingSystem.txt\");\n std::vector<Account> Accounts(std::istream_iterator<Account>{ifs}, std::istream_iterator<Account>{});\n</code></pre>\n\n<p>Done. Standard patterns are nice.</p>\n\n<hr>\n\n<h3>return bool</h3>\n\n<p>The use of an if/then to return a bool.</p>\n\n<pre><code>bool func() {\n if (cond) {return true;}\n else {return false;}\n}\n</code></pre>\n\n<p>Can be simplified to:</p>\n\n<pre><code>bool func {return cond;}\n</code></pre>\n\n<p>So you can simplify this:</p>\n\n<pre><code>bool Valid(unsigned int AccNo, vector<Account> Accounts){\n if(AccNo <= Accounts.size() && AccNo > 0 && Accounts[AccNo].isOpen())\n return true;\n return false;\n}\n</code></pre>\n\n<hr>\n\n<h3>Encapsulation</h3>\n\n<p>Hmm:</p>\n\n<pre><code> Account::setCurAccNo(Accounts.size());\n</code></pre>\n\n<p>Forcing initialization of some global state independently of loading the state. This is a bug waiting to happen. Your account state and the next number need to be combined into their own class.</p>\n\n<pre><code> class Bank\n {\n // Some accounts.\n // Some state about the next valid bank account number.\n };\n</code></pre>\n\n<p>There is a dependency between <code>Accounts</code> and <code>Account::CurAccNo</code> you need to formalize and protect this dependency.</p>\n\n<hr>\n\n<h3>Prefer \"\\n\" over std::endl</h3>\n\n<p>Prefer <code>\"\\n\"</code> over <code>std::endl</code>.</p>\n\n<pre><code> while(true){\n cout << \"|=============================|\" << endl;\n cout << \"| WELCOME TO |\" << endl;\n cout << \"| RANDOM BANK |\" << endl;\n cout << \"|=============================|\" << endl;\n\n cout << endl;\n</code></pre>\n\n<p>Did you really want to force a flush after each line? Why? Don't do it. This is what leads to all the slowdowns in the C++ streams unnecessarily flushed by the engineer. The streams will always flush themselves at the correct time. You should only force a flush if you need to (unless you are very experienced and have done the tests to prove it).</p>\n\n<hr>\n\n<h3>Self-documenting code</h3>\n\n<p>Long switch (or multi-branch if/else) statements are a pain to read.</p>\n\n<p>This is where self-documenting code comes in. Each switch can call a function with a nice name so that you know what the option is doing.</p>\n\n<pre><code> if(option == \"1\"){\n Account acc;\n cin >> acc;\n\n if(Accounts.size() != 0)\n ofs << endl;\n\n Accounts.push_back(acc);\n ofs << acc;\n\n cout << \"Account Opened Successfully!\" << endl;\n cout << \"Your Account Number is \" << acc.getAccNo() << endl;\n }\n etc...\n\n // More like this:\n\n switch(option) {\n case 1: loadAccount(); break;\n case 2: closeAccount(); break;\n etc...\n</code></pre>\n\n<hr>\n\n<h3>Notes</h3>\n\n<pre><code> if(option == \"1\"){\n</code></pre>\n\n<p>This seems like the perfect place to ask those questions you put in the input operator.\n Account acc;<br>\n cin >> acc;</p>\n\n<hr>\n\n<h3>Range-based for loop</h3>\n\n<pre><code> else if(option == \"3\"){\n cout << endl;\n\n for(unsigned int i = 0; i < Accounts.size(); i++)\n cout << Accounts[i] << endl;\n</code></pre>\n\n<p>You might want to instead look at using a range-based for loop:</p>\n\n<pre><code> for(auto const& account: Accounts) {\n std::cout << account << \"\\n\";\n }\n</code></pre>\n\n<hr>\n\n<h1>Alternative</h1>\n\n<pre><code>#include <iomanip>\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <iterator>\n\nenum Action {BADAction, OpenAccount, CloseAccount, ShowAllAccounts, DepositInAccount, WithdrawFromAccount, TransferToAnAccount, ShowBalance, ShowAllTransactions, Quit};\n\nstd::istream& operator>>(std::istream& str, Action& action)\n{\n int value;\n if (str >> value && value >= 1 && value <= 9) {\n action = static_cast<Action>(value);\n }\n else {\n action = BADAction;\n }\n return str;\n}\nstd::ostream& operator<<(std::ostream& str, Action const& action)\n{\n return str << static_cast<int>(action);\n}\n\nclass AccountPrettyPrint;\nclass Account\n{\n // Pretty printing is tightly coupled to the\n // state of the class. So we are noting this\n // by making it a friend of the class.\n friend class AccountPrettyPrint;\n\n std::string firstName;\n std::string surName;\n int balance;\n bool open;\n int accountNo;\n\n public:\n Account();\n Account(std::string const& firstName, std::string const& surName, int balance);\n Account(Account const&) = default;\n Account(Account&&) = default;\n Account& operator=(Account const&) = default;\n Account& operator=(Account&&) = default;\n\n void swap(Account& other) noexcept;\n friend void swap(Account& lhs, Account& rhs) {lhs.swap(rhs);}\n friend std::ostream& operator<<(std::ostream& str, Account const& acc);\n friend std::istream& operator>>(std::istream& str, Account& acc);\n};\n\nstruct AccountPrettyPrint\n{\n Account const& acc;\n AccountPrettyPrint(Account const& acc): acc(acc) {}\n\n std::ostream& print(std::ostream& str) const\n {\n return str << \"Print Account Nicely: \" << acc.firstName << \"\\n\"\n << \" $\" << (acc.balance / 100)\n << \".\" << std::setw(2) << std::setfill('0') << (acc.balance % 100)\n << \"\\n\";\n }\n friend std::ostream& operator<<(std::ostream& str, AccountPrettyPrint const& pp)\n {\n return pp.print(str);\n }\n};\n\nclass Bank\n{\n static std::vector<Account> accounts;\n public:\n static int getNextAccountNumber() {return accounts.size();}\n static void loadAccount(std::string const& fileName);\n};\n\nAccount::Account()\n : balance(0)\n , open(false)\n , accountNo(-1)\n{}\n\nAccount::Account(std::string const& firstName, std::string const& surName, int balance)\n : firstName(firstName)\n , surName(surName)\n , balance(balance)\n , open(true)\n , accountNo(Bank::getNextAccountNumber())\n{}\n\nvoid Account::swap(Account& other) noexcept\n{\n using std::swap;\n swap(firstName, other.firstName);\n swap(surName, other.surName);\n swap(balance, other.balance);\n swap(open, other.open);\n swap(accountNo, other.accountNo);\n}\n\nstd::ostream& operator<<(std::ostream& str, Account const& acc)\n{\n return str << acc.firstName.size() << \" \" << acc.firstName\n << acc.surName.size() << \" \" << acc.surName\n << acc.balance << \" \"\n << acc.open << \" \"\n << acc.accountNo << \"\\n\";\n}\n\nstd::istream& operator>>(std::istream& str, Account& acc)\n{\n Account tmp;\n std::size_t size;\n char ignore;\n if (str >> size) {\n tmp.firstName.resize(size);\n str.read(&ignore, 1);\n str.read(&tmp.firstName[0], size);\n }\n if (str >> size) {\n tmp.surName.resize(size);\n str.read(&ignore, 1);\n str.read(&tmp.firstName[0], size);\n }\n if (str >> tmp.balance >> tmp.open >> tmp.accountNo) {\n // Only change the state if the object was correctly read from the stream.\n acc.swap(tmp);\n }\n return str;\n}\n\nstd::vector<Account> Bank::accounts;\n\nvoid Bank::loadAccount(std::string const& fileName)\n{\n std::ifstream logFile(fileName);\n std::vector<Account> load(std::istream_iterator<Account>{logFile},\n std::istream_iterator<Account>{});\n\n accounts = std::move(load);\n}\noid reportError()\n{\n std::cerr << \"Unrecognized user input\\n\";\n std::cerr << \"Flushing Input stream\\n\";\n std::cin.clear();\n cin.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');\n}\nvoid openAccount()\n{\n // Get user input\n // Bank::openAccount(userInput);\n}\nvoid closeAccount()\n{\n // get user input\n // Bank::closeAccount(userInput);\n}\nvoid showAllAccounts()\n{\n // Bank::showBalance()\n}\nvoid depositInAccount()\n{\n // getUserInput\n // Bank::deposit(account, value)\n}\nvoid withdrawFromAccount()\n{\n // get user input\n // Bank::withdraw(account, value);\n}\nvoid transferToAnAccount()\n{\n // get user input\n // Bank::transfer(srcAccount, dstAccount, value);\n}\nvoid showBalance()\n{\n // get user input\n // Bank::showBalance(account);\n}\nvoid showAllTransactions()\n{\n // Bank::showAllTransactions();\n}\n\nvoid displayMenu()\n{\n std::cout << \"Choose an Option:\\n\"\n << \"\\t\" << OpenAccount << \" To open an Account\\n\"\n << \"\\t\" << CloseAccount << \" To close an Account\\n\"\n << \"\\t\" << ShowAllAccounts << \" To show all accounts\\n\"\n << \"\\t\" << DepositInAccount << \" To deposit in an account\\n\"\n << \"\\t\" << WithdrawFromAccount << \" To withdraw from an account\\n\"\n << \"\\t\" << TransferToAnAccount << \" To transfer to an account\\n\"\n << \"\\t\" << ShowBalance << \" To show account balance\\n\"\n << \"\\t\" << ShowAllTransactions << \" To show all transactions\\n\"\n << \"\\t\" << Quit << \" To quit application\\n\";\n}\n\nint main(int argc, char* argv[])\n{\n if (argc != 2) {\n std::cerr << \"Failed to start: CLA <transaction Log Name>\\n\";\n exit(1);\n }\n Bank::loadAccount(argv[1]);\n\n Action userAction;\n do {\n displayMenu();\n std::cin >> userAction;\n switch(userAction) {\n case BADAction: reportError(); break;\n case OpenAccount: openAccount(); break;\n case CloseAccount: closeAccount(); break;\n case ShowAllAccounts: showAllAccounts(); break;\n case DepositInAccount: depositInAccount(); break;\n case WithdrawFromAccount: withdrawFromAccount(); break;\n case TransferToAnAccount: transferToAnAccount(); break;\n case ShowBalance: showBalance(); break;\n case ShowAllTransactions: showAllTransactions(); break;\n case Quit: /* Nothing */ break;\n }\n }\n while(userAction != Quit);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T05:10:29.107",
"Id": "454982",
"Score": "1",
"body": "Amazing! Didn't even know these many things existed. I am quite a beginner in C++."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T16:56:52.820",
"Id": "455134",
"Score": "1",
"body": "I disagree with your observation about multiple variable declarations in the same line. Repeating the type over and over again, over multiple lines, is a waste of screen space and declaring `int x, y, z` should absolutely not look remotely unclear to anyone familiar with C _or_ C++. After a point, separating your declarations actually makes the code less readable, due to the amount of noise one has to go through."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T17:37:32.740",
"Id": "455140",
"Score": "0",
"body": "@osuka_ If I am looking for a specific variable I would consider it much harder to find if there were multiple variables per line. The one-declaration-per-line suggestion, when taken in conjunction with \"declare closest to first use\"/\"avoid declaring everything at the top\" suggestions actually help to reduce noise. The ODPL also prevents errors such as `int* x, y, z;`. Where the programmer intended to declare three pointers and instead gets a pointer and two ints."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T17:44:14.010",
"Id": "455142",
"Score": "1",
"body": "@Casey Declaring closest to first use should be kept in mind, but it is unfortunately not possible for class members. Mistakes with `*` (and `&` or `&&`) are also avoided by separating them from the type, in favor of typing them close to the variable ID. The decision here is about tradeoffs - I don’t think there’s an absolutely correct answer to this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T22:56:45.653",
"Id": "455176",
"Score": "1",
"body": "@osuka_ I think your argument is exceedingly old and bad advice. This was the standard thirty years ago but has been superseded by clean code practices like \"Self Documenting Code\". Unless you can point at some good coding practice book that suggests this is good advice? I would love to read it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T23:20:04.877",
"Id": "455179",
"Score": "0",
"body": "@MartinYork What does self documenting code have to do with anything I said? The C++ Core Guidelines _do_ mention that a single declaration should be made per statement (ES.10), _but_ ES.11 mentions using `auto` to avoid repeating yourself - which often isn't possible in a class declaration, where a meaningful value may not exist."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T23:33:59.633",
"Id": "455180",
"Score": "1",
"body": "@osuka_ You said: \"I disagree with your observation about multiple variable declarations in the same line.\" I said this is against clean self documenting code. Self documenting is not just about naming there are a whole bunch of practices around it. Your advice is old and dangerous (and goes against best practices) please reconsider. Or simply never work for me (either work)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T23:39:33.340",
"Id": "455181",
"Score": "0",
"body": "@MartinYork I wasn't picking on _that_ - sorry it was unclear. Code should be self-documenting, and style should be consistent - and, arguably, if you have to declare 50 variables something else is terribly wrong anyways - but in a trivial declaration such as the example in the question, I see no problem with it whatsoever. It is a bit more succinct, but I don't think I would even bother mentioning this in a code review."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T23:01:39.830",
"Id": "232876",
"ParentId": "232852",
"Score": "37"
}
},
{
"body": "<p>No comments anywhere within the code. This could lead to the code being difficult to maintain/understand in the future.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T14:07:07.720",
"Id": "455101",
"Score": "5",
"body": "Self documenting code should be preferred over comments because comments have to be maintained as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T09:28:43.507",
"Id": "455222",
"Score": "0",
"body": "I think the wording \"Should be preferred\" is a little strong. \"Can be used\", might be better. A quick search on google gives pro's and con's of comments vs. self documenting code. I think we can agree however that there needs to be some method of documentation, especially if you are a beginner."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T14:02:54.590",
"Id": "232943",
"ParentId": "232852",
"Score": "0"
}
},
{
"body": "<h1>Never use <code>float</code> or <code>double</code> for money</h1>\n\n<p>Floating point types (in C++, those include <code>float</code>, <code>double</code>, <code>long double</code>, etc.) are inherently inaccurate due to how they are represented in memory. It's not a <em>huge</em> deal for most applications - but for a banking system (where rounding error is unacceptable) you should stay as far away as possible from this. A solution to this is to separate the whole and fractional amounts as integer types:</p>\n\n<pre><code>struct Money {\n int dollars = 0, cents = 0;\n}\n</code></pre>\n\n<p>Then, define some operators:</p>\n\n<pre><code>Money operator+(const Money &x, const Money &y);\nMoney operator-(const Money &x, const Money &y);\n...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T16:53:23.043",
"Id": "232955",
"ParentId": "232852",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "232876",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T09:15:27.050",
"Id": "232852",
"Score": "17",
"Tags": [
"c++",
"c++14"
],
"Title": "Banking system in C++"
}
|
232852
|
<p>I would like to write a C++ code for the n-queens problem using the permutation approach. This means I index the queens from 1 to n, and the state of the checkerboard will be defined by an array where the i-th entry stores the row of the queen at the i-th column.
Clearly, such array will contain a permutation of the set [1, 2, ..., n].</p>
<p>My first attempt is based on the idea to generate a new permutation by switching two entries of the state vector at random.
This certainly is not an efficient way of doing this, but I do not know how to modify Heap's algorithm so that it returns a new permutation every time I call it.</p>
<p>I was also thinking about using boost's <a href="https://www.boost.org/doc/libs/1_71_0/libs/iterator/doc/permutation_iterator.html" rel="nofollow noreferrer">permutation iterator</a> but it seems very complicated.</p>
<p>This is the code:</p>
<pre class="lang-cpp prettyprint-override"><code>// queens.cc
#include <iostream>
#include "queens.h"
int main() {
Queens<8> a;
try {
auto q = a.solve();
std::cout << a.length() << "\n";
std::cout << "found configuration:\n";
for (auto it : q) {
std::cout << it.col << " " << it.row << "\n";
}
std::cout << std::flush;
} catch (const char* msg) {
std::cerr << msg << std::endl;
}
}
</code></pre>
<pre class="lang-cpp prettyprint-override"><code>// queens.h
#ifndef QUEENS_H
#define QUEENS_H
#include <random>
#include <vector>
typedef struct {
unsigned int row, col;
} Position;
constexpr unsigned int factorial(const unsigned int n) {
if (n == 1)
return 1;
else
return n*factorial(n - 1);
}
template <unsigned int N>
class Queens {
public:
Queens();
std::vector<Position>::size_type length() const { return queens.size(); };
std::vector<Position>& solve();
private:
// Used for generating the permutations.
std::default_random_engine generator;
std::uniform_int_distribution<unsigned int> distribution{1, N};
// The coordinates of the queens.
std::vector<Position> queens{N};
void generate_permutation();
bool configuration_acceptable(const std::vector<Position>&) const;
};
template<unsigned int N>
Queens<N>::Queens() {
for (unsigned int i = 1; i <= N; ++i) {
queens[i - 1].col = i;
queens[i - 1].row = i;
}
}
// Keeps generating new permutations by random swap.
template<unsigned int N>
void Queens<N>::generate_permutation() {
auto i = distribution(generator);
auto j = distribution(generator);
auto ri = queens[i - 1].row;
queens[i - 1].row = queens[j - 1].row;
queens[j - 1].row = ri;
}
// Given the queens's position c, returns true if the queens are not attacking
// each other, otherwise false.
template<unsigned int N>
bool Queens<N>::configuration_acceptable(const std::vector<Position>& c) const {
for (auto i = 0; i < c.size() - 1; ++i) {
auto qi = c[i];
for (auto j = i + 1; j < c.size(); ++j) {
auto qj = c[j];
auto delta = qj.col - qi.col;
if (qj.row == qi.row + delta || qj.row == qi.row - delta)
return false;
}
}
return true;
}
// Sweeps through all permutations of (1..N) and returns the first one that
// fulfills the constraints.
template<unsigned int N>
std::vector<Position>& Queens<N>::solve() {
for (unsigned int i = 0; i < factorial(N); ++i) {
generate_permutation();
if (configuration_acceptable(queens))
return queens;
}
throw "Solution not found";
}
#endif
</code></pre>
<p>The code seems to be working in the sense that it returns a solution to the n-queen's problem. I would like to modify it (by changing the permutation generator) so that it returns all the possible configurations for a given n.</p>
<p>As for the efficiency of the code, I guess I could probably just use an <code>std::vector<unsigned></code> for storing the row index of every queen, but the code would probably be less readable.</p>
<p>I was also thinking that maybe I could initialise the <code>queens</code> variable at compile time rather than in the constructor, by using a constexpr utility function?</p>
<p>This problem is mostly an excuse to practice/learn my C++ skills, so I am very interested on any feedback on the code quality and on how to improve this simple program as much as possible, following good practices for production C++.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T14:45:14.947",
"Id": "454914",
"Score": "1",
"body": "I believe you can use backtracking to generate all possible solutions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T15:02:22.923",
"Id": "454916",
"Score": "0",
"body": "Welcome to code review, where we review working code and provide suggestions on how that code can be improved. Unfortunately we can't really provide you with an alternate method for solving the problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T21:40:45.523",
"Id": "454969",
"Score": "0",
"body": "@pacmaninbw thanks, I would be happy just to have a review on the code I posted, without any comment on how to improve the algorithm."
}
] |
[
{
"body": "<h2>Avoid the Comma Operator in Declarations</h2>\n\n<p>In the declaration of Position the comma operator is being used.</p>\n\n<pre><code>typedef struct {\n unsigned int row, col;\n} Position;\n</code></pre>\n\n<p>It is preferable to declare each variable separately, it is easier to find variable declarations this way, it is easier to add and remove variables this way and it makes the code more readable.</p>\n\n<pre><code>typedef struct {\n size_t row;\n size_t col;\n} Position;\n</code></pre>\n\n<p>In many cases it is preferable to use <code>size_t</code> instead of <code>unsigned int</code>, especially for array and vector indexes. The <code>size()</code> function of <strong>STL</strong> container classes returns <code>size_t</code>.</p>\n\n<h2>The <code>factorial()</code> Function</h2>\n\n<p>It would be better to use an iterative solution for the <code>factorial()</code> function, it would perform faster and use less memory. While this probably won't happen in this program, for large numbers the current implementation of <code>factorial()</code> may cause a stack overflow due to the number of copies of <code>factorial()</code> on the stack. Using an iterative approach would also allow for testing the value to be returned to make sure it never exceeds the size of the variable being used (Arithmetic Overflow).</p>\n\n<pre><code>constexpr unsigned int factorial(const unsigned int n) {\n if (n == 1)\n return 1;\n else\n return n*factorial(n - 1);\n}\n</code></pre>\n\n<p>A good habit to get into is to wrap actions after <code>if</code> or <code>else</code> in brackets (<code>{}</code>). This improves the maintainability of the code. If someone had to modify the <code>if</code> statement by adding another statement before the <code>return</code> statement they could introduce a bug if the didn't add the brackets. </p>\n\n<pre><code>constexpr unsigned int factorial(const unsigned int n) {\n if (n == 1) {\n return 1;\n }\n else {\n return n*factorial(n - 1);\n }\n}\n</code></pre>\n\n<h2>Algorithm</h2>\n\n<p>It might be better if the class Queens had a way to print the contents of the <code>queens</code> vector, that way the <code>main()</code> function would be simpler, because the <code>solve()</code> function could return <code>true</code> or <code>false</code> and the code would not be using <code>try{}</code> and <code>catch{}</code>. Generally <code>try{}</code> and <code>catch{}</code> are used for error processing, and what is thrown is an exception. Not finding a solution to the N Queens problem should not be considered an error and shouldn't use try and catch. This would also remove any necessity for <code>main()</code> to have any knowledge of the private vector <code>queens</code> or the struct <code>Position</code></p>\n\n<pre><code>template<unsigned int N>\nbool Queens<N>::solve() {\n for (unsigned int i = 0; i < factorial(N); ++i) {\n generate_permutation();\n if (configuration_acceptable(queens))\n {\n return true;\n }\n }\n return false;\n}\n\ntemplate<unsigned int N>\nvoid Queens<N>::printQueens()\n{\n for (auto it : queens) {\n std::cout << it.col << \" \" << it.row << \"\\n\";\n }\n std::cout << std::flush;\n}\n\nint main() {\n Queens<8> a;\n bool solved = a.solve();\n std::cout << a.length() << \"\\n\";\n if (solved)\n {\n std::cout << \"found configuration:\\n\";\n a.printQueens();\n } else {\n std::cout << \"No Solution Found\\n\";\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T13:39:41.713",
"Id": "455095",
"Score": "0",
"body": "Thanks. I guess it is a good practice to use brackets every time we write a for loop, even if it is a one-line action.\n\nAs for the `printQueens` member function, would you recommend doing this instead:\n\n`\ntemplate<size_t N2>\nfriend std::ostream& operator<<(std::ostream& s, const Queens<N2>& q) {\n for (auto it : q.queens) {\n s << it.col << \" \" << it.row << \"\\n\";\n }\n s << std::flush;\n return s;\n}\n`\n\nAnd then calling:\n\n`\nif (solved) {\n std::cout << a;\n } else {\n std::cerr << \"Solution not found.\" << std::endl;\n }\n`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T13:42:17.970",
"Id": "455097",
"Score": "0",
"body": "That's a good alternative."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T16:38:38.430",
"Id": "232899",
"ParentId": "232856",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "232899",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T12:33:08.747",
"Id": "232856",
"Score": "2",
"Tags": [
"c++",
"n-queens"
],
"Title": "n-queens problems and permutation strategy"
}
|
232856
|
<p>I am adding a <code>List</code> of songs to a Playlist in the <code>PlaylistBusinessBean</code> class. The objective of this class is to add a song/tracks at an index in an existing playlist.</p>
<p>I am trying to refactor <code>PlaylistBusinessBean</code> class. As per my understanding the method <code>validateIndexes</code> in the class <code>PlaylistBusinessBean</code> holds no significance because <code>playList.getNrOfTracks()</code> and <code>playList.getPlayListTracks().size()</code> will return same value. So, my question is that the below lines can be removed from class, as they are unnecessary? Is there anything else, that can be done to refactor the class?</p>
<pre><code> if (!validateIndexes(toIndex, playList.getNrOfTracks())) {
return Collections.EMPTY_LIST;
}
</code></pre>
<p><strong><em>Business class:</em></strong></p>
<pre><code>public class PlaylistBusinessBean {
private PlaylistDaoBean playlistDaoBean;
@Inject
public PlaylistBusinessBean(PlaylistDaoBean playlistDaoBean) {
this.playlistDaoBean = playlistDaoBean;
}
List<PlayListTrack> addTracks(String uuid, List<Track> tracksToAdd, int toIndex) throws PlaylistException {
if (StringUtils.isNotBlank(uuid) && CollectionUtils.isNotEmpty(tracksToAdd)) {
try {
Optional<PlayList> playlistByUUID = Optional.ofNullable(playlistDaoBean.getPlaylistByUUID(uuid));
if (playlistByUUID.isPresent()) {
PlayList playList = playlistByUUID.get();
// We do not allow > 500 tracks in new playlists
if (playList.getNrOfTracks() + tracksToAdd.size() > 500) {
throw new PlaylistException("Playlist cannot have more than " + 500 + " tracks");
}
// The index is out of bounds, put it in the end of the list.
int size = playList.getPlayListTracks() == null ? 0 : playList.getPlayListTracks().size();
if (toIndex > size || toIndex == -1) {
toIndex = size;
}
if (!validateIndexes(toIndex, playList.getNrOfTracks())) {
return Collections.EMPTY_LIST;
}
Set<PlayListTrack> originalSet = playList.getPlayListTracks();
List<PlayListTrack> original;
if (originalSet == null || originalSet.size() == 0)
original = new ArrayList<PlayListTrack>();
else
original = new ArrayList<PlayListTrack>(originalSet);
Collections.sort(original);
List<PlayListTrack> added = new ArrayList<PlayListTrack>(tracksToAdd.size());
for (Track track : tracksToAdd) {
PlayListTrack playlistTrack = new PlayListTrack();
playlistTrack.setTrack(track);
playlistTrack.setTrackPlaylist(playList);
playlistTrack.setDateAdded(new Date());
playlistTrack.setTrack(track);
playList.setDuration(addTrackDurationToPlaylist(playList, track));
original.add(toIndex, playlistTrack);
added.add(playlistTrack);
toIndex++;
}
int i = 0;
for (PlayListTrack track : original) {
track.setIndex(i++);
}
playList.getPlayListTracks().clear();
playList.getPlayListTracks().addAll(original);
playList.setNrOfTracks(original.size());
return added;
}
throw new PlaylistException("Playlist with UUID: " + uuid + " not found");
} catch (Exception e) {
e.printStackTrace();
throw new PlaylistException("Generic error");
}
} else {
throw new PlaylistException("Bad input data error");
}
}
private boolean validateIndexes(int toIndex, int length) {
return toIndex >= 0 && toIndex <= length;
}
private float addTrackDurationToPlaylist(PlayList playList, Track track) {
return (track != null ? track.getDuration() : 0)
+ (playList != null && playList.getDuration() != null ? playList.getDuration() : 0);
}
}
</code></pre>
<pre><code>public class PlayList {
private Integer id;
private String playListName;
private Set<PlayListTrack> playListTracks = new HashSet<PlayListTrack>();
private Date registeredDate;
private Date lastUpdated;
private String uuid;
private int nrOfTracks;
private boolean deleted;
private Float duration;
public PlayList() {
this.uuid = UUID.randomUUID().toString();
Date d = new Date();
this.registeredDate = d;
this.lastUpdated = d;
this.playListTracks = new HashSet<PlayListTrack>();
}
.....getter setters...
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T19:20:48.270",
"Id": "454953",
"Score": "1",
"body": "Please [edit] the title to better reflect the *purpose of the code*, rather than what you need to do with it."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T17:50:49.353",
"Id": "232864",
"Score": "1",
"Tags": [
"java"
],
"Title": "Adding a List of songs to a playlist"
}
|
232864
|
<p>I started learning JavaFX a few days ago and I have just created as an exercise a simple Gem Puzzle game. The puzzle pieces can be moved if we click on them. The visual aspect of the game is very basic. The code is based on a MVC architecture.</p>
<p>It's not totally finished. Still, before I get any further in this exercise (shuffling pieces, checking if the puzzle is solved, creating a solver, improve visual...)
I would like to get some feedback about my code from more advanced programmers to know which point I should improve in order to be a better developer. I would be grateful for any remarks and tips. Is the code clean, MVC pattern correctly used, JavaFX used wisely, are code conventions followed, and anything that would help me to improve myself.</p>
<p>The classes are organized as follows:</p>
<p>model : Board, Piece</p>
<p>view : GemMainGUI, Tile, GemBoard</p>
<p>controller : MouseController</p>
<p><strong>MODEL</strong></p>
<pre class="lang-java prettyprint-override"><code>package games.gem.model;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class Board {
private final int boundX;
private final int boundY;
private List<Piece> pieces;
private int emptyPositionX;
private int emptyPositionY;
public Board(int x, int y) {
this.boundX = x;
this.boundY = y;
this.pieces = new ArrayList<>();
// Create each pieces with their position in the board
List<Integer> ids = new ArrayList<>();
for (int i = 1; i < this.boundX * this.boundY; i++) {
ids.add(i);
}
Collections.shuffle(ids);
Iterator<Integer> it = ids.iterator();
for (int i = 0; i < this.boundX; i++) {
for (int j = 0; j < this.boundY; j++) {
if (i != this.boundX - 1 || j != this.boundY - 1) this.pieces.add(new Piece(j, i, it.next()));
}
}
this.emptyPositionX = this.boundX - 1;
this.emptyPositionY = this.boundY - 1;
this.shuffle();
}
public List<Piece> getPieces() {
return this.pieces;
}
public void move(Piece currentPiece) {
if (((Math.abs(currentPiece.getX() - this.emptyPositionX) <= 1) && !(Math.abs(currentPiece.getY() - this.emptyPositionY) >= 1)) ||
(!(Math.abs(currentPiece.getX() - this.emptyPositionX) >= 1) && (Math.abs(currentPiece.getY() - this.emptyPositionY) <=1))) {
int saveX = currentPiece.getX();
int saveY = currentPiece.getY();
currentPiece.setX(this.emptyPositionX);
currentPiece.setY(this.emptyPositionY);
this.emptyPositionX = saveX;
this.emptyPositionY = saveY;
}
}
private boolean isSolvable() {
// Count the number of inversion
Piece currentPiece;
int inversion;
int totalInversion = 0;
for (int i = 0; i < this.pieces.size() - 1; i++) {
currentPiece = this.pieces.get(i);
inversion = 0;
for (int j = i + 1; j < this.pieces.size(); j++) {
if (currentPiece.getId() > this.pieces.get(j).getId()) {
inversion++;
}
}
totalInversion += inversion;
}
if (this.boundX % 2 != 0) {
return totalInversion % 2 == 0;
} else {
if ((this.boundY - this.emptyPositionY) % 2 == 0) {
return totalInversion % 2 != 0;
} else {
return totalInversion % 2 == 0;
}
}
}
public void shuffle() {
Collections.shuffle(this.pieces);
System.out.println(this.pieces);
if (!this.isSolvable()) {
Collections.swap(this.pieces, 0, 1);
}
}
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>package games.gem.model;
public class Piece {
private final int id;
private int x;
private int y;
public Piece(int x, int y, int id) {
this.id = id;
this.x = x;
this.y = y;
}
public int getId() {
return this.id;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
@Override
public String toString() {
return String.valueOf(this.id);
}
}
</code></pre>
<p><strong>VIEW</strong></p>
<pre class="lang-java prettyprint-override"><code>import games.gem.controller.MouseController;
import games.gem.model.Board;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.stage.Stage;
public class GemMainGUI extends Application {
public static final int WIDTH = 400;
public static final int GRID_SIZE = 4;
private GemBoard container;
@Override
public void start(Stage stage) throws Exception {
Group root = new Group();
Scene scene = new Scene(root, WIDTH, WIDTH);
Canvas canvas = new Canvas(WIDTH, WIDTH);
root.getChildren().add(canvas);
GraphicsContext gc = canvas.getGraphicsContext2D();
Board model = new Board(GRID_SIZE, GRID_SIZE);
this.container = new GemBoard(model);
scene.setOnMouseClicked(new MouseController(model, this.container));
stage.setTitle("Gem game");
stage.setScene(scene);
this.run(gc);
stage.show();
}
private void run(GraphicsContext gc) {
new AnimationTimer() {
@Override
public void handle(long l) {
// Erase former drawings
gc.clearRect(0, 0, WIDTH, WIDTH);
// Drawing tiles
GemMainGUI.this.container.draw(gc);
}
}.start();
}
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>package games.gem.view;
import games.gem.model.Board;
import games.gem.model.Piece;
import javafx.scene.canvas.GraphicsContext;
import java.util.ArrayList;
import java.util.List;
public class GemBoard {
private List<Tile> tiles;
public GemBoard(Board board) {
this.tiles = new ArrayList<>();
for (Piece p : board.getPieces()) {
tiles.add(new Tile(p));
}
}
public List<Tile> getTiles() {
return this.tiles;
}
public void draw(GraphicsContext gc) {
for (Tile tile : this.tiles) {
tile.draw(gc);
}
}
}
</code></pre>
<pre class="lang-java prettyprint-override"><code>package games.gem.view;
import games.gem.model.Piece;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
public class Tile {
private Piece piece;
private static int width = GemMainGUI.WIDTH / GemMainGUI.GRID_SIZE;
public Tile(Piece piece) {
this.piece = piece;
}
public Piece getPiece() {
return this.piece;
}
public boolean contains(double x, double y) {
boolean betweenX = this.piece.getX() * width <= x && x <= this.piece.getX() * width + width;
boolean betweenY = this.piece.getY() * width <= y && y <= this.piece.getY() * width + width;
return betweenX && betweenY;
}
public void draw(GraphicsContext gc) {
if (this.piece == null) {
return;
}
int x = this.piece.getX() * width;
int y = this.piece.getY() * width;
gc.setFill(Color.BLUE);
gc.fillRect(x, y, width, width);
gc.setStroke(Color.BLACK);
gc.strokeRect(x, y, width, width);
gc.setFill(Color.BLACK);
gc.fillText(String.valueOf(this.piece.getId()), x + width / 2, y + width / 2);
}
}
</code></pre>
<p><strong>CONTROLLER</strong></p>
<pre class="lang-java prettyprint-override"><code>package games.gem.controller;
import games.gem.model.Board;
import games.gem.view.GemBoard;
import games.gem.view.Tile;
import javafx.event.EventHandler;
import javafx.scene.input.MouseEvent;
public class MouseController implements EventHandler<MouseEvent> {
private Board model;
private GemBoard view;
public MouseController(Board model, GemBoard view) {
this.model = model;
this.view = view;
}
@Override
public void handle(MouseEvent mouseEvent) {
for (Tile currentTile : this.view.getTiles()) {
if (currentTile.contains(mouseEvent.getX(), mouseEvent.getY())) {
// System.out.println(currentTile.getPiece().getId());
this.model.move(currentTile.getPiece());
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T11:42:22.250",
"Id": "455084",
"Score": "1",
"body": "Where is your `Piece` class? I cannot run your code without it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T17:42:52.080",
"Id": "455141",
"Score": "0",
"body": "@0009laH Sorry, my bad. I've added the missing class and there is also a method to shuffle the game in Board."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T17:51:33.997",
"Id": "455143",
"Score": "0",
"body": "Thanks, I'll watch that tonight :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T09:18:45.707",
"Id": "456201",
"Score": "0",
"body": "I suggest you use GitHub if you don't already use it, and than in the Marketing page you should subscribe to CodeBeat, Codacy and BetterCodeHub apps for automated code review. It is free of charge for public repositories. It is very helpful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-07T17:43:48.033",
"Id": "456695",
"Score": "1",
"body": "Thank you very much for your response @ZoranJankov"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-10T20:28:47.440",
"Id": "457153",
"Score": "0",
"body": "@YTTY You are very welcome! :)"
}
] |
[
{
"body": "<p>You should avoid complex <code>boolean</code> expressions in <code>if</code> statements like you used here:</p>\n\n<pre><code>if (((Math.abs(currentPiece.getX() - this.emptyPositionX) <= 1) && !(Math.abs(currentPiece.getY() - this.emptyPositionY) >= 1)) ||\n (!(Math.abs(currentPiece.getX() - this.emptyPositionX) >= 1) && (Math.abs(currentPiece.getY() - this.emptyPositionY) <=1)))\n</code></pre>\n\n<p>You should have a <code>private</code> <code>boolean</code> method:</p>\n\n<pre><code>if(isSomeStatmentValid())\n{\n //do something\n}\n\nprivate boolean isSomeStatmentValid()\n{\n (!(Math.abs(currentPiece.getX() - this.emptyPositionX) >= 1)\n &&(Math.abs(currentPiece.getY() - this.emptyPositionY) <= 1))\n}\n</code></pre>\n\n<p>This is more clear to read.</p>\n\n<p>As I said in the comment, I suggest you use <a href=\"https://github.com/\" rel=\"nofollow noreferrer\">GitHub</a> if you don't already use it, and than in the <a href=\"https://github.com/marketplace\" rel=\"nofollow noreferrer\">Marketplace</a> page you should subscribe to <a href=\"https://codebeat.co/\" rel=\"nofollow noreferrer\">CodeBeat</a>, <a href=\"https://app.codacy.com/\" rel=\"nofollow noreferrer\">Codacy</a> and <a href=\"https://bettercodehub.com/\" rel=\"nofollow noreferrer\">BetterCodeHub</a> apps for <a href=\"https://en.wikipedia.org/wiki/Automated_code_review\" rel=\"nofollow noreferrer\">automated code review</a>. It is free of charge for public repositories. It is very helpful.</p>\n\n<p>And you should take look at <a href=\"https://www.oracle.com/technetwork/java/codeconventions-150003.pdf\" rel=\"nofollow noreferrer\">Java Code Conventions</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-10T08:09:54.350",
"Id": "233765",
"ParentId": "232866",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T18:18:59.443",
"Id": "232866",
"Score": "7",
"Tags": [
"java",
"game",
"mvc",
"gui",
"javafx"
],
"Title": "Gem Puzzle game"
}
|
232866
|
<p>Question statement:</p>
<blockquote>
<p>A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:</p>
<pre><code>1/2 = 0.5
1/3 = 0.(3)
1/4 = 0.25
1/5 = 0.2
1/6 = 0.1(6)
1/7 = 0.(142857)
1/8 = 0.125
1/9 = 0.(1)
1/10 = 0.1
</code></pre>
<p>Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle.</p>
<p>Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.</p>
</blockquote>
<p>Link: <a href="https://projecteuler.net/problem=26" rel="noreferrer">https://projecteuler.net/problem=26</a></p>
<p>I tried to solve it in <strong>Python</strong>:</p>
<p>My approach:</p>
<ul>
<li><p>For every d, assume you are solving for <code>1 / d</code> by hand. </p></li>
<li><p>In case the 1 is completely divisible by d, it means the cycle length is 0.</p></li>
<li><p>If a value you have already divided appears again, it means you've found the cycle.</p></li>
<li><p>The cycle would have length of the number of times you've repeated the first step minus the first time the cycled value appears as we have to remove non-cycling values.</p></li>
</ul>
<p>Here's my code following the above steps in <strong>Python</strong>:</p>
<pre class="lang-py prettyprint-override"><code>LIMIT = 1000
# The maximum length
maxi = 0
# The 'd' that has maximum length
maxi_d = 1
for d in range(1, LIMIT):
quotient = [] # Stores the decimal quotient
cur_value = 1 # Variable used to perform division as if by hand
len_recur = 0 # Recurring length
# Performing division as if by hand.
while cur_value not in quotient:
if not cur_value: # If the value is not recurring:
break # break as the rucurring length must be 0
len_recur += 1
quotient.append(cur_value)
cur_value = (cur_value % d) * 10
if not cur_value:
continue
# Remove number of values that do not recur
len_recur -= quotient.index(cur_value) + 1
if len_recur > maxi:
maxi = len_recur
maxi_d = d
print(maxi_d)
</code></pre>
<p>I'd like to make this code as fast as possible. This currently takes ~3.5 seconds for <code>LIMIT = 2000</code> and grows exponentially larger.</p>
<p>PS: I know <code>len_recur</code> can be replaced by <code>len(quotient)</code>, but I want the code to be as fast as possible.</p>
|
[] |
[
{
"body": "<h3><em>Boosting time performance:</em></h3>\n\n<p>Starting with minor naming issues:\n<code>maxi</code> is better named as <strong><code>max_len</code></strong> (as stated in comment). <code>maxi_d</code> is renamed to <strong><code>max_d</code></strong>.<br>\nIt's good to move the processing into a separate function, called like <strong><code>calc_longest_recur_cycle</code></strong>.</p>\n\n<p>The main <em>time-performance</em> hits in your implementation is caused by <strong><code>quotient</code></strong> list and its expensive <em>list</em> operations:</p>\n\n<ul>\n<li><code>quotient.append</code></li>\n<li><code>quotient.index</code></li>\n<li><code>cur_value not in quotient</code></li>\n</ul>\n\n<p>According to that fact that <code>quotient</code> and <code>len_recur</code> are reset on each outer <code>for</code> loop iteration and on the level of <code>while</code> loop the fragment</p>\n\n<pre><code>len_recur += 1\nquotient.append(cur_value)\n</code></pre>\n\n<p>tells that <code>cur_value</code> is appended synchronously with incrementing <code>len_recur</code> i.e. the <code>cur_value</code> will get the position equal to <code>len_recur</code>. That means that, on this level, <code>cur_value</code> can be <strong>mapped</strong> to its position contained in <code>len_recur</code>.<br>Thus, <code>quotient</code> is initiated as dictionary (instead of list): <strong><code>quotient = {}</code></strong> or even <strong><code>quotient = {0: 0}</code></strong> as <a href=\"https://codereview.stackexchange.com/users/100620/ajneufeld\"><code>AJNeufeld</code></a> suggested to eliminate <code>cur_value</code> evaluation on the <code>while</code> loop condition. </p>\n\n<hr>\n\n<p>The construction:</p>\n\n<pre><code>while cur_value not in quotient:\n if not cur_value: # If the value is not recurring:\n break\n</code></pre>\n\n<p>is essentially a verbose equivalent to:</p>\n\n<pre><code>while cur_value and cur_value not in quotient:\n</code></pre>\n\n<hr>\n\n<p><em>List</em> indexing </p>\n\n<pre><code>len_recur -= quotient.index(cur_value) + 1 \n</code></pre>\n\n<p>is now efficiently replaced with <em>dict</em> indexing (where values are <em>positions</em>)</p>\n\n<pre><code>len_recur -= quotient[cur_value]\n</code></pre>\n\n<hr>\n\n<p>Now, with <code>quotient</code> as <code>dict</code>, we have <strong><em>O(1)</em></strong> complexity for <em>membership check</em> (<code>cur_value not in quotient</code>) and <em>indexing</em> operation (<code>len_recur -= quotient[cur_value]</code>)</p>\n\n<p>The final version:</p>\n\n<pre><code>LIMIT = 5000\n\ndef calc_longest_recur_cycle():\n max_len = 0 # The maximum length\n max_d = 1 # The 'd' that has maximum length\n\n for d in range(1, LIMIT):\n quotient = {0: 0} # Stores the decimal quotient\n cur_value = 1 # Variable used to perform division as if by hand\n len_recur = 0 # Recurring length\n\n # Performing division as if by hand\n while cur_value not in quotient: # while the value is not recurring\n len_recur += 1\n quotient[cur_value] = len_recur\n cur_value = (cur_value % d) * 10\n\n if not cur_value:\n continue\n\n # Remove number of values that do not recur\n len_recur -= quotient[cur_value]\n # quotient.clear()\n\n if len_recur > max_len:\n max_len = len_recur\n max_d = d\n\n return max_d\n</code></pre>\n\n<hr>\n\n<p>What needs to be mentioned is that despite of its <em>fast nature</em> <code>dict</code> would take more space than <code>list</code>, but only at the time of one nominal loop iteration as it's reset and last <code>quotient</code> filled at the end will be garbage-collected on function exit.</p>\n\n<p>Let's get to tests.<br>\nI've increased limit to <strong><code>LIMIT = 5000</code></strong> to <em>\"turn up the heat\"</em> and have put the \"old\" implementation into separate function <code>calc_recur_cycle_old</code> for comparison.<br>\nAs for resulting <code>max_d</code> value - both functions return the same result:</p>\n\n<pre><code>print(calc_recur_cycle_old()) # 4967\nprint(calc_longest_recur_cycle()) # 4967\n</code></pre>\n\n<p>And the most interesting <em>time performance</em> comparison:</p>\n\n<pre><code>from timeit import timeit\n\nprint(timeit('calc_recur_cycle_old()', 'from __main__ import calc_recur_cycle_old', number=1))\n19.648109548998036\n\nprint(timeit('calc_longest_recur_cycle()', 'from __main__ import calc_longest_recur_cycle', number=1))\n0.26926991600339534\n</code></pre>\n\n<p>The end ... )</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T23:27:58.340",
"Id": "454975",
"Score": "0",
"body": "You should initialize `quotient = {0: 0}`, then the loop condition could simplify to `while cur_value not in quotient:`, which should execute slightly faster."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T23:48:07.550",
"Id": "454976",
"Score": "1",
"body": "@AJNeufeld, that gained only `0.02` sec, but also a good micro-improvement. Thanks, mentioned you in the answer description"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T23:07:01.743",
"Id": "232877",
"ParentId": "232867",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "232877",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T19:35:46.383",
"Id": "232867",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"programming-challenge"
],
"Title": "Project Euler problem 26 in Python"
}
|
232867
|
<p>I implemented a simple maze generator as practice and I wonder what can I do to improve my C++ skills. I saw this implementation and used it as an inspiration for some parts of my code <a href="https://github.com/corporateshark/random-maze-generator/blob/master/Maze.cpp" rel="nofollow noreferrer">link</a>.</p>
<p>I am a little bit confused about usage of the 'inline' keyword. Should the definition of an <code>inline</code> declared method be in .cpp file? I read somewhere that inline method sources should be visible to users of those methods. For small scale programs like this should I keep everything in one file or separate each struct/class to .h & .cpp?</p>
<pre><code>#include <stack>
#include <iostream>
#include <random>
enum Direction{ Left, Right, Up, Down };
Direction operator!(const Direction& dir){
return Direction( (dir==Left || dir==Up) ? dir+1 : dir-1 );
}
struct Coords{
int x, y;
static const Coords directionOffset[];
};
const Coords Coords::directionOffset[] = {
Coords{-1, 0 }, // left
Coords{ 1, 0 }, // right
Coords{ 0,-1 }, // up
Coords{ 0, 1 } // down
};
Coords operator+(const Coords& left, const Coords& right){
return Coords{left.x + right.x, left.y + right.y };
}
struct MazeCell{
unsigned char connections = 0;
inline bool isConnected(Direction dir) const;
inline void connect(Direction dir);
inline bool visited() const;
static const unsigned char connectionMask[];
};
bool MazeCell::isConnected(Direction dir) const{
return connections & connectionMask[dir];
}
void MazeCell::connect(Direction dir){
connections |= connectionMask[dir];
}
bool MazeCell::visited() const{
return connections;
}
const unsigned char MazeCell::connectionMask[] = {
(1 << 0), // left
(1 << 1), // right
(1 << 2), // up
(2 << 3) // down
};
struct MazePosition;
class Maze{
friend MazePosition;
unsigned int width,height;
MazeCell* cells;
public:
Maze(unsigned int width, unsigned int height);
MazePosition at(unsigned int x, unsigned int y) const;
private:
bool succsesfullyConnectedToNeighbour(Coords& cellCoords);
inline void connect(Coords& from, Coords& to, Direction dir);
inline bool areCoordsValid(const Coords& coords) const;
inline MazeCell& cellAt(const Coords& coords) const;
};
void Maze::connect(Coords& from, Coords& to, Direction dir){
cellAt(from).connect(dir);
cellAt(to).connect(!dir);
}
bool Maze::areCoordsValid(const Coords& coords) const {
return coords.x >= 0 && coords.y >= 0 &&
coords.x < (int)width && coords.y < (int)height;
}
MazeCell& Maze::cellAt(const Coords& coords) const {
if(!areCoordsValid(coords)){std::cout << "hit bad";}
return cells[coords.x + coords.y*width];
}
Maze::Maze(unsigned int width, unsigned int height) : width(width), height(height) {
cells = new MazeCell[width*height];
Coords currentCellCoords{0,0};
std::stack<Coords> visitedCellsStack;
visitedCellsStack.push(currentCellCoords);
while(true){
if(succsesfullyConnectedToNeighbour(currentCellCoords)){
visitedCellsStack.push(currentCellCoords);
}else{
currentCellCoords = visitedCellsStack.top();
visitedCellsStack.pop();
if(visitedCellsStack.empty()) break;
}
}
}
bool Maze::succsesfullyConnectedToNeighbour(Coords& cellCoords){
std::random_device rd;
std::mt19937 eng(rd());
std::uniform_int_distribution<std::mt19937::result_type> random(1,4);
Direction random_direction = Direction(random(eng));
for(int i = 0; i < 4; i++){
auto next_rand_direction = Direction( (random_direction + i)%4 );
auto neighbour_coords = Coords::directionOffset[next_rand_direction] + cellCoords;
if( areCoordsValid(neighbour_coords) && !cellAt(neighbour_coords).visited() ){
connect(cellCoords, neighbour_coords, next_rand_direction);
cellCoords = neighbour_coords;
return true;
}
}
return false;
}
struct MazePosition{
const Maze& maze;
Coords currentCoords;
MazePosition(const Maze& maze, Coords coords) : maze(maze), currentCoords(coords){}
bool canGo(Direction dir){
return maze.cellAt(currentCoords).isConnected(dir);
}
void go(Direction dir){
if(canGo(dir))
currentCoords = currentCoords + Coords::directionOffset[dir];
}
};
MazePosition Maze::at( unsigned int x, unsigned int y) const{
return MazePosition(*this,Coords{(int)x, (int)y});
}
int main(){
const static int w = 30;
const static int h = 70;
Maze maze(w,h);
//printing maze
std::cout << std::string(2*w, '_') << '\n';
for(unsigned int y = 0; y < h; y++){
for(unsigned int x = 0; x < w; x++){
if(maze.at(x,y).canGo(Left)) std::cout << ' ';
else::std::cout << '|';
if(maze.at(x,y).canGo(Down)) std::cout << ' ';
else::std::cout << '_';
if( x==(w-1) && !maze.at(x,y).canGo(Right) ) std::cout << '|';
}
std::cout << '\n';
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T20:34:28.967",
"Id": "454962",
"Score": "1",
"body": "The `inline` keyword is at best a hint to the compiler it isn't necessary because modern compilers will decide if the function can be inlined or not. At one time it generated optimized code but that is no longer true. See this stackoverflow question https://stackoverflow.com/questions/1759300/when-should-i-write-the-keyword-inline-for-a-function-method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T20:36:36.137",
"Id": "454963",
"Score": "2",
"body": "Welcome to code review, how much of the code in the question is borrowed from the link. If it is more than 50%, this question may be off-topic and put on hold or closed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T20:45:07.660",
"Id": "454964",
"Score": "0",
"body": "Thanks! I borrowed just a concept for storing connections between cells as individual bits and implemented it in a more OOP way, but generally my code is a lot different than the one from the link which is not in OOP style."
}
] |
[
{
"body": "<p>A few points that might be useful:</p>\n\n<ul>\n<li><p>Firstly, don't worry about having small header/source files. It's generally good practice to put structs/classes in separate files.</p></li>\n<li><p>You declare <code>MazeCell</code> and <code>MazePosition</code> as <code>struct</code>. I would still use <code>class</code> here. It's a matter of preference but a pretty good rule is to use <code>struct</code> when you just want a container for data with no methods or added functionality.</p></li>\n<li><p>Don't really worry about inline because any decent compiler will do this for you.</p></li>\n<li><p><code>unsigned</code> can be used instead of <code>unsigned int</code> and is more idiomatic.</p></li>\n<li><p>Your use of <code>unsigned int</code> in <code>Maze</code> is inconsistent with your use of <code>int</code> in <code>Coords</code>. This is causing a lot of C style <code>(int)</code> casts. If you just continue to use <code>int</code> instead, you can forget all of these and prevent the chance of overflow.</p></li>\n<li><p>You never <code>delete[] cells;</code> in <code>Maze</code>! As is, the class should also have a destructor, copy constructor and copy assignment operator. An easier way to solve this though would be to use <code>std::vector<MazeCell></code> for your cells.</p></li>\n<li><p><code>Maze::succsesfullyConnectedToNeighbour(...)</code> is confusingly named. Ignoring the typo, it does not indicate that it will change the coords you pass it. Maybe <code>bool Maze::connectToNeighbour(const Coords& currentCell, Coords& neighbourCell)</code> would be more appropriate?</p></li>\n<li><p>In <code>Maze::succsesfullyConnectedToNeighbour(...)</code> you should declare your random device, engine & distribution as static. You are not intended to construct new ones every time you need a random number</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T01:45:48.223",
"Id": "232920",
"ParentId": "232868",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "232920",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T20:04:27.287",
"Id": "232868",
"Score": "4",
"Tags": [
"c++"
],
"Title": "Depth first maze generating algorithm c++ implementation"
}
|
232868
|
<p>This program I have written automates some of the more manual work in getting the results from my experiments.</p>
<p>The idea is that I have folders and subdirectories in my main directory. Some of these subdirectories contain the data I need process. Inside each of these subdirectories that contain data, there are another five subdirectories with the files. To process these files, I must run a program called <strong>processResults.py</strong>. </p>
<p>For example, if I have two data folders, then each of these will have 5 subdirectories for a total of 10 subdirectories, each of which must have <strong>processResults.py</strong> copied into and then ran. </p>
<p>Running <strong>processResults.py</strong> produces a new directory called <strong>results</strong> that has a summary csv file inside it called <strong>Summary_Total.csv</strong>. </p>
<p>All <strong>Summary_Total.csv</strong> files in a given data folder must be concatenated into a new csv file for processing. So, in our example, there would be two end product csv's that each contain 5 Summary_Total csvs, one for each original subdirectory. </p>
<p>The process described above is what I have automated through a program called <strong>generate_results.py</strong>.</p>
<p>Before I provide a manual demonstration and an automated one, I want to say that I am looking to</p>
<p><strong>1. Reduce the number of lines of my code</strong></p>
<p><strong>2. Make the code more efficient or optimized</strong></p>
<p><strong>3. Improve documentation</strong></p>
<p>After the demonstrations, the code for <strong>processResults.py</strong> and <strong>generate_results.py</strong>, the program I would like to improve, is provided. </p>
<pre><code>(base) ip-75-193:Test trevormartin$ ls
N_Test UN_Test processResults.py generate_results.py
(base) ip-75-193:Test trevormartin$ cd N_Test
(base) ip-75-193:N_Test trevormartin$ cat
x_1 x_3 x_5
x_2 x_4
(base) ip-75-193:N_Test trevormartin$ cd ..; cd UN_Test; ls; cd ..
xx_1 xx_3 xx_5
xx_2 xx_4
(base) ip-75-193:Test trevormartin$
</code></pre>
<p><strong>The subdirectories x_1 ... x_5 and xx_1 ... xx_5 are currently empty</strong></p>
<p>For testing here is what you should do:</p>
<pre><code>(base) ip-75-193:Home trevormartin$ mkdir Test
(base) ip-75-193:Home trevormartin$ cd Test
(base) ip-75-193:Test trevormartin$ emacs processResults.py
(copy my code for processResults.py)
(base) ip-75-193:Test trevormartin$ emacs generate_results.py
(copy my code for generate_results.py)
(base) ip-75-193:Test trevormartin$ mkdir N_Test
(base) ip-75-193:Test trevormartin$ mkdir UN_Test
(base) ip-75-193:Test trevormartin$ cd N_Test
(base) ip-75-193:N_Test trevormartin$ mkdir x_1 x_2 x_3 x_4 x_5
(base) ip-75-193:N_Test trevormartin$ cd ..
(base) ip-75-193:Test trevormartin$ cd UN_Test
(base) ip-75-193:UN_Test trevormartin$ mkdir xx_1 xx_2 xx_3 xx_4 xx_5
(base) ip-75-193:UN_Test trevormartin$ cd ..
</code></pre>
<p>You are now good to go. </p>
<p>Now I will give you the idea of what used to be done manually.</p>
<pre><code>(base) ip-75-193:Test trevormartin$ cp processResults.py ./N_Test/x_1
(base) ip-75-193:Test trevormartin$ cp processResults.py ./N_Test/x_2
.
.
.
(base) ip-75-193:Test trevormartin$ cp processResults.py ./N_Test/x_5
(base) ip-75-193:Test trevormartin$ cp processResults.py ./UN_Test/xx_1
(base) ip-75-193:Test trevormartin$ cp processResults.py ./UN_Test/xx_2
.
.
.
(base) ip-75-193:Test trevormartin$ cp processResults.py ./UN_Test/xx_5
(base) ip-75-193:Test trevormartin$ cd ./N_Test/x_1; python3 processResults.py; cd ..; cd ..
.
.
.
(base) ip-75-193:Test trevormartin$ cd ./N_Test/x_5; python3 processResults.py; cd ..; cd ..
(base) ip-75-193:Test trevormartin$ cd ./UN_Test/xx_1; python3 processResults.py; cd ..; cd ..
.
.
.
(base) ip-75-193:Test trevormartin$ cd ./UN_Test/xx_5; python3 processResults.py; cd ..; cd ..
(base) ip-75-193:Test trevormartin$ cd ./N_Test
(base) ip-75-193:N_Test trevormartin$ ls
x_1 x_2 x_4
x_3 x_5
(base) ip-75-193:N_Test trevormartin$ cd x_1; ls
processResults.py results
(base) ip-75-193:x_1 trevormartin$ cd results; ls
Summary_Total.csv
(base) ip-75-193:results trevormartin$ cat Summary_Total.csv
A,B,C,D,E,F,G
1,1,1,1,1,1,1
2,2,2,2,2,2,2
3,3,3,3,3,3,3
</code></pre>
<p>I would then copy each Summary_Total.csv across all subdirectories into a large csv file for each data folder. </p>
<p>Here is the demonstration of the automated one. There are no files in the subdirectories x_1,...,x_5 and xx_1,...,xx_5 at this point. </p>
<pre><code>(base) ip-75-193:Test trevormartin$ ls
N_Test UN_Test processResults.py generate_results.py
(base) ip-75-193:Test trevormartin$ cd N_Test; ls; cd ..
x_1 x_3 x_5
x_2 x_4
(base) ip-75-193:Test trevormartin$ python3 generate_results.py
(base) ip-75-193:Test trevormartin$ ls
N_Test UN_Test processResults.py
N_Test.csv UN_Test.csv generate_results.py
(base) ip-75-193:Test trevormartin$ cat N_Test.csv
A,B,C,D,E,F,G
1,1,1,1,1,1,1
2,2,2,2,2,2,2
3,3,3,3,3,3,3
1,1,1,1,1,1,1
2,2,2,2,2,2,2
3,3,3,3,3,3,3
1,1,1,1,1,1,1
2,2,2,2,2,2,2
3,3,3,3,3,3,3
1,1,1,1,1,1,1
2,2,2,2,2,2,2
3,3,3,3,3,3,3
1,1,1,1,1,1,1
2,2,2,2,2,2,2
3,3,3,3,3,3,3
</code></pre>
<p>Here is <strong>generate_results.py</strong> that I would like to improve and here is <strong>processResults.py</strong>, which is called by <strong>generate_results.py</strong></p>
<p><strong>generate_results.py</strong></p>
<pre><code>'''
Automates running processResults.py and then concatentating the
csv files into a large csv file
'''
import csv
import pandas
import os
from subprocess import Popen, call
from functools import reduce
cwd = os.getcwd()
dirs = os.listdir(path='.')
# all data dirs begin with N or U, no other dirs begin with these letters
needed_dirs = [cwd+'/'+dir for dir in dirs if dir[0] == 'N' or dir[0] == 'U']
for dir in needed_dirs:
# this only matters if num data folders > 1
os.chdir(cwd)
# copy processResults.py into data folder (i.e. N_Test or UN_Test)
process1 = Popen(['cp','processResults.py',dir])
process1.communicate()
# change directory to inside data folder (i.e. ./N_Test or ./UN_Test)
os.chdir(dir)
cwd2 = os.getcwd()
# get all sub dirs in this directory
sub_dirs = next(os.walk('.'))[1]
# needed_subs will look like ['cwd/N_Test/x_1'...'cwd/N_Test/x_5']
needed_subs = [cwd2+'/'+sub_dir for sub_dir in sub_dirs]
summaries_csvs = []
for sub_dir in needed_subs:
# put processResults.py into each sub_directory
call(["cp","processResults.py",sub_dir])
os.chdir(sub_dir)
# run processResults.py
call(["python3","processResults.py"])
# change the directory back
os.chdir(dir)
for sub_dir in needed_subs:
# go into each 'results' (generated by processResults.py) and collect all summary csvs
os.chdir(sub_dir+'/results')
summary = pandas.read_csv('Summary_Total.csv', delimiter=',')
summaries_csvs.append(summary)
# concatenate all csvs as a pandas dataframe
all_dfs = pandas.concat(summaries_csvs).reset_index(drop=True)
# convert the summaries for a given data folder into a large csv (i.e N_Test.csv or UN_Test.csv)
all_dfs.to_csv(path_or_buf=dir+'.csv',
columns=all_dfs.columns,
index=False,
sep=',',
encoding='utf-8')
</code></pre>
<p><strong>processResults.py</strong></p>
<pre><code>'''
Artificial process.py that illustrates proof of concept.
This artificial process.py creates a subdirectory called 'results'
in the current directory and generates a Summary_Total.csv file
that contains data.
'''
import csv
import os
data = [['A','B','C','D','E','F','G'],
[1,1,1,1,1,1,1],
[2,2,2,2,2,2,2],
[3,3,3,3,3,3,3]]
if not os.path.exists('results'):
os.mkdir('results')
with open('results/'+'Summary_Total.csv', "w") as file:
file_writer = csv.writer(file)
for row in data:
file_writer.writerow(row)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T08:39:08.517",
"Id": "455002",
"Score": "1",
"body": "1) With \"*if I have two data files, then each of these will have 5 subdirectories*\", I guess you meant \"two data **folders**\" (`N_Test`, `UN_Test`). 2) `processResults.py` script has `data` as a common hardcoded list - but where does the real csv data for each sub-folder come from, how they differ?"
}
] |
[
{
"body": "<p>Copying <code>processResults.py</code> into the subdirectories is unnecessary and clutters up the code and your disk drive. Change <code>processResults.py</code> so that it takes a path of the directory to process. Better still, turn processResults.py into a function and combine the two scripts into one much simpler one. Without the overhead of using <code>POpen()</code> or <code>call()</code> this should run faster.</p>\n\n<pre><code>''' \nAutomates data processing and collection\n'''\n\nimport csv\nfrom pathlib import Path\n\n\ndef process(directory='.'):\n '''\n Artificial process() function that generates and returns\n dummy Summary_Total data.\n '''\n\n header = ['A','B','C','D','E','F','G']\n directory = Path(directory).resolve()\n name = directory.parts[-1]\n data = [[name] + [i]*(len(header) - 1) for i in range(1, 4)]\n\n return [header] + data\n\n\ndef write_csv(path, rows):\n '''\n Boilerplate for writing a list of lists to a csv file\n '''\n\n with path.open('w', newline='') as f:\n csv.writer(f).writerows(rows)\n\n\ndef generate_results(pattern='*'):\n '''\n Automates processing each data directory under folders matching the glob-style pattern\n and creating individual and collective summary CSV's\n '''\n for folder in Path('.').glob(pattern):\n\n summaries_csvs = []\n\n # if the sub_dirs need to be done in order, use sorted(folder.iterdir())\n for sub_dir in folder.iterdir():\n if sub_dir.is_dir():\n sub_dir = sub_dir.resolve()\n\n summary = process(sub_dir)\n\n # for the big csv, only include the header from the first summary data\n if not summaries_csvs:\n summaries_csvs.extend(summary)\n else:\n summaries_csvs.extend(summary[1:])\n\n result_dir = sub_dir / 'results'\n result_dir.mkdir(exist_ok=True)\n\n # this is the individual csv in each data sub_dir\n write_csv(result_dir / 'Summary_Total.csv', summary)\n\n # this is the collective summary csv in each data folder\n write_csv(folder.with_suffix('.csv'), summaries_csvs)\n\n\n# process data folders that match the glob pattern\ngenerate_results('Test/[UN]*Test')\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T01:59:13.307",
"Id": "233502",
"ParentId": "232870",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "233502",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T21:22:53.080",
"Id": "232870",
"Score": "1",
"Tags": [
"python",
"performance"
],
"Title": "Processes Files Using Subprocess and Os"
}
|
232870
|
<p>Here's what I could comprehend in C code:</p>
<ol>
<li>Generates a key using PBKDF2</li>
<li>Generates an IV which is MD5 of PBKDF2 key in step #1</li>
<li>Does AES-256 encryption on customer-id - which is one of the output</li>
<li>RSA public encryption on PBKDF2 key which is the second output.</li>
</ol>
<p><strong>Objective</strong>
Need to send a request map to a third party with encryptedValue of customerId, sessionKey and IDDigest [SHA1 of customerId] and get the response. </p>
<p>The system where the request is sent should be responding with 00 if all the values in the request are correct. At the moment, I am getting null in the response body. To reduce your time & effort - aes_dynakey_encrypt is the method you can start within the C implementation</p>
<p><strong>What am I looking for?</strong>
I need somebody to validate that java code does enough to perform the steps implemented in the C code. I could see RSA public encrypt calls. I have done the coding after doing my research but would like the experts to validate it since I'm still getting a null in the response. Not sure if I am doing something wrong. Please guide</p>
<pre><code>****************************************************************************/
* Name: generateSessionKey */
* Desc: To generate session key of size = KEY_SIZE bytes. This */
* key will be used as the secret key for AES 256 encryption */
* and decryption functions that follows. */
* Inputs: None */
* */
* Output: key */
* Returns: 0 for success and -1 for failure. */
****************************************************************************/
int generateSessionKey(unsigned char* key)
unsigned char keyData[8];
unsigned char salt[8];
int iterCount = 5;
/* Randomly generate key_data and salt here. */
if(RAND_bytes(keyData, 8) == 0)
{
return -1;
}
if(RAND_bytes(salt, 8) == 0)
{
return -1;
}
if(PKCS5_PBKDF2_HMAC_SHA1(keyData, 8, salt, 8, iterCount, KEY_SIZE, key))
{
return 0;
}
return -1;
****************************************************************************/
* Name: generateIV */
* Desc: To generate the initialization vector for AES encryption. */
* This iv must be the same for encryption and decryption. */
* So iv is generated as MD5 digest of the key generated */
* using generateSessionKey function. The decryption side */
* can then generate the same iv by creating MD5 digest */
* of the key, once it gets the key for decryption. */
* */
* Inputs: key - Generated by generateSessionKey */
* keySize - Size of key in bytes */
* Output: iv */
* Returns: 0 for success and -1 for failure. */
****************************************************************************/
int generateIV(char* key, int keySize, unsigned char* iv)
if(keySize == 0)
{
return -1;
}
if(MD5(key, keySize, iv) == NULL)
{
return -1;
}
return 0;
int aes_encrypt_text(const unsigned char* intxt, int clen, unsigned char* outtxt,
unsigned char* key, unsigned char* iv)
int outlen = 0, tmplen = 0;
EVP_CIPHER_CTX ctx;
EVP_CIPHER_CTX_init(&ctx);
EVP_EncryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, key, iv);
if(!EVP_EncryptUpdate(&ctx, outtxt, &outlen, intxt, clen))
{
return 0;
}
/* Buffer passed to EVP_EncryptFinal() must be after data just
* encrypted to avoid overwriting it.
*/
if(!EVP_EncryptFinal_ex(&ctx, outtxt + outlen, &tmplen))
{
return 0;
}
outlen += tmplen;
EVP_CIPHER_CTX_cleanup(&ctx);
return outlen;
int aes_dynakey_encrypt(const char* cid, int len, char* encd, char* skey)
int rc = 0;
unsigned char* aesedId = 0;
unsigned char* encodedId = 0;
unsigned char* encodedKey = NULL;
unsigned char iv[16];
unsigned char sessionKey[32];
unsigned char encryptedKey[100];
char *certFile = NULL;
int rsaSize = 0;
int encodedIdLen = 0, encodedKeyLen = 0;
int aesTxtLen = 0;
int encryptedKeyLen = 0;
//RSA *rsaPriv = NULL;
RSA *rsaPub = NULL;
certFile = (access(CERT_PATH, F_OK|R_OK) == 0) ?CERT_PATH:
(access(CERT_PATH_ACR, F_OK|R_OK) == 0)?CERT_PATH_ACR:NULL;
memset(iv, 0, sizeof(iv));
memset(sessionKey, 0, sizeof(sessionKey));
memset(encryptedKey, 0, sizeof(encryptedKey));
if(generateSessionKey(sessionKey) != 0)
{
log_event(LOGCAT_POS, LL1, _HERE, "session key generation failed.");
return -1;
}
if(generateIV(sessionKey, sizeof(sessionKey), iv) != 0)
{
log_event(LOGCAT_POS, LL1, _HERE, "iv generation failed.");
return -1;
}
/* Encrypting the id. */
aesedId = (unsigned char*)malloc(len + AES_BLOCK_SIZE);
memset(aesedId, 0, len + AES_BLOCK_SIZE);/* Modified for PPM#117496 [cppcheck Error Fix - Phase 1] */
//if(aes256EncryptMsg(cid, encryptedId, sessionKey, iv) != 0)
aesTxtLen = aes_encrypt_text(cid, len, aesedId, sessionKey, iv);
if(aesTxtLen > 0)
{
if(base64Encode(aesedId, aesTxtLen, &encodedId, &encodedIdLen) == 0)
{
if((rsaPub = getRSAPubKeyFromCertificate(certFile, &rsaSize)) != NULL)
{
encryptedKeyLen = RSA_public_encrypt(sizeof(sessionKey), sessionKey, encryptedKey, rsaPub, RSA_PKCS1_PADDING);
if(encryptedKeyLen != -1)
{
if(base64Encode(encryptedKey, encryptedKeyLen, &encodedKey, &encodedKeyLen) == 0)
{
rc = 0;
}
else
{
log_event(LOGCAT_POS, LL1, _HERE, "Key encoding failed.");
rc = -1;
}
}
else
{
log_event(LOGCAT_POS, LL1, _HERE, "Key encryption failed.");
rc = -1;
}
}
else
{
log_event(LOGCAT_POS, LL1, _HERE, "Failed to read RSA public key.");
rc = -1;
}
}
else
{
log_event(LOGCAT_POS, LL1, _HERE, "Id encoding failed.");
rc = -1;
}
}
else
{
log_event(LOGCAT_POS, LL1, _HERE, "Id encryption failed.");
rc = -1;
}
free(aesedId);
RSA_free(rsaPub);
if(rc == 0)
{
strncpy(encd, encodedId, encodedIdLen);
strncpy(skey, encodedKey, encodedKeyLen);
}
free(encodedId);
free(encodedKey);
return rc;
</code></pre>
<p>Here is my Java implementation:</p>
<pre><code>// Get the PBKDF2 key
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(customerId.toCharArray(), RefundUtil.getSalt(), 5, 256);
SecretKey tmp = factory.generateSecret(spec);
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] iv = md.digest(tmp.getEncoded());
IvParameterSpec ivspec = new IvParameterSpec(iv);
// Gets the PBKDF2Key RSA public encrypted
String sessionKey = rsaEncrypt(tmp.getEncoded());
LOGGER.info("Key: {}", sessionKey);
keyMap.put("key", sessionKey);
SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivspec);
keyMap.put("encVal", Base64.getEncoder().encodeToString(cipher.doFinal(customerId.getBytes("UTF-8"))));
return keyMap;
</code></pre>
<p>Salt function</p>
<pre><code>public static byte[] getSalt() {
byte[] salt = new byte[8];
SecureRandom sr;
try {
sr = SecureRandom.getInstance("SHA1PRNG");
sr.nextBytes(salt);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return salt;
}
</code></pre>
<p>//RSAencrypt function</p>
<pre><code> InputStream inStream = null;
try {
inStream = RefundUtil.class.getClassLoader().getResourceAsStream("refund.crt");
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
PublicKey pubKey = cert.getPublicKey();
Cipher encryptCipher = Cipher.getInstance("RSA");
encryptCipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] cipherText = encryptCipher.doFinal(sessionKey);
inStream.close();
return Base64.getEncoder().encodeToString(cipherText);
} catch (IOException e) {
LOGGER.error(e.getMessage());
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T14:50:03.247",
"Id": "454971",
"Score": "2",
"body": "Code review questions should normally be considered off-topic on stackoverflow. The main goal of SO is to be an archive of solved problems that programmers are likely to encounter. Most code review questions are only useful to the original asker, and will likely never be useful to anyone else."
}
] |
[
{
"body": "<p>You should move the first piece of Java code into its own method if it isn't already, as that would make calling and testing it easier.</p>\n\n<p>Also, your <code>getSalt()</code> method's <code>catch</code> block only prints the stack trace in case of exception, but still returns the value, is this intended?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T15:56:41.400",
"Id": "455014",
"Score": "0",
"body": "The first piece of Java code is copied from its function. I am not worried about such things at the moment. Rather I would like to know if I have done enough to replicate the steps performed in the C code or if I'm missing out anything. I could see a RSA encryption in the C code where it gets a cert file, read its key and does RSA public encryption. Is that possible in Java too? I mean to use a stored key and use it for RSA public encryption? If yes, could someone share any inputs as to how to get it done?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T22:38:57.500",
"Id": "232873",
"ParentId": "232871",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-20T08:45:27.077",
"Id": "232871",
"Score": "1",
"Tags": [
"java",
"cryptography",
"aes"
],
"Title": "Password hashing (PBKDF2) and RSA encrypt + AES 256 in Java"
}
|
232871
|
<p>I haven't written a linked list from scratch in a couple years, so I decided to take a stab at it again. After working on it on and off for a little over a week, I'm finally happy with it.</p>
<p>It implements <a href="https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence" rel="nofollow noreferrer">Sequence</a>. Since it overrides each method, having it extend an ABC wasn't really necessary, but I thought that it would be a good indicator of what the class can be used for.</p>
<p>This is a plain, basic LL. The only reference I'm holding is of the head, so most operations on it are inefficient.</p>
<p>It's composed of two parts: A basic <code>Node</code> class that I delegate a lot of the work to, and a <code>LinkedList</code> wrapper that handles size and maintains the node structure.</p>
<p>Example of use:</p>
<pre><code>>>> ll = LinkedList.from_iterable(range(20))
>>> ll
<0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19>
>>> del ll[5]
ll
<0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19>
ll[15 : 0 : -3]
<16, 13, 10, 7, 3>
>>> ll.index(14)
13
</code></pre>
<p>The main things that I want commented on:</p>
<ul>
<li><p><code>Node.from_iterable</code> has an awkward bit. Right now, I'm checking inside the loop if <code>cur</code> has been initialized yet each iteration, just to handle the very first element. I tried calling <code>next</code> on <code>iterable</code> to pre-initialize <code>head</code> before the loop, but then if <code>iterable</code> is empty I'll get a <code>StopIteration</code> thrown. I tried giving <code>next</code> a sentinel value, but then I needed to check for it later... It ended up getting messier than what I'm already doing, so I left it as-is.</p></li>
<li><p><code>remove</code> is ugly. In most other methods I was able to fall-back on some lower-level constructs to do most of the work. <code>remove</code> though proved to be kind of a corner case that doesn't share a lot with other functionality.</p></li>
</ul>
<p>Or anything else that is worth mentioning. I think this is the first time I've gone all out in creating a structure like this in Python, so I welcome any feedback.</p>
<pre><code>from __future__ import annotations
from typing import Generic, TypeVar, Optional, Iterator, Iterable, Union, Sequence, Tuple
from dataclasses import dataclass
from itertools import islice
from functools import reduce
T = TypeVar("T")
@dataclass
class _Node(Generic[T]):
data: T
tail: Optional[_Node[T]] = None
def insert_after(self, new_data: T) -> None:
old_tail = self.tail
self.tail = _Node(new_data, old_tail)
def remove_next(self) -> None:
if self.tail:
self.tail = self.tail.tail
def __iter__(self) -> Iterable[_Node[T]]:
cur = self
while cur:
yield cur
cur = cur.tail
def find_last(self) -> _Node[T]:
cur = self # Isn't actually necessary. self will never be an empty iterable
for node in self:
cur = node
return cur
def copy(self) -> Tuple[_Node[T], _Node[T], int]:
"""Produces a copy of the given node (including a shallow copy of the entire tail).
Returns a tuple of (copy_head, copy_last_node, copy_list_length)."""
return _Node.from_iterable(node.data for node in self)
@staticmethod
def from_iterable(iterable: Iterable[T]) -> Tuple[_Node[T], _Node[T], int]:
"""Constructs a node-list from an iterable.
Returns a tuple of (head, last_node, list_length). head and last_node will be None if iterable is empty."""
head = None
cur = None
count = 0
for t in iterable:
new_node = _Node(t)
# TODO: Eww. How to cleanly pre-initialize?
# TODO: Moving this out of the loop causes issues with next throwing when iterable is empty.
if cur:
cur.tail = new_node
cur = cur.tail
else:
head = new_node
cur = head
count += 1
return head, cur, count
def mul_node(self, n: int) -> Optional[_Node[T]]:
"""__mul__, but will return None if n is <= 0."""
if n <= 0:
return None
else:
initial_head, cur_last, _ = self.copy()
for _ in range(n - 1):
copy_head, copy_tail, _ = self.copy()
cur_last.tail = copy_head
cur_last = copy_tail
return initial_head
def __repr__(self) -> str:
return f"<{'-'.join(str(node.data) for node in self)}>"
def _wrap_negative_index(i: int, length: int) -> int:
"""Wraps negative indices to the back of the list."""
return i if i >= 0 else length + i
class LinkedList(Sequence[T]):
def __init__(self):
self._head: Optional[_Node] = None
self._size: int = 0
def _node_iter(self) -> Iterable[_Node[T]]:
if self._head:
return self._head
else:
return []
def _find_last_node(self) -> Optional[_Node]:
return self._head.find_last() if self._head else None
def _pop_head(self) -> _Node[T]:
"""Helper that replaces and returns the head. DOES NOT MODIFY THE SIZE!"""
popped = self._head
self._head = self._head.tail
return popped
def prepend(self, elem: T) -> None:
self.insert(0, elem)
def append(self, elem: T) -> None:
self.insert(len(self), elem)
def insert(self, key: int, elem: T) -> None:
if not self or key <= 0:
new_head = _Node(elem, self._head)
self._head = new_head
else:
node_before = self._get_ith_node(min(key - 1, len(self) - 1))
node_before.insert_after(elem)
self._size += 1
def count(self, elem: T) -> int:
return reduce(lambda found, t: found + 1 if elem == t else found,
self,
0)
def index(self, elem: T, start: int = 0, stop: Optional[int] = None) -> int:
self._assert_inbounds(start)
checked_stop = stop if stop is not None else len(self) - 1
indexed_search_slice = islice(enumerate(self), start, checked_stop)
try:
return next(i for i, t in indexed_search_slice if t == elem)
except StopIteration: # If the generator is empty, next will raise a StopIteration
raise ValueError(f"{elem} is not in the list in the range specified.")
def extend(self, iterable: Iterable[T]) -> None:
new_nodes, _, count = _Node.from_iterable(iterable)
if last_node := self._find_last_node():
last_node.tail = new_nodes
else:
self._head = new_nodes
self._size += count
def pop(self, key: Optional[int] = None) -> T:
key = _wrap_negative_index(key, len(self)) if key is not None else len(self) - 1
self._assert_inbounds(key)
if key == 0:
popped = self._pop_head()
else:
node_before = self._get_ith_node(key - 1)
popped = node_before.tail
node_before.remove_next()
self._size -= 1
return popped.data
# TODO: Neaten up
def remove(self, elem: T): # TODO: Eww
prev_node = None
for node in self._node_iter():
if node.data == elem:
if prev_node:
prev_node.remove_next()
else:
self._pop_head()
self._size -= 1
return
prev_node = node
raise ValueError(f"{elem} not in list.")
def reverse(self):
self._head, *_ = _Node.from_iterable(reversed(self))
def __bool__(self):
return bool(self._head)
def __iter__(self):
return (node.data for node in self._node_iter())
def __len__(self):
return self._size
def _assert_inbounds(self, *wrapped_indices: int):
for index in wrapped_indices:
if not 0 <= index < len(self):
raise IndexError(f"Index {index} out of bounds for list of size {len(self)}.")
def _get_ith_node(self, i: int) -> _Node[T]:
self._assert_inbounds(i)
return next(islice(self._head, i, None))
def __getitem__(self, key: Union[int, slice]) -> Union[T, LinkedList[T]]:
if isinstance(key, int):
node = self._get_ith_node(_wrap_negative_index(key, len(self)))
return node.data
else:
if key.step > 0:
ll_slice = islice(self, key.start, key.stop, key.step) # FIXME: Need to handle a negative step
return LinkedList.from_iterable(ll_slice)
else:
surrogate = list(self)
start = len(self) - 1 if key.start is None else key.start
stop = -1 if key.stop is None else key.stop
indices = range(start, stop, key.step)
return LinkedList.from_iterable(surrogate[i] for i in indices)
def __setitem__(self, key: int, elem: T) -> None:
# TODO: Allow for slice assignment?
node = self._get_ith_node(_wrap_negative_index(key, len(self)))
node.data = elem
def __delitem__(self, key: int) -> None:
self.pop(_wrap_negative_index(key, len(self)))
def __contains__(self, elem: T) -> bool:
return any(t == elem for t in self)
def __repr__(self) -> str:
return f"<{', '.join(str(t) for t in self)}>"
def __reversed__(self) -> Iterator[T]:
return reversed(list(self)) # I think this is the best option for a simple SL LL
def __add__(self, iterable: Iterable[T]) -> LinkedList[T]:
copy_head, copy_end, copy_count = _Node.from_iterable(self)
added_head, added_end, added_count = _Node.from_iterable(iterable)
copy_end.tail = added_head
return LinkedList._from_existing_nodes(copy_head, copy_count + added_count)
def __iadd__(self, iterable: Iterable[T]) -> LinkedList[T]:
self.extend(iterable)
return self
def __mul__(self, n: int) -> LinkedList[T]:
if not self or n <= 0:
return LinkedList.from_iterable([])
else:
return LinkedList._from_existing_nodes(self._head.mul_node(n), max(0, len(self) * n))
def __imul__(self, n: int) -> LinkedList[T]:
if self._head:
self._head = self._head.mul_node(n)
self._size *= max(n, 0)
return self
@staticmethod
def _from_existing_nodes(head: _Node[T], node_count: int) -> LinkedList[T]:
l_list = LinkedList()
l_list._size = node_count
l_list._head = head
return l_list
@staticmethod
def from_iterable(iterable: Iterable[T]) -> LinkedList[T]:
head, _, count = _Node.from_iterable(iterable)
return LinkedList._from_existing_nodes(head, count)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T23:27:48.260",
"Id": "455048",
"Score": "0",
"body": "Oops. `# FIXME: Need to handle a negative step` isn't supposed to be there. I dealt with that."
}
] |
[
{
"body": "<p>Using a <a href=\"https://en.wikipedia.org/wiki/Linked_list#Sentinel_nodes\" rel=\"nofollow noreferrer\">dummy node</a> is one way to simplify the logic in <code>_Node.from_iterable</code> and <code>LinkedList.remove</code>. We incur a constant-space cost of one extra node, and in return we don't need to write a separate branch of logic to handle the empty/null head case:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>@dataclass\nclass _DummyNode(_Node[T]):\n data: Optional[T] = None\n tail: Optional[_Node[T]] = None\n</code></pre>\n\n<pre class=\"lang-py prettyprint-override\"><code>@staticmethod\ndef from_iterable(iterable: Iterable[T]) -> Tuple[Optional[_Node[T]], Optional[_Node[T]], int]:\n \"\"\"Constructs a node-list from an iterable.\n Returns a tuple of (head, last_node, list_length). head and last_node will be None if iterable is empty.\"\"\"\n dummy_head: _DummyNode[T] = _DummyNode()\n cur: _Node[T] = dummy_head\n count = 0\n\n for t in iterable:\n cur.tail = _Node(t)\n cur = cur.tail\n count += 1\n\n return dummy_head.tail, None if count == 0 else cur, count\n</code></pre>\n\n<pre class=\"lang-py prettyprint-override\"><code>class LinkedList(Sequence[T]):\n def __init__(self):\n self._dummy_head: _DummyNode[T] = _DummyNode()\n self._size: int = 0\n\n def _all_node_iter(self) -> Iterable[_Node[T]]:\n \"\"\"Iterable over all nodes, including the dummy head node\"\"\"\n yield self._dummy_head\n yield from self._node_iter()\n\n def _node_iter(self) -> Iterable[_Node[T]]:\n \"\"\"Iterable over only the real nodes\"\"\"\n cur = self._dummy_head.tail\n while cur:\n yield cur\n cur = cur.tail\n\n # [...]\n\n def remove(self, elem: T) -> None:\n for prev, cur in zip(self._all_node_iter(), self._node_iter()):\n if cur.data == elem:\n prev.remove_next()\n self._size -=1\n return\n raise ValueError(f\"{elem} not in list.\")\n\n # [...]\n</code></pre>\n\n<p>This does involve changing the design of <code>LinkedList</code> to use <code>_dummy_head</code> instead of <code>_head</code>, but other methods like <code>insert</code> can be refactored with simpler logic in a similar way.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T12:00:39.513",
"Id": "455085",
"Score": "0",
"body": "Thanks, I had never seen dummy nodes in this context before."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T05:44:53.043",
"Id": "232926",
"ParentId": "232875",
"Score": "1"
}
},
{
"body": "<h1><code>from_iterable</code></h1>\n\n<p>Based on my answer to <a href=\"https://codereview.stackexchange.com/a/232694/123200\">this</a> linked list question</p>\n\n<pre><code>def from_iterable(iterable: Iterable[T]) -> Tuple[_Node[T], _Node[T], int]:\n \"\"\"Constructs a node-list from an iterable.\n Returns a tuple of (head, last_node, list_length). head and last_node will be None if iterable is empty.\"\"\"\n it = iter(iterable)\n\n try:\n head = current = _Node(next(it))\n count = 1\n except StopIteration:\n return None, None, 0\n\n for count, t in enumerate(it, 2):\n current.tail = current = _Node(t)\n\n return head, current, count\n</code></pre>\n\n<blockquote>\n<pre><code>n = _Node.from_iterable(range(6))\n</code></pre>\n</blockquote>\n\n<pre><code>(\n _Node(data=0, tail=_Node(data=1, tail=_Node(data=2, tail=_Node(data=3, tail=_Node(data=4, tail=_Node(data=5, tail=None)))))),\n _Node(data=5, tail=None),\n 6\n)\n</code></pre>\n\n<h1><code>remove</code></h1>\n\n<p>For the <code>remove</code> you can use 2 ways to make it more clear: you can do the check whether the head is the element to remove outside of the loop, and use the <code>pairwise</code> itertools recipe to iterate over the node 2 by 2</p>\n\n<pre><code>from itertools import tee\ndef pairwise(iterable):\n \"s -> (s0,s1), (s1,s2), (s2, s3), ...\"\n a, b = tee(iterable)\n next(b, None)\n return zip(a, b)\n\n\n\ndef remove(self, elem: T): \n if self.head.data == elem:\n self._pop_head()\n self._size -= 1\n return\n for first, second in pairwise(self._node_iter()):\n if second.data == elem:\n first.remove_next()\n self._size -= 1\n return\n raise ValueError(f\"{elem} not in list.\")\n</code></pre>\n\n<p>Or you can use <code>pop</code> This results in cleaner code, but 2 iterations until the index</p>\n\n<pre><code>def remove(self, elem: T):\n for i, value in enumerate(self):\n if value == elem:\n self.pop(i)\n return\n raise ValueError(f\"{elem} not in list.\")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T12:02:20.990",
"Id": "455086",
"Score": "0",
"body": "Thanks. Those are both much cleaner."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T08:42:26.603",
"Id": "232929",
"ParentId": "232875",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T22:54:49.547",
"Id": "232875",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"linked-list"
],
"Title": "Barebones but Sequence compliant Singly Linked List"
}
|
232875
|
<p>I'm a newbie playing around with <strong>Fortran 90</strong> and <strong>openmp</strong> and wrote the code below (a simple 2D heat transfer simulation) for testing purposes.</p>
<p><strong>So far I don't see any speedup by using openmp / parallel processing.</strong> In fact, it gets slower when I use more procs. I understand that the parallelization requires some extra overhead, but my <code>T</code> array should be big enough (2500 x 1500) to make a parallelization "worth it". What am I doing wrong? What can be improved?</p>
<p>I am compiling with:
<code>gfortran -fopenmp heat.f90 -o heat</code></p>
<p>and setting the number of threads in my shell with:
<code>export OMP_NUM_THREADS=4</code></p>
<p><code>heat.f90</code> is below:</p>
<pre><code>program heat
use omp_lib
implicit none
integer, parameter :: nx = 2500
integer, parameter :: ny = 1500
real, parameter :: H = 1.
real, parameter :: alpha = 1.e-4
real, parameter :: sigma = 0.2
real, parameter :: dt = 0.001
real, parameter :: physical_time = 50.
real x, y
integer i, j
real aspect, L, dx, dy
real, dimension (:,:), allocatable :: T, Tn
real d2Tdx2, d2Tdy2
! -----
integer ts, total_ts, ts_left, frames_total, output_period_ts, pic_counter
real t1, t2, time_elapsed, run_rate, progress_pct
real time_left_s, time_left_h, time_left_d, time_total_s, time_total_h, time_total_d
character(len=16) :: pic_counter_str
! -----
aspect = real(nx)/real(ny)
L = H*aspect
dx = L/real(nx)
dy = H/real(ny)
! ----- initialize T
allocate (T(nx,ny))
allocate (Tn(nx,ny))
do i=1, nx
do j=1, ny
x = real(i)/real(nx)*L
y = real(j)/real(ny)*H
T(i,j) = 10. + 2. * ( &
1./(2.*3.14*sigma**2.) * &
exp(-1. * ( (x-L/2.)**2. + (y-H/2.)**2. ) / (2.*sigma**2.)) &
)
enddo
enddo
! ----- report
total_ts = ceiling(physical_time/dt)
frames_total = 30*20
output_period_ts = int(total_ts/frames_total)
print '(A, ES10.4)', 'dt ................... ', dt
print '(A, ES10.4)', 'physical time ........ ', physical_time
print '(A, I2)', 'num procs ............ ', omp_get_num_procs()
print '(A, I2)', 'num threads .......... ', omp_get_max_threads()
print '(A, I6)', 'timesteps ............ ', total_ts
print '(A, I4)', 'output period [ts] ... ', output_period_ts
print '(A, I6)', 'num frames ........... ', frames_total
print *, ' '
print *, 'ts, %, time left [h], time total [h]'
print *, '------------------------------------'
! ----- evolve T field
call cpu_time (t1)
pic_counter = 0
do ts = 0, total_ts
if (mod(ts,output_period_ts) .eq. 0) then
! ----- plot (optional)
!open(3, file="T.dat", access="stream")
!write(3) T(:,:)
!close(3)
!write (pic_counter_str,'(I5.5)') pic_counter
!call system('gnuplot -c plot3d.gnu '//trim(pic_counter_str))
!pic_counter = pic_counter + 1
! ----- quick check if everythings alright
if (isnan(T(100,100))) then
print *, "divergence! decrease ts."
end if
if (isnan(T(100,100))) call EXIT(1)
! ----- report run speed stats
if ( ts .gt. 0) then
call cpu_time (t2)
time_elapsed = t2-t1
ts_left = total_ts-ts
run_rate = real(ts)/time_elapsed
time_left_s = real(ts_left)/run_rate
time_left_h = time_left_s/3600.
time_left_d = time_left_h/24.
time_total_s = real(total_ts)/run_rate
time_total_h = time_total_s/3600.
time_total_d = time_total_h/24.
progress_pct = 100.*real(ts)/real(total_ts)
print '(I8, F7.2, A, F8.2, F8.2)', ts, progress_pct, "%", time_left_h, time_total_h
end if
end if
! ----- energy eqn
Tn(:,:) = T(:,:)
!$omp parallel shared(T) private(i,j,d2Tdx2,d2Tdy2)
!$omp do
do i=2, nx-1
do j=2, ny-1
d2Tdx2 = ( Tn(i+1,j) - 2.*Tn(i,j) + Tn(i-1,j) ) / dx**2.
d2Tdy2 = ( Tn(i,j+1) - 2.*Tn(i,j) + Tn(i,j-1) ) / dy**2.
T(i,j) = Tn(i,j) + dt*(alpha*(d2Tdx2 + d2Tdy2))
end do
end do
!$omp end do
!$omp end parallel
!! adiabatic BCs
T(:, 1) = T(:, 2)
T(:, ny) = T(:, ny-1)
T(1, :) = T(2, :)
T(nx, :) = T(nx-1, :)
! -----
end do
end program heat
</code></pre>
<p>... the (optional) <code>gnuplot</code> (5.0) plot script <code>plot3d.gnu</code> is below, uncomment the 'plot' portion of the code above for image output if you'd like</p>
<pre><code>#!/usr/bin/gnuplot --persist
pic_counter=ARG1
png_filename = sprintf("%s%s%s", "T_", pic_counter, ".png")
set terminal pngcairo background rgb "white" enhanced font "arial,16" fontscale 1.0 size 1280, 720
set key top
set border 1+2+4+8+16+32+64+256+512
set xrange [0:2500]
set yrange [0:1500]
set zrange [10:20]
set cbrange [10:18]
set view equal xy
set style data pm3d
set pm3d implicit at s hidden3d depth noborder
set pm3d lighting primary 0.5 specular 0.4
set view 57, 20, 2.05, 0.55
#show view
set colorbox horizontal user origin 0.05, 0.05 size 0.35, 0.05
set output png_filename
splot "T.dat" binary array=2500x1500 format="%f" notitle
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>One problem is that you're using <code>d2Tdx2</code> and <code>d2Tdy2</code> inside your omp loop but they're not listed as private in the parallel directive. This will cause all the threads to use the same variables with a big performance hit, and possibly errors in the calculations.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T07:32:22.473",
"Id": "454998",
"Score": "0",
"body": "Great catch! This came from some last minute edits before posting on SE. Unfortunately fixing this does not help with the parallel performance. I've updated the question accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T09:32:00.407",
"Id": "455072",
"Score": "1",
"body": "Assuming \"cpu_time()\" measures what the name says it does, then you should expect it to get worse when you add parallelism (due to some overhead in creating threads and so on). You need to measure elapsed (wall-clock) time to see a speedup, for which omp_get_wtime() is a simple and useful function. If you are measuring performance, you should also compile with optimization enabled (e.g. -O3)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T03:20:17.247",
"Id": "232883",
"ParentId": "232878",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-23T23:10:23.850",
"Id": "232878",
"Score": "4",
"Tags": [
"beginner",
"numerical-methods",
"openmp",
"fortran"
],
"Title": "Fortran 90 / openmp heat transfer simulation optimization"
}
|
232878
|
<p>My goal here is to make data driven nested forms in React. I've created a function that points to a form configuration JSON, which can contain both components and references to other configuration files, with their own components. I'm splitting it to separate files to keep things DRY and to get an easier overview (hierarchy can be about 5 levels deep, one JSON file would be rather hard to overview).</p>
<p>I've introduced <code>$ref</code> to be able to point to another JSON configuration and <code>$extends</code> for inheritance (configurations can differ dependings on context but have common properties). <code>args</code> will be spread out as props to the component.</p>
<p><strong>config-builder.js</strong></p>
<pre><code>function createConfiguration(configuration) {
return _.reduce(configuration.components, (result, data) => {
// if it's a reference to another configuration - fetch it - otherwise use as is
const component = data.$ref ? getComponentByReference(data) : data
return addResult(result, component.key, component.components ? { ...component, components: createConfiguration(component) } : component)
}, {})
}
function getComponentByReference(data) {
const component = _.merge({}, configMap[data.$ref], data)
const result = component.$extends ? _.merge({}, configMap[component.$extends], component) : component
// clear internal values like $ref, $extends
return _.omitBy(result, (value, key) => _.startsWith(key, '$'))
}
// use an array to wrap results to handle multiple keys of the same type on same level
function addResult(result, key, data) {
if(!result[key]) {
result[key] = [data]
} else {
result[key].push(data)
}
return result
}
</code></pre>
<p><strong>foo.json</strong></p>
<pre><code>{
"key": "foo",
"type": "DefaultContainer",
"components": [
{ "key": "name", "type": "Text" },
{ "$ref": "Bar" }
]
}
</code></pre>
<p><strong>bar.json</strong></p>
<pre><code>{
"key": "bar",
"type": "DefaultContainer",
"components": [
{ "key": "id", "type": "DropDown", "args": { options: [] } }
]
}
</code></pre>
<p><a href="https://jsfiddle.net/wkmrp4gc/" rel="nofollow noreferrer">https://jsfiddle.net/wkmrp4gc/</a></p>
|
[] |
[
{
"body": "<h2>Good things</h2>\n\n<p>This code uses <code>const</code> for variables that don't get re-assigned.</p>\n\n<p>The functions are concise, though some of the lines are a bit long due to ternary operators.</p>\n\n<h2>Suggestions</h2>\n\n<p>Bear in mind that functional programming is typically slower than imperative because each iteration leads to a function being added to the call stack. This would be noticeable with large data sets. Having the function <code>addResult()</code> seems like an excess step since it is only called in one spot. The lines to ensure the object at the given key is an array and push an element to that array could simply exist in the callback to the <code>_.reduce()</code> call. </p>\n\n<p>Also, instead of either creating a new array with the data item or pushing it into an existing array, it could create an empty array when appropriate and then always push the data. This may be slightly less performant but requires fewer lines of code than storing the data in a temporary variable.</p>\n\n<pre><code>function createConfiguration(configuration) {\n return _.reduce(configuration.components, (result, data) => {\n const component = data.$ref ? getComponentByReference(data) : data;\n if(!result[component.key]) {\n result[component.key] = [];\n }\n result[component.key].push(component.components ? { ...component, components: createConfiguration(component) } : component)\n return result;\n }, {});\n}\n</code></pre>\n\n<p>Unless you fully understand the ways <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion\" rel=\"nofollow noreferrer\">Automatic semicolon insertion</a> can be broken by certain statements, add semi-colons to terminate the lines. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-01T06:08:58.170",
"Id": "233217",
"ParentId": "232880",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "233217",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T01:27:52.067",
"Id": "232880",
"Score": "6",
"Tags": [
"javascript",
"json",
"ecmascript-6",
"react.js",
"lodash.js"
],
"Title": "Recursive component JSON configuration builder"
}
|
232880
|
<p>Here’s my code, the traps are the slightly visible squares. The user controls a red square (with arrow keys) and cannot touch the walls or traps or else the game resets. Additionally, if the user touches the green line, the game ends.</p>
<p>Code:</p>
<hr>
<pre><code> <!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>Maze Game</title>
</head>
<body>
<header> </header>
<nav> </nav>
<section>
<div>
<canvas id="canvas" width="907" height="907">
This text is displayed if your browser does not support HTML5 Canvas.
</canvas>
</div>
<script type="text/javascript">
var canvas;
var ctx;
var dx = 5;
var dy = 5;
var x = 345;
var y = 135;
var WIDTH = 907;
var HEIGHT = 907;
var img = new Image();
var collision = 0;
//set minutes
var mins = 2;
//calculate the seconds
var secs = mins * 60;
//countdown function is evoked when page is loaded
function countdown() {
setTimeout('Decrement()', 60);
}
//Decrement function decrement the value.
function Decrement() {
if (document.getElementById) {
minutes = document.getElementById("minutes");
seconds = document.getElementById("seconds");
//if less than a minute remaining
//Display only seconds value.
if (seconds < 59) {
seconds.value = secs;
}
//Display both minutes and seconds
//getminutes and getseconds is used to
//get minutes and seconds
else {
minutes.value = getminutes();
seconds.value = getseconds();
}
//when less than a minute remaining
//colour of the minutes and seconds
//changes to red
if (mins < 1) {
minutes.style.color = "red";
seconds.style.color = "red";
}
//if seconds becomes zero,
//then page alert time up
if (mins < 0) {
alert('Times up!');
minutes.value = 0;
seconds.value = 0;
document.location.reload();
clearInterval(interval); // Needed for Chrome to end game
}
//if seconds > 0 then seconds is decremented
else {
secs--;
setTimeout('Decrement()', 1000);
} }
}
function getminutes() {
//minutes is seconds divided by 60, rounded down
mins = Math.floor(secs / 60);
return mins;
}
function getseconds() {
//take minutes remaining (as seconds) away
//from total seconds remaining
return secs - Math.round(mins * 60);
}
function rect(x,y,w,h) {
ctx.beginPath();
ctx.rect(x,y,w,h);
ctx.closePath();
ctx.fill();
}
function clear() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
ctx.drawImage(img, 0, 0);
}
function init() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
img.src = "canvas.png";
return setInterval(draw, 10);
}
function doKeyDown(evt){
switch (evt.keyCode) {
case 38: /* Up arrow was pressed */
if (y - dy > 0){
y -= dy;
clear();
checkcollision();
if (collision == 1){
y += dy;
collision = 0;
}
}
break;
case 40: /* Down arrow was pressed */
if (y + dy < HEIGHT ){
y += dy;
clear();
checkcollision();
if (collision == 1){
y -= dy;
collision = 0;
}
}
break;
case 37: /* Left arrow was pressed */
if (x - dx > 0){
x -= dx;
clear();
checkcollision();
if (collision == 1){
x += dx;
collision = 0;
}
}
break;
case 39: /* Right arrow was pressed */
if ((x + dx < WIDTH)){
x += dx;
clear();
checkcollision();
if (collision == 1){
x -= dx;
collision = 0;
}
}
break;
}
}
function checkcollision() {
var imgd = ctx.getImageData(x, y, 15, 15);
var pix = imgd.data;
for (var i = 0; n = pix.length, i < n; i += 4) {
if (pix[i] == 0) {
collision = 1;
}
} }
function draw() {
clear();
ctx.fillStyle = "red";
rect(x, y, 15,15);
}
init();
window.addEventListener('keydown',doKeyDown,true);
</script>
<body onload="countdown();">
<div>
Time Left ::
<input id="minutes" type="text" style="width: 16px;
border: none; font-size: 30px;
font-weight: bold; color: black;"><font size="30"> :
</font>
<input id="seconds" type="text" style="width: 40px;
border: none; font-size: 30px;font-weight: bold; color: black;">
</section>
<aside> </aside>
<footer> </footer>
</body>
</html>
</code></pre>
<p><img src="https://i.stack.imgur.com/57Vay.gif" alt="enter image description here"></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T03:32:49.863",
"Id": "454979",
"Score": "0",
"body": "Please help me figure this out!!!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T06:38:57.107",
"Id": "454995",
"Score": "1",
"body": "Welcome to CodeReview@SE. As shown, the code file contains extraneous contents after the closing `</html>`. [To the best of your knowledge: Does this code work?](https://codereview.stackexchange.com/help/on-topic)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T12:32:51.980",
"Id": "455009",
"Score": "0",
"body": "Trying it as-is will result in an error, but substituting a temporary image makes the game run. Without proper markers it does not do anything useful tho. An actual image to load would be useful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T15:36:24.220",
"Id": "455013",
"Score": "0",
"body": "Sigh, this looks a really cool question, but if you want good feedback, we should be able to run it, and right now it wont because of the image requirement. Note to vote-closers; there is enough context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T23:52:23.733",
"Id": "455183",
"Score": "0",
"body": "Sorry guys, I totally forgot about the canvas.png. I added it so you can save it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T08:31:42.953",
"Id": "455220",
"Score": "0",
"body": "The HTML is broken. There are two opening `body` tags."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-29T18:53:25.827",
"Id": "455683",
"Score": "0",
"body": "Might I suggest using https://jsfiddle.net/? It'll help others run your code & help yourself ensure you're including enough details for others to run the project."
}
] |
[
{
"body": "<p>From a lengthy review;</p>\n<ul>\n<li>Clean up tags that are not used (doubles like <code>body</code> or unused like <code>nav</code>)</li>\n<li>Use a beautifier like <a href=\"https://beautifier.io/\" rel=\"nofollow noreferrer\">https://beautifier.io/</a></li>\n<li>Make sure you close your tags properly (the closing tag of the time section was missing)</li>\n<li>Leverage css styling, inline styling does not scale, and HTML is not the right place to style!</li>\n<li>document.getElementById is supported since IE 5.5, not need to check for <code>if (document.getElementById)</code>\n<ul>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById</a></li>\n</ul>\n</li>\n<li>Your starting image should probably not have a red square ;)</li>\n<li>I prefer naming to be either Spartan (one letter) or spelled out, no middle ground like <code>evt</code></li>\n<li>You should use <code>e.preventDefault();</code> to prevent the browser window from trying to act on the key arrow events</li>\n<li>Redesign your code to have fewer globals, like <code>collision</code> which is only set in 1 place, and checked in 1 place</li>\n<li>15 is a repeated magical constant, it should be a variable</li>\n<li>JavaScript uses lowerCamelCase, so <code>getseconds</code> -> <code>getSeconds</code></li>\n<li>Using <code>input</code> tags for the minutes/seconds is unorthdox, since they are not input fields</li>\n<li><code>secs</code> was an unfortunate name, <code>secondsLeft</code> might have been better, I went for <code>timer</code></li>\n<li>The movement code contained a lot of pasting, you could make it data structure driven</li>\n<li>The checking for mines and the green line end of the game is not implemented..</li>\n</ul>\n<p>Bigger topic, do not use the UI to store state, I repeat, do not use the UI to store state. You are counting on the black lines in the image as walls, I had to downsample the image because an answer can only 64K long (and the full image is 72K) Because of this, none of the detection logic worked any more. Using the UI to store state will always bite you, when you least expect it. Yes, I am still bitter.</p>\n<p>I wrote a counter proposal 'that works', it still has many globals, but at least in this state I would be willing to maintain the code.</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 minutes = document.getElementById(\"minutes\");\nconst seconds = document.getElementById(\"seconds\");\nconst canvas = document.getElementById(\"canvas\");\n\nlet ctx;\nconst img = new Image();\n//Dimensions\nconst WIDTH = canvas.clientWidth;\nconst HEIGHT = canvas.clientHeight;\n//Player start position\nlet x = 170;\nlet y = 60;\nconst playerSize = 15;\n\n//The timer starts at 2 minutes\nlet timer = 2 * 60;\n\n//Decrement function decrement the value.\nfunction countDown() {\n //Calculate label values\n minutes.textContent = ~~(timer/60); //Fancy math trick\n seconds.textContent = timer % 60;\n\n //when less than a minute remains, change to red\n if (timer < 60) {\n minutes.style.color = \"red\";\n seconds.style.color = \"red\";\n }\n //alert if the time is up\n //then page alert time up\n if (timer < 0) {\n alert('Times up!');\n minutes.value = 0;\n seconds.value = 0;\n //Not sure about this.. at all..\n document.location.reload();\n clearInterval(interval); // Needed for Chrome to end game <- Not sure I believe you\n } else { //if seconds > 0 then keep counting down\n timer--;\n setTimeout(countDown, 1000);\n }\n}\n\n//I almost dropped this, you only use this once \n//I assume you plan to do more with this\nfunction rect(x, y, w, h) {\n ctx.beginPath();\n ctx.rect(x, y, w, h);\n ctx.closePath();\n ctx.fill();\n}\n\n//init() is called from body.onload in HTML\nfunction init() {\n ctx = canvas.getContext(\"2d\");\n \n //This is set with base64 encoding below\n //Because otherwise ctx.getImageData will throw a security exception when running on stackoverflow\n //In real life, with the image and source on the same host, there is no need for base64 shenanigans\n //img.src = \"https://i.stack.imgur.com/57Vay.gif\";\n\n //Moved this here, it's part of the initialization.\n window.addEventListener('keydown', doKeyDown, true);\n \n //This draws every 10 milliseconds, so 100fps, not sure this is needed\n setInterval(draw, 10);\n \n //Start the countdown\n setTimeout(countDown, 60);\n}\n\nfunction draw() {\n clear();\n ctx.fillStyle = \"red\";\n rect(x, y, playerSize, playerSize);\n}\n\nfunction clear() {\n ctx.clearRect(0, 0, WIDTH, HEIGHT);\n ctx.drawImage(img, 0, 0);\n}\n\nfunction doKeyDown(e) {\n const moveSize = 5;\n const moves = {\n 37: {dx: -moveSize, dy: 0}, /* Left arrow was pressed */\n 38: {dy: -moveSize, dx: 0}, /* Up arrow was pressed */\n 39: {dx: moveSize, dy: 0}, /* Right arrow was pressed */\n 40: {dy: moveSize, dx: 0} /* Down arrow was pressed */\n }\n\n if(moves[e.keyCode]){\n const move = moves[e.keyCode];\n x += move.dx;\n y += move.dy;\n clear();\n if (hasCollision()) {\n x -= move.dx;\n y -= move.dy;\n }\n e.preventDefault();\n }\n}\n\n/* This only checks for the walls, not for the exit or the mines*/\nfunction hasCollision() {\n //checkingCollision = true;\n const imageData = ctx.getImageData(x, y, playerSize, playerSize);\n const pixels = imageData.data;\n const n = pixels.length;\n\n for (var i = 0; i < n; i += 4) {\n //Because black lines have rgb code r0,g0,b0 \n //And we have no other color that has zero as the r value\n //If we had, then this check would have to be more cumbersome!\n \n //Update: downscaling the image must have added some quite black, but not exactly black images\n //So I changed the check to pixels[i] < 100\n if (pixels[i] < 100 ) {\n return true;\n }\n }\n}\n\n\n//Obviously, this does not belong here.. it should be in init()\n//However the StackOverflow editor is suffering from this huge string, so I've put it at the end to put it and myself out of our misery\nimg.setAttribute('src','data:image/png;base64,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');</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#minutes {width: 16px;border: none;font-weight: bold; color: black}\n#seconds {width: 40px;border: none;font-weight: bold; color: black}\n.bigFont {font-size: 30px}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><!doctype html>\n<html>\n\n<head>\n <meta charset=\"UTF-8\" />\n <title>Maze Game</title>\n</head>\n\n<body onload=\"init()\">\n <section>\n <div>\n <canvas id=\"canvas\" width=\"454\" height=\"454\">\n This text is displayed if your browser does not support HTML5 Canvas.\n </canvas>\n </div>\n <div class=\"bigFont\">\n Time Left :: <span id=\"minutes\" type=\"text\">2</span> : <span id=\"seconds\" type=\"text\" style=\"\">0</span>\n </div>\n </section>\n <aside> </aside>\n <footer> </footer>\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-07-02T14:35:47.170",
"Id": "480803",
"Score": "1",
"body": "One small remark: \"countdown\" can be spelled as a single word, so writing it with a lower case \"d\" is fine IMO."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-02T14:49:47.720",
"Id": "480806",
"Score": "1",
"body": "'Fortunately' there was a pattern of that, fixed!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-02T12:52:55.590",
"Id": "244874",
"ParentId": "232884",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T03:31:45.907",
"Id": "232884",
"Score": "3",
"Tags": [
"javascript",
"game",
"collision"
],
"Title": "Creating a maze game where the game resets if you hit traps/walls and finishes when you hit a different color"
}
|
232884
|
<p>I am a beginner Java programmer and am in need of someone to read over it and help me condense my repetitive coding. I wrote code for a Bingo game and feel like I repeat code too often. If anyone could help me with my over obsessive use of repetitive code it would be greatly appreciated </p>
<pre><code>package bingo;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
public class Bingo {
static int b[] = new int[5];
static int i[] = new int[5];
static int n[] = new int[4];
static int g[] = new int[5];
static int o[] = new int[5];
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception e) {
}
start();
}
public static void start() {
//Creating Variables for the frame...
JFrame k = new JFrame("Bingo!");
JLabel bk = new JLabel(new ImageIcon("images/bk.png"));
JButton Play = new JButton();
JButton view = new JButton();
JLabel nice = new JLabel(new ImageIcon("images/bk2.png"));
//Setting size of JFrame...
k.setSize(600, 680);
k.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Setting the location of the labels
bk.setBounds(-10, 170, 600, 200);
Play.setBounds(190, 400, 190, 100);
nice.setBounds(0, 0, 600, 680);
view.setBounds(235, 520, 100, 50);
Play.setForeground(Color.BLACK);//sets foreground/background/font
Play.setContentAreaFilled(false);
Play.setFocusPainted(false);
Play.setFont(new Font("Helvetica", Font.BOLD, 12));
Play.setText("Generate Card");
view.setForeground(Color.WHITE);//sets foreground/background/font
view.setContentAreaFilled(false);
view.setFocusPainted(false);
view.setFont(new Font("Helvetica", Font.BOLD, 10));
view.setText("Cards");
k.add(bk);
k.add(Play);
k.add(view);
k.add(nice);
k.setLayout(null);
k.setVisible(true);
Play.addActionListener(new ActionListener() { //Action Listener when called, calls random();
public void actionPerformed(ActionEvent e) {
k.dispose();
random();
}
});
view.addActionListener(new ActionListener() { //Action Listener when pressing "Generate Card"
public void actionPerformed(ActionEvent e) {
k.dispose();
stats();
}
}); //Action listener when called, calls stats();
}
public static void stats() {
JFrame k = new JFrame();//creating variables for all labels
JLabel bk = new JLabel(new ImageIcon("images/bk2.png"));
JLabel title = new JLabel(new ImageIcon("images/title.png"));
JLabel star = new JLabel(new ImageIcon("images/star.png"));
JButton gen = new JButton();
JButton back = new JButton("Back");
back.setForeground(Color.WHITE);//sets foreground/background/font
back.setContentAreaFilled(false);
back.setFocusPainted(false);
gen.setText("Generate Card");//sets foreground/background/font
gen.setForeground(Color.WHITE);
gen.setContentAreaFilled(false);
gen.setFocusPainted(false);
int x = 175;
JTextField B[] = new JTextField[5];//Jtextfield arrays for user input
JTextField I[] = new JTextField[5];
JTextField N[] = new JTextField[4];
JTextField G[] = new JTextField[5];
JTextField O[] = new JTextField[5];
for (int p = 0; p < B.length; p++) {//for loops that set bounds to each index in each Jtextfield array
B[p] = new JTextField();
B[p].setBounds(100, x, 75, 75);
x = x + 75;
B[p].setOpaque(false);
k.add(B[p]);
}
x = 175;
for (int p = 0; p < I.length; p++) {
I[p] = new JTextField();
I[p].setBounds(175, x, 75, 75);
x = x + 75;
I[p].setOpaque(false);
k.add(I[p]);
}
x = 175;
for (int p = 0; p < N.length; p++) {
N[p] = new JTextField();
while (x == 325) {
x = x + 75;
}
N[p].setBounds(250, x, 75, 75);
x = x + 75;
N[p].setOpaque(false);
k.add(N[p]);
}
x = 175;
for (int p = 0; p < G.length; p++) {
G[p] = new JTextField();
G[p].setBounds(325, x, 75, 75);
x = x + 75;
G[p].setOpaque(false);
k.add(G[p]);
}
x = 175;
for (int p = 0; p < O.length; p++) {
O[p] = new JTextField();
O[p].setBounds(400, x, 75, 75);
x = x + 75;
O[p].setOpaque(false);
k.add(O[p]);
}
for (int p = 0; p < B.length; p++) {
try {
N[p].setFont(new Font("Comic Sans MS", Font.BOLD, 18));
} catch (Exception e) {
}
B[p].setFont(new Font("Comic Sans MS", Font.BOLD, 18));//sets font of the text field
I[p].setFont(new Font("Comic Sans MS", Font.BOLD, 18));
G[p].setFont(new Font("Comic Sans MS", Font.BOLD, 18));
O[p].setFont(new Font("Comic Sans MS", Font.BOLD, 18));
}
B[0].setText("1-15");// sets range in text field that user is instructed to input
I[0].setText("16-30");
N[0].setText("31-45");
G[0].setText("46-60");
O[0].setText("61-75");
back.setBounds(400, 570, 75, 40);
title.setBounds(40, 60, 500, 114);
gen.setBounds(190, 570, 190, 50);// sets bounds of all labels/button
bk.setBounds(0, 0, 600, 680);
star.setBounds(250, 325, 75, 75);
k.setSize(600, 680);
k.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
k.add(back);
k.add(star);
k.add(title);
k.add(gen);
k.add(bk);
k.setLayout(null);
k.setVisible(true);
gen.addActionListener(new ActionListener() { //Action Listener when called, check
String BS[] = new String[5];
String IS[] = new String[5];
String NS[] = new String[4];
String GS[] = new String[5];
String OS[] = new String[5];
int Bi[] = new int[5];
int Ii[] = new int[5];
int Ni[] = new int[4];
int Gi[] = new int[5];
int Oi[] = new int[5];
public void actionPerformed(ActionEvent e) {
boolean isGood = true;
try {
for (int p = 0; p < B.length; p++) {
try {
BS[p] = B[p].getText();
Bi[p] = Integer.parseInt(BS[p]);
IS[p] = I[p].getText();
Ii[p] = Integer.parseInt(IS[p]);
NS[p] = N[p].getText();
Ni[p] = Integer.parseInt(NS[p]);
GS[p] = G[p].getText();
Gi[p] = Integer.parseInt(GS[p]);
OS[p] = O[p].getText();
Oi[p] = Integer.parseInt(OS[p]);
} catch (Exception ign) {
}
}
} catch (Exception ignored) {
isGood = false;
}
if (isGood == false) {
card(Bi, Ii, Ni, Gi, Oi);
k.dispose();
} else{
B[0].setText("Invalid!");
I[0].setText("Enter");
N[0].setText("Numbers");
G[0].setText("To");
O[0].setText("Continue");
}
}
});
back.addActionListener(new ActionListener() { //Action Listener when pressing "Generate Card"
public void actionPerformed(ActionEvent e) {
k.dispose();
start();
}
});
}
public static void random() { // Random number Generator method, is called when action listener runs
Random random = new Random();
for (int p = 0; p < b.length; p++) { //The loops are to check for duplication in random numbers
b[p] = (int) (random.nextDouble() * 14 + 1);
do {
b[1] = (int) (random.nextDouble() * 14 + 1);
} while (b[1] == b[0]);
do {
b[2] = (int) (random.nextDouble() * 14 + 1);
} while (b[2] == b[1] || b[2] == b[0]);
do {
b[3] = (int) (random.nextDouble() * 14 + 1);
} while (b[3] == b[0] || b[3] == b[1] || b[3] == b[2]);
do {
b[4] = (int) (random.nextDouble() * 14 + 1);
} while (b[4] == b[0] || b[4] == b[1] || b[4] == b[2] || b[4] == b[3]);
}
for (int p = 0; p < i.length; p++) { //The loops are to check for duplication in random numbers
i[p] = (int) (random.nextDouble() * 14 + 16);
do {
i[1] = (int) (random.nextDouble() * 14 + 16);
} while (i[1] == i[0]);
do {
i[2] = (int) (random.nextDouble() * 14 + 16);
} while (i[2] == i[1] || i[2] == i[0]);
do {
i[3] = (int) (random.nextDouble() * 14 + 16);
} while (i[3] == i[0] || i[3] == i[1] || i[3] == i[2]);
do {
i[4] = (int) (random.nextDouble() * 14 + 16);
} while (i[4] == i[0] || i[4] == i[1] || i[4] == i[2] || i[4] == i[3]);
}
for (int p = 0; p < n.length; p++) { //The loops are to check for duplication in random numbers
n[p] = (int) (random.nextDouble() * 14 + 31);
do {
n[1] = (int) (random.nextDouble() * 14 + 31);
} while (n[1] == n[0]);
do {
n[2] = (int) (random.nextDouble() * 14 + 31);
} while (n[2] == n[1] || n[2] == n[0]);
do {
n[3] = (int) (random.nextDouble() * 14 + 31);
} while (n[3] == n[0] || n[3] == n[1] || n[3] == n[2]);
}
for (int p = 0; p < n.length; p++) { //The loops are to check for duplication in random numbers
g[p] = (int) (random.nextDouble() * 14 + 46);
do {
g[1] = (int) (random.nextDouble() * 14 + 46);
} while (g[1] == g[0]);
do {
g[2] = (int) (random.nextDouble() * 14 + 46);
} while (g[2] == g[1] || g[2] == g[0]);
do {
g[3] = (int) (random.nextDouble() * 14 + 46);
} while (g[3] == g[0] || g[3] == g[1] || g[3] == g[2]);
do {
g[4] = (int) (random.nextDouble() * 14 + 46);
} while (g[4] == g[0] || g[4] == g[1] || g[4] == g[2] || g[4] == g[3]);
}
for (int p = 0; p < n.length; p++) { //The loops are to check for duplication in random numbers
o[p] = (int) (random.nextDouble() * 14 + 61);
do {
o[1] = (int) (random.nextDouble() * 14 + 61);
} while (o[1] == o[0]);
do {
o[2] = (int) (random.nextDouble() * 14 + 61);
} while (o[2] == o[1] || o[2] == o[0]);
do {
o[3] = (int) (random.nextDouble() * 14 + 61);
} while (o[3] == o[0] || o[3] == o[1] || o[3] == o[2]);
do {
o[4] = (int) (random.nextDouble() * 14 + 61);
} while (o[4] == o[0] || o[4] == o[1] || o[4] == o[2] || o[4] == o[3]);
}
card(b, i, n, g, o);
}
public static void card(int[] b, int[] i, int[] n, int[] g, int[] o) { //Creates frame for card
JFrame R = new JFrame("Bingo!");
int x = 175;
JButton reset = new JButton();
reset.setText("Generate New Card");
reset.setBounds(195, 570, 190, 40);
reset.setForeground(Color.WHITE);
reset.setContentAreaFilled(false);
reset.setFocusPainted(false);
R.setSize(600, 680);
R.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel title = new JLabel(new ImageIcon("images/title.png"));
JLabel star = new JLabel(new ImageIcon("images/star.png"));
JLabel nice = new JLabel(new ImageIcon("images/bk2.png"));
JButton back = new JButton("Back");
back.setForeground(Color.WHITE);
back.setContentAreaFilled(false);
back.setFocusPainted(false);
back.setBounds(400, 570, 75, 40);
title.setBounds(40, 60, 500, 114);
star.setBounds(250, 325, 75, 75);
nice.setBounds(0, 0, 600, 680);
//Creating JButtons for Bingo card
JButton B[] = new JButton[5];
String b1[] = new String[5];
JButton I[] = new JButton[5];
String i1[] = new String[5];
JButton N[] = new JButton[4];
String n1[] = new String[4];
JButton G[] = new JButton[5];
String g1[] = new String[5];
JButton O[] = new JButton[5];
String o1[] = new String[5];
//For loops to setText to all of the buttons
for (int p = 0; p < b.length; p++) {
b1[p] = String.valueOf(b[p]);
B[p] = new JButton();
B[p].setText(b1[p]);
B[p].setForeground(Color.BLACK);
B[p].setContentAreaFilled(false);
B[p].setFocusPainted(false);
B[p].setFont(new Font("Comic Sans MS", Font.PLAIN, 26));
R.add(B[p]);
}
for (int p = 0; p < i.length; p++) {
i1[p] = String.valueOf(i[p]);
I[p] = new JButton();
I[p].setText(i1[p]);
I[p].setForeground(Color.BLACK);
I[p].setContentAreaFilled(false);
I[p].setFocusPainted(false);
I[p].setFont(new Font("Comic Sans MS", Font.PLAIN, 26));
R.add(I[p]);
}
for (int p = 0; p < n.length; p++) {
n1[p] = String.valueOf(n[p]);
N[p] = new JButton();
N[p].setText(n1[p]);
N[p].setForeground(Color.BLACK);
N[p].setContentAreaFilled(false);
N[p].setFocusPainted(false);
N[p].setFont(new Font("Comnc Sans MS", Font.PLAIN, 26));
R.add(N[p]);
}
for (int p = 0; p < g.length; p++) {
g1[p] = String.valueOf(g[p]);
G[p] = new JButton();
G[p].setText(g1[p]);
G[p].setForeground(Color.BLACK);
G[p].setContentAreaFilled(false);
G[p].setFocusPainted(false);
G[p].setFont(new Font("Comic Sans MS", Font.PLAIN, 26));
R.add(G[p]);
}
for (int p = 0; p < o.length; p++) {
o1[p] = String.valueOf(o[p]);
O[p] = new JButton();
O[p].setText(o1[p]);
O[p].setForeground(Color.BLACK);
O[p].setContentAreaFilled(false);
O[p].setFocusPainted(false);
O[p].setFont(new Font("Comic Sans MS", Font.PLAIN, 26));
R.add(O[p]);
}
for (int p = 0; p < b.length; p++) {
B[p].setBounds(100, x, 75, 75);
x = x + 75;
}
x = 175;
for (int p = 0; p < I.length; p++) {
I[p].setBounds(175, x, 75, 75);
x = x + 75;
}
x = 175;
for (int p = 0; p < N.length; p++) {
while (x == 325) {
x = x + 75;
}
N[p].setBounds(250, x, 75, 75);
x = x + 75;
}
x = 175;
for (int p = 0; p < G.length; p++) {
G[p].setBounds(325, x, 75, 75);
x = x + 75;
}
x = 175;
for (int p = 0; p < O.length; p++) {
O[p].setBounds(400, x, 75, 75);
x = x + 75;
}
R.add(title);//adds all of the components to the Frame...
R.add(back);
R.add(reset);
R.add(star);
R.add(nice);
R.setLayout(null);
R.setVisible(true);
reset.addActionListener(new ActionListener() { //Action Listener when pressing "Generate Card"
public void actionPerformed(ActionEvent e) {
R.dispose();
random();
}
});
back.addActionListener(new ActionListener() { //Action Listener when pressing "Generate Card"
public void actionPerformed(ActionEvent e) {
R.dispose();
start();
}
});
B[0].addActionListener(new ActionListener() {
private boolean right = false;
public void actionPerformed(ActionEvent e) {
if (!right) {
B[0].setForeground(Color.red);
} else if (right) {
B[0].setForeground(Color.BLACK);
}
right = !right;
}
});
B[1].addActionListener(new ActionListener() {
private boolean right = false;
public void actionPerformed(ActionEvent e) {
if (!right) {
B[1].setForeground(Color.red);
} else if (right) {
B[1].setForeground(Color.BLACK);
}
right = !right;
}
});
B[2].addActionListener(new ActionListener() {
private boolean right = false;
public void actionPerformed(ActionEvent e) {
if (!right) {
B[2].setForeground(Color.red);
} else if (right) {
B[2].setForeground(Color.BLACK);
}
right = !right;
}
});
B[3].addActionListener(new ActionListener() {
private boolean right = false;
public void actionPerformed(ActionEvent e) {
if (!right) {
B[3].setForeground(Color.red);
} else if (right) {
B[3].setForeground(Color.BLACK);
}
right = !right;
}
});
B[4].addActionListener(new ActionListener() {
private boolean right = false;
public void actionPerformed(ActionEvent e) {
if (!right) {
B[4].setForeground(Color.red);
} else if (right) {
B[4].setForeground(Color.BLACK);
}
right = !right;
}
});
I[0].addActionListener(new ActionListener() {
private boolean right = false;
public void actionPerformed(ActionEvent e) {
if (!right) {
I[0].setForeground(Color.red);
} else if (right) {
I[0].setForeground(Color.BLACK);
}
right = !right;
}
});
I[1].addActionListener(new ActionListener() {
private boolean right = false;
public void actionPerformed(ActionEvent e) {
if (!right) {
I[1].setForeground(Color.red);
} else if (right) {
I[1].setForeground(Color.BLACK);
}
right = !right;
}
});
I[2].addActionListener(new ActionListener() {
private boolean right = false;
public void actionPerformed(ActionEvent e) {
if (!right) {
I[2].setForeground(Color.red);
} else if (right) {
I[2].setForeground(Color.BLACK);
}
right = !right;
}
});
I[3].addActionListener(new ActionListener() {
private boolean right = false;
public void actionPerformed(ActionEvent e) {
if (!right) {
I[3].setForeground(Color.red);
} else if (right) {
I[3].setForeground(Color.BLACK);
}
right = !right;
}
});
I[4].addActionListener(new ActionListener() {
private boolean right = false;
public void actionPerformed(ActionEvent e) {
if (!right) {
I[4].setForeground(Color.red);
} else if (right) {
I[4].setForeground(Color.BLACK);
}
right = !right;
}
});
N[0].addActionListener(new ActionListener() {
private boolean right = false;
public void actionPerformed(ActionEvent e) {
if (!right) {
N[0].setForeground(Color.red);
} else if (right) {
N[0].setForeground(Color.BLACK);
}
right = !right;
}
});
N[1].addActionListener(new ActionListener() {
private boolean right = false;
public void actionPerformed(ActionEvent e) {
if (!right) {
N[1].setForeground(Color.red);
} else if (right) {
N[1].setForeground(Color.BLACK);
}
right = !right;
}
});
N[2].addActionListener(new ActionListener() {
private boolean right = false;
public void actionPerformed(ActionEvent e) {
if (!right) {
N[2].setForeground(Color.red);
} else if (right) {
N[2].setForeground(Color.BLACK);
}
right = !right;
}
});
N[3].addActionListener(new ActionListener() {
private boolean right = false;
public void actionPerformed(ActionEvent e) {
if (!right) {
N[3].setForeground(Color.red);
} else if (right) {
N[3].setForeground(Color.BLACK);
}
right = !right;
}
});
G[0].addActionListener(new ActionListener() {
private boolean right = false;
public void actionPerformed(ActionEvent e) {
if (!right) {
G[0].setForeground(Color.red);
} else if (right) {
G[0].setForeground(Color.BLACK);
}
right = !right;
}
});
G[1].addActionListener(new ActionListener() {
private boolean right = false;
public void actionPerformed(ActionEvent e) {
if (!right) {
G[1].setForeground(Color.red);
} else if (right) {
G[1].setForeground(Color.BLACK);
}
right = !right;
}
});
G[2].addActionListener(new ActionListener() {
private boolean right = false;
public void actionPerformed(ActionEvent e) {
if (!right) {
G[2].setForeground(Color.red);
} else if (right) {
G[2].setForeground(Color.BLACK);
}
right = !right;
}
});
G[3].addActionListener(new ActionListener() {
private boolean right = false;
public void actionPerformed(ActionEvent e) {
if (!right) {
G[3].setForeground(Color.red);
} else if (right) {
G[3].setForeground(Color.BLACK);
}
right = !right;
}
});
G[4].addActionListener(new ActionListener() {
private boolean right = false;
public void actionPerformed(ActionEvent e) {
if (!right) {
G[4].setForeground(Color.red);
} else if (right) {
G[4].setForeground(Color.BLACK);
}
right = !right;
}
});
O[0].addActionListener(new ActionListener() {
private boolean right = false;
public void actionPerformed(ActionEvent e) {
if (!right) {
O[0].setForeground(Color.red);
} else if (right) {
O[0].setForeground(Color.BLACK);
}
right = !right;
}
});
O[1].addActionListener(new ActionListener() {
private boolean right = false;
public void actionPerformed(ActionEvent e) {
if (!right) {
O[1].setForeground(Color.red);
} else if (right) {
O[1].setForeground(Color.BLACK);
}
right = !right;
}
});
O[2].addActionListener(new ActionListener() {
private boolean right = false;
public void actionPerformed(ActionEvent e) {
if (!right) {
O[2].setForeground(Color.red);
} else if (right) {
O[2].setForeground(Color.BLACK);
}
right = !right;
}
});
O[3].addActionListener(new ActionListener() {
private boolean right = false;
public void actionPerformed(ActionEvent e) {
if (!right) {
O[3].setForeground(Color.red);
} else if (right) {
O[3].setForeground(Color.BLACK);
}
right = !right;
}
});
O[4].addActionListener(new ActionListener() {
private boolean right = false;
public void actionPerformed(ActionEvent e) {
if (!right) {
O[4].setForeground(Color.red);
} else if (right) {
O[4].setForeground(Color.BLACK);
}
right = !right;
}
});
}
}
</code></pre>
|
[] |
[
{
"body": "<p>You're thinking too procedural instead of actually using Java in the way it's designed to be used. This is most obvious in that you're only ever using static methods that don't even return anything.</p>\n\n<p>Correcting everything would be a bit out of scope of this review so I'll give some pointers on how to improve your current code without changing <em>too</em> much. In no particular order, here's my list of changes I suggest, in order that I encountered them:</p>\n\n<h1>variable naming conventions</h1>\n\n<p>The java convention is to start variable names with a small case That way it's immediatly clear when something is a variable name and when it's a class name.<br>\n<code>JButton Play</code> should be <code>play</code> instead.</p>\n\n<p>Variables should also get meaningful names. Editors these days usually include autocomplete anyway so it doesn't take much more typing to use longer names. Other people using (or reviewing) your code will be thankful if you don't use one letter variables.<br>\nVariables like <code>b</code>, <code>i</code>, ... could be namend <code>columnB</code> ... instead, <code>k</code> should probably be something like <code>frame</code> and <code>bk</code> took me way longer than I'd like to admit before I figured out that it's the <code>background</code> for the application.</p>\n\n<p>The only exceptions where one letter variables are commonly used is in a for loop. The convention is to use <code>i</code> (or <code>j</code> in a nested loop) instead of how you used <code>p</code>.</p>\n\n<h1>static fields</h1>\n\n<p>These made me think you don't understand OOP yet. Since they're used only inside the <code>random()</code> method, the easiest quickfix for now is to just move them inside that method.</p>\n\n<p>Static fields are rarely useful, except if they're constants, in which case they should also be declared <code>final</code> (and following Java naming conventions written in ALLCAPS). At some point you'll want to introduce an actual instance of one of your classes and use non-static fields. I'm considering that out of scope of this review for now. It's advisable you search for a Java tutorial to explain how to use classes and objects.</p>\n\n<h1>random.double()</h1>\n\n<p>I don't like casting if you don't need it.<br>\nThis should probably be replaced with <code>random.nextInt(to - from + 1) + from</code>.</p>\n\n<h1>removing random generation repetition.</h1>\n\n<p>One of the most obvious points where repetition can be avoided is in your <code>random()</code> method. My initial thought was to provide a new helper method like this:</p>\n\n<pre><code>private static int[] generateRandomNumbers(int from, int to) {\n Random random = new Random();\n int[] result = new int[5];\n for(int i = 0; i < 5; i++){\n boolean found = false;\n while(!found) {\n result[i] = random.nextInt(to-from+1)+from;\n found = true;\n for(int j = 0; j<i; j++){\n if(result[i] == result[j]) {\n found = false;\n }\n }\n }\n }\n return result;\n}\n</code></pre>\n\n<p>Which can be used for all the columns except for the middle one. The only difference is the size of the array to be returned. So if we pass that in as a variable as well we can simplify your entire <code>random()</code> method to this:</p>\n\n<pre><code>public static void random() { // Random number Generator method, is called when action listener runs\n int b[] = generateRandomNumbers(1, 15, 5);\n int i[] = generateRandomNumbers(16, 30, 5);\n int n[] = generateRandomNumbers(31, 45, 4);\n int g[] = generateRandomNumbers(46, 60, 5);\n int o[] = generateRandomNumbers(61, 75, 5);\n\n card(b, i, n, g, o);\n}\n\nprivate static int[] generateRandomNumbers(int from, int to, int amount) {\n Random random = new Random();\n int[] result = new int[amount];\n for (int i = 0; i < amount; i++) {\n boolean found = false;\n while (!found) {\n result[i] = random.nextInt(to - from + 1) + from;\n found = true;\n for (int j = 0; j < i; j++) {\n if (result[i] == result[j]) {\n found = false;\n }\n }\n }\n }\n return result;\n}\n</code></pre>\n\n<h1>removing button creation repetition</h1>\n\n<p>Another place where you repeat the same lines over and over is when you're creating all the buttons inside the <code>card</code> method.</p>\n\n<p>Let's start by creating a helper method that creates a button</p>\n\n<pre><code>private static JButton createButton( String text) {\n JButton button = new JButton();\n button.setText(text);\n button.setForeground(Color.BLACK);\n button.setContentAreaFilled(false);\n button.setFocusPainted(false);\n button.setFont(new Font(\"Comic Sans MS\", Font.PLAIN, 26));\n return button;\n}\n</code></pre>\n\n<p>That way we can simplify the for loops to create the buttons to:</p>\n\n<pre><code> //For loops to setText to all of the buttons\n for (int p = 0; p < b.length; p++) {\n b1[p] = String.valueOf(b[p]);\n columnB[p] = createButton(b1[p]);\n frame.add(columnB[p]);\n }\n</code></pre>\n\n<p>I also noticed that the <code>b1</code> array is only used inside that loop, so we can inline that instead to remove that variable altogether:</p>\n\n<pre><code> //For loops to setText to all of the buttons\n for (int p = 0; p < b.length; p++) {\n columnB[p] = createButton(String.valueOf(b[p]));\n frame.add(columnB[p]);\n }\n</code></pre>\n\n<p>A bit further into the method there's a lot of repetition to add a click listener to each of the buttons. We can just add that listener inside our new helper method so that it's already done for each of the buttons when they're created. That way we can remove all of that repetition.</p>\n\n<pre><code>private static JButton createButton( String text) {\n JButton button = new JButton();\n button.setText(text);\n button.setForeground(Color.BLACK);\n button.setContentAreaFilled(false);\n button.setFocusPainted(false);\n button.setFont(new Font(\"Comic Sans MS\", Font.PLAIN, 26));\n button.addActionListener(new ActionListener() {\n private boolean right = false;\n\n @Override\n public void actionPerformed(ActionEvent e) {\n if (!right) {\n button.setForeground(Color.red);\n } else if (right) {\n button.setForeground(Color.BLACK);\n }\n right = !right;\n }\n });\n return button;\n}\n</code></pre>\n\n<h1>layout manager</h1>\n\n<p>You should really consider using a layout manager instead of hard coding positions yourself. Explaining how to use one is a bit too much to do in this review. I suggest looking up how to use a <code>MigLayout</code> for example where you can define a 5x5 grid. That way it's enough to just add the buttons in the earlier mentioned for loops without explicitly setting each of the bounds.</p>\n\n<h1>handling middle square</h1>\n\n<p>An idea that could further simplify your code is to first not treat the middle square as anything special and actually create a 5x5 grid instead of separate columns. Then only where it actually matters make the difference for that middle square. That way you can do things like:</p>\n\n<pre><code>public static void card(int[][] numberGrid) {\n.... \n\nfor(int row = 0; row < grid.length; row++) {\n for(int col = 0; col < grid[row].length; col ++) {\n if (row == 2 && col == 2) {\n R.add(new JLabel(\"Free square!\")); //todo replace with something useful \n } else {\n R.add(createButton(String.valueOf(numberGrid[row][col])));\n }\n }\n}\n</code></pre>\n\n<p>I'll leave figuring out how to update the rest of your code to use such a grid up to you.</p>\n\n<h1>one frame</h1>\n\n<p>It's probably nicer if you can only create one frame for your application and keep using that one instead of always disposing your frame and creating a new one. This may require actually using an instance of your Bingo class to store the frame in so I'll leave it out of scope of this review.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-28T17:47:25.547",
"Id": "455597",
"Score": "0",
"body": "Thank you for taking your time and reviewing my code, it really means a lot to someone like me that is new to the program and community!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-28T15:35:57.827",
"Id": "233121",
"ParentId": "232885",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "233121",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T04:09:01.250",
"Id": "232885",
"Score": "2",
"Tags": [
"java",
"beginner",
"array",
"game"
],
"Title": "Bingo Game that needs someone to look over because of repetitive coding"
}
|
232885
|
<p>The problem is stated in <a href="https://www.codewars.com/kata/encrypt-this/java" rel="nofollow noreferrer">Encrypt this!</a>:</p>
<blockquote>
<p>Your message is a string containing space separated words. You need to
encrypt each word in the message using the following rules:</p>
<ul>
<li><p>The first letter needs to be converted to its ASCII code.</p>
</li>
<li><p>The second letter needs to be switched with the last letter</p>
</li>
<li><p>Keepin' it simple: There are no special characters in input.</p>
</li>
</ul>
<p>Kata.encryptThis("Hello") => "72olle"</p>
<p>Kata.encryptThis("good")` => "103doo"</p>
<p>Kata.encryptThis("hello world") => "104olle 119drlo"</p>
</blockquote>
<pre><code>class NewEnpc{
public static String encryptThis(String text) {
StringBuilder sb=new StringBuilder();
String[] arry=text.split(" ");
if(text!=""){
for(int j=0;j<arry.length;j++){
char[] sd=arry[j].toCharArray();
int number=(int)sd[0];
if(sd.length>1){
for(int k=0;k<sd.length;k++){
if(k==0){
sb.append(number);
}
else if(k==1){
int len=sd.length-1;
char c=sd[len];
sb.append(c);
}
else if(k==sd.length-1){
char c=sd[1];
sb.append(c);
}
else{
char c=sd[k];
sb.append(c);
}
}
}
else{
sb.append(number);
}
sb.append(" ");
}
}
return sb.toString().trim();
}
}
public class EncryPt {
public static void main(String[]args){
System.out.println("Hello");
System.out.println(NewEnpc.encryptThis("A
wise old owl lived in an oak"));
}
}
</code></pre>
<p>Can someone help me improve my coding standards. I have solved the problem.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T07:24:40.047",
"Id": "454997",
"Score": "3",
"body": "Did you write any unit tests for this code? You should do this, and add them to your code, to show us examples of plain text and the corresponding \"encrypted\" text. By reading the unit tests, we can also tell you which corner cases you forgot to test. The one I'm thinking about has several spaces in a row, like `\"three spaces\"` (I actually wrote 3 spaces between the words, but they are not shown as such here). Your code should not crash while encrypting this text. And what about the text `\"hello, world\"`, is it encrypted as you expect it to be?"
}
] |
[
{
"body": "<p>I would suggest following:</p>\n\n<ol>\n<li><p>Do not compare strings by <code>==</code>, use <code>String.equals()</code>. And in Your case is better <code>String.isEmpty()</code></p>\n\n<p><code>text != \"\"</code> → <code>!text.isEmpty()</code></p></li>\n<li><p>Use constants for numbers and strings. It increases readability and futher refactoring.</p>\n\n<p><code>private static final String WORD_SEPARATOR = \" \";</code></p></li>\n<li><p>There is no need to use indexed iterations</p>\n\n<p><code>for(int j=0;j<arry.length;j++)</code> → <code>for (String s : arry)</code></p></li>\n<li><p>Use IDE with spelling checker:</p>\n\n<p><code>arry</code> → <code>array</code></p></li>\n<li><p>Use meaning variable names.</p>\n\n<p><code>String s</code> → <code>String word</code></p></li>\n<li><p>No need to use cast:</p>\n\n<p><code>int number = (int) sd[0];</code> → <code>int number = sd[0];</code></p></li>\n<li><p>Decrease level of visibility</p>\n\n<p><code>public static String encryptThis</code> → <code>static String encryptThis</code></p></li>\n<li><p>Use method extraction to decrease <code>nesting level</code></p>\n\n<p><code>private static StringBuilder encrypt(char[] wordChars, int number)</code></p></li>\n<li><p>You add first char in any case so condition can be omitted.</p></li>\n<li><p>You could use chain of method <code>.append(...)</code> calls for <code>StringBuilder</code></p></li>\n<li><p>It is nice to move conditions like <code>k==1</code> to meaningful named method:</p>\n\n<p>See <code>isSecondChar(...)</code></p></li>\n<li><p>It is nice to validate input params early and prevent any actions if it is not valid:</p>\n\n<p><code>if(text!=\"\")</code> → <code>if (text.equals(\"\")) then return empty string;</code></p></li>\n</ol>\n\n<p>I would strongly suggest you to read great Joshua Bloch 'Effective Java' book. </p>\n\n<p>Have a look at the refactored code:</p>\n\n<pre><code>class NewEnpc {\n\n private static final String WORD_SEPARATOR = \" \";\n\n static String encryptThis(String text) {\n if (text.isEmpty()) {\n return text;\n }\n StringBuilder result = new StringBuilder();\n String[] words = text.split(WORD_SEPARATOR);\n for (String word : words) {\n char[] wordChars = word.toCharArray();\n result.append((int) wordChars[0])\n .append(encrypt(wordChars))\n .append(\" \");\n }\n return result.toString().trim();\n }\n\n private static StringBuilder encrypt(char[] wordChars) {\n StringBuilder encrypted = new StringBuilder();\n for (int index = 1; index < wordChars.length; index++) {\n if (isSecondChar(index)) {\n int len = wordChars.length - 1;\n encrypted.append(wordChars[len]);\n } else if (isLastChar(index, wordChars.length - 1)) {\n encrypted.append(wordChars[1]);\n } else {\n encrypted.append(wordChars[index]);\n }\n }\n return encrypted;\n }\n\n private static boolean isLastChar(int currentIndex, int prevCharIndex) {\n return currentIndex == prevCharIndex;\n }\n\n private static boolean isSecondChar(int currentIndex) {\n return isLastChar(currentIndex, 1);\n }\n}\n\npublic class EncryPt {\n public static void main(String[] args) {\n System.out.println(\"Hello\");\n System.out.println(NewEnpc.encryptThis(\"A wise old owl lived in an oak\"));\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T07:41:22.607",
"Id": "232888",
"ParentId": "232886",
"Score": "4"
}
},
{
"body": "<p>The solution I'm proposing is based on these rules and examples, so I suppose a generic message contains words of length more than 1 character and composed of letters and numbers. The edge cases like empty strings or others to pass other tests on the site can be added to my code.\nMy class contains a <code>main</code> method including the tests:</p>\n\n<pre><code>public class NewEnpc {\n\n public static void main(String[] args) {\n assertEquals(encryptThis(\"Hello\"), \"72olle\");\n assertEquals(encryptThis(\"good\"), \"103doo\");\n assertEquals(encryptThis(\"hello world\"), \"104olle 119drlo\");\n }\n}\n</code></pre>\n\n<p>The method <code>encryptThis</code> splits the message by space into words, encrypts every single word and finally return the encrypted message: this can be done like the code below:</p>\n\n<pre><code>public static String encryptThis(String message) {\n String sep = \" \";\n String[] words = message.split(sep);\n StringJoiner joiner = new StringJoiner(sep);\n\n for (String word : words) {\n String encryptedWord = encryptWord(word);\n joiner.add(encryptedWord);\n }\n\n return joiner.toString();\n}\n</code></pre>\n\n<p>I used the class <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html#StringJoiner-java.lang.CharSequence-\" rel=\"nofollow noreferrer\">StringJoiner</a> to obtain the encrypted message.\nThe method encryptWord takes a word as a parameter and encrypt it using rules I quoted at the beginning of my answer:</p>\n\n<pre><code>private static String encryptWord(String word) {\n char[] arr = word.toCharArray();\n final int n = arr.length;\n int asciiFirstChar = arr[0];\n char secondChar = arr[n - 1];\n char lastChar = arr[1];\n\n StringBuilder builder = new StringBuilder(Integer.toString(asciiFirstChar));\n builder.append(secondChar);\n builder.append(word.substring(2, n - 1));\n builder.append(lastChar);\n\n return builder.toString();\n}\n</code></pre>\n\n<p>Below all the code of the class:</p>\n\n<pre><code>public class NewEnpc {\n\n public static void main(String[] args) {\n assertEquals(encryptThis(\"Hello\"), \"72olle\");\n assertEquals(encryptThis(\"good\"), \"103doo\");\n assertEquals(encryptThis(\"hello world\"), \"104olle 119drlo\");\n }\n\n public static String encryptThis(String message) {\n String sep = \" \";\n String[] words = message.split(sep);\n StringJoiner joiner = new StringJoiner(sep);\n\n for (String word : words) {\n String encryptedWord = encryptWord(word);\n joiner.add(encryptedWord);\n }\n\n return joiner.toString();\n }\n\n private static String encryptWord(String word) {\n char[] arr = word.toCharArray();\n final int n = arr.length;\n int asciiFirstChar = arr[0];\n char secondChar = arr[n - 1];\n char lastChar = arr[1];\n\n StringBuilder builder = new StringBuilder(Integer.toString(asciiFirstChar));\n builder.append(secondChar);\n builder.append(word.substring(2, n - 1));\n builder.append(lastChar);\n\n return builder.toString();\n }\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T16:09:14.990",
"Id": "232953",
"ParentId": "232886",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "232888",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T04:51:05.307",
"Id": "232886",
"Score": "1",
"Tags": [
"java",
"strings"
],
"Title": "Create secret messages"
}
|
232886
|
<p>I was presented with a coding challenge:</p>
<blockquote>
<p>Given two integer arrays (in this case, the two given arrays have the same length of 6). And a target of 24. Find two pairs of numbers from those 2 arrays whose sums are closest to the target.</p>
</blockquote>
<p>I kinda find it lengthy. How can I improve it?</p>
<pre><code>#include <iostream>
void which_no(int x, int arr01[6], int arr02[6]) {
if (x <= 6) {
std::cout << "(" << arr01[0] << ",";
switch (x) {
case 1:
std::cout << arr02[0] << ")" << std::endl;
break;
case 2:
std::cout << arr02[1] << ")" << std::endl;
break;
case 3:
std::cout << arr02[2] << ")" << std::endl;
break;
case 4:
std::cout << arr02[3] << ")" << std::endl;
break;
case 5:
std::cout << arr02[4] << ")" << std::endl;
break;
case 6:
std::cout << arr02[5] << ")" << std::endl;
}
}
else if (x > 6 && x < 13) {
std::cout << "(" << arr01[1] << ",";
switch (x) {
case 7:
std::cout << arr02[0] << ")" << std::endl;
break;
case 8:
std::cout << arr02[1] << ")" << std::endl;
break;
case 9:
std::cout << arr02[2] << ")" << std::endl;
break;
case 10:
std::cout << arr02[3] << ")" << std::endl;
break;
case 11:
std::cout << arr02[4] << ")" << std::endl;
break;
case 12:
std::cout << arr02[5] << ")" << std::endl;
}
}
else if (x > 12 && x < 19) {
std::cout << "(" << arr01[2] << ",";
switch (x) {
case 13:
std::cout << arr02[0] << ")" << std::endl;
break;
case 14:
std::cout << arr02[1] << ")" << std::endl;
break;
case 15:
std::cout << arr02[2] << ")" << std::endl;
break;
case 16:
std::cout << arr02[3] << ")" << std::endl;
break;
case 17:
std::cout << arr02[4] << ")" << std::endl;
break;
case 18:
std::cout << arr02[5] << ")" << std::endl;
}
}
else if (x > 18 && x < 25) {
std::cout << "(" << arr01[3] << ",";
switch (x) {
case 19:
std::cout << arr02[0] << ")" << std::endl;
break;
case 20:
std::cout << arr02[1] << ")" << std::endl;
break;
case 21:
std::cout << arr02[2] << ")" << std::endl;
break;
case 22:
std::cout << arr02[3] << ")" << std::endl;
break;
case 23:
std::cout << arr02[4] << ")" << std::endl;
break;
case 24:
std::cout << arr02[5] << ")" << std::endl;
}
}
else if (x > 24 && x < 31) {
std::cout << "(" << arr01[4] << ",";
switch (x) {
case 25:
std::cout << arr02[0] << ")" << std::endl;
break;
case 26:
std::cout << arr02[1] << ")" << std::endl;
break;
case 27:
std::cout << arr02[2] << ")" << std::endl;
break;
case 28:
std::cout << arr02[3] << ")" << std::endl;
break;
case 29:
std::cout << arr02[4] << ")" << std::endl;
break;
case 30:
std::cout << arr02[5] << ")" << std::endl;
}
}
else if (x > 30 && x < 37) {
std::cout << "(" << arr01[5] << ",";
switch (x) {
case 31:
std::cout << arr02[0] << ")" << std::endl;
break;
case 32:
std::cout << arr02[1] << ")" << std::endl;
break;
case 33:
std::cout << arr02[2] << ")" << std::endl;
break;
case 34:
std::cout << arr02[3] << ")" << std::endl;
break;
case 35:
std::cout << arr02[4] << ")" << std::endl;
break;
case 36:
std::cout << arr02[5] << ")" << std::endl;
}
}
}
int main(){
int arr01[] = { 5,-8,6,7,-10,9 };
int arr02[] = { 1,3,10,20,-5,6 };
int arr_sum[36]; int x = 0;
for (int i = 0; i < 6; ++i) {
for (int j = 0; j < 6; ++j) {
arr_sum[x] = arr01[i] + arr02[j];
++x;
}
}
int arr_diff[36];
for (int i = 0; i < 36; ++i) {
if (arr_sum[i] > 24) {
arr_diff[i] = arr_sum[i] - 24;
}
else {
arr_diff[i] = 24 - arr_sum[i];
}
}
int min=arr_diff[0],min_n=1;
for (int j = 1; j < 36; ++j) {
if (min > arr_diff[j]) {
min = arr_diff[j];
min_n = j+1;
}
}
int s_min = arr_diff[0], s_min_n = 1;
for (int j = 1; j < 36; ++j) {
if (s_min > arr_diff[j]&&arr_diff[j]>min) {
s_min = arr_diff[j];
s_min_n = j + 1;
}
}
which_no(min_n, arr01, arr02);
which_no(s_min_n, arr01, arr02);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T04:28:20.990",
"Id": "454990",
"Score": "2",
"body": "What if both arrays had 100 elements or 1000 elements? That's how you should approach the problem. Hardcoding a solution for 6 elements is not a good solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T04:30:49.830",
"Id": "454991",
"Score": "0",
"body": "Let me confirm again. So \"From two given arrays(`A` and `B`) we need to pick two numbers (`a` ∈ `A` and `b` ∈ `B`). Such that sum(`a+b`) is close to 24.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T04:35:29.077",
"Id": "454992",
"Score": "1",
"body": "Advice -- These online coding questions are notorious for asking questions that have very naive solutions that work for small input, but fail due to \"time out\" issues (the solution took too long due to the size of the input). The goal of these questions is to see if you can come up with a non-naive solution, i.e. think outside the box (usually get a handle on data structures and algorithms)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T04:46:22.373",
"Id": "454993",
"Score": "1",
"body": "Oh, and this: `for (int i = 0; i < 6; ++i) {for (int j = 0; j < 6; ++j)` -- Strive to never write solutions with these types of nested loops. This is almost always never going to work. Again, if you had 1,000 items, you will be looping a million times! Ten thousand items, that is 100 million loop iterations! That is an example of naive solutions that only work for small input, and will time-out on larger sets of input. This is exactly what those online quizzes are testing for."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T04:47:10.590",
"Id": "454994",
"Score": "0",
"body": "There are several mods possible in your code. The switch statements in `which_no()` can be trivially replaced with oneliners, if you simply use `x` (or an expression using it) as an array index.That will help with readability, and make your code much shorter. The multiple loops in `main()` can be combined quite easily into one. I won't write an answer to do that though - you'll learn more of use by thinking about how to simplify the code, than you will if someone just gives you the answer. Having magic numbers like `6` and `36` littered in your code is bad practice, and also easily removed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T14:35:15.160",
"Id": "455268",
"Score": "0",
"body": "@PaulMcKenzie It is misleading to say you always have to generalize. Imagine I have some kind of problem involving integers. It would make little sense to try to generalize to complex numbers, although it might be possible and might work fine. If I don't need it, I would only waste a lot of time with the generalization. If I am given a task with 6 elements I will solve for 6 elements unless I am aware of a generalized version of the problem, or unless I expect having to solve the problem for different number of elements. But if 6 elements is all my problem, 6 elements solution is fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T14:55:11.750",
"Id": "455271",
"Score": "0",
"body": "As my comment suggested, many, if not all of the questions given by the online coding challenge sites will always give the easy case as an example, thus goad the question solver into giving solutions like the one given here. This is for them to be aware of this tactic, that's all."
}
] |
[
{
"body": "<p>Your solution is <code>O(n*n)</code>, due to the usage of the nested <code>for</code> loop. For just 6 elements, this may not be such a big deal, but if the number of elements are in the hundreds or thousands, the comments in the main section explains why this solution is not really viable.</p>\n\n<p>Thus a better (probably not the best, but somewhat better) should be worked out. This requires some manipulation of one of the arrays. Here is a proposed solution:</p>\n\n<p>The \"goal amount\" is the integer you want to find the pair of numbers closest to it (in your case, this value is <code>24</code>).</p>\n\n<ol>\n<li>Sort the second array of numbers in ascending order</li>\n<li>Keep a \"global minimum\" value, which holds the current smallest distance between the goal amount and the pair of numbers you're testing.</li>\n<li>Iterate through the first array. For each iteration, subtract the current value in the first array from the goal amount (call this value the \"search value\"). For example, <code>search_value = 24 - arr01[i]</code> if <code>i</code> is the index of the current item.</li>\n<li>Given that the items in the second array are now sorted, using a binary search (i.e. <code>std::lower_bound</code>) can be used to find the item in the second array closest to the search value found in step 3. </li>\n<li>If the value found (call this the \"found_value\") using <code>std::lower_bound</code> added to <code>arr01[i]</code>, less the goal amount, is smaller than the global minimum distance, then the new minimum distance is the pair <code>[arr01[i], found_value]</code>.</li>\n</ol>\n\n<p>The runtime of doing this, given <code>n</code> elements is:</p>\n\n<ol>\n<li><code>O(n * log(n))</code> -- for the initial sort (use <code>std::sort</code>), plus</li>\n<li><code>O(n * log(n))</code> -- for the linear traversal through the first array and for the binary search.</li>\n</ol>\n\n<p>So if you add all this up, the algorithmic complexity should be <code>O(n * log(n))</code> (someone correct me if this analysis is not correct).</p>\n\n<p>Thus, when given a large amount of input, the runtime of doing things this way will outweigh using an <code>O(n*n)</code> solution (which is the one you came up with -- read my comments about the nested <code>for</code> loop). </p>\n\n<p>For example, a thousand numbers would be <code>1000 * 10 == 10 000</code> using the logarithmic runtime, as opposed to <code>1000 * 1000 == 1 000 000</code> iterations using the <code>O(n*n)</code> runtime.</p>\n\n<hr>\n\n<p>Here is a probable solution (disclosure: not tested 100%), that captures the steps above:</p>\n\n<pre><code>#include <algorithm>\n#include <vector>\n#include <utility>\n#include <climits>\n#include <iostream>\n#include <cmath>\n#include <cstdlib>\n\nint arr01[] = { 5,-8,6,7,-10,9 };\nint arr02[] = { 1,3,10,20,-5,6 };\n\nint main()\n{\n int goal = 24; // Our goal amount\n\n // The final pair of numbers \n std::pair<int, int> answer;\n\n // 1. Sort the second array\n std::sort(std::begin(arr02), std::end(arr02));\n\n // 2. Initialize the minimum distance found so far \n int min_distance = std::numeric_limits<int>::max();\n\n // 3. Iterate through the first array \n for (size_t i = 0; i < std::size(arr01); ++i)\n {\n // This is the search value\n int search_value = goal - arr01[i];\n\n // 4. Get value in our sorted list that is closest to the search value\n int *pClosest = std::lower_bound(std::begin(arr02), std::end(arr02), search_value);\n\n // 5. check if the distance is smaller than our current minimum \n int test_distance = abs(arr01[i] + *pClosest - goal);\n if ( test_distance < min_distance)\n {\n // Yes, so our new answer is the pair we just tested,\n // and we set the minimum distance to the smaller distance\n answer = std::make_pair(arr01[i], *pClosest);\n min_distance = test_distance;\n }\n }\n\n // Output results \n std::cout << answer.first << \" \" << answer.second;\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>5 20\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T17:01:35.533",
"Id": "232900",
"ParentId": "232887",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T04:20:16.833",
"Id": "232887",
"Score": "1",
"Tags": [
"c++"
],
"Title": "Coding challenge involving integer pairs"
}
|
232887
|
<h1>How would I clean this code/shorten it (most of it is login)</h1>
<p>What the program does:</p>
<p>Only authorized players are allowed to play.</p>
<p>Input from user should be validated where possible.</p>
<p>5 rounds.</p>
<p>Score cannot go below 0.</p>
<p>2 players roll 2 6-sided dice.</p>
<p>Points rolled on each player's dice are added to their score.</p>
<p>If total is even number, add 10 points to score.</p>
<p>If total is odd number, subtract 5 points from score.</p>
<p>If they roll a double they get to roll one extra die and the points rolled added to their score.</p>
<p>Person with highest score wins.</p>
<p>If have same score at end, they roll 1 die and whoever gets the highest score wins.</p>
<pre><code>#Importing modules
import random
import time
import re
##################################################################################################################################
#Defining global variables
i = 0
Player1Points = 0
Player2Points = 0
Player1Tiebreaker = 0
Player2Tiebreaker = 0
Winner_Points = 0
##################################################################################################################################
#Authorisation/Registration
#Login
def login():
#Defining function variables
x = 0
UserNumber = 1
login = False
found = False
placeholder = True
NoLowercase = True
NoUppercase = True
NoNumber = True
NoSymbol = True
NoSymbolPlaceHolder = False
#Function starts
while login == False:
while found != True:
player = input("Has User{} got an account? Y/N: ".format(UserNumber))
if player == "Y" or player == "y":
user = input("Input User{}'s username: ".format(UserNumber))
password = input("\nInput your password: ")
user = user.lower()
user = user.replace(" ","")
password = password.replace(" ","")
with open('Usernames.TXT') as file:
for line in file:
uu, pp = line.strip().split(':')
if user == uu and password == pp:
print("\nUser found\n")
if x == 0:
global user1
user1 = user
found = True
x = 1
UserNumber = 2
elif x == 1:
global user2
user2 = user
found = True
login = True
x = 2
break
if not found:
print("\nUser{} not found\n".format(UserNumber))
if x == 1:
found = False
#Register username
elif player == "N" or player == "n":
UsernameModule = False
while UsernameModule != True:
RegisterUsername = input("\nInput your desired username: ")
RegisterUsername = RegisterUsername.lower()
RegisterUsername = RegisterUsername.replace(" ","")
if len(RegisterUsername) <= 16 and len(RegisterUsername) >= 4:
RegisterUsernameValidation = input("\nInput your desired username again: ")
RegisterUsernameValidation = RegisterUsernameValidation.lower()
RegisterUsernameValidation = RegisterUsernameValidation.replace(" ","")
if RegisterUsername != RegisterUsernameValidation:
print("\nThe username you have inputted is not the same, please try again.")
elif RegisterUsername == RegisterUsernameValidation:
print("\nThe username you have inputted match.")
print("\nYour username is:",RegisterUsernameValidation)
UsernameModule = True
elif len(RegisterUsername) > 16 or len(RegisterUsername) < 4:
print("\nSorry, your username is either shorter than 4 characters or longer than 16 characters.")
#Register password
PasswordModule = False
while PasswordModule != True:
RegisterPassword = input("\nInput your desired password: ")
#Checking if password has symbols, numbers, upper and lower case
N = 0
N2 = 1
while N2 < 17:
if N == 0:
RegisterPassword = RegisterPassword.replace(" ","")
else:
placeholder1 = True
RegisterPassword1 = RegisterPassword[N:N2]
if RegisterPassword1.islower() == True: # there is lowercase
NoLowercase = False
else:
placeholder1 = True
if RegisterPassword1.isupper() == True:
NoUppercase = False
else:
placeholder1 = True
if RegisterPassword1.isdigit() == True:
NoNumber = False
else:
placeholder1 = True
if RegisterPassword1 == "[" or RegisterPassword1 == "@" or RegisterPassword1 == "_" or RegisterPassword1 == "!" or RegisterPassword1 == "#" or RegisterPassword1 == "$" or RegisterPassword1 == "%" or RegisterPassword1 == "^" or RegisterPassword1 == "&" or RegisterPassword1 == "*" or RegisterPassword1 == "(" or RegisterPassword1 == ")" or RegisterPassword1 == "<" or RegisterPassword1 == ">" or RegisterPassword1 == "?" or RegisterPassword1 == "/" or RegisterPassword1 == "\\" or RegisterPassword1 == "|" or RegisterPassword1 == "}" or RegisterPassword1 == "{" or RegisterPassword1 == "~" or RegisterPassword1 == ":" or RegisterPassword1 == "]":
NoSymbolPlaceHolder = True
else:
placeholder1 = True
if NoSymbolPlaceHolder == True:
NoSymbol = False
else:
placeholder1 = True
N = N + 1
N2 = N2 + 1
if len(RegisterPassword) > 7 and len(RegisterPassword) < 17 and NoLowercase == False and NoUppercase == False and NoNumber == False and NoSymbol == False:
RegisterPasswordValidation = input("\nInput your desired password again:")
RegisterPasswordValidation = RegisterPasswordValidation.replace(" ","")
if RegisterPassword != RegisterPasswordValidation:
print("\nThe password you have inputted is not the same, please try again.")
elif RegisterPassword == RegisterPasswordValidation:
print("\nThe password you have inputted match.")
print("\nYour password is:",RegisterPasswordValidation)
PasswordModule = True
RegisteredUsernameAndPassword = RegisterUsername+":"+RegisterPassword
with open("Usernames.txt", "a") as file:
file.write("\n")
file.write(RegisteredUsernameAndPassword)
print("\nYou have successfully registered!")
elif len(RegisterPassword) <= 7 or len(RegisterPassword) > 16:
print("\nYour password needs a total of 8 to 16 characters.")
if NoLowercase == True:
print("\nYour password does not have lowercase letters.")
if NoUppercase == True:
print("\nYour password does not have uppercase letters.")
if NoNumber == True:
print("\nYour password does not have numbers.")
if NoSymbol == True:
print("\nYour password does not have symbols, please try again.")
N = 0
N2 = 1
elif placeholder == True:
placeholder1 = True
N = 0
N2 = 1
elif NoSymbol == True:
print("\nYour password does not have symbols, please try again.")
N = 0
N2 = 1
elif NoNumber == True:
print("\nYour password does not have numbers.")
if NoSymbol == True:
print("\nYour password does not have symbols, please try again.")
N = 0
N2 = 1
elif placeholder == True:
placeholder1 = True
N = 0
N2 = 1
elif NoSymbol == True:
print("\nYour password does not have symbols, please try again.")
N = 0
N2 = 1
elif NoUppercase == True:
print("\nYour password does not have uppercase letters.")
if NoNumber == True:
print("\nYour password does not have numbers.")
if NoSymbol == True:
print("\nYour password does not have symbols, please try again.")
N = 0
N2 = 1
elif placeholder == True:
placeholder1 = True
N = 0
N2 = 1
elif NoSymbol == True:
print("\nYour password does not have symbols, please try again.")
N = 0
N2 = 1
elif NoNumber == True:
print("\nYour password does not have numbers.")
if NoSymbol == True:
print("\nYour password does not have symbols, please try again.")
N = 0
N2 = 1
elif placeholder == True:
placeholder1 = True
N = 0
N2 = 1
elif NoSymbol == True:
print("\nYour password does not have symbols, please try again.")
N = 0
N2 = 1
elif NoLowercase == True:
print("\nYour password does not have lowercase letters.")
if NoUppercase == True:
print("\nYour password does not have uppercase letters.")
if NoNumber == True:
print("\nYour password does not have numbers.")
if NoSymbol == True:
print("\nYour password does not have symbols, please try again.")
N = 0
N2 = 1
elif placeholder == True:
placeholder1 = True
N = 0
N2 = 1
elif NoSymbol == True:
print("\nYour password does not have symbols, please try again.")
N = 0
N2 = 1
elif NoNumber == True:
print("\nYour password does not have numbers.")
if NoSymbol == True:
print("\nYour password does not have symbols, please try again.")
N = 0
N2 = 1
elif placeholder == True:
placeholder1 = True
N = 0
N2 = 1
elif NoSymbol == True:
print("\nYour password does not have symbols, please try again.")
N = 0
N2 = 1
elif NoUppercase == True:
print("\nYour password does not have uppercase letters.")
if NoNumber == True:
print("\nYour password does not have numbers.")
if NoSymbol == True:
print("\nYour password does not have symbols, please try again.")
N = 0
N2 = 1
elif placeholder == True:
placeholder1 = True
N = 0
N2 = 1
elif NoSymbol == True:
print("\nYour password does not have symbols, please try again.")
N = 0
N2 = 1
elif NoNumber == True:
print("\nYour password does not have numbers.")
if NoSymbol == True:
print("\nYour password does not have symbols, please try again.")
N = 0
N2 = 1
elif placeholder == True:
placeholder1 = True
N = 0
N2 = 1
elif NoSymbol == True:
print("\nYour password does not have symbols, please try again.")
N = 0
N2 = 1
elif player != "y" or player != "n" or player != "Y" or player != "N":
print("\nTry again.\n")
return()
login()
###### DEFINING ROLL ######
### Makes the dice roll for the player and works out the total for that roll ###
def roll():
points = 0
die1 = random.randint(1,6)
die2 = random.randint(1,6)
dietotal = die1 + die2
points = points + dietotal
if dietotal % 2 == 0:
points = points + 10
else:
points = points - 5
if die1 == die2:
die3 = random.randint(1,6)
points = points +die3
return(points)
###### DICE ROLL ######
### This rolls the dice 5 times for the players, and then adds up the total. If the scores are equal, it starts a tie breaker and determines the winner off that ###
for i in range(1,5):
Player1Points += roll()
print('After this round ',user1, 'you now have: ',Player1Points,' Points')
time.sleep(1)
Player2Points += roll()
print('After this round ',user2, 'you now have: ',Player2Points,' Points')
time.sleep(1)
if Player1Points == Player2Points:
while Player1Tiebreaker == Player2Tiebreaker:
Player1Tiebreaker = random.randint(1,6)
Player2Tiebreaker = random.randint(1,6)
if Player1Tiebreaker > Player2Tiebreaker:
Player2Points = 0
elif Player2Tiebreaker > Player1Tiebreaker:
Player1Points = 0
###### WORKING OUT THE WINNER ######
### This checks which score is bigger, then creates a tuple for my leaderboard code ###
if Player1Points>Player2Points:
Winner_Points = Player1Points
winner_User = user1
winner = (Winner_Points, user1)
elif Player2Points>Player1Points:
Winner_Points = Player2Points
winner = (Winner_Points, user2)
winner_User = user2
print('\nWell done, ', winner_User,' you won with ',Winner_Points,' Point\n\n')
###### CODE TO UPLOAD ALL SCORES TO A FILE ######
### This will store the winners username and score in a text file ###
leaderboard1 = "{}:{}".format(Winner_Points,winner_User)
with open ("Leaderboard.txt", "a") as file:
file.write("\n")
file.write(leaderboard1)
###### CODE TO LOAD, UPDATE AND SORT LEADERBOARD ######
### This loads the leaderboard into an array, then compares the scores just gotton and replaces it ###
f = open('Leaderboard.txt', 'r')
leaderboard = [line.replace('\n','') for line in f.readlines()]
f.close()
### This sorts the leaderboard in reverse, and then rewrites it ###
leaderboard.sort(reverse=True)
with open('Leaderboard.txt', 'w') as f:
for item in leaderboard:
f.write("%s\n" % item)
print("TOP 5 SCORES:")
with open("Leaderboard.txt", "r") as f:
counter = 0
N = 1
for line in f:
head,sep,tail = line.partition(":")
print("Place No.{}\nUsername: {}Score: {}\n".format(N,tail,head))
N = N + 1
counter += 1
if counter == 5: break
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T17:02:59.640",
"Id": "455026",
"Score": "0",
"body": "It would be very helpful if the title indicated what the entire project is."
}
] |
[
{
"body": "<p>For simplicity I have just used variables to assign a user name and password. You should never hard code this, instead use a dictionary file <code>with open</code> that compares the key username to the value password for simple storage. If you want a more creative way to store and gather the information you can use an encrypted database such as <a href=\"https://www.zetetic.net/sqlcipher/\" rel=\"nofollow noreferrer\">SQlCipher</a>. You do not need to account for every instance of what an input is, you can just use an <code>else</code> clause if the credentials are not correct.</p>\n\n<pre><code>user_name = 'admin'\npwd = 'password'\n\ndef login():\n while True:\n try:\n i = input('Enter username:> ')\n if i == user_name:\n p = input('Enter password:> ')\n if p == pwd:\n print('FUNCTION TO GAME HERE')\n break # whatever your game function is\n else:\n print('Wrong password')\n else:\n print('User does not exist')\n except ValueError:\n print('Invalid')\n\nlogin()\n</code></pre>\n\n<p>Your code gives hints to what the password or user name is. This defeats the object of keeping the information safe with as little possibility that it is going to be guessed. </p>\n\n<p>Output: </p>\n\n<pre><code>Enter username:> a\nUser does not exist\nEnter username:> 1\nUser does not exist\nEnter username:> admin\nEnter password:> p\nWrong password\nEnter username:> admin\nEnter password:> password\nFUNCTION TO GAME HERE\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T17:50:39.333",
"Id": "232956",
"ParentId": "232890",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "232956",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T10:54:19.643",
"Id": "232890",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"game",
"dice"
],
"Title": "Python Dice Game"
}
|
232890
|
<p>This is the Haskell version of my <a href="https://stackoverflow.com/a/45967133/4543207">recursive Fisher-Yates shuffle in JS</a>.</p>
<pre><code>import System.Random
pick :: Int -> [a] -> ([a],[a])
pick _ [] = ([],[])
pick 0 (x:xs) = ([x],xs)
pick i (x:xs) = (,) <$> fst <*> ((x:) . snd) $ pick (i-1) xs
shuffle :: [a] -> IO [a]
shuffle = runner =<< length
where
runner :: Int -> [a] -> IO [a]
runner 0 xs = return xs
runner i xs = randomRIO (0, i-1) >>= \r -> let (y,ys) = pick r xs
in (y ++) <$> runner (i-1) ys
</code></pre>
<p>The <code>pick</code> function fetches the <code>i</code>'th item in a the list as a singular list alongside a list with the remaining items. ie <code>pick 3 [1,2,3,4,5,6,7] = ([4],[1,2,3,5,6,7])</code>.</p>
<p>Although the above code is a version of the <a href="https://www.wikizeroo.org/index.php?q=aHR0cHM6Ly9lbi53aWtpcGVkaWEub3JnL3dpa2kvRmlzaGVy4oCTWWF0ZXNfc2h1ZmZsZQ#The_modern_algorithm" rel="nofollow noreferrer">modern method</a> which is claimed to work in O(n) this pretty fast shuffle code still seems to work in exponential time (i think). </p>
<pre><code>Prelude Main> take 10 <$> shuffle [1..100000]
[20141,12487,79977,44600,14825,86744,65941,84737,97850,21214]
(0.57 secs, 334,790,152 bytes)
Prelude Main> take 10 <$> shuffle [1..1000000]
[698377,452503,263121,737622,550957,927399,453318,657374,728367,775039]
(6.81 secs, 3,782,234,776 bytes)
</code></pre>
<p>I have two questions.</p>
<ol>
<li>Can the time complexity improved while using the List type?</li>
<li>I am not fully in control of Haskell's performance gimmicks like unboxed types and such. Can it's performance boosted by means of such Haskell tools or what data type would be the best?</li>
</ol>
|
[] |
[
{
"body": "<p>First, let me ungolf and simplify your code slightly, so it will be easier for me to read:</p>\n\n<pre><code>import System.Random\n\npick :: Int -> [a] -> (a,[a])\npick 0 (x:xs) = (x, xs)\npick i (x:xs) = let (y,ys) = pick (i-1) xs\n in (y, x:ys)\npick _ [] = error \"pick: Invalid index\"\n\nshuffle :: [a] -> IO [a]\nshuffle lst = runner (length lst) lst\n where\n runner :: Int -> [a] -> IO [a]\n runner 0 xs = return xs\n runner i xs = do\n r <- randomRIO (0, i-1)\n let (y,ys) = pick r xs\n (y:) <$> runner (i-1) ys\n</code></pre>\n\n<p>Every call to <code>pick</code> is <code>O(i)</code>, since you need to iterate through on average half of the array to extract the value and move it to the front. In when calling pick, <code>i</code> is on average equal to <code>n/2</code> (where <code>n</code> is the length of the list). <code>runner</code> is called recursively <code>n</code> times.</p>\n\n<p>So in conclusion, <code>pick</code> has time complexity <code>O(n)</code> and <code>shuffle</code> has time complexity <code>O(n^2)</code>, which is indeed much worse than linear, but not quite exponential as you feared. There are also some minor issues with your functions not being tail recursive, but that should only affect constant factors and memory usage, not complexity.</p>\n\n<p>This also matches your measurements, since <code>0.57 * 10^2 ≈ 6.81</code></p>\n\n<p>If you compare it to <a href=\"https://www.wikizeroo.org/index.php?q=aHR0cHM6Ly9lbi53aWtpcGVkaWEub3JnL3dpa2kvRmlzaGVy4oCTWWF0ZXNfc2h1ZmZsZQ#The_modern_algorithm\" rel=\"nofollow noreferrer\">the modern method</a> which you linked, that code instead uses a swap operation which is <code>O(1)</code>, which gives you the promised <code>O(n)</code> complexity.</p>\n\n<p>On a side-note, your javascript version of the algorithm has the same problem, since <code>Array.splice</code> <a href=\"https://stackoverflow.com/questions/5175925/whats-the-time-complexity-of-array-splice-in-google-chrome\">is an <code>O(n)</code> operation</a>.</p>\n\n<hr>\n\n<p>So, to your questions:</p>\n\n<ol>\n<li><p>Can we improve the time complexity while using the list type?</p>\n\n<p>No. Not unless we change the algorithm to something different, which in a way you have already done in both your implementations by not using the swap operation. An <code>O(1)</code> swap operation for lists is not available, since all random access costs <code>O(n)</code>. You can however easily fix it in your js-version (see <a href=\"https://jsperf.com/js-list-swap\" rel=\"nofollow noreferrer\">here</a>).</p>\n\n<p>If you do want to use a different algorithm, there are <code>O(n*log n)</code> algorithms that works on lists, which is not quite linear, but it's the best we can get for lists. You could also use the same algorithm with a Map, which has <code>O(log n)</code> swap operations.</p></li>\n<li><p>Unboxed types and similar gimmicks will only only help with constant factors, not algorithmic complexity. However, what would help a lot is to use a <a href=\"https://hackage.haskell.org/package/array\" rel=\"nofollow noreferrer\">mutable array</a> or <a href=\"https://hackage.haskell.org/package/vector\" rel=\"nofollow noreferrer\">vector</a>. They do have an <code>O(1)</code> swap operation. They come in both an <code>IO</code> version and an <code>ST</code> version which can be used from pure functions.</p></li>\n</ol>\n\n<p>There are a number of different implementations of a random shuffle function on <a href=\"https://wiki.haskell.org/Random_shuffle\" rel=\"nofollow noreferrer\">this page</a>, including Fisher-Yates with both a <code>Map</code> (<code>O(n*log n)</code>) and a mutable <code>Array</code> (<code>O(n)</code>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T16:53:35.897",
"Id": "455023",
"Score": "1",
"body": "Thank you, but i guess your code won't compile primarily due to the `pick _ [] = ([], [])` line. That's basically why i had chosen to return a singleton instead of the head. But anyways, thank again... I suppose i have to use a `Vector` type and do like `fromList` and `toList`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T16:56:24.507",
"Id": "455024",
"Score": "1",
"body": "Oh, right, I missed that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T17:16:31.927",
"Id": "455029",
"Score": "1",
"body": "Your answer is great and accepted. The only thing is, i don't like throwing exceptions unless i definitelly need to. I compared the `:` and `++` versions and they have similar performance. However i will annex a swap version to my JS answer. Thanks for the heads up at there."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T16:32:48.687",
"Id": "232898",
"ParentId": "232894",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "232898",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T14:42:52.477",
"Id": "232894",
"Score": "3",
"Tags": [
"algorithm",
"haskell",
"shuffle"
],
"Title": "Fisher-Yates shuffle in Haskell"
}
|
232894
|
<p>I am a hobbyist programmer trying to learn modern C++. My son had an assignment in his C++ class to fill in some functions that populate draw the cave in the "hunt for the wumpus" game. When I viewed the instructors skeleton code I found it to be very C-like rather than C++-like. So, I decided to rewrite it so I could show it to my son. Since I don't want to show my son bad code, I thought I would bring it here first. So, the big question is did I do a good job of producing creditable C++ code?</p>
<p>Secondarily, when I checked the code against the core guidelines (Visual C++ 2019 NuGet Microsoft.GSL v0.1.2.1) I received a number of lifetime.3 warnings (shown by gsl::suppress). I cannot figure out how to rewrite the code not to get these warnings, and any help in getting a conceptual understanding of these warnings would be appreciated.</p>
<p>wompus.cpp</p>
<pre><code>#include <iostream>
#include <map>
#include <vector>
#include <array>
#include <set>
#include <string>
#include <string_view>
#include "dhth.hpp"
using std::vector;
using std::array;
using std::set;
using std::map;
using std::string;
using std::cout;
using std::endl;
using grid_point = array<int, 2>;
grid_point Get_A_Random_Grid_Point(int rows, int cols) {
dhth::Rand rand;
return grid_point{ rand(1, rows), rand(1, cols) };
}
enum class Cave_Item : int8_t {
breeze,
stench,
pit,
ladder,
player,
wumpus,
gold
};
string citos(Cave_Item item) noexcept { // citos - Cave_Item to std::string
try {
switch (item) {
case Cave_Item::breeze: return string{ "breeze" };
case Cave_Item::stench: return string{ "stench" };
case Cave_Item::pit: return string{ "pit" };
case Cave_Item::ladder: return string{ "ladder" };
case Cave_Item::player: return string{ "player" };
case Cave_Item::wumpus: return string{ "wumpus" };
case Cave_Item::gold: return string{ "gold" };
default:
std::abort();
}
return string{ "error" };
}
catch (...)
{
try {
cout << "Failed to make string\n";
return string{ "error" };
}
catch (...) {
std::abort();
}
}
}
class Cave
{
public:
Cave() noexcept;
Cave(int rows, int cols) noexcept;
void Add_Item(grid_point loc, Cave_Item cave_item);
void Print_Square(grid_point loc);
void Print_Cave_Diagram();
bool Remove_Item(Cave_Item cave_item);
bool Remove_Item(grid_point loc, Cave_Item cave_item);
private:
void Fill_Adjacent(grid_point loc, Cave_Item sensation);
void Get_Cave_Diagram(vector<string>& cave_diagram);
void init();
bool Is_Square_Valid(grid_point indx) noexcept;
void Remove_Adjacent(grid_point loc, Cave_Item sensation);
int rows_ = 4;
int cols_ = 4;
map<grid_point, set<Cave_Item>> cave;
};
Cave::Cave() noexcept
{
try {
init();
}
catch (...) {
try {
cout << "Failed to initialize\n";
}
catch (...) {
std::abort();
}
}
}
Cave::Cave(int rows, int cols) noexcept : rows_{ rows }, cols_{ cols }
{
try {
init();
}
catch (...) {
try {
cout << "Failed to initialize\n";
}
catch (...) {
std::abort();
}
}
}
void Cave::Add_Item(grid_point loc, Cave_Item cave_item)
{
[[gsl::suppress(26486)]] // Don't pass a pointer that may be invalid
cave[loc].insert(cave_item); // Parameter 0'@(*this).cave
if (cave_item == Cave_Item::wumpus) Fill_Adjacent(loc, Cave_Item::stench);
if (cave_item == Cave_Item::pit) Fill_Adjacent(loc, Cave_Item::breeze);
}
void Cave::Print_Square(grid_point loc)
[[gsl::suppress(26486)]] // Don't pass a pointer that may be invalid
{ // Parameter 0'@(*this).cave
cout << "This part of the cave (" << loc.at(0) << ", " << loc.at(1) <<
") contains:\n";
if (cave[loc].empty()) {
cout << " nothing\n\n";
return;
}
for (auto item : cave[loc]) cout << " " << citos(item) << "\n";
cout << "\n";
}
void Cave::Print_Cave_Diagram() {
vector<string> cave_diagram;
cave_diagram.reserve(5 * rows_ + 1);
Get_Cave_Diagram(cave_diagram);
for (auto s : cave_diagram)
cout << s << endl;
}
bool Cave::Remove_Item(Cave_Item cave_item)
{
bool ret = false;
for (auto& items : cave) {
auto itr = items.second.find(cave_item);
if (itr != items.second.end()) {
ret = true;
items.second.erase(itr);
if (cave_item == Cave_Item::wumpus)
Remove_Adjacent(items.first, Cave_Item::stench);
if (cave_item == Cave_Item::pit)
Remove_Adjacent(items.first, Cave_Item::breeze);
}
}
return ret;
}
[[gsl::suppress(26486)]] // Don't pass a pointer that may be invalid
// Parameter 0'@(*this).cave
bool Cave::Remove_Item(grid_point loc, Cave_Item cave_item)
{
const auto num = cave[loc].erase(cave_item);
if (num == 0) return false;
if (cave_item == Cave_Item::wumpus)
Remove_Adjacent(loc, Cave_Item::stench);
if (cave_item == Cave_Item::pit)
Remove_Adjacent(loc, Cave_Item::breeze);
return true;
}
[[gsl::suppress(26486)]] // Don't pass a pointer that may be invalid
// Parameter 0'@(*this).cave
void Cave::Fill_Adjacent(grid_point loc, Cave_Item sensation)
{
for (auto& coord : loc) {
coord--;
if (Is_Square_Valid(loc)) cave[loc].insert(sensation);
coord += 2;
if (Is_Square_Valid(loc)) cave[loc].insert(sensation);
coord--;
}
}
void Cave::Get_Cave_Diagram(vector<string>& cave_diagram)
{
constexpr int cell_rows = 5;
constexpr int cell_columns = 11;
const int total_rows = cell_rows * rows_ + 1;
const int total_columns = cell_columns * cols_ + 1;
// fill in with vertical cell divisions
for (int r = 0; r < total_rows; r++) {
string row(total_columns, ' ');
for (int c = 0; c < total_columns; c += cell_columns) {
row.at(c) = '|';
}
cave_diagram.push_back(row);
}
// udpate horizontal rows with '-'
for (int i = 0; i < total_rows; i += cell_rows) {
cave_diagram.at(i) = string(total_columns, '-');
}
// update cell corners with '+'
for (int r = 0; r < total_rows; r += cell_rows) {
for (int c = 0; c < total_columns; c += cell_columns) {
cave_diagram.at(r).at(c) = '+';
}
}
// replace the part of the string with the cell contents
for (auto items : cave)
[[gsl::suppress(26486)]] // Don't pass a pointer that may be invalid
{ // Parameter 0'@(*this).cave
grid_point loc{ items.first };
const int& row = loc.at(0);
const int& col = loc.at(1);
if (cave[loc].empty()) continue;
int r = (row - 1) * cell_rows + 2;
const int c = (col - 1) * cell_columns + 3;
if (cave[loc].size() == 4) --r;
for (auto item : cave[loc]) {
cave_diagram.at(r).replace(c, citos(item).size(), citos(item));
++r;
}
}
}
void Cave::init()
[[gsl::suppress(26486)]] // Don't pass a pointer that may be invalid
{ // Parameter 0'@(*this).cave
grid_point loc{ 1, 1 }; // row column
cave[loc].insert(Cave_Item::ladder);
cave[loc].insert(Cave_Item::player);
while (cave[loc].find(Cave_Item::ladder) != cave[loc].cend())
loc = Get_A_Random_Grid_Point(rows_, cols_);
Add_Item(loc, Cave_Item::wumpus);
for (auto i = 0; i < 3; ++i) {
while (!(cave[loc]).empty()) loc = Get_A_Random_Grid_Point(rows_, cols_);
Add_Item(loc, Cave_Item::pit);
}
while (cave[loc].find(Cave_Item::ladder) != cave[loc].cend() ||
cave[loc].find(Cave_Item::pit) != cave[loc].cend())
loc = Get_A_Random_Grid_Point(rows_, cols_);
cave[loc].insert(Cave_Item::gold);
}
bool Cave::Is_Square_Valid(const grid_point loc) noexcept {
const int& row = loc.at(0);
const int& col = loc.at(1);
if (row < 1 || row > rows_) return false;
if (col < 1 || col > cols_) return false;
return true;
}
void Cave::Remove_Adjacent(grid_point loc, Cave_Item sensation)
{
for (auto& coord : loc) {
coord--;
if (Is_Square_Valid(loc)) {
const bool first = Remove_Item(loc, sensation);
if (!first) {
cout << "Disaster first remove adjacent\n";
std::abort();
}
}
coord += 2;
if (Is_Square_Valid(loc)) {
const bool first = Remove_Item(loc, sensation);
if (!first) {
cout << "Disaster second remove adjacent\n";
std::abort();
}
}
coord--;
}
}
int main()
{
constexpr int rows = 4;
constexpr int cols = 4;
Cave cave(rows, cols);
for (int r = 1; r <= rows; r++) {
for (int c = 1; c <= cols; c++) {
const grid_point loc{ r,c };
cave.Print_Square(loc);
}
}
cave.Print_Cave_Diagram();
cave.Remove_Item(Cave_Item::wumpus);
cout << "\n";
cave.Print_Cave_Diagram();
cave.Add_Item({ 1,1 }, Cave_Item::wumpus);
cout << "\n";
cave.Print_Cave_Diagram();
return 0;
}
</code></pre>
<p>Additionally, I was already working on trying to encapsulate random number generation, so I wrote my first impl/pimpl implementation of a <code>Rand class</code>. During this, the compiler complained that I needed to include the other constructors (again seen as gsl::suppress), and when I did the program fail to work. Interestingly, one of the gsl suggestions to make a variable const since it was used only once proved to be fatal when I used the compiler explorer <code>http://godbolt.org</code> I discovered that my changes created errors in gcc. So, how can I improve this code? </p>
<p>dhth.hpp</p>
<pre><code>#ifndef DHTH_HPP
#define DHTH_HPP
#pragma once
#include <random>
#include <memory>
#include <iostream>
namespace dhth {
class Rand {
public:
Rand() noexcept;
[[gsl::suppress(26432)]]
~Rand();
// Rand(const Rand& rand) = default;
// Rand(Rand&& rand) = default;
double operator()(void);
int operator()(int limit);
int operator()(int lower, int upper);
double operator()(double lower, double upper);
private:
class impl;
std::unique_ptr<impl> upimpl;
};
}
#endif
</code></pre>
<p>dhth.cpp</p>
<pre><code>#include "dhth.hpp"
namespace dhth {
class Rand::impl {
public:
impl() noexcept {
try { e1.seed(rd()); }
catch (const std::exception e)
{
try {
std::cout << "Failed to seed\n";
}
catch (...) {
std::abort();
}
}
}
[[gsl::suppress(26432)]]
~impl() {}
// impl(const impl& imp) = default;
// impl(impl&& imp) = default;
int func(int lower, int upper);
double func(double lower, double upper);
private:
std::random_device rd;
std::default_random_engine e1;
};
#pragma warning(push)
#pragma warning(disable:26447) // noexcept violation
Rand::Rand() noexcept : upimpl{ std::make_unique<impl>() } {}
#pragma warning(pop)
Rand::~Rand() = default;
double Rand::operator()(void) {
return upimpl->func(0.0, 1.0);
}
int Rand::operator()(int limit)
{
return upimpl->func(0,limit-1);
}
int Rand::operator()(int lower, int upper)
{
return upimpl->func(lower, upper);
}
double Rand::operator()(double lower, double upper)
{
return upimpl->func(lower, upper);
}
[[gsl::suppress(26496)]] // dist used once make const
int Rand::impl::func(int lower, int upper)
{
std::uniform_int_distribution<int> dist(lower, upper);
return dist(e1);
}
[[gsl::suppress(26496)]] // dist used once make const
double Rand::impl::func(double lower, double upper)
{
std::uniform_real_distribution<double> dist(lower, upper);
return dist(e1);
}
}
</code></pre>
<p>This is the output of the entire program. I make remove the wumpus and then add it back to location 1,1.</p>
<pre><code>This part of the cave (1, 1) contains:
ladder
player
This part of the cave (1, 2) contains:
nothing
This part of the cave (1, 3) contains:
breeze
This part of the cave (1, 4) contains:
pit
This part of the cave (2, 1) contains:
stench
gold
This part of the cave (2, 2) contains:
breeze
This part of the cave (2, 3) contains:
pit
This part of the cave (2, 4) contains:
breeze
This part of the cave (3, 1) contains:
wumpus
This part of the cave (3, 2) contains:
breeze
stench
This part of the cave (3, 3) contains:
breeze
This part of the cave (3, 4) contains:
nothing
This part of the cave (4, 1) contains:
breeze
stench
This part of the cave (4, 2) contains:
pit
This part of the cave (4, 3) contains:
breeze
This part of the cave (4, 4) contains:
nothing
+----------+----------+----------+----------+
| | | | |
| ladder | | breeze | pit |
| player | | | |
| | | | |
+----------+----------+----------+----------+
| | | | |
| stench | breeze | pit | breeze |
| gold | | | |
| | | | |
+----------+----------+----------+----------+
| | | | |
| wumpus | breeze | breeze | |
| | stench | | |
| | | | |
+----------+----------+----------+----------+
| | | | |
| breeze | pit | breeze | |
| stench | | | |
| | | | |
+----------+----------+----------+----------+
+----------+----------+----------+----------+
| | | | |
| ladder | | breeze | pit |
| player | | | |
| | | | |
+----------+----------+----------+----------+
| | | | |
| gold | breeze | pit | breeze |
| | | | |
| | | | |
+----------+----------+----------+----------+
| | | | |
| | breeze | breeze | |
| | | | |
| | | | |
+----------+----------+----------+----------+
| | | | |
| breeze | pit | breeze | |
| | | | |
| | | | |
+----------+----------+----------+----------+
+----------+----------+----------+----------+
| | | | |
| ladder | stench | breeze | pit |
| player | | | |
| wumpus | | | |
+----------+----------+----------+----------+
| | | | |
| stench | breeze | pit | breeze |
| gold | | | |
| | | | |
+----------+----------+----------+----------+
| | | | |
| | breeze | breeze | |
| | | | |
| | | | |
+----------+----------+----------+----------+
| | | | |
| breeze | pit | breeze | |
| | | | |
| | | | |
+----------+----------+----------+----------+
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T16:32:42.500",
"Id": "455017",
"Score": "0",
"body": "A comment as to why I am receiving down votes would be appreciated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T16:47:56.987",
"Id": "455021",
"Score": "2",
"body": "_\"I cannot figure out how to rewrite the code not to get these errors\"_ As you should know already: SE Code Review is only for reviewing already working code, and not about fixing errors."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T17:11:17.183",
"Id": "455028",
"Score": "1",
"body": "The code as written works! (as demonstrated by the output) Probably should have said \"warnings.\" When I tried to add the commented code it didn't work. I'm trying to understand the impl/pimpl idiom."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T17:20:30.877",
"Id": "455030",
"Score": "2",
"body": "Questions asking what the code does are also off-topic, so we can't help with the impl/pimpl idiom."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T22:04:29.127",
"Id": "455171",
"Score": "1",
"body": "I've edited to reword \"error\" -> \"warning\", but I'll leave it up to the community to vote to keep it open or have it closed, since it's unclear to me whether the last part is about code that produces compiler errors... which *would* be off-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T02:03:11.943",
"Id": "455202",
"Score": "1",
"body": "Honestly this looks totally on topic. The code runs, gives the expected output. I suspect you got downvoted/VTCd because there was the word \"error\" in your title. This looks on-topic to me."
}
] |
[
{
"body": "<h2>Include Order</h2>\n\n<pre><code>#include <iostream>\n#include <map>\n#include <vector>\n#include <array>\n#include <set>\n#include <string>\n#include <string_view>\n#include \"dhth.hpp\"\n</code></pre>\n\n<p>I always put the most significant at the top and then work down to the least significant. The reason for this is that if I miss a required header file in the most significant include then I will spot it during compilation.</p>\n\n<p>Here you put the most significant class last \"dhth.hpp\". This is the most important header to \"dhth.cpp\" so it should go first. At the moment if this header file requires something like <code>vector</code> (lets just imagine) to work correctly that fact is hidden from you because you have included this in the source file first. If you look at from another developer that is building \"TheLandOfWump.cpp\" and he #includes your header file \"dhth.hpp\" but finds it does not compile because you forgot to include <code>vector</code> he is going to be pissed that you have not included the required headers in your file (why does he need to include <code>vector</code> in his source file if he is not using it.</p>\n\n<p>So load headers from most significant to least.</p>\n\n<pre><code> #include \"HeaderForThisSource.h\"\n\n #include \"OtherHeadersForThisProject.h\"\n\n #include <Headers For libraries you use>\n\n #include <Standard C++ Libraries>\n\n #include <C Libraries>\n</code></pre>\n\n<p>Within each group some thinks it is worth sorting them (alphabetically). Personally I don't but I do group them with each block. For the C++ headers I will list all the stream stuff together all the iterator stuff together and all the algorithm stuff together.</p>\n\n<p>Though I don't use alphabetical sorting I do trying and making the grouping logical.</p>\n\n<hr>\n\n<p>Not quite is bad as <code>using namespace std;</code> but close.</p>\n\n<pre><code>using std::vector;\nusing std::array;\nusing std::set;\nusing std::map;\nusing std::string;\nusing std::cout;\nusing std::endl;\n</code></pre>\n\n<p>Is it really that hard to prefix standard types with <code>std::</code>?</p>\n\n<hr>\n\n<p>Two points:</p>\n\n<pre><code>using grid_point = array<int, 2>;\n</code></pre>\n\n<p>Not sure an array is the best type?</p>\n\n<pre><code>std::pair? std::tuple? struct Point {int x,y};\n</code></pre>\n\n<hr>\n\n<p>Random. You are doing it wrong.</p>\n\n<pre><code>grid_point Get_A_Random_Grid_Point(int rows, int cols) {\n dhth::Rand rand;\n return grid_point{ rand(1, rows), rand(1, cols) };\n}\n</code></pre>\n\n<p>The random number generator is not supposed to be created everytime you need a random number. You create it once then use it multiple times so you get a sequence of numbers that are random from the same generator.</p>\n\n<p>In this context you can do this by marking it a static member of the function. But I am sure you want to use it other contexts so making it a global object or accessed from a static function on Rand may be a better choice.</p>\n\n<pre><code>grid_point Get_A_Random_Grid_Point(int rows, int cols) {\n static dhth::Rand rand;\n return grid_point{ rand(1, rows), rand(1, cols) };\n}\n</code></pre>\n\n<hr>\n\n<p>Not sure that catching the exception here is a good thing.</p>\n\n<pre><code>string citos(Cave_Item item) noexcept { // citos - Cave_Item to std::string\n try {\n switch (item) {\n case Cave_Item::breeze: return string{ \"breeze\" };\n case Cave_Item::stench: return string{ \"stench\" };\n case Cave_Item::pit: return string{ \"pit\" };\n case Cave_Item::ladder: return string{ \"ladder\" };\n case Cave_Item::player: return string{ \"player\" };\n case Cave_Item::wumpus: return string{ \"wumpus\" };\n case Cave_Item::gold: return string{ \"gold\" };\n default:\n std::abort();\n }\n return string{ \"error\" };\n }\n catch (...)\n {\n try { \n cout << \"Failed to make string\\n\"; \n return string{ \"error\" };\n }\n catch (...) {\n std::abort();\n }\n }\n}\n</code></pre>\n\n<p>Just let the exception propogate all the way out and close the application. If this function fails then something has gone terribly wrong with the application and trying to continue is a mistake.</p>\n\n<p>In main you can catch all exceptions and report on them.</p>\n\n<pre><code>int main()\n{\n try {\n runGame();\n }\n // Catch print error message then re-throw the exception.\n // This way the external systems will know the application\n // failed abnormally.\n //\n // Also use std::cerr for error messages.\n catch(std::exception const& e) {\n std::cerr << \"Exception: \" << e.what() << \"\\n\";\n throw;\n }\n catch(...) {\n std::cerr << \"Exception: Unknown\\n\";\n throw;\n }\n} \n</code></pre>\n\n<hr>\n\n<p>You should only mark a function <code>noexcept</code> if it cant throw an exception.</p>\n\n<pre><code>Cave::Cave() noexcept\n</code></pre>\n\n<p>Again I don't like your use of <code>std::abort()</code> here. Simply allow the exception to propogate up to main and force the application to exit. That way you make sure all the resources are correctly released via the destructors.</p>\n\n<pre><code>{\n try {\n init();\n }\n catch (...) {\n try {\n cout << \"Failed to initialize\\n\";\n }\n catch (...) {\n std::abort();\n }\n }\n}\n</code></pre>\n\n<p>So 1: remove <code>noexcept</code> 2: Remove the try/catch 3: Catch the exception in main.</p>\n\n<hr>\n\n<p>Always put braces around sub statements: </p>\n\n<pre><code> if (cave_item == Cave_Item::wumpus) Fill_Adjacent(loc, Cave_Item::stench);\n</code></pre>\n\n<p>It looks innocuous enough. But there are situations where this will fail. So it is good habit to always put braces around the statements of an <code>if</code>, even if there looks to only be one.</p>\n\n<pre><code> if (cave_item == Cave_Item::wumpus) {\n Fill_Adjacent(loc, Cave_Item::stench);\n }\n</code></pre>\n\n<p>This protects you from some enthusiastic amateur breaking the code by changing <code>Fill_Adjacent()</code> from a method to inline macro. I have seen that happen.</p>\n\n<p>Also using two lines is always nice for when you are debugging. Its hard to tell with the interactive debugger has decided to activate the if statement if it is all on one line. If it is on two lines simply stepping through this immediately shows that the if was activated.</p>\n\n<hr>\n\n<p>Not sure it is worth using the <code>at()</code> method.</p>\n\n<pre><code> cout << \"This part of the cave (\" << loc.at(0) << \", \" << loc.at(1) <<\n \") contains:\\n\";\n</code></pre>\n\n<p>We know a location is 2 places. So 0 and 1 are always valid. So why are we forcing a check to see if they are valid? I would use <code>loc[0]</code> and <code>loc[1]</code> unverified check because I know the array always has two elements (actually I would probably use a Point class so there is no need to worry and x and y cords have named members that are checked by the compiler at compile time).</p>\n\n<hr>\n\n<p>Again I would always use braces around the sub expression.</p>\n\n<pre><code> for (auto item : cave[loc]) cout << \" \" << citos(item) << \"\\n\";\n</code></pre>\n\n<p>And put it on two lines so it is easy to read:</p>\n\n<pre><code> for (auto item : cave[loc]) {\n cout << \" \" << citos(item) << \"\\n\";\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T21:33:03.100",
"Id": "455039",
"Score": "0",
"body": "Thank you for your review, I learned a lot. The choice of array was driven in part on the by the desire to use a loop in `Fill_Adjacent` routine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T23:03:49.627",
"Id": "455177",
"Score": "0",
"body": "1. Why differentiate between standard headers? Also, mention sorting each list? 2. There is something to be said for `thread_local` for random number generators. 3. Always forcing blocks is a call to flamewar. Anyway, good one."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T20:41:30.707",
"Id": "232909",
"ParentId": "232896",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "232909",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T15:28:00.523",
"Id": "232896",
"Score": "3",
"Tags": [
"c++",
"beginner",
"reinventing-the-wheel",
"c++14"
],
"Title": "Cave Setup for Hunting the Wumpus"
}
|
232896
|
<p>Here's a password generator I created.</p>
<pre><code>### THIS PROGRAM WAS CREATED FOR LEARNING PURPOSES ###
### AND SHOULD NOT BE USED TO CREATE PASSWORDS! ###
import string
from enum import Enum
from random import randint, shuffle, choice
class PasswordError(Exception):
__module__ = Exception.__module__
# Types of characters possible
class Types(Enum):
CAP = 'CAP' # Capital
SMA = 'SMA' # Small
DIG = 'DIG' # Digits
SPE = 'SPE' # Special
# Characters for each type of possible characters
type_chars = {
Types.CAP: string.ascii_uppercase,
Types.SMA: string.ascii_lowercase,
Types.DIG: string.digits,
Types.SPE: '!()-.?[]_`~;:@#$%^&*='
}
def password_generator(min_length=6, max_length=20, caps=1, small=1, digits=1, special=1):
types = {
Types.CAP: caps,
Types.SMA: small,
Types.DIG: digits,
Types.SPE: special,
}
num_chars = sum(list(types.values())) # Number of mandatory characters
min_length = max(num_chars, min_length) # In case 'num_chars' is greater
# Number of characters required for each possible type of character
# Is greater than maximum possible length
if min_length > max_length:
raise PasswordError(f'No password with the given criteria')
length = randint(min_length, max_length)
# List that stores the "types" of possible character
char_list = []
# Mandatory requirements
for typ, val in zip(types.keys(), types.values()):
char_list.extend([typ] * val)
# The remaining values to fill
for rem in range(length - num_chars):
char_list.append(choice(list(types.keys())))
shuffle(char_list)
password = ''
for typ in char_list:
password += choice(type_chars[typ])
return password
if __name__ == '__main__':
min_length = int(input('Minimum number of characters required: '))
max_length = int(input('Maximum number of characters possible: '))
print()
caps = int(input('Number of capital letters required: '))
small = int(input('Number of small letters required: '))
digits = int(input('Number of digits required: '))
special = int(input('Number of special characters required: '))
print()
number = int(input('Number of passwords required: '))
print('\n' + '-' * 50 + '\n')
print(' Here are your passwords: \n')
for i in range(number):
print(password_generator(min_length, max_length, caps, small, digits, special))
</code></pre>
<p>You can also modify the mandatory types of characters (Like 3 caps, 2 digits, etc). Also, minimum length and maximum length can be specified.</p>
<p>I think this code looks a bit ugly. How do I improve this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T15:32:52.877",
"Id": "455112",
"Score": "6",
"body": "Please note that [Official Guidelines](https://spycloud.com/new-nist-guidelines/) state that *requiring* special character classes results in bad passwords. The only difference it makes it that it turns all `password` into `Password123!` instead, which add exactly zero security."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T16:31:01.297",
"Id": "455127",
"Score": "0",
"body": "@Gloweye I didn't quite know that! I just based of my program from my experience with websites that said 'weak' for `password` and 'medium' for `Password123!` and 'strong' for `P@ssword$123!`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T18:51:47.897",
"Id": "455148",
"Score": "3",
"body": "@Gloweye regardless, many sites still require special characters. This tool generates passwords. OP is not asking advice for what rules to use for a site they control."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T03:48:25.313",
"Id": "455208",
"Score": "2",
"body": "I'd suggest including a warning in the output (or at least in the source as a comment) that this is (probably) *not* safe for real use; you're not a crypto expert. Neither am I, but I know enough to be cautious about where my random numbers come from (does Python make sure to seed its RNG from /dev/random or similar? Maybe but IDK), and that there are some agreed-upon standards for generating passwords for humans."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T06:51:16.330",
"Id": "455209",
"Score": "0",
"body": "@CaptainMan Many sites have crappy password standards. I didn't say this program was bad because of it, but it's something people should be aware of. (But please to note that special character *should* be allowed in passwords - forbidding them is even less secure than forcing.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T06:52:29.710",
"Id": "455210",
"Score": "2",
"body": "@PeterCordes You should read AlexV's answer below. Python has the `secrets` module for cryptographic-quality random numbers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T06:54:09.257",
"Id": "455211",
"Score": "0",
"body": "@Gloweye Yes, I agree with you. I wasn't aware of it till when you posted the official guidelines. Thanks for posting it!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T07:09:05.867",
"Id": "455213",
"Score": "0",
"body": "@Gloweye: yeah, I saw that after commenting. Probably I'm being overcautious, and nobody would take security-critical code from *questions* posted on codereview, but it might still be a good idea to make the first line a warning comment like `# don't use for real passwords; this is a toy program as a learning exercise`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T07:12:54.793",
"Id": "455214",
"Score": "0",
"body": "@PeterCordes Done!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T07:34:55.807",
"Id": "455217",
"Score": "0",
"body": "@PeterCordes Never underestimate the cross section of laziness and ignorance that could lead to people copying random internet code. If Alex's answer hadn't been there, I'd have mentioned the secrets module right away as well."
}
] |
[
{
"body": "<p>There are a few things I'd suggest to clean up the code. </p>\n\n<p>First, you should be able to write the following</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for typ, val in zip(types.keys(), types.values()):\n char_list.extend([typ] * val)\n</code></pre>\n\n<p>without using <code>zip</code> by doing as follows</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for typ, val in types.items():\n char_list.extend([typ] * val)\n</code></pre>\n\n<h3>Comprehensions</h3>\n\n<p>Comprehensions are a great way to clean up.</p>\n\n<p>The first case would be </p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for rem in range(length - num_chars):\n char_list.append(choice(list(types.keys())))\n</code></pre>\n\n<p>as</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>char_list.extend([choice(list(types.keys())) for _ in range(length - num_chars)])\n</code></pre>\n\n<p>And a second time</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>password = ''\n\nfor typ in char_list:\n password += choice(type_chars[typ])\n\nreturn password\n</code></pre>\n\n<p>as</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>return \"\".join([choice(type_chars[typ]) for typ in char_list])\n</code></pre>\n\n<h3>Functions</h3>\n\n<p>I'd probably put the following piece of code as a separate function to make it more modular and manageable</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># List that stores the \"types\" of possible character\nchar_list = []\n\n# Mandatory requirements\nfor typ, val in zip(types.keys(), types.values()):\n char_list.extend([typ] * val)\n\n# The remaining values to fill\nfor rem in range(length - num_chars):\n char_list.append(choice(list(types.keys())))\n\nshuffle(char_list)\n</code></pre>\n\n<p>Likewise, with the suggested list comprehension that makes the password.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def make_password(char_list)\n return \"\".join([choice(type_chars[typ]) for typ in char_list])\n</code></pre>\n\n<h3>Optionals (fancy)</h3>\n\n<p>If you want to be very fancy, you can use <code>dataclasses</code> or <code>attrs</code> to package the options to the main function. This would allow you to make some validation of the input, namely, that everything you get are numbers (particularly <code>ints</code> or a string that can be parsed as such). Such a dataclass can be thought of as the communication layer between the front end (whatever is in the <code>__main__</code> part of the program) and the backend part in <code>generate_password</code>.</p>\n\n<p>I say this because your program will fail if you don't give numbers. For example in the first logic line <code>num_chars = sum(list(types.values()))</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T20:48:52.157",
"Id": "232910",
"ParentId": "232897",
"Score": "4"
}
},
{
"body": "<p>The <a href=\"https://codereview.stackexchange.com/a/232910/92478\">other</a> <a href=\"https://codereview.stackexchange.com/a/232913/92478\">answers</a> have great hints that you should definitely follow.</p>\n\n<p>However, since we are talking about passwords here, a little bit of extra security might not hurt. Especially if it's readily available in the <a href=\"https://docs.python.org/3/library/secrets.html\" rel=\"nofollow noreferrer\"><code>secrets</code></a> module in Python 3. <code>secrets</code> uses a cryptograhically strong random number generator (in contrast to the <em>pseudo</em> random number generator in the normal <code>random</code> module). There is a special warning in that regard in the <a href=\"https://docs.python.org/3/library/random.html\" rel=\"nofollow noreferrer\">docs of random</a>. If you want to stick to <code>random</code>, at least use an instance of <a href=\"https://docs.python.org/3/library/random.html#random.SystemRandom\" rel=\"nofollow noreferrer\"><code>random.SystemRandom()</code></a>, which is basically what <code>secrets</code> does. An example:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>RNG = random.SystemRandom()\n\ndef password_generator(...):\n ...\n # The remaining values to fill\n type_ = list(types.keys())\n for rem in range(length - num_chars):\n char_list.append(RNG.choice(type_))\n # alternatively\n char_list.append(secrets.choice(type_))\n ...\n</code></pre>\n\n<p><code>random.choice</code> uses what is called a pseudo-random number generator, i.e. an algorithm that generates a deterministic \"randomly looking\" sequence of bytes starting from a given seed. <code>secrets.choice</code> uses a randomness source implemented in the OS, which likely takes electrical noise and other things into consideration to generate non-deterministic random data. random.org has a comprehensive article on the differences at <a href=\"https://www.random.org/randomness/\" rel=\"nofollow noreferrer\">https://www.random.org/randomness/</a>. And of course, there is also the obligatory Wikipedia page about <a href=\"https://en.wikipedia.org/wiki/Random_number_generation\" rel=\"nofollow noreferrer\">Randomness</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T09:16:11.817",
"Id": "455070",
"Score": "0",
"body": "Great answer! But can I ask why `secrets.choice` is cryptographically stronger than `random.choice`? The random library page doesn't quite explain it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T15:29:52.353",
"Id": "455111",
"Score": "2",
"body": "+1 for secrets. This is important information. Since other answer lack it, this is the best answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T16:39:36.873",
"Id": "455131",
"Score": "2",
"body": "Sorry this wasn't the accepted answer. This really was a great answer and a great point, but it mostly improves the output cryptographically, but does not improve the code as a whole which @RomanPerekhrest's answer does."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T21:37:59.797",
"Id": "232912",
"ParentId": "232897",
"Score": "23"
}
},
{
"body": "<h3><em>Refactoring in steps</em></h3>\n\n<p><strong><em>Enumeration class</em></strong></p>\n\n<p><code>Types</code> is too generic name for the <em>enum</em> representing <em>char types</em>. Renamed to <strong><code>CharTypes</code></strong>.<br>\nInstead <code>CAP</code>, <code>SMA</code>, <code>DIG</code>, <code>SPE</code> as <em>enumeration members</em> are better replaced with a more common/familiar and comprehensive abbreviations/associations:<br><code>UPPER</code>, <code>LOWER</code>, <code>DIGIT</code> and <code>SPECIAL</code>.<br>\nSince <code>string.ascii_uppercase</code> and other <code>string.*</code> are essentially just <em>string constants</em> - they can be easily set as <em>enumeration values</em>:</p>\n\n<pre><code>class CharTypes(Enum):\n UPPER = string.ascii_uppercase # Capital\n LOWER = string.ascii_lowercase # Small\n DIGIT = string.digits # Digits\n SPECIAL = '!()-.?[]_`~;:@#$%^&*=' # Special\n</code></pre>\n\n<p>thus, making all intermediate re-mappings like <code>type_chars</code> and <code>types</code> (in <code>password_generator</code> function) redundant and unnecessary. </p>\n\n<hr>\n\n<p><strong><em><code>password_generator</code></strong> function</em></p>\n\n<p>The function signature is slightly changed in arguments names to conform with <code>CharTypes</code> members:</p>\n\n<pre><code>def password_generator(min_length=6, max_length=20, upper=1, lower=1, digits=1, special=1)\n</code></pre>\n\n<p><code>types</code> mapping is eliminated as redundant.</p>\n\n<p><em>char counts</em> passed as arguments are gathered and summed at once:</p>\n\n<pre><code>char_counts = (upper, lower, digits, special)\nnum_chars = sum(char_counts)\n</code></pre>\n\n<p>Avoid overwriting/assigning to function argument like <code>min_length = max(num_chars, min_length)</code> as <strong><code>min_length</code></strong> might be potentially referenced as <em>\"original\"</em> argument value (and relied on) in other places in the function's body.<br>\nA safer way is assigning it to a separate variable:</p>\n\n<pre><code>min_len = max(num_chars, min_length)\n</code></pre>\n\n<p><code>length</code> variable is renamed to <strong><code>target_length</code></strong> (to emphasize the <em>final</em> size).</p>\n\n<p><code>char_list</code> is renamed to <strong><code>char_types</code></strong> as it's aimed to accumulate <code>CharTypes</code> enum members</p>\n\n<p>Two <code>for</code> loops which performed <code>char_list.extend</code> and <code>char_list.append</code> are efficiently replaced with 2 <em>generators</em> which further joined/merged by <a href=\"https://docs.python.org/3/library/itertools.html#itertools.chain\" rel=\"nofollow noreferrer\"><code>itertools.chain</code></a> function:</p>\n\n<pre><code>char_types = list(chain(*([c_type] * num for c_type, num in zip(CharTypes, char_counts)),\n (choice(char_types_enums) for _ in range(target_length - num_chars))))\n</code></pre>\n\n<p>Furthermore, <code>itertools.chain</code> is smart enough to skip <em>empty</em> generators (if let's say there's no <em>remaining values to fill</em>).</p>\n\n<p>The last <code>for</code> loop (accumulating password from random chars) is simply replaced with <code>str.join</code> call on generator expression:</p>\n\n<pre><code>password = ''.join(choice(char_type.value) for char_type in char_types)\n</code></pre>\n\n<hr>\n\n<p>The whole crucial functionality is now shortened to the following:</p>\n\n<pre><code>import string\nfrom enum import Enum\nfrom random import randint, shuffle, choice\nfrom itertools import chain\n\n\nclass PasswordError(Exception):\n pass\n\n\nclass CharTypes(Enum):\n UPPER = string.ascii_uppercase # Capital\n LOWER = string.ascii_lowercase # Small\n DIGIT = string.digits # Digits\n SPECIAL = '!()-.?[]_`~;:@#$%^&*=' # Special\n\n\ndef password_generator(min_length=6, max_length=20, upper=1, lower=1, digits=1, special=1):\n char_counts = (upper, lower, digits, special)\n num_chars = sum(char_counts) # Number of mandatory characters\n min_len = max(num_chars, min_length) # In case 'num_chars' is greater\n\n # If number of characters required for each possible char type\n # is greater than maximum possible length\n if min_len > max_length:\n raise PasswordError(f'No password with the given criteria')\n\n target_length = randint(min_len, max_length)\n char_types_enums = list(CharTypes) # get list of enums to pass `random.choice` call\n\n # List of char \"types\" comprised of: mandatory requirements + remaining values to fill\n char_types = list(chain(*([c_type] * num for c_type, num in zip(CharTypes, char_counts)),\n (choice(char_types_enums) for _ in range(target_length - num_chars))))\n shuffle(char_types)\n\n password = ''.join(choice(char_type.value) for char_type in char_types)\n return password\n\n\nif __name__ == '__main__':\n ....\n</code></pre>\n\n<p>Sample usage:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Minimum number of characters required: >? 10\nMaximum number of characters possible: >? 30\nNumber of capital letters required: >? 5\nNumber of small letters required: >? 4\nNumber of digits required: >? 6\nNumber of special characters required: >? 5\nNumber of passwords required: >? 4\n--------------------------------------------------\n\n Here are your passwords: \n\n32S%km3A^v04h9pwR-T7O;=0O\nmh8a:38Q-pGS3PtGs)e0P1g)$(#0U1\nz@a0r;b7v.~K!8S@R343J7L\nMie:8Ec0C=3Cz93HPHDFm_84#;6@\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T07:19:21.477",
"Id": "455216",
"Score": "0",
"body": "Yes, treating incoming args as const is often considered good style especially in a function of non-trivial size (and if nothing else makes debugging easier). But the choice of names is problematic here: `min_len` vs. `min_length` are visually very similar. A reader looking at some part of the function could easily miss that it was reading a different var name, not the arg. Naming is hard, especially when you need multiple variables with similar semantic meaning/purpose but holding different values."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T16:12:09.023",
"Id": "455279",
"Score": "0",
"body": "-1 for not using `secrets`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T16:26:53.157",
"Id": "455284",
"Score": "0",
"body": "@GregSchmit-ReinstateMonica, You would need to figure out one simple thing - I didn't review a cryptography but the codebase. But at least you've downvoted openly, although not very convincingly, in my opinion"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T16:33:27.970",
"Id": "455288",
"Score": "0",
"body": "@RomanPerekhrest I did figure that out. Using `secrets` rather than `random` when writing a **PASSWORD GENERATOR** doesn't take a cryptographer, just a code reviewer :) -- BTW, I know I can be strident, but my downvote is not personal. If you edit your answer to use `secrets` then I will upvote you very quickly!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T17:02:48.293",
"Id": "455291",
"Score": "0",
"body": "@GregSchmit-ReinstateMonica, The best I can advise to you is to spend your energy and efforts for writing your own answer with a new implementation based on `secrets` to express your idea more extensively and convincing the people how the best answer should look like. Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T17:07:38.450",
"Id": "455292",
"Score": "1",
"body": "AlexV already wrote an answer using `secrets` (why it has more upvotes), but yours is the accepted answer so it would be good to use `secrets` on yours as well. I'm sorry you're offended that you didn't know to use that module when generating secrets."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T19:51:40.867",
"Id": "455312",
"Score": "3",
"body": "@GregSchmit-ReinstateMonica while recommending `secrets` would improve the quality, I don't see in this answer where `random` is specifically recommended. [Answers need not cover every issue in every line of the code](https://codereview.stackexchange.com/help/how-to-answer), and if an answer skips over certain components, I don't think that invalidates the rest of the answer. Is `secrets` the way to go for the cryptography? Absolutely. Is that relevant for *this specific answer*? I don't think so, especially since AlexV covered that bit perfectly in their answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T19:59:04.197",
"Id": "455314",
"Score": "0",
"body": "@C.Nivs Ok, and I also note that reading back what I wrote, I realize I sound like a jerk. I just figured that crypto should be important for a password generator. It's like seeing a code review for a SSH server where the review doesn't mention that the implementation doesn't check host keys at all, so anyone could MITM the implementation. But now we want to have it be the top-listed code review because they optimized some some list comprehensions and renamed some variables."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T20:00:11.687",
"Id": "455315",
"Score": "0",
"body": "@RomanPerekhrest Sorry for my \"I'm sorry you're offended...\" comment. That was jerky."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T20:02:45.510",
"Id": "455316",
"Score": "0",
"body": "Fair point as that may be, it's not outside reason to see OP's mention *this looks ugly* and not go for some style recommendations. If I were to tackle this, I'd go for the style and organization stuff largely because I'm no expert at crypto (I learned about `secrets` through this question :) ). So, I'd leave the crypto stuff to the experts there, and offer the advice I can speak to. I'd argue it's *really* poor form to offer bad advice rather than none at all"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T20:09:59.460",
"Id": "455317",
"Score": "0",
"body": "@C.Nivs Ok, fair enough, but that's the whole point of the `secrets` module. It would be silly of me to criticize him for not manually feeding ambient temperature data into the password-generation process, because if he tried to do that as a non-cryptographer, he could easily screw it up and make the resulting password less random. The `secrets` module is explicitly a user-friendly tool to provide non-cryptographers an interface for generating secrets. But I take your point that if one didn't know about the `secrets` module, then one wouldn't know it's meant for non-cryptographers."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T22:07:25.140",
"Id": "232913",
"ParentId": "232897",
"Score": "13"
}
},
{
"body": "<p>You can generate a password simply with the <code>random</code> module.</p>\n\n<pre><code>import string\nimport random\n\nls = string.ascii_letters + string.digits + string.punctuation\nlength = random.randrange(6, 20) \npwd = random.choices(ls, k=length)\nprint('new password: ', ''.join(pwd))\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>new password: xsC+.vrsZ<$\\\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T13:52:17.433",
"Id": "455098",
"Score": "1",
"body": "Great idea! I should have thought of that! In the case of really needing to use the generator, I'll use this method. But right now, I'm trying to improve my programming skills! :-D"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T11:48:50.933",
"Id": "232938",
"ParentId": "232897",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "232913",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T16:15:17.160",
"Id": "232897",
"Score": "14",
"Tags": [
"python",
"python-3.x"
],
"Title": "Password generator in python"
}
|
232897
|
<p>I've been working on a personal project. There's this game called <a href="https://en.wikipedia.org/wiki/Teamfight_Tactics" rel="nofollow noreferrer">TFT</a> which is an autochess game. Each match is played by 8 players and there's a <strong>shared</strong> pool of champions. Each champion has their cost and how many of each there are, below is the table:</p>
<p>12 Champs that cost 1 gold, 39 of each champ.</p>
<p>12 Champs that cost 2 gold, 26 of each champ.</p>
<p>12 Champs that cost 3 gold, 18 of each champ.</p>
<p>9 Champs that cost 4 gold, 13 of each champ.</p>
<p>6 Champs that cost 5 gold, 10 of each champ.</p>
<p>So, I've been doing some functions to <strong>get the probability of getting x champ in a 5 champion deck</strong>, something I forgot to say is that in the game, you have your player level which somewhat influences in the pool, below is the multiplicator array, each row is a player level starting from Level 2 (which is the zeroth row) to Level 9, and each column is the champions cost (cost 1 to 5).</p>
<pre><code>// pool.class.js
class Pool {
constructor(champPool) {
this.champPool = champPool; //this is an array of Champions(name,pool,cost)
this.chancePerTier = [
[1, 0, 0, 0, 0], //Level 2
[0.7, 0.25, 0.05, 0, 0], //Level 3
[0.5, 0.35, 0.15, 0, 0], //Level 4
[0.35, 0.35, 0.25, 0.05, 0], //Level 5
[0.25, 0.35, 0.3, 0.1, 0], //Level 6
[0.2, 0.3, 0.33, 0.15, 0.02], //Level 7
[0.15, 0.2, 0.35, 0.24, 0.06], //Level 8
[0.1, 0.15, 0.3, 0.3, 0.15] //Level 9
];
}
getChampProbability(champName, playerLevel) {
let poolSize = this.getPoolBasedOnLevel(playerLevel);
let poolIndex = this.champPool.findIndex(function(champ) {
return champ.getName() === champName;
});
if (poolIndex === -1) return 0;
let champPool = this.champPool[poolIndex].getPool();
let champCost = this.champPool[poolIndex].getCost();
return (
(champPool / poolSize) *
5 *
100 *
this.chancePerTier[playerLevel - 2][champCost - 1]
).toFixed(2);
}
getPoolBasedOnLevel(summonerLevel) {
let pool;
if (summonerLevel == 2) {
pool = this.champPool.reduce(function(prevChamp, currentChamp) {
if (currentChamp.getCost() == 1) {
return prevChamp + currentChamp.getPool();
} else {
return prevChamp;
}
}, 0);
} else if (summonerLevel == 3 || summonerLevel == 4) {
pool = this.champPool.reduce(function(prevChamp, currentChamp) {
if (currentChamp.getCost() >= 1 && currentChamp.getCost() <= 3) {
return prevChamp + currentChamp.getPool();
} else {
return prevChamp;
}
}, 0);
} else if (summonerLevel == 5 || summonerLevel == 6) {
pool = this.champPool.reduce(function(prevChamp, currentChamp) {
if (currentChamp.getCost() >= 1 && currentChamp.getCost() <= 4) {
return prevChamp + currentChamp.getPool();
} else {
return prevChamp;
}
}, 0);
} else {
pool = this.getWholePool();
}
return pool;
}
getWholePool() {
let allPool = this.champPool.reduce(function(prevChamp, currentChamp) {
return prevChamp + currentChamp.getPool();
}, 0);
return allPool;
}
}
module.exports = Pool;
</code></pre>
<pre><code>// champion.class.js
class Champion {
constructor(name, pool, cost, origin) {
this.name = name; // String
this.pool = pool; // Integer
this.cost = cost; // Integer
this.origin = origin; // Origin
}
getName() {
return this.name;
}
setPool(newPool) {
this.pool = newPool;
}
getPool() {
return this.pool;
}
getCost() {
return this.cost;
}
getOrigin() {
return this.origin;
}
}
module.exports = Champion;
</code></pre>
<p>The code is working, but I think there's a good-looking approach to this ugly mess.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-27T03:51:59.190",
"Id": "455352",
"Score": "1",
"body": "Honestly, the only part of it all that I think could be improved (beyond comments in your code) is to use a switch/case instead of the if/else waterfall. Switch/case logic is a lot easier to read when you've got straightforward logic as you have here."
}
] |
[
{
"body": "<p>As was already mentioned in the comments, a <code>switch</code> statement could be used to clean up the sets of <code>if</code> statements. Another option would be to abstract the similar callback functions passed to <code>.reduce()</code>- perhaps using partially applied functions to accept parameters - e.g. the minimum values in conditions like <code>currentChamp.getCost() <= 3</code>.</p>\n<p>It seems like <code>let</code> is used for most variables. It is wise to default to using <code>const</code> to avoid accidental re-assignment. When you decide you do need to reassign a value then use <code>let</code>.</p>\n<p>The method <code>Pool::getChampProbability()</code> could use <code>this.champPool.find()</code> instead of <code>this.champPool.findIndex()</code>, since the <code>index</code> is only used to dereference an array element. This would mean <code>0</code> should be returned if <code>find()</code> returned <code>undefined</code> (instead of <code>if (poolIndex === -1) return 0;</code>).</p>\n<p>The method <code>Pool::getWholePool()</code> has a single use variable- i.e. <code>allPool</code>. That variable can be eliminated. Use of a linter would help find things like this.</p>\n<p>The <code>else</code> keywords can be eliminated in many spots following a <code>return</code> in a conditional e.g. many of the else’s in <code>Pool::getPoolBasedOnLevel()</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-29T17:25:25.477",
"Id": "244728",
"ParentId": "232903",
"Score": "1"
}
},
{
"body": "<p><code>getPoolBasedOnLevel()</code> is the oddity here. There are three arrow functions doing similar jobs. Using one function with a lookup should clean things up. Effectively, each of them is doing this:</p>\n<pre><code>const sum = list=>list.reduce((a,b)=>a+b,0)\n\nfunction poolTotal(champ_pool,min_cost,max_cost) {\n const champs_for_level = champ_pool.filter(champ=>\n champ.getCost()>=min_cost &&\n champ.getCost()<=max_cost\n );\n const pools = champs_for_level.map(\n champ=>champ.getPool()\n )\n return sum(pools);\n}\n</code></pre>\n<p>That function also implicitly determines the min and maxchampion cost for each level. It would benefit readability to state this is explcitly.</p>\n<pre><code>function costsForLevel(level) {\n if (level===2) return {min:1,max:1}\n if (level===3 || level===4) return {min:1,max:3}\n if (level===5 || level===6) return {min:1,max:4}\n return {min:0,max:Number.MAX_VALUE}\n}\n</code></pre>\n<p>With both of these functions defined, then <code>getPoolBasedOnLevel()</code> can be written as so</p>\n<pre><code>getPoolBasedOnLevel(summonerLevel) {\n const {min,max} = costForLevel(summonerLevel);\n return poolTotal(this.champPool,min,max);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-13T04:02:05.817",
"Id": "245391",
"ParentId": "232903",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T18:43:27.263",
"Id": "232903",
"Score": "9",
"Tags": [
"javascript",
"node.js",
"ecmascript-6",
"statistics",
"electron"
],
"Title": "Return probability (Javascript)"
}
|
232903
|
<p>This is a simple Java application, which adds songs to a playlist, removes songs from playlist based on indexes. A database is not used in this. I am creating dummy data through a <code>Utility</code> class. I want to get feedback on design and code, so that I can refactor it.</p>
<p><code>MusicApp</code> main class, creates a random playlist. Adds/Removes Tracks from Playlist.</p>
<pre><code>public class MusicApp {
public static void main(String[] args) {
PlaylistBusinessBean app = new PlaylistBusinessBean(new PlaylistDaoBean(new PlaylistUtils()),
new PlaylistUtils());
/* dummy tracks to add into Playlist */
List<Track> tracksToAdd = new ArrayList<Track>();
for (int i = 0; i < 20; i++) {
tracksToAdd.add(PlaylistUtils.getTrack());
}
int toIndex = 10;
String playlistUUID = UUID.randomUUID().toString();
app.addTracks(playlistUUID, tracksToAdd, toIndex);
System.out.println("Tracks added to playlist: " + playlistUUID);
System.out.println("Fetching playlist uuid: " + playlistUUID);
Playlist list = app.getPlaylist(playlistUUID);
System.out.println("No. of tracks: " + list.getNrOfTracks());
System.out.println("Removing songs from playlist:...");
List<Integer> indexes = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);
app.removeTracks(playlistUUID, indexes);
System.out.println("Playlist updated...");
System.out.println("No. of tracks after removing: " + list.getNrOfTracks());
}
}
</code></pre>
<p><code>PlaylistBusinessBean</code> is a service class, provides implementation to add/remove tracks from Playlist.</p>
<pre><code>public class PlaylistBusinessBean {
private PlaylistDaoBean playlistDaoBean;
private PlaylistUtils playlistUtils;
@Inject
public PlaylistBusinessBean(PlaylistDaoBean playlistDaoBean, PlaylistUtils playlistUtils) {
this.playlistDaoBean = playlistDaoBean;
this.playlistUtils = playlistUtils;
}
/**
* Add tracks to the index
*
* @param uuid
* @param tracksToAdd
* @param toIndex
* @return
* @throws PlaylistException
*/
public List<PlaylistTrack> addTracks(String uuid, List<Track> tracksToAdd, int toIndex) throws PlaylistException {
if (StringUtils.isNotBlank(uuid) && CollectionUtils.isNotEmpty(tracksToAdd)) {
try {
Playlist playList = playlistDaoBean.getPlaylistByUUID(uuid);
if (playList != null) {
// We do not allow > 500 tracks in new playlists
if (playList.getNrOfTracks() + tracksToAdd.size() > 500) {
throw new PlaylistException("Playlist cannot have more than " + 500 + " tracks");
}
// The index is out of bounds, put it in the end of the list.
int size = playList.getPlayListTracks() == null ? 0 : playList.getPlayListTracks().size();
if (toIndex > size || toIndex == -1) {
toIndex = size;
}
if (!(playlistUtils.validateIndexes(toIndex, playList.getNrOfTracks()))) {
return Collections.EMPTY_LIST;
}
List<PlaylistTrack> original;
Set<PlaylistTrack> originalSet = playList.getPlayListTracks();
if (originalSet == null || originalSet.size() == 0) {
original = new ArrayList<PlaylistTrack>();
} else {
original = new ArrayList<PlaylistTrack>(originalSet);
Collections.sort(original);
}
List<PlaylistTrack> added = new ArrayList<PlaylistTrack>(tracksToAdd.size());
for (Track track : tracksToAdd) {
PlaylistTrack playlistTrack = new PlaylistTrack();
playlistTrack.setId(track.getId());
playlistTrack.setTrackPlaylist(playList);
playlistTrack.setIndex(toIndex + 1);
playlistTrack.setDateAdded(new Date());
playlistTrack.setTrackId(track.getId());
playlistTrack.setTrack(track);
playList.setDuration(playlistUtils.addTrackDurationToPlaylist(playList, track));
original.add(toIndex, playlistTrack);
added.add(playlistTrack);
toIndex++;
}
setPlaylistTracks(playList, original);
playlistDaoBean.savePlaylistByUUID(uuid, playList);
return added;
} else {
throw new PlaylistException("Playlist not found error");
}
} catch (Exception e) {
e.printStackTrace();
throw new PlaylistException("Generic error");
}
} else {
throw new PlaylistException("Bad input data error");
}
}
/**
* Remove the tracks from the playlist located at the sent indexes
*
* @param uuid
* @param indexes
* @return
* @throws PlaylistException
*/
public List<PlaylistTrack> removeTracks(String uuid, List<Integer> indexes) throws PlaylistException {
// TODO
if (StringUtils.isNotBlank(uuid) && CollectionUtils.isNotEmpty(indexes)) {
try {
Playlist playList = playlistDaoBean.getPlaylistByUUID(uuid);
if (playList != null) {
List<PlaylistTrack> original;
Set<PlaylistTrack> originalSet = playList.getPlayListTracks();
if (originalSet == null || originalSet.size() == 0) {
original = new ArrayList<PlaylistTrack>();
} else {
original = new ArrayList<PlaylistTrack>(originalSet);
Collections.sort(original);
}
List<PlaylistTrack> removed = new ArrayList<PlaylistTrack>(indexes.size());
for (int index : indexes) {
if (index >= 0 && index <= original.size()) {
original.removeIf(track -> index == track.getIndex());
}
}
setPlaylistTracks(playList, original);
playlistDaoBean.savePlaylistByUUID(uuid, playList);
return removed;
}
} catch (Exception e) {
e.printStackTrace();
throw new PlaylistException("Generic error");
}
}
return Collections.EMPTY_LIST;
}
/**
*
* @param uuid
* @return
*/
public Playlist getPlaylist(String uuid) {
if (StringUtils.isEmpty(uuid)) {
throw new PlaylistException("Bad UUID input");
} else {
Optional<Playlist> playlist = Optional.ofNullable(playlistDaoBean.getPlaylistByUUID(uuid));
if (playlist.isPresent()) {
return playlist.get();
} else {
throw new PlaylistException("Playlist not found");
}
}
}
/**
* This method set new index in updated {@link List} of {@link PlaylistTrack}
* and also add {@link List} of {@link PlaylistTrack} into original
* {@link Playlist}
*
* @param playList
* @param original
*/
private void setPlaylistTracks(Playlist playList, List<PlaylistTrack> original) {
int i = 0;
for (PlaylistTrack track : original) {
track.setIndex(i++);
}
playList.getPlayListTracks().clear();
playList.getPlayListTracks().addAll(original);
playList.setNrOfTracks(original.size());
}
}
</code></pre>
<p><code>PlaylistDaoService</code> defines <code>DAO</code> layer methods</p>
<pre><code>public interface PlaylistDaoService {
public void savePlaylistByUUID(String uuid, Playlist newPlaylist);
public Playlist getPlaylistByUUID(String uuid);
}
</code></pre>
<p><code>PlaylistDaoBean</code> provides implementation to <code>DAO</code> layer methods.</p>
<pre><code>/**
* This class provides implementation to {@link PlaylistDaoService} methods
*
* @author root
*
*/
public class PlaylistDaoBean implements PlaylistDaoService {
private final Map<String, Playlist> playlists = new HashMap<String, Playlist>();
private PlaylistUtils playlistUtils;
@Inject
public PlaylistDaoBean(PlaylistUtils playlistUtils) {
this.playlistUtils = playlistUtils;
}
@Override
public Playlist getPlaylistByUUID(String uuid) {
return Optional.ofNullable(playlists.get(uuid)).orElse(playlistUtils.createPlaylist(uuid));
}
@Override
public void savePlaylistByUUID(String uuid, Playlist newPlaylist) {
playlists.put(uuid, newPlaylist);
}
}
</code></pre>
<p><code>PlaylistUtils</code> contains utility methods to support playlist operations</p>
<pre><code>/**
*
* This utility class creates dummy {@link Track}, add them to
* {@link PlaylistTrack} and return the fake {@link Playlist}. And, also
* provides utility methods for validation and other tasks
*
* @author root
*
*/
public class PlaylistUtils {
private static ArrayList<Integer> numberList = new ArrayList<Integer>();
private static int nrOfTracks = 1;
public Playlist createPlaylist(String uuid) {
Playlist trackPlayList = new Playlist();
trackPlayList.setDeleted(false);
trackPlayList.setDuration((float) (60 * 60 * 2));
trackPlayList.setId(49834);
trackPlayList.setLastUpdated(new Date());
trackPlayList.setNrOfTracks(nrOfTracks);
trackPlayList.setPlayListName("Collection of great songs");
trackPlayList.setPlayListTracks(getPlaylistTracks());
trackPlayList.setUuid(uuid);
return trackPlayList;
}
private static Set<PlaylistTrack> getPlaylistTracks() {
Set<PlaylistTrack> playListTracks = new HashSet<PlaylistTrack>();
for (int i = 0; i < nrOfTracks; i++) {
PlaylistTrack playListTrack = new PlaylistTrack();
playListTrack.setDateAdded(new Date());
playListTrack.setId(i + 1);
playListTrack.setIndex(i);
playListTrack.setTrack(getTrack());
playListTrack.setTrackId(playListTrack.getTrack().getId());
playListTracks.add(playListTrack);
}
return playListTracks;
}
public static Track getTrack() {
Track track = new Track();
Random randomGenerator = new Random();
while (track.getId() == 0) {
int num = randomGenerator.nextInt(500);
if (!numberList.contains(num)) {
numberList.add(num);
track.setId(num);
}
}
track.setTitle("Track no: " + track.getId());
track.setArtistId(randomGenerator.nextInt(10000));
track.setDuration(60 * 3);
return track;
}
public boolean validateIndexes(int toIndex, int length) {
return toIndex >= 0 && toIndex <= length;
}
public float addTrackDurationToPlaylist(Playlist playList, Track track) {
return (track != null ? track.getDuration() : 0)
+ (playList != null && playList.getDuration() != null ? playList.getDuration() : 0);
}
}
</code></pre>
<p><code>PlaylistException</code> exception class</p>
<pre><code>public class PlaylistException extends RuntimeException {
private static final long serialVersionUID = 759495431208011733L;
public PlaylistException(String s) {
super(s);
}
}
</code></pre>
<p><code>Playlist</code> POJO</p>
<pre><code>public class Playlist {
private Integer id;
private String playListName;
private Set<PlaylistTrack> playListTracks = new HashSet<PlaylistTrack>();
private Date registeredDate;
private Date lastUpdated;
private String uuid;
private int nrOfTracks;
private boolean deleted;
private Float duration;
public Playlist() {
this.uuid = UUID.randomUUID().toString();
Date d = new Date();
this.registeredDate = d;
this.lastUpdated = d;
this.playListTracks = new HashSet<PlaylistTrack>();
}
...getter setter...
}
</code></pre>
<p><code>PlaylistTrack</code> POJO</p>
<pre><code>public class PlaylistTrack implements Serializable, Comparable<PlaylistTrack> {
private static final long serialVersionUID = 5464240796158432162L;
private Integer id;
private Playlist playlist;
private int index;
private Date dateAdded;
private int trackId;
private Track track;
public PlaylistTrack() {
dateAdded = new Date();
}
...getter setter...
}
</code></pre>
<p><code>Track</code> POJO</p>
<pre><code>public class Track {
private String title;
private float duration;
private int artistId;
private int id;
public Track() {
}
...getter setter...
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>This is a partial review, since I went over only some of the classes/methods </p>\n\n<h2><code>PlaylistTrack</code></h2>\n\n<p>there are several problems with this class:</p>\n\n<ol>\n<li><p><strong>Copy of properties</strong><br>\nif the class already holds a reference to <code>Track</code>, why does it hold a copy of the track's id in a separate property? it requires you to maintain that property via a separate setter. you can access the same info from the <code>track</code> instance variable. </p></li>\n<li><p><strong>dateAdded</strong><br>\nDon't use the obsolete date/time classes from <code>java.util</code>. use the newer <code>java.time</code> package. In your case, you probably want to define <code>dateAdded</code> with type <code>LocalDateTime</code> and assign it the returned value of <code>LocalDateTime.now()</code>. </p></li>\n<li><p><strong>playlist</strong><br>\nI question the necessity of this reference. It seems to me like a direct translation of DB many-to-many model to Java. However, this relation is represented differently in Java, since we have the construct of collections. usually items inside a collection <em>do not</em> maintain a reference to the POJO that holds the collection, since it is not needed: when you access a collection of <code>PlaylistTrack</code> it is through a reference to a particular <code>PLaylist</code>. If you want to know which playlists have a particular track, you would maintain a collection of playlists in the <code>Track</code> class - this is how many-to-many relation is represented in Java - two independent one-to-many relations. I also do not understand why <code>addTracks()</code> returns a list of <code>PlaylistTrack</code>. the method is a special case of setter method, and we know what is the proper return value of this type of method.</p></li>\n<li><p><strong>setters vs constructor</strong><br>\ninstances of <code>PlaylistTrack</code> class are initialized by calling multiple setter methods. this is an error prone process. what if you forgot to set a property? moreover, <code>dateAdded</code> is initialized to a default <code>now()</code> value that is not dependent on the track. Having an \"all args\" constructor forces the caller to supply values to all the properties that rely on external values. the constructor should <em>NOT</em> require a value for <code>dateAdded</code> as it can initialize this property internally. If you fell like the constructor contains too many args, or that some properties can have default values, use the <code>Builder</code> pattern to supply callers with method-chaining instance creation.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T09:19:00.983",
"Id": "232932",
"ParentId": "232906",
"Score": "3"
}
},
{
"body": "<p>Overall it looks like your code should work. Some of the things I'm going to say here are mere nitpicking. Other things should really be done differently if you're planning to write code professionally. Here's my ideas in no particular order (other than the order I thought of them while looking at your code):</p>\n\n<h1>POJO with default constructor + setter for everything</h1>\n\n<p>There's really no good reason to do this ... ever (except if a certain framework forces you to provide it this way and someone else is forcing you to use said framework, see also my last point \"bean overkill\"). </p>\n\n<p>Immutability is a nice property to have for data objects. Java objects should only be mutable if it makes sense for them to be changed. A good example is your playlist that allows adding or removing tracks. It makes sense to do so on a playlist. What doesn't make sense is changing a title or worse the ID of a track. The easiest way to fix this is to require the unchangeable fields as parameters during construction and remove the setters.</p>\n\n<pre><code>public class Track {\n\n private final String title;\n private final float duration;\n private final int artistId;\n private final int id;\n\n public Track(String title, float duration, int artistId, int id) {\n this.title = title;\n this.duration = duration;\n this.artistId = artistId\n this.id = id;\n }\n\n ... only getters here, no setters!\n}\n</code></pre>\n\n<h1>PlaylistTrack fields ???</h1>\n\n<p>Other than making this immutable similar to Track example in my previous point, this class has some questionable fields. The most obvious one is the trackId. You can remove this field entirely and modify the getter as follows to not lose the functionality:</p>\n\n<pre><code>getTrackId() {\n return track.getId();\n}\n</code></pre>\n\n<p>When would you ever get the playlist from a playlisttrack? Isn't this class meant to be used inside a playlist to hold extra information like when it was added to that list? The rest of your application should be dealing with the playlist directly and get tracks from that playlist, not the other way around. I suggest just removing this field entirely along with the getter (and setter).</p>\n\n<p>The index is another weird field. I would expect a playlist to have some list of <code>PlaylistTrack</code>s. That list inherently has an index for each of the tracks. What happens if we remove a certain track from that list? Are you going to update all the <code>PlaylistTrack</code>s after it to keep their index field up to date? That sounds like a lot of work that you're most likely going to forget with hard bugs to find later on. Remove this field as well.</p>\n\n<p>The new constructor could look like this:</p>\n\n<pre><code>public PlaylistTrack (int id, Track track) {\n this.id = id;\n this.track = track;\n this.date = now(); //notice how this isn't passed in as parameter since it's always \"now\"\n}\n</code></pre>\n\n<p>Note that your only example usage of this class has the <code>id</code> the same as <code>trackId</code> if this is always going to be the case you might as well remove this <code>id</code> entirely too.</p>\n\n<p>Do you really need to know when a track was added to a playlist? Most music apps I've used don't provide this functionality. This is a design choice for your app that I'm not going to make for you. If you think it's not really needed afterall, you might as well just remove the <code>PlaylistTrack</code> class and use <code>Track</code>s directly instead.</p>\n\n<h1>null handling</h1>\n\n<p>You have a lot of <code>if(something == null)</code> statements in your code. Most of those can be removed if you pass in a meaningful result instead of <code>null</code>. The most obvious one is when you request a list of tracks. If a playlist is empty, this should just return an empty (not null!) list instead. That way you can simplify thise piece of code:</p>\n\n<pre><code>List<PlaylistTrack> original;\nSet<PlaylistTrack> originalSet = playList.getPlayListTracks();\n\nif (originalSet == null || originalSet.size() == 0) {\n original = new ArrayList<PlaylistTrack>();\n} else {\n original = new ArrayList<PlaylistTrack>(originalSet);\n Collections.sort(original);\n}\nList<PlaylistTrack> added = new ArrayList<PlaylistTrack>(tracksToAdd.size());\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>List<PlaylistTrack> original = new ArrayList<PlaylistTrack>();\noriginal.addAll(playList.getPlayListTracks());\nCollections.sort(original);\n//note, you can sort an empty list, this doesn't matter much performance wise\n</code></pre>\n\n<h1>playList.setDuration(playlistUtils.addTrackDurationToPlaylist(playList, track));</h1>\n\n<p>This is just asking for trouble. Someone else using your playlist class is really likely to forget using this setter. A far better way to update the duration of a playlist is inside the <code>Playlist</code> class. More specifically when you add or remove a track from this playlist.</p>\n\n<pre><code>public void addTrack (PlaylistTrack track, int index) {\n hmmm ...\n</code></pre>\n\n<p>Now I noticed why your PlaylistTrack has an index field. Your playlist itself is keeping the tracks in an unordered set. This seems like an odd design choice. Any time you want to just play the tracks in order you'll have to get the tracks from the playlist, put them into a different data structure and order them. Why can't the playlist be responsible for providing some ordering of the tracks?</p>\n\n<pre><code>public class PlayList { \n ...\n private List<PlaylistTrack> tracks = new ArrayList<>();\n ...\n\n public void addTrack(PlaylistTrack track) {\n tracks.add(track);\n duration += track.getDuration();\n }\n\n /**\n * inserts the track at a given position in the playlist.\n * if the position is larger than the number of tracks currently in the playlist\n * it will be added at the back of the playlist instead.\n */\n public void addTrack(PlaylistTrack track, int position) {\n if(position > tracks.size()-1) {\n position = tracks.size()-1;\n }\n if(position < 0) {\n position = 0;\n }\n tracks.add(position, track);\n duration += track.duration();\n }\n\n public void removeTrack(int index) {\n duration -= tracks.get(index).getDuration(); //TODO handle out of bounds error?\n tracks.remove(index);\n }\n</code></pre>\n\n<h1>guard clause</h1>\n\n<p>Instead of writing </p>\n\n<pre><code>if(some precondition ) {\n big code block\n} else {\n throw error\n}\n</code></pre>\n\n<p>It's also possible to write it as follows</p>\n\n<pre><code>if ( ! precondition ) {\n throw error\n}\nbig code block\n</code></pre>\n\n<p>This form of checking preconditions first and handling the odd cases is called a \"guard clause\". It's preferable because you don't have to keep the special cases in your head while reading through the big code block. Because they're handled first and consise it's a lot less mentaly draining to read the code while looking for bugs. Another minor added advantage is that the big code block doesn't need that extra indentation. This becomes more usefull the more special cases you have to handle first.</p>\n\n<h1>runtime exceptions</h1>\n\n<p>A runtime exception should only ever be used if it no longer makes sense to keep using the application. For a music app, this could be when you can't play sounds because there's no speaker available. Or if you can't access the file system to load in the songs. In such cases the user should be notified that there is a major problem before shutting down the app.</p>\n\n<p>If on the other hand there's a minor UI bug that causes a song to be removed twice from the list, it would be really anoying if this causes the entire app to shut down. A much nicer behaviour would be to give a small popup saying you're trying to remove a track that isn't in the playlist (it's still a bug, so should be fixed) and allow the user to still continue listening to songs when he ignores that popup.</p>\n\n<p>The problem with runtime exceptions is that programmers using your classes don't know (or just forgot) to check for these exceptions. It's better to make them excplicit so the compiler will complain for you if you forget to check for those.</p>\n\n<p>Alternatively, you can try to do the next best thing instead. Like in my example earlier where adding an track to an index that is too big, would just add the track at the end of the list instead of throwing an error. It's often a good idea to add these kinds of decisions into a comment so other programmers who use your class will know what to expect without reading through the entire implementation.</p>\n\n<h1>PlaylistUtils</h1>\n\n<p>On the one hand I like specific utility classes (unlike some puritarian coders). But they should make sense. Your <code>PlaylistUtils</code> class is questionable at best.</p>\n\n<p>The index validity check should just be placed inside the <code>Playlist</code> class. This is an implementation detail of said class that might change when said implementation changes (like in my example of dealing with the too large index). </p>\n\n<p><code>addTrackDurationToPlaylist</code> should be removed (see earlier).</p>\n\n<p>What should I expect the <code>getTrack()</code> method to do? Is it fetching some random track? Is it createing a new track (should be called create instead of get)? Is it a valid track that can be used in actual production code outside of testing?</p>\n\n<p>The main issue I think is that you're using this class for testing purposes (which in itself isn't a bad thing) but <strong>also</strong> for actual checks in your production code (which makes the testing part a problem). With the production methods removed as I suggested this problem is mostly fixed, but the class should be renamed to make it obvious it's meant for testing purposes only. That way it doesn't really matter <em>too much</em> that the code inside doesn't make sense (you're creating invalid playlists!).</p>\n\n<h1>bean overkill</h1>\n\n<p>Your playlist app looks like it would mainly be used as a standalone, batteries-included application. This means you should keep it as simple as possible and follow the normal java conventions. It doesn't read like any typical parse to JSON to communicate with other applications backend kind of app. </p>\n\n<p>To me this implies that you really shouldn't be using any frameworks that require you to provide beans/POJO's that have a default constructor and setters for everything. Those are useful if you're writing a backend microservice that takes in a non-java specific format (JSON for example) and needs an easy way to parse that into java, do something with it and pass it on to the next microservice or respond with some universal parsable (again JSON?) format.</p>\n\n<p>What you want is easy to maintain code that you can extend without worrying too much about someone else using it in an unintended way. To achieve this, immutability, required fields in constructor, explicit error handling and other best java practices are your friend.</p>\n\n<p>As a final remark I'd like to point out 2 principles</p>\n\n<ul>\n<li><a href=\"https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it\" rel=\"nofollow noreferrer\">YAGNI</a> which tells you to only write code that you actually need, when you need it. Don't write code that might be useful in the future (because it rarely is). </li>\n<li><strong>nobody will reuse code they don't understand.</strong> This one is my own that i've learned from experience (and that many others have figured out as well). If there exists 20 frameworks to deal with a certain problem but they're all hard to understand/use, then the next developper that runs into said problem will design \"a better framework\" to replace those! Now there are 21 frameworks that are all hard to understand/use.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T12:14:49.627",
"Id": "232941",
"ParentId": "232906",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "232941",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T19:04:59.403",
"Id": "232906",
"Score": "3",
"Tags": [
"java",
"object-oriented",
"design-patterns",
"collections"
],
"Title": "Adding/removing songs to a playlist"
}
|
232906
|
<p>this is my code for watching IP packets. I am doing project for my self because I want to learn how this things works.</p>
<p>This is my IP Packet class:</p>
<pre><code>public class IPPacket
{
private IPHeader _ipHeader;
private TCPHeader _tcpHeader;
private UDPHeader _udpHeader;
public IPPacket(IPHeader ipHeader, TCPHeader tcpHeader, UDPHeader udpHeader)
{
_ipHeader = ipHeader;
_tcpHeader = tcpHeader;
_udpHeader = udpHeader;
}
public static IPPacket ParseData(byte[] bytes)
{
var ipHeader = new IPHeader(bytes);
UDPHeader udpHeader = null;
TCPHeader tcpHeader = null;
switch (ipHeader.Protocol)
{
case System.Net.Sockets.ProtocolType.Tcp:
tcpHeader = new TCPHeader(ipHeader.Data);
break;
case System.Net.Sockets.ProtocolType.Udp:
udpHeader = new UDPHeader(ipHeader.Data);
break;
default:
if (Debugger.IsAttached) Debugger.Break();
break;
}
return new IPPacket(ipHeader, tcpHeader, udpHeader);
}
}
</code></pre>
<p>IP Header class:</p>
<pre><code>// 0 1 2 3
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//|Version| IHL |Type of Service| Total Length |
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//| Identification | Flags | Fragment offset |
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//|Time to live | Protocol | Header checksum |
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//| Source IP address |
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//| Destination IP address |
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//| Options | Padding |
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
public class IPHeader
{
public byte Version { get; set; }
public ushort IHL { get; set; }
public byte DifferentiatedServices { get; set; }
public ushort TotalLength { get; set; }
public ushort Identification { get; set; }
public Flags Flags { get; set; }
public ushort FragmentOffset { get; set; }
public byte TimeToLive { get; set; }
public ProtocolType Protocol { get; set; }
public string HeaderChecksum { get; set; }
public IPAddress SourceIPAddress { get; set; }
public IPAddress DestinationIPAddress { get; set; }
public byte[] Data { get; set; }
public IPHeader(byte[] bytes)
{
Version = (byte)((bytes[0] >> 4) & 0x0F); //0000XXXX & 0000FFFF
IHL = (ushort)((bytes[0] & 0x0F) * 4);
DifferentiatedServices = bytes[1];
TotalLength = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(bytes, 2));
Identification = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(bytes, 4));
Flags = new Flags(bytes[6]);
FragmentOffset = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(bytes, 6) << 3);
TimeToLive = bytes[8];
Protocol = (ProtocolType)bytes[9];
HeaderChecksum = string.Format("0x{0:x2}", IPAddress.NetworkToHostOrder(BitConverter.ToInt16(bytes, 10)));
SourceIPAddress = new IPAddress(BitConverter.ToInt32(bytes, 12));
DestinationIPAddress = new IPAddress(BitConverter.ToInt32(bytes, 16));
Data = new byte[TotalLength - IHL];
Array.Copy(bytes, IHL, Data, 0, TotalLength - IHL);
}
}
public class Flags
{
public bool Reserved { get; set; }
public bool DontFragment { get; set; }
public bool MoreFragments { get; set; }
public Flags(byte flags)
{
Reserved = Convert.ToBoolean((flags >> 7) & 0x01);
DontFragment = Convert.ToBoolean((flags >> 6) & 0x01);
MoreFragments = Convert.ToBoolean((flags >> 5) & 0x01);
}
}
</code></pre>
<p>TCP Header class:</p>
<pre><code>// 0 1 2 3
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//| Source Port | Destination Port |
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//| Sequence Number |
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//| Acknowledgment Number |
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//| Data | |U|A|P|R|S|F| |
//| Offset| Reserved |R|C|S|S|Y|I| Window |
//| | |G|K|H|T|N|N| |
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//| Checksum | Urgent Pointer |
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//| Options | Padding |
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//| data |
//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
public class TCPHeader
{
public ushort SourcePort { get; set; }
public ushort DestinationPort { get; set; }
public uint SequenceNumber { get; set; }
public uint AcknowledgmentNumber { get; set; }
public byte DataOffset { get; set; }
public byte Reserved { get; set; }
public ControlBits ControlBits { get; set; }
public ushort Window { get; set; }
public string Checksum { get; set; }
public ushort UrgentPointer { get; set; }
public byte[] Data { get; set; }
public TCPHeader(byte[] bytes)
{
SourcePort = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(bytes, 0));
DestinationPort = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(bytes, 2));
SequenceNumber = (uint)IPAddress.NetworkToHostOrder(BitConverter.ToInt32(bytes, 4));
AcknowledgmentNumber = (uint)IPAddress.NetworkToHostOrder(BitConverter.ToInt32(bytes, 8));
DataOffset = (byte)((bytes[9] >> 4) & 0x0F);
Reserved = 0;
ControlBits = new ControlBits(bytes[13]);
Window = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(bytes, 14));
Checksum = string.Format("0x{0:x2}", (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(bytes, 16)));
UrgentPointer = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(bytes, 18));
Data = new byte[bytes.Length - 20];
Array.Copy(bytes, 20, Data, 0, bytes.Length - 20);
}
}
public class ControlBits
{
public bool URG { get; set; }
public bool ACK { get; set; }
public bool PSH { get; set; }
public bool RST { get; set; }
public bool SYN { get; set; }
public bool FIN { get; set; }
public ControlBits(byte controlBits)
{
URG = Convert.ToBoolean(controlBits >> 5 & 0x01);
ACK = Convert.ToBoolean(controlBits >> 4 & 0x01);
PSH = Convert.ToBoolean(controlBits >> 3 & 0x01);
RST = Convert.ToBoolean(controlBits >> 2 & 0x01);
SYN = Convert.ToBoolean(controlBits >> 1 & 0x01);
FIN = Convert.ToBoolean(controlBits & 0x01);
}
}
</code></pre>
<p>UDP Header class:</p>
<pre><code>// 0 7 8 15 16 23 24 31
//+--------+--------+--------+--------+
//| Source | Destination |
//| Port | Port |
//+--------+--------+--------+--------+
//| | |
//| Length | Checksum |
//+--------+--------+--------+--------+
//|
//| data octets...
//+---------------- ...
public class UDPHeader
{
public ushort SourcePort { get; set; }
public ushort DestinationPort { get; set; }
public ushort Length { get; set; }
public ushort Checksum { get; set; }
public byte[] Data { get; set; }
public UDPHeader(byte[] bytes)
{
SourcePort = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(bytes, 0));
DestinationPort = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(bytes, 2));
Length = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(bytes, 4));
Checksum = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(bytes, 6));
Data = new byte[Length - 8];
Array.Copy(bytes, 8, Data, 0, Length - 8);
}
}
</code></pre>
<p>Can you give some advice what seems bad code practice?
And one more thing how would be best to define TCP and UDP header inside IP packet, because one packet can have TCP header second can have UDP header.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-27T22:15:59.280",
"Id": "455479",
"Score": "0",
"body": "I have rolled back the last edit. Please see *[what you may and may not do after receiving answers](http://meta.codereview.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<p>I would rename <code>IPPacket</code> to <code>PacketParser</code>, and then create an <code>IPacketParser</code> interface that defines the parse method, but make it a regular method, not static. </p>\n\n<p>Then, I would create a <code>TcpPacketParser</code> class and a <code>UdpPacketParser</code> class, which would eliminate the need for your switch logic within the parse method, thus there would be no need to return the <code>IPPacket</code> object. It's good to reduce cyclomatic complexity.</p>\n\n<p>You'll probably want some way to access the parsed data, but I'm not sure what your use cases would be.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T21:08:31.320",
"Id": "455167",
"Score": "0",
"body": "But this parse methods from TcpPacketParser and UdpPacketParser should return TCPHeader or UDPHeader object or should be void method?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T18:32:44.473",
"Id": "232959",
"ParentId": "232914",
"Score": "2"
}
},
{
"body": "<p>I improved my code and now I made console application for tracking IP packets.\nI tracked IP packets with Wireshark and got same result.</p>\n\n<p>IPPacket class now contains IPHeader and ProtocolHeader data.\nUDPHeader and TCPHeader class inherit abstract ProtocolHeader class, I added method ParseProtocolData which return UDPHeader or TCPHeader depending on protocol type inside IP header.</p>\n\n<pre><code>public class IPPacket\n{\n\n private IPHeader ipHeader;\n private ProtocolHeader protocolHeader;\n\n public IPPacket(IPHeader ipHeader, ProtocolHeader protocolHeader)\n {\n this.ipHeader = ipHeader;\n this.protocolHeader = protocolHeader;\n }\n\n public static IPPacket ParseData(byte[] bytes)\n {\n\n var ipHeader = new IPHeader(bytes);\n var protocolHeader = ParseProtocolData(ipHeader.Data, ipHeader.Protocol);\n\n return new IPPacket(ipHeader, protocolHeader);\n }\n\n public static ProtocolHeader ParseProtocolData(byte[] bytes, ProtocolType protocolType)\n {\n switch (protocolType)\n {\n case ProtocolType.Tcp:\n return new TCPHeader(bytes);\n case ProtocolType.Udp:\n return new UDPHeader(bytes);\n default:\n return null;\n }\n }\n\n public override string ToString()\n {\n return $\"---------------------- IP Packet ---------------------- \\n\" +\n $\"{this.ipHeader.ToString()} \\n\" +\n $\"{this.protocolHeader.ToString()} \\n\" +\n $\"-------------------------------------------------------\";\n }\n\n}\n</code></pre>\n\n<p>IPheader class:</p>\n\n<pre><code>// 0 1 2 3\n// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1\n//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n//|Version| IHL |Type of Service| Total Length |\n//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n//| Identification | Flags | Fragment offset |\n//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n//|Time to live | Protocol | Header checksum | \n//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n//| Source IP address |\n//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n//| Destination IP address |\n//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n//| Options | Padding |\n//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\npublic class IPHeader\n{\n public byte Version { get; set; }\n public ushort IHL { get; set; }\n public byte DifferentiatedServices { get; set; }\n public ushort TotalLength { get; set; }\n public ushort Identification { get; set; }\n public Flags Flags { get; set; }\n public ushort FragmentOffset { get; set; }\n public byte TimeToLive { get; set; }\n public ProtocolType Protocol { get; set; }\n public string HeaderChecksum { get; set; }\n public IPAddress SourceIPAddress { get; set; }\n public IPAddress DestinationIPAddress { get; set; }\n public byte[] Data { get; set; }\n\n public IPHeader(byte[] bytes)\n {\n Version = (byte)((bytes[0] >> 4) & 0x0F); //0000XXXX & 0000FFFF\n IHL = (ushort)((bytes[0] & 0x0F) * 4);\n DifferentiatedServices = bytes[1];\n TotalLength = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(bytes, 2));\n Identification = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(bytes, 4));\n Flags = new Flags(bytes[6]);\n FragmentOffset = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(bytes, 6) << 3);\n TimeToLive = bytes[8];\n Protocol = (ProtocolType)bytes[9];\n HeaderChecksum = string.Format(\"0x{0:x2}\", IPAddress.NetworkToHostOrder(BitConverter.ToInt16(bytes, 10)));\n SourceIPAddress = new IPAddress(BitConverter.ToUInt32(bytes, 12));\n DestinationIPAddress = new IPAddress(BitConverter.ToUInt32(bytes, 16));\n Data = new byte[TotalLength - IHL];\n Array.Copy(bytes, IHL, Data, 0, TotalLength - IHL);\n }\n\n public override string ToString()\n {\n return $\"Version: {Version} \\n\" +\n $\"Header Length: {IHL} \\n\" +\n $\"Differentiated services: {DifferentiatedServices} \\n\" +\n $\"Total length: {TotalLength} \\n\" +\n $\"Identification: {string.Format(\"0x{0:x2}\", Identification)} ({Identification}) \\n\" +\n $\"Flags: {Flags} \\n\" +\n $\"Fragment offset: {FragmentOffset} \\n\" +\n $\"Time to live: {TimeToLive} \\n\" +\n $\"Protocol : {Protocol} \\n\" +\n $\"Header checksum: {HeaderChecksum} \\n\" +\n $\"Source IP address: {SourceIPAddress} \\n\" +\n $\"Destination IP address: {DestinationIPAddress}\";\n }\n}\n\npublic class Flags\n{\n public bool Reserved { get; set; }\n public bool DontFragment { get; set; }\n public bool MoreFragments { get; set; }\n\n public Flags(byte flags)\n {\n Reserved = Convert.ToBoolean((flags >> 7) & 0x01);\n DontFragment = Convert.ToBoolean((flags >> 6) & 0x01);\n MoreFragments = Convert.ToBoolean((flags >> 5) & 0x01);\n }\n\n public override string ToString()\n {\n return $\"\\n\" +\n $\" -- Reserved: {(Reserved ? \"Set\" : \"Not set\")} \\n\" +\n $\" -- Dont fragment: {(DontFragment ? \"Set\" : \"Not set\")} \\n\" +\n $\" -- More fragments: {(MoreFragments ? \"Set\" : \"Not set\")}\";\n\n }\n}\n</code></pre>\n\n<p>I made abstract class ProtocolHeader because IP packet can contain TCP or UDP segment depends on Protocol Type inside IPheader.</p>\n\n<pre><code>public abstract class ProtocolHeader\n{\n public uint SourcePort { get; set; }\n public uint DestinationPort { get; set; }\n}\n</code></pre>\n\n<p>TCP Header class:</p>\n\n<pre><code>// 0 1 2 3 \n// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 \n//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n//| Source Port | Destination Port |\n//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n//| Sequence Number |\n//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n//| Acknowledgment Number |\n//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n//| Data | |U|A|P|R|S|F| |\n//| Offset| Reserved |R|C|S|S|Y|I| Window |\n//| | |G|K|H|T|N|N| |\n//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n//| Checksum | Urgent Pointer |\n//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n//| Options | Padding |\n//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n//| data |\n//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\npublic class TCPHeader : ProtocolHeader\n{\n public uint SequenceNumber { get; set; }\n public uint AcknowledgmentNumber { get; set; }\n public byte DataOffset { get; set; }\n public byte Reserved { get; set; }\n public ControlBits ControlBits { get; set; }\n public ushort Window { get; set; }\n public string Checksum { get; set; }\n public ushort UrgentPointer { get; set; }\n public byte[] Data { get; set; }\n\n public TCPHeader(byte[] bytes)\n {\n SourcePort = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(bytes, 0));\n DestinationPort = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(bytes, 2));\n SequenceNumber = (uint)IPAddress.NetworkToHostOrder(BitConverter.ToInt32(bytes, 4));\n AcknowledgmentNumber = (uint)IPAddress.NetworkToHostOrder(BitConverter.ToInt32(bytes, 8));\n DataOffset = (byte)((bytes[9] >> 4) & 0x0F);\n Reserved = 0;\n ControlBits = new ControlBits(bytes[13]);\n Window = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(bytes, 14));\n Checksum = string.Format(\"0x{0:x2}\", (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(bytes, 16)));\n UrgentPointer = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(bytes, 18));\n Data = new byte[bytes.Length - 20];\n Array.Copy(bytes, 20, Data, 0, bytes.Length - 20);\n }\n\n public override string ToString()\n {\n return $\" Transmision control protocol \\n\" +\n $\" -- Source port: {SourcePort} \\n\" +\n $\" -- Destination port: {DestinationPort} \\n\" +\n $\" -- Sequence number: {SequenceNumber} \\n\" +\n $\" -- Acknowledgment number: {AcknowledgmentNumber} \\n\" +\n $\" -- Dataoffset: {DataOffset} \\n\" +\n $\" -- Reserved: {Reserved} \\n\" +\n $\" -- Control bits: {ControlBits} \\n\" +\n $\" -- Window: {Window} \\n\" +\n $\" -- Checksum: {Checksum} \\n\" +\n $\" -- Urgent pointer: {UrgentPointer}\";\n }\n}\n\npublic class ControlBits\n{\n public bool URG { get; set; }\n public bool ACK { get; set; }\n public bool PSH { get; set; }\n public bool RST { get; set; }\n public bool SYN { get; set; }\n public bool FIN { get; set; }\n\n public ControlBits(byte controlBits)\n {\n URG = Convert.ToBoolean(controlBits >> 5 & 0x01);\n ACK = Convert.ToBoolean(controlBits >> 4 & 0x01);\n PSH = Convert.ToBoolean(controlBits >> 3 & 0x01);\n RST = Convert.ToBoolean(controlBits >> 2 & 0x01);\n SYN = Convert.ToBoolean(controlBits >> 1 & 0x01);\n FIN = Convert.ToBoolean(controlBits & 0x01);\n }\n\n public override string ToString()\n {\n return $\"URG: {URG} \\n\" +\n $\"ACK: {ACK} \\n\" +\n $\"PSH: {PSH} \\n\" +\n $\"RST: {RST} \\n\" +\n $\"SYN: {SYN} \\n\" +\n $\"FIN: {FIN}\";\n }\n}\n</code></pre>\n\n<p>UDPHeader class:</p>\n\n<pre><code>// 0 7 8 15 16 23 24 31 \n//+--------+--------+--------+--------+ \n//| Source | Destination | \n//| Port | Port | \n//+--------+--------+--------+--------+ \n//| | | \n//| Length | Checksum | \n//+--------+--------+--------+--------+ \n//| \n//| data octets...\n//+---------------- ... \n\npublic class UDPHeader : ProtocolHeader\n{\n public ushort Length { get; set; }\n public ushort Checksum { get; set; }\n public byte[] Data { get; set; }\n\n public UDPHeader(byte[] bytes)\n {\n SourcePort = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(bytes, 0));\n DestinationPort = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(bytes, 2));\n Length = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(bytes, 4));\n Checksum = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(bytes, 6));\n Data = new byte[bytes.Length - 8];\n Array.Copy(bytes, 8, Data, 0, bytes.Length - 8);\n }\n\n public override string ToString()\n {\n return $\" User datagram protocol \\n\" +\n $\" -- Source port: {SourcePort} \\n\" + \n $\" -- Destination port: {DestinationPort} \\n\" +\n $\" -- Length: {Length} \\n\" +\n $\" -- Checksum: {Checksum} \\n\" +\n $\" -- Data: {ASCIIEncoding.ASCII.GetString(Data)}\";\n }\n}\n</code></pre>\n\n<p>Implementation of main method:</p>\n\n<pre><code>class Program\n{\n private static Socket socket;\n private static byte[] buffer = new byte[4096];\n static void Main(string[] args)\n {\n\n try\n {\n\n if(!NetworkInterface.GetIsNetworkAvailable())\n {\n Console.WriteLine(\"Network is not available.\");\n }\n else\n {\n var address = NetworkInterface.GetAllNetworkInterfaces()\n .AsEnumerable()\n .Where(i => (i.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 ||\n i.NetworkInterfaceType == NetworkInterfaceType.Ethernet) && \n i.OperationalStatus == OperationalStatus.Up)\n .SelectMany(i => i.GetIPProperties().UnicastAddresses)\n .Where(a => a.Address.AddressFamily == AddressFamily.InterNetwork)\n .Select(a => a.Address.ToString())\n .ToList();\n int counter = 0;\n\n if(address != null)\n {\n Console.WriteLine(\"Please choose address for tracking IP packets: (Enter address number.)\");\n }\n\n foreach (var addr in address)\n {\n Console.WriteLine($\"Number [{counter}] Addres: {addr}\");\n counter++;\n }\n\n int.TryParse(Console.ReadLine(), out counter);\n\n socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);\n\n socket.Bind(new IPEndPoint(IPAddress.Parse(address[counter]), 0));\n socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true);\n\n byte[] byTrue = new byte[4] { 1, 0, 0, 0 };\n byte[] byOut = new byte[4];\n\n socket.IOControl(IOControlCode.ReceiveAll, byTrue, byOut);\n\n socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnRecieve), null);\n\n }\n\n Console.ReadLine();\n\n }\n catch (Exception ex)\n {\n Console.WriteLine(ex.Message);\n }\n\n }\n\n public static void OnRecieve(IAsyncResult ar)\n {\n\n try\n {\n\n int recv = socket.EndReceive(ar);\n byte[] buf = new byte[recv];\n\n Array.Copy(buffer, buf, recv);\n\n IPPacket ipPacket = IPPacket.ParseData(buf);\n\n Console.WriteLine(ipPacket.ToString());\n\n socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnRecieve), null);\n\n }\n catch (Exception ex)\n {\n Console.WriteLine(ex.Message);\n }\n\n }\n}\n</code></pre>\n\n<p>Could you give me advice now after I improved my code and gave whole picture how tracking program should work?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-27T22:43:00.693",
"Id": "233090",
"ParentId": "232914",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T22:09:31.023",
"Id": "232914",
"Score": "5",
"Tags": [
"c#",
"tcp",
"udp"
],
"Title": "Network IP packet tracker"
}
|
232914
|
<p><strong>The task</strong></p>
<blockquote>
<p>Given an integer array, move all elements that are equal to 0 to the
left while maintaining the order of other elements in the array. Let's
look at the following integer array.</p>
<p>After moving all zero elements to the left, the array should look like
this. We need to maintain the order of non-zero elements.</p>
<pre><code>0 0 0 1 10 20 59 63 88
</code></pre>
</blockquote>
<p><strong>My approach</strong>, I used TDD and hoped my solution would become just as good as the sample solution.</p>
<pre><code>test('contains no element', () => {
expect(moveZeroToLeft([])).toStrictEqual(undefined);
});
test('contains only a 0 element', () => {
expect(moveZeroToLeft([0])).toStrictEqual([0]);
});
test('contains only a non 0 element', () => {
expect(moveZeroToLeft([1])).toStrictEqual([1]);
});
test('contains more than one element with a 0', () => {
expect(moveZeroToLeft([1, 0])).toStrictEqual([0, 1]);
});
test('contains more than one element without 0', () => {
expect(moveZeroToLeft([1, 3])).toStrictEqual([1, 3]);
});
test('contains more than one element with a 0 somewhere in the middle', () => {
expect(moveZeroToLeft([1, 0, 3])).toStrictEqual([0, 1, 3]);
});
test('contains random number of zeros and non-zero elements', () => {
expect(moveZeroToLeft([1, 0, 3, 0, 0, 44, 1, 0, 2])).toStrictEqual([0, 0, 0, 0, 1, 3, 44, 1, 2]);
});
</code></pre>
<p><strong>My solution</strong></p>
<pre><code>function moveZeroToLeft(arr) {
if (arr.length < 2) {
return arr;
}
if (arr.some(x => x === 0)) {
let zeroCounter = 0;
const res = arr.filter(el => {
if (el !== 0) {
return true;
}
zeroCounter++;
});
const leadingZeros = Array(zeroCounter).fill(0);
return leadingZeros.concat(res);
}
return arr;
}
</code></pre>
<p>But the <strong>sample solution</strong> is much more elegant than mine:</p>
<pre><code>let move_zeros_to_left = function(A) {
if (A.length < 1) {
return;
}
let lengthA = A.length;
let write_index = lengthA - 1;
let read_index = lengthA - 1;
while (read_index >= 0) {
if (A[read_index] != 0) {
A[write_index] = A[read_index];
write_index--;
}
read_index--;
}
while (write_index >= 0) {
A[write_index] = 0;
write_index--;
}
};
</code></pre>
<p>How could I have come to the sample solution with a TDD approach?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T08:03:51.183",
"Id": "455065",
"Score": "1",
"body": "...And you're already off to a bad start: your first test case expects the wrong result! `moveZeroToLeft([])` should result in `[]`, not `undefined`. If your test is incorrect in the first place, TDD would be a hindrance to you instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T08:15:06.803",
"Id": "455066",
"Score": "0",
"body": "Ah, just forgot to update the code in the question. My first impulse was indeed to return an empty array. But the sample solution returned undefined, therefore I changed the test case but forgot to update the question here"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T10:52:22.327",
"Id": "455082",
"Score": "0",
"body": "The code returns a new array, the task is to modify the existing array. It seems the tests and implementation are wrong."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T13:59:04.147",
"Id": "455100",
"Score": "1",
"body": "It's been said in the answers but it is worth saying on it's own: the sample solution is _awful, awful, awful_. The only lines I don't have problems with are the blank lines and most of the ones with only \"}\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-30T23:32:35.390",
"Id": "455759",
"Score": "0",
"body": "@konijn where does it say that the function should return the existing array?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-01T10:21:54.023",
"Id": "455767",
"Score": "0",
"body": "@Odalrick why exactly is the sample solution \"awful\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T08:24:36.253",
"Id": "455845",
"Score": "0",
"body": "@thadeuszlay Two glaring problems are the unnecessary shortcut in the beginning and that is is generally unreadable. It looks like C code written in JavaScript. _I_ have more problems with it (using let instead of const, semicolons and more) but my point was mostly that the OP solution is _so_ much elegant than the sample solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T17:33:28.203",
"Id": "455925",
"Score": "0",
"body": "The description (to me) clearly talks about moving the elements, not creating a new array."
}
] |
[
{
"body": "<p>TDD is not for finding <em>\"elegant\"</em> solutions, but for finding <em>working</em> solutions that cover all edge cases. Without edge cases, solutions are often too naive and in the end won't work. </p>\n\n<p>You missed some edge cases; the task states: \"order of <strong>other elements</strong> in the array\" (that are integer). How about <code>Infinity</code> and <code>-Infinity</code>? Are they numbers? :) <code>isNaN(Infinity)</code>?</p>\n\n<p>Another thing is, that beauty lies in the eye of the beholder. For me elegant code, is code, that is easy to grasp and not overly complex. Whenever a problem can be solved in such a generic way, that edge case do not need any special handling this is good code. :)</p>\n\n<p>Speaking of which - your problem is clearly about <em>transforming</em> an array - with JavaScript you have a good set of <code>Array.fns()</code> at you disposal and fat arrow functions. Thus I'd intuitively never use loops, but only array functions.</p>\n\n<p>The original problem sounds very constructed to me - I guess some stupid code interview stuff. I guess it is about thinking of how to find zeros in an array and move them around.</p>\n\n<p>However the solution is quite trivial if you are <em>thinking outside the box</em> (which you are!), that with the elements being numbers, the solution is <strong>not</strong> about <em>moving</em> around zeros (and thus maintain their reference, if it where not zeros but objects), <strong>but</strong> in <em>filtering</em> and reconstructing them.</p>\n\n<pre><code>const move_zeros_to_left = function(unsortedArray) {\n const numberOfZeros = unsortedArray.filter(item => item === 0).length;\n const nonZeroArray = unsortedArray.filter(item => item !== 0);\n return [...Array.from({length: numberOfZeros}).fill(0), ...nonZeroArray];\n}\n</code></pre>\n\n<p>Covers all the edge cases and is <em>readable</em>. Your provided sample solution is the worst of all solution, because it neglects the fact, that JavaScript has a rich set of Array functions and thus it is neither <em>readable</em> nor <em>idiomatic</em> and I'd say thus not elegant all. :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T07:00:59.163",
"Id": "455058",
"Score": "0",
"body": "Can you explain what you mean by \"How about Infinity and -Infinity? Are they numbers? :) isNaN(Infinity)?\"? That's a bit misleading to say at least. `isNaN(x) === false` does not imply x is number. Well, depends what you mean by \"being a number\". If you mean being of js data type `Number` then Inf, -Inf and NaN are Numbers. If you mean mathematical sense, then nor inf nor -inf nor nan are numbers. You wont find infinity on the real number line, nor in the complex plane. And definitely not in the set of all integers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T08:26:00.997",
"Id": "455067",
"Score": "4",
"body": "I think doing two `filter`s is not very elegant. You could compute `nonZeroArray` first and then `numberOfZeros = unsortedArray.length - nonZeroArray.length`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T08:26:49.953",
"Id": "455068",
"Score": "1",
"body": "Also, isn't `Array.from({length: numberOfZeros})` the same as `Array(numberOfZeros)`? Please correct me if there's a subtle difference"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T13:42:04.073",
"Id": "455096",
"Score": "0",
"body": "@Clashsoft Or just go `[...arr.filter(n => n === 0), ...arr.filter(n => n !== 0)]`, unless I'm missing some weird special case. If they're `=== 0`, aren't they always, well, `0`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T14:47:35.000",
"Id": "455106",
"Score": "1",
"body": "@Clashsoft Not @ChristianUlbrich, but: From a readability standpoint `Array(numberOfZeros)` is ambiguous. For example, `Array(a, b, c)` creates an array containing a, b and c, so one could expect `Array(a)` to create an array containing just `a` - which is does **unless** `a` is an integer, in which case it creates an array of the length `a` instead. So using `Array.from(...)` like this makes it more obvious what is happening. That said: In this case I myself would prefer `Array(numberOfZeros)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T09:36:48.527",
"Id": "455223",
"Score": "0",
"body": "@Clashsoft **I** like my code being _descriptive_ and I find `Array.from({length: 4})` very easy to grasp. I won't argue with you over _elegance_ feel free to submit your own _elegant_ answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T09:40:19.250",
"Id": "455224",
"Score": "0",
"body": "@slepic `isNaN(Infinity)` _evaluates_ to `false` and the `typeof Infinity` is `number` and I think it should be covered as an _edge case_. It is not about math, but about JavaScript (`0.1 * 0.2`). The original task is not precise enough and this is what I am alluding to."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T10:10:53.330",
"Id": "455228",
"Score": "0",
"body": "And isNaN(NaN) is true, And yet typeof NaN is number. The task states that input Is Array of integers. That said, Infinity or NaN in the input array means the behaviour Is undefined And as such can be anything you want. Throwing error might be appropriate..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T10:28:05.503",
"Id": "455231",
"Score": "0",
"body": "All I'm trying to say Is that you should not treat Infinity as an edge case integer but an invalid input instead. Let me prove it by saying this. For any integer `a` the following equality Is Always true `a == a`. Because Infinity does not hold this equality, it Is not an integer. It Is actualy not a number at all by the same argument."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T16:30:50.347",
"Id": "455286",
"Score": "0",
"body": "@slepic I disagree with you and that proves to me, that the original **task** is simply not precise enough. Anyway it is not the scope of the question and both solutions - _mine_ and OP's will gracefully work with `Infinity` as input and they will also work without. But what is life without Infinity, I'd say!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T17:17:02.167",
"Id": "455293",
"Score": "0",
"body": "I am not arguing at all against your code. Your code is not checking for infinity, it checks only for zeros or anything else and that fits well the definition of the task that is to accept array of integers and undefined behaviour otherwise. I argue that infinity is not an integer nor a number. You can think whatever you want, but this is true mathematical statement. I can give you another dozen proofs that confirm that. For example every integer is sum of two other nonzero integers. Infinity is not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T20:45:57.293",
"Id": "455322",
"Score": "0",
"body": "@slepic The thing is, it is not about math; it is about JavaScript: `typeof (Infinity + Infinity) === typeof (1+2)` For me `Infinity` is a `number` in JavaScript, if it is not for you - I am totally fine with that, be my guest! The test that OP wrote, were not for testing a solution for a math problem, but for a solution for a JS problem. I'd think we exchanged arguments pretty well..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T21:15:16.757",
"Id": "455325",
"Score": "0",
"body": "It is about math, since it is about integers. In what way is integer related to javascript? There are just numbers in js and they are capable of representing a superset (+nonintegers) of a subset (not all integers are representable) of all integers. By your argument, `NaN` is also a `number`. Anyway for me Infinity is of the number type in JavaScript, but nowhere it is an integer. Anyway I would like to ask you to delete (or at least modify) the paragraph which causes all this confusion. Infinity being a number (js type) is irrelevant and misleading in context of task involving integers."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T01:12:38.873",
"Id": "232919",
"ParentId": "232916",
"Score": "8"
}
},
{
"body": "<h2>Testing elegance</h2>\n<p>Testing ignores the method and only focuses on the result. If however you add testing that includes criteria that focus on what you may call the elegant parts of the solution this can help you create better solutions.</p>\n<p>Personally elegance is a fit, performant and lean, in that order.</p>\n<ul>\n<li>Fit, it <em>must</em> pass all test.</li>\n<li>Performant it must be as fast and use as little memory as possible.</li>\n<li>Lean, the code must be as compact and neat as possible.</li>\n</ul>\n<p>You can test all these and iterate to a more elegant solution. However the last point is subjective and this can be hard to test. Personally I measure lean as number of lines (including empty lines) and the number of tokens used.</p>\n<p>The last to criteria are always comparative, one solution compared to another as they have no value in isolation.</p>\n<p>The sample solution is in my book is far from elegant</p>\n<ul>\n<li>It is overly verbose, names too long, not using shorthand styles (short circuiting and decremented operators) contains redundant length check at start.</li>\n<li>Poor use of comparisons as it forces type checking for each comparison. <code>>=</code> should use <code>!== 0</code> as its quicker.</li>\n<li>Has a wasted variable. There is no need for the variable <code>lengthA</code></li>\n</ul>\n<p>One can rewrite the function as</p>\n<pre><code>function bubbleDown(arr) {\n var wIdx = arr.length, rIdx = wIdx;\n while (rIdx--) { arr[rIdx] && (arr[--wIdx] = arr[rIdx]) }\n while (wIdx--) { arr[wIdx] = 0 }\n}\n</code></pre>\n<p>Slightly faster by avoiding the type checks</p>\n<pre><code>function bubbleDown(arr) {\n var w = arr.length, r = w;\n while (r-- !== 0) { arr[r] !== 0 && (arr[--w] = arr[r]) }\n while (w-- !== 0) { arr[w] = 0 }\n}\n</code></pre>\n<p>And slower but lean. Sucks that <code>Array.fill</code> is so much slower than a while loop.</p>\n<pre><code>function bubbleDown(arr) {\n var w = arr.length, r = w;\n while (r--) { arr[r] && (arr[--w] = arr[r]) }\n arr.fill(0, 0, w);\n}\n</code></pre>\n<p>The first two are up to 10% faster (last 30% slower) and easier to read and maintain (if that was important as having passed all tests it never needs to be read or changed), and all 3 are elegant.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T07:23:18.193",
"Id": "455059",
"Score": "1",
"body": "Having performant code and having compact code are often opposed to each other. One must sort their priorities for this. Also using `&&` just for the shortcut evaluation effect is less readable then you think IMO. And btw you say `>=` is less performant then `!==` and then you use the implicit bool conversion `arr[r]` as condition, which is even worse. Looks like you advocate against yourself..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T07:29:45.520",
"Id": "455060",
"Score": "1",
"body": "Also being as fast as possible and using as little memory as possible is also often opposed to each other. You can often improve time complexity at the cost of consuming more memory. And you can often reduce memory usage at the cost of decreased speed. Again, one must sort their priorities first."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T13:04:28.350",
"Id": "455094",
"Score": "1",
"body": "Personally, I strongly disagree with „performant and lean, in that order.“ – I much rather prefer the idiom „Make it work. Make it beautiful [i.e. manitainable]. Make it fast. In that order“ ([source](https://tomharrisonjr.com/make-it-work-make-it-beautiful-make-it-fast-three-realities-df7255a8fa09)). The burden of badly maintainable code is often larger than the burden of an efficiency problem, (and those do not even matter most of the time). I do note that beauty, maintainability, and „neatness“/„leanness“ of code are not the same and very subjective, but I'd argue they're very correlated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T15:02:34.640",
"Id": "455110",
"Score": "0",
"body": "@Luke Two working (fit) products all things equal the faster product always has the advantage.Good coders write perfomant maintainable code from the get go. Look at the other answer, not only does it not work (it should sort in place) it is 20 times slower. Customers notice these things, they notice fans kicking in, batteries being drained, and time ticking by. Show them the same product 20 times faster and you have a sale, not only that they come back and tell there friends, they certainly don't give a hoot about the source."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T06:35:53.593",
"Id": "232927",
"ParentId": "232916",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "232919",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T22:41:22.940",
"Id": "232916",
"Score": "7",
"Tags": [
"javascript",
"array",
"unit-testing"
],
"Title": "Move all zeros to the left with TDD approach"
}
|
232916
|
<p>I wrote a JSON parser for C++. It is not particularly fast, efficient or elegant. I'd like to change that and primarily I'd like the code to be more elegant. How do I improve it and get rid of all the code smell?</p>
<p>Aside: I have never taken a computer science course in my life and I'm not sure how far this deviates from the theoretical model I was trying to implement .i.e a LL1 parser. Perhaps that's why it feels so hacky.</p>
<p>The header file is as follows.</p>
<pre><code>#pragma once
#include <string>
#include <vector>
#include <map>
#include <variant>
#include <algorithm>
#include <fstream>
#include <stack>
// Debugging
#include <iostream>
// Types to store JSON ouput
struct jlist;
struct jobject;
using json_value = std::variant<int, float, bool, std::string, jlist, jobject>;
struct jlist {
std::vector<json_value> vector_value;
json_value & operator [](int index) {
return vector_value[index];
}
void push_back(json_value & value) {
vector_value.push_back(value);
}
};
struct jobject {
std::map<std::string, json_value> map_value;
json_value & operator [](std::string key) {
return map_value[key];
}
void insert(json_value & key, json_value & value) {
map_value.insert( { std::get<std::string>(key), value } );
}
};
class JSONParser
{
public:
JSONParser();
~JSONParser();
void parseFile(std::string);
private:
json_value root;
std::stack<std::string> s;
std::stack<json_value> s_value;
// Lexer
bool checkDeliminator(char);
std::vector<std::string> lexer(std::ifstream &);
// FSM varaibles
enum state { int_value, float_value, bool_value, string_value, default_value, bad_state};
state current;
// FSM
void fsm(std::string);
// Parser variables
enum stack_map { list_open, list_close, object_open, object_close, colon, comma, buffer, follow};
std::map<std::string, stack_map> stack_conversion;
// Parser helper functions
template<typename T> void addElement();
template<typename T> void insert(std::string &, T (*)(const std::string &));
template<typename T> void insert();
void insert(std::string &);
void pushBuffer();
template<typename ... T> bool multiComparision(const char scope, T ... args);
bool isDigit(const char);
static int st2i(const std::string & value);
static float st2f(const std::string & value);
static bool st2b(const std::string & value);
// Parser
void parser(const std::string & cursor);
};
</code></pre>
<p>The implementation is below</p>
<pre><code>#include "JSONParser.h"
JSONParser::JSONParser() {
state current = default_value;
stack_conversion = { { "[", list_open }, { "]", list_close }, { "{", object_open }, { "}", object_close }, { ":", colon }, { ",", comma }, { "buffer", buffer } };
}
JSONParser::~JSONParser() = default;
void JSONParser::parseFile(std::string FILE) {
std::ifstream configfile(FILE);
std::vector<std::string> scan = lexer(configfile);
scan.push_back("terminate");
for (auto it = scan.begin(); it != scan.end(); ++it) {
parser(*it);
}
root = s_value.top();
s_value.pop();
}
// Lexer
bool JSONParser::checkDeliminator(char piece) {
switch (piece) {
case '[':
return true;
case ']':
return true;
case '{':
return true;
case '}':
return true;
case ':':
return true;
case ',':
return true;
default:
return false;
}
}
std::vector<std::string> JSONParser::lexer(std::ifstream & configfile) {
char piece;
std::string capture = "";
std::string conversion;
std::vector<std::string> capture_list;
while(configfile >> piece) {
if (checkDeliminator(piece)) {
conversion = piece;
if (capture != "") {
capture_list.push_back(capture);
capture_list.push_back(conversion);
capture = "";
} else {
capture_list.push_back(conversion);
}
} else {
capture += piece;
}
}
return capture_list;
}
// FSM
void JSONParser::fsm(std::string value) {
current = default_value;
char point;
auto it = value.begin();
while (it != value.end()) {
point = *it;
if (point == '"' & current == default_value) {
current = string_value;
return;
} else if (isdigit(point)) {
if (current == default_value | current == int_value) {
current = int_value;
++it;
} else if (current == float_value) {
++it;
} else {
current = bad_state;
return;
}
} else if (point == '.' & current == int_value) {
current = float_value;
++it;
} else if (point == 'f' & current == float_value) {
++it;
} else if (current == default_value) {
if (value == "true" | value == "false") {
current = bool_value;
return;
} else {
current = bad_state;
return;
}
} else {
current = bad_state;
return;
}
}
}
// Parser Helper functions
template<>
void JSONParser::addElement<jobject>() {
json_value value_read;
json_value key_read;
value_read = s_value.top();
s_value.pop();
key_read = s_value.top();
s_value.pop();
std::get<jobject>(s_value.top()).insert(key_read, value_read);
}
template<>
void JSONParser::addElement<jlist>() {
json_value value_read;
value_read = s_value.top();
s_value.pop();
std::get<jlist>(s_value.top()).push_back(value_read);
}
template<typename T>
void JSONParser::insert(std::string & value, T (*fptr)(const std::string &)) {
T T_value(fptr(value));
s_value.push(T_value);
}
template<typename T>
void JSONParser::insert() {
T T_value;
s_value.push(T_value);
}
void JSONParser::insert(std::string & value) {
value.erase(std::remove(value.begin(), value.end(), '"'), value.end());
s_value.push(value);
}
void JSONParser::pushBuffer() {
s.pop();
s.push("buffer");
}
template<typename ... T>
bool JSONParser::multiComparision(const char scope, T ... args) {
return (scope == (args || ...));
}
bool JSONParser::isDigit(const char c) {
return multiComparision<char>(c, '1', '2', '3', '4', '5', '6', '7', '8', '9', '0');
}
int JSONParser::st2i(const std::string & value) {
return stoi(value);
}
float JSONParser::st2f(const std::string & value) {
return stof(value);
}
bool JSONParser::st2b(const std::string & value) {
if (value == "true") {
return true;
} else {
return false;
}
}
// Parser
void JSONParser::parser(const std::string & cursor) {
if(s.empty()) {
s.push(cursor);
} else {
stack_map stack_value;
std::string value = s.top();
if (stack_conversion.find(value) != stack_conversion.end()) {
stack_value = stack_conversion[s.top()];
} else {
stack_value = follow;
}
switch (stack_value) {
case buffer:
s.pop();
break;
case list_open:
insert<jlist>();
if (cursor == "]") {
pushBuffer();
return;
}
break;
case list_close:
addElement<jlist>();
s.pop();
s.pop();
break;
case object_open:
insert<jobject>();
if (cursor == "}") {
pushBuffer();
return;
}
break;
case object_close:
addElement<jobject>();
s.pop();
s.pop();
break;
case colon:
s.pop();
break;
case comma:
s.pop();
if (s.top() == "{") {
addElement<jobject>();
} else {
addElement<jlist>();
}
break;
default:
s.pop();
fsm(value);
switch (current) {
case string_value:
insert(value);
break;
case int_value:
insert<int>(value, st2i);
break;
case float_value:
insert<float>(value, st2f);
break;
case bool_value:
insert<bool>(value, st2b);
break;
default:
std::cout << "Bad state\n";
}
}
s.push(cursor);
}
}
</code></pre>
<p>The idea was to have the <code>lexer</code> break at each deliminator and place all the generated tokens into a vector. This vector called <code>scan</code> could then be looped through. At each iteration of this loop, <code>parser</code> would be run. In general this reads the top of the stack <code>s</code> and determines whether a bracket/brace is opening or closing or a terminal value has been reached. If a bracket/brace is opening, a new <code>jobject</code> or <code>jlist</code> is generated and placed onto a new stack <code>s_value</code>, if a terminal value is reached <code>fsm</code> (finite state machine) runs and determines the type of value and places it on top of <code>s_value</code>, should a comma or closing bracket be reached the appropriate values are moved off the stack and the elements from <code>s_value</code> are inserted into their appropriate containers.</p>
<p>The biggest meatball in this spaghetti is how elements in the JSON tree are called.</p>
<pre><code>std::cout << std::get<bool>(std::get<jobject>(std::get<jobject>(std::get<jlist>(root)[6])["input"])["bool"]);
</code></pre>
<p>The nested <code>std::get</code> calls seem just plain wrong and I'm not sure if they can be incorporated into the <code>operator []</code>.</p>
<p>For completeness this is the JSON file parsed, so the above call would output 1.</p>
<pre><code>[
{
"libraries":[
"terminal",
"binary"
]
,
"functions":[
"terminal-basic",
"binary-basic"
]
}
,
{
"name":"addition",
"type":"binary-basic",
"function":"add_float",
"input":{
"float" : 2.0f
},
"output":"float",
"max-number":2
}
,
{
"name":"exponent",
"type":"binary-basic",
"function":"exponent_float",
"input":{
"float":2.0f
},
"output":"float",
"max-number":2
}
,
{
"name":"exponent",
"type":"binary-basic",
"function":"exponent_float",
"input":{
"float":2.0f,
"int":1
},
"output":"float",
"max-number":1
}
,
{
"name":"constant_1",
"type":"terminal-basic",
"function":"non_random_constant",
"value":0.5f,
"input":{ },
"output":"float",
"max-number":3
}
,
{
"name":"constant_2",
"type":"terminal-basic",
"function":"non_random_constant",
"value":2.0f,
"input":{ },
"output":"float",
"max-number":3
}
,
{
"name":"constant_3",
"type":"terminal-basic",
"function":"non_random_constant",
"value":true,
"input":{
"bool":true
},
"output":"bool",
"max-number":1
}
]
</code></pre>
<p>How can I improve on what I have?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T23:04:30.307",
"Id": "455046",
"Score": "0",
"body": "You might want to look into a lexical analiser generated such as flex. https://en.wikipedia.org/wiki/Flex_(lexical_analyser_generator)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T23:15:10.550",
"Id": "455047",
"Score": "0",
"body": "@pacmaninbw I'll check it out but I'd really like to try do this by hand."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T16:18:05.950",
"Id": "455123",
"Score": "0",
"body": "Just FYI, after an answer has been added, there really should be no edits to the question. Since the answer didn't cover that portion of the code I won't roll back the edit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T16:33:28.030",
"Id": "455129",
"Score": "0",
"body": "OK it has been rolled back."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-26T11:43:30.373",
"Id": "455236",
"Score": "0",
"body": "Since no one mentioned it: Don't declare and define a destructor if it is empty. `= default;` is the right approach, but only if it appears in the class declaration. If it is in a separate file there is no difference to defining it with `{}`, which one shouldn't do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-29T22:34:24.643",
"Id": "455708",
"Score": "0",
"body": "See: [Yet another C++ JSON parser](https://codereview.stackexchange.com/q/7536/507)"
}
] |
[
{
"body": "<h2>Overview</h2>\n<p>My main issue is that you convert the whole stream into tokens first. Then you parse the tokens. This can get very expensive. Normally you would parse (and push) enough tokens to understand the next part to interpret. Then pop the bit you can to convert the next part.</p>\n<p>I dislike the way you have two different types of token state:</p>\n<pre><code> stack_conversion = { { "[", list_open }, { "]", list_close }, { "{", object_open }, { "}", object_close }, { ":", colon }, { ",", comma }, { "buffer", buffer } };\n\n ....\n enum state { int_value, float_value, bool_value, string_value, default_value, bad_state};\n</code></pre>\n<p>I would have a single list of all tokens (there is not that many in JSON).</p>\n<pre><code> {, }, [, ], :, ',', null, true, false, number(int), number(float), string\n</code></pre>\n<hr />\n<p>Probably a better way to write this is with lex and yacc (or really there more modern equivalents) flex and bison. A lot of research has gone into these tools to achieve exactly this and you can specify a json parser in about 20 lines of code.</p>\n<hr />\n<p>This does not do what you think.</p>\n<pre><code>template<typename ... T>\nbool JSONParser::multiComparision(const char scope, T ... args) {\n return (scope == (args || ...));\n}\n</code></pre>\n<p>This expands</p>\n<pre><code>JSONParser::multiComparision('a', '1', '2', '3');\n\n=>\n return ('a' == ('1' || '2' || '3'));\n</code></pre>\n<p>I don't think that is what you want.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T15:02:12.087",
"Id": "232949",
"ParentId": "232917",
"Score": "4"
}
},
{
"body": "<p>For testing purposes I created a <code>main()</code>. I used Visual Studio 2019 for the testing, and used C++17. Note that the posted code did not compile in C++11.</p>\n<pre><code>#include <iostream>\n#include <string>\n#include <cstdlib>\n#include "JSONParser.h"\n\nint main(int argc, char* argv[])\n{\n std::string jsonFile;\n\n if (argc > 1)\n {\n jsonFile = argv[1];\n }\n else\n {\n std::cout << "Please enter a JSON file name." << std::endl;\n std::cin >> jsonFile;\n }\n\n JSONParser jsonParser;\n try\n {\n jsonParser.parseFile(jsonFile);\n }\n catch (std::runtime_error ex)\n {\n std::cerr << ex.what() << std::endl;\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n}\n</code></pre>\n<p>I discovered several possible issues during testing, some are not listed here because I ran out of time to debug.</p>\n<h2>Error Checking</h2>\n<p>There is no test for if the input file containing the JSON was found or not, this can cause the program to terminate abnormally. Since the user has to indicate what file to open somewhere, there needs to be tests to see if the file can be opened and if the file can be read from. When there is no input file the function <code>std::vector<std::string> JSONParser::lexer(std::string fileName)</code> returns an empty list of strings that causes the program to terminate in the processing of the empty list rather than in the input itself.</p>\n<p>One possible alternative implementation of <code>lexor</code> is :</p>\n<pre><code>std::vector<std::string> JSONParser::lexer(std::string fileName) {\n char piece;\n std::string capture = "";\n std::string conversion;\n std::vector<std::string> capture_list;\n\n std::ifstream configfile(fileName);\n\n piece = configfile.get();\n if (configfile.bad() || configfile.fail())\n {\n std::string emsg("Can't read json from file: ");\n emsg += fileName;\n throw std::runtime_error(emsg);\n }\n\n while (configfile.good()) {\n if (checkDeliminator(piece)) {\n conversion = piece;\n if (capture != "") {\n capture_list.push_back(capture);\n capture_list.push_back(conversion);\n capture = "";\n }\n else {\n capture_list.push_back(conversion);\n }\n }\n else {\n capture += piece;\n }\n piece = configfile.get();\n }\n\n configfile.close();\n\n return capture_list;\n}\n</code></pre>\n<p><em>Note the change of the input for <code>lexor</code>: The ifstream configfile is only used within the function <code>lexor</code> so it is better to instantiate the configfile variable within the body of <code>lexor</code>. This also permits better error messages by passing the file name.</em></p>\n<h2>Possible Syntax Errors or Typos</h2>\n<p>There are several if statements in <code>void JSONParser::fsm(std::string value)</code> that may not return the proper results, instead of using the <code>logical</code> operators <code>&&</code> and <code>||</code> the bit wise operators <code>|</code> and <code>&</code> were used. This may cause a program using the parser to fail when it should pass, or pass when it should fail. It should also be noted that the function name <code>fsm</code> is not clear to anyone that needs to maintain the code.</p>\n<h2>Algorithm</h2>\n<p>Fast lexical analyzers (such as those generated by <a href=\"https://en.wikipedia.org/wiki/Lex_(software)\" rel=\"nofollow noreferrer\">lex</a> or <a href=\"https://en.wikipedia.org/wiki/Flex_(lexical_analyser_generator)\" rel=\"nofollow noreferrer\">flex</a>) are generally implemented as state machines using tables. Parsers generally accept a single token at a time from the lexical analyzer. Parser generators such as <a href=\"https://en.wikipedia.org/wiki/Yacc\" rel=\"nofollow noreferrer\">YACC</a> or <a href=\"https://en.wikipedia.org/wiki/GNU_Bison\" rel=\"nofollow noreferrer\">Bison</a> generate push down automata which as state machines using tables coupled with a stack. To improve performance it might be better to implement the lexer and the parser this way.</p>\n<p>If you want to experiment with these compiler development tools you can find <a href=\"https://github.com/westes/flex\" rel=\"nofollow noreferrer\">flex here</a> and <a href=\"https://www.gnu.org/software/bison/\" rel=\"nofollow noreferrer\">bison here</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-25T19:15:28.060",
"Id": "232966",
"ParentId": "232917",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "232949",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-24T22:50:29.093",
"Id": "232917",
"Score": "7",
"Tags": [
"c++",
"parsing",
"json"
],
"Title": "Improving a JSON parser for C++"
}
|
232917
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.