body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I have a simple binary tree that has no parent pointers.</p> <pre><code>class Node: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Tree: def __init__(self, root=None): self.root = root </code></pre> <p>I need to traverse the tree from bottom up and cannot modify the <code>Node</code> class, so I'd like to memoize the parents. I can modify the <code>Tree</code> class as such:</p> <pre><code>class Tree: def __init__(self, root=None): self.root = root self.memo = {} def memoize(self, node, parent_node): if node is None: return False self.memo[id(node)] = parent_node self.memoize(node.left, node) self.memoize(node.right, node) def get_parent(self, child): return self.memo[id(child)] </code></pre> <p>If I create a tree, memoize it, and run <code>get_parent()</code> I see what I expect:</p> <pre><code>a = Node(1) tree = Tree(a) b = Node(2) c = Node(3) a.left = b a.right = c tree.memoize(a, None) # Tree root is instantiated with no parent parent = tree.get_parent(b) print(tree.memo) &gt;&gt;&gt; {4405793712: None, 4405793856: &lt;__main__.Node instance at 0x1069b13b0&gt;, 4405793928: &lt;__main__.Node instance at 0x1069b13b0&gt;} print(parent.val) &gt;&gt;&gt; 1 </code></pre> <p>This seems to work nicely. However, I am a Python beginner, and want to know: is there a more Pythonic way to do this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T06:46:44.577", "Id": "482769", "Score": "1", "body": "Does the Tree class have methods for modifying the tree? For example, adding or deleting nodes, etc.? They would need to update `self.memo` so that is stays synched with the state of the tree." } ]
[ { "body": "<p>Nodes are usually used internally within the tree and are created inside the insert function of your tree. This is to hide the implementation for users as well as prevent any corruptions that could occur due to external mutability. This isn't Python specific, but more about data structures in general. Data is encapsulated in the structure and use specific operations (functions) for retrieval/mutations.</p>\n<p>I'm not sure what your use case is here, but I'd deter you from allowing <code>Node</code>s to be used outside of the <code>Tree</code> class (if possible).</p>\n<p>To traverse the tree bottom up, here are two methods you can try:</p>\n<ol>\n<li><p><a href=\"https://www.geeksforgeeks.org/reverse-level-order-traversal/\" rel=\"nofollow noreferrer\">Reverse level order traversal</a></p>\n</li>\n<li><p><a href=\"https://www.geeksforgeeks.org/binary-tree-array-implementation/\" rel=\"nofollow noreferrer\">implement the binary tree with a list internally</a>. Then if you wanted to traverse from the bottom up, the last item in the list would certainly be the node at the bottom of the tree and you can get its parent via a list index (you can work this out by reading the previous link).</p>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-21T07:58:16.060", "Id": "248228", "ParentId": "245791", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T05:23:38.057", "Id": "245791", "Score": "6", "Tags": [ "python", "python-3.x", "memoization" ], "Title": "Memoizing a tree's parent pointers in Python" }
245791
<p>I developed a college fee report generator application using Java with internet as referance,but now I need you guys help in making it more obvious and a sturdy application as I am a rookie to Java Swing.</p> <pre><code>import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.FileWriter; public class College extends Frame { JLabel l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, l12, l13, l14, l11, l15; JTextField tf1, tf2, tf3, tf4, tf5, tf6, tf7, tf8, tf9, tf10; JTextArea area2, area1; JRadioButton rb1, rb2, rb3, rb4, rb5, rb6, rb7; JFileChooser f1; // Default constructor to // initialize the parameters College() { l1 = new JLabel(&quot;Fee Report&quot;); l1.setBounds(550, 100, 250, 20); l2 = new JLabel( &quot;Name of the Student:&quot;); l2.setBounds(50, 150, 250, 20); tf1 = new JTextField(); tf1.setBounds(250, 150, 250, 20); l3 = new JLabel( &quot;Name of the Father:&quot;); l3.setBounds(50, 200, 250, 20); tf2 = new JTextField(); tf2.setBounds(250, 200, 250, 20); l4 = new JLabel(&quot;Roll Number:&quot;); l4.setBounds(50, 250, 250, 20); tf3 = new JTextField(); tf3.setBounds(250, 250, 250, 20); l5 = new JLabel(&quot;Email ID:&quot;); l5.setBounds(50, 300, 250, 20); tf4 = new JTextField(); tf4.setBounds(250, 300, 250, 20); l6 = new JLabel(&quot;Contact Number:&quot;); l6.setBounds(50, 350, 250, 20); tf5 = new JTextField(); tf5.setBounds(250, 350, 250, 20); l7 = new JLabel(&quot;Address:&quot;); l7.setBounds(50, 400, 250, 20); area1 = new JTextArea(); area1.setBounds(250, 400, 250, 90); l9 = new JLabel(&quot;Gender:&quot;); l9.setBounds(50, 500, 250, 20); JRadioButton r5 = new JRadioButton(&quot; Male&quot;); JRadioButton r6 = new JRadioButton(&quot; Female&quot;); r5.setBounds(250, 500, 100, 30); r6.setBounds(350, 500, 100, 30); ButtonGroup bg = new ButtonGroup(); bg.add(r5); bg.add(r6); l10 = new JLabel(&quot;Nationality:&quot;); l10.setBounds(50, 550, 250, 20); String nationality[] = { &quot;Indian&quot;,&quot;Other&quot;}; final JComboBox cb3 = new JComboBox(nationality); cb3.setBounds(250, 550, 250, 20); l11 = new JLabel( &quot;Year of passing 10th&quot;); l11.setBounds(50, 600, 250, 20); String language[] = { &quot;2017&quot;,&quot;2016&quot;, &quot;2015&quot;, &quot;2014&quot; ,&quot;2013&quot;,&quot;2012&quot;}; final JComboBox cb1 = new JComboBox(language); cb1.setBounds(250, 600, 90, 20); l12 = new JLabel( &quot;Year of passing 12th&quot;); l12.setBounds(50, 650, 250, 20); String languagess[] = { &quot;2020&quot;,&quot;2019&quot;, &quot;2018&quot;, &quot;2017&quot;,&quot;2016&quot;,&quot;2015&quot; }; l13 = new JLabel( &quot;Percentage Secured in 10th:&quot;); l13.setBounds(50, 700, 250, 20); tf7 = new JTextField(); tf7.setBounds(250, 700, 250, 20); l14 = new JLabel(&quot;Percentage Secured in 12th:&quot;); l14.setBounds(50, 750, 250, 20); tf8 = new JTextField(); tf8.setBounds(250, 750, 250, 20); ImageIcon i2 = new ImageIcon(&quot;2.png&quot;); JLabel l15 = new JLabel(&quot;&quot;, i2, JLabel.CENTER); l15.setBounds(900, 50, 600, 200); final JComboBox cb2 = new JComboBox(languagess); cb2.setBounds(250, 650, 90, 20); l8 = new JLabel( &quot;Groups Offered here are:&quot;); l8.setBounds(800, 150, 250, 20); rb1 = new JRadioButton(&quot;Engineering&quot;); rb1.setBounds(550, 150, 100, 30); rb2 = new JRadioButton(&quot;Arts&quot;); rb2.setBounds(650, 150, 100, 30); ButtonGroup bg1 = new ButtonGroup(); bg1.add(rb1); bg1.add(rb2); rb3 = new JRadioButton(&quot;Hosteller / Residential &quot;); rb3.setBounds(550, 200, 100, 30); rb4 = new JRadioButton(&quot;Day-Scholar&quot;); rb4.setBounds(650, 200, 120, 30); ButtonGroup bg2 = new ButtonGroup(); bg2.add(rb3); bg2.add(rb4); String languages[] = { &quot;CSE&quot;, &quot;ECE&quot;, &quot;EEE&quot;,&quot;IT&quot;,&quot;AERO&quot;,&quot;MCT&quot;,&quot;AUTO&quot;,&quot;PROD&quot;,&quot;TEXT&quot;,&quot;CIVIL&quot;, &quot;MECH&quot; }; final JComboBox cb = new JComboBox(languages); cb.setBounds(800, 200, 90, 20); final JLabel label = new JLabel(); label.setBounds(600, 430, 500, 30); JButton b = new JButton(&quot;Show&quot;); b.setBounds(1000, 300, 80, 30); final DefaultListModel&lt;String&gt; li1 = new DefaultListModel&lt;&gt;(); li1.addElement(&quot;CSE(2, 50, 000)&quot;); li1.addElement(&quot;ECE(2, 50, 000)&quot;); li1.addElement(&quot;EEE(2, 50, 000)&quot;); li1.addElement(&quot;IT(2, 50, 000)&quot;); li1.addElement(&quot;AERO(2, 50, 000)&quot;); li1.addElement(&quot;MCT(3, 50, 000)&quot;); li1.addElement(&quot;AUTO(3, 50, 000)&quot;); li1.addElement(&quot;CHEMICAL(3, 50, 000)&quot;); li1.addElement(&quot;BIOTECH(3, 50, 000)&quot;); li1.addElement(&quot;CIVIL(3, 50, 000)&quot;); li1.addElement(&quot;MECH(3, 50, 000)&quot;); final JList&lt;String&gt; list1 = new JList&lt;&gt;(li1); list1.setBounds(600, 300, 125, 125); DefaultListModel&lt;String&gt; li2 = new DefaultListModel&lt;&gt;(); li2.addElement( &quot;2 SHARE(1, 50, 000)&quot;); li2.addElement( &quot;3 SHARE(1, 40, 000)&quot;); li2.addElement( &quot;5 SHARE(1, 20, 000)&quot;); li2.addElement( &quot;8 SHARE(1, 10, 000)&quot;); li2.addElement( &quot;BUS(40, 000)&quot;); li2.addElement(&quot;SELF(0)&quot;); final JList&lt;String&gt; list2 = new JList&lt;&gt;(li2); list2.setBounds( 800, 300, 125, 125); JButton Receipt = new JButton(&quot;Generate Receipt&quot;); Receipt.setBounds(600, 490, 150, 30); JButton b2 = new JButton(&quot;Reset&quot;); b2.setBounds(750, 490, 150, 30); JButton Print = new JButton(&quot;Print&quot;); Print.setBounds(900, 490, 150, 30); area2 = new JTextArea(); area2.setBounds(600, 540, 450, 240); add(l1); add(l2); add(l3); add(l4); add(l5); add(l6); add(l7); add(l8); add(l9); add(l10); add(l11); add(l12); add(l13); add(l14); add(tf1); add(tf2); add(tf3); add(tf4); add(tf5); add(tf7); add(tf8); add(area1); add(area2); add(l15); add(rb1); add(rb2); add(rb3); add(rb4); add(r5); add(r6); add(cb); add(cb3); add(cb1); add(cb2); add(list1); add(list2); add(b); add(label); add(Receipt); add(b2); add(Print); b.addActionListener(new ActionListener() { // Method to display the data // entered in the text fields public void actionPerformed(ActionEvent e) { String data = &quot;&quot;; if (list1.getSelectedIndex() != -1) { data = &quot;You had selected the Group:&quot; + list1.getSelectedValue(); label.setText(data); } if (list2.getSelectedIndex() != -1) { data += &quot; and Hostel with the &quot; + &quot;facility of: &quot;; for (Object frame : list2.getSelectedValues()) { data += frame + &quot; &quot;; } } label.setText(data); } }); // Reset the text fields b2.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e) { area2.setText(&quot;&quot;); area1.setText(&quot; &quot;); tf1.setText(&quot;&quot;); tf2.setText(&quot;&quot;); tf3.setText(&quot;&quot;); tf4.setText(&quot;&quot;); tf5.setText(&quot;&quot;); tf6.setText(&quot; &quot;); } }); Print.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent e) { try { area2.print(); } catch (java.awt.print .PrinterException a) { System.err.format( &quot;NoPrinter Found&quot;, a.getMessage()); } } }); Receipt.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { area2.setText( &quot;--------------------&quot; + &quot;-----------XYZ EDUCATIONAL INSTITUTIONS----&quot; + &quot;--------------------&quot; + &quot;----------&quot; + &quot;---------\n&quot;); area2.setText(area2.getText() + &quot;Student Name: &quot; + tf1.getText() + &quot;\n&quot;); area2.setText(area2.getText() + &quot;Father's Name: &quot; + tf2.getText() + &quot;\n&quot;); area2.setText(area2.getText() + &quot;Register No : &quot; + tf3.getText() + &quot;\n&quot;); area2.setText(area2.getText() + &quot;Email ID: &quot; + tf4.getText() + &quot;\n&quot;); area2.setText(area2.getText() + &quot;Contact Number: &quot; + tf5.getText() + &quot;\n&quot;); area2.setText(area2.getText() + &quot;Department Chosen : &quot; + cb.getSelectedItem() .toString() + &quot;\n&quot;); if (rb1.isSelected()) { area2.setText(area2.getText() + &quot;Interested to join in: &quot; + &quot; Engineering &quot; + &quot;and Technology\n&quot;); } if (rb2.isSelected()) { area2.setText(area2.getText() + &quot;Interested to join in: &quot; + &quot;Arts and Sciences\n&quot;); } if (rb3.isSelected()) { area2.setText(area2.getText() + &quot;Wants to be a &quot; + &quot;Hosteller \n&quot;); } if (rb4.isSelected()) { area2.setText(area2.getText() + &quot;Wants to be a &quot; + &quot;Day Scholar \n&quot;); } area2.setText(area2.getText() + &quot;Had chosen: &quot; + list1.getSelectedValue() .toString() + &quot;\n&quot;); area2.setText(area2.getText() + &quot;Had chosen: &quot; + list2.getSelectedValue() .toString() + &quot;\n&quot;); int index2 = list2.getSelectedIndex(); area2.setText(area2.getText()+&quot; &quot;+&quot; Total amount to be paid &quot;+&quot; will be informed to you using e-mail/post\n &quot;); if (e.getSource() == Receipt) { try { FileWriter fw = new FileWriter( &quot;java.txt&quot;, true); fw.write(area2.getText()); fw.close(); } catch (Exception ae) { System.out.println(ae); } } JOptionPane.showMessageDialog( area2, &quot;Data stored in Server Successfully !&quot;); }; }); addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent we) { System.exit(0); } }); setSize(800, 800); setLayout(null); setVisible(true); setBackground(Color.lightGray); } public static void main(String[] args) { new College(); } } </code></pre>
[]
[ { "body": "<h2>Absolute positioning</h2>\n<p>This:</p>\n<pre><code> l1.setBounds(550, 100, 250, 20);\n</code></pre>\n<p>and lines like it are non-ideal. Absolute positioning will fail to scale the controls and their positions according to different window sizes. Re-think your approach after <a href=\"https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html\" rel=\"noreferrer\">reading about layouts</a>. Instead of setting bounds, you should specify layouts and border widths, etc.</p>\n<h2>Members</h2>\n<p>There is no reason to store these:</p>\n<pre><code>JLabel l1, l2, l3, l4,\n l5, l6, l7, l8,\n l9, l10, l12, l13,\n l14, l11, l15;\n</code></pre>\n<p>as members on the class. They should just be declared at the function level. When they go out of scope they will not disappear; the <code>Frame</code> will keep a reference to them but you do not have to.</p>\n<h2>Variable names</h2>\n<p>Particularly for important variables like <code>f1</code> - but probably all of the others, too - you're going to want to give that a more meaningful name, such as <code>fileChooser</code>.</p>\n<h2>Grouped <code>add</code></h2>\n<p>Rather than issuing your <code>add</code>s all in one lump, I think it would be more legible to rearrange these such that they occur directly after the declaration of their respective control, i.e.</p>\n<pre><code> l1 = new JLabel(&quot;Fee Report&quot;);\n l1.setBounds(550, 100, 250, 20);\n add(l1);\n</code></pre>\n<h2>Action listeners</h2>\n<p>Given the length of your action listener methods, you should move the body of those methods to methods on your class rather than on the anonymous <code>ActionListener</code> object you make.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T14:10:41.253", "Id": "245810", "ParentId": "245796", "Score": "5" } }, { "body": "<p>In addition to the valuable technical hints given by @Reinderien, I'd like to comment on your code structure.</p>\n<p>You are doing everything within one class (even inside the constructor of that class):</p>\n<ul>\n<li>Creating the user interface (<code>new JLabel()</code>, <code>setBounds()</code>, <code>add()</code> and so on)</li>\n<li>Getting user interactions (<code>addActionListener()</code>)</li>\n<li>Doing the business logic (e.g. generating various reports)</li>\n<li>Presenting results (<code>print()</code>, <code>setText()</code> etc.)</li>\n</ul>\n<p>I'd typically expect an application like yours to be split into at least two major parts:</p>\n<ul>\n<li><p>The business logic, consisting of classes corresponding to the real-world concepts you're working with, e.g. <code>Student</code>, <code>Group</code>, <code>Course</code>, <code>Year</code>. There shouldn't be any user interface elements in there (nothing coming from <code>javax.swing</code>, <code>java.awt</code>, <code>System.out</code> etc.). There you should find the fields that describe a student, a group etc. as well as the actions necessary (e.g. in a class <code>Group</code> a method like <code>add(Student student)</code>, modifying the Group's fields to now contain one more Student).</p>\n</li>\n<li><p>The user interface, consisting of everything you need to show the user the current state of the application, and to get his commands. Execute them by just calling the business logic.</p>\n</li>\n</ul>\n<p>If you organize your code that way, you gain some benefits:</p>\n<ul>\n<li>Your code is more readable. If you want to know what it means to add a student to a group, you find it in the <code>Group</code> business class. There's no need to skip over the Swing code where get JLabel contents and add text to other JLabels. The same is true for the UI classes. They just define how to interact with the user, e.g. when a user presses this or that button, you want to add a student to a group, no matter how that works internally. That's responsibility of the business logic.</li>\n<li>You gain a better re-usability. Maybe you later want to deploy your app on a server and have the users interact from their browsers. Then you can keep the business logic unchanged, &quot;just&quot; write a fresh web-based front-end, replacing or adding to the Swing user interface.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T15:08:57.580", "Id": "245817", "ParentId": "245796", "Score": "3" } } ]
{ "AcceptedAnswerId": "245810", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T06:41:21.930", "Id": "245796", "Score": "1", "Tags": [ "java", "swing", "gui" ], "Title": "College Billing System - Java" }
245796
<p>I recently <a href="https://codereview.stackexchange.com/questions/245345/a-vba-product-dictionary-with-a-collection-of-product-services/245356#245356">posted</a> some code for review, and am now looking to gather some feedback on my latest implementation with that code. Yes, I have fallen into the OOP rabbit hole (thanks <a href="https://rubberduckvba.wordpress.com/" rel="nofollow noreferrer">Mathieu Guindon</a>) and am curious if my OOP approach is on the right track.</p> <p>Some background: I am creating a Chart Workbook from scratch via data that is generated from a Bot at work. Basically I take the data from the Bot generated Workbook, store it into an Array and then use a <code>Scripting Dictionary</code> to sort out all the duplicates, this approach works great! My code below is merely just the Worksheet part of my project, and am only at the point of creating the Headers for said chart.</p> <p>Am I on the right track so far?</p> <p><strong>IChartFormatService</strong></p> <blockquote> <p>My hope was to separate this concern from my <code>ChartWorksheet</code> class. Why would I want to do that? In the future I may need to implement different styles for different reasons, based on customer / work needs. I can have a particular <code>Worksheet</code> implement a particular flavor of colors for different representations.</p> </blockquote> <pre><code>'@Interface Option Explicit Public Sub FormatProductHeaderLabel() End Sub Public Sub FormatServiceHeaderLabel() End Sub </code></pre> <p>Here is one implementation:</p> <p><strong>StandardChartWorkSheet</strong></p> <pre><code>'@PredeclaredId Option Explicit Implements IChartFormatService Implements IChart Private Const ProductHeaderFont As String = &quot;Arial&quot; Private Const ProductHeaderFontSize As Integer = 12 Private Const ProductHeaderFontColor As Long = 16777215 Private Const ServiceHeaderFont As String = &quot;Arial&quot; Private Const ServiceHeaderFontSize As Integer = 10 Private Const ServiceHeaderFontColor As Long = 0 Public Enum ChartColor InteriorProductColumnColor = 12549120 InteriorServiceColumnColor = 14277081 End Enum Private Type TChartWorksheetService HeaderColumn As Long HeaderData As Scripting.Dictionary ChartWorksheet As Worksheet End Type Private this As TChartWorksheetService Public Function Create(ByVal hData As Scripting.Dictionary, cSheet As Worksheet) As IChart With New StandardChartWorksheet Set .HeaderData = hData Set .ChartWorksheet = cSheet Set Create = .Self End With End Function Public Property Get HeaderData() As Scripting.Dictionary Set HeaderData = this.HeaderData End Property Public Property Set HeaderData(ByVal value As Scripting.Dictionary) Set this.HeaderData = value End Property Public Property Get ChartWorksheet() As Worksheet Set ChartWorksheet = this.ChartWorksheet End Property Public Property Set ChartWorksheet(ByVal value As Worksheet) Set this.ChartWorksheet = value End Property Public Property Get HeaderColumn() As Long HeaderColumn = this.HeaderColumn End Property Public Property Let HeaderColumn(ByVal value As Long) this.HeaderColumn = value End Property Public Property Get Self() As IChart Set Self = Me End Property Private Sub BuildHeaders() Application.ScreenUpdating = False Dim product As Variant For Each product In HeaderData PrintProductValues product this.HeaderColumn = this.HeaderColumn + 1 Dim service As Variant For Each service In HeaderData(product) PrintServiceValues service this.HeaderColumn = this.HeaderColumn + 1 Next Next Application.ScreenUpdating = True End Sub Private Sub PrintProductValues(ByVal product As String) With this.ChartWorksheet.Range(Cells(4, this.HeaderColumn), Cells(50, this.HeaderColumn)) .Interior.Color = InteriorProductColumnColor End With With Sheet3.Cells(4, this.HeaderColumn) .value = product IChartFormatService_FormatProductHeaderLabel End With End Sub Private Sub PrintServiceValues(ByVal service As String) With this.ChartWorksheet.Cells(4, this.HeaderColumn) .value = Mid(service, 14, 100) IChartFormatService_FormatServiceHeaderLabel End With End Sub Private Sub IChartFormatService_FormatProductHeaderLabel() With this.ChartWorksheet.Cells(4, this.HeaderColumn) .Font.Name = ProductHeaderFont .Font.Size = ProductHeaderFontSize .Font.Color = ProductHeaderFontColor .Font.Bold = True .Orientation = Excel.XlOrientation.xlUpward .Columns.AutoFit End With End Sub Private Sub IChartFormatService_FormatServiceHeaderLabel() With this.ChartWorksheet.Cells(4, this.HeaderColumn) .Interior.Color = InteriorServiceColumnColor .Font.Name = ServiceHeaderFont .Font.Size = ServiceHeaderFontSize .Font.Bold = False .Font.Color = ServiceHeaderFontColor .Orientation = Excel.XlOrientation.xlUpward .Columns.AutoFit End With End Sub Private Sub IChart_BuildChart() If Not this.HeaderData Is Nothing Then BuildHeaders Else: Exit Sub End If End Sub Private Sub Class_Initialize() this.HeaderColumn = 3 End Sub </code></pre> <p><code>StandardChartWorksheet</code> class implements another interface, <code>IChart</code> basically separating the concern of building a chart</p> <pre><code>'@Interface Option Explicit Public Sub BuildChart() End Sub </code></pre> <p>My sample procedure, housed in Module 1</p> <pre><code>Sub test() Dim chart As IChart Set chart = StandardChartWorksheet.Create(GetTMProductDictionary, Sheet3) chart.BuildChart End Sub </code></pre> <p><strong>Snippet of what's produced</strong></p> <blockquote> <p>There are 50 more columns, cropped the picture to keep it simple.</p> </blockquote> <p><a href="https://i.stack.imgur.com/dCA93.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dCA93.png" alt="enter image description here" /></a></p>
[]
[ { "body": "<h2>Naming</h2>\n<p>I would change <code>StandardChartWorkSheet</code> to <code>StandardChart</code> to avoid an ambiguity with a Chart sheet.</p>\n<p>The <code>Print</code> prefix implies printing to the debug window. <code>Add</code> makes more sense to me (e.g AddProductValues()`.</p>\n<p><code>ByVal value As Scripting.Dictionary</code> Value should be capitalized because it is a common property and the VBE changes case of variables to match the last declaration using with that name. This will prevent confusion when reading and writing code. You don't want to see <code>cell.value</code> when you are expecting <code>cell.Value</code>.</p>\n<h2>TChartWorksheetService</h2>\n<p>I prefer to use <code>this</code> instead of Matt's <code>Self()</code>. In any case, <code>this</code> implies a reference to the actual class.</p>\n<p>Mathieu Guindon likes to wrap the private fields (members) of his classes in a Type and name the Type <code>T</code> + <code>ClassName</code>. This is an awesome idea but I prefer to standardize the names whenever possible. The Type that holds the private fields of my class are always named <code>Members</code> and I always name my reference variable <code>m</code> (this is similar to the VBA class field convention that prefixes class variables with <code>m</code>.</p>\n<p>Don't get me wrong Matt knows 10 times more than I do about coding than I do. But when I am review a class if I see <code>TChartWorksheetService</code> I have to stop think what is <code>TChartWorksheetService</code>. Is it a built in or custom class? Oh wait, its a Type so it can't be passed into a class. How is it used? Where is it used? Where as I see <code>private m As Members</code>, I think oh private fields and move on.</p>\n<p><a href=\"https://i.stack.imgur.com/HAZ1C.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HAZ1C.png\" alt=\"Code Image\" /></a></p>\n<h2>Properties and Constants</h2>\n<p>Constants values are great for storing magic numbers and immutable strings but are constants really what you need here? If a user needs an Arial <code>ServiceHeaderFont</code> on one worksheet and a Times New Roman <code>ServiceHeaderFont</code> on another then you will have to write two different classes or worse yet (what usually happens) you write a hack routine to make the <code>StandardChartWorkSheet</code> fit the new specifications. Can you imagine having to have an <code>ArialTexbox</code> and <code>TimesNewRomanTextBox</code>...ugh. It would be better to define most of these settings as properties of the <code>IChart</code> and assign the default values in your factory methods.</p>\n<p>For example:</p>\n<p><strong>IChart:</strong></p>\n<pre><code>Option Explicit\n\nPublic Sub BuildChart()\nEnd Sub\n\nPublic Property Get ProductHeaderFont() As String\nEnd Property\n\nPublic Property Let ProductHeaderFont(ByVal Value As String)\nEnd Property\n\nPublic Property Get ProductHeaderFontSize() As Single\nEnd Property\n\nPublic Property Let ProductHeaderFontSize(ByVal Value As Single)\nEnd Property\n\n'***** More settings *******\n</code></pre>\n<p><strong>StandardChartWorkSheet</strong></p>\n<p><code>AsIChart()</code> was added to make it easier to reference the class as <code>StandardChartWorkSheet</code> class.</p>\n<pre><code>Private mProductHeaderFont As String\nPrivate mProductHeaderFontSize As Integer\n\nPublic Function Create(ByVal hData As Scripting.Dictionary, cSheet As Worksheet) As IChart\n With New StandardChartWorkSheet\n Set .HeaderData = hData\n Set .ChartWorksheet = cSheet\n Set Create = .Self\n With .AsIChart\n .ProductHeaderFont = ProductHeaderFont\n .ProductHeaderFontSize = ProductHeaderFontSize\n End With\n End With\nEnd Function\n\nPublic Function AsIChart() As IChart\n Set GetIChartFromClass = Self\nEnd Function\n\nPrivate Property Let IChart_ProductHeaderFont(ByVal RHS As String)\n mProductHeaderFont = RHS\nEnd Property\n\nPrivate Property Get IChart_ProductHeaderFont() As String\n IChart_ProductHeaderFont = mProductHeaderFont\nEnd Property\n\nPrivate Property Let IChart_ProductHeaderFontSize(ByVal RHS As Single)\n mProductHeaderFontSize = RHS\nEnd Property\n\nPrivate Property Get IChart_ProductHeaderFontSize() As Single\n IChart_ProductHeaderFontSize = mProductHeaderFontSize\nEnd Property\n</code></pre>\n<blockquote>\n<pre><code>Sub NewTest()\n Dim chart As IChart\n Set chart = StandardChartWorkSheet.Create(GetTMProductDictionary, Sheet3)\n chart.ProductHeaderFont = &quot;Times New Roman&quot;\n chart.ProductHeaderFontSize = 14\n chart.BuildChart\nEnd Sub\n</code></pre>\n</blockquote>\n<h2>IChartFormatService</h2>\n<p>If the VBA supported polymorphism, I would tell you that <code>IChartFormatService</code> should be an abstract class because it is only used internally by the <code>StandardChartWorkSheet</code> class. Interfaces are meant to be used to expose methods of the class not just to enforce implementation of a method. IMO <code>IChartFormatService</code> is just decoration. I would drop it because I don't want to have to port it the next project I need a <code>StandardChartWorkSheet</code>.</p>\n<h2>BuildHeaders</h2>\n<p><code>Application.ScreenUpdating = True</code> is no longer necessary. <code>ScreenUpdating</code> will automatically resume after all the code has ran. This was changed in either Excel 2007 or 2010. If you are worried about backwards compatibility then you should save and restore the <code>Application.ScreenUpdating</code> state. This will prevent slow downs when running multiple procedures.</p>\n<h2>PrintProductValues</h2>\n<p><code>With Sheet3.Cells(4, this.HeaderColumn)</code> is a refactoring over site.</p>\n<h2>Create()</h2>\n<p>Referencing the <code>TopLeftCell</code> that you want to target will allow you to add multiple chart to the same worksheet.</p>\n<blockquote>\n<pre><code>Public Function Create(ByVal hData As Scripting.Dictionary, TopLeftCell As Range) As IChart\n</code></pre>\n</blockquote>\n<h2>HeaderColumn</h2>\n<p><code>CurrentHeaderColumn</code> or change <code>HeaderIndex</code> are better names for <code>HeaderColumn</code>.</p>\n<p><code>HeaderColumn</code> should not belong to the class. Class variables are subject to modification by multiple procedures. This makes it far easier to make mistakes and takes longer to read, modify and debug.</p>\n<p>If by contrast, you pass the <code>HeaderColumn</code> as a parameter, you will know empirically when and where the value is being modified.</p>\n<blockquote>\n<pre><code>Private Sub PrintProductValues(ByVal product As String, ByVal HeaderColumn As Long)\n</code></pre>\n</blockquote>\n<h2>Miscellaneous</h2>\n<p><code>.Value = Mid(service, 14, 100)</code> works perfect and is exactly what you need if you expect values over 100 characters. Otherwise, <code>.Value = Mid(service, 14)</code> will return the same value.</p>\n<p><code>Cells(50, this.HeaderColumn)</code> Why fifty? It seems like this needs to be more dynamic.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T21:13:13.543", "Id": "483033", "Score": "0", "body": "thank you for your honest review! I'll admit probably the most challenging part of OOP for me so far is the naming of variables / creating meaningful names with value. I hear you about setting the font names via `Factory` however I only need to implement 1 chart per Sheet. With that said yes, I would be creating a whole new `Class` for say a `QuarterlyChart` or a `YearEndChat`. I think it would be much cleaner at that point, for each Chart `Class` would have its own logic, and methods with fonts and colors." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T21:27:31.077", "Id": "483034", "Score": "0", "body": "Have you given any thought to how you are going to populate the chart?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T15:08:04.833", "Id": "483391", "Score": "0", "body": "@JoseCortez you should read this answer to [views\nExcel Data Import and Manipulation, too slow?](https://codereview.stackexchange.com/a/246034/171419). He lays down the principles for writing solid code. Basically, everything I said but in a generic way. So much better than mine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T17:20:48.583", "Id": "483397", "Score": "0", "body": "thanks for providing the link! I'm going to take time to read it. Don't sell yourself short, you provided a similar best practices in my previous post regarding Product Dictionary's ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-22T21:54:18.293", "Id": "493985", "Score": "0", "body": "@TinMan, I'm having trouble following. Seeing `With .AsIChart` (thought Whaaat? Undocumented feature?) but then no, `AsIChart` is a function. But `Public Function AsIChart() As IChart` doesn't set `AsIChart` but does `Set GetIChartFromClass = Self`. Guessing `GetIChartFromClass` is a member that didn't get included in the paste?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-22T22:09:16.483", "Id": "493986", "Score": "0", "body": "Also, do appreciate the link above to the @BZngr answer. Never did Module Properties (in particular) outside of Classes before, but can see the utility." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T23:49:12.037", "Id": "245845", "ParentId": "245797", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T06:52:56.863", "Id": "245797", "Score": "6", "Tags": [ "object-oriented", "vba", "excel" ], "Title": "Creating a Chart Worksheet from scratch with VBA / OOP Design" }
245797
<p>Is there a better way to design this code? I have read that too many function parameters is a sign of poorly design code, and would love some feedback on this code.</p> <p>The functions Google Maps markers and update the state.</p> <p>Also any other feedback unrelated is welcome.</p> <p>Functions:</p> <pre><code>// Initialising map and markers export const handleApiLoaded = ( games, map, setGameMarkers, setInfoWindow, handleMarkerClick ) =&gt; { const infoWindow = new google.maps.InfoWindow({}); const gameMarkers = []; for (const game of games) { const newMarker = createGameMarker( map, game, infoWindow, gameMarkers, handleMarkerClick ); newMarker ? gameMarkers.push(newMarker) : null; } // Update state setGameMarkers(gameMarkers); setInfoWindow(infoWindow); }; // Create marker object for game export const createGameMarker = ( map, game, infoWindow, gameMarkers, handleMarkerClick ) =&gt; { const [lat, lng] = [parseFloat(game.latitude), parseFloat(game.longitude)]; if (locationIsUnoccupied(lat, lng, gameMarkers)) { var icon = { url: GAME_ICON_URL, scaledSize: new google.maps.Size(30, 45), }; var marker = new google.maps.Marker({ position: { lat: lat, lng: lng, }, icon: icon, map, }); marker.addListener(&quot;click&quot;, () =&gt; { infoWindow.close(); map.panTo(marker.getPosition()); handleMarkerClick(marker, map); infoWindow.setContent(createGameInfoWindow(game)); infoWindow.open(map, marker); }); return marker; } }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T13:04:08.613", "Id": "482809", "Score": "2", "body": "Adding the missing `locationIsUnoccupied` and `createGameInfoWindow` will improve the reviews you receive. Currently this question is off-topic for Code Review due to missing context. Please see our [help center](https://codereview.stackexchange.com/help/asking) for more information on how to ask a good question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T05:48:54.880", "Id": "483062", "Score": "1", "body": "@pacmaninbw: In all fairness, the methods sought after aren't burdened with an excessive number of parameters." } ]
[ { "body": "<p>From a short review;</p>\n<ul>\n<li><code>locationIsUnoccupied</code> and <code>createGameInfoWindow</code> are mysterious, where are they defined?</li>\n<li><code>newMarker ? gameMarkers.push(newMarker) : null;</code> should trigger jshint, I would just go for the <code>if</code> statement</li>\n<li>I would structure all the code and functions in to MVC (model view controller)\n<ul>\n<li>So <code>GAME_ICON_URL</code> becomes <code>model.GAME_ICON_URL</code></li>\n<li>So <code>createGameInfoWindow</code> becomes <code>ui.createGameInfoWindow</code></li>\n<li>So <code>locationIsUnoccupied</code> becomes <code>model.locationIsUnoccupied</code></li>\n</ul>\n</li>\n</ul>\n<p>This could make your code look like;</p>\n<pre><code>// Initialising map and markers\nexport function handleApiLoaded(model, ui, controller){\n ui.infoWindow = new google.maps.InfoWindow({});\n\n model.gameMarkers = [];\n for (const game of games) {\n addGameMarker(game, model, ui, controller);\n }\n\n //Not sure the below would still make sense?\n model.setGameMarkers(gameMarkers);\n ui.setInfoWindow(ui.infoWindow);\n};\n\n\n// Create marker object for game\nexport function addGameMarker(game, model, ui, controller){\n\n const [lat, lng] = [parseFloat(game.latitude), parseFloat(game.longitude)];\n\n if (model.locationIsUnoccupied(lat, lng, model.gameMarkers)) {\n var icon = {\n url: model.GAME_ICON_URL,\n //Why 30 and 45, a comment would be good here\n scaledSize: new google.maps.Size(30, 45),\n };\n\n var marker = new google.maps.Marker({\n position: {\n lat: lat,\n lng: lng,\n },\n icon: icon,\n map: model.map,\n });\n\n marker.addListener(&quot;click&quot;, () =&gt; {\n ui.infoWindow.close();\n //Maybe `map` should be part of `ui`, deep thoughts to be had..\n model.map.panTo(marker.getPosition());\n ui.handleMarkerClick(marker, map);\n ui.infoWindow.setContent(createGameInfoWindow(game));\n ui.infoWindow.open(map, marker);\n });\n\n model.gameMarkers.push(marker);\n }\n};\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T09:42:22.670", "Id": "245804", "ParentId": "245802", "Score": "1" } } ]
{ "AcceptedAnswerId": "245804", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T09:04:45.567", "Id": "245802", "Score": "2", "Tags": [ "javascript", "game", "react.js", "google-maps" ], "Title": "Google Maps marker management for games" }
245802
<p><strong>Project</strong></p> <p>I wanted to create a syntax highlighter for Java using JavaScript, HTML and CSS. It uses regular expressions to find the parts that should be highlighted (at the moment: keywords, strings, comments, imports) and then uses HTML-tags to highlight the found parts.</p> <p><strong>Result</strong></p> <p>The website looks like this before entering some code:</p> <blockquote> <p><a href="https://i.stack.imgur.com/vEX2Z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vEX2Z.png" alt="enter image description here" /></a></p> </blockquote> <p><strong>Example</strong></p> <p>I've used the following java-snippet to test the code:</p> <pre class="lang-java prettyprint-override"><code>import java.time.LocalDate; public class Person { //Local variable for dateOfBirth private LocalDate dateOfBirth; public Person(int year, int month, int day) { //See API also: https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html dateOfBirth = LocalDate.of(year, month, day); //Keywords (e.g. int) are not highlighted in comments and strings System.out.println(&quot;Hello (int)&quot;); } /* * Getter */ public LocalDate getDateOfBirth() { return dateOfBirth; } } </code></pre> <p>The result looks like this:</p> <blockquote> <p><a href="https://i.stack.imgur.com/juWBq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/juWBq.png" alt="enter image description here" /></a></p> </blockquote> <p><strong>Background</strong></p> <p>This is my first HTML/CSS/JS-project.</p> <p><strong>Code</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var keywordsColor = "#0033cc"; var controlKeywordsColor = "#009933"; var typesKeywordsColor = "#3399ff"; var stringColor = "#ff3300"; var importColor = "#0033cc"; var commentColor = "gray"; var text; var keywords = ["abstract", "assert", "class", "const", "extends", "false", "final", "implements", "import", "instanceof", "interface", "native", "new", "null", "package", "private", "protected", "public", "return", "static", "strictfp", "super", "synchronized", "System", "this", "throw", "throws", "transient", "true", "volatile"]; var controlKeywords = ["break", "case", "catch", "continue", "default", "do", "else", "finally", "for", "goto", "if", "switch", "try", "while"]; var typesKeywords = ["boolean", "byte", "char", "double", "enum", "float", "int", "long", "short", "String", "void"]; var otherKeywords = []; function highlight() { text = document.getElementById("Input").value; highlightKeywords(); highlightStrings(); highlightImports(); highlightSingleLineComments(); highlightMultiLineComments(); addStyles(); document.getElementById("Output").value = text; document.getElementById("outputArea").innerHTML = text; } function highlightKeywords() { var i; for (i = 0; i &lt; keywords.length; i++) { var x = new RegExp(keywords[i] + " ", "g"); var y = "&lt;span style='color:" + keywordsColor + ";font-weight:bold;'&gt;" + keywords[i] + " &lt;/span&gt;"; text = text.replace(x, y); } for (i = 0; i &lt; controlKeywords.length; i++) { var x = new RegExp(controlKeywords[i] + " ", "g"); var y = "&lt;span style='color:" + controlKeywordsColor + "; font-weight:bold; '&gt;" + controlKeywords[i] + " &lt;/span&gt;"; text = text.replace(x, y); } for (i = 0; i &lt; typesKeywords.length; i++) { var x = new RegExp(typesKeywords[i] + " ", "g"); var y = "&lt;span style='color:" + typesKeywordsColor + "; font-weight:bold; '&gt;" + typesKeywords[i] + " &lt;/span&gt;"; text = text.replace(x, y); } } function highlightStrings() { text = text.replace(/"(.*?)"/g, "&lt;span id=\"str\"style='color:" + stringColor + "; font-weight:bold; '&gt;" + "\"$1\"" + "&lt;/span&gt;"); } function highlightImports() { text = text.replace(/import(.*?);/g, "&lt;span id=\"str\"style='color:" + importColor + "; font-weight:bold; '&gt;" + "import$1;" + "&lt;/span&gt;"); } function highlightSingleLineComments() { text = text.replace(/\/\/(.*)/g, "&lt;span id=\"comment\"style='color:" + commentColor + "; font-weight:bold; '&gt;" + "//$1" + "&lt;/span&gt;"); } function highlightMultiLineComments() { text = text.replace(/\/\*([\s\S]*?)\*\//g, "&lt;span id=\"comment\"style='color:" + commentColor + "; font-weight:bold; '&gt;" + "/*$1*/" + "&lt;/span&gt;"); } function addStyles() { text = "&lt;!-- Code begins here --&gt;\n&lt;pre&gt;&lt;code&gt;\n" + "&lt;style&gt;#comment span {color:" + commentColor + "!important;}&lt;/style&gt;" + "&lt;style&gt;#str span {color:" + stringColor + "!important;}&lt;/style&gt;" + text + "\n&lt;/code&gt;&lt;/pre&gt;\n&lt;!-- Code ends here --&gt;\n"; }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>/* Navigation bar style */ .nav ul { background: ForestGreen; /* Sets the background-color */ list-style: none; /* Removes bullet point */ overflow: hidden; /* What happens when element is too big for formatting context*/ padding: 0px; /* padding-area at all four sides of an element */ } .nav li { float: left; /* Move element to the left and add new element on the right side*/ border-right: 2px solid LightGray;/* Border lines on the right side of each element */ } .nav a { color: black; /* Font color has to be set here, because otherwise it would be a blue hyperlink */ display: inline-block; /* One box for all elements */ font-size: large; /* Sets font size to a large size */ text-decoration: none; /* Removes underline */ padding: 4px; } .nav a:hover { background: AliceBlue; /* Changes background of element when user is hovering over it */ } .nav a.active { background: DarkGreen; /* Changes background of current element */ } /* Other */ #code { background: LightGray; font: monospace; } .column { float: left; width: 50%; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;!-- Head --&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;link rel="stylesheet" type="text/css" href="style.css"&gt; &lt;/head&gt; &lt;!-- Navigation bar --&gt; &lt;header&gt; &lt;div class="nav"&gt; &lt;ul&gt; &lt;li&gt;&lt;a class = "active" href="index.html"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/header&gt; &lt;!-- Body --&gt; &lt;body&gt; &lt;h2&gt;HTML syntax-highlighting for Java&lt;/h2&gt; &lt;!-- Left column --&gt; &lt;div class="column"&gt; &lt;!-- Input Area --&gt; &lt;h4&gt;Input:&lt;/h4&gt; &lt;div style = "white-space = pre !important"&gt; &lt;textarea id="Input" cols="80" rows="8" wrap = "off" style = "resize: none; background: LightGray"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;br&gt;&lt;br&gt; &lt;button type="button" onclick="highlight()"&gt;Highlight&lt;/button&gt; &lt;!-- Output Area --&gt; &lt;h4&gt;Output:&lt;/h4&gt; &lt;div style = "white-space = pre !important"&gt; &lt;textarea id="Output" cols="80" rows="8" wrap = "off" style = "resize: none; background: LightGray"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;style&gt; document.getElementById("Input").style.whiteSpace = "nowrap"; document.getElementById("Output").style.whiteSpace = "nowrap"; &lt;/style&gt; &lt;/div&gt; &lt;!-- Right Column --&gt; &lt;div class="column"&gt; &lt;h4&gt;Preview&lt;/h4&gt; &lt;div id="outputArea" style="overflow-y:auto; overflow-x:auto; height: 690px"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;script language = "javascript" type = "text/javascript" src = "highlightSyntax.js"&gt;&lt;/script&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p><strong>Questions</strong></p> <p>How can this code be improved? Did I make a major mistake in regards to the best-practices of HTML/CSS/JS?</p> <p>Any suggestions are appreciated.</p> <hr /> <p>The follow-up question can be found <a href="https://codereview.stackexchange.com/questions/247282/follow-up-javascript-syntax-highlighter-for-java">here</a>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T09:45:40.800", "Id": "482928", "Score": "1", "body": "What about `\"\\\"\"`? Or `\"\\\\\\\"\"`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T17:59:07.293", "Id": "483008", "Score": "1", "body": "Try highlighting `serif (x);`, `if (x) y();` and `if(x) y();`. The first is a false positive, and the third a false negative. The regex `\\b` for word-boundaries may be more useful (`/\\bif\\b`) than just looking for a trailing space (`/if /`)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T03:15:52.833", "Id": "483047", "Score": "0", "body": "And the moment I see RegEx and HTML tags, I will have to say [RegEx is not an XHTML parser](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T04:29:28.807", "Id": "483051", "Score": "0", "body": "@Nelson: He's not parsing HTML with regex, he's parsing Java with regex and generating HTML. The same argument applies as well, though: Java is not a regular language, it is a (mostly) context-free language with some context-sensitive bits here and there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T04:34:39.730", "Id": "483052", "Score": "3", "body": "Please, call this \"Lexical Highlighting\" instead of \"Syntax Highlighting\". I know that every editor on the planet calls it syntax highlighting, but it really isn't. You are not using any syntactical properties of the language in your highlighting, only lexical ones. Unless you *actually* analyze the syntax and highlight based on that, please don't call it syntax highlighting. Don't take part in this dilution of the meaning of the word \"syntax\"." } ]
[ { "body": "<p>There's a glaring problem with this: no user input validation.</p>\n<p>A basic test revealed this:</p>\n<p><a href=\"https://i.stack.imgur.com/JeCFK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/JeCFK.png\" alt=\"Oops\" /></a></p>\n<p>Ah, but that's not Java you say? True, but what if some poor sod has a stray HTML tag in their docstring?</p>\n<p><a href=\"https://i.stack.imgur.com/W7stq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/W7stq.png\" alt=\"Centered Java\" /></a></p>\n<p>All HTML that's already in the user input should probably be made harmless. Either escape it, wrap it in a container that will treat it as a string instead of code, anything. Or people will do all kinds of strange things with your site.</p>\n<p>The docstring should've been properly rendered instead of cutting out the this-just-happens-to-be-valid-HTML.</p>\n<pre><code>/**\n * &lt;center&gt;\n */\n</code></pre>\n<p>That's a valid docstring. It should've been rendered as such.</p>\n<p>Another example. The following input:</p>\n<pre><code>public final class Solution extends Mightyfine &lt;A, B&gt;\n implements Foo {\n /**\n * &lt;hr&gt;\n */&lt;span id=&quot;comment&quot; style='color:gray; font-weight:bold;'&gt;\n }\n}\n</code></pre>\n<p>Results in the following output:</p>\n<pre><code>&lt;!-- Code begins here --&gt;\n&lt;pre&gt;&lt;code&gt;\n&lt;style&gt;#comment span {color:gray!important;}&lt;/style&gt;&lt;style&gt;#str span {color:#ff3300!important;}&lt;/style&gt;&lt;span style='color:#0033cc;font-weight:bold;'&gt;public &lt;/span&gt;&lt;span style='color:#0033cc;font-weight:bold;'&gt;final &lt;/span&gt;&lt;span style='color:#0033cc;font-weight:bold;'&gt;class &lt;/span&gt;Solution &lt;span style='color:#0033cc;font-weight:bold;'&gt;extends &lt;/span&gt;Mightyfine &lt;A, B&gt;\n &lt;span style='color:#0033cc;font-weight:bold;'&gt;implements &lt;/span&gt;Foo {\n &lt;span id=&quot;comment&quot;style='color:gray; font-weight:bold; '&gt;/**\n * &lt;hr&gt;\n */&lt;/span&gt;&lt;span id=&lt;span id=&quot;str&quot;style='color:#ff3300; font-weight:bold; '&gt;&quot;comment&quot;&lt;/span&gt; style='color:gray; font-weight:bold;'&gt;\n }\n}\n&lt;/code&gt;&lt;/pre&gt;\n&lt;!-- Code ends here --&gt;\n</code></pre>\n<p><code>*/&lt;/span&gt;&lt;span id=&lt;span id=</code> is going to be interesting to parse for a browser. On my machine, that looks like this:</p>\n<p><a href=\"https://i.stack.imgur.com/zYM8N.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zYM8N.png\" alt=\"Java Unhinged\" /></a></p>\n<p>Notice that there's a lot of parts being parsed wrong. For example, where did <code>&lt;A, B&gt;</code> go? It's incorrectly parsed as HTML. The offending characters should either be <a href=\"https://en.wikipedia.org/wiki/Escape_character\" rel=\"nofollow noreferrer\">escaped</a> or simply be parsed differently than they are now. Leaving them unescaped, like how it is done now, will lead to behaviour you don't want.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T14:59:08.183", "Id": "245816", "ParentId": "245806", "Score": "13" } }, { "body": "<p>For a beginner this looks like a great start! Below are some suggestions to clean things up and make things more consistent.</p>\n<p>It is a common convention for HTML to not contain spaces between attribute keys and values.</p>\n<p>So instead of</p>\n<blockquote>\n<pre><code>&lt;script language = &quot;javascript&quot; type = &quot;text/javascript&quot; src = &quot;highlightSyntax.js&quot;&gt;&lt;/script&gt;\n</code></pre>\n</blockquote>\n<p>make it simply:</p>\n<pre><code>&lt;script language=&quot;javascript&quot; type=&quot;text/javascript&quot; src=&quot;highlightSyntax.js&quot;&gt;&lt;/script&gt;\n</code></pre>\n<p>And similarly for the <code>&lt;div&gt;</code> that contains the first <code>&lt;textarea&gt;</code>.</p>\n<p>While single quotes can be used to delimit the attribute values of HTML, it is best to be consistent and use double quotes - so the JavaScript functions that wrap keywords in HTML can use single-quotes to delimit the strings, which is inline with many style guides (e.g. <a href=\"https://github.com/airbnb/javascript#strings\" rel=\"nofollow noreferrer\">aibnb</a>, <a href=\"https://google.github.io/styleguide/jsguide.html#features-string-literals\" rel=\"nofollow noreferrer\">google</a>).</p>\n<p>Instead of</p>\n<blockquote>\n<pre><code>var y = &quot;&lt;span style='color:&quot; + typesKeywordsColor + &quot;; font-weight:bold; '&gt;&quot; + typesKeywords[i] \n + &quot; &lt;/span&gt;&quot;;\n</code></pre>\n</blockquote>\n<p>Use single quotes:</p>\n<pre><code>var y = '&lt;span style=&quot;color:' + typesKeywordsColor + '; font-weight:bold; &quot;&gt;' + typesKeywords[i] \n + ' &lt;/span&gt;';\n</code></pre>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals\" rel=\"nofollow noreferrer\">Template literals</a> could also be used to generate the strings though note the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Browser_compatibility\" rel=\"nofollow noreferrer\">browser support</a> as that may affect the target audience.</p>\n<pre><code>var y = `&lt;span style=&quot;color:${typesKeywordsColor}; font-weight:bold; &quot;&gt;${typesKeywords[i]} &lt;/span&gt;`;\n</code></pre>\n<p>The attribute <code>id</code> must be unique<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id\" rel=\"nofollow noreferrer\">1</a></sup> so instead of using multiple elements with the same <code>id</code> attribute (e.g. <code>&lt;span id=\\&quot;comment\\&quot;</code>), use a class name instead. Also, the inline <code>style</code> attributes should be put into CSS because they aren't so dynamic. Thus variables like <code>keywordsColor</code> can be eliminated from the JavaScript. <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties\" rel=\"nofollow noreferrer\">CSS custom properties (variables)</a> could be used if there is a need.</p>\n<p>Instead of adding event handlers in HTML, e.g.</p>\n<blockquote>\n<pre><code>&lt;button type=&quot;button&quot; onclick=&quot;highlight()&quot;&gt;Highlight&lt;/button&gt; \n</code></pre>\n</blockquote>\n<p>It can be done in JavaScript in multiple ways. One way (which many prefer) is to use <code>element.addEventListener()</code> which allows adding multiple handlers to an element. For example, presuming an attribute <code>id=&quot;highlightButton&quot;</code> is added to that button (though that isn’t the only way to access that element via JS):</p>\n<pre><code>document.getElementById('highlightButton').addEventListener('click', highlight);\n</code></pre>\n<p>This keeps the event handling logic separate from the markup.</p>\n<p>There appears to be a <code>style</code> tag with JavaScript in it - I presume the intention was to use <code>script</code> instead. And those styles can be put into the CSS instead (i.e. in <code>style.css</code>). If you were aiming for the styles to be applied at a certain event (e.g. <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event\" rel=\"nofollow noreferrer\"><em>DOMContentLoaded</em></a>) then apply classes accordingly.</p>\n<blockquote>\n<pre><code> &lt;style&gt;\n document.getElementById(&quot;Input&quot;).style.whiteSpace = &quot;nowrap&quot;; \n document.getElementById(&quot;Output&quot;).style.whiteSpace = &quot;nowrap&quot;; \n &lt;/style&gt;\n</code></pre>\n</blockquote>\n<p>In the styles there is one rule for <code>padding</code> on <code>.nav ul</code>:</p>\n<blockquote>\n<pre><code>padding: 0px;\n</code></pre>\n</blockquote>\n<p>For <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/length\" rel=\"nofollow noreferrer\"><code>&lt;length&gt;</code></a> values &quot;unit is optional after the number <code>0</code>&quot;<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/length#Syntax\" rel=\"nofollow noreferrer\">2</a></sup> (and could add confusion<sup><a href=\"https://stackoverflow.com/a/7923077/1575353\">3</a></sup>).</p>\n<p>I also see this in the HTML:</p>\n<blockquote>\n<pre><code>&lt;div style = &quot;white-space = pre !important&quot;&gt;\n</code></pre>\n</blockquote>\n<p>But note that:</p>\n<blockquote>\n<p>Using `!important, however, is <strong>bad practice</strong> and should be avoided because it makes debugging more difficult by breaking the natural <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/Cascade\" rel=\"nofollow noreferrer\">cascading</a> in your stylesheets.\n<br> ...<br>\nInstead of using !important, consider:</p>\n</blockquote>\n<blockquote>\n<ol>\n<li>Make better use of the CSS cascade</li>\n<li>Use more specific rules. By indicating one or more elements before the element you're selecting, the rule becomes more specific and gets higher priority</li>\n</ol>\n</blockquote>\n<p><sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity#The_!important_exception\" rel=\"nofollow noreferrer\">4</a></sup></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T12:00:33.497", "Id": "482939", "Score": "1", "body": "Just a small nitpick: \"The attribute `id` should be unique [...]\" <-- For HTML5, the `id` attribute ***MUST*** be unique for THE WHOLE DOCUMENT. The `name` attribute *should* be unique. You can see this in the standard: https://www.w3.org/TR/html51/dom.html#the-id-attribute" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T12:37:44.097", "Id": "482946", "Score": "0", "body": "*\"The name attribute should be unique\"* - That's incorrect. Radio buttons are just one example whereby I might want duplicate `name` attributes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T12:40:47.623", "Id": "482947", "Score": "1", "body": "@Geroge presuming you are addressing Ismael, please @-mentioning him to avoid confusion" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T12:45:19.160", "Id": "482948", "Score": "1", "body": "There's irony in you spelling my name incorrectly ;) kidding of course - thanks for highlighting. @SᴀᴍOnᴇᴌᴀ" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T12:53:08.833", "Id": "482949", "Score": "0", "body": "Wow I apologize- perhaps I shouldn’t be typing with my thumbs early in my morning (-‸ლ )" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T14:12:04.367", "Id": "482972", "Score": "1", "body": "@George Therefore *should*, not *must*. There are other exceptions, like `name[]`, where (in PHP) each element with name `name[]` will be in `$_POST['name']` or `$_GET['name']`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-13T18:09:31.210", "Id": "485432", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ That's just Skitt's Law in action. In its most applicable form: \"Any post correcting an error in another post will contain at least one error itself.\" You were doomed from the start. ;-)" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T15:10:56.180", "Id": "245818", "ParentId": "245806", "Score": "11" } }, { "body": "<p>Your current approach of highlighting one token type after another will fail for more complicated examples. Imagine this:</p>\n<pre><code>String s = &quot;public data, private secrets&quot;;\n</code></pre>\n<p>The words in the string are not keywords.</p>\n<p>To fix this, you need to change your code to tokenize the input text in a single pass, like this pseudo code:</p>\n<pre class=\"lang-js prettyprint-override\"><code>function tokenize(text) {\n const tokens = [];\n\n while (text !== '') {\n if (text starts with whitespace)\n tokens.push(['space', leading space]);\n else if (text starts with keyword)\n tokens.push(['keyword.flow', keyword]);\n else if (text starts with string)\n tokens.push(['string', string]);\n else\n error();\n text = text without the current token;\n }\n return tokens;\n}\n</code></pre>\n<p>Using this structure, you can correctly parse Java code. Parsing more esoteric languages like Python or Kotlin or even Perl requires even more sophisticated parsers, but Java is a very simple language (on the syntactical level).</p>\n<p>Once you have split the text into tokens, generating the highlighted HTML from the tokens is trivial.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T17:53:04.170", "Id": "482865", "Score": "2", "body": "Thanks for your answer. I don't really get what you mean with your example provided above. My program is highlighting the string correctly as a string and not as keywords. Could you provide an example that isn't working (without html-code in it; I already try to solve this problem)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T21:42:02.037", "Id": "483035", "Score": "1", "body": "Your program is only highlighting my example code \"as expected\" because you are cheating by using the `!important` CSS feature. If you were to use regular CSS only, the keywords inside the string would be shown in keyword color, not in string color. In other words, your highlighting \"looks as\" expected, but inspecting the generated HTML clearly shows that it is not correct." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T17:32:47.067", "Id": "245823", "ParentId": "245806", "Score": "3" } }, { "body": "<p>Interpreting any source code language entirely by regular expression — which is to say, without actually <em>parsing</em> the code and building an understanding of it on a syntactic level — is notoriously difficult to do. Your regular expressions do fall prey to some of the common issues with regexp-as-parser, since it will mis-highlight all of the following:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class Person {\n private Account my_import_export;\n private Multibyte stupidClassName;\n System.out.println(&quot;Hi \\&quot;friend\\&quot;.&quot;);\n}\n</code></pre>\n<p>Ensuring that your keywords don't start in the middle of a word would help a lot, and fix the first two. The escaped quotes thing is trickier.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T12:54:29.810", "Id": "482951", "Score": "5", "body": "The Stack Overflow classic is [the question for which an answer](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) starts with *\"You can't parse [X]HTML with regex.\"*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T13:41:51.133", "Id": "482961", "Score": "0", "body": "Some would claim it's one of the Classic Blunders, right after \"Never get involved in a land war in Asia\" and \"Never go against a Sicilian when death is on the line.\" I'm not quite that alarmist. Not that I believe it can be done correctly — it can't, period. But with enough complexity, you can make it probably 90-95% of the way using regex. And if all you're doing is syntax-highlighting some code, nobody's going to die or get maimed because your code mis-highlights the remaining 5-10%. **#YOLO** and **#YOPWREO** `¯\\_(ツ)_/¯`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T04:21:37.793", "Id": "245850", "ParentId": "245806", "Score": "8" } } ]
{ "AcceptedAnswerId": "245818", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T10:04:36.057", "Id": "245806", "Score": "12", "Tags": [ "javascript", "beginner", "html", "css", "regex" ], "Title": "Javascript Syntax-Highlighter for Java" }
245806
<p>I'm doing an exercise where I pick an existing webpage and I code its front end (in HTML and CSS) from scratch, just by looking at it. I started off with an easy one. It would be great if somebody could review my code.</p> <ul> <li>What are the best units to use? I know px is discouraged. Should I replace them with em and rem? How do I know where to use em and where to use rem?</li> <li>In CSS, is one line per property good, or is it better to go more compact?</li> <li>I declare each selector only once. I don't use multiple selectors and commas, I feel that leads to that selector's code getting spread out all over the place. Is my way good practice?</li> <li>Are my names for ID's, classes, etc OK?</li> <li>Feel free to make other suggestions.</li> </ul> <p>Note: The original website has working menus and is mobile friendly. My copy is not. I kept it simple.</p> <h2>Original Website</h2> <p><a href="https://www.titanvolunteers.com/" rel="nofollow noreferrer">https://www.titanvolunteers.com/</a></p> <p><a href="https://i.stack.imgur.com/ohbV6.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ohbV6.jpg" alt="screenshot of volunteer registration website's home page" /></a></p> <h2>My Copy</h2> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { background-color: #999999; margin-bottom: 0; } #page-container { background-color: #DFDFDF; width: 1150px; /* is margin: auto the best way to center a display: block? */ margin: 12px auto 0 auto; } #page-container2 { padding: 12px 12px 0 12px; } header { background-color: white; } nav { background-color: black; color: white; } article { background-color: #F5F5F5; color: #666666; } #site-name-container { /* No floating needed. It sits on the left automatically. */ text-align: center; width: 360px; padding: 20px 10px 20px 10px; } #site-name { color: #059BD8; font-size: 2.5rem; } #tagline { color: #6E6C6A; font-family: sans-serif; } .category { display: inline-block; padding: 18px 25px; font-family: sans-serif; } .category:hover { background-color: #059BD8; } #hero-image { width: 580px; } #mid-page { background-color: #F5F5F5; /* Is display: flex the best way to get 2 fixed width blocks side by side? Or better to use something else? */ display: flex; } article { /* padding-bottom: 1px here because if I set it to 0, the p margin-bottom disappears. Is there a better way to do this? */ padding: 20px 20px 1px 20px; width: 670px; } aside { padding: 20px 0 0 40px; background-color: #F5F5F5; color: #666666; width: 360px; } h1 { border-bottom: 1px solid #666666; font-weight: normal; } p { font-family: sans-serif; } h2 { font-weight: bold; font-style: italic; text-decoration: underline; font-size: 1rem; font-family: sans-serif; } aside &gt; h1 { border: 0; border-bottom: 1px solid #666666; padding-bottom: 15px; margin-bottom: 0; } .sidebar-event { border-bottom: 1px solid #666666; padding: 15px 0; display: flex; } .event-logo { display: flex; justify-content: center; align-items: center; background-color: white; border: 1px solid #666666; width: 130px; height: 130px; } .event-logo &gt; img { width: 90%; display: block; } a { color: #059BD8; font-family: sans-serif; } a:hover { background-color: darkorange; } .event-description { width: 200px; margin-left: 10px; } .event-description &gt; p { margin: 0; } .event-description &gt; a { font-weight: bold; } footer { background-color: #3D3D3D; color: white; font-family: sans-serif; padding: 12px 25px; display: flex; justify-content: space-between; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en-us"&gt; &lt;head&gt; &lt;title&gt;TitanVolunteers.com - Volunteer Registration For Events&lt;/title&gt; &lt;link rel="stylesheet" href="style.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="page-container"&gt; &lt;div id="page-container2"&gt; &lt;header&gt; &lt;div id="site-name-container"&gt; &lt;div id="site-name"&gt; TitanVolunteers.com &lt;/div&gt; &lt;div id="tagline"&gt; Volunteer Registration For Events &lt;/div&gt; &lt;/div&gt; &lt;/header&gt; &lt;nav&gt; &lt;div class="category"&gt; Home &lt;/div&gt; &lt;div class="category"&gt; Sign Up To Volunteer &lt;/div&gt; &lt;div class="category"&gt; Volunteer Coordinators &lt;!-- TODO: get hover to display a sub menu. I checked, it's all CSS, no JS --&gt; &lt;/div&gt; &lt;div class="category"&gt; Control Panel &lt;/div&gt; &lt;div class="category"&gt; About Us &lt;/div&gt; &lt;div class="category"&gt; Contact Us &lt;/div&gt; &lt;/nav&gt; &lt;div id="mid-page"&gt; &lt;article&gt; &lt;img id="hero-image" src="https://www.titanvolunteers.com/assets/images/liquid_run_volunteers.jpg"&gt; &lt;h1&gt; Welcome! &lt;/h1&gt; &lt;p&gt; Welcome to Titan Volunteers, your one stop shop for everything related to volunteering for events. Whether you're a volunteer looking for a great event, or an event manager who needs the right tools to collect and track signups for an event, we've got you covered. &lt;/p&gt; &lt;h2&gt; Getting Started &lt;/h2&gt; &lt;p&gt; Volunteers are encouraged to look for events via our &lt;a href="https://www.titanvolunteers.com/volunteers/view_event_list"&gt;sign up to volunteer&lt;/a&gt; page. Volunteer coordinators are encouraged to check out our &lt;a href="https://www.titanvolunteers.com/general/screenshots"&gt;features page&lt;/a&gt; and &lt;a href="https://www.titanvolunteers.com/general/sign_up_company"&lt;/a&gt;create a free account&lt;/a&gt;. &lt;/p&gt; &lt;h2&gt; Need Help? &lt;/h2&gt; &lt;p&gt; If you have any questions or issues with anything on the website, we're here to help! Simply use our Contact Us page and we will assist you right away. &lt;/p&gt; &lt;h2&gt; Spread The Word! &lt;/h2&gt; &lt;p&gt; Please tell your friends about us. We are always looking to help out more people. Thanks a lot and enjoy the site. &lt;/p&gt; &lt;/article&gt; &lt;aside&gt; &lt;h1&gt; Volunteer at these great events &lt;/h1&gt; &lt;div class="sidebar-event"&gt; &lt;div class="event-logo"&gt; &lt;img src="https://www.titanvolunteers.com/uploads/race_logos/E351-Herbalife24-Triathlon-Los-Angeles-2020-1574926089.png"&gt; &lt;/div&gt; &lt;div class="event-description"&gt; &lt;a href="https://www.titanvolunteers.com/volunteers/sign_up_individual/416-Herbalife24-Triathlon-Los-Angeles-2020"&gt; Herbalife24 Triathlon Los Angeles 2020 &lt;/a&gt; &lt;p&gt; Our second annual event provides a one-of-a-kind journey through the heart of LA. Participants start in Venice Beach and end in Downtown Los Angeles at L.A ... &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="sidebar-event"&gt; &lt;div class="event-logo"&gt; &lt;img src="https://gallery.mailchimp.com/b03d2aea85ec993d0dd85362d/images/d2a54ce5-4e35-4c9c-844e-4cc4685e08ef.png"&gt; &lt;/div&gt; &lt;div class="event-description"&gt; &lt;a href="https://www.titanvolunteers.com/volunteers/sign_up_individual/355-SDCCU-OC-Marathon-OC-Half-Marathon"&gt; SDCCU OC Marathon &amp; OC Half Marathon &lt;/a&gt; &lt;p&gt; The SDCCU OC Marathon would not be possible without the support of over 2,000 volunteers that assist throughout the event weekend. We will host and suppor ... &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/aside&gt; &lt;/div&gt; &lt;/div&gt; &lt;footer&gt; &lt;div id="copyright"&gt; Copyright © 2016-2020 TitanVolunteers.com. All Rights Reserved. &lt;/div&gt; &lt;div id="template"&gt; Template by &lt;a href="http://www.os-templates.com/"&gt;OS Templates&lt;/a&gt; &lt;/div&gt; &lt;/footer&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<p>I will focus on the CSS file.</p>\n<p>Keep the CSS file organized, whether it be class first, then ID, then element tags (<code>p</code>, <code>a</code>, <code>nav</code> etc), alphabetical or some other logical organization.</p>\n<p>One of the lines you have is <code>background-color: darkorange;</code>. Without the quotes, it looks odd to me (although allowed by the specification). Also, why is this the one of the few that are not in hex notation?</p>\n<p>Keep the definitions consistent (<code>padding</code> always before <code>display</code> or <code>display</code> always before <code>padding</code> or some other logical grouping and organization):</p>\n<pre><code>.category {\n display: inline-block;\n padding: 18px 25px;\n font-family: sans-serif;\n}\n\n.sidebar-event {\n border-bottom: 1px solid #666666;\n padding: 15px 0;\n display: flex;\n}\n</code></pre>\n<p>In the HTML file, there is one/two extraneous <code>&lt;/a&gt;</code> (at the very end):</p>\n<pre><code>Volunteers are encouraged to look for events via our &lt;a href=&quot;https://www.titanvolunteers.com/volunteers/view_event_list&quot;&gt;sign up to volunteer&lt;/a&gt; page. Volunteer coordinators are encouraged to check out our &lt;a href=&quot;https://www.titanvolunteers.com/general/screenshots&quot;&gt;features page&lt;/a&gt; and &lt;a href=&quot;https://www.titanvolunteers.com/general/sign_up_company&quot;&lt;/a&gt;create a free account&lt;/a&gt;.\n</code></pre>\n<p>This might be a copy/paste error for <code>&lt;a href=&quot;https://www.titanvolunteers.com/general/sign_up_company&quot;&lt;/a&gt;</code>.</p>\n<p>I'm not sure about the legalities of copying the website design and posting it here (see <a href=\"https://codereview.stackexchange.com/help/licensing\">https://codereview.stackexchange.com/help/licensing</a>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T03:09:48.770", "Id": "482906", "Score": "0", "body": "Darkorange wasn't in hex notation because I couldn't use my color grabber tool on it because the color only appears on hover. I was lazy, didn't want to go into Chrome Inspect Element and manually trigger the hover. That stray </a> tag might be my code editor adding it incorrectly when I was typing/pasting stuff. I own that website, I promise not to sue Code Review. Thanks for the tips! For keeping properties in a consistent order, maybe I should just alphabetize them?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T00:03:24.507", "Id": "245847", "ParentId": "245808", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T12:49:08.850", "Id": "245808", "Score": "1", "Tags": [ "html", "css" ], "Title": "Volunteer Signup Website Homepage" }
245808
<p>For practice purposes I implemented a function that checks for palindromes:</p> <pre><code>def palindrom(name): name_reversed = &quot;&quot; for buchstabe in name[::-1]: name_reversed += buchstabe return name.lower() == name_reversed.lower() print(palindrom(&quot;Tom&quot;)) print(palindrom(&quot;Bob&quot;)) </code></pre> <p>How may I improve this code, especially the <code>for</code>-loop?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T14:47:39.307", "Id": "482829", "Score": "2", "body": "Great first question!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T19:33:44.747", "Id": "482874", "Score": "0", "body": "btw what's a buchstabe?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T00:10:47.660", "Id": "482900", "Score": "0", "body": "@VisheshMangla It's German for \"letter\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T05:17:55.107", "Id": "482909", "Score": "0", "body": "Thank's @TheDaleks" } ]
[ { "body": "<h2>Localisation</h2>\n<p>It's fine to localise your user-facing strings (e.g. <code>print('Die Buchstaben in diesem Wort bilden ein Palindrom')</code>, but it is not advisable to write the code itself in a language other than English. For better or worse, English is the de-facto language of programming. Thus, <code>buchstabe</code> would be better as <code>letter</code>.</p>\n<h2>For-loop</h2>\n<p>The loop is not necessary:</p>\n<pre><code> name_reversed = name[::-1]\n</code></pre>\n<p><code>name</code> is a string, which is itself a sequence of one-character strings. Applying a slice, as is done here, reverses the sequence but does not change the type: the output of the expression is still a string.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T09:53:07.420", "Id": "482929", "Score": "1", "body": "Not only that \"the loop is not necessary\", creating an empty string and then concatenating to it in a loop is an anti-pattern in Python since it has a very poor performance." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T14:50:59.907", "Id": "245815", "ParentId": "245813", "Score": "9" } }, { "body": "<p>For your for-loop, you can use <code>reversed(name)</code> instead of <code>name[::-1]</code>. This will increase performance by preventing unnecessary copying by creating a generator instead of another string. However in your case, because you are only checking if the reversed is the same as the original, your function can be even simpler</p>\n<pre><code>def palindrome(name):\n return name.lower() == name[::-1].lower()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T07:36:49.307", "Id": "482920", "Score": "1", "body": "This lowercases two strings - why not lowercase the string on input (i.e. just once) then do the reverse and compare?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T14:25:31.983", "Id": "482974", "Score": "1", "body": "Ideally when comparing strings you would use `.casefold()` instead of `.lower()` since it handles cases such as `ß` -> `ss`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T14:39:55.090", "Id": "482978", "Score": "0", "body": "@QuantumChris yes you are correct, I left it as `.lower()` because I wanted it to look simple (not necessarily perfect) and from what I've seen, no one seems to know about `.casefold()`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T15:45:51.590", "Id": "245820", "ParentId": "245813", "Score": "5" } }, { "body": "<p>@Reinderien and @vlovero have already told whatever could be done but maybe you would also like the <code>reversed</code> function. Also you do not need to <code>lower()</code> your strings twice when you can do it only once. Strings(immutable type) are passed by value in python and doesn't modify the original string since a shallow copy of your string is sent to the function.</p>\n<pre><code>def palindrome(name):\n\n name = name.lower()\n\n return &quot;&quot;.join(reversed(name)) == name #or simply name[::-1] == name\n\n\nprint(palindrome(&quot;Tom&quot;))\nprint(palindrome(&quot;Bob&quot;))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T08:16:55.390", "Id": "482923", "Score": "1", "body": "This also points to another python perfomance issue, you rarely want to do repeated += with strings as strings are immutable so you end up making a copy of the intermediate string each time. Instead if you need to build a string up, add each element to a list then do \"\".join() at the end." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T08:31:43.213", "Id": "482925", "Score": "0", "body": "Yep, you are right." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T09:56:34.627", "Id": "482931", "Score": "1", "body": "This beats every advantage that `reversed` brings to the table (ie the fact it returns an iterator rather than a string). Just use `[::-1]` and get back a reversed string directly instead of needing to use `''.join`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T20:21:27.903", "Id": "483027", "Score": "0", "body": "I 'm not sure how [::-1] works. I can't say anything. When I learned C++ 3-4 years ago I was told strings take 1 byte(256 ascii) and they require contiguous memory and thus they are immutable since if you break the pattern of the string like swap 3rd and 4th character the addresses order ruins. Since python's too implemented in c++ I do believe this slicing wouldn't be as simple as you thing it to be." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T20:23:44.550", "Id": "245836", "ParentId": "245813", "Score": "1" } }, { "body": "<p>It's also possible to work with two pointers. This is not the shortest solution, but it should be very fast and you don't have to store the reversed string.</p>\n<pre><code>def palindrome(name):\n name = name.lower()\n left = 0\n right = len(name) - 1\n while left &lt; right:\n if name[left] != name[right]:\n return False\n left += 1\n right -= 1\n return True\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T12:34:53.780", "Id": "482944", "Score": "0", "body": "This is Python - there are no pointers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T12:36:24.727", "Id": "482945", "Score": "0", "body": "Also, this will not be fast. I encourage you to compare it with `timeit`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T10:40:21.397", "Id": "245862", "ParentId": "245813", "Score": "2" } } ]
{ "AcceptedAnswerId": "245815", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T14:43:23.287", "Id": "245813", "Score": "2", "Tags": [ "python", "python-3.x", "palindrome" ], "Title": "Python palindrome checker function" }
245813
<p>Tried to do my own implementation of reflection(introspection) for using in my next projects.</p> <p>Is it optimized at compile time? If no, how can I improve it?</p> <p>This macro is good interface for adapting structures for reflection?</p> <p>What features can(should) be added to make reflection(introspection) more useful?</p> <p><a href="https://godbolt.org/z/86TM85" rel="nofollow noreferrer">Godbolt</a></p> <p>Macros:</p> <pre><code>#include &lt;tuple&gt; #include &lt;iostream&gt; #include &lt;string_view&gt; #include &lt;boost/preprocessor/comparison/equal.hpp&gt; #include &lt;boost/preprocessor/seq/for_each_i.hpp&gt; #include &lt;boost/preprocessor/seq/subseq.hpp&gt; #include &lt;boost/preprocessor/seq/to_tuple.hpp&gt; #include &lt;boost/preprocessor/seq/transform.hpp&gt; #include &lt;boost/preprocessor/stringize.hpp&gt; #include &lt;boost/preprocessor/tuple/pop_front.hpp&gt; #include &lt;boost/preprocessor/variadic/to_seq.hpp&gt; #include &lt;boost/vmd/is_tuple.hpp&gt; namespace reflection { template&lt;typename T&gt; struct meta { }; } namespace { template&lt;typename T&gt; constexpr bool is_sorted(const std::initializer_list&lt;T&gt; &amp;il) { for (auto it = il.begin(); it != il.end() - 1; it++) { if (*(it + 1) &lt; *it) { return false; } } return true; } }// namespace #define REFLECTION_ADAPT_STRUCT_ARGS(...) __VA_ARGS__ #define REFLECTION_ADAPT_STRUCT_STRIP_PARENTHESES(X) X #define REFLECTION_ADAPT_STRUCT_PASS_PARAMETERS(X) REFLECTION_ADAPT_STRUCT_STRIP_PARENTHESES(REFLECTION_ADAPT_STRUCT_ARGS X) #define REFLECTION_ADAPT_STRUCT_NAME(info) \ BOOST_PP_IF(BOOST_VMD_IS_TUPLE(info), BOOST_PP_IF(BOOST_VMD_IS_TUPLE(BOOST_PP_TUPLE_ELEM(0, info)), BOOST_PP_TUPLE_ELEM(0, BOOST_PP_TUPLE_ELEM(0, info)), BOOST_PP_TUPLE_ELEM(0, info)), info) #define REFLECTION_ADAPT_STRUCT_BASE(info) \ BOOST_PP_IF(BOOST_VMD_IS_TUPLE(info), BOOST_PP_IF(BOOST_VMD_IS_TUPLE(BOOST_PP_TUPLE_ELEM(0, info)), BOOST_PP_IF(BOOST_PP_GREATER(BOOST_PP_TUPLE_SIZE(BOOST_PP_TUPLE_ELEM(0, info)), 1), BOOST_PP_TUPLE_ELEM(1, BOOST_PP_TUPLE_ELEM(0, info)), void), void), void) #define REFLECTION_ADAPT_STRUCT_ATTRIBUTES(info) \ BOOST_PP_IF(BOOST_VMD_IS_TUPLE(info), BOOST_PP_IF(BOOST_PP_GREATER(BOOST_PP_TUPLE_SIZE(info), 1), BOOST_PP_TUPLE_POP_FRONT(info), ()), ()) #define REFLECTION_ADAPT_STRUCT_FIELDS_TRANSFORM(s, data, element) \ BOOST_PP_CAT(field_, REFLECTION_ADAPT_STRUCT_NAME(element)()) #define REFLECTION_ADAPT_STRUCT_FIELDS(info) \ BOOST_PP_SEQ_TO_TUPLE(BOOST_PP_SEQ_TRANSFORM(REFLECTION_ADAPT_STRUCT_FIELDS_TRANSFORM, _, BOOST_PP_SEQ_SUBSEQ(info, 1, BOOST_PP_DEC(BOOST_PP_SEQ_SIZE(info))))) #define REFLECTION_ADAPT_STRUCT_FIELD_OFFSETS_TRANSFORM(s, data, element) \ offsetof(data, REFLECTION_ADAPT_STRUCT_NAME(element)) #define REFLECTION_ADAPT_STRUCT_FIELD_OFFSETS(info) \ BOOST_PP_SEQ_TO_TUPLE(BOOST_PP_SEQ_TRANSFORM(REFLECTION_ADAPT_STRUCT_FIELD_OFFSETS_TRANSFORM, REFLECTION_ADAPT_STRUCT_NAME(BOOST_PP_SEQ_ELEM(0, info)), BOOST_PP_SEQ_SUBSEQ(info, 1, BOOST_PP_DEC(BOOST_PP_SEQ_SIZE(info))))) #define REFLECTION_ADAPT_STRUCT_HEADER(info) \ template&lt;&gt; \ struct reflection::meta&lt;REFLECTION_ADAPT_STRUCT_NAME(info)&gt; { \ static constexpr std::string_view name = BOOST_PP_STRINGIZE(REFLECTION_ADAPT_STRUCT_NAME(info)); \ using type = REFLECTION_ADAPT_STRUCT_NAME(info); \ using base = REFLECTION_ADAPT_STRUCT_BASE(info); \ static_assert(std::is_same_v&lt;base, void&gt; || std::is_base_of_v&lt;base, REFLECTION_ADAPT_STRUCT_NAME(info)&gt;); \ static constexpr auto attributes = std::make_tuple(REFLECTION_ADAPT_STRUCT_PASS_PARAMETERS(REFLECTION_ADAPT_STRUCT_ATTRIBUTES(info))); #define REFLECTION_ADAPT_STRUCT_FIELD(struct_name, info) \ struct BOOST_PP_CAT(field_, REFLECTION_ADAPT_STRUCT_NAME(info)) { \ static constexpr std::string_view name = BOOST_PP_STRINGIZE(REFLECTION_ADAPT_STRUCT_NAME(info)); \ using type = decltype(struct_name::REFLECTION_ADAPT_STRUCT_NAME(info)); \ static constexpr auto reference = &amp;struct_name::REFLECTION_ADAPT_STRUCT_NAME(info); \ static constexpr auto attributes = std::make_tuple(REFLECTION_ADAPT_STRUCT_PASS_PARAMETERS(REFLECTION_ADAPT_STRUCT_ATTRIBUTES(info))); \ }; #define REFLECTION_ADAPT_STRUCT_FOOTER(info) \ static constexpr auto fields = std::make_tuple REFLECTION_ADAPT_STRUCT_FIELDS(info); \ static_assert(is_sorted({REFLECTION_ADAPT_STRUCT_PASS_PARAMETERS(REFLECTION_ADAPT_STRUCT_FIELD_OFFSETS(info))})); \ } \ ; #define REFLECTION_ADAPT_STRUCT_I(r, data, index, info) \ BOOST_PP_IF(BOOST_PP_EQUAL(index, 0), REFLECTION_ADAPT_STRUCT_HEADER(info), REFLECTION_ADAPT_STRUCT_FIELD(data, info)) #define REFLECTION_ADAPT_STRUCT(...) \ BOOST_PP_SEQ_FOR_EACH_I(REFLECTION_ADAPT_STRUCT_I, REFLECTION_ADAPT_STRUCT_NAME(BOOST_PP_VARIADIC_ELEM_0(__VA_ARGS__)), BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)) \ REFLECTION_ADAPT_STRUCT_FOOTER(BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__)) </code></pre> <p>Reflection:</p> <pre><code>namespace { template&lt;typename Tuple, typename F, std::size_t... Indices&gt; constexpr void for_each_impl(Tuple &amp;&amp;tuple, F &amp;&amp;f, std::index_sequence&lt;Indices...&gt;) noexcept { (f(std::get&lt;Indices&gt;(std::forward&lt;Tuple&gt;(tuple))), ...); } template&lt;typename Tuple, typename F&gt; constexpr void for_each(Tuple &amp;&amp;tuple, F &amp;&amp;f) noexcept { const auto N = std::tuple_size&lt;std::remove_reference_t&lt;Tuple&gt;&gt;::value; for_each_impl(std::forward&lt;Tuple&gt;(tuple), std::forward&lt;F&gt;(f), std::make_index_sequence&lt;N&gt;{}); } template &lt;typename T, typename Tuple&gt; struct has_type : std::false_type {}; template &lt;typename T, typename... Tuple&gt; struct has_type&lt;T, std::tuple&lt;Tuple...&gt;&gt; : std::disjunction&lt;std::is_same&lt;T, Tuple&gt;...&gt; {}; }// namespace namespace reflection { template&lt;typename M, typename F&gt; constexpr void meta_for_each_field(F &amp;&amp;f) noexcept { for_each( M::fields, [&amp;f](const auto &amp;field) constexpr noexcept { f(field); }); } template&lt;typename F&gt; constexpr const auto meta_name = F::name; template&lt;typename F&gt; using meta__type = typename F::type; template&lt;typename F&gt; constexpr const auto &amp;meta_attributes = F::attributes; template&lt;typename F, typename T&gt; constexpr const auto &amp;meta_attribute = std::get&lt;T&gt;(meta_attributes&lt;F&gt;); template&lt;typename F, typename T&gt; constexpr auto meta_has_attribute = has_type&lt;T, std::decay_t&lt;decltype(meta_attributes&lt;F&gt;)&gt;&gt;::value; template&lt;typename F&gt; constexpr auto &amp;meta_value(auto &amp;&amp;t) noexcept { return t.*F::reference; } }// namespace reflection </code></pre> <p>Usage:</p> <pre><code>struct A { int a; }; struct B : A { std::string s; bool b; float f; float f1; }; struct Attr1 { std::string_view data; }; struct Attr2 { bool data; }; REFLECTION_ADAPT_STRUCT( ((B, A), Attr1{&quot;test&quot;}), s, b, (f, Attr2{true}), (f1) ) int main() { B b; b.a = 42; b.s = &quot;hello&quot;; b.b = true; b.f = 42.42f; b.f1 = -42; using meta_B = reflection::meta&lt;B&gt;; std::cout &lt;&lt; reflection::meta_name&lt;meta_B&gt; &lt;&lt; std::endl; if constexpr (reflection::meta_has_attribute&lt;meta_B, Attr1&gt;) { std::cout &lt;&lt; &quot;Attr1 &quot; &lt;&lt; reflection::meta_attribute&lt;meta_B, Attr1&gt;.data &lt;&lt; std::endl; } reflection::meta_for_each_field&lt;meta_B&gt;([&amp;b]&lt;typename F&gt;(F) constexpr { if constexpr (reflection::meta_has_attribute&lt;F, Attr2&gt;) { std::cout &lt;&lt; &quot;Attr2 &quot; &lt;&lt; reflection::meta_attribute&lt;F, Attr2&gt;.data &lt;&lt; std::endl; } std::cout &lt;&lt; reflection::meta_name&lt;F&gt; &lt;&lt; &quot; &quot; &lt;&lt; reflection::meta_value&lt;F&gt;(b) &lt;&lt; std::endl; }); } </code></pre> <p>Output:</p> <pre><code>B Attr1 test s hello b 1 Attr2 1 f 42.42 f1 -42 </code></pre> <p>REFLECTION_ADAPT_STRUCT in this case will expand to</p> <pre><code>template&lt;&gt; struct reflection::meta&lt;B&gt; { static constexpr std::string_view name = &quot;B&quot;; using type = B; using base = A; static_assert(std::is_same_v&lt;base, void&gt; || std::is_base_of_v&lt;base, B&gt;); static constexpr auto attributes = std::make_tuple(Attr1{&quot;test&quot;}); struct field_s { static constexpr std::string_view name = &quot;s&quot;; using type = decltype(B::s); static constexpr auto reference = &amp;B::s; static constexpr auto attributes = std::make_tuple(); }; struct field_b { static constexpr std::string_view name = &quot;b&quot;; using type = decltype(B::b); static constexpr auto reference = &amp;B::b; static constexpr auto attributes = std::make_tuple(); }; struct field_f { static constexpr std::string_view name = &quot;f&quot;; using type = decltype(B::f); static constexpr auto reference = &amp;B::f; static constexpr auto attributes = std::make_tuple(Attr2{true}); }; struct field_f1 { static constexpr std::string_view name = &quot;f1&quot;; using type = decltype(B::f1); static constexpr auto reference = &amp;B::f1; static constexpr auto attributes = std::make_tuple(); }; static constexpr auto fields = std::make_tuple(field_s(), field_b(), field_f(), field_f1()); static_assert(is_sorted({offsetof(B, s), offsetof(B, b), offsetof(B, f), offsetof(B, f1)})); }; </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T14:43:34.887", "Id": "245814", "Score": "3", "Tags": [ "c++", "reflection", "boost", "meta-programming", "macros" ], "Title": "Yet another reflection library" }
245814
<p>I am pretty new to C++ and I think I have some problems of keeping code clean and optimized, especially I have problems with writing comments. I just don't know when should I be explaining what I write. Any tips and advices will be hugely appreciated!</p> <p>Here's the code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;initializer_list&gt; #include &lt;stdexcept&gt; template &lt;typename T&gt; class DynamicArray { public: DynamicArray(std::initializer_list&lt;T&gt; elements) : m_size(elements.size()) , m_capacity(elements.size()) , m_array(new T[elements.size()]) { std::copy(elements.begin(), elements.end(), m_array); } DynamicArray() : m_size(0) , m_capacity(1) , m_array(nullptr) { } DynamicArray(DynamicArray&lt;T&gt;&amp;&amp; other) : DynamicArray() { swap(*this, other); } ~DynamicArray() { delete[] m_array; } DynamicArray(const DynamicArray&amp; other) : m_capacity(other.m_capacity) , m_size(other.m_size) , m_array(new T[other.m_capacity]) { std::copy(other.m_array, other.m_array + other.m_size, m_array); } DynamicArray&amp; operator=(DynamicArray other) { swap(*this, other); return *this; } friend void swap(DynamicArray&lt;T&gt;&amp; obj1, DynamicArray&lt;T&gt;&amp; obj2) noexcept { std::swap(obj1.m_size, obj2.m_size); std::swap(obj1.m_capacity, obj2.m_capacity); std::swap(obj1.m_array, obj2.m_array); } void insert(int index, T value) { if (index != m_size) m_check_range(index); if (m_capacity == m_size) resize(m_capacity * 2); m_size++; for (int i = m_size - 2; i &gt;= index; i--) { (*this)[i + 1] = (*this)[i]; } (*this)[index] = value; } T remove(int index) { m_check_range(index); T to_remove = (*this)[index]; for (int i = index; i &lt; m_size - 1; i++) { (*this)[i] = (*this)[i + 1]; } m_size--; return to_remove; } // Resizes array to store n elements. // Guarantees strong exception safety. void resize(int n) { T *temp = new T[n]; m_capacity = n; std::copy(m_array, m_array + m_capacity, temp); delete[] m_array; m_array = temp; } void shrink_to_fit() { resize(m_size); } int size() const { return m_size; } bool empty() const { return m_size == 0; } int capacity() const { return m_capacity; } void append(T value) { insert(m_size, value); } void prepend(T value) { insert(0, value); } T pop(int index) { return remove(m_size - 1); } T front() const { return (*this)[0]; } T back() const { return (*this)[m_size - 1]; } void print() const { for (int i = 0; i &lt; m_size; i++) { std::cout &lt;&lt; m_array[i] &lt;&lt; &quot; &quot;; } std::cout &lt;&lt; std::endl; } T&amp; operator[](int index) { m_check_range(index); return m_array[index]; } const T&amp; operator[](int index) const { m_check_range(index); return m_array[index]; } private: T *m_array; int m_capacity; // Capacity of the array int m_size ; // Number of added elements void m_check_range(int index) const { if (index &lt; 0 || index &gt;= m_size) { throw std::out_of_range(&quot;Index out of range!&quot;); } } }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T15:19:20.760", "Id": "482836", "Score": "1", "body": "Is this for learning purposes, or why aren't you simply use `std::vector` instead of rolling your own class?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T15:20:26.760", "Id": "482837", "Score": "4", "body": "Learning purpouses of course. I want to implement all the data structures by myself." } ]
[ { "body": "<p>While the following list might seem somewhat intimidating, let me first make clear that your class has a nice interface, seems reasonable safe and has a reasonable implementation.</p>\n<h1>Undefined behaviour</h1>\n<p>Unfortunately, your code contains undefined behaviour:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>int main() {\n DynamicArray&lt;int&gt; test;\n test.append(1);\n}\n</code></pre>\n<p>As <code>test</code> uses the default constructor, <code>m_array == nullptr</code>. As <code>m_size &lt; m_capacity</code>, we use <code>nullptr[0] = 1</code> in <code>append</code>, which leads to a segmentation fault on my system.</p>\n<h1>Documentation of implementation details</h1>\n<p>You should document your invariants: when do you need to allocate memory? When <code>m_capacity == 1</code>? Or when <code>m_array == nullptr</code>?</p>\n<h1>Types</h1>\n<p>An <code>index</code> should always be non-negative. Therefore, <code>size_t</code> is more suitable. This also removes the checks for a negative <code>index</code>.</p>\n<h1>Copy vs moves</h1>\n<p>Some of your internal operations use copies. However, those might be costly. Instead, use <code>std::move</code> or <code>std::move_backward</code> to move the elements in your ranges.</p>\n<h1>Tests</h1>\n<p>Add some basic tests for your class. Also, try <a href=\"https://github.com/google/sanitizers\" rel=\"nofollow noreferrer\">AddressSanitizer</a> to find memory issues like this faster.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T17:49:05.997", "Id": "482864", "Score": "0", "body": "So should I test if `m_array == nullptr` each time in `insert()` to fix this? Isn't there some more elegant solution? I also can't initialize `m_array = new T[1]`, because then the move constructor will become very inefficient" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T17:57:44.090", "Id": "482866", "Score": "2", "body": "@Pythenx There are several approaches. I would set `m_capacity = 0` in the constructor and not allocate at all. Note that `resize` also breaks on an empty `DynamicArray`. I would add a new private method `increase_capacity`, which handles `m_capacity == 0` accordingly." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T17:20:28.730", "Id": "245821", "ParentId": "245819", "Score": "3" } }, { "body": "<h2>Observation</h2>\n<p>Array allocated and initializes <code>capacity</code> elements. Which sort of defeats the purpose of having a capacity. The point of using a capacity is that you should not be paying the price of calling the constructor on elements that you don't use.</p>\n<h2>Code Review</h2>\n<p>You should put your code into a namespace.</p>\n<hr />\n<p>This does not seem correct.</p>\n<pre><code> DynamicArray()\n : m_size(0) // Size is zero fine.\n , m_capacity(1) // But a capacity of 1 with no memory allocated!\n // I would say the capacity here is zero\n // as you have no room to add any elements.\n , m_array(nullptr)\n { }\n</code></pre>\n<hr />\n<p>You have accepted the initializer list <code>elements</code> by value.</p>\n<pre><code> DynamicArray(std::initializer_list&lt;T&gt; elements)\n</code></pre>\n<p>So you have already made a copy of the list.</p>\n<p>Since you have made a copy of the list the elements in the list are yours to mutate if you want to so here you could use move semantics rather than copy semantics.</p>\n<pre><code> std::copy(elements.begin(), elements.end(), m_array);\n // RATHER DO THIS\n std::move(elements.begin(), elements.end(), m_array);\n</code></pre>\n<hr />\n<p>Normally you expect to see the move operators marked as <code>noexcept</code></p>\n<pre><code> DynamicArray(DynamicArray&lt;T&gt;&amp;&amp; other)\n</code></pre>\n<p>This allows certain optimizations when you use standard algorithms and containers.</p>\n<hr />\n<p>Normally I write the swap function in terms of the swap method.</p>\n<pre><code> friend void swap(DynamicArray&lt;T&gt;&amp; obj1, DynamicArray&lt;T&gt;&amp; obj2) noexcept\n {\n std::swap(obj1.m_size, obj2.m_size);\n std::swap(obj1.m_capacity, obj2.m_capacity);\n std::swap(obj1.m_array, obj2.m_array);\n }\n\n // I would write it like this:\n\n void swap(DynamicArray&lt;T&gt;&amp; other) noexcept\n {\n using std::swap;\n swap(m_size, other.m_size);\n swap(m_capacity, other.m_capacity);\n swap(m_array, other.m_array);\n }\n friend void swap(DynamicArray&lt;T&gt;&amp; lhs, DynamicArray&lt;T&gt;&amp; rhs) noexcept\n {\n lhs.swap(rhs);\n }\n</code></pre>\n<p>Now methods (like move operators) don't need to call a free function to do a swap. They simply call the method version of swap and get the same affect.</p>\n<hr />\n<p>Nice try.</p>\n<pre><code> // Resizes array to store n elements.\n // Guarantees strong exception safety.\n</code></pre>\n<p>Unfortunately not quite. You can not do anything that may throw while the state of the object has been mutate but not in the final state.</p>\n<pre><code> void resize(int n)\n {\n T *temp = new T[n];\n m_capacity = n; // Mutation here\n\n std::copy(m_array, m_array + m_capacity, temp); // Throw possible here\n delete[] m_array; // Throw possible here.\n m_array = temp; // Final mutation\n }\n</code></pre>\n<p>The way to do this is in three phases:</p>\n<pre><code> void resize(int n)\n {\n // Phase 1: Make your copy.\n T *temp = new T[n];\n std::copy(m_array, m_array + m_capacity, temp);\n\n // Phase 2: Mutate &quot;ALL&quot; your state to final state.\n // You can not call anything that is not `noexcept`\n // This limits you to very basic operations.\n m_capacity = n;\n std::swap(temp, m_array);\n\n // Phase 3: Clean up\n delete[] temp; // Note the swap above.\n }\n</code></pre>\n<p>Note we can simplify this:</p>\n<pre><code> void resize(int n)\n {\n // Phase 1: Make your copy.\n DynamicArray copy(*this, n); // Private constructor\n // Allocates n spaces but copies size\n // objects from the passed item.\n\n // Phase 2: Mutate &quot;ALL&quot; your state to final state.\n // You can not call anything that is not `noexcept`\n // This limits you to very basic operations.\n // Luckily swap method is `noexcept`\n swap(copy);\n\n // Phase 3: Clean up\n // the object copy's destructor will do cleanup.\n }\n</code></pre>\n<hr />\n<p>I am a fan of one liners for methods that are this imple.</p>\n<pre><code> bool empty() const \n {\n return m_size == 0;\n }\n</code></pre>\n<hr />\n<p>Its OK to have a print method. But to make it more C++ like I would also add the <code>operator&lt;&lt;</code> so you can stream it. This means modifying print to take a stream.</p>\n<pre><code> void print(std::ostream&amp; out = std::cout) const\n {\n for (int i = 0; i &lt; m_size; i++)\n {\n out &lt;&lt; m_array[i] &lt;&lt; &quot; &quot;;\n }\n out &lt;&lt; &quot;\\n&quot;;\n }\n friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; str, DynamicArray const&amp; data)\n {\n data.print(str);\n return str;\n }\n</code></pre>\n<hr />\n<p>In the standard library containers that use <code>operator[]</code> make it a non checked interface. It is the responsibility of the user to validate before calling. They add an additional checked interface <code>at()</code> when the user want to validate that the index is range.</p>\n<pre><code> T&amp; operator[](int index)\n {\n m_check_range(index);\n return m_array[index];\n }\n\n\n // Think of this situation\n for(int loop = 0; loop &lt; dA.size(); ++loop) {\n std::cout dA[loop];\n }\n\n // Here we have already guaranteed that the index is within the correct\n // range but we your code still forces an additional check (that we\n // know is never going to fail).\n\n // If I need to check then I call the `at()`version.\n printArrayElement(std::size_t index)\n {\n std::cout &lt;&lt; dA.at(index); // Use checked accesses\n }\n</code></pre>\n<h2>Self Plug</h2>\n<p>I have a lot of other pointers in my articles about writing a vector:</p>\n<p><a href=\"https://lokiastari.com/series/\" rel=\"nofollow noreferrer\">https://lokiastari.com/series/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-29T05:59:11.147", "Id": "483597", "Score": "0", "body": "`initializer_list`s only give const references to their elements, so `std::copy` is equivalent to `std::move` in this case." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T18:31:30.607", "Id": "245830", "ParentId": "245819", "Score": "7" } }, { "body": "<ol>\n<li><code>int</code> does not seem a good choice for sizes and indices which can only be non-negative. <code>std::size_t</code> was introduced for such things.</li>\n</ol>\n<p>1b. When reallocating array you don't check if doubling <code>capacity</code> overflows.</p>\n<ol start=\"2\">\n<li><p>When inserting an element into a saturated array you: 1) reallocate it with double the capacity; 2) copy all existing elements into the new buffer; 3) shift elements past the newly inserted in the new buffer.<br>\nThis hits especially sensitively if you insert an element at array's front. IMO, a slight microoptimisation would be to split current array in two, before and past the newly inserted element, and copy them separately, thus eliminating excess moves of the suffix.</p>\n</li>\n<li><p>While you double the capacity on reallocations, its initial value is only one higher than the initial size, thus causing reallocation on the second insertion already.</p>\n</li>\n<li><p>Using the so-called 'smart pointers', <code>std::unique_ptr</code> would be a good example, would relieve you from manually maintaining the pointers.</p>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T17:43:03.350", "Id": "483005", "Score": "1", "body": "Note you are correct about using `std::size_t`. But your argument (1) about `int` and `std::size` does not hold. If you pass a `-1` to a method that only accepts `std::size_t (unsigned integer type)` then it auto converts to an unsigned value. So it does not provide any real protection against negative values. The reason to use `std::size_t` is not because it is unsigned but because the name conveys meaning. The standard committee has long lamented that it chose `unsigned` for `std::size` (now consider that a mistake, But we are now stuck with it as `unsigned` for backward compatability)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T21:01:32.990", "Id": "483029", "Score": "0", "body": "It's not about protection against negative values (though any value of an unsigned type is, by definition, non-negative). Unsigned types have such notable property as always perfectly defined operations, unlike signed which are not completely defined." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T22:17:00.043", "Id": "483039", "Score": "0", "body": "If it's not about non-negative values. Then why bring it up in your explanation? If the problem is something about not completely defined operations you should add that to your description and explain why it makes the interface bad. At the moment I still don't see anything bad about using an `int` in the interface per se. I would still use `std::size_t` but only because of its documentation purposes." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T20:38:40.463", "Id": "245837", "ParentId": "245819", "Score": "3" } } ]
{ "AcceptedAnswerId": "245830", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T15:16:18.373", "Id": "245819", "Score": "9", "Tags": [ "c++", "array", "reinventing-the-wheel" ], "Title": "DynamicArray class in C++" }
245819
<p>I was inspired by <a href="https://www.youtube.com/watch?v=7LKy3lrkTRA" rel="nofollow noreferrer">this video by Matt Parker</a> to use the <a href="https://en.wikipedia.org/wiki/Farey_sequence" rel="nofollow noreferrer">Farey Sequence</a> to convert a float into a string representation of a fraction, how did I do? How well did I follow F# workflow and patterns (I'm new to the language)? Can it be done better, or rather, how would a &quot;professional&quot; F# developer write this function? Thanks in advance!</p> <pre><code>let toFraction num = let rec farey n0 d0 n1 d1 = let n2 = n0 + n1 let d2 = d0 + d1 match (n2 / d2) with | x when abs (x - num) &lt; 1e-5 -&gt; string n2 + &quot; / &quot; + string d2 | x when x &lt; num -&gt; farey n2 d2 n1 d1 | x when x &gt; num -&gt; farey n0 d0 n2 d2 | _ -&gt; &quot;&quot; // Compiler detects &quot;incomplete pattern matches on this expression without this wildcard, // maybe this is where my method can be improved? farey 0. 1. 1. 1. </code></pre> <p>Additionally, this problem assumes the input <code>num</code> is in the set <code>0 &lt;= num &lt; 1</code></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T17:30:22.817", "Id": "482857", "Score": "0", "body": "Additionally, this problem assumes the input `num` is in the set `0 <= num < 1`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-22T11:20:26.300", "Id": "486222", "Score": "0", "body": "How would it handle `1e-6`?" } ]
[ { "body": "<p>There isn't much to say about the function and algorithm it self. It's an ordinary recursive function - with tail call - which is optimal for recursive functions.</p>\n<p>I don't find a string as return value really useful. Instead I think, I would return a tuple of two integers representing the numerator and denominator</p>\n<pre><code>let toFraction (num: float): (int * int) = etc...\n</code></pre>\n<p>Alternatively you could define a discriminated union as something like:</p>\n<pre><code>type Fraction = Fraction of int * int\n</code></pre>\n<p>... used like:</p>\n<pre><code>let toFraction num =\nif num &lt;= 0.0 || num &gt;= 1.0 then\n failwith &quot;Invalid input&quot;\nelse\n let rec farey n0 d0 n1 d1 =\n let n2 = n0 + n1\n let d2 = d0 + d1\n\n match float n2 / float d2 with\n | x when abs (x - num) &lt; 1e-10 -&gt; Fraction(n2, d2)\n | x when x &lt; num -&gt; farey n2 d2 n1 d1\n | x when x &gt; num -&gt; farey n0 d0 n2 d2\n | _ -&gt; failwith &quot;Something went completely wrong&quot; // just to fulfill the pattern matching - it should never happen\n\n farey 0 1 1 1\n</code></pre>\n<p>and called as</p>\n<pre><code>let (Fraction(num, denom)) = toFraction value\nprintfn &quot;%d / %d&quot; num denom\n</code></pre>\n<p>As shown, I've chosen to run <code>farey</code> with integers instead of floats. You should test if that is more efficient than using floats.</p>\n<hr />\n<blockquote>\n<p><code>match (n2 / d2) with</code></p>\n</blockquote>\n<p>You don't need the parentheses.</p>\n<hr />\n<blockquote>\n<p><code>num</code> is in the set <code>0 &lt;= num &lt; 1</code></p>\n</blockquote>\n<p><code>0 = num</code> is an edge case that is calculated wrongly to</p>\n<pre><code>1 / 100001\n</code></pre>\n<p>If you want <code>0</code> to be included in the domain, you need to start <code>faray</code> with the values <code>-1 0 1 1</code>. Then it will return <code>&quot;0 / 1&quot;</code>.</p>\n<hr />\n<p>Even though you specify in the comment, that it is assumed that <code>num</code> should be between zero and one, you should guard against invalid input, especially because invalid input may result in an infinite recursive loop.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T09:47:37.670", "Id": "245859", "ParentId": "245822", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T17:25:26.973", "Id": "245822", "Score": "5", "Tags": [ "algorithm", "f#" ], "Title": "Converting a float to a fraction as a string" }
245822
<p>I am working on a C# application and I want to support multiple themes, so I wrote a <code>ThemeManager</code> class that can check, load and apply a specific theme. A theme is considered valid, when all of it's member variables are set (not <code>null</code>). If a theme is invalid I want to throw an <code>IncompleteThemeException</code>. However the following code feels a bit stupid...</p> <pre><code>public static void Load(Theme theme) { AccentBrush = theme.AccentBrush ?? throw new IncompleteThemeException(); AccentBrushLight = theme.AccentBrushLight ?? throw new IncompleteThemeException(); WarningBrush = theme.WarningBrush ?? throw new IncompleteThemeException(); WarningBrushLight = theme.WarningBrushLight ?? throw new IncompleteThemeException(); ErrorBrush = theme.ErrorBrush ?? throw new IncompleteThemeException(); ErrorBrushLight = theme.ErrorBrushLight ?? throw new IncompleteThemeException(); MainBackgroundBrush = theme.MainBackgroundBrush ?? throw new IncompleteThemeException(); InactiveDecoratorBrush = theme.InactiveDecoratorBrush ?? throw new IncompleteThemeException(); SecondaryBackgroundBrush = theme.SecondaryBackgroundBrush ?? throw new IncompleteThemeException(); MainTextBrush = theme.MainTextBrush ?? throw new IncompleteThemeException(); SecondaryTextBrush = theme.SecondaryTextBrush ?? throw new IncompleteThemeException(); DefaultPasswordIndicatorBrush = theme.DefaultPasswordIndicatorBrush ?? throw new IncompleteThemeException(); AccentColor = theme.AccentColor ?? throw new IncompleteThemeException(); MainBackgroundColor = theme.MainBackgroundColor ?? throw new IncompleteThemeException(); AccentColorLight = theme.AccentColorLight ?? throw new IncompleteThemeException(); } </code></pre> <p>I thought about maybe using reflection to somehow iterate over all members of the theme instance to check if one of them is null, but I'm unsure what the best solution to this would be in terms of readability, performance and extensibility in the future.</p> <p>How can this be improved?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T18:04:15.917", "Id": "482867", "Score": "2", "body": "_\"I thought about maybe using reflection to somehow iterate over all members of the theme instance ...\"_ Did you make a working attempt already? Usually we don't write new code for you. It seems to be a reasonable idea doing so though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T22:26:44.443", "Id": "482888", "Score": "0", "body": "What type of project are working on ? ASP.NET ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T22:27:49.610", "Id": "482889", "Score": "0", "body": "It's an AvaloniaUI project" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T23:01:27.667", "Id": "482892", "Score": "0", "body": "@FrederikHoeft is Theme class a part of Avalonia ? or is it a user defined class ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T23:08:34.113", "Id": "482894", "Score": "0", "body": "It is a user defined class and it's expected to grow in the future when it comes to the number of public member variables" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T07:31:15.997", "Id": "483074", "Score": "0", "body": "I would advice against throwing an exception at the first missing property. Instead, compile a list of errors and serve that to the user, so they don't have to fix every item one by one until all of them are OK. I recently worked on a project where the remote endpoint threw an exception at the slightest mistake (often caused by bad documentation or a bad implementation on their side), requiring me to contact them for almost every problem. This was a pointlessly elongated process that could have gone way smoother if I'd gotten a list of all errors in one go." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T14:25:19.173", "Id": "483111", "Score": "0", "body": "The easiest (though certainly not _best_) solution here would be to not null check, catch **any** null reference exception, and then throw your `IncompleteThemeException`. There are many things you could've tried here, did you attempt any improvement over the current code?" } ]
[ { "body": "<p>It sure looks somehow clumsy like it is. You should place such stuff deep down the road, meaning you should have a method inside <code>Theme</code> e.g. <code>IsThemeValid() </code> where you can place all these <code>null</code> checks.</p>\n<p>Hence you would only have one method to maintain instead of each occurrence where you pass a <code>Theme</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T22:04:02.643", "Id": "483038", "Score": "1", "body": "I would use the name `IsValid` because `theme.IsThemeValid` is needlessly wordy, and `if (theme.IsValid)` is closer to English. I'd also make it a property since methods are thought by many to be *verbs,* and I wouldn't want to call it `GetIsValid()`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T18:20:12.993", "Id": "245828", "ParentId": "245826", "Score": "6" } }, { "body": "<p>Since your <code>Theme</code> class is a user defined class, you could do something like :</p>\n<pre><code>public class Theme\n{ // Cache the reflection once, then reuse it\n private static readonly PropertyInfo[] _properties = typeof(Theme).GetProperties();\n \n // properties \n \n public Theme() { }\n \n \n public bool IsValid()\n {\n foreach(var property in _properties)\n { \n var value = property.GetValue(this, null);\n\n if (value == null)\n {\n return false;\n }\n }\n \n return true;\n }\n}\n</code></pre>\n<p>Or if you are into Linq (thanks Peter Csala):</p>\n<pre><code>public bool IsValid() =&gt; _properties.All(property =&gt; property.GetValue(this, null) != null);\n</code></pre>\n<p>Then this should go like :</p>\n<pre><code>public static void Load(Theme theme)\n{\n if(!theme.IsValid()) { throw new IncompleteThemeException(); }\n \n AccentBrush = theme.AccentBrush; \n //... etc..\n}\n</code></pre>\n<p><strong>UPDATE :</strong>\n@Blindy suggested to use <code>static</code> reflection and reuse it instead, to avoid creating multiple reflection instances. Which I mostly agree. So, I've updated the code so it can reuse the reflection instance (this including the Linq version as well). (Thanks to Blindy)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T07:33:02.093", "Id": "482919", "Score": "0", "body": "You can also use Linq for validation: `public bool IsValid() => this.GetType().GetProperties().All(property => property.GetValue(this, null) != null)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T07:49:35.043", "Id": "482922", "Score": "1", "body": "@PeterCsala I've included that in my answer, thank." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T15:09:51.090", "Id": "482984", "Score": "2", "body": "Please cache those reflection properties, the way you wrote it it will call very expensive virtual reflection functions over and over every time you call this function (which we don't know how often it is). Use a `static readonly PropertyInfo[] PropertiesToCheck = typeof(Theme).GetProperties();`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T17:07:18.260", "Id": "482996", "Score": "0", "body": "@Blindy thanks mate, I have updated the code." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T23:16:50.960", "Id": "245844", "ParentId": "245826", "Score": "15" } }, { "body": "<p>Two things to think about:</p>\n<ol>\n<li>Could you code this so it's impossible to create an invalid <code>Theme</code> instance thus not having to worry about it in this method?</li>\n<li>How does a consumer know what is invalid about their instance?</li>\n</ol>\n<p>For 1, you could simply have a constructor that takes all of the arguments and throws if any are invalid. A pattern that can also work well is having defaults - that way, a theme can just override part of the default theme rather than having to specify everything.</p>\n<p>For 2, add some context to your exceptions:</p>\n<pre><code>throw new IncompleteThemeException(&quot;Default Password Indicator Brush was not specified&quot;);\n</code></pre>\n<p>However, I would probably lean towards having a mutable builder class with defaults and have a create method there. Consuming it could look like:</p>\n<pre><code>var builder = new ThemeBuilder(Theme.Default /* or existing theme etc. */)\n .WithErrorBrush(myErrorBrush)\n .WithAccentBrush(myAccentBrush);\n\n// Now build it.\nvar theme = builder.Build();\n</code></pre>\n<p>That seems like it would make it easier for consumers to use a <code>Theme</code> as all instances would always be valid and you get the ease of use via the builder class. A nice bonus is that you can add new properties to the theme without breaking consumers. They get a sensible default that they can choose to override if needed. You don't just start throwing <code>IncompleteThemeException</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T12:41:02.643", "Id": "245868", "ParentId": "245826", "Score": "16" } }, { "body": "<p>If you want your <code>Theme</code> to be unaware of what is valid or invalid which makes sense as <code>ThemeLoader</code> may be responsible for defining it, you may try writing something like ef core's fluent api.</p>\n<p>Something like following;</p>\n<pre><code> var validator = new ThemeValidator&lt;Theme&gt;();\n validator.Property(theme =&gt; theme.AccentBrush)\n .IsRequired();\n validator.Propert(theme =&gt; theme.AccentBrushLight)\n .IsRequired();\n validator.validate(theme); // raises exception\n</code></pre>\n<p>This may look like what you do as you have to define for each variable. But i think, this way is open for extension as different conditions other than null check become necessary.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T13:32:20.803", "Id": "245873", "ParentId": "245826", "Score": "3" } }, { "body": "<p>The code is not too far off of the of execution and I take your reflection proposal as a means to work around limitations in the language. This is a fairly straightforward use case for code generation.</p>\n<p>Something <a href=\"https://blogs.u2u.be/peter/post/Using-T4-to-automatically-generate-your-entities\" rel=\"nofollow noreferrer\">like T4</a> or <a href=\"https://doc.postsharp.net/t_postsharp_patterns_contracts_notnullattribute\" rel=\"nofollow noreferrer\">AOP via PostSharp</a> or similar could easily generate the same code without the potential typos, readability, and maintenance issues.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T19:39:39.570", "Id": "245888", "ParentId": "245826", "Score": "3" } }, { "body": "<pre><code>#nullable enable\n\nnamespace Examples {\n\n using System;\n using System.Collections.Generic;\n using System.Diagnostics;\n using System.Linq;\n using System.Reflection;\n\n public class Program {\n\n public static void Main( String[] args ) {\n var theme = new Theme();\n\n var valid = theme.IsValid( out var invalidPropertyNames );\n\n if ( valid ) {\n Debug.WriteLine( $&quot;All properties on {nameof( theme )} are valid.&quot; );\n }\n else {\n foreach ( var name in invalidPropertyNames ) {\n Debug.WriteLine( $&quot;Found invalid property {name}.&quot; );\n }\n }\n }\n\n }\n\n public class Theme {\n\n /// &lt;summary&gt;\n /// Cache the reflection once.\n /// &lt;/summary&gt;\n private static readonly PropertyInfo[] _properties = typeof( Theme ).GetProperties( BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public );\n\n private Int32? Test1 { get; } = 1;\n private Int32? Test2 { get; } = null;\n private Int32? Test3 { get; } = 3;\n\n /// &lt;summary&gt;\n /// Run a check to see if all properties are valid (not null).\n /// &lt;/summary&gt;\n /// &lt;returns&gt;Returns true if all properties do not have a null value.&lt;/returns&gt;\n public Boolean IsValid() =&gt; this.IsValid( out _ );\n\n /// &lt;summary&gt;\n /// Output a list of any invalid (null) properties.\n /// &lt;/summary&gt;\n /// &lt;param name=&quot;InvalidPropertyNames&quot;&gt;&lt;/param&gt;\n /// &lt;returns&gt;Returns true if all properties do not have a null value.&lt;/returns&gt;\n public Boolean IsValid( out IList&lt;String&gt; InvalidPropertyNames ) {\n InvalidPropertyNames = _properties.Where( info =&gt; info.GetValue( this, null ) == null ).Select( info =&gt; info.Name ).ToList();\n\n return !InvalidPropertyNames.Any();\n }\n\n }\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-03T14:26:51.840", "Id": "484265", "Score": "1", "body": "Please review the code given by the OP and describe why your code is better. This is a code review website and code only answers, might not be clear enough for the OP to understand why your code would be better" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-03T13:12:40.737", "Id": "247439", "ParentId": "245826", "Score": "1" } } ]
{ "AcceptedAnswerId": "245844", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T18:00:39.227", "Id": "245826", "Score": "14", "Tags": [ "c#", "null" ], "Title": "C# consecutive and redundant null checks" }
245826
<p>I wrote a function that is supposed to take a format string similar to what <code>date</code> accepts and replace all format specifiers with strings provided by a callback function.</p> <ul> <li>Format specifiers are sequences of a <code>%</code> plus another character; <code>%%</code> for a literal <code>%</code></li> <li>Replace the format specifier with the string provided by the callback function</li> <li>If the callback function returns <code>NULL</code>, no replacement should take place (leave the specifier in)</li> <li>The callback function receives the character following <code>%</code> as argument</li> <li>An optional pointer can be passed through to the callback function</li> <li>If the last character of the format string is <code>%</code>, it should be left as-is</li> <li>The result of the processing is to be placed in the provided buffer</li> <li>If the provided buffer isn't big enough, simply stop processing</li> <li>Always null-terminate the provided buffer, even if it isn't big enough</li> </ul> <p>The function works fine as far as I can tell. I'm looking for any feedback I can get.</p> <pre><code>char* format(const char* format, char *buf, size_t len, char* (*cb)(char c, void* ctx), void *ctx) { const char *curr; // current char from format const char *next; // next char from format size_t i = 0; // index into buf char *ins = NULL; // string to insert // iterate `format`, abort once we exhaust the output buffer for (; *format &amp;&amp; i &lt; (len-1); ++format) { curr = format; next = format+1; if (*curr == '%' &amp;&amp; *next) { if (*next == '%') // escaped %, copy it over and skip { buf[i++] = *format++; continue; } if ((ins = cb(*next, ctx))) // get string to insert { // copy string, again aborting once buffer full while (*ins &amp;&amp; i &lt; (len-1)) { buf[i++] = *ins++; } ++format; continue; } } // any other character, just copy over buf[i++] = *curr; } // null terminate buf[i] = '\0'; return buf; } </code></pre> <p>Examples for (tested) input and output, assuming the callback function always returns <code>FOO</code>:</p> <ul> <li>(empty string): (empty string)</li> <li><code>%</code>: <code>%</code></li> <li><code>%%</code>: <code>%</code></li> <li><code>%f</code>: <code>FOO</code></li> <li><code>%%f</code>: <code>%f</code></li> <li><code>%%%f</code>: <code>%FOO</code></li> <li><code>%%%%f</code>: <code>%%f</code></li> </ul> <p>If so requested, I can provide a link to the context/project where this is used.</p>
[]
[ { "body": "<h1>Return the number of bytes written to <code>buf</code></h1>\n<p>You will notice that functions like <code>sprintf()</code> and <code>strftime()</code> don't return a pointer, but rather an integer that says something about the number of bytes that (would) have been written to the output buffer. This is much more useful than just copying the pointer to <code>buf</code>, which doesn't give the caller any new information.</p>\n<h1>Where is the string returned by the callback function allocated?</h1>\n<p>The callback function returns a pointer to a string. But where is this allocated? Your <code>format()</code> function doesn't call <code>free()</code>, so either the string should be stored in some statically allocated array, or it is allocated on the heap. In the former case, unless you return a pointer to a string literal, your <code>format()</code> function can only be used from one thread at a time. If you return memory that is allocated on the heap, then you have to keep track of it so the caller can clean up all the allocated memory once <code>format()</code> returns.</p>\n<h1>Consider having the callback function write into <code>buf</code> directly</h1>\n<p>To solve the above issue, and to avoid an unncessary copy, you can pass a pointer into the buffer and the remaining size to the callback function, and have the callback function write directly to the buffer. For example:</p>\n<pre><code>char*\nformat(const char* format, char *buf, size_t len, size_t (*cb)(char c, void* ctx, char *buf, size_t len), void *ctx) {\n ...\n if (*curr == '%' &amp;&amp; *next) \n {\n if (*next == '%') // escaped %, copy it over and skip\n {\n buf[i++] = *format++;\n continue;\n }\n i += cb(*next, ctx, buf + i, len - i - 1);\n ++format;\n continue;\n }\n ...\n}\n</code></pre>\n<p>And then your callback function can look like:</p>\n<pre><code>size_t example_cb(char c, void *ctx, char *buf, size_t len) {\n if (c == 'f') {\n if (len &gt; 3)\n len = 3;\n memcpy(buf, &quot;FOO&quot;, len);\n return len;\n }\n\n return 0;\n}\n</code></pre>\n<p>You can create a helper function to avoid repeating the above construction, and to safely write any string to the buffer:</p>\n<pre><code>size_t emplace_string(const char *str, char *buf, size_t max_len) {\n size_t len = strlen(str);\n if (len &gt; max_len)\n len = max_len;\n memcpy(buf, str, len);\n return len;\n}\n \nsize_t example_cb(char c, void *ctx, char *buf, size_t len) {\n switch (c) {\n case 'f':\n return emplace_string(&quot;FOO&quot;, buf, len);\n case 'B':\n return emplace_string(&quot;bar&quot;, buf, len);\n ...\n default:\n return 0;\n } \n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T22:06:54.510", "Id": "245841", "ParentId": "245827", "Score": "2" } }, { "body": "<p>Just a small idea:</p>\n<p><strong>Handle <code>len==0</code></strong></p>\n<p>Just add a little code to gracefully cope with <code>len==0</code> rather than UB.</p>\n<pre><code>char *format(const char* format, char *buf, size_t len, ...) {\n ...\n // 0 -1 is SIZE_MAX!\n // for (; *format &amp;&amp; i &lt; (len-1); ++format) {\n for (; *format &amp;&amp; i + 1 &lt; len); ++format) {\n ...\n // buf[i] = '\\0';\n if (i &lt; len) buf[i] = '\\0';\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T10:26:48.543", "Id": "483082", "Score": "0", "body": "Hm, `if (i < len)` looks a bit dangerous. If the above code accidentily made `i` equal to `len` for example, you no longer write the NUL byte. I'd rather write: `if (len) buf[i] = '\\0'`. And if that would overflow a buffer, then at least something like Valgrind can catch that error where it happens." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T14:27:20.037", "Id": "483112", "Score": "0", "body": "@G.Sliepen Either way gets to not writing a _null character_ when `len == 0`. `i < len` works nice if later code slipped in a signed `i` or `len`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T01:44:38.777", "Id": "245849", "ParentId": "245827", "Score": "2" } } ]
{ "AcceptedAnswerId": "245841", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T18:01:59.993", "Id": "245827", "Score": "4", "Tags": [ "c", "strings", "formatting" ], "Title": "Format string processing similar to date or printf()" }
245827
<p>I've been working on building a Rust version of GNU tar following the spec <a href="https://www.gnu.org/software/tar/manual/html_node/Standard.html" rel="nofollow noreferrer">here</a>.</p> <p>As of right now, I've got the binary accepting a single argument, the path to the file/directory to tar, which is passed to a separate library which does the heavy lifting.</p> <p>The library handles building the Tar record (1 per file), which consists of the header and the file data, if it's not a directory. So far, I can successfully tar single files and multiple files in nested directories, and these tar files can be read by GNU tar as valid (and extracted). I don't have any support for handling sym-links as of yet.</p> <p>Next step is handling untar-ing a given archive.</p> <p>I'm new to rust, having only done small toy projects in the past, and wanted feedback if I'm following Rust conventions or if there's more idiomatic ways to write some of my code before I dive headlong into the next piece of functionality.</p> <p>tar.rs</p> <pre><code>use crate::tar::tar_record::TarRecord; use std::fs::File; use std::io; use std::io::{BufWriter, Write}; use std::path::PathBuf; use walkdir::WalkDir; const TAR_MAGIC: &amp;str = &quot;ustar\0&quot;; const TAR_VERSION: u32 = 0u32; const DEV_MAJOR_VERSION: u64 = 0o0; const DEV_MINOR_VERSION: u64 = 0o0; const BLOCK_SIZE: usize = 512; const NAME_SIZE: usize = 100; const PREFIX_SIZE: usize = 155; mod tar_record; pub struct Tar { files: Vec&lt;TarRecord&gt;, } impl Tar { pub fn new(path: PathBuf) -&gt; Tar { let mut root = path.clone(); root.pop(); let root = root.as_path(); if path.is_dir() { let files: Vec&lt;TarRecord&gt; = WalkDir::new(path) .into_iter() .filter_entry(|e| !crate::is_hidden(e)) .filter_map(|e| e.ok()) .map(|file| TarRecord::new(file.into_path(), root)) .collect(); return Tar { files }; } let record = TarRecord::new(path, root); Tar { files: vec![record], } } pub fn write_tar(&amp;self, path: &amp;mut PathBuf) -&gt; Result&lt;(), io::Error&gt; { let result_path = path; result_path.set_extension(&quot;tar&quot;); let mut writer = BufWriter::new(File::create(result_path).unwrap()); for record in self.files.iter() { record.write_record(&amp;mut writer)? } // write 2 empty blocks to signify end of TAR write!(writer, &quot;{:\0&lt;size$}&quot;, &quot;&quot;, size = BLOCK_SIZE * 2)?; writer.flush() } } </code></pre> <p>tar_record</p> <pre><code>use crate::tar::{ BLOCK_SIZE, DEV_MAJOR_VERSION, DEV_MINOR_VERSION, NAME_SIZE, PREFIX_SIZE, TAR_MAGIC, TAR_VERSION, }; use std::fs::File; use std::io; use std::io::{BufRead, BufReader, Write}; use std::os::macos::fs::MetadataExt; use std::os::unix::fs::PermissionsExt; use std::path::{Path, PathBuf}; use users::{get_group_by_gid, get_user_by_uid}; #[derive(Debug)] pub struct TarRecord { name: String, mode: u32, user_id: u64, group_id: u64, size: u64, // size of the file in bytes modified_time: i64, // Unix time file modified type_flag: TypeFlag, linkname: String, username: String, group_name: String, file: File, } impl TarRecord { pub fn new(path: PathBuf, root: &amp;Path) -&gt; TarRecord { let name = path .strip_prefix(root) .unwrap() .to_str() .unwrap() .to_string(); println!(&quot;a {}&quot;, name); let file = File::open(path.clone()).unwrap(); let metadata = file.metadata().unwrap(); let user_id = metadata.st_uid(); let group_id = metadata.st_gid(); let modified_time = metadata.st_mtime(); let type_flag; let size; if path.is_dir() { size = 0; type_flag = TypeFlag::Directory; } else { size = metadata.len(); type_flag = TypeFlag::ARegFile; } let username = get_user_by_uid(user_id).unwrap(); let group_name = get_group_by_gid(group_id).unwrap(); TarRecord { name, mode: (metadata.permissions().mode() &amp; 0o07777), user_id: user_id as u64, group_id: group_id as u64, size, modified_time, type_flag, linkname: &quot;&quot;.to_string(), username: username.name().to_str().unwrap().to_string(), group_name: group_name.name().to_str().unwrap().to_string(), file, } } pub fn write_record(&amp;self, writer: &amp;mut impl Write) -&gt; Result&lt;(), io::Error&gt; { self.write_header(writer)?; if self.type_flag != TypeFlag::Directory { self.write_file(writer) } else { Ok(()) } } fn write_file(&amp;self, writer: &amp;mut impl Write) -&gt; Result&lt;(), io::Error&gt; { let mut reader = BufReader::new(&amp;self.file); loop { let buf = reader.fill_buf()?; let len = buf.len(); if buf.is_empty() { break; } writer.write_all(buf)?; reader.consume(len) } let residual = BLOCK_SIZE - (self.size as usize % BLOCK_SIZE); if residual != BLOCK_SIZE { write!(writer, &quot;{:\0&lt;size$}&quot;, &quot;&quot;, size = residual)?; } Ok(()) } fn write_header(&amp;self, writer: &amp;mut impl Write) -&gt; Result&lt;(), io::Error&gt; { let mut vec_writer: Vec&lt;u8&gt; = Vec::new(); // Write all elements of the header to the vector write!( vec_writer, &quot;{name:\0&lt;name_size$}{mode:06o} \0{user_id:06o} \0{group_id:06o} \0{size:011o} {modified_time:011o} {checksum}{typeflag}{linkname:\0&lt;100}{magic:\0&lt;6}{version:02}{username:\0&lt;32}{group_name:\0&lt;32}{dev_major:06o} \0{dev_minor:06o} \0{prefix:\0&lt;prefix_size$}&quot;, name = self.name, name_size = NAME_SIZE, mode = self.mode, user_id = self.user_id, group_id = self.group_id, size = self.size, modified_time = self.modified_time, checksum =&quot; &quot;, typeflag = self.type_flag as u8, linkname = self.linkname, magic = TAR_MAGIC, version = TAR_VERSION, username = self.username, group_name = self.group_name, dev_major = DEV_MAJOR_VERSION, dev_minor = DEV_MINOR_VERSION, prefix = &quot;&quot;, prefix_size = PREFIX_SIZE, )?; let sum: u64 = vec_writer.iter().map(|&amp;x| x as u64).sum(); let mut checksum: Vec&lt;u8&gt; = Vec::new(); write!(checksum, &quot;{:06o}\0 &quot;, sum)?; println!(&quot;Length is {}&quot;, vec_writer[148..156].len()); println!(&quot;Length is {}&quot;, checksum[0..].len()); vec_writer[148..156].swap_with_slice(&amp;mut checksum[0..]); writer.write_all(&amp;vec_writer)?; // Header is exactly 12 bytes shy of a single block. // Write 12 nulls to fill the block before moving on. write!(writer, &quot;{:\0&lt;size$}&quot;, &quot;&quot;, size = 12) } } #[repr(u8)] #[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)] #[allow(dead_code)] enum TypeFlag { ARegFile = b'\0', Link = 1, Directory = 5, } </code></pre> <p>Utilities (library root)</p> <pre><code>use walkdir::DirEntry; pub mod tar; fn is_hidden(entry: &amp;DirEntry) -&gt; bool { entry .file_name() .to_str() .map(|s| s.starts_with('.')) .unwrap_or(false) } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T20:39:29.313", "Id": "482879", "Score": "0", "body": "I don't know, but this line seems suspicious to me: \nwrite!(checksum, \"{:06o}\\0 \", sum - 64)?;\n\nWhat is that doing? How many bytes is the checksum ( 2? 8? ). What is going on?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T20:50:15.917", "Id": "482880", "Score": "0", "body": "@GeorgeBarwood Spec defines checksum as `char [8]`, so `u64`. However, it also defines all numerics as \"Each numeric field of width w contains w minus 1 digits, and a null\". So in practice, its 6 bytes (6 bytes for the checksum, 1 null, 1 space). The `sum - 64`, is due to an unknown off-by-one error resulting in my checksum being exactly 64 higher than it should be. And all numerics are written in octal, again based on the spec, hence the `\"{:06o}\" ` formatter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T21:04:03.180", "Id": "482881", "Score": "0", "body": "Reading here \n\nhttps://www.gnu.org/software/tar/manual/html_node/Standard.html\n\nit says \"When calculating the checksum, the chksum field is treated as if it were all blanks.\" Is that the problem perhaps, it looks like you haven't added in the blanks?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T21:21:00.363", "Id": "482882", "Score": "0", "body": "@GeorgeBarwood, I'm writing the header twice, once in memory and the second time to the file. The in-memory is going to a `Vec<u8>`, and the checksum is written as all 0's. This is done in the first (very large) write block. This Vec is then summed to get what the checksum is supposed to be, and the values are swapped into the Vec which is then written to the file." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T21:26:02.623", "Id": "482883", "Score": "2", "body": "It says blanks not zeros? Ascii zero is 48, blank is 32, difference of 16, not sure how that can account of a difference of 64 though. Sorry, I am a bit lost here!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T23:27:03.017", "Id": "482898", "Score": "2", "body": "@GeorgeBarwood you were right, I was using ASCII nulls (0x00), and should have been using ASCII blanks (0xA0). Changing this fixed my off-by-one error. Updating above code to reflect this. Thanks for the insight!" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T19:18:34.513", "Id": "245831", "Score": "4", "Tags": [ "file-system", "rust" ], "Title": "Tar file utility - Rust" }
245831
<p>I just made a small Luhn Checksum validator <a href="https://en.wikipedia.org/wiki/Luhn_algorithm" rel="nofollow noreferrer">Description of Luhn Checksum</a></p> <p>Every number in the Integer gets added individually together, but every second digit gets instead doubled and added. If the doubled number is over ten each individual digit gets added.</p> <p>It works, but is there a way to make it more elegant and maybe more efficient, while maintaining readability?</p> <p>The while loop seems a bit ugly to me, and I'm not completely satisfied with the name getLuhn but I don't know how else to name it.</p> <pre><code>public class Luhn { public static void main(String[] args) { System.out.println(validate(1762483)); } public static boolean validate(int id){ int totalSum = 0; while(id&gt;0){ totalSum += id%10; id /= 10; if(id&gt;0){ totalSum += getLuhn(id%10); id /= 10; } } return (totalSum%10 == 0); } private static int getLuhn(int id){ id *= 2; return id%10 + id/10; } } </code></pre> <p>Every comment is appreciated &lt;3 From cleaner code, over more idiomatic Java, to improvements in performance.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T06:54:32.977", "Id": "482915", "Score": "1", "body": "As the parameter to getLuhn is in the range [0..9] you could replace it with a lookup table, or memoize it. That might be faster." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T06:59:51.037", "Id": "482916", "Score": "1", "body": "You could also look at `java.lang.Integer.toString()` for some tricks to convert a number to individual digits more efficiently." } ]
[ { "body": "<p>Extracting each digit of a number is very similar to the operations performed by the JDK when a number is converted to a String. As many smart people must have spent time optimising this, I used the same code as used by Integer.toString().</p>\n<p>As they did, I used a lookup table to avoid arithmetic operations where the range of input values was small.</p>\n<p>This takes a third of the time on my machine as the original code.</p>\n<p>It is certainly not easier to read or understand, trading clarity for speed.</p>\n<pre><code>package org.example;\n\n\npublic class Luhn {\n /*\n * A table which translates integers from 0..99 to the 10s place digit\n * with the 'Luhn' function applied to it\n */\n static final int[] LuhnDigitTens = {\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,\n 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,\n 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,\n 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,\n 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,\n 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,\n } ;\n\n static final int[] DigitOnes = {\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,\n };\n\n static final int[] Luhn = {\n 0, 2, 4, 6, 8,\n 1, 3, 5, 7, 9\n };\n public static void main(String[] args) {\n // check results are the same\n for (int i = 0; i &lt; 176248300; i++) {\n if (validate2(i) != validate(i)) {\n throw new RuntimeException(&quot;Different at &quot; + i);\n }\n }\n long start = System.currentTimeMillis();\n for (int i = 0; i &lt; 176248300; i++) {\n validate(i);\n }\n System.out.println(System.currentTimeMillis() - start);\n start = System.currentTimeMillis();\n for (int i = 0; i &lt; 176248300; i++) {\n validate2(i);\n }\n System.out.println(System.currentTimeMillis() - start);\n }\n\n public static boolean validate(int id){\n int totalSum = 0;\n while(id&gt;0){\n totalSum += id%10;\n id /= 10;\n if(id&gt;0){\n totalSum += getLuhn(id%10);\n id /= 10;\n }\n }\n return (totalSum%10 == 0);\n }\n\n private static int getLuhn(int id){\n id *= 2;\n return id%10 + id/10;\n }\n\n public static boolean validate2(int i){\n int q, r;\n int totalSum = 0;\n i = -i;\n // Generate two digits per iteration\n while (i &lt;= -100) {\n q = i / 100;\n r = (q * 100) - i;\n i = q;\n totalSum += DigitOnes[r];\n totalSum += LuhnDigitTens[r];\n }\n\n // We know there are at most two digits left at this point.\n q = i / 10;\n r = (q * 10) - i;\n totalSum += r;\n\n // Whatever left is the remaining digit.\n if (q &lt; 0) {\n totalSum += Luhn[-q];\n }\n\n return (totalSum%10 == 0);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T08:25:43.353", "Id": "482924", "Score": "1", "body": "Welcome to Code Review. At the moment you are providing an alternate solution with no explanation or justification and your answer could be deleted, see [how-to-answer](https://codereview.stackexchange.com/help/how-to-answer) for further informations. To avoid this possibility you could explain you reasoning, moreover I have seen you already made significative comments in the OP's question explaining the reason of your implementation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T09:42:19.333", "Id": "482927", "Score": "0", "body": "Thanks @dariosicily, I have improved the explanation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T12:06:29.227", "Id": "482940", "Score": "0", "body": "You are welcome." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T19:14:18.600", "Id": "483016", "Score": "1", "body": "There is a further minor optimization for your algorithm. Place the values in `DigitTens` in the same order they are in `Luhn`, then call `DigitTens[r]` instead of `Luhn[DigitTens[r]]`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T23:27:21.550", "Id": "483043", "Score": "0", "body": "Thanks @tinstaafl, I've added that." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T07:28:30.857", "Id": "245856", "ParentId": "245832", "Score": "1" } }, { "body": "<p>There is not much to improve in your code, it's compact and efficient. These are few suggestions:</p>\n<h2>Input validation</h2>\n<p>When the input number is negative the result is always true. To avoid confusion you can launch an exception.</p>\n<pre class=\"lang-java prettyprint-override\"><code>public static boolean validate(int id) {\n if (id &lt; 0) {\n throw new IllegalArgumentException(&quot;Input cannot be negative.&quot;);\n }\n // ..\n}\n</code></pre>\n<h2>Clarity</h2>\n<p>The Luhn Checksum algorithm is described very well on Wikipedia and by you on your question, but your implementation is not easy to follow. For example:</p>\n<pre class=\"lang-java prettyprint-override\"><code>totalSum += id%10;\n</code></pre>\n<p>Here the last digit of <code>id</code> is added to <code>totalSum</code>. Adding a method (with the explanation of the operation in the name) makes it more readable:</p>\n<pre class=\"lang-java prettyprint-override\"><code>totalSum += getRightMostDigit(id);\n</code></pre>\n<p>Same for:</p>\n<pre class=\"lang-java prettyprint-override\"><code>id /= 10;\n</code></pre>\n<p>This operation removes the last digit of <code>id</code>, which can be changed to:</p>\n<pre class=\"lang-java prettyprint-override\"><code>id = dropRightMostDigit(id);\n</code></pre>\n<p>I would also change the input variable name from <code>id</code> to <code>number</code>, but this is personal taste.</p>\n<h2>Perfomance</h2>\n<p>It's hard to improve performance and keep readability for your method. The only change I would suggest is to replace the <code>getLuhn</code> method with a static array.</p>\n<p>This change makes it two times faster on my machine and gets rid of the additional method.</p>\n<h2>Code refactored</h2>\n<pre class=\"lang-java prettyprint-override\"><code>public static boolean validate(int number) {\n if (number &lt; 0) {\n throw new IllegalArgumentException(&quot;Input cannot be negative.&quot;);\n }\n // Array containing:\n // - for index in [0,4]: the double of the index value \n // - for index in [5,9]: the sum of the digits of the doubled index value. E.g. index = 6 -&gt; 6*2 = 12 -&gt; 1+2 = 3\n int[] luhn = new int[] { 0, 2, 4, 6, 8, 1, 3, 5, 7, 9 };\n \n int totalSum = 0;\n while (number &gt; 0) {\n totalSum += getRightMostDigit(number);\n number = dropRightMostDigit(number);\n if (number &gt; 0) {\n totalSum += luhn[getRightMostDigit(number)];\n number = dropRightMostDigit(number);\n }\n }\n return totalSum % 10 == 0;\n}\n\nprivate static int getRightMostDigit(int number) {\n return number % 10;\n}\n\nprivate static int dropRightMostDigit(int number) {\n return number / 10;\n}\n\n</code></pre>\n<h2>Personal opinion</h2>\n<p>Many implementations of the Luhn Checksum accept a <code>String</code> as input, so they can be used to validate credit cards or simply to operate on numbers bigger than an <code>int</code>. What is the use case of your algorithm?</p>\n<p>The purpose of your implementation can also be included as a comment, it will help others to understand whether they need it or not.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T18:06:00.663", "Id": "483009", "Score": "0", "body": "Thank you for the answer, really appreciate it. For clarity, what do you mean by the behaviour doesn't match the description?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T05:33:21.017", "Id": "483058", "Score": "0", "body": "@elauser I updated my answer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T11:38:32.070", "Id": "483087", "Score": "1", "body": "Great Idea to extract the % and / to functions. Uncle Bob would be proud ;) I'd say that's the max amount of readability. And The perfect use case for a useful comment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T11:56:55.667", "Id": "483088", "Score": "0", "body": "@elauser thanks. Please consider picking an answer when you are satisfied ;)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T10:56:06.750", "Id": "245863", "ParentId": "245832", "Score": "3" } } ]
{ "AcceptedAnswerId": "245863", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T19:27:22.423", "Id": "245832", "Score": "3", "Tags": [ "java", "algorithm" ], "Title": "Improvement to Luhn-Checksum Algorithm in Java" }
245832
<p>I have written this logic for logging, but is getting replication for all fields (last name, DOB,city, state, ZIP, etc). Here only validation logic is going to differ, whereas logging functionality will remain the same.</p> <pre><code>public boolean validFirstName(UserInputDetails record) { if (CommonUtil.isNullOrEmpty(record.getFirstName())) { record.setErrorCode(ErrorCodes.FIRSTNAME_NULL.getErrorCode()); if(record.isDetailedLoggingEnabled()){ Map&lt;String,String&gt; dtlLogMap = new HashMap&lt;&gt;(5); dtlLogMap.put(&quot;transId&quot;,String.valueOf(record.getTransactionId())); dtlLogMap.put(&quot;firstName&quot;,record.getFirstName()); dtlLogMap.put(&quot;validationName&quot;,&quot;VALID_FIRSTNAME_CHECK&quot;); dtlLogMap.put(&quot;validationStatus&quot;,&quot;Errored&quot;); dtlLogMap.put(&quot;errorCode&quot;,record.getErrorCode()); DetailedLogger.log(dtlLogMap); } return false; } if ( record.getFirstName().length() &gt;=50) { record.setErrorCode(ErrorCodes.FIRSTNAME_INVALID_LENGTH.getErrorCode()); if(record.isDetailedLoggingEnabled()){ Map&lt;String,String&gt; dtlLogMap = new HashMap&lt;&gt;(6); dtlLogMap.put(&quot;transId&quot;,String.valueOf(record.getTransactionId())); dtlLogMap.put(&quot;firstName&quot;,record.getFirstName()); dtlLogMap.put(&quot;firstNameLength&quot;,returnStringifNotNull(record.getFirstName().length())); dtlLogMap.put(&quot;validationName&quot;,&quot;VALID_FIRSTNAME_LENGTH_CHECK&quot;); dtlLogMap.put(&quot;validationStatus&quot;,&quot;Errored&quot;); dtlLogMap.put(&quot;errorCode&quot;,record.getErrorCode()); DetailedLogger.log(dtlLogMap); } return false; } if(record.isDetailedLoggingEnabled()){ Map&lt;String,String&gt; dtlLogMap = new HashMap&lt;&gt;(4); dtlLogMap.put(&quot;transId&quot;,String.valueOf(record.getTransactionId())); dtlLogMap.put(&quot;firstName&quot;,record.getFirstName()); dtlLogMap.put(&quot;validationName&quot;,&quot;VALID_FIRSTNAME_CHECK&quot;); dtlLogMap.put(&quot;validationStatus&quot;,&quot;passed&quot;); DetailedLogger.log(dtlLogMap); } return true; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T05:02:27.783", "Id": "482908", "Score": "3", "body": "i'm not sure how to say but have you considered putting some logic in methods?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T06:18:47.853", "Id": "482912", "Score": "0", "body": "Adding key value combination in hashmap and logging will be the same for validation success Or failure. Only key and value will be change... is there any way to write this code in jeneric method to avoid duplication of code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T06:34:58.240", "Id": "482913", "Score": "3", "body": "`if (record.getFirstName().length() <=50) { return false; }` Are you sure you want to fail when a first name is shorter than 50 characters?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T13:02:01.640", "Id": "482953", "Score": "0", "body": "One side-note: creating a `HashMap` with size `n` for `n` elements is *not* what you want, as the map will be resized after reaching the size `n * 0.75`, i.e. you will *always* have a resize operation of the map. As this is microoptimization anyway, just leave the parameter out." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T13:22:33.170", "Id": "482955", "Score": "1", "body": "Have you tested this code? Does it produce the results you expect? If the results are wrong, it's not ready for review yet." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T13:32:32.100", "Id": "482958", "Score": "0", "body": "@marc I changed to >" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T13:35:11.863", "Id": "482959", "Score": "0", "body": "@mtj it will populate only n key and value pair , I will not add it after that" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T14:41:48.010", "Id": "482979", "Score": "0", "body": "@Vasanth Create a map with size 5, add 5 elements (which you do) step into the put-method calls in a debugger, and see that the map resizes. Then, read the docs again, to gather the meanings of size and load factor in a hash map." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T05:38:40.190", "Id": "483060", "Score": "0", "body": "`returnStringifNotNull(record.getFirstName().length())` looks *wrong*, in addition to *uncalled for* after `isNullOrEmpty(record.getFirstName())`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T08:58:08.413", "Id": "483182", "Score": "2", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T09:03:59.683", "Id": "483183", "Score": "0", "body": "@Zeta I am not changed the question , I am just re-frame the question and added some more method for clear understanding ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T09:05:33.070", "Id": "483185", "Score": "0", "body": "@greybeard please ignore that , that is typo , i just mock it manually for review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T09:06:34.153", "Id": "483186", "Score": "0", "body": "@mtj i have removed the parameter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T09:29:41.397", "Id": "483187", "Score": "0", "body": "@Zeta thanks for having a look at it..." } ]
[ { "body": "<p>as mentioned in the comments it might be helpful to <strong><a href=\"https://refactoring.guru/extract-method\" rel=\"nofollow noreferrer\">extract methods</a></strong> to remove redundant code - you might want to read a more detailed explanation on <a href=\"https://www.tutorialspoint.com/java/java_methods.htm\" rel=\"nofollow noreferrer\">&quot;methods in java&quot;</a> to gain basic knowledge on methods.</p>\n<p>tl;dr</p>\n<p><em>&quot;A Java method is a collection of statements that are grouped together to perform an operation&quot;</em></p>\n<p>let's collect your your statements that all checks have in common</p>\n<pre><code>Map&lt;String,String&gt; dtlLogMap = new HashMap&lt;&gt;(4);\ndtlLogMap.put(&quot;transId&quot;,String.valueOf(record.getTransactionId()));\ndtlLogMap.put(&quot;firstName&quot;,record.getFirstName());\ndtlLogMap.put(&quot;validationName&quot;,&quot;VALID_FIRSTNAME_CHECK&quot;);\ndtlLogMap.put(&quot;validationStatus&quot;,&quot;passed&quot;);\nDetailedLogger.log(dtlLogMap);\n</code></pre>\n<p>we can extract a lot of stuff here into a method named <code>Map&lt;String,String&gt; createLog(Record record, String checkResult)</code> - noteworthy is, that we only group things together, that belong together - we do not (yet) extract the logging action - to maintain the <strong><a href=\"https://clean-code-developer.com/grades/grade-2-orange/#Single_Responsibility_Principle_SRP\" rel=\"nofollow noreferrer\">Single Responsibility-principle</a></strong>. That makes it also a lot easier to find proper method names (instead of creating an obfucasting method name <code>createAndPrintLog()</code>)</p>\n<pre><code>private Map&lt;String,String&gt; createLog(Record record, String checkName, String checkResult){\n Map&lt;String,String&gt; logs= new HashMap&lt;&gt;(4);\n logs.put(&quot;transId&quot;,String.valueOf(record.getTransactionId()));\n logs.put(&quot;firstName&quot;,record.getFirstName());\n logs.put(&quot;validationName&quot;,checkName);\n logs.put(&quot;validationStatus&quot;,checkResult);\n return logs;\n}\n</code></pre>\n<p>note that a method has parameters that let you control the output of the method: the parameters should be self-explaining (<a href=\"https://clean-code-developer.com/grades/grade-4-green/#Tell_dont_ask\" rel=\"nofollow noreferrer\"><strong>Tell - dont Ask</strong></a>)</p>\n<p>we can now apply this method in your checks and remove redundant code</p>\n<pre><code>...\nif(record.isDetailedLoggingEnabled()){\n //here: method call instead of redundancy\n Map&lt;String,String&gt; dtlLogMap = createLogs(record,&quot;VALID_FIRSTNAME_CHECK&quot;, &quot;Errored&quot;);\n dtlLogMap.put(&quot;errorCode&quot;,record.getErrorCode());\n DetailedLogger.log(dtlLogMap);\n}\n...\n</code></pre>\n<h2>use more methods to remove more reduncancy!</h2>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T08:02:14.480", "Id": "483175", "Score": "0", "body": "Its correct for single field ie firstName, If we apply this method ie createLogs() for more then one fields (last name, DOB,city, state,zip code) - there should be mapping, So question is how i can write the Generic method to receive the field name,field value ,error code ,message , transaction id ,status ? these arguments may grow or shrink based on validation pass or failure . Please refer the code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T08:18:00.727", "Id": "483177", "Score": "0", "body": "thanks for pointing that part out! these requirements were not described clearly in your question **Believe in your ideas!** - if you feel you need some kind of Mapping then create a `Mapper`. Always keep in mind to [segregate concerns](https://clean-code-developer.com/grades/grade-2-orange/#Separation_of_Concerns_SoC): Things from the Model (in your case: `UserInputDetails`) should know how to create its proper log, while the results don't belong to that model" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T07:02:59.263", "Id": "245855", "ParentId": "245833", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "14", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T19:34:49.593", "Id": "245833", "Score": "3", "Tags": [ "java", "logging" ], "Title": "User details logging" }
245833
<p>I'm posting my code for a LeetCode problem. If you'd like to review, please do so. Thank you for your time!</p> <h3>Problem</h3> <p>You have a very large square wall and a circular dartboard placed on the wall. You have been challenged to throw darts into the board blindfolded. Darts thrown at the wall are represented as an array of points on a 2D plane.</p> <p>Return the maximum number of points that are within or lie on any circular dartboard of radius <code>r</code>.</p> <h3>Example 1:</h3> <p><a href="https://i.stack.imgur.com/u3LrF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u3LrF.png" alt="enter image description here" /></a></p> <pre><code>Input: points = [[-2,0],[2,0],[0,2],[0,-2]], r = 2 Output: 4 Explanation: Circle dartboard with center in (0,0) and radius = 2 contain all points. </code></pre> <h3>Example 2:</h3> <p><a href="https://i.stack.imgur.com/rJQMu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rJQMu.png" alt="enter image description here" /></a></p> <pre><code>Input: points = [[-3,0],[3,0],[2,6],[5,4],[0,9],[7,8]], r = 5 Output: 5 Explanation: Circle dartboard with center in (0,4) and radius = 5 contain all points except the point (7,8). </code></pre> <h3>Example 3:</h3> <pre><code>Input: points = [[-2,0],[2,0],[0,2],[0,-2]], r = 1 Output: 1 </code></pre> <h3>Example 4:</h3> <pre><code>Input: points = [[1,2],[3,5],[1,-1],[2,3],[4,1],[1,3]], r = 2 Output: 4 </code></pre> <h3>Constraints:</h3> <ul> <li><span class="math-container">\$1 &lt;= points.length &lt;= 100\$</span></li> <li><span class="math-container">\$points[i].length == 2\$</span></li> <li><span class="math-container">\$-10^4 &lt;= points[i][0], points[i][1] &lt;= 10^4\$</span></li> <li><span class="math-container">\$1 &lt;= r &lt;= 5000\$</span></li> </ul> <h3>Inputs</h3> <pre><code>[[-2,0],[2,0],[0,2],[0,-2]] 2 [[-3,0],[3,0],[2,6],[5,4],[0,9],[7,8]] 5 [[-2,0],[2,0],[0,2],[0,-2]] 1 [[1,2],[3,5],[1,-1],[2,3],[4,1],[1,3]] 2 [[5738,-1857],[2264,1769],[5944,-9368],[3459,-9748],[8624,159],[985,-5051],[-8275,-9383],[7923,-591],[-8121,4781],[-9594,938],[-24,223],[9084,-4952],[-6787,5289],[4879,-4],[3998,369],[-7996,-7220],[-414,3638],[5092,4406],[1454,2965],[9210,-6966],[-4111,-8614],[4507,2213],[-4112,3699],[-9956,-2420],[7246,6775],[1164,5762],[6778,-5099],[-6655,-9514],[-2778,-7768],[6973,-7458],[7334,-1124],[4840,-8991],[941,5018],[1937,3608],[6807,6159],[763,1355],[-9776,-5074],[1107,1822],[-6779,-5400],[4219,-5674],[9823,-4630],[-9172,-7089],[-1875,162],[2267,1685],[4161,-1638],[-2475,9697],[-5367,-952],[-7786,4367],[839,1415],[8832,-4596],[-3843,7126],[-4242,8513],[-7883,1951],[9105,8342],[-4109,-4510],[1875,3149],[-7759,-6505],[1764,1624],[-6917,-6653],[-1438,6916],[-758,-3300],[3694,6699],[6135,2622],[7485,8284],[-9616,-8501],[408,4743],[8939,-731],[9208,-3748],[6059,-2587],[8403,4154],[2361,5708],[-3958,-3943],[-1746,-9082],[2864,-3231],[-4940,8519],[-8786,7898],[5154,-3647],[9011,8170],[-205,8717],[... 4411 </code></pre> <h3>Outputs</h3> <pre><code>4 5 1 4 23 </code></pre> <h3>Code</h3> <pre><code>#include &lt;cstdint&gt; #include &lt;cmath&gt; #include &lt;vector&gt; #include &lt;utility&gt; #include &lt;algorithm&gt; class Solution { static constexpr double precision = 1e-6; double R; static struct Point { double x; double y; }; std::vector&lt;Point&gt; point; public: std::int_fast32_t numPoints( const std::vector&lt;std::vector&lt;int&gt;&gt;&amp; points, const std::int_fast32_t r ) { const std::size_t length = points.size(); R = (double) r; point.resize(length); for (std::size_t len = 0; len &lt; length; ++len) { point[len].x = points[len][0]; point[len].y = points[len][1]; } std::int_fast32_t max_darts = 1; for (std::size_t i = 0; i &lt; length; ++i) { for (std::size_t j = 0; j &lt; length; ++j) { if (i == j || getEuclideanDistance(point[i], point[j]) - 2 * R &gt; precision) { continue; } std::int_fast32_t curr_darts = 0; const auto center = getDartboardCenter(point[i], point[j]); for (std::size_t k = 0; k &lt; length; ++k) { if (getEuclideanDistance(point[k], center.first) - R &lt; precision) { ++curr_darts; } } max_darts = std::max(max_darts, curr_darts); } } return max_darts; } private: double getEuclideanDistance( const Point&amp; a, const Point&amp; b ) { return std::sqrt(std::pow(a.x - b.x, 2) + std::pow(a.y - b.y, 2)); } std::pair&lt;Point, Point&gt; getDartboardCenter( const Point&amp; a, const Point&amp; b ) { Point mid; std::pair&lt;Point, Point&gt; center; mid.x = (a.x + b.x) / 2; mid.y = (a.y + b.y) / 2; const double theta = std::atan2(a.y - b.y, b.x - a.x); const double temp_point = getEuclideanDistance(a, b) / 2; const double euc_dist = std::sqrt(std::pow(R, 2) - std::pow(temp_point, 2)); center.first.x = mid.x - euc_dist * std::sin(theta); center.first.y = mid.y - euc_dist * std::cos(theta); // For optimization, later! center.second.x = mid.x + euc_dist * std::sin(theta); center.second.y = mid.y + euc_dist * std::cos(theta); return center; } }; </code></pre> <h3>References</h3> <ul> <li><p><a href="https://leetcode.com/problems/maximum-number-of-darts-inside-of-a-circular-dartboard/" rel="nofollow noreferrer">Problem</a></p> </li> <li><p><a href="https://leetcode.com/problems/maximum-number-of-darts-inside-of-a-circular-dartboard/discuss/" rel="nofollow noreferrer">Discuss</a></p> </li> <li><p><a href="https://leetcode.com/problems/maximum-number-of-darts-inside-of-a-circular-dartboard/solution/" rel="nofollow noreferrer">Solution</a></p> </li> </ul>
[]
[ { "body": "<h1>Don't change the API</h1>\n<p>The LeetCode problem gives you the public API:</p>\n<pre><code>int numPoints(vector&lt;vector&lt;int&gt;&gt;&amp; points, int r)\n</code></pre>\n<p>Don't change <code>int</code> to <code>int_fast32_t</code>, since this might cause your function to become incompatible with what LeetCode expects. If you want to use <code>int_fast32_t</code> internally, that is fine.</p>\n<h1>Make functions that do not access member variables <code>static</code></h1>\n<p>This applies to <code>getEuclideanDistance()</code>.</p>\n<h1>Make functions that do not change member variables <code>const</code></h1>\n<p>This applies to <code>getDartboardCenter()</code>.</p>\n<h1>Naming things</h1>\n<p>It's one of the two hard things in computer science, along with cache invalidation and off-by-one errors.</p>\n<p>Your function <code>getDartboardCenter()</code> does not in fact return the center of the dartboard. It just returns two guesses based on two input points. And only one element of the pair is ever used. Maybe <code>getCandidateCenter()</code> is a better name.</p>\n<p>Also, <code>temp_point</code> is not a point, it is a distance, so name it <code>temp_distance</code> or <code>temp_dist</code>.</p>\n<h1>Use <code>std::hypot()</code></h1>\n<p>The standard library already has a function for you that can help you calculate the euclidian distance: <a href=\"https://en.cppreference.com/w/cpp/numeric/math/hypot\" rel=\"nofollow noreferrer\"><code>std::hypot()</code></a>. So:</p>\n<pre><code>static double getEuclideanDistance(const Point&amp; a, const Point&amp; b) {\n return std::hypot(a.x - b.x, a.y - b.y);\n}\n</code></pre>\n<p>But even better:</p>\n<h1>Avoid unnecessary floating point math</h1>\n<p>You have already noticed that floating point math is not infinitely precise. However, integer math is (as long as you don't exceed the maximum value an integer variable can hold). You can check if a given point with integer coordinates is within a circle centered at the origin with radius <code>R</code> by writing:</p>\n<pre><code>int R; // radius\nint x, y; // point coordinates\n\nif (x * x + y * y &lt;= R * R) {\n // point x, y is inside the circle\n}\n</code></pre>\n<p>There might be more math that can be done using integers.</p>\n<h1>Simplify your trigonometry</h1>\n<p>Given two doubles, <code>dx</code> and <code>dy</code>, and:</p>\n<pre><code>double theta = std::atan2(dy, dx);\ndouble dist = std::hypot(dy, dx);\n</code></pre>\n<p>Then <code>std::sin(theta) * dist == dy</code>, and <code>std::cos(theta) * dist == dx</code>. This means that you didn't need to use these trigonometric functions at all, and could have written:</p>\n<pre><code>const double temp_dist = getEuclideanDistance(a, b);\nconst double euc_dist = std::sqrt(std::pow(R, 2) - std::pow(temp_dist / 2, 2));\nconst double scaled_dist = euc_dist / temp_dist;\ncenter.first.x = mid.x - scaled_dist * a;\ncenter.first.y = mid.y - scaled_dist * b;\n</code></pre>\n<p>This could be further simplified a bit.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T22:51:34.427", "Id": "245843", "ParentId": "245840", "Score": "2" } } ]
{ "AcceptedAnswerId": "245843", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T22:04:22.740", "Id": "245840", "Score": "2", "Tags": [ "c++", "beginner", "algorithm", "programming-challenge", "c++17" ], "Title": "LeetCode 1453: Maximum Number of Darts Inside of a Circular Dartboard" }
245840
<p>The idea of a defer statement or a ScopeGuard has, for a while, been something I have wanted in C++, but up until recently I had always assumed that C++ did not have it. However, that's when I found <a href="https://en.cppreference.com/w/cpp/experimental/scope_exit" rel="noreferrer"><code>std::experimental::scope_exit</code></a> but it had a problem, which was that it had not been implemented in any of the compilers I use. As a result, I decided to implement it.</p> <p><code>scope.hh</code></p> <pre><code>#ifndef SCOPE_SCOPE_HH #define SCOPE_SCOPE_HH #include &lt;utility&gt; #include &lt;new&gt; #include &lt;concepts&gt; namespace turtle { template&lt;typename EF&gt; requires std::invocable&lt;EF&gt; &amp;&amp; requires(EF x) {{ x() } -&gt; std::same_as&lt;void&gt;; } struct scope_exit { constexpr scope_exit operator=(const scope_exit &amp;) = delete; constexpr scope_exit operator=(scope_exit &amp;&amp;) = delete; template&lt;typename Fn, typename = std::enable_if_t&lt;!std::is_same_v&lt;std::remove_cvref_t&lt;Fn&gt;, scope_exit&gt;, int&gt;, typename = std::enable_if_t&lt;std::is_constructible_v&lt;EF, Fn&gt;, int&gt;&gt; constexpr explicit scope_exit(Fn &amp;&amp;fn) noexcept(std::is_nothrow_constructible_v&lt;EF, Fn&gt; || std::is_nothrow_constructible_v&lt;EF, Fn &amp;&gt;) { set_functor(std::forward&lt;Fn&gt;(fn)); } template&lt;typename = std::disjunction&lt;std::enable_if_t&lt;std::is_nothrow_move_constructible_v&lt;EF&gt;, int&gt;, std::enable_if_t&lt;std::is_nothrow_move_constructible_v&lt;EF&gt;, int&gt;&gt;&gt; constexpr scope_exit(scope_exit &amp;&amp;other) noexcept(std::is_nothrow_move_constructible_v&lt;EF&gt; || std::is_nothrow_copy_constructible_v&lt;EF&gt;) { set_functor_move(std::move(other)); } constexpr scope_exit(const scope_exit &amp;) = delete; constexpr ~scope_exit() noexcept { /* if active, call functor and then destroy it */ if (!m_released) { m_functor(); m_released = true; } m_functor.~EF(); } constexpr void release() noexcept { m_released = true; } constexpr const auto&amp; exit_function() noexcept { return m_functor; } private: union { EF m_functor; char m_functor_bytes[sizeof(EF)] = {}; }; bool m_released{false}; template&lt;typename Fn&gt; constexpr void set_functor(Fn &amp;&amp;fn) noexcept(std::is_nothrow_constructible_v&lt;EF, Fn&gt; || std::is_nothrow_constructible_v&lt;EF, Fn &amp;&gt;) { if constexpr(!std::is_lvalue_reference_v&lt;Fn&gt; &amp;&amp; std::is_nothrow_constructible_v&lt;EF, Fn&gt;) { ::new(&amp;m_functor) EF(std::forward&lt;Fn&gt;(fn)); } else { try { ::new(&amp;m_functor) EF(fn); } catch (...) { m_released = true; fn(); throw; } } } constexpr void set_functor_move(scope_exit &amp;&amp;other) noexcept(std::is_nothrow_move_constructible_v&lt;EF&gt; || std::is_nothrow_copy_constructible_v&lt;EF&gt;) { /* only preform construction if other is active */ if (!other.m_released) { if constexpr(std::is_nothrow_move_constructible_v&lt;EF&gt;) { ::new(&amp;m_functor) EF(std::forward&lt;EF&gt;(other.m_functor)); } else { try { ::new(&amp;m_functor) EF(other.m_functor); } catch (...) { m_released = true; other.m_functor(); other.release(); throw; } } other.release(); } } }; template&lt;typename EF&gt; scope_exit(EF) -&gt; scope_exit&lt;EF&gt;; } namespace turtle { template&lt;typename EF&gt; requires std::invocable&lt;EF&gt; &amp;&amp; requires(EF x) {{ x() } -&gt; std::same_as&lt;void&gt;; } struct scope_fail { constexpr scope_fail operator=(const scope_fail &amp;) = delete; constexpr scope_fail operator=(scope_fail &amp;&amp;) = delete; template&lt;typename Fn, typename = std::enable_if_t&lt;!std::is_same_v&lt;std::remove_cvref_t&lt;Fn&gt;, scope_fail&gt;, int&gt;, typename = std::enable_if_t&lt;std::is_constructible_v&lt;EF, Fn&gt;, int&gt;&gt; constexpr explicit scope_fail(Fn &amp;&amp;fn) noexcept(std::is_nothrow_constructible_v&lt;EF, Fn&gt; || std::is_nothrow_constructible_v&lt;EF, Fn &amp;&gt;) : m_uncaught_exceptions(std::uncaught_exceptions()) { set_functor(std::forward&lt;Fn&gt;(fn)); } template&lt;typename = std::disjunction&lt;std::enable_if_t&lt;std::is_nothrow_move_constructible_v&lt;EF&gt;, int&gt;, std::enable_if_t&lt;std::is_nothrow_move_constructible_v&lt;EF&gt;, int&gt;&gt;&gt; constexpr scope_fail(scope_fail &amp;&amp;other) noexcept(std::is_nothrow_move_constructible_v&lt;EF&gt; || std::is_nothrow_copy_constructible_v&lt;EF&gt;) : m_uncaught_exceptions(other.m_uncaught_exceptions) { set_functor_move(std::move(other)); } constexpr scope_fail(const scope_fail &amp;) = delete; constexpr ~scope_fail() noexcept { /* if active and an exception happened, call functor. */ if (!m_released &amp;&amp; std::uncaught_exceptions() &gt; m_uncaught_exceptions) { m_functor(); } /* destroy functor */ m_functor.~EF(); } constexpr void release() noexcept { m_released = true; } constexpr const auto&amp; exit_function() noexcept { return m_functor; } private: union { EF m_functor; char m_functor_bytes[sizeof(EF)] = {}; }; bool m_released{false}; int m_uncaught_exceptions{0}; template&lt;typename Fn&gt; constexpr void set_functor(Fn &amp;&amp;fn) noexcept(std::is_nothrow_constructible_v&lt;EF, Fn&gt; || std::is_nothrow_constructible_v&lt;EF, Fn &amp;&gt;) { if constexpr(!std::is_lvalue_reference_v&lt;Fn&gt; &amp;&amp; std::is_nothrow_constructible_v&lt;EF, Fn&gt;) { ::new(&amp;m_functor) EF(std::forward&lt;Fn&gt;(fn)); } else { try { ::new(&amp;m_functor) EF(fn); } catch (...) { m_released = true; fn(); throw; } } } constexpr void set_functor_move(scope_fail &amp;&amp;other) noexcept(std::is_nothrow_move_constructible_v&lt;EF&gt; || std::is_nothrow_copy_constructible_v&lt;EF&gt;) { /* only preform construction if other is active */ if (!other.m_released) { if constexpr(std::is_nothrow_move_constructible_v&lt;EF&gt;) { ::new(&amp;m_functor) EF(std::forward&lt;EF&gt;(other.m_functor)); } else { try { ::new(&amp;m_functor) EF(other.m_functor); } catch (...) { m_released = true; other.m_functor(); other.release(); throw; } } other.release(); } } }; template&lt;typename EF&gt; scope_fail(EF) -&gt; scope_fail&lt;EF&gt;; } namespace turtle { template&lt;typename EF&gt; requires std::invocable&lt;EF&gt; &amp;&amp; requires(EF x) {{ x() } -&gt; std::same_as&lt;void&gt;; } struct scope_success { constexpr scope_success operator=(const scope_success &amp;) = delete; constexpr scope_success operator=(scope_success &amp;&amp;) = delete; template&lt;typename Fn, typename = std::enable_if_t&lt;!std::is_same_v&lt;std::remove_cvref_t&lt;Fn&gt;, scope_success&gt;, int&gt;, typename = std::enable_if_t&lt;std::is_constructible_v&lt;EF, Fn&gt;, int&gt;&gt; constexpr explicit scope_success(Fn &amp;&amp;fn) noexcept(std::is_nothrow_constructible_v&lt;EF, Fn&gt; || std::is_nothrow_constructible_v&lt;EF, Fn &amp;&gt;) : m_uncaught_exceptions(std::uncaught_exceptions()) { set_functor(std::forward&lt;Fn&gt;(fn)); } template&lt;typename = std::disjunction&lt;std::enable_if_t&lt;std::is_nothrow_move_constructible_v&lt;EF&gt;, int&gt;, std::enable_if_t&lt;std::is_nothrow_move_constructible_v&lt;EF&gt;, int&gt;&gt;&gt; constexpr scope_success(scope_success &amp;&amp;other) noexcept(std::is_nothrow_move_constructible_v&lt;EF&gt; || std::is_nothrow_copy_constructible_v&lt;EF&gt;) : m_uncaught_exceptions(other.m_uncaught_exceptions) { set_functor_move(std::move(other)); } constexpr scope_success(const scope_success &amp;) = delete; constexpr ~scope_success() noexcept(noexcept(std::declval&lt;EF&amp;&gt;()())) { /* if active and an exception did not happen, call functor. */ if (!m_released &amp;&amp; std::uncaught_exceptions() &lt;= m_uncaught_exceptions) { m_functor(); } /* destroy functor */ m_functor.~EF(); } constexpr void release() noexcept { m_released = true; } constexpr const auto&amp; exit_function() noexcept { return m_functor; } private: union { EF m_functor; char m_functor_bytes[sizeof(EF)] = {}; }; bool m_released{false}; int m_uncaught_exceptions{0}; template&lt;typename Fn&gt; constexpr void set_functor(Fn &amp;&amp;fn) noexcept(std::is_nothrow_constructible_v&lt;EF, Fn&gt; || std::is_nothrow_constructible_v&lt;EF, Fn &amp;&gt;) { if constexpr(!std::is_lvalue_reference_v&lt;Fn&gt; &amp;&amp; std::is_nothrow_constructible_v&lt;EF, Fn&gt;) { ::new(&amp;m_functor) EF(std::forward&lt;Fn&gt;(fn)); } else { try { ::new(&amp;m_functor) EF(fn); } catch (...) { m_released = true; fn(); throw; } } } constexpr void set_functor_move(scope_success &amp;&amp;other) noexcept(std::is_nothrow_move_constructible_v&lt;EF&gt; || std::is_nothrow_copy_constructible_v&lt;EF&gt;) { /* only preform construction if other is active */ if (!other.m_released) { if constexpr(std::is_nothrow_move_constructible_v&lt;EF&gt;) { ::new(&amp;m_functor) EF(std::forward&lt;EF&gt;(other.m_functor)); } else { try { ::new(&amp;m_functor) EF(other.m_functor); } catch (...) { m_released = true; other.m_functor(); other.release(); throw; } } other.release(); } } }; template&lt;typename EF&gt; scope_success(EF) -&gt; scope_success&lt;EF&gt;; } #endif //SCOPE_SCOPE_HH </code></pre> <p>here is an example of it:</p> <p><code>main.cc</code></p> <pre><code>#include &lt;iostream&gt; #include &lt;ctime&gt; #include &lt;SDL.h&gt; #include &quot;scope.hh&quot; int main(int, char*[]) { // Reseed rand std::srand(std::time(0)); SDL_Init(SDL_INIT_VIDEO); // Initialize SDL2 // Create an application window with the following settings: SDL_Window* window = SDL_CreateWindow( &quot;An SDL2 window&quot;, // window title SDL_WINDOWPOS_UNDEFINED, // initial x position SDL_WINDOWPOS_UNDEFINED, // initial y position 640, // width, in pixels 480, // height, in pixels SDL_WINDOW_OPENGL ); // Check that the window was successfully created if (window == nullptr) { // In the case that the window could not be made... std::cerr &lt;&lt; &quot;Could not create window: &quot; &lt;&lt; SDL_GetError() &lt;&lt; &quot;\n&quot;; return 1; } // Clean up when exiting the scope turtle::scope_exit cleanup{[&amp;]{ SDL_DestroyWindow(window); SDL_Quit(); }}; // An exception could be thrown if(std::rand() % 4 == 0) { throw; } // The window is open: could enter program loop here SDL_Delay(3000); // Pause execution for 3000 milliseconds, for example return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T12:58:38.023", "Id": "482952", "Score": "1", "body": "I don't understand. What's this scope exit?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T22:26:24.150", "Id": "483040", "Score": "2", "body": "@ALX23z: it's a way to register a function that is called when the scope ends. For example: `{ scope_exit foo([]{std::cout << \"scope exit\\n\";}); if(rand()&1) throw std::runtime_error(\"onoes!\"); std::cout << \"hello\\n\"; }` Here, the text `scope exit` will always be printed, if there was no uncaught exception it will be done after printing `hello`. The above code also has variants that only trigger if there was an exception or if there were none. @user222866: it would help if you added an example of how you intend your code to be used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T12:10:11.313", "Id": "483089", "Score": "1", "body": "I added an example of usage" } ]
[ { "body": "<h1>Bugs</h1>\n<p>It isn't necessary to require <code>x()</code> to return exactly <code>void</code> — in fact, any return type would do, since we can discard the result. So, the requirements on the <code>struct</code>s should be simplified to <code>template &lt;std::invocable EF&gt;</code>.</p>\n<p>This code is problematic:</p>\n<blockquote>\n<pre><code>template&lt;typename = std::disjunction&lt;std::enable_if_t&lt;std::is_nothrow_move_constructible_v&lt;EF&gt;, int&gt;,\n std::enable_if_t&lt;std::is_nothrow_move_constructible_v&lt;EF&gt;, int&gt;&gt;&gt;\n</code></pre>\n</blockquote>\n<ul>\n<li><p><code>std::disjunction</code> doesn't work the way you think it does;</p>\n</li>\n<li><p>one of the <code>move</code>s should be <code>copy</code>;</p>\n</li>\n<li><p>SFINAE with <code>std::enable_if_t</code> needs to depend on a template parameter of the function template.</p>\n</li>\n</ul>\n<p>So it should be</p>\n<pre><code>template &lt;typename EF2 = EF, typename = std::enable_if_t&lt;\n std::is_nothrow_move_constructible_v&lt;EF2&gt;\n || std::is_nothrow_copy_constructible_v&lt;EF2&gt;\n&gt;&gt;\n</code></pre>\n<p>or just use <code>requires</code>.</p>\n<p>You'll need to special-case references. <code>union</code>s containing references are ill-formed IIRC.</p>\n<p>Don't mark things as <code>constexpr</code> unless the spec says so if your objective is conformance — the standard <a href=\"https://eel.is/c++draft/constexpr.functions#1\" rel=\"nofollow noreferrer\">prohibits</a> implementations from adding <code>constexpr</code>.</p>\n<h1>Non-bugs</h1>\n<p>As I said before, you can use <code>requires</code> instead of <code>enable_if</code> in many cases.</p>\n<p>You don't need a <code>union</code>-simulated <code>std::optional</code> to store the exit function, because all scope guards (including inactive ones) keep their exit function alive. (per comment) For the move constructor, use <code>std::move_if_noexcept</code> for the <code>noexcept</code> dispatch behavior; for example:</p>\n<pre><code>scope_exit(scope_exit&amp;&amp; other)\n noexcept(std::is_nothrow_move_constructible_v&lt;EF&gt; ||\n std::is_nothrow_copy_constructible_v&lt;EF&gt;)\n requires std::is_nothrow_move_constructible_v&lt;EF&gt; ||\n std::is_copy_constructible_v&lt;EF&gt;\n : m_functor(std::move_if_noexcept(other.m_functor))\n{\n other.release();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T22:49:37.973", "Id": "483262", "Score": "0", "body": "Using `std::optional` instead of that broken hack with the `union` is a good suggestion… but a better one would be to ask why all that is necessary at all. It looks like the only point where the object doesn’t have an active `m_functor` is in the moments right after construction, which means all that song-and-dance with the `union`s is just to emulate ordinary construction." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T22:49:48.207", "Id": "483263", "Score": "0", "body": "In other words, why couldn’t the move constuctor just be basically `constexpr scope_exit(scope_exit&& other) : m_functor{std::move(other.m_functor)} { other.m_released = true; }`, and the converting constructor `template <typename Fn> constexpr explicit scope_exit(Fn&& fn) : m_functor(std::forward<Fn>(fn)) {}` (plus the `noexcept` specifiers, omitted for brevity)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T05:04:36.787", "Id": "483274", "Score": "0", "body": "@indi The dispatch behavior is mandated by the [spec](https://en.cppreference.com/w/cpp/experimental/scope_exit/scope_exit). As for `optional`, yes, you're right, seems that inactive `scope_exit`s keep their function. I'll edit the answer." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T07:04:19.280", "Id": "245950", "ParentId": "245846", "Score": "4" } } ]
{ "AcceptedAnswerId": "245950", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-21T23:51:57.777", "Id": "245846", "Score": "9", "Tags": [ "c++", "c++20" ], "Title": "C++20 ScopeGuard" }
245846
<p>I am new to coding/programming. About four months ago I decided to develop my skills using Python. After several books and a lot of assistance from this awesome community I developed the first part of my &quot;Pizza Order System&quot; program.</p> <p><strong>Explanation of my program:</strong></p> <p>When the program in ran, the user is prompted to pick a pizza size. The user can choose more until they press <kbd>t</kbd> which will return the total of all the pizzas chosen. The program then continues to the topping menu where the user can choose toppings ($1 each). When they are finished choosing their toppings the user will press <kbd>f</kbd> and the program will return the final order total.</p> <pre><code>size_mappings = { 1: &quot;Small&quot;, 2: &quot;Large&quot;, 3: &quot;Extra Large&quot;, 4: &quot;Party Size&quot; } cost_mappings = { &quot;Small&quot;: 6, &quot;Large&quot;: 10, &quot;Extra Large&quot;: 12, &quot;Party Size&quot;: 24 } class Pizza(): def __init__(self, size): self.size = size def set_size(self, size): self.size = size def get_size(self): return self.size() def get_cost(self): return cost_mappings[self.size] class Order(): def __init__(self): self.pizzas = [] def addPizza(self, pizza): self.pizzas.append(pizza) def getTotal(self): total = 0 for pizza in self.pizzas: total += pizza.get_cost() return total # start processing the order order = Order() def run(): print(&quot;\nWhat size pizza would you like?\n\n\ _____________________________________________________________\n\ | 1: Small | 2: Large | 3: Extra Large | 4: Party Size |\n\ | $6 | $10 | $12 | $24 |\n\ |___________|____________|__________________|________________|\n\ \n- Press 't' to choose your toppings\n&quot;) while True: try: response = input('-') if response == 't': break size_wanted = int(response) size_wanted = size_mappings[size_wanted] print(f&quot;Pizza: {size_wanted}&quot;) order.addPizza(Pizza(size_wanted)) except: print(&quot;An error occurred, please try again&quot;) run() print(&quot;your current order total: &quot;, &quot;$&quot; + str(order.getTotal())) topping_mappings = { 1: 'Anchovies', 2: 'Bacon', 3: 'Bell Peppers', 4: 'Black Olives', 5: 'Chicken', 6: 'Ground Beef', 7: 'Jalapenos', 8: 'Mushrooms', 9: 'Pepperoni', 10: 'Pineapple', 11: 'Spinach', 12: 'Onion' } topping_cost_mappings = { 'Anchovies': 1, 'Bacon': 1, 'Bell Peppers': 1, 'Black Olives': 1, 'Chicken': 1, 'Ground Beef': 1, 'Jalapenos': 1, 'Mushrooms': 1, 'Pepperoni': 1, 'Pineapple': 1, 'Spinach': 1, 'Onion': 1 } class CustomerToppings(): &quot;&quot;&quot; Have customer pick toppings for pizza&quot;&quot;&quot; def __init__(self, numToppings): self.numToppings = numToppings def set_toppings(self, numToppings): self.numToppings = numToppings def get_toppings(self): return topping_cost_mappings[self.numToppings] class ToppingOrder(): def __init__(self): self.topping = [] def addTopping(self, toppings): self.topping.append(toppings) def toppingTotal(self): get_topping_total = 0 for toppings in self.topping: get_topping_total += toppings.get_toppings() return get_topping_total # Strat processing the order topping_order = ToppingOrder() def runTopping(): print(&quot;\nWhat toppings would you like on your pizza?\n\n\ ______________________________________________________________________\n\ | 1: Anchovies | 2: Bacon | 3: Bell Peppers | 4: Black Olives |\n\ | 5: Chicken | 6: Ground Beef | 7: Jalapenos | 8: Mushrooms |\n\ | 9: Pepperoni | 10: Pineapple | 11: Spinach | 12: Onions |\n\ |______________|________________|_________________|__________________|\n\ Press 'f' for your final total: \n&quot;) while True: try: response = input('-') if response == 'f': break toppings_wanted = int(response) toppings_wanted = topping_mappings[toppings_wanted] print(f&quot;Topping: {toppings_wanted}&quot;) topping_order.addTopping(CustomerToppings(toppings_wanted)) except: print(&quot;An error occurred, please try again&quot;) runTopping() sub_size = int(order.getTotal()) sub_toppings = int(topping_order.toppingTotal()) final_total = sub_size + sub_toppings print(f&quot; \nYour final total will be ${final_total}\n&quot;) </code></pre>
[]
[ { "body": "<p>Welcome to CR community.</p>\n<ol>\n<li><p>Keep constant declarations at the top. Although you follow the PEP8 naming conventions throughout (almost) the whole code base, I'll point out a few key things:</p>\n<ul>\n<li>variables, functions and methods should be named using <code>snake_case</code>. So, the <code>addTopping</code> would be renamed to <code>add_topping</code>.</li>\n<li>constant (or globals) are named as <code>UPPER_SNAKE_CASE</code>. So, the <code>size_mappings</code> would become <code>SIZE_MAPPINGS</code>.</li>\n<li>classes are named as <code>CamelCase</code>. You're already following this convention.</li>\n</ul>\n</li>\n<li><p>Use triple-quoted strings in python for multiline content. Your print statements would look a lot cleaner (no need for <code>\\n\\n\\n...</code> chains). The following prints the same list/table:</p>\n<pre><code> print(&quot;&quot;&quot;\n What size pizza would you like?\n\n _____________________________________________________________\n | 1: Small | 2: Large | 3: Extra Large | 4: Party Size |\n | $6 | $10 | $12 | $24 |\n |___________|____________|__________________|________________|\n\n - Press 't' to choose your toppings\n &quot;&quot;&quot;)\n</code></pre>\n</li>\n<li><p>Put the execution flow of your code inside <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\">the <code>if __name__ == &quot;__main__&quot;</code></a> block.</p>\n</li>\n<li><p>When ordering a pizza, usually I am asked toppings for each pizza separately, instead of me listing down the different sizes of pizzas, and then choosing toppings for those in bulk. This would also change how your program execution goes.</p>\n</li>\n<li><p>If following the above, <code>Toppings</code> elements would be a list of elements inside the <code>Pizza</code> class.</p>\n</li>\n<li><p>You do not need a separate <code>ToppingsOrder</code> class.</p>\n</li>\n<li><p>Instead of maintaining 2 different variables for mapping pizza choice &lt;-&gt; size &lt;-&gt; price (and similarly for toppings), you can use <a href=\"https://devdocs.io/python%7E3.7/library/collections#collections.namedtuple\" rel=\"nofollow noreferrer\">a namedtuple</a> (or <a href=\"https://devdocs.io/python%7E3.7/library/dataclasses#dataclasses.dataclass\" rel=\"nofollow noreferrer\">dataclass</a>, as per your needs):</p>\n<pre><code> from collections import namedtuple\n\n Pizza = namedtuple(&quot;Pizza&quot;, [&quot;name&quot;, &quot;price&quot;])\n SIZE_MAPPINGS = {\n 1: Pizza(&quot;Small&quot;, 6),\n .\n .\n }\n</code></pre>\n<p>Now, you can <code>add_pizza</code> to an order as simply as:</p>\n<pre><code> order.add_pizza(SIZE_MAPPINGS[size_wanted])\n</code></pre>\n<p>and when fetching price (or name) of pizza, it would be <code>pizza.price</code> (or <code>pizza.name</code>).</p>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T19:09:01.833", "Id": "483015", "Score": "0", "body": "Thank you so much taking the time to review my code, this was very helpful." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T05:03:30.737", "Id": "245853", "ParentId": "245852", "Score": "6" } } ]
{ "AcceptedAnswerId": "245853", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T04:33:59.090", "Id": "245852", "Score": "5", "Tags": [ "python", "beginner", "object-oriented" ], "Title": "Pizza Order System" }
245852
<p>My target is to have an environment variable being set to a leading substring of <code>$PWD</code> and to be unset when <code>$PWD</code> does not start with that substring.</p> <p>So I decided to override <code>cd</code> like this (here I'm assuming the substring is just my home directory <code>/home/enrico</code>, but in general is fine for me that it be an hardcoded regex):</p> <pre class="lang-bsh prettyprint-override"><code>cd() { command cd &quot;$@&quot; export MYVARIABLE=$(&lt;&lt;&lt; $PWD sed -E 's!(/home/enrico)(/?$|.*)!\1!') if [[ $MYVARIABLE == $PWD ]]; then unset MYVARIABLE fi } </code></pre> <p>This seems to work fine, but I'd like to have some different point of view on it.</p> <p>(Btw, if there are appropriate tags to add, please do, as I haven't found any more than <code>bash</code>.)</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T08:35:09.470", "Id": "245857", "Score": "1", "Tags": [ "bash" ], "Title": "Define cd so that it changes a variable (as it does already with PWD, OLDPWD, ...)" }
245857
<p>I'm writing a simple REST API to my MongoDB using PyMongo (Python 3.7).</p> <p>Each collection I have in the DB has a route (e.g <a href="http://the.api.url/collection_name" rel="nofollow noreferrer">http://the.api.url/collection_name</a> ), and every document under that collection has a sub-route (e.g <a href="http://the.api.url/collection_name/document_id" rel="nofollow noreferrer">http://the.api.url/collection_name/document_id</a> ).</p> <p>The micro-services in my program need to access this API in order to get stuff from the DB and upload stuff to it.</p> <p>I feel like my code isn't DRY enough but cant think of how to make it better.</p> <pre><code>from flask import Flask,jsonify,request from flask_pymongo import PyMongo from pymongo import errors import os app = Flask(__name__) mongodb_ip = os.environ.get(&quot;DB_IP&quot;, &quot;chaos.mongodb.openshift&quot;) mongodb_port = os.environ.get(&quot;DB_PORT&quot;, &quot;8080&quot;) db_name = os.environ.get(&quot;DB_NAME&quot;, &quot;chaos&quot;) server_port = int(os.environ.get(&quot;SERVER_PORT&quot;, 5001)) mongodb_uri = &quot;mongodb://{}:{}/{}&quot;.format(mongodb_ip,mongodb_port,db_name) app.config['MONGODB_NAME'] = db_name app.config['MONGO_URI'] = mongodb_uri mongo = PyMongo(app) @app.route('/servers',methods=['GET']) @app.route('/server',methods=['GET']) def get_all_servers(): collection = &quot;servers&quot; expected_returned_keys = [&quot;dns&quot;,&quot;active&quot;,&quot;groups&quot;] output = get_all_objects(collection, expected_returned_keys) return output @app.route('/servers/&lt;dns&gt;' ,methods=['GET']) @app.route('/server/&lt;dns&gt;' ,methods=['GET']) def get_one_server(dns): collection = &quot;servers&quot; identifier_key = &quot;dns&quot; identifier_value = dns expected_returned_keys = [&quot;dns&quot;, &quot;active&quot;,&quot;groups&quot;] output = get_one_object(collection,identifier_key,identifier_value,expected_returned_keys) return output @app.route('/servers', methods=['POST']) @app.route('/server', methods=['POST']) def add_server(): collection = &quot;servers&quot; json_object = request.get_json() expected_returned_keys = [&quot;dns&quot;, &quot;active&quot;,&quot;groups&quot;] identifier_key = &quot;dns&quot; try : identifier_value = json_object[&quot;dns&quot;] except KeyError : return &quot;dns is a required parameter&quot;,400 default_request_values = {'active' : False, 'groups' : [], 'last_fault' : '15:12:00:00:00:00'} add_object_to_db(collection, json_object, expected_returned_keys, identifier_key, identifier_value,default_request_values) @app.route('/groups', methods=['GET']) @app.route('/group', methods=['GET']) def get_all_groups(): collection = &quot;groups&quot; expected_returned_keys = [&quot;name&quot;, &quot;active&quot;] output = get_all_objects(collection, expected_returned_keys) return output @app.route('/groups/&lt;name&gt;' ,methods=['GET']) @app.route('/group/&lt;name&gt;' ,methods=['GET']) def get_one_group(name): collection = &quot;groups&quot; identifier_key = &quot;name&quot; identifier_value = name expected_returned_keys = [&quot;name&quot;, &quot;active&quot;] output = get_one_object(collection, identifier_key, identifier_value, expected_returned_keys) return output @app.route('/groups', methods=['POST']) @app.route('/group', methods=['POST']) def add_group(): collection = &quot;groups&quot; json_object = request.get_json() expected_returned_keys = [&quot;name&quot;, &quot;active&quot;] identifier_key = &quot;name&quot; try: identifier_value = json_object[&quot;name&quot;] except KeyError: return &quot;name is a required parameter&quot;, 400 default_request_values = {'members' : [], 'active' : False} output = add_object_to_db(collection, json_object, expected_returned_keys, identifier_key, identifier_value,default_request_values) return output output = add_object_to_db(collection, json_object, expected_returned_keys, identifier_key, identifier_value,default_request_values) return output @app.route('/logs', methods=['GET']) @app.route('/log', methods=['GET']) def get_all_logs(): collection = &quot;logs&quot; expected_returned_keys = [&quot;name&quot;, 'logs' , &quot;date&quot;, &quot;successful&quot; ] output = get_all_objects(collection, expected_returned_keys) return output @app.route('/logs/&lt;name&gt;' ,methods=['GET']) @app.route('/log/&lt;name&gt;' ,methods=['GET']) def get_one_log(name): collection = &quot;logs&quot; identifier_key = &quot;name&quot; identifier_value = name expected_returned_keys = [&quot;name&quot;, 'logs' , &quot;date&quot;, &quot;successful&quot; ] output = get_one_object(collection, identifier_key, identifier_value, expected_returned_keys) return output def get_one_object(collection,identifier_key,identifier_value,expected_returned_keys): # Easyiest way to use a string as a property of an object objects = eval(&quot;mongo.db.{}&quot;.format(collection)) query = objects.find_one({identifier_key : identifier_value}) if query: output = {} for key in expected_returned_keys : output[key] = query[key] else : output = &quot;object not found&quot; return jsonify(output) def get_all_objects(collection,expected_returned_keys): # Easyiest way to use a string as a property of an object objects = eval(&quot;mongo.db.{}&quot;.format(collection)) output = [] for query in objects.find(): found_object = {} for key in expected_returned_keys : found_object[key] = query[key] output.append(found_object) return jsonify({'result' : output}) def add_object_to_db(collection,json_object,expected_returned_keys,identifier_key,identifier_value,default_request_values): # Easyiest way to use a string as a property of an object objects = eval(&quot;mongo.db.{}&quot;.format(collection)) # Fill out default values if not in sent object json_object = parse_json_object(json_object, default_request_values) try: if objects.count_documents({identifier_key: identifier_value}) &gt; 0: return {&quot;result&quot; : &quot;object with the same identifier already exists&quot;}, 400 else: new_object_id = objects.insert(json_object, check_keys=False) query = objects.find_one({'_id': new_object_id}) except (errors.WriteError, TypeError) as E: print(E) return jsonify({'result': 'the object failed the validation schema'}), 400 output = {} for expected_key in expected_returned_keys: output[expected_key] = query[expected_key] return jsonify({'result': output}) def parse_json_object(json_object,default_values_dict): default_keys = default_values_dict.keys() object_keys = json_object.keys() for default_key in default_keys: if default_key not in object_keys : json_object[default_key] = default_values_dict[default_key] return json_object if __name__ == '__main__': app.run(host='0.0.0.0' , port=server_port) <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T11:23:14.343", "Id": "482936", "Score": "1", "body": "Welcome to Code Review. Please state the purpose of the code. What prompted you to write this? You wrote an API, to do what? Why?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T11:46:16.567", "Id": "482937", "Score": "0", "body": "@Mast just updated the intro, is this what you expected?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T12:32:10.137", "Id": "482942", "Score": "0", "body": "Yes, much better, thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T12:34:04.167", "Id": "482943", "Score": "0", "body": "For what Python version did you write this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T13:15:59.917", "Id": "482954", "Score": "1", "body": "@Mast python 3.7" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T10:06:36.223", "Id": "245860", "Score": "2", "Tags": [ "python", "python-3.x", "mongodb", "flask", "pymongo" ], "Title": "Simple Flask REST API to a MongoDB" }
245860
<p>I have made a program for my calculator's <strong><code>micropython</code></strong>, that can solve various <strong>a level statistics</strong> questions for me. However due to the limitations of the <code>micropython's</code> standard library, i had to reinvent the wheel on some functions and could not rely on external modules to do the tasks as they don't exist in <code>micropython</code>. I tried to implement everything using mostly pure python. As such, I would like some advice on shortcuts to make my code, more efficient and compact, and if there is an easier way to do a task, it'd be appreciated.</p> <pre><code>def find_median(lst): # finds the median of a sorted_list quotient, remainder = divmod(len(lst), 2) if remainder: return lst[quotient] return sum(lst[quotient - 1:quotient + 1]) / 2 def find_mode(listed_data): # finds the mode for listed data Counter = {value: listed_data.count(value) for value in listed_data} m = max(Counter.values()) mode = [x for x in set(listed_data) if Counter[x] == m] if m&gt;1 else None return mode def interpolation_grouped_data(grouped_data, cumulative_frequencies, position): # responsible for using linear interpolation to find the lower quartile, median, and upper quartile of grouped data if cumulative_frequencies[0] &gt; position: # if the position of the data required is not in the first interval, then it is between 0 , and the lowest bound in the first interval mn_cu_freq = 0 mx_cu_freq = cumulative_frequencies[0] mid_cu_freq = position interval_index = 0 else: for index in range(len(cumulative_frequencies) - 1): if cumulative_frequencies[index+1] &gt; position &gt;= cumulative_frequencies[index]: # if the position is within this interval mn_cu_freq = cumulative_frequencies[index] mx_cu_freq = cumulative_frequencies[index + 1] mid_cu_freq = position interval_index = index + 1 break lower_bound, upper_bound = grouped_data[interval_index][0:2] return interpolation(mn_cu_freq, mid_cu_freq, mx_cu_freq, lower_bound, upper_bound) def interpolation(mn_cu_freq, mid_cu_freq, mx_cu_freq, lower_bound, upper_bound): # uses interpolation to find the result, cu represents cumulative result = lower_bound + ( ( (mid_cu_freq - mn_cu_freq)/(mx_cu_freq - mn_cu_freq) ) * (upper_bound - lower_bound) ) return result def listed_data_stats(listed_data): # for dealing with listed data Ex: 1,2,3,4 or 5,1,4,2,6,7 # sum of data, number of data, mean sum_x = sum(listed_data) number_of_data = len(listed_data) mean = sum_x / number_of_data # sum of each data squared sum_x_squared = sum(i**2 for i in listed_data) # variance, and standard deviation variance = (sum_x_squared / number_of_data) - mean**2 standard_deviation = round((variance)**0.5, 5) # data sorted for finding measure of locations sorted_listed_data = sorted(listed_data) middle = number_of_data//2 # minimum, and maximum value minimum = sorted_listed_data[0] maximum = sorted_listed_data[-1] # lower quartile, median, upper quartile LQ_list, Median_list = sorted_listed_data[:middle], sorted_listed_data UQ_list = sorted_listed_data[middle:] if number_of_data % 2 == 0 else sorted_listed_data[middle+1:] lower_quartile = find_median(LQ_list) median = find_median(Median_list) upper_quartile = find_median(UQ_list) # Interquartile Range interquartile_range = upper_quartile - lower_quartile Range = sorted_listed_data[-1] - sorted_listed_data[0] # Outliers lower_outlier_bound = lower_quartile - (1.5*standard_deviation) upper_outlier_bound = upper_quartile + (1.5*standard_deviation) # Skewness skewness_quantity = (3*(mean-median))/standard_deviation if skewness_quantity &gt; 0: skewness = &quot;positive&quot; elif skewness_quantity &lt; 0: skewness = &quot;negative&quot; else: skewness = &quot;symmetrical&quot; # mode mode = find_mode(sorted_listed_data) return [round(x, 5) if isinstance(x, float) else x for x in (sorted_listed_data, minimum, maximum, sum_x, sum_x_squared, number_of_data, mean, mode, lower_quartile, median, upper_quartile, interquartile_range, Range, variance, standard_deviation, lower_outlier_bound, upper_outlier_bound, skewness, skewness_quantity)] def continuous_grouped_data_stats(grouped_data): # for dealing with grouped data ex: [[lower bound, upper bound, frequency], [...], [...]] etc. in [[0, 10, 16], [10, 15, 18], [15, 20, 50]] in the first list, 0 and 10 represents the interval 0 -&gt; 10, and 16 is the frequency of numbers in this range midpoints = [] cumulative_frequencies = [] sum_x = 0 sum_x_squared = 0 number_of_data = 0 if grouped_data[1][0] != grouped_data[0][1]: # if there are gaps in data gap = (grouped_data[1][0] - grouped_data[0][1])/2 for data in grouped_data: if data[0] != 0: data[0] -= gap data[1] += gap count = 0 for data in grouped_data: start_bound = data[0] end_bound = data[1] frequency = data[2] midpoints.append((start_bound + end_bound)/2) # acquires a list of midpoints for the each interval/tuple current_midpoint = midpoints[count] number_of_data += frequency # acquires the number of data/ total frequency of all intervals sum_x += (current_midpoint * frequency) # gets the sum of all midpoints x frequency sum_x_squared += (current_midpoint**2 * frequency) # gets the sum of all midpoints^2 x frequency if count == 0: # if it is the first loop, then add the first value of cumulative frequency to the list cumulative_frequencies.append(frequency) else: # if it is not, then get the value of the previous cumulative frequency and add to it the frequency of the current data, and append it cumulative_frequencies.append(cumulative_frequencies[count-1] + frequency) count += 1 # mean mean = sum_x / number_of_data # variance, and standard deviation variance = (sum_x_squared / number_of_data) - mean**2 standard_deviation = (variance)**0.5 # lower quartile, median, and upper quartile, interquartile range, Range, and outlier lower_quartile = interpolation_grouped_data(grouped_data, cumulative_frequencies, 0.25 * number_of_data) # performs interpolation to acquire it median = interpolation_grouped_data(grouped_data, cumulative_frequencies, 0.5 * number_of_data) upper_quartile = interpolation_grouped_data(grouped_data, cumulative_frequencies, 0.75 * number_of_data) interquartile_range = upper_quartile - lower_quartile Range = grouped_data[-1][1] - grouped_data[0][0] lower_outlier_bound = lower_quartile - (1.5*standard_deviation) upper_outlier_bound = upper_quartile + (1.5*standard_deviation) # Skewness skewness_quantity = (3*(mean-median))/standard_deviation if skewness_quantity &gt; 0: skewness = &quot;positive&quot; elif skewness_quantity &lt; 0: skewness = &quot;negative&quot; else: skewness = &quot;symmetrical&quot; return [round(x, 5) if isinstance(x, float) else x for x in (sum_x, sum_x_squared, number_of_data, midpoints, cumulative_frequencies, mean, lower_quartile, median, upper_quartile, interquartile_range, Range, variance, standard_deviation, lower_outlier_bound, upper_outlier_bound, skewness, skewness_quantity)] def discrete_grouped_data_stats(grouped_data): cumulative_frequencies = [] sum_data = 0 sum_data_squared = 0 sum_x = 0 sum_x_squared = 0 sum_y_squared = 0 number_of_data = 0 count = 0 for data in grouped_data: value, frequency = data number_of_data += frequency sum_data += (value * frequency) sum_data_squared += (value**2 * frequency) sum_x += value sum_x_squared += value**2 sum_y_squared += frequency**2 if count != 0: # if it is not the first loop, then get the value of the previous cumulative frequency and add to it the frequency of the current data, and append it cumulative_frequencies.append(cumulative_frequencies[count-1] + frequency) else: # if it is the first loop, then add the first value of cumulative frequency to the list cumulative_frequencies.append(frequency) count += 1 # mean mean = sum_data / number_of_data # variance, and standard deviation variance = (sum_data_squared / number_of_data) - mean**2 standard_deviation = variance**0.5 # data sorted for finding measure of locations sorted_listed_data = [] if all((isinstance(freq[1], int) for freq in grouped_data)): for value, frequency in grouped_data: sorted_listed_data.extend([float(value)] * frequency) sorted_listed_data.sort() else: sorted_listed_data = None if sorted_listed_data: # standard discrete data # lower quartile, median, upper quartile middle = number_of_data//2 LQ_list = sorted_listed_data[:middle] UQ_list = sorted_listed_data[middle:] if number_of_data % 2 == 0 else sorted_listed_data[middle+1:] lower_quartile = find_median(LQ_list) median = find_median(sorted_listed_data) upper_quartile = find_median(UQ_list) # Interquartile Range interquartile_range = upper_quartile - lower_quartile Range = sorted_listed_data[-1] - sorted_listed_data[0] # Outliers lower_outlier_bound = lower_quartile - (1.5*standard_deviation) upper_outlier_bound = upper_quartile + (1.5*standard_deviation) # Skewness skewness_quantity = (3*(mean-median))/standard_deviation if skewness_quantity &gt; 0: skewness = &quot;positive&quot; elif skewness_quantity &lt; 0: skewness = &quot;negative&quot; else: skewness = &quot;symmetrical&quot; else: # Path towards regression line related data cumulative_frequencies = None # Sxx, Syy, Sxy, Regression Line equation (y = a + bx) sum_y = number_of_data sum_xy = sum_data Sxx = sum_x_squared - ( (sum_x**2)/ count ) Syy = sum_y_squared - ( (sum_y**2)/ count ) Sxy = sum_xy - ((sum_x * sum_y)/ count ) mean_x = sum_x/count mean_y = sum_y/count b = Sxy/Sxx a = mean_y - b*(mean_x) regression_line_equation = ['y = {} + {}x'.format(round(a, 5), round(b, 5))] if not cumulative_frequencies: # if it is regression related, then no Nones lower_quartile = upper_quartile = interquartile_range = lower_outlier_bound = upper_outlier_bound = None sum_data = sum_data_squared = number_of_data = mean = skewness = skewness_quantity = median = Range = None # Product Moment Coefficient product_momentum_correlation_coefficient = Sxy/(Sxx * Syy)**0.5 return [round(x, 5) if isinstance(x, float) else x for x in (sum_data, sum_data_squared, number_of_data, cumulative_frequencies, mean, lower_quartile, median, upper_quartile, interquartile_range, Range, variance, standard_deviation, lower_outlier_bound, upper_outlier_bound, skewness, skewness_quantity, count, sum_x, sum_x_squared, sum_y, sum_y_squared, sum_xy, mean_x, mean_y, Sxx, Syy, Sxy, b, a, regression_line_equation, product_momentum_correlation_coefficient)] def check_type(x): if isinstance(x, float): # if type is list, do not convert to int return str(int(x)) if x % 1 == 0 else str(x) elif isinstance(x, list): if isinstance(x[0], float): return str([int(x[i]) if x[i] % 1 == 0 else x[i] for i in range(len(x))]) return str(x) def print_stats(results_names, results): print(&quot;&quot;, *(results_names[i] + &quot; = &quot; + check_type(results[i]) for i in range(len(results_names))), sep='\n') def linear_interpolation(): # a variables = [None] * 5 # values to be inputted for interpolation variables_names = [&quot;mn_cu_freq&quot;, &quot;mid_cu_freq&quot;, &quot;mx_cu_freq&quot;, &quot;lower_bound&quot;, &quot;upper_bound&quot;] for index in range(5): variables[index] = float(input(&quot;{}: &quot;.format(variables_names[index]))) print(&quot;x = &quot;, interpolation(*variables)) def listed_data_statistics(): # b listed_data = [] value = input(&quot;Enter Values: &quot;) while value != 'x': value = float(value) listed_data.append(value) value = input(&quot;Enter Values: &quot;) results = listed_data_stats(listed_data) # for concatonation results_names = ('Sorted_Data', 'Minimum', 'Maximum', 'Sum_x', 'Sum_x^2', 'n', 'Mean', 'Mode', 'Lower Quartile', 'Median', 'Upper Quartile', 'IQR', 'Range', 'Variance', 'Standard Deviation', 'Lower Outlier', 'Upper Outlier', 'Skewness', 'Skewness Value') print_stats(results_names, results) def continuous_grouped_data_statistics(): # c grouped_data = [] while True: start_boundary = input(&quot;Start Bound: &quot;) if start_boundary == &quot;x&quot;: # enter x when no more data available break end_boundary = input(&quot;End Bound: &quot;) frequency = input(&quot;Frequency: &quot;) grouped_data.append([float(start_boundary), float(end_boundary), int(frequency)]) # each row in the grouped data is a list results = continuous_grouped_data_stats(grouped_data) results_names = ('Sum_x', 'Sum_x^2', 'n', 'Midpoints', 'Cum. Freq', 'Mean', 'Lower Quartile', 'Median', 'Upper Quartile', 'IQR', 'Range', 'Variance', 'Standard Deviation', 'Lower Outlier', 'Upper Outlier', 'Skewness', 'Skewness Value') print_stats(results_names, results) def discrete_grouped_data_statistics(): # d grouped_data = [] while True: value = input(&quot;Value: &quot;) if value == &quot;x&quot;: break frequency = input(&quot;Frequency: &quot;) grouped_data.append([float(value), (int(frequency) if float(frequency) % 1 == 0 else float(frequency))]) results = discrete_grouped_data_stats(grouped_data) results_names = ('Sum', 'Sum^2', 'n', 'Cum. Freq', 'Mean', 'Lower Quartile', 'Median', 'Upper Quartile', 'IQR', 'Range', 'Variance', 'Standard Deviation', 'Lower Outlier', 'Upper Outlier', 'Skewness', 'Skewness Value', 'Sample_n', 'Sum_x', 'Sum_x^2', 'Sum_y', 'Sum_y^2', 'Sum_xy', 'Mean_x', 'Mean_y', 'Sxx', 'Syy', 'Sxy', 'b', 'a', 'Reg. Eq', 'Prod. Momen. Coeff') print_stats(results_names, results) def coded_data_discrete_output(grouped_data, prompt_index): prompts = [&quot;-- With Coding --&quot;, '-- Without Coding --'] print(prompts[prompt_index]) results = discrete_grouped_data_stats(grouped_data) results_names = ('Sum', 'Sum^2', 'n', 'Cum. Freq', 'Mean', 'Lower Quartile', 'Median', 'Upper Quartile', 'IQR', 'Range', 'Variance', 'Standard Deviation', 'Lower Outlier', 'Upper Outlier', 'Skewness', 'Skewness Value', 'Sample_n', 'Sum_x', 'Sum_x^2', 'Sum_y', 'Sum_y^2', 'Sum_xy', 'Mean_x', 'Mean_y', 'Sxx', 'Syy', 'Sxy', 'b', 'a', 'Reg. Eq', 'Prod. Momen. Coeff') print_stats(results_names, results) def histogram_calculator(): # e names = [&quot;Freq. 1 : &quot;, &quot;ClassWidth 1 : &quot;, &quot;Freq. 2 : &quot;, &quot;ClassWidth 2 : &quot;, &quot;Height 1 : &quot;, &quot;Width 1 : &quot;] Frequency_1, Class_Width_1, Frequency_2, Class_Width_2, Height_1, Width_1 = [float(input(prompt)) for prompt in names] Freq_Dens_1 = Frequency_1/Class_Width_1 Freq_Dens_2 = Frequency_2/Class_Width_2 Width_2 = (Class_Width_2*Width_1)/Class_Width_1 Height_2 = (Freq_Dens_2*Height_1)/Freq_Dens_1 print(&quot;&quot;, &quot;Other Width = &quot; + str(Width_2), &quot;Other Height = &quot; + str(Height_2), sep=&quot;\n&quot;) def code_data(): # f # codes x and y data x_lst = [] y_lst = [] count = 2 x = input(&quot;X1: &quot;) y = input(&quot;Y1: &quot;) while x != 'x' and y != 'x': x_lst.append(x) y_lst.append(y) x = input(&quot;X{}: &quot;.format(count)) y = input(&quot;Y{}: &quot;.format(count)) count += 1 x_lst = list(map(float, x_lst)) y_lst = list(map(float, y_lst)) original_data = list(zip(x_lst, y_lst)) choices = {'+': lambda n1, n2: n1+n2, '-': lambda n1, n2: n1-n2, '*': lambda n1, n2: n1*n2, '/': lambda n1, n2: n1/n2} prompts = [&quot;Enter Operation: &quot;, &quot;Enter Value: &quot;] x_operations = [] y_operations = [] count = 0 print(&quot;\nCoding X values - - - -&quot;) # coding x coding = input(prompts[0]) while coding != 'x': count += 1 x_operations.append(coding) coding = input(prompts[count%2]) count = 0 print(&quot;\nCoding Y values - - - -&quot;) # coding y coding = input(prompts[0]) while coding != 'x': count += 1 y_operations.append(coding) coding = input(prompts[count%2]) # coding elements in x and y lsts for i in range(0, len(x_operations), 2): number = float(x_operations[i+1]) for j in range(0, len(x_lst)): x_lst[j] = choices[x_operations[i]](x_lst[j], number) x_lst[j] = int(x_lst[j]) if x_lst[j] % 1 == 0 else float(x_lst[j]) for i in range(0, len(y_operations), 2): number = float(y_operations[i+1]) for j in range(0, len(y_lst)): y_lst[j] = choices[y_operations[i]](y_lst[j], number) y_lst[j] = int(y_lst[j]) if y_lst[j] % 1 == 0 else float(y_lst[j]) coded_data = list(zip(x_lst, y_lst)) print(&quot;Coded X: {}&quot;.format(x_lst)) print(&quot;Coded Y: {}\n&quot;.format(y_lst)) d = {'x': coded_data_discrete_output} c = input(&quot;Stats?: x=yes: &quot;) choice = d.get(c, lambda a, b: None)(coded_data, 0) if c == 'x': print(&quot;\n&quot;) coded_data_discrete_output(original_data, 1) def normal_distribution(): &quot;&quot;&quot; Acquires a, given x [and y], for a standard Normal Distribution of mean 0, and standard deviation 1 1) P(Z &lt; x) = a 2) P(Z &gt; x) = a 3) P(x &lt; Z &lt; y) = a 4) P(Z &lt; a) = x 5) P(Z &gt; a) = x 6) P(-a &lt; x &lt; a) = x &quot;&quot;&quot; from math import sqrt, exp mean = 0 standard_dev = 1 percentage_points = {0.5000: 0.0000, 0.4000: 0.2533, 0.3000: 0.5244, 0.2000: 0.8416, 0.1000: 1.2816, 0.0500: 1.6440, 0.0250: 1.9600, 0.0100: 2.3263, 0.0050: 2.5758, 0.0010: 3.0902, 0.0005: 3.2905} def erf(x): &quot;&quot;&quot; python implementation of math.erf() as it is not available in micropython &quot;&quot;&quot; # save the sign of x sign = 1 if x &gt;= 0 else -1 x = abs(x) # constants a1 = 0.254829592 a2 = -0.284496736 a3 = 1.421413741 a4 = -1.453152027 a5 = 1.061405429 p = 0.3275911 # A&amp;S formula 7.1.26 t = 1.0/(1.0 + p*x) y = 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x) return sign*y # erf(-x) = -erf(x) def get_z_less_than(x=None, digits=4): &quot;&quot;&quot; P(Z &lt; x) = a &quot;&quot;&quot; if x is None: x = float(input(&quot;Enter x: &quot;)) res = 0.5 * (1 + erf((x - mean) / sqrt(2 * standard_dev ** 2))) return round(res, digits) def get_z_greater_than(x=None): &quot;&quot;&quot; P(Z &gt; x) = a &quot;&quot;&quot; if x is None: x = float(input(&quot;Enter x: &quot;)) return round(1 - get_z_less_than(x), 4) def get_z_in_range(lower_bound=None, upper_bound=None): &quot;&quot;&quot; P(lower_bound &lt; Z &lt; upper_bound) = &quot;&quot;&quot; if lower_bound is None and upper_bound is None: lower_bound = float(input(&quot;Enter lower_bound: &quot;)) upper_bound = float(input(&quot;Enter upper_bound: &quot;)) return round(get_z_less_than(upper_bound) - get_z_less_than(lower_bound), 4) def get_z_less_than_a_equal(x=None, digits=4, round_=2): &quot;&quot;&quot; P(Z &lt; a) = x &quot;&quot;&quot; if x is None: x = float(input(&quot;Enter x: &quot;)) if x &lt;= 0.0 or x &gt;= 1.0: raise ValueError(&quot;x must be &gt;0.0 and &lt;1.0&quot;) min_res, max_res = -10, 10 while max_res - min_res &gt; 10 ** -(digits * 2): mid = (max_res + min_res) / 2 if get_z_less_than(mid, digits*2) &lt; x: min_res = mid else: max_res = mid return round((max_res + min_res) / 2, round_) def get_z_greater_than_a_equal(x=None): &quot;&quot;&quot; P(Z &gt; a) = x &quot;&quot;&quot; if x is None: x = float(input(&quot;Enter x: &quot;)) if x in percentage_points: return percentage_points[x] else: return get_z_less_than_a_equal(1-x) def get_z_in_range_a_b_equal(x=None): &quot;&quot;&quot; P(-a &lt; Z &lt; a) = x acquires a &quot;&quot;&quot; if x is None: x = float(input(&quot;Enter x: &quot;)) return get_z_less_than_a_equal(0.5 + x/2, 4, 4) norm_choices = {'1': get_z_less_than, '2': get_z_greater_than, '3': get_z_in_range, '4': get_z_less_than_a_equal, '5': get_z_greater_than_a_equal, '6': get_z_in_range_a_b_equal} option = input(&quot;1: P(Z &lt; x) = a\n2: P(Z &gt; x) = a\n3: P(-x &lt; Z &lt; x) = a\n4: P(Z &lt; a) = x\n5: P(Z &gt; a) = x\n6: P(-a &lt; Z &lt; a) = x\n: &quot;) # if not a valid option, then do nothing and naturally exit print(norm_choices.get(option, lambda: None)()) again = input(&quot;Try again? 1 = Yes\n: &quot;) if again == '1': normal_distribution() def statistics(): # checks for what you want choices = {'1': linear_interpolation, '2': listed_data_statistics, '3': continuous_grouped_data_statistics, '4': discrete_grouped_data_statistics, '5': histogram_calculator, '6': code_data, '7': normal_distribution} choice = input(&quot;1: Interpolation\n2: Listed Data\n3: Continuous Data\n4: Discrete Data\n5: Histogram\n6: Code Data\n7: Norm_Dist : &quot;) choices.get(choice, lambda: None)() statistics() </code></pre>
[]
[ { "body": "<p>As a disclaimer, I'm not familiar with either micropython, nor the calculator hardware that it will run on. I can only give advice on the Python code itself in isolation.</p>\n<hr />\n<pre><code>def find_median(lst): # finds the median of a sorted_list\n quotient, remainder = divmod(len(lst), 2)\n if remainder:\n return lst[quotient]\n return sum(lst[quotient - 1:quotient + 1]) / 2\n</code></pre>\n<p>There is a pretty big oversight in this code. It does not check if the sequence is sorted, nor does it sort it. You'll need to do one of the two.</p>\n<p>Quotient and remainder, while accurate, are not particularly communicative names. Why do you why the quotient and remainder? You could try something like half_len and has_odd_len.</p>\n<p>Since you know there will be exactly two values to sum up, I'd say stick with the simple <code>lst[quotient - 1] + lst[quotient]</code></p>\n<p>If I were to be picky</p>\n<ul>\n<li><code>find_median</code> could be simply <code>median</code></li>\n<li><code># finds the median of a sorted_list</code> seems like it is a docstring without the conventional triple quotes.</li>\n<li><code>lst</code> is not a great name. The <a href=\"https://docs.python.org/3/library/statistics.html#statistics.median\" rel=\"nofollow noreferrer\">statistics module</a> tends to go with <code>data</code>, which I think is a better choice.</li>\n</ul>\n<p>def median(data):\n&quot;&quot;&quot;Get the median of a sorted list&quot;&quot;&quot;\nif not is_sorted(data):\nraise ValueError(&quot;The data must be sorted&quot;)</p>\n<pre><code>half_len, has_odd_len = divmod(len(data), 2)\nif has_odd_len:\n return data[half_len]\nreturn (data[half_len - 1] + data[half_len]) / 2\n</code></pre>\n<hr />\n<pre><code>def find_mode(listed_data): # finds the mode for listed data\n Counter = {value: listed_data.count(value) for value in listed_data}\n m = max(Counter.values())\n mode = [x for x in set(listed_data) if Counter[x] == m] if m&gt;1 else None\n return mode\n</code></pre>\n<p>You have an implicit O(n<sup>2</sup>) time complexity in this function (with n being the length of the list). <code>listed_data.count(value)</code> takes up to O(n) time as it needs to check every element. This counting is done O(n) times. You can fix this by implementing your own mini collections.Counter with a dict.</p>\n<p>Making a set out of listed_data is unnecessary, the keys in the Counter dict are already the set you want. I would change the list comprehension to use the dict as it has all the information you need.</p>\n<p>If were are re-implementing Python's statistics, this seems more like multimode than mode, since it may return multiple elements.</p>\n<p>In a list with just one element, this unexpectedly returns None. I think you need a few tests to see if everything is actually working as expected. I've left the behaviour alone in the sample code below.</p>\n<p>Again being picky, don't have any variables start with uppercase. That is usually an indicator that this is the name of a class.</p>\n<pre><code>def mode(data):\n &quot;&quot;&quot;Find the mode(s) of the data.\n A mode is any value which occurs the most number of times.\n &quot;&quot;&quot;\n counter = dict()\n for value in data:\n if value not in counter:\n counter[value] = 0\n counter[value] += 1\n\n m = max(counter.values())\n if m &lt;= 1:\n return None\n\n return [x for x, occurance in counter.items() if occurance == m]\n</code></pre>\n<hr />\n<pre><code>def listed_data_stats(listed_data): # for dealing with listed data Ex: 1,2,3,4 or 5,1,4,2,6,7\n # sum of data, number of data, mean\n sum_x = sum(listed_data)\n number_of_data = len(listed_data)\n mean = sum_x / number_of_data\n\n # sum of each data squared\n sum_x_squared = sum(i**2 for i in listed_data)\n\n # variance, and standard deviation\n variance = (sum_x_squared / number_of_data) - mean**2\n standard_deviation = round((variance)**0.5, 5)\n\n # data sorted for finding measure of locations\n sorted_listed_data = sorted(listed_data)\n middle = number_of_data//2\n\n # minimum, and maximum value\n minimum = sorted_listed_data[0]\n maximum = sorted_listed_data[-1]\n</code></pre>\n<p>You can make a small improvement to the functionality of this code by computing the sorted list of data first. This will allow you to compute the stats for one time iterators (you can only iterate over them once, a.k.a. one call to len, sum, etc).</p>\n<p>Comments like <code># sum of data, number of data, mean</code> don't really add much to the code. I can see you've computed the sum of the data, the size of it, and it's mean, but I still don't know why you want these. If the comment is purely descriptive of the code, it probably isn't worth keeping.</p>\n<pre><code>return [round(x, 5) if isinstance(x, float) else x for x in (sorted_listed_data, minimum, \n maximum, sum_x, sum_x_squared, number_of_data, mean, mode, lower_quartile, median, \n upper_quartile, interquartile_range, Range, variance, standard_deviation, \n lower_outlier_bound, upper_outlier_bound, skewness, skewness_quantity)]\n</code></pre>\n<p>This is a lot of data to return as a tuple. Without a good comment in the docstring, it will be rather cumbersome for the user of this function to figure out which position in the list corresponds to which statistic. This is problematic as this is the only place in the whole function that will give them this information, and it is not easy to use. Consider making a class with attributes, a dictionary with easy to use key value pairs (e.g. <code>{&quot;skewness&quot;: skewness}</code>), or splitting this up into multiple functions and letting the user decide which statistics they want.</p>\n<hr />\n<p>Some other things to consider are</p>\n<ul>\n<li>Which the functions will react poorly to being fed an empty list of data? Or a very long list of data? It is worth writing down these tests and running them after each code change.</li>\n<li>Try running the code through pylint, flake8, pep8, or another linter. It will point out a fair number of small problems with styling, especially with weird spacing. Don't take the results too seriously, they are useful to get code into shape for when other people will look at the code.</li>\n<li>There are a few places with hardcoded precision values that might be nicer as positional parameters, or a global constant, so that they can be changed later.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T17:25:28.087", "Id": "482999", "Score": "0", "body": "+1 oh i should've considered using a dictionary instead of a tuple to represent this" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T15:35:33.023", "Id": "245879", "ParentId": "245866", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T11:48:15.143", "Id": "245866", "Score": "6", "Tags": [ "python", "python-3.x", "mathematics", "statistics" ], "Title": "A Level Statistics Calculator/Helper For A Casio Fx-CG50 Calculator's MicroPython" }
245866
<p>I've written PHP code to upload multiple images to a server.</p> <p>This function processes a maximum of 10 images at one time and if any image's width or height is larger than 2000px it will resize it. But the code is a little bit slow.</p> <p>I would like to hear your opinion of this code.</p> <p>Is there a way to make it faster and more and secure?</p> <p>P.S.: I use an .htaccess file in upload folder to make it more secure.</p> <p>This is my PHP code:</p> <pre class="lang-php prettyprint-override"><code>$img_num=count($_FILES['upload_images']['name']); if($img_num&gt;0 &amp;&amp; $img_num&lt;11){ for($i=0;$i&lt;$img_num;$i++){ if($_FILES['upload_images']['name'][$i]!=''){ $ext=explode(&quot;.&quot;,$_FILES['upload_images']['name'][$i]); $ext=strtolower($ext[1]); if ((($_FILES['upload_images']['type'][$i] == &quot;image/gif&quot;) || ($_FILES['upload_images']['type'][$i] == &quot;image/jpeg&quot;) || ($_FILES['upload_images']['type'][$i] == &quot;image/jpg&quot;) || ($_FILES['upload_images']['type'][$i] == &quot;image/pjpeg&quot;) || ($_FILES['upload_images']['type'][$i] == &quot;image/x-png&quot;) || ($_FILES['upload_images']['type'][$i] == &quot;image/png&quot;)) &amp;&amp; ($_FILES['upload_images']['size'][$i] &lt; 12000000) &amp;&amp; in_array($ext,array(&quot;gif&quot;,&quot;jpeg&quot;,&quot;jpg&quot;,&quot;png&quot;))){ $is_jpg=1;$ex='jpg'; switch ($ext){ case 'jpg':$image=imagecreatefromjpeg($_FILES['upload_images']['tmp_name'][$i]);break; case 'jpeg':$image=imagecreatefromjpeg($_FILES['upload_images']['tmp_name'][$i]);break; case 'png':$image=imagecreatefrompng($_FILES['upload_images']['tmp_name'][$i]);if($_FILES['upload_images']['size'][$i] &lt; 2000000){$ex='png';$is_jpg=2;}break; case 'gif':$image=imagecreatefromgif($_FILES['upload_images']['tmp_name'][$i]);$ex='gif';$is_jpg=3;break; default:$image=imagecreatefromjpeg($_FILES['upload_images']['tmp_name'][$i]);break; } $path='upload/img_'.mb_substr(md5($_FILES['upload_images']['name'][$i].rand(0,50)),0,rand(5,10)).'.'.$ex; $width=imagesx($image);$height=imagesy($image); $resize=false; if($width&gt;2000 || $height&gt;2000){ $width_orig=$width;$height_orig=$height; $width=2000;$height=2000; $ratio_orig=$width_orig/$height_orig; ($width/$height &gt; $ratio_orig)?$width=$height*$ratio_orig:$height=$width/$ratio_orig; $resize=true; } if($is_jpg==1){ if($resize){ $bg=imagecreatetruecolor($width, $height); imagecopyresampled($bg, $image, 0, 0, 0, 0,$width, $height,$width_orig, $height_orig); imagejpeg($bg,$path,75); imagedestroy($bg); } else{imagejpeg($image,$path,80);} imagedestroy($image); $img_url[]=$ex; } elseif($is_jpg==2){ $bg = imagecreatetruecolor($width, $height); imagesavealpha($bg, TRUE); imagefill($bg, 0, 0, imagecolorallocatealpha($bg, 0, 0, 0,127)); $resize?imagecopyresampled($bg, $image, 0, 0, 0, 0,$width, $height,$width_orig, $height_orig):imagecopy($bg, $image, 0, 0, 0, 0,$width, $height); imagedestroy($image); imagepng($bg,$path,8); imagedestroy($bg); } elseif($is_jpg==3){ move_uploaded_file($_FILES['upload_images']['tmp_name'][$i], $path); } } } } } </code></pre> <p>and this the .htaccess file:</p> <pre><code>IndexIgnore * deny from all &lt;Files ~ &quot;^(.*)+\.(gif|jpg|png|jpeg|svg|mp4)$&quot;&gt; order deny,allow allow from all &lt;/Files&gt; Options -Indexes -ExecCGI RemoveHandler .php .phtml .php3 RemoveType .php .phtml .php3 php_flag engine off ForceType application/octet-stream &lt;FilesMatch &quot;(?i).jpe?g$&quot;&gt; ForceType image/jpeg &lt;/FilesMatch&gt; &lt;FilesMatch &quot;(?i).gif$&quot;&gt; ForceType image/gif &lt;/FilesMatch&gt; &lt;FilesMatch &quot;(?i).png$&quot;&gt; ForceType image/png &lt;/FilesMatch&gt; &lt;FilesMatch &quot;(?i)\.mp4$&quot;&gt; ForceType video/mp4 &lt;/FilesMatch&gt; </code></pre>
[]
[ { "body": "<h2>Formatting</h2>\n<p>I'd recommend looking at the accepted <a href=\"https://www.php-fig.org/psr/\" rel=\"nofollow noreferrer\">PSRs</a> - e.g. <a href=\"https://www.php-fig.org/psr/psr-1/\" rel=\"nofollow noreferrer\">PSR-1</a>, <a href=\"https://www.php-fig.org/psr/psr-12/\" rel=\"nofollow noreferrer\">PSR-12</a>. Updating the code to comply with them will help make the code readable and consistent with idiomatic PHP code.</p>\n<p>Maybe this is just a copy-paste issue, but even if you don't strictly follow <a href=\"https://www.php-fig.org/psr/psr-12/\" rel=\"nofollow noreferrer\">PSR-12</a> please <strong>indent</strong> nested lines within blocks.</p>\n<h2>Array syntax</h2>\n<p>As of the time of writing, <a href=\"https://www.php.net/supported-versions.php\" rel=\"nofollow noreferrer\">PHP 7 has Active support for versions 7.4 and 7.3</a>, and since PHP 5.4 arrays can be declared with <a href=\"https://www.php.net/manual/en/migration54.new-features.php\" rel=\"nofollow noreferrer\">short array syntax (PHP 5.4)</a> - i.e. <code>[&quot;gif&quot;,&quot;jpeg&quot;,&quot;jpg&quot;,&quot;png&quot;]</code>.</p>\n<h2>Redundant lines</h2>\n<p>If you aren't familiar with the principle <a href=\"http://deviq.com/don-t-repeat-yourself/\" rel=\"nofollow noreferrer\">Don't repeat yourself</a> I recommend reading about it:</p>\n<blockquote>\n<p>The Don’t Repeat Yourself (DRY) principle states that duplication in logic should be eliminated via abstraction;</p>\n</blockquote>\n<p>Let's look at a few place that are redundant:</p>\n<blockquote>\n<pre><code>if ((($_FILES['upload_images']['type'][$i] == &quot;image/gif&quot;) \n|| ($_FILES['upload_images']['type'][$i] == &quot;image/jpeg&quot;)\n|| ($_FILES['upload_images']['type'][$i] == &quot;image/jpg&quot;)\n|| ($_FILES['upload_images']['type'][$i] == &quot;image/pjpeg&quot;)\n|| ($_FILES['upload_images']['type'][$i] == &quot;image/x-png&quot;)\n|| ($_FILES['upload_images']['type'][$i] == &quot;image/png&quot;))\n&amp;&amp; ($_FILES['upload_images']['size'][$i] &lt; 12000000)\n&amp;&amp; in_array($ext,array(&quot;gif&quot;,&quot;jpeg&quot;,&quot;jpg&quot;,&quot;png&quot;))){\n</code></pre>\n</blockquote>\n<p>The last conditional uses <code>in_array()</code> - why not use that for checking the type? That way there is no need to repeat <code>$_FILES['upload_images']['type'][$i]</code> for each type:</p>\n<pre><code>if (in_array($_FILES['upload_images']['type'][$i], \n [&quot;image/gif&quot;, &quot;image/jpeg&quot;, &quot;image/jpg&quot;, &quot;image/pjpeg&quot;, &quot;image/x-png&quot;, &quot;image/png&quot;])\n &amp;&amp; ($_FILES['upload_images']['size'][$i] &lt; 12000000)\n &amp;&amp; in_array($ext, [&quot;gif&quot;,&quot;jpeg&quot;,&quot;jpg&quot;,&quot;png&quot;])) {\n</code></pre>\n<p>Also the <code>switch</code> statement has three cases that do the same thing: <code>'jpg'</code>, <code>'jpeg'</code> and <code>default</code> - so those first to can be eliminated.</p>\n<h2>Tri-state variable <code>$is_jpg</code></h2>\n<p>This variable has three possible values, yet has a name that might be conceived as a boolean. And somebody reading the code might not know what the values <code>1</code>, <code>2</code> and <code>3</code> signify without scanning through the code to see where those values are assigned. I'd suggest eliminating it and instead of checking to see if the value is <code>1</code>, <code>2</code>, or <code>3</code>, check to see if <code>$ex</code> is <code>'jpg'</code>, <code>'png'</code>, or <code>'gif'</code> since those values are already being set.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-03T17:47:28.703", "Id": "251556", "ParentId": "245867", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T11:57:55.320", "Id": "245867", "Score": "6", "Tags": [ "performance", "php", "security", "image", "io" ], "Title": "upload multiple images and resize" }
245867
<p>I am currently reviewing CTCI(Cracking the Coding Interview)</p> <p>The question is asking me to implement an algorithm which checks whether the characters in a string are all unique however they do not want me to use any auxillary data structures</p> <p><strong>My Algorithm</strong> is relatively straight forward, Two nested loops one starting at 0(i) and another at 1(i+1)</p> <p>If the condition finds two characters that are equal then I print duplicate characters have been found.</p> <pre><code> public static void checkUnique(String s) { for(int i = 0; i&lt;s.length(); ++i) { for(int j = i +1; j&lt;s.length(); ++j) { if(s.charAt(i) == s.charAt(j)) { System.out.println(&quot;Duplicates found&quot;); } } } } </code></pre> <p>My question</p> <ol> <li>Is this an optimal algorithm, my second approach was to sort, and find a pair which contains the same characters.</li> <li>Obviously a hashmap would be beneficial here, but questions does not really want me to use it.</li> </ol> <p>I have refactored the code and hopefully now it is correct.</p> <p>Is there any way of reducing it to an O(N) runtime. What if we keep track of the Unicode code's for each char character. I doubt O(N^2) is the best we can do here.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T13:29:30.777", "Id": "482957", "Score": "0", "body": "Your implementation Is O(n^2) indeed. The sort approach would get you to O(n * log(n)). You can get to O(n) using a hashset. You can also do it in O(n) using an array of bools of size 256, which would effectively emulate a hashset for 1-byte characters. Not sure from what you wrote if you should not use data structures from standard library or if you are even asked to not implement them on your own..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T13:37:40.050", "Id": "482960", "Score": "0", "body": "Oh actually, your implementation Is O(n) but that's because It's flawed. It just does not do what you claim it does. That makes your question off topic here. Please test your code before posting the next time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T13:44:37.070", "Id": "482962", "Score": "0", "body": "How so, I have tested the inputs \"abcdefghijklmnopqrstuvwxyz\", it worked, similarly if included duplicate characters it still worked. Am i missing something here" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T13:46:25.353", "Id": "482963", "Score": "0", "body": "Try \"ABB\", your code only checks if the first character is duplicit, others are ignored." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T13:47:48.217", "Id": "482964", "Score": "0", "body": "`while(i<j) if (i==j) ...` Will never execute the body of the if." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T13:48:50.360", "Id": "482965", "Score": "0", "body": "oh shoot, it should of been while(i<=j) correct." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T13:51:21.973", "Id": "482966", "Score": "0", "body": "Nope, then charAt(i) == charAt(j) would be true for i==j, but that does not make it duplicit..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T13:52:18.237", "Id": "482967", "Score": "0", "body": "Just fix your code, add more tests, and post a new question and include those tests too!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T13:55:48.367", "Id": "482969", "Score": "0", "body": "Btw maybe if you iterate i from zero while < length-1 And j from i+1 while less then length, it would be easier to understand whats happening. There Is no reason why you would have to iterate backwards. It just makes it less intuitive IMO..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T14:08:53.927", "Id": "482971", "Score": "2", "body": "Love the question, but I voted to close since this is not working code. Please update the question with working code (include tests!!) so that after we can vote to re-open" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T15:18:24.990", "Id": "482985", "Score": "0", "body": "Hey thanks so much for the feedback hopefully it should work now haha" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T15:43:21.597", "Id": "482991", "Score": "1", "body": "For those in the VTC queue, the edit should fix the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T09:21:17.050", "Id": "483077", "Score": "0", "body": "Please don't add/remove/modify code in your question once answers start coming in." } ]
[ { "body": "<p>If I were your interviewer, I'd not hire you, because of that piece of code.</p>\n<p>The one absolute showstopper is that your method prints to System.out instead of returning a boolean.</p>\n<p>Even if no one told you explicitly, from a professional developer we expect that algorithms just compute something and give the results to their callers (by means of a boolean return value), and not write it to the user. But your solution mixes the algorithm with text output.</p>\n<p>Otherwise, your solution is okay, given the condition that no additional data structure is to be used (by the way, that's a strange condition, not representative for professional development).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T15:48:41.523", "Id": "482992", "Score": "0", "body": "What if I told you the solution in the book uses an int as a bitset to store occurrences? Would that count as an *auxiliary* data structure? https://stackoverflow.com/questions/19484406/detecting-if-a-string-has-unique-characters-comparing-my-solution-to-cracking" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T15:58:22.663", "Id": "482993", "Score": "1", "body": "@spyr03 Even with ASCII, the int need to be at least of the 128-bit variant, and in 2020, ASCII is simply outdated. With Unicode, you'd need an unlimited-length-integer (or at least some 200kbit), and that surely is an auxiliary data structure. And don't fall into the trap of operating on the UTF-8 representation bytes, that one will give wrong results." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T16:13:23.563", "Id": "482994", "Score": "1", "body": "So much this, you stole my answer ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T16:23:08.200", "Id": "482995", "Score": "0", "body": "Yea, I forgot to remove this. The Print was for testing purposes. My bad." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T14:37:43.510", "Id": "483113", "Score": "0", "body": "\"...given the condition that no additional data structure is to be used (by the way, that's a strange condition, not representative for professional development).\" - hardly, if the professional development environment is for embedded or high-performance computing. If I'm working on some wearable device and I've got 16KB to use for everything, I will be bending over backwards to avoid allocating additional data structures. Granted, that might not be the case on Windows or web servers or even in mobile phones nowadays, but even so." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T14:55:31.140", "Id": "483115", "Score": "0", "body": "@BittermanAndy Remember that we are talking about Java." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T16:53:35.633", "Id": "483122", "Score": "0", "body": "Fair point, well made, my objection (mostly) retracted, with apologies. Although... I would hope even Java devs would know the costs of allocating additional data structures. I'm a C# guy, but there are times when you want to be really, really sure there won't be a garbage collection. I assume the GC in Java works in a similar way? A corner case, though, to be sure." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T15:41:35.443", "Id": "245880", "ParentId": "245869", "Score": "1" } }, { "body": "<p>A way to optimize it would be to return as soon as you have found a duplicate, unless the question specifically asks you to list all duplicates.</p>\n<p>You could refactor it to something like that:</p>\n<pre><code>public static boolean checkUnique(String s) {\n int len = s.length();\n for (int i = 0; i &lt; len; i++) {\n int c = s.codePointAt(i);\n int next = s.indexOf(c, i + 1);\n if (next &gt; i) {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n<p>It isn't more efficient as your solution, but I doubt there is an algorithm that can do it better.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T03:24:51.077", "Id": "483050", "Score": "1", "body": "Early return sure. But lastIndexOf can only decrease performance. Further there Is also no point to use i++ over ++i, why you even mention it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T05:05:02.683", "Id": "483056", "Score": "0", "body": "lastIndexOf can decrease performance compared to what? I mentioned i++ because I find that easier to read." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T05:21:09.523", "Id": "483057", "Score": "0", "body": "Compared to scanning only those characters that can change the result. In every iteration you're going to scan one more character then you need to (unless you find a duplicate). But that's miniscule anyway. And for i++ being easier to read, that's just subjective. Either be explicit about that being your personal opinion or don't include it in your answer at all, as the answer should not be opinion based." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T07:13:31.880", "Id": "483069", "Score": "0", "body": "Ok, I changed both in my answer." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T19:16:37.517", "Id": "245886", "ParentId": "245869", "Score": "5" } } ]
{ "AcceptedAnswerId": "245886", "CommentCount": "13", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T12:44:49.313", "Id": "245869", "Score": "4", "Tags": [ "java", "strings", "interview-questions" ], "Title": "Checking if a string contains all unique characters" }
245869
<p>My <a href="https://github.com/georgebarwood/Rust" rel="nofollow noreferrer">exploration of Rust</a> continues. I'm quite pleased with the 2-step table lookup for decoding variable bit-length codes here, for some reason I found this tricky to work out, but now it's done I like it. InputBitStream has a required &quot;lifetime parameter&quot;, it seems these are not given meaningful names, which seems odd, but perhaps that's just how it is.</p> <pre><code>/// RFC 1951 inflate ( de-compress ). pub fn inflate( data: &amp;[u8] ) -&gt; Vec&lt;u8&gt; { let mut input = InputBitStream::new( &amp;data ); let mut output = Vec::new(); let _flags = input.get_bits( 16 ); loop { let last_block = input.get_bit(); let block_type = input.get_bits( 2 ); match block_type { 2 =&gt; dyn_block( &amp;mut input, &amp;mut output ), 1 =&gt; fixed_block( &amp;mut input, &amp;mut output ), 0 =&gt; copy_block( &amp;mut input, &amp;mut output ), _ =&gt; () } if last_block != 0 { break; } } // Check the checksum. input.clear_bits(); let check_sum = input.get_bits(32) as u32; if crate::compress::adler32( &amp;output ) != check_sum { panic!( &quot;Bad checksum&quot; ) } output } /// Decode block encoded with dynamic Huffman codes. fn dyn_block( input: &amp;mut InputBitStream, output: &amp;mut Vec&lt;u8&gt; ) { let n_lit = 257 + input.get_bits( 5 ); let n_dist = 1 + input.get_bits( 5 ); let n_len = 4 + input.get_bits( 4 ); // The lengths of the main Huffman codes (lit,dist) are themselves decoded by LenDecoder. let mut len = LenDecoder::new( n_len, input ); let lit : BitDecoder = len.get_decoder( n_lit, input ); let dist : BitDecoder = len.get_decoder( n_dist, input ); loop { let x : usize = lit.decode( input ); match x { 0..=255 =&gt; output.push( x as u8 ), 256 =&gt; break, _ =&gt; // LZ77 match code - replicate earlier output. { let mc = x - 257; let length = MATCH_OFF[ mc ] as usize + input.get_bits( MATCH_EXTRA[ mc ] as usize ); let dc = dist.decode( input ); let distance = DIST_OFF[ dc ] as usize + input.get_bits( DIST_EXTRA[ dc ] as usize ); copy( output, distance, length ); } } } } // end do_dyn /// Copy length bytes from output ( at specified distance ) to output. fn copy( output: &amp;mut Vec&lt;u8&gt;, distance: usize, mut length: usize ) { let mut i = output.len() - distance; while length &gt; 0 { output.push( output[ i ] ); i += 1; length -= 1; } } /// Decode length-limited Huffman codes. // For speed, a lookup table is used to compute symbols from the variable length codes ( rather than reading single bits ). // To keep the lookup table small, codes longer than PEEK bits are looked up in two operations. struct BitDecoder { nsym: usize, // The number of symbols. bits: Vec&lt;u8&gt;, // The length in bits of the code that represents each symbol. maxbits: usize, // The length in bits of the longest code. peekbits: usize, // The bit length for the first lookup ( not greater than PEEK ). lookup: Vec&lt;usize&gt; // The table used to look up a symbol from a code. } /// Maximum number of bits for first lookup. const PEEK : usize = 8; impl BitDecoder { fn new( nsym: usize ) -&gt; BitDecoder { BitDecoder { nsym, bits: vec![0; nsym], maxbits: 0, peekbits: 0, lookup: Vec::new() } } /// The main function : get a decoded symbol from the input bit stream. /// Codes of up to PEEK bits are looked up in a single operation. /// Codes of more than PEEK bits are looked up in two steps. fn decode( &amp;self, input: &amp;mut InputBitStream ) -&gt; usize { let mut sym = self.lookup[ input.peek( self.peekbits ) ]; if sym &gt;= self.nsym { sym = self.lookup[ sym - self.nsym + ( input.peek( self.maxbits ) &gt;&gt; self.peekbits ) ]; } input.advance( self.bits[ sym ] as usize ); sym } fn init_lookup( &amp;mut self ) { let mut max_bits : usize = 0; for bp in &amp;self.bits { let bits = *bp as usize; if bits &gt; max_bits { max_bits = bits; } } self.maxbits = max_bits; self.peekbits = if max_bits &gt; PEEK { PEEK } else { max_bits }; self.lookup.resize( 1 &lt;&lt; self.peekbits, 0 ); // Code below is from rfc1951 page 7. // bl_count is the number of codes of length N, N &gt;= 1. let mut bl_count : Vec&lt;usize&gt; = vec![ 0; max_bits + 1 ]; for sym in 0..self.nsym { bl_count[ self.bits[ sym ] as usize ] += 1; } let mut next_code : Vec&lt;usize&gt; = vec![ 0; max_bits + 1 ]; let mut code = 0; bl_count[ 0 ] = 0; for i in 0..max_bits { code = ( code + bl_count[ i ] ) &lt;&lt; 1; next_code[ i + 1 ] = code; } for sym in 0..self.nsym { let length = self.bits[ sym ] as usize; if length != 0 { self.setup_code( sym, length, next_code[ length ] ); next_code[ length ] += 1; } } } fn setup_code( &amp;mut self, sym: usize, len: usize, mut code: usize ) { if len &lt;= self.peekbits { let diff = self.peekbits - len; code &lt;&lt;= diff; for i in code..code + (1 &lt;&lt; diff) { // lookup index is reversed to match InputBitStream::peek self.lookup[ reverse( i, self.peekbits ) ] = sym; } } else { // Secondary lookup required let peekbits2 = self.maxbits - self.peekbits; // Split code into peekbits portion ( key ) and remainder ( code). let diff1 = len - self.peekbits; let key = reverse( code &gt;&gt; diff1, self.peekbits ); code &amp;= ( 1 &lt;&lt; diff1 ) - 1; // Get the base for the secondary lookup. let mut base = self.lookup[ key ]; if base == 0 // Secondary lookup not yet allocated for this key. { base = self.lookup.len(); self.lookup.resize( base + ( 1 &lt;&lt; peekbits2 ), 0 ); self.lookup[ key ] = self.nsym + base; } else { base -= self.nsym; } // Set the secondary lookup values. let diff = self.maxbits - len; code &lt;&lt;= diff; for i in code..code + (1&lt;&lt;diff) { self.lookup[ base + reverse( i, peekbits2 ) ] = sym; } } } } // end impl BitDecoder /// Decodes an array of lengths, returning a new BitDecoder. /// There are special codes for repeats, and repeats of zeros, per RFC 1951 page 13. struct LenDecoder { plenc: u8, // previous length code ( which can be repeated ) rep: usize, // repeat bd: BitDecoder } impl LenDecoder { fn new( n_len: usize, input: &amp;mut InputBitStream ) -&gt; LenDecoder { let mut result = LenDecoder { plenc: 0, rep:0, bd: BitDecoder::new( 19 ) }; // Read the array of 3-bit code lengths (used to encode the main code lengths ) from input. for i in CLEN_ALPHABET.iter().take( n_len ) { result.bd.bits[ *i as usize ] = input.get_bits(3) as u8; } result.bd.init_lookup(); result } fn get_decoder( &amp;mut self, nsym: usize, input: &amp;mut InputBitStream ) -&gt; BitDecoder { let mut result = BitDecoder::new( nsym ); let bits = &amp;mut result.bits; let mut i = 0; while self.rep &gt; 0 { bits[ i ] = self.plenc; i += 1; self.rep -= 1; } while i &lt; nsym { let lenc = self.bd.decode( input ) as u8; if lenc &lt; 16 { bits[ i ] = lenc; i += 1; self.plenc = lenc; } else { if lenc == 16 { self.rep = 3 + input.get_bits(2); } else if lenc == 17 { self.rep = 3 + input.get_bits(3); self.plenc=0; } else if lenc == 18 { self.rep = 11 + input.get_bits(7); self.plenc=0; } while i &lt; nsym &amp;&amp; self.rep &gt; 0 { bits[ i ] = self.plenc; i += 1; self.rep -= 1; } } } result.init_lookup(); result } } // end impl LenDecoder /// For reading bits from input array of bytes. struct InputBitStream&lt;'a&gt; { data: &amp;'a [u8], // Input data. pos: usize, // Position in input data. buf: usize, // Bit buffer. got: usize, // Number of bits in buffer. } impl &lt;'a&gt; InputBitStream&lt;'a&gt; { fn new( data: &amp;'a [u8] ) -&gt; InputBitStream { InputBitStream { data, pos: 0, buf: 1, got: 0 } } // Get n bits of input ( but do not advance ). fn peek( &amp;mut self, n: usize ) -&gt; usize { while self.got &lt; n { // Not necessary to check index, considering adler32 checksum is 32 bits. self.buf |= ( self.data[ self.pos ] as usize ) &lt;&lt; self.got; self.pos += 1; self.got += 8; } self.buf &amp; ( ( 1 &lt;&lt; n ) - 1 ) } // Advance n bits. fn advance( &amp;mut self, n:usize ) { self.buf &gt;&gt;= n; self.got -= n; } // Get a single bit. fn get_bit( &amp;mut self ) -&gt; usize { if self.got == 0 { self.peek( 1 ); } let result = self.buf &amp; 1; self.advance( 1 ); result } // Get n bits of input. fn get_bits( &amp;mut self, n: usize ) -&gt; usize { let result = self.peek( n ); self.advance( n ); result } // Get n bits of input, reversed. fn get_huff( &amp;mut self, mut n: usize ) -&gt; usize { let mut result = 0; while n &gt; 0 { result = ( result &lt;&lt; 1 ) + self.get_bit(); n -= 1; } result } // Discard any buffered bits. fn clear_bits( &amp;mut self ) { // Note: this might work right if peeking more than 8 bits. self.got = 0; } } // end impl InputBitStream /// Reverse a string of n bits. pub fn reverse( mut x:usize, mut n: usize ) -&gt; usize { let mut result: usize = 0; while n &gt; 0 { result = ( result &lt;&lt; 1 ) | ( x &amp; 1 ); x &gt;&gt;= 1; n -= 1; } result } /// Copy uncompressed block to output. fn copy_block( input: &amp;mut InputBitStream, output: &amp;mut Vec&lt;u8&gt; ) { input.clear_bits(); // Discard any bits in the input buffer let mut n = input.get_bits( 16 ); let _n1 = input.get_bits( 16 ); while n &gt; 0 { output.push( input.data[ input.pos ] ); n -= 1; input.pos += 1; } } /// Decode block encoded with fixed (pre-defined) Huffman codes. fn fixed_block( input: &amp;mut InputBitStream, output: &amp;mut Vec&lt;u8&gt; ) // RFC1951 page 12. { loop { // 0 to 23 ( 7 bits ) =&gt; 256 - 279; 48 - 191 ( 8 bits ) =&gt; 0 - 143; // 192 - 199 ( 8 bits ) =&gt; 280 - 287; 400..511 ( 9 bits ) =&gt; 144 - 255 let mut x = input.get_huff( 7 ); // Could be optimised. if x &lt;= 23 { x += 256; } else { x = ( x &lt;&lt; 1 ) + input.get_bit(); if x &lt;= 191 { x -= 48; } else if x &lt;= 199 { x += 88; } else { x = ( x &lt;&lt; 1 ) + input.get_bit() - 256; } } match x { 0..=255 =&gt; { output.push( x as u8 ); } 256 =&gt; { break; } _ =&gt; // 257 &lt;= x &amp;&amp; x &lt;= 285 { x -= 257; let length = MATCH_OFF[x] as usize + input.get_bits( MATCH_EXTRA[ x ] as usize ); let dcode = input.get_huff( 5 ); let distance = DIST_OFF[dcode] as usize + input.get_bits( DIST_EXTRA[dcode] as usize ); copy( output, distance, length ); } } } } // end fixed_block // RFC 1951 constants. pub static CLEN_ALPHABET : [u8; 19] = [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; pub static MATCH_OFF : [u16; 30] = [ 3,4,5,6, 7,8,9,10, 11,13,15,17, 19,23,27,31, 35,43,51,59, 67,83,99,115, 131,163,195,227, 258, 0xffff ]; pub static MATCH_EXTRA : [u8; 29] = [ 0,0,0,0, 0,0,0,0, 1,1,1,1, 2,2,2,2, 3,3,3,3, 4,4,4,4, 5,5,5,5, 0 ]; pub static DIST_OFF : [u16; 30] = [ 1,2,3,4, 5,7,9,13, 17,25,33,49, 65,97,129,193, 257,385,513,769, 1025,1537,2049,3073, 4097,6145,8193,12289, 16385,24577 ]; pub static DIST_EXTRA : [u8; 30] = [ 0,0,0,0, 1,1,2,2, 3,3,4,4, 5,5,6,6, 7,7,8,8, 9,9,10,10, 11,11,12,12, 13,13 ]; </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T12:52:37.983", "Id": "245870", "Score": "1", "Tags": [ "rust", "compression" ], "Title": "RFC 1951 \"Inflate\" (de-compression)" }
245870
<p>My implementation of a Sudoku solver. It isn't done using the most naive way but still it does an exhaustive search with some assistance from a heap. The only constraints I have used is the basic rules of Sudoku (a number can occur only once in a row, column and it's box). There probably are more techniques or reasonings with which it can be improved but before that I would like to get this as optimized as possible. I would appreciate any advice on how to make it faster and how my code can be made compatible with modern C++ best practices. Thank you for your time!</p> <p>Edit: I forgot to mention the main idea here. The heap is used to choose the next cell having the least total of possible numbers it can be filled with. When you place one of the possible numbers in that cell say <code>n</code> in cell <code>(x, y)</code>, then <code>n</code> is removed from the list of possibilities of all cells in row <code>x</code>, column <code>y</code> and the box which <code>(x, y)</code> belongs to AND these changes are reflected in the heap. To backtrack, <code>n</code> is added back to those lists (these changes too are reflected in the heap). When the heap becomes empty, all cells have been filled and we have found a solution.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;unordered_map&gt; using namespace std; // table to calculate no. of set bits in a number vector&lt;int&gt; bitset_table(256); // function to print the board ostream&amp; operator&lt;&lt; (ostream&amp; out, const vector&lt;vector&lt;int&gt;&gt;&amp; M) { for (const vector&lt;int&gt;&amp; V : M) { for (int e : V) out &lt;&lt; e &lt;&lt; ' '; out &lt;&lt; endl; } return out; } // function used by heap to order it's elements based on the contents of `*ptr1` and `*ptr2` bool isLower(const int* ptr1, const int* ptr2) { int size1, size2; size1 = bitset_table[*ptr1 &amp; 0xff] + bitset_table[*ptr1 &gt;&gt; 8 &amp; 0xff] + bitset_table[*ptr1 &gt;&gt; 16 &amp; 0xff] + bitset_table[*ptr1 &gt;&gt; 24 &amp; 0xff]; size2 = bitset_table[*ptr2 &amp; 0xff] + bitset_table[*ptr2 &gt;&gt; 8 &amp; 0xff] + bitset_table[*ptr2 &gt;&gt; 16 &amp; 0xff] + bitset_table[*ptr2 &gt;&gt; 24 &amp; 0xff]; return size1 &lt; size2; } class Heap { private: int heap_size; // no. of elements in the heap vector&lt;int*&gt; A; // heap container of elementes of type `int*` (for 1 by 1 mapping), note that `A.size()` can be greater than `heap_size` unordered_map&lt;int*, int&gt; mapping; // mapping to keep track of the index of `int*` in `A` int parent(int i) { return (i - 1) / 2; } int left(int i) { return 2 * i + 1; } int right(int i) { return 2 * i + 2; } // taken from CLRS. Puts A[i] at the correct place by &quot;heapifying&quot; the heap (requires A[left(i)] and A[right(i)] to follow heap propertey.) void minHeapify(int i) { int l, r, smallest; l = left(i); r = right(i); smallest = i; if (l &lt; heap_size &amp;&amp; isLower(A[l], A[i])) smallest = l; if (r &lt; heap_size &amp;&amp; isLower(A[r], A[smallest])) smallest = r; if (smallest != i) { swap(mapping[A[i]], mapping[A[smallest]]); swap(A[i], A[smallest]); minHeapify(smallest); } } // updated key at A[i] is pushed towards the top of the heap if it's priority is high otherwise towards the bottom. void heapUpdateKey(int i) { if (i == 0 || !isLower(A[i], A[parent(i)])) minHeapify(i); else { int p = parent(i); while (i &gt; 0 &amp;&amp; isLower(A[i], A[p])) { swap(mapping[A[i]], mapping[A[p]]); swap(A[i], A[p]); i = p; p = parent(i); } } } public: Heap() : heap_size(0) {} // `opt = 0` means delete `val` from `*ptr`, otherwise insert. // if it fails to detele, return false. (this fact is used in `search` method) bool heapUpdateKey(int *ptr, int opt, int val) { if (mapping.find(ptr) == mapping.cend() || (opt == 0 &amp;&amp; !(*ptr &amp; (1 &lt;&lt; val)))) return false; if (opt == 0) *ptr &amp;= ~(1 &lt;&lt; val); else *ptr |= 1 &lt;&lt; val; heapUpdateKey(mapping[ptr]); return true; } // inserts element at the end of the heap and calls `heapUpdateKey` on it void insert(int *ptr) { if (heap_size &lt; A.size()) A[heap_size] = ptr; else A.push_back(ptr); mapping[ptr] = heap_size; heapUpdateKey(heap_size++); } // returns the element at the top of the heap and heapifies the rest of the heap. int* heapExtractMin() { //if (heap_size == 0) //return nullptr; int *res = A[0]; mapping.erase(res); A[0] = A[--heap_size]; mapping[A[0]] = 0; minHeapify(0); return res; } bool isEmpty() { return heap_size == 0; } }; class Solve { private: int N; // recursive function which basically performs an exhaustive search using backtracking bool search(Heap&amp; H, unordered_map&lt;int*, unordered_map&lt;int, vector&lt;int*&gt;&gt;&gt;&amp; adj, vector&lt;vector&lt;int&gt;&gt;&amp; board, unordered_map&lt;int*, pair&lt;int, int&gt;&gt;&amp; mapping) { if (H.isEmpty()) return true; int *ptr = H.heapExtractMin(); pair&lt;int, int&gt;&amp; p = mapping[ptr]; for (int k = 1; k &lt;= N; ++k) if (*ptr &amp; (1 &lt;&lt; k)) { board[p.first][p.second] = k; vector&lt;int*&gt; deleted_from; for (int *ptr2 : adj[ptr][k]) if (H.heapUpdateKey(ptr2, 0, k)) deleted_from.push_back(ptr2); if (search(H, adj, board, mapping)) return true; for (int *ptr2 : deleted_from) H.heapUpdateKey(ptr2, 1, k); } H.insert(ptr); return false; } public: Solve() {} Solve(vector&lt;vector&lt;int&gt;&gt;&amp; board) : N(board.size()) { int n = (int)ceil(sqrt(N)); if (n*n != N) exit(0); // look at already filled cells like number 5 at cell say (x, y). // set the 5th bit at rows[x], columns[y] and the 3x3 (for 9x9 Sudoku) box which (x, y) belongs to. vector&lt;int&gt; rows(N), columns(N), boxes(N); for (int i = 0; i &lt; N; ++i) for (int j = 0; j &lt; N; ++j) if (board[i][j]) { int bit = 1 &lt;&lt; board[i][j]; rows[i] |= bit; columns[j] |= bit; boxes[(i / n)*n + (j / n)] |= bit; } // possibilities[i][j] = list of numbers which the cell (i, j) can be filled with. // &amp;possibilities[i][j] is the pointer int* used in the heap. vector&lt;vector&lt;int&gt;&gt; possibilities(N, vector&lt;int&gt;(N)); // mapping used in `search` method to get the coordinates (i, j) which &amp;possibilities[i][j] represents. unordered_map&lt;int*, pair&lt;int, int&gt;&gt; mapping; // look at yet to be filled cells and calculate it's possibilities[i][j] for (int i = 0; i &lt; N; ++i) for (int j = 0; j &lt; N; ++j) if (!board[i][j]) { mapping.emplace(&amp;possibilities[i][j], make_pair(i, j)); for (int k = 1; k &lt;= N; ++k) { int bit = 1 &lt;&lt; k; if (!(rows[i] &amp; bit) &amp;&amp; !(columns[j] &amp; bit) &amp;&amp; !(boxes[(i / n)*n + (j / n)] &amp; bit)) possibilities[i][j] |= bit; } } // adjacency list used in 'search' method. // adj[p][k] is the list of pointers (of cells, i.e., &amp;possibilities[i][j]) which are adjacent to cell at pointer p (same row, column and box) // and have their kth bit set. It seems complex and conjested but it simply creates adjencty list for adj[p][k] for all values of p and k. unordered_map&lt;int*, unordered_map&lt;int, vector&lt;int*&gt;&gt;&gt; adj; for (int i = 0; i &lt; N; ++i) for (int j = 0; j &lt; N; ++j) if (possibilities[i][j]) { for (int k = 0; k &lt; N; ++k) if (!board[i][k] &amp;&amp; k / n != j / n) for (int l = 1; l &lt;= N; ++l) if (possibilities[i][k] &amp; (1 &lt;&lt; l)) adj[&amp;possibilities[i][j]][l].push_back(&amp;possibilities[i][k]); for (int k = 0; k &lt; N; ++k) if (!board[k][j] &amp;&amp; k / n != i / n) for (int l = 1; l &lt;= N; ++l) if (possibilities[k][j] &amp; (1 &lt;&lt; l)) adj[&amp;possibilities[i][j]][l].push_back(&amp;possibilities[k][j]); int ti, tj; ti = (i / n)*n, tj = (j / n)*n; for (int tti = 0; tti &lt; n; ++tti) for (int ttj = 0; ttj &lt; n; ++ttj) if (!board[ti + tti][tj + ttj] &amp;&amp; (ti + tti != i || tj + ttj != j)) for (int l = 1; l &lt;= N; ++l) if (possibilities[ti + tti][tj + ttj] &amp; (1 &lt;&lt; l)) adj[&amp;possibilities[i][j]][l].push_back(&amp;possibilities[ti + tti][tj + ttj]); } // create heap and insert the address (int*) of the list of possibilities of unfilled cells. Heap H; for (int i = 0; i &lt; N; ++i) for (int j = 0; j &lt; N; ++j) if (possibilities[i][j]) H.insert(&amp;possibilities[i][j]); if (search(H, adj, board, mapping)) cout &lt;&lt; board &lt;&lt; endl; } }; int main() { // fill the bitset_table (bitset_table[i] = no. of set bits of i) for (int i = 1; i &lt; bitset_table.size(); ++i) bitset_table[i] = (i &amp; 1) + bitset_table[i / 2]; int N; cin &gt;&gt; N; vector&lt;vector&lt;int&gt;&gt; board(N, vector&lt;int&gt;(N)); for (int i = 0; i &lt; N; ++i) for (int j = 0; j &lt; N; ++j) cin &gt;&gt; board[i][j]; Solve obj(board); } </code></pre> <hr /> <p>Some puzzles you can try:</p> <pre><code>9 8 0 0 0 0 0 0 0 0 0 0 3 6 0 0 0 0 0 0 7 0 0 9 0 2 0 0 0 5 0 0 0 7 0 0 0 0 0 0 0 4 5 7 0 0 0 0 0 1 0 0 0 3 0 0 0 1 0 0 0 0 6 8 0 0 8 5 0 0 0 1 0 0 9 0 0 0 0 4 0 0 16 0 2 14 0 0 0 16 4 0 0 0 1 0 0 5 0 0 0 9 0 0 10 0 1 0 0 0 0 0 4 0 0 0 0 0 0 13 6 0 0 0 14 0 0 15 12 0 16 6 5 10 0 8 2 0 0 0 12 0 0 0 1 0 7 9 0 5 4 1 0 0 2 0 0 0 0 12 0 7 0 0 0 0 0 11 0 0 13 0 3 0 0 0 0 0 1 0 0 0 0 16 0 0 0 13 10 15 9 14 0 4 0 10 0 0 11 0 4 8 15 0 0 0 0 5 0 13 0 0 11 0 1 0 0 0 0 10 7 4 0 3 0 0 6 0 7 0 2 14 16 6 10 0 0 0 11 0 0 0 0 16 0 0 0 0 0 1 0 12 0 0 14 0 0 0 0 0 4 0 10 0 0 0 0 15 0 0 2 16 5 0 11 11 0 12 0 0 0 14 0 0 0 13 7 0 9 6 2 8 0 7 9 0 0 11 0 0 0 14 10 0 0 0 0 0 0 4 0 0 0 0 0 11 0 2 0 0 8 0 0 0 6 0 0 12 0 0 0 9 8 0 0 0 14 1 0 25 0 0 12 6 0 0 7 0 18 0 5 24 0 10 1 0 0 4 0 0 0 0 0 0 0 2 0 19 0 13 0 0 0 10 0 0 0 0 0 0 0 0 18 5 0 0 0 0 0 1 0 0 0 0 0 0 0 22 0 0 0 0 3 0 2 0 0 14 12 0 16 8 25 0 0 0 16 0 0 0 2 23 0 0 13 12 22 0 0 0 21 15 19 3 0 0 0 0 14 0 23 0 24 0 0 0 0 0 25 8 4 0 16 19 21 0 0 7 0 0 0 3 12 0 9 0 4 0 2 0 0 0 0 0 0 0 10 0 24 12 17 16 0 0 0 5 0 0 0 0 0 0 9 0 0 6 25 0 0 0 8 0 5 3 0 0 0 0 0 0 20 0 0 18 19 15 0 10 11 0 0 0 18 12 19 0 0 0 0 0 0 0 23 0 0 7 0 0 4 0 0 0 0 0 0 0 0 14 0 22 0 0 18 16 20 0 6 11 13 0 0 0 0 0 0 0 22 0 25 0 0 1 17 5 4 7 0 0 14 0 8 3 21 0 0 11 0 0 0 6 0 20 13 15 0 0 0 0 0 0 9 0 0 2 0 25 0 1 8 0 0 5 0 21 0 0 1 0 0 0 0 16 10 0 7 0 0 4 20 0 0 9 0 0 14 0 24 0 17 0 25 2 5 0 0 0 0 0 13 0 0 0 0 0 22 0 0 0 0 0 19 1 8 0 0 0 0 7 21 0 0 12 0 2 17 0 0 0 18 6 16 0 0 15 0 0 13 0 10 0 8 10 18 12 16 9 0 0 0 5 0 0 0 0 19 0 0 17 0 21 0 15 0 0 22 0 8 0 0 15 0 3 0 6 0 21 0 0 7 0 18 14 5 0 1 0 0 0 0 0 0 0 0 19 0 1 0 16 11 0 0 0 10 22 25 15 0 0 0 0 0 0 21 0 0 0 3 1 0 21 0 0 4 0 0 0 0 2 0 13 0 24 25 0 0 14 0 0 6 0 0 0 0 0 0 0 0 15 0 12 14 0 6 17 24 0 0 0 0 0 0 0 13 0 0 0 5 23 16 4 0 13 24 7 2 0 9 0 0 15 3 0 22 0 0 0 0 0 0 8 0 0 25 20 2 0 19 0 0 0 0 1 0 0 0 0 21 3 0 0 12 0 0 0 0 16 12 0 5 0 11 21 0 23 0 0 15 0 0 0 0 19 9 0 0 0 0 0 25 10 0 0 0 0 9 20 22 7 4 0 3 0 14 25 18 0 11 0 0 0 0 0 1 0 15 24 0 6 0 22 8 0 25 14 0 10 11 0 9 0 20 1 16 0 7 0 23 0 0 13 14 13 21 1 0 0 5 0 0 0 6 0 22 0 23 10 0 0 0 2 0 0 18 7 11 </code></pre> <p>The 9x9 is supposedly the &quot;hardest 9x9 Sudoku puzzle&quot;. Takes no time. The 16x16 is another hard one and takes about 20 minutes on my machine lol.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T17:32:11.527", "Id": "483002", "Score": "0", "body": "The 16x16 one takes 7 seconds on my PC, that's too much difference to ignore. Are you timing the debug build?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T17:41:34.150", "Id": "483003", "Score": "0", "body": "@harold I'm using Visual Studio 2017. And I'm running it with \"start without debugging\" option. Shall I optimize it? I have seen people do it but have never done it myself. But 7 seconds is unimaginable to me. Have you checked if the answer is right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T17:43:02.797", "Id": "483004", "Score": "0", "body": "The answer looks fine to me. \"Start without debugger\" only does just that, that choice is independent of whether the Debug or Release build is used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T17:48:18.760", "Id": "483007", "Score": "0", "body": "@harold wow I just set it to release and it's super fast < 10s. Thank you. There is another hard 25x25 you can try. I'll post it in question. Thank you so much for this!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T18:22:49.243", "Id": "483010", "Score": "0", "body": "I tried running the 25x25 for half an hour and it was able to place atmost 484 (out of 625) correct numbers without breaking any rules. Oh well, maybe some randomization would do the trick." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T18:51:50.097", "Id": "483132", "Score": "0", "body": "This is what happens when you use `O(n^3)` algorithm. With small values of `n` it works fine but it quickly becomes unusable. That is why Bubble Sort `O(n^2)` is a great sorting tool because of its low overhead when n is small but terrible when n becomes large." } ]
[ { "body": "<h1>Freebies</h1>\n<p>Looking at the performance profile for the 16x16 puzzle (there is a profiler built into Visual Studio 2017, which you said you are using, and I used that, so you can reproduce this), I see that <code>deleted_from.push_back(ptr2);</code> is hotter than it deserves. That indicates the vector is growing too often.</p>\n<p>So change this:</p>\n<pre><code>vector&lt;int*&gt; deleted_from;\n</code></pre>\n<p>To this:</p>\n<pre><code>vector&lt;int*&gt; deleted_from(8);\n</code></pre>\n<p>Before: 6 seconds. After: 5.5 seconds. That's significant, but a trivial change to the code.</p>\n<p>Reading between the lines of the profile, it turns out that <code>isLower</code> is taking a substantial amount of time. It is not directly implicated by the profile, but the places where it is called are redder than they ought to be. It really should be trivial, but it's not.</p>\n<p>Here is an other way to write it:</p>\n<pre><code>#include &lt;intrin.h&gt;\n\n...\n\n// function used by heap to order it's elements based on the contents of `*ptr1` and `*ptr2`\nbool isLower(const int* ptr1, const int* ptr2)\n{\n return _mm_popcnt_u32(*ptr1) &lt; _mm_popcnt_u32(*ptr2);\n}\n</code></pre>\n<p>Before: 5.5 seconds. After: 5.0 seconds. That's nice, and it even made the code simpler.</p>\n<h1>The Heap</h1>\n<p>It should be no surprise that a lot of time is spent on modifying the heap. So let's tinker with it.</p>\n<p>This logic:</p>\n<blockquote>\n<pre><code> if (l &lt; heap_size &amp;&amp; isLower(A[l], A[i]))\n smallest = l;\n if (r &lt; heap_size &amp;&amp; isLower(A[r], A[smallest]))\n smallest = r;\n</code></pre>\n</blockquote>\n<p>Can be rewritten to:</p>\n<pre><code>if (r &lt; heap_size)\n{\n smallest = isLower(A[l], A[r]) ? l : r;\n smallest = isLower(A[i], A[smallest]) ? i : smallest;\n}\nelse if (l &lt; heap_size)\n smallest = isLower(A[l], A[i]) ? l : i;\n</code></pre>\n<p>It looks like it should be about the same, but it's not.</p>\n<p>Before: 5.0 seconds. After: 2.0 seconds.</p>\n<p>What?! The biggest difference I saw in the disassembly of the function was that <code>cmovl</code> was used this way, but not before. Conditional-move is better than a badly-predicted branch, but worse than a well-predicted branch - it makes sense that these branches would be badly predicted, after all they depend on which path the data item takes &quot;down the heap&quot;, which is some semi-randomly zig-zagging path.</p>\n<p>This on the other hand does <em>not</em> help:</p>\n<pre><code>smallest = (l &lt; heap_size &amp;&amp; isLower(A[l], A[i])) ? l : i;\nsmallest = (r &lt; heap_size &amp;&amp; isLower(A[r], A[smallest])) ? r : smallest;\n</code></pre>\n<p>When MSVC chooses to use a cmov or not is a mystery. Clearly it has a large impact, but there seems to be no reliable way to ask for a cmov.</p>\n<p>An extra trick is using that what this &quot;minHeapify&quot; is doing is moving items up the heap along a path, and dropping the item which it was originally called on into the open spot at the end. That isn't <em>how</em> it's doing it though: it's doing a lot of swaps. In total it's doing twice as many assignments as are necessary. That could be changed such as this:</p>\n<pre><code>void minHeapify(int i)\n{\n int l, r, smallest;\n int* item = A[i];\n do {\n l = left(i);\n r = right(i);\n smallest = i;\n\n if (r &lt; heap_size)\n {\n smallest = isLower(A[l], A[r]) ? l : r;\n smallest = isLower(item, A[smallest]) ? i : smallest;\n }\n else if (l &lt; heap_size)\n smallest = isLower(A[l], item) ? l : i;\n\n if (smallest == i)\n break;\n\n A[i] = A[smallest];\n mapping[A[i]] = i;\n i = smallest;\n } while (1);\n\n A[i] = item;\n mapping[item] = i;\n}\n</code></pre>\n<p>Before: 2.0 seconds. After: 1.85 seconds.</p>\n<h1><code>unordered_map</code></h1>\n<p>Often some other hash map can do better than the default <code>unordered_map</code>. For example you could try Boost's version of <code>unordered_map</code>, or Abseil's <code>flat_hash_map</code>, or various others. There are too many to list.</p>\n<p>In any case, with Skarupke's <code>flat_hash_map</code>, the time went from 1.85 seconds to 1.8 seconds. Not amazing, but it's as simple as including a header and changing <code>unordered_map</code> to <code>ska::flat_hash_map</code>.</p>\n<p>By the way, for MSVC specifically, <code>unordered_map</code> is a common reason for poor performance of the Debug build. It's not nearly as bad for the Release build.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T21:01:39.530", "Id": "483030", "Score": "0", "body": "Thanks for answering my question. The `deleted_from` can contain all adjacent cells of a particular cell (column, row and box). Doing some simple arithmetic give me it's maximum (when board is empty) to be `3*N - 2*sqrt(N)-1`. The heap changes helped a lot. I guess 'heapUpdateKey` could be updated too as there are many unnecessary swaps. I'll try using boost's `unordered_map`. Also what tools do you use to look into a function?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T21:07:58.293", "Id": "483031", "Score": "1", "body": "@lucieon I only used Visual Studio itself, you can set a breakpoint somewhere and when it's hit, right click and select \"Go to disassembly\"" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T20:04:01.117", "Id": "245889", "ParentId": "245874", "Score": "1" } } ]
{ "AcceptedAnswerId": "245889", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T14:12:38.730", "Id": "245874", "Score": "3", "Tags": [ "c++", "sudoku" ], "Title": "Generalised NxN Sudoku solver using heap" }
245874
<p>I have written a program that will determine the height of a <a href="https://en.wikipedia.org/wiki/Tetris" rel="nofollow noreferrer">Tetris board</a> after a sequence of moves are made. These inputs are in the form of a comma-delimited list, and look like <code>&lt;piece&gt;&lt;position&gt;</code>. List of pieces:</p> <ul> <li><code>I</code> - this is a 1x4 piece lying on its side</li> <li><code>Q</code> - this is a 2x2 square piece</li> <li><code>T</code> - this is a T-shaped piece</li> <li><code>Z</code> - this is a left-facing 2x2 offset</li> <li><code>S</code> - this is a right-facing 2x2 offset</li> <li><code>L</code> - this is a right-facing L</li> <li><code>J</code> - this is a left-facing L</li> </ul> <p>Image (<a href="http://www.kineticallyconstrained.com/2010/07/statistical-mechanics-of-tetris.html" rel="nofollow noreferrer">source</a>) of the pieces. Pieces are always in the same orientation as below. <a href="https://i.stack.imgur.com/CbBIa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CbBIa.png" alt="Visual representation of the shapes" /></a></p> <p>I've diagrammed them out below as well. Rotation is not in scope for this problem (e.g. a vertical <code>I</code> is out of scope).</p> <pre><code>I - xxxx Q - xx xx T - xxx x Z - xx xx S - xx xx L - x x xx J - x x xx </code></pre> <p>Positions are 0-indexed, and represent a location from the left side of the board (the board is 10-wide).</p> <p><strong>Example 1:</strong></p> <p>Input: <code>I0,Q4</code></p> <p>Output: <code>2</code></p> <p>Board:</p> <pre><code>bbbbQQbbbb IIIIQQbbbb </code></pre> <p>(<code>b</code> represents a blank space, and the blank lines above this are left out)</p> <p><strong>Example 2</strong></p> <p>Input: <code>Q0,Q2,Q4,Q6,Q8</code></p> <p>Output: 0</p> <p>Board (intentionally left blank):</p> <pre><code></code></pre> <p>Explanation: Using normal Tetris rules, a row is removed whenever every block in a row is filled. This sequence would place 5 square cubes evenly spaced along the bottom, which then removes those two rows.</p> <pre class="lang-py prettyprint-override"><code>class Tetris: def __init__(self): self.board =[] self.pieces = { 'I' : [[1,1,1,1]], 'Q' : [[1,1], [1,1]], 'T': [[1,1,1], [0,1,0]], 'Z':[[1,1,0], [0,1,1]], 'S':[[0,1,1], [1,1,0]], 'L':[[1,0], [1,0], [1,1]], 'J':[[0,1], [0,1], [1,1]]} def newRow(self): return [0 for _ in range(10)] def doesThePieceFit(self,row,pieceName,pos): #checks to see if a piece fits on the row at given position #check bottom to the top piece = self.pieces[pieceName] for i in range(len(piece)): pieceRow = piece[-1*(1+i)] if i+row == len(self.board): return True boardRow = self.board[i+row] for j in range(len(pieceRow)): if pieceRow[j] and boardRow[pos+j]: return False return True def removeFullRows(self,startRow,numRows): #removes full rows from the board #only checks rows between startRow and startRow+numRows fullRows = [i+startRow for i in range(numRows) if all(self.board[i+startRow])] for fullRow in sorted(fullRows,reverse=True): del self.board[fullRow] def addPieceAt(self,row,pieceName,pos): #Adds piece at this row. piece = self.pieces[pieceName] for i in range(len(piece)): pieceRow = piece[-1*(1+i)] if i+row == len(self.board): self.board+=self.newRow(), boardRow = self.board[i+row] for j in range(len(pieceRow)): if pieceRow[j]: boardRow[pos+j] = pieceRow[j] self.removeFullRows(row,len(piece)) def addPiece(self,pieceName,pos): #1.find the first row where piece is blocked #2.Add the piece at the row above it blockedByRow = None for row in range(len(self.board)-1,-1,-1): if not self.doesThePieceFit(row,pieceName,pos): blockedByRow = row break targetRow = 0 if blockedByRow == None else blockedByRow+1 self.addPieceAt(targetRow,pieceName,pos) def addPieces(self,pieces): for piece in pieces.split(','): self.addPiece(piece[0],int(piece[1])) return len(self.board) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T19:15:19.807", "Id": "483017", "Score": "1", "body": "This is a very good question, well detailed, interesting and even with images! You will become a great contributor of this site :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T19:18:04.347", "Id": "483019", "Score": "0", "body": "Your second example board is empty?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T22:01:34.443", "Id": "483036", "Score": "2", "body": "@Reinderien yes - because all rows have been cleared" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T01:23:36.327", "Id": "483046", "Score": "1", "body": "@Caridorc thank you. The credit goes to @ Dannno :D" } ]
[ { "body": "<ol>\n<li><p><strong>Use Booleans instead of Integers:</strong> The code uses integers to check if a cell is occupied or not. Example: Replace <code>I = [1,1,1,1]</code> with <code>I=[True,True,True,True]</code></p>\n</li>\n<li><p><strong>Mark internal functions with underscores:</strong> By python convention, any function that is not meant to be invoked from outside the class is usually marked with underscores. Example: Replace <code>def addPiece(...)</code> with <code>def _addPiece_(...)</code>.</p>\n</li>\n<li><p><strong>Use meaningful variable names:</strong> Use meaningful names for variables (including iterator variables) Don't use arbitrary names like i or j. Looking at the variable names, it isn't clear whether <code>doesThePieceFit</code> validates columns at all</p>\n</li>\n<li><p><strong>Handling invalid input:</strong> You can return an error value (throw a python error or return integer value -1) for invalid inputs. (Such as I9 on a size 10 board)</p>\n</li>\n</ol>\n<hr />\n<p>Also, if you can change the input format, you can make some minor changes to make this code more useful. You can change the constructor to <code>__init__(self,size)</code> instead of fixing the size to 10. Also, you can change the input format from string <code>&quot;Q0,Q2&quot;</code> to list <code>[[&quot;Q&quot;,0],[&quot;Q&quot;,2]]</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T18:46:42.197", "Id": "483012", "Score": "0", "body": "You _should not_ use the `__dunder__` method to mark \"internal\" functions. If you want, you can use `_one_under` to mark internal, and `__two_under` if you need name mangling too (you almost never need name mangling)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T18:49:04.673", "Id": "483013", "Score": "0", "body": "@Dannnno fixed it" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T18:32:20.083", "Id": "245883", "ParentId": "245876", "Score": "0" } }, { "body": "<p>The first thing I did was use <a href=\"https://black.now.sh/?version=stable\" rel=\"nofollow noreferrer\">Black</a> to reformat the code - yours is pretty good, but there are some minor style complaints I had (generally around the lack of whitespace in a few places). Additionally, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> defines the naming conventions in python - generally, <code>prefer_this</code> <code>notThis</code>.</p>\n<p>Lastly, all of your methods should have docstrings. I haven't added this b/c it isn't as pertinent to the code review, but it is good practice in general.</p>\n<p>From there, I thought about your actual approach. At a high level you:</p>\n<ul>\n<li>Create a new instance of the object</li>\n<li>Pass it a string, parse the string, and process each token</li>\n<li>Attempt to fit pieces</li>\n<li>Clear full rows</li>\n</ul>\n<p>None of that is inherently bad, but I think it can be tightened up a bit.</p>\n<h2>User Input</h2>\n<p>Right now you don't have any validation of the user inputs - we're being very trusting that the values that are provided will be usable. We probably want to do this validation</p>\n<p>Additionally, I don't think that the <code>Tetris</code> class should be responsible for handling the comma-delimited string - it should just take a piece and a position, and something else should be responsible for taking the input and translating it into arguments. If you're feeling friendly, a <a href=\"https://stackoverflow.com/a/1669524/3076272\"><code>@classmethod</code></a> might be appropriate. Lastly, I think this class method should return the board, not the height, so I added a new <code>height</code> property to the class. I ended up with something like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>pieces = {\n &quot;I&quot;: ((True, True, True, True)),\n &quot;Q&quot;: ((True, True), (True, True)),\n &quot;T&quot;: ((True, True, True), (False, True, False)),\n &quot;Z&quot;: ((True, True, False), (False, True, True)),\n &quot;S&quot;: ((False, True, True), (True, True, False)),\n &quot;L&quot;: ((True, False), (True, False), (True, True)),\n &quot;J&quot;: ((False, True), (False, True), (True, True)),\n}\n\n@classmethod\ndef add_pieces(cls, user_input):\n board = Tetris()\n for piece in user_input.split(&quot;,&quot;):\n if len(piece) &gt; 2:\n raise ValueError(f&quot;Piece {piece} is malformed&quot;)\n piece_id = piece[0]\n drop_position = piece[1]\n if not Tetris.is_valid_piece(piece_id):\n raise ValueError(f&quot;Piece {piece_id} is not a valid Tetris piece&quot;)\n if not Tetris.is_valid_drop_location(drop_position):\n raise IndexError(\n f&quot;Drop location {drop_position} is not a valid board location&quot;\n )\n board.add_piece(piece_id, drop_position)\n return board\n\n@classmethod\ndef is_valid_piece(cls, piece_id):\n return piece_id in cls.pieces\n\n@classmethod\ndef is_valid_drop_location(drop_position):\n try:\n int(drop_position)\n except ValueError:\n return False\n\n return drop_position &gt;= 0 and drop_position &lt; 10\n\n@property\ndef height(self):\n return self.board.length\n\n</code></pre>\n<p>You'll also notice that I moved <code>Tetris.pieces</code> into a class attribute instead of an instance attribute - this is because it should be the same everywhere. I also changed <code>0/1</code> to <code>True/False</code> because it is a binary value (I think an <code>enum</code> is probably best to be explicit, e.g. <code>boardState.FULL</code> and <code>boardState.EMPTY</code>). Lastly, I changed from nested lists to nested tuples - this is because tuples are immutable, and you never need to change the shape definition.</p>\n<h2>OOP</h2>\n<p>I wonder if it is worthwhile making a separate class to represent the pieces, and then you can do something like <code>TetrisPiece.fitsAtLocation(board, location)</code>. I haven't fully thought about what this would look like or if it is actually better, but it might be a nice way to encapsulate that functionality.</p>\n<p>This would also be a convenient way to extend this to handle rotations as well, as you would just do <code>TetrisPiece.rotate(Direction.LEFT)</code> and handle it all under the hood.</p>\n<p>If you want to extend this to a full game, then instead of just having a &quot;drop position&quot; you also need a relative location on the board, handling T-spins, etc. The more complicated this gets, the more I think a separate class is going to improve readability.</p>\n<h2>General nitpicks</h2>\n<ul>\n<li><code>doesThePieceFit</code> seems really weird - I get how it works, but you should definitely introduce some constants to replace the magic method, and maybe consider if there is a better way to model the data.\n<ul>\n<li>In particular, perhaps we should store the block state for a different shape in reverse order (e.g. bottom-to-top instead of top-to-bottom)?</li>\n</ul>\n</li>\n<li><code>removeFullRows</code> creates a list, then sorts it - I think you can probably come up with a different approach for this</li>\n<li><code>addPieceAt</code> has the same magic as <code>doesThePieceFit</code> - is there a way that we can either combine their functionality, or use a common helper method?</li>\n<li><code>addPiece</code> I think you can use <code>for-else</code> to handle this a bit more elegantly than using the ternary, but my mood on the <code>for-else</code> swings every time I use it</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T19:01:38.303", "Id": "245884", "ParentId": "245876", "Score": "2" } }, { "body": "<p>Your code is good but it is not intuitive to interface with grafically.</p>\n<p>I can print the board but it comes out reversed and as zeros and ones and I got to do:</p>\n<pre><code>&gt;&gt;&gt; t = Tetris()\n&gt;&gt;&gt; print(t.board)\n</code></pre>\n<p>But you can use the special method <code>repr</code> to make it print nicely automagically (whenever the user asks <code>print(t)</code>)</p>\n<p>In Python 3 you can just add this at the end of your class:</p>\n<pre><code>class Tetris:\n # other code\n\n def __repr__(self):\n return '\\n'.join(reversed([''.join(&quot;■&quot; if elem else '□' for elem in line) for line in t.board]))\n</code></pre>\n<p>And now you have an intuitive and graphically nice pretty print:</p>\n<pre><code>t = Tetris()\nfor piece, pos in ( ('L',1), ('Z', 2), ('S', 3), ('I',5)):\n t.addPiece(piece, pos)\n print(t)\n print(&quot;\\n&quot;*5)\n</code></pre>\n<p>Outputs:</p>\n<pre><code>□■□□□□□□□□\n□■□□□□□□□□\n□■■□□□□□□□\n\n\n\n\n\n\n\n□■□□□□□□□□\n□■■■□□□□□□\n□■■■■□□□□□\n\n\n\n\n\n\n□□□□■■□□□□\n□■□■■□□□□□\n□■■■□□□□□□\n□■■■■□□□□□\n\n\n\n\n\n\n□□□□□■■■■□\n□□□□■■□□□□\n□■□■■□□□□□\n□■■■□□□□□□\n□■■■■□□□□□\n</code></pre>\n<p>In Python 2 you might have to use ASCII characters but this allows for easy developing and testing and is necessary in case you want to turn this into a game.</p>\n<p>(It looks way nicer in Python IDLE than in this site).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T19:12:56.303", "Id": "245885", "ParentId": "245876", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T14:38:16.743", "Id": "245876", "Score": "6", "Tags": [ "python", "game", "tetris" ], "Title": "Determine the height of a Tetris game's board after a sequence of moves" }
245876
<p>I am trying to recreate a neat effect that I saw posted on Stack Overflow <a href="https://media.giphy.com/media/d55DvGHjLFm1T8KDsi/giphy.gif" rel="nofollow noreferrer">as a GIF</a> .</p> <p>I am trying to recreate this with CSS and JavaScript and I have created a similar effect with a button press.</p> <p>I know there is a better way to position the divs since I am working with 3d moving and rotating. I need to have a formula that is using cos and sin to calculate the actual position it needs to be in. My math sadly isn't that good so I calculate it by getting the actual height after the <code>transform</code> and with that I calculate the <code>top</code> value the next elements need to get.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const shiftAmount = 2; const elements = document.querySelectorAll(".fold"); const elementBase = elements[0].getBoundingClientRect(); let currentState = "open"; let active = false; let $foldStateLabel = $("#foldButton span"); document.onkeydown = function (e) { switch (e.which) { case 37: // left break; case 38: // up addDeg(); break; case 39: // right break; case 40: // down minDeg(); break; default: return; // exit this handler for other keys } e.preventDefault(); // prevent the default action (scroll / move caret) }; $("#foldButton").click(function () { if (currentState == "open" &amp;&amp; !active) { active = true; let interval = setInterval(function () { if (!minDeg()) { clearInterval(interval); currentState = "closed"; active = false; $foldStateLabel.html("Out"); } }, 10); } else if (currentState == "closed" &amp;&amp; !active) { active = true; let interval = setInterval(function () { if (!addDeg()) { clearInterval(interval); currentState = "open"; active = false; $foldStateLabel.html("In"); } }, 10); } }); let rotation = 0; function addDeg() { let posDiff = 0; let origin; if (Math.abs(rotation) &gt; 0) { rotation += shiftAmount; for (var i = 0; i &lt; elements.length; i++) { let rot; elem = elements[i]; $element = $(elem); if (i % 2 == 0) { origin = "top"; rot = rotation; } else { origin = "bottom"; rot = Math.abs(rotation); } $element.css(createTransformCss(rot, origin, posDiff)); posDiff += elem.getBoundingClientRect().height - elementBase.height; if (origin == "bottom") { $element.css(createTransformCss(rot, origin, posDiff)); } } return true; } else { return false; } } function minDeg() { let posDiff = 0; let origin; if (Math.abs(rotation) &lt; 90 &amp;&amp; Math.abs(rotation) &gt;= 0) { rotation -= shiftAmount; for (var i = 0; i &lt; elements.length; i++) { let rot; elem = elements[i]; $element = $(elem); if (i % 2 == 0) { origin = "top"; rot = rotation; } else { origin = "bottom"; rot = Math.abs(rotation); } $element.css(createTransformCss(rot, origin, posDiff)); posDiff += elem.getBoundingClientRect().height - elementBase.height; if (origin == "bottom") { $element.css(createTransformCss(rot, origin, posDiff)); } } return true; } else { return false; } } function createTransformCss(rotationDeg, transformOrigin, top, perspective = 200) { var shadow = 0; shadow = 140 - (Math.abs(rotationDeg) * 2); var boxShadow = 'rgba(0, 0, 0, 0.75) 0px 0px 151px -' + shadow + 'px inset'; if (transformOrigin == "bottom") { shadow = 370 - (Math.abs(rotationDeg) * 3); boxShadow = 'rgba(0, 0, 0, 0.75) 0px 200px 151px -' + shadow + 'px inset'; } if(Math.abs(rotationDeg) == 0) { boxShadow = "none"; } return { 'top': top + "px", 'transform-origin': transformOrigin, 'transform': 'perspective(' + perspective + 'px) rotateX(' + (rotationDeg) + 'deg)', 'box-shadow': boxShadow } }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.container { max-width: 500px; margin: 0 auto; } .fold-items { width: 200px; display: flex; flex-direction: column; } .fold-items section { height: 75px; position: relative; background-color: bisque; } .fold-items section.visible { display: flex; border-bottom: 2px solid black; } .fold-items section.visible a { margin: auto; color: black; font-family: 'Roboto', sans-serif; font-weight: 700; text-transform: uppercase; text-decoration: none; padding: 5px 10px; border: 2px solid black; transition: all .3s; } .fold-items section.visible a:hover { background-color: rgba(0,0,0, 0.3); border: 4px solid black; color: white; } .fold-items section .inner { height: 100%; width: 100%; position: relative; } .fold-items section:nth-of-type(5n + 3) { background-image: url('https://via.placeholder.com/200x225'); background-size: cover; background-position: top; } .fold-items section:nth-of-type(5n + 4) { background-image: url('https://via.placeholder.com/200x225'); background-size: cover; background-position: center; } .fold-items section:nth-of-type(5n + 5) { background-image: url('https://via.placeholder.com/200x225'); background-size: cover; background-position: bottom; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&amp;display=swap" rel="stylesheet"&gt; &lt;link rel="stylesheet" href="css/style.css"&gt; &lt;script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;div class="fold-wrapper"&gt; &lt;div id="fold-items" class="fold-items"&gt; &lt;section class="visible"&gt; &lt;a id="foldButton" href="#"&gt;Fold &lt;span&gt;In&lt;/span&gt;&lt;/a&gt; &lt;/section&gt; &lt;section class="fold"&gt; &lt;/section&gt; &lt;section class="fold image"&gt; &lt;/section&gt; &lt;section class="fold image"&gt; &lt;/section&gt; &lt;section class="fold image"&gt; &lt;/section&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;script src="js/script.js"&gt;&lt;/script&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>You can use my snippet by pressing the button or you can use the arrow keys up and down to open or close it in a single step.</p> <p>UPDATE:</p> <p>I've updated the effect and it now works on scroll like the example.</p> <p><a href="https://jsfiddle.net/2wf7zb31/" rel="nofollow noreferrer">The new jsfiddle</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T23:35:14.167", "Id": "483045", "Score": "0", "body": "@HenrikHansen the VTC was there before I and Mast edited the question. Look at the original wording." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T14:55:54.420", "Id": "245877", "Score": "4", "Tags": [ "javascript", "jquery", "html", "css" ], "Title": "Created a paperfold like effect" }
245877
<p>Improved version of <a href="https://codereview.stackexchange.com/questions/245718/get-release-npm-module">the original question</a></p> <p>I've created a simple npm module and CLI program to get the latest GitHub and Bitbucket release from their APIs using Node.js. Please tell me if there's anything to improve!</p> <p><a href="https://github.com/KhushrajRathod/get-release" rel="nofollow noreferrer">GitHub</a> <br /> <a href="https://www.npmjs.com/package/get-release" rel="nofollow noreferrer">npm</a> <br /> <a href="https://npm.runkit.com/get-release" rel="nofollow noreferrer">RunKit</a></p> <h2>Improved module code</h2> <pre class="lang-js prettyprint-override"><code>#!/usr/bin/env node const fetch = require(&quot;node-fetch&quot;); /** * @param {string} string * @return {string} */ const normalize = (string) =&gt; { try { return string.toUpperCase().trim() } catch (e) { return string } } /** * @param {string} url * @return {string} */ const getJSON = async (url) =&gt; { return (await (await fetch(url)).json()) } module.exports.providerMethods = { GITHUB: async ({user, repo, part = &quot;&quot;}) =&gt; { let json = await getJSON(`https://api.github.com/repos/${user}/${repo}/releases/latest`) if (json.message === &quot;Not Found&quot;) throw &quot;Invalid repository&quot; if (!(&quot;assets&quot; in json)) throw &quot;Rate limit exceeded&quot; let browser_download_urls = json.assets.map(asset =&gt; asset.browser_download_url) return browser_download_urls.filter(url =&gt; url.includes(part)) }, BITBUCKET: async ({user, repo, part = &quot;&quot;}) =&gt; { let json = await getJSON(`https://api.bitbucket.org/2.0/repositories/${user}/${repo}/downloads/`) if (json.type === &quot;error&quot;) throw &quot;Invalid repository&quot; let links = json.values.map(value =&gt; value.links.self.href) return links.filter(url =&gt; url.includes(part)) } } /** * @param {string} provider * @param {string} user * @param {string} repo * @param {string} part */ module.exports.getRelease = async ({provider, user, repo, part = &quot;&quot;}) =&gt; { if (!(module.exports.providerMethods[normalize(provider)])) { throw &quot;Invalid provider&quot; } return module.exports.providerMethods[normalize(provider)]({user, repo, part}) } const usage = _ =&gt; { console.log( `Usage: get-release (github|bitbucket) user repo [partofreleasefile] Ex: get-release github phhusson treble_experimentations get-release github phhusson treble_experimentations arm64-ab-gapps get-release bitbucket JesusFreke smali get-release bitbucket JesusFreke smali baksmali` ) process.exit(1) } // If via CLI if (require.main === module) { let args = process.argv.slice(2) if (args.length !== 3 &amp;&amp; args.length !== 4) { usage() } module.exports.getRelease({ provider: args[0], user: args[1], repo: args[2], part: args[3] }).then(result =&gt; { if (result.length !== 1) { console.log(result) } else { console.log(result[0]) } }).catch(error =&gt; { console.log(error) usage() process.exit(1) }) } </code></pre> <h2>To be called using</h2> <pre class="lang-js prettyprint-override"><code>/** * Options: * { * provider: (github | bitbucket), * user: username, * repo: repository, * part: part of release file name - optional * } * */ const { getRelease, providerMethods } = require(&quot;get-release&quot;) ;(async _ =&gt; { let url = await getRelease( { provider: &quot;github&quot;, user: &quot;phhusson&quot;, repo: &quot;treble_experimentations&quot;, part: &quot;arm64-ab-gapps&quot; } ) console.log(url[0]) })() </code></pre> <h2>Custom providers can be defined using</h2> <pre><code>const { getRelease, providerMethods } = require(&quot;get-release&quot;) providerMethods.GITLAB = async ({user, repo, part = &quot;&quot;}) =&gt; { // Custom code, should return a string } </code></pre>
[]
[ { "body": "<p>Now that you've allowed the users to add custom providers, how about hiding the <code>providerMethods</code> object itself, and only providing a function which allows them to add to it. This would allow you to also validate if the users' want to override behaviour for predefined providers.</p>\n<p>You have a <code>process.exit(1)</code> inside the call to <code>usage()</code>. Butm when used from cli, you catch all exceptions, then call the <code>usage</code> function, and against have another <code>process.exit(1)</code>.</p>\n<p>The call to usage should not be exiting from the program entirely. It is already handled in case of errors. You can then have a <code>--help</code> commandline parameter, which spits out the usage string (without raising an error for the shell).</p>\n<hr />\n<p>Most of your <code>if-</code> conditions use the negated equality check, which is somewhat harder to follow for a developer (at least in my experience). When checking for <code>args.length</code>, you have double negation checks. It took me almost a minute to figure out what it is supposed to do. How about applying <a href=\"https://en.wikipedia.org/wiki/De_Morgan%27s_laws\" rel=\"nofollow noreferrer\">de Morgan's laws</a>:</p>\n<pre><code>if (!(args.length === 3 || args.length === 4))\n</code></pre>\n<p>Or, maybe simply adding a comment?</p>\n<p>Also consider:</p>\n<pre><code>console.log((result.length === 1) ? result[0] : result)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T03:53:17.180", "Id": "483159", "Score": "0", "body": "Hi, thanks for answering (again). I don't understand why hiding providerMethods is required. I want users to be able to override the existing providers anyway, and they can add new providers. Is there any advantage to this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-29T07:05:00.557", "Id": "483602", "Score": "0", "body": "@KhushrajRathod Since you're releasing this as a package, someone is free to extend/use in their application. Now, if you're providing them access to the `providerMethods` object itself, they may override and cause (un)intentional harm to the end user. Which is why I closed the statement with \"_This would allow you to also validate if the users' want to override behaviour for predefined providers_\"." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T09:32:09.713", "Id": "245909", "ParentId": "245878", "Score": "1" } } ]
{ "AcceptedAnswerId": "245909", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T15:24:48.833", "Id": "245878", "Score": "3", "Tags": [ "javascript", "node.js", "console", "git", "modules" ], "Title": "(Improved) get-release npm module" }
245878
<p>I have a rails app with a Project model. Each project has usages which is numeric data.</p> <p>I need to get all the usage for each month and year. I also need to get usage for specific months and years across multiple projects.</p> <p>Instead of writing one large service file with raw SQL queries to handle this, I have decided to extract a lot of the code to a model which isn't based on any table, but instead gets the data by using certain SQL aggregation features.</p> <p>This allows me to take (almost) full advantage of ActiveRecord in consumers to extend the default query to get specific fields (e.g. where the month is May or the project is project #15).</p> <p>Here is the example of the code I wrote:</p> <pre><code>class MonthlyUsage &lt; ActiveRecord::Base self.table_name = 'projects' default_scope do select(select_monthly_data_and_dates) .group('year', 'month', '&quot;projects&quot;.&quot;id&quot;') end def self.select_monthly_data_and_dates &lt;&lt;~SQL.squish &quot;projects&quot;.&quot;id&quot; AS &quot;project_id&quot;, SUM(&quot;usages&quot;.&quot;usage&quot;) AS &quot;monthly_usage&quot;, date_part('year', &quot;usages&quot;.&quot;timestamp&quot;)::INT AS &quot;year&quot;, date_part('month', &quot;usages&quot;.&quot;timestamp&quot;)::INT AS &quot;month&quot; SQL end end </code></pre> <p>In reality there are a few joins and extra steps to this code which I'm omitting here since they aren't relevant.</p> <p>Basically I'm of two minds on this. On the one hand I think it allows for powerful querying and fits the definition of a model, but on the other hand I think it might be too &quot;hacky&quot; and not really much clearer than just using a service file (e.g. setting the table name as 'projects' even though that's not really the real table name). That's why I'm asking for code review here, to get some opinions on whether this is good or bad, as well as how you would do it.</p>
[]
[ { "body": "<p>I agree with you that this does not really fit a service nor a model. This might be more like a Query object.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class MonthlyUsageQuery\n def intialize(relation: Project.all)\n @relation = relation\n end\n\n def all\n relation.select(select_monthly_data_and_dates)\n .group('year', 'month', '&quot;projects&quot;.&quot;id&quot;')\n end\n\n private\n \n attr_reader :relation\n\n def select_monthly_data_and_dates\n &lt;&lt;~SQL.squish\n &quot;projects&quot;.&quot;id&quot; AS &quot;project_id&quot;,\n SUM(&quot;usages&quot;.&quot;usage&quot;) AS &quot;monthly_usage&quot;,\n date_part('year', &quot;usages&quot;.&quot;timestamp&quot;)::INT AS &quot;year&quot;,\n date_part('month', &quot;usages&quot;.&quot;timestamp&quot;)::INT AS &quot;month&quot;\n SQL\n end\nend\n\nMonthlyUsage.all\nMonthlyUsage.new(relation: Project.where(name: 'Stackoverflow')).all\n</code></pre>\n<p><a href=\"https://medium.com/selleo/essential-rubyonrails-patterns-part-2-query-objects-4b253f4f4539\" rel=\"nofollow noreferrer\">https://medium.com/selleo/essential-rubyonrails-patterns-part-2-query-objects-4b253f4f4539</a>\n<a href=\"https://medium.flatstack.com/query-object-in-ruby-on-rails-56ea434365f0\" rel=\"nofollow noreferrer\">https://medium.flatstack.com/query-object-in-ruby-on-rails-56ea434365f0</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-17T21:05:29.867", "Id": "249514", "ParentId": "245881", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T17:05:26.240", "Id": "245881", "Score": "2", "Tags": [ "ruby-on-rails", "orm" ], "Title": "Rails model for aggregate data instead of a real table" }
245881
<p>I'm moving some files from a Linux machine to a Windows machine over a low-speed, possibly buggy experimental communications channel that I want to test. One of the tests is to transfer large numbers of large and small files and verify their cryptographic hashes at the receiving end. On the Linux side, we're using <code>md5sum</code> to generate file hashes like so:</p> <pre><code>md5sum * &gt; files.md5 </code></pre> <p>Then the files are transmitted from the Linux machine to the Windows 10 machine. What I'd like to do next is to verify the hashes on the plain-vanilla Windows machine (no Cygwin installed). So to mimic the default operation of <code>md5sum -c files.md5</code> which would go through, line by line and verify each md5 checksum, I've written this Powershell script. I'm a lot more at home in bash than in Powershell, so thought I might benefit from a review.</p> <pre><code>param ( [Parameter(Mandatory=$true)][string]$infile ) $basedir = Split-Path -Parent $infile $badcount = 0 foreach ($line in [System.IO.File]::ReadLines(&quot;$infile&quot;)) { $sum, $file = $line.split(' ') $fullfile = &quot;$basedir\$file&quot; $filehash = Get-FileHash -Algorithm MD5 $fullfile if ($sum -eq $filehash.Hash) { Write-Host $file &quot;: OK&quot; } else { Write-Host $file &quot;: FAILED&quot; $badcount++ } } if ($badcount -gt &quot;0&quot;) { Write-Host &quot;WARNING:&quot; $badcount &quot;computed checksums did NOT match&quot; } </code></pre>
[]
[ { "body": "<p>here are a few changes i would make. [<em>grin</em>] the ideas ...</p>\n<ul>\n<li>use <code>Get-Content</code> instead of <code>ReadLines()</code><br />\nthe speed difference is not large unless you are dealing with a very large number of files. go with the standard cmdlets unless there is a meaningful benefit from doing otherwise.</li>\n<li>test to see if the file exists</li>\n<li>build a <code>[PSCustomObject]</code> to hold the resulting items that you want</li>\n<li>keep those PSCOs in a collection</li>\n<li>view your hash failure items after the full test ends</li>\n</ul>\n<p>what it does ...</p>\n<ul>\n<li>sets the constants</li>\n<li>builds a test file to work with<br />\nremove the entire <code>#region/#endregion</code> block when you are ready to use your own data.</li>\n<li>reads in the hash list file</li>\n<li>iterates thru the resulting array</li>\n<li>splits out the file name and hash value</li>\n<li>builds the full file name to check</li>\n<li>tests to see if that file exists</li>\n<li>if YES, gets the file hash and saves it</li>\n<li>if NO, sets the file hash $Var to <code>'__N/A__'</code></li>\n<li>builds a PSCO with the properties that seem useful</li>\n<li>sends that to the <code>$Result</code> collection</li>\n<li>gets the hash failures from the collection and displays them<br />\nif all you want it the count, wrap that all in <code>@()</code> and add <code>.Count</code> to the end.</li>\n</ul>\n<p>the code ...</p>\n<pre><code>$SourceDir = $env:TEMP\n$HashFileName = 'FileHashList.txt'\n$FullHashFileName = Join-Path -Path $SourceDir -ChildPath $HashFileName\n\n#region &gt;&gt;&gt; make a hash list to compare with\n# remove this entire &quot;#region/#endregion&quot; block when ready to work with your real data\n$HashList = Get-ChildItem -LiteralPath $SourceDir -Filter '*.log' -File |\n ForEach-Object {\n '{0} {1}' -f $_.Name, (Get-FileHash -LiteralPath $_.FullName-Algorithm 'MD5').Hash\n }\n# munge the 1st two hash values\n$HashList[0] = $HashList[0] -replace '.{5}$', '--BAD'\n$HashList[1] = $HashList[1] -replace '.{5}$', '--BAD'\n\n$HashList |\n Set-Content -LiteralPath $FullHashFileName\n#endregion &gt;&gt;&gt; make a hash list to compare with\n\n$Result = foreach ($Line in (Get-Content -LiteralPath $FullHashFileName))\n {\n $TestFileName, $Hash = $Line.Split(' ')\n $FullTestFileName = Join-Path -Path $SourceDir -ChildPath $TestFileName\n if (Test-Path -LiteralPath $FullTestFileName)\n {\n $THash = (Get-FileHash -LiteralPath $FullTestFileName -Algorithm 'MD5').Hash\n }\n else\n {\n $THash = '__N/A__'\n }\n [PSCustomObject]@{\n FileName = $TestFileName\n CopyOK = $THash -eq $Hash\n OriHash = $Hash\n CopyHash = $THash\n }\n }\n\n$Result.Where({$_.CopyOK -eq $False})\n</code></pre>\n<p>output [with the 1st two hash values deliberately munged] ...</p>\n<pre><code>FileName CopyOK OriHash CopyHash \n-------- ------ ------- -------- \nGenre-List_2020-07-07.log False 7C0C605EA7561B7020CBDAE24D1--BAD 7C0C605EA7561B7020CBDAE24D140E40\nGenre-List_2020-07-14.log False 20F234ACE66B860821CF8F8BD5E--BAD 20F234ACE66B860821CF8F8BD5EC144D\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T21:08:18.027", "Id": "483032", "Score": "0", "body": "Thanks! I'm definitely going to have to study this. One question I have already is about \"go with the standard cmdlets\" -- how do I know which are standard and which are not? Is there a list somewhere?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T22:03:41.067", "Id": "483037", "Score": "0", "body": "@Edward - you are most welcome! glad to help a bit. [*grin*] ///// by `standard cmdlets` i mean the actual powershell cmdlets, not calls to dotnet stuff. you can see the ones that are available to your setup with `Get-Command`. the verbs are viewable with `Get-Verb`. [*grin*]" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T20:33:48.177", "Id": "245890", "ParentId": "245882", "Score": "5" } } ]
{ "AcceptedAnswerId": "245890", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T18:07:28.573", "Id": "245882", "Score": "7", "Tags": [ "linux", "windows", "powershell" ], "Title": "Powershell script to verify Linux-generated md5sum file" }
245882
<p>I am writing a python GUI application that plots weather data on a map for a specific region. It plots temperature, dewpoint, wind data, and icons that represent the sky conditions. It extracts the data for longitude/latitude from text files. I timed out how long it takes for the program to plot each type of weather data and I got the following results:</p> <p>temperature: 10 seconds</p> <p>dewpoint: 10 seconds</p> <p>wind: 15 seconds</p> <p>sky conditions: 90 seconds</p> <p>So, it doesn't take too long for it to plot temperature, dewpoint, and wind. However, it takes a very long time for it to plot the sky conditions, which are icon images. My goal is for my application to display any kind of weather data in a few seconds. I am wondering what I can do to my python code to make it more efficient and run faster, so it meets that goal.</p> <p>I use global variables, which I know is not good programming practice. This is likely one thing I am doing in my code that is slowing things down. I also use numerous function calls, which could also be slowing things down as well. I would like to rewrite my code, so that I don't use so many global variables and function calls.</p> <p>The biggest problem I think is when it displays the icons, which are images as stated above. I am new at working with images in python, so I don't know if python is just slow with dealing with images or not. Any analysis of my code/suggestions to make it better would be greatly appreciated.</p> <pre><code>import tkinter as tk from tkinter import ttk import tkinter.font as tkFont from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.figure import Figure import matplotlib.image as mpimg from mpl_toolkits.basemap import Basemap from PIL import Image from matplotlib.offsetbox import OffsetImage, AnnotationBbox import matplotlib.pyplot as plt import numpy as np import requests def retrieve_filedata(): file = area.get() + '.txt' f = open(file, 'r') line = f.readline() global minlon minlon = float(line.split(' ')[0]) global minlat minlat = float(line.split(' ')[1]) global maxlon maxlon = float(line.split(' ')[2]) global maxlat maxlat = float(line.split()[3]) global centerlat centerlat = float(line.split()[4]) global centerlon centerlon = float(line.split()[5]) lines = f.readlines()[1:] #put longitude and latitudes into array global lat lat = [] global lon lon = [] for x in lines: lat.append(float(x.split(' ')[0])) lon.append(float(x.split()[1])) f.close() def current_weather(): retrieve_filedata() key = '4a7a419e4e16e2629a4cedc37cbf7e50' url = 'https://api.openweathermap.org/data/2.5/weather' global observation observation = [] global u u = [] global v v = [] global icon icon = [] for i in range(0,len(lon)): params = {'lat': lat[i], 'lon': lon[i], 'appid': key, 'units': 'imperial'} response = requests.get(url, params = params) weather = response.json() airtemp = round(weather['main']['temp']) humidity = weather['main']['humidity'] #relative humidity kelvin = ((airtemp-32)/1.8)+273 #convert temperature from F to Kelvin #E = 0.611 * np.exp(5423 * ((1/273) - (1/dewpoint))) vapor pressure Es = 0.611 * np.exp(5423 * ((1/273) - (1/kelvin))) #saturation vapor pressure kelvindew = 5423/((5423/273)-np.log(((humidity/100)*Es)/0.611)) #use vapor pressure equation to find dewpoint in Kelvin dewpoint = round(((kelvindew-273)*1.8)+32) #convert dewpoint from Kelvin to F windspeed = round(weather['wind']['speed']) winddirection = weather['wind']['deg'] u.append(-(windspeed)*np.sin(((np.pi)/180)*winddirection)) v.append(-(windspeed)*np.cos(((np.pi)/180)*winddirection)) icon.append(weather['weather'][0]['icon']) if data.get() == 'Temperature': observation.append(airtemp) if data.get() == 'Dewpoint': observation.append(dewpoint) def display_winds(): current_weather() map = Basemap(llcrnrlon= minlon, llcrnrlat= minlat, urcrnrlon= maxlon, urcrnrlat= maxlat ,resolution='i', lat_0 = centerlat, lon_0 = centerlon) for i in range(0, len(lon)): x,y = map(lon[i], lat[i]) map.barbs(x, y, u[i], v[i], length = 5, pivot = 'middle', zorder = 100) plt.show() def display_icons(): map = Basemap(llcrnrlon= minlon, llcrnrlat= minlat, urcrnrlon= maxlon, urcrnrlat= maxlat ,resolution='i', lat_0 = centerlat, lon_0 = centerlon) image = [] im = [] ab = [] x,y = map(lon, lat) for i in range(0, len(lon)): image.append(Image.open(requests.get('http://openweathermap.org/img/wn/' + icon[i] + '@2x.png', stream=True).raw)) im.append(OffsetImage(image[i], zoom = 0.25)) ab.append(AnnotationBbox(im[i], (x[i],y[i]), frameon=False)) map._check_ax().add_artist(ab[i]) plt.show() def plot_data(): current_weather() map = Basemap(llcrnrlon= minlon, llcrnrlat= minlat, urcrnrlon= maxlon, urcrnrlat= maxlat ,resolution='i', lat_0 = centerlat, lon_0 = centerlon) map.drawmapboundary(fill_color='#A6CAE0') map.drawcounties(zorder = 20) map.drawstates() map.fillcontinents(color='#e6b800',lake_color='#A6CAE0') for i in range(0, len(lon)): x,y = map(lon[i], lat[i]) if data.get() == 'Temperature' or data.get() == 'Dewpoint': plt.text(x, y, observation[i], fontsize = 7) if data.get() == 'Wind': display_winds() if data.get() == 'Sky Conditions': display_icons() plt.show() root = tk.Tk() canvas = tk.Canvas(root, height = '300', width = '400') canvas.pack() #create widgets titlefont = tkFont.Font(size = 20) title = tk.Label(text = &quot;Current Weather Map Data&quot;, font = titlefont) arealabel = tk.Label(text = &quot;Choose Region: &quot;) areavalue = tk.StringVar() area = ttk.Combobox(root, width = '13', textvariable = areavalue) datalabel = tk.Label(text = &quot;Choose Data: &quot;) datavalue = tk.StringVar() data = ttk.Combobox(root, width = '12', textvariable = datavalue) button = tk.Button(root, text = &quot;Plot Data&quot;, command = plot_data) #organize widgets title.place(relx = 0.1, rely = 0.05) arealabel.place(relx = 0.05, rely = 0.25) area.place(relx = 0.35, rely = 0.25) datalabel.place(relx = 0.05, rely = 0.40) data.place(relx = 0.35, rely = 0.40) button.place(relx = 0.40, rely = 0.65) #Insert Values into Area Combobox area['values'] = ('Pennsylvania', 'Maryland', 'Delaware', 'New Jersey', 'Virginia', 'West Virginia', 'Ohio', 'New York', 'Rhode Island', 'Massachusetts', 'Connecticut', 'Vermont', 'New Hampshire', 'Maine', 'Mid Atlantic', 'New England') area.current(0) #Insert Values into Data Combobox data['values'] = ('Temperature', 'Dewpoint', 'Wind', 'Sky Conditions') data.current(0) root.mainloop() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T17:16:14.057", "Id": "483127", "Score": "0", "body": "Looks like your internet is slow or that api's server is slow in serving you.Lots of get requests for image download, code has to be slow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T17:25:30.260", "Id": "483128", "Score": "0", "body": "Code can be made faster if you download images in async but I don't have experience with that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T02:39:21.103", "Id": "483362", "Score": "0", "body": "Please show a sample of your input text file." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T21:54:59.460", "Id": "245892", "Score": "3", "Tags": [ "python", "performance" ], "Title": "Weather map GUI application needs performance improvement" }
245892
<p>I'm posting my code for a LeetCode problem. If you'd like to review, please do so. Thank you for your time!</p> <h3>Problem</h3> <p>Given a non-empty binary tree, find the maximum path sum.</p> <p>For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.</p> <h3>Example 1:</h3> <pre><code>Input: [1,2,3] 1 / \ 2 3 Output: 6 </code></pre> <h3>Example 2:</h3> <pre><code>Input: [-10,9,20,null,null,15,7] -10 / \ 9 20 / \ 15 7 Output: 42 </code></pre> <h3>Inputs</h3> <pre><code>[1,2,3] [-10,9,20,null,null,15,7] [-10,9,20,null,null,15,7,9,20,null,null,15,7] [-10,9,20,null,null,15,7,9,20,null,null,15,720,null,null,15,7,9,20,null,null,15,7] [-10,9,20,null,null,15,7,9,20,null,null,15,720,null,null,15,7,9,20,null,null,15,7999999,20,null,null,15,7,9,20,null,null,15,720,null,null,15,7,9,20,null,null,15,7] </code></pre> <h3>Outputs</h3> <pre><code>6 42 66 791 8001552 </code></pre> <h3>Code</h3> <pre><code>#include &lt;cstdint&gt; #include &lt;algorithm&gt; struct Solution { int maxPathSum(TreeNode* root) { std::int_fast64_t sum = INT_FAST64_MIN; depthFirstSearch(root, sum); return sum; } private: static std::int_fast64_t depthFirstSearch( const TreeNode* node, std::int_fast64_t&amp; sum ) { if (!node) { return 0; } const std::int_fast64_t left = std::max( (std::int_fast64_t) 0, depthFirstSearch(node-&gt;left, sum) ); const std::int_fast64_t right = std::max( (std::int_fast64_t) 0, depthFirstSearch(node-&gt;right, sum) ); sum = std::max(sum, left + right + node-&gt;val); return std::max(left, right) + node-&gt;val; } }; </code></pre> <h3>References</h3> <ul> <li><p><a href="https://leetcode.com/problems/binary-tree-maximum-path-sum/" rel="nofollow noreferrer">Problem</a></p> </li> <li><p><a href="https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/" rel="nofollow noreferrer">Discuss</a></p> </li> <li><p><a href="https://leetcode.com/problems/binary-tree-maximum-path-sum/solution/" rel="nofollow noreferrer">Solution</a></p> </li> </ul>
[]
[ { "body": "<p>There's not much to say about your answer, it looks fine! One could quibble over the names of variables, maybe <code>left</code> and <code>right</code> could be named <code>left_sum</code> and <code>right_sum</code> for example, and you could've used <code>auto</code> for the type of those two variables. But other than that I think there is nothing that can be improved.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T22:51:16.033", "Id": "245895", "ParentId": "245893", "Score": "1" } }, { "body": "<p>Not sure why you decided to use <code>std::int_fast64_t</code> over the common <code>int</code> that is used as the type of the tree nodes values.</p>\n<p>But since you did, it would be more idiomatic to do at least:</p>\n<pre><code>static_cast&lt;std::int_fast64_t&gt;(0);\n</code></pre>\n<p>instead of</p>\n<pre><code>(std::int_fast64_t) 0;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T10:00:40.503", "Id": "483078", "Score": "1", "body": "Maybe it is better to avoid casting altogether. Casting implies you started with some different type. You can construct a zero of the proper type directly by writing: `std::int_fast64_t(0)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T18:44:38.613", "Id": "483129", "Score": "0", "body": "Or create a named object `static constexpr std::int_fast64_t fast_zero(0);`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T05:02:48.230", "Id": "245903", "ParentId": "245893", "Score": "2" } } ]
{ "AcceptedAnswerId": "245895", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T21:56:54.043", "Id": "245893", "Score": "1", "Tags": [ "c++", "beginner", "algorithm", "programming-challenge", "c++17" ], "Title": "LeetCode 124: Binary Tree Maximum Path Sum" }
245893
<p>I'm posting my code for a LeetCode problem. If you'd like to review, please do so. Thank you for your time!</p> <h3>Problem</h3> <p>Given a non-empty binary tree, find the maximum path sum.</p> <p>For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.</p> <h3>Example 1:</h3> <pre><code>Input: [1,2,3] 1 / \ 2 3 Output: 6 </code></pre> <h3>Example 2:</h3> <pre><code>Input: [-10,9,20,null,null,15,7] -10 / \ 9 20 / \ 15 7 Output: 42 </code></pre> <h3>Inputs</h3> <pre><code>[1,2,3] [-10,9,20,null,null,15,7] [-10,9,20,null,null,15,7,9,20,null,null,15,7] [-10,9,20,null,null,15,7,9,20,null,null,15,720,null,null,15,7,9,20,null,null,15,7] [-10,9,20,null,null,15,7,9,20,null,null,15,720,null,null,15,7,9,20,null,null,15,7999999,20,null,null,15,7,9,20,null,null,15,720,null,null,15,7,9,20,null,null,15,7] </code></pre> <h3>Outputs</h3> <pre><code>6 42 66 791 8001552 </code></pre> <h3>Code</h3> <pre><code># Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def maxPathSum(self, root: TreeNode) -&gt; int: def depth_first_search(node: TreeNode) -&gt; int: if not node: return 0 left_sum = depth_first_search(node.left) right_sum = depth_first_search(node.right) if not left_sum or left_sum &lt; 0: left_sum = 0 if not right_sum or right_sum &lt; 0: right_sum = 0 self.sum = max(self.sum, left_sum + right_sum + node.val) return max(left_sum, right_sum) + node.val self.sum = float('-inf') depth_first_search(root) return self.sum </code></pre> <h3>References</h3> <ul> <li><p><a href="https://leetcode.com/problems/binary-tree-maximum-path-sum/" rel="nofollow noreferrer">Problem</a></p> </li> <li><p><a href="https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/" rel="nofollow noreferrer">Discuss</a></p> </li> <li><p><a href="https://leetcode.com/problems/binary-tree-maximum-path-sum/solution/" rel="nofollow noreferrer">Solution</a></p> </li> </ul>
[]
[ { "body": "<h1>Unnecessary checks in <code>depth_first_search()</code></h1>\n<p>The function <code>depth_first_search()</code> always returns an integer value, never <code>None</code>. So the check for a partial sum being <code>None</code> or <code>&lt; 0</code> can be rewritten using <code>max()</code>:</p>\n<pre><code>left_sum = max(0, depth_first_search(node.left))\nright_sum = max(0, depth_first_search(node.right))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T22:59:05.340", "Id": "245896", "ParentId": "245894", "Score": "1" } } ]
{ "AcceptedAnswerId": "245896", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T22:06:50.550", "Id": "245894", "Score": "1", "Tags": [ "python", "beginner", "algorithm", "python-3.x", "programming-challenge" ], "Title": "LeetCode 124: Binary Tree Maximum Path Sum 2" }
245894
<p>In another Code Review, it was recommended that I alphabetize my CSS. So I made a tool to do this quickly in JavaScript.</p> <p>Because CSS has two levels (selector on the outside, parameters on the inside), and they both need to be alphabetized, alphabetizing it is not as easy as just doing <code>array.sort()</code>. A custom tool is needed.</p> <p>Feel free to comment on anything JavaScript. Here's my code.</p> <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>"use strict"; class CSSAlphabetizer { alphabetize(s) { let lines, blocks; // TODO: this._validate(); // TODO: this._beautify(); using regex and replace of { ; } lines = this._makeLinesArray(s); blocks = this._sortSelectors(lines); blocks = this._sortParameters(blocks); s = this._makeString(blocks); s = this._addBlankLineBetweenBlocks(s); s = s.trim(); return s; } _addBlankLineBetweenBlocks(s) { return s.replace(/}\n([^\n])/, "}\n\n$1"); } _makeString(blocks) { // blocks =&gt; lines let lines = []; for ( let block of blocks ) { let lines2 = block[1]; for ( let line of lines2 ) { lines.push(line); } } // lines =&gt; string let s = ""; for ( let line of lines ) { s += line[1] + "\n"; } s = s.slice(0, s.length-1); return s; } _sortSelectors(lines) { /** [parameterTrimmed, [line, line, line, line]] */ let blocks = []; /** [line, line, line, line] **/ let buffer = []; let lineNumTracker = 0; let parameterTrimmed = ""; let len = lines.length; for ( let i = 0; i &lt; len; i++ ) { let line = lines[i]; let lineNum = line[2]; if ( ! parameterTrimmed &amp;&amp; line[0].includes("{") ) { parameterTrimmed = line[0]; } if ( lineNum !== lineNumTracker ) { lineNumTracker++; blocks.push([parameterTrimmed, buffer]); buffer = []; parameterTrimmed = ""; } buffer.push(line); // Last line. Finish the block. if ( i === len-1 ) { lineNumTracker++; blocks.push([parameterTrimmed, buffer]); buffer = []; parameterTrimmed = ""; } } blocks = blocks.sort(); return blocks; } _sortParameters(blocks) { for ( let key in blocks ) { let lines = blocks[key][1]; let lineBuffer = []; let sortBuffer = []; for ( let line of lines ) { let isParameter = line[3]; if ( isParameter ) { sortBuffer.push(line); } else { if ( sortBuffer ) { sortBuffer = sortBuffer.sort(); lineBuffer = lineBuffer.concat(sortBuffer); } lineBuffer.push(line); } } blocks[key][1] = lineBuffer; } console.log(blocks); return blocks; } /** Makes an array of arrays. [trimmed, notTrimmed, blockNum, isParameter]. Having unique block numbers will be important later, when we are alphabetizing things. */ _makeLinesArray(s) { // TODO: refactor to use associative array, more readable code, and less likely to have bugs if later we want to add/change/delete fields let lines = s.split("\n"); let blockNum = 0; let isParameter = false; for ( let key in lines ) { let value = lines[key]; if ( value.includes("}") ) { isParameter = false; } lines[key] = [ // Trimmed line in first spot. Important for sorting. value.trim(), value, blockNum, isParameter, ]; // When } is found, increment the block number. This keeps comment lines above block grouped with that block. if ( value.includes("}") ) { blockNum++; } if ( value.includes("{") ) { isParameter = true; } } console.log(lines); return lines; } } window.addEventListener('DOMContentLoaded', (e) =&gt; { let css = document.getElementById('css'); let alphabetize = document.getElementById('alphabetize'); // TODO: Combo box that loads tests. alphabetize.addEventListener('click', function(e) { let alphabetizer = new CSSAlphabetizer(); css.value = alphabetizer.alphabetize(css.value); }); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { margin: 1em; width: 95%; max-width: 700px; font-family: sans-serif; } textarea { width: 100%; height: 360px; tab-size: 4; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en-us"&gt; &lt;head&gt; &lt;title&gt;CSS Alphabetizer&lt;/title&gt; &lt;link rel="stylesheet" href="style.css" /&gt; &lt;script type="module" src="css-alphabetizer.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt; CSS Alphabetizer &lt;/h1&gt; &lt;p&gt; Beautify your CSS. Sort your selectors alphabetically (which groups together #id's, .classes, and then elements), and sort your parameters alphabetically too. Parameters are nested within braces, so those aren't easy to sort with a normal A-Z sort. &lt;/p&gt; &lt;p&gt; &lt;textarea id="css"&gt;body { background-color: #999999; margin-bottom: 0; } #page-container { background-color: #DFDFDF; width: 1150px; margin: 12px auto 0 auto; } #page-container2 { padding: 12px 12px 0 12px; } header { background-color: white; } .category { display: inline-block; padding: 18px 25px; font-family: sans-serif; } .category:hover { background-color: #059BD8; }&lt;/textarea&gt; &lt;/p&gt; &lt;p&gt; &lt;button id="alphabetize"&gt;Alphabetize&lt;/button&gt; &lt;/p&gt; &lt;p&gt; Want to report a bug or request a feature? &lt;a href="https://github.com/RedDragonWebDesign/css-alphabetizer/issues"&gt;Create an issue&lt;/a&gt; on our GitHub. &lt;/p&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T06:34:39.360", "Id": "483064", "Score": "1", "body": "I completely agree with @Emma. That regex is want you want." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T10:13:55.957", "Id": "483080", "Score": "1", "body": "Nice. I like how you promote \"groups together #id's, .classes, and then elements\" as a feature instead of (at least) giving the option to (and writing the code for) strip `#` and `.` etc. for sorting - something I'd prefer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-31T20:42:36.970", "Id": "484003", "Score": "0", "body": "Cool concept. It would be prudent to add annotations that would prevent regions of the code from being sorted. Consider that you have a table 40 columns wide. All columns except 5, 9, 15 and 21 have the same format. All rows have the same format other than 6, 9, 25. Do you really want to write a work around using CSS? Size may not matter but position sure does!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-31T23:11:29.053", "Id": "484008", "Score": "0", "body": "@TinMan Are you saying that they would be alphabetized in an order that would mess things up? Feel free to link a fiddle with some sample code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-06T19:44:45.840", "Id": "484682", "Score": "1", "body": "[CSS Inheritance, Cascade, and Specificity](http://web.simmons.edu/~grabiner/comm244/weekfour/css-concepts.html#:~:text=CSS%20Order%20Matters,the%20one%20that%20is%20applied.): If a rule from the same style sheet, with the same level of specificity exists, the rule that is declared last in the CSS document will be the one that is applied." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-06T20:01:48.630", "Id": "484683", "Score": "1", "body": "[JS Fiddle](https://jsfiddle.net/a9npsgf7/). This cruse example has two css blocks that both target `p` elements. The first block `color: red;` style is later replaced with `color: black;`. It would be best for the author to catch the inconsistencies, but unrealistic that everyone would be handled" } ]
[ { "body": "<p>To be honest, I didn't read all of the code. I gave up half way through. I believe this is due to two points:</p>\n<ul>\n<li><p>You are not using the established CSS terms, e.g. &quot;block&quot; instead of &quot;rule&quot; and &quot;parameter&quot; instead of &quot;declaration&quot;.</p>\n</li>\n<li><p>Most of the comments confused me more than they helped.</p>\n</li>\n</ul>\n<p>Additionally the parsing is too simple. It will choke on unexpected braces, for example <code>content: &quot;}&quot;</code>, and on group rules such as media queries.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T10:39:10.810", "Id": "483440", "Score": "0", "body": "I feel your pain, could have been a comment?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T14:08:03.573", "Id": "483450", "Score": "0", "body": "Thanks for the honest feedback. I didn't realize that my code is hard to read, so that's good to know. I also added the 2 bugs you mentioned to my GitHub issues." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T10:11:26.367", "Id": "246069", "ParentId": "245897", "Score": "3" } }, { "body": "<p>From a long review;</p>\n<ul>\n<li><p>You should use a beautifier it will turn <code>if ( i === len-1 )</code> to <code>if (i === len-1)</code></p>\n</li>\n<li><p>This could really use an IFFE to hide your worker functions and expose 1 actual function, the <code>class</code> seems overkill.</p>\n</li>\n<li><p>You can club together some statements</p>\n<pre><code> blocks = this._sortSelectors(lines);\n blocks = this._sortParameters(blocks);\n</code></pre>\n<p>can become</p>\n<pre><code> blocks = sortParameters(sortSelectors(lines));\n</code></pre>\n<p>and</p>\n<pre><code> s = this._makeString(blocks);\n s = this._addBlankLineBetweenBlocks(s);\n s = s.trim();\n</code></pre>\n<p>can become</p>\n<pre><code> s = this.separateBlocks(makeString(blocks)).trim();\n</code></pre>\n</li>\n<li><p>This looks write you wrote your own <code>String.join()</code></p>\n<pre><code> // lines =&gt; string\n let s = &quot;&quot;;\n for ( let line of lines ) {\n s += line[1] + &quot;\\n&quot;;\n }\n s = s.slice(0, s.length-1);\n return s;\n</code></pre>\n<p>you could just</p>\n<pre><code> return lines.map(line=&gt;line[1]).join('\\n');\n</code></pre>\n</li>\n<li><p>Always consider FP when dealing with list;</p>\n<pre><code> let lines = [];\n for ( let block of blocks ) {\n let lines2 = block[1];\n for ( let line of lines2 ) {\n lines.push(line);\n }\n }\n</code></pre>\n<p>could be</p>\n<pre><code> const lines = blocks.map(block =&gt; block[1]).flat(); \n</code></pre>\n</li>\n<li><p>Minor nitpicking on this;</p>\n<pre><code> // Trimmed line in first spot. Important for sorting.\n value.trim(),\n</code></pre>\n<p>You could have written a custom sort function that does the <code>trim()</code></p>\n</li>\n<li><p>Dont do <code>console.log</code> in final code</p>\n</li>\n<li><p><code>let</code> vs. <code>const</code> always requires some contemplation</p>\n<ul>\n<li><code>let value = lines[key];</code> should be <code>const value = lines[key];</code></li>\n<li><code>let isParameter = line[3];</code> should be a <code>const</code></li>\n<li><code>let lines = s.split(&quot;\\n&quot;);</code> should be a <code>const</code></li>\n</ul>\n</li>\n<li><p>Potential Parsing Problems</p>\n<ul>\n<li><code> value.includes(&quot;}&quot;</code> would go funky with some comments /* } */</li>\n<li>Also, <code>value.includes(&quot;{&quot;)</code> of course</li>\n</ul>\n</li>\n<li><p>If you like <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator\" rel=\"nofollow noreferrer\">ternary operators</a> then</p>\n<pre><code> if ( value.includes(&quot;{&quot;) ) {\n isParameter = true;\n }\n</code></pre>\n<p>could be</p>\n<pre><code> isParameter = value.includes(&quot;{&quot;) ? true : isParameter;\n</code></pre>\n<p>however I think your version reads better</p>\n</li>\n<li><p>The html could use a <code>&lt;meta charset=&quot;UTF-8&quot;&gt;</code></p>\n</li>\n<li><p><code>if ( sortBuffer ) {</code> always executes, you probably meant to go for <code>if ( sortBuffer.length ) {</code>, personally I dropped the <code>if</code> statement altogether for elegance, the code works either way</p>\n</li>\n</ul>\n<p>The below is my counter proposal, my FP skills were not good enough to convert <code>sortSelectors</code> and <code>sortParameters</code> but I am sure there is a way to make these functions cleaner;</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>/*jshint esnext:true */\n\nconst styleSorter = (function createStyleSorter(){\n \"use strict\";\n \n // TODO: this._validate();\n // TODO: this._beautify(); using regex and replace of { ; }\n function alphabetize(s){\n \n const lines = makeLines(s + '\\n');\n const blocks = sortParameters(sortSelectors(lines));\n\n return separateBlocks(makeString(blocks)).trim(); \n }\n \n //TODO: Always document your regex expressions\n function separateBlocks(s) {\n return s.replace(/}\\n([^\\n])/, \"}\\n\\n$1\");\n } \n \n function makeString(blocks){\n //get 2nd element of each block, flatten, get 2nd element again\n const lines = blocks.map(block =&gt; block[1]).flat().map(fields =&gt; fields[1]);\n return lines.join('\\n');\n }\n \n //Makes an array of arrays. [trimmed, notTrimmed, blockNum, isParameter].\n //Having unique block numbers will be important later, when we sort\n //TODO: refactor with associative array &lt;- Not sure that will help much?\n function makeLines(s) {\n let blockNum = 0;\n let isParameter = false;\n \n return s.split(\"\\n\").map((value, key) =&gt; {\n \n if ( value.includes(\"}\") ) {\n isParameter = false;\n }\n \n //First value is trimmed for sorting\n const line = [value.trim(), value, blockNum, isParameter];\n \n if ( value.includes(\"}\") ) {\n blockNum++;\n }\n \n if ( value.includes(\"{\") ) {\n isParameter = true;\n } \n \n return line;\n });\n }\n \n function sortSelectors(lines) {\n /** [parameterTrimmed, [line, line, line, line]] */\n let blocks = [];\n /** [line, line, line, line] **/\n let buffer = [];\n let lineNumTracker = 0;\n let parameterTrimmed = \"\";\n let len = lines.length;\n \n for ( let i = 0; i &lt; len; i++ ) {\n let line = lines[i];\n let lineNum = line[2];\n \n if (!parameterTrimmed &amp;&amp; line[0].includes(\"{\") ) {\n parameterTrimmed = line[0];\n }\n \n if (lineNum !== lineNumTracker) {\n lineNumTracker++;\n blocks.push([parameterTrimmed, buffer]);\n buffer = [];\n parameterTrimmed = \"\";\n }\n \n buffer.push(line);\n }\n \n return blocks.sort();\n }\n \n function sortParameters(blocks) {\n const IS_PARAMETER = 3;\n for ( let key in blocks ) {\n let lines = blocks[key][1];\n let lineBuffer = [];\n let sortBuffer = [];\n \n for (let line of lines) {\n \n if (line[IS_PARAMETER]) {\n sortBuffer.push(line);\n } else {\n lineBuffer = lineBuffer.concat(sortBuffer.sort());\n lineBuffer.push(line); \n }\n \n blocks[key][1] = lineBuffer;\n }\n return blocks;\n }\n }\n \n return alphabetize; \n})();\n\nwindow.addEventListener('DOMContentLoaded', (e) =&gt; {\n let css = document.getElementById('css');\n let alphabetize = document.getElementById('alphabetize');\n \n // TODO: Combo box that loads tests.\n alphabetize.addEventListener('click', function(e) {\n css.value = styleSorter(css.value);\n });\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {\n margin: 1em;\n width: 95%;\n max-width: 700px;\n font-family: sans-serif;\n}\n\ntextarea {\n width: 100%;\n height: 360px;\n tab-size: 4;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;!DOCTYPE html&gt;\n\n&lt;html lang=\"en-us\"&gt;\n\n&lt;head&gt;\n &lt;meta charset=\"UTF-8\"&gt;\n &lt;title&gt;CSS Alphabetizer&lt;/title&gt;\n &lt;link rel=\"stylesheet\" href=\"style.css\" /&gt;\n &lt;script type=\"module\" src=\"css-alphabetizer.js\"&gt;&lt;/script&gt;\n&lt;/head&gt;\n\n&lt;body&gt;\n &lt;h1&gt;\n CSS Alphabetizer\n &lt;/h1&gt;\n \n &lt;p&gt;\n Beautify your CSS. Sort your selectors alphabetically (which groups together #id's, .classes, and then elements), and sort your parameters alphabetically too. Parameters are nested within braces, so those aren't easy to sort with a normal A-Z sort.\n &lt;/p&gt;\n \n &lt;p&gt;\n &lt;textarea id=\"css\"&gt;body {\n background-color: #999999;\n margin-bottom: 0;\n}\n\n#page-container {\n background-color: #DFDFDF;\n width: 1150px;\n margin: 12px auto 0 auto;\n}\n\n#page-container2 {\n padding: 12px 12px 0 12px;\n}\n\nheader {\n background-color: white;\n}\n\n.category {\n display: inline-block;\n padding: 18px 25px;\n font-family: sans-serif;\n}\n\n.category:hover {\n background-color: #059BD8;\n}&lt;/textarea&gt;\n &lt;/p&gt;\n \n &lt;p&gt;\n &lt;button id=\"alphabetize\"&gt;Alphabetize&lt;/button&gt;\n &lt;/p&gt;\n \n &lt;p&gt;\n Want to report a bug or request a feature? &lt;a href=\"https://github.com/RedDragonWebDesign/css-alphabetizer/issues\"&gt;Create an issue&lt;/a&gt; on our GitHub.\n &lt;/p&gt;\n&lt;/body&gt;\n\n&lt;/html&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T14:06:01.423", "Id": "483448", "Score": "0", "body": "Thanks for the detailed response. I'll incorporate a lot of these changes. If you get a minute, can you give a summary of the advantages and disadvantages of functional programming? So far, I like that functions like `.map()` make code more concise. And I guess having many small functions is good for self documenting code. But I do not like having to spend mental effort on deciding if a variable is going to change or not (let vs const). And the `const = function` structure used above looks similar to a class. I also think that clubbing together statements might sometimes be less readable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-30T10:54:25.343", "Id": "483783", "Score": "0", "body": "*The const function* looks like a class; yes, but it returns 1 function. `let` vs. `const` has actually saved me a few times already where I was unwittingly overriding a variable. Finally, yes, clubbing is a matter of personal taste but can also prevent the creation of 1 time use variables." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T10:47:57.700", "Id": "246071", "ParentId": "245897", "Score": "3" } } ]
{ "AcceptedAnswerId": "246071", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-22T22:59:30.603", "Id": "245897", "Score": "7", "Tags": [ "javascript" ], "Title": "CSS Alphabetizer" }
245897
<p>I made the UI for the hacking minigame from the Fallout series. Could I get some feedback on the main <code>Game.js</code> component? It's my first React app.</p> <p>I'm especially curious as to whether my code is easily testable, and also if it has a lot of clarity, ie. if it's easy to understand. I am also curious of improvements that can be made to the algorithm. Also, does it follow React best practices?</p> <p>Game.js</p> <pre><code>import React from &quot;react&quot;; import CharacterSequence from &quot;./CharacterSequence&quot;; function Game() { let nbAttempsLeft = 3; let characters = &quot;./@.!@#$%^&amp;*()-=+&gt;&lt;,[]{}&quot;; let words = [&quot;STORY&quot;, &quot;SYNOPSIS&quot;, &quot;THE&quot;, &quot;PLAYER&quot;, &quot;CHARACTER&quot;, &quot;STUMBLES&quot;, &quot;IRRADIATED&quot;, &quot;PRESSURE&quot;, &quot;ABILITY&quot;]; /** * Generates a string from filler characters. Ex: &quot;*.!++}/.,.#^&quot; * @param {*} characters the characters to randomly choose from * @param {*} length the length of the filler string */ function generateFiller(characters, length) { let filler = &quot;&quot;; for (let i = 0; i &lt; length; i++) { filler += characters.charAt(Math.floor(Math.random() * characters.length)); } return filler; } /** * Each row is preceded by 0x${HEXCODE}. * @param {*} hexStart the decimal number to use as a starting point. * @param {*} i number of times to multiply increment by. * @param {*} increment the increment to use when adding to hexStart. */ function generateHex(hexStart, i, increment) { // Each row has a HEX identifier which starts at 61623 (decimal) and increases by 12 every row. // Ex: 0xF0B7, 0xF0C3, etc. const hex = `0x${(hexStart + increment * i).toString(16).toLocaleUpperCase()}`; return hex; } /** * Generates an array of sequences in the Fallout terminal format. * Ex: 0xEF8B %^ABILITY/.} * @param {*} amount how many sequences to put in the array. */ function generateSequences(amount) { let sequences = []; for (let i = 0; i &lt; amount; i++) { let sequence = `${generateHex(61323, i, 12)} ${generateFiller(characters, 12)}`; sequences.push(sequence); } return sequences; } /** * Randomly adds words from a word list to an array of sequences. * @param {*} sequences the array of sequences to add words to. * @param {*} words the word list to choose from. * @param {*} amount the amount of words to add in the sequences array. */ function addWords(sequences, words, amount) { const lengthOfHex = 7; for (let i = 0; i &lt; amount; i++) { // Choose a word in the word list and remove it after (prevent duplicates). let wordIndex = Math.floor(Math.random() * words.length); let word = words[wordIndex]; words.splice(wordIndex, 1); // Choose a random number that will determine where the word starts in the sequence. // (12 - word.length) is the remaining spaces for filler characters. let wordStart = Math.floor(Math.random() * (12 - word.length)); // Choose a random sequence to add a word to. TODO: Prevent duplicates. let index = Math.floor(Math.random() * sequences.length); sequences[index] = sequences[index].substr(0, wordStart + lengthOfHex) + word + sequences[index].substr(wordStart + word.length + lengthOfHex); } } let sequences = generateSequences(34); addWords(sequences, words, 9); return ( &lt;div id=&quot;App&quot;&gt; &lt;div id=&quot;terminal&quot;&gt; &lt;div className=&quot;header&quot;&gt; &lt;p&gt;ROBCO INDUSTRIES (TM) TERMLINK PROTOCOL&lt;/p&gt; &lt;p&gt;ENTER PASSWORD NOW&lt;/p&gt; &lt;/div&gt; &lt;div className=&quot;attempts&quot;&gt; &lt;p&gt;{nbAttempsLeft} ATTEMPT(S) LEFT...&lt;/p&gt; &lt;/div&gt; {sequences.map((sequence) =&gt; ( &lt;CharacterSequence sequence={`${sequence}`}&gt;&lt;/CharacterSequence&gt; ))} &lt;/div&gt; &lt;/div&gt; ); } export default Game; <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T03:19:44.887", "Id": "483048", "Score": "0", "body": "You're missing the symbol pairs `[...],{...},(...)` and probably some others. These are \"bonuses\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T16:05:28.503", "Id": "483117", "Score": "0", "body": "@Nelson that's true, I wanted to keep the project simple. Also in the fallout games a word can continue on another line.. like: \"#$>}SPECI<change line>AL#$%..,\"." } ]
[ { "body": "<h1>Questions</h1>\n<ol>\n<li>Is it easily testable</li>\n<li>Is it easy to understand</li>\n<li>Does it follow best practices</li>\n</ol>\n<h1>Answers</h1>\n<ol>\n<li>In my opinion, not really. You've essentially a collection of unexposed utility functions that aren't available to directly test. In order to exercise them all you'd need to come up with many sets of inputs to the component (i.e. props). The <code>Game</code> component, however, doesn't consume any props, so you'll have a single test using the hardcoded magic numbers <em>also</em> defined internally.</li>\n</ol>\n<p>The suggestion here is to factor these utility functions into a separate file and export, which allows for very easy testing.</p>\n<ol start=\"2\">\n<li>Yes, this code is very straight forward and documented well.</li>\n</ol>\n<p>My only suggestion here is to utilize the <em>jsDoc</em> notation more effectively by <em>actually</em> declaring the parameter types, and if necessary, define the return type (if your IDE intellisense isn't capable of determining this via static analysis).</p>\n<ol start=\"3\">\n<li>Not quite. There appears to be some missed opportunities to make your code more DRY (i.e. generating a random number in a range), unnecessarily defining variables that don't ever change within the functional component body (i.e. they will be redeclared on every render), and mutating function arguments.</li>\n</ol>\n<p>My suggestion here is to also move these declarations out of the component and declare them const. Additionally, it appears that <code>nbAttemptsLeft</code> and <code>sequences</code> are intended to be component state, so make them component state. Generally speaking, functions <em>shouldn't</em> mutate passed parameters, as is the case with <code>addWords</code>, so it should return a <em>new</em> array of updated sequence values.</p>\n<h2>Updated code suggestions</h2>\n<p>Utility file - these can now all be easily tested in isolation/decoupled from component</p>\n<pre><code>/**\n * Generate a random integer between 0 inclusive and max exclusive\n * @param {number} max maximum random value range, exclusive\n */\nexport const random = max =&gt; Math.floor(Math.random() * max);\n\n/**\n * Generates a string from filler characters. Ex: &quot;*.!++}/.,.#^&quot;\n * @param {string} characters the characters to randomly choose from\n * @param {number} length the length of the filler string\n */\nexport function generateFiller(characters, length) {\n let filler = &quot;&quot;;\n\n for (let i = 0; i &lt; length; i++) {\n filler += characters.charAt(random(characters.length));\n }\n\n return filler;\n}\n\n/**\n * Each row is preceded by 0x${HEXCODE}.\n * @param {number} hexStart the decimal number to use as a starting point.\n * @param {number} i number of times to multiply increment by.\n * @param {number} increment the increment to use when adding to hexStart.\n */\nexport function generateHex(hexStart, i, increment) {\n // Each row has a HEX identifier which starts at 61623 (decimal) and increases by 12 every row.\n // Ex: 0xF0B7, 0xF0C3, etc.\n return `0x${(hexStart + increment * i).toString(16).toLocaleUpperCase()}`;\n}\n\n/**\n * Generates an array of sequences in the Fallout terminal format.\n * Ex: 0xEF8B %^ABILITY/.}\n * @param {number} amount how many sequences to put in the array.\n * @param {string} characters the characters to randomly choose from\n */\nfunction generateSequences(amount, characters) {\n const sequences = [];\n\n for (let i = 0; i &lt; amount; i++) {\n let sequence = `${generateHex(61323, i, 12)} ${generateFiller(characters, 12)}`;\n sequences.push(sequence);\n }\n\n return sequences;\n}\n\n/**\n * Randomly adds words from a word list to an array of sequences.\n * @param {string[]} sequences the array of sequences to add words to.\n * @param {string[]} words the word list to choose from.\n * @param {number} amount the amount of words to add in the sequences array.\n * @return {string[]} updated sequences array\n */\nexport function addWords(sequences, words, amount) {\n const lengthOfHex = 7;\n\n // create shallow copy to not mutate passed argument\n const updatedSequences = [...sequences];\n\n for (let i = 0; i &lt; amount; i++) {\n // Choose a word in the word list and remove it after (prevent duplicates).\n const wordIndex = random(words.length);\n const word = words[wordIndex];\n words.splice(wordIndex, 1);\n\n // Choose a random number that will determine where the word starts in the sequence.\n // (12 - word.length) is the remaining spaces for filler characters.\n const wordStart = random(12 - word.length);\n\n // Choose a random sequence to add a word to. TODO: Prevent duplicates.\n const index = random(sequences.length);\n updatedSequences[index] = sequences[index].substring(0, wordStart + lengthOfHex) + word + sequences[index].substring(wordStart + word.length + lengthOfHex);\n\n // NOTE: string::substr is actually a deprecated API and no longer recommended\n // use string::substring instead\n\n // return new sequences array\n return updatedSequences;\n }\n}\n</code></pre>\n<p>Game component</p>\n<pre><code>import React, { useEffect, useState} from &quot;react&quot;;\nimport CharacterSequence from &quot;./CharacterSequence&quot;;\nimport {\n addWords,\n generateFiller,\n generateHex,\n generateSequences,\n random,\n} from './utils';\n\nconst characters = &quot;./@.!@#$%^&amp;*()-=+&gt;&lt;,[]{}&quot;;\nconst words = [&quot;STORY&quot;, &quot;SYNOPSIS&quot;, &quot;THE&quot;, &quot;PLAYER&quot;, &quot;CHARACTER&quot;, &quot;STUMBLES&quot;, &quot;IRRADIATED&quot;, &quot;PRESSURE&quot;, &quot;ABILITY&quot;];\n\nfunction Game() {\n // Number of hacking attempts remaining\n const [attemptsLeft, setAttemptsLeft] = useState(3);\n\n // Randomly generated sequence of byte-code\n const [sequences, setSequences] = useState(() =&gt; {\n return addWords(\n generateSequences(34),\n words,\n 9\n );\n });\n\n return (\n &lt;div id=&quot;App&quot;&gt;\n &lt;div id=&quot;terminal&quot;&gt;\n &lt;div className=&quot;header&quot;&gt;\n &lt;p&gt;ROBCO INDUSTRIES (TM) TERMLINK PROTOCOL&lt;/p&gt;\n &lt;p&gt;ENTER PASSWORD NOW&lt;/p&gt;\n &lt;/div&gt;\n &lt;div className=&quot;attempts&quot;&gt;\n &lt;p&gt;{attemptsLeft} ATTEMPT(S) LEFT...&lt;/p&gt;\n &lt;/div&gt;\n {sequences.map((sequence) =&gt; (\n &lt;CharacterSequence sequence={`${sequence}`} /&gt;\n ))}\n &lt;/div&gt;\n &lt;/div&gt;\n );\n}\n\nexport default Game;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T07:23:34.750", "Id": "245953", "ParentId": "245898", "Score": "1" } } ]
{ "AcceptedAnswerId": "245953", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T00:08:27.563", "Id": "245898", "Score": "6", "Tags": [ "game", "react.js", "jsx" ], "Title": "Hacking Minigame" }
245898
<p>Good evening, I'm new to Rust and would like some help refactoring this small app I made so that it's more efficient, even if it may be unnecessary.</p> <p>Basically I'm trying to figure out better ways to do stuff, and if I could analyze how someone would do the same thing, but better, I think it could help me learn a bit more about the language.</p> <p>I haven't got too far into the language yet, but I would like to nip any bad habits I might run into before they become a problem.</p> <p>What this app basically does, is it asks for how many cards are in a Magic: The Gathering deck, and then a few questions about the cards, then determines how much and what types of lands you should have in the deck.</p> <pre><code>use std::io; fn main() { let deck_size = get_deck_size(); let spells = get_spell_count(deck_size); let total_cmc = get_total_cmc(); calculate_mana(deck_size, spells, total_cmc); fn get_deck_size() -&gt; f32 { loop { let mut input = String::new(); println!(&quot;How many cards are in your deck?&quot;); io::stdin() .read_line(&amp;mut input) .expect(&quot;Failed to read input.&quot;); let input = input .trim() .parse::&lt;f32&gt;() .expect(&quot;Please enter a valid number.&quot;); if input &gt;= 40.0 { break input; } println!(&quot;Your deck is too small, the minimum amount of cards in a deck is 40, please enter a new deck size.&quot;) } } fn get_spell_count(deck_size: f32) -&gt; f32 { loop { let mut input = String::new(); println!(&quot;How many spells are in your deck?&quot;); io::stdin() .read_line(&amp;mut input) .expect(&quot;Failed to read input.&quot;); let input = input .trim() .parse::&lt;f32&gt;() .expect(&quot;Please enter a valid number.&quot;); if input &lt;= deck_size { break input; } println!(&quot;You have more spells in your deck than the amount of cards in your deck, please enter a new number of spells.&quot;) } } fn get_total_cmc() -&gt; f32 { loop { let mut input = String::new(); println!(&quot;What's the total converted mana cost of all your spells?&quot;); io::stdin() .read_line(&amp;mut input) .expect(&quot;Failed to read input.&quot;); let input = input .trim() .parse::&lt;f32&gt;() .expect(&quot;Please enter a valid number.&quot;); if input &gt;= 0.0 { break input; } println!(&quot;Something is wrong here.&quot;) } } fn calculate_mana(deck_size: f32, spells: f32, total_cmc: f32) { let mut symbol_count = Vec::new(); let total_lands = deck_size - spells; let colors = [&quot;white&quot;, &quot;blue&quot;, &quot;green&quot;, &quot;red&quot;, &quot;black&quot;, &quot;colorless&quot;]; println!(&quot;Now we need to get all the mana symbols throughout your deck (not just in the cmc, but in the cards abilities as well).&quot;); for i in colors.iter() { let mut input = String::new(); println!(&quot;How many {} symbols are in the deck?&quot;, i); io::stdin() .read_line(&amp;mut input) .expect(&quot;Failed to read input.&quot;); let color = ( input .trim() .parse::&lt;f32&gt;() .expect(&quot;Please enter a valid number.&quot;), i, ); symbol_count.push(color); } println!(&quot;Your average CMC is: {}&quot;, total_cmc / deck_size); println!(&quot;You should have {} total land&quot;, total_lands); for i in symbol_count { if i.0 &gt; 0.0 { let x = ((total_lands / spells) * i.0).round(); println!(&quot;{} of those lands should be {}&quot;, x, i.1); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T04:51:16.793", "Id": "483055", "Score": "0", "body": "Your question title is too generic, change it to a brief description of what your code is supposed to do please." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T07:23:15.443", "Id": "483072", "Score": "1", "body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." } ]
[ { "body": "<p>Your code passes <code>rustfmt</code> and <code>clippy</code> — good job!</p>\n<p>Here's my suggestions.</p>\n<h1>Organization</h1>\n<p>Move the functions out of <code>main</code>. The local functions make <code>main</code>\nunnecessarily long. Having free functions instead clarifies the\nsemantics of the program, and reduces the indentation.</p>\n<h1>Type usage</h1>\n<p>In my understanding, the number of cards contained in a deck is always\na nonnegative integer, so it is probably better to use <code>u32</code> instead\nof <code>f32</code> to store the card counts. <code>u32</code> can be losslessly converted\nto <code>f64</code> when doing floating point arithmetic.</p>\n<h1>Error handling</h1>\n<p>When the user input cannot be deciphered, the program panics with an\nerror message. Failing to read a line is probably an irrecoverable\nerror, but for parse errors, a better alternative is to ask the user\nto re-enter data, so that users don't have to repeat everything they\ntyped because of a typo.</p>\n<h1>Deduplication</h1>\n<p>This pattern occurs many times:</p>\n<pre><code>let mut input = String::new();\nprintln!(&quot;&lt;prompt&gt;&quot;);\nio::stdin()\n .read_line(&amp;mut input)\n .expect(&quot;Failed to read input.&quot;);\nlet input = input\n .trim()\n .parse::&lt;f32&gt;()\n .expect(&quot;Please enter a valid number.&quot;);\n</code></pre>\n<p>We can make a dedicated function:</p>\n<pre><code>fn input(prompt: &amp;str) -&gt; Result&lt;u32, std::num::ParseIntError&gt; {\n println!(&quot;{}&quot;, prompt);\n\n let mut input = String::new();\n io::stdin()\n .read_line(&amp;mut input)\n .expect(&quot;cannot read input&quot;);\n input.trim().parse()\n}\n</code></pre>\n<p>Now, the functions that ask for input can be simplified:</p>\n<pre><code>fn get_deck_size() -&gt; u32 {\n loop {\n match input(&quot;How many cards are in your deck?&quot;) {\n Ok(deck_size) if deck_size &gt;= 40 =&gt; return deck_size,\n Ok(_) =&gt; println!(&quot;The minimum number of cards in a deck is 40.&quot;),\n Err(_) =&gt; println!(&quot;Invalid number.&quot;),\n }\n }\n}\n\nfn get_spell_count(deck_size: u32) -&gt; u32 {\n loop {\n match input(&quot;How many spells are in your deck?&quot;) {\n Ok(spell_count) if spell_count &lt;= deck_size =&gt; return spell_count,\n Ok(_) =&gt; println!(&quot;You cannot have more spells than cards.&quot;),\n Err(_) =&gt; println!(&quot;Invalid number.&quot;),\n }\n }\n}\n\nfn get_total_cmc() -&gt; u32 {\n loop {\n match input(&quot;What's the total converted mana cost of all your spells?&quot;) {\n Ok(total_cmc) =&gt; return total_cmc,\n Err(_) =&gt; println!(&quot;Invalid number.&quot;),\n }\n }\n}\n</code></pre>\n<p>Note that the <code>total_cmc &gt;= 0</code> check can be elided.</p>\n<h1>Calculation</h1>\n<p>Here's my version:</p>\n<pre><code>const COLORS: [&amp;str; 6] = [&quot;white&quot;, &quot;blue&quot;, &quot;green&quot;, &quot;red&quot;, &quot;black&quot;, &quot;colorless&quot;];\n\nfn calculate_mana(deck_size: u32, spells: u32, total_cmc: u32) {\n let total_lands = deck_size - spells;\n\n println!(&quot;Now we need to get all the mana symbols throughout your deck (not just in the cmc, but in the cards abilities as well).&quot;);\n let symbol_counts = get_symbol_counts();\n\n println!(\n &quot;Your average CMC is: {}&quot;,\n f64::from(total_cmc) / f64::from(deck_size)\n );\n println!(&quot;You should have {} total land&quot;, total_lands);\n\n // FIXME: rename to fit game nomenclature\n let land_percentage = f64::from(total_lands) / f64::from(spells);\n\n for (&amp;symbol_count, &amp;color) in symbol_counts.iter().zip(COLORS.iter()) {\n if symbol_count &gt; 0 {\n // FIXME: rename to fit game nomenclature\n let land_count = land_percentage * f64::from(symbol_count);\n println!(&quot;{} of those lands should be {}&quot;, land_count, color);\n }\n }\n}\n</code></pre>\n<p>Changes I made:</p>\n<ul>\n<li><p>rename <code>i</code> to <code>color</code>;</p>\n</li>\n<li><p>rename <code>symbol_count</code> to <code>symbol_counts</code>, since it's a vector;</p>\n</li>\n<li><p>use <a href=\"https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.copied\" rel=\"nofollow noreferrer\"><code>.copied()</code></a>, so that the vector stores the colors directly,\nrather than references to elements within the local array;</p>\n</li>\n<li><p>promotes <code>colors</code> to a global <code>const</code>;</p>\n</li>\n<li><p>use a separate function to read the data;</p>\n</li>\n<li><p>remove the <code>.0</code> and <code>.1</code>, and store colors only once;</p>\n</li>\n<li><p>use <a href=\"https://doc.rust-lang.org/std/vec/struct.Vec.html#method.with_capacity\" rel=\"nofollow noreferrer\"><code>Vec::with_capacity</code></a> to avoid unnecessary reallocations.</p>\n</li>\n</ul>\n<p>I also reported the result as a floating point number, since they may\nbe helpful for, say, probabilistic analysis. This is purely\nsubjective.</p>\n<h1>Result</h1>\n<p>Putting everything together:</p>\n<pre><code>use std::io;\n\nconst COLORS: [&amp;str; 6] = [&quot;white&quot;, &quot;blue&quot;, &quot;green&quot;, &quot;red&quot;, &quot;black&quot;, &quot;colorless&quot;];\n\nfn main() {\n let deck_size = get_deck_size();\n let spells = get_spell_count(deck_size);\n let total_cmc = get_total_cmc();\n\n calculate_mana(deck_size, spells, total_cmc);\n}\n\nfn input(prompt: &amp;str) -&gt; Result&lt;u32, std::num::ParseIntError&gt; {\n println!(&quot;{}&quot;, prompt);\n\n let mut input = String::new();\n io::stdin()\n .read_line(&amp;mut input)\n .expect(&quot;cannot read input&quot;);\n input.trim().parse()\n}\n\nfn get_deck_size() -&gt; u32 {\n loop {\n match input(&quot;How many cards are in your deck?&quot;) {\n Ok(deck_size) if deck_size &gt;= 40 =&gt; return deck_size,\n Ok(_) =&gt; println!(&quot;The minimum number of cards in a deck is 40.&quot;),\n Err(_) =&gt; println!(&quot;Invalid number.&quot;),\n }\n }\n}\n\nfn get_spell_count(deck_size: u32) -&gt; u32 {\n loop {\n match input(&quot;How many spells are in your deck?&quot;) {\n Ok(spell_count) if spell_count &lt;= deck_size =&gt; return spell_count,\n Ok(_) =&gt; println!(&quot;You cannot have more spells than cards.&quot;),\n Err(_) =&gt; println!(&quot;Invalid number.&quot;),\n }\n }\n}\n\nfn get_total_cmc() -&gt; u32 {\n loop {\n match input(&quot;What's the total converted mana cost of all your spells?&quot;) {\n Ok(total_cmc) =&gt; return total_cmc,\n Err(_) =&gt; println!(&quot;Invalid number.&quot;),\n }\n }\n}\n\nfn get_symbol_counts() -&gt; Vec&lt;u32&gt; {\n let mut symbol_counts = Vec::with_capacity(COLORS.len());\n\n for color in COLORS.iter().copied() {\n let symbol_count = loop {\n // FIXME: could be written more clearly\n print!(&quot;How many {} symbols are in the deck?&quot;, color);\n match input(&quot;&quot;) {\n Ok(symbol_count) =&gt; break symbol_count,\n Err(_) =&gt; println!(&quot;Invalid number.&quot;),\n }\n };\n symbol_counts.push(symbol_count);\n }\n\n symbol_counts\n}\n\nfn calculate_mana(deck_size: u32, spells: u32, total_cmc: u32) {\n let total_lands = deck_size - spells;\n\n println!(&quot;Now we need to get all the mana symbols throughout your deck (not just in the cmc, but in the cards abilities as well).&quot;);\n let symbol_counts = get_symbol_counts();\n\n println!(\n &quot;Your average CMC is: {}&quot;,\n f64::from(total_cmc) / f64::from(deck_size)\n );\n println!(&quot;You should have {} total land&quot;, total_lands);\n\n // FIXME: rename to fit game nomenclature\n let land_percentage = f64::from(total_lands) / f64::from(spells);\n\n for (&amp;symbol_count, &amp;color) in symbol_counts.iter().zip(COLORS.iter()) {\n if symbol_count &gt; 0 {\n // FIXME: rename to fit game nomenclature\n let land_count = land_percentage * f64::from(symbol_count);\n println!(&quot;{} of those lands should be {}&quot;, land_count, color);\n }\n }\n}\n</code></pre>\n<p>(<a href=\"https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=03c0e56ceaa603916896532865368376\" rel=\"nofollow noreferrer\">playground</a>)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T06:22:00.117", "Id": "245992", "ParentId": "245899", "Score": "1" } } ]
{ "AcceptedAnswerId": "245992", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T03:16:05.780", "Id": "245899", "Score": "4", "Tags": [ "rust" ], "Title": "An app that helps determine lands in a Magic: The Gathering deck" }
245899
<p>I've got this quick and dirty little console app in C# to serve an HTTP/HTML page.</p> <pre><code>static void Main() { // create a socket var socket = new Socket(SocketType.Stream, ProtocolType.Tcp); // bind to localhost:8080 socket.Bind(new IPEndPoint(IPAddress.Loopback, 8080)); socket.Listen(16); // listen // begin our accept task var t = socket.AcceptTaskAsync(); // when we're done accepting process the request t.ContinueWith((task) =&gt; { _ProcessRequest(socket, t); }); // show a prompt and wait for a keypress to exit Console.WriteLine(&quot;Press any key to exit...&quot;); Console.ReadKey(); } static void _ProcessRequest(Socket socket,Task&lt;Socket&gt; t) { Console.Write(&quot;Awaiting request...&quot;); t.ContinueWith((task1) =&gt; { var s = t.Result; var rt = s.ReceiveHttpRequestAsync(); rt.ContinueWith((task2) =&gt; { Console.Write(&quot;Done: &quot;); var req = rt.Result; Console.WriteLine(req.Method + &quot; &quot; + req.Url); // our html to send var html = &quot;&lt;html&gt;&lt;head&gt;&lt;title&gt;Hello&lt;/title&gt;&lt;/head&gt;&lt;body&gt;&lt;h1&gt;Hello World!&lt;/h1&gt;&lt;/body&gt;&quot;; var headers = &quot;HTTP/1.1 200 OK\nDate: &quot; + DateTime.Now.ToUniversalTime().ToString(&quot;r&quot;) + &quot;\nContent-Type: text/html\nContent-Length: &quot; + html.Length.ToString() + &quot;\nConnection: Closed\n&quot;; s.SendAsync(headers + &quot;\n&quot; + html, Encoding.UTF8) .ContinueWith((task3) =&gt; { s.DisconnectAsync(false); t = socket.AcceptTaskAsync(); t.ContinueWith((task4) =&gt; { _ProcessRequest(socket, t); }); }).Wait(); s.Close(); }); }); } </code></pre> <p>I'm calling async TAP methods on a socket because I use an EAP-&gt;TAP adapter class that I built up from this code: <a href="https://blogs.msdn.microsoft.com/pfxteam/2011/12/15/awaiting-socket-operations/" rel="nofollow noreferrer">https://blogs.msdn.microsoft.com/pfxteam/2011/12/15/awaiting-socket-operations/</a> It appears to work, and it has little to do with my question, which has to do with handling incoming requests using TAP. I've also got <code>HttpReceiveRequestAsync</code> which I've used for a year and isn't important here.</p> <p>Basically what I'm trying to do is accept on a socket and then asynchronously serve the request, and then accept on a socket again to keep it going. The code works, but I don't think it works right. For one thing, my <code>_ProcessRequest()</code> routine is getting called 3 times every time I refresh the browser (i'm using chrome) - i know chrome will sometimes initiate multiple requests but i think it will only do two. Edit: I figured out why this is, and it's fine</p> <p>Also this seems dodgy. I don't know why but there's code smell, and not just because I threw it together. I don't trust it. Can anyone take a look and see if there isn't a better way to do this? I'm pretty new at this.</p> <p>Edit: I fixed it up and I trust it more now, but I just wanted to see if it could be improved, or if there is some better pattern for this. I don't care about using async/await keywords unless it significantly eases things. Sometimes it does. Here I didn't find much use.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T07:18:55.413", "Id": "483070", "Score": "0", "body": "Please edit your question's title to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T07:20:31.090", "Id": "483071", "Score": "1", "body": "Also, do not put things like \"Edit: I figured out why this is, and it's fine\" in your text. Remove the superfluous parts, if we care about the edit history we can look at https://codereview.stackexchange.com/posts/245900/revisions ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T09:02:18.907", "Id": "483076", "Score": "4", "body": "It's not fine anyway. You should use `async/await` all the way to `async Task Main`, not `ContinueWith`. `_ProcessAsync` calls `.Wait()` in the end, blocking what should be an async operation. The safe way to close a Socket is to create it inside a `using` block. That's easy to do if you use `async/await`, a lot harder with `ContinueWith` and lambdas" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T16:25:19.330", "Id": "483118", "Score": "0", "body": "Thank you Panagiotis - I think you just unstuck my brain. I get what you're saying, and I understand what you mean because await creates the state machine to break up your code and make that work." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T04:16:14.083", "Id": "245900", "Score": "2", "Tags": [ "c#", "asynchronous", "async-await" ], "Title": "I'm just starting out with tasks. I need to know if there's a better way to do TAP for socket handling (serving a request)" }
245900
<p>I am not happy with two functions calling get_user() since while testing I mock get_user and to test with <code>get_user_returns_null</code> case, it returns Null for both function calls naturally which hints that the structure is not correct. I am using flask-sqlalchemy with postgres models ORM.</p> <pre><code> def insert_user(user_details): user_record = None try: user = User(name = user_details['name'], email = user_details['email']) db.session().add(user) db.session().commit() user_record = get_user(user_details) except SQLAlchemyError as e: db.session().rollback() finally: db.session().close() return user_record def add_user_favorite(user_details, project_code): user_id = None user_record = get_user(user_details) if user_record is None: user_record = insert_user(user_details) user_id = user_record['user_id'] try: user_fav = UserFavoriteProject(user_id = user_id, project_code = project_code) db.session().add(user_fav) db.session().commit() except SQLAlchemyError as e: db.session().rollback() finally: db.session().close() return is_user_favorite(user_details, project_code) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T00:14:38.297", "Id": "483155", "Score": "0", "body": "Please show all of your code, including `import` statements." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T04:30:59.597", "Id": "245901", "Score": "2", "Tags": [ "python", "python-3.x", "design-patterns", "postgresql", "sqlalchemy" ], "Title": "A task to store user's favorited projects in postgres using python" }
245901
<p>Problem:</p> <blockquote> <p>Write a program that prints the numbers from 1 to 100. But for multiples of three print &quot;Fizz&quot; instead of the number and for the multiples of five print &quot;Buzz&quot;. For numbers which are multiples of both three and five print &quot;FizzBuzz&quot;.</p> </blockquote> <p>Problem from <a href="https://programmingbydoing.com/a/fizzbuzz.html" rel="noreferrer">here</a>.</p> <p>This is my code:</p> <pre><code>/* * Code by Clint */ public class FizzBuzz { public static void main(String[] args) { for (int numbers = 1; numbers &lt;= 100; numbers++) { if (numbers % 3 == 0 &amp;&amp; numbers % 5 == 0) { System.out.println(&quot;Fizz Buzz&quot;); } else if (numbers % 3 == 0) { System.out.println(&quot;Fizz&quot;); } else if (numbers % 5 == 0) { System.out.println(&quot;Buzz&quot;); } else { System.out.println(numbers); } } } } </code></pre> <p>Here's the output: <a href="https://i.stack.imgur.com/RQ3ot.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/RQ3ot.jpg" alt="Fizz Buzz output" /></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T04:40:56.613", "Id": "483053", "Score": "5", "body": "I believe your post is unsuitable here, since your code doesn't do what the problem says to do.(e.g. for 15 it prints Fizz)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T05:37:57.030", "Id": "483059", "Score": "0", "body": "@tinstaafl It appears to be fixed with the last update." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T05:39:45.667", "Id": "483061", "Score": "0", "body": "I realised that I haven't add the condition for the numbers that are divisible by 3 and 5." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T06:47:38.280", "Id": "483065", "Score": "6", "body": "Hello, according to the original exercise you should print FizzBuzz instead of Fizz whitespace Buzz for multiples of both three and five." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T06:52:19.497", "Id": "483068", "Score": "7", "body": "Things divisible by 3 and 5 are divisble by 15." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T13:44:18.580", "Id": "483110", "Score": "0", "body": "Yes, and for multiples of 3 and 5 (15) it prints \"Fizz Buzz\" instead of \"FizzBuzz\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T08:46:11.737", "Id": "483181", "Score": "0", "body": "One thing that is worth noting is that since 3 and 5 are coprime then a integer is divisible by 3 and 5 if and only if it is divisible by 15, you can use this fact to tidy up the first conditional to `if(number % 15 == 0)...`" } ]
[ { "body": "<p>The code looks perfect, except for the variable name <code>numbers</code>. This variable only holds a single number, therefore its name must be <code>number</code> instead.</p>\n<p>Since the variable is only used in a very small scope, the names <code>n</code> or <code>i</code> may be acceptable as well. (Subject to personal preference.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T11:01:22.930", "Id": "483192", "Score": "1", "body": "The scope is literally the entire program. ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T23:37:27.603", "Id": "483264", "Score": "0", "body": "By the way, if you want to write an enterprise-grade FizzBuzz, have a look at [this project](https://github.com/EnterpriseQualityCoding/FizzBuzzEnterpriseEdition/)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T05:41:58.490", "Id": "245904", "ParentId": "245902", "Score": "13" } }, { "body": "<p>For me this formatting is a little easier to read, but basically the same:</p>\n<pre><code>public class FizzBuzz {\n public static void main(String[] args) {\n for (int i = 1; i &lt;= 100; i++) {\n if (i % 3 == 0) System.out.println(&quot;Fizz&quot;);\n if (i % 5 == 0) System.out.println(&quot;Buzz&quot;);\n if (i % 3 != 0 &amp;&amp; i % 5 != 0) System.out.println(i);\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T15:39:54.587", "Id": "483116", "Score": "3", "body": "If someone said something like this to me in an interview, I would think they were trying to get a response rather than being honest. I would point them to \"Making Wrong Code Look Wrong\" and I would seriously reconsider whether I'd want to work there, if they really think that this is better code by a significant enough amount that it is worth \"correcting\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T17:08:28.350", "Id": "483126", "Score": "2", "body": "In my opinion, not adding the brace in loop / if is way more error prone, since you can easily break the logic by forgetting to add them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T18:47:19.163", "Id": "483131", "Score": "7", "body": "This solution also has a bug. If `i` is divisible by both 3 and 5, it will print out `Fizz\\nBuzz` (Fizz and Buzz on separate lines), not `FizzBuzz`. You could get around this by starting a newline either at the beginning or end of each iteration of the loop and using the `print` method instead of `println`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T19:16:31.060", "Id": "483135", "Score": "1", "body": "Ignoring the bug, the removal of `{}` goes against my very core. And I don't even use a language that uses `{}` for control flow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T00:10:28.357", "Id": "483154", "Score": "1", "body": "@Peilonrayz I too have added that to my on-save code-formatter. Too many times I've seen someone add a second line and not braces..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T10:31:18.293", "Id": "483190", "Score": "0", "body": "@corsiKa To be fair if you're using an auto formatter, it would indent the second line very differently to the first one which should be just as obvious." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T11:35:55.500", "Id": "483441", "Score": "0", "body": "thanks for pointing out the bug, but i dont get why removing the brackets is such a big issue? For me that syntax is way easier to read, plus autoformatter handles it perfectly.." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T15:28:09.660", "Id": "245921", "ParentId": "245902", "Score": "0" } }, { "body": "<p>Personally, i see multiple &quot;Tasks&quot; in that code</p>\n<ul>\n<li>Start the application</li>\n<li>Count from 1 to 100</li>\n<li>Decide what to print for the current number</li>\n<li>Print it</li>\n</ul>\n<p>The &quot;Start&quot; is for me an extra Task, because if i want that my application behaves differently on different environments (count to 100 on my local machine, but count to 1 Million on my super computer), than this would be a place to get the desired information and then forward it to the &quot;functionality&quot;.<br />\nYes this is over engineered for this small code example, but we lean with small code examples and then apply it to big applications. Therefor i like to take the big gun for small examples, as long as the goal is training. :-)</p>\n<p>In my eyes, the following code is much longer, but its easier to understand, because each methodname gives a &quot;context&quot; what will happen in it. That makes it easier to follow and understand the underlying code.</p>\n<p>Also, when the &quot;tasks&quot; are logically separated, then its much easier to apply changes to it. Changing the &quot;rules&quot; would only mean to change the <code>convertNumber</code> function. Changing the way it should print the result would be only to change the <code>output</code> method.\nAlso it would be quite easy to extract those functionalities in extra classes, and inject them. Then it would be a breeze to decide on the outside (environment) that the output should be done via <code>System.out.println</code> or via a graphical interface.</p>\n<p>But as always, many ways bring us to our goal(s). And as always if you choose one way, then you get good things, but you have to pay for them. My approach gives flexibility, but it its much more writing. The minimal slower performance would be only an argument in a high performance environment, i think, where we have to count each cycle.</p>\n<pre><code>public class FizzBuzzApp {\n public static void main(String[] args) {\n FizzBuzz game = new FizzBuzz();\n game.playGame();\n }\n}\n\npublic class FizzBuzz {\n public void playGame(){\n for (int numbers = 1; numbers &lt;= 100; numbers++) {\n String result = convertNumber(number);\n output(result);\n }\n }\n \n private String convertNumber(int number) {\n if (numbers % 3 == 0 &amp;&amp; numbers % 5 == 0) {\n return &quot;Fizz Buzz&quot;;\n } else if (numbers % 3 == 0) {\n return &quot;Fizz&quot;;\n } else if (numbers % 5 == 0) {\n return &quot;Buzz&quot;;\n } else {\n return String.valueOf(number);\n }\n }\n\n private void output(String value) {\n System.out.println(value);\n }\n}\n</code></pre>\n<p>Happy to hear about your opinion about my approach</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T16:55:27.987", "Id": "483124", "Score": "1", "body": "You should review your code, since it does not compile." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T17:00:58.013", "Id": "483125", "Score": "3", "body": "It reminds me of the Devil's Dictionary definition of structured programming: \"A way to make programs longer, sometimes without degrading their performance\". There is arguably some justification for making convertNumber a separate function, but the rest is just padding. (And \"playGame\" is a poor name for a function which has no user interaction at all - where is the \"play\" exactly?)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T19:02:45.743", "Id": "483133", "Score": "0", "body": "If this is the direction we are going, where is the dependency injection and interfaces? I kid. Sort of. I have found the simple Fizz Buzz challenge to be a good vehicle for introducing SOLID principles (or functional programming) to people because they can focus on the principles instead of the problem because it is so simple to understand. And yes, I have written a dependency-injected Fizz Buzz complete with injected sequence generator/iterator and \"FizzBuzzer\" classes" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T05:37:01.153", "Id": "483163", "Score": "0", "body": "Thanks Doi9t for the remark, Sorry, just wrote the code on the fly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T10:40:22.450", "Id": "483191", "Score": "1", "body": "There really is no reason to use a class here. Notice the missing state or virtual methods that would allow to adapt behavior. Just using static methods to separate concerns would get you the same advantages without all the boiler plate. If you want to use a class you should either make the output method abstract/virtual to allow different output. Or much better: Just pass a stream in the constructor where it should be written. But honestly you can do the same just in static methods without any downside." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T16:15:09.400", "Id": "245924", "ParentId": "245902", "Score": "1" } }, { "body": "<p>I suggest that you extract the evaluations in variables, to make the code a bit shorter <strike>and faster</strike> .</p>\n<pre class=\"lang-java prettyprint-override\"><code>for (int number = 1; number &lt;= 100; number++) {\n final boolean isFizz = number % 3 == 0;\n final boolean isBuzz = number % 5 == 0;\n\n if (isFizz &amp;&amp; isBuzz) {\n System.out.println(&quot;Fizz Buzz&quot;);\n } else if (isFizz) {\n System.out.println(&quot;Fizz&quot;);\n } else if (isBuzz) {\n System.out.println(&quot;Buzz&quot;);\n } else {\n System.out.println(number);\n }\n}\n</code></pre>\n<h2>Edit</h2>\n<p>As specified in the comments, it's not worth of talking of speed in this case, due to the optimization done by the compiler and since I didn't do any verification.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T18:47:07.677", "Id": "483130", "Score": "0", "body": "Or even boolean methods" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T20:14:14.050", "Id": "483139", "Score": "8", "body": "re: \"faster\": Speculative micro-optimisations are bad. Always write the clearest code possible, until you have measured numbers that say you need to do otherwise." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T20:41:03.073", "Id": "483142", "Score": "0", "body": "[Related](https://softwareengineering.stackexchange.com/questions/80084/is-premature-optimization-really-the-root-of-all-evil) to @JonathanHartley's comment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T07:15:56.300", "Id": "483169", "Score": "0", "body": "If your argument is about speed, then you should consider declaring those final variables outside the loop. Otherwise, the variables are reinitialized every time the loop runs. However, the compiler might optimize it for you and moreover, you need a couple of 100k iterations before you realize a difference." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T10:26:23.623", "Id": "483188", "Score": "0", "body": "@momo Any compiler that can't do that optimization (which you get for free if you use SSA anyhow) isn't worth worrying about. That said the same applies to the OPs original point. The much bigger problem is that the code is in main the main method so won't get JITed as a whole but at best via OSR which can result in much less optimal code.\nAlso obviously it doesn't matter at all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T11:41:46.390", "Id": "483193", "Score": "0", "body": "Thanks for the comments, I was thinking that moving the evaluations to a variable was preventing the revaluation of the `number % n` multiple times." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T17:02:31.447", "Id": "245925", "ParentId": "245902", "Score": "2" } }, { "body": "<p>Imagine a variant on FizzBuzz with <span class=\"math-container\">\\$n\\$</span> different say-this-syllable-if rules. Would you want to check <span class=\"math-container\">\\$2^n\\$</span> cases? That will lead to either a lot of code (<span class=\"math-container\">\\$O(2^n)\\$</span> lines) or deeply nested code (with <span class=\"math-container\">\\$O(n)\\$</span> maximum indentation). Luckily, the problem statement does you a favour: on divisibility by 15, it asks you to print FizzBuzz, not Fizz Buzz with a space as you tried. So the clean-code approach (with <span class=\"math-container\">\\$O(n)\\$</span> lines, and <span class=\"math-container\">\\$O(1)\\$</span> maximum indentation) is more like this:</p>\n<pre><code>public class FizzBuzz {\n public static void main(String[] args) {\n for (int number = 1; number &lt;= 100; number++) {\n String toPrint = &quot;&quot;;\n if(number % 3 == 0) {\n toPrint += &quot;Fizz&quot;;\n }\n if(number % 5 == 0) {\n toPrint += &quot;Buzz&quot;;\n }\n if (toPrint.isEmpty()) {\n toPrint = Integer.toString(number);\n }\n System.out.println(toPrint);\n }\n }\n}\n</code></pre>\n<p>Even in this case, where <span class=\"math-container\">\\$n=2\\$</span>, this approach has definite advantages. You easily avoid what-if-both problems, <em>and it's obvious to a reader that you did</em>. No need to think through boolean logic. Tom Scott discusses the advantages further <a href=\"https://www.youtube.com/watch?v=QPZ0pIK_wsc\" rel=\"noreferrer\">here</a>, albeit for JavaScript, not Java.</p>\n<p><a href=\"https://stackoverflow.com/questions/8020228/is-it-ok-if-i-omit-curly-braces-in-java\">A separate issue</a> is whether we even need all those braces.</p>\n<p>(By the way, I depluralized your dummy variable's name, so it doesn't look like a list of numbers.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T19:59:37.997", "Id": "483136", "Score": "1", "body": "Although this answer does encourage to think further than the problem at hand, it might be too much for someone who's learning the basics. I used to always try to think afar, and was oftenly overengineering, trying to solve \"potential future problems\". Though I definitely agree with the answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T20:04:59.403", "Id": "483137", "Score": "1", "body": "@Clockwork You have a point. Part of the reason I included that video link is because Scott gives such a good illustration of the gradualism in improving an algorithm. But yes, Fizz Buzz is usually intended as a \"can you code at all?\" test, rather than one of maintenance concerns in architecture (which is about all I could contribute that earlier answers hadn't discussed). Mind you, in interviews there can be follow-up questions. It's also worth noting the reasoning I gave is related to why we use [guard clauses](http://wiki.c2.com/?GuardClause)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T13:05:54.630", "Id": "483198", "Score": "0", "body": "I thought this answer was about performance and yet we use String concatenation??" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T13:51:37.673", "Id": "483208", "Score": "0", "body": "\"I thought this answer was about performance\" No, it's about concise, readable, maintainable code whose validity is easy to discern. FizzBuzz is never going to be a performance choke." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T14:11:25.023", "Id": "483213", "Score": "0", "body": "This solution depends on a possible coincidence that the output for a number satisfying multiple conditions is the concatenation of the outputs for each condition. Imagine a variation where the requirement for multiples of 15 were `FB` rather than `FizzBuzz`. OTOH it does demonstrate a good way to think about refactoring when the spec allows for it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T16:22:57.477", "Id": "483332", "Score": "0", "body": "@GetMeARemoteJob Using StringBuilder instead of + for simple non-loop string concatenations is worse in modern HotSpot implementations. You can either simply look at the byte code for this or read [this here](https://stackoverflow.com/questions/46512888/how-is-string-concatenation-implemented-in-java-9)." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T17:09:48.763", "Id": "245926", "ParentId": "245902", "Score": "12" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T04:34:48.513", "Id": "245902", "Score": "6", "Tags": [ "java", "fizzbuzz" ], "Title": "Solving Fizz Buzz using Java" }
245902
<p>This is my first C program. I want to optimize this simulation.</p> <p><strong>Algorithm</strong><br /> The simulation algorithm is:</p> <ol> <li>The system can go from <span class="math-container">\$i\$</span> to <span class="math-container">\$i+1\$</span> with probability <span class="math-container">\$e^{-L\theta(\rho_i)}\$</span>, where <span class="math-container">\$\rho_i=i/L\$</span>, and <span class="math-container">\$\theta(\rho)=\rho(2b-\rho)\$</span>.</li> <li>When system reaches <span class="math-container">\$n=0\$</span>, it is revieved (resurected) to position based on how much time it spent on <span class="math-container">\$n&gt;0\$</span>.</li> <li>At the end we are intrested in knowing <span class="math-container">\$\langle\rho\rangle=\sum_{t}\rho_t\$</span>.</li> </ol> <p><strong>Code</strong><br /> Following is the code. I believe this code can be compactified also. I think I do not understand the norms of the ANSI C standard. Feel free to correct me anywhere. I also do not understand if I am properly generating random numbers or not!.</p> <pre><code>#include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; #include&lt;math.h&gt; #include&lt;time.h&gt; #define LATTICE 10 #define SWEEPS 100000000 #define BETA 0.5 float rho[LATTICE]; /* Following function will make variable defined above: rho = 1/10, 2/10, 3/10, ... 1. */ void initialize() { for(int i = 0; i &lt; LATTICE; i++) rho[i] = (i+1.0)/LATTICE; return; } /* These are the rates for going form n to n+1 for a given b. */ void rates(double *death_rate, float b) { double theta; for(int i=0; i &lt; LATTICE; i++) { theta = rho[i]*(2*b - rho[i]); *death_rate = exp(-LATTICE*theta); death_rate++; } return; } /* Following function generates uniform random number between 0 to 1. */ double uniform_rand() { return (double)rand()/(double)RAND_MAX; } /* The following function revive the system when n becomes -1 with the weights = distribution. */ int revive(unsigned long long *distribution, unsigned long long norm) { int n = -1; double cumsum = 0.0, u_rand = uniform_rand(); while(cumsum &lt;= u_rand) { cumsum += (double) *distribution/(double)norm; distribution++; n++; } return n; } /* Following function calculate the average density. */ double rho_avg(unsigned long long *distribution, unsigned long long norm) { int i; double avg_density = 0.0; for (i=0; i&lt;LATTICE; i++) { avg_density += (rho[i]*(*distribution))/norm; distribution++; } return avg_density; } double monte_carlo(float b, int n) { unsigned long long i; unsigned long long distribution[LATTICE]={0}; double death_rate[LATTICE]; srand(time(0)); rates(death_rate, b); for(i = 1; i &lt;= SWEEPS; i++) { distribution[n] += 1; if (uniform_rand() &lt; death_rate[n]) { n--; if (n == -1) n = revive(distribution, i); } } return rho_avg(distribution, SWEEPS); } int main(void) { int i; double avg_density; initialize(); avg_density = monte_carlo(BETA, LATTICE-1); printf(&quot;\nAverage density is %lf\n\n&quot;, avg_density); return 0; } </code></pre>
[]
[ { "body": "<h1>Naming things</h1>\n<p>Naming things is one of the hard things in computer science. You should make sure names of functions and variables are clear and concise. In general, use nouns for variable names and verbs for function names. Looking at your choices of names in more detail:</p>\n<ul>\n<li><code>LATTICE</code> is not a lattice, it is the size of the lattice. So call it <code>LATTICE_SIZE</code>.</li>\n<li><code>SWEEPS</code> is the number of sweeps to perform, so maybe it is better to call it <code>N_SWEEPS</code> (<code>N</code> is a commonly used prefix meaning &quot;number of&quot;).</li>\n<li><code>rates()</code> is a function, so use a verb for the function name, for example <code>calculate_rates()</code>.</li>\n<li><code>rho_avg()</code> is a function again, so use a verb for that as well, like <code>calculate_rho_avg()</code>.</li>\n</ul>\n<p>You should also be consistent in how you name things. Is it <code>rho</code> or <code>density</code>? Pick one and stick with it. I would also write <code>beta</code> instead of <code>b</code>, to match how you write down other greek letters like <code>rho</code> and <code>theta</code>.</p>\n<h1>Use array indexing notation where appropriate</h1>\n<p>In <code>rates()</code>, you are using pointer arithmetic when you could just have used standard array notation:</p>\n<pre><code> for(int i = 0; i &lt; LATTICE; i++)\n {\n theta = rho[i] * (2 * b - rho[i]);\n death_rate[i] = exp(-LATTICE * theta);\n }\n</code></pre>\n<p>Similarly, in <code>revive()</code>, write:</p>\n<pre><code> for(n = 0; cumsum &lt;= u_rand; n++)\n {\n cumsum += (double)distribution[n] / (double)norm;\n }\n\n return n - 1;\n</code></pre>\n<h1>Terminology</h1>\n<p>Death rates? Revive? That sounds very morbid! Unless you are simulating some system that predicts cell death or pandemics, this is not terminology normally used in Monte Carlo simulations. Your code looks like it implements the <a href=\"https://en.wikipedia.org/wiki/Metropolis%E2%80%93Hastings_algorithm\" rel=\"nofollow noreferrer\">Metropolis algorithm</a>, where your <code>death_rate</code> would be equivalent to the transition probability, although I'm not sure what the equivalent of <code>revive()</code> would be. If it is the Metropolis algorithm you are implementing, then it doesn't look like you have detailed balance. What system are you simulating exactly? It might help to document that in the code as well.</p>\n<h1>Avoid global variables</h1>\n<p>It is good practice to avoid using global variables. That makes it easier if your program grows and becomes part of something larger. Or perhaps you want to run multiple simulations at the same time using threads. This should be easy; you already have the arrays <code>distribution[]</code> and <code>death_rate[]</code> inside <code>monte_carlo()</code>, just move <code>rho[]</code> there as well and pasas a pointer to <code>rho</code> to <code>rates()</code>.</p>\n<p>You might want to do this in a more organized way, and create a <code>struct</code> to hold all the information relevant to your simulation:</p>\n<pre><code>struct simulation_parameters {\n unsigned long long distribution[LATTICE];\n double death_rate[LATTICE];\n double rho[LATTICE];\n};\n\n...\n\ndouble monte_carlo(float beta) {\n struct simulation_parameters params = {0}; // sets everything in params to zero\n calculate_rho(params.rho); // should do what initialize() did\n calculate_death_rates(params.death_rate, beta);\n\n for (unsinged long long i = 1; i &lt;= SWEEPS; i++) {\n distribution[n]++;\n if (uniform_rand() &lt; params.death_rate[n]) {\n n--;\n if (n == -1)\n n = revive(params.distribution, i);\n }\n }\n\n return calculate_rho_avg(distribution, SWEEPS);\n}\n\nint main(void) {\n srand(time(0)); // srand() should only be called once, so do it in main()\n printf(&quot;Average density is %lf\\n&quot;, monte_carlo(BETA));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T07:23:21.510", "Id": "483287", "Score": "0", "body": "The code looks neat and readable now. I am doing the simulation of the quasi-stationary state, which is similar to Monte-Carlo process. Your suggesting for not using global variables is right because, in the end, I want to simulate for several values of betas using multiprocessing threads. In python, it is easy, but I do not know how to do it here! Any reference?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T11:04:21.850", "Id": "483306", "Score": "1", "body": "C++ comes with lots of support for [threads](https://en.cppreference.com/w/cpp/thread). You could use [`std::async()`](https://en.cppreference.com/w/cpp/thread/async) to start multiple invocations of `monte_carlo()`, and then wait for the results. Have a look at the documentation, try it out yourself, and if you get stuck just ask a question on [StackOverflow](https://stackoverflow.com/). If you get it working then you can consider creating a new code review." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T09:57:35.377", "Id": "245911", "ParentId": "245907", "Score": "4" } } ]
{ "AcceptedAnswerId": "245911", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T07:59:19.583", "Id": "245907", "Score": "4", "Tags": [ "performance", "beginner", "c" ], "Title": "Monte carlo simulation in C" }
245907
<p>I have the following method that is responsible for retrieving an <code>Item</code> from the database. There will be multiple threads instantiating this class, so I want to make sure that the operation will be thread-safe. As a result, I have added a lock around it, however since class only contains instance variables (and no static variables), is adding a lock necessary for this scenario?</p> <p></p> <pre><code>using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; namespace My.Library { public class MyDataProvider : IMyDataProvider { private object sync = new object(); private string connectionString; public MyDataProvider(string connString) { connectionString = connString; } public Item GetItem(Guid itemId) { lock (sync) { Item item = new Item(); string sqlQuery = @&quot;SELECT ItemId, ItemName FROM Item WHERE ItemId = @itemId&quot;; using SqlConnection connection = new SqlConnection(connectionString); SqlCommand command = new SqlCommand(sqlQuery, connection); command.Parameters.AddWithValue(&quot;@itemId&quot;, itemId); connection.Open(); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { item.ItemId = reader[&quot;ItemId&quot;] == DBNull.Value ? Guid.Empty : (Guid)reader[&quot;ItemId&quot;]; item.ItemName = reader[&quot;ItemName&quot;] == DBNull.Value ? null : reader[&quot;ItemName&quot;]; } return item; } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T12:31:05.430", "Id": "483092", "Score": "2", "body": "Why do you think locking is needed? What resource do you want to protect? Which piece of code would require exclusive access?" } ]
[ { "body": "<p>According to information you provided it's not necessary to wrap it with lock.</p>\n<p>Let's consider situation you described. You wrote:</p>\n<blockquote>\n<p>There will be multiple threads instantiating this class</p>\n</blockquote>\n<p>So there will be one instance for each thread. There's no synchronisation needed, because only one thread will be accessing your class at a time.</p>\n<p>Other scenarios:</p>\n<ol>\n<li>Single instance of MyDataProvider class is shared between multiple threads. What does it mean? GetItem() method could be invoked by multiple threads at the same time. In that case you'll need synchronization <strong>IF</strong> your class have any state that (private field for example) could be accessed and modified from GetItem() method. You don't have such situation, so synchronization is not needed. Also you get connection from '<a href=\"https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-connection-pooling?redirectedfrom=MSDN\" rel=\"noreferrer\">[POOL]</a>' each time anyone is invoking GetItem() instance method.</li>\n<li>Single instance of MyDataProvider class is shared between multiple threads <strong>AND</strong> sqlconnection is a state in it. Then you would need to synchronize it.</li>\n</ol>\n<p>Your implementation should be fine.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T10:25:19.130", "Id": "483081", "Score": "0", "body": "So if a single instance of MyDataProvider is not shared across multiple threads, I can remove the lock, correct?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T10:31:11.463", "Id": "483083", "Score": "0", "body": "Yes. Even if it will be shared you don't modify your state (connectionString field) so everything should be fine." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T10:05:04.563", "Id": "245912", "ParentId": "245908", "Score": "8" } } ]
{ "AcceptedAnswerId": "245912", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T09:00:55.103", "Id": "245908", "Score": "7", "Tags": [ "c#", ".net", "locking" ], "Title": "Is Lock necessary to make operation thread safe for this scenario" }
245908
<p>I have a file with over 2 million lines. I want to get the 8th column of the file and find the pattern that contains &quot;DP=&quot; and &quot;QD=&quot; and then save all the values in an array, get the mean, median and create a figure. I wrote the following script. This script goes through each line in a loop, find the pattern and saves its value in a numpy array. This is however very slow. I was wondering if there is another algorithm that can speed up the script? Thanks!</p> <pre><code>#!/usr/bin/python import sys import re import gzip import matplotlib.pyplot as plt import numpy as np dp_array = np.empty(0, dtype=float) qd_array = np.empty(0, dtype=float) c = 0 with gzip.open(sys.argv[1], 'rb') as vcf: for line in vcf: line = line.decode() # decode byte into string if not line.startswith(&quot;#&quot;): line = line.strip(&quot;\n&quot;).split(&quot;\t&quot;) c += 1 #print(c) #print(line) info = line[7] # print(info) pattern1 = re.compile(r'DP=([^;]+)') depth = re.search(pattern1, info).group(1) dp_array = np.append(dp_array, depth) #print(dp_array) pattern2 = re.compile(r'QD=([^;]+)') qd = re.search(pattern2, info).group(1) qd_array = np.append(qd_array, qd) #print(qd_array) # Calculate the mean and median depth_mean = np.array(dp_array) qd_mean = np.array(qd_array) print(&quot;mean&quot;, depth_mean) print(&quot;median&quot;, qd_mean) depth_median = np.array(dp_array) qd_median = np.array(qd_array) print(&quot;mean&quot;, depth_median) print(&quot;median&quot;, qd_median) # plot plt.hist(depth_mean, bins = 20, facecolor='blue', alpha=0.5) plt.hist(qd_mean, bins = 20, facecolor='blue', alpha=0.5) plt.savefig(&quot;dp.qd.pdf&quot;) </code></pre> <p>Example of data:</p> <pre><code>scaffold53 1174 . C G 196.03 PASS AC=1;AF=0.100;AN=10;BaseQRankSum=-6.360e-01;ClippingRankSum=0.00;DP=2865;ExcessHet=23.2938;FS=3.961;InbreedingCoeff=-0.3494;MQ=74.21;MQRankSum=11.081;NEGATIVE_TRAIN_SITE;QD=6.53;ReadPosRankSum=0.775;SOR=0.053;VQSLOD=5.67;culprit=QD;set=variant20 GT:AD:DP:GQ:PL 0/0:761,0:761:0:0,0,15737 0/0:779,0:779:0:0,0,13278 0/0:756,0:756:0:0,0,14720 0/0:539,0:539:0:0,0,10431 0/1:17,13:30:99:217,0,357 scaffold53 1799 . A G 11721.2 PASS AC=1;AF=0.100;AN=10;BaseQRankSum=-2.752e+00;ClippingRankSum=0.00;DP=139;ExcessHet=3.7680;FS=2.569;InbreedingCoeff=-0.0576;MQ=76.95;MQRankSum=2.152;POSITIVE_TRAIN_SITE;QD=22.80;ReadPosRankSum=0.807;SOR=0.486;VQSLOD=5.76;culprit=FS;set=variant20 GT:AD:DP:GQ:PGT:PID:PL 0/0:34,0:34:99:.:.:0,99,1010 0/0:35,0:35:99:.:.:0,102,1005 0/0:31,0:31:90:.:.:0,90,1350 0/1:9,10:19:99:0|1:1793_CT_C:380,0,442 0/0:20,0:20:57:.:.:0,57,855 scaffold53 1926 . T C 15709.2 PASS AC=3;AF=0.300;AN=10;BaseQRankSum=-2.196e+00;ClippingRankSum=0.00;DP=126;ExcessHet=0.6002;FS=0.000;InbreedingCoeff=0.2059;MQ=65.52;MQRankSum=0.678;POSITIVE_TRAIN_SITE;QD=22.25;ReadPosRankSum=-0.468;SOR=0.668;VQSLOD=6.23;culprit=DP;set=variant20 GT:AD:DP:GQ:PL 0/0:30,0:30:61:0,61,872 0/1:8,18:26:99:429,0,176 0/0:30,0:30:81:0,81,1215 0/1:14,7:21:99:148,0,386 0/1:13,6:19:99:114,0,341 scaffold53 1956 . G A 11382.4 PASS AC=1;AF=0.100;AN=10;BaseQRankSum=2.67;ClippingRankSum=0.00;DP=132;ExcessHet=5.6547;FS=0.000;InbreedingCoeff=-0.1352;MQ=68.43;MQRankSum=0.000;POSITIVE_TRAIN_SITE;QD=16.81;ReadPosRankSum=-0.352;SOR=0.733;VQSLOD=8.93;culprit=MQRankSum;set=variant20 GT:AD:DP:GQ:PL 0/0:32,0:32:63:0,63,904 0/0:29,0:29:81:0,81,1215 0/0:27,0:27:78:0,78,1170 0/1:13,10:23:99:266,0,332 0/0:21,0:21:60:0,60,900 scaffold53 6213 . G A 13615 PASS AC=2;AF=0.200;AN=10;BaseQRankSum=3.09;ClippingRankSum=0.00;DP=155;ExcessHet=6.8518;FS=1.104;InbreedingCoeff=-0.1832;MQ=69.25;MQRankSum=-0.713;POSITIVE_TRAIN_SITE;QD=18.11;ReadPosRankSum=-0.138;SOR=0.606;VQSLOD=4.32;culprit=FS;set=variant20 GT:AD:DP:GQ:PL 0/0:25,0:25:23:0,23,524 0/0:36,0:36:99:0,99,957 0/0:38,0:38:0:0,0,758 0/1:11,14:25:99:368,0,215 0/1:13,18:31:99:446,0,224 scaffold53 6794 . G A 6939.88 PASS AC=2;AF=0.200;AN=10;BaseQRankSum=2.48;ClippingRankSum=0.00;DP=117;ExcessHet=9.2123;FS=5.276;InbreedingCoeff=-0.2454;MQ=76.23;MQRankSum=0.754;QD=13.74;ReadPosRankSum=0.423;SOR=0.412;VQSLOD=0.800;culprit=QD;set=variant20 GT:AD:DP:GQ:PL 0/0:25,0:25:72:0,72,747 0/0:19,0:19:54:0,54,810 0/0:27,0:27:75:0,75,837 0/1:9,11:20:99:236,0,190 0/1:14,12:26:99:283,0,282 scaffold53 7613 . G C 4715.43 PASS AC=3;AF=0.300;AN=10;BaseQRankSum=0.367;ClippingRankSum=0.00;DP=131;ExcessHet=1.7167;FS=0.000;InbreedingCoeff=0.0683;MQ=92.82;MQRankSum=0.000;QD=13.63;ReadPosRankSum=-1.640;SOR=0.626;VQSLOD=1.57;culprit=QD;set=variant20 GT:AD:DP:GQ:PL 0/1:11,11:22:99:260,0,265 0/1:15,18:33:99:433,0,366 0/1:16,12:28:99:280,0,391 0/0:23,0:23:63:0,63,945 0/0:25,0:25:72:0,72,746 scaffold53 7643 . T G 18643.4 PASS AC=7;AF=0.700;AN=10;BaseQRankSum=-2.330e+00;ClippingRankSum=0.00;DP=158;ExcessHet=1.7167;FS=1.314;InbreedingCoeff=0.0683;MQ=62.44;MQRankSum=0.000;POSITIVE_TRAIN_SITE;QD=22.41;ReadPosRankSum=0.577;SOR=0.679;VQSLOD=10.21;culprit=MQRankSum;set=variant20 GT:AD:DP:GQ:PL 0/1:10,16:26:99:384,0,238 0/1:21,23:44:99:568,0,509 0/1:12,19:31:99:471,0,292 1/1:0,27:27:81:808,81,0 1/1:0,30:30:89:836,89,0 scaffold53 8477 . T G 4933.45 PASS AC=3;AF=0.300;AN=10;BaseQRankSum=-2.717e+00;ClippingRankSum=0.00;DP=122;ExcessHet=1.7167;FS=4.887;InbreedingCoeff=0.0681;MQ=93.80;MQRankSum=0.000;QD=15.13;ReadPosRankSum=1.452;SOR=0.833;VQSLOD=2.21;culprit=SOR;set=variant20 GT:AD:DP:GQ:PL 0/1:10,11:21:99:272,0,261 0/1:15,17:32:99:437,0,397 0/1:12,12:24:99:276,0,309 0/0:25,0:25:72:0,72,1080 0/0:20,0:20:57:0,57,855 scaffold53 8654 . A G 15051 PASS AC=6;AF=0.600;AN=10;BaseQRankSum=-2.419e+00;ClippingRankSum=0.00;DP=125;ExcessHet=1.4147;FS=0.000;InbreedingCoeff=0.0971;MQ=63.92;MQRankSum=0.000;POSITIVE_TRAIN_SITE;QD=21.23;ReadPosRankSum=0.780;SOR=0.672;VQSLOD=9.32;culprit=DP;set=variant20 GT:AD:DP:GQ:PL 0/1:14,12:26:99:252,0,321 0/1:14,10:24:99:200,0,339 0/1:6,18:24:99:407,0,108 1/1:0,26:26:78:733,78,0 0/1:8,17:25:99:417,0,164 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T13:09:14.490", "Id": "483101", "Score": "0", "body": "Did you look into pandas? https://stackoverflow.com/questions/26063231/read-specific-columns-with-pandas-or-other-python-module this way you don't read columns you don't need" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T20:35:20.357", "Id": "483141", "Score": "4", "body": "It would help if you told us what the lines in the file looked like. The code suggests it is a tab-delimited file. 5-10 sample lines would help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T15:44:39.573", "Id": "483230", "Score": "0", "body": "@RootTwo I added 10 lines of the sample file." } ]
[ { "body": "<p>Presuming that DP always comes before QD on a line, you could do something like this:</p>\n<p>Match fields preceded by 'DP' or 'QD'.</p>\n<pre><code>pattern = re.compile(r&quot;(?:DP|QD)=([^;]+)&quot;)\n</code></pre>\n<p>Use a list comprehension to build a list of [DP value, QD value] from the lines in the file.</p>\n<pre><code>with gzip.open(sys.argv[1], 'rt') as vcf:\n data = [pattern.findall(line) for line in vcf if not line.startswith(&quot;#&quot;)]\n</code></pre>\n<p>Convert to an numpy array.</p>\n<pre><code>data = np.array(data)\n</code></pre>\n<p>Use numpy functions to calculate on both columns at once.</p>\n<pre><code>dp_mean, qd_mean = np.mean(data, axis=1)\ndp_median, qd_median = np.median(data, axis=1)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T19:06:22.667", "Id": "245971", "ParentId": "245914", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T10:48:19.080", "Id": "245914", "Score": "3", "Tags": [ "python" ], "Title": "Faster solution to pattern search in a large file" }
245914
<p>I'm in the process of reviewing some old code released by an old colleague.</p> <p>We have a cronjob that executes once in an hour to download some thumbnails: the paths to the thumbnails are stored in a plain array.</p> <pre><code>// $totalThumbs is usually less than 2000 (each about 3kb) while ($i &lt; $totalThumbs) { $imgName = basename($thumbs_array[$i]); $fgc = file_get_contents($thumbs_array[$i]); $currentFile = __DIR__ . &quot;/&quot; . $imgName; // if file_get_contents doesn't return false if ($fgc !== false) { // if the file is not in that directory, write the file if (!file_exists($currentFile)) { file_put_contents($currentFile, $fgc); clearstatcache(true, $currentFile); } } $i++; sleep(1); } </code></pre> <p>This code works but, for example, we can't use CURL <code>multi_exec</code> because of the <strong>limited resources of our server</strong>.</p> <p>Is there a way to improve it (more efficient and/or more secure), considering our hardware limits? We don't need speed, but eventually less memory consumption because the same server is at the same time busy with many other 'jobs'.</p> <p>Thanks</p> <p><em>EDIT (for Mast): one important thing to say is the current idea is to remove this part and use a cronjob to directly store an array in a file, so that the file we are talking about has only to read that array</em></p> <pre><code>$dir = &quot;https://mylocaldir&quot;; $thumbs_array = []; // this one returns JSONP $raw_json = 'https://endpoint'; $json = file_get_contents($raw_json); // JSONP removal $json = str_replace(&quot;jsonOutreachFeed(&quot;, &quot;&quot;, $json); $json = substr($json, 0, -1); $decoded_json = json_decode($json); $itm = $decoded_json-&gt;items; $totalThumbs = count($itm); for ($i = 0; $i &lt; $totalThumbs; $i++) { $thumbs_array[] = $itm[$i]-&gt;media-&gt;m; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T12:45:57.857", "Id": "483096", "Score": "1", "body": "Can you share the rest of the function as well?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T12:52:46.437", "Id": "483098", "Score": "0", "body": "@Mast: of course" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T12:54:20.337", "Id": "483099", "Score": "0", "body": "When in doubt, [our FAQ on asking questions](https://codereview.meta.stackexchange.com/q/2436/52915) is a great start to make sure a question can be answered efficiently." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T12:57:22.463", "Id": "483100", "Score": "0", "body": "@Mast: ok, thanks" } ]
[ { "body": "<p>Since the code is only reading the contents of the file to see if there are contents in the file, an optimization for both speed and memory usage would be to use the <a href=\"https://www.php.net/manual/en/function.filesize.php\" rel=\"nofollow noreferrer\"><code>filesize()</code> function</a> and not read the contents. Reading the contents of the file consumes both time and memory.</p>\n<p>Rather than writing the contents read in, copy or move the original file to the new location using either <code>rename()</code> or <a href=\"https://www.php.net/manual/en/function.move-uploaded-file.php\" rel=\"nofollow noreferrer\"><code>move_uploaded_file()</code></a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T13:15:21.267", "Id": "483104", "Score": "0", "body": "So, correct me if I'm wrong: you are suggesting not to use file_get_contents and use filesize() instead. And you are suggesting to remove file_put_contents and use copy instead. Am I understanding well?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T13:24:27.723", "Id": "483107", "Score": "0", "body": "That is what I am suggesting, yes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T13:25:10.457", "Id": "483108", "Score": "0", "body": "I must try, it looks like a very promising approach, thanks! :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T08:03:59.947", "Id": "483176", "Score": "1", "body": "Your idea was great but it didn't work for techical reasons: we couldn't read the filesize of the remote file. I tried to replace it with get_headers (HEAD context), but I wasn't lucky. Don't worry, maybe they'll listen to me the next time I say we need better hardware. :-)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T12:59:13.803", "Id": "245918", "ParentId": "245915", "Score": "5" } } ]
{ "AcceptedAnswerId": "245918", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T11:31:18.280", "Id": "245915", "Score": "5", "Tags": [ "performance", "php", "memory-optimization" ], "Title": "Improving efficiency of download code" }
245915
<p>I have the following code, which displays the content for my custom page template <em>&quot;landingpage.php&quot;</em> and for single posts. The site is based on Bootstrap 4.</p> <pre><code>&lt;?php if(is_page_template( 'landingpage.php' )): ?&gt; &lt;div id=&quot;content&quot; class=&quot;site-content&quot;&gt; &lt;div class=&quot;container-fluid&quot;&gt; &lt;div class=&quot;row&quot;&gt; &lt;?php elseif (is_single()): ?&gt; &lt;div id=&quot;content&quot; class=&quot;site-content pt-4&quot;&gt; &lt;div class=&quot;container-fluid&quot;&gt; &lt;div class=&quot;row&quot;&gt; &lt;?php else: ?&gt; &lt;div id=&quot;content&quot; class=&quot;site-content&quot;&gt; &lt;div class=&quot;container&quot;&gt; &lt;div class=&quot;row&quot;&gt; &lt;?php endif; ?&gt; </code></pre> <p>Is there a more elegant and/or shorter way to achieve this?</p>
[]
[ { "body": "<p>The third <code>&lt;div&gt;</code> appears to be the same in all three cases, so that can be abstracted out of the cases.</p>\n<p>The outermost <code>&lt;div&gt;</code> appears to have class <code>pt-4</code> applied only if <code>is_page_template( 'landingpage.php' )</code> returns a value that evaluates to <code>FALSE</code> <em>and</em> <code>is_single()</code> returns a value that evaluates to <code>TRUE</code>.</p>\n<p>And the first nested (i.e. second) <code>&lt;div&gt;</code> has class <code>container-fluid</code> if either of those functions return a value that evaluates to <code>TRUE</code>.</p>\n<p>This logic could be rewritten as below. I know it strays away from the familiar wordpress style of using the <a href=\"https://www.php.net/manual/en/control-structures.alternative-syntax.php\" rel=\"nofollow noreferrer\">Alternative syntax for control structures</a> and uses the <em>shortcut syntax</em> (i.e. <code>&lt;?=</code>) of <code>echo</code> but it does add some separation of the logic from the markup</p>\n<pre><code>&lt;?php\n// default class names\n$contentClass = 'site-content';\n$containerClass = 'container-fluid';\nif (!is_page_template( 'landingpage.php' )) {\n if (is_single()) {\n $contentClass .= ' pt-4';\n }\n else {\n $containerClass = 'container';\n }\n}\n?&gt;\n &lt;div id=&quot;content&quot; class=&quot;&lt;?= $contentClass; ?&gt;&quot;&gt;\n &lt;div class=&quot;&lt;?= $containerClass; ?&gt;&quot;&gt;\n &lt;div class=&quot;row&quot;&gt;\n</code></pre>\n<p>It could be simplified using <a href=\"https://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary\" rel=\"nofollow noreferrer\">ternary operators</a> but some may argue that would detract from readability.</p>\n<ul>\n<li><p><em>Is this shorter</em>?</p>\n<p>yes, only by two lines</p>\n</li>\n<li><p><em>is this more elegant</em>?</p>\n<p>Well, that is subjective. The code above should be simpler to read. Consider the scenario where the code is updated by multiple people, including programmers and designers. The programmers can have designers update the markup without affecting the business logic. For more on this topic, refer to <a href=\"https://thisinterestsme.com/mixing-php-html/\" rel=\"nofollow noreferrer\">Mixing PHP and HTML</a>.</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T08:11:36.340", "Id": "483293", "Score": "0", "body": "In php, `if`, `elseif`, and `else` are [language constructs](https://www.php.net/manual/en/reserved.keywords.php). I assume languages like javascript do not have `elseif` which would explain why they require a space to form `else if`. When writing php, please suggest the use of the single language construct `elseif`, versus using two language constructs `else` (an else branch with no curly bracing) followed immediately by a new `if` branch." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T12:14:27.580", "Id": "483314", "Score": "0", "body": "Updated- you are correct about [JS not having `elseif`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else#Examples) - and there are interesting comments on [this SO answer](https://stackoverflow.com/a/4005623/1575353)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T22:29:22.187", "Id": "483351", "Score": "0", "body": "Maybe I should have added these links as well to help explain to researchers... https://www.php.net/manual/en/control-structures.elseif.php and \n https://www.amitmerchant.com/difference-between-elseif-and-else-if-php/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-03T15:24:14.720", "Id": "484274", "Score": "0", "body": "Sorry for the late response. Thank you so much for the improvement, that's exactly what i was looking for." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-03T15:26:17.347", "Id": "484275", "Score": "0", "body": "No worries- thank you for taking the time to accept the answer. Please consider voting on it as well. [\"_The first thing you should do after reading someone's answer to your question is vote on the answer, like any user with sufficient reputation does. Vote up answers that are helpful, and vote down answers that give poor advice._\"](https://codereview.stackexchange.com/help/someone-answers)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T14:38:11.110", "Id": "245962", "ParentId": "245920", "Score": "0" } } ]
{ "AcceptedAnswerId": "245962", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T14:40:01.037", "Id": "245920", "Score": "5", "Tags": [ "php", "wordpress", "twitter-bootstrap" ], "Title": "Wordpress single post content class customization with if-else function" }
245920
<p>The below algorithm is supposed to take a list of input IPs/networks and a list of IPs/networks to exclude, and return a list of networks that don't include any of the IPs/networks to exclude...</p> <p>Please review it and provide me with some feedback!</p> <pre><code>import ipaddress from ipaddress import IPv4Network def recurse_exclude(supernet_list, exclude_list): # For some reason, this only works if we force the generators into lists for supernet in list(supernet_list): for exclude in exclude_list: try: excluded_list = recurse_exclude(list(supernet.address_exclude(exclude)), exclude_list) except ValueError: # Ignore when the IP/net to exclude was not in the supernet continue else: return list(excluded_list) return supernet_list supernet_list = [IPv4Network('1.1.0.0/24')] output = recurse_exclude(supernet_list, exclude_list=[IPv4Network('1.1.0.0/25'),IPv4Network('1.1.0.128/26')]) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T16:27:59.023", "Id": "483119", "Score": "0", "body": "Please clarify your intentions. If you're looking for an explanation of the code provided, we don't do that. Does the code work to your satisfaction?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T16:29:45.203", "Id": "483120", "Score": "0", "body": "I wrote this code, I was hoping for some feedback on my logic. I shall change the title" } ]
[ { "body": "<h1>Review</h1>\n<ol>\n<li><p>Python and recursion are not the best match, instead use loops</p>\n<p>It could even be done with list comprehension</p>\n<p><code>return [ip if ip not in exclude for ip in subnet]</code></p>\n</li>\n<li><p>Alter your imports to use one of the two not both</p>\n<p>I suggest to use <code>from ipaddress import IPv4Network</code> because that seems to be only thing imported from the library.</p>\n</li>\n<li><p>Use sets!</p>\n<p>Lists are O(N), while sets are O(1)!</p>\n<p>Secondly it's quite easy to subtract sets simply use <code>set(c) = set(a) - set(b)</code></p>\n</li>\n</ol>\n<h1>Example</h1>\n<pre><code>from ipaddress import IPv4Network\n\nexclude = set(IPv4Network('1.1.0.0/25')) | set(IPv4Network('1.1.0.128/26'))\nnet = set(IPv4Network('1.1.0.0/24'))\n\nprint(net - exclude)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T14:49:46.580", "Id": "483225", "Score": "2", "body": "Lists can be O(1) per element as well, if you know they are sorted (which `list(IPv4Network(...))` is), and use that fact to only do a single pass over each list." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T14:17:29.837", "Id": "245960", "ParentId": "245922", "Score": "4" } } ]
{ "AcceptedAnswerId": "245960", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T15:31:51.930", "Id": "245922", "Score": "3", "Tags": [ "python", "generator" ], "Title": "IP address exclusion algorithm" }
245922
<p>I'm attempting exercise A.2.1 from the book <a href="http://alloytools.org/book.html" rel="nofollow noreferrer">http://alloytools.org/book.html</a>. Having got this far, I find that when stepping through instances I only ever get 2 <em>connects</em> links, no matter how many <em>requests</em> links, when using the <em>MiniSat</em> solver. When using <em>MiniSat plus Unsat core</em>, I sometimes get more <em>connects</em>, but not many <em>requests</em>. Obviously, these all satisfy the model, but it feels wrong to me. Am I over-thinking this?</p> <pre><code>module exercises/telephone sig Phone { , requests : set Phone , connects: lone Phone } fact minimum_system { some requests some connects } fact dont_call_yourself { no p: Phone | p.connects = p no p: Phone | p in p.requests } fact connect_from_a_request { no (connects - requests) } fact only_receive_once { all p: Phone.connects | one ~connects[p] } fact receiver_or_caller_only { no (Phone.connects &amp; Phone.~connects) } pred show {} run show for exactly 12 Phone </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T16:32:43.613", "Id": "483121", "Score": "5", "body": "If you're not sure whether the code actually works the way it should, it's not yet ready for review. Please take a look at the [help/on-topic]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T05:51:37.600", "Id": "483164", "Score": "0", "body": "Please give it some leeway?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T08:20:16.193", "Id": "483178", "Score": "1", "body": "Dear @Mast, I'm not sure you understand how Alloy works. It generates a range of solutions and \"works\" is sometimes a matter of judgement. I tried posting stuff to SO and got bounced off there too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T08:21:26.817", "Id": "483179", "Score": "0", "body": "Does or doesn't the result comply to your expectations?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T08:28:57.183", "Id": "483180", "Score": "0", "body": "Really, if you want to judge this entry, please take a look at Alloy. It's closer to data science in that this is not that simple a question to answer. I'm beginning to wonder if this the right place for us." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T12:17:00.747", "Id": "483194", "Score": "1", "body": "If you can't answer that question, I'm beginning to wonder that too. You talk about 'us', are you part of a group that we can reach about this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T12:30:39.020", "Id": "483196", "Score": "0", "body": "Would you perhaps be more interested in our [Datascience site](https://datascience.stackexchange.com/help/on-topic)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T13:26:13.677", "Id": "483201", "Score": "0", "body": "@Mast Looking at the help section you pointed, I think this is valid use. As Steve said, the model is correct. It would be nice if you could allow this tag to grow. If it doesn't I am sure you got enough credit to delete it. So unless you can point out an exact rule we violate I suggest we continue like we started." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T13:40:37.573", "Id": "483205", "Score": "1", "body": "@PeterKriens https://codereview.meta.stackexchange.com/a/3650 We're more than happy for this tag to grow. Just like every other language and question just follow our rules. If you don't like them post on Meta." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T14:07:40.790", "Id": "483210", "Score": "0", "body": "@Peilonrayz That rule is not applicable here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T14:33:06.333", "Id": "483219", "Score": "2", "body": "If that is the case then the OP should be [edit]ed to be worded in such a way that doesn't make it sound like it's asking what's wrong with code that doesn't behave as intended - the users \"policing\" this site don't know the intricacies of every programming language that ever existed. But they are very effective at voting to \"close\" / *put on hold* (to prevent the inevitable mess caused by answers to off-topic questions that later get edited into shape) questions where the OP is asking reviewers to find what's wrong with their code that's not working: knowledge of the tech is irrelevant." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T14:34:55.450", "Id": "483220", "Score": "3", "body": "Note that a \"closed\" question on this network isn't the end of the post at all - it just means the post should be edited before it can accept answers on the site. The first edit made to a \"closed\" question brings it to the *reopen* review queue, where reviewers cast *reopen* votes. The goal is to make sure all posts on the site are on-topic, not to slam down new language tags." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T14:41:43.147", "Id": "483223", "Score": "3", "body": "Lastly, having a discussion about the intricacies of the tag on [meta] can't hurt; it would give other users visibility on what's special about this language and why we should avoid casting close votes on these posts. For example posting an Excel question in the [tag:vba] tag and mentioning that \"Excel freezes and stops responding\" would often attract downvotes and close votes by users unfamiliar with the tech - a post on meta and a tag wiki edit helped clarify that such behavior is normal because X, it's a perfectly reviewable performance/algorithm issue that doesn't mean the code is broken." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T15:53:59.483", "Id": "483462", "Score": "2", "body": "@MathieuGuindon perhaps you already saw this but for posterity: [the alloy tag is being discussed on meta](https://codereview.meta.stackexchange.com/q/10533/120114)." } ]
[ { "body": "<p>When you get lots of instances, it's not really practical to look through them all. What most Alloy users would do in this case is to add a constraint to the show predicate to see if you can get the instance you expect. So I modified it to</p>\n<pre><code>pred show {\n#connects &gt; 4\n#requests &gt; 4\n}\n</code></pre>\n<p>and now I see instances with more than 4 connects and requests.</p>\n<p>Another suggestion: don't use exactly unless you really need to. You usually want to look for all instances up to some bound, and if you set it to exactly, you might find that you get no instances because it's not possible to construct one with exactly that number. For example, if you don't allow conference calls and you require phones to matched one to one, and you then set the bound to &quot;exactly 3&quot; you would get no solutions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T21:32:19.620", "Id": "483145", "Score": "2", "body": "Please don't answer off-topic questions. You should be able to see that Mast posted a comment that the question is off-topic. It takes a little bit of time to get things close around here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T13:27:04.357", "Id": "483202", "Score": "0", "body": "@Peilonrayz Please point out the rule that is violated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T14:27:26.463", "Id": "483216", "Score": "1", "body": "@PeterKriens the OP is worded in such a way that people that aren't familiar with the tech read it as the description of a script that is not behaving the way it was intended. The first criteria for a question to be on-topic on this site, is that the code works as intended. We *review working code* to make it better in every way, but we don't do bug-hunting. I cannot judge whether the OP's code works correctly or not and it seems rather blurry so I'll err on the \"let it slide\" side of the fence, but people vote with what they see, and right now the OP reads like it's asking about broken code." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T20:54:12.507", "Id": "245934", "ParentId": "245923", "Score": "2" } } ]
{ "AcceptedAnswerId": "245934", "CommentCount": "14", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T16:12:53.630", "Id": "245923", "Score": "0", "Tags": [ "alloy" ], "Title": "This spec creates very few connects, is that plausible?" }
245923
<p>Am using Java 1.8 and JUnit 5 to test a program which I wrote which grabs external zip files from a public url and then converts them into MD5 based hashes.</p> <p>This post / question serves as not only a code review (but also contains a design &amp; implementation question) for the class that is under test and the test case, itself.</p> <hr /> <p>JUnit 5 dependencies declared in pom.xml:</p> <pre><code>&lt;properties&gt; &lt;junit-jupiter.version&gt;5.5.2&lt;/junit-jupiter.version&gt; &lt;/properties&gt; &lt;dependency&gt; &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt; &lt;artifactId&gt;junit-jupiter-api&lt;/artifactId&gt; &lt;version&gt;${junit-jupiter.version}&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt; &lt;artifactId&gt;junit-jupiter-params&lt;/artifactId&gt; &lt;version&gt;${junit-jupiter.version}&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt; &lt;artifactId&gt;junit-jupiter-engine&lt;/artifactId&gt; &lt;version&gt;${junit-jupiter.version}&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; </code></pre> <hr /> <p>FileHasher.java:</p> <pre><code>import java.io.InputStream; import java.net.URL; import java.security.DigestInputStream; import java.security.MessageDigest; public class FileHasher { public static String makeHashFromUrl(String fileUrl) { try { MessageDigest md = MessageDigest.getInstance(&quot;MD5&quot;); InputStream is = new URL(fileUrl).openStream(); try { is = new DigestInputStream(is, md); // Up to 8K per read byte[] ignoredBuffer = new byte[8 * 1024]; while (is.read(ignoredBuffer) &gt; 0) { } } finally { is.close(); } byte[] digest = md.digest(); StringBuilder sb = new StringBuilder(); for (int i = 0; i &lt; digest.length; i++) { sb.append(Integer.toString((digest[i] &amp; 0xff) + 0x100, 16).substring(1)); } return sb.toString(); } catch (Exception ex) { throw new RuntimeException(ex); } } } </code></pre> <hr /> <p>FileHasterTest.java (JUnit 5 test case):</p> <pre><code>import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class FileHasterTest { private String bsrFileUrl = &quot;https://raw.githubusercontent.com/mlampros/DataSets/master/BSR_bsds500.zip&quot;; private String fastTextFileUrl = &quot;https://raw.githubusercontent.com/mlampros/DataSets/master/fastText_data.zip&quot;; @Test public void hashesAreTheSame() { String hashedBsrFile1 = FileHasher.makeHashFromUrl(bsrFileUrl); String hashedBsrFile2 = FileHasher.makeHashFromUrl(bsrFileUrl); assertThat(hashedBsrFile1).isEqualTo(hashedBsrFile2); } @Test public void hashesAreDifferent() { String hashedBsrFile = FileHasher.makeHashFromUrl(bsrFileUrl); String hashedFastTextFile = FileHasher.makeHashFromUrl(fastTextFileUrl); assertThat(hashedBsrFile).isNotEqualTo(hashedFastTextFile); } @Test public void hashIsNotNull() { String hashedBsrFile = FileHasher.makeHashFromUrl(bsrFileUrl); assertThat(hashedBsrFile).isNotNull(); } @Test public void hashedFileThrowsRuntimeExceptionWhenUrlIsNullOrEmpty() { Assertions.assertThrows(RuntimeException.class, () -&gt; { String hashedNull = FileHasher.makeHashFromUrl(null); }); Assertions.assertThrows(RuntimeException.class, () -&gt; { String hashedEmpty = FileHasher.makeHashFromUrl(&quot;&quot;); }); } } </code></pre> <hr /> <p>Question(s):</p> <p><strong>Unit test specific</strong>:</p> <ol> <li><p>Is this good test coverage (am I missing any edge cases)?</p> </li> <li><p>Is there a better way (e.g. am I missing something) to test my <code>FileHasher</code> class?</p> </li> <li><p>Is there a better way to test when external file URL is empty or null?</p> </li> </ol> <p><strong>Implementation / Design specific</strong>:</p> <ol start="4"> <li>Is throwing a RuntimeException seen as bad practice? If so, what's a better way to catch Exceptions in <code>FileHasher</code>?</li> </ol>
[]
[ { "body": "<p>Nice implementation, easy to understand and well tested.\nFew suggestions:</p>\n<h2>Close resources with try-with-resources</h2>\n<p>Java provides the try-with-resources statement to close resources automatically. Instead of:</p>\n<pre class=\"lang-java prettyprint-override\"><code>try {\n is = new DigestInputStream(is, md);\n //...\n} finally {\n is.close();\n}\n</code></pre>\n<p>You can use:</p>\n<pre class=\"lang-java prettyprint-override\"><code>try (DigestInputStream is = new DigestInputStream(is, md)) {\n //...\n}\n</code></pre>\n<h2>Exception handling</h2>\n<p>Wrapping an <code>IOException</code> into a <code>RuntimeException</code> is not good practice, but when a method throws too many different exceptions is not nice either. A trade off could be to create your own exception that wraps all other exceptions and provide the users enough information when an error occurs.</p>\n<p>Regarding the input validation I suggest to launch an <code>IllegalArgumentException</code>:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public static String makeHashFromUrl(String fileUrl) {\n if(fileUrl == null) {\n throw new IllegalArgumentException(&quot;Input cannot be null&quot;);\n }\n //...\n}\n</code></pre>\n<h2>Unit test isolation</h2>\n<p>Two properties of the unit test:</p>\n<ul>\n<li>Anyone should be able to run it</li>\n<li>It should run quickly</li>\n</ul>\n<p>If there is no internet connection your tests fail, which is in contrast with the first property. And if the internet connection is too slow the tests take to long to run, which invalidates the second property.</p>\n<p>There are more than one approach to tests methods that download files:</p>\n<ul>\n<li>Spin up an HTTP server which serves your resources</li>\n<li>Change the method to accept a <code>URL</code> instead of a <code>String</code> and use a local file</li>\n<li>...</li>\n</ul>\n<p>I suggest the second approach because it's simpler but if you can't change the signature of your method you need to take other approaches.\nThe method signature changes from:</p>\n<pre><code>public static String makeHashFromUrl(String fileUrl)\n</code></pre>\n<p>To:</p>\n<pre><code>public static String makeHashFromUrl(URL url)\n</code></pre>\n<p>And then test it with a local file:</p>\n<pre><code>@Test\npublic void myTest() {\n URL localUrl = ClassLoader.getSystemResource(&quot;my local zip file.zip&quot;);\n\n String hash = FileHasher.makeHashFromUrl(localUrl);\n\n // asserts\n}\n</code></pre>\n<h2>Minor changes</h2>\n<ul>\n<li>Typo in class name <code>FileHasterTest</code></li>\n</ul>\n<h2>Code refactored</h2>\n<pre class=\"lang-java prettyprint-override\"><code>public class FileHasher {\n public static String makeHashFromUrl(URL url) {\n if(url == null) {\n throw new IllegalArgumentException(&quot;Input url cannot be null&quot;);\n }\n \n MessageDigest md = createMessageDigest();\n\n try (DigestInputStream dis = new DigestInputStream(url.openStream(), md)) {\n // Up to 8K per read\n byte[] ignoredBuffer = new byte[8 * 1024];\n\n while (dis.read(ignoredBuffer) &gt; 0) {\n }\n } catch (IOException e) {\n new RuntimeException(e);\n }\n \n return digestToString(md.digest());\n }\n \n private static MessageDigest createMessageDigest() {\n MessageDigest md = null;\n try {\n md = MessageDigest.getInstance(&quot;MD5&quot;);\n } catch (NoSuchAlgorithmException e) {\n new RuntimeException(&quot;No Providers for algorithm MD5&quot;,e);\n }\n return md;\n }\n \n private static String digestToString(byte[] digest) {\n StringBuilder sb = new StringBuilder();\n\n for (int i = 0; i &lt; digest.length; i++) {\n sb.append(Integer.toString((digest[i] &amp; 0xff) + 0x100, 16).substring(1));\n }\n return sb.toString();\n }\n}\n</code></pre>\n<p>And the <code>FileHasherTest</code>:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public class FileHasherTest {\n private static final String testResourcesFilePath = &quot;src/test/resources&quot;;\n private static final String bsrFileName = &quot;BSR_bsds500.zip&quot;;\n private static final String fastTextFileName = &quot;fastText_data.zip&quot;;\n\n @Test\n public void hashesAreTheSame() {\n URL bsrURL = ClassLoader.getSystemResource(bsrFileName);\n\n String hashedBsrFile1 = FileHasher.makeHashFromUrl(bsrURL);\n String hashedBsrFile2 = FileHasher.makeHashFromUrl(bsrURL);\n\n assertThat(hashedBsrFile1).isEqualTo(hashedBsrFile2);\n }\n\n @Test\n public void hashesAreDifferent() {\n URL bsrURL = ClassLoader.getSystemResource(bsrFileName);\n URL fastTextUrl = ClassLoader.getSystemResource(fastTextFileName);\n\n String hashedBsrFile = FileHasher.makeHashFromUrl(bsrURL);\n String hashedFastTextFile = FileHasher.makeHashFromUrl(fastTextUrl);\n\n assertThat(hashedBsrFile).isNotEqualTo(hashedFastTextFile);\n }\n\n @Test\n public void hashIsNotNull() {\n URL bsrURL = ClassLoader.getSystemResource(bsrFileName);\n\n String hashedBsrFile = FileHasher.makeHashFromUrl(bsrURL);\n\n assertThat(hashedBsrFile).isNotNull();\n }\n\n @Test\n public void hashedFileThrowsIllegalArgumentExceptionWhenUrlIsNull() {\n IllegalArgumentException thrown = Assertions.assertThrows(IllegalArgumentException.class, () -&gt; {\n FileHasher.makeHashFromUrl(null);\n });\n\n assertThat(thrown.getMessage()).isEqualTo(&quot;Input url cannot be null&quot;);\n }\n}\n\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T06:41:38.077", "Id": "245947", "ParentId": "245928", "Score": "3" } } ]
{ "AcceptedAnswerId": "245947", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T18:39:56.150", "Id": "245928", "Score": "4", "Tags": [ "java", "junit" ], "Title": "Proper way to unit test MD5 Hashing of Zip Files from URL using JUnit 5?" }
245928
<p>I'm writing a web server from scratch on pure Java in learning purpose. As a part of request handling, I worked on a class to parse HTTP request, I expect from it to be able to do next things:</p> <ul> <li>extract http method, headers and body from request</li> <li>return BAD REQUEST in case of malformed request</li> <li>response with error on client timeout if client is not sending data and connection is hanging too long</li> </ul> <p>The result is:</p> <pre class="lang-java prettyprint-override"><code>class HttpRequestParser { private BufferedReader in; private int serverPort; private HttpMethods method; private InetAddress clientAddr; private InetAddress serverAddr; private URL url; private HashMap&lt;String, String&gt; collectedHeaders; private long parsingStartTime; HttpRequestParser(Socket clientSock) throws IOException { this.in = new BufferedReader(new InputStreamReader(clientSock.getInputStream())); this.clientAddr = clientSock.getLocalAddress(); this.serverAddr = clientSock.getInetAddress(); this.serverPort = clientSock.getLocalPort(); this.collectedHeaders = new HashMap&lt;&gt;(); } HttpOneZeroRequest parseAll() throws IOException { return this.parseAll(this.in); } private HttpOneZeroRequest parseAll(BufferedReader inputStream) throws IOException { this.parsingStartTime = System.currentTimeMillis(); this.waitUntilClientInputReady(); String line = inputStream.readLine(); this.parseTopHeader(line); this.waitUntilClientInputReady(); while (!(line = inputStream.readLine().trim()).equals(&quot;&quot;)) { this.parseCommonHeader(line); this.waitUntilClientInputReady(); } byte[] body = {}; if (this.method == HttpMethods.POST || this.method == HttpMethods.PUT || this.method == HttpMethods.PATCH) { body = this.readBody(); } return this.prepareRequest(body); } private void parseTopHeader(String line) throws HttpException { String[] parts = line.split(&quot;\\s+&quot;, 3); if (parts.length != 3 || !parts[1].startsWith(&quot;/&quot;) || !parts[2].toUpperCase().startsWith(&quot;HTTP/&quot;)) { throw new BadRequest(); } try { this.url = new URL(&quot;http://&quot; + this.getServerNetloc() + parts[1]); } catch (MalformedURLException e) { throw new BadRequest(); } this.method = HttpMethods.cleanMethod(parts[0]); } private void parseCommonHeader(String line) throws HttpException { String[] pair = line.split(&quot;:&quot;, 2); if (pair.length != 2) { throw new BadRequest(); } String name = pair[0].replaceAll(&quot; &quot;, &quot;&quot;); String value = pair[1].trim(); this.collectedHeaders.put(name, value); } private byte[] readBody() throws HttpException, IOException { ByteArrayOutputStream bodyStream = new ByteArrayOutputStream(); int contentLength = 0; // for now content without Content-Length header are ignored if (this.collectedHeaders.containsKey(&quot;Content-Length&quot;)) { String valueStr = this.collectedHeaders.get(&quot;Content-Length&quot;); try { contentLength = Integer.valueOf(valueStr); } catch (NumberFormatException e) { throw new BadRequest(); } } int nextByte; while (bodyStream.size() &lt; contentLength) { this.waitUntilClientInputReady(); nextByte = this.in.read(); bodyStream.write(nextByte); } return bodyStream.toByteArray(); } private String getServerNetloc() { String hostname = this.serverAddr.getHostName(); return hostname + ((this.serverPort != 80) ? (&quot;:&quot; + this.serverPort) : &quot;&quot;); } private HttpOneZeroRequest prepareRequest(byte[] body) { return new HttpOneZeroRequest( this.method, this.url, this.collectedHeaders, body, this.clientAddr, this.serverAddr, this.serverPort); } private void waitUntilClientInputReady() throws IOException { long timeout = (long)(120 * 1000); while (!this.in.ready()) { if (System.currentTimeMillis() - this.parsingStartTime &gt; timeout) { throw new RequestTimeout(); } } } } </code></pre> <p>Can you, please, kindly review my implementation, and give some advises about code formatting and optimization? I have poor (close to zero) experience at Java programming and I'm not sure if I choose proper approach to implement certain parts, especially handling client timeout and extract urls...</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T20:13:38.193", "Id": "483138", "Score": "4", "body": "Welcome to Code Review! \"I expect from it to be able to do next things\" And, did you test it? Did it do the things?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T18:49:15.420", "Id": "483246", "Score": "1", "body": "Yes, as a part of whole web server implementation (didn't shown here) this class works as desired. I tested it manually with telnet, sent various http headers and got response, also tried not finish response and it responses on timeout. (Wish I to write unit tests, but unfortunately I don't know how to do it with java). But I have doubt in chosen approach, it's hard for me to say if this code bad or not (especially from java programming perspective) and what could be done better.." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T20:02:38.197", "Id": "245930", "Score": "4", "Tags": [ "java", "http", "server" ], "Title": "Parsing HTTP request for webserver implementation" }
245930
<p>I am importing an Excel sheet where the first column will contain product numbers. I match those numbers to my SQL database and display the product number and description of the matching products to a datagridview.</p> <p>The code works, but if there are a lot of products it can take a long time. What I'd really like to do is have it read the Excel sheet and add the description directly into the Excel sheet after the last column with data. Or at very least optimize the code to run quicker.</p> <pre><code> Dim v As New FormRec Dim x As New FormRec Dim MyConnection As OleDb.OleDbConnection Dim DtSet As DataSet Dim MyCommand As OleDb.OleDbDataAdapter MyConnection = New OleDb.OleDbConnection(String.Format(&quot;Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0&quot;, workbook)) MyCommand = New OleDb.OleDbDataAdapter(&quot;select * from [Sheet1$]&quot;, MyConnection) MyCommand.TableMappings.Add(&quot;Table&quot;, &quot;match&quot;) DtSet = New DataSet MyCommand.Fill(DtSet) v.dgv.DataSource = DtSet.Tables(0) MyConnection.Close() Dim col As New DataGridViewTextBoxColumn col.HeaderText = &quot;Product Number&quot; col.Name = &quot;prodnmbr&quot; col.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells col.DefaultCellStyle.Font = New Font(&quot;Arial&quot;, 14) x.dgv.Columns.Add(col) Dim co2 As New DataGridViewTextBoxColumn co2.HeaderText = &quot;Description&quot; co2.Name = &quot;descrip&quot; co2.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill co2.DefaultCellStyle.Font = New Font(&quot;Arial&quot;, 14) x.dgv.Columns.Add(co2) For index As Integer = 0 To v.dgv.RowCount - 1 Using conn As New SqlConnection(myconnection) Dim commandText As String = &quot;select productnmbr,descr from database where productnmbr = @prodnmbr&quot; Using command As SqlCommand = New SqlCommand(commandText, conn) conn.Open() With command.Parameters .AddWithValue(&quot;@prodnmbr&quot;, v.dgv.Rows(index).Cells(0).Value.ToString) End With Using sqlread As SqlDataReader = command.ExecuteReader If sqlread.Read Then Dim match As String = sqlread.GetString(0) If match = v.dgv.Rows(index).Cells(0).Value Then x.dgv.Rows.Add(v.dgv.Rows(index).Cells(0).Value.ToString, sqlread.GetString(1)) x.dgv.Rows(index).DefaultCellStyle.BackColor = Color.LightGreen End If Else x.dgv.Rows.Add(v.dgv.Rows(index).Cells(0).Value.ToString, &quot;N/A&quot;) x.dgv.Rows(index).DefaultCellStyle.BackColor = Color.Red End If End Using End Using End Using Next x.ShowDialog() </code></pre>
[]
[ { "body": "<p>You are repeatedly opening the DB connection in a loop:</p>\n<pre><code>For index As Integer = 0 To v.dgv.RowCount - 1\n Using conn As New SqlConnection(myconnection)\n Dim commandText As String = &quot;select productnmbr,descr from database where productnmbr = @prodnmbr&quot;\n Using command As SqlCommand = New SqlCommand(commandText, conn)\n conn.Open()\n With command.Parameters\n .AddWithValue(&quot;@prodnmbr&quot;, v.dgv.Rows(index).Cells(0).Value.ToString)\n End With\n ...\n End Using\n End Using\nNext\n</code></pre>\n<p>There is overhead involved when opening a connection. You could just open it once, leave it open, do your stuff, then dispose of it:</p>\n<pre><code>Using conn As New SqlConnection(myconnection)\n For index As Integer = 0 To v.dgv.RowCount - 1\n ' do something\n Next\nEnd Using\n</code></pre>\n<p>Just moving code a bit should improve performance.</p>\n<p>Something else: no need to read values from the DGV. This could even freeze your UI. Read the rows from the dataset instead, that is the one table it contains (match).</p>\n<p>I see that you are also adding rows to the DGV but the better way would be to feed the underlying source, that is your datatable, possibly a bindingsource. Then let the DGV refresh itself.</p>\n<p>I am not familiar with your SQL table but if the product table is not too large, I might be tempted to load it to a second datatable, then compare both datatable with LINQ for example (you will find code samples on Stack Overflow). The benefit is that all your data will be preloaded to memory and comparison should be quite fast if you're not doing it row by row. It depends on how much data there is.</p>\n<p>Or do it differently: load your Excel file to a temporary table in your SQL server. Then compare the tables by doing a join, a stored procedure if you like.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T20:45:45.753", "Id": "245933", "ParentId": "245931", "Score": "1" } } ]
{ "AcceptedAnswerId": "245933", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T20:14:48.883", "Id": "245931", "Score": "2", "Tags": [ "sql", "excel", "vb.net", "visual-studio" ], "Title": "VB.net SQL match against Excel data to datagridview" }
245931
<p>While quarantine I decided to look into the assembly language, as it's quite interesting to see how code works on the lower levels. To challenge myself I made a binary search algorithm. The OS is Windows. I just code casually (in Python and C++, so I know about the concept of pointers), therefore I don't have <em>that</em> much experience.</p> <p>I just wanted to put this on code review to know if this code style is acceptable or if I'm disregarding important conventions. So please critique and let me know.</p> <pre><code>bits 64 section .text global main extern printf extern ExitProcess main: mov r12, list ; load list into register mov r13, len &gt;&gt; 3 ; r13 holds the width of the search &quot;sector&quot; test r13, 1 ; test if the first search &quot;sector&quot; is even jz is_even ; if not, it's set to an even number inc r13 is_even: push r13 ; save width shl r13, 2 ; multiply index by 4 to get the width in bytes add r12, r13 ; move the pointer to the first search position pop r13 ; restore width search: shr r13, 1 ; halve search &quot;sector&quot; push r13 shl r13, 2 ; get width in bytes mov r14d, dword [r12] cmp r14d, dword [target] ;compare target to current search position je finish jl search_right jg search_left search_left: sub r12, r13 ; move search position pop r13 jmp search search_right: add r12, r13 ; move search position pop r13 jmp search finish: lea rcx, [fmt] ; set printf format mov rdx, r12 ; rdx is pointer to the target sub rdx, list ; we want the index of the target, so we SUB the pointer to the first element shr rdx, 2 ; ints are 4-byte, so we have to devide the difference by 4 sub rsp, 40 ; shadow space call printf add rsp, 40 mov rax, 0 call ExitProcess section .data fmt db &quot;%d&quot;, 10, 0 ; printf format string target dd 123 ; number we're looking for list dd 4, 123 ,2584, 4510, 8451, 6987, 12543 len equ $ - list </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T00:16:00.523", "Id": "483156", "Score": "0", "body": "Have you compared this to the disassembled output of a roughly-equivalent C compilation?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T12:14:56.843", "Id": "483371", "Score": "1", "body": "yeah, but it took me some time. basically, it's very similar to my manual asm code, but the if/else flow is at first unintuitive" } ]
[ { "body": "<h2>Code style</h2>\n<p>Your code style is certainly acceptable - everyone is entitled to their own coding habits.\nTo further improve readability, and readability is key, I would change the following:</p>\n<ul>\n<li>put all labels in the same separate column. You didn't do this for <em>is_even</em>, <em>fmt</em>, <em>target</em>, <em>list</em>, and <em>len</em>.</li>\n<li>don't just have 1 space character between the instruction/directive and its operand(s). Start all operands in their own column.</li>\n<li>beware of redundant comments like 'mov r12, list ; load list into register'</li>\n<li>don't add redundant tags like <code>dword</code> in <code>mov r14d, dword [r12]</code>. The register name <code>r14d</code> already states this is a dword.</li>\n<li>avoid using ambiguous terminology. I found it odd to read about <em>sectors</em> and <em>widths</em>. In case of binary searching, many people will prefer to talk about <em>array partitions</em> and <em>number of elements</em>.</li>\n</ul>\n<h2>The code has multiple issues</h2>\n<p>You seem to be confident that a match will always be found. No provision is made for a failure!</p>\n<p>The comment on <code>mov rdx, r12 ; rdx is pointer to the target</code> is wrong. What you've got is a pointer to the matching array element.</p>\n<p>The array <em>list</em> holds dword-sized elements. In <code>mov r13, len &gt;&gt; 3</code>, you only need to shift twice to get the <em>number of elements</em>.</p>\n<p>In the top part of the program you first add an imaginary element to the array, then you make <code>r12</code> point to behind it, and later your code also happily reads from these non-existing elements. Analyzing beyond this point becomes futile.</p>\n<p>I think having recognized an attempt to write a <em>uniform binary search</em>. Although I didn't use that particular approach, you might find it interesting to read <a href=\"https://codereview.stackexchange.com/questions/105165/variations-on-binary-searching-an-ordered-list\">a post of mine that shows 2 ways to binary search an array</a>. I know it was written for 16-bit, but that should not stop you from stealing from it...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-02T18:18:16.250", "Id": "247393", "ParentId": "245935", "Score": "2" } } ]
{ "AcceptedAnswerId": "247393", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T21:02:37.923", "Id": "245935", "Score": "7", "Tags": [ "beginner", "windows", "assembly", "binary-search" ], "Title": "x64 NASM Assembler: Binary Search" }
245935
<p>This is my scraper for AWS ECS (Elastic Container Service). My primary use for this is to <code>grep</code> through the resulting file to see which cluster a given service is in.</p> <p>I've been coding in python for a few years now, but I don't feel like my code is as pythonic as it should be. I've run this though <code>pylint</code> and it passes cleanly now. I'm open to any suggestions for how to make this cleaner, more reliable, or more pythonic.</p> <pre><code>#!/usr/bin/env python3 &quot;&quot;&quot;scrape ECS for inventory&quot;&quot;&quot; import pprint # pylint: disable=unused-import import sys import time import boto3 # pylint: disable=import-error import sre_logging def ecs_services(ecs): &quot;&quot;&quot;get all ECS services&quot;&quot;&quot; # get list of clusters from AWS ecs_clusters = [] paginator1 = ecs.get_paginator('list_clusters') for page in paginator1.paginate(): for cluster in page['clusterArns']: ecs_clusters.append(cluster) service_map = {} for cluster in ecs_clusters: # describe cluster cluster_details = ecs.describe_clusters(clusters=[cluster]) cluster_name = cluster_details['clusters'][0]['clusterName'] cluster_tags = cluster_details['clusters'][0]['tags'] logger.info(&quot;getting services for cluster %s, tags: %s...&quot;, cluster_name, cluster_tags) service_map[cluster_name] = {} # get services paginator2 = ecs.get_paginator('list_services') this_ecs_services = [] for page in paginator2.paginate(cluster=cluster): for service in page['serviceArns']: this_ecs_services.append(service) #pp.pprint(this_ecs_services) for service in this_ecs_services: service_details = ecs.describe_services(cluster=cluster, services=[service]) service_name = service_details['services'][0]['serviceName'] service_definition = service_details['services'][0]['taskDefinition'] service_map[cluster_name][service_name] = { &quot;serviceArn&quot;: service, &quot;clusterArn&quot;: cluster, &quot;taskDefinition&quot;: service_definition } return service_map def find_consul(env): &quot;&quot;&quot;pull consul variables out of environment&quot;&quot;&quot; #pp.pprint(env) host = '' port = '' prefix = '' for entry in env: if entry['name'] == 'CONSUL_HOST': host = entry['value'] if entry['name'] == 'CONSUL_PORT': port = entry['value'] if entry['name'] == 'CONSUL_SERVICE_PREFIX': prefix = entry['value'] if prefix: consul_url = &quot;%s:%s/%s&quot; % (host, port, prefix) else: consul_url = &quot;undefined&quot; return consul_url def scrape_ecs_stats(): &quot;&quot;&quot;do one pass of scraping ECS&quot;&quot;&quot; ecs = boto3.client('ecs') services = ecs_services(ecs) #pp.pprint(services) logger.info(&quot;getting task definitions...&quot;) # find consul config result_txt = [] for cluster in services: for service in services[cluster]: task_def_arn = services[cluster][service][&quot;taskDefinition&quot;] task_def = ecs.describe_task_definition(taskDefinition=task_def_arn) env = task_def['taskDefinition']['containerDefinitions'][0]['environment'] consul_url = find_consul(env) result_txt.append(&quot;%s\t%s\t%s\t%s\n&quot; % (cluster, service, task_def_arn, consul_url)) send_content = &quot;&quot;.join(result_txt) #pp.pprint(send_content) # upload to S3 bucket = &quot;redacted&quot; filepath = &quot;ecs/ecs_services.txt&quot; boto_s3 = boto3.client('s3') boto_s3.put_object(Bucket=bucket, Body=send_content, ContentType=&quot;text/plain&quot;, Key=filepath) logger.info(&quot;sent %s to s3&quot;, filepath) def main(): &quot;&quot;&quot;main control loop for scraping ECS stats&quot;&quot;&quot; while True: try: start = time.time() scrape_ecs_stats() end = time.time() duration = end - start naptime = 600 - duration if naptime &lt; 0: naptime = 0 logger.info(&quot;ran %d seconds, sleeping %3.2f minutes&quot;, duration, naptime/60) time.sleep(naptime) except KeyboardInterrupt: sys.exit(1) except: # pylint: disable=bare-except # so we can log unexpected and intermittant errors, from boto mostly logger.exception(&quot;top level catch&quot;) time.sleep(180) # 3 minutes if __name__ == &quot;__main__&quot;: logger = sre_logging.configure_logging() pp = pprint.PrettyPrinter(indent=4) main() </code></pre>
[]
[ { "body": "<h2>Scraping?</h2>\n<p>Scraping should be the last resort for getting data from a service that does not have an <a href=\"https://docs.aws.amazon.com/AmazonECS/latest/APIReference/Welcome.html\" rel=\"nofollow noreferrer\">API</a>. Thankfully, not only does ECS have a full API, you're using it via Boto - which means that you are not scraping. Scraping is hacking together unstructured content into structured data, which is not what you're doing.</p>\n<h2>Comprehensions</h2>\n<pre><code>ecs_clusters = []\npaginator1 = ecs.get_paginator('list_clusters')\nfor page in paginator1.paginate():\n for cluster in page['clusterArns']:\n ecs_clusters.append(cluster)\n</code></pre>\n<p>can be</p>\n<pre><code>ecs_clusters = [\n cluster\n for page in paginator1.paginate()\n for cluster in page['clusterArns']\n]\n</code></pre>\n<h2>Temporary variables</h2>\n<pre><code>cluster_details['clusters'][0]\n</code></pre>\n<p>should receive a variable since it's used multiple times.</p>\n<h2>Logging</h2>\n<p>I want to call out that you're using logging properly, and that's not nothing. Good job; keep it up.</p>\n<h2>Interpolation</h2>\n<pre><code>&quot;%s:%s/%s&quot; % (host, port, prefix)\n</code></pre>\n<p>can be</p>\n<pre><code>f&quot;{host}:{port}/{prefix}&quot;\n</code></pre>\n<h2>Successive string concatenation</h2>\n<p>As these things go, <code>&quot;&quot;.join(result_txt)</code> is not the worst way to do concatenation. It's generally guaranteed to be more performant than <code>+=</code>. That said, I consider the <code>StringIO</code> interface to be simpler to use than having to manage and then aggregate a sequence, and it has the added advantage that you can more readily swap this out with an actual file object (including, maybe, an HTTP stream) if that's useful.</p>\n<h2>Maxima</h2>\n<pre><code> naptime = 600 - duration\n if naptime &lt; 0:\n naptime = 0\n</code></pre>\n<p>can be</p>\n<pre><code>naptime = max(0, 600 - duration)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T00:11:56.787", "Id": "245940", "ParentId": "245936", "Score": "2" } } ]
{ "AcceptedAnswerId": "245940", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T21:38:28.817", "Id": "245936", "Score": "3", "Tags": [ "python", "python-3.x", "amazon-web-services" ], "Title": "scrape AWS ECS and store summary in S3" }
245936
<p>The goal here is to notate and produce essential PDF reports.</p> <p>The For loop takes an id number and puts it into specified calculator worksheet. The workbook is set to automatic calculation so all of the necessary values update. Then it copies the result then saves as PDF a set of worksheets labeled <code>Report</code></p> <p>The code works perfectly fine for a small number of iterations, but RAM usage increases by about 70 MB after every iteration and that is indeed eventually problematic - is there anything in this code that suggests there could be a memory leak?</p> <p>What else could be improved?</p> <p>Main Sub</p> <pre><code>Sub CalculateEmods() Application.ScreenUpdating = False Application.EnableEvents = False Dim emod As Range Dim member As Range Dim emodsws As Variant Dim i As Integer Dim RowCount As Integer Dim NeededEmods As Range Set emodsws = ThisWorkbook.Sheets(&quot;2020Emods&quot;) Set NeededEmods = emodsws.Range(&quot;A2&quot;, Range(&quot;A2&quot;).End(xlDown)) RowCount = NeededEmods.Rows.Count + 1 For i = 2 To RowCount Set emod = ThisWorkbook.Sheets(&quot;Yearly Breakdown&quot;).Range(&quot;G334&quot;) Set member = ThisWorkbook.Sheets(&quot;Yearly Breakdown&quot;).Range(&quot;B2&quot;) 'Changes member_ID on &quot;Yearly Breaksown&quot; sheet Application.EnableEvents = True member.Value2 = emodsws.Range(&quot;A&quot; &amp; i).Value2 Application.EnableEvents = False 'Copies emod and pastes it to Emod Worksheet emodsws.Cells(i, 4).Value2 = emod.Value2 Set emod = Nothing Set member = Nothing 'Prints Emod Report for member as PDF from function SaveReportAsPDFIn2020 emodsws.Select DoEvents Application.Wait Now + #12:00:07 AM# Next i Application.ScreenUpdating = True Application.EnableEvents = True MsgBox &quot;Emod Reports Created!&quot; End Sub </code></pre> <p>Change Events Macro</p> <pre><code>Private Sub Worksheet_Change(ByVal Target As Range) Application.ScreenUpdating = False Application.EnableEvents = False If Intersect(Target, Range(&quot;B2&quot;)) Then Dim primaryarray As Range Dim secondaryarray As Range Dim rw As Range Set primaryarray = ThisWorkbook.Sheets(&quot;Experience Rating Sheet&quot;).Range(&quot;B9:M322&quot;) Set secondaryarray = ThisWorkbook.Sheets(&quot;Mod Snapshot&quot;).Range(&quot;A29:E39&quot;) ' unhide all rows before we begin primaryarray.EntireRow.Hidden = False secondaryarray.EntireRow.Hidden = False 'function recalculates sheets that wil change number of rows to hide Call ChangeFooters 'hides rows based on criteria set in function For Each rw In primaryarray.Rows rw.EntireRow.Hidden = BlankOrZero(rw.Cells(3)) And BlankOrZero(rw.Cells(8)) Next rw For Each rw In secondaryarray.Rows rw.EntireRow.Hidden = BlankOrZero(rw.Cells(1)) Next Set primaryarray = Nothing Set secondaryarray = Nothing End If Application.EnableEvents = True Application.ScreenUpdating = True End Sub Function BlankOrZero(c As Range) BlankOrZero = Len(c.Value) = 0 Or c.Value = 0 End Function Function ChangeFooters() Dim ws As Worksheet Dim Report As Variant Dim Calculator As Variant Set Report = ThisWorkbook.Sheets(Array(&quot;Cover Sheet&quot;, &quot;Ag Loss Sensitivity&quot;, _ &quot;Experience Rating Sheet&quot;, &quot;Loss Ratio Analysis&quot;, _ &quot;Mod Analysis&amp;Strategy Proposal&quot;, &quot;Mod Snapshot&quot;, _ &quot;Mod &amp; Potential Savings&quot;)) For Each ws In Report ws.PageSetup.RightFooter = Sheet17.Range(&quot;B3&quot;).Text &amp; Chr(10) &amp; &quot;Mod Effective Date: &quot; &amp; Sheet17.Range(&quot;B4&quot;) Next ws Set Report = Nothing End Function </code></pre> <p>Save as PDF Sub</p> <pre><code>Sub SaveReportAsPDFIn2020() Application.ScreenUpdating = False Application.EnableEvents = False 'Ben Matson : 5-June-2020 'Test macro to save as pdf with ExportAsFixedFormat Dim filename As String Dim Folderstring As String Dim FilePathName As String Dim Report As Variant Dim ws As Sheets Dim sh As Worksheet Set ws = Sheets Set Report = ThisWorkbook.Sheets(Array(&quot;Cover Sheet&quot;, &quot;Ag Loss Sensitivity&quot;, _ &quot;Experience Rating Sheet&quot;, &quot;Loss Ratio Analysis&quot;, _ &quot;Mod Analysis&amp;Strategy Proposal&quot;, &quot;Mod Snapshot&quot;, _ &quot;Mod &amp; Potential Savings&quot;)) ws(&quot;Cover Sheet&quot;).PageSetup.PrintArea = Range(&quot;A1:G37&quot;).Address ws(&quot;Ag Loss Sensitivity&quot;).PageSetup.PrintArea = Range(&quot;A1:H55&quot;).Address ws(&quot;Experience Rating Sheet&quot;).PageSetup.PrintArea = Range(&quot;A4:L322,A324:M340&quot;).Address ws(&quot;Loss Ratio Analysis&quot;).PageSetup.PrintArea = Range(&quot;A1:M54&quot;).Address ws(&quot;Mod Analysis&amp;Strategy Proposal&quot;).PageSetup.PrintArea = Range(&quot;A1:M44&quot;).Address ws(&quot;Mod Snapshot&quot;).PageSetup.PrintArea = Range(&quot;A1:O69&quot;).Address ws(&quot;Mod &amp; Potential Savings&quot;).PageSetup.PrintArea = Range(&quot;A1:L80&quot;).Address 'Name of the pdf file filename = ThisWorkbook.Sheets(&quot;Cover Sheet&quot;).Range(&quot;B20&quot;) &amp; &quot;_Emod&quot; &amp; &quot;_&quot; &amp; ThisWorkbook.Sheets(&quot;Yearly Breakdown&quot;).Range(&quot;F2&quot;) &amp; &quot;.pdf&quot; 'Path Creation and Setting Folderstring = &quot;/Users/ben/Desktop/Emod_Calc/Emods_2&quot; FilePathName = Folderstring &amp; Application.PathSeparator &amp; filename 'Selecting what sheets to Print Report.Select 'Prints as PD ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, filename:= _ FilePathName, Quality:=xlQualityStandard, _ IncludeDocProperties:=True, IgnorePrintAreas:=False 'Clears Print Area For Each sh In Report sh.PageSetup.PrintArea = &quot;&quot; Next sh 'Clears the variables Set Report = Nothing filename = &quot;&quot; Folderstring = &quot;&quot; FilePathName = &quot;&quot; ThisWorkbook.Sheets(&quot;Yearly Breakdown&quot;).Select Application.ScreenUpdating = True Application.EnableEvents = True End Sub </code></pre> <p>The worksheet Change handler may seem like it’s unnecessary for the over-all code but that what updates things that are not formula/calculation related in the <code>Report</code> array of worksheets. I included it here just in case it may be involved in a memory leak.</p> <p>Is it the <code>Select</code>/<code>ActiveSheet</code> that is causing this and if so what recommendations would you give to optimize even more?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T15:28:18.777", "Id": "483328", "Score": "3", "body": "That said, my sympathies; memory leaks can be hard to debug, and it's hard to ask about them on Stack Overflow without making a post *too broad* (SO often doesn't like getting code dumps and not knowing what specific line is the problem)... Good luck!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T16:59:56.533", "Id": "483336", "Score": "3", "body": "I would suggest adding an explicit `DoEvents` just before application events get disabled. `BlankOrZero` will throw a *type mismatch* error if it's given a `Range` with multiple cells or if the cell value is a worksheet error like `#N/A` or `#VALUE`, needs `If IsError(c.Value)` before attempting string operations on it. I would extract the \"B2 was modified\" logic into its own scope, and conditionally invoke it from the change handler and unconditionally in the macro, so it runs without involving worksheet events at all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T17:09:55.243", "Id": "483338", "Score": "3", "body": "What could definitely fix the memory leak, would be to fully separate collecting the input from producing the output; move that logic to another workbook entirely, and tweak it so that it is given a `Workbook` object to work with; the top-level macro would be responsible for creating and quitting a `New Excel.Application` instance (which could even be hidden), such that each PDF is spawned from a fresh Excel instance that is explicitly destroyed / free memory explicitly gets reclaimed, at each iteration. Could run for much longer though, consider implementing a progress indicator =)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T14:42:18.740", "Id": "483452", "Score": "0", "body": "Since it is the Print as PDF sub, was there really nothing I could for that specific part to help?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T22:12:30.433", "Id": "483488", "Score": "0", "body": "@MathieuGuindon An important note that could affect the \"instance\" solution is that I am running Excel for Mac. I am not sure if i can open another instance as easily as it is on Windows" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-29T22:31:23.723", "Id": "483716", "Score": "0", "body": "@MathieuGuindon I figured out how to open another instance of excel on mac. Memory usage went down but excel ended up closing after 21 iterations forcefully." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T22:12:42.793", "Id": "245937", "Score": "1", "Tags": [ "vba", "excel" ], "Title": "Iteratively Exporting PDF Reports with Excel" }
245937
<p>Users input their pin-code which is checked against the database and returned with the locality, district and state associated with that pin-code. Multiple localities may be returned so the options are passed to a select element so the user can choose theirs.</p> <p>Old values are also passed as props to the Vue component and displayed in event of server side validation error.</p> <h2>Vue Component</h2> <pre><code>&lt;template&gt; &lt;div&gt; &lt;div class=&quot;form-row&quot;&gt; &lt;b-form-group class=&quot;col-6&quot; label=&quot;Pincode&quot; label-for=&quot;pincode&quot;&gt; &lt;b-form-input id=&quot;pincode&quot; name=&quot;pincode&quot; v-model=&quot;pincode&quot; placeholder=&quot;Pincode&quot; type=&quot;number&quot; min=&quot;100000&quot; max=&quot;999999&quot; :state=&quot;pincodeState&quot; &gt;&lt;/b-form-input&gt; &lt;b-form-invalid-feedback id=&quot;pincode-live-feedback&quot;&gt; Pincode must be 6 digits &lt;/b-form-invalid-feedback&gt; &lt;/b-form-group&gt; &lt;b-form-group class=&quot;col-6&quot; label=&quot;Locality (Please Select)&quot; label-for=&quot;locality&quot; &gt; &lt;b-form-select id=&quot;locality&quot; name=&quot;locality&quot; class=&quot;form-control&quot; v-model=&quot;locality&quot; :options=&quot;l_options&quot; :state=&quot;pinValid&quot; &gt; &lt;/b-form-select&gt; &lt;b-form-invalid-feedback id=&quot;locality-live-feedback&quot;&gt; Pincode doesn't exist &lt;/b-form-invalid-feedback&gt; &lt;/b-form-group&gt; &lt;/div&gt; &lt;div class=&quot;form-row&quot;&gt; &lt;b-form-group class=&quot;col-6&quot; label=&quot;District&quot; label-for=&quot;district&quot;&gt; &lt;b-form-input id=&quot;district&quot; type=&quot;text&quot; class=&quot;form-control&quot; v-model=&quot;district&quot; :state=&quot;pinValid&quot; disabled &gt;&lt;/b-form-input&gt; &lt;b-form-invalid-feedback id=&quot;district-live-feedback&quot;&gt; Pincode doesn't exist &lt;/b-form-invalid-feedback&gt; &lt;/b-form-group&gt; &lt;b-form-group class=&quot;col-6&quot; label=&quot;State&quot; label-for=&quot;state&quot;&gt; &lt;b-form-input id=&quot;state&quot; type=&quot;text&quot; class=&quot;form-control&quot; v-model=&quot;state&quot; :state=&quot;pinValid&quot; disabled &gt;&lt;/b-form-input&gt; &lt;b-form-invalid-feedback id=&quot;state-live-feedback&quot;&gt; Pincode doesn't exist &lt;/b-form-invalid-feedback&gt; &lt;/b-form-group&gt; &lt;input type=&quot;text&quot; hidden name=&quot;district&quot; :value=&quot;district&quot; /&gt; &lt;input type=&quot;text&quot; hidden name=&quot;state&quot; :value=&quot;state&quot; /&gt; &lt;/div&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; export default { name: &quot;AddressReceiver&quot;, props: { p_old: { default: null, }, l_old: { default: null, }, d_old: { default: null, }, s_old: { default: null, }, }, data() { return { pincode: this.p_old, locality: this.l_old, l_options: [], district: this.d_old, state: this.s_old, pincodeState: null, pinValid: null, }; }, methods: { pincodeSearch() { axios .get(&quot;/api/pincode/&quot; + parseInt(this.pincode)) .then((response) =&gt; { this.pinValid = true; this.resetIn(); for (let i = 0; i &lt; response.data.length; i++) { this.l_options.push(response.data[i].locality); } if (this.l_old) { this.locality = this.l_old; } else { this.locality = response.data[0].locality; } this.district = response.data[0].district; this.state = response.data[0].state; }) .catch((error) =&gt; { this.pinValid = false; this.resetIn(); }); }, resetIn() { this.l_options = []; this.locality = null; this.district = null; this.state = null; }, }, mounted() { if (this.p_old) { this.pincode = this.p_old; this.pincodeSearch(); } }, watch: { pincode(newPin) { if (newPin &gt;= 100000 &amp;&amp; newPin &lt;= 999999) { this.pincodeSearch(); this.pincodeState = true; } else { this.resetIn(); this.pinValid = null; this.pincodeState = false; if (!newPin) { this.pincodeState = null; } } }, }, computed: { pincodeValid() {}, }, }; &lt;/script&gt; </code></pre> <h2>Component in Blade file</h2> <pre><code>&lt;address-receiver p_old=&quot;{{ old('pincode') }}&quot; l_old=&quot;{{ old('locality') }}&quot; d_old=&quot;{{ old('district') }}&quot; s_old=&quot;{{ old('state') }}&quot; &gt; &lt;/address-receiver&gt; </code></pre> <p>Is there a more elegant way of implementing the old data? I am doing the API call again and getting the options after which the old value is set as the selected value. Any criticism is welcome. I am new to Vue and would love to learn.</p>
[]
[ { "body": "<p>You can use <code>:old=&quot;{{ json_encode(Session::getOldInput()) }}&quot;</code> to get old values from session. Other than that try to avoid props like: <code>p_old</code> they break 2 principles:</p>\n<ol>\n<li>I have no idea for what p stands for</li>\n<li>It does not follow style guideline of Vue</li>\n</ol>\n<p>When you define props as object try to be explicit about type: <code>String, Array</code> etc.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T22:47:52.947", "Id": "483352", "Score": "0", "body": "Changed names of the props and added String type. Is it necessary to v-bind since it's going to be string anyways and I don't need to check if old value exists before passing it. If I bind it Vue throws an error when no data exists." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T08:24:42.087", "Id": "245997", "ParentId": "245939", "Score": "2" } }, { "body": "<h2>User Experience</h2>\n<p>The function method <code>pincodeSearch</code> is called whenever the pincode value changes and is vald. It would likely be wise to consider minimizing server requests by debouncing the function and/or cancelling existing requests if the method is called rapidly in short succession.</p>\n<h2>Vue / Javascript</h2>\n<p>It looks like you started to add a computed property <code>pincodeValid</code> but didn't implement and use it. It could be something as simple as this example:</p>\n<pre><code>pincodeValid: function () {\n return this.pincode &gt;= 100000 &amp;&amp; this.pincode &lt;= 999999\n} \n</code></pre>\n<p>then instead of needing the watcher, a method could be added and bound to the <code>@input</code> attribute of the pincode input:</p>\n<pre><code>pincodeChange: function() {\n if (this.pincodeValid) {\n //this should probably be debounced to minimize server requests\n this.pincodeSearch();\n \n }\n else {\n this.resetIn();\n this.pinValid = null\n }\n}\n</code></pre>\n<p>Then the whole <code>watch</code> section can be eliminated.</p>\n<p>According to the <a href=\"https://vuejs.org/v2/guide/computed.html#Computed-vs-Watched-Property\" rel=\"nofollow noreferrer\">VueJS documentation</a>:</p>\n<blockquote>\n<p>When you have some data that needs to change based on some other data, it is tempting to overuse <code>watch</code> - especially if you are coming from an AngularJS background. However, it is often a better idea to use a computed property rather than an imperative <code>watch</code> callback. <sup><a href=\"https://vuejs.org/v2/guide/computed.html#Computed-vs-Watched-Property\" rel=\"nofollow noreferrer\">1</a></sup></p>\n</blockquote>\n<p>While it may not help this situation much, it is better to get into the practice of using computed properties instead of watchers where possible, since &quot;<em>computed properties are cached based on their reactive dependencies. A computed property will only re-evaluate when some of its reactive dependencies have changed.</em>&quot;<sup><a href=\"https://vuejs.org/v2/guide/computed.html#Computed-Caching-vs-Methods\" rel=\"nofollow noreferrer\">2</a></sup></p>\n<hr />\n<p>There is this loop in the callback to the <code>axios.get()</code> call:</p>\n<blockquote>\n<pre><code>for (let i = 0; i &lt; response.data.length; i++) {\n this.l_options.push(response.data[i].locality);\n}\n</code></pre>\n</blockquote>\n<p>That could be simplified using a <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\"><code>for...of</code> loop</a> - e.g.</p>\n<pre><code>for (const datum of response.data) {\n this.l_options.push(datum.locality); \n}\n</code></pre>\n<p>While there may be a slight performance hit due to the iterator it is simpler to read.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-06T16:59:00.457", "Id": "247579", "ParentId": "245939", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-23T23:54:56.633", "Id": "245939", "Score": "5", "Tags": [ "javascript", "beginner", "php", "laravel", "vue.js" ], "Title": "Implementing Laravel old data in Vuejs" }
245939
<p>This is my first big project. I missed ArrayList a lot in C and thought that it would a very good learning exercise if I implemented my own in C. I tried to take all the features from Java's ArrayList and Python's list. I'd be really glad if you guys could give me some reviews on it.</p> <p>The only code that needs to be reviewed is <code>ArrayList.h</code>. <code>Demo.c</code> is just a demonstration of each function in <code>ArrayList.h</code>.</p> <h1>ArrayList.h</h1> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdarg.h&gt; #include &lt;stdbool.h&gt; #include &lt;string.h&gt; typedef struct List List; typedef struct List* ListPtr; struct List { int capacity; int size; int *arr; }; ListPtr initialiseWithCapacity(int initialCapacity) { ListPtr a = malloc(sizeof *a); a-&gt;capacity = initialCapacity; a-&gt;arr = malloc(a-&gt;capacity * sizeof *(a-&gt;arr)); a-&gt;size = 0; return a; } ListPtr initialise() { return initialiseWithCapacity(10); } ListPtr initialiseWithArray(int arr[], int length) { ListPtr a = initialiseWithCapacity(length); for(int i = 0; i &lt; length; i++) a-&gt;arr[a-&gt;size++] = arr[i]; return a; } ListPtr values(int n, ...) { va_list valist; va_start(valist, n); ListPtr a = initialiseWithCapacity(n); for(int i = 0; i &lt; n; i++) { a-&gt;arr[a-&gt;size++] = va_arg(valist, int); } va_end(valist); return a; } ListPtr range(int start, int stop, int step) { if(step == 0) return initialiseWithCapacity(0); ListPtr a = initialiseWithCapacity( abs(stop - start) / abs(step) + 1 ); if(step &gt; 0) { for(int i = start; i &lt; stop; i += step) a-&gt;arr[a-&gt;size++] = i; } else { for(int i = start; i &gt; stop; i += step) a-&gt;arr[a-&gt;size++] = i; } return a; } ListPtr slice(ListPtr a, int start, int stop, int step) { if(step == 0 || start &lt; 0 || stop &lt; -1 || start &gt;= a-&gt;size || stop &gt;= a-&gt;size) return initialiseWithCapacity(0); ListPtr b = initialiseWithCapacity( abs(stop - start) / abs(step) + 1 ); if(step &gt; 0) { for(int i = start; i &lt; stop; i += step) b-&gt;arr[b-&gt;size++] = a-&gt;arr[i]; } else { for(int i = start; i &gt; stop; i += step) b-&gt;arr[b-&gt;size++] = a-&gt;arr[i]; } return b; } bool clear(ListPtr a) { free(a-&gt;arr); a-&gt;arr = malloc(0); a-&gt;capacity = 0; a-&gt;size = 0; return true; } bool ensureCapacity(ListPtr a, int minCapacity) { if(minCapacity &gt; a-&gt;capacity) { a-&gt;capacity += (a-&gt;capacity &gt;&gt; 1); if(a-&gt;capacity &lt; minCapacity) a-&gt;capacity = minCapacity; a-&gt;arr = realloc(a-&gt;arr, a-&gt;capacity * sizeof *(a-&gt;arr)); } return true; } bool trimToSize(ListPtr a) { a-&gt;capacity = a-&gt;size; a-&gt;arr = realloc(a-&gt;arr, a-&gt;capacity * sizeof *(a-&gt;arr)); return true; } bool fill(ListPtr a, int value, int n) { ensureCapacity(a, n); a-&gt;size = n; for(int i = 0; i &lt; n; i++) { a-&gt;arr[i] = value; } return true; } bool append(ListPtr a, int n) { ensureCapacity(a, a-&gt;size + 1); a-&gt;arr[a-&gt;size++] = n; return true; } bool extendWithArray(ListPtr a, int arr[], int length) { ensureCapacity(a, a-&gt;size + length); for(int i = 0; i &lt; length; i++) a-&gt;arr[a-&gt;size++] = arr[i]; return true; } bool extend(ListPtr a, ListPtr b) { extendWithArray(a, b-&gt;arr, b-&gt;size); return true; } bool insert(ListPtr a, int index, int n) { if(index &lt; 0) index = a-&gt;size + index; if(index &gt; a-&gt;size || index &lt; 0) return false; if(index == a-&gt;size) { append(a, n); return true; } ensureCapacity(a, a-&gt;size + 1); for(int i = a-&gt;size; i &gt; index; i--) { a-&gt;arr[i] = a-&gt;arr[i-1]; } a-&gt;arr[index] = n; a-&gt;size++; return true; } ListPtr copy(ListPtr a) { ListPtr b = initialiseWithCapacity(a-&gt;capacity); extendWithArray(b, a-&gt;arr, a-&gt;size); return b; } int indexOf(ListPtr a, int value) { for(int i = 0; i &lt; a-&gt;size; i++) { if(a-&gt;arr[i] == value) return i; } return -1; } int lastIndexOf(ListPtr a, int value) { for(int i = a-&gt;size - 1; i &gt;= 0; i--) { if(a-&gt;arr[i] == value) return i; } return -1; } int binarySearch(ListPtr a, int value) { int lower = 0, upper = a-&gt;size - 1, mid = 0; while(lower &lt;= upper) { mid = (lower + upper) / 2; if(a-&gt;arr[mid] == value) return mid; else if(a-&gt;arr[mid] &lt; value) lower = mid + 1; else upper = mid - 1; } return -1; } bool contains(ListPtr a, int value) { return indexOf(a, value) &gt;= 0; } bool isEmpty(ListPtr a) { return a-&gt;size == 0; } bool isEqual(ListPtr a, ListPtr b) { if(a-&gt;size != b-&gt;size) return false; for(int i = 0; i &lt; a-&gt;size; i++) { if(a-&gt;arr[i] != b-&gt;arr[i]) return false; } return true; } bool pop(ListPtr a, int index) { if(index &lt; 0) index = a-&gt;size + index; if(index &gt;= a-&gt;size || index &lt; 0) return false; for(int i = index; i &lt; a-&gt;size-1; i++) a-&gt;arr[i] = a-&gt;arr[i+1]; a-&gt;size--; return true; } bool delete(ListPtr a, int value) { int index = indexOf(a, value); if(index == -1) return false; return pop(a, index); } int get(ListPtr a, int index) { if(index &lt; 0) index = a-&gt;size + index; if(index &gt;= a-&gt;size || index &lt; 0) return -1; return a-&gt;arr[index]; } bool set(ListPtr a, int index, int value) { if(index &lt; 0) index = a-&gt;size + index; if(index &gt;= a-&gt;size || index &lt; 0) return false; a-&gt;arr[index] = value; return true; } bool reverse(ListPtr a) { for(int start = 0, stop = a-&gt;size-1; start &lt; stop; start++, stop--) { int t = a-&gt;arr[start]; a-&gt;arr[start] = a-&gt;arr[stop]; a-&gt;arr[stop] = t; } return true; } bool replace(ListPtr a, int oldValue, int newValue) { for(int i = 0; i &lt; a-&gt;size; i++) { if(a-&gt;arr[i] == oldValue) a-&gt;arr[i] = newValue; } return true; } /*Code for sorting begins*/ int comparisonFunctionAscending (const void *a, const void *b) { return ( *(int*)a - *(int*)b ); } int comparisonFunctionDescending (const void *a, const void *b) { return ( *(int*)b - *(int*)a ); } bool sort(ListPtr a) { qsort(a-&gt;arr, a-&gt;size, sizeof(int), comparisonFunctionAscending); return true; } bool sortReverse(ListPtr a) { qsort(a-&gt;arr, a-&gt;size, sizeof(int), comparisonFunctionDescending); return true; } /*Code for sorting ends*/ int count(ListPtr a, int value) { int c = 0; for(int i = 0; i &lt; a-&gt;size; i++) { if(a-&gt;arr[i] == value) c++; } return c; } int sum(ListPtr a) { int s = 0; for(int i = 0; i &lt; a-&gt;size; i++) s += a-&gt;arr[i]; return s; } int len(ListPtr a) { return a-&gt;size; } int cap(ListPtr a) { return a-&gt;capacity; } int* toArray(ListPtr a) { int *b = malloc(a-&gt;size * sizeof *b); for(int i = 0; i &lt; a-&gt;size; i++) b[i] = a-&gt;arr[i]; return b; } char* toString(ListPtr a) { int iMax = a-&gt;size - 1; if(iMax == -1) return &quot;[]&quot;; char *str = malloc( (a-&gt;size * 12 + 1) * sizeof *str ); strcpy(str, &quot;[&quot;); for(int i = 0; ; i++) { char temp[11]; sprintf(temp, &quot;%d&quot;, a-&gt;arr[i]); strcat(str, temp); if(i == iMax) { strcat(str, &quot;]&quot;); return str; } strcat(str, &quot;, &quot;); } } bool display(ListPtr a) { printf(&quot;%s \n&quot;, toString(a)); return true; } </code></pre> <h1>Demo.c</h1> <pre><code>#include &quot;ArrayList.h&quot; void initialiseDemo() { printf(&quot;\n\t\t =============== START DEMO - initialise() =============== \n\n\n&quot;); printf(&quot;Initialising List a with initialise() \n\n&quot;); List *a = initialise(); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Appending 5, 9 \n\n&quot;); append(a, 5); append(a, 9); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n&quot;, cap(a)); printf(&quot;\n\n\t\t =============== END DEMO - initialise() =============== \n\n\n&quot;); } void initialiseWithCapacityDemo() { printf(&quot;\n\t\t =============== START DEMO - initialiseWithCapacity() =============== \n\n\n&quot;); printf(&quot;Initialising List a with initialiseWithCapacity(0) \n\n&quot;); List *a = initialiseWithCapacity(0); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Appending 5, 4, 15, 9, 19 \n\n&quot;); append(a, 5); append(a, 4); append(a, 15); append(a, 9); append(a, 19); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n&quot;, cap(a)); printf(&quot;\n\n\t\t =============== END DEMO - initialiseWithCapacity() =============== \n\n\n&quot;); } void initialiseWithArrayDemo() { printf(&quot;\n\t\t =============== START DEMO - initialiseWithArray() =============== \n\n\n&quot;); printf(&quot;Initialising int arr[] with numbers from 1 to 18 \n\n&quot;); int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18}; printf(&quot;Initialising List a with arr[] using initialiseWithArray(arr, 18) \n\n&quot;); List *a = initialiseWithArray(arr, 18); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n&quot;, cap(a)); printf(&quot;\n\n\t\t =============== END DEMO - initialiseWithArray() =============== \n\n\n&quot;); } void valuesDemo() { printf(&quot;\n\t\t =============== START DEMO - values() =============== \n\n\n&quot;); printf(&quot;Initialising List a with values(5, 1, 2, 5, 9, 17) \n\n&quot;); List *a = values(5, 1, 2, 5, 9, 17); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n&quot;, cap(a)); printf(&quot;\n\n\t\t =============== END DEMO - values() =============== \n\n\n&quot;); } void rangeDemo() { printf(&quot;\n\t\t =============== START DEMO - range() =============== \n\n\n&quot;); printf(&quot;Initialising List a with range(0, 11, 2) \n\n&quot;); List *a = range(0, 11, 2); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Initialising List b with range(10, -1, -2) \n\n&quot;); List *b = range(10, -1, -2); printf(&quot;\t b = %s \n&quot;, toString(b)); printf(&quot;\t Number of elements = %d \n&quot;, len(b)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(b)); printf(&quot;toString( range(5, 51, 5) ) = %s \n&quot;, toString( range(5, 51, 5) )); printf(&quot;\n\n\t\t =============== END DEMO - range() =============== \n\n\n&quot;); } void sliceDemo() { printf(&quot;\n\t\t =============== START DEMO - slice() =============== \n\n\n&quot;); printf(&quot;Initialising List a with range(10, 21, 1) \n\n&quot;); List *a = range(10, 21, 1); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;toString( slice(a, 2, 6, 1) ) = %s \n\n&quot;, toString( slice(a, 2, 6, 1) )); printf(&quot;toString( slice(a, 10, -1, -2) ) = %s \n\n&quot;, toString( slice(a, 10, -1, -2) )); printf(&quot;\n\n\t\t =============== END DEMO - slice() =============== \n\n\n&quot;); } void clearDemo() { printf(&quot;\n\t\t =============== START DEMO - clear() =============== \n\n\n&quot;); printf(&quot;Initialising List a with range(0, 11, 1) \n\n&quot;); List *a = range(0, 11, 1); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Removing all elements from List a using clear(a) \n\n&quot;); clear(a); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Appending 5 \n\n&quot;); append(a, 5); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n&quot;, cap(a)); printf(&quot;\n\n\t\t =============== END DEMO - clear() =============== \n\n\n&quot;); } void ensureCapacityDemo() { printf(&quot;\n\t\t =============== START DEMO - ensureCapacity() =============== \n\n\n&quot;); printf(&quot;Initialising List a with range(0, 11, 2) \n\n&quot;); List *a = range(0, 11, 2); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Ensuring a minimum capacity of 2 using ensureCapacity(a, 2) \n\n&quot;); ensureCapacity(a, 2); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Ensuring a minimum capacity of 6 using ensureCapacity(a, 6) \n\n&quot;); ensureCapacity(a, 6); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Ensuring a minimum capacity of 7 using ensureCapacity(a, 7) \n\n&quot;); ensureCapacity(a, 7); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Ensuring a minimum capacity of 20 using ensureCapacity(a, 20) \n\n&quot;); ensureCapacity(a, 20); printf(&quot;\t Capacity of a = %d \n&quot;, cap(a)); printf(&quot;\n\n\t\t =============== END DEMO - ensureCapacity() =============== \n\n\n&quot;); } void trimToSizeDemo() { printf(&quot;\n\t\t =============== START DEMO - trimToSize() =============== \n\n\n&quot;); printf(&quot;Initialising List a with initialise() \n\n&quot;); List *a = initialise(); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Initialising int arr[] with numbers from 1 to 6 \n\n&quot;); int arr[] = {1, 2, 3, 4, 5, 6}; printf(&quot;Extending List a with arr[] using extendWithArray(a, arr, 6) \n\n&quot;); extendWithArray(a, arr, 6); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Trimming Unused Space in List a using trimToSize(a) \n\n&quot;); trimToSize(a); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n&quot;, cap(a)); printf(&quot;\n\n\t\t =============== END DEMO - trimToSize() =============== \n\n\n&quot;); } void fillDemo() { printf(&quot;\n\t\t =============== START DEMO - fill() =============== \n\n\n&quot;); printf(&quot;Initialising List a with initialise() \n\n&quot;); List *a = initialise(); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Filling List a with 20 occurences of 5 using fill(a, 5, 20) \n\n&quot;); fill(a, 5, 20); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Filling List a with 7 occurences of 19 using fill(a, 19, 7) \n\n&quot;); fill(a, 19, 7); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n&quot;, cap(a)); printf(&quot;\n\n\t\t =============== END DEMO - fill() =============== \n\n\n&quot;); } void appendDemo() { printf(&quot;\n\t\t =============== START DEMO - append() =============== \n\n\n&quot;); printf(&quot;Initialising List a with initialiseWithCapacity(0) \n\n&quot;); List *a = initialiseWithCapacity(0); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Appending 5, 4, 15, 9, 19 using append(a, n) \n\n&quot;); append(a, 5); append(a, 4); append(a, 15); append(a, 9); append(a, 19); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n&quot;, cap(a)); printf(&quot;\n\n\t\t =============== END DEMO - append() =============== \n\n\n&quot;); } void extendWithArrayDemo() { printf(&quot;\n\t\t =============== START DEMO - extendWithArray() =============== \n\n\n&quot;); printf(&quot;Initialising List a with range(0, 11, 2) \n\n&quot;); List *a = range(0, 11, 2); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Initialising int arr[] with numbers from 1 to 6 \n\n&quot;); int arr[] = {1, 2, 3, 4, 5, 6}; printf(&quot;Extending List a with arr[] using extendWithArray(a, arr, 6) \n\n&quot;); extendWithArray(a, arr, 6); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n&quot;, cap(a)); printf(&quot;\n\n\t\t =============== END DEMO - extendWithArray() =============== \n\n\n&quot;); } void extendDemo() { printf(&quot;\n\t\t =============== START DEMO - extend() =============== \n\n\n&quot;); printf(&quot;Initialising List a with range(0, 11, 2) \n\n&quot;); List *a = range(0, 11, 2); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Initialising List b with range(1, 11, 2) \n\n&quot;); List *b = range(1, 11, 2); printf(&quot;\t b = %s \n&quot;, toString(b)); printf(&quot;\t Number of elements = %d \n&quot;, len(b)); printf(&quot;\t Capacity of b = %d \n\n&quot;, cap(b)); printf(&quot;Extending List a with List b using extend(a, b) \n\n&quot;); extend(a, b); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Extending List a using extend(a, range(90, 96, 2)) \n\n&quot;); extend(a, range(90, 96, 2)); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n&quot;, cap(a)); printf(&quot;\n\n\t\t =============== END DEMO - extend() =============== \n\n\n&quot;); } void insertDemo() { printf(&quot;\n\t\t =============== START DEMO - insert() =============== \n\n\n&quot;); printf(&quot;Initialising List a with range(0, 10, 1) \n\n&quot;); List *a = range(0, 10, 1); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Inserting 99 at 0th index using insert(a, 0, 99) \n\n&quot;); insert(a, 0, 99); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Inserting 88 at the end using insert(a, len(a), 88) \n\n&quot;); insert(a, len(a), 88); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Inserting 55 at 5th index using insert(a, 5, 55) \n\n&quot;); insert(a, 5, 55); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Inserting 22 at the last index using insert(a, -1, 22) \n\n&quot;); insert(a, -1, 22); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n&quot;, cap(a)); printf(&quot;\n\n\t\t =============== END DEMO - insert() =============== \n\n\n&quot;); } void copyDemo() { printf(&quot;\n\t\t =============== START DEMO - copy() =============== \n\n\n&quot;); printf(&quot;Initialising List a with range(0, 10, 2) \n\n&quot;); List *a = range(0, 10, 2); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Initialising List b with copy(a) \n\n&quot;); List *b = copy(a); printf(&quot;\t b = %s \n&quot;, toString(b)); printf(&quot;\t Number of elements = %d \n&quot;, len(b)); printf(&quot;\t Capacity of b = %d \n&quot;, cap(b)); printf(&quot;\n\n\t\t =============== END DEMO - copy() =============== \n\n\n&quot;); } void indexOfDemo() { printf(&quot;\n\t\t =============== START DEMO - indexOf() =============== \n\n\n&quot;); printf(&quot;Initialising List a with range(0, 11, 2) \n\n&quot;); List *a = range(0, 11, 2); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Searching for the first occurrence of numbers from 0 to 10 using indexOf(a, i) \n\n&quot;); for(int i = 0; i &lt; 11; i++) { int index = indexOf(a, i); if(index &lt; 0) printf(&quot;\t %d not found in a \n&quot;, i); else printf(&quot;\t %d found at index %d \n&quot;, i, index); } printf(&quot;\n\n\t\t =============== END DEMO - indexOf() =============== \n\n\n&quot;); } void lastIndexOfDemo() { printf(&quot;\n\t\t =============== START DEMO - lastIndexOf() =============== \n\n\n&quot;); printf(&quot;Initialising int arr[] with {0, 1, 2, 2, 3, 4, 5, 6, 2, 7, 8, 9} \n\n&quot;); int arr[] = {0, 1, 2, 2, 3, 4, 5, 6, 2, 7, 8, 9}; printf(&quot;Initialising List a with arr[] using initialiseWithArray(arr, 12) \n\n&quot;); List *a = initialiseWithArray(arr, 12); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Searching for the last occurrence of 2, 10 using lastIndexOf(a, i) \n\n&quot;); printf(&quot;\t Last index of 2 = %d \n&quot;, lastIndexOf(a, 2)); printf(&quot;\t Last index of 10 = %d \n&quot;, lastIndexOf(a, 10)); printf(&quot;\n\n\t\t =============== END DEMO - lastIndexOf() =============== \n\n\n&quot;); } void binarySearchDemo() { printf(&quot;\n\t\t =============== START DEMO - binarySearch() =============== \n\n\n&quot;); printf(&quot;Initialising List a with range(0, 11, 2) \n\n&quot;); List *a = range(0, 11, 2); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Searching for the index of numbers from 0 to 10 using binarySearch(a, i) \n\n&quot;); for(int i = 0; i &lt; 11; i++) { int index = binarySearch(a, i); if(index &lt; 0) printf(&quot;\t %d not found in a \n&quot;, i); else printf(&quot;\t %d found at index %d \n&quot;, i, index); } printf(&quot;\n\n\t\t =============== END DEMO - binarySearch() =============== \n\n\n&quot;); } void containsDemo() { printf(&quot;\n\t\t =============== START DEMO - contains() =============== \n\n\n&quot;); printf(&quot;Initialising List a with range(0, 11, 2) \n\n&quot;); List *a = range(0, 11, 2); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Checking for the presence of numbers from 0 to 10 using contains(a, i) \n\n&quot;); for(int i = 0; i &lt; 11; i++) { if(contains(a, i)) printf(&quot;\t a contains %d \n&quot;, i); else printf(&quot;\t a doesn't contain %d \n&quot;, i); } printf(&quot;\n\n\t\t =============== END DEMO - contains() =============== \n\n\n&quot;); } void isEmptyDemo() { printf(&quot;\n\t\t =============== START DEMO - isEmpty() =============== \n\n\n&quot;); printf(&quot;Initialising List a with range(0, 11, 1) \n\n&quot;); List *a = range(0, 11, 1); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Checking if a is empty using isEmpty(a) \n\n&quot;); if(isEmpty(a)) printf(&quot;\t a is empty \n\n&quot;); else printf(&quot;\t a is not empty \n\n&quot;); printf(&quot;Removing all elements from List a using clear(a) \n\n&quot;); clear(a); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Checking if a is empty using isEmpty(a) \n\n&quot;); if(isEmpty(a)) printf(&quot;\t a is empty \n&quot;); else printf(&quot;\t a is not empty \n&quot;); printf(&quot;\n\n\t\t =============== END DEMO - isEmpty() =============== \n\n\n&quot;); } void isEqualDemo() { printf(&quot;\n\t\t =============== START DEMO - isEqual() =============== \n\n\n&quot;); printf(&quot;Initialising List a with range(0, 10, 2) \n\n&quot;); List *a = range(0, 10, 2); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Initialising List b with copy(a) \n\n&quot;); List *b = copy(a); printf(&quot;\t b = %s \n&quot;, toString(b)); printf(&quot;\t Number of elements = %d \n&quot;, len(b)); printf(&quot;\t Capacity of b = %d \n\n&quot;, cap(b)); printf(&quot;Checking if List a is equal to List b using isEqual(a, b) \n\n&quot;); if(isEqual(a, b)) printf(&quot;\t a is equal to b \n\n&quot;); else printf(&quot;\t a is not equal to b \n\n&quot;); printf(&quot;Appending 0 to List b using append(b, 0) \n\n&quot;); append(b, 0); printf(&quot;\t b = %s \n&quot;, toString(b)); printf(&quot;\t Number of elements = %d \n&quot;, len(b)); printf(&quot;\t Capacity of b = %d \n\n&quot;, cap(b)); printf(&quot;Checking if List a is equal to List b using isEqual(a, b) \n\n&quot;); if(isEqual(a, b)) printf(&quot;\t a is equal to b \n\n&quot;); else printf(&quot;\t a is not equal to b \n\n&quot;); printf(&quot;Appending 0 to List a using append(a, 0) \n\n&quot;); append(a, 0); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Checking if List a is equal to List b using isEqual(a, b) \n\n&quot;); if(isEqual(a, b)) printf(&quot;\t a is equal to b \n&quot;); else printf(&quot;\t a is not equal to b \n&quot;); printf(&quot;\n\n\t\t =============== END DEMO - isEqual() =============== \n\n\n&quot;); } void popDemo() { printf(&quot;\n\t\t =============== START DEMO - pop() =============== \n\n\n&quot;); printf(&quot;Initialising List a with range(0, 11, 1) \n\n&quot;); List *a = range(0, 11, 1); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Removing first element of a using pop(a, 0) \n\n&quot;); pop(a, 0); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Removing last element of a using pop(a, -1) \n\n&quot;); pop(a, -1); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Trying to remove value at index 10 from a using pop(a, 10) \n\n&quot;); if(pop(a, 10)) printf(&quot;\t a = %s \n\n&quot;, toString(a)); else printf(&quot;\t index %d not found in a \n\n&quot;, 10); printf(&quot;Trying to remove value at index 2 from a using pop(a, 2) \n\n&quot;); if(pop(a, 2)) printf(&quot;\t a = %s \n\n&quot;, toString(a)); else printf(&quot;\t index %d not found in a \n\n&quot;, 10); printf(&quot;Removing value at 2nd last index using pop(a, -2) \n\n&quot;); pop(a, -2); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n&quot;, cap(a)); printf(&quot;\n\n\t\t =============== END DEMO - pop() =============== \n\n\n&quot;); } void deleteDemo() { printf(&quot;\n\t\t =============== START DEMO - delete() =============== \n\n\n&quot;); printf(&quot;Initialising List a with range(0, 11, 2) \n\n&quot;); List *a = range(0, 11, 2); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Trying to delete numbers from 0 to 10 using delete(a, i) \n\n&quot;); for(int i = 0; i &lt; 11; i++) { if(delete(a, i)) printf(&quot;\t %d deleted from a \n&quot;, i); else printf(&quot;\t a doesn't contain %d \n&quot;, i); } printf(&quot;\n&quot;); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n&quot;, cap(a)); printf(&quot;\n\n\t\t =============== END DEMO - delete() =============== \n\n\n&quot;); } void getDemo() { printf(&quot;\n\t\t =============== START DEMO - get() =============== \n\n\n&quot;); printf(&quot;Initialising List a with range(0, 11, 2) \n\n&quot;); List *a = range(0, 11, 2); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Trying to print the values at indexes 0 to 10 using get(a, i) \n\n&quot;); for(int i = 0; i &lt; 11; i++) { printf(&quot;\t Value at index %d = %d \n&quot;, i, get(a, i)); } printf(&quot;\n\n\t\t =============== END DEMO - get() =============== \n\n\n&quot;); } void setDemo() { printf(&quot;\n\t\t =============== START DEMO - set() =============== \n\n\n&quot;); printf(&quot;Initialising List a with range(0, 11, 2) \n\n&quot;); List *a = range(0, 11, 2); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Trying to double the value of all elements using set(a, i, get(a, i) * 2) \n\n&quot;); for(int i = 0; i &lt; 11; i++) { if(set(a, i, get(a, i) * 2)) printf(&quot;\t Doubling value at index %d successful \n&quot;, i); else printf(&quot;\t Index %d not found \n&quot;, i); } printf(&quot;\n&quot;); printf(&quot;a after doubling \n\n&quot;); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n&quot;, cap(a)); printf(&quot;\n\n\t\t =============== END DEMO - set() =============== \n\n\n&quot;); } void reverseDemo() { printf(&quot;\n\t\t =============== START DEMO - reverse() =============== \n\n\n&quot;); printf(&quot;Initialising List a with range(0, 11, 1) \n\n&quot;); List *a = range(0, 11, 1); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Reversing the order of elements using reverse(a) \n\n&quot;); reverse(a); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n&quot;, cap(a)); printf(&quot;\n\n\t\t =============== END DEMO - reverse() =============== \n\n\n&quot;); } void replaceDemo() { printf(&quot;\n\t\t =============== START DEMO - replace() =============== \n\n\n&quot;); printf(&quot;Initialising int arr[] with {0, 1, 2, 3, 4, 5, 6, 1, 2, 2, 3, 4, 2, 6, 2} \n\n&quot;); int arr[] = {0, 1, 2, 3, 4, 5, 6, 1, 2, 2, 3, 4, 2, 6, 2}; printf(&quot;Initialising List a with arr[] using initialiseWithArray(arr, 15) \n\n&quot;); List *a = initialiseWithArray(arr, 15); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Replacing all occurrences of 2 with 99 using replace(a, 2, 99) \n\n&quot;); replace(a, 2, 99); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n&quot;, cap(a)); printf(&quot;\n\n\t\t =============== END DEMO - replace() =============== \n\n\n&quot;); } void sortDemo() { printf(&quot;\n\t\t =============== START DEMO - sort() =============== \n\n\n&quot;); printf(&quot;Initialising List a with range(0, 11, 2) \n\n&quot;); List *a = range(0, 11, 2); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Extending List a using extend(a, range(1, 11, 2)) \n\n&quot;); extend(a, range(1, 11, 2)); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Sorting the elements of a in increasing order using sort(a) \n\n&quot;); sort(a); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n&quot;, cap(a)); printf(&quot;\n\n\t\t =============== END DEMO - sort() =============== \n\n\n&quot;); } void sortReverseDemo() { printf(&quot;\n\t\t =============== START DEMO - sortReverse() =============== \n\n\n&quot;); printf(&quot;Initialising List a with range(0, 11, 2) \n\n&quot;); List *a = range(0, 11, 2); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Extending List a using extend(a, range(1, 11, 2)) \n\n&quot;); extend(a, range(1, 11, 2)); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Sorting the elements of a in increasing order using sortReverse(a) \n\n&quot;); sortReverse(a); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n&quot;, cap(a)); printf(&quot;\n\n\t\t =============== END DEMO - sortReverse() =============== \n\n\n&quot;); } void countDemo() { printf(&quot;\n\t\t =============== START DEMO - count() =============== \n\n\n&quot;); printf(&quot;Initialising int arr[] with {1, 2, 2, 3, 3, 3, 5, 5, 5, 5} \n\n&quot;); int arr[] = {1, 2, 2, 3, 3, 3, 5, 5, 5, 5}; printf(&quot;Initialising List a with arr[] using initialiseWithArray(arr, 10) \n\n&quot;); List *a = initialiseWithArray(arr, 10); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Counting the frequency of numbers from 0 to 5 using count(a, i) \n\n&quot;); for(int i = 0; i &lt;= 5; i++) printf(&quot;\t %d is present %d times \n&quot;, i, count(a, i)); printf(&quot;\n\n\t\t =============== END DEMO - count() =============== \n\n\n&quot;); } void sumDemo() { printf(&quot;\n\t\t =============== START DEMO - sum() =============== \n\n\n&quot;); printf(&quot;Initialising List a with range(0, 11, 2) \n\n&quot;); List *a = range(0, 11, 2); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Calculating sum of all elements of a using sum(a) \n\n&quot;); printf(&quot;\t Sum(a) = %d \n&quot;, sum(a)); printf(&quot;\n\n\t\t =============== END DEMO - sum() =============== \n\n\n&quot;); } void lenDemo() { printf(&quot;\n\t\t =============== START DEMO - len() =============== \n\n\n&quot;); printf(&quot;Initialising List a with range(0, 11, 2) \n\n&quot;); List *a = range(0, 11, 2); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Appending 5, 9 \n\n&quot;); append(a, 5); append(a, 9); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Finding new length of a using len(a) \n\n&quot;); printf(&quot;\t Len(a) = %d \n&quot;, len(a)); printf(&quot;\n\n\t\t =============== END DEMO - len() =============== \n\n\n&quot;); } void capDemo() { printf(&quot;\n\t\t =============== START DEMO - cap() =============== \n\n\n&quot;); printf(&quot;Initialising List a with range(0, 11, 2) \n\n&quot;); List *a = range(0, 11, 2); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Appending 5 \n\n&quot;); append(a, 5); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n\n&quot;, len(a)); printf(&quot;Finding new capacity of a using cap(a) \n\n&quot;); printf(&quot;\t Cap(a) = %d \n&quot;, cap(a)); printf(&quot;\n\n\t\t =============== END DEMO - cap() =============== \n\n\n&quot;); } void toArrayDemo() { printf(&quot;\n\t\t =============== START DEMO - toArray() =============== \n\n\n&quot;); printf(&quot;Initialising List a with range(0, 11, 2) \n\n&quot;); List *a = range(0, 11, 2); printf(&quot;\t a = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Initialising int arr[] with elements of List a using toArray(a) \n\n&quot;); int *arr = toArray(a); int arrLength = len(a); printf(&quot;\t arr[] = &quot;); for(int i = 0; i &lt; arrLength; i++) printf(&quot;%d &quot;, arr[i]); printf(&quot;\n&quot;); printf(&quot;\n\n\t\t =============== END DEMO - toArray() =============== \n\n\n&quot;); } void toStringDemo() { printf(&quot;\n\t\t =============== START DEMO - toString() =============== \n\n\n&quot;); printf(&quot;Initialising List a with range(1000000000, 1000000009, 1) \n\n&quot;); List *a = range(1000000000, 1000000009, 1); printf(&quot;\t toString(a) = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n\n&quot;, cap(a)); printf(&quot;Appending 1111111111 \n\n&quot;); append(a, 1111111111); printf(&quot;\t toString(a) = %s \n&quot;, toString(a)); printf(&quot;\t Number of elements = %d \n&quot;, len(a)); printf(&quot;\t Capacity of a = %d \n&quot;, cap(a)); printf(&quot;\n\n\t\t =============== END DEMO - toString() =============== \n\n\n&quot;); } void displayDemo() { printf(&quot;\n\t\t =============== START DEMO - display() =============== \n\n\n&quot;); printf(&quot;Initialising List a with range(0, 11, 2) \n\n&quot;); List *a = range(0, 11, 2); printf(&quot;Displaying the elements of a using display(a) \n\n&quot;); printf(&quot;\t &quot;); display(a); printf(&quot;\n&quot;); printf(&quot;Appending 5 \n\n&quot;); append(a, 5); printf(&quot;Displaying the elements of a using display(a) \n\n&quot;); printf(&quot;\t &quot;); display(a); printf(&quot;\n\n\t\t =============== END DEMO - display() =============== \n\n\n&quot;); } int main(void) { initialiseDemo(); initialiseWithCapacityDemo(); initialiseWithArrayDemo(); valuesDemo(); rangeDemo(); sliceDemo(); clearDemo(); ensureCapacityDemo(); trimToSizeDemo(); fillDemo(); appendDemo(); extendWithArrayDemo(); extendDemo(); insertDemo(); copyDemo(); indexOfDemo(); lastIndexOfDemo(); binarySearchDemo(); containsDemo(); isEmptyDemo(); isEqualDemo(); popDemo(); deleteDemo(); getDemo(); setDemo(); reverseDemo(); replaceDemo(); sortDemo(); sortReverseDemo(); countDemo(); sumDemo(); lenDemo(); capDemo(); toArrayDemo(); toStringDemo(); displayDemo(); return 0; } </code></pre>
[]
[ { "body": "<h1><code>(s)size_t</code></h1>\n<p>Use <code>size_t</code> (It is in <code>&lt;stddef.h&gt;</code> in standard C) or <code>ssize_t</code> (<code>&lt;sys/types.h&gt;</code> in POSIX systems) for raw sizes in bytes.</p>\n<h1><code>ptrdiff_t</code></h1>\n<p>Use <code>ptrdiff_t</code> (<code>&lt;stddef.h&gt;</code>) for element counts such as <code>List.size</code> or array indices such as <code>[i]</code>.</p>\n<h1>Data type</h1>\n<p>Don't restrict the data to <code>int</code>.</p>\n<p>Use <code>void *arr</code> instead so that the user can fill the array with any data.</p>\n<p>If you do this, then many of the specific functions for sorting, summing, etc, should be removed, as the data will not be known. The user should write its own loops for summing, use the standard <code>qsort()</code> with a custom comparison function for sorting, etc.</p>\n<h1>Naming</h1>\n<p>You are using very generic names for functions such as <code>clear()</code>. If you want to have this as a library, you may want to prefix all functions with something like <code>arrlist_</code> to avoid name clashing.</p>\n<h1>Implicit <code>(void)</code></h1>\n<p>Empty parentheses in function definitions mean an implicit <code>(void)</code>, but in function prototypes mean an unspecified number of parameters, which if I remember correctly is a deprecated feature. It's better to explicitly use <code>(void)</code> always and avoid any problems.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T14:12:11.840", "Id": "483214", "Score": "0", "body": "Why `ptrdiff_t` for element counts? Is rather take `size_t` for that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T14:16:46.477", "Id": "483215", "Score": "2", "body": "See [this answer](https://stackoverflow.com/a/3174900/6872717). I also tend to avoid any unsigned types unless I really need them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T14:27:50.120", "Id": "483217", "Score": "2", "body": "*\"Use [signed] int until you have a reason not to. Use unsigned if you are fiddling with bit patterns, and never mix signed and unsigned.\"* [See around 12:56](https://channel9.msdn.com/Events/GoingNative/2013/Interactive-Panel-Ask-Us-Anything)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T14:31:45.860", "Id": "483218", "Score": "1", "body": "IMO, `size_t` being unsigned was a mistake, and compatibility with old functions that use it is the only reason I use it. However, for any new code that I write, I use `ssize_t` or `ptrdiff_t` everywhere." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T14:38:59.183", "Id": "483221", "Score": "2", "body": "Thanks for the additional information. Even after reading the answer, I'll continue to disagree since I prefer unsigned array indices." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T14:40:52.913", "Id": "483222", "Score": "1", "body": "Thanks for the video, I'll have a look at that later. The list of names sounds convincing though. :)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T11:42:50.423", "Id": "245955", "ParentId": "245941", "Score": "2" } }, { "body": "<p>(This was a comment, but then I had more thoughts...)</p>\n<p>I have some stylistic things for you to think about, but can't tell you what's &quot;better&quot;.</p>\n<p>What you've defined is an API for manipulating an ArrayList. I feel like it also shows that you've come from an OOP language, but may not have all the things you want out of your C implementation.</p>\n<h2>Code structure</h2>\n<p>One of the first things I'd do is actually split this into an implementation (in a <code>.c</code> file) and an API definition (in a <code>.h</code> file). In practice, this means you'd have declarations of functions that you want to expose in the <code>.h</code> file, and then you'd have definitions of those functions in the corresponding <code>.c</code> file.</p>\n<p>The other very important thing you can do is <strong>comment your exposed API</strong>.</p>\n<p>ArrayList.h</p>\n<pre class=\"lang-c prettyprint-override\"><code>/*\n * Create an ArrayList with specified initial capacity (can be resized).\n */\nListPtr initialiseWithCapacity(int initialCapacity);\n\n/*\n * Create an ArrayList using the first `length` elements of the given array.\n */\nListPtr initialiseWithArray(int arr[], int length);\n</code></pre>\n<p>ArrayList.c</p>\n<pre class=\"lang-c prettyprint-override\"><code>ListPtr initialiseWithCapacity(int initialCapacity) {\n ListPtr a = malloc(sizeof *a);\n a-&gt;capacity = initialCapacity;\n a-&gt;arr = malloc(a-&gt;capacity * sizeof *(a-&gt;arr));\n a-&gt;size = 0;\n return a;\n}\n\nListPtr initialiseWithArray(int arr[], int length) {\n ListPtr a = initialiseWithCapacity(length);\n for(int i = 0; i &lt; length; i++)\n a-&gt;arr[a-&gt;size++] = arr[i];\n return a;\n}\n</code></pre>\n<h2>Opaque handles</h2>\n<p>Once you've separated your implementation and API definition, another thing you could consider consider is whether or not you want to actually expose the real type of <code>ListPtr</code> to the end-user, or if you want it to be an opaque pointer to a list.</p>\n<p>The reason I say this is because the code looks like it's trying to adopt OOP-style encapsulation, but it also exposes the underlying <code>List *</code>.</p>\n<p>In your case, it'd be:</p>\n<p>ArrayList.h</p>\n<pre class=\"lang-c prettyprint-override\"><code>/*\n * Note that List isn't defined in this file!\n *\n * The user of your API now has to use your initialisation functions to get a ListPtr type.\n * This has advantages:\n * - You can replace the underlying implementation without breaking user code\n * - You can add happily add extra internal stuff that you don't want the user \n * to play with (e.g. do you really want them changing the size field?)\n * - You clarify your expectation of how your API is used\n */\n\ntypedef struct *List ListPtr;\n</code></pre>\n<p>ArrayList.c</p>\n<pre class=\"lang-c prettyprint-override\"><code>struct List {\n int capacity;\n int size;\n int *arr;\n}\n</code></pre>\n<p>See <a href=\"https://stackoverflow.com/questions/7553750/what-is-an-opaque-pointer-in-c\">this answer</a> for a much more involved and better description.</p>\n<h2><code>static</code> functions</h2>\n<p>Another benefit of splitting your API definition and implementation is that you can hide away the functions you don't want your user to mess with. That's what <code>static</code> is useful for with functions (see <a href=\"https://stackoverflow.com/questions/558122/what-is-a-static-function-in-c\">here</a> for more details).</p>\n<p>In your case, I haven't considered in much detail, but at the least I'd make your <code>int comparisonFunctionAscending (...)</code> and <code>int comparisonFunctionDescending (...)</code> functions static.</p>\n<h2>Utility functions</h2>\n<p>Another OOPism here is that a lot of these functions look like methods. That's certainly ok if it's what you're going for (see the previous sections). However, if you're not hiding the implementation of <code>ListPtr</code>, then I think it'd be easier for a C programmer to read:</p>\n<pre><code>if (my_list-&gt;len != 0) {\n ...do stuff...\n}\n</code></pre>\n<p>rather than:</p>\n<pre><code>if (is_empty(my_list)) {\n ...do stuff...\n}\n</code></pre>\n<h2>Early return</h2>\n<p>This is contentious, but it's worth considering if you want to avoid early returns (i.e. just return once from your function at the very end). There's no right or wrong answer, but you should think about what is easiest for you.</p>\n<h2>Use <code>void</code> functions</h2>\n<p>You have some odd functions that return <code>bool</code> (e.g. <code>bool clear(...)</code>), which always return <code>true</code>. Just use <code>void</code>, or even better, consider some error handling and return some type saying whether the operation succeeded or not.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-15T13:35:23.103", "Id": "247946", "ParentId": "245941", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T02:20:51.653", "Id": "245941", "Score": "4", "Tags": [ "c" ], "Title": "ArrayList implementation in C" }
245941
<p>This is my first ever created game. I been slowly but continuously learning PHP for the past 2 months and just last night I thought that I might be able to create a simple and very basic game.</p> <p>Due to my lack of coding experience I am aware that my code could be pretty bad to the point of making anyone to cringe.</p> <p>But because I am totally aware that my code could be a shame when it comes to write simple and easy to understand code, that's why I Google &quot;code review&quot; and I found this site.</p> <p>I want to improve the code and game in 3 ways.</p> <p>1- Change the code from procedural to object oriented. (But I need to learn object oriented PHP first.)</p> <p>2- Create a scoreboard that shows player and computer score. (I assume I can get this done with $_SESSION.)</p> <p>3- Create a highest player scoreboard. (I already know how to create prepared PDO statements to insert data into MariaDB. I also learned procedural MySQLi but I already decided to focus on learning PDO just because of scalability. Then later I can continue learning MySQLi.)</p> <p>So, my problem is that I just want to know what experienced PHP programmers can tell me to improve my code. Maybe a way to simplify what I've done into an easier to read code or less lines of code etc. Any comment is very appreciated, positive or negative. I don't take anything personal.</p> <p>The code consist of just a single index.php file with everything in there. Nothing more, nothing less. Anyone can literally copy paste the code and get it running with XAMPP etc.</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;title&gt;Document&lt;/title&gt; &lt;/head&gt; &lt;style&gt; .game_form { text-align: center; margin: 100px; font-size: 150%; } &lt;/style&gt; &lt;body&gt; &lt;?php // First shuffle/randomizer algorithm. // There are multiple duplicated values to alter the options because otherwise // the computer will almost always choose the same values // and it is easy to win by learning/guessing the pattern. $array = ['rock', 'rock', 'rock', 'rock', 'paper', 'paper', 'paper', 'paper', 'scissor', 'scissor', 'scissor', 'scissor']; shuffle($array); $computerSelection = $array[3]; // Second shuffle/randomizer algorithm. // $input = [&quot;rock&quot;=&gt;&quot;rock&quot;, &quot;paper&quot;=&gt;&quot;paper&quot;, &quot;scissor&quot;=&gt;&quot;scissor&quot;, // &quot;rock&quot;=&gt;&quot;rock&quot;, &quot;paper&quot;=&gt;&quot;paper&quot;, &quot;scissor&quot;=&gt;&quot;scissor&quot;, // &quot;rock&quot;=&gt;&quot;rock&quot;, &quot;paper&quot;=&gt;&quot;paper&quot;, &quot;scissor&quot;=&gt;&quot;scissor&quot;, // &quot;rock&quot;=&gt;&quot;rock&quot;, &quot;paper&quot;=&gt;&quot;paper&quot;, &quot;scissor&quot;=&gt;&quot;scissor&quot;, // &quot;rock&quot;=&gt;&quot;rock&quot;, &quot;paper&quot;=&gt;&quot;paper&quot;, &quot;scissor&quot;=&gt;&quot;scissor&quot;]; // $computerRandomSelection = array_rand($input, 1); ?&gt; &lt;form class=&quot;game_form&quot; action=&quot;index.php&quot; method=&quot;POST&quot;&gt; &lt;input type=&quot;radio&quot; name=&quot;playerSelection&quot; value=&quot;rock&quot;&gt;Rock&lt;br&gt; &lt;input type=&quot;radio&quot; name=&quot;playerSelection&quot; value=&quot;paper&quot;&gt;Paper&lt;br&gt; &lt;input type=&quot;radio&quot; name=&quot;playerSelection&quot; value=&quot;scissor&quot;&gt;Scissor&lt;br&gt; &lt;button name=&quot;submit&quot;&gt;SUBMIT&lt;/button&gt;&lt;br&gt;&lt;br&gt; &lt;?php if (isset($_POST['playerSelection']) == NULL) { echo &quot;Select an option.&quot;; } if (isset($_POST['playerSelection'])) { $playerSelection = $_POST['playerSelection']; echo &quot;You selected: &quot; . $playerSelection . &quot;&lt;br&gt;&quot;; echo &quot;Computer selected: &quot; . $computerSelection . &quot;&lt;br&gt;&quot;; if ($playerSelection == 'rock') { if ($computerSelection == 'rock') echo &quot;&lt;h1&gt;Draw...&lt;/h1&gt;&quot;; if ($computerSelection == 'paper') echo &quot;&lt;h1&gt;You lose.&lt;/h1&gt;&quot;; if ($computerSelection == 'scissor') echo &quot;&lt;h1&gt;Winner!&lt;/h1&gt;&quot;; } if ($playerSelection == 'paper') { if ($computerSelection == 'paper') echo &quot;&lt;h1&gt;Draw...&lt;/h1&gt;&quot;; if ($computerSelection == 'rock') echo &quot;&lt;h1&gt;Winner!&lt;/h1&gt;&quot;; if ($computerSelection == 'scissor') echo &quot;&lt;h1&gt;You lose.&lt;/h1&gt;&quot;; } if ($playerSelection == 'scissor') { if ($computerSelection == 'scissor') echo &quot;&lt;h1&gt;Draw...&lt;/h1&gt;&quot;; if ($computerSelection == 'rock') echo &quot;&lt;h1&gt;You lose.&lt;/h1&gt;&quot;; if ($computerSelection == 'paper') echo &quot;&lt;h1&gt;Winner!&lt;/h1&gt;&quot;; } } ?&gt; &lt;/form&gt; &lt;!-- Just a reference to build the winner vs the looser. Rock &amp; Rock ===== Draw Rock &amp; Paper ==== Paper wins Rock &amp; Scissor == Rock wins Paper &amp; Paper === Draw Paper &amp; Rock ==== Paper wins Paper &amp; Scissor = Scissor wins Scissor &amp; Scissor = Draw Scissor &amp; Rock == Rock wins Scissor &amp; Paper = Scissor wins --&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T04:01:45.777", "Id": "483160", "Score": "0", "body": "We can definitely give you advice about how to refine your code, however asking for help creating new functionality is a no-no here. As for refactoring the script to convert it from procedural to oop, I have a feeling that you are expected to DO that work yourself, then if it works, then we can help you polish it up. This question _may_be closed due to these concerns." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T05:36:56.963", "Id": "483162", "Score": "0", "body": "Understand, I have to do my homework to learn what I need to learn. I am here just for the code review. I wanted to know how bad is my code. Maybe I am underestimating myself and my code might be fine just the way it is. But definitely I don’t want to be spoon feed what I want to add to the code. I’m here just for a code review. I would like to know how an experienced PHP developer would’ve tackle a game like that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-29T00:10:42.190", "Id": "483593", "Score": "1", "body": "For UX I'd just use buttons for direct submission, rather than selecting something, and then submitting." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-30T01:38:02.400", "Id": "483741", "Score": "0", "body": "I didn’t thought about that. Will definitely implement it. Thanks for the idea." } ]
[ { "body": "<p>I personally find the fun part of programming to be the challenge of trying to find the leanest, most direct way to execute a task. One measure of how careful a developer is is to pay attention to occurrences where a script repeats something. You should always strive to not repeat yourself (D.R.Y. means Don't Repeat Yourself).</p>\n<p>You don't need to bloat your array of options with redundant elements. Just name the three options and move on.</p>\n<pre><code>$options = ['paper', 'rock', 'scissors'];\n</code></pre>\n<p>...and don't repeat the <code>&lt;h1&gt;</code> elements in your condition block. Find the outcome, save the string as a variable and echo that variable inside your html markup just one time.</p>\n<p>When you want to create your html form, don't manually write the options, loop over the <code>$options</code> array. <code>printf()</code> is a personal choice to avoid needing to escape double quotes or use concatenation syntax. In other words, the extra function call is for code cleanliness.</p>\n<pre><code>foreach ($options as $option) {\n printf (\n '&lt;input type=&quot;radio&quot; name=&quot;playerSelection&quot; value=&quot;%s&quot;&gt;%s&lt;br&gt;',\n $option,\n ucfirst($option)\n );\n}\n</code></pre>\n<p>Another important point is to never generate data that you will not use. On the page load before the human makes a selection, there will be no comparison. This means that you should definitely not be making a random selection for the &quot;computer&quot;.</p>\n<p>I don't like the loose comparison to <code>NULL</code>, just use <code>if (!isset($_POST['playerSelection'])) {</code>. Instead of writing the inverted <code>if</code> condition immediately after the first, just use <code>} else {</code>.</p>\n<p>As for determining the outcomes, there will be several different techniques to choose from. Some developers will prefer to have a literal lookup array of all combinations of selections pointing to a literal output value. Others will aim for a mathematical technique that will spare memory at a cost of readability. This part will come down to how adventurous you'd care to be. Your battery of conditions is very easy to read but it is also one of the longest ways to code your logic. Compare to this alternative:</p>\n<p>After further consideration, I think it is better to only declare the flipped options array since this perfectly enables the random selection for the computer and the lookups to determine the <code>$difference</code>.</p>\n<p>Code: (<a href=\"https://3v4l.org/kcR45\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n<pre><code>$options = array_flip(['paper', 'rock', 'scissors']);\n$outcomes = ['draw', 'win', 'lose'];\n\n$cpuSelection = array_rand($options);\n$playerSelection = 'rock';\n$difference = $options[$cpuSelection] - $options[$playerSelection];\n\nvar_export([\n 'cpu' =&gt; $cpuSelection,\n 'human' =&gt; $playerSelection,\n 'outcome' =&gt; $outcomes[($difference + 3) % 3]\n]);\n</code></pre>\n<p>Outputs (potentially):</p>\n<pre><code>array (\n 'cpu' =&gt; 'rock',\n 'human' =&gt; 'rock',\n 'outcome' =&gt; 'draw',\n)\n\narray (\n 'cpu' =&gt; 'scissors',\n 'human' =&gt; 'rock',\n 'outcome' =&gt; 'win',\n)\n\narray (\n 'cpu' =&gt; 'paper',\n 'human' =&gt; 'rock',\n 'outcome' =&gt; 'lose',\n)\n</code></pre>\n<p>It isn't instantly comprehensible. Why do I have a magic <code>3</code> in there? If you sharpen your pencil and write a matrix of inputs and outputs, you will find that if you subtract the computer's option's <s>index</s>value from the player's option's <s>index</s>value, then a pattern forms...</p>\n<p>If the difference is <code>0</code>, then it is a draw.\nIf the difference is <code>1</code> or <code>-2</code>, then it is a win.\nIf the difference is <code>2</code> or <code>-1</code>, then it is a loss.\nBy adding <code>3</code> then using the modulus operator to find the remainder upon dividing by 3, you have 3 reliable integers by which you can translate into words via the <code>$outcomes</code> lookup array.</p>\n<p>As I said, there will be several ways to attack the outcome calculation. At the end of the day, this is the type of logical algorithm that you will write once and put behind you so that you can focus on more important things like improving the UX, or converting the script structure to oop, etc.</p>\n<p>In terms of the UI, yeah, it's pretty raw, but because I don't really care to delve into the html/js/css aspects of this little project, I'll end my review here.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T16:50:18.203", "Id": "483235", "Score": "0", "body": "Wow! Thank you very much for this answer. It is priceless. This way the code will be more than 50% shorter and cleaner. Probably wouldn't thought about making an array of the potential answers.\nOnce again, thank you very much, really appreciated!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T06:45:05.453", "Id": "245948", "ParentId": "245942", "Score": "3" } } ]
{ "AcceptedAnswerId": "245948", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T03:15:12.623", "Id": "245942", "Score": "4", "Tags": [ "beginner", "php", "game", "random" ], "Title": "Rock, Paper, Scissor - Game" }
245942
<p>My form comprises of a mandatory file input.</p> <ul> <li><p>The form is validated according to the jQuery validate plugin.</p> </li> <li><p>The file input has attribute <code>required</code> so that the validator recognises it as a mandatory field.</p> </li> </ul> <p><a href="https://i.stack.imgur.com/0LIOP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0LIOP.png" alt="enter image description here" /></a></p> <hr /> <p><strong>Problem statement:</strong></p> <p>Each time the user selects a file, the value of the file input is immediately reset to <code>&quot;&quot;</code>. This is done to allow the same file to be uploaded again (see <a href="https://stackoverflow.com/a/22521275">here</a>) and cannot be changed by me.</p> <p>Since the file input is mandatory, its value must be non-empty to be marked as valid. <strong>However, the file input is validated <em>after</em> the value has been reset to <code>&quot;&quot;</code>, so the input is always marked as invalid, even if the user has selected a file.</strong></p> <p><a href="https://jsfiddle.net/mmerchant/ykxz2jfv/" rel="nofollow noreferrer"><strong>See demo here</strong></a></p> <hr /> <p><strong>Solution:</strong></p> <p><strong>Step 1:</strong> Each time the user selects a file, store the value of the selected file(s) in a <code>data-</code> attribute of the file input:</p> <pre><code>$('input[type=file]').change(function() { $(this).data('files', $(this).val()); }); </code></pre> <p><strong>Step 2:</strong> Change the way the validator accesses the value of the file input. To do this I modify the <strong>elementValue</strong> function (line 718 of the <a href="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.js" rel="nofollow noreferrer"><strong>plugin source</strong></a>) to use <code>$element.data('files')</code> instead of using <code>$element.val()</code> for file inputs:</p> <pre><code>$.extend( $.validator.prototype, { elementValue: function( element ) { ... ... if ( isContentEditable ) { val = $element.text(); } else if (type === &quot;file&quot;) { val = $element.data(&quot;files&quot;) === undefined ? &quot;&quot; : $element.data(&quot;files&quot;); } else { val = $element.val(); } ... ... }); </code></pre> <p><strong><a href="https://jsfiddle.net/mmerchant/c7unjxef/57/" rel="nofollow noreferrer">***See demo here***</a></strong></p> <hr /> <p><strong>Concerns:</strong></p> <p>I am wary of overwriting 'elementValue' in this way as it is an internal function of the plugin.</p> <p>It doesn't seem too dangerous since the return value of the modified 'elementValue' function is the same as that of the original, so <strong>any modifications I have made are restricted to that single function and won't spill over to the rest of the plugin.</strong> But I'm not sure of this and would be grateful for any guidance as I am new to jQuery/JS and don't have any collaborators to think this through with.</p> <p>Another drawback I can think of is that I will always have to check the solution's compatibility with future releases of the plugin.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T04:04:37.250", "Id": "245943", "Score": "3", "Tags": [ "jquery", "validation", "form", "plugin" ], "Title": "Validating a file input whose value is reset to empty string (\"\") after selection" }
245943
<p>I have designed and Online Book Reader System as considering the previous reviews on this platform. You can find the classes below. I would be appreciated for the valuable reviews.</p> <p>Assumptions: &quot;Online Book Reader System&quot; is a system that includes online books and serves its customers to read books online. Users should be login to reach their accounts. The system can include many users and many books. Multiple users can access the same book. Users can add any books to their reading list. After users log in to the system they can start to read any book they want and also can proceed with the latest page they have resumed.</p> <p>Book.java</p> <pre><code>package oopdesign.onlinebookreader; public class Book { private long bookId; private String name; private String category; private String author; private int pageCount; public Book(String name, String category, String author, int pageCount){ this.bookId = name.hashCode(); this.name = name; this.category = category; this.author = author; this.pageCount = pageCount; } } </code></pre> <p>BookProgress.java</p> <pre><code>package oopdesign.onlinebookreader; public class BookProgress { User user; Book book; int resumedPage; public BookProgress(Book book, User user) { this.book = book; this.user = user; this.resumedPage = 0; } public void setResumedPage(int resumedPage) { this.resumedPage = resumedPage; } public int getResumedPage() { return resumedPage; } public void pageForward(){ resumedPage++; setResumedPage(resumedPage); } public void pageBackward(){ resumedPage--; setResumedPage(resumedPage); } public int startReading() { int resumedPage = this.resumedPage; for(int i=0;i&lt;50;i++){ pageForward(); } System.out.println(&quot;Started reading&quot;); return resumedPage; } public void finishReading(){ System.out.println(&quot;Finished reading at &quot;+ resumedPage); } } </code></pre> <p>Library.java</p> <pre><code>package oopdesign.onlinebookreader; import java.util.ArrayList; import java.util.List; public class Library { List&lt;Book&gt; library; public Library(){ library = new ArrayList&lt;&gt;(); } public void addBook(Book book){ library.add(book); } public List&lt;Book&gt; getBookList(){ return library; } } </code></pre> <p>OnlineReaderSystem.java</p> <pre><code>package oopdesign.onlinebookreader; import java.util.List; public class OnlineReaderSystem { private Library library; private UserManager userConsole; private BookProgress progress; public OnlineReaderSystem() { userConsole = new UserManager(); library = new Library(); } public static void main(String[] args) { OnlineReaderSystem onlineReaderSystem = new OnlineReaderSystem(); // Create user User userNes = new User(&quot;Nesly&quot;, &quot;Nesly&quot;,&quot;Password&quot;); onlineReaderSystem.userConsole.addUser(userNes); List&lt;User&gt; userAllList = onlineReaderSystem.userConsole.getAllUsers(); for(User u: userAllList){ System.out.println(u.getName()); } // Create book Book bookFiction = new Book(&quot;Fiction Book&quot;, &quot;Fiction&quot;, &quot;James&quot;,320); onlineReaderSystem.library.addBook(bookFiction); // User login userNes.login(&quot;Nesly&quot;,&quot;password&quot;); // Start reading book onlineReaderSystem.progress = new BookProgress(bookFiction, userNes); onlineReaderSystem.progress.startReading(); onlineReaderSystem.progress.finishReading(); int page = onlineReaderSystem.progress.getResumedPage(); System.out.println(page); } } </code></pre> <p>User.java</p> <pre><code>package oopdesign.onlinebookreader; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Date; public class User { private long userId; public String getName() { return name; } public String getSubcriptionType() { return subcriptionType; } public Date getSubsciptionDate() { return subsciptionDate; } private String name; private String subcriptionType; private Date subsciptionDate; private String loginUserId; private String loginPassword; private String lastLoginDate; private String creditCardInfo; public User(String name, String loginUserId, String loginPassword) { this.userId = name.hashCode(); this.name = name; this.subcriptionType = &quot;Classic&quot;; this.loginUserId = loginUserId; this.loginPassword = loginPassword; } public void login(String loginUser, String login_Password){ if(this.loginUserId.equals(loginUserId) &amp;&amp; this.loginPassword.equals(login_Password)) { System.out.println(&quot;Welcome &quot; + name); DateTimeFormatter dtf = DateTimeFormatter.ofPattern(&quot;yyyy/MM/dd HH:mm:ss&quot;); LocalDateTime now = LocalDateTime.now(); lastLoginDate = dtf.format(now); }else { System.out.println(&quot;Unsuccessful login &quot; + name); } } } </code></pre> <p>UserManager.java</p> <pre><code>package oopdesign.onlinebookreader; import java.util.ArrayList; import java.util.List; public class UserManager { List&lt;User&gt; users; public UserManager(){ users = new ArrayList&lt;&gt;(); } public void addUser(User user){ users.add(user); } public List&lt;User&gt; getAllUsers(){ return users; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T07:56:04.197", "Id": "483174", "Score": "0", "body": "There's a convention for Java package names, aiming to avoid collisions. Packages should begin with a reversed domain name that you own or something similar, e.g. com.stackexchange.neslihanbozer.onlinebookreader." } ]
[ { "body": "<h2>bloater pt 1</h2>\n<p>on my first glance i saw that two classes are not required - the name for that anti-pattern is called <a href=\"https://refactoring.guru/smells/middle-man\" rel=\"nofollow noreferrer\">Middle Man</a>:</p>\n<ul>\n<li><code>Library</code></li>\n<li><code>UserManager</code></li>\n</ul>\n<p>you can easily refer directly to these <code>List&lt;?&gt;</code> (Note: if you provide more function to these classes, maybe like a filter, then these classes would make totally sense - it also would have a name then: <a href=\"https://softwareengineering.stackexchange.com/questions/139353/why-should-we-preferably-use-first-class-collections\">first-class collection</a>. Since it is not (yet) needed it also violates <a href=\"https://clean-code-developer.com/grades/grade-5-blue/#You_Aint_Gonna_Need_It_YAGNI\" rel=\"nofollow noreferrer\">YAGNI</a></p>\n<h2>bloater pt 2</h2>\n<p>the <code>User</code> class is bloated - it has <a href=\"https://clean-code-developer.com/grades/grade-2-orange/#Single_Responsibility_Principle_SRP\" rel=\"nofollow noreferrer\">too much responsibility</a></p>\n<p><a href=\"https://refactoring.guru/extract-class\" rel=\"nofollow noreferrer\">extract these responsibilites</a> into the proper classes</p>\n<pre><code>//TODO class Subscription\nprivate String subcriptionType;\nprivate Date subsciptionDate;\n...\npublic String getSubcriptionType() \npublic Date getSubsciptionDate()\n...\n</code></pre>\n<pre><code>//TODO class LogIn\nprivate String loginUserId;\nprivate String loginPassword;\nprivate String lastLoginDate;\n...\npublic void login(String loginUser, String login_Password)\n...\n</code></pre>\n<h2>some other minor issues</h2>\n<ul>\n<li><a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">magic numbers</a> <code>for(int i=0;i&lt;50;i++)...</code> - why <strong>50</strong>?</li>\n<li><a href=\"https://refactoring.guru/smells/primitive-obsession\" rel=\"nofollow noreferrer\">primitve Obsession</a> (why not use an <code>enum</code> for <code>subcriptionType</code> - that would make turn <code>&quot;Classic&quot;</code> into it's proper value)</li>\n<li><a href=\"https://refactoring.guru/smells/primitive-obsession\" rel=\"nofollow noreferrer\">primitve Obsession</a> - <code>String creditCardInfo</code> - a class would make sense here (especially because you have to treat these information with special care)</li>\n<li>hardcoded Strings - <code>&quot;Started reading&quot;</code>, <code>&quot;Finished reading at &quot;</code></li>\n<li>use a test class instead of a <code>main()</code> test</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T05:33:01.030", "Id": "245946", "ParentId": "245944", "Score": "3" } }, { "body": "<p>@Martin Frank has given you a few things to think about, so I'm only going to add a couple of points. Firstly, use consistent formatting it makes a difference for readability. Most IDE's will do this for you automatically. As it stands, you have some method signatures that have spaces between <code>) {</code> and some that don't <code>){</code>.</p>\n<p>Secondly, your <code>Book</code> class has a bunch of private fields, that don't have getters, or any methods that operate on them other than the constructor that set's them. Consider not adding fields until they're actually needed, it'll save you time in the long run.</p>\n<p>Finally, consider these methods:</p>\n<blockquote>\n<pre><code>public void pageForward(){\n resumedPage++;\n setResumedPage(resumedPage);\n}\npublic void setResumedPage(int resumedPage) {\n this.resumedPage = resumedPage;\n}\n</code></pre>\n</blockquote>\n<p>Your <code>pageForward</code> increments the <code>resumedPage</code> field then calls the properties setter to set the field to the value that the field already has. You don't need to call <code>setResumedPage</code> in this scenario, since <code>resumedPage</code> already has the same value...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-01T13:32:29.807", "Id": "484052", "Score": "0", "body": "I didn't see that, you are a good observer! +1" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-30T15:25:57.580", "Id": "246256", "ParentId": "245944", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T04:06:57.477", "Id": "245944", "Score": "4", "Tags": [ "java", "object-oriented" ], "Title": "Online Reader System Object Oriented System" }
245944
<p>I wrote this variant of Bresenham's for fun. I am looking to see what I can optimize as it is still slower than Bresenham's.</p> <p>The idea here was that if I could isolate out the <code>IFs</code> in Bresenham's loop it'd be more efficient. Well go figure, the added multiplication (A) or array lookups (B) in the pre-calc destroy said efficiency in overhead. That said, might be more efficient in a shader on GPUs? Haven't tested yet.</p> <p>Both versions <code>A</code> and <code>B</code> have the same efficiency, weirdly enough.</p> <p>Version A:</p> <pre><code>void bresenprecalcA(int x1, int y1, int x2, int y2) { int dx = x2 - x1, dy = y2 - y1, // dxyA is the sign of the quadrant xy delta. dxA = sgn(dx), dyA = sgn(dy), // dyB is the absolute quadrant xy delta (to isolate the quadrant math). dxB = abs(dx), dyB = abs(dy), // check if x&gt;y or y&gt;x for quadrant determination. cx = dxB &gt;= dyB, cy = dyB &gt;= dxB, // qx is whether we're in a horz-x facing quadrant. // qy is whether we're in a vert-y facing quadrant. qx = cy * dxB, qy = cx * dyB, // qr checks if we lie in a quadrant rather than one of the 8 cardinal dir. // pd is for the incremental error check below. qr = qx != qy, pd = qx + qy, // if the line is horz, move horz other move vert. xm = cx * dxA, ym = cy * dyA, // if the line is horz, move horz other move vert. xym = cx? dxB : dyB, // Incremental error check (see Bresenhams algorithm). er = pd - (xym/2), ec; // Create a lookup table, rather than use multiplication in the for(;;) below. // look*[0] is if the line is horz, vert or diag. // look*[1] is if the line is in between angles (direction is not mod 45 == 0). int lookx[2] = {xm,xm + (qr * cy * dxA)}, looky[2] = {ym,ym + (qr * cx * dyA)}, lookd[2] = {qr * pd, qr * (pd - xym)}; //draw_point(xx, yy); for(;;) { // Error check above/below the line. ec = er &gt;= 0; // Increment lookup table based on error check. // ec==0 -&gt; line is horz/vert/diagonal (dir%45 = 0). // ec==1 -&gt; line is between cardinals (dir%45 != 0). x1 += lookx[ec]; y1 += looky[ec]; er += lookd[ec]; // Break loop when line is done. //draw_point(xx, yy); if (x2 == x1 &amp;&amp; y2 == y1) break; }; } </code></pre> <p>Version B:</p> <pre><code>void bresenprecalcB(int x1, int y1, int x2, int y2) { int dx = x2 - x1, dy = y2 - y1, dxA = sgn(dx), dyA = sgn(dy), dxB = abs(dx), dyB = abs(dy), cx = dxB &gt;= dyB, cy = dyB &gt;= dxB; int lookm[10] = {0,dxB,0,dyB,0,dxA,0,dyA,dyB,dxB}; int qx = lookm[cy], qy = lookm[2+cx], xm = lookm[4+cx], ym = lookm[6+cy], xym = lookm[8+cx], qr = qx != qy, pd = qx + qy, er = pd - (xym / 2), ec; int lookx[2] = {xm,xm + (qr * cy * dxA)}, looky[2] = {ym,ym + (qr * cx * dyA)}, lookd[2] = {qr * pd, qr * (pd - xym)}; //draw_point(x1, y1); for(;;) { ec = er &gt;= 0; x1 += lookx[ec]; y1 += looky[ec]; er += lookd[ec]; //draw_point(x1, y1); if (x2 == x1 &amp;&amp; y2 == y1) break; }; }; </code></pre> <p>Bresenham's from this <a href="https://stackoverflow.com/a/16405254/2808956">StackOverflow</a> post:</p> <pre><code>void bresenhams(int x1, int y1, int x2, int y2) { int xx, yy, dx, dy, dx1, dy1, px, py, xe, ye, i; dx = x2 - x1; dy = y2 - y1; dx1 = abs(dx); dy1 = abs(dy); px = 2 * dy1 - dx1; py = 2 * dx1 - dy1; if (dy1 &lt;= dx1) { if (dx &gt;= 0) { xx = x1; yy = y1; xe = x2; } else { xx = x2; yy = y2; xe = x1; } //draw_point(xx, yy); for (i = 0; xx &lt; xe; i++) { xx = xx + 1; if (px &lt; 0) { px = px + 2 * dy1; } else { if ((dx &lt; 0 &amp;&amp; dy &lt; 0) || (dx &gt; 0 &amp;&amp; dy &gt; 0)) { yy = yy + 1; } else { yy = yy - 1; } px = px + 2 * (dy1 - dx1); } //draw_point(xx, yy); } } else { if (dy &gt;= 0) { xx = x1; yy = y1; ye = y2; } else { xx = x2; yy = y2; ye = y1; } //draw_point(xx, yy); for (i = 0; yy &lt; ye; i++) { yy = yy + 1; if (py &lt;= 0) { py = py + 2 * dx1; } else { if ((dx &lt; 0 &amp;&amp; dy &lt; 0) || (dx &gt; 0 &amp;&amp; dy &gt; 0)) { xx = xx + 1; } else { xx = xx - 1; } py = py + 2 * (dx1 - dy1); } //draw_point(xx, yy); } } }; </code></pre>
[]
[ { "body": "<h1>Removing unncessary branches</h1>\n<p>Looking at the assembly generated by your code, you indeed managed to get rid of all branches save for the one needed by the loop itself. Nice! But maybe you removed too many? The main issue is the speed of the loop itself. Branches outside the loop do not impact performance much, and they can actually help performance! Consider for example that in the &quot;non-compact&quot; Bresenham implementation, they basically have two specialized loops, and choose which one to use depending on the slope. You could do that as well and perhaps reduce the amount of pre-calculation necessary in each case.</p>\n<p>Another issue is the use of multiplications in lines such as these:</p>\n<pre><code>int lookx[2] = {xm, xm + (qr * cy * dxA)},\n looky[2] = {ym, ym + (qr * cx * dyA)},\n lookd[2] = {qr * pd, qr * (pd - xym)};\n</code></pre>\n<p>Here, <code>qr</code>, <code>cx</code> and <code>cy</code> are both booleans. By using a multiplication here, it seems that at least on some CPU architectures, GCC actually generates multiplication instructions, when it could have used fast instructions such as <code>and</code> and conditional moves. Rewriting the above to the following lines seems to get rid of the multiplication instructions:</p>\n<pre><code>int lookx[2] = {xm, xm + ((qr &amp; cy) * dxA)},\n looky[2] = {ym, ym + ((qr &amp; cx) dyA)},\n lookd[2] = {qr ? pd : 0, qr ? (pd - xym) : 0};\n</code></pre>\n<p>Clang seems to see that it can use conditional moves here without having to rewrite it, at least on x86_64. Of course, this is not so important unless you expect to draw many short lines, where the setup cost dominates.</p>\n<p>Again, if you allow branches in the setup, you can have specialized init functions for the 8 distinct slope ranges which will be much simpler.</p>\n<h1>Branch predictors are awesome</h1>\n<p>Branches are bad on GPUs, but on CPUs a lot of effort has been spent optimizing the branch predictors. Conditions that are static during a loop are probably predicted with 100% accuracy and cost basically nothing. But even conditions that change often, like <code>if (px &lt; 0)</code>, might be predicted with a high degree of accuracy if they follow a pattern. And they do in the case of drawing lines using Bresenham's algorithm. It probably works better for some slopes than others though.</p>\n<p>The above can very well explain why the &quot;non-compact&quot; version performs just as well. But it will probably also depend a lot on what CPU it is running on, what optimization level is used, and what kind of lines you are drawing (long/short, right angles/arbitrary angles).</p>\n<h1>Other possible optimizations</h1>\n<p>Assuming you keep the loop the same, you can thing about vectorizing it a little bit. You could group <code>x1</code>, <code>y1</code> and <code>ec</code> together in a single 128-bit register, and also make a single <code>__m128 lookup[2]</code>, so you can just do a single <code>_mm_add_epi32()</code> to add the three components of the lookup table to <code>x1</code>, <code>y1</code> and <code>ec</code> in one go.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T16:01:51.273", "Id": "245966", "ParentId": "245945", "Score": "3" } } ]
{ "AcceptedAnswerId": "245966", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T04:11:16.683", "Id": "245945", "Score": "4", "Tags": [ "c++", "performance", "algorithm", "graphics" ], "Title": "Super Compact Bresenham's Line Algorithm Variant" }
245945
<p>I'm learning C++ using a book and currently, I'm reading the section about formating output data using manipulators. There is a program written to output data once without showing the base and again with its base. It is a simple program as follows:</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main() { int x = 1237; cout&lt;&lt;&quot;x in decimal: &quot;&lt;&lt; x &lt;&lt; endl; cout&lt;&lt;&quot;x in octal: &quot;&lt;&lt;oct&lt;&lt; x &lt;&lt; endl; cout&lt;&lt;&quot;x in hexadecimal: &quot;&lt;&lt; hex &lt;&lt; x &lt;&lt; endl &lt;&lt; endl; cout&lt;&lt;&quot;x in decimal: &quot; &lt;&lt; x &lt;&lt; endl; cout&lt;&lt;&quot;x in octal: &quot; &lt;&lt; showbase &lt;&lt; oct &lt;&lt; x &lt;&lt; endl; cout&lt;&lt;&quot;x in hexadecimal: &quot; &lt;&lt; showbase &lt;&lt; hex &lt;&lt; x &lt;&lt; endl; return 0; } </code></pre> <p>When the program is run the output is:</p> <pre><code> x in decimal: 1237 x in octal: 2325 x in hexadecimal: 4d5 x in decimal: 4d5 x in octal: 02325 x in hexadecimal: 0x4d5 </code></pre> <p>That is, in the line containing <code>x in decimal</code> the value is in <code>hex</code> rather than <code>dec</code>. I've compiled and run this code both using GCC and cpp.sh website but the result is not what is now in the book indicating a decimal value. Could anyone please explain to me why does this happen and how could I solve it?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T12:59:47.910", "Id": "483197", "Score": "0", "body": "Welcome to Code Review! Please inform yourself, [take the tour](https://codereview.stackexchange.com/tour), and read up at our [help center](https://codereview.stackexchange.com/help/on-topic). This question is _off-topic_ because this site is for reviewing code you write. [“_For licensing, moral, and procedural reasons, we cannot review code written by other programmers. We expect you, as the author, to understand why the code is written the way that it is._”](https://codereview.stackexchange.com/help/on-topic)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T13:07:24.640", "Id": "483199", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ Yeah, Surely you're right." } ]
[ { "body": "<p>This would probably better fit to StackOverflow. The reason is that the <code>std::hex</code>manipulator is persistent. You must explicitly switch back to decimal.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T07:26:25.127", "Id": "483170", "Score": "0", "body": "Yes, I added `dec` at that line and it worked! Would you please tell me, why Code Review isn't suitable for this question? Thank you" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T07:36:12.867", "Id": "483172", "Score": "2", "body": "I'm by far not a StackExchange veteran, but my understanding is that StackOverflow is for code that does not work as expected and questions about specific things, whereas CodeReview is for code that works and is finished, but the author wants to know what could have been done better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T07:37:18.443", "Id": "483173", "Score": "0", "body": "That's right. Thanks for being so informative!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T13:10:14.503", "Id": "483200", "Score": "1", "body": "[Please refrain from answering questions that are likely to get closed.](https://codereview.meta.stackexchange.com/a/6389/35991). in the future please use the [flag option](https://codereview.stackexchange.com/help/privileges/flag-posts) until you gain the [cast close and reopen votes](https://codereview.stackexchange.com/help/privileges/close-questions) privilege" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T15:19:43.807", "Id": "483228", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ I saw the question is not ok, but given the simplicity I decided to answer anyway. I did not know that an accepted answer forbids mods from deleting the question (which is what I assumed would happen). Sorry about that." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T07:17:39.603", "Id": "245952", "ParentId": "245949", "Score": "0" } } ]
{ "AcceptedAnswerId": "245952", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T06:50:00.353", "Id": "245949", "Score": "-3", "Tags": [ "c++" ], "Title": "Outputting a decimal value in Cpp" }
245949
<p>Hi guys Im very very new To Angular/Typescript Im teaching my self section by section by just messing around and figuring things out.</p> <p>Currently im just doing loop's and outputs so I decided to write a Randomizer for a Moba</p> <p>Its. 5 Arrays then I select a Random item from each Check that they dont match and output</p> <p>But I just have to think theres a way to improve on this, Note: I will be expanding to classes and 1 list where i'll pull item's based on a Role: ID but for the moment I need to get arround the if's because its making the values blank when it fails which is fine, but I feel like this can be avoided with an alternative to my way of doing it.</p> <p>Would appreciate any suggestions or alternative's</p> <p>Learning Material Welcomed</p> <pre><code> constructor() { } midhero; tophero; botHero; hardShero; softShero; ngOnInit(): void { this.createHeroes(); } createHeroes(): void{ var topheroz = [ &quot;Mars&quot;, &quot;Void Spirit&quot; ,&quot;Pango&quot;, &quot;Brisle&quot;, &quot;Axe&quot;, &quot;Ogre&quot; ]; var midheroz = [ &quot;OD&quot;, &quot;Void Spirit&quot; ,&quot;SkyWrath&quot;, &quot;TA&quot;, &quot;Morph&quot; ]; var botheroz = [ &quot;AM&quot;, &quot;WK&quot; , &quot;Ursa&quot; , &quot;Morph&quot; , &quot;Brisle&quot; ]; var hardSupz = [ &quot;Dazzle&quot;, &quot;Winter Wyvern&quot; , &quot;Ogre&quot; , &quot;Crystal Maidan&quot; , &quot;Jakiro&quot; ]; var softSupz = [ &quot;Dazzle&quot;, &quot;Winter Wyvern&quot; , &quot;Ogre&quot; , &quot;Crystal Maidan&quot; , &quot;Jakiro&quot; ]; var miditem = midheroz[Math.floor(Math.random() * midheroz.length)]; var topitem = topheroz[Math.floor(Math.random() * topheroz.length)]; var botitem = botheroz[Math.floor(Math.random() * botheroz.length)]; var harditem = hardSupz[Math.floor(Math.random() * hardSupz.length)]; var softitem = softSupz[Math.floor(Math.random() * softSupz.length)]; var midfine; var topfine; var botfine; var hardfine; var softfine; if(topitem == miditem || topitem == botitem || topitem == harditem || topitem == softitem){ var topitem = topheroz[Math.floor(Math.random() * topheroz.length)]; } else{ topfine = true; } if(miditem == topitem || miditem == botitem || miditem == harditem || miditem == softitem){ var miditem = midheroz[Math.floor(Math.random() * midheroz.length)]; } else{ midfine = true; } if(botitem == topitem || botitem == miditem || botitem == harditem || botitem == softitem ){ var miditem = botheroz[Math.floor(Math.random() * botheroz.length)]; } else{ botfine = true; } if(softitem == topitem || softitem == miditem || softitem == botitem || softitem == harditem){ var miditem = botheroz[Math.floor(Math.random() * botheroz.length)]; } else{ softfine = true; } if(harditem == topitem || harditem == miditem || harditem == botitem || harditem == softitem){ var miditem = botheroz[Math.floor(Math.random() * botheroz.length)]; } else{ hardfine = true; } if(midfine &amp;&amp; topfine &amp;&amp; botfine &amp;&amp; softfine &amp;&amp; hardfine){ this.midhero = miditem; this.tophero = topitem; this.botHero = botitem; this.hardShero = harditem; this.softShero = softitem; } else{ this.createHeroes(); } } </code></pre> <pre><code> &lt;section &gt; &lt;div&gt; &lt;p style=&quot;color:blue;&quot;&gt;Mid:{{midhero}}&lt;/p&gt; &lt;p style=&quot;color:red;&quot;&gt;Top:{{tophero}}&lt;/p&gt; &lt;p style=&quot;color:green;&quot;&gt;Bot:{{botHero}}&lt;/p&gt; &lt;p style=&quot;color:purple;&quot;&gt;Soft Support:{{softShero}}&lt;/p&gt; &lt;p style=&quot;color:orange;&quot;&gt;Hard Support:{{hardShero}}&lt;/p&gt; &lt;/div&gt; &lt;/section&gt; <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T18:30:52.890", "Id": "483476", "Score": "0", "body": "welcome to Code Review! would you please add a **complete** code example?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T07:13:05.717", "Id": "245951", "Score": "3", "Tags": [ "typescript", "angular-2+" ], "Title": "Alternative Way of comparing multiple variable's to multiple variables" }
245951
<pre><code>class ChristmasTree { private static void byHand() { System.out.println( &quot;Chritsmas tree, yey.&quot; ); System.out.println( &quot; *&quot; ); System.out.println( &quot; ***&quot; ); System.out.println( &quot; *****&quot; ); System.out.println( &quot; *******&quot; ); System.out.println( &quot; ********&quot; ); System.out.println( &quot;**********&quot; ); System.out.println( &quot; |&quot; ); System.out.println( &quot; _&quot; ); } private static void withLoops() { int rows = 6; StringBuilder sb = new StringBuilder(); for( int row = 0; row &lt; rows; ++row ) { for( int spaces = rows - row; spaces &gt; 0; --spaces ) { sb.append( &quot; &quot; ); } for( int stars = 0; stars &lt; 2 * row + 1; ++stars ) { sb.append( &quot;*&quot; ); } sb.append( &quot;\n&quot; ); } for( int spaces = 0; spaces &lt; rows; ++spaces ) { sb.append( &quot; &quot; ); } sb.append( &quot;|&quot; ); sb.append( &quot;\n&quot; ); for( int spaces = 0; spaces &lt; rows; ++spaces ) { sb.append( &quot; &quot; ); } sb.append( &quot;_&quot; ); System.out.println( sb.toString() ); } private static String spaces( int num ) { StringBuilder sb = new StringBuilder(); for( int spaces = 0; spaces &lt; num; ++spaces ) { sb.append( &quot; &quot; ); } return sb.toString(); } private static String properly( int rows ) { StringBuilder sb = new StringBuilder(); for( int row = 0; row &lt; rows; ++row ) { for( int spaces = rows - row; spaces &gt; 0; --spaces ) { sb.append( &quot; &quot; ); } for( int stars = 0; stars &lt; 2 * row + 1; ++stars ) { sb.append( &quot;*&quot; ); } sb.append( &quot;\n&quot; ); } sb.append( spaces( rows ) ); sb.append( &quot;|&quot; ); sb.append( &quot;\n&quot; ); sb.append( spaces( rows ) ); sb.append( &quot;_&quot; ); return sb.toString(); } public static void main(String[] args) { byHand(); withLoops(); // What if the tree needs to be 100 lines high? // We arrive at the concept of `scalability`. System.out.println( properly( 16 ) ); } } </code></pre> <p>Topics I have considered but decided against:</p> <ul> <li>pass the tree height on the command line via <code>java.util.Scanner;</code></li> <li>make a copy of <code>spaces()</code> called <code>stars()</code></li> <li>explain the purpose of the class at the very beginning a la <code>python docstring</code></li> <li>split the methods so the don't exceed 20 LOC</li> </ul> <p>Also there's <a href="https://stackoverflow.com/questions/30723247/creating-a-christmas-tree-using-for-loops">this.</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T20:32:48.307", "Id": "483257", "Score": "1", "body": "I kept having this nagging feeling your \"by hand\" tree isn't quite right. You may want to keep all the ending string delimiters in the same column (11 characters after the first) so little typos like this are easier to see. :)" } ]
[ { "body": "<p>I have some suggestions for your code.</p>\n<ol>\n<li>Most of your loops can be replaced with <a href=\"https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/String.html#repeat(int)\" rel=\"nofollow noreferrer\">java.lang.String#repeat</a> (Java 11+)</li>\n</ol>\n<p><em>Example</em></p>\n<pre class=\"lang-java prettyprint-override\"><code>&quot;*&quot;.repeat(10) // Will give you &quot;**********&quot;\n</code></pre>\n<ol start=\"2\">\n<li><p>I suggest that you create a class constant for each of the tree's parts (<code>*</code>, <code>\\n</code>, <code>|</code>) to allow the code to be easier to refactor / make changes in the future, if you need to (i.e., change the star by a plus sign, etc.).</p>\n</li>\n<li><p>For the tree's parts, I suggest that you use character instead of string, since the character will take less memory than the string (very small amount in this case, but still).\n<code>&quot; &quot;</code> -&gt; <code>' '</code></p>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T14:07:52.393", "Id": "483211", "Score": "0", "body": "What is your rationale for adding constants in this particular code? In a more complicated setting I would agree, but in this simple example code I think the constants only create unnecessary bloat." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T15:20:08.387", "Id": "483229", "Score": "1", "body": "For my part, when I have more than one place that uses the same string, I always create a constant / enum for the value. This makes the code easier to refactor, in my opinion, even with small task like this one." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T12:25:59.643", "Id": "245956", "ParentId": "245954", "Score": "4" } }, { "body": "<p>As @Doi9t said, most of your code is about creating strings of repeated characters like the method below:</p>\n<pre><code>private static String spaces( int num )\n{\n StringBuilder sb = new StringBuilder();\n for( int spaces = 0; spaces &lt; num; ++spaces )\n {\n sb.append( &quot; &quot; );\n }\n return sb.toString();\n}\n</code></pre>\n<p>You can use instead the <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#fill(char%5B%5D,%20char)\" rel=\"nofollow noreferrer\">Arrays.fill</a> method to create strings of replicated characters like below:</p>\n<pre><code>private static String spaces( int num , char c)\n{\n char[] arr = new char[num];\n Arrays.fill(arr, c); \n\n return new String(arr);\n}\n</code></pre>\n<p>About the construction of your tree like this below for <code>nRows = 6</code> :</p>\n<pre><code>Note : \\n and whitespaces are invisible\n\n * \\n &lt;-- row = 0 \n *** \\n \n ***** \\n \n ******* \\n \n ********* \\n\n *********** \\n &lt;-- row = 5\n | \\n &lt;-- row = 6 \n _ \\n &lt;-- row = 7 \n</code></pre>\n<p>You are doing it using one <code>StringBuilder</code> and consecutive <code>append</code> operations, but you already can calculate the length of the result and where to put characters different from <code>' '</code> to minimize operations.<br />\nYou can check that lines 6, 7, 0 have in common the characteristic to have just one char in the middle, while every line from 1 to 5 can be obtained from the previous one adding one char to the the left and to the right. So if you start from creating a <code>char</code> tree like below:</p>\n<pre><code>private static String generateTree(int nRows) {\n final int nColumns = 2 * (nRows + 1);\n final int middle = nColumns / 2;\n char[] tree = new char[(nRows + 2) * nColumns];\n \n //...other instructions\n\n return new String(tree);\n}\n</code></pre>\n<p>After you can calculate every row of your tree putting it in the right position in tree starting from the trunk lines and the peak of your tree:</p>\n<pre><code>char[] row = new char[nColumns]; \nArrays.fill(row, ' ');\n \nrow[middle] = '|';\nrow[nColumns - 1] = '\\n'; //newline will added to every line of the tree.\nSystem.arraycopy(row, 0, tree, nRows * nColumns, nColumns);\n \nrow[middle] = '_';\nSystem.arraycopy(row, 0, tree, (nRows + 1) * nColumns, nColumns);\n \nrow[middle] = '*';\nSystem.arraycopy(row, 0, tree, 0, nColumns);\n</code></pre>\n<p>After you can calculate the other lines of the tree starting from the peak and add them to obtain the final result:</p>\n<pre><code>private static String generateTree(int nRows) {\n final int nColumns = 2 * (nRows + 1);\n final int middle = nColumns / 2;\n char[] tree = new char[(nRows + 2) * nColumns];\n \n char[] row = new char[nColumns]; \n Arrays.fill(row, ' ');\n \n row[middle] = '|';\n row[nColumns - 1] = '\\n';\n System.arraycopy(row, 0, tree, nRows * nColumns, nColumns);\n \n row[middle] = '_';\n System.arraycopy(row, 0, tree, (nRows + 1) * nColumns, nColumns);\n \n row[middle] = '*';\n System.arraycopy(row, 0, tree, 0, nColumns);\n \n for (int i = 1; i &lt; nRows; ++i) {\n row[middle - i] = '*';\n row[middle + i] = '*';\n System.arraycopy(row, 0, tree, i * nColumns, nColumns);\n }\n \n return new String(tree);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T13:12:42.663", "Id": "245958", "ParentId": "245954", "Score": "4" } }, { "body": "<p>Nice implementation, easy to understand and efficient. Few suggestions:</p>\n<ol>\n<li>As others said, by using <code>&quot;*&quot;.repeat()</code> you can avoid some of the loops</li>\n<li>Make use of <code>String.format</code> it's very powerful for arranging the text</li>\n<li>If you want to change the character <code>*</code> is better to use a single constant or even better an enum</li>\n</ol>\n<h2>Code refactored</h2>\n<p>It can actually be solved in one line:</p>\n<pre class=\"lang-java prettyprint-override\"><code>String christmasTree = IntStream.range(0, rows+2).mapToObj(i-&gt;String.format(&quot;%1$&quot;+rows+&quot;s%2$s%n&quot;,i&lt;rows?&quot;*&quot;.repeat(i+1):i&lt;rows+1?&quot;|&quot;:&quot;_&quot;,i&lt;rows?&quot;*&quot;.repeat(i):&quot;&quot;)).collect(Collectors.joining());\n</code></pre>\n<p>Given <code>rows=4</code> the string <code>christmasTree</code> will be:</p>\n<pre><code> *\n ***\n *****\n*******\n |\n _\n</code></pre>\n<p>This is a simplified version with a regular for-loop:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public static String christmasTree(int rows) {\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i &lt; rows; i++) {\n sb.append(String.format(&quot;%1$&quot; + rows + &quot;s%2$s%n&quot;, &quot;*&quot;.repeat(i + 1), &quot;*&quot;.repeat(i)));\n }\n sb.append(String.format(&quot;%1$&quot; + rows + &quot;s%n&quot;, &quot;|&quot;));\n sb.append(String.format(&quot;%1$&quot; + rows + &quot;s&quot;, &quot;_&quot;));\n return sb.toString();\n}\n</code></pre>\n<h2>Explanation</h2>\n<p>The key methods are <code>.repeat()</code> (as @Doi9t suggested) and <code>String.format</code>.</p>\n<p>Regarding the line in the for-loop, the parameters of <code>String.format()</code> are described below:</p>\n<ul>\n<li><code>%1$</code> means take the first argument, which is <code>&quot;*&quot;.repeat(i + 1)</code></li>\n<li><code>%2$</code> means take the second argument, which is <code>&quot;*&quot;.repeat(i)</code></li>\n<li><code>s</code> means convert the argument to a <code>String</code></li>\n<li><code>%1$&quot; + rows + &quot;s</code> pads the first string argument to <code>rows</code> characters</li>\n<li><code>%n</code> represents the line terminator</li>\n</ul>\n<p>More about <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax\" rel=\"nofollow noreferrer\">String.format</a> (which uses a <code>java.util.Formatter</code>).</p>\n<p>This is a version with a configurable ornament:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public static String christmasTree(int rows, Ornament ornament) {\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i &lt; rows; i++) {\n sb.append(String.format(&quot;%1$&quot; + rows + &quot;s%2$s%n&quot;, ornament.getValue().repeat(i + 1), ornament.getValue().repeat(i)));\n }\n sb.append(String.format(&quot;%1$&quot; + rows + &quot;s%n&quot;, &quot;|&quot;));\n sb.append(String.format(&quot;%1$&quot; + rows + &quot;s&quot;, &quot;_&quot;));\n return sb.toString();\n}\n</code></pre>\n<p>The <code>Ornament</code> enum:</p>\n<pre><code>public enum Ornament{\n BULBS(&quot;o&quot;),\n STARS(&quot;*&quot;);\n \n private String value;\n \n Ornament(String value){\n this.value=value;\n }\n \n public String getValue() {\n return this.value;\n }\n}\n</code></pre>\n<p>Merry Christmas in advance <code>System.out.println(christmasTree(10,Ornament.BULBS))</code></p>\n<pre><code> o\n ooo\n ooooo\n ooooooo\n ooooooooo\n ooooooooooo\n ooooooooooooo\n ooooooooooooooo\n ooooooooooooooooo\nooooooooooooooooooo\n |\n _\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T20:20:31.933", "Id": "245976", "ParentId": "245954", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T08:15:51.060", "Id": "245954", "Score": "6", "Tags": [ "java", "beginner" ], "Title": "Print a christmas tree" }
245954
<p>I have a macro created by my predecessor that I run on a monthly basis. However, it does take a while to get through, and I would like to clean it up for efficiency please.</p> <p>It copies data from multiple Workbooks:</p> <p><code>Wholesale\Reporting\Market6 Scorecard\Templates\52 Wk Data.csv</code></p> <p><code>Wholesale\Reporting\Market6 Scorecard\Templates\26 Wk Data.csv</code></p> <p>etc..</p> <p>and pastes to the Destination Worksheet: <code>Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;COMBINED&quot;)</code></p> <p>Here is the macro, and I keep thinking there are duplicate variables. But maybe there's a reason that I don't understand yet. Thoughts?</p> <pre><code>Sub DataPaste() 'Turn Off Screen Updates Application.ScreenUpdating = False Application.DisplayAlerts = False Application.Calculation = xlCalculationManual 'Weekly Division Tab: 'Open Weekly Data Workbook Workbooks.Open &quot;O:\Wholesale\Reporting\Market6 Scorecard\Templates\Weekly Data.csv&quot; 'Remove Current Data Dim aDataPaste As Worksheet Set aDataPaste = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;Weekly Division&quot;) Dim TemplateLastRow As Long TemplateLastRow = aDataPaste.Cells(aDataPaste.Rows.Count, &quot;B&quot;).End(xlUp).Offset(1).Row Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;Weekly Division&quot;).Range(&quot;A1:A12&quot;).ClearContents Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;Weekly Division&quot;).Range(&quot;A15:Z&quot; &amp; TemplateLastRow).ClearContents 'Copy Title Information Workbooks(&quot;Weekly Data.csv&quot;).Worksheets(&quot;Weekly Data&quot;).Range(&quot;A1:A12&quot;).Copy Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;Weekly Division&quot;).Range(&quot;A1:A12&quot;) 'Copy data Dim aTemplate As Worksheet Dim DataLastRow As Long Set aTemplate = Workbooks(&quot;Weekly Data.csv&quot;).Worksheets(&quot;Weekly Data&quot;) DataLastRow = aTemplate.Cells(aTemplate.Rows.Count, &quot;B&quot;).End(xlUp).Offset(1).Row Workbooks(&quot;Weekly Data.csv&quot;).Worksheets(&quot;Weekly Data&quot;).Range(&quot;A17:I&quot; &amp; DataLastRow).Copy Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;Weekly Division&quot;).Range(&quot;A15:I&quot; &amp; DataLastRow) Workbooks(&quot;Weekly Data.csv&quot;).Worksheets(&quot;Weekly Data&quot;).Range(&quot;J17:N&quot; &amp; DataLastRow).Copy Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;Weekly Division&quot;).Range(&quot;L15:P&quot; &amp; DataLastRow) Workbooks(&quot;Weekly Data.csv&quot;).Worksheets(&quot;Weekly Data&quot;).Range(&quot;O17:P&quot; &amp; DataLastRow).Copy Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;Weekly Division&quot;).Range(&quot;V15:W&quot; &amp; DataLastRow) 'Close Weekly Data Workbook Workbooks(&quot;Weekly Data.csv&quot;).Close SaveChanges:=False 'Combined Tab: 'Remove Current Data Dim bDataPaste As Worksheet Set bDataPaste = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;COMBINED&quot;) Dim bTemplateLastRow As Long bTemplateLastRow = bDataPaste.Cells(bDataPaste.Rows.Count, &quot;B&quot;).End(xlUp).Offset(1).Row Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;COMBINED&quot;).Range(&quot;A5:U&quot; &amp; bTemplateLastRow).ClearContents 'Copy 52 Wk Data Workbooks.Open &quot;O:\Wholesale\Reporting\Market6 Scorecard\Templates\52 Wk Data.csv&quot; Dim cWkData As Worksheet Dim cDataPaste As Worksheet Set cWkData = Workbooks(&quot;52 Wk Data.csv&quot;).Worksheets(&quot;52 Wk Data&quot;) Set cDataPaste = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;COMBINED&quot;) Dim cTemplateLastRow As Long Dim cCopyLastRow As Long cTemplateLastRow = cDataPaste.Cells(cDataPaste.Rows.Count, &quot;B&quot;).End(xlUp).Offset(1).Row cCopyLastRow = cWkData.Cells(cWkData.Rows.Count, &quot;A&quot;).End(xlUp).Row cWkData.Range(&quot;A18:H&quot; &amp; cCopyLastRow).Copy cDataPaste.Range(&quot;B5:I&quot; &amp; bTemplateLastRow) cWkData.Range(&quot;I18:R&quot; &amp; cCopyLastRow).Copy cDataPaste.Range(&quot;L5:U&quot; &amp; cTemplateLastRow) 'Add Dates Dim cTemplateLastRowb As Long Dim cTemplateLastRowc As Long cTemplateLastRowb = cDataPaste.Cells(cDataPaste.Rows.Count, &quot;B&quot;).End(xlUp).Row cTemplateLastRowc = cDataPaste.Cells(cDataPaste.Rows.Count, &quot;B&quot;).End(xlUp).Offset(1).Row Dim cFirstRow As Range Dim cLastRow As Range Set cFirstRow = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;COMBINED&quot;).Range(&quot;A5&quot;) Set cLastRow = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;COMBINED&quot;).Range(&quot;A&quot; &amp; cTemplateLastRowb) Range(cFirstRow, cLastRow).Formula = &quot;=concatenate(&quot;&quot;Latest 52 Wks - Ending &quot;&quot;,left(right('Weekly Division'!$A$4,24),23))&quot; Workbooks(&quot;52 Wk Data.csv&quot;).Close SaveChanges:=False 'Copy 26 Wk Data Workbooks.Open &quot;O:\Wholesale\Reporting\Market6 Scorecard\Templates\26 Wk Data.csv&quot; Dim dWkData As Worksheet Dim dDataPaste As Worksheet Set dWkData = Workbooks(&quot;26 Wk Data.csv&quot;).Worksheets(&quot;26 Wk Data&quot;) Set dDataPaste = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;COMBINED&quot;) Dim dTemplateLastRow As Long Dim dCopyLastRow As Long dTemplateLastRow = dDataPaste.Cells(dDataPaste.Rows.Count, &quot;B&quot;).End(xlUp).Offset(1).Row dCopyLastRow = dWkData.Cells(dWkData.Rows.Count, &quot;A&quot;).End(xlUp).Row dWkData.Range(&quot;A18:H&quot; &amp; dCopyLastRow).Copy dDataPaste.Range(&quot;B&quot; &amp; dTemplateLastRow) dWkData.Range(&quot;I18:R&quot; &amp; dCopyLastRow).Copy dDataPaste.Range(&quot;L&quot; &amp; dTemplateLastRow) 'Add Dates Dim dTemplateLastRowb As Long Dim dTemplateLastRowc As Long dTemplateLastRowb = dDataPaste.Cells(dDataPaste.Rows.Count, &quot;B&quot;).End(xlUp).Row dTemplateLastRowc = dDataPaste.Cells(dDataPaste.Rows.Count, &quot;B&quot;).End(xlUp).Offset(1).Row Dim dFirstRow As Range Dim dLastRow As Range Set dFirstRow = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;COMBINED&quot;).Range(&quot;A&quot; &amp; cTemplateLastRowc) Set dLastRow = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;COMBINED&quot;).Range(&quot;A&quot; &amp; dTemplateLastRowb) Range(dFirstRow, dLastRow).Formula = &quot;=concatenate(&quot;&quot;Latest 26 Wks - Ending &quot;&quot;,left(right('Weekly Division'!$A$4,24),23))&quot; Workbooks(&quot;26 Wk Data.csv&quot;).Close SaveChanges:=False 'Copy 13 Wk Data Workbooks.Open &quot;O:\Wholesale\Reporting\Market6 Scorecard\Templates\13 Wk Data.csv&quot; Dim eWkData As Worksheet Dim eDataPaste As Worksheet Set eWkData = Workbooks(&quot;13 Wk Data.csv&quot;).Worksheets(&quot;13 Wk Data&quot;) Set eDataPaste = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;COMBINED&quot;) Dim eTemplateLastRow As Long Dim eCopyLastRow As Long eTemplateLastRow = eDataPaste.Cells(eDataPaste.Rows.Count, &quot;B&quot;).End(xlUp).Offset(1).Row eCopyLastRow = eWkData.Cells(eWkData.Rows.Count, &quot;A&quot;).End(xlUp).Row eWkData.Range(&quot;A18:H&quot; &amp; eCopyLastRow).Copy eDataPaste.Range(&quot;B&quot; &amp; eTemplateLastRow) eWkData.Range(&quot;I18:R&quot; &amp; eCopyLastRow).Copy eDataPaste.Range(&quot;L&quot; &amp; eTemplateLastRow) 'Add Dates Dim eTemplateLastRowb As Long Dim eTemplateLastRowc As Long eTemplateLastRowb = eDataPaste.Cells(eDataPaste.Rows.Count, &quot;B&quot;).End(xlUp).Row eTemplateLastRowc = eDataPaste.Cells(eDataPaste.Rows.Count, &quot;B&quot;).End(xlUp).Offset(1).Row Dim eFirstRow As Range Dim eLastRow As Range Set eFirstRow = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;COMBINED&quot;).Range(&quot;A&quot; &amp; dTemplateLastRowc) Set eLastRow = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;COMBINED&quot;).Range(&quot;A&quot; &amp; eTemplateLastRowb) Range(eFirstRow, eLastRow).Formula = &quot;=concatenate(&quot;&quot;Latest 13 Wks - Ending &quot;&quot;,left(right('Weekly Division'!$A$4,24),23))&quot; Workbooks(&quot;13 Wk Data.csv&quot;).Close SaveChanges:=False 'Copy 4 Wk Data Workbooks.Open &quot;O:\Wholesale\Reporting\Market6 Scorecard\Templates\4 Wk Data.csv&quot; Dim fWkData As Worksheet Dim fDataPaste As Worksheet Set fWkData = Workbooks(&quot;4 Wk Data.csv&quot;).Worksheets(&quot;4 Wk Data&quot;) Set fDataPaste = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;COMBINED&quot;) Dim fTemplateLastRow As Long Dim fCopyLastRow As Long fTemplateLastRow = fDataPaste.Cells(fDataPaste.Rows.Count, &quot;B&quot;).End(xlUp).Offset(1).Row fCopyLastRow = fWkData.Cells(fWkData.Rows.Count, &quot;A&quot;).End(xlUp).Row fWkData.Range(&quot;A18:H&quot; &amp; fCopyLastRow).Copy fDataPaste.Range(&quot;B&quot; &amp; fTemplateLastRow) fWkData.Range(&quot;I18:R&quot; &amp; fCopyLastRow).Copy fDataPaste.Range(&quot;L&quot; &amp; fTemplateLastRow) 'Add Dates Dim fTemplateLastRowb As Long Dim fTemplateLastRowc As Long fTemplateLastRowb = fDataPaste.Cells(fDataPaste.Rows.Count, &quot;B&quot;).End(xlUp).Row fTemplateLastRowc = fDataPaste.Cells(fDataPaste.Rows.Count, &quot;B&quot;).End(xlUp).Offset(1).Row Dim fFirstRow As Range Dim fLastRow As Range Set fFirstRow = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;COMBINED&quot;).Range(&quot;A&quot; &amp; eTemplateLastRowc) Set fLastRow = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;COMBINED&quot;).Range(&quot;A&quot; &amp; fTemplateLastRowb) Range(fFirstRow, fLastRow).Formula = &quot;=concatenate(&quot;&quot;Latest 04 Wks - Ending &quot;&quot;,left(right('Weekly Division'!$A$4,24),23))&quot; Workbooks(&quot;4 Wk Data.csv&quot;).Close SaveChanges:=False 'Copy YTD Data Workbooks.Open &quot;O:\Wholesale\Reporting\Market6 Scorecard\Templates\YTD Data.csv&quot; Dim gWkData As Worksheet Dim gDataPaste As Worksheet Set gWkData = Workbooks(&quot;YTD Data.csv&quot;).Worksheets(&quot;YTD Data&quot;) Set gDataPaste = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;COMBINED&quot;) Dim gTemplateLastRow As Long Dim gCopyLastRow As Long gTemplateLastRow = gDataPaste.Cells(gDataPaste.Rows.Count, &quot;B&quot;).End(xlUp).Offset(1).Row gCopyLastRow = gWkData.Cells(gWkData.Rows.Count, &quot;A&quot;).End(xlUp).Row gWkData.Range(&quot;A18:H&quot; &amp; gCopyLastRow).Copy gDataPaste.Range(&quot;B&quot; &amp; gTemplateLastRow) gWkData.Range(&quot;I18:R&quot; &amp; gCopyLastRow).Copy gDataPaste.Range(&quot;L&quot; &amp; gTemplateLastRow) 'Add Dates Dim gTemplateLastRowb As Long Dim gTemplateLastRowc As Long gTemplateLastRowb = gDataPaste.Cells(gDataPaste.Rows.Count, &quot;B&quot;).End(xlUp).Row gTemplateLastRowc = gDataPaste.Cells(gDataPaste.Rows.Count, &quot;B&quot;).End(xlUp).Offset(1).Row Dim gFirstRow As Range Dim gLastRow As Range Set gFirstRow = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;COMBINED&quot;).Range(&quot;A&quot; &amp; fTemplateLastRowc) Set gLastRow = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;COMBINED&quot;).Range(&quot;A&quot; &amp; gTemplateLastRowb) Range(gFirstRow, gLastRow).Formula = &quot;=concatenate(&quot;&quot;Kroger YTD - Ending &quot;&quot;,left(right('Weekly Division'!$A$4,24),23))&quot; Workbooks(&quot;YTD Data.csv&quot;).Close SaveChanges:=False 'Stores Selling Summary Tab: 'Remove Current Data Dim hDataPaste As Worksheet Set hDataPaste = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;stores selling summary&quot;) Dim hTemplateLastRow As Long hTemplateLastRow = hDataPaste.Cells(hDataPaste.Rows.Count, &quot;B&quot;).End(xlUp).Offset(1).Row Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;stores selling summary&quot;).Range(&quot;A6:N&quot; &amp; hTemplateLastRow).ClearContents 'Copy 52 Wk Data Workbooks.Open &quot;O:\Wholesale\Reporting\Market6 Scorecard\Templates\Stores Selling 52 Wks.csv&quot; Dim iStrData As Worksheet Dim iDataPaste As Worksheet Set iStrData = Workbooks(&quot;Stores Selling 52 Wks.csv&quot;).Worksheets(&quot;Stores Selling 52 Wks&quot;) Set iDataPaste = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;stores selling summary&quot;) Dim iTemplateLastRow As Long Dim iCopyLastRow As Long iTemplateLastRow = iDataPaste.Cells(iDataPaste.Rows.Count, &quot;B&quot;).End(xlUp).Offset(1).Row iCopyLastRow = iStrData.Cells(iStrData.Rows.Count, &quot;A&quot;).End(xlUp).Row iStrData.Range(&quot;A13:B&quot; &amp; iCopyLastRow).Copy iDataPaste.Range(&quot;B6:C&quot; &amp; iTemplateLastRow) iStrData.Range(&quot;C13:C&quot; &amp; iCopyLastRow).Copy iDataPaste.Range(&quot;G6:G&quot; &amp; iTemplateLastRow) iStrData.Range(&quot;F13:I&quot; &amp; iCopyLastRow).Copy iDataPaste.Range(&quot;I6:L&quot; &amp; iTemplateLastRow) iStrData.Range(&quot;D13:E&quot; &amp; iCopyLastRow).Copy iDataPaste.Range(&quot;M6:N&quot; &amp; iTemplateLastRow) 'Add Dates Dim iTemplateLastRowb As Long Dim iTemplateLastRowc As Long iTemplateLastRowb = iDataPaste.Cells(iDataPaste.Rows.Count, &quot;B&quot;).End(xlUp).Row iTemplateLastRowc = iDataPaste.Cells(iDataPaste.Rows.Count, &quot;B&quot;).End(xlUp).Offset(1).Row Dim iFirstRow As Range Dim iLastRow As Range Set iFirstRow = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;stores selling summary&quot;).Range(&quot;A6&quot;) Set iLastRow = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;stores selling summary&quot;).Range(&quot;A&quot; &amp; iTemplateLastRowb) Range(iFirstRow, iLastRow).Formula = &quot;=concatenate(&quot;&quot;Latest 52 Wks - Ending &quot;&quot;,left(right('Weekly Division'!$A$4,24),23))&quot; Workbooks(&quot;Stores Selling 52 Wks.csv&quot;).Close SaveChanges:=False 'Copy 26 Wk Data Workbooks.Open &quot;O:\Wholesale\Reporting\Market6 Scorecard\Templates\Stores Selling 26 Wks.csv&quot; Dim jStrData As Worksheet Dim jDataPaste As Worksheet Set jStrData = Workbooks(&quot;Stores Selling 26 Wks.csv&quot;).Worksheets(&quot;Stores Selling 26 Wks&quot;) Set jDataPaste = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;stores selling summary&quot;) Dim jTemplateLastRow As Long Dim jCopyLastRow As Long jTemplateLastRow = jDataPaste.Cells(jDataPaste.Rows.Count, &quot;B&quot;).End(xlUp).Offset(1).Row jCopyLastRow = jStrData.Cells(jStrData.Rows.Count, &quot;A&quot;).End(xlUp).Row jStrData.Range(&quot;A13:B&quot; &amp; jCopyLastRow).Copy jDataPaste.Range(&quot;B&quot; &amp; jTemplateLastRow) jStrData.Range(&quot;C13:C&quot; &amp; jCopyLastRow).Copy jDataPaste.Range(&quot;G&quot; &amp; jTemplateLastRow) jStrData.Range(&quot;F13:I&quot; &amp; jCopyLastRow).Copy jDataPaste.Range(&quot;I&quot; &amp; jTemplateLastRow) jStrData.Range(&quot;D13:E&quot; &amp; jCopyLastRow).Copy jDataPaste.Range(&quot;M&quot; &amp; jTemplateLastRow) 'Add Dates Dim jTemplateLastRowb As Long Dim jTemplateLastRowc As Long jTemplateLastRowb = jDataPaste.Cells(jDataPaste.Rows.Count, &quot;B&quot;).End(xlUp).Row jTemplateLastRowc = jDataPaste.Cells(jDataPaste.Rows.Count, &quot;B&quot;).End(xlUp).Offset(1).Row Dim jFirstRow As Range Dim jLastRow As Range Set jFirstRow = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;stores selling summary&quot;).Range(&quot;A&quot; &amp; iTemplateLastRowc) Set jLastRow = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;stores selling summary&quot;).Range(&quot;A&quot; &amp; jTemplateLastRowb) Range(jFirstRow, jLastRow).Formula = &quot;=concatenate(&quot;&quot;Latest 26 Wks - Ending &quot;&quot;,left(right('Weekly Division'!$A$4,24),23))&quot; Workbooks(&quot;Stores Selling 26 Wks.csv&quot;).Close SaveChanges:=False 'Copy 13 Wk Data Workbooks.Open &quot;O:\Wholesale\Reporting\Market6 Scorecard\Templates\Stores Selling 13 Wks.csv&quot; Dim kStrData As Worksheet Dim kDataPaste As Worksheet Set kStrData = Workbooks(&quot;Stores Selling 13 Wks.csv&quot;).Worksheets(&quot;Stores Selling 13 Wks&quot;) Set kDataPaste = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;stores selling summary&quot;) Dim kTemplateLastRow As Long Dim kCopyLastRow As Long kTemplateLastRow = kDataPaste.Cells(kDataPaste.Rows.Count, &quot;B&quot;).End(xlUp).Offset(1).Row kCopyLastRow = kStrData.Cells(kStrData.Rows.Count, &quot;A&quot;).End(xlUp).Row kStrData.Range(&quot;A13:B&quot; &amp; kCopyLastRow).Copy kDataPaste.Range(&quot;B&quot; &amp; kTemplateLastRow) kStrData.Range(&quot;C13:C&quot; &amp; kCopyLastRow).Copy kDataPaste.Range(&quot;G&quot; &amp; kTemplateLastRow) kStrData.Range(&quot;F13:I&quot; &amp; kCopyLastRow).Copy kDataPaste.Range(&quot;I&quot; &amp; kTemplateLastRow) kStrData.Range(&quot;D13:E&quot; &amp; kCopyLastRow).Copy kDataPaste.Range(&quot;M&quot; &amp; kTemplateLastRow) 'Add Dates Dim kTemplateLastRowb As Long Dim kTemplateLastRowc As Long kTemplateLastRowb = kDataPaste.Cells(kDataPaste.Rows.Count, &quot;B&quot;).End(xlUp).Row kTemplateLastRowc = kDataPaste.Cells(kDataPaste.Rows.Count, &quot;B&quot;).End(xlUp).Offset(1).Row Dim kFirstRow As Range Dim kLastRow As Range Set kFirstRow = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;stores selling summary&quot;).Range(&quot;A&quot; &amp; jTemplateLastRowc) Set kLastRow = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;stores selling summary&quot;).Range(&quot;A&quot; &amp; kTemplateLastRowb) Range(kFirstRow, kLastRow).Formula = &quot;=concatenate(&quot;&quot;Latest 13 Wks - Ending &quot;&quot;,left(right('Weekly Division'!$A$4,24),23))&quot; Workbooks(&quot;Stores Selling 13 Wks.csv&quot;).Close SaveChanges:=False 'Copy 4 Wk Data Workbooks.Open &quot;O:\Wholesale\Reporting\Market6 Scorecard\Templates\Stores Selling 4 Wks.csv&quot; Dim lStrData As Worksheet Dim lDataPaste As Worksheet Set lStrData = Workbooks(&quot;Stores Selling 4 Wks.csv&quot;).Worksheets(&quot;Stores Selling 4 Wks&quot;) Set lDataPaste = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;stores selling summary&quot;) Dim lTemplateLastRow As Long Dim lCopyLastRow As Long lTemplateLastRow = lDataPaste.Cells(lDataPaste.Rows.Count, &quot;B&quot;).End(xlUp).Offset(1).Row lCopyLastRow = lStrData.Cells(lStrData.Rows.Count, &quot;A&quot;).End(xlUp).Row lStrData.Range(&quot;A13:B&quot; &amp; lCopyLastRow).Copy lDataPaste.Range(&quot;B&quot; &amp; lTemplateLastRow) lStrData.Range(&quot;C13:C&quot; &amp; lCopyLastRow).Copy lDataPaste.Range(&quot;G&quot; &amp; lTemplateLastRow) lStrData.Range(&quot;F13:I&quot; &amp; lCopyLastRow).Copy lDataPaste.Range(&quot;I&quot; &amp; lTemplateLastRow) lStrData.Range(&quot;D13:E&quot; &amp; lCopyLastRow).Copy lDataPaste.Range(&quot;M&quot; &amp; lTemplateLastRow) 'Add Dates Dim lTemplateLastRowb As Long Dim lTemplateLastRowc As Long lTemplateLastRowb = lDataPaste.Cells(lDataPaste.Rows.Count, &quot;B&quot;).End(xlUp).Row lTemplateLastRowc = lDataPaste.Cells(lDataPaste.Rows.Count, &quot;B&quot;).End(xlUp).Offset(1).Row Dim lFirstRow As Range Dim lLastRow As Range Set lFirstRow = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;stores selling summary&quot;).Range(&quot;A&quot; &amp; kTemplateLastRowc) Set lLastRow = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;stores selling summary&quot;).Range(&quot;A&quot; &amp; lTemplateLastRowb) Range(lFirstRow, lLastRow).Formula = &quot;=concatenate(&quot;&quot;Latest 04 Wks - Ending &quot;&quot;,left(right('Weekly Division'!$A$4,24),23))&quot; Workbooks(&quot;Stores Selling 4 Wks.csv&quot;).Close SaveChanges:=False 'Copy YTD Data Workbooks.Open &quot;O:\Wholesale\Reporting\Market6 Scorecard\Templates\Stores Selling YTD.csv&quot; Dim mStrData As Worksheet Dim mDataPaste As Worksheet Set mStrData = Workbooks(&quot;Stores Selling YTD.csv&quot;).Worksheets(&quot;Stores Selling YTD&quot;) Set mDataPaste = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;stores selling summary&quot;) Dim mTemplateLastRow As Long Dim mCopyLastRow As Long mTemplateLastRow = mDataPaste.Cells(mDataPaste.Rows.Count, &quot;B&quot;).End(xlUp).Offset(1).Row mCopyLastRow = mStrData.Cells(mStrData.Rows.Count, &quot;A&quot;).End(xlUp).Row mStrData.Range(&quot;A13:B&quot; &amp; mCopyLastRow).Copy mDataPaste.Range(&quot;B&quot; &amp; mTemplateLastRow) mStrData.Range(&quot;C13:C&quot; &amp; mCopyLastRow).Copy mDataPaste.Range(&quot;G&quot; &amp; mTemplateLastRow) mStrData.Range(&quot;F13:I&quot; &amp; mCopyLastRow).Copy mDataPaste.Range(&quot;I&quot; &amp; mTemplateLastRow) mStrData.Range(&quot;D13:E&quot; &amp; mCopyLastRow).Copy mDataPaste.Range(&quot;M&quot; &amp; mTemplateLastRow) 'Add Dates Dim mTemplateLastRowb As Long Dim mTemplateLastRowc As Long mTemplateLastRowb = mDataPaste.Cells(mDataPaste.Rows.Count, &quot;B&quot;).End(xlUp).Row mTemplateLastRowc = mDataPaste.Cells(mDataPaste.Rows.Count, &quot;B&quot;).End(xlUp).Offset(1).Row Dim mFirstRow As Range Dim mLastRow As Range Set mFirstRow = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;stores selling summary&quot;).Range(&quot;A&quot; &amp; lTemplateLastRowc) Set mLastRow = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;stores selling summary&quot;).Range(&quot;A&quot; &amp; mTemplateLastRowb) Range(mFirstRow, mLastRow).Formula = &quot;=concatenate(&quot;&quot;Kroger YTD - Ending &quot;&quot;,left(right('Weekly Division'!$A$4,24),23))&quot; 'Add Attributes where possible Dim nFirstRow As Range Dim nLastRow As Range Set nFirstRow = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;stores selling summary&quot;).Range(&quot;D6&quot;) Set nLastRow = Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;stores selling summary&quot;).Range(&quot;F&quot; &amp; mTemplateLastRowb) Range(nFirstRow, nLastRow).Formula = &quot;=INDEX(COMBINED!$C:$F,MATCH($C6,COMBINED!$H:$H,0),MATCH(D$5,COMBINED!$C$4:$F$4,0))&quot; Workbooks(&quot;Stores Selling YTD.csv&quot;).Close SaveChanges:=False 'Calculate Workbook Calculate 'Paste Values Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;COMBINED&quot;).Range(&quot;A5:U&quot; &amp; gTemplateLastRowb).Copy Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;COMBINED&quot;).Range(&quot;A5:U&quot; &amp; gTemplateLastRowb).PasteSpecial Paste:=xlPasteValues Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;stores selling summary&quot;).Range(&quot;A5:N&quot; &amp; mTemplateLastRowb).Copy Workbooks(&quot;KROGER M6 SCORECARD TEMPLATE.xlsm&quot;).Worksheets(&quot;stores selling summary&quot;).Range(&quot;A5:N&quot; &amp; mTemplateLastRowb).PasteSpecial Paste:=xlPasteValues Application.CutCopyMode = False 'Save File as Template File ActiveWorkbook.Save 'Turn on Screen Updates Application.ScreenUpdating = True Application.DisplayAlerts = True Application.Calculation = xlCalculationAutomatic End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T13:37:23.073", "Id": "483204", "Score": "6", "body": "Welcome to CR! Does the actual complete code not fit in? Curious what `'Etc...` stands for - you'll get much better & thorough feedback if you include the whole module, including any `Option` and module-level declarations =)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T13:53:34.643", "Id": "483209", "Score": "6", "body": "Also, as noted in the [help] on \"asking\", please [edit] the title to give a brief summary of what the code does, not your goal in the code review (after all, everybody wants to \"simplify\" code or \"make it run faster\", those would be the title of nearly _every_ question here and _that_ would be confusing!). It's in the body of the question that you describe the improvements you're looking for. Also, as noted above, please give us _complete_, working routine(s) - it's very difficult to review bits and pieces." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-29T13:14:29.157", "Id": "483655", "Score": "0", "body": "@MathieuGuindon Thank you for welcome! Sorry, I didn't know I could put the entire code in. It has been updated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-29T13:15:12.263", "Id": "483657", "Score": "0", "body": "@FreeMan Thank you for the feedback :) ... the Title and Code have been updated." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T13:08:25.570", "Id": "245957", "Score": "2", "Tags": [ "vba", "excel" ], "Title": "Copying Data from multiple workbooks -> Into One Worksheet (continuous data)" }
245957
<p>Aware that this is a very common exercise; but I'm getting a bit obsessed about creating a simple, clean-ui todo app, at least for myself.</p> <p>It's not quite finished yet, but I guess it will be much easier to review now than at the end, in case you look at the javascript code (react)</p> <p>I'm looking any simple advice, best practice or error in the javascript-react file, or in the css html too.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function H1(){ let hello = "Hi," let h1 = ( &lt;h1&gt; {hello} &lt;/h1&gt; ) return h1 } class Todos extends React.Component{ constructor(){ super() this.state={todos:[]} //todos will be an array of objects this.addTodo = this.addTodo.bind(this) this.toggleCompleted = this.toggleCompleted.bind(this) } addTodo(){ //press go -&gt; take input value let theValue = document.getElementById('input').value //push array w value and id this.setState(s =&gt; s.todos.push({id:s.todos.length, value:theValue, completed:false})) return 1 } toggleCompleted(e){ //toggle completed value in the state object let parentId = e.target.parentElement.id let completed = this.state.todos[parentId].completed if (completed){ this.setState(s =&gt; s.todos[parentId].completed=false) } else { this.setState(s =&gt; s.todos[parentId].completed=true) } } render() { let listOfTodos = "" if (this.state.todos !== []){ listOfTodos = this.state.todos.map(todo =&gt; &lt;TodoItem toggler={this.toggleCompleted} key={todo.id} thisItem={todo}/&gt;) } return ( &lt;div className="todos__area"&gt; &lt;div className="todos__events"&gt; &lt;input id='input' className="todos__input" placeholder="type here" type="text" /&gt; &lt;button onClick = {this.addTodo} className="todos__button"&gt;Go&lt;/button&gt; &lt;/div&gt; &lt;ul className="todos__list"&gt; {listOfTodos} &lt;/ul&gt; &lt;/div&gt; ) } } function TodoItem(props){ return (&lt;li id={props.thisItem.id}&gt; &lt;input onClick={props.toggler} className="checkbox" type='checkbox'/&gt; &lt;span style= {{textDecoration:props.thisItem.completed?"line-through":"none"}}&gt; {props.thisItem.value} &lt;/span&gt; &lt;/li&gt;) } function Footer(){ return ( &lt;footer&gt; &lt;ul className="footer__ul pointer"&gt; &lt;li&gt;Github&lt;/li&gt; &lt;li&gt;Reddit&lt;/li&gt; &lt;li&gt;FCC&lt;/li&gt; &lt;/ul&gt; &lt;/footer&gt; ) } function App(){ //render components return ( &lt;main&gt; &lt;H1 /&gt; &lt;Todos /&gt; &lt;Footer /&gt; &lt;/main&gt; ) } ReactDOM.render(&lt;App/&gt;, document.getElementById('root'))</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>* { padding: 0; margin: 0; box-sizing: border-box; } :root { --blue:#2c3251; } ul { list-style-type: none; } ul &gt; li { display: block; padding: 0.5rem; } .pointer &gt; li:hover { cursor: pointer; } body { font-family: "Ubuntu", sans-serif; text-align: left; background-color: white; background-image: radial-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.6)), url("./table.png"); background-repeat: repeat; padding: 2rem 2rem 0.1rem; } main { display: grid; min-height: auto; height: 100vh; width: 100%; } h1 { font-size: 1.8rem; color: var(--blue); box-shadow: inset 0px 2px 5px var(--blue); align-self: start; padding: 1.5rem; border-radius: 15px 15px 0 0; margin-bottom: 0.5rem; } .todos__area { box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.7), 1px 1px 5px rgba(0, 0, 0, 0.3); display: flex; flex-direction: column; max-height: 300px; } .todos__events { display: flex; flex-direction: row; flex: 0 1 40px; } .todos__events .todos__input { border: none; padding: 0.5rem; border-radius: 2px 0 0 2px; flex: 2 1 150px; } .todos__events .todos__button { border: none; padding: 10px; flex: 1 1 60px; color: white; font-weight: bold; cursor: pointer; max-width: 100px; position: relative; background-color: rgba(0, 0, 0, 0); } .todos__events .todos__button:after { z-index: -1; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-color: #2d7b57; opacity: 0.5; transition: opacity 0.3s ease-out; content: ""; } .todos__events .todos__button:hover:after { opacity: 0.7; } /* Inline #1 | http://localhost:3000/ */ .todos__list { font-family: "Dancing Script", "cursive"; font-size: 1.2rem; padding: 2rem; background-color: rgba(227, 227, 134, 0.58); flex: 1 1 200px; overflow: auto; } .todos__list input[type=checkbox] { margin-right: 0.6rem; } footer { background-color: rgba(0, 0, 0, 0.1); align-self: end; margin-top: 0.5rem; } .footer__ul { display: flex; justify-content: center; color: var(--blue); font-weight: bold; } .footer__ul &gt; li { padding: 1rem; box-shadow: 1px 0px 1px var(--blue); transition: transform 0.1s ease-out; } .footer__ul &gt; li:hover { transform: scaleX(1.05); } @media screen and (min-width: 700px) { body { max-width: 700px; margin: auto; } } /*# sourceMappingURL=index.css.map */</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"&gt;&lt;/script&gt; &lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;link href="https://fonts.googleapis.com/css2?family=Dancing+Script&amp;family=Ubuntu&amp;display=swap" rel="stylesheet"&gt; &lt;head&gt; &lt;meta charset="utf-8" /&gt; &lt;title&gt;React App: todoist&lt;/title&gt; &lt;/head&gt; &lt;body &gt; &lt;div id="root"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>A few things yet to add:</p> <ul> <li>&quot;delete button&quot;</li> <li>&quot;done&quot; button (and probably remove the checkbox)</li> <li>color scheme and welcome message (&quot;Hi&quot;) changing with the time of the day.</li> <li>the &quot;go&quot; button, should work by hitting enter/return too. I'm not sure how to do that so far.</li> </ul> <p>Hope you like :-)</p>
[]
[ { "body": "<p>You've several issues with state mutation, which is a major anti-pattern in react, poor variable declarations, and other sub-optimal coding style.</p>\n<h3><code>constructor</code></h3>\n<ol>\n<li>The constructor is missing props (and passing them to <code>super</code>). It doesn't appear that currently any props are passed to <code>Todos</code>, but should this ever change it could cause issue later on down the road. Better to just assume <em>some</em> props can be passed.</li>\n</ol>\n<p>updates</p>\n<pre><code>constructor(props) {\n super(props);\n this.state={\n todos: [],\n };\n ...\n}\n</code></pre>\n<h3><code>addToDo</code></h3>\n<pre><code>addTodo(){\n //press go -&gt; take input value\n let theValue = document.getElementById('input').value;\n\n //push array w value and id\n this.setState(s =&gt; s.todos.push({id:s.todos.length, value: theValue, completed:false}));\n\n return 1;\n}\n</code></pre>\n<ol>\n<li><code>theValue</code> never changes so it should be declared const.</li>\n<li>Pushing into an array mutates the existing array <em><strong>and</strong></em> returns\nthe new length, so not only did this mutate existing state, it updated it to no longer be an array. Use a correct functional state update that shallowly copies previous state.</li>\n<li><code>addToDo</code> is used as an <code>onClick</code> handler, so the return is meaningless.</li>\n<li><code>document.getElementById</code> is generally also considered an anti-pattern. Using a ref is the more &quot;react way&quot; of getting the value</li>\n</ol>\n<p><em><strong>User Experience (UX):</strong> After finishing a code review I ran your code snippet and noticed the input doesn't clear after being added. Just a suggestion here, but maybe clear out the input field upon adding a todo item.</em></p>\n<p>updates</p>\n<pre><code>constructor() {\n super();\n ...\n\n this.inputRef = React.createRef(); // &lt;-- create input ref\n ...\n}\n\naddTodo(){\n // press go -&gt; take input value\n const { value } = this.inputRef.current;\n\n // shallow copy existing state and append new value\n this.setState(({ todos }) =&gt; ({\n todos: [...todos, { id: todos.length, value, completed: false }],\n }));\n\n // Suggestion to clear input\n this.inputRef.current.value = '';\n}\n\n...\n&lt;input\n ref={this.inputRef} // &lt;-- attach inputRef to input\n id='input'\n className=&quot;todos__input&quot;\n placeholder=&quot;type here&quot;\n type=&quot;text&quot;\n/&gt;\n...\n</code></pre>\n<h3><code>toggleCompleted</code></h3>\n<pre><code>toggleCompleted(e){\n //toggle completed value in the state object\n let parentId = e.target.parentElement.id\n let completed = this.state.todos[parentId].completed\n if (completed){ \n this.setState(s =&gt; s.todos[parentId].completed=false)\n } else {\n this.setState(s =&gt; s.todos[parentId].completed=true)\n }\n}\n</code></pre>\n<ol>\n<li>Variables <code>parentId</code> and <code>completed</code> don't change, so should also be declared const.</li>\n<li>Similar issue with state mutation. You still need to shallowly copy the existing state and update the element by index/id.</li>\n<li>The two logic branches of <code>if (completed)</code> are nearly identical, a more DRY approach would be to do the branching at the value, i.e. using a ternary, or even better, just simply toggle the boolean value, like the function's name suggests.</li>\n<li>Get the id of the target element of the event object (<em>more on this later</em>)</li>\n</ol>\n<p>updates</p>\n<pre><code>toggleCompleted(e){\n // toggle completed value in the state object\n const { id } = e.target;\n\n this.setState(({ todos }) =&gt; ({\n todos: todos.map(todo =&gt; todo.id === Number(id) ? { // &lt;-- id is string\n ...todo,\n completed: !todo.completed,\n } : todo),\n }));\n}\n</code></pre>\n<h3><code>render</code></h3>\n<ol>\n<li>So long as <code>this.state.todos</code> is an array, the map function can correctly handle an empty array, no need really to test that it isn't equal to an empty array (<code>[]</code>), but if there is concern it is more common to conditionally render with a check on the length, i.e. <code>this.state.todos.length &amp;&amp; this.state.todos.map(...</code>.</li>\n</ol>\n<p>updates</p>\n<pre><code>render() {\n return (\n &lt;div className=&quot;todos__area&quot;&gt;\n &lt;div className=&quot;todos__events&quot;&gt;\n &lt;input ref={this.inputRef} id='input' className=&quot;todos__input&quot; placeholder=&quot;type here&quot; type=&quot;text&quot; /&gt;\n &lt;button onClick={this.addTodo} className=&quot;todos__button&quot;&gt;Go&lt;/button&gt;\n &lt;/div&gt;\n &lt;ul className=&quot;todos__list&quot;&gt;\n {this.state.todos.map(todo =&gt; (\n &lt;TodoItem\n key={todo.id}\n toggler={this.toggleCompleted}\n thisItem={todo}\n /&gt;\n ))}\n &lt;/ul&gt; \n &lt;/div&gt;\n )\n}\n</code></pre>\n<h3><code>TodoItem</code></h3>\n<ol>\n<li>The input checkbox should probably use the <code>onChange</code> handler versus an <code>onClick</code>, it's semantically more correct.</li>\n<li>Attach the <code>id</code> to the input instead of the parent node.</li>\n<li>Set the <code>checked</code> value of the input to the item completed status.</li>\n<li>Wrap the input and span in a label so it can be clicked on to toggle the completed state.</li>\n</ol>\n<p>updates</p>\n<pre><code>function TodoItem({ thisItem, toggler }){\n return (\n &lt;li&gt;\n &lt;label&gt;\n &lt;input\n id={thisItem.id}\n checked={thisItem.completed}\n className=&quot;checkbox&quot;\n onChange={toggler}\n type='checkbox'\n /&gt;\n &lt;span\n style={{\n textDecoration: thisItem.completed ? &quot;line-through&quot; : &quot;none&quot;\n }}\n &gt;\n {thisItem.value}\n &lt;/span&gt;\n &lt;/label&gt;\n &lt;/li&gt;\n ) \n}\n</code></pre>\n<h1>Running Demo</h1>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function H1() {\n let hello = \"Hi,\";\n let h1 = &lt;h1&gt; {hello} &lt;/h1&gt;;\n return h1;\n}\n\nclass Todos extends React.Component {\n constructor() {\n super();\n this.state = {\n todos: []\n };\n this.inputRef = React.createRef(); // &lt;-- create input ref\n //todos will be an array of objects\n this.addTodo = this.addTodo.bind(this);\n this.toggleCompleted = this.toggleCompleted.bind(this);\n }\n\n addTodo() {\n // press go -&gt; take input value\n const { value } = this.inputRef.current;\n\n // shallow copy existing state and append new value\n this.setState(({ todos }) =&gt; ({\n todos: [\n ...todos,\n {\n id: todos.length,\n value,\n completed: false\n }\n ]\n }));\n\n // Suggestion to clear input\n this.inputRef.current.value = \"\";\n }\n\n toggleCompleted(e) {\n // toggle completed value in the state object\n const { id } = e.target;\n\n this.setState(({ todos }) =&gt; ({\n todos: todos.map(todo =&gt;\n todo.id === Number(id)\n ? {\n ...todo,\n completed: !todo.completed\n }\n : todo\n )\n }));\n }\n\n render() {\n return (\n &lt;div className=\"todos__area\"&gt;\n &lt;div className=\"todos__events\"&gt;\n &lt;input\n ref={this.inputRef}\n id=\"input\"\n className=\"todos__input\"\n placeholder=\"type here\"\n type=\"text\"\n /&gt;\n &lt;button onClick={this.addTodo} className=\"todos__button\"&gt;\n {\" \"}\n Go{\" \"}\n &lt;/button&gt;{\" \"}\n &lt;/div&gt;{\" \"}\n &lt;ul className=\"todos__list\"&gt;\n {\" \"}\n {this.state.todos.map(todo =&gt; (\n &lt;TodoItem\n key={todo.id}\n toggler={this.toggleCompleted}\n thisItem={todo}\n /&gt;\n ))}{\" \"}\n &lt;/ul&gt;{\" \"}\n &lt;/div&gt;\n );\n }\n}\n\nfunction TodoItem({ thisItem, toggler }) {\n return (\n &lt;li&gt;\n &lt;label&gt;\n &lt;input\n id={thisItem.id}\n checked={thisItem.completed}\n className=\"checkbox\"\n onChange={toggler}\n type=\"checkbox\"\n /&gt;\n &lt;span\n style={{\n textDecoration: thisItem.completed ? \"line-through\" : \"none\"\n }}\n &gt;\n {thisItem.value}{\" \"}\n &lt;/span&gt;{\" \"}\n &lt;/label&gt;{\" \"}\n &lt;/li&gt;\n );\n}\n\nfunction Footer() {\n return (\n &lt;footer&gt;\n &lt;ul className=\"footer__ul pointer\"&gt;\n &lt;li&gt; Github &lt;/li&gt; &lt;li&gt; Reddit &lt;/li&gt; &lt;li&gt; FCC &lt;/li&gt;{\" \"}\n &lt;/ul&gt;{\" \"}\n &lt;/footer&gt;\n );\n}\n\nfunction App() {\n //render components\n return (\n &lt;main&gt;\n &lt;H1 /&gt;\n &lt;Todos /&gt;\n &lt;Footer /&gt;\n &lt;/main&gt;\n );\n}\n\nReactDOM.render( &lt; App / &gt; , document.getElementById('root'))</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>* {\n padding: 0;\n margin: 0;\n box-sizing: border-box;\n}\n\n:root {\n --blue: #2c3251;\n}\n\nul {\n list-style-type: none;\n}\n\nul&gt;li {\n display: block;\n padding: 0.5rem;\n}\n\n.pointer&gt;li:hover {\n cursor: pointer;\n}\n\nbody {\n font-family: \"Ubuntu\", sans-serif;\n text-align: left;\n background-color: white;\n background-image: radial-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.6)), url(\"./table.png\");\n background-repeat: repeat;\n padding: 2rem 2rem 0.1rem;\n}\n\nmain {\n display: grid;\n min-height: auto;\n height: 100vh;\n width: 100%;\n}\n\nh1 {\n font-size: 1.8rem;\n color: var(--blue);\n box-shadow: inset 0px 2px 5px var(--blue);\n align-self: start;\n padding: 1.5rem;\n border-radius: 15px 15px 0 0;\n margin-bottom: 0.5rem;\n}\n\n.todos__area {\n box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.7), 1px 1px 5px rgba(0, 0, 0, 0.3);\n display: flex;\n flex-direction: column;\n max-height: 300px;\n}\n\n.todos__events {\n display: flex;\n flex-direction: row;\n flex: 0 1 40px;\n}\n\n.todos__events .todos__input {\n border: none;\n padding: 0.5rem;\n border-radius: 2px 0 0 2px;\n flex: 2 1 150px;\n}\n\n.todos__events .todos__button {\n border: none;\n padding: 10px;\n flex: 1 1 60px;\n color: white;\n font-weight: bold;\n cursor: pointer;\n max-width: 100px;\n position: relative;\n background-color: rgba(0, 0, 0, 0);\n}\n\n.todos__events .todos__button:after {\n z-index: -1;\n position: absolute;\n top: 0;\n left: 0;\n width: 100%;\n height: 100%;\n background-color: #2d7b57;\n opacity: 0.5;\n transition: opacity 0.3s ease-out;\n content: \"\";\n}\n\n.todos__events .todos__button:hover:after {\n opacity: 0.7;\n}\n\n\n/* Inline #1 | http://localhost:3000/ */\n\n.todos__list {\n font-family: \"Dancing Script\", \"cursive\";\n font-size: 1.2rem;\n padding: 2rem;\n background-color: rgba(227, 227, 134, 0.58);\n flex: 1 1 200px;\n overflow: auto;\n}\n\n.todos__list input[type=checkbox] {\n margin-right: 0.6rem;\n}\n\nfooter {\n background-color: rgba(0, 0, 0, 0.1);\n align-self: end;\n margin-top: 0.5rem;\n}\n\n.footer__ul {\n display: flex;\n justify-content: center;\n color: var(--blue);\n font-weight: bold;\n}\n\n.footer__ul&gt;li {\n padding: 1rem;\n box-shadow: 1px 0px 1px var(--blue);\n transition: transform 0.1s ease-out;\n}\n\n.footer__ul&gt;li:hover {\n transform: scaleX(1.05);\n}\n\n@media screen and (min-width: 700px) {\n body {\n max-width: 700px;\n margin: auto;\n }\n}\n\n\n/*# sourceMappingURL=index.css.map */</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js\"&gt;&lt;/script&gt;\n&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js\"&gt;&lt;/script&gt;\n&lt;!DOCTYPE html&gt;\n&lt;html lang=\"en\"&gt;\n&lt;link href=\"https://fonts.googleapis.com/css2?family=Dancing+Script&amp;family=Ubuntu&amp;display=swap\" rel=\"stylesheet\"&gt;\n\n&lt;head&gt;\n &lt;meta charset=\"utf-8\" /&gt;\n &lt;title&gt;React App: todoist&lt;/title&gt;\n&lt;/head&gt;\n\n&lt;body&gt;\n &lt;div id=\"root\"&gt;&lt;/div&gt;\n&lt;/body&gt;\n\n&lt;/html&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T06:51:53.027", "Id": "245994", "ParentId": "245959", "Score": "1" } } ]
{ "AcceptedAnswerId": "245994", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T14:13:29.680", "Id": "245959", "Score": "3", "Tags": [ "react.js" ], "Title": "Todo application written in react" }
245959
<p>I am writing myself a little wrapper and I decided to cache values that shouldn't change (often or at all) for returning to the user, I'm coming from the premise that the WinAPI call is more expensive than returning my cached values, which I'm not sure if is true (or much more expensive to the point where it's worth it).</p> <p>Here is my function:</p> <pre><code>const SYSTEM_INFO&amp; getSystemInfo(const bool reCache) { static SYSTEM_INFO nativeSystemInfo; static bool cached_nativeSystemInfo{ false }; if (!cached_nativeSystemInfo || reCache) { GetNativeSystemInfo(&amp;nativeSystemInfo); cached_nativeSystemInfo = true; } return nativeSystemInfo; } </code></pre> <p>After some research on <code>GetNativeSystemInfo</code> and <code>SYSTEM_INFO</code> in general, I've seen that under normal circunstances the return structure should never change, but it is not impossible for it to happen. That is why I came up with the <code>reCache</code> function parameter.</p> <p>Would you understand what the <code>reCache</code> argument does even without documentation? Is this actually efficient? Would it be fit for it to be inlined?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T15:53:41.550", "Id": "483231", "Score": "0", "body": "Welcome to code review where we review working code from a project that you have written and provide suggestions on how to improve that code. From this single function it is very difficult to understand what the entire program is doing (what actions are you wrapping?), and how effective the caching is. This is an optimization, but without more code we can't really tell if this is an effective optimization or not. The question is currently off-topic due to lack of context, please see our [guidelines](https://codereview.stackexchange.com/help/asking)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T14:21:44.710", "Id": "245961", "Score": "1", "Tags": [ "c++", "windows", "cache", "wrapper", "winapi" ], "Title": "Wrapper function that returns cached value from WinAPI call" }
245961
<p>I've implemented a <em>Game of Life</em> in <em>Kotlin</em>.</p> <p>There are some major requirements on this solution:</p> <ul> <li>Purely object-<em>functional</em> production code.</li> <li>As close to an <em>infinite</em> universe as possible.</li> </ul> <h1>File <code>src/test/kotlin/…/PointTest.kt</code></h1> <pre class="lang-kotlin prettyprint-override"><code>package com.nelkinda.training.gameoflife import org.junit.jupiter.api.Test import kotlin.test.assertEquals internal class PointTest { @Test fun testToString() = assertEquals(&quot;P(0, 1)&quot;, P(0, 1).toString()) @Test fun plus() = assertEquals(P(3, 30), P(2, 20) + P(1, 10)) @Test fun neighbors() = assertEquals( setOf(P(4, 49), P(4, 50), P(4, 51), P(5, 49), P(5, 51), P(6, 49), P(6, 50), P(6, 51)), P(5, 50).neighbors().toSet() ) } </code></pre> <h1>File <code>src/main/kotlin/…/Point.kt</code></h1> <pre class="lang-kotlin prettyprint-override"><code>package com.nelkinda.training.gameoflife private val neighbors = (P(-1, -1)..P(1, 1)).filter { it != P(0, 0) } typealias P = Point data class Point constructor(private val x: Int, private val y: Int) { operator fun plus(p: Point) = P(x + p.x, y + p.y) operator fun rangeTo(p: Point) = (x..p.x).map { x -&gt; (y..p.y).map { y -&gt; P(x, y) } }.flatten() fun neighbors() = neighbors.map { this + it } fun neighbors(predicate: (Point) -&gt; Boolean) = neighbors().filter(predicate) override fun toString() = &quot;P($x, $y)&quot; } </code></pre> <h1>File <code>src/test/kotlin/…/RulesTest.kt</code></h1> <pre class="lang-kotlin prettyprint-override"><code>package com.nelkinda.training.gameoflife import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertAll import kotlin.test.assertEquals internal class RulesTest { private fun assertSurvival(rules: Rules, liveNeighbors: Set&lt;Int&gt;) = assertAll( (0..8).map { { assertEquals(it in liveNeighbors, rules.survives(it)) } } ) private fun assertBirth(rules: Rules, liveNeighbors: Set&lt;Int&gt;) = assertAll( (0..8).map { { assertEquals(it in liveNeighbors, rules.born(it)) } } ) @Test fun testConwayRules() = assertAll( { assertEquals(&quot;R 23/3&quot;, ConwayRules.toString()) }, { assertSurvival(ConwayRules, setOf(2, 3)) }, { assertBirth(ConwayRules, setOf(3)) } ) } </code></pre> <h1>File <code>src/main/kotlin/…/Rules.kt</code></h1> <pre class="lang-kotlin prettyprint-override"><code>package com.nelkinda.training.gameoflife @Suppress(&quot;MagicNumber&quot;) val ConwayRules: Rules = StandardRules(setOf(2, 3), setOf(3)) interface Rules { fun survives(liveNeighbors: Int): Boolean fun born(liveNeighbors: Int): Boolean } data class StandardRules( private val liveNeighborsForSurvival: Set&lt;Int&gt;, private val liveNeighborsForBirth: Set&lt;Int&gt; ) : Rules { private fun Set&lt;Int&gt;.toStr() = sorted().joinToString(&quot;&quot;) override fun survives(liveNeighbors: Int) = liveNeighbors in liveNeighborsForSurvival override fun born(liveNeighbors: Int) = liveNeighbors in liveNeighborsForBirth override fun toString() = &quot;R ${liveNeighborsForSurvival.toStr()}/${liveNeighborsForBirth.toStr()}&quot; } </code></pre> <h1>File <code>src/test/kotlin/…/UniverseTest.kt</code></h1> <pre class="lang-kotlin prettyprint-override"><code>package com.nelkinda.training.gameoflife import org.junit.jupiter.api.Test import kotlin.test.assertEquals internal class UniverseTest { @Test fun testToString() = assertEquals(&quot;Universe{R 23/3\n[P(0, 1)]}&quot;, Universe(life = setOf(P(0, 1))).toString()) } </code></pre> <h1>File <code>src/main/kotlin/…/Universe.kt</code></h1> <pre class="lang-kotlin prettyprint-override"><code>package com.nelkinda.training.gameoflife internal typealias Cell = Point @Suppress(&quot;TooManyFunctions&quot;) data class Universe constructor( private val rules: Rules = ConwayRules, private val life: Set&lt;Cell&gt; ) { operator fun inc() = Universe(rules, survivingCells() + bornCells()) private fun survivingCells() = life.filter { it.survives() }.toSet() private fun bornCells() = deadNeighborsOfLivingCells().filter { it.born() }.toSet() private fun deadNeighborsOfLivingCells() = life.flatMap { it.deadNeighbors() } private fun Cell.isAlive() = this in life private fun Cell.survives() = rules.survives(countLiveNeighbors()) private fun Cell.born() = rules.born(countLiveNeighbors()) private fun Cell.deadNeighbors() = neighbors { !it.isAlive() } private fun Cell.liveNeighbors() = neighbors { it.isAlive() } private fun Cell.countLiveNeighbors() = liveNeighbors().count() override fun toString() = &quot;Universe{$rules\n$life}&quot; } </code></pre> <p>At this point, you may suspect missing tests, but wait until you've seen the <code>.feature</code> file.</p> <h1>File <code>src/test/kotlin/…/ParserTest.kt</code></h1> <pre class="lang-kotlin prettyprint-override"><code>package com.nelkinda.training.gameoflife import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertAll import org.junit.jupiter.api.assertThrows import kotlin.test.assertEquals internal class ParserTest { private fun parses(spec: String, vararg cells: Cell) = assertEquals(Universe(life = setOf(*cells)), `parse simplified Life 1_05`(spec)) @Test fun testParses() = assertAll( { parses(&quot;&quot;) }, { parses(&quot;*&quot;, P(0, 0)) }, { parses(&quot;**&quot;, P(0, 0), P(1, 0)) }, { parses(&quot;*\n*&quot;, P(0, 0), P(0, 1)) }, { parses(&quot;*.*&quot;, P(0, 0), P(2, 0)) } ) @Test fun testInvalid() { val e = assertThrows&lt;IllegalArgumentException&gt; { parses(&quot;o&quot;) } assertEquals(&quot;Unexpected character 'o' at line 1, column 1&quot;, e.message) } } </code></pre> <h1>File <code>src/test/kotlin/…/Parser.kt</code></h1> <pre class="lang-kotlin prettyprint-override"><code>package com.nelkinda.training.gameoflife internal fun `parse simplified Life 1_05`(life1_05: String): Universe { val cells = HashSet&lt;Cell&gt;() var line = 1 var column = 1 val syntax = mapOf( '\n' to { line++; column = 0 }, '*' to { cells.add(P(column - 1, line - 1)) }, '.' to { } ).withDefault { c -&gt; throw IllegalArgumentException(&quot;Unexpected character '$c' at line $line, column $column&quot;) } life1_05.forEach { syntax.getValue(it).invoke() column++ } return Universe(life = cells.toSet()) } </code></pre> <h1>File <code>src/test/kotlin/…/GameOfLifeSteps.kt</code></h1> <pre class="lang-kotlin prettyprint-override"><code>package com.nelkinda.training.gameoflife import io.cucumber.java.en.Given import io.cucumber.java.en.Then import kotlin.test.assertEquals class GameOfLifeSteps { private lateinit var universe: Universe @Given(&quot;the following universe:&quot;) fun defineUniverse(spec: String) { universe = `parse simplified Life 1_05`(spec) } @Then(&quot;the next generation MUST be:&quot;) fun assertNextGenerationEquals(spec: String) { ++universe assertEquals(`parse simplified Life 1_05`(spec), universe) } } </code></pre> <h1>File <code>src/test/kotlin/…/RunCukesTest.kt</code></h1> <pre class="lang-kotlin prettyprint-override"><code>package com.nelkinda.training.gameoflife import io.cucumber.junit.Cucumber import io.cucumber.junit.CucumberOptions import org.junit.runner.RunWith @CucumberOptions( features = [&quot;src/test/resources/features&quot;], strict = true ) @RunWith(Cucumber::class) class RunCukesTest </code></pre> <h1>File <code>src/test/resources/features/GameOfLife.feature</code></h1> <pre class="lang-gherkin prettyprint-override"><code>Feature: Conway Game of Life Scenario: Empty universe Given the following universe: &quot;&quot;&quot; &quot;&quot;&quot; Then the next generation MUST be: &quot;&quot;&quot; &quot;&quot;&quot; Scenario: Single cell universe Given the following universe: &quot;&quot;&quot; * &quot;&quot;&quot; Then the next generation MUST be: &quot;&quot;&quot; &quot;&quot;&quot; Scenario: Block Given the following universe: &quot;&quot;&quot; ** ** &quot;&quot;&quot; Then the next generation MUST be: &quot;&quot;&quot; ** ** &quot;&quot;&quot; Scenario: Blinker Given the following universe: &quot;&quot;&quot; .* .* .* &quot;&quot;&quot; Then the next generation MUST be: &quot;&quot;&quot; *** &quot;&quot;&quot; Then the next generation MUST be: &quot;&quot;&quot; .* .* .* &quot;&quot;&quot; </code></pre> <p>Note: The actual feature file includes additional documentation and a scenario for the <em>Glider</em> which I have omitted from here for brevity, and has <code>Conway's Game of Life</code> as feature title, which breaks StackOverflow/Google Prettify Gherkin syntax highlighting, so I've removed the <code>'s</code> from it in this copy here.</p> <p>If you prefer to review the code in GitHub: <a href="https://github.com/nelkinda/gameoflife-kotlin" rel="nofollow noreferrer">https://github.com/nelkinda/gameoflife-kotlin</a></p> <p>Poke at it, tell me anything you find.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T15:03:36.613", "Id": "245963", "Score": "3", "Tags": [ "game-of-life", "kotlin" ], "Title": "Game of Life in Kotlin" }
245963
<p>I've included the files that I felt were relevant (i.e I haven't included the individual pieces in the inheritance hierarchy). I'm particularly curious as to whether the system as a whole is constructed well. I've used MVC along with the Observer pattern to decouple the model and view.</p> <p>Controller.java</p> <pre><code>package chess; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Observable; import java.util.Observer; public class Controller implements Observer { private Board board; private final View view; private final MinimaxAI ai; private Position startOfPlayerMove; private Position endOfPlayerMove; private Team currentTeam; public Controller() { board = new Board(); view = new View(); setupBoardImages(); view.addObserver(this); ai = new MinimaxAI(4, Team.WHITE); } // Main control method for entire program public void run() { currentTeam = Team.WHITE; Move move; GameStatus status; boolean running = true; while (running) { // Check if there's a checkmate or stalemate. If there is, end of game status = board.getGameStatus(currentTeam); if (status == GameStatus.CHECKMATE || status == GameStatus.STALEMATE) { view.gameOverMessage(status, currentTeam); running = false; continue; } move = getMove(); // Check if move follows the rules of Chess. If not, repeat turn if (!board.isValidMove(move, currentTeam)) { view.invalidMoveMessage(move); continue; } // Attempt to make move. If move results in the mover being checked, repeat turn if (!board.makeMove(move)) { view.checkMessage(currentTeam); continue; } // Update GUI and switch to next player updateView(move); view.moveMessage(move); currentTeam = getNextTurn(); } } // Maps pieces on the board to the view private void setupBoardImages() { for (int row = 0; row &lt; 8; row++) { for (int column = 0; column &lt; 8; column++) { Position position = new Position(row, column); if (board.pieceAt(position) != null) view.updateTile(position, board.pieceAt(position).toString()); else view.clearTile(position); } } } private Move getMove() { if (currentTeam == Team.WHITE) return ai.pickMove(board); else return pickPlayerMove(); } private Move pickPlayerMove() { while (startOfPlayerMove == null || endOfPlayerMove == null) waitForValidInput(); Move ret = new Move(startOfPlayerMove, endOfPlayerMove); resetMove(); return ret; } private void waitForValidInput() { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } private Team getNextTurn() { return Team.otherTeam(currentTeam); } // Update GUI with new state of board resulting from a move private void updateView(Move move) { String updateNewPiecePos = board.pieceAt(move.destination()).toString(); view.clearTile(move.start()); view.updateTile(move.destination(), updateNewPiecePos); } @Override public void update(Observable gui, Object information) { switch (view.getUpdateType()) { case SAVE: save(information); break; case LOAD: load(information); break; case MOVE: updatePlayerMove(information); break; default: throw new AssertionError(&quot;Enum doesn't seem to match with any supported types&quot;); } } private void updatePlayerMove(Object object) { if (!(object instanceof Position)) throw new AssertionError(&quot;There doesn't seem to be a position here&quot;); Position position = (Position) object; if (isValidEndOfMove(position)) endOfPlayerMove = position; else { startOfPlayerMove = position; endOfPlayerMove = null; } } private boolean isValidEndOfMove(Position position) { Piece selectedPiece = board.pieceAt(position); return (selectedPiece == null || selectedPiece.getTeam() != currentTeam) &amp;&amp; startOfPlayerMove != null; } private void save(Object object) { if (!(object instanceof File)) throw new AssertionError(&quot;There doesn't seem to be a file here&quot;); File file = (File) object; try (FileOutputStream fileStream = new FileOutputStream(file); ObjectOutputStream os = new ObjectOutputStream(fileStream)) { os.writeObject(board); } catch (IOException e) { e.printStackTrace(); view.fileIOError(); } } private void resetMove() { startOfPlayerMove = null; endOfPlayerMove = null; } private void load(Object object) { if (!(object instanceof File)) throw new AssertionError(&quot;There doesn't seem to be a file here&quot;); File file = (File) object; try (FileInputStream fileStream = new FileInputStream(file); ObjectInputStream os = new ObjectInputStream(fileStream)) { board = (Board) os.readObject(); resetMove(); setupBoardImages(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); view.fileIOError(); } } } </code></pre> <p>Board.java</p> <pre><code>package chess; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Stack; public class Board implements Serializable { private final Piece[][] board; // Cache is used to save moves in case you want to reverse them. private final Stack&lt;Piece&gt; deletedPieceCache; private final Stack&lt;Move&gt; moveCache; private final Stack&lt;Position&gt; pawnToQueenConversionCache; // Maps a pieces string representation onto it's relative value private final Map&lt;String, Integer&gt; heuristicMap; public Board() { board = new Piece[8][8]; deletedPieceCache = new Stack&lt;&gt;(); moveCache = new Stack&lt;&gt;(); pawnToQueenConversionCache = new Stack&lt;&gt;(); heuristicMap = new HashMap&lt;&gt;(); buildHeuristicMapping(); addPieces(0, 1, Team.WHITE); addPieces(7, 6, Team.BLACK); } public void reverseLastMove() { Move move = moveCache.pop(); Position start = move.start(); Position end = move.destination(); board[start.row()][start.column()] = pieceAt(end); board[end.row()][end.column()] = deletedPieceCache.pop(); checkForReversePawnReplacement(); } // Returns true if last move was successful, false if unsuccessful public boolean makeMove(Move move) { Position start = move.start(); Position end = move.destination(); Team team = pieceAt(start).getTeam(); cacheMove(move, end); movePiece(start, end); checkForPawnReplacement(start, end); if (isChecked(team)) { reverseLastMove(); return false; } return true; } private void movePiece(Position start, Position end) { board[end.row()][end.column()] = pieceAt(start); board[start.row()][start.column()] = null; } private void cacheMove(Move move, Position end) { deletedPieceCache.push(pieceAt(end)); moveCache.push(move); } public GameStatus getGameStatus(Team team) { for (Move move : generatePossibleMovesForTeam(team)) { if (makeMove(move)) { reverseLastMove(); return GameStatus.INPLAY; } } // No moves can be made, game is either in checkmate or stalemate if (isChecked(team)) return GameStatus.CHECKMATE; else return GameStatus.STALEMATE; } // Returns true if a move doesn't break the rules public boolean isValidMove(Move move, Team team) { if (pieceAt(move.start()) == null) return false; if (pieceAt(move.start()).getTeam() != team) return false; List&lt;Move&gt; possibleMoves = generatePossibleMovesForPiece(move.start()); return possibleMoves.contains(move); } public List&lt;Move&gt; generatePossibleMovesForTeam(Team team) { List&lt;Move&gt; ret = new ArrayList&lt;&gt;(); for (Position pos : getPositionsOfPiecesForTeam(team)) ret.addAll(generatePossibleMovesForPiece(pos)); return ret; } // Adds piece objects to board for each team private void addPieces(int backRow, int frontRow, Team team) { board[backRow][0] = new Rook(team); board[backRow][7] = new Rook(team); board[backRow][1] = new Knight(team); board[backRow][6] = new Knight(team); board[backRow][2] = new Bishop(team); board[backRow][5] = new Bishop(team); board[backRow][3] = new Queen(team); board[backRow][4] = new King(team); for (int i = 0; i &lt; 8; i++) board[frontRow][i] = new Pawn(team); } private boolean isChecked(Team team) { Position kingsPosition = getKingPosition(team); Team otherTeam = Team.otherTeam(team); for (Position position : getPositionsOfPiecesForTeam(otherTeam)) { Move move = new Move(position, kingsPosition); if (isValidMove(move, otherTeam)) return true; } return false; } // If pawn reached the end, replace with queen private void checkForPawnReplacement(Position start, Position end) { if (pieceAt(end) instanceof Pawn &amp;&amp; (end.row() == 0 || end.row() == 7)) { replacePawnWithQueen(end); pawnToQueenConversionCache.push(start); } else pawnToQueenConversionCache.push(null); } private void replacePawnWithQueen(Position end) { board[end.row()][end.column()] = new Queen(pieceAt(end).getTeam()); } // Uses cache to reverse a move where a pawn has turned into a queen private void checkForReversePawnReplacement() { Position pos = pawnToQueenConversionCache.pop(); if (pos != null) board[pos.row()][pos.column()] = new Pawn(pieceAt(pos).getTeam()); } private List&lt;Move&gt; generatePossibleMovesForPiece(Position start) { Piece piece = pieceAt(start); if (piece instanceof Pawn) updatePawnSurroundings(start); return removeInvalidMoves(piece.generateMoveList(start)); } // Tells a pawn object where its surrounding pieces are so it can make a move private void updatePawnSurroundings(Position pawnPosition) { boolean leftTake = false, rightTake = false; boolean isPieceInFront = false, isPieceTwoInFront = false; Pawn pawn = (Pawn) pieceAt(pawnPosition); int directionModifier = getDirectionModifier(pawn.getTeam()); Position pos; // True if an opposing teams piece is at top left of pawn pos = new Position(pawnPosition.row() + directionModifier, pawnPosition.column() + 1); if (pieceAt(pos) != null &amp;&amp; pieceAt(pos).getTeam() != pawn.getTeam()) rightTake = true; // True if an opposing teams piece is at top right of pawn pos = new Position(pawnPosition.row() + directionModifier, pawnPosition.column() - 1); if (pieceAt(pos) != null &amp;&amp; pieceAt(pos).getTeam() != pawn.getTeam()) leftTake = true; // True if a piece is in front of the pawn pos = new Position(pawnPosition.row() + directionModifier, pawnPosition.column()); if (pieceAt(pos) != null) isPieceInFront = true; // True if no piece lies 2 spots ahead of pawn pos = new Position(pawnPosition.row() + (directionModifier * 2), pawnPosition.column()); if (pieceAt(pos) != null) isPieceTwoInFront = true; pawn.setSurroundingPositions(leftTake, rightTake, isPieceInFront, isPieceTwoInFront); } // Returns the direction where a pawn should move given the team it's in private int getDirectionModifier(Team team) { if (team == Team.WHITE) return 1; else return -1; } // Filters out any moves that don't follow the rules of the game private List&lt;Move&gt; removeInvalidMoves(List&lt;Move&gt; moves) { List&lt;Move&gt; ret = new ArrayList&lt;&gt;(); for (Move move : moves) if (isClearPath(move) &amp;&amp; isValidDestination(move)) ret.add(move); return ret; } // Returns true if no other pieces lie in a pieces path when moving private boolean isClearPath(Move move) { List&lt;Position&gt; path = move.drawPath(); for (Position position : path) if (pieceAt(position) != null) return false; return true; } private Position getKingPosition(Team team) { for (int row = 0; row &lt; 8; row++) { for (int column = 0; column &lt; 8; column++) { Position pos = new Position(row, column); if (pieceAt(pos) != null &amp;&amp; (pieceAt(pos) instanceof King) &amp;&amp; pieceAt(pos).getTeam() == team) return pos; } } throw new AssertionError(&quot;King not found&quot;); } // Returns List of all positions of a given teams pieces that can make a move private List&lt;Position&gt; getPositionsOfPiecesForTeam(Team team) { List&lt;Position&gt; ret = new ArrayList&lt;&gt;(); for (int i = 0; i &lt; 8; i++) for (int j = 0; j &lt; 8; j++) { Position pos = new Position(i, j); if (pieceAt(pos) != null &amp;&amp; pieceAt(pos).getTeam() == team) if (generatePossibleMovesForPiece(pos).size() &gt; 0) ret.add(pos); } return ret; } // Returns true if the destination isn't occupied by a pieces own team private boolean isValidDestination(Move move) { Position start = move.start(); Position end = move.destination(); Team team = pieceAt(start).getTeam(); if (pieceAt(end) != null &amp;&amp; pieceAt(end).getTeam() == team) return false; return true; } public Piece pieceAt(Position position) { if (!position.isOnBoard()) return null; return board[position.row()][position.column()]; } @SuppressWarnings(&quot;unused&quot;) private void printBoard() { for (Piece[] row : board) { System.out.println(); for (Piece piece : row) if (piece == null) System.out.print(&quot;-&quot;); else System.out.print(piece); } System.out.println(&quot;\n&quot;); } public void clearCache() { deletedPieceCache.clear(); moveCache.clear(); pawnToQueenConversionCache.clear(); } private void buildHeuristicMapping() { heuristicMap.put(&quot;k&quot;, 950); heuristicMap.put(&quot;q&quot;, 100); heuristicMap.put(&quot;r&quot;, 60); heuristicMap.put(&quot;b&quot;, 40); heuristicMap.put(&quot;n&quot;, 30); heuristicMap.put(&quot;p&quot;, 10); } public int generateHeuristicValue(Team team) { int value = 0; for (Piece[] row : board) for (Piece piece : row) if (piece != null) { if (team == piece.getTeam()) value += heuristicMap.get(piece.toString().toLowerCase()); else value -= heuristicMap.get(piece.toString().toLowerCase()); } return value; } } </code></pre> <p>Piece.java</p> <pre><code>package chess; import java.io.Serializable; import java.util.List; abstract public class Piece implements Serializable { private final Team team; public Piece(Team t) { team = t; } protected void addPositionToMoveList(List&lt;Move&gt; moves, Position start, Position pos) { if (pos.isOnBoard()) moves.add(new Move(start, pos)); } public Team getTeam() { return team; } // Generates set of all possible positions a piece can move to public abstract List&lt;Move&gt; generateMoveList(Position start); } </code></pre> <p>View.java</p> <pre><code>package chess; import java.awt.BorderLayout; import java.awt.Color; import java.awt.GridLayout; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Observable; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.filechooser.FileSystemView; public class View extends Observable { // Allows us to access a tile given a position on the board private final JButton[][] tiles; // Main frame that the GUI runs on private final JFrame frame; // Main panel that all tiles on the board are placed on private final JPanel board; // Panel that holds any buttons the player needs private final JPanel playerOptions; // Maps string representation of a piece to its image private final Map&lt;String, Image&gt; pieceToImage; // Displays any information on the game (i.e checks, illegal moves) private final JTextField gameStatus; // These components represent the filemenu dropdown menu for saving and loading private final JMenuBar fileMenuBar; private final JMenu fileMenu; private final JMenuItem save; private final JMenuItem load; // Allows view to tell the controller any requests that come from the player private UpdateType updateType; public View() { frame = new JFrame(&quot;Chess&quot;); board = new JPanel(new GridLayout(0, 8)); fileMenuBar = new JMenuBar(); fileMenu = new JMenu(&quot;File&quot;); save = new JMenuItem(&quot;Save&quot;); load = new JMenuItem(&quot;Load&quot;); setUpFileMenu(); playerOptions = new JPanel(); setupPlayerOptions(); gameStatus = new JTextField(&quot;&quot;); gameStatus.setHorizontalAlignment(JTextField.CENTER); tiles = new JButton[8][8]; setupBoardButtons(); addBoardBehaviour(); pieceToImage = new HashMap&lt;&gt;(); addPieceImagesToMap(); addComponentsToFrame(); configureFrame(); } private void configureFrame() { frame.setSize(1000, 1000); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } private void setUpFileMenu() { fileMenu.add(save); fileMenu.add(load); fileMenuBar.add(fileMenu); addSaveBehaviour(); addLoadBehaviour(); } // Tells program what to do when save button is pressed private void addSaveBehaviour() { save.addActionListener(actionEvent -&gt; { File file = getFileFromUser(); if (file != null) { updateType = UpdateType.SAVE; setChanged(); notifyObservers(file); updateType = UpdateType.NONE; } }); } // Tells program what to do when load button is pressed private void addLoadBehaviour() { load.addActionListener(actionEvent -&gt; { File file = getFileFromUser(); if (file != null) { updateType = UpdateType.LOAD; setChanged(); notifyObservers(file); updateType = UpdateType.NONE; } }); } public void fileIOError() { JOptionPane.showMessageDialog(null, &quot;Error when loading in file&quot;); } // Allows user to select a file from their computer's file menu private File getFileFromUser() { JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); if (jfc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) return jfc.getSelectedFile(); return null; } public UpdateType getUpdateType() { return updateType; } public void gameOverMessage(GameStatus status, Team team) { if (status == GameStatus.STALEMATE) JOptionPane.showMessageDialog(null, &quot;Game has ended in a stalemate&quot;); else JOptionPane.showMessageDialog(null, &quot;Checkmate, &quot; + Team.toString(Team.otherTeam(team)) + &quot; has won&quot;); } // Updates the images displayed on the board for a move public void updateTile(Position position, String update) { tiles[position.row()][position.column()].setIcon(new ImageIcon(pieceToImage.get(update))); } // Remove image from a tile public void clearTile(Position position) { tiles[position.row()][position.column()].setIcon(null); } public void invalidMoveMessage(Move move) { gameStatus.setText(&quot;Attempted move &quot; + move + &quot; is invalid&quot;); } public void moveMessage(Move move) { gameStatus.setText(move.toString()); } public void checkMessage(Team team) { gameStatus.setText(Team.toString(team) + &quot; would be checked as the result of that move&quot;); } private void addComponentsToFrame() { frame.getContentPane().add(BorderLayout.CENTER, board); frame.getContentPane().add(BorderLayout.SOUTH, playerOptions); frame.getContentPane().add(BorderLayout.NORTH, gameStatus); } private void setupPlayerOptions() { playerOptions.add(fileMenuBar); } // Adds the actionlistener to every button in the board private void addBoardBehaviour() { for (int row = 0; row &lt; 8; row++) for (int column = 0; column &lt; 8; column++) addButtonBehaviour(row, column); } // Allows user to select pieces for a move private void addButtonBehaviour(final int row, final int column) { tiles[row][column].addActionListener(actionEvent -&gt; { updateType = UpdateType.MOVE; setChanged(); notifyObservers(new Position(row, column)); updateType = UpdateType.NONE; }); } // Create buttons and add to panel private void setupBoardButtons() { for (int row = 0; row &lt; 8; row++) { for (int column = 0; column &lt; 8; column++) { JButton button = new JButton(); setBackgroundForTile(row, column, button); tiles[row][column] = button; board.add(button); } } } private void setBackgroundForTile(int row, int column, JButton button) { if ((column % 2 == 0 &amp;&amp; row % 2 == 0) || (column % 2 == 1 &amp;&amp; row % 2 == 1)) button.setBackground(Color.WHITE); else button.setBackground(Color.BLACK); } private void addPieceImagesToMap() { Image[][] pieceImages = new Image[2][6]; readPieceImages(pieceImages); pieceToImage.put(&quot;q&quot;, pieceImages[0][0]); pieceToImage.put(&quot;k&quot;, pieceImages[0][1]); pieceToImage.put(&quot;r&quot;, pieceImages[0][2]); pieceToImage.put(&quot;n&quot;, pieceImages[0][3]); pieceToImage.put(&quot;b&quot;, pieceImages[0][4]); pieceToImage.put(&quot;p&quot;, pieceImages[0][5]); pieceToImage.put(&quot;Q&quot;, pieceImages[1][0]); pieceToImage.put(&quot;K&quot;, pieceImages[1][1]); pieceToImage.put(&quot;R&quot;, pieceImages[1][2]); pieceToImage.put(&quot;N&quot;, pieceImages[1][3]); pieceToImage.put(&quot;B&quot;, pieceImages[1][4]); pieceToImage.put(&quot;P&quot;, pieceImages[1][5]); } // Get piece images from file private void readPieceImages(Image[][] pieceImages) { int imageSize = 64; try { BufferedImage imageBuffer = ImageIO.read(new File(&quot;piece_images.png&quot;)); for (int i = 0; i &lt; 2; i++) for (int j = 0; j &lt; 6; j++) pieceImages[i][j] = imageBuffer.getSubimage(j * imageSize, i * imageSize, imageSize, imageSize); } catch (IOException io) { System.out.println(&quot;Error with handling images&quot;); io.printStackTrace(); } } } </code></pre> <p>Move.java</p> <pre><code>package chess; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class Move implements Serializable { private final Position start; private final Position end; public Move(Position s, Position e) { start = s; end = e; } // Example: drawPath((1, 1), (4, 4)) returns [(2, 2), (3, 3)] public List&lt;Position&gt; drawPath() { List&lt;Position&gt; path = new ArrayList&lt;&gt;(); MovementType movementType = getMovementType(); // Not necessary for horse, return empty list if (movementType == MovementType.HORSE) return path; int rowIncrement = getIncrementValues(movementType)[0] * getRowDirection(); int columnIncrement = getIncrementValues(movementType)[1] * getColumnDirection(); int rowOffset = rowIncrement; int columnOffset = columnIncrement; // Draw path until we reach end position while (start.row() + rowOffset != end.row() || start.column() + columnOffset != end.column()) { path.add(new Position(start.row() + rowOffset, start.column() + columnOffset)); rowOffset += rowIncrement; columnOffset += columnIncrement; } return path; } // Returns 1 if piece moved down, -1 if moved up, 0 if piece didn't change row private int getRowDirection() { if (end.row() - start.row() &gt; 0) return 1; else if (end.row() - start.row() &lt; 0) return -1; else return 0; } // Returns 1 if piece moved right, -1 if moved left, 0 if piece didn't change column private int getColumnDirection() { if (end.column() - start.column() &gt; 0) return 1; else if (end.column() - start.column() &lt; 0) return -1; else return 0; } public Position destination() { return end; } public Position start() { return start; } private MovementType getMovementType() { if (Math.abs(start.row() - end.row()) == Math.abs(start.column() - end.column())) return MovementType.DIAGONAL; if (start.row() == end.row()) return MovementType.HORIZONTAL; if (start.column() == end.column()) return MovementType.VERTICAL; return MovementType.HORSE; } // Returns the change in co-ordinates that came from a movement private int[] getIncrementValues(MovementType movement) { int rowIncrement = 0; int columnIncrement = 0; switch (movement) { case DIAGONAL: rowIncrement = 1; columnIncrement = 1; break; case HORIZONTAL: columnIncrement = 1; break; case VERTICAL: rowIncrement = 1; break; default: throw new AssertionError(&quot;Enum doesn't seem to match with any supported types&quot;); } return new int[] { rowIncrement, columnIncrement }; } @Override public boolean equals(Object obj) { if (!(obj instanceof Move)) return false; Move move = (Move) obj; return start.equals(move.start) &amp;&amp; end.equals(move.end); } @Override public int hashCode() { return start.hashCode() * 27832 + end.hashCode(); } @Override public String toString() { return start.toString() + &quot; to &quot; + end.toString(); } enum MovementType { DIAGONAL, HORIZONTAL, VERTICAL, HORSE } } </code></pre> <p>Minimax.java</p> <pre><code>package chess; /* * Uses the minimax algorithm with alpha beta pruning to make moves */ public class MinimaxAI { private final int maxDepth; private final Team team; public MinimaxAI(int m, Team t) { maxDepth = m; team = t; } // Return move that minimax algorithm wants to make by // running minimax on all possible moves public Move pickMove(Board board) { int max = Integer.MIN_VALUE; int current; Move optimalMove = null; for (Move move : board.generatePossibleMovesForTeam(team)) { if (board.makeMove(move)) { current = min(board, 1, Integer.MIN_VALUE, Integer.MAX_VALUE); if (current &gt;= max) { optimalMove = move; max = current; } board.reverseLastMove(); } } board.clearCache(); return optimalMove; } // For all moves the opposing team could make, return least optimal for the AI private int min(Board board, int depth, int alpha, int beta) { if (depth == maxDepth) return board.generateHeuristicValue(team); for (Move move : board.generatePossibleMovesForTeam(Team.otherTeam(team))) { if (board.makeMove(move)) { beta = Math.min(max(board, depth + 1, alpha, beta), beta); board.reverseLastMove(); } if (alpha &gt;= beta) break; } return beta; } // For all moves the AI could make, return most optimal private int max(Board board, int depth, int alpha, int beta) { if (depth == maxDepth) return board.generateHeuristicValue(team); for (Move move : board.generatePossibleMovesForTeam(team)) { if (board.makeMove(move)) { alpha = Math.max(min(board, depth + 1, alpha, beta), alpha); board.reverseLastMove(); } if (alpha &gt;= beta) break; } return alpha; } } </code></pre>
[]
[ { "body": "<p>On first glance, I wouldn't call things just <code>View</code>, <code>Controller</code>, and <code>Observable</code>, even if they are indirectly qualified by their package. It's a bit surprising to see that in Java, the names suggest reusability and independence of Chess. It probably should be <code>ChessBoardView</code> and <code>ChessBoardController</code>. Having <code>Observable</code> as an interface is a bit unusual in Java MVC, it's more common to have the counter-part <em>Observer</em> and name it <code>Listener</code>, in this case <code>ChessBoardListener</code>.</p>\n<p>The <code>fileStream</code> is overly qualified as <code>FileInputStream</code>, <code>InputStream</code> would suffice.</p>\n<p>If <code>readPieceImages()</code> fails, the program will continue with broken data and throw a <code>NullPointerException</code> when calling <code>updateTile()</code> at <code>new ImageIcon(pieceToImage.get(update))</code>: <code>pieceToImage.get(update)</code> will return <code>null</code>, and <code>new ImageIcon((java.awt.Image) null)</code> throws a <code>NullPointerException</code> in the constructor.</p>\n<p>Method <code>fileIOError()</code> could use <code>JOptionPane.ERROR_MESSAGE</code> to signal to the user that the message is about an error.</p>\n<p>Nice: Mostly immutable fields. You could go one step further and use unmodifiable collections as well. Instead of, in the constructor,</p>\n<pre><code> pieceToImage = new HashMap&lt;&gt;();\n addPieceImagesToMap();\n</code></pre>\n<p>you could have</p>\n<pre><code> private final Map&lt;String, Image&gt; pieceToImage = loadPieceImages();\n</code></pre>\n<p>and <code>loadPieceImages()</code> would create a <code>new HashMap&lt;&gt;()</code> plus <code>return Collections.unmodifiableMap(pieceToImage)</code>.</p>\n<p>Besides, <code>pieceToImage</code> should probably cache the <code>ImageIcon</code>, not the <code>Image</code>. That would save repetitive constructor calls of <code>new ImageIcon</code> in <code>updateTile()</code>.</p>\n<p>For <code>equals()</code> and <code>hashCode()</code> you might want to use Lombok, it saves a lot of boilerplate.</p>\n<p>The <code>switch (movement)</code> could be avoided altogether by giving the <code>enum MovementType</code> fields <code>rowIncrement</code> and <code>columnIncrement</code>. This could also replace the <code>int[]</code> return type, which is not necessarily intuitive (one has to remember whether row or column comes first). (In other words. the implementation of the enum is not OO.)</p>\n<p>The <code>MovementType</code> enum is also partially confusing, because in some contexts all four enum constants, including <code>HORSE</code> are allowed, and in some contexts, only 3 excluding <code>HORSE</code> are allowed.</p>\n<p>Some of the methods and classes appear a bit long at first glance, and some responsibility misplaced. Loading and saving a board should probably not be in the same <code>Controller</code> as other UI functions.</p>\n<p>Update: The current class <code>Board</code> conflates different responsibilities (it would change for more than one reason), and thus should be split:</p>\n<ul>\n<li>The <code>Board</code> itself, merely representing the chess board with the positions of the pieces. It shouldn't even know that the pieces are chess. Hypothetically, this should be reusable for implementing Draughts instead of Chess.</li>\n<li>An interface <code>Rules</code> which merely connects the Board and the AI to what's allowed.</li>\n<li>A class <code>ChessRules</code> which implements <code>Rules</code> for the actual rules of Chess.</li>\n<li>A class <code>ChessAI</code> or something like that for all parts currently in <code>Board</code> which only serve the purpose of feeding the <code>MinimaxAI</code>.</li>\n<li>The current behavior of the <code>MinimaxAI</code> is great, the behavior already doesn't know anything about Chess. The dependency could be decoupled so that even structurally it doesn't know about Chess. (Right now, <code>Board</code> is still specific to Chess.)</li>\n</ul>\n<p>Update 2</p>\n<ul>\n<li>In enum <code>Team</code> (not shown in the question), method <code>otherTeam()</code> should not be a <code>static</code> utility method but an instance method of the enum.</li>\n<li>In enum <code>Team</code> (not shown in the question), method <code>toString()</code> also should not be a <code>static</code> utility method but an instance method of that enum.</li>\n</ul>\n<p>Overall, I really enjoyed looking at the code. That's it for now, I might have a more detailed look later.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T20:53:26.547", "Id": "245977", "ParentId": "245964", "Score": "6" } } ]
{ "AcceptedAnswerId": "245977", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T15:53:25.297", "Id": "245964", "Score": "7", "Tags": [ "java", "object-oriented", "mvc", "swing", "chess" ], "Title": "Chess application with GUI and AI in Java" }
245964
<p>I'm posting my code for a LeetCode problem. If you'd like to review, please do so. Thank you for your time!</p> <h3>Problem</h3> <blockquote> <p>For an integer n, we call k&gt;=2 a good base of n, if all digits of n base k are 1.</p> <p>Now given a string representing n, you should return the smallest good base of n in string format.</p> <h3>Example 1:</h3> <ul> <li>Input: &quot;13&quot;</li> <li>Output: &quot;3&quot;</li> <li>Explanation: 13 base 3 is 111.</li> </ul> <h3>Example 2:</h3> <ul> <li>Input: &quot;4681&quot;</li> <li>Output: &quot;8&quot;</li> <li>Explanation: 4681 base 8 is 11111.</li> </ul> <h3>Example 3:</h3> <ul> <li>Input: &quot;1000000000000000000&quot;</li> <li>Output: &quot;999999999999999999&quot;</li> <li>Explanation: 1000000000000000000 base 999999999999999999 is 11.</li> </ul> <h3>Note:</h3> <ul> <li>The range of n is [3, 10^18].</li> <li>The string representing n is always valid and will not have leading zeros.</li> </ul> </blockquote> <h3>Inputs</h3> <pre><code>&quot;1000000000000000000&quot; &quot;999999999999999999&quot; &quot;141038407950127511&quot; &quot;836507047502348570&quot; &quot;123489798271512411&quot; &quot;995437985793784539&quot; &quot;4681&quot; &quot;4800&quot; &quot;48000&quot; &quot;480000&quot; &quot;5120000&quot; &quot;51200000&quot; </code></pre> <h3>Outputs</h3> <pre><code> &quot;999999999999999999&quot; &quot;999999999999999998&quot; &quot;141038407950127510&quot; &quot;836507047502348569&quot; &quot;123489798271512410&quot; &quot;995437985793784538&quot; &quot;8&quot; &quot;4799&quot; &quot;47999&quot; &quot;479999&quot; &quot;5119999&quot; &quot;51199999&quot; </code></pre> <h3>Code</h3> <pre><code>#include &lt;cstdint&gt; #include &lt;string&gt; #include &lt;algorithm&gt; struct Solution { std::string smallestGoodBase(const std::string n) { std::uint_fast64_t num = (std::uint_fast64_t) std::stoull(n); std::uint_fast64_t x = 1; for (int bit = 62; bit &gt; 0; --bit) { if ((x &lt;&lt; bit) &lt; num) { std::uint_fast64_t curr = binarySearch(num, bit); if (curr) { return std::to_string(curr); } } } return std::to_string(num - 1); } private: static std::uint_fast64_t binarySearch( const std::uint_fast64_t num, const std::uint_fast8_t bit ) { const long double dnum = (long double) num; std::uint_fast64_t lo = 1; std::uint_fast64_t hi = (std::uint_fast64_t) (std::pow(dnum, 1.0 / bit) + 1); while (lo &lt; hi) { std::uint_fast64_t mid = lo + ((hi - lo) &gt;&gt; 1); std::uint_fast64_t sum = 1; std::uint_fast64_t curr = 1; for (std::uint_fast8_t iter = 1; iter &lt;= bit; ++iter) { curr *= mid; sum += curr; } if (sum == num) { return mid; } else if (sum &gt; num) { hi = mid; } else { lo = mid + 1; } } return 0; } }; </code></pre> <h3>References</h3> <ul> <li><p><a href="https://leetcode.com/problems/smallest-good-base/" rel="nofollow noreferrer">Problem</a></p> </li> <li><p><a href="https://leetcode.com/problems/smallest-good-base/discuss/" rel="nofollow noreferrer">Discuss</a></p> </li> <li><p><a href="https://leetcode.com/problems/smallest-good-base/solution/" rel="nofollow noreferrer">Solution</a></p> </li> </ul>
[]
[ { "body": "<h1>Don't use <code>std::uint_fast*_t</code></h1>\n<p>The performance gain of these types is minimal. If you really need to squeeze out the last bits of performance, it might help, but only if:</p>\n<ul>\n<li>These types are actually different from the regular <code>std::uint*_t</code></li>\n<li>Implicit casts and integer promotions don't change the actual type used</li>\n</ul>\n<p>The drawback is that the type names get very verbose. Also, can a <code>std::uint_fast64_t</code> actually hold an <code>unsigned long long</code>? The latter might very well be 128 bits long.</p>\n<p>I suggest you stick with (<code>unsigned</code>) <code>int</code> when dealing with numbers that don't grow large (for example, for counting bits), <code>size_t</code> when you need to support arbitratily large counts, sizes and array indices, and other types as appropriate, such as <code>unsigned long long</code> to store the results of <code>std::stoull()</code>.</p>\n<p>Also use a <code>using</code> declaration to declare the type used to store the numbers in one place, so if you ever decide to change it, you don't have to search and replace all over the code. You can combine it with <code>decltype()</code> to get the type returned by an arbitrary function, like so:</p>\n<pre><code>class Solution {\n using value_type = decltype(std::stoull(&quot;&quot;));\n ...\n};\n</code></pre>\n<h1>Avoid unnecessary one-use temporaries</h1>\n<p>There are several cases where you define a temporary variable that is only used once, and which could be avoided. The first is <code>x</code>, which is only used to create a constant <code>1</code> of the right type. You can do that instead like so:</p>\n<pre><code>if ((value_type{1} &lt;&lt; bit) &lt; num) {\n ...\n}\n</code></pre>\n<p>The second one will still technically create a temporary, but we can use C++17's <code>if</code> with an init statement:</p>\n<pre><code>if (auto curr = binarySearch(num, bit); curr) {\n return curr;\n}\n</code></pre>\n<p>When passing an integer type to <a href=\"https://en.cppreference.com/w/cpp/numeric/math/pow\" rel=\"nofollow noreferrer\"><code>std::pow()</code></a>, it will convert it to <code>double</code> for you, so you don't have to explcitly create a temporary constant <code>dnum</code>, and can just write:</p>\n<pre><code>value_type hi = std::pow(num, 1.0 / bit) + 1;\n</code></pre>\n<p>Note that you also don't need to explicitly cast it back to an integer here.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-02T19:00:28.743", "Id": "248830", "ParentId": "245969", "Score": "1" } } ]
{ "AcceptedAnswerId": "248830", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T17:32:11.350", "Id": "245969", "Score": "3", "Tags": [ "c++", "beginner", "algorithm", "programming-challenge", "c++17" ], "Title": "LeetCode 483: Smallest Good Base" }
245969
<p>I created a music player using swiftUI.I need to ask a question when I break up my player into usable components. How should I take this approach with the music player? because the music player is one view can't break up?</p> <pre><code>import SwiftUI struct ContentView: View { var body: some View { VStack { Image(&quot;albumCover&quot;) HStack{ VStack { Text(&quot;Album name&quot;) Text(&quot;Artist name&quot;) } Spacer() Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/) { Image(systemName: &quot;heart&quot;) } }.padding() HStack{ Text(&quot;0&quot;) Slider(value: /*@START_MENU_TOKEN@*//*@PLACEHOLDER=Value@*/.constant(10)/*@END_MENU_TOKEN@*/) Text(&quot;-5:00&quot;) }.padding() HStack{ Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/) { Image(systemName: &quot;shuffle&quot;) } Spacer() Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/) { Image(systemName:&quot;backward.end&quot;) } Spacer() Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/) { Image(systemName: &quot;play&quot;) } Spacer() Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/) { Image(systemName: &quot;forward.end&quot;) } Spacer() Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/) { Image(systemName: &quot;repeat&quot;) } }.padding() HStack{ Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/) { Image(systemName: &quot;hifispeaker&quot;) } Spacer() Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/) { Image(systemName: &quot;music.note.list&quot;) } }.padding() } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } </code></pre>
[]
[ { "body": "<blockquote>\n<p>I need to ask a question when I break up my player into usable\ncomponents. How should I take this approach</p>\n</blockquote>\n<p>The idea is to break a long and not so readable code into smaller parts. Also, each individual part needs to access variables etc.</p>\n<p>For this you can use a <code>private extension</code> (unless it's in another file, then skip <code>private</code>):</p>\n<pre><code>struct ContentView: View {\n @State private var sliderValue = 1.0\n\n var body: some View {\n VStack {\n Image(&quot;albumCover&quot;)\n infoView\n sliderView\n actionsView\n bottomView\n }\n }\n}\n</code></pre>\n<pre><code>private extension ContentView {\n var infoView: some View {\n HStack {\n VStack {\n Text(&quot;Album name&quot;)\n Text(&quot;Artist name&quot;)\n }\n Spacer()\n Button(action: {}) {\n Image(systemName: &quot;heart&quot;)\n }\n }\n .padding()\n }\n}\n</code></pre>\n<pre><code>private extension ContentView {\n var sliderView: some View {\n HStack {\n Text(&quot;0&quot;)\n Slider(value: $sliderValue)\n Text(&quot;-5:00&quot;)\n }\n .padding()\n }\n}\n</code></pre>\n<pre><code>private extension ContentView {\n var actionsView: some View {\n HStack {\n Button(action: {}) {\n Image(systemName: &quot;shuffle&quot;)\n }\n Spacer()\n Button(action: {}) {\n Image(systemName: &quot;backward.end&quot;)\n }\n Spacer()\n Button(action: {}) {\n Image(systemName: &quot;play&quot;)\n }\n Spacer()\n Button(action: {}) {\n Image(systemName: &quot;forward.end&quot;)\n }\n Spacer()\n Button(action: {}) {\n Image(systemName: &quot;repeat&quot;)\n }\n }\n .padding()\n }\n}\n</code></pre>\n<pre><code>private extension ContentView {\n var bottomView: some View {\n HStack {\n Button(action: {}) {\n Image(systemName: &quot;hifispeaker&quot;)\n }\n Spacer()\n Button(action: {}) {\n Image(systemName: &quot;music.note.list&quot;)\n }\n }\n .padding()\n }\n}\n</code></pre>\n<p>Note that you can declare <code>sliderValue</code> directly in <code>ContentView</code>:</p>\n<pre><code>struct ContentView: View {\n @State private var sliderValue = 1.0\n</code></pre>\n<p>and access it in the extension:</p>\n<pre><code>private extension ContentView {\n var sliderView: some View {\n Slider(value: $sliderValue)\n</code></pre>\n<hr />\n<p>But the code above still doesn't address the problem of repeating blocks of code in your <code>ContentView</code>. See how often this block is reused:</p>\n<pre><code>Button(action: {}) {\n Image(systemName: &quot;hifispeaker&quot;)\n}\n</code></pre>\n<p>What if you want to apply a modifier to every Image?</p>\n<p>A solution may be to extract the repeating code to one function:</p>\n<pre><code>private extension ContentView {\n func customButton(imageName: String, action: @escaping () -&gt; Void) -&gt; some View {\n Button(action: action) {\n Image(systemName: imageName)\n }\n }\n}\n</code></pre>\n<p>and use it like this:</p>\n<pre><code>private extension ContentView {\n var bottomView: some View {\n HStack {\n customButton(imageName: &quot;hifispeaker&quot;, action: {})\n customButton(imageName: &quot;music.note.list&quot;, action: {})\n }\n .padding()\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-02T19:08:31.603", "Id": "248831", "ParentId": "245972", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T19:08:54.640", "Id": "245972", "Score": "3", "Tags": [ "swift", "ios", "macos", "swiftui" ], "Title": "Break music player into usable components in SwiftUI" }
245972
<p>I'm new programmer and I'm working on Xamarin MVVM app and I have a pin view like</p> <p><a href="https://i.stack.imgur.com/gXG3I.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gXG3I.png" alt="enter image description here" /></a></p> <p>So, basically I have numbers from <code>0-9</code> if you pick one number its visible then if you pick a second one first one changed to <code>*</code> and I store all numbers into string called <code>PinCode</code></p> <p>ViewModel Code:</p> <pre><code> public string PinCode { get; set; } = string.Empty; private async Task&lt;bool&gt; SelectedButton(Button button) { //If button is a number then if (button.Text != null) { if (PinCode.Length &lt; 4) { PinCode = PinCode + button.Text; //Assign every number field text depending of PinCode length if (PinCode.Length == 1) { PinNumberOne = button.Text; } else if (PinCode.Length == 2) { PinNumberTwo = button.Text; PinNumberOne = &quot;*&quot;; } else if (PinCode.Length == 3) { PinNumberThree = button.Text; PinNumberOne = &quot;*&quot;; PinNumberTwo = &quot;*&quot;; } else if (PinCode.Length == 4) { PinNumberFour = button.Text; PinNumberOne = &quot;*&quot;; PinNumberTwo = &quot;*&quot;; PinNumberThree = &quot;*&quot;; } } } // if it's backspace button then else { PinCode = PinCode.Remove(PinCode.Length - 1); if (PinCode.Length == 3) { PinNumberFour = &quot;_&quot;; } else if (PinCode.Length == 2) { PinNumberFour = &quot;_&quot;; PinNumberThree = &quot;_&quot;; } else if (PinCode.Length == 1) { PinNumberFour = &quot;_&quot;; PinNumberThree = &quot;_&quot;; PinNumberTwo = &quot;_&quot;; } else if (PinCode.Length == 0) { PinNumberFour = &quot;_&quot;; PinNumberThree = &quot;_&quot;; PinNumberTwo = &quot;_&quot;; PinNumberOne = &quot;_&quot;; } } return true; } </code></pre> <p>As you can see, I have a lot of repeated code and I know it's possible to improve this method much better, but I can not find the way. If you guys have an idea of a recursion or how can I refactor this code to do something much clear and clean I really appreciate it. Regards</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T19:49:39.883", "Id": "483253", "Score": "1", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here (since many users want to _refactor repeated code_). Please [edit] to the site standard, which is for the title to simply state the task accomplished by the code. Please see [How to get the best value out of Code Review: Asking Questions](https://codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T21:16:35.290", "Id": "483259", "Score": "0", "body": "Put `PinNumber*` in an array. Change the array values by index. Iterate the array by loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T21:31:12.573", "Id": "483260", "Score": "0", "body": "Can you show me how can I iterate and replace that length... I know how can I iterate an array but I don't see how can I use in code instead if and else conditions @AlexanderPetrov" } ]
[ { "body": "<p>This is a common problem. Sometimes it's tricky to generalise a process even when its iterative in nature.</p>\n<p>By keeping track of both:</p>\n<ul>\n<li>the location of the user's cursor (<code>cursor_position</code>), and</li>\n<li>an <strong>iterable</strong> data structure storing which characters are shown (<code>pinNumbers</code>),</li>\n</ul>\n<p>it is possible to implement this behaviour without so much repeated code. This gave the desired behaviour after some thorough testing (in my imagination).</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public string PinCode { get; set; } = string.Empty;\n\nprivate int cursor_position = -1;\nprivate string[] pinNumbers = new string[] {&quot;_&quot;, &quot;_&quot;, &quot;_&quot;, &quot;_&quot;};\n\n private async Task&lt;bool&gt; SelectedButton(Button button)\n {\n //If button is a number then\n if (button.Text != null)\n {\n if ( cursor_position &lt; 3 )\n {\n PinCode = PinCode + button.Text;\n\n if ( cursor_position &gt; 0 )\n {\n pinNumbers[cursor_position] = &quot;*&quot;;\n }\n\n cursor_position += 1;\n pinNumbers[cursor_position] = button.Text;\n }\n } else { // apparently backspace?\n if ( cursor_position &gt;= 0 )\n {\n PinCode = PinCode.Remove(PinCode.Length - 1);\n pin_numbers[cursor_position] = &quot;_&quot;;\n cursor_position -= 1;\n }\n }\n\n pinNumberOne = pinNumbers[0]; // update actual shown values with array\n pinNumberTwo = pinNumbers[1]; // you could probably take out the &quot;pinNumberX&quot; middleman\n pinNumberThree = pinNumbers[2]; // but I dont know what relation these variables have to\n pinNumberFour = pinNumbers[3]; // the rest of your code\n\n return true;\n }\n</code></pre>\n<p>Depending on how you are assigning values to the actual rendered characters you may be able to remove the first four of the last five lines. You likely could just refer the rendered components directly to the values in the <code>pinNumbers</code> array.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T14:36:14.190", "Id": "483386", "Score": "0", "body": "@yamfox missed a semicolon on line 3, and missing closing braces on line 38." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T05:28:38.913", "Id": "246023", "ParentId": "245973", "Score": "3" } }, { "body": "<p>You really need to store the original values into an <code>int</code> array or collection. The reason behind that is you don't need to recasting the values every now and then. Keep the original values in their correct form, and then cast them to <code>string</code> or any other type whenever needed. If you just keep going doing the same concept (using strings on everything) you'll end up having many parts that need to be refactored, and probably it will impact the overall performance.</p>\n<p>Your Pin Code can be simplified by using <code>string[]</code> for the code mask, and <code>List&lt;int&gt;</code> for the actual integers.</p>\n<pre><code>public string PinCode { get; set; } = string.Empty;\n\nprivate string[] _codeMask = new string[] { &quot;_&quot;, &quot;_&quot;, &quot;_&quot;, &quot;_&quot; };\n\nprivate List&lt;int&gt; _pinNumber = new List&lt;int&gt;(4); // limit list size to 4 elements, if you remove it would dynamic size. \n\nprivate async Task&lt;bool&gt; SelectedButton(Button button)\n{\n if(PinCode == 4) { return true; }\n \n // validate input\n if(int.TryParse(button.Text, out int number) &amp;&amp; (number &lt; 10 &amp;&amp; number &gt; 0))\n {\n if(_pinNumber.Count == 4) { return; } \n \n _pinNumber.Add(number);\n \n var maskPosition = _pinNumber.Count - 2;\n \n var numberPosition = _pinNumber.Count - 1;\n \n _codeMask[numberPosition] = number.ToString(); \n \n if(maskPosition != -1)\n { \n _codeMask[maskPosition] = &quot;*&quot;;\n }\n \n PinCode = String.Join(' ', _codeMask); \n }\n \n return false;\n}\n</code></pre>\n<p>Then just use the <code>_codeMask</code> or <code>_pinNumber</code> to assign their values to any releated variable. But I would suggest you get rid of <code>PinNumberOne</code> , <code>PinNumberX</code> variables, and use <code>_pinNumber[x]</code> directly. would be more appropriate and much maintainable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T14:32:27.520", "Id": "246041", "ParentId": "245973", "Score": "0" } } ]
{ "AcceptedAnswerId": "246023", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T19:29:49.380", "Id": "245973", "Score": "3", "Tags": [ "c#", ".net", "recursion", "xamarin" ], "Title": "Refactor multiple if-else conditions when condition is a minor change" }
245973
<p>I have completed <a href="https://www.codewars.com/kata/585d7d5adb20cf33cb000235/python" rel="noreferrer">this</a> question and I am wondering what is the fastest way to solve it.</p> <p>The question is <em><strong>&quot;There is an array with some numbers. All numbers are equal except for one. Try to find it!&quot;</strong></em></p> <p>Example:</p> <pre class="lang-py prettyprint-override"><code>find_uniq([ 1, 1, 1, 2, 1, 1 ]) == 2 find_uniq([ 0, 0, 0.55, 0, 0 ]) == 0.55 </code></pre> <p>I came up with the solution:</p> <pre class="lang-py prettyprint-override"><code>from collections import Counter def find_uniq(arr): nums = list(Counter(arr).items()) data = [i for i in nums if i[1] == 1] return data[0][0] </code></pre> <p>I decided on using <code>Counter</code> because I felt comfortable using it but when looking at others answers some use sets and others use counter as well.</p> <p>I am wondering is my code sufficient and which method to solving this question would lead to the fastest time complexity?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T23:10:02.280", "Id": "483417", "Score": "0", "body": "What should this return for `[0, 1]`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T00:37:39.423", "Id": "483421", "Score": "0", "body": "@Cireo As noted by tinstaafl \"The challenge guarantees at least 3 elements. How can you tell which is unique if there are only 2\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T00:47:52.193", "Id": "483422", "Score": "2", "body": "\"There is an array with some numbers. All numbers are equal except for one. Try to find it!\" if arr[0] == arr[1] and arr[0] != arr[2] return arr[2] else return \"I tried\"" } ]
[ { "body": "<p>You can use <code>.most_common</code> to remove the need for the list comprehension. This makes the code easier to read. You will still need to use <code>[0]</code> as it will return a tuple of the key and the value.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def find_uniq(arr):\n return Counter(arr).most_common()[-1][0]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T21:30:57.347", "Id": "245979", "ParentId": "245978", "Score": "7" } }, { "body": "<p>A <code>Counter</code> is basically a &quot;multiset&quot;. The question doesn't ask for a count of the numbers, so counting them may be extra overhead. Here's an possible set implementation:</p>\n<pre><code>def find_uniq(arr):\n a, b = set(arr)\n return a if arr[:3].count(a) &lt; 2 else b\n</code></pre>\n<p>Both implementations pass through the list once, so they are O(n) time complexity. Your list comprehension, my <code>.count(a)</code>, and @Peilonrays' <code>.most_common()</code> are insignificant for large n.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T00:58:42.220", "Id": "245985", "ParentId": "245978", "Score": "6" } }, { "body": "<p>One of things about the solutions presented so far, is they all require iterating over all the elements at least once.</p>\n<p>Using an iterative approach allows you to short circuit the loop when the unique item is found. something like this would work:</p>\n<pre><code>def find_uniq(arr):\n for i in range(len(arr)-1):\n if arr[i] != arr[i+1]:\n if i == 0 and arr[i] != arr[i + 2]:\n return arr[i]\n return arr[i + 1]]\n</code></pre>\n<p>Did some thinking and came up with an optimization which improves the time considerably:</p>\n<pre><code>def find_uniq(arr):\n for i in range(0,len(arr) - 1, 2):\n if arr[i] != arr[i+1]:\n if i == 0:\n if arr[i] != arr[i + 2]:\n return arr[i]\n return arr[i + 1]\n else:\n if arr[i] != arr[i-1]:\n return arr[i]\n return arr[i + 1]\n return arr[-1] \n</code></pre>\n<p>The complexity of this in the worst case is O(n) the lengthy of the array - 1.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T07:09:22.943", "Id": "483283", "Score": "0", "body": "If your code gets a 2-element array, it access `arr[2]`, which is out of bounds." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T07:11:58.770", "Id": "483285", "Score": "16", "body": "The challenge guarantees at least 3 elements. How can you tell which is unique if there are only 2" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T09:47:51.553", "Id": "483301", "Score": "0", "body": "This answer breaks for `[0, 1, 0, 0, 1, 2]`. You will always need to read the whole list, because the unique element could always be the last one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T10:01:31.320", "Id": "483302", "Score": "19", "body": "@Turksarama That is an invalid input as \"All numbers are equal except for one.\" The code works for `[0,0,2]`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T11:48:22.607", "Id": "483311", "Score": "0", "body": "There are two redundant `else`s here. the code will work without them too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T11:54:27.200", "Id": "483312", "Score": "0", "body": "Yes you're right. It's been fixed" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T11:56:21.727", "Id": "483313", "Score": "0", "body": "@tinstaafl Oh you changed the conditions.. I meant the literal string `else:` can be removed & indent be fixed, and it will still work fine. It's one of C++ style preferences. http://clang.llvm.org/extra/clang-tidy/checks/readability-else-after-return.html" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T17:24:53.887", "Id": "483339", "Score": "5", "body": "Rather disappointing that the by far slowest solution gets the most upvotes and gets accepted. See [benchmarks](https://codereview.stackexchange.com/a/246010/219610)." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T02:59:28.527", "Id": "245988", "ParentId": "245978", "Score": "13" } }, { "body": "<p>No matter how the array is traversed, the distinguished element can occur at the end of the traversal. Therefore, it is necessary to go through the entire array in the worst case and <strong>there does not exist an algorithm that can have a better worst-case time complexity than <span class=\"math-container\">\\$n\\$</span></strong>. However, in practise, the actual runtime of your implementation can be improved, as well as the <strong>average-case time complexity</strong>.</p>\n<p>Firstly, your solution converts the key-value pairs of <code>Counter(arr)</code> into a list. Assuming the input is well-formed, this conversion is unnecessary since it is sufficient to return the first key that has a corresponding frequency value of 1. The improved implementation is as follows:</p>\n<pre><code>def find_uniq(arr):\n return next(k for k, freq in Counter(arr).items() if freq == 1)\n</code></pre>\n<p>Secondly, creating a <code>Counter</code> requires going through the entire input array. In most cases, this can be avoided by returning the distinguished element once it is found, as mentioned in <a href=\"https://codereview.stackexchange.com/a/245988/207952\">the previous answer</a>. This approach <strong>improves the average-case time complexity</strong> by a constant factor of 2. Note that if the time complexity is described using the <span class=\"math-container\">\\$O(\\cdot)\\$</span> and <span class=\"math-container\">\\$\\Theta(\\cdot)\\$</span> notations there is no difference, since <strong>these notations only characterize the asymptotic order of growth of runtime given the input size</strong>. More explanations can be found <a href=\"https://www.programiz.com/dsa/asymptotic-notations\" rel=\"noreferrer\">here</a>.</p>\n<p>A Python-specific efficient implementation of this improved approach is to use the <a href=\"https://docs.python.org/3/library/itertools.html#itertools.groupby\" rel=\"noreferrer\">itertools.groupby</a> function, as shown in the following. It avoids an explicit <code>for</code>-loop in Python, which is typically slower than an implicit-loop-based implementation, such as <code>Counter(arr)</code>.</p>\n<pre><code>from itertools import groupby\n\ndef find_uniq(arr):\n group_iter = groupby(arr)\n k1, g1 = next(group_iter)\n c1 = len(list(g1))\n k2, g2 = next(group_iter)\n if c1 &gt; 1:\n # Group g1 has more than one element\n return k2\n try:\n # Group g2 has more than one element\n next(g2)\n next(g2)\n return k1\n except StopIteration:\n # Both g1 and g2 has one element\n return k2 if next(group_iter)[0] == k1 else k1\n</code></pre>\n<p><strong>Update:</strong> @HeapOverflow provides <a href=\"https://codereview.stackexchange.com/a/246008/207952\">an improved version</a> of this implementation in his answer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T07:14:37.343", "Id": "483286", "Score": "1", "body": "How about O(n-1)? That's better than O(n)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T07:47:29.190", "Id": "483290", "Score": "8", "body": "@tinstaafl O(n-1) is the same as O(n). If an algorithm is O(n), it means the runtime is upper-bounded by a linear function of the input size n when n is sufficiently large. Actual runtimes of both 2n and 0.01n are both O(n). I have edited my answer to be more accurate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T14:35:23.330", "Id": "483324", "Score": "1", "body": "I was going to say \"improves the average-case time complexity\" should maybe just be \"average-case time\", but I guess we can say \"complexity\" and be more specific than \"complexity *class*\" (big-O or theta) where you drop all constant factors and smaller terms. I also wanted to point out that an early-out improves the best-case time to O(1), when the first 3 elements differ. (Or with SIMD, if the first 4 elements aren't all equal, then you only have to look at 1 vector.) Also +1 for the Python specific ways of reducing interpreter overhead, which is *massive* for CPython." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T21:40:36.800", "Id": "483347", "Score": "2", "body": "An improved version of your second solution is now by far [the fastest](https://codereview.stackexchange.com/a/246010/219610) :-)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T06:25:39.600", "Id": "245993", "ParentId": "245978", "Score": "13" } }, { "body": "<p>Another one going only as far as necessary, with O(1) to check whether the first value is the outlier and otherwise simple O(n) to search for the outlier.</p>\n<pre><code>def find_uniq(arr):\n a = arr[0]\n if a not in arr[1:3]:\n return a\n for b in arr:\n if b != a:\n return b\n</code></pre>\n<p>Slight variation, getting the duplicate value from the first three and then searching the non-dupe:</p>\n<pre><code>def find_uniq(arr):\n dupe = sorted(arr[:3])[1]\n for x in arr:\n if x != dupe:\n return x\n</code></pre>\n<p>Another variation, finding a difference pair first:</p>\n<pre><code>def find_uniq(arr):\n a = arr[0]\n for b in arr:\n if b != a:\n return b if a in arr[1:3] else a\n</code></pre>\n<p>Optimized version of <a href=\"https://www.codewars.com/kata/reviews/5941972edacd78ae0a00013c/groups/59428499985bf99a9100006f\" rel=\"nofollow noreferrer\">this</a>, also O(n) because, you know, Timsort:</p>\n<pre><code>def find_uniq(arr):\n arr.sort()\n return arr[-(arr[0] == arr[1])]\n</code></pre>\n<p>Optimized version of GZ0's <code>groupby</code> solution, faster and taking only O(1) space:</p>\n<pre><code>def find_uniq(arr):\n group_iter = groupby(arr)\n k1, _ = next(group_iter)\n k2, g2 = next(group_iter)\n next(g2)\n return k1 if k2 in g2 else k2\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T15:43:32.980", "Id": "246008", "ParentId": "245978", "Score": "7" } }, { "body": "<p><strong>Benchmarks!</strong></p>\n<p>Benchmarks for lists with a thousand or a million elements, with the unique element in the middle of the array to reflect the &quot;typical&quot;/&quot;average&quot; case. The results are times, so lower=faster.</p>\n<pre><code>n=1000\n0.90 find_uniq_Jacques\n1.18 find_uniq_tinstaafl_1\n0.59 find_uniq_tinstaafl_2\n0.88 find_uniq_GZ0_1\n0.14 find_uniq_GZ0_2\n0.88 find_uniq_Peilonrayz\n0.22 find_uniq_RootTwo\n0.26 find_uniq_HeapOverflow_1\n0.28 find_uniq_HeapOverflow_2\n0.26 find_uniq_HeapOverflow_3\n0.09 find_uniq_HeapOverFlow_Codewars\n0.06 find_uniq_HeapOverflow_GZ0\n0.57 unique_different_ethiy\n0.28 find_uniq_KyleG_1\n0.25 find_uniq_KyleG_2\n\nn=1000000\n0.94 find_uniq_Jacques\n1.36 find_uniq_tinstaafl_1\n0.68 find_uniq_tinstaafl_2\n0.99 find_uniq_GZ0_1\n0.19 find_uniq_GZ0_2\n0.98 find_uniq_Peilonrayz\n0.19 find_uniq_RootTwo\n0.23 find_uniq_HeapOverflow_1\n0.26 find_uniq_HeapOverflow_2\n0.25 find_uniq_HeapOverflow_3\n0.09 find_uniq_HeapOverFlow_Codewars\n0.04 find_uniq_HeapOverflow_GZ0\n0.57 unique_different_ethiy\n0.28 find_uniq_KyleG_1\n0.22 find_uniq_KyleG_2\n</code></pre>\n<p>Done with Python 3.8.1 32 bit on Windows 10 64 bit.</p>\n<p>Benchmark code:</p>\n<pre><code>from timeit import timeit\nfrom collections import Counter\nfrom itertools import groupby\n\nsolutions = []\ndef register(solution):\n solutions.append(solution)\n return solution\n\n@register\ndef find_uniq_Jacques(arr):\n nums = list(Counter(arr).items())\n data = [i for i in nums if i[1] == 1]\n return data[0][0]\n\n@register\ndef find_uniq_tinstaafl_1(arr):\n for i in range(len(arr)-1):\n if arr[i] != arr[i+1]:\n if i == 0 and arr[i] != arr[i + 2]:\n return arr[i]\n return arr[i + 1]\n\n@register\ndef find_uniq_tinstaafl_2(arr):\n for i in range(0,len(arr) - 1, 2):\n if arr[i] != arr[i+1]:\n if i == 0:\n if arr[i] != arr[i + 2]:\n return arr[i]\n return arr[i + 1]\n else:\n if arr[i] != arr[i-1]:\n return arr[i]\n return arr[i + 1]\n return arr[-1]\n\n@register\ndef find_uniq_GZ0_1(arr):\n return next(k for k, freq in Counter(arr).items() if freq == 1)\n\n@register\ndef find_uniq_GZ0_2(arr):\n group_iter = groupby(arr)\n k1, g1 = next(group_iter)\n c1 = len(list(g1))\n k2, g2 = next(group_iter)\n if c1 &gt; 1:\n # Group g1 has more than one element\n return k2\n try:\n # Group g2 has more than one element\n next(g2)\n next(g2)\n return k1\n except StopIteration:\n # Both g1 and g2 has one element\n return k2 if next(group_iter)[0] == k1 else k1\n\n@register\ndef find_uniq_Peilonrayz(arr):\n return Counter(arr).most_common()[-1][0]\n\n@register\ndef find_uniq_RootTwo(arr):\n a, b = set(arr)\n return a if arr[:3].count(a) &lt; 2 else b\n\n@register\ndef find_uniq_HeapOverflow_1(arr):\n a = arr[0]\n if a not in arr[1:3]:\n return a\n for b in arr:\n if b != a:\n return b\n\n@register\ndef find_uniq_HeapOverflow_2(arr):\n dupe = sorted(arr[:3])[1]\n for x in arr:\n if x != dupe:\n return x\n\n@register\ndef find_uniq_HeapOverflow_3(arr):\n a = arr[0]\n for b in arr:\n if b != a:\n return b if a in arr[1:3] else a\n\n@register\ndef find_uniq_HeapOverFlow_Codewars(arr):\n arr.sort()\n return arr[-(arr[0] == arr[1])]\n\n@register\ndef find_uniq_HeapOverflow_GZ0(arr):\n group_iter = groupby(arr)\n k1, _ = next(group_iter)\n k2, g2 = next(group_iter)\n next(g2)\n return k1 if k2 in g2 else k2\n\n@register\ndef unique_different_ethiy(iterable):\n # assert isinstance(iterable, Iterable)\n # assert len(iterable) &gt; 2\n if iterable[0] != iterable[1]:\n return iterable[0] if iterable[1] == iterable[2] else iterable[1]\n else:\n for element in iterable[2:]:\n if element != iterable[1]:\n return element\n\n@register\ndef find_uniq_KyleG_1(arr):\n common = arr[0]\n if common not in arr[1:3]:\n return common\n for a, b in zip(arr[1::2], arr[2::2]):\n if a != b:\n if a == common:\n return b\n else:\n return a\n return arr[-1]\n\n@register\ndef find_uniq_KyleG_2(arr):\n iterator = iter(arr)\n common = next(iterator)\n if common not in arr[1:3]:\n return common\n for a, b in zip(iterator, iterator):\n if a != b:\n if a == common:\n return b\n else:\n return a\n return arr[-1]\n\n# Run the benchmarks\nfor e in 3, 6:\n n = 10**e\n number = 10**(7 - e) # fewer number of runs for larger n\n print(f'{n=}')\n arr = [0] * n\n arr[n // 2] = 1\n\n # Repeat round-robin to reduce effects of CPU speed changes etc\n timeses = [[] for _ in solutions]\n for i in range(20):\n for solution, times in zip(solutions, timeses):\n arrs = iter([arr[:] for _ in range(number)])\n t = timeit(lambda: solution(next(arrs)), number=number)\n times.append(t)\n print(i, end=' ')\n print()\n for solution, times in zip(solutions, timeses):\n print('%.2f' % min(times), solution.__name__)\n print()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T20:10:52.623", "Id": "483343", "Score": "3", "body": "Thank you for the comparisons I was also curious." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T22:52:31.590", "Id": "483353", "Score": "2", "body": "Thanks for improving my solution and the benchmarking effort. Since the runtime of early-exit solutions depends on the position of the distinguished element, it is better to test different kinds of inputs. More specifically, you may conduct three kinds of tests and output the corresponding runtimes:\n(1) best-case: the distinguished element occurs at the beginning;\n(2) worse-case: the distinguished element occurs at the end;\n(3) average-case: generate all possible inputs (i.e. one input for each occuring position of the distinguished element) and take the average runtime." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T00:11:18.803", "Id": "483356", "Score": "0", "body": "@GZ0 Hmm, I'm not really interested in best-case unless I have reason to believe that it's relevant (that's why I mentioned that the `sort` solution is O(n) here, as this problem's inputs are pretty much best-cases for it). Worst-case... meh, since all posted solutions are O(n) both worst-case and average-case, I'm more interested in average-case. So my current benchmark attempts to do average-case. Maybe I'll redo it with different unique-element positions tomorrrow, but I'd be surprised if it changed much." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T00:50:42.183", "Id": "483360", "Score": "1", "body": "@HeapOverflow (1) Best-case scenarios are relevant because tinstaafl's iterative solution is supposed to rank better in those cases. (2) Worst-case scenarios could also result in a different ranking. Meanwhile, they reflect the differences of implementation overhead, which is independent of the differences caused by the choice of early-exiting. If you don't have much time, it is fine that you only show the average-case scenarios. But then you need to be VERY careful in your conclusion and explicitly mentions that the winner is based on a comparison of average-case runtime." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T10:58:58.397", "Id": "483368", "Score": "2", "body": "@GZ0 Yes, best-case is \"relevant\" for determining who's fastest at best-cases. But who cares about that? These best-cases are irrelevantly rare and even when they do occur, they contribute irrelevantly little to the overall time. So they're irrelevant² :-) Yes, worst-case should result in a different ranking, but again, the complexity class is the same for average and worst, and worst-case should take only about twice the time, so worst-case is not really that interesting. In my opinion we care about worst case when it's both realistic that it actually occurs and it's catastrophic. I had a ..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T10:59:01.430", "Id": "483369", "Score": "0", "body": "... look now at the [test cases at Codewars](https://www.codewars.com/kata/585d7d5adb20cf33cb000235/discuss/python) (the stated source of the problem) and it agrees: The performance tests are with random positions for the unique elements, i.e., average-case. But ok, I'll phrase the introduction differently. Btw, I simplified your solution further, by ignoring the size of the first group :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T12:51:30.047", "Id": "483373", "Score": "0", "body": "@HeapOverflow A complete comparison of the performance of algorithms needs to consider different kinds of inputs. When you say the best and worst cases are rare, it is based on the assumption that the position of the distinguished element follows a uniform distribution. This may not always be the case in a particular problem setting. E.g., in a particular situation, it is possible that the distinguished element occurs mostly at the beginning of the input (near-best cases). Therefore, a complete understanding of algorithm performances in different scenarios can provide a better guidance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T12:51:37.403", "Id": "483374", "Score": "0", "body": "... This problem may be unimportant so that it is not worth the effort for a complete comparison. But for popular algorithms such as those for sorting, it is very common to analyze their performances in different scenarios. In one of your solutions, you mentioned that TimSort is linear when the list is near sorted. Would you say the best and worst case performances of TimSort are not interesting to study because these cases are rarer (probability of 1 / n!) than the current problem (probability of 1 / n)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T14:12:33.053", "Id": "483379", "Score": "0", "body": "@GZ0 Yes, but in this problem I have no reason to believe that the distribution is non-uniform, and looking at the source of the problem (Codewars) shows that it *is* uniform there. And again, I find best-case irrelevant not just for the rarity but also for each occurrance's tiny impact. You'd need an *extremely* biased distribution for the best-cases to matter in the whole picture. If you have sizes up to a million, then you probably need tens of thousands of best-cases in order to have an impact that's significant compared to the impact of just a *single* average case. For worst-case, ..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T14:12:37.937", "Id": "483380", "Score": "1", "body": "... again, factor 2. Not that interesting even if you do have reason to believe the distribution is heavily biased towards worst-cases. For Timsort there *is* reason to believe that \"best-cases\" do occur. As [Wikipedia](https://en.wikipedia.org/wiki/Timsort) says, *\"Timsort was designed to take advantage of runs of consecutive ordered elements that **already exist in most real-world data**\"*. And besides such \"real-world data\", it's also good for little coding challenges like this one where all allowed inputs are best-cases for Timsort." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T17:23:59.527", "Id": "246010", "ParentId": "245978", "Score": "21" } }, { "body": "<p>This is my first time posting here, so please let me know if there are any conventions I'm missing.</p>\n<p>Here is my solution, which doesn't need to traverse the entire array except by using the built-in <code>sum()</code> function:</p>\n<pre><code>def find_uniq(listToSearch):\n if len(listToSearch) &lt; 3:\n return 'Cannot have one unique value unless there are at least three values.'\n \n #out of three values, minimum of two must be the same\n if listToSearch[0] == listToSearch[1]:\n commonValue = listToSearch[0]\n elif listToSearch[0] == listToSearch[2]:\n commonValue = listToSearch[0]\n elif listToSearch[1] == listToSearch[2]:\n commonValue = listToSearch[1]\n else:\n return 'Array has more than one unique value'\n \n numberOfCommonItems = len(listToSearch) - 1;\n uniqueValue = sum(listToSearch) - numberOfCommonItems * commonValue\n return uniqueValue\n</code></pre>\n<p>These are the test cases I've tried:</p>\n<pre><code>find_uniq([ 1, 1, 1, 2, 1, 1 ])\nfind_uniq([ 0, 0, 0.55, 0, 0 ])\nfind_uniq([ 0, 0, -0.55, 0, 0 ])\nfind_uniq[ 1, 1.0, 1, 2, 1, 1 ])\n\n</code></pre>\n<p>And these are the outputs:</p>\n<pre><code>2\n0.55\n-0.55\n2.0\n\n</code></pre>\n<p>This solution is O(n) as it only has to perform one extra addition per extra element of the array. Besides that, assuming the data format is valid, there are a maximum of four if statements, one multiplication operation and one subtraction operation.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T10:37:53.537", "Id": "483366", "Score": "0", "body": "Fails 40% of the test cases at Codewars." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T10:56:29.277", "Id": "483367", "Score": "0", "body": "I've never been on Codewars. How do I find the test cases?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T11:21:47.087", "Id": "483370", "Score": "0", "body": "I don't think you can see the test cases before you solved it, but if you paste your code there and click ATTEMPT, you'll see the issue." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T13:47:04.123", "Id": "483376", "Score": "1", "body": "Welcome to Code Review. What we do here is examine the code in the original post and the the author of the original post how that code can be improved. It isn't until the last paragraph of your answer that you come close to to reviewing the code. Alternate solutions are not considered good answers on Code Review." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T09:09:33.213", "Id": "246028", "ParentId": "245978", "Score": "0" } }, { "body": "<p>First, check that there are, at least, 3 elements otherwise this is undefined!</p>\n<p>Personally, I would check the first and second elements:</p>\n<ol>\n<li>If different: one of them is the one you are looking for. Compare with third element.</li>\n<li>If equal: iterate over all elements until you find it.</li>\n</ol>\n<p>This seems to be the most optimal solution:</p>\n<pre><code>from collections.abc import Iterable\n\ndef unique_different(iterable):\n assert isinstance(iterable, Iterable)\n assert len(iterable) &gt; 2\n if iterable[0] != iterable[1]:\n return iterable[0] if iterable[1] == iterable[2] else iterable[1]\n else\n for element in iterable[2:]:\n if element != iterable[1]:\n return element\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T15:09:40.337", "Id": "246083", "ParentId": "245978", "Score": "1" } }, { "body": "<p>Why do <code>n</code> comparisons when you only need ~<code>n/2</code>? We can compare every <em>pair</em> of elements until we find a non-matching pair, then &quot;short-circuit&quot; and return whichever element is unique.</p>\n<pre><code>def find_uniq(arr):\n common = arr[0]\n if common not in arr[1:3]:\n return common\n for a, b in zip(arr[1::2], arr[2::2]):\n if a != b:\n if a == common:\n return b\n else:\n return a\n return arr[-1]\n</code></pre>\n<p>A further improvement would be to use <code>iter</code> to avoid copies of <code>arr</code> being made in the <code>zip</code> statement.</p>\n<pre><code>def find_uniq(arr):\n iterator = iter(arr)\n common = next(iterator)\n if common not in arr[1:3]:\n return common\n for a, b in zip(iterator, iterator):\n if a != b:\n if a == common:\n return b\n else:\n return a\n return arr[-1]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-30T11:25:44.760", "Id": "483788", "Score": "0", "body": "Good point, focusing on the number of comparisons. I'll add it to my benchmark later. Might be faster than my similar solution because of the fewer comparisons, but going through zip might make it slower." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-03T15:48:37.187", "Id": "484277", "Score": "1", "body": "In general, my guess is the `groupby` and the `timsort` solutions will be the fastest, purely because they are both super tight C code that is written to take advantage of long runs of data. My version *might* be beneficial if your compare is expensive enough. Because the test data is an array of the exact same object instance (`[0]*n`), comparisons are almost free." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-03T21:03:18.453", "Id": "484316", "Score": "1", "body": "Right, my test data is rather artificial. Then again, so is the problem :-). (And the original test case generator at Codewars also does pretty much the same.)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-28T19:34:58.473", "Id": "246142", "ParentId": "245978", "Score": "1" } } ]
{ "AcceptedAnswerId": "245988", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T21:21:45.343", "Id": "245978", "Score": "23", "Tags": [ "python", "performance", "complexity" ], "Title": "The fastest way to find one unique value when all other values are the same" }
245978
<p>I recently created a program that could get information from a client, a name and some text, and then put that into a text file. From there the user can get open the text file straight from the program. I made it in two days. Please give me some tips in ways I can improve it, thank you!</p> <p>The Server:</p> <pre><code>import java.io.*; import java.net.*; import java.nio.*; import java.nio.channels.FileChannel; import java.nio.file.*; public class Server { static boolean isAvailable = false; public static void main(String[] args) throws IOException { // Get both connections to the client ServerSocket serverSocket = new ServerSocket(4999); ServerSocket serverSocket2 = new ServerSocket(4998); Socket socket = serverSocket.accept(); Socket socket2 = serverSocket2.accept(); // Confirm client connection System.out.println(&quot;The client has been connected to the server&quot;); // Get the streams from the client containing the string InputStreamReader fileNameIn = new InputStreamReader(socket.getInputStream()); BufferedReader br = new BufferedReader(fileNameIn); InputStreamReader informationIn = new InputStreamReader(socket2.getInputStream()); BufferedReader br2 = new BufferedReader(informationIn); // Read and assign the strings String fileName = br.readLine(); String fileInformation = br2.readLine(); // Get char array to write to the created file char[] fileInformationC = fileInformation.toCharArray(); // Create file and write to it try (FileChannel fileChannel = (FileChannel) Files.newByteChannel( Path.of(&quot;C:\\Users\\Emman\\&quot; + fileName + &quot;.txt&quot;), StandardOpenOption.CREATE, StandardOpenOption.WRITE )) { int allocatedVal = 1000; ByteBuffer byteBuffer = ByteBuffer.allocate(allocatedVal); for (char c : fileInformationC){ byteBuffer.put((byte) c); // Error handling: it is now impossible for the Buffer to run out of space // However a BufferOverflowException is caught, in case of a problem if (!(byteBuffer.position() == allocatedVal)){ ByteBuffer.allocate(allocatedVal * 2); } } byteBuffer.rewind(); fileChannel.write(byteBuffer); System.out.println(&quot;File has been created and written to, \n&quot; + &quot;Press Enter to open file&quot;); // The input does not matter //noinspection ResultOfMethodCallIgnored System.in.read(); ProcessBuilder processBuilder = new ProcessBuilder(&quot;notepad.exe&quot;, &quot;C:\\Users\\Emman\\&quot; + fileName + &quot;.txt&quot;); processBuilder.start(); } catch (InvalidPathException e) { isAvailable = true; PrintWriter printToClient = new PrintWriter(socket.getOutputStream()); printToClient.write(&quot;\&quot;Error in creating/writing to file \\n\&quot; +\n&quot; + &quot;Due to incorrect/invalid path\&quot; +\n&quot; + &quot;e&quot;); printToClient.close(); } catch (IOException e) { isAvailable = true; PrintWriter printToClient = new PrintWriter(socket.getOutputStream()); printToClient.write(&quot;Error in creating/writing to file \n&quot; + &quot;Due to error in IO&quot; + e); printToClient.close(); } catch (BufferOverflowException e) { isAvailable = true; PrintWriter printToClient = new PrintWriter(socket.getOutputStream()); printToClient.write(&quot;Error in creating/writing to file \n&quot; + &quot;Due to a buffer overflow&quot; + e); printToClient.close(); } } } </code></pre> <p>The Client:</p> <pre><code>import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; public class Client { public static void main(String[] args) throws IOException{ // Create connections to server Socket socket = new Socket(&quot;localhost&quot;, 4999); Socket socket2 = new Socket(&quot;localhost&quot;, 4998); // Create print writer output stream to give to server PrintWriter pr = new PrintWriter(socket.getOutputStream()); PrintWriter pr2 = new PrintWriter(socket2.getOutputStream()); // Create a buffered reader for reading the file name and information BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) ); // Get the file names and information String fileName = br.readLine(); String information = br.readLine(); // Put in the file Name and the file information pr.write(fileName); pr.close(); pr2.write(information); pr2.close(); // Checking whether the error message is available, // if not only one line of code is read, wasting barely any time if(Server.isAvailable){ InputStreamReader errorInfoIn = new InputStreamReader(socket.getInputStream()); BufferedReader readErrorInfo = new BufferedReader(errorInfoIn); String errorInfo = readErrorInfo.readLine(); System.out.println(errorInfo); errorInfoIn.close(); } } } </code></pre>
[]
[ { "body": "<p>Don't put everything in a single function. That makes your code difficult to maintain and reuse, even by yourself. The ideal function size is so small that one can no longer reasonably extract further functions from it. In your code, each program is just one function, quite the opposite of the ideal.</p>\n<p>All resources should be handled with <code>try</code>-with-resources constructs, not only the <code>fileChannel</code>.</p>\n<p>It is not possible for a reviewer to run your program without changing it first, because you use an absolute, operating-system-specific and user-specific path in your program: <code>Path.of(&quot;C:\\\\Users\\\\Emman\\\\&quot; + fileName + &quot;.txt&quot;)</code>.</p>\n<p>If you're serious about learning network programming, you may want to do some sanitation to <code>fileName</code>. What if it contains <code>..</code>? What if somebody sends <code>..\\..\\WINNT\\explorer.exe</code> or something like that as filename?</p>\n<p>The way how your program is written, <code>isAvailable</code> can and should be a local variable. In general, having non-<code>final</code> <code>static</code> variables is considered bad design. It prevents multiple instances of your class to function independently in parallel.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T16:00:13.440", "Id": "246009", "ParentId": "245980", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T21:45:15.173", "Id": "245980", "Score": "5", "Tags": [ "java", "file", "io", "socket" ], "Title": "A Program that gets text from a client and puts it into a file on a server" }
245980
<p>So this is my first time writing a Lexer, and I want to make sure I'm doing it right. The lexer is not complete for a programming language right now, because I think I can easily add more stuff later. Here is the code:</p> <p><code>main.cpp</code></p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;memory&gt; #include &lt;unordered_map&gt; #include &quot;lexer.h&quot; std::vector&lt;std::unique_ptr&lt;table_entry&gt;&gt; symbol_table; int main(int argc, char **argv) { --argc; ++argv; std::string input_string; std::ifstream file(*argv); std::string next_line; char last_char; while (std::getline(file, next_line)) { last_char = next_line.back(); next_line.pop_back(); input_string.append(next_line + &quot;\n&quot;); } input_string.pop_back(); input_string.append(std::string(1, last_char)); // std::cout &lt;&lt; input_string &lt;&lt; std::endl; init_lexer(&amp;input_string); table_entry* next_token; while((next_token = next())-&gt;type != token_type::end) { // Just For Testing, I'll remove this later. std::cout &lt;&lt; next_token-&gt;lexme &lt;&lt; &quot; &quot; &lt;&lt; next_token-&gt;type &lt;&lt; std::endl; } } </code></pre> <p><code>lexer.h</code></p> <pre><code>#ifndef LEXER #define LEXER #include &lt;utility&gt; #include &lt;utility&gt; #include &lt;utility&gt; #include &lt;vector&gt; #include &lt;list&gt; #include &lt;unordered_set&gt; #include &lt;sstream&gt; #include &lt;string&gt; #define letter_pair(num) std::make_pair(num, 'a'), std::make_pair(num, 'b'), std::make_pair(num, 'c'), std::make_pair(num, 'd'), std::make_pair(num, 'e'), std::make_pair(num, 'f'), std::make_pair(num, 'g'), std::make_pair(num, 'h'), std::make_pair(num, 'i'), std::make_pair(num, 'j'), std::make_pair(num, 'k'), std::make_pair(num, 'l'), std::make_pair(num, 'm'), std::make_pair(num, 'n'), std::make_pair(num, 'o'), std::make_pair(num, 'p'), std::make_pair(num, 'q'), std::make_pair(num, 'r'), std::make_pair(num, 's'), std::make_pair(num, 't'), std::make_pair(num, 'u'), std::make_pair(num, 'v'), std::make_pair(num, 'w'), std::make_pair(num, 'x'), std::make_pair(num, 'y'), std::make_pair(num, 'z') enum token_type { /// Relative Operations /// not_op /* ! */, lt /* &lt; */, le /* &lt;= */, eq /* == */, ne /* != */, gt /* &gt; */, ge /* &gt;= */, /// Assignment /// assign, /* = */ /// Identifiers /// id /* Variable/Function Names */, num /* Numbers */, string_lit /* strings */, decimal /* decimal number */, /// Conrol Flow /// if_stmt /* if */, elif_stmt /* elif */, else_stmt /* else */, while_stmt /* while */, for_stmt /* for */, /// Other /// ws /* Space, New Line, Or Tabs */, end /* End Of File */ }; struct table_entry { std::string lexme; token_type type; int line; int col; table_entry(std::string &amp;lexme, token_type token_type, int line, int col) : lexme(lexme), type(token_type), line(line), col(col) {} }; extern std::vector&lt;std::unique_ptr&lt;table_entry&gt;&gt; symbol_table; int pos = 0, line = 1, col = 1; std::vector&lt;std::list&lt;std::pair&lt;int, char&gt;&gt;&gt; state_machine; std::unordered_set&lt;int&gt; accepting_states; std::string *input; void init_lexer(std::string *_input) { input = _input; /* Set the states of the finite state machine. You can view the output at * State_Machine.png, but good luck understanding it since it was drawn by * yours truly. */ state_machine.push_back({ /* State 0 */ std::make_pair(1, '_'), std::make_pair(2, ' '), std::make_pair(2, '\t'), std::make_pair(2, '\n'), letter_pair(3), std::make_pair(4, '!'), std::make_pair(6, '='), std::make_pair(8, '&lt;'), std::make_pair(10, '&gt;') }); state_machine.push_back({ /* State 1 */ std::make_pair(1, '_'), letter_pair(3) }); state_machine.push_back({ /* State 2 */ std::make_pair(2, '\n'), std::make_pair(2, ' '), std::make_pair(2, '\t') }); state_machine.push_back({ /* State 3 */ std::make_pair(3, '_'), letter_pair(3) }); state_machine.push_back({ /* State 4 */ std::make_pair(5, '=') }); state_machine.emplace_back( /* State 5 */ ); state_machine.push_back({ /* State 6 */ std::make_pair(7, '=') }); state_machine.emplace_back( /* State 7 */ ); state_machine.push_back({ /* State 8 */ std::make_pair(9, '=') }); state_machine.emplace_back( /* State 9 */ ); state_machine.push_back({ /* State 10 */ std::make_pair(11, '=') }); state_machine.push_back({ }); accepting_states.insert(2); accepting_states.insert(3); accepting_states.insert(4); accepting_states.insert(5); accepting_states.insert(6); accepting_states.insert(7); accepting_states.insert(8); accepting_states.insert(9); accepting_states.insert(10); accepting_states.insert(11); } table_entry *generate_entry(int state, std::string &amp;lexme) { switch (state) { case 2: return new table_entry(lexme, token_type::ws, line, col); case 3: if (lexme == &quot;if&quot;) { return new table_entry(lexme, token_type::if_stmt, line, col); } else if (lexme == &quot;elif&quot;) { return new table_entry(lexme, token_type::elif_stmt, line, col); } else if (lexme == &quot;else&quot;) { return new table_entry(lexme, token_type::else_stmt, line, col); } else if (lexme == &quot;for&quot;) { return new table_entry(lexme, token_type::for_stmt, line, col); } else if (lexme == &quot;while&quot;) { return new table_entry(lexme, token_type::while_stmt, line, col); } else { return new table_entry(lexme, token_type::id, line, col); } case 4:return new table_entry(lexme, token_type::not_op, line, col); case 5:return new table_entry(lexme, token_type::ne, line, col); case 6:return new table_entry(lexme, token_type::assign, line, col); case 7:return new table_entry(lexme, token_type::eq, line, col); case 8:return new table_entry(lexme, token_type::lt, line, col); case 9:return new table_entry(lexme, token_type::le, line, col); case 10:return new table_entry(lexme, token_type::gt, line, col); case 11:return new table_entry(lexme, token_type::ge, line, col); default:return nullptr; } } table_entry *next() { if (pos &gt;= input-&gt;length()) { return new table_entry(*(new std::string()), token_type::end, line, col); } int state = 0; int _pos = pos; // Copy the positions to save the initial locations of the tokens int _line = line; int _col = col; std::string next_lexme; while (true) { if (_pos &gt;= input-&gt;length()) { break; } char next = (*input)[_pos]; std::list&lt;std::pair&lt;int, char&gt;&gt; &amp;neighbors = state_machine[state]; bool didFind = false; for (auto &amp;neighbor : neighbors) { if (neighbor.second == next) { state = neighbor.first; didFind = true; break; } } if (!didFind) { break; } if (next == '\n') { _col = 1; _line++; } else { _col++; } _pos++; next_lexme.push_back(next); } if (accepting_states.contains(state)) { table_entry *ans = generate_entry(state, next_lexme); if (ans-&gt;type != token_type::id) { symbol_table.emplace_back(ans); } pos = _pos; line = _line; col = _col; return ans; } else { std::cerr &lt;&lt; &quot;Unexpected Token: &quot; &lt;&lt; next_lexme &lt;&lt; &quot; At Line &quot; &lt;&lt; line &lt;&lt; &quot; And Column &quot; &lt;&lt; col; return new table_entry(*(new std::string()), token_type::end, line, col); } } #endif // LEXER </code></pre> <p>A couple of things:</p> <ol> <li>My source is the Dragon Book, 1st edition.</li> <li>My finite automata is probably not conventional because it is not a standard DFA. The way I'm using it right now is I have a NFA but I keep track of the string going through it. Once I reach the end, I call another method to determine the correct token depending on the string and the state.</li> <li>I know there are better input buffering techniques that I use. What I'm doing right now is just stuffing every line into a string. I'm probably going to make it better later.</li> <li>Incase it helps you visualize it better, here is a drawing of the state machine (sorry for the bad drawing):</li> </ol> <p><a href="https://i.stack.imgur.com/2bLwO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2bLwO.png" alt="enter image description here" /></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T17:38:40.263", "Id": "483340", "Score": "1", "body": "My drawing skills are not any better than yours, and that's why I don't draw such diagrams by hand. Consider using a program made for making diagrams do it for you, like for example [Graphviz](https://graphviz.org/Gallery/directed/fsm.html)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T17:46:44.583", "Id": "483341", "Score": "1", "body": "Also, is there are reason you are implementing a lexer from scratch? There are also lots of tools that can either generate a lexer for you, like [GNU flex](https://en.wikipedia.org/wiki/Flex_lexical_analyser), or libraries that help you write one, like [Boost Spirit](https://theboostcpplibraries.com/boost.spirit)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T21:00:15.987", "Id": "483346", "Score": "0", "body": "@G.Sliepen I just wanted to make one by hand first then use a generator after I understand. I think understanding it will help when I reach high school and then maybe college." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T22:10:42.473", "Id": "245981", "Score": "3", "Tags": [ "c++", "lexer" ], "Title": "Lexical Analyzer In C++" }
245981
<p>I'm new to programming and this is the first thing I'm doing on my own. I would appreciate it if you could point me ways to optimize this RPG dice roller code in Python!</p> <pre><code>import random def dice_reader(): ##this should read messages like '2 d 6 + 3, 5 d 20 + 2 or just 3 d 8'## message = input('&gt;') reader = message.split(' ') times = reader[0] sides = reader[2] output_with_modifier = [] result = [] if len(reader) == 5: modifier = reader[4] else: modifier = 0 for output in range(int(times)): output = random.randint(1, int(sides)) result.append(output) output_with_modifier = [(int(x) + int(modifier)) for x in result] print(f' Dice rolls: {tuple(result)}') if modifier != 0: print(f' With modifier: {tuple(output_with_modifier)}') end = False while end == False: dice_reader() end_message = input('Again? ') if end_message.lower() == 'no': end = True else: pass </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T02:10:47.453", "Id": "483270", "Score": "0", "body": "I've taken the liberty of removing the performance tag, because nothing here will challenge your CPU or memory (even remotely)." } ]
[ { "body": "<h2>Mystery inputs</h2>\n<p>It's clear that there's an implied structure to this input:</p>\n<pre><code>message = input('&gt;')\nreader = message.split(' ')\n</code></pre>\n<p>requiring between four and five tokens. I have no idea what those are, and neither does your user. Replace <code>'&gt;'</code> with an actual description of what's expected here.</p>\n<h2>Unpacking</h2>\n<pre><code>times = reader[0]\nsides = reader[2]\n</code></pre>\n<p>can be</p>\n<pre><code>times, _, sides = reader[:3]\n</code></pre>\n<p>though the discarded second item is suspicious. You do need to show what this is, and it probably shouldn't be there.</p>\n<h2>Looping and overwrites</h2>\n<p>This:</p>\n<pre><code>for output in range(int(times)):\n output_with_modifier = [(int(x) + int(modifier)) for x in result]\n</code></pre>\n<p>does not make sense. If you ask for 100 times, <code>output_with_modifier</code> will be calculated 100 times and thrown away 99 of them. Only the last value will be kept. You probably want to de-indent that last assignment so that it happens outside of the loop.</p>\n<h2>More looping</h2>\n<pre><code>end = False\nwhile end == False:\n dice_reader()\n end_message = input('Again? ')\n if end_message.lower() == 'no':\n end = True\nelse:\n pass\n</code></pre>\n<p>First, delete that <code>else; pass</code> - it isn't doing anything. Also, <code>end == False</code> should be <code>not end</code>; but you shouldn't be using a termination variable at all. If you find a <code>no</code>, simply <code>break</code>.</p>\n<h2>Suggested code</h2>\n<p>Some of this may challenge a beginner, but I like to think that CodeReview is for &quot;aspiring advanced programmers&quot;. I've tried to comment it extensively, but feel free to ask questions in the comments.</p>\n<pre><code>import re\nfrom random import randint\nfrom re import Pattern\nfrom typing import ClassVar, Iterable\n\n\nclass Dice:\n &quot;&quot;&quot;\n One specification for dice rolls in Dungeons &amp; Dragons-like format.\n &quot;&quot;&quot;\n\n def __init__(self, times: int, sides: int, modifier: int = 0):\n if times &lt; 1:\n raise ValueError(f'times={times} is not a positive integer')\n if sides &lt; 1:\n raise ValueError(f'sides={sides} is not a positive integer')\n\n self.times, self.sides, self.modifier = times, sides, modifier\n\n # This is a class variable (basically a &quot;static&quot;) that only has one copy\n # for the entire class type, rather than a copy for every class instance\n # It is a regular expression pattern that will allow us to parse user\n # input.\n INPUT_PAT: ClassVar[Pattern] = re.compile(\n # From the start, maybe some whitespace, then a group named &quot;times&quot;\n # that contains one or more digits\n r'^\\s*(?P&lt;times&gt;\\d+)' \n \n # Maybe some whitespace, then the letter &quot;d&quot;\n r'\\s*d'\n \n # Maybe some whitespace, then a group named &quot;sides&quot; that contains one\n # or more digits\n r'\\s*(?P&lt;sides&gt;\\d+)'\n \n # The beginning of a group that we do not store.\n r'(?:'\n \n # Maybe some whitespace, then a &quot;+&quot; character\n r'\\s*\\+'\n \n # Maybe some whitespace, then a group named &quot;modifier&quot; that\n # contains one or more digits\n r'\\s*(?P&lt;modifier&gt;\\d+)'\n \n # End of the group that we do not store; mark it optional\n r')?'\n \n # Maybe some whitespace, then the end.\n r'\\s*$',\n\n # We might use &quot;d&quot; or &quot;D&quot;\n re.IGNORECASE\n )\n\n # This can only be called on the class type, not a class instance. It\n # returns a new class instance, so it acts as a secondary constructor.\n @classmethod\n def parse(cls, message: str) -&gt; 'Rolls':\n match = cls.INPUT_PAT.match(message)\n if match is None:\n raise ValueError(f'Invalid dice specification string &quot;{message}&quot;')\n\n # Make a new instance of this class based on the matched regular\n # expression.\n return cls(\n int(match['times']),\n int(match['sides']),\n # If there was no modifier specified, pass 0.\n 0 if match['modifier'] is None else int(match['modifier']),\n )\n\n @classmethod\n def from_stdin(cls) -&gt; 'Rolls':\n &quot;&quot;&quot;\n Parse and return a new Rolls instance from stdin.\n &quot;&quot;&quot;\n\n while True:\n try:\n message = input(\n 'Enter your dice specification, of the form\\n'\n '&lt;times&gt;d&lt;sides&gt; [+ modifier], e.g. 3d6 or 4d12 + 1:\\n'\n )\n return cls.parse(message)\n except ValueError as v:\n print(v)\n print('Please try again.')\n\n def roll(self, with_modifier: bool = False) -&gt; Iterable[int]:\n &quot;&quot;&quot;\n Return a generator of rolls. This is &quot;lazy&quot; and will only execute the\n rolls that are consumed by the caller, because it returns a generator\n (not a list or a tuple).\n &quot;&quot;&quot;\n mod = self.modifier if with_modifier else 0\n return (\n randint(1, self.sides) + mod\n for _ in range(self.times)\n )\n\n def print_roll(self):\n print(\n 'Dice rolls:',\n ', '.join(str(x) for x in self.roll()),\n )\n\n if self.modifier != 0:\n print(\n 'With modifier:',\n ', '.join(str(x) for x in self.roll(with_modifier=True)),\n )\n\n\ndef test():\n &quot;&quot;&quot;\n This is an automated test method that does some sanity checks on the Dice\n implementation.\n &quot;&quot;&quot;\n \n d = Dice.parse('3 d 6')\n assert d.times == 3\n assert d.sides == 6\n assert d.modifier == 0\n\n d = Dice.parse('3D6 + 2')\n assert d.times == 3\n assert d.sides == 6\n assert d.modifier == 2\n\n try:\n Dice.parse('nonsense')\n raise AssertionError()\n except ValueError as v:\n assert str(v) == 'Invalid dice specification string &quot;nonsense&quot;'\n\n try:\n Dice.parse('-2d5')\n raise AssertionError()\n except ValueError as v:\n assert str(v) == 'Invalid dice specification string &quot;-2d5&quot;'\n\n try:\n Dice.parse('0d6')\n raise AssertionError()\n except ValueError as v:\n assert str(v) == &quot;times=0 is not a positive integer&quot;\n\n d = Dice.parse('100 d 12+3')\n n = 0\n for x in d.roll(True):\n assert 4 &lt;= x &lt;= 15\n n += 1\n assert n == 100\n\n\ndef main():\n test()\n\n dice = Dice.from_stdin()\n dice.print_roll()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T13:06:44.383", "Id": "483318", "Score": "0", "body": "I should've used comments to clarify what this is all about, my bad lol. This code is for reading messages like \"2 d 10 + 3\", for RPG dice rolling. Although \"d\" is completely useless, it makes for the classic virtual dice roller structure. It should print a message with the structure need for reading. Besides that, I didn't about anything you pointed me out, thanks for the help, I didn't expect any answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T20:33:10.030", "Id": "483344", "Score": "0", "body": "Oh my. Thank you very much for your time and suggestions. I will definitely study that, as didn't expect such an answer. I would also like to extend it a bit and ask another question: I'm a little overwhelmed by the amount of stuff that comes along with Python (Atom, Pycharm, Anaconda, virtual environments) and I don't know where to start. What do I really need to play around with Python a little, but without limiting myself?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T20:41:18.480", "Id": "483345", "Score": "2", "body": "Personally my favourite environment is PyCharm. It goes a long way to suggesting where things are wrong or non-standard." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T02:18:15.067", "Id": "245987", "ParentId": "245982", "Score": "5" } } ]
{ "AcceptedAnswerId": "245987", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-24T22:12:25.487", "Id": "245982", "Score": "6", "Tags": [ "python", "beginner" ], "Title": "Easier ways to make an RPG dice roller code?" }
245982
<p>I'm currently building an application using Passport and bcrypt for user authentication. I've created the registration part. Is there anything I could improve on? I'm still getting the hang of writing in JavaScript and I'm not sure if I'm using arrow functions correctly.</p> <pre class="lang-js prettyprint-override"><code>require('dotenv').config(); const express = require('express'); const bodyParser = require('body-parser'); const ejs = require(&quot;ejs&quot;); const mongoose = require('mongoose'), Schema = mongoose.Schema, bcrypt = require('bcrypt'), saltRounds = 10; const session = require('express-session'); const passport = require('passport'); const passportLocalMongoose = require(&quot;passport-local-mongoose&quot;); const GoogleStrategy = require('passport-google-oauth20').Strategy; const findOrCreate = require('mongoose-findorcreate') const port = process.env.PORT; const app = express(); app.use(express.static(__dirname + '/public')); app.set('view engine', 'ejs'); app.use(bodyParser.urlencoded({ extended: true })); app.use(session({ secret: process.env.SECRET, resave: false, saveUninitialized: false })); app.use(passport.initialize()); app.use(passport.session()); mongoose.connect('mongodb://localhost:27017/userDB', { useNewUrlParser: true, useUnifiedTopology: true }); mongoose.set('useCreateIndex', true); const userSchema = new Schema({ username: { type: String, unique: true, lowercase: true, required: true }, password: String, googleId: String, }); userSchema.pre('save', function(next) { const user = this; // only hash the password if it has been modified (or is new) if (!user.isModified('password')) return next(); // generate a salt bcrypt.genSalt(saltRounds, (err, salt) =&gt; { if (err) return next(err); // hash the password using our new salt bcrypt.hash(req.body.password, saltRounds, (err, hash) =&gt; { if (err) return next(err); // override the cleartext password with the hashed one req.body.password = hash; next(); }); }); }); userSchema.methods.comparePassword = function(candidatePassword, cb) { bcrypt.compare(candidatePassword, this.password, function(err, isMatch) { if (err) return cb(err); cb(null, isMatch); }); }; userSchema.plugin(passportLocalMongoose); userSchema.plugin(findOrCreate); const User = new mongoose.model('User', userSchema); passport.serializeUser((user, done) =&gt; { done(null, user.id); }); passport.deserializeUser((id, done) =&gt; { User.findById(id, (err, user) =&gt; { done(err, user); }); }); passport.use(new GoogleStrategy({ clientID: process.env.CLIENT_ID, clientSecret: process.env.CLIENT_SECRET, callbackURL: 'http://localhost:3000/auth/google/welcome', userProfileURL: 'https://www.googleapis.com/oauth2/v3/userinfo' }, function(accessToken, refreshToken, profile, cb) { User.findOrCreate({ googleId: profile.id }, (err, user) =&gt; { return cb(err, user); }); } )); app.get('/', (req, res) =&gt; { res.render('pages/home'); }); app.get('/auth/google', (req, res) =&gt; { passport.authenticate('google', { scope: ['profile'] }) }); app.get('/auth/google/welcome', passport.authenticate('google', { failureRedirect: '/login' }), (req, res) =&gt; { // Successful authentication, redirect welcome page. res.redirect('/welcome'); }); app.get('/login', (req, res) =&gt; { res.render('pages/login'); }); app.get('/register', (req, res) =&gt; { res.render('pages/register'); }); app.get('/welcome', (req, res) =&gt; { res.render('pages/welcome'); }); app.get('/welcome', (req, res) =&gt; { if (req.isAuthenticated()) { res.render('/register'); } else { res.redirect('/welcome') } }); app.post('/register', (req, res) =&gt; { User.register({ username: req.body.username }, req.body.password, (err, user) =&gt; { if (err) { console.log(err); res.redirect('/register'); } else { passport.authenticate('local')(req, res, () =&gt; { res.redirect('/welcome'); }); } }); }); app.post('/login', (req, res) =&gt; { const user = new User({ username: req.body.username, password: req.body.password }); req.login(user, (err) =&gt; { if (err) { console.log(err); } else { passport.authenticate('local')(req, res, () =&gt; { res.redirect('pages/welcome'); }); } }); }); app.listen(port, () =&gt; { console.log(&quot;Server has started.&quot;); }); </code></pre>
[]
[ { "body": "<p>The use of arrow functions looks okay to me. One advantage to using them is that they can be simplified to a single line but one might hold the opinion that is less readable.</p>\n<p>For example:</p>\n<blockquote>\n<pre><code>app.get('/welcome', (req, res) =&gt; {\n res.render('pages/welcome');\n});\n</code></pre>\n</blockquote>\n<p>Could be simplified to:</p>\n<pre><code>app.get('/welcome', (req, res) =&gt; res.render('pages/welcome'));\n</code></pre>\n<p>Note that while the return value isn’t used, the single line arrow function returns the value of the single expression.</p>\n<hr />\n<p>There is a common convention in JavaScript and many other languages to put constant names in All_CAPS- so the name <code>saltRounds</code> would be changed to <code>SALT_ROUNDS</code> instead.</p>\n<hr />\n<p>There is a single use variable <code>user</code> here:</p>\n<blockquote>\n<pre><code>userSchema.pre('save', function(next) {\n const user = this;\n</code></pre>\n</blockquote>\n<p>I often see code like this when there is a need to reference the context of <code>this</code> in a different function context, but that doesn’t appear to be the case. If it was the case, arrow functions or <code>Function.bind()</code> could eliminate that need.</p>\n<p>Why not just use <code>this</code> in the one spot <code>user</code> is used?</p>\n<hr />\n<p>One possibility to reduce the nesting levels is to use <code>async</code> functions- refer to <a href=\"https://zellwk.com/blog/async-await-express/\" rel=\"nofollow noreferrer\">this article</a> for more information.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T05:54:09.843", "Id": "245991", "ParentId": "245986", "Score": "3" } } ]
{ "AcceptedAnswerId": "245991", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T01:48:30.240", "Id": "245986", "Score": "6", "Tags": [ "javascript", "beginner", "node.js", "mongodb" ], "Title": "creating accounts with passportJs" }
245986
<p>To practice learning x64 AT&amp;T Assembly (GAS), I implemented three solutions for <a href="https://projecteuler.net/problem=1" rel="noreferrer">Project Euler Problem 1</a> (find the sum of all the multiples of 3 or 5 below 1000).</p> <p>The codes and a rough pseudocode sketch of each are shown below. I'd like some open-ended feedback (some more specific questions are at the bottom). To clarify, I am not asking to compare the following solutions (I'm aware of their algorithmic complexities), but they are all working pieces of Assembly that I would like feedback on.</p> <p>Sorry for the poor code formatting, looks like 8-width tabs didn't carry over so well.</p> <p>For all versions, compilation is simply <code>gcc pe001.S -no-pie</code>.</p> <p>Version 1:</p> <pre><code> .global main .text main: xor %rbx, %rbx # sum = 0 xor %rax, %rax # i = 0 sum3: add %rax, %rbx # sum += i add $3, %rax # i += 3 cmp max, %rax # if(rax &lt; max) jl sum3 # goto sum3 xor %rax, %rax sum5: add %rax, %rbx add $5, %rax cmp max, %rax jl sum5 xor %rax, %rax sub15: sub %rax, %rbx add $15, %rax cmp max, %rax jl sub15 mov $fmt, %rdi # printf(fmt, sum) mov %rbx, %rsi xor %rax, %rax # clear this (for printf to work properly) call printf xor %rax, %rax # return(0) ret fmt: .asciz &quot;%d\n&quot; max: .quad 1000 </code></pre> <p>Version 1 Algorithm:</p> <pre><code>int sum = 0; for(int i=0; i&lt;1000; i+=3) if(!(i%3)) sum += i; for(int i=0; i&lt;1000; i+=5) if(!(i%5)) sum += i; for(int i=0; i&lt;1000; i+=15) if(!(i%15)) sum -= i; </code></pre> <p>Version 2:</p> <pre><code> .global main .text main: mov $999, %rax # i = 999 xor %rbx, %rbx # sum = 0 mov $3, %rcx # dividends = 3, 5 mov $5, %r8 iter: push %rax # save divisor (i) xor %rdx, %rdx # set rdx to 0 div %rcx # i/3 =&gt; rax remainder rdx pop %rax # restore divisor (i) test %rdx, %rdx # check if remainder == 0 jz addts # if divides evenly, add to sum push %rax xor %rdx, %rdx div %r8 pop %rax test %rdx, %rdx jz addts deci: # decrement i dec %rax jnz iter mov $fmt, %rdi # printf(&quot;%d\n&quot;, rbx) mov %rbx, %rsi xor %rax, %rax call printf xor %rax, %rax ret addts: # add to sum add %rax, %rbx jmp deci fmt: .asciz &quot;%d\n&quot; </code></pre> <p>Version 2 Algorithm:</p> <pre><code>int sum; for(int i=0; i&lt;1000; i++) if(!(i%3) || !(i%5)) sum += i; </code></pre> <p>Version 3:</p> <pre><code> .global main .text sumtm: # arithmetic SUM up To Max: int sum(int n) mov max, %rax # i = floor(max/n) (result in rax) xor %rdx, %rdx div %rdi mov %rax, %rcx # j = i+1 inc %rcx imul %rcx, %rax # j *= i (= i*(i+1)) shr $1, %rax # j &gt;&gt;= 1 (= i*(i+1)/2) imul %rdi, %rax # j *= n (= n*i*(i+1)/2) ret # return j main: xor %rsi, %rsi # sum = 0 mov $3, %rdi call sumtm add %rax, %rsi # sum += sumtm(3) mov $5, %rdi call sumtm add %rax, %rsi # sum += sumtm(5) mov $15, %rdi call sumtm sub %rax, %rsi # sum -= sumtm(15) mov $fmt, %rdi # printf(&quot;%d\n&quot;, sum) xor %rax, %rax # needed for printf to work correctly call printf xor %rax, %rax # return 0 ret fmt: .asciz &quot;%d\n&quot; max: .quad 999 </code></pre> <p>Version 3 Algorithm:</p> <pre><code>int sumtm(int n) { int i = floor(999/n); return n*i*(i+1)/2; } int sum = sumtm(3) + sumtm(5) - sumtm(15); </code></pre> <hr /> <p>Questions:</p> <ul> <li>Best practices for naming? Is there a common length limit for labels? (From the examples I've seen, it seems like variable names are often very terse and somewhat cryptic.) Common casing convention?</li> <li>Choosing registers? This is the biggest trouble for me. The names are not very intuitive to me, and I'm not sure if there's a commonly-accepted set of guidelines on when to choose what. I was slightly influenced by caller-saved/callee-saved (e.g., use caller-saved registers in a function so as to not worry about pushing/popping it) and the use of explicit registers in certain operations (e.g., reuse <code>%rax</code> as divisor, reuse <code>%rsi</code> as second parameter for <code>printf</code>).</li> <li>Is it common/good practice to follow the ABI's callee/caller-saved registers even in small code snippets like this, and when you have complete control over the code? I'd assume that this is much more important when writing a library, but how important is it for completely self-contained code?</li> <li>Verbosity/comment density? Is this abnormal?</li> <li>Overall efficiency/operator choice?</li> </ul> <p>I'm very new to Assembly, so any other open-ended feedback is welcome.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T06:09:05.837", "Id": "483277", "Score": "2", "body": "Hello, I suggest you to change the title of your question to one describing the task you are implementing, because the actual one is too general and could be applied to several other questions here. You could also add the tag `comparative-review` to your question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T06:13:10.850", "Id": "483280", "Score": "0", "body": "@dariosicily I updated the title to be a little more specific to the questions, but I don't think [tag:comparative-review] would be a good fit. (I'm not asking for a comparison of these solutions; these are all samples of code that I'd like some advice on.) If that makes the scope of this question off-topic, please let me know." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T06:36:16.293", "Id": "483281", "Score": "3", "body": "For me your question is on-topic, mine was just a suggestion that about the title I would add some reference to the euler project." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T08:45:00.607", "Id": "483299", "Score": "1", "body": "It looks like you want all 3 versions reviewed. That's ok, but do note it's quite possible answerers will only pick a subset. I see nothing wrong with this question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-22T01:42:27.427", "Id": "500429", "Score": "0", "body": "[x86-64 Assembly - Sum of multiples of 3 or 5](https://codereview.stackexchange.com/q/253680) is the same problem with NASM, including answers suggesting down-counters instead of division, or unrolling to hide the repeating patterns of 3 and/or 5. (LCM of only 15)" } ]
[ { "body": "<blockquote>\n<p>Sorry for the poor <strong>code formatting</strong>, looks like 8-width tabs didn't carry over so well.</p>\n</blockquote>\n<p>A well known problem on StackExchange...<br />\nI looked at your text in a separate editor and can vouch that your indentations are fine except on the lines that define the labels <em>deci</em>, <em>addts</em>, and <em>sumtm</em>.</p>\n<blockquote>\n<p>Best <strong>practices for naming</strong>? Is there a common length limit for labels? (From the examples I've seen, it seems like variable names are often very terse and somewhat cryptic.) Common casing convention?</p>\n</blockquote>\n<p>Important identifiers should always have descriptive names. In the second snippet e.g. you used <em>deci</em> and <em>addts</em>. I find both not very informative. Since you've written them on a separate line (and thus could not claim 'lack of space'), there's nothing that prevents you from writing the longer <em>DecrementIndex</em> and <em>AddToTheSum</em>. Much clearer!</p>\n<blockquote>\n<p><strong>Choosing registers</strong>? This is the biggest trouble for me. The names are not very intuitive to me, and I'm not sure if there's a commonly-accepted set of guidelines on when to choose what. I was slightly influenced by caller-saved/callee-saved (e.g., use caller-saved registers in a function so as to not worry about pushing/popping it) and the use of explicit registers in certain operations (e.g., reuse <code>%rax</code> as divisor, reuse <code>%rsi</code> as second parameter for <code>printf</code>).</p>\n</blockquote>\n<p>Because you know that division imperatively uses the <code>%rax</code> register, you should perhaps not put <em>i</em> in <code>%rax</code>. Maybe use <code>mov $999, %r9 # i = 999</code>. No more need for the many <code>push</code>/<code>pop</code>'s around these divisions.</p>\n<p>The clever choice you've made in the third program to build the sum in <code>%rsi</code> (for use by <em>printf</em>), would equally work in the other programs.</p>\n<blockquote>\n<p>Is it common/good practice to <strong>follow the ABI</strong>'s callee/caller-saved registers even in small code snippets like this, and when you have complete control over the code? I'd assume that this is much more important when writing a library, but how important is it for completely self-contained code?</p>\n</blockquote>\n<p>In case you're writing your own code, you can and should make the most of the registers that you have at your disposal. Also don't put too much thought in this. Use the registers that give you a comfortable feeling and if need be, the occasional <code>push</code>/<code>pop</code> around a library call won't kill you.</p>\n<blockquote>\n<p>Verbosity/<strong>comment density</strong>? Is this abnormal?</p>\n</blockquote>\n<p>Your commenting is good, but keep in mind that these 3 code snippets must stand on their own. So if you find it useful to write next comments in the first and third programs:</p>\n<pre><code>xor %rax, %rax # clear this (for printf to work properly)\ncall printf\nxor %rax, %rax # return(0)\nret\n</code></pre>\n<p>you should also mention them in the second program, so that a person that only sees the second program can benefit from your observation.</p>\n<blockquote>\n<p><strong>Overall efficiency</strong>/operator choice?</p>\n</blockquote>\n<p>Intel advices against using the 64-bit division with the 128-bit dividend <code>%rdx:%rax</code>. Whenever possible use the 32-bit division with the 64-bit dividend <code>%edx:%eax</code>. In all of these little programs there's nothing that stands in the way of following this advice.</p>\n<p>In fact most everything in these here programs can benefit from using the 32-bit registers instead of the 64-bit registers. The <em>REX</em> prefix will not get encoded and the CPU will zero the high dword automatically. Read about this in the Intel manual.</p>\n<p>Lastly and FWIW, a 1-instruction replacement for <code>mov %rax, %rcx</code> <code>inc %rcx</code> is <code>lea 1(%rax), %rcx</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-03T14:55:46.603", "Id": "484270", "Score": "0", "body": "Thanks for your answer, it really helps clarify some ideas! Everything you said makes sense. The only thing I’m wondering is what you mean by the indentations for the labels not correct" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-09T14:32:45.487", "Id": "484915", "Score": "0", "body": "@JonathanLam The 3 lines where you define the labels *deci*, *addts*, and *sumtm* all have a tail comment that is 1 tab further to the right than all of the other comments that you've written." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-02T19:50:57.580", "Id": "247396", "ParentId": "245990", "Score": "3" } } ]
{ "AcceptedAnswerId": "247396", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T05:42:55.503", "Id": "245990", "Score": "7", "Tags": [ "assembly", "x86" ], "Title": "Project Euler #1 AT&T Assembly" }
245990
<p>I need to manipulate <code>chunks</code> <code>quantity</code> until total will be as close as possible to the <code>requirements</code>. Decimals are ok in the quantity.</p> <p>Again: I can change only <code>quantity</code> property.</p> <p>So if the requirements are {a:500; b:1200; c:1500}, then the <code>quantity</code> field in the <code>chunks</code> array should be changed so that when I run this:</p> <pre><code>// sum all chunks Object.keys(chunks).forEach(chunk=&gt; { Object.keys(total).forEach(id=&gt; { total[id] += chunks[chunk].payload[id] * chunks[chunk].quantity }); </code></pre> <p>It returns an object as close as possible to <code>{a:500; b:1200; c:1500}</code>.</p> <p>How do I do that efficiently?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const chunks = { // &lt;- the chunks chunk1: { quantity: 0, // &lt;- the quantity payload: { a: 19, b: 17, c: 10 } }, chunk2: { quantity: 0, // &lt;- the quantity payload: { a: 17, b: 11, c: 15 } }, chunk3: { quantity: 0, // &lt;- the quantity payload: { a: 7, b: 19, c: 0 } }, chunk4: { quantity: 0, // &lt;- the quantity payload: { a: 14, b: 4, c: 19 } }, chunk5: { quantity: 0, // &lt;- the quantity payload: { a: 3, b: 15, c: 6 } }, chunk6: { quantity: 0, // &lt;- the quantity payload: { a: 10, b: 16, c: 3 } }, chunk7: { quantity: 0, // &lt;- the quantity payload: { a: 2, b: 3, c: 2 } }, chunk8: { quantity: 0, // &lt;- the quantity payload: { a: 14, b: 16, c: 11 } }, chunk9: { quantity: 0, // &lt;- the quantity payload: { a: 7, b: 2, c: 2 } }, chunk10: { quantity: 0, // &lt;- the quantity payload: { a: 1, b: 7, c: 17 } } } const requirements = { // &lt;- the requirements a: 500, b: 1200, c: 1500 } const total = { a: 0, b: 0, c: 0 } // sum all chunks Object.keys(chunks).forEach(chunkId =&gt; { Object.keys(total).forEach(propId =&gt; { total[propId] += chunks[chunkId].payload[propId] * chunks[chunkId].quantity }) }) console.log(total) // &lt;- i need this to be as close as possible to the `requirements`. // MY SOLUTION: const percentages = JSON.parse(JSON.stringify(chunks)) Object.keys(percentages).forEach(chunkId =&gt; { let total = 0 Object.keys(percentages[chunkId].payload).forEach(propId =&gt; { const perc = percentages[chunkId].payload[propId] / (requirements[propId] / 100) percentages[chunkId].payload[propId] = perc total += perc }) Object.keys(percentages[chunkId].payload).forEach(propId =&gt; { percentages[chunkId].payload[propId] = percentages[chunkId].payload[propId] / (total / 100) }) }) const myTotal = { a: 0, b: 0, c: 0 } Array.from(Array(10)).forEach(() =&gt; { Object.keys(percentages).forEach(chunkId =&gt; { let highestPropId let highestPropPercentage = 0 Object.keys(percentages[chunkId].payload).forEach(propId =&gt; { const perc = percentages[chunkId].payload[propId] if (perc &gt; highestPropPercentage) { highestPropPercentage = perc highestPropId = propId } }) const remainingNum = requirements[highestPropId] - myTotal[highestPropId] const koe = 0.5 const multiplier = (remainingNum / chunks[chunkId].payload[highestPropId]) * koe Object.keys(myTotal).forEach(propId =&gt; { myTotal[propId] += chunks[chunkId].payload[propId] * multiplier }) chunks[chunkId].quantity += multiplier }) }) console.log('myTotal', myTotal) /* in the console log output you'll see this: { "a": 499.98450790851257, "b": 1202.1742982865637, "c": 1499.5877967505367 } compare it with the `requirements` object above: const requirements = { // &lt;- the requirements a: 500, b: 1200, c: 1500 } as you see, it's almost the same. I need more efficient solution */</code></pre> </div> </div> </p> <p>It's not accurate and quite inefficient. Any better options?</p> <p>Notes, answering the first comment:</p> <ul> <li>Second snippet contains first snippet and my solution.</li> <li>The <code>quantity</code> is a property in <code>chunks</code> object. Find it in the very beginning of the first snippet</li> <li>&quot;As close as possible&quot; means as close to <code>requirements</code> as mathematically possible.</li> <li>Input is in the first code snippet. To get output, pls run the first snippet.</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T08:30:19.050", "Id": "483298", "Score": "3", "body": "This is not a particularily bad question, but you might want to invest some more time to clarify the problem. Maybe explain how the first code snippet is related to the second one. Define what as close as possible mean. Define what manipulate quantity mean. Maybe show some example intput-output combinations, especialy one that would show an output that one might have not expected and explain why it should return that output rather than a different one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T08:55:51.607", "Id": "483300", "Score": "0", "body": "@slepic alright, i've added answers to your questions" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T12:33:05.957", "Id": "483315", "Score": "3", "body": "Sorry, but that did not help at all. You're gonna have to invest a bit more then 2 minutes and describe the problém as if to someone who knows nothing about it. And btw if the first snippet Is part of the second, then remove the first one, Its just confusing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T00:14:27.133", "Id": "483358", "Score": "1", "body": "I read the question twice and still have no idea what the \"requirements\" are, as in how they relate to the `requirements` object. Can't you share a way smaller example with just one requirement?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T07:51:57.307", "Id": "483430", "Score": "0", "body": "@slepic i've changed code snippet. I hope now everything i clear" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T07:52:56.193", "Id": "483431", "Score": "0", "body": "@GirkovArpa requirements is the `requirements` object. I've changed the code snippet, hope now it's clear" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T12:38:35.777", "Id": "483446", "Score": "0", "body": "Is the code allowed to have chunks with zero quantity?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T16:32:49.903", "Id": "483468", "Score": "2", "body": "I am trying very hard to understand what this question is asking us but it is still unclear what @stkvtflw goal is with this code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-28T05:12:50.577", "Id": "483501", "Score": "1", "body": "When running the code as is, I get negative values for the `quantity` of chunk 4, 6, 7, 8 and 9. It seems rather counterintuitive to me having negative quantities - which would mean, that I have to remove something from a total, that isn't really there to begin with. Or maybe the term `quantity` isn't the right/original name for the value?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-28T06:29:22.550", "Id": "483505", "Score": "0", "body": "Can `quantity` be 0 or negative?" } ]
[ { "body": "<p>You can replace this entire block of code with <code>const percentages = chunks;</code> and your results more precisely match the requirements:</p>\n<pre><code>// MY SOLUTION:\nconst percentages = JSON.parse(JSON.stringify(chunks))\nObject.keys(percentages).forEach(chunkId =&gt; {\n let total = 0\n Object.keys(percentages[chunkId].payload).forEach(propId =&gt; {\n const perc =\n percentages[chunkId].payload[propId] / (requirements[propId] / 100)\n percentages[chunkId].payload[propId] = perc\n total += perc\n })\n Object.keys(percentages[chunkId].payload).forEach(propId =&gt; {\n percentages[chunkId].payload[propId] =\n percentages[chunkId].payload[propId] / (total / 100)\n })\n})\n</code></pre>\n<pre><code>myTotal { a: 500.3204153326983, b: 1200.0002333151795, c: 1499.7678177477337 }\n</code></pre>\n<p>Previously your result was:</p>\n<pre><code>myTotal { a: 499.98450790851257, b: 1202.1742982865637, c: 1499.5877967505367 }\n</code></pre>\n<p>For the record, I still have no idea what you're trying to do.</p>\n<blockquote>\n<p>manipulate chunks quantity until total will be as close as possible to the requirements</p>\n</blockquote>\n<p>Then why not just add the difference so they are equal?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-28T01:33:36.133", "Id": "246106", "ParentId": "245995", "Score": "2" } }, { "body": "<p>From a short review;</p>\n<ul>\n<li><p>Your code is really hard to read/parse, I would not want to maintain this</p>\n</li>\n<li><p>You have no useful comments, <code>// &lt;- the quantity</code> is not useful</p>\n</li>\n<li><p><a href=\"https://stackoverflow.com/questions/5171651/why-is-a-semicolon-required-at-end-of-line\">You should terminate your lines with <code>;</code></a>,</p>\n</li>\n<li><p>I don't know if you have control over how you get the data, but getting it as an object is not helpful, this would be much easier/readable if you got a list instead</p>\n</li>\n<li><p>In fact, this code is full of functional programming on objects, if you really want to do this, you should convert your objects to lists first</p>\n</li>\n<li><p><code>Array(10)</code> &lt;- You hardcoded <code>10</code>, at least go for <code>Object.keys(chunks).length</code></p>\n</li>\n<li><p><code>koe</code> is an unfortunate variable name, why is it 0.5? (See lack of comments)</p>\n</li>\n<li><p>In a <code>solution</code> driven approach, you should probably never enumerate over the keys of the payload (<code>Object.keys(percentages[chunkId].payload).forEach</code>), the payload could have more fields than the solution</p>\n</li>\n<li><p>This should be 1 line</p>\n<pre><code>const perc =\n percentages[chunkId].payload[propId] / (requirements[propId] / 100)\n</code></pre>\n</li>\n<li><p>I see this as a <a href=\"https://en.wikipedia.org/wiki/Knapsack_problem\" rel=\"nofollow noreferrer\">Knapsack problem</a>, which is NP-hard, meaning that getting the perfect result will always be slow, in fact I see this as a multi-dimensional knapsack problem which is even harder than the regular knapsack problem.</p>\n</li>\n</ul>\n<p>From the comments, if we think of <code>(a,b,c)</code> as (length, width, height) and <code>requirements</code> as a bag of size (500, 1200, 1500). Then the question is how can we best (best as, least space wasted) fill the bag with different <code>chunks</code> (they all have their <code>size</code> defined in <code>payload</code>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-28T17:10:59.987", "Id": "483553", "Score": "0", "body": "You describe it as a knapsack problem, implying you may have greater insight into what the poster is asking? Could you elaborate?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-28T23:57:42.927", "Id": "483592", "Score": "1", "body": "\"_You should terminate your lines with `;`_\" I know why but others, especially the OP, likely don't - it would be good to provide an explanation, possibly with references" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-29T10:16:26.497", "Id": "483624", "Score": "2", "body": "@GirkovArpa added more, let me know if not sufficient. Sᴀᴍ Onᴇᴌᴀ; fair point, updated my comment with a link" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-29T16:59:32.083", "Id": "483688", "Score": "0", "body": "Ah! I see what the OP is asking now. If there were only a couple chunks, and `solution.a == 100`, and `chunk1.payload.a == 5` and `chunk2.payload.a == 15`, OP wants to know what to multiply `5` and `15` by so that when you sum them, they add up to `100`. He calls this number `quantity`. So `chunk1.quantity` would be `50` if `chunk2.quantity` is `1/3`. Because `(5 * 10) + (15 * (1/3)) == 100`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-29T17:02:40.210", "Id": "483689", "Score": "0", "body": "But the same `quantity` has to work for `chunk1.payload.a`, `chunk1.payload.b`, and `chunk1.payload.c`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-29T17:10:44.450", "Id": "483690", "Score": "0", "body": "And maybe `quantity` should be as small as possible." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-28T14:37:09.123", "Id": "246127", "ParentId": "245995", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T07:15:20.737", "Id": "245995", "Score": "5", "Tags": [ "javascript", "mathematics" ], "Title": "Find the best matching combination of numbers" }
245995
<p>I have a <code>ViewController</code> and <code>ViewModel</code>. Here I am using the <code>.subscribe()</code> method too many times to bind title property and etc.</p> <p>As you can see in the <code>bindActions</code> method I am subscribing to <code>action.fetchCaregivers</code> inside and calling <code>fetchCaregivers()</code>.</p> <p>How can I make this code a bit better?</p> <pre class="lang-swift prettyprint-override"><code>import UIKit import RxDataSources class PatientCaregiversViewController: ViewController { var tableView: UITableView! var viewModel: PatientCaregiversViewModel! static func initalise() -&gt; PatientCaregiversViewController { let viewController = PatientCaregiversViewController() let dataProvider = AlternateCaregiverRemoteRepo() viewController.viewModel = PatientCaregiversViewModel(dataProvider: dataProvider) return viewController } override func setupView() { super.setupView() setupTableView() configureEmptyDataSetView() } override func bindViews() { super.bindViews() // Bind State viewModel.state.title .subscribe(onNext: { [weak self] text in self?.title = text }).disposed(by: viewModel.disposeBag) // Bind View viewModel.state.displayData .bind(to: tableView.rx.items(dataSource: getDataSource())) .disposed(by: disposeBag) bindEmptyDataSet(observable: viewModel.state.emptyDataSetState) .subscribe(onNext: { [weak self] in self?.viewModel.action.fetchCaregivers.onNext(()) }).disposed(by: viewModel.disposeBag) } override func finishedLoading() { super.finishedLoading() viewModel.action.fetchCaregivers.onNext(()) } } extension PatientCaregiversViewController { private func setupTableView() { tableView = UITableView() tableView.translatesAutoresizingMaskIntoConstraints = false tableView.tableHeaderView = UIView(frame: .zero) tableView.tableFooterView = UIView(frame: .zero) view.addSubview(tableView) [tableView.topAnchor.constraint(equalTo: view.topAnchor), tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor), tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor), tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor)] .forEach({ $0?.isActive = true }) view.layoutIfNeeded() } func getDataSource() -&gt; RxTableViewSectionedReloadDataSource&lt;RxAnimatableTableSectionModel&gt;! { let dataSource = RxTableViewSectionedReloadDataSource&lt;RxAnimatableTableSectionModel&gt;( configureCell: { [weak self] dataSource, tableView, indexPath, item in switch item { case let model as CaregiverInviteCellModel: let cell = tableView.dequeueReusableCell(withIdentifier: &quot;CaregiverInviteTableViewCell&quot;, for: indexPath) as! CaregiverInviteTableViewCell cell.data = model return cell default: return UITableViewCell() } }) return dataSource } } </code></pre> <pre class="lang-swift prettyprint-override"><code>import Foundation import RxSwift import RxCocoa import RxDataSources class PatientCaregiversViewModel: ViewModel { struct Action { let fetchCaregivers = PublishSubject&lt;()&gt;() let inviteCaregiver = PublishSubject&lt;()&gt;() let refreshList = PublishSubject&lt;()&gt;() } struct State { let title = BehaviorRelay&lt;String&gt;.init(value: &quot;CAREGIVERS&quot;) let displayData = BehaviorRelay&lt;[RxAnimatableTableSectionModel]&gt;(value: []) let emptyDataSetState = BehaviorRelay&lt;DataState&gt;.init(value: .loading(title: &quot;&quot;, message: &quot;&quot;)) let showInviteLink = BehaviorRelay&lt;Bool&gt;.init(value: false) let invitTapped = PublishSubject&lt;()&gt;() } var action: Action var state: State var dataProvider: AlternateCaregiverRemoteRepo init(dataProvider: AlternateCaregiverRemoteRepo) { self.dataProvider = dataProvider action = Action() state = State() super.init() bindActions() } } // MARK:- PRIVATE METHODS. extension PatientCaregiversViewModel { private func bindActions() { action.fetchCaregivers .subscribe(onNext: { [weak self] _ in self?.fetchCaregivers() }).disposed(by: disposeBag) action.inviteCaregiver .subscribe(onNext: { [weak self] _ in self?.state.invitTapped.onNext(()) }).disposed(by: disposeBag) } private func fetchCaregivers() { state.emptyDataSetState.accept(loadingState) dataProvider.getAllCaregivers() .subscribe { [weak self] (event) in guard let this = self else { return } this.state.emptyDataSetState.accept(.failed(title: this.failedTitle, message: this.failedTitle)) }.disposed(by: disposeBag) } } // MARK:- MESSAGES. extension PatientCaregiversViewModel { var loadingState: DataState { let title = &quot;Loading Caregivers&quot; let message = &quot;Please wait while we load caregivers for you.&quot; return DataState.loading(title: title, message: message) } var noDataState: DataState { let title = &quot;No Caregiver linked&quot; let message = &quot;Please invite an alternate caregiver by clicking the invite button.&quot; return DataState.noData(title: title, message: message) } var failedTitle: String { return &quot;Failed to get Caregivers&quot; } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-28T18:12:46.560", "Id": "483555", "Score": "0", "body": "Here in code review, you should be posting code that compiles and works. This code doesn't compile." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-28T18:15:31.780", "Id": "483556", "Score": "0", "body": "This code compiles but will require third party libraries." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-28T18:16:24.457", "Id": "483557", "Score": "0", "body": "I wanted to know like how can I make ViewModel more better?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-28T18:17:50.330", "Id": "483558", "Score": "0", "body": "What third party libraries? What library provides the `ViewController` type? What library provides the `ViewModel` type? Put imports on the code to show what libraries you are depending on." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-28T18:19:11.583", "Id": "483559", "Score": "1", "body": "Yeah now I added import statements" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-28T18:49:03.413", "Id": "483564", "Score": "0", "body": "Still doesn't compile." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-30T20:41:29.460", "Id": "483886", "Score": "0", "body": "Please don't update the code once an answer is received. Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 4 → 2." } ]
[ { "body": "<p>I'm looking at just the view model for this review... You can make this code better by getting rid of all the relays and subjects. These are supposed to be rarely used but you are using them for every property it seems.</p>\n<p>The key here though is to isolate each piece of output and provide it with its own subscription.</p>\n<p>Also, I noticed that most of the code in the view model isn't getting used, so I removed the unused bits.</p>\n<pre class=\"lang-swift prettyprint-override\"><code>class PatientCaregiversViewModelʹ {\n struct Action {\n let fetchCaregivers: Observable&lt;Void&gt;\n let inviteCaregiver: Observable&lt;Void&gt;\n }\n\n struct State {\n let emptyDataSetState: Observable&lt;DataState&gt;\n let invitTapped: Observable&lt;Void&gt;\n }\n\n let dataProvider: AlternateCaregiverRemoteRepo\n\n init(dataProvider: AlternateCaregiverRemoteRepo) {\n self.dataProvider = dataProvider\n }\n\n func configure(action: Action) -&gt; State {\n let caregivers = Observable.merge(action.fetchCaregivers, Observable.just(()))\n .flatMapLatest { [dataProvider] in dataProvider.getAllCaregivers() }\n .share(replay: 1)\n\n let emptyDataSetState = Observable.merge(\n action.fetchCaregivers.map { DataState.loading(title: &quot;Loading Caregivers&quot;, message: &quot;Please wait while we load caregivers for you.&quot;) },\n caregivers.map { _ in DataState.failed(title: &quot;Failed to get Caregivers&quot;, message: &quot;Failed to get Caregivers&quot;) } // this seems quite wrong. Why aren't you inspecting the emission of getAllCaregivers() to see if the data is correct? Why aren't you using the information for anything?\n )\n\n let inviteTapped = action.inviteCaregiver\n return State(emptyDataSetState: emptyDataSetState, invitTapped: inviteTapped)\n }\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-30T18:33:49.807", "Id": "483863", "Score": "0", "body": "How do I call `fetchCaregivers` from ViewController at multiple places? as once you create Observable you can't emit an event to it. You can see in my ViewController I am calling `fetchCaregivers` from 2 places." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-30T18:36:01.227", "Id": "483864", "Score": "0", "body": "What are the two causes that lead to the fetch effect? What do you mean by \"you can't emit an event to it\"? _You_ don't exist in the code so _you_ can't do anything." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-30T18:39:50.820", "Id": "483865", "Score": "0", "body": "Sorry, I mean cannot emit a value to Observable here from a different place other than `configure` method. As value can only be emitted to Observable while creating it. Am I right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-30T18:40:54.053", "Id": "483866", "Score": "0", "body": "No, you are not right. For example `myButton.rx.tap` can emit values long after the Observable was created." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-30T18:42:16.913", "Id": "483867", "Score": "0", "body": "Yeah, that's correct." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-30T18:49:41.373", "Id": "483870", "Score": "0", "body": "Okay so you have converted `fetchCaregivers` from `PublishSubject<()>()` to `Observable<Void>` so how do I call it at the end of `ViewDidLoad`? And consider I need to call the `fetchCaregivers` again on click of some button then how can I achieve it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-30T18:53:10.250", "Id": "483871", "Score": "0", "body": "Again _you_ don't. All you do is wire up the Observables. `Observable.just(())` can be merged with the `someButton.rx.tap`. Then the result of that can be flatMapped. I will adjust the code above." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-30T18:54:53.640", "Id": "483873", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/111242/discussion-between-anirudha-mahale-and-daniel-t)." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-28T20:28:59.417", "Id": "246145", "ParentId": "245996", "Score": "2" } } ]
{ "AcceptedAnswerId": "246145", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T08:20:17.147", "Id": "245996", "Score": "5", "Tags": [ "swift", "rx-swift" ], "Title": "Binding ViewModel to ViewController using RxSwift" }
245996
<p>I am trying to work with a list of Person objects where the Person object has a property called &quot;children&quot; which is an array of same type. I idea is to have methods called “addChildrenToMain” and “removeChildrenFromMain”. In case of addChildrenToMain I want to take the child objects and insert into the array just of the parent. For removeChildrenFromMain, find out number of children (plus children’s children if expanded) and remove those many elements from the list.</p> <p>I tried to simplify the problem for clarity, and this is what I have. Some things about the problem.</p> <ul> <li>The List wouldn’t be very large</li> <li>We should remove children from main only when its expanded.</li> <li>Max limit of the children levels is 10</li> </ul> <p>I specifically would like to know if the underlying approach can result in accidental deletion/addition during adding/removing (in the resulting array).</p> <pre><code>import java.util.ArrayList; import java.util.List; public class PersonList { public static void main(String[] args) { List&lt;Person&gt; persons = getPersons(); System.out.printf(&quot;----------- ORGINAL ----------\n&quot;); persons.forEach(System.out::println); persons = addChildrenToMain(persons, 0); System.out.printf(&quot;----------- EXPAND Emma ----------\n&quot;); persons.forEach(System.out::println); //collapse(persons, 0); persons = addChildrenToMain(persons, 2); System.out.printf(&quot;------------EXPAND Emma Jr2-----------\n&quot;); persons.forEach(System.out::println); //collapse(persons, 0); removeChildrenFromMain(persons, 2); System.out.printf(&quot;------------COLLAPSE -----------\n&quot;); persons.forEach(System.out::println); } private static List&lt;Person&gt; addChildrenToMain(List&lt;Person&gt; persons, int i) { List&lt;Person&gt; children = persons.get(i).children; if (children != null &amp;&amp; children.size() &gt; 0 &amp;&amp; !persons.get(i).isNodeExpanded) { persons.get(i).isNodeExpanded = true; persons.addAll(i + 1, children); } return persons; } private static List&lt;Person&gt; removeChildrenFromMain(List&lt;Person&gt; persons, int i) { List&lt;Person&gt; children = persons.get(i).children; if (children != null &amp;&amp; children.size() &gt; 0 &amp;&amp; persons.get(i).isNodeExpanded) { //Need to find out how many elements that need to be deleted //starting i+1 index int numElementsToDelete = getExpandedChildCount(persons.get(i)); System.out.println(&quot;Number of children for &quot; + persons.get(i).name + &quot; = &quot; + numElementsToDelete); if (numElementsToDelete &gt; 0) { persons.subList(i + 1, i + 1 + numElementsToDelete).clear(); persons.get(i).isNodeExpanded = false; } } return persons; } private static int getExpandedChildCount(Person person) { int count = 0; if (person.children != null &amp;&amp; person.children.size() &gt; 0 &amp;&amp; person.isNodeExpanded) { count = count + person.children.size(); for (Person p : person.children) { count = count + getExpandedChildCount(p); } } return count; } private static List&lt;Person&gt; getPersons() { List&lt;Person&gt; persons = new ArrayList&lt;&gt;(); Person emma = new Person(&quot;Emma&quot;); Person emmaChild1 = new Person(&quot;Emma Jr1&quot;); Person emmaChild2 = new Person(&quot;Emma Jr2&quot;); Person emmaGrandChild1 = new Person(&quot;Emma Grand Child1&quot;); Person emmaGrandChild2 = new Person(&quot;Emma Grand Child2&quot;); List&lt;Person&gt; emmaGrandChild = new ArrayList&lt;&gt;(); emmaGrandChild.add(emmaGrandChild1); emmaGrandChild.add(emmaGrandChild2); emmaChild2.children = emmaGrandChild; List&lt;Person&gt; emmaChildren = new ArrayList&lt;&gt;(); emmaChildren.add(emmaChild1); emmaChildren.add(emmaChild2); emma.children = emmaChildren; //------------------------------------------ Person olivia = new Person(&quot;Olivia&quot;); Person isabella = new Person(&quot;Isabella&quot;); persons.add(emma); persons.add(olivia); persons.add(isabella); return persons; } } class Person { public String name; public List&lt;Person&gt; children; public boolean isNodeExpanded; public Person(String name) { this.name = name; } @Override public String toString() { return &quot;NAME='&quot; + name + '\'' + &quot;, NUM_CHILDREN=&quot; + (children == null ? 0 : children.size()) + (children == null ? &quot;&quot; : &quot;, IS_EXPANDED=&quot; + isNodeExpanded); } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T09:57:44.103", "Id": "245998", "Score": "1", "Tags": [ "java", "algorithm", "recursion" ], "Title": "Tree kind of Object. Adding and Removing children" }
245998
<p>I've understood the method used in post <a href="https://stackoverflow.com/q/63066903/12214867">How can I render an html from a JSON-like string?</a></p> <p>I guess I can use a for loop to create a bunch of elements as well as go through each of them, setting attributes and <code>textContent</code>.</p> <p>This code snippet</p> <pre><code>f1=open('./notes.html', 'a') num_attributes = 0 num_insert = 0 for i in json_arr: if len(i) == 2: attr_color = i['attributes']['color'] content = '&lt;p&gt;&lt;span style=&quot;color:' + attr_color + ';&quot;&gt;'+i['insert']+'&lt;/span&gt;&lt;/p&gt;' else: content = '&lt;p&gt;&lt;br&gt;&lt;/p&gt;' f1.write(content + &quot;\n&quot;) f1.close() </code></pre> <p>is to convert the following json (click <a href="https://onlinegdb.com/SJYtEEdeP" rel="nofollow noreferrer">here</a> to get the complete list)</p> <pre><code>[{'attributes': {'color': '#ff0084'}, 'insert': 'Hello everyone, welcome to class..'}, {'insert': '\n\n\n'}, {'attributes': {'color': '#dc4d50'}, 'insert': '-I often go walk.'}] </code></pre> <p>to an html.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;p&gt;&lt;span style="color:#ff0084;"&gt;Hello everyone, welcome to class..&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:#dc4d50;"&gt;-I often go walk.&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:#20b69d;"&gt;-I often go for a walk.&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:#20b69d;"&gt;-I often take a walk.&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:#dc4d50;"&gt;-I often go eat out.&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:#20b69d;"&gt;-I often eat out.&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:#dc4d50;"&gt;-Not usual meet my coworks after work.&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:#20b69d;"&gt;-I hardly{Rarely} meet my coworkers after work.&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:#dc4d50;"&gt;-We usually eating out together.&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:#20b69d;"&gt;-We usually eat out together.&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:#dc4d50;"&gt;-The feel is relaxing.&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:#20b69d;"&gt;-The feeling is relaxing.&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:#dc4d50;"&gt;-What do we need take with us?&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:#20b69d;"&gt;-What do we need &lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:#424242;"&gt;to&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:#20b69d;"&gt; take with us?&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:#dc4d50;"&gt;-We don't swimming.&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:#20b69d;"&gt;-We don't swim.&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:#20b69d;"&gt;-We won't be swimming.&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:#dc4d50;"&gt;-We need to food.&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:#20b69d;"&gt;-We need to take some food.&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:#dc4d50;"&gt;-Anything activity?&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:#20b69d;"&gt;-Are we going to be doing any activities?&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:#dc4d50;"&gt;-We don't need to take tent.&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:#20b69d;"&gt;-We don't need to take a tent.&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:#20b69d;"&gt;-We don't need to take tents.&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:#9952fd;"&gt;-We need to take some sun lotion.&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;&lt;p&gt;&lt;span style="color:#9952fd;"&gt;-We don't need to take boots.&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;</code></pre> </div> </div> </p> <p>The code works the way as expected. I'd just like to know whether my code is Pythonic. If not, how do I improve it?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T13:40:49.283", "Id": "483321", "Score": "0", "body": "Does it work the way it should?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T15:08:07.840", "Id": "483326", "Score": "0", "body": "@Mast \nThe code works the way as expected. I'd just like to know whether my code is Pythoneer. If not, how do I improve it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T02:33:07.263", "Id": "483361", "Score": "3", "body": "_Missing Review Context: Code Review requires concrete code from a project, with enough code and / or context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site._ This is the closure category since you describe this as a snippet. We need to see the full code." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T11:35:11.497", "Id": "245999", "Score": "2", "Tags": [ "python" ], "Title": "convert json to html with Python" }
245999
<p>I am fairly new to GUI programming and I am interested in improving my code from every aspect. Performance, security, readability, conciseness, and the look-and-feel aspects are all important to me.</p> <p>Here is the non-GUI part of the code:</p> <pre><code>import java.util.Random; public class Universe { private int generation; private int alive; private boolean[][] currentGeneration; private boolean[][] nextGeneration; private Random random; public Universe(int height, int width, int seed, String pattern) { this.currentGeneration = new boolean[height][width]; if (pattern.equalsIgnoreCase(&quot;Random&quot;)) { random = new Random(seed); for (int i = 0; i &lt; height; i++) { for (int j = 0; j &lt; width; j++) { currentGeneration[i][j] = random.nextBoolean(); } } } else if (pattern.equalsIgnoreCase(&quot;glider&quot;)) { getGlider(currentGeneration); } //to add more cases here nextGeneration = generateNextGeneration(currentGeneration); generation = 1; alive = calculateAlive(currentGeneration); } //Getters and instance methods int getGeneration() { return generation; } int getAlive() { return alive; } boolean[][] getCurrentGeneration() { return currentGeneration; } boolean[][] getNextGeneration() { return nextGeneration; } void moveToNextState() { boolean[][] temp = generateNextGeneration(nextGeneration); currentGeneration = nextGeneration; nextGeneration = temp; alive = calculateAlive(currentGeneration); generation++; } void reset(int h, int w, int seed) { this.currentGeneration = new boolean[h][w]; random = new Random(seed); for (int i = 0; i &lt; h; i++) { for (int j = 0; j &lt; w; j++) { this.currentGeneration[i][j] = random.nextBoolean(); } } nextGeneration = generateNextGeneration(currentGeneration); generation = 1; alive = calculateAlive(currentGeneration); } //Utility methods static int calculateNeighbours(boolean[][] grid, int row, int column) { int neighbours = 0, r, c; int N = grid.length; int M = grid[0].length; for (int p = -1; p &lt;= 1; p++) { for (int m = -1; m &lt;= 1; m++) { r = row + p; c = column + m; if (r &lt; 0) r = N - 1; if (r &gt; N - 1) r = 0; if (c &lt; 0) c = M - 1; if (c &gt; M - 1) c = 0; if (grid[r][c] &amp;&amp; (p != 0 || m != 0)) neighbours++; } } return neighbours; } static int calculateAlive(boolean[][] grid) { int alive = 0; for (int i = 0; i &lt; grid.length; i++) { for (int j = 0; j &lt; grid[0].length; j++) { if (grid[i][j]) alive++; } } return alive; } static boolean[][] generateNextGeneration(boolean[][] currentGeneration) { int N = currentGeneration.length; int M = currentGeneration[0].length; boolean[][] nextGeneration = new boolean[N][M]; int neighbours; for (int i = 0; i &lt; N; i++) { for (int j = 0; j &lt; M; j++) { neighbours = calculateNeighbours(currentGeneration, i, j); if (neighbours == 3 || (currentGeneration[i][j] &amp;&amp; neighbours == 2)) nextGeneration[i][j] = true; else nextGeneration[i][j] = false; } } return nextGeneration; } static boolean[][] generateNthGeneration(boolean[][] currentGeneration, int X) { if (X == 0) return currentGeneration; else return generateNthGeneration(generateNextGeneration(currentGeneration), X - 1); } static void printGeneration(boolean[][] generation) { for (int i = 0; i &lt; generation.length; i++) { for (int j = 0; j &lt; generation[0].length; j++) System.out.print(generation[i][j]? &quot;O&quot; : &quot; &quot;); System.out.println(); } } static void getGlider(boolean currentGeneration[][]) { for(int i = 0; i &lt; 60; i++) { for (int j =0; j &lt; 90; j++) currentGeneration[i][j] = false; } currentGeneration[1][3] = true; currentGeneration[2][3] = true; currentGeneration[3][3] = true; currentGeneration[2][1] = true; currentGeneration[3][2] = true; } </code></pre> <p>}</p> <p>And here is the GUI part of the code:</p> <pre><code>import javax.swing.*; import java.awt.*; import java.awt.event.ActionListener; class Cells extends JPanel { boolean[][] grid; int h, w; Cells(boolean[][] grid) { this.grid = grid; h = grid.length; w = grid[0].length; } { setBounds(50, 20, 961, 620); setBackground(Color.DARK_GRAY); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; //g2.setColor(Color.BLUE); for (int x = 0; x &lt; w * 10; x+=10) { for (int y = 0; y &lt; h * 10; y+=10) { if (grid[y/10][x/10]) { g2.setColor(Color.BLUE); g2.fillRect(x, y, 10, 10); } else { g2.setColor(Color.gray); g2.drawRect(x, y, 10, 10); } } } } } public class GameOfLife extends JFrame { public final int height = 60; public final int width = 90; Universe universe = new Universe(height, width, (int) Math.random(), &quot;Random&quot;); Cells cells = new Cells(universe.getCurrentGeneration()); JLabel generationLabel = new JLabel(&quot;Generation#&quot; + universe.getGeneration()); JLabel aliveLabel = new JLabel(&quot;Alive: &quot; + universe.getAlive()); JButton resetButton, speedUpButton, slowDownButton; JToggleButton playToggleButton; String[] items = {&quot;random&quot;, &quot;Glider&quot;, &quot;Gun&quot;, &quot;Spaceship&quot;, &quot;Beacon&quot;, &quot;Pulsar&quot;}; //to be added JComboBox patterns = new JComboBox(items); //to be added ActionListener repaint = e -&gt; { universe.moveToNextState(); generationLabel.setText(&quot;Generation #&quot; + universe.getGeneration()); aliveLabel.setText(&quot;Alive: &quot; + universe.getAlive()); cells.grid = universe.getCurrentGeneration(); repaint(); setVisible(true); }; int speed = 100; Timer timer = new Timer(speed, repaint); public GameOfLife() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(1000, 700); setResizable(false); setLocationRelativeTo(null); setLayout(null); setBackground(Color.darkGray); getContentPane().setBackground(Color.darkGray); generationLabel.setName(&quot;GenerationLabel&quot;); aliveLabel.setName(&quot;AliveLabel&quot;); resetButton = new JButton(&quot;Reset&quot;); resetButton.setName(&quot;ResetButton&quot;); playToggleButton = new JToggleButton(&quot;Pause&quot;); playToggleButton.setName(&quot;PlayToggleButton&quot;); speedUpButton = new JButton(&quot;Speed+&quot;); slowDownButton = new JButton(&quot;Speed-&quot;); add(cells); addLabels(); addButtons(); addFunctionality(); timer.start(); setVisible(true); } void addLabels() { JPanel labels = new JPanel() { { setBounds(50, 636, 200, 40); setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); setBackground(Color.DARK_GRAY); generationLabel.setForeground(Color.LIGHT_GRAY); aliveLabel.setForeground(Color.LIGHT_GRAY); add(generationLabel); add(aliveLabel); } }; add(labels); } void addButtons() { JPanel buttons = new JPanel() { { setBounds(250, 636, 500, 40); setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); setBackground(Color.DARK_GRAY); resetButton.setForeground(Color.darkGray); playToggleButton.setForeground(Color.darkGray); speedUpButton.setForeground(Color.darkGray); slowDownButton.setForeground(Color.darkGray); resetButton.setBackground(Color.LIGHT_GRAY); playToggleButton.setBackground(Color.LIGHT_GRAY); speedUpButton.setBackground(Color.LIGHT_GRAY); slowDownButton.setBackground(Color.LIGHT_GRAY); add(resetButton); add(playToggleButton); add(speedUpButton); add(slowDownButton); } }; add(buttons); } void addFunctionality() { playToggleButton.addActionListener(e -&gt; { if (playToggleButton.getText().equals(&quot;Play&quot;) &amp;&amp; !timer.isRunning()) { timer.restart(); playToggleButton.setText(&quot;Pause&quot;); } else if (playToggleButton.getText().equals(&quot;Pause&quot;) &amp;&amp; timer.isRunning()) { timer.stop(); playToggleButton.setText(&quot;Play&quot;); } }); speedUpButton.addActionListener(e -&gt; { if (speed == 0) {} else timer.setDelay(speed -= 50); }); slowDownButton.addActionListener(e -&gt; timer.setDelay(speed += 50)); resetButton.addActionListener(e -&gt; universe.reset(height, width, (int) Math.random())); } public static void main(String[] args) { new GameOfLife(); } } </code></pre> <p>Any comment, even if it was on one small issue with my code will be appreciated. The purpose of the code is to simulate Conway's game of life based on an initial random state, though I am planning to add a JComponent that allows the user to choose an initial state. The evolution of the universe is displayed as an animation with options for the user to pause, resume, reset the universe, and adjust the speed of the animation. The code does all of that, but I am not sure about it's performance, look-and-feel, conciseness, or readability.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T13:01:55.407", "Id": "483316", "Score": "0", "body": "Please explain the purpose of the code and tell us whether it does so successfully." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T13:06:05.753", "Id": "483317", "Score": "0", "body": "The purpose of the code is to simulate Conway's game of life based on an initial random state. The evolution of the universe is viewed as an animation with features to pause, resume, reset the universe, and adjust the speed of the animation. Yes, it does so successfully. @Mast" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T13:07:43.077", "Id": "483319", "Score": "2", "body": "@Hadil Add additional information [into your question](https://codereview.stackexchange.com/posts/246001/edit) please, not in comments." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T13:34:03.050", "Id": "483320", "Score": "1", "body": "Thank you, welcome to Code Review." } ]
[ { "body": "<p>The first thing that I notice when looking at the code is something that directly stings in my eyes: Formatting. The code is is not formatted according to the SUN or Google Code Conventions (which are largely identical). The opening curly braces are misplaced, and the <code>else</code> is misplaced. Also, the indentation is inconsistent. Some blocks are indented 2, some 3, some 4 spaces. The visual appearance of Java code should be an indentation of 4 spaces.</p>\n<p>The second thing which I noticed right away is that there are no tests.</p>\n<p>The third thing is that your implementation of Game of Life is limited to a finite universe: the width and height of the universe must be known upfront. It is possible to create an implementation that supports an infinite universe. And if you like Game of Life (I do), you may find it a very interesting and enlightening challenge to attempt yourself at such an implementation.</p>\n<p>Use descriptive names for variables. In your code, unless <code>i</code> really is just an anonymous counter, it's better to use <code>x</code> and <code>y</code> or <code>row</code> and <code>col</code>. And these names should be consistent throughout the code. I see sometimes <code>i</code> and <code>j</code>, sometimes <code>p</code> and <code>m</code>, sometimes <code>row</code> and <code>column</code> in your code.</p>\n<p>Same goes for <code>width</code> and <code>height</code>, for which I sometimes see <code>N</code> and <code>M</code> instead.</p>\n<p>The <code>this</code> qualifier should be omitted unless it is necessary to resolve ambiguity or otherwise communicate intent.</p>\n<p>Your &quot;main&quot; class is a component that <code>extends JFrame</code>. I know that code examples in books and tutorials are full of examples like that. But this is bad practice and not proper OO: It violates the LSP (Liskov Substitution Principle; Barbara Liskov justifiedly received a Turing award for coming up with this) because your main class cannot be reused the same way as a JFrame. In layman's terms, subclasses should always represent adequate substitutes for their superclasses. And it is not necessary at all to <code>extend JFrame</code>. You can just fine do something like <code>JFrame frame = new JFrame()</code> and then call its methods.</p>\n<p>Besides, <code>GameOfLife</code> is a bad name for something that <code>extends JFrame</code>. It should be possible to make an educated guess about the class hierarchy from the class name. The class name <code>GameOfLife</code> has nothing in it that suggests that it is a <code>JFrame</code>, nor anything that suggests that this is the class with the <code>main()</code> method.</p>\n<p>Same goes for <code>Cells</code>. The name <code>Cells</code> does not suggest to the reader that this class is a UI component.</p>\n<p>The superclass for <code>Cells</code> should be <code>JComponent</code>, not <code>JPanel</code>. The purpose of a <code>JPanel</code> is that you can set its layout manager and add components. Using <code>JPanel</code> instead of <code>JComponent</code> is again an LSP violation.</p>\n<p>You could use more and thus smaller methods. This would allow you to have less duplication, more code reuse, and thus also fewer errors. For example, look at the constructor <code>Universe()</code>. It includes a section of code that initializes the entire universe with random bits. The method <code>reset()</code> does the same. You could extract this into a method <code>randomize()</code>, like this:</p>\n<pre><code> public void randomize(int height, int width, int seed) {\n for (int y = 0; y &lt; h; y++) {\n for (int x = 0; x &lt; h; x++) {\n currentGeneration[y][x] = random.nextBoolean();\n }\n }\n }\n</code></pre>\n<p>You could call this <code>randomize()</code> method from both, <code>reset()</code> and <code>Universe()</code>.</p>\n<p>You might want to prefer method references over anonymous lambdas if you do not need Java's half-assed closures (access to variables of the enclosing method; in Java half-assed because they must be effectively <code>final</code>). This makes your code cleaner.</p>\n<p>Fields which are initialized with a field initializer or with an assignment in the constructor but never assigned again should be <code>final</code>. If you want to write really good code, then most of your data will be <code>final</code>.</p>\n<p><code>calculateNeighbors()</code> is always called with <code>currentGrid</code> as its first argument. Remove the argument and make <code>calculateNeighbors()</code> an instance method. Same for <code>calculateAlive()</code>.</p>\n<p>In <code>calculateNeighbors()</code>, the code</p>\n<pre><code> if (r &lt; 0)\n r = N - 1;\n if (r &gt; N - 1)\n r = 0;\n if (c &lt; 0)\n c = M - 1;\n if (c &gt; M - 1)\n c = 0;\n</code></pre>\n<p>can be simplified significantly:</p>\n<pre><code> r = (r + N) % N;\n c = (c + M) % M;\n</code></pre>\n<p><em>(x + r) % r</em> is the general formula to ensure for <em>x ∈ ℤ, r ∈ ℕ</em> that <em>0 &lt;= x &lt; r</em>.\nBesides, this simplification will ensure the expected (torus universe) behavior in case you want to support a ruleset with a neighbor distance &gt; 1.</p>\n<p>In the methods <code>generateNthGeneration()</code>, <code>X</code> (uppercase) is used as a parameter name. This is misleading: A single uppercase letter is expected to be a type or a constant, but not a (in this case parameter) variable.</p>\n<p>In your <code>repaint</code>, you have this code:</p>\n<pre><code>cells.grid = universe.getCurrentGeneration();\n</code></pre>\n<p>The class <code>Cells</code> should be able to render the correct generation without having another class (<code>GameOfLife</code>) helping with it. For that, class <code>Cells</code> should directly refer to class <code>Universe</code>, not its <code>grid[][]</code>.</p>\n<p>Overall, look out for duplication and remove it.</p>\n<p>Also, look out for misplaced responsibility. You can detect misplaced responsibility by using <code>.</code>, especially when using it multiple times. There is a princple called <em>Law of Demeter</em> that can help you with identifying misplaced responsibility. You will notice that when you fix misplaced responsibility by moving things in the right places, that lines become shorter.</p>\n<p>Remove unused code. Method <code>getNextGeneration()</code> is never used.</p>\n<p>In method <code>generateNextGeneration()</code>, you may want to use a separate class to determine whether a cell survives or is born. This would allow you to easily implement other rulesets. Conway's Game of Life is B3/S23. Another popular ruleset is Highlife, B36/S23. The design pattern to do that is called <em>Strategy</em>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T15:41:01.123", "Id": "246007", "ParentId": "246001", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T12:20:41.343", "Id": "246001", "Score": "3", "Tags": [ "java", "swing", "game-of-life" ], "Title": "Game of life GUI simulation using java.swing" }
246001
<p>I am currently working on a project for an online course, my goal is to create a bookmark manager web app. So I created this python script to parse a chrome/firefox HTML bookmarks file (Netscape-Bookmark-file) into a JSON object, while preserving the hierarchy and location of the folders and urls.</p> <p>The code works fine and parses the HTML file to JSON correctly.</p> <p>I feel like the code is messy and that the approach I am using is not the best. I would appreciate any critique/criticism in any aspect of the code.</p> <p>The code runs by passing the html file location to the <code>main()</code> function:</p> <pre class="lang-py prettyprint-override"><code>output = main(&quot;html_file_location&quot;) </code></pre> <p>Here is the Code:</p> <pre class="lang-py prettyprint-override"><code>from bs4 import BeautifulSoup # Counter for the id of each item (folders and urls) ID = 1 def indexer(item, index): &quot;&quot;&quot; Add position index for urls and folders &quot;&quot;&quot; if item.get(&quot;type&quot;) in [&quot;url&quot;, &quot;folder&quot;]: item[&quot;index&quot;] = index index += 1 return index def parse_url(child, parent_id): &quot;&quot;&quot; Function that parses a url tag &lt;DT&gt;&lt;A&gt; &quot;&quot;&quot; global ID result = { &quot;type&quot;: &quot;url&quot;, &quot;id&quot;: ID, &quot;index&quot;: None, &quot;parent_id&quot;: parent_id, &quot;url&quot;: child.get(&quot;href&quot;), &quot;title&quot;: child.text, &quot;date_added&quot;: child.get(&quot;add_date&quot;), &quot;icon&quot;: child.get(&quot;icon&quot;), } # getting icon_uri &amp; tags are only applicable in Firefox icon_uri = child.get(&quot;icon_uri&quot;) if icon_uri: result[&quot;icon_uri&quot;] = icon_uri tags = child.get(&quot;tags&quot;) if tags: result[&quot;tags&quot;] = tags.split(&quot;,&quot;) ID += 1 return result def parse_folder(child, parent_id): &quot;&quot;&quot; Function that parses a folder tag &lt;DT&gt;&lt;H3&gt; &quot;&quot;&quot; global ID result = { &quot;type&quot;: &quot;folder&quot;, &quot;id&quot;: ID, &quot;index&quot;: None, &quot;parent_id&quot;: parent_id, &quot;title&quot;: child.text, &quot;date_added&quot;: child.get(&quot;add_date&quot;), &quot;date_modified&quot;: child.get(&quot;last_modified&quot;), &quot;special&quot;: None, &quot;children&quot;: [], } # for Bookmarks Toolbar in Firefox and Bookmarks bar in Chrome if child.get(&quot;personal_toolbar_folder&quot;): result[&quot;special&quot;] = &quot;toolbar&quot; # for Other Bookmarks in Firefox if child.get(&quot;unfiled_bookmarks_folder&quot;): result[&quot;special&quot;] = &quot;other_bookmarks&quot; ID += 1 return result def recursive_parse(node, parent_id): &quot;&quot;&quot; Function that recursively parses folders and lists &lt;DL&gt;&lt;p&gt; &quot;&quot;&quot; index = 0 # case were node is a folder if node.name == &quot;dt&quot;: folder = parse_folder(node.contents[0], parent_id) items = recursive_parse(node.contents[2], folder[&quot;id&quot;]) folder[&quot;children&quot;] = items return folder # case were node is a list elif node.name == &quot;dl&quot;: data = [] for child in node: tag = child.contents[0].name if tag == &quot;h3&quot;: folder = recursive_parse(child, parent_id) index = indexer(folder, index) data.append(folder) elif tag == &quot;a&quot;: url = parse_url(child.contents[0], parent_id) index = indexer(url, index) data.append(url) return data def parse_root_firefox(root): &quot;&quot;&quot; Function to parse the root of the firefox bookmark tree &quot;&quot;&quot; # create bookmark menu folder and give it an ID global ID bookmarks = { &quot;type&quot;: &quot;folder&quot;, &quot;id&quot;: ID, &quot;index&quot;: 0, &quot;parent_id&quot;: 0, &quot;title&quot;: &quot;Bookmarks Menu&quot;, &quot;date_added&quot;: None, &quot;date_modified&quot;: None, &quot;special&quot;: &quot;main&quot;, &quot;children&quot;: [], } ID += 1 index = 0 # index for bookmarks/bookmarks menu main_index = 1 # index for root level result = [0] # root contents for node in root: # skip node if not &lt;DT&gt; if node.name != &quot;dt&quot;: continue # get tag of first node child tag = node.contents[0].name if tag == &quot;a&quot;: url = parse_url(node.contents[0], 1) index = indexer(node, index) bookmarks[&quot;children&quot;].append(url) if tag == &quot;h3&quot;: folder = recursive_parse(node, 1) # check for special folders (Other Bookmarks / Toolbar) # add them to root level instead of inside bookmarks if folder[&quot;special&quot;]: folder[&quot;parent_id&quot;] = 0 main_index = indexer(folder, main_index) result.append(folder) else: index = indexer(folder, index) bookmarks[&quot;children&quot;].append(folder) result[0] = bookmarks return result def parse_root_chrome(root): &quot;&quot;&quot; Function to parse the root of the chrome bookmark tree &quot;&quot;&quot; global ID # Create &quot;other bookmarks&quot; folder and give it an ID other_bookmarks = { &quot;type&quot;: &quot;folder&quot;, &quot;id&quot;: ID, &quot;index&quot;: 1, &quot;parent_id&quot;: 0, &quot;title&quot;: &quot;Other Bookmarks&quot;, &quot;date_added&quot;: None, &quot;date_modified&quot;: None, &quot;special&quot;: &quot;other_bookmarks&quot;, &quot;children&quot;: [], } ID += 1 result = [0] index = 0 for node in root: if node.name != &quot;dt&quot;: continue # get the first child element (&lt;H3&gt; or &lt;A&gt;) element = node.contents[0] tag = element.name # if an url tag is found at root level, add it to &quot;Other Bookmarks&quot; children if tag == &quot;a&quot;: url = parse_url(node.contents[0], 1) index = indexer(node, index) other_bookmarks[&quot;children&quot;].append(url) elif tag == &quot;h3&quot;: # if a folder tag is found at root level, check if its the main &quot;Bookmarks Bar&quot;, else append to &quot;Other Bookmarks&quot; children if element.get(&quot;personal_toolbar_folder&quot;): folder = recursive_parse(node, 0) folder[&quot;index&quot;] = 0 folder[&quot;special&quot;] = &quot;main&quot; result[0] = folder else: parent_id = other_bookmarks[&quot;id&quot;] folder = recursive_parse(node, parent_id) index = indexer(folder, index) other_bookmarks[&quot;children&quot;].append(folder) # add &quot;Other Bookmarks&quot; folder to root if it has children if len(other_bookmarks[&quot;children&quot;]) &gt; 0: result.append(other_bookmarks) return result # Main function def main(bookmarks_file): &quot;&quot;&quot; Main function, takes in a HTML bookmarks file from Chrome/Firefox and returns a JSON nested tree of the bookmarks. &quot;&quot;&quot; # Open HTML Bookmark file and pass contents into beautifulsoup with open(bookmarks_file, encoding=&quot;Utf-8&quot;) as f: soup = BeautifulSoup(markup=f, features=&quot;html5lib&quot;, from_encoding=&quot;Utf-8&quot;) # Check if HTML Bookmark version is Chrome or Firefox # Prepare the data to be parsed # Parse the root of the bookmarks tree heading = soup.find(&quot;h1&quot;) root = soup.find(&quot;dl&quot;) if heading.text == &quot;Bookmarks&quot;: bookmarks = parse_root_chrome(root) elif heading.text == &quot;Bookmarks Menu&quot;: bookmarks = parse_root_firefox(root) return bookmarks </code></pre>
[]
[ { "body": "<h2>Global state</h2>\n<p>This:</p>\n<pre><code># Counter for the id of each item (folders and urls)\nID = 1\n</code></pre>\n<p>has issues. It will prevent your code from being re-entrant. Instead, this should either be passed around in your function parameters, or made a member of a class.</p>\n<h2>Type hints</h2>\n<pre><code>def indexer(item, index):\n</code></pre>\n<p>could stand to get some type hints. Probably <code>index: int</code>, return value is <code>-&gt; int</code>, and <code>item</code> is a <code>: dict</code>. However,</p>\n<ol>\n<li>You're better off using <code>Dict[str, ???]</code> - I don't know what the values are; and</li>\n<li>You're even better off representing the item not as a dictionary, but as a more strongly-typed class instance - maybe a <code>@dataclass</code>, or at least a named tuple - to gain confidence that your data are valid and your code is correct.</li>\n</ol>\n<h2>Enums</h2>\n<p>Another aspect of strengthening your types is to reframe this:</p>\n<pre><code>item.get(&quot;type&quot;) in [&quot;url&quot;, &quot;folder&quot;]:\n</code></pre>\n<p>as an <code>Enum</code>. Also, you shouldn't <code>in</code>-compare to a list; do it to a <code>set</code> literal instead, i.e. <code>{'url', 'folder'}</code>. This will work equally well for strings or enums.</p>\n<h2>Generators</h2>\n<p>Consider replacing this:</p>\n<pre><code> data = []\n for child in node:\n data.append(folder)\n return data\n</code></pre>\n<p>with</p>\n<pre><code>for child in node:\n yield folder\n</code></pre>\n<p>It's easier to write, and will use up less memory - though the last bit will only matter if you're processing millions of these.</p>\n<h2>Returns from main</h2>\n<pre><code>def main(bookmarks_file):\n return bookmarks\n</code></pre>\n<p>This means that your <code>main</code> isn't really a <code>main</code>; something else (that you unfortunately haven't shown) is calling it. This method needs to be renamed, and your <em>actual</em> <code>main</code> needs to call it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T21:02:22.130", "Id": "483412", "Score": "0", "body": "Thank you for your detailed reply, there were quite somethings I didn't know about that I have learned. I do have some questions tho.\n1. from my experience it seems that passing ``ID`` through 3 or 4 functions will cause the code to be quite difficult to maintain. (I guess changing to a class will be better?)\n2. Wouldn't using Enum just to increment a dictionary value be over-complicating the code?\n3. You mentioned using the Generator for returning the values, but since I am creating a nested structure, I will have to add them to a list after each yield anyway. won't that make it usless?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T00:04:02.780", "Id": "483418", "Score": "0", "body": "_passing ID through 3 or 4 functions will cause the code to be quite difficult to maintain_ - Your thinking on this may evolve as you mature as a programmer. Ease of maintenance overlaps with ease of testability, and having functions that rely on their parameters only and have no side effects really enhances testability." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T00:04:56.537", "Id": "483419", "Score": "0", "body": "_Wouldn't using Enum just to increment a dictionary value be over-complicating the code_ - It may very well end up producing code that is longer, but it will also be code that is inherently resistant to certain classes of errors where the data are not checked for validity until it's too late." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T00:06:06.057", "Id": "483420", "Score": "0", "body": "_since I am creating a nested structure, I will have to add them to a list after each yield anyway_ - Nested generators are entirely possible." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T02:17:42.883", "Id": "246019", "ParentId": "246002", "Score": "3" } } ]
{ "AcceptedAnswerId": "246019", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T13:12:56.250", "Id": "246002", "Score": "3", "Tags": [ "python", "performance", "algorithm", "parsing" ], "Title": "Parse HTML bookmarks file to JSON using python" }
246002
<p>Just wanted a general review of the code to make sure I'm doing it properly/efficently. New to JS and don't use RegEx too often.</p> <pre><code>// ==UserScript== // @name Youtube Subscriptions Redirect // @namespace https://github.com/spacegIider // @version 1.0 // @license MIT // @description Shows all subscribed videos in subscription feed. // @author Spaceglider // @match *://www.youtube.com/feed/subscriptions // @grant none // @homepageURL https://github.com/spacegIider/Youtube-Subscriptions-Redirect // @supportURL https://github.com/spacegIider/Youtube-Subscriptions-Redirect/issues // @downloadURL https://raw.githubusercontent.com/spacegIider/Youtube-Subscriptions-Redirect/redirect.js // @updateURL https://raw.githubusercontent.com/spacegIider/Youtube-Subscriptions-Redirect/redirect.js // ==/UserScript== var BadDumbYoutubeURL = window.location.pathname; if ( ! /\?flow=1$/.test (BadDumbYoutubeURL) ) { var ActuallySeeAllVideosURL = window.location.protocol + &quot;//&quot; + window.location.host + BadDumbYoutubeURL + &quot;?flow=1&quot; +window.location.search +window.location.hash ; window.location.replace (ActuallySeeAllVideosURL); } </code></pre>
[]
[ { "body": "<p>A short review;</p>\n<ul>\n<li><p><code>BadDumbYoutubeURL</code> should be lowerCamelCase and perhaps is a bit silly</p>\n</li>\n<li><p>the <code>;</code> does not deserve it's on own line</p>\n</li>\n<li><p>My understanding is that <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Location/search\" rel=\"nofollow noreferrer\">location.search already starts with <code>?</code></a> so you probably want to do something about that, like</p>\n<pre><code> const search = window.location.search ? '&amp;' + window.location.search.substring(1) : 0;\n</code></pre>\n</li>\n<li><p>Other than looks fine, perfectly maintainable</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T07:48:49.150", "Id": "246066", "ParentId": "246003", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T14:08:00.090", "Id": "246003", "Score": "3", "Tags": [ "javascript", "regex", "youtube" ], "Title": "Tampermonkey script to check and replace youtube's subscriptions to show all videos" }
246003
<p>The code below was for a code camp project and done in Codepen (so the CSS is automatically referenced). Here is the link: <a href="https://codepen.io/andyzam/pen/mdVvrLB" rel="nofollow noreferrer">https://codepen.io/andyzam/pen/mdVvrLB</a></p> <p>I wanted the input fields to align and so I used a table in HTML. My thinking was it would be easier to just apply style to all the tags in CSS vs. having to use individual tags and style each separately. That said, when it came to the radio buttons and checkboxes, I could not get these to align in the table and so I styled them outside the table and put those blocks in their own . But this caused an issue as the radio buttons and checkboxes are not responsive and when a shrink the browser window they stay in the same place. Doesn't look good.</p> <p>The below code passes the code camp &quot;tests&quot; but my issue is whether or not the use of a table is optimal and getting the radio and checkboxes to move with window size. Please note that the Submit button is not intended to work and is there for visual purposes only.</p> <pre><code>body{ background: lightblue; font-family: monospace; margin: 0px; } p { text-align: center; font-size: 14px; } #title { text-align: center; } #description { margin-left: auto; margin-right: auto; width: 500px; font-size: 20px; text-align: justify; padding: 10px; } input { width: 250px; } label { font-size: 14px; margin-right: 0px; } table { margin-left: auto; margin-right: 35em; } td { text-align: right; width: 250px; padding: 10px; } input:invalid { border: 2px dashed red; } input:invalid:required { background-image: linear-gradient(to right, pink, white); } input:valid { border: 2px solid black; } select { width: 260px; } select:invalid:required { background-image: linear-gradient(to right, pink, white); } select:valid { border: 2px solid black; } #radio { display: block; margin-left: 53em; padding: 10px; } input[type=&quot;radio&quot;] { width: 20px; } #checkboxes { display: block; margin-left: 53em; padding: 10px; } input[type=&quot;checkbox&quot;] { width: 20px; } #text-field { display: block; margin-left: 45em; padding: 10px; } #submit-button { text-align: center; padding: 20px; } &lt;html&gt; &lt;body&gt; &lt;title&gt;TikTok User Survey&lt;/title&gt; &lt;main&gt; &lt;h1 id=&quot;title&quot;&gt;TikTok User Survey&lt;/h1&gt; &lt;p id=&quot;description&quot;&gt;We are gathering information from various TikTok users to gauge their satisfaction with the social media platform.&lt;/p&gt; &lt;p&gt; All fields are required.&lt;/p&gt; &lt;form id=&quot;survey-form&quot;&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt;&lt;label for=&quot;name&quot; id=&quot;name-label&quot;&gt;Your name:&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input type=&quot;text&quot; id=&quot;name&quot; name=&quot;name-label&quot; placeholder=&quot;Your Name&quot; required&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;label for=&quot;email&quot; id=&quot;email-label&quot;&gt;Enter your email:&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input type=&quot;email&quot; id=&quot;email&quot; name=&quot;email&quot; placeholder=&quot;Email&quot; required&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;label for=&quot;number&quot; id=&quot;number-label&quot;&gt;How many followers:&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input type=&quot;number&quot; id=&quot;number&quot; name=&quot;number&quot; placeholder=&quot;No. of Followers (0-100k)&quot; required min=&quot;0&quot; max=&quot;100000&quot;&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;label for=&quot;age&quot;&gt;How old are you?:&lt;/label&gt;&lt;/td&gt; &lt;td&gt; &lt;select id=&quot;dropdown&quot; name=&quot;age&quot; required&gt; &lt;option disabled selected value&gt; -- select an option -- &lt;/option&gt; &lt;option value=&quot;under13&quot;&gt;Under 13&lt;/option&gt; &lt;option value=&quot;13-20&quot;&gt;13-20&lt;/option&gt; &lt;option value=&quot;20-30&quot;&gt;20-30&lt;/option&gt; &lt;option value=&quot;over30&quot;&gt;Over 30&lt;/option&gt; &lt;/select&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;p&gt;My gender:&lt;/p&gt; &lt;div id='radio'&gt; &lt;input type=&quot;radio&quot; id=&quot;male&quot; name=&quot;gender&quot; value=&quot;male&quot;&gt; &lt;label for=&quot;male&quot;&gt;Male&lt;/label&gt;&lt;br&gt; &lt;input type=&quot;radio&quot; id=&quot;female&quot; name=&quot;gender&quot; value=&quot;female&quot;&gt; &lt;label for=&quot;female&quot;&gt;Female&lt;/label&gt;&lt;br&gt; &lt;input type=&quot;radio&quot; id=&quot;other&quot; name=&quot;gender&quot; value=&quot;other&quot;&gt; &lt;label for=&quot;other&quot;&gt;Other&lt;/label&gt; &lt;/div&gt; &lt;p&gt;Favorite types of videos:&lt;/p&gt; &lt;div id=&quot;checkboxes&quot;&gt; &lt;input type=&quot;checkbox&quot; id=&quot;dancing&quot; name=&quot;dancing&quot; value=&quot;dancing&quot;&gt; &lt;label for=&quot;dancing&quot;&gt;Dancing&lt;/label&gt;&lt;br&gt; &lt;input type=&quot;checkbox&quot; id=&quot;cooking&quot; name=&quot;cooking&quot; value=&quot;cooking&quot;&gt; &lt;label for=&quot;cooking&quot;&gt;Cooking&lt;/label&gt;&lt;br&gt; &lt;input type=&quot;checkbox&quot; id=&quot;pranks&quot; name=&quot;pranks&quot; value=&quot;pranks&quot;&gt; &lt;label for=&quot;pranks&quot;&gt;Pranks&lt;/label&gt;&lt;br&gt; &lt;/div&gt; &lt;p&gt;Any additional comments about what you like:&lt;/p&gt; &lt;div id=&quot;text-field&quot;&gt; &lt;textarea name=&quot;message&quot; rows=&quot;10&quot; cols=&quot;30&quot;&gt;I also like....&lt;/textarea&gt; &lt;/div&gt; &lt;div id=&quot;submit-button&quot;&gt; &lt;button type=&quot;submit&quot; id=&quot;submit&quot;&gt;Submit&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; &lt;/main&gt; &lt;/body&gt; &lt;/html&gt; <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T19:19:41.853", "Id": "246012", "Score": "1", "Tags": [ "html", "css" ], "Title": "Survey page - is using a table the best way to get all fields to align?" }
246012
<p>This code imports a list of equipment (around 8000), and then filters the errors and creates some lots for the processes that come next. The code is working, but I'm sure it can be improved, especially in terms of performance, as it takes a bit. I think the slowest part is in the &quot;ErrorProcessing&quot; sub.</p> <p>Any suggestion about how to make it better or better practises when coding vba would be much appreciated. As an extra, I tried to put a userform with an animation while the process is going on, but it's not showing anything, so I commented that part. Any ideas?</p> <pre class="lang-vb prettyprint-override"><code>Sub Import_data() Dim FilePath As Variant, FileName As Variant, TempSheetName As String, k As Integer, n As Integer, RegisterNumb As Integer, RegisterNoError As Integer, Errors As Integer, i As Integer Dim LastRow As Long Dim ThisWorBookName As String, PathWorkbook As String, ProjectName As String Dim AreaName As String, Areacode As String, AreaNumber As String Dim wsCon As Worksheet, wsLot As Worksheet, wsReg As Worksheet Set wsCon = Sheets(&quot;CONTROL&quot;) Set wsLot = Sheets(&quot;LOTS&quot;) Call PageVisibility(1) Application.ScreenUpdating = False Application.DisplayAlerts = False Application.Calculation = xlCalculationManual ThisWorkBookName = ActiveWorkbook.Name PathWorkbook = Application.ThisWorkbook.Path &amp; &quot;\&quot; ProjectName = Left(wsCon.Cells(4, 3).Value, 8) &amp; &quot;_&quot; &amp; (Format(wsCon.Cells(5, 3).Value, &quot;yyyy_mm_dd&quot;)) ChDir PathWorkbook 'Check if Project exist var1 = Application.ThisWorkbook.Path &amp; &quot;\&quot; var2 = Left(wsCon.Cells(4, 3).Value, 8) &amp; &quot;_&quot; &amp; (Format(wsCon.Cells(5, 3).Value, &quot;yyyy_mm_dd&quot;)) sFolderpath = var1 &amp; var2 If Dir(var1 &amp; var2, vbDirectory) &lt;&gt; &quot;&quot; Then Else Result = MsgBox(&quot;Project &quot; &amp; var2 &amp; &quot; Does not exist.&quot; &amp; vbNewLine &amp; vbNewLine &amp; &quot;Do You want to Create it?&quot;, vbYesNo + vbExclamation) If Result = 6 Then Call CreateProjects Else MsgBox &quot;You Need to create the project before Importing the records&quot;, vbExclamation Exit Sub End If End If wsLot.Range(&quot;B5:D5&quot;).Value = 0 wsLot.Range(&quot;D9:E100&quot;).Delete Shift:=xlUp TempSheetName = &quot;REGISTER&quot; 'Check that workbook is reset For Each Sheet In Worksheets If TempSheetName = UCase(Sheet.Name) Then MsgBox &quot;Reset before importing&quot; Exit Sub End If Next Sheet 'File opening FilePath = Application.GetOpenFilename(FileFilter:=&quot;Excel Files (*.XLSX), *.XLSX&quot;, Title:=&quot;Select File To Be Opened&quot;) If FilePath = False Then Exit Sub 'Animated.Show vbModeless 'Application.Wait (Now + TimeValue(&quot;0:00:05&quot;)) 'DoEvents FileName = Mid$(FilePath, InStrRev(FilePath, &quot;\&quot;) + 1, Len(FilePath)) ControlFile = ActiveWorkbook.Name Workbooks.Open FileName:=FilePath Sheets(&quot;REGISTER&quot;).Copy After:=Workbooks(ControlFile).Sheets(&quot;LOTEVAL&quot;) Windows(FileName).Activate ActiveWorkbook.Close SaveChanges:=False Windows(ControlFile).Activate 'Formulas to values Set wsReg = Sheets(&quot;REGISTER&quot;) wsReg.Unprotect wsReg.Range(&quot;B:B&quot;).Value = wsReg.Range(&quot;B:B&quot;).Value wsReg.Range(&quot;V:V&quot;).Value = wsReg.Range(&quot;V:V&quot;).Value wsReg.Range(&quot;Y:Y&quot;).Value = wsReg.Range(&quot;Y:Y&quot;).Value LastRow = Cells.Find(What:=&quot;*&quot;, After:=Range(&quot;A1&quot;), SearchOrder:=xlByRows, Searchdirection:=xlPrevious).Row RegisterNumb = LastRow - 6 RegisterNoError = RegisterNumb wsLot.Cells(5, &quot;C&quot;).Value = RegisterNoError wsLot.Cells(5, &quot;D&quot;).Value = RegisterNumb 'Error Filtering '-------------------- Call ErrorPorcessing RegisterNoError = wsLot.Cells(5, &quot;C&quot;).Value 'Order '------------ Call PutSomeOrder(LastRow) 'Main Areas creation '------------------- wsLot.Range(&quot;A9&quot;).Formula2R1C1 = &quot;=UNIQUE(FILTER(REGISTER!R7C3:R65536C3,REGISTER!R7C3:R65536C3&lt;&gt;&quot;&quot;&quot;&quot;))&quot; 'Lot assignement '--------------- n = 6 + RegisterNoError For k = 7 To n AreaNumber = wsLot.Cells(5, 1).Value If wsReg.Cells(k, &quot;B&quot;).Value &gt; 0 Then If wsReg.Cells(k, &quot;B&quot;).Value = wsReg.Cells((k - 1), &quot;B&quot;).Value Then wsReg.Cells(k, &quot;AA&quot;).Value = wsReg.Cells((k - 1), &quot;AA&quot;).Value Else For i = 9 To AreaNumber + 8 If wsReg.Range(&quot;C&quot; &amp; k).Value = wsLot.Range(&quot;A&quot; &amp; i) Then wsReg.Cells(k, &quot;AA&quot;).Value = wsLot.Range(&quot;C&quot; &amp; i) Next i End If wsReg.Cells(k, &quot;AB&quot;).Value = wsReg.Cells(k, &quot;H&quot;).Value wsReg.Cells(k, &quot;AC&quot;).Value = wsReg.Cells(k, &quot;V&quot;).Value wsReg.Cells(k, &quot;AD&quot;).Value = wsReg.Cells(k, &quot;AA&quot;).Value &amp; &quot;_&quot; &amp; wsReg.Cells(k, &quot;AB&quot;).Value &amp; &quot;_&quot; &amp; wsReg.Cells(k, &quot;AC&quot;).Value End If Next k n = 8 + wsLot.Cells(5, &quot;A&quot;).Value wsLot.Cells(9, &quot;E&quot;).Value = 7 For k = 9 To n wsLot.Cells(k, &quot;D&quot;).Value = WorksheetFunction.CountIf(wsReg.Range(&quot;AA:AA&quot;), wsLot.Cells(k, &quot;C&quot;).Value) If k &gt; 9 Then wsLot.Cells(k, &quot;E&quot;).Value = wsLot.Cells(k - 1, &quot;E&quot;).Value + wsLot.Cells(k - 1, &quot;D&quot;).Value Next k wsLot.Cells(5, &quot;C&quot;).Value = WorksheetFunction.CountA(wsReg.Range(&quot;AA:AA&quot;)) wsLot.Range(&quot;G9&quot;).Formula2R1C1 = &quot;=UNIQUE(FILTER(REGISTER!R7C30:R12000C30,REGISTER!R7C30:R12000C30&lt;&gt;&quot;&quot;&quot;&quot;))&quot; wsLot.Range(&quot;E5&quot;).Formula = &quot;=IFERROR(IF(G9&lt;&gt;&quot;&quot;&quot;&quot;,COUNTA(G9#),0),0)&quot; wsLot.Range(&quot;Q9&quot;).Formula2R1C1 = &quot;=UNIQUE(FILTER(REGISTER!R7C30:R12000C30,REGISTER!R7C30:R12000C30&lt;&gt;&quot;&quot;&quot;&quot;))&quot; wsLot.Range(&quot;R9&quot;).Formula2R1C1 = &quot;UNIQUE(FILTER(R:R,R:R&lt;&gt;&quot;&quot;&quot;&quot;))&quot; n = 8 + wsLot.Cells(5, &quot;E&quot;).Value wsLot.Cells(9, &quot;E&quot;).Value = 7 For k = 9 To n wsLot.Cells(k, &quot;H&quot;).Value = WorksheetFunction.CountIf(wsReg.Range(&quot;AD:AD&quot;), wsLot.Cells(k, &quot;G&quot;).Value) Next k wsLot.Range(&quot;H8&quot;).Formula = &quot;=MAX(H9:H3000)&quot; Calculate If wsLot.Range(&quot;H8&quot;).Value &gt; 3200 Then MsgBox &quot;Warning, at least one of the lots has more than 32000 elements&quot; 'Export errors and Registers to Project Folder Call ExportErrorsAndRegisters RegisterNumb = wsLot.Range(&quot;D5&quot;).Value RegisterNoError = wsLot.Range(&quot;C5&quot;).Value Errors = wsLot.Range(&quot;B5&quot;).Value wsCon.Range(&quot;O3&quot;).Value = 1 wsCon.Activate MsgBox (&quot;Ex DataBase Import Completed&quot; &amp; vbNewLine &amp; vbNewLine _ &amp; &quot;TOTAL EQUIPMENT IN Ex DATABASE : &quot; &amp; RegisterNumb &amp; vbNewLine _ &amp; &quot;EQUIPMENT EXCLUDED DUE TO ERROR : &quot; &amp; Errors &amp; vbNewLine _ &amp; &quot;TOTAL EQUIPMENT IMPORTED : &quot; &amp; RegisterNoError &amp; vbNewLine &amp; vbNewLine _ &amp; &quot;The Equipment with errors have been recorded on the ERRROR_LOG. You can continue discarting those elements or correct them in the originalfile and do the Import again.&quot; &amp; vbNewLine) 'Save for Navigation ActiveWorkbook.SaveAs PathWorkbook &amp; ProjectName &amp; &quot;\NAV\&quot; &amp; ProjectName &amp; &quot;_Step_1.exp&quot;, FileFormat:=52 ActiveWorkbook.SaveAs PathWorkbook &amp; ProjectName &amp; &quot;\&quot; &amp; ProjectName &amp; &quot;.exp&quot;, FileFormat:=52 ActiveWorkbook.SaveAs PathWorkbook &amp; ThisWorkBookName, FileFormat:=52 Call PageVisibility(2) Application.DisplayAlerts = True Application.ScreenUpdating = True Application.Calculation = xlCalculationAutomatic 'Unload Animated Sheets(&quot;LOTEVAL&quot;).Activate wsCon.Activate End Sub Sub ErrorPorcessing() Dim WSActual As Worksheet, WSError As Worksheet Dim ErrorLastRow As Long, ErrorLastRowPrev As Long, ThisCatErrors As Long Dim k As Integer, tempvar As Variant Dim wsCon As Worksheet, wsLot As Worksheet, wsReg As Worksheet, wsErr As Worksheet Set wsCon = Sheets(&quot;CONTROL&quot;) Set wsLot = Sheets(&quot;LOTS&quot;) Set wsReg = Sheets(&quot;REGISTER&quot;) Set WSActual = ActiveSheet Application.ScreenUpdating = False Application.DisplayAlerts = False Application.Calculation = xlCalculationManual 'Check if ERROR exists, and if so, delete it For Each Sheet In ActiveWorkbook.Worksheets If Sheet.Name = &quot;ERROR&quot; Then Application.DisplayAlerts = False Sheet.Delete Application.DisplayAlerts = True End If Next Sheet 'Create ERROR Sheet Set WSError = Sheets(&quot;ERRORT&quot;) WSError.Copy Before:=wsCon ActiveSheet.Name = &quot;ERROR&quot; Set WSError = ActiveSheet Set wsErr = Sheets(&quot;ERROR&quot;) wsErr.Cells(2, 2).Value = &quot;REGISTERS WITH ERRORS&quot; wsErr.Cells(5, 23).Value = &quot;ERROR CODE&quot; ErrorLastRowPrev = 6 ErrorLastRow = 6 'Clear any existing filters On Error Resume Next wsReg.ShowAllData On Error GoTo 0 'Identify the Errors for Zone, Discipline and Ex Certificate For k = 7 To (wsLot.Cells(5, 3).Value + 6) wsReg.Activate tempvar = wsReg.Range(&quot;H&quot; &amp; k).Value If tempvar = &quot;Z0&quot; Or tempvar = &quot;Z1&quot; Or tempvar = &quot;Z2&quot; Then wsReg.Range(&quot;Y&quot; &amp; k).Value = &quot;OK&quot; Else wsReg.Range(&quot;Y&quot; &amp; k).Value = &quot;FAIL&quot; End If tempvar = wsReg.Range(&quot;T&quot; &amp; k).Value If tempvar = &quot;Instrument&quot; Or tempvar = &quot;Electrical&quot; Then wsReg.Range(&quot;Z&quot; &amp; k).Value = &quot;OK&quot; Else wsReg.Range(&quot;Z&quot; &amp; k).Value = &quot;FAIL&quot; End If tempvar = wsReg.Range(&quot;U&quot; &amp; k).Value If tempvar = &quot;Ex d&quot; Or tempvar = &quot;Ex e&quot; Or tempvar = &quot;Ex n&quot; Or tempvar = &quot;Ex p&quot; Or tempvar = &quot;Ex i&quot; Then wsReg.Range(&quot;AA&quot; &amp; k).Value = &quot;OK&quot; Else wsReg.Range(&quot;AA&quot; &amp; k).Value = &quot;FAIL&quot; End If tempvar = wsReg.Range(&quot;V&quot; &amp; k).Value If tempvar = &quot;High&quot; Or tempvar = &quot;Medium&quot; Or tempvar = &quot;Low&quot; Then wsReg.Range(&quot;AB&quot; &amp; k).Value = &quot;OK&quot; Else wsReg.Range(&quot;AB&quot; &amp; k).Value = &quot;FAIL&quot; End If Next k 'Filter the rows with errors Application.DisplayAlerts = False On Error Resume Next With wsReg.Range(&quot;A7:AD&quot; &amp; wsLot.Cells(5, 3).Value) .AutoFilter Field:=2, Criteria1:=&quot;=&quot; .SpecialCells(xlCellTypeVisible).Cells.Copy wsErr.Rows(ErrorLastRow + 1).PasteSpecial .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete End With On Error GoTo 0 'Clear any existing filters On Error Resume Next wsReg.ShowAllData On Error GoTo 0 'Recalculate ErrorLastRow ErrorLastRow = wsErr.Cells.Find(What:=&quot;*&quot;, After:=Range(&quot;A1&quot;), SearchOrder:=xlByRows, Searchdirection:=xlPrevious).Row If ErrorLastRow &lt; ErrorLastRowPrev Then 'No Errors ErrorLastRow = ErrorLastRowPrev ThisCatErrors = ErrorLastRow - ErrorLastRowPrev Else 'Errors ThisCatErrors = ErrorLastRow - ErrorLastRowPrev wsErr.Range(&quot;W&quot; &amp; (ErrorLastRowPrev + 1) &amp; &quot;:W&quot; &amp; ErrorLastRow).Value = &quot;Id or record Missing&quot; wsLot.Cells(5, 3).Value = wsLot.Cells(5, 3).Value - (ThisCatErrors) ErrorLastRowPrev = ErrorLastRow End If 'Zone Errors On Error Resume Next With wsReg.Range(&quot;A7:AD&quot; &amp; wsLot.Cells(5, 3).Value) .AutoFilter Field:=25, Criteria1:=&quot;FAIL&quot; .SpecialCells(xlCellTypeVisible).Cells.Copy wsErr.Rows(ErrorLastRow + 1).PasteSpecial .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete End With On Error GoTo 0 'Clear any existing filters On Error Resume Next wsReg.ShowAllData On Error GoTo 0 ErrorLastRow = wsErr.Cells.Find(What:=&quot;*&quot;, After:=Range(&quot;A1&quot;), SearchOrder:=xlByRows, Searchdirection:=xlPrevious).Row If ErrorLastRow &lt; ErrorLastRowPrev + 1 Then 'No Errors ErrorLastRow = ErrorLastRowPrev ThisCatErrors = ErrorLastRow - ErrorLastRowPrev Else 'Errors ThisCatErrors = ErrorLastRow - ErrorLastRowPrev wsErr.Range(&quot;W&quot; &amp; (ErrorLastRowPrev + 1) &amp; &quot;:W&quot; &amp; ErrorLastRow).Value = &quot;Zone Field not valid&quot; wsLot.Cells(5, 3).Value = wsLot.Cells(5, 3).Value - (ThisCatErrors) ErrorLastRowPrev = ErrorLastRow End If 'Discipline Errors On Error Resume Next With wsReg.Range(&quot;A7:AD&quot; &amp; wsLot.Cells(5, 3).Value) .AutoFilter Field:=26, Criteria1:=&quot;FAIL&quot; .SpecialCells(xlCellTypeVisible).Cells.Copy wsErr.Rows(ErrorLastRow + 1).PasteSpecial .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete End With On Error GoTo 0 'Clear any existing filters On Error Resume Next wsReg.ShowAllData On Error GoTo 0 'Recalculate ErrorLastRow ErrorLastRow = wsErr.Cells.Find(What:=&quot;*&quot;, After:=Range(&quot;A1&quot;), SearchOrder:=xlByRows, Searchdirection:=xlPrevious).Row If ErrorLastRow &lt; ErrorLastRowPrev + 1 Then 'Cero Errores ErrorLastRow = ErrorLastRowPrev ThisCatErrors = ErrorLastRow - ErrorLastRowPrev Else 'Hay Errores ThisCatErrors = ErrorLastRow - ErrorLastRowPrev wsErr.Range(&quot;W&quot; &amp; (ErrorLastRowPrev + 1) &amp; &quot;:W&quot; &amp; ErrorLastRow).Value = &quot;Discipline not valid&quot; wsLot.Cells(5, 3).Value = wsLot.Cells(5, 3).Value - (ThisCatErrors) ErrorLastRowPrev = ErrorLastRow End If 'Errores de Ex cert On Error Resume Next With wsReg.Range(&quot;A7:AD&quot; &amp; wsLot.Cells(5, 3).Value) .AutoFilter Field:=27, Criteria1:=&quot;FAIL&quot; .SpecialCells(xlCellTypeVisible).Cells.Copy wsErr.Rows(ErrorLastRow + 1).PasteSpecial .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete End With On Error GoTo 0 'Clear any existing filters On Error Resume Next wsReg.ShowAllData On Error GoTo 0 'Recalculate ErrorLastRow ErrorLastRow = wsErr.Cells.Find(What:=&quot;*&quot;, After:=Range(&quot;A1&quot;), SearchOrder:=xlByRows, Searchdirection:=xlPrevious).Row If ErrorLastRow &lt; ErrorLastRowPrev + 1 Then 'No Errors ErrorLastRow = ErrorLastRowPrev ThisCatErrors = ErrorLastRow - ErrorLastRowPrev Else 'Errores ThisCatErrors = ErrorLastRow - ErrorLastRowPrev wsErr.Range(&quot;W&quot; &amp; (ErrorLastRowPrev + 1) &amp; &quot;:W&quot; &amp; ErrorLastRow).Value = &quot;Ex protection type not valid&quot; wsLot.Cells(5, 3).Value = wsLot.Cells(5, 3).Value - (ThisCatErrors) ErrorLastRowPrev = ErrorLastRow End If 'Risk Level Errors On Error Resume Next With wsReg.Range(&quot;A7:AD&quot; &amp; wsLot.Cells(5, 3).Value) .AutoFilter Field:=28, Criteria1:=&quot;FAIL&quot; .SpecialCells(xlCellTypeVisible).Cells.Copy wsErr.Rows(ErrorLastRow + 1).PasteSpecial .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete End With On Error GoTo 0 'Clear any existing filters On Error Resume Next wsReg.ShowAllData On Error GoTo 0 'Recalculate ErrorLastRow ErrorLastRow = wsErr.Cells.Find(What:=&quot;*&quot;, After:=Range(&quot;A1&quot;), SearchOrder:=xlByRows, Searchdirection:=xlPrevious).Row If ErrorLastRow &lt; ErrorLastRowPrev + 1 Then 'No Errors ErrorLastRow = ErrorLastRowPrev ThisCatErrors = ErrorLastRow - ErrorLastRowPrev Else 'Errors ThisCatErrors = ErrorLastRow - ErrorLastRowPrev wsErr.Range(&quot;W&quot; &amp; (ErrorLastRowPrev + 1) &amp; &quot;:W&quot; &amp; ErrorLastRow).Value = &quot;Risk level not valid&quot; wsLot.Cells(5, 3).Value = wsLot.Cells(5, 3).Value - (ThisCatErrors) ErrorLastRowPrev = ErrorLastRow End If wsLot.Cells(5, &quot;B&quot;).Value = ErrorLastRow - 6 'End Application.DisplayAlerts = True Application.Calculation = xlCalculationAutomatic WSActual.Activate End Sub Sub PutSomeOrder(LastRow2 As Long) Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets(&quot;REGISTER&quot;) With ws.Sort .SortFields.Clear .SortFields.Add Key:=ws.Range(&quot;C7&quot;), Order:=xlAscending .SortFields.Add Key:=ws.Range(&quot;H7&quot;), Order:=xlAscending .SortFields.Add Key:=ws.Range(&quot;T7&quot;), Order:=xlAscending .SetRange ws.Range(&quot;A7:AH&quot; &amp; LastRow2) .Apply End With End Sub </code></pre>
[]
[ { "body": "<p>Before considering performance...some comments from reviewing the code.</p>\n<ol>\n<li>(Best Practice) Use <code>Option Explicit</code> at the top of the module. This forces the requirement for all variables and constants to be declared. Consequently, it can identify typos like <code>Dim ThisWorBookName As String</code> (found in the code) when <code>Dim ThisWorkBookName As String</code> was intended. Declaring variables at the top of a procedure is better than not declaring them at all. Better still is declaring them closer to where they are first used.</li>\n<li>(Deprecated) <code>Call</code> is no longer required to call procedures. It can be removed.</li>\n<li><code>Sub Import_data()</code> is a fairly lengthy subroutine. Notice how comments are required throughout to identify what 'task' is being performed by various blocks of code. Your code can become somewhat self-documenting by creating and calling procedures that are named for the task. This will will make all your subroutines easier to read, debug, and instrument in order to find what operations are taking the longest time. Doing this applies the <em>Single Responsibility Principle</em> (SRP): Each Subroutine and Function should accomplish a single task...or put another way, each Subroutine and Function should have a single 'reason to change'. (Easier said than done...but it is something for your code to aspire to).</li>\n<li>Apply the <em>Don't Repeat Yourself</em> (DRY) principle. There is a lot of repeated statements and code blocks that vary only by a single parameter. The repeated blocks can be eliminated by extracting the logic into focused subroutines and functions.</li>\n<li>Give variable names a meaningful identifier. Using an abbreviation is not going to make your code faster (or slower)...but abbreviations and single character variable names will definitely be require more time and effort to understand when you come back to this code (for whatever reason) months later.</li>\n<li>There are many references to cells using constant row and column identifiers. For example <code>wsLot.Cells(5, &quot;C&quot;)</code> is a particular favorite. It is referred to often using different row and cell constants: <code>wsLot.Cells(5,3)</code>, <code>wsLot.Cells(&quot;C5&quot;)</code>\nThis cell is consistently associated with the variable <code>RegisterNoError</code>. Consider adding a module Property by the same name and removing the variable altogether.</li>\n</ol>\n<p>Same applies to:\n<code>Worksheets(&quot;LOTS&quot;).Cells(5, &quot;D&quot;)</code> =&gt; <code>RegisterNumb</code> (use the full name?)\n<code>Worksheets(&quot;LOTS&quot;).Cells(5, 1)</code> =&gt; <code>AreaNumber</code>\nIn fact, there appears to be a number of important cells in row 5 of <code>Worksheets(&quot;LOTS&quot;)</code>. I've deciphered 3...Give them all names/properties and your code becomes more readable (and consistent).\nOther similar opportunities: <code>Worksheets(&quot;CONTROL&quot;).Cells(4,3)</code> and <code>Worksheets(&quot;CONTROL&quot;).Cells(5,3)</code>. Another option for consistency and easy interpretation is using <code>NamedRanges</code>.</p>\n<ol start=\"7\">\n<li>Magic Numbers - there are many cases where numeric literals are used within the code. It is nearly impossible to figure out what they mean. If they can be given a name, then declare them as constants. For example, '6' is used in many places. My guess is that it is an important offset from <em>something</em>. Declare a module constant with a meaningful name: <code>Private Const IMPORTANT_OFFSET As Long = 6</code> (you can pick a better name). Other frequently used magic numbers in the code are 7 and 9. What do they mean?...give them a name. Magic numbers also make their way into hard coded formula strings - build the formula strings using the constant(s) there as well. When the need arises to change these magic numbers, you only have to modify the declaration rather than hunt through your code and hope that you've updated them all (spoiler alert: you haven't). Note: column value string literals within <code>Range</code> or <code>Cell</code> calls are essentially 'magic numbers' as well and can possibly be declared as constant string values with names that provide more meaning.</li>\n<li>Finally - performance. Not sure what you would consider fast or slow, but one way to determine where the code is 'slowest' is to log timestamps and see where bottlenecks might exist. They are often not where you expect. So, log timestamp subroutine calls throughout your code and you will know where to spend your effort. Before and after a section of code you deem significant call a logging procedure...something like.</li>\n</ol>\n<pre><code>Private Sub LogTime(message As String)\n Dim timestamp As String, logEntry As String\n timestamp = Format(Now, &quot;mm/dd/yyyy HH:mm:ss&quot;)\n logEntry = message &amp; &quot;: &quot; &amp; timestamp\n 'Append logEntry to a text file or write them out to an excel sheet \nEnd Sub\n</code></pre>\n<p>Below is the module refactored using some of the ideas described above. I had to stub a few procedures to get the original code to compile - so obviously, the code below does not <em>work</em>.</p>\n<pre><code>Option Explicit\n\nPrivate Const IMPORTANT_OFFSET As Long = 6\n\nPrivate Property Get RegisterNoError() As Long\n RegisterNoError = Worksheets(&quot;LOTS&quot;).Range(&quot;C5&quot;).value\nEnd Property\n\nPrivate Property Let RegisterNoError(value As Long)\n Worksheets(&quot;LOTS&quot;).Range(&quot;C5&quot;).value = value\nEnd Property\n\nPrivate Property Get RegisterNumb() As Long\n RegisterNoError = Worksheets(&quot;LOTS&quot;).Range(&quot;D5&quot;).value\nEnd Property\n\nPrivate Property Let RegisterNumb(value As Long)\n Worksheets(&quot;LOTS&quot;).Range(&quot;D5&quot;).value = value\nEnd Property\n\nSub Import_data()\n\nDim FilePath As Variant, FileName As Variant, TempSheetName As String, k As Integer, n As Integer, Errors As Integer, i As Integer\nDim LastRow As Long\nDim PathWorkbook As String, ProjectName As String\nDim AreaName As String, Areacode As String, AreaNumber As String\nDim wsCon As Worksheet, wsLot As Worksheet, wsReg As Worksheet\n\nSet wsCon = Sheets(&quot;CONTROL&quot;)\nSet wsLot = Sheets(&quot;LOTS&quot;)\n\nPageVisibility (1) 'Not declared - I've added stub so that this subroutine can compile\n\nApplication.ScreenUpdating = False\nApplication.DisplayAlerts = False\nApplication.Calculation = xlCalculationManual\n\nDim ThisWorkBookName As String 'Identified when Option Explicit was added\nThisWorkBookName = ActiveWorkbook.Name\n\nPathWorkbook = Application.ThisWorkbook.Path &amp; &quot;\\&quot;\nProjectName = Left(wsCon.Cells(4, 3).value, 8) &amp; &quot;_&quot; &amp; (Format(wsCon.Cells(5, 3).value, &quot;yyyy_mm_dd&quot;))\n\nChDir PathWorkbook\n\n'Check if Project exist\nDim var1 As String 'Identified when Option Explicit was added\nDim var2 As String 'Identified when Option Explicit was added\n\nvar1 = Application.ThisWorkbook.Path &amp; &quot;\\&quot;\nvar2 = Left(wsCon.Cells(4, 3).value, 8) &amp; &quot;_&quot; &amp; (Format(wsCon.Cells(5, 3).value, &quot;yyyy_mm_dd&quot;))\n\nIf Dir(var1 &amp; var2, vbDirectory) = &quot;&quot; Then\n Dim Result As Long\n Result = MsgBox(&quot;Project &quot; &amp; var2 &amp; &quot; Does not exist.&quot; &amp; vbNewLine &amp; vbNewLine &amp; &quot;Do You want to Create it?&quot;, vbYesNo + vbExclamation)\n If Result = 6 Then\n CreateProjects 'Is not declared - added a stub to make the module compile\n Else\n \n MsgBox &quot;You Need to create the project before Importing the records&quot;, vbExclamation\n Exit Sub\n \n End If\n \nEnd If\n\nwsLot.Range(&quot;B5:D5&quot;).value = 0\nwsLot.Range(&quot;D9:E100&quot;).Delete Shift:=xlUp\n\nTempSheetName = &quot;REGISTER&quot;\n \n'Check that workbook is reset\n\nDim Sheet As Worksheet\nFor Each Sheet In Worksheets\n If TempSheetName = UCase(Sheet.Name) Then\n \n MsgBox &quot;Reset before importing&quot;\n Exit Sub\n End If\nNext Sheet\n\n'File opening\n\nFilePath = Application.GetOpenFilename(FileFilter:=&quot;Excel Files (*.XLSX), *.XLSX&quot;, Title:=&quot;Select File To Be Opened&quot;)\nIf FilePath = False Then Exit Sub\n\n'Animated.Show vbModeless\n'Application.Wait (Now + TimeValue(&quot;0:00:05&quot;))\n'DoEvents\n\nFileName = Mid$(FilePath, InStrRev(FilePath, &quot;\\&quot;) + 1, Len(FilePath))\n\nDim ControlFile As String\nControlFile = ActiveWorkbook.Name\nWorkbooks.Open FileName:=FilePath\nSheets(&quot;REGISTER&quot;).Copy After:=Workbooks(ControlFile).Sheets(&quot;LOTEVAL&quot;)\nWindows(FileName).Activate\nActiveWorkbook.Close SaveChanges:=False\nWindows(ControlFile).Activate\n\n'Formulas to values\n\nSet wsReg = Sheets(&quot;REGISTER&quot;)\n\nwsReg.Unprotect\n\nwsReg.Range(&quot;B:B&quot;).value = wsReg.Range(&quot;B:B&quot;).value '&lt;--Copies self(?)\nwsReg.Range(&quot;V:V&quot;).value = wsReg.Range(&quot;V:V&quot;).value '&lt;--Copies self(?)\nwsReg.Range(&quot;Y:Y&quot;).value = wsReg.Range(&quot;Y:Y&quot;).value '&lt;--Copies self(?)\n\nLastRow = Cells.Find(What:=&quot;*&quot;, After:=Range(&quot;A1&quot;), SearchOrder:=xlByRows, Searchdirection:=xlPrevious).Row\n\nRegisterNumb = LastRow - IMPORTANT_OFFSET\nRegisterNoError = RegisterNumb\n\n'Error Filtering\n'--------------------\n\nErrorProcessing 'fixed typo\n\n'Order\n'------------\n\nPutSomeOrder LastRow\n\n'Main Areas creation\n'-------------------\n\nwsLot.Range(&quot;A9&quot;).Formula2R1C1 = &quot;=UNIQUE(FILTER(REGISTER!R7C3:R65536C3,REGISTER!R7C3:R65536C3&lt;&gt;&quot;&quot;&quot;&quot;))&quot;\n\n'Lot assignement\n'---------------\n\nn = IMPORTANT_OFFSET + RegisterNoError\n\nFor k = 7 To n\nAreaNumber = wsLot.Cells(5, 1).value 'Assign this outside the loop, it is not modified in the loop or depend on k\n\nIf wsReg.Cells(k, &quot;B&quot;).value &gt; 0 Then\n \n If wsReg.Cells(k, &quot;B&quot;).value = wsReg.Cells((k - 1), &quot;B&quot;).value Then\n wsReg.Cells(k, &quot;AA&quot;).value = wsReg.Cells((k - 1), &quot;AA&quot;).value\n Else\n For i = 9 To AreaNumber + 8\n If wsReg.Range(&quot;C&quot; &amp; k).value = wsLot.Range(&quot;A&quot; &amp; i) Then wsReg.Cells(k, &quot;AA&quot;).value = wsLot.Range(&quot;C&quot; &amp; i)\n Next i\n End If\n\nwsReg.Cells(k, &quot;AB&quot;).value = wsReg.Cells(k, &quot;H&quot;).value\nwsReg.Cells(k, &quot;AC&quot;).value = wsReg.Cells(k, &quot;V&quot;).value\nwsReg.Cells(k, &quot;AD&quot;).value = wsReg.Cells(k, &quot;AA&quot;).value &amp; &quot;_&quot; &amp; wsReg.Cells(k, &quot;AB&quot;).value &amp; &quot;_&quot; &amp; wsReg.Cells(k, &quot;AC&quot;).value\n\nEnd If\n\nNext k\n\nn = 8 + wsLot.Cells(5, &quot;A&quot;).value\n\nwsLot.Cells(9, &quot;E&quot;).value = 7\n\nFor k = 9 To n\n\nwsLot.Cells(k, &quot;D&quot;).value = WorksheetFunction.CountIf(wsReg.Range(&quot;AA:AA&quot;), wsLot.Cells(k, &quot;C&quot;).value)\n\nIf k &gt; 9 Then wsLot.Cells(k, &quot;E&quot;).value = wsLot.Cells(k - 1, &quot;E&quot;).value + wsLot.Cells(k - 1, &quot;D&quot;).value\n\nNext k\n\nRegisterNoError = WorksheetFunction.CountA(wsReg.Range(&quot;AA:AA&quot;))\n\nwsLot.Range(&quot;G9&quot;).Formula2R1C1 = &quot;=UNIQUE(FILTER(REGISTER!R7C30:R12000C30,REGISTER!R7C30:R12000C30&lt;&gt;&quot;&quot;&quot;&quot;))&quot;\nwsLot.Range(&quot;E5&quot;).Formula = &quot;=IFERROR(IF(G9&lt;&gt;&quot;&quot;&quot;&quot;,COUNTA(G9#),0),0)&quot;\nwsLot.Range(&quot;Q9&quot;).Formula2R1C1 = &quot;=UNIQUE(FILTER(REGISTER!R7C30:R12000C30,REGISTER!R7C30:R12000C30&lt;&gt;&quot;&quot;&quot;&quot;))&quot;\nwsLot.Range(&quot;R9&quot;).Formula2R1C1 = &quot;UNIQUE(FILTER(R:R,R:R&lt;&gt;&quot;&quot;&quot;&quot;))&quot;\n\nn = 8 + wsLot.Cells(5, &quot;E&quot;).value\n\nwsLot.Cells(9, &quot;E&quot;).value = 7\n\nFor k = 9 To n\n\nwsLot.Cells(k, &quot;H&quot;).value = WorksheetFunction.CountIf(wsReg.Range(&quot;AD:AD&quot;), wsLot.Cells(k, &quot;G&quot;).value)\n\nNext k\n\nwsLot.Range(&quot;H8&quot;).Formula = &quot;=MAX(H9:H3000)&quot;\n\nCalculate\n\nIf wsLot.Range(&quot;H8&quot;).value &gt; 3200 Then MsgBox &quot;Warning, at least one of the lots has more than 32000 elements&quot;\n\n'Export errors and Registers to Project Folder\nExportErrorsAndRegistersToProjectFolder 'no longer a need for the above comment (#3)\n\nErrors = wsLot.Range(&quot;B5&quot;).value\nwsCon.Range(&quot;O3&quot;).value = 1\nwsCon.Activate\n\nMsgBox (&quot;Ex DataBase Import Completed&quot; &amp; vbNewLine &amp; vbNewLine _\n&amp; &quot;TOTAL EQUIPMENT IN Ex DATABASE : &quot; &amp; RegisterNumb &amp; vbNewLine _\n&amp; &quot;EQUIPMENT EXCLUDED DUE TO ERROR : &quot; &amp; Errors &amp; vbNewLine _\n&amp; &quot;TOTAL EQUIPMENT IMPORTED : &quot; &amp; RegisterNoError &amp; vbNewLine &amp; vbNewLine _\n&amp; &quot;The Equipment with errors have been recorded on the ERRROR_LOG. You can continue discarting those elements or correct them in the originalfile and do the Import again.&quot; &amp; vbNewLine)\n\n\n'Save for Navigation\n \nActiveWorkbook.SaveAs PathWorkbook &amp; ProjectName &amp; &quot;\\NAV\\&quot; &amp; ProjectName &amp; &quot;_Step_1.exp&quot;, FileFormat:=52\nActiveWorkbook.SaveAs PathWorkbook &amp; ProjectName &amp; &quot;\\&quot; &amp; ProjectName &amp; &quot;.exp&quot;, FileFormat:=52\nActiveWorkbook.SaveAs PathWorkbook &amp; ThisWorkBookName, FileFormat:=52\n \n \nCall PageVisibility(2)\n \nApplication.DisplayAlerts = True\nApplication.ScreenUpdating = True\nApplication.Calculation = xlCalculationAutomatic\n\n'Unload Animated\n\nSheets(&quot;LOTEVAL&quot;).Activate\nwsCon.Activate\n\nEnd Sub\n\nSub ErrorProcessing()\n\nDim WSActual As Worksheet, WSError As Worksheet\nDim k As Integer, tempvar As Variant\nDim wsCon As Worksheet, wsLot As Worksheet, wsReg As Worksheet, wsErr As Worksheet\n\nSet wsCon = Sheets(&quot;CONTROL&quot;)\nSet wsLot = Sheets(&quot;LOTS&quot;)\nSet wsReg = Sheets(&quot;REGISTER&quot;)\n\nSet WSActual = ActiveSheet\n\nApplication.ScreenUpdating = False\nApplication.DisplayAlerts = False\nApplication.Calculation = xlCalculationManual\n\n\n'Check if ERROR exists, and if so, delete it\nDim Sheet As Worksheet\nFor Each Sheet In ActiveWorkbook.Worksheets\n If Sheet.Name = &quot;ERROR&quot; Then\n Application.DisplayAlerts = False\n Sheet.Delete\n Application.DisplayAlerts = True\n End If\nNext Sheet\n\n'Create ERROR Sheet\n\nSet WSError = Sheets(&quot;ERRORT&quot;) '&lt;--Typo?\n \nWSError.Copy Before:=wsCon\nActiveSheet.Name = &quot;ERROR&quot;\nSet WSError = ActiveSheet\n\nSet wsErr = Sheets(&quot;ERROR&quot;)\n\nwsErr.Cells(2, 2).value = &quot;REGISTERS WITH ERRORS&quot;\nwsErr.Cells(5, 23).value = &quot;ERROR CODE&quot;\n\nClearAnyExistingFilters wsReg ' - DRY (#4)\n\n'Identify the Errors for Zone, Discipline and Ex Certificate\n\nFor k = 7 To RegisterNoError + IMPORTANT_OFFSET\n\n wsReg.Activate\n \n LoadOKFail MeetsSuccessCriteria1(wsReg.Range(&quot;H&quot; &amp; k).value), wsReg, &quot;Y&quot;, k ' - DRY (#4)\n \n LoadOKFail MeetsSuccessCriteria2(wsReg.Range(&quot;T&quot; &amp; k).value), wsReg, &quot;Z&quot;, k ' - DRY (#4)\n \n LoadOKFail MeetsSuccessCriteria3(wsReg.Range(&quot;U&quot; &amp; k).value), wsReg, &quot;AA&quot;, k ' - DRY (#4)\n \n LoadOKFail MeetsSuccessCriteria4(wsReg.Range(&quot;V&quot; &amp; k).value), wsReg, &quot;AB&quot;, k ' - DRY (#4)\n\nNext k\n\n'Filter the rows with errors\nApplication.DisplayAlerts = False\n\nDim ErrorLastRowPrev As Long\nErrorLastRowPrev = IMPORTANT_OFFSET\n\nEvaluateField wsLot, wsReg, wsErr, 2, ErrorLastRowPrev ' - DRY (#4)\n\nErrorLastRowPrev = HandleErrors(ErrorLastRowPrev - 1, wsErr, wsLot, &quot;Id or record Missing&quot;) ' - DRY (#4)\n\n'Zone Errors\nEvaluateField wsLot, wsReg, wsErr, 25, ErrorLastRowPrev ' - DRY (#4)\n\nErrorLastRowPrev = HandleErrors(ErrorLastRowPrev, wsErr, wsLot, &quot;Zone Field not valid&quot;) ' - DRY (#4)\n\n'Discipline Errors\nEvaluateField wsLot, wsReg, wsErr, 26, ErrorLastRowPrev ' - DRY (#4)\n\nErrorLastRowPrev = HandleErrors(ErrorLastRowPrev, wsErr, wsLot, &quot;Discipline not valid&quot;) ' - DRY (#4)\n\n'Errores de Ex cert\nEvaluateField wsLot, wsReg, wsErr, 27, ErrorLastRowPrev ' - DRY (#4)\n\nErrorLastRowPrev = HandleErrors(ErrorLastRowPrev, wsErr, wsLot, &quot;Ex protection type not valid&quot;) ' - DRY (#4)\n\n'Risk Level Errors\nEvaluateField wsLot, wsReg, wsErr, 28, ErrorLastRowPrev ' - DRY (#4)\n\nErrorLastRowPrev = HandleErrors(ErrorLastRowPrev, wsErr, wsLot, &quot;Risk level not valid&quot;) ' - DRY (#4)\n\nwsLot.Cells(5, &quot;B&quot;).value = ErrorLastRowPrev - IMPORTANT_OFFSET\n\n'End\n\nApplication.DisplayAlerts = True\nApplication.Calculation = xlCalculationAutomatic\nWSActual.Activate\n\nEnd Sub\n\nSub PutSomeOrder(LastRow2 As Long)\n\nDim ws As Worksheet: Set ws = ThisWorkbook.Worksheets(&quot;REGISTER&quot;)\n\n With ws.Sort\n .SortFields.Clear\n .SortFields.Add Key:=ws.Range(&quot;C7&quot;), Order:=xlAscending\n .SortFields.Add Key:=ws.Range(&quot;H7&quot;), Order:=xlAscending\n .SortFields.Add Key:=ws.Range(&quot;T7&quot;), Order:=xlAscending\n .SetRange ws.Range(&quot;A7:AH&quot; &amp; LastRow2)\n .Apply\n End With\n\nEnd Sub\n'EvaluateField needs a better name\nPrivate Sub EvaluateField(wsLot As Worksheet, wsReg As Worksheet, wsErr As Worksheet, field As Long, ErrorLastRow As Long)\nOn Error Resume Next\n With wsReg.Range(&quot;A7:AD&quot; &amp; RegisterNoError)\n .AutoFilter field:=field, Criteria1:=&quot;FAIL&quot;\n .SpecialCells(xlCellTypeVisible).Cells.Copy\n wsErr.Rows(ErrorLastRow + 1).PasteSpecial\n .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete\n End With\nOn Error GoTo 0\n\nClearAnyExistingFilters wsReg ' - DRY (#4)\n\nEnd Sub\n\nPrivate Sub ClearAnyExistingFilters(wsReg As Worksheet)\n On Error Resume Next\n wsReg.ShowAllData\n On Error GoTo 0\nEnd Sub\n\n'MeetsSuccessCriteriaX functions need a more meaningful name\n\nPrivate Function MeetsSuccessCriteria1(value As Variant) As Boolean\n MeetsSuccessCriteria1 = &quot;Z0&quot; Or value = &quot;Z1&quot; Or value = &quot;Z2&quot;\nEnd Function\n\nPrivate Function MeetsSuccessCriteria2(value As Variant) As Boolean\n MeetsSuccessCriteria2 = value = &quot;Instrument&quot; Or value = &quot;Electrical&quot;\nEnd Function\n\nPrivate Function MeetsSuccessCriteria3(value As Variant) As Boolean\n MeetsSuccessCriteria3 = value = &quot;Ex d&quot; Or value = &quot;Ex e&quot; Or value = &quot;Ex n&quot; Or value = &quot;Ex p&quot; Or value = &quot;Ex i&quot;\nEnd Function\n\nPrivate Function MeetsSuccessCriteria4(value As Variant) As Boolean\n MeetsSuccessCriteria4 = value = &quot;High&quot; Or value = &quot;Medium&quot; Or value = &quot;Low&quot;\nEnd Function\n\nPrivate Sub LoadOKFail(ByVal isOK As Boolean, ByRef wsReg As Worksheet, ByVal columnID As String, ByVal rowIndex As Integer)\nIf isOK Then\n wsReg.Range(columnID &amp; rowIndex).value = &quot;OK&quot;\nElse\n wsReg.Range(columnID &amp; rowIndex).value = &quot;FAIL&quot;\nEnd If\n\nEnd Sub\nPrivate Function HandleErrors(ByVal errLastRowPrev As Long, ByRef wsErr As Worksheet, ByRef wsLot As Worksheet, ByVal message As String) As Long\n'Recalculate ErrorLastRow\nDim errLastRow As Long\nerrLastRow = wsErr.Cells.Find(What:=&quot;*&quot;, After:=Range(&quot;A1&quot;), SearchOrder:=xlByRows, Searchdirection:=xlPrevious).Row\n\n Dim thisCatErrs As Long\n HandleErrors = errLastRow\n If errLastRow &lt; errLastRowPrev + 1 Then\n 'No Errors\n errLastRow = errLastRowPrev\n thisCatErrs = errLastRow - errLastRowPrev\n Else\n 'Errors\n thisCatErrs = errLastRow - errLastRowPrev\n wsErr.Range(&quot;W&quot; &amp; (errLastRowPrev + 1) &amp; &quot;:W&quot; &amp; errLastRow).value = message\n RegisterNoError = RegisterNoError - (thisCatErrs)\n HandleErrors = errLastRow\n End If\n\nEnd Function\n\n'Stubs\nPublic Sub ExportErrorsAndRegistersToProjectFolder()\nEnd Sub\n\nPublic Sub PageVisibility(value As Long)\nEnd Sub\n\nPublic Sub CreateProjects()\nEnd Sub\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T14:38:02.343", "Id": "483387", "Score": "0", "body": "Excellent post. I'm pretty sure that you prepared most of it as a generic snippet. Genius,! it so much better than my reviews." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T14:42:44.553", "Id": "483388", "Score": "1", "body": "I have never liked `Call` until I wrote my `ShapeTextFormatter` class. Because it uses a builder pattern, numerous functions are called without any values being received. `Call` gave it a cleaner look." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T14:48:16.227", "Id": "483389", "Score": "1", "body": "@TinMan thanks. Actually not a generic snippet...but you're right. It could/should have been done that way. Not passing judgement on using `Call`, just that it's no longer required and _usually_ the less text to enter, visually parse and maintain, the better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T15:40:37.407", "Id": "483392", "Score": "0", "body": "I can just say, WOW, thank you very much for your time and effort. I will have a look on the code you wrote and try to do the same by myself. It's true that my original code is a bit of a mesh as I was adding stuff on the go... Got coding last time at the uni, but I wanted to make auto some inspections we need to perform, so learning vba as I'm writing it. I Will update with later developments. Thanks Again!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-29T12:33:19.697", "Id": "483652", "Score": "0", "body": "@BZngr did Try to follow your advice and did the thing below. Much faster and I hope also much cleaner! Thanks Again" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-29T14:04:44.313", "Id": "483666", "Score": "0", "body": "@Lander-Garro Glad to hear of the performance improvements. Congrats! You may also find content [here](https://rubberduckvba.com) useful as you work to improve your VBA coding." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T12:36:53.923", "Id": "246034", "ParentId": "246013", "Score": "6" } }, { "body": "<p>I spent a bit of time on it and incorporated the suggestions of @BZngr as well as other small tricks. The first code was taking more than two minutes in processing a list of 6000 elements when the one below is taking around 10 seconds to do the same. I can't do much about the delays in the file and copy operations, so I'm quite ok with the result, but, again, any suggestion that makes me improve the way I code would be fantastic.</p>\n<pre><code>Option Explicit\nOption Base 1\n\n\nSub ImportDatabase()\n\n\nChDir MainWBPath\n\nUnhideAll True\nUnprotectAll True\nScreenAndAlertsOff True\n\n'Maybe Create a sub for this, as can be used by createproject\nIf Dir(MainWBPath &amp; ProjectName, vbDirectory) = &quot;&quot; Then\n\n Dim Result As Boolean\n Call OKCancelButton(Result, &quot;Project &quot; &amp; ProjectName &amp; &quot; Does not exist.&quot; &amp; vbNewLine &amp; vbNewLine &amp; &quot;Do You want to Create it?&quot;)\n If Result = True Then\n Call CreateProjectFolders\n Call SaveStep(0)\n Else\n Call OKButton(&quot;You need to create a project before import a DataBase&quot;)\n GoTo Endline\n End If\n\nEnd If\n\nCall ResetWorkBookValues\nCall WsExistsAndDelete(&quot;REGISTER&quot;, 2, Result) 'Option 2 to show a warning, result true means it exist\nIf Result = True Then GoTo Endline\n\nCall OKButton(&quot;Please, be confirm that the DB to import is stored in the REGISTER tab of the file&quot;)\n\n'Opening the File and copy to my workbook\nDim FileName As Variant, RegisterWorkBook As Workbook, Mainworkbook As Workbook\nFileName = Application.GetOpenFilename(FileFilter:=&quot;Excel Files (*.XLSX), *.XLSX&quot;, Title:=&quot;Select File To Be Opened&quot;)\nIf FileName = False Then GoTo Endline\nSet Mainworkbook = ActiveWorkbook\nDim t#, TimerReg(1 To 10) As Long\nt = Timer\nSet RegisterWorkBook = Workbooks.Open(FileName:=FileName)\n\nRegisterWorkBook.Sheets(&quot;REGISTER&quot;).Copy After:=Mainworkbook.Sheets(&quot;LOTEVAL&quot;)\nRegisterWorkBook.Close SaveChanges:=False\n\nTimerReg(1) = Timer - t\n\nCalculationsOff True\n\nDim WS_REG As Worksheet\nSet WS_REG = Sheets(&quot;REGISTER&quot;)\nWS_REG.Unprotect Password:=&quot;lukenandmeia&quot;\n\n'Change the formulas to Values\nWith WS_REG\n .Range(&quot;B1:B12000&quot;).value = .Range(&quot;B1:B12000&quot;).value\n .Range(&quot;V1:V12000&quot;).value = .Range(&quot;V1:V12000&quot;).value\n .Range(&quot;Y1:Y12000&quot;).value = .Range(&quot;Y1:Y12000&quot;).value\n .Range(&quot;G2&quot;).value = .Range(&quot;G2&quot;).value\n .AutoFilterMode = False\nEnd With\n\nTimerReg(2) = Timer - t\n\n'RemoveConditional Formating\nDim RegFirstCell As Range, RegLastCell As Range, RegisterData As Range\nSet RegFirstCell = WS_REG.Range(&quot;A6&quot;)\nSet RegLastCell = GetLastCell(WS_REG.Range(&quot;A1:AH12000&quot;))\nSet RegisterData = WS_REG.Range(RegFirstCell.Address &amp; &quot;:&quot; &amp; RegLastCell.Address)\n\nWith WS_REG.Cells\n .FormatConditions.Delete\n .Validation.Delete\n .Hyperlinks.Delete\nEnd With\n\nDim RegisterTemp As Long\nRegisterTemp = RegLastCell.row - Register_Offset\nRegisterNumb = RegisterTemp\nRegisterNoError = RegisterTemp\n\nTimerReg(3) = Timer - t\n\nCalculationsOff False\n\n'Error Filtering\nRemoveErrors RegisterData\n'Reorder\nOrderRegisters WS_REG, &quot;C7&quot;, &quot;H7&quot;, &quot;T7&quot;, 7\n\nAssignAreasAndLots 'Area Asignation and calculation of Registers and last Rows\n\nExportErrorsAndRegisters 'Mirar por si se puede mejorar\n\nDim Errors As Long\nErrors = Sheets(&quot;LOTS&quot;).Range(&quot;B5&quot;).value\n\nOKButtonBig &quot;Ex DataBase Import Completed&quot; &amp; vbNewLine &amp; vbNewLine _\n&amp; &quot;TOTAL EQUIPMENT IN Ex DATABASE : &quot; &amp; RegisterNumb &amp; vbNewLine _\n&amp; &quot;EQUIPMENT EXCLUDED DUE TO ERROR : &quot; &amp; Errors &amp; vbNewLine _\n&amp; &quot;TOTAL EQUIPMENT IMPORTED : &quot; &amp; RegisterNoError &amp; vbNewLine &amp; vbNewLine _\n&amp; &quot;The Equipment with errors have been recorded on the ERRROR_LOG. You can continue discarting those elements or correct them in the originalfile and do the Import again.&quot; &amp; vbNewLine\n\n\nActualStep = 1\nSaveStep 1\n\nEndline:\n\n\nUnhideAll False\nUnprotectAll False\nScreenAndAlertsOff False\nCalculationsOff False\n\n\nEnd Sub\n\nSub CreateProjectFolders()\n\nMkDir MainWBPath &amp; ProjectName\nMkDir MainWBPath &amp; ProjectName &amp; &quot;\\AREAS&quot;\nMkDir MainWBPath &amp; ProjectName &amp; &quot;\\LOTS&quot;\nMkDir MainWBPath &amp; ProjectName &amp; &quot;\\NAV&quot;\n\nEnd Sub\n\nSub SaveStep(ByVal Step As Long)\nDim Path As String, Name As String\n\nScreenAndAlertsOff True\n\nPath = MainWBPath\nName = MainWBname\n\nOn Error Resume Next\nActiveWorkbook.SaveAs Path &amp; ProjectName &amp; &quot;\\NAV\\&quot; &amp; ProjectName &amp; &quot;_Step_&quot; &amp; Step &amp; &quot;.exp&quot;, FileFormat:=52\nActiveWorkbook.SaveAs Path &amp; ProjectName &amp; &quot;\\&quot; &amp; ProjectName &amp; &quot;.exp&quot;, FileFormat:=52\nActiveWorkbook.SaveAs Path &amp; Name, FileFormat:=52\nOn Error GoTo 0\nEnd Sub\n\nSub ResetWorkBookValues()\n\nCONTROL.Range(&quot;B22&quot;).ClearContents\nLOTS.Range(&quot;B5:D5&quot;).ClearContents\nLOTS.Range(&quot;D9:E100&quot;).ClearContents\nLOTEVAL.Range(&quot;I6:U200&quot;).ClearContents\n\nEnd Sub\n\nSub WsExistsAndDelete(ByVal Name As String, ByVal OptionErase As Long, ByRef Result As Boolean)\n\n'Option 1 Delete, Option 2 For RegisterCheck\nDim Sheet As Worksheet\nUnprotectAll True\nResult = False\nFor Each Sheet In Worksheets\n If Sheet.Name Like Name Then\n Result = True\n If OptionErase = 1 Then Sheet.Delete\n If OptionErase = 2 Then\n Call OKButton(&quot;Reset Before Import&quot;)\n GoTo Endline\n End If\n Else\n Result = False\n End If\nNext Sheet\n\nEndline:\nUnprotectAll False\n\nEnd Sub\n\nSub RemoveErrors(ByRef RegisterData As Range)\n\nDim Result As Boolean\nCall WsExistsAndDelete(&quot;ERROR&quot;, 1, Result)\nCall CreateWsFromTemplate(&quot;ERROR&quot;, &quot;ERRORT&quot;)\n\nDim WS_ERROR As Worksheet, WS_REG As Worksheet\nDim i As Integer\n\nSet WS_ERROR = Sheets(&quot;ERROR&quot;)\nSet WS_REG = Sheets(&quot;REGISTER&quot;)\n\nCalculationsOff True\nClearAllFilters WS_REG\n\n'For the Advance Filter\nFor i = 1 To 30\nWS_REG.Cells(6, i).value = &quot;Column &quot; &amp; i\nWS_ERROR.Cells(6, i).value = &quot;Column &quot; &amp; i\nNext i\n\nDim Criteria(1 To 5) As Variant\nDim Column As Variant, Errorcode As Variant\n\nCriteria(1) = Array(&quot;=&quot;)\nCriteria(2) = Array(&quot;&lt;&gt;Z1&quot;, &quot;&lt;&gt;Z2&quot;, &quot;&lt;&gt;Z0&quot;)\nCriteria(3) = Array(&quot;&lt;&gt;Instrument&quot;, &quot;&lt;&gt;Electrical&quot;)\nCriteria(4) = Array(&quot;&lt;&gt;Ex d&quot;, &quot;&lt;&gt;Ex e&quot;, &quot;&lt;&gt;Ex n&quot;, &quot;&lt;&gt;Ex p&quot;, &quot;&lt;&gt;Ex i&quot;)\nCriteria(5) = Array(&quot;&lt;&gt;High&quot;, &quot;&lt;&gt;Medium&quot;, &quot;&lt;&gt;Low&quot;)\nColumn = Array(&quot;Column 2&quot;, &quot;Column 8&quot;, &quot;Column 20&quot;, &quot;Column 21&quot;, &quot;Column 22&quot;)\nErrorcode = Array(&quot;Equipment Id&quot;, &quot;Zone&quot;, &quot;Discipline&quot;, &quot;Protection Type&quot;, &quot;Risk&quot;)\n\nFor i = 1 To 5\nCall FilterAndCopy(RegisterData, Column, Criteria, Errorcode, i)\nNext i\n\nDim NumberofErrors As Long, RegisterTemp As Long\n\nNumberofErrors = GetLastCell(WS_ERROR.UsedRange).row - ErrorLog_Offset\nLOTS.Range(&quot;B5&quot;) = NumberofErrors\nRegisterTemp = RegisterNoError\nRegisterNoError = RegisterNoError - NumberofErrors\n\nWS_REG.Rows(6).ClearContents\nWS_ERROR.Rows(6).ClearContents\nClearAllFilters WS_REG\n\n\nEndline:\nCalculationsOff False\n\nEnd Sub\nSub CreateWsFromTemplate(ByVal Name As String, ByVal Template As String)\nSheets(Template).Copy After:=Sheets(Sheets.Count)\nActiveSheet.Name = Name\nEnd Sub\nSub ClearAllFilters(WS As Worksheet)\n On Error Resume Next\n WS.ShowAllData\n On Error GoTo 0\nEnd Sub\nSub FilterAndCopy(ByRef RegisterData As Range, ByRef Column As Variant, ByRef Criteria As Variant, ByRef Errorcode As Variant, ByVal Opt As Long)\n\nDim rngCriteria As Range, ErrLastCell As Range, ErrLastRow As Range\nDim WS_REG As Worksheet, WS_ERROR As Worksheet\nDim i As Long\n\nSet WS_REG = Sheets(&quot;REGISTER&quot;)\nSet WS_ERROR = Sheets(&quot;ERROR&quot;)\nSet rngCriteria = WS_ERROR.Range(&quot;AA1:AE2&quot;)\n\nSet rngCriteria = rngCriteria.Resize(2, UBound(Criteria(Opt)))\nFor i = 1 To UBound(Criteria(Opt))\n rngCriteria(1, i) = Column(Opt)\n rngCriteria(2, i) = Criteria(Opt)(i)\nNext i\n\nSet ErrLastCell = GetLastCell(WS_ERROR.UsedRange)\nSet ErrLastRow = ErrLastCell.EntireRow\n\n With RegisterData\n .AdvancedFilter xlFilterInPlace, rngCriteria\n .SpecialCells(xlCellTypeVisible).Cells.Copy\n ErrLastRow.Offset(1, 0).PasteSpecial\n ErrLastRow.Offset(1, 0).EntireRow.Delete\n .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete\n End With\n\nSet ErrLastCell = GetLastCell(WS_ERROR.UsedRange)\n\nIf (ErrLastCell.row - ErrLastRow.row) &lt;&gt; 0 Then WS_ERROR.Range(&quot;W&quot; &amp; ErrLastRow.row + 1 &amp; &quot;:W&quot; &amp; ErrLastCell.row).value = Errorcode(Opt) &amp; &quot; Not Valid&quot;\nrngCriteria.Clear\n\nEnd Sub\n\nSub OrderRegisters(ByRef WS As Worksheet, ByVal Col1 As String, ByVal Col2 As String, ByVal Col3 As String, Optional ByVal OffsetO As Long = 0)\n\n With WS.Sort\n .SortFields.Clear\n .SortFields.Add Key:=WS.Range(Col1), Order:=xlAscending\n .SortFields.Add Key:=WS.Range(Col2), Order:=xlAscending\n .SortFields.Add Key:=WS.Range(Col3), Order:=xlAscending\n .SetRange WS.Range(&quot;A&quot; &amp; OffsetO &amp; &quot;:AH&quot; &amp; GetLastCell(WS.UsedRange).row)\n .Apply\n End With\n\n\nEnd Sub\n\nSub AssignAreasAndLots()\n\nCalculationsOff True\nScreenAndAlertsOff True\n\nDim dictArea As New Scripting.Dictionary, dictAreaCode As New Scripting.Dictionary, dictLots As New Scripting.Dictionary\nDim WS_REG As Worksheet, WS_LOTS As Worksheet, i As Long, k As Long\n\ndictArea.CompareMode = TextCompare\n\nSet WS_REG = Sheets(&quot;REGISTER&quot;)\nSet WS_LOTS = Sheets(&quot;LOTS&quot;)\n\nFor i = 7 To RegisterNoError + Register_Offset\n\ndictArea(WS_REG.Range(&quot;C&quot; &amp; i).value) = i\ndictAreaCode(Sheets(&quot;REF1&quot;).Range(&quot;A&quot; &amp; i - 6).value) = i\nWith WS_REG\n For k = 0 To dictArea.Count - 1\n If .Range(&quot;C&quot; &amp; i).value = dictArea.Keys(k) Then .Range(&quot;AA&quot; &amp; i).value = dictAreaCode.Keys(k)\n Next k\n .Range(&quot;AB&quot; &amp; i).value = .Range(&quot;H&quot; &amp; i).value\n .Range(&quot;AC&quot; &amp; i).value = .Range(&quot;V&quot; &amp; i).value\n .Range(&quot;AD&quot; &amp; i).value = .Range(&quot;AA&quot; &amp; i).value &amp; &quot;_&quot; &amp; .Range(&quot;AB&quot; &amp; i).value &amp; &quot;_&quot; &amp; Left(.Range(&quot;AC&quot; &amp; i).value, 1)\n dictLots(.Range(&quot;AD&quot; &amp; i).value) = .Range(&quot;AA&quot; &amp; i).value\nEnd With\n\nNext i\n\nFor i = 0 To dictArea.Count - 1\nWS_LOTS.Range(&quot;E9&quot;).value = 7\nWith WS_LOTS\n.Range(&quot;A&quot; &amp; 9 + i).value = dictArea.Keys(i)\nIf .Range(&quot;A&quot; &amp; 9 + i).value &lt;&gt; &quot;&quot;&quot;&quot; Then .Range(&quot;C&quot; &amp; 9 + i).value = dictAreaCode.Keys(i)\n.Range(&quot;E&quot; &amp; 10 + i).value = dictArea.Items(i) + 1\n.Range(&quot;F&quot; &amp; 9 + i).value = dictArea.Items(i)\n.Range(&quot;D&quot; &amp; 9 + i).value = .Range(&quot;F&quot; &amp; 9 + i) - .Range(&quot;E&quot; &amp; 9 + i) + 1\nEnd With\nNext i\nWS_LOTS.Range(&quot;E&quot; &amp; 9 + dictArea.Count).ClearContents\nWS_LOTS.Range(&quot;A5&quot;) = dictArea.Count\n\nFor i = 0 To dictLots.Count - 1\nWS_LOTS.Range(&quot;G&quot; &amp; 9 + i).value = dictLots.Keys(i)\nWS_LOTS.Range(&quot;Q&quot; &amp; 9 + i).value = dictLots.Keys(i)\nLOTEVAL.Range(&quot;B&quot; &amp; 6 + i).value = dictLots.Keys(i)\nLOTEVAL.Range(&quot;C&quot; &amp; 6 + i).value = dictLots.Items(i)\nFor k = 0 To dictArea.Count - 1\n If LOTEVAL.Range(&quot;C&quot; &amp; 6 + i).value = dictAreaCode.Keys(k) Then LOTEVAL.Range(&quot;D&quot; &amp; 6 + i).value = dictArea.Keys(k)\nNext k\nNext i\n\nWS_LOTS.Range(&quot;E5&quot;) = dictLots.Count\n\nCalculationsOff False\n\nEnd Sub\n\nSub Reset_workbook()\n\nScreenAndAlertsOff True\nUnprotectAll True\n\nDim WS As Worksheet\n\nDim Result As Boolean\nCall OKCancelButton(Result, &quot;This Will Reset All the Fields.&quot; &amp; vbNewLine &amp; &quot;Are You Sure?&quot;)\nIf Result &lt;&gt; True Then GoTo Endline\n\nFor Each WS In ThisWorkbook.Sheets\n If WS.Name Like &quot;AREA_*&quot; Then\n WS.Delete\n ElseIf WS.Name Like &quot;LOT_*&quot; Then\n WS.Delete\n ElseIf WS.Name Like &quot;REGISTER&quot; Then\n WS.Delete\n End If\nNext WS\n\nResetWorkBookValues\n \nActualStep = 0\n \nEndline:\n\nUnprotectAll False\nScreenAndAlertsOff False\n\n\nEnd Sub\n\n</code></pre>\n<p>To complete the above, there are some public declarations and functions from other modules:</p>\n<pre><code>Option Explicit\n\nPublic Const Register_Offset As Long = 6\nPublic Const ErrorLog_Offset As Long = 6\nPublic Const LotsOffset As Long = 12\n\n\n\nPublic Property Get MainWBPath() As String\nMainWBPath = Application.ThisWorkbook.Path &amp; &quot;\\&quot;\nEnd Property\n\nPublic Property Get MainWBname() As String\nMainWBname = ThisWorkbook.Name\nEnd Property\n\nPublic Property Get NumberOfAreas() As String\nNumberOfAreas = WS_CONTROL.Range(&quot;C6&quot;).Value2\nEnd Property\n\nPublic Property Get NumberOfLots() As String\nNumberOfLots = CONTROL.Range(&quot;C7&quot;).Value2\nEnd Property\n\nPublic Property Get ProjectName() As String\nProjectName = Left(CONTROL.Range(&quot;C4&quot;).value, 8) &amp; &quot;_&quot; &amp; (Format(CONTROL.Range(&quot;C5&quot;).value, &quot;yyyy_mm_dd&quot;))\nEnd Property\nPublic Property Get RegisterNoError() As Long\n RegisterNoError = Worksheets(&quot;LOTS&quot;).Range(&quot;C5&quot;).value\nEnd Property\n\nPublic Property Let RegisterNoError(value As Long)\n Worksheets(&quot;LOTS&quot;).Range(&quot;C5&quot;).value = value\nEnd Property\n\nPublic Property Get RegisterNumb() As Long\n RegisterNumb = Worksheets(&quot;LOTS&quot;).Range(&quot;D5&quot;).value\nEnd Property\n\nPublic Property Let RegisterNumb(value As Long)\n Worksheets(&quot;LOTS&quot;).Range(&quot;D5&quot;).value = value\nEnd Property\nPublic Property Get ActualStep() As Long\n ActualStep = Worksheets(&quot;CONTROL&quot;).Range(&quot;O3&quot;).value\nEnd Property\n\nPublic Property Let ActualStep(value As Long)\n Worksheets(&quot;CONTROL&quot;).Range(&quot;O3&quot;).value = value\nEnd Property\n\nPublic Function GetLastCell(Optional ByRef rng As Range = Nothing) As Range\n'Credit to @ZygD\n\n 'Returns the last cell containing a value, or A1 if Worksheet is empty\n\n Const NONEMPTY As String = &quot;*&quot;\n Dim lRow As Range, lCol As Range, GetMaxCell As Range\n\n If rng Is Nothing Then Set rng = Application.ActiveWorkbook.Activesheets.UsedRange\n If WorksheetFunction.CountA(rng) = 0 Then\n Set GetMaxCell = rng.Parent.Cells(1, 1)\n Else\n With rng\n Set lRow = .Cells.Find(What:=NONEMPTY, LookIn:=xlFormulas, _\n After:=.Cells(1, 1), _\n SearchDirection:=xlPrevious, _\n SearchOrder:=xlByRows)\n If Not lRow Is Nothing Then\n Set lCol = .Cells.Find(What:=NONEMPTY, LookIn:=xlFormulas, _\n After:=.Cells(1, 1), _\n SearchDirection:=xlPrevious, _\n SearchOrder:=xlByColumns)\n\n Set GetLastCell = .Parent.Cells(lRow.row, lCol.Column)\n End If\n End With\n End If\nEnd Function\n\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-29T09:32:27.110", "Id": "246163", "ParentId": "246013", "Score": "0" } }, { "body": "<p>The rewritten code (below) is much easier to follow - nicely done!</p>\n<p>Below are some general follow-up comments that you may find useful.</p>\n<ol>\n<li><p>Use a <code>Function</code> when a procedure is required to return a value to the caller. From the code:\n<code>Sub WsExistsAndDelete(ByVal Name As String, ByVal OptionErase As Long, ByRef Result As Boolean)</code>\nThe procedure is expected to modify the input parameter <code>Result</code> with the outcome. And, <code>Result</code> has no meaning until the procedure is called. So, a <code>Function</code> would be preferred here. (e.g, <code>Private Function WsExistsAndDelete(ByVal Name As String, ByVal OptionErase As Long) As Boolean</code>).</p>\n</li>\n<li><p>Procedure versus variable/parameter casing: Typically procedures begin with a capital letter. Variables and parameters begin with a lower case letter. This makes it easier to know what an identifier <em>is</em> as you scan through code.</p>\n</li>\n<li><p>Application Structure: I'm going to assume that this process is launched by a button on a worksheet that is linked to the macro <code>ImportDatabase</code>. This makes the worksheet with the button the user interface (UI) and the macro is the UI's <em>code-behind</em>. Generally, UI code-behind has as little behavior as possible (other than managing UI presentation). Using this analogy, organize the button-click-initiated macros into its own dedicated module (making it your code-behind module). So, <code>Sub ImportDatabase()</code> and <code>Sub Reset_workbook()</code> should be in a module dedicated to handling user interactions. Then organize non-user interaction code into other module(s). This organizes your code into a Presentation tier and an Application tier (Data tier is also common and may be something to consider eventually). This is an important distinction to maintain and manage as your application grows. See comment #6 below for an example.</p>\n</li>\n<li><p>Assign <code>Public</code> or <code>Private</code> visibility to all procedures. Leaving them unassigned defaults to <code>Public</code>. If a <code>Function</code> or <code>Sub</code> is only called from within the module where it is declared, assign it <code>Private</code> visibility. By doing so, when a procedure needs to be made <code>Public</code> because some other module uses it...there is a built-in reminder to consider making it <code>Public</code> and moving the procedure to a module with commonly used code/utilities.</p>\n</li>\n<li><p>Single Responsibility Principle (SRP): <code>WsExistsAndDelete</code> is an example of a procedure that has too many responsibilities. By its name, the word 'and' betrays that it does at least two things. Its responsibilities include: a) detecting that a worksheet exists. b) Deleting the sheet (sometimes) and, c) Interacting with the User - with a return value that terminates the import. Consider breaking <code>WsExistsAndDelete</code> this into two procedures. As a bonus, the <code>OptionErase</code> parameter and comment are no longer needed once the procedure is broken into single responsibilities.</p>\n<pre><code> Private Function IsExistingWorksheet(worksheetName As String) As Boolean\n IsExistingWorksheet = False\n Dim wrkSheet As Worksheet\n For Each wrkSheet In Worksheets\n If wrkSheet.Name = worksheetName Then\n IsExistingWorksheet = True\n Exit Function\n End If\n Next wrkSheet\n End Function\n\n Private Sub DeleteWorksheet(worksheetName As String)\n If IsExistingWorksheet(worksheetName) Then\n Worksheets(worksheetName).Delete\n End If\n End Sub\n</code></pre>\n</li>\n<li><p>The logic flow allows changes to be made (e.g., create files and folders) before all required conditions to import a database have been met. It is preferred, to get all required conditions resolved before executing any code that will create permanent artifacts. Consider organizing the <code>ImportDatabase()</code> macro to have clear Presentation and Application tiers...something like:</p>\n<pre><code> 'Presentation tier\n Sub ImportDatabase()\n Dim createNewProject As Boolean\n createNewProject = False\n\n 'Validate criteria to proceed\n '1. Project has to exist\n '2. &quot;REGISTER&quot; worksheet does not exist\n '3. Valid file is selected by user\n\n ChDir MainWBPath\n\n If Dir(MainWBPath &amp; ProjectName, vbDirectory) = &quot;&quot; Then\n Call OKCancelButton(createNewProject, &quot;Project &quot; &amp; ProjectName &amp; &quot; Does not exist.&quot; &amp; vbNewLine &amp; vbNewLine &amp; &quot;Do You want to Create it?&quot;)\n If createNewProject = False Then\n Exit Sub\n End If\n End If\n\n 'May want this to be the first validation check\n If IsExistingWorksheet(&quot;REGISTER&quot;) Then\n Call OKButton(&quot;Reset before Import. Exiting database import&quot;)\n Exit Sub\n End If\n\n 'Not sure what the user can do here other than click OK...does not appear to have the option of\n 'terminating the import.\n Call OKButton(&quot;Please, be confirm that the DB to import is stored in the REGISTER tab of the file&quot;)\n\n 'Opening the File and copy to my workbook\n Dim fileName As Variant\n fileName = Application.GetOpenFilename(FileFilter:=&quot;Excel Files (*.XLSX), *.XLSX&quot;, Title:=&quot;Select File To Be Opened&quot;)\n If fileName = False Then\n Call OKButton(&quot;File not selected. Exiting database import&quot;)\n Exit Sub\n End If\n\n UnhideAll True\n UnprotectAll True\n ScreenAndAlertsOff True\n\n On Error GoTo ResetFlags\n 'Validation requirements met, flags set...call the Application tier to do the work\n Dim errors As Long\n errors = ImportDatabaseImpl(fileName, createNewProject)\n\n OKButtonBig &quot;Ex DataBase Import Completed&quot; &amp; vbNewLine &amp; vbNewLine _\n &amp; &quot;TOTAL EQUIPMENT IN Ex DATABASE : &quot; &amp; RegisterNumb &amp; vbNewLine _\n &amp; &quot;EQUIPMENT EXCLUDED DUE TO ERROR : &quot; &amp; errors &amp; vbNewLine _\n &amp; &quot;TOTAL EQUIPMENT IMPORTED : &quot; &amp; RegisterNoError &amp; vbNewLine &amp; vbNewLine _\n &amp; &quot;The Equipment with errors have been recorded on the ERRROR_LOG. You can continue discarting those elements or correct them in the originalfile and do the Import again.&quot; &amp; vbNewLine\n\n ResetFlags:\n UnhideAll False\n UnprotectAll False\n ScreenAndAlertsOff False\n CalculationsOff False\n\n End Sub\n</code></pre>\n</li>\n</ol>\n<p>And in another module (Application tier):</p>\n<pre><code> Public Function ImportDatabaseImpl(fileName As Variant, createNewProject As Boolean) As Long\n ImportDatabaseImpl = 0\n\n If createNewProject Then\n Call CreateProjectFolders\n Call SaveStep(0)\n End If\n\n Call ResetWorkBookValues\n \n 'Opening the File and copy to my workbook\n Dim RegisterWorkBook As Workbook, Mainworkbook As Workbook\n Set Mainworkbook = ActiveWorkbook\n Dim t#, TimerReg(1 To 10) As Long\n t = Timer\n Set RegisterWorkBook = Workbooks.Open(fileName:=fileName)\n\n RegisterWorkBook.Sheets(&quot;REGISTER&quot;).Copy After:=Mainworkbook.Sheets(&quot;LOTEVAL&quot;)\n RegisterWorkBook.Close SaveChanges:=False\n\n TimerReg(1) = Timer - t\n\n CalculationsOff True\n\n Dim WS_REG As Worksheet\n Set WS_REG = Sheets(&quot;REGISTER&quot;)\n WS_REG.Unprotect Password:=&quot;lukenandmeia&quot;\n\n 'Change the formulas to Values\n With WS_REG\n .Range(&quot;B1:B12000&quot;).value = .Range(&quot;B1:B12000&quot;).value\n .Range(&quot;V1:V12000&quot;).value = .Range(&quot;V1:V12000&quot;).value\n .Range(&quot;Y1:Y12000&quot;).value = .Range(&quot;Y1:Y12000&quot;).value\n .Range(&quot;G2&quot;).value = .Range(&quot;G2&quot;).value\n .AutoFilterMode = False\n End With\n\n TimerReg(2) = Timer - t\n\n 'RemoveConditional Formating\n Dim RegFirstCell As Range, RegLastCell As Range, RegisterData As Range\n Set RegFirstCell = WS_REG.Range(&quot;A6&quot;)\n Set RegLastCell = GetLastCell(WS_REG.Range(&quot;A1:AH12000&quot;))\n Set RegisterData = WS_REG.Range(RegFirstCell.Address &amp; &quot;:&quot; &amp; RegLastCell.Address)\n\n With WS_REG.Cells\n .FormatConditions.Delete\n .Validation.Delete\n .Hyperlinks.Delete\n End With\n\n Dim RegisterTemp As Long\n RegisterTemp = RegLastCell.Row - Register_Offset\n RegisterNumb = RegisterTemp\n RegisterNoError = RegisterTemp\n\n TimerReg(3) = Timer - t\n\n CalculationsOff False\n\n 'Error Filtering\n RemoveErrors RegisterData\n 'Reorder\n OrderRegisters WS_REG, &quot;C7&quot;, &quot;H7&quot;, &quot;T7&quot;, 7\n\n AssignAreasAndLots 'Area Asignation and calculation of Registers and last Rows\n\n ExportErrorsAndRegisters 'Mirar por si se puede mejorar\n \n ActualStep = 1\n SaveStep 1\n\n CalculationsOff False\n\n ImportDatabaseImpl = Sheets(&quot;LOTS&quot;).Range(&quot;B5&quot;).value\n\n End Function\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-30T18:49:00.077", "Id": "246272", "ParentId": "246013", "Score": "1" } } ]
{ "AcceptedAnswerId": "246034", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T20:07:18.903", "Id": "246013", "Score": "4", "Tags": [ "vba", "excel" ], "Title": "Excel Data Import and Manipulation" }
246013
<p>I have to process raw sql user input with Laravel. I've backed them up as follows:</p> <pre class="lang-php prettyprint-override"><code>$query = DB::table('table_name'); function escapeString($str) { return DB::connection()-&gt;getPdo()-&gt;quote($str); } $column = escapeString($rule['query']['operand']); $value = escapeString($rule['query']['value']); if(in_array($rule['query']['operator'], $query-&gt;operators)) { return $column . ' ' . $rule['query']['operator'] . ' ' . $value; } </code></pre> <p>Is that enough, or can I still be attacked over it?</p> <p>I read:</p> <ul> <li><a href="https://stackoverflow.com/questions/18951057/escape-raw-sql-queries-in-laravel-4">https://stackoverflow.com/questions/18951057/escape-raw-sql-queries-in-laravel-4</a> - recommend it</li> <li><a href="https://www.php.net/manual/de/pdo.quote.php" rel="nofollow noreferrer">https://www.php.net/manual/de/pdo.quote.php</a> - they do not recommend it, but it seems possible</li> </ul> <p>(This question was postet originaly at <a href="https://stackoverflow.com/questions/63091979/is-my-code-protected-against-sql-injection">https://stackoverflow.com/questions/63091979/is-my-code-protected-against-sql-injection</a>, but STA suggest to post this question here again)</p> <p><strong>Update:</strong></p> <p>I figured out, how to use <code>value</code> in variable binding. Also I changed <code>escapeString</code> to</p> <pre class="lang-php prettyprint-override"><code>$column = preg_replace('/[^a-zA-Z_]/', '', $rule['query']['operand']); </code></pre> <p>Thats fine for alle columns names and I am pretty sure that this is safe. This filtering approch ist also used in <a href="https://stackoverflow.com/questions/10080850/using-a-whitelist-on-user-input">https://stackoverflow.com/questions/10080850/using-a-whitelist-on-user-input</a></p>
[]
[ { "body": "<p>The <code>PDO::quote()</code> function is not correct for making column names safe. It's basically a wrapper for the <a href=\"https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_quote\" rel=\"nofollow noreferrer\">QUOTE() function in MySQL</a>:</p>\n<blockquote>\n<p>The string is returned enclosed by single quotation marks and with each instance of backslash (), single quote ('), ASCII NUL, and Control+Z preceded by a backslash. If the argument is NULL, the return value is the word “NULL” without enclosing single quotation marks.</p>\n</blockquote>\n<p>The enclosing single-quote marks make the result usable as a string value in SQL, but you are using it for a column name. So you would end up with:</p>\n<pre><code>'mycolumn' = 'myvalue'\n</code></pre>\n<p>The single quotes make it not act like a column in your expression. The QUOTE() function is for string or date values, not identifiers like column names or table names.</p>\n<p>You posted an update, where you changed to using a bound query parameter for the value, and you used a regular expression replacement function to strip out any non-word characters from the column name.</p>\n<p>But this still risks the column being a <a href=\"https://dev.mysql.com/doc/refman/8.0/en/keywords.html\" rel=\"nofollow noreferrer\">reserved SQL keyword</a>, which will cause errors in your code:</p>\n<pre><code>SELECT = 'myvalue'\n</code></pre>\n<p>To avoid this, the column name should be enclosed in backticks:</p>\n<pre><code>`SELECT` = 'myvalue'\n</code></pre>\n<p>If you enclose the column in backticks, then the column may be a reserved keyword, or it can even have punctuation, whitespace, international characters. Those are legitimate for SQL identifiers, but your escaping function would not allow it.</p>\n<p>You should make sure if the column name contains a literal back-tick, you double it, which will make it act like a literal back-tick in your SQL.</p>\n<pre><code>function quoteIdentifier($str) {\n return '`' . preg_replace('/`/', '``', $str) . '`';\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T14:48:41.617", "Id": "246042", "ParentId": "246015", "Score": "2" } } ]
{ "AcceptedAnswerId": "246042", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T21:28:53.790", "Id": "246015", "Score": "3", "Tags": [ "sql", "pdo", "laravel", "sql-injection" ], "Title": "Does PDO::quote helps me to protect me against sql injection?" }
246015
<p>I have asked <a href="https://stackoverflow.com/questions/63083677/getting-error-on-logoff-the-provided-anti-forgery-token-was-meant-for-a-differe">this</a> question on stackoverflow... here, I am asking for some feedback on the solution that I have implemented.</p> <hr /> <p>I am using ASP.NET MVC default template to logout user:</p> <pre><code>// POST: /Account/LogOff [HttpPost] [ValidateAntiForgeryToken] public ActionResult LogOff() { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie); return RedirectToAction(&quot;index&quot;, &quot;home&quot;); } </code></pre> <p>The above code is part of MVC web template, I have not changed anything. There is a edge case scenario that I get the following error:</p> <blockquote> <p>The provided anti-forgery token was meant for a different claims-based user than the current user</p> </blockquote> <p><strong>How to reproduce the error:</strong></p> <p><em>User1</em> and <em>User2</em> are both using the same computer, they both use Chrome (i.e. share the cookie). <em>User1</em> logs in to <em>my-website.com</em> and does not log out. 10 mins later, <em>Users2</em> uses the same computer, opens a <strong>new</strong> chrome tab and logs in to <em>my-website.com</em>. This would invalidate <em>User1's</em> cookie... 10 min later <em>User1</em> comes back to the computer and opens the <strong>original</strong> tab... <em>User1</em> is unaware that his cookie is no longer valid and the website still shows him as the logged in user (if he refreshes the page, he would notice that <em>User2</em> is logged in, but if he does not refresh the tab, it appears that he is still logged in). Now when <em>User1</em> clicks logout he gets the above error, because his AntiForgeryToken is no longer valid... and he keeps getting the error until he refreshes the page.</p> <p>This is edge case scenario but I have got this error several times, because I have 2 different users using the same computer.</p> <p><strong>My solution</strong></p> <pre><code>// POST: /Account/LogOff [HttpPost] // [ValidateAntiForgeryToken] &lt;-- removed public ActionResult LogOff() { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie); return RedirectToAction(&quot;index&quot;, &quot;home&quot;); } </code></pre> <p>I have decided to remove the validation of anitforgery token from this action method... this way, user can always logoff... I think the worst thing an attacker can do is to logoff a user and I think that should be OK...</p> <p><strong>Other Issues</strong></p> <p>Given the same scenario, when <em>User1</em> comes back to the website, unaware that his token is invalidated, he may perform any other post action and he would get the same <em>Invalid AntiForgery</em> error...</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T07:06:34.843", "Id": "483363", "Score": "1", "body": "Surely each user should have their own login to the computer, if they log into the computer with different users then they won't share the cookies. If it is just an open computer then it's up to the user to ensure they log out of the account properly before leaving the computer, if they log out the cookie gets invalidated." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T22:22:26.840", "Id": "246017", "Score": "2", "Tags": [ "c#", "asp.net-mvc", "asp.net-mvc-5", "asp.net-identity" ], "Title": "Managing invalid cookie when 2 users use the same computer and therefore share the same cookie" }
246017
<p>I have a array-object which should look something like this and is used to create a form</p> <pre><code>const questions = [ { condition_action: &quot;selected&quot;, label: &quot;What is your name?&quot;, question_type: &quot;free_text&quot;, required: true, }, { condition_action: &quot;selected&quot;, label: &quot;Where do you live?&quot;, question_options: [ { label: &quot;India&quot;, }, { label: &quot;china&quot;, }, { label: &quot;japan&quot;, }, ], question_type: &quot;single_answer&quot;, required: false, }, ]; </code></pre> <p>Now, When user is done creating the form, I have to validate the data and add a key name <code>order</code> in the above snippet (more below) to array-object (main array and question_options)</p> <p>For validation, There are two conditions</p> <ol> <li>Main array-object should have a label (if not throw error).</li> <li>Question option should have at-least 1 item and the label inside it can't be empty</li> </ol> <p>Basically, question_options is for multiple-select and single select drop down. So question_option should only contain value if <code>question_type</code> key in the above snippet is <code>single_answer</code> or <code>multiple_answer</code></p> <p>The backend api also require attribute <code>order</code> on the main question array and question_options array (yeah even though it's an array we could determine the order through index)</p> <p>So this is the code I wrote</p> <pre><code> const validateAndFormatdata = (questions) =&gt; { // we will change this to true if error exist and send it at return of this function let errorsExsist = false // we are formating data here, if error exist while validation, we change flag const formatedData = (questions || []).map((question, index) =&gt; { // delete all previous errors since we are iterating and we don't care about our previous errors if (Object.prototype.hasOwnProperty.call(question, &quot;errors&quot;)) { delete question.errors } // There can be more than one thing wrong, hence using an array const newErrors = [] // if label does not have value, add it it in errors array if (question.label === &quot;&quot;) { newErrors.push(errorReasons.missingLabel) } if ( question.question_type === &quot;multiple_answer&quot; || question.question_type === &quot;single_answer&quot; ) { const questionOptions = _.filter(question.question_options, &quot;label&quot;).map( (option, position) =&gt; { return { ...option, order: position } } ) // if question optiond does not have single item, add it it in errors array if (questionOptions.length &lt; 1) { newErrors.push(errorReasons.noOption) } else { question.question_options = [...questionOptions] } } else if (Object.prototype.hasOwnProperty.call(question, &quot;question_options&quot;)) { // remove question otpions of question type isn't single or mult-text delete question.question_options } if (newErrors.length &gt; 0) { errorsExsist = true question.errors = newErrors } return { ...question, order: index } }) return { errorsExsist, data: formatedData } } </code></pre> <p><strong>Question:</strong> I was wondering if someone can share review, optimisation and suggestions (including naming)?</p>
[]
[ { "body": "<p>I have made some changes and added comments for each change.</p>\n<pre class=\"lang-js prettyprint-override\"><code>// add the default array here ------------↓ \nconst validateAndFormatdata = (questions = []) =&gt; {\n let errorsExist = false, // &lt;- typo in exist\n // in case you want to add new types\n optionTypes = new Set([&quot;multiple_answer&quot;, &quot;single_answer&quot;]);\n \n // no need to check for || [] because default is added\n // remove the errors property here itself by using destructuring\n const formattedData = questions.map(({ errors, question_options, ...question }, index) =&gt; {\n // because of the destructuring, question is a new object.\n // So, will not mutate the original object\n question.order = index;\n\n const newErrors = []\n \n // checks if label exists and if it is an empty string\n if (!question.label) {\n newErrors.push(errorReasons.missingLabel)\n }\n \n if (optionTypes.has(question.question_type)) {\n const questionOptions = question_options\n .filter(q =&gt; q.label)\n .map((option, order) =&gt; ({ ...option, order }));\n \n // === 0 is much more clearer to read\n if (questionOptions.length === 0) {\n newErrors.push(errorReasons.noOption)\n } else {\n // no need for [...]. It's a new array\n question.question_options = questionOptions\n }\n }\n // no need for delete question.question_options because it is destructured\n\n if (newErrors.length &gt; 0) {\n errorsExist = true\n question.errors = newErrors\n }\n\n return question;\n })\n \n return {\n errorsExist,\n data: formattedData\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T13:27:20.180", "Id": "246035", "ParentId": "246018", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-25T23:51:56.347", "Id": "246018", "Score": "3", "Tags": [ "javascript" ], "Title": "Validating json data for dynamic form" }
246018
<p>I have the following Java 8+ code (on Java 14). I have a (terminal) <code>forEach</code> call and I am adding each mapped object to a newly created <code>ArrayList</code>.</p> <p>Is there a more idiomatic way this could be rewritten using <code>Collectors.toList()</code> and potentially <code>flatMap</code>?</p> <pre><code>public List&lt;SearchSuggestion&gt; suggest() { List&lt;Watchlist&gt; watchlists = someService.findAll(); List&lt;SearchSuggestion&gt; suggestions = new ArrayList&lt;&gt;(); watchlists.forEach(watchlist -&gt; watchlist.getWatchlistItems() .forEach(watchlistItem -&gt; { suggestions.add(mapToSearchSuggestion(watchlistItem.getInstrument())); }) ); return suggestions; } private SearchSuggestion mapToSearchSuggestion(Instrument instrument) { return SearchSuggestion.builder() .symbol(instrument.getSymbol()) .build(); } </code></pre>
[]
[ { "body": "<p>This is one way using <code>flatMap</code> and <code>Collectors.toList()</code>:</p>\n<pre><code>public List&lt;SearchSuggestion&gt; suggest() {\n return someService.findAll().stream()\n .flatMap(wl-&gt;wl.getWatchlistItems().stream())\n .map(wli-&gt;mapToSearchSuggestion(wli.getInstrument()))\n .collect(Collectors.toList());\n}\n</code></pre>\n<p>However (since this is Code Review) the method <code>mapToSearchSuggestion</code> seems more appropriate to be in the class <code>Instrument</code>. If you can move it there then the function becomes:</p>\n<pre><code>public List&lt;SearchSuggestion&gt; suggest() {\n return watchlists.stream()\n .flatMap(wl -&gt;wl.getWatchlistItems().stream())\n .map(WatchlistItem::getInstrument)\n .map(Instrument::mapToSearchSuggestion)\n .collect(Collectors.toList());\n}\n</code></pre>\n<p><code>Instrument</code> class:</p>\n<pre><code>public class Instrument {\n //...\n public SearchSuggestion mapToSearchSuggestion() {\n return SearchSuggestion.builder().symbol(getSymbol()).build();\n }\n //...\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T13:09:38.573", "Id": "483375", "Score": "2", "body": "Is it possible to maybe simplify the syntax further using `.map(WatchListItem::getInstrument)` in the second example?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T13:57:24.280", "Id": "483378", "Score": "1", "body": "@BusyAnt yes thanks for the hint, I updated it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T17:04:16.920", "Id": "483396", "Score": "0", "body": "Thank you! I will try out the first suggestion. The second part may not apply in my case because I will be adding more logic to that method. I feel like the IDE should have an intention to suggest this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-29T15:37:43.993", "Id": "483678", "Score": "1", "body": "@marc I disagree that the method `mapToSearchSuggestion` should be in `Instrument`.. Does Instrument even need to know about `SearchSuggestion`? I think not. Better to extract to a `Util`/`Converter`/`Builder` type of class" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T07:37:19.277", "Id": "246026", "ParentId": "246020", "Score": "7" } } ]
{ "AcceptedAnswerId": "246026", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T02:34:57.947", "Id": "246020", "Score": "7", "Tags": [ "java" ], "Title": "Using Collectors.toList instead of forEach and a new ArrayList" }
246020
<p>This is my second C program (an improved version of the <a href="https://codereview.stackexchange.com/q/245907/224270">first one</a>). I want to optimize this simulation.</p> <p><strong>Algorithm</strong><br /> The simulation algorithm is:</p> <ol> <li>The system can go from <span class="math-container">\$i\$</span> to <span class="math-container">\$i+1\$</span> with probability <span class="math-container">\$e^{-L\theta(\rho_i)}\$</span>, where <span class="math-container">\$\rho_i=i/L\$</span>, and <span class="math-container">\$\theta(\rho)=\rho(2b-\rho)\$</span>.</li> <li>When system reaches <span class="math-container">\$n=0\$</span>, it is reset to a position based on how much time it spent on some <span class="math-container">\$n&gt;0\$</span>.</li> <li>At the end we are intrested in knowing <span class="math-container">\$\langle\rho\rangle=\sum_{t}\rho_t\$</span>.</li> </ol> <p><strong>Code</strong><br /> Following is the code. I believe this code can be compactified also. I do not understand the norms of the ANSI C standard. Feel free to correct me anywhere.</p> <ol> <li>I also do not understand if I am properly using random numbers or not!.</li> <li>I am limited by the number of Monte-Carlo steps. With my code, I cannot go beyond <code>sweeps &gt; ULONG_MAX</code>. Can this be improved?</li> <li>The program is slower than the equivalent python program I wrote! I tried to learn C so that I can write optimised code! And it seems that I am not successful in that yet. Will learning C++ and write code in that would help?</li> <li>Is <code>&lt;pthread.h&gt;</code> a good library?</li> </ol> <pre><code>/* Monte Carlo Simulation for calculating QSD (or Quasi-Stationary distribution) for the forwarded random walk. complie using &quot;gcc filename.c -lm -lpthread&quot; run using &quot;./a.out 0.5&quot; Author: Kartik Date: July 23 */ #include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; #include&lt;math.h&gt; #include&lt;time.h&gt; #include&lt;limits.h&gt; #include &lt;pthread.h&gt; #define LATTICE_SIZE 10 #define N_SWEEPS 10000000 #define PRECISION 1/1000000. #define CPUs 10 #define RAND (double)rand()/(double)RAND_MAX double rho[LATTICE_SIZE]; double initial; FILE *fp; struct simulation_parameters{ int n; unsigned long long sweep; unsigned long long distribution[LATTICE_SIZE]; double forward_rate[LATTICE_SIZE]; double rho_t, rho_tminus; }; void calculate_forward_rates(double *forward_rate, double b) { int i; double theta; for(i = 0; i &lt; LATTICE_SIZE; i++) { theta = rho[i] * (2 * b - rho[i]); forward_rate[i] = exp(-LATTICE_SIZE * theta); } return; } //Following function activate when the system gets absorbed int activate(unsigned long long *distribution, unsigned long long norm) { int n; double cumsum = 0.0, u_rand = RAND; for(n = 0; cumsum &lt;= u_rand; n++) cumsum += (double)distribution[n]/(double)norm; return n - 1; } double calculate_avg_density(unsigned long long *distribution, unsigned long long norm) { int i; double avg_density = 0.0; for (i=0; i&lt;LATTICE_SIZE; i++) avg_density += (rho[i]*distribution[i])/norm; return avg_density; } void *monte_carlo_sweeps(void *vargp) { int i; double *beta = (double *)vargp; struct simulation_parameters par = {0}; par.n = initial*LATTICE_SIZE-1; calculate_forward_rates(par.forward_rate, *beta); par.rho_t = rho[par.n]; while (fabs(par.rho_t-par.rho_tminus) &gt; PRECISION &amp;&amp; par.sweep &lt; ULONG_MAX) { for(i = 1; i &lt;= N_SWEEPS; i++) { par.distribution[par.n]++; par.sweep++; if (RAND &lt; par.forward_rate[par.n]) { par.n--; if (par.n == -1) par.n = activate(par.distribution, par.sweep); } } par.rho_tminus = par.rho_t; par.rho_t = calculate_avg_density(par.distribution, par.sweep); } fprintf(fp, &quot;%lf\t%lf\t%lf\n&quot;, *beta, initial, par.rho_t); } int main(int argc, char **argv) { int i; double betas[CPUs]; pthread_t id; initial = atof(argv[1]); fp = fopen(&quot;data.dat&quot;, &quot;a&quot;); srand(time(0)); for(i = 0; i &lt; LATTICE_SIZE; i++) rho[i] = (i+1.0)/LATTICE_SIZE; for(i = 0; i &lt; CPUs; i++) betas[i] = (double)i/(double)CPUs; //Creating threads for (i = 0; i &lt; CPUs; i++) pthread_create(&amp;id, NULL, monte_carlo_sweeps, (void *)&amp;betas[i]); pthread_exit(NULL); fclose(fp); return 0; } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T17:49:15.360", "Id": "483399", "Score": "0", "body": "Compacted < compactified < compactificated, I suppose :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-30T12:38:41.167", "Id": "483798", "Score": "0", "body": "`for(n = 0; cumsum <= u_rand; n++) cumsum += (double)distribution[n]/(double)norm;` iterates usually once, rarely twice. If this truly the intended functionality?." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-30T16:29:42.030", "Id": "483842", "Score": "0", "body": "@chux-ReinstateMonica In simulation, particle has visited different sites `n` from `0` to `LATTICE_SIZE-1.` When particle goes to `n=-1,` which is not allowed state, so we activate it back based on its history, i.e., how much time it has visited `n.`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-30T16:30:28.697", "Id": "483843", "Score": "0", "body": "I am from math background, so this is what I intended -- I have box full of balls, and each ball inscribed with some number from `0` to `LATTICE_SIZE -1.` Probability of choosing any ball is equally likely. Now if I pick up ball from a `distribution,` (of number inscribed) then what is probability of it been inscribed with number `i.` I hope the `activate` is doing this. If not, then I am in trouble." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-30T16:34:37.863", "Id": "483844", "Score": "0", "body": "KartikChhajed On review, my concern does not apply. Tip: `for()` loops are best for iterating things `n` times." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-30T16:40:30.327", "Id": "483845", "Score": "0", "body": "@chux-ReinstateMonica Point noted, an equivalent while loop would look much nicer." } ]
[ { "body": "<p>When compiling, always enable the warnings, then fix those warnings. A run of the code through the <code>gcc</code> compiler results in:</p>\n<pre class=\"lang-none prettyprint-override\"><code>gcc -ggdb3 -Wall -Wextra -Wconversion -pedantic -std=gnu11 -c &quot;untitled2.c&quot; -o &quot;untitled2.o&quot; \n\nuntitled2.c: In function ‘calculate_avg_density’:\n\nuntitled2.c:56:31: warning: conversion to ‘double’ from ‘long long unsigned int’ may alter its value [-Wconversion]\n avg_density += (rho[i]*distribution[i])/norm;\n ^\n\nuntitled2.c:56:48: warning: conversion to ‘double’ from ‘long long unsigned int’ may alter its value [-Wconversion]\n avg_density += (rho[i]*distribution[i])/norm;\n ^\n\nuntitled2.c: In function ‘monte_carlo_sweeps’:\n\nuntitled2.c:65:13: warning: conversion to ‘int’ from ‘double’ may alter its value [-Wfloat-conversion]\n par.n = initial*LATTICE_SIZE-1;\n ^~~~~~~\n\nuntitled2.c: In function ‘main’:\n\nuntitled2.c:96:11: warning: conversion to ‘unsigned int’ from ‘time_t {aka long int}’ may alter its value [-Wconversion]\n srand(time(0));\n ^~~~\n\nuntitled2.c:88:14: warning: unused parameter ‘argc’ [-Wunused-parameter]\n int main(int argc, char **argv)\n ^~~~\n\nuntitled2.c: In function ‘monte_carlo_sweeps’:\nuntitled2.c:85:1: warning: control reaches end of non-void function [-Wreturn-type]\n }\n ^\n\nCompilation finished successfully.\n</code></pre>\n<p>The statement: <code>Compilation finished successfully.</code> only means the compiler produced some workaround for each of the warnings. That 'workaround' may (or may not) be what you want.</p>\n<p>regarding:</p>\n<pre><code>initial = atof(argv[1]);\n</code></pre>\n<p>Never access beyond <code>argv[0]</code> without first checking <code>argc</code> to assure the expected command line parameter was actually entered by the user. If the expected number of command line arguments are not found, then output a <code>USAGE</code> message to <code>stderr</code>, similar to:</p>\n<pre><code>fprintf( stderr, &quot;USAGE: %s initialValue\\n&quot;, argv[0] );\nexit( EXIT_FAILURE );\n</code></pre>\n<p>in function: <code>monte_carlo_sweeps()</code></p>\n<p>It is a bad idea to just run off the end of a non-void function and returning from a thread should be exited with:</p>\n<pre><code>pthread_exit( NULL );\n</code></pre>\n<p>Regarding:</p>\n<pre><code>srand(time(0));\n</code></pre>\n<p>This produces a compiler warning. Suggest:</p>\n<pre><code>srand( (unsigned)time( NULL ) );\n</code></pre>\n<p>for ease of readability and understanding:</p>\n<ol>\n<li>insert a blank line around code blocks: <code>for</code> <code>if</code> <code>else</code> <code>while</code> <code>do...while</code> <code>switch</code> <code>case</code> <code>default</code></li>\n<li>insert 2 or 3 blank lines between functions (be consistent)</li>\n<li>insert an appropriate space: inside parens, inside braces, inside brackets, after commas, after semicolons, around C operators</li>\n</ol>\n<p>it is best to not use 'global' variables. Rather define them as 'local' variables within a function (like <code>main()</code> ) and pass pointers to them to sub functions that need them.</p>\n<p>regarding:</p>\n<pre><code>#define RAND (double)rand()/(double)RAND_MAX\n</code></pre>\n<p>it is best to place parens around the whole calculation so when <code>RAND</code> is invoked all the desired order of operations is not lost.</p>\n<p>regarding;</p>\n<pre><code>fp = fopen(&quot;data.dat&quot;, &quot;a&quot;);\n</code></pre>\n<p>always check (!=NULL) the returned value to assure the operation was successful. When not successful (==NULL) then call</p>\n<pre><code>perror( &quot;fopen to append data.dat failed&quot; );\nexit( EXIT_FAILURE );\n</code></pre>\n<p>where <code>exit()</code> and <code>EXIT_FAILURE</code> are exposed via:</p>\n<pre><code>#include &lt;stdlib.h&gt;\n</code></pre>\n<p>regarding;</p>\n<pre><code>pthread_create(&amp;id, NULL, monte_carlo_sweeps, (void *)&amp;betas[i]); \n</code></pre>\n<p>there are going to be <code>CPUs</code> threads, each with a unique <code>thread_t ID</code></p>\n<p>Should always check the returned value to assure the operation was successful. Suggest:</p>\n<pre><code>pthread_t id[ CPUs ];\n</code></pre>\n<p>and</p>\n<pre><code>if( pthread_create(&amp;id[i], NULL, monte_carlo_sweeps, (void *)&amp;betas[i]) != 0 )\n{\n perror( &quot;pthread_create failed&quot; );\n // cleanup then\n exit( EXIT_FAILURE );\n}\n</code></pre>\n<p>at the end of <code>main()</code>, do NOT call:</p>\n<pre><code>pthread_exit( NULL );\n</code></pre>\n<p>when waiting for the threads to complete.</p>\n<p>because there are <code>CPUs</code> threads, do this instead:</p>\n<pre><code>for( int i = 0; i &lt; CPUs; i++ )\n{\n pthread_join( id[i], NULL );\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T19:15:37.973", "Id": "483406", "Score": "0", "body": "There is no requirement whatsoever to call `pthread_exit()` to end a thread. Just `return`ing from the thread entry function is enough. Sure, you should return a value, even if it's just `NULL`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T01:11:08.337", "Id": "483423", "Score": "0", "body": "@G.Sliepen, True, there are other ways to return from a thread function other than `pthread_exit()` However, just running off the end of the function is NOT one of them" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T16:40:01.027", "Id": "246045", "ParentId": "246021", "Score": "2" } }, { "body": "<p><code>for(n = 0; cumsum &lt;= u_rand; n++) cumsum += (double) distribution[n]/(double) norm;</code> is not clear to me that <code>distribution[n]</code> will always use a <code>n</code> in the [0... LATTICE_SIZE-1] range. I suspect, depending on the roundings and sequencing of adding floating point numbers, code may iterate too far and attempt <code>distribution[LATTICE_SIZE]</code> which is bad.</p>\n<p>Best not to risk an out of buffer access due to some rounding - even if <em>mathmatically</em>, the loop limited by <code>cumsum &lt;= u_rand</code> should be a sufficient end condition.</p>\n<pre><code>// for(n = 0; cumsum &lt;= u_rand; n++)\n// cumsum += (double)distribution[n]/(double)norm;\n\nfor(n = 0; n &lt; LATTICE_SIZE; n++) {\n cumsum += (double)distribution[n] / (double)norm;\n if (cumsum &gt; u_rand) {\n break;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-31T06:45:51.080", "Id": "483913", "Score": "0", "body": "I did not got your point. Are you saying that `n` may exceed `LATTICE_SIZE-1` is some cases due to rounding off? I see this could happen in my `for` loop. And your `for` loop takes care of it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-31T14:03:47.980", "Id": "483960", "Score": "1", "body": "@KartikChhajed Yes. The original loop's end condition is a mathematical/floating point one and not strongly tied to `n < LATTICE_SIZE`. I assert that original code could attempt to index beyond the array size. By limiting the index to the valid range, that undefined behavior will not occur. If the algorithm wanted to index beyond the array, that is a problem of the algorithm. OTOH, if it is the FP math that caused an extra interaction, like `for (double x = 0; x < 1.0; x += 1/3.0)` iterating 4 times rather than 3, then that 4th iteration is discardable." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-30T16:54:37.863", "Id": "246261", "ParentId": "246021", "Score": "1" } } ]
{ "AcceptedAnswerId": "246045", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T02:38:50.803", "Id": "246021", "Score": "3", "Tags": [ "performance", "beginner", "c", "multithreading", "pthreads" ], "Title": "Implementing metropolis algorithm in C" }
246021
<p>Hi I'm trying to create a c++ code based node editor (GUI versions to be implemented). Here is how it works, each node has ports which can be of INPUT or OUTPUT (they only connect with each other so INPUT-&gt;OUTPUT or OUTPUT-&gt;INPUT).</p> <p>Here is the code so far:</p> <p>main.cpp</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; #include &quot;addition_node.h&quot; #include &quot;value_node.h&quot; int main() { value_node&lt;double&gt;* number1 = new value_node&lt;double&gt;(new double(8.0)); value_node&lt;double&gt;* number2 = new value_node&lt;double&gt;(new double(9.0)); value_node&lt;double&gt;* number3 = new value_node&lt;double&gt;(new double(10.0)); addition_node&lt;double&gt;* add1 = new addition_node&lt;double&gt;(); addition_node&lt;double&gt;* add2 = new addition_node&lt;double&gt;(); addition_node&lt;double&gt;* add3 = new addition_node&lt;double&gt;(); number1-&gt;out-&gt;connect_to(add1-&gt;in1); number2-&gt;out-&gt;connect_to(add1-&gt;in2); //std::cout &lt;&lt; number1-&gt;out-&gt;disconnect_from(add1-&gt;inputs[0]) &lt;&lt; std::endl; add1-&gt;out-&gt;connect_to(add2-&gt;in1); number2-&gt;out-&gt;connect_to(add2-&gt;in2); add2-&gt;out-&gt;connect_to(add3-&gt;in1); number3-&gt;out-&gt;connect_to(add3-&gt;in2); //number1-&gt;out-&gt;disconnect_from(add1-&gt;in1); std::cout &lt;&lt; *add3-&gt;out-&gt;value &lt;&lt; std::endl; } </code></pre> <p>node_editor.h:</p> <pre class="lang-cpp prettyprint-override"><code>#pragma once #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;memory.h&gt; #include &lt;typeinfo&gt; enum iotype { INPUT = true, OUTPUT = false }; struct node; struct port_abstract { node* parent = nullptr; std::vector&lt;port_abstract*&gt; connections = {}; iotype io = INPUT; virtual bool connect_to(port_abstract* p); virtual bool disconnect_from(port_abstract* p); virtual void make_empty(); virtual bool is_empty(); virtual void give_value_to(port_abstract* p); }; template &lt;class T&gt; struct port : port_abstract { T* value; virtual bool connect_to(port_abstract* p); virtual bool disconnect_from(port_abstract* p); virtual void make_empty(); virtual bool is_empty(); virtual void give_value_to(port_abstract* p); }; struct node { std::vector&lt;port_abstract*&gt; inputs, outputs; virtual void compute() {}; }; bool is_valid_port(port_abstract* p) { return p != nullptr &amp;&amp; p-&gt;parent != nullptr; } void nested_compute(port_abstract* p) { if (is_valid_port(p)) { p-&gt;parent-&gt;compute(); for (port_abstract* output : p-&gt;parent-&gt;outputs) { for (port_abstract* input : output-&gt;connections) { if (p-&gt;is_empty()) { input-&gt;make_empty(); } else { output-&gt;give_value_to(input); } nested_compute(input); } } } } bool connection_check(port_abstract* p1, port_abstract* p2) { if (is_valid_port(p1) &amp;&amp; is_valid_port(p2)) { if (p1-&gt;io == (!p2-&gt;io)) { std::vector&lt;port_abstract*&gt; ports = {}; (p1-&gt;io ? ports = p2-&gt;parent-&gt;inputs : ports = p2-&gt;parent-&gt;outputs); for (port_abstract* p : ports) { for (port_abstract* c : p-&gt;connections) { if (c-&gt;parent == p1-&gt;parent) { return false; } if (!connection_check(p1, c)) { return false; } } } return true; } return false; } return false; } bool port_abstract::connect_to(port_abstract* p) { if (is_valid_port(p)) { if ( p-&gt;io == (!io) &amp;&amp; (p-&gt;connections.size() != (p-&gt;io ? 1 : -1)) &amp;&amp; (connections.size() != (io ? 1 : -1)) &amp;&amp; connection_check(this, p) ) { connections.push_back(p); p-&gt;connections.push_back(this); (p-&gt;io ? nested_compute(p) : nested_compute(this)); return true; } return false; } return false; } bool port_abstract::disconnect_from(port_abstract* p) { if (is_valid_port(p)) { size_t original_length = connections.size(); connections.erase(std::remove(connections.begin(), connections.end(), p), connections.end()); size_t new_length = connections.size(); if (new_length != original_length) { p-&gt;connections.erase(std::remove(p-&gt;connections.begin(), p-&gt;connections.end(), this), p-&gt;connections.end()); (p-&gt;io ? nested_compute(p) : nested_compute(this)); return true; } return false; } return false; } void port_abstract::make_empty() { return; } bool port_abstract::is_empty() { return false; } void port_abstract::give_value_to(port_abstract* p) {} template &lt;class T&gt; bool port&lt;T&gt;::connect_to(port_abstract* p) { port&lt;T&gt;* p1 = dynamic_cast&lt;port&lt;T&gt;*&gt;(p); if (is_valid_port(p)) { if ( p1 != 0 &amp;&amp; p-&gt;io == (!io) &amp;&amp; (p-&gt;connections.size() != (p-&gt;io ? 1 : -1)) &amp;&amp; (connections.size() != (io ? 1 : -1)) &amp;&amp; connection_check(this, p) ) { connections.push_back(p); p-&gt;connections.push_back(this); (p-&gt;io ? ((port&lt;T&gt;*)p)-&gt;value = value : value = ((port&lt;T&gt;*)p)-&gt;value); (p-&gt;io ? nested_compute(p) : nested_compute(this)); return true; } return false; } return false; } template &lt;class T&gt; bool port&lt;T&gt;::disconnect_from(port_abstract* p) { if (is_valid_port(p)) { size_t original_length = connections.size(); connections.erase(std::remove(connections.begin(), connections.end(), p), connections.end()); size_t new_length = connections.size(); if (new_length != original_length) { p-&gt;connections.erase(std::remove(p-&gt;connections.begin(), p-&gt;connections.end(), this), p-&gt;connections.end()); (p-&gt;io ? ((port&lt;T&gt;*)p)-&gt;value = nullptr : value = nullptr); (p-&gt;io ? nested_compute(p) : nested_compute(this)); return true; } return false; } return false; } template &lt;class T&gt; void port&lt;T&gt;::make_empty() { if (value) { value = nullptr; return; } return; } template &lt;class T&gt; bool port&lt;T&gt;::is_empty() { return value == nullptr; } template &lt;class T&gt; void port&lt;T&gt;::give_value_to(port_abstract* p) { if (is_valid_port(p)) { port&lt;T&gt;* p1 = dynamic_cast&lt;port&lt;T&gt;*&gt;(p); if (p1 != 0) { ((port&lt;T&gt;*)p)-&gt;value = value; } } } </code></pre> <p>value_node.h:</p> <pre class="lang-cpp prettyprint-override"><code>#pragma once #include &quot;node_editor.h&quot; template &lt;class T&gt; struct value_node : node { port&lt;T&gt;* out = nullptr; value_node(); value_node(T* value); virtual void compute(); }; template&lt;class T&gt; value_node&lt;T&gt;::value_node() { out = new port&lt;T&gt;(); out-&gt;io = OUTPUT; out-&gt;parent = this; *out-&gt;value = 0; this-&gt;outputs.push_back(out); } template&lt;class T&gt; value_node&lt;T&gt;::value_node(T* value) { out = new port&lt;T&gt;(); out-&gt;io = OUTPUT; out-&gt;parent = this; out-&gt;value = value; this-&gt;outputs.push_back(out); } template&lt;class T&gt; void value_node&lt;T&gt;::compute() {} </code></pre> <p>addition_node.h:</p> <pre class="lang-cpp prettyprint-override"><code>#pragma once #include &quot;node_editor.h&quot; template&lt;class T&gt; struct addition_node : node { port&lt;T&gt;* in1; port&lt;T&gt;* in2; port&lt;T&gt;* out; addition_node(); virtual void compute(); }; template&lt;class T&gt; addition_node&lt;T&gt;::addition_node() { in1 = new port&lt;T&gt;(); in2 = new port&lt;T&gt;(); out = new port&lt;T&gt;(); out-&gt;io = OUTPUT; in1-&gt;parent = this; in2-&gt;parent = this; out-&gt;parent = this; this-&gt;inputs.push_back(in1); this-&gt;inputs.push_back(in2); this-&gt;outputs.push_back(out); } template&lt;class T&gt; void addition_node&lt;T&gt;::compute() { std::cout &lt;&lt; &quot;compute&quot; &lt;&lt; std::endl; if (in1 &amp;&amp; in2) { if (in1-&gt;value &amp;&amp; in2-&gt;value) { out-&gt;value = new T; *out-&gt;value = *in1-&gt;value + *in2-&gt;value; return; } } //std::cout &lt;&lt; '0' &lt;&lt; std::endl; out-&gt;value = nullptr; } </code></pre> <p>Any advice is greatly appreciated!</p>
[]
[ { "body": "<p>I just recently wrote a similar bit of code, and I put it through half a dozen iterations before I was finally happy with it. Along the way, I ran into several issues you're probably encountering with this system. I'll talk through some of the pitfalls I ran into and how I dealt with them. Before that, here are some more general modifications I'd suggest...</p>\n<h1>Physical State vs. Logical State</h1>\n<p>Don't expose implementation -- C++ allows for access modifiers for exactly this purpose. For logical abstractions like this, favor classes and keep internal implementation (like pointers to parent and child nodes/ports) private. <strong>PHYSICAL</strong> state shouldn't matter to the user -- the values of your class's internal members. <strong>LOGICAL</strong> state should be accessible and (where applicable) mutable to the user. A connection is a logical abstraction from a set of child-to-parent pointers -- let the user think about the connection, you mess with the pointers.</p>\n<p>Along the same vein, the current design has too much latitude -- writing a check to ensure that two output ports aren't connected should hint to you that you are exposing too much functionality to the client code. If output ports shouldn't be connected together, your code should never allow it to happen.</p>\n<p>As for the node system and its implementation, there are several design choices to be made. First is your choice to tackle this problem with polymorphism -- a natural place to go given that every type of node is-a node. Each node contains a list of inputs and outputs. A drawback to this design choice is that the evaluation algorithm is tightly coupled to the hierarchy itself. A potential alternative would be to have a free function to traverse the hierarchy and evaluate it:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> template &lt;typename T&gt; T evaluate(port&lt;T&gt; port) {\n // ...\n }\n</code></pre>\n<p>This allows slightly more latitude, as the internal node implementation no longer matters as long as the interface the function used to traverse the node graph doesn't change. The decreased coupling means that you could do something like this if you ever needed to:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> template &lt;typename T&gt; std::string asExpression(port&lt;T&gt; port) {\n // Returns the string &quot;(2 * 3) + 2&quot;\n }\n \n template &lt;typename T&gt; T evaluate(port&lt;T&gt; port) {\n // Returns the number 8\n }\n</code></pre>\n<h1>Memory Management</h1>\n<p>Another drawback of using polymorphism is copy semantics. Consider the factory method:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> node&lt;float&gt; getSomeUsefulFunction() {\n // ...\n }\n\n</code></pre>\n<p>How is this function implemented? If we create several node instances on the stack, point them at each other and return the root, its parent nodes go out of scope and we get an access violation trying to evaluate the result. Do we allocate heap memory for those nodes? Who deletes them? How do you decide which ones to delete? If a node has the same parent for two inputs, a naive algorithm could accidentally delete an object twice. Even if you decide who owns what and who deletes what, you'd still have problems if you ever wanted to copy-construct the whole hierarchy. You don't know the type of each node, so you can't simply copy-construct them. The typical solution to this dilemma is often known as the prototype pattern -- each node must implement a virtual <code>clone</code> method returning a <code>node</code> instance of the same type and with identical fields. Here again you run into memory management issues -- how do you allocate and manage memory you create within <code>clone()</code>?</p>\n<p>You could try to use shared memory by only using shared pointers to these structures, or specifically enforcing it by making node structures work like shared pointers to an internal implementation. However, with this method, we no longer have a zero-cost abstraction -- we're using garbage collection. More importantly, though, does this choice properly reflect the intent of your program -- are the nodes supposed to have shared ownership? It might be a better idea to create a class to represent a node graph and force nodes to be created as part of a node graph. This way ownership is clear and undisputed. This means that the factory from earlier could be modified like this:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> node_graph&lt;float&gt; getSomeUsefulFunction() {\n node_graph&lt;float&gt; graph;\n node&lt;float&gt;&amp; n = // note the return by reference -- the memory is acquired\n // and initialized by the node_graph and you get a handle\n graph.add_node();\n // ...\n return graph; // Copy constructor implementation here is critical\n }\n</code></pre>\n<p>At this point, you could even reference input/output nodes simply by their index within the node_graph's internal node container (although this quickly creates a problem for insertion or removal of nodes -- but it makes copying the structure much easier).</p>\n<p>This brings me to the non-polymorphic <code>node</code> class. Instead of making a subclass for every different function, you could add a separate field, possibly an <code>enum</code>, to track the node's function. In other words, replace <code>addition_node</code>, <code>multiplication_node</code>, etc. with <code>node(func::add)</code>, <code>node(func::multiply)</code>, etc. It might look like this:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> enum class node_func { add, subtract, value };\n \n template &lt;typename T&gt; class node {\n public:\n node_func func;\n T value;\n }\n\n template &lt;typename T&gt; T evaluate(node&lt;T&gt; n) {\n switch (n.func) {\n case node_func::value:\n return n.value;\n case node_func::add:\n return evaluate(*n.input[0]) + evaluate(*n.input[1]);\n // etc.\n }\n }\n</code></pre>\n<p>As long as your node_graph's copy and move constructors are properly implemented, you won't have problems with access violations because all the nodes used in the graph come with it in the copy/move. You won't have problems with deleting because the graph can simply delete all of its nodes when it goes out of scope with the assurance that nothing else should be referencing the nodes within that system.</p>\n<p>The biggest drawback for this design lies within the copy/move functionality. Because the nodes would all contain pointers to nodes memory-managed by their parent node_graph, the node_graph would need to take special care to make sure all of these pointers are valid. A possible algorithm might look something like this:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> node_graph::node_graph(const node_graph&amp; other) {\n m_nodes = other.m_nodes;\n for (node&amp; n : m_nodes) {\n // for each pointer, get the index in 'other' of the node it points to\n // set that pointer to point at our own node at that index\n }\n }\n</code></pre>\n<h1>Recursion</h1>\n<p>One final consideration is recursion -- what happens when you connect a node's output to a node that eventually drives it? Your evaluation code will go on forever. Note that with the free-function design I proposed earlier, your code wouldn't necessarily ever encounter a problem with recursion -- for example, if you used the system to represent a set of logic gates and you wanted to simulate signals propagating through, recursion would be a common occurrence. Your evaluation function could then simply use only the current input values to advance the simulation instead of recursing all the way down the hierarchy into an infinite loop. Thus, recursion within a node graph system is not inherently evil. That said, you're still best off adding a function to traverse the hierarchy and detect loops. That way, when a recursive setup would result in an infinite evaluation, you can handle the case before you attempt to evaluate.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-03T15:59:55.917", "Id": "484279", "Score": "3", "body": "Welcome to Code Review. Very nice in depth review." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-03T15:41:40.133", "Id": "247442", "ParentId": "246022", "Score": "5" } } ]
{ "AcceptedAnswerId": "247442", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T02:46:03.980", "Id": "246022", "Score": "3", "Tags": [ "c++" ], "Title": "Is this a good code based node editor \"framework\"?" }
246022
<p>I recently posted <a href="https://codereview.stackexchange.com/questions/245945/super-compact-bresenhams-line-algorithm-variant">here</a> about an implementation of the Besenham's line algorithm that I wrote. I've been hard at work improving it and redoing it from the ground up. However I still can't seem to beat BLA--not sure if I'm testing wrong or if it's something else.</p> <pre><code>void bresenprecalc(int x1, int y1, int x2, int y2) { // Initialization, x,y directions and horz/vert line length. int dx = x2 - x1, dy = y2 - y1, dxA = sign(dx), dyA = sign(dy), dxB = abs(dx), dyB = abs(dy), // Set case 1 by default (dyB &gt;= dxB). xm=0, ym=dyA, yxm=dxB, xym=dyB; // Set case 1 if dxB &gt;= dyB. if (dxB &gt;= dyB) { xm = dxA; ym = 0; yxm = dyB; xym = dxB; } // Incremental error check (see Bresenhams algorithm). int er2 = yxm - xym, er = yxm - (xym&gt;&gt;1); // draw x1,y1 (starting pixel). // End when x1 OR y1 reach EOL (faster than AND). for(;x1!=x2 || y1!=y2;) { // Error check above/below the line. if (er &gt;= 0) { // If we've crossed the line, adjust the pixel diagonally. x1 += dxA; y1 += dyA; er += er2; } else { // Move in primary vertical/horizontal direction of the line. x1 += xm; y1 += ym; er += yxm; } // draw x1,y1 (line pixel). } }; </code></pre> <p>Without Comments:</p> <pre><code>void bresenprecalc(int x1, int y1, int x2, int y2) { int dx = x2 - x1, dy = y2 - y1, dxA = sign(dx), dyA = sign(dy), dxB = abs(dx), dyB = abs(dy), xm=0, ym=dyA, yxm=dxB, xym=dyB; if (dxB &gt;= dyB) { xm = dxA; ym = 0; yxm = dyB; xym = dxB; } int er2 = yxm - xym, er = yxm - (xym&gt;&gt;1); // draw x1,y1 (starting pixel). for(;x1!=x2 || y1!=y2;) { if (er &gt;= 0) { x1 += dxA; y1 += dyA; er += er2; } else { x1 += xm; y1 += ym; er += yxm; } // draw x1,y1 (line pixel). } }; </code></pre> <p>I honestly think I've squeezed everything out of this implementation. I'm out of ideas.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T08:21:06.903", "Id": "483364", "Score": "0", "body": "I made a quick change on the loop itself to use an OR check. Seems to be quicker." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-01T06:15:36.920", "Id": "484024", "Score": "0", "body": "Bump. Anyone have any solutions to this?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T07:26:42.373", "Id": "246025", "Score": "2", "Tags": [ "c++", "performance", "algorithm", "graphics" ], "Title": "Super Compact Bresenham's Line Algorithm v2" }
246025
<p>I've recently been learned how to implement a token based authentication with ASP.NET and I would love to get some input on how my code &amp; structure is as well as how I can make it better.</p> <p>The code I'd like to share consists of the ASP.NET web API controller, and the client Xamarin application.</p> <p>One question I have been having is am I taking the proper approach with refreshing the token every time the app is launched (and the user has already entered their credentials prior?)</p> <p>Web API Controller:</p> <pre><code> [HttpPost(&quot;token&quot;)] [AllowAnonymous] public async Task&lt;IActionResult&gt; GenerateToken([FromForm]LoginModel model) { var user = await _userManager.FindByNameAsync(model.Username); if (user != null &amp;&amp; await _userManager.CheckPasswordAsync(user, model.Password)) { var token = _identityService.GenerateToken(user); string tokenText = new JwtSecurityTokenHandler().WriteToken(token); var refreshToken = _identityService.GenerateRefreshToken(); user.RefreshToken = refreshToken; _context.Update(user); _context.SaveChanges(); string expirationString = token.Claims.Single(x =&gt; x.Type == &quot;exp&quot;).Value; DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(long.Parse(expirationString)); return Ok(new { token = tokenText, refreshToken, expiration = dateTimeOffset }); } ModelState.AddModelError(&quot;&quot;, &quot;Your email or password did not match any users. Please verify you have entered the right credentials.&quot;); return Unauthorized(ModelState); } [HttpPost(&quot;RefreshToken&quot;)] public IActionResult RefreshToken([FromForm]string token, [FromForm]string refreshToken) { var principal = _identityService.GetPrincipalFromExpiredToken(token); var username = principal.Identity.Name; var allClaims = principal.Claims.ToList(); var name = allClaims.First(c =&gt; c.Type.Contains(&quot;nameidentifier&quot;)).Value; var user = _context.Users.Single(x =&gt; x.UserName == name); var savedRefreshToken = user.RefreshToken; if (savedRefreshToken != refreshToken) throw new SecurityTokenException(&quot;Invalid refresh token&quot;); var newJwtToken = _identityService.GenerateToken(user); var newRefreshToken = _identityService.GenerateRefreshToken(); user.RefreshToken = newRefreshToken; _context.Update(user); _context.SaveChanges(); string tokenText = new JwtSecurityTokenHandler().WriteToken(newJwtToken); string expirationString = newJwtToken.Claims.Single(x =&gt; x.Type == &quot;exp&quot;).Value; DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(long.Parse(expirationString)); return new ObjectResult(new { token = tokenText, refreshToken = newRefreshToken, expiration = dateTimeOffset }); } </code></pre> <p>Xamarin Client</p> <pre><code>private async void RefreshToken() { // get the saved refresh token string refreshToken = CrossSettings.Current.GetValueOrDefault(&quot;RefreshToken&quot;, &quot;_&quot;); string token = CrossSettings.Current.GetValueOrDefault(&quot;Token&quot;, &quot;_&quot;); // the IDatabaseManager implementation simply makes the HTTP calls var db = TinyIoCContainer.Current.Resolve&lt;IDatabaseManager&gt;(); // returns http result from HTTP call to refresh token controller action var response = await db.RefreshToken(token, refreshToken); if (response.IsSuccessStatusCode) { var contentString = await response.Content.ReadAsStringAsync(); var content = JsonConvert.DeserializeObject&lt;IdentityResponse&gt;(contentString); var newToken = content.Token; var newRefreshToken = content.RefreshToken; db.SetToken(token); CrossSettings.Current.AddOrUpdateValue(&quot;RefreshToken&quot;, newRefreshToken); CrossSettings.Current.AddOrUpdateValue(&quot;Token&quot;, newToken); MainPage = new NavigationPage(new HomeMaster()); isLaunched = true; } else { // the refresh token is invalid MainPage = new LoginPage(); await MainPage.DisplayAlert(&quot;Authentication Error&quot;, &quot;You have been logged out&quot;, &quot;Ok&quot;); } } </code></pre> <p>When the Xamarin app is launched, it will check for an existing token first. If a token is found, the RefreshToken method is called. If not, it brings the user to the login screen.</p>
[]
[ { "body": "<p>It is fine to refresh the token on every app start.</p>\n<p>It will also prevent potential hijacked tokens to be usefull for a longer time, when the token is refreshed everytime the user starts the app and the old token becomes invalid.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-12T11:56:47.440", "Id": "247808", "ParentId": "246027", "Score": "2" } } ]
{ "AcceptedAnswerId": "247808", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T08:40:26.660", "Id": "246027", "Score": "2", "Tags": [ "c#", "authentication", "asp.net-web-api", "xamarin", "asp.net-identity" ], "Title": "ASP.NET Web API Authentication For Xamarin App" }
246027
<p>I have a dataset and I want to search task name inside initialTasks array.</p> <pre><code>const stagesTasks = [ { &quot;dataTestID&quot;: &quot;stage-0&quot;, &quot;headerText&quot;: &quot;Backlog&quot;, &quot;initialTasks&quot;: [&quot;task 1&quot;, &quot;task 2&quot;, &quot;task 3&quot;] }, { &quot;dataTestID&quot;: &quot;stage-1&quot;, &quot;headerText&quot;: &quot;To Do&quot;, &quot;initialTasks&quot;: [&quot;task 4&quot;, &quot;task 5&quot;, &quot;task 6&quot;] }, { &quot;dataTestID&quot;: &quot;stage-2&quot;, &quot;headerText&quot;: &quot;Ongoing&quot;, &quot;initialTasks&quot;: [&quot;task 7&quot;, &quot;task 8&quot;] }, { &quot;dataTestID&quot;: &quot;stage-3&quot;, &quot;headerText&quot;: &quot;Done&quot;, &quot;initialTasks&quot;: [&quot;task 9&quot;] } ] </code></pre> <p>For example if I want to know dataTestID for &quot;task 8&quot;, I have to make two loops. Like below :-</p> <pre><code>getStageName = task =&gt; { for(let record of stagesTasks){ for(let data of record.initialTasks){ if(data === task){ return record } } } return null } </code></pre> <p>Just need your guidance to identify is there any way to avoid two loops?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T09:38:38.860", "Id": "483435", "Score": "1", "body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which is for the title to simply **state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." } ]
[ { "body": "<p>You may use <code>indexOf</code> (<a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf\" rel=\"nofollow noreferrer\">Array.indexOf</a>) to avoid nested looping.</p>\n<pre><code>getStageName = task =&gt; {\n for (let record of stagesTasks) {\n if (-1 === record.initialTasks.indexOf(task))\n continue\n return record\n }\n return null\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-29T13:21:14.227", "Id": "483660", "Score": "0", "body": "`indexOf` loops the array, so this does nothing to avoid the nested looping outside of providing the optimization of an early return if value is found early in the nested `indexOf` search. This could be achieved by `break` command in traditional loop." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T11:44:42.023", "Id": "246031", "ParentId": "246029", "Score": "1" } }, { "body": "<p>You could use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find\" rel=\"nofollow noreferrer\"><code>find</code></a> to get the object which <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes\" rel=\"nofollow noreferrer\"><code>includes</code></a> the given task in its <code>initialTasks</code> array. This also uses 2 loops. But, it returns when the match is found and is less verbose.</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 stagesTasks=[{dataTestID:\"stage-0\",headerText:\"Backlog\",initialTasks:[\"task 1\",\"task 2\",\"task 3\"]},{dataTestID:\"stage-1\",headerText:\"To Do\",initialTasks:[\"task 4\",\"task 5\",\"task 6\"]},{dataTestID:\"stage-2\",headerText:\"Ongoing\",initialTasks:[\"task 7\",\"task 8\"]},{dataTestID:\"stage-3\",headerText:\"Done\",initialTasks:[\"task 9\"]}];\n\nfunction getStageName(task) {\n return stagesTasks.find(s =&gt; s.initialTasks.includes(task))?.dataTestID\n}\n\nconsole.log(getStageName(\"task 2\"))\nconsole.log(getStageName(\"task 7\"))\nconsole.log(getStageName(\"doesn't exist\"))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>If you call this function repeatedly, then you could create a mapper object which maps each task to it's <code>dataTestID</code>. You can just use <code>mapper[task]</code> to obtain the <code>dataTestID</code>. Since you are returning early, I'm assuming the tasks are unique.</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 stagesTasks=[{dataTestID:\"stage-0\",headerText:\"Backlog\",initialTasks:[\"task 1\",\"task 2\",\"task 3\"]},{dataTestID:\"stage-1\",headerText:\"To Do\",initialTasks:[\"task 4\",\"task 5\",\"task 6\"]},{dataTestID:\"stage-2\",headerText:\"Ongoing\",initialTasks:[\"task 7\",\"task 8\"]},{dataTestID:\"stage-3\",headerText:\"Done\",initialTasks:[\"task 9\"]}];\n\nconst mapper = stagesTasks.reduce((acc, o) =&gt; {\n o.initialTasks.forEach(t =&gt; acc[t] = o.dataTestID)\n return acc\n}, {})\n\nfunction getStageName(task) {\n return mapper[task]\n}\n\nconsole.log(getStageName(\"task 2\"))\nconsole.log(getStageName(\"task 7\"))\nconsole.log(getStageName(\"task 9\"))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T12:22:24.903", "Id": "246033", "ParentId": "246029", "Score": "3" } }, { "body": "<p>The reality is that your data structure is forcing you to do nested loops. There is no two ways around doing nested loops unless you change your data structure.</p>\n<p>If you want to change you data structure, you can get this two an <code>O(n)</code> complexity operation from it's current state of <code>O(m x n)</code> (where <code>n</code> is number of stages and <code>m</code> is max number of tasks in any stage).</p>\n<p>The simplest approach might be to <code>initialTasks</code> from an <code>Array</code> to a <code>Set</code>. So something like...</p>\n<pre><code>const stagesTasks = [\n {\n &quot;dataTestID&quot;: &quot;stage-0&quot;,\n &quot;headerText&quot;: &quot;Backlog&quot;,\n &quot;initialTasks&quot;: new Set([&quot;task 1&quot;, &quot;task 2&quot;, &quot;task 3&quot;])\n },\n {\n &quot;dataTestID&quot;: &quot;stage-1&quot;,\n &quot;headerText&quot;: &quot;To Do&quot;,\n &quot;initialTasks&quot;: new Set([&quot;task 4&quot;, &quot;task 5&quot;, &quot;task 6&quot;])\n },\n {\n &quot;dataTestID&quot;: &quot;stage-2&quot;,\n &quot;headerText&quot;: &quot;Ongoing&quot;,\n &quot;initialTasks&quot;: new Set([&quot;task 7&quot;, &quot;task 8&quot;])\n },\n {\n &quot;dataTestID&quot;: &quot;stage-3&quot;,\n &quot;headerText&quot;: &quot;Done&quot;,\n &quot;initialTasks&quot;: new Set([&quot;task 9&quot;])\n }\n];\n\nconst getStageByTask = (task) =&gt; {\n return stagesTasks.find( (stage) =&gt; stage.initialTasks.has(task) ) || null;\n}\n</code></pre>\n<p>A few other thoughts:</p>\n<ul>\n<li>I am guessing that you are fairly new to development and/or javascript, so I would heavily make the recommendation to use <code>;</code> to terminate your lines. In javascript, generally speaking, it is very forgiving about not using line terminators, but there are a few gotchas out there to be aware of in knowing how to write JS without <code>;</code>. I would suggest you use them until you are thoroughly familiar with these cases.</li>\n<li><code>getStageName</code> is probably not a very good name for the function, as you are not just returning a name, but an object. Perhaps <code>getStageByTask</code> or similar?</li>\n<li>Make sure you are using <code>const</code> (in this case), or <code>let</code>`var<code>when declaring your variables. So</code>const getStageName = ...`.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-29T13:27:27.983", "Id": "246175", "ParentId": "246029", "Score": "0" } } ]
{ "AcceptedAnswerId": "246033", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T10:00:36.593", "Id": "246029", "Score": "3", "Tags": [ "javascript", "array" ], "Title": "How to optimize two loop" }
246029
<p>I made a Three Monte Card game using Java</p> <p>Problem:</p> <blockquote> <p>This is the original &quot;ball and cups&quot; game where you try to find out which cup has the ball under it. You may play with three cups and a ball, three cards (two jacks and an ace), or three doors and a car. Basically, randomly select a cup to hide the &quot;ball&quot;. Let the player guess which cup hides the ball. The player wins if they guess correctly.</p> </blockquote> <p>Problem taken from:</p> <blockquote> <p>https://programmingbydoing.com/a/three-card-monte.html</p> </blockquote> <p>My code:</p> <pre><code>/* * Code by CLint */ import java.util.Random; import java.util.Scanner; public class ThreeCardMonte { public static void main(String[] args) { Random random = new Random(); Scanner input = new Scanner(System.in); int userInput; int randomN = random.nextInt(3)+1; System.out.println(&quot;You slide up to Fast Eddie's card table and plop down your cash.\n&quot; + &quot;He glances at you out of the corner of his eye and starts shuffling.\n&quot; + &quot;He lays down three cards.\n&quot;); System.out.println(&quot;Which one is the ace?\n&quot; + &quot;\t##\t##\t##\n&quot; + &quot;\t##\t##\t##\n&quot; + &quot;\t1\t2\t3&quot;); System.out.print(&quot;\n&gt; &quot;); userInput = input.nextInt(); if (userInput == randomN) { if (randomN == 1) { System.out.println(&quot;\nYou nailed it! Fast Eddie reluctantly hands over your winnings, scowling.\n&quot; + &quot;\tAA\t##\t##\n&quot; + &quot;\tAA\t##\t##\n&quot; + &quot;\t1\t2\t3&quot;); } else if (randomN == 2) { System.out.println(&quot;\nYou nailed it! Fast Eddie reluctantly hands over your winnings, scowling.\n&quot; + &quot;\t##\tAA\t##\n&quot; + &quot;\t##\tAA\t##\n&quot; + &quot;\t1\t2\t3&quot;); } else if (randomN == 3) { System.out.println(&quot;\nYou nailed it! Fast Eddie reluctantly hands over your winnings, scowling.\n&quot; + &quot;\t##\t##\tAA\n&quot; + &quot;\t##\t##\tAA\n&quot; + &quot;\t1\t2\t3&quot;); } } if (userInput != randomN) { if (randomN == 1) { System.out.println(&quot;\nHa! Fast Eddie wins again! The ace was card number 1.\n&quot; + &quot;\tAA\t##\t##\n&quot; + &quot;\tAA\t##\t##\n&quot; + &quot;\t1\t2\t3&quot;); } else if (randomN == 2) { System.out.println(&quot;\nHa! Fast Eddie wins again! The ace was card number 2.\n&quot; + &quot;\t##\tAA\t##\n&quot; + &quot;\t##\tAA\t##\n&quot; + &quot;\t1\t2\t3&quot;); } else if (randomN == 3) { System.out.println(&quot;\nHa! Fast Eddie wins again! The ace was card number 3.\n&quot; + &quot;\t##\t##\tAA\n&quot; + &quot;\t##\t##\tAA\n&quot; + &quot;\t1\t2\t3&quot;); } } } } </code></pre> <p>The output:</p> <blockquote> <p><a href="https://i.stack.imgur.com/awK05.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/awK05.png" alt="Code Output" /></a></p> </blockquote> <p>PS: I am open for corrections to make my code for efficient and clean.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T04:49:46.487", "Id": "483426", "Score": "0", "body": "there is not much left for efficency since this program flow is linear." } ]
[ { "body": "<h2><a href=\"https://clean-code-developer.com/grades/grade-2-orange/#Single_Responsibility_Principle_SRP\" rel=\"nofollow noreferrer\">single responsibility</a></h2>\n<p>your class does all things together</p>\n<ul>\n<li>reading user input</li>\n<li>printing dialogs</li>\n<li>handle game logic</li>\n</ul>\n<p>by this you violate the <a href=\"https://clean-code-developer.com/grades/grade-4-green/#Open_Closed_Principle\" rel=\"nofollow noreferrer\">openClosed principle</a>. If you want to change your code (eg. play a one of <strong>four</strong> game) you have to make a lot of changes. If you want to add handling for <code>InputExceptions</code> (<a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt()\" rel=\"nofollow noreferrer\">see <code>Scanner.nextInt()</code></a> you would find the proper place. <strong>Make Classes for each responsibility!</strong></p>\n<h2>minor issues</h2>\n<ul>\n<li><a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">magic numbers</a>: <code>(3)+1</code></li>\n<li>hardcoded Strings (put them in a language file) - that also helps to <a href=\"https://clean-code-developer.com/grades/grade-2-orange/#Separation_of_Concerns_SoC\" rel=\"nofollow noreferrer\">separate concerns</a> between dialogs and logic</li>\n<li><a href=\"https://refactoring.guru/smells/duplicate-code\" rel=\"nofollow noreferrer\">redundancy</a> (<strong>use a formatter</strong> for the text from the language files)</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T05:13:22.453", "Id": "246063", "ParentId": "246032", "Score": "4" } }, { "body": "<h1>Constants</h1>\n<p>A couple of constants would make your code easier to adapt. So, for example a constant for the number of cards would allow the potential to adapt the program to 2/4 card play.</p>\n<h1>Variable naming</h1>\n<p>To make the program easier to follow, I favour names that indicate what a variable represents, rather than where it comes from. So, rather than <code>randomN</code>, consider <code>acePosition</code>. Rather than <code>userInput</code>, consider <code>guessedPosition</code>.</p>\n<h1>Duplicated logic</h1>\n<p>When you're doing things that are identical / very similar it's a good indication that there's scope to extract into a function / class. There are two main duplications that you've got, when printing out each of the winning/losing statements with the card positions. These also share printing the end card positions. Consider extracting a method that can output the card positions, with the ace in a given position.</p>\n<h1>If/Else</h1>\n<p>When you've got two if conditions that are exclusive, use if/else, rather than <code>if(userInput == randomN)</code> and <code>if(userInput != randomN)</code></p>\n<h1>Putting it together</h1>\n<p>You might end up with something more like this:</p>\n<pre><code>public class ThreeCardMonte {\n final static int UNKNOWN_POSITION = 0;\n final static int NUMBER_OF_CARDS = 3;\n\n public static String formatCards(int acePosition) {\n var cardValue = IntStream.range(0, NUMBER_OF_CARDS)\n .mapToObj(i -&gt; i + 1 == acePosition ? &quot;\\tAA&quot; : &quot;\\t##&quot;)\n .collect(Collectors.joining()) + &quot;\\n&quot;;\n var columnLabels = IntStream.range(0, NUMBER_OF_CARDS)\n .mapToObj(i-&gt;&quot;\\t&quot;+(i+1))\n .collect(Collectors.joining()) + &quot;\\n&quot;;\n\n return cardValue + cardValue + columnLabels;\n }\n\n public static void main(String[] args) {\n Random random = new Random();\n Scanner input = new Scanner(System.in);\n int acePosition = random.nextInt(NUMBER_OF_CARDS) + 1;\n\n\n System.out.println(&quot;You slide up to Fast Eddie's card table and plop down your cash.\\n&quot; +\n &quot;He glances at you out of the corner of his eye and starts shuffling.\\n&quot; +\n &quot;He lays down three cards.\\n&quot;);\n System.out.println(&quot;Which one is the ace?\\n&quot; + formatCards(UNKNOWN_POSITION));\n System.out.print(&quot;&gt; &quot;);\n int guessedPosition = input.nextInt();\n\n if (guessedPosition == acePosition) {\n System.out.println(&quot;\\nYou nailed it! Fast Eddie reluctantly hands over your winnings, scowling.\\n&quot; +\n formatCards(acePosition));\n } else {\n System.out.format(&quot;\\nHa! Fast Eddie wins again! The ace was card number %d.\\n&quot; +\n formatCards(acePosition), acePosition);\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T11:29:09.897", "Id": "246073", "ParentId": "246032", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T12:13:16.590", "Id": "246032", "Score": "4", "Tags": [ "java", "game", "playing-cards" ], "Title": "Three Card Monte game using Java" }
246032
<p>I'm doing my first big unity project and I'm really unsure about my current code I use for my level generation.</p> <p>I would greatly appreciate any feedback. I'm very new to c# and I'm not at all aware of all of my options with MonoBehaviour and such.</p> <p>On the editor side of unity I have Prefabs that have sprite renderers with unique sprites, a Colors script that can also be found below and optionally an edge collider. I also have a 2100x2100 map of pixels that are assigned a tile according to color in the script.</p> <p>In the Colors script there is at least one color for foreground and optionally colors for background</p> <p>Main Script:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using UnityEngine; public class LevelGenerator : MonoBehaviour { public Player player; // The player script public Texture2D map; // map of the 1-color tiles to be deciphered public GameObject[] gameobjects; // tile gameobjects with sprite renderers, Colors script featuring foreground and backgrounds colors and a bool for constant background. Optionally also an edge collider2D private Vector2Int playerPos; // player's position int private Vector2 _playerPos; // player's position float private const int radius = 8; // radius of generation private Dictionary&lt;GameObject, Pair&gt; prefabs; // prefabs to be populated with gameobjects and their foreground and background colors as pairs private Dictionary&lt;Vector2, List&lt;GameObject&gt;&gt; posDictionary; // Dictionary of all active tile positions in the level private Dictionary&lt;Vector2, List&lt;GameObject&gt;&gt; tilePosDictionary; // Dictionary of all active tile positions in the level private Dictionary&lt;Color, List&lt;KeyValuePair&lt;GameObject, Pair&gt;&gt;&gt; colorDictionary; // Dictionary of all colors and the gameobjects associated with them // Start is called before the first frame update void Start() { prefabs = new Dictionary&lt;GameObject, Pair&gt;(); posDictionary = new Dictionary&lt;Vector2, List&lt;GameObject&gt;&gt;(); tilePosDictionary = new Dictionary&lt;Vector2, List&lt;GameObject&gt;&gt;(); colorDictionary = new Dictionary&lt;Color, List&lt;KeyValuePair&lt;GameObject, Pair&gt;&gt;&gt;(); AssignPrefabs(); // populate prefabs dictionary playerPos = new Vector2Int((int)Mathf.Round(player.transform.position.x), (int)Mathf.Round(player.transform.position.y)) + new Vector2Int(map.width / 2, map.height / 2); // center map to player _playerPos = (Vector2)player.transform.position + new Vector2(map.width / 2, map.height / 2); GenerateLevel(); } private void AssignPrefabs() { foreach (GameObject go in gameobjects) { prefabs.Add(go, new Pair(go.GetComponent&lt;Colors&gt;().colors, go.GetComponent&lt;Colors&gt;().backgrounds)); } } void Update() { _playerPos = (Vector2)player.transform.position + new Vector2(map.width / 2, map.height / 2); float movementDelta = (playerPos - _playerPos).magnitude; if (movementDelta &gt;= 1) { playerPos = new Vector2Int((int)Mathf.Round(player.transform.position.x), (int)Mathf.Round(player.transform.position.y)) + new Vector2Int(map.width / 2, map.height / 2); GenerateLevel(); } } void GenerateLevel() { CheckBounds(); // create bounds around player and remove any additional tiles from level for (int y = playerPos.y - radius; y &lt; playerPos.y + radius; y++) { for (int x = playerPos.x - radius; x &lt; playerPos.x + radius; x++) { if (!Generated(new Vector2(x, y))) { if (tilePosDictionary.ContainsKey(new Vector2(x, y))) // check if it has already been created { foreach (GameObject go in tilePosDictionary[new Vector2(x, y)]) go.SetActive(true); } else GenerateTile(x, y); } } } } private void CheckBounds() { Bounds b = new Bounds(new Vector3(playerPos.x - 0.5f, playerPos.y - 0.5f), new Vector3(radius * 2, radius * 2, 0)); List&lt;Vector2&gt; toDestroy = new List&lt;Vector2&gt;(); foreach (Vector2 pos in posDictionary.Keys) { if (!tilePosDictionary.ContainsKey(pos)) tilePosDictionary.Add(pos, posDictionary[pos]); if (!b.Contains(pos)) { toDestroy.Add(pos); foreach (GameObject prefab in posDictionary[pos]) { prefab.SetActive(false); } } } foreach (Vector2 pos in toDestroy) { posDictionary.Remove(pos); } } bool Generated(Vector2 pos) { if (posDictionary.ContainsKey(pos)) // if it is in current active tiles return true; return false; } void GenerateTile(int x, int y) { Color pixelColor = map.GetPixel(x, y); // store current pixel's color if (pixelColor.a == 0) // skip if transparent return; posDictionary[new Vector2(x, y)] = new List&lt;GameObject&gt;(); KeyValuePair&lt;GameObject, Pair&gt; foreground = new KeyValuePair&lt;GameObject, Pair&gt;(); GameObject background = null; if (colorDictionary.Keys.Contains(pixelColor)) // if it's color has already been encountered { foreach (var prefab in colorDictionary[pixelColor]) // store at least the foreground object { if (foreground.Key == null) { foreground = prefab; } else { background = prefab.Key; } } } if (foreground.Key == null) // if earlier didn't do the trick { colorDictionary[pixelColor] = new List&lt;KeyValuePair&lt;GameObject, Pair&gt;&gt;(); foreach (var prefab in prefabs) { foreach (Color color in prefab.Value.item1) // iterate foreground colors of each prefab { if (color == pixelColor) // if it matches the pixel color { foreground = prefab; } } } foreground.Key.GetComponent&lt;Colors&gt;().constbg = false; // wont set by default so set here } if (foreground.Key != null) // if a foreground object is located { if (background == null) { background = GetBackground(foreground, new Vector2(x, y)); // final attempt to get background } if (colorDictionary[pixelColor].Count == 0) // if there are no elements in the color dictionary for the pixel color { colorDictionary[pixelColor].Add(foreground); // always same foreground for color (...) if (foreground.Key.GetComponent&lt;Colors&gt;().constbg || background == null) // if background is constant such as constbg and null { colorDictionary[pixelColor].Add(new KeyValuePair&lt;GameObject, Pair&gt;(background, null)); } } Vector2 position = new Vector2(x - map.width / 2, y - map.height / 2); // offset to center map to center of scene var tmp = Instantiate(foreground.Key, position, Quaternion.identity, transform); posDictionary[new Vector2(x, y)].Add(tmp); if (background != null) // if there is a background to be instantiated { tmp = Instantiate(background, position, Quaternion.identity, transform); posDictionary[new Vector2(x, y)].Add(tmp); } } } private GameObject GetBackground(KeyValuePair&lt;GameObject, Pair&gt; prefab, Vector2 pos) { // different methods will be added later return CheckAround(pos, prefab); // get the most encountered tile out of possible background colors } private GameObject CheckAround(Vector2 pos, KeyValuePair&lt;GameObject, Pair&gt; prefab) { if (!prefab.Key.GetComponent&lt;Colors&gt;().constbg) // dont attempt again if the background is constant { if (prefab.Value.item2.Length == 0) { prefab.Key.GetComponent&lt;Colors&gt;().constbg = true; return null; } else if (prefab.Value.item2.Length == 1) { prefab.Key.GetComponent&lt;Colors&gt;().constbg = true; // null and single backgrounds will be constant return prefab.Value.item2[0]; } else // if there are multiple possible backgrounds { int[] score = new int[prefab.Value.item2.Length]; for (int i = 0; i &lt; 9; i++) // create a 3x3 excluding middle tile (the current) { if (i == 4) continue; int xi = (i % 3) - 1; int yi = (i / 3) - 1; for (int j = 0; j &lt; prefab.Value.item2.Length; j++) { foreach (Color col in prefab.Value.item2[j].GetComponent&lt;Colors&gt;().colors) { if (col == map.GetPixel((int)pos.x + xi, (int)pos.y + yi)) { score[j]++; } } } } return prefab.Value.item2[Array.IndexOf(score, score.Max())]; // return the tile that was encountered most often } } return null; } } public class Pair // custom mutable Pair class { public Color[] item1; public GameObject[] item2; public Pair(Color[] item1, GameObject[] item2) { this.item1 = item1; this.item2 = item2; } } </code></pre> <p>Colors:</p> <pre><code>using UnityEngine; public class Colors : MonoBehaviour { public Color[] colors; public GameObject[] backgrounds; [HideInInspector] public bool constbg = false; } </code></pre>
[]
[ { "body": "<p>Let's start with <code>Colors</code> class.</p>\n<ul>\n<li>It's not a bad idea to add [<a href=\"https://docs.unity3d.com/ScriptReference/DisallowMultipleComponent.html\" rel=\"nofollow noreferrer\">DisallowMultipleComponent</a>] attribute to a class if you're not planning to add this component multiple times to the same gameobject.</li>\n</ul>\n<hr />\n<ul>\n<li>Public fields are considered a bad practice. They are used in tutorials to keep code as simple as possible only. You should use <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties\" rel=\"nofollow noreferrer\">properties</a> instead. But there is a problem: properties are not displayed in the inspector.</li>\n</ul>\n<p>The solution is to use public properties with private fields:</p>\n<pre><code>[SerializeField] // Attribute to show private field in the inspector.\nprivate List&lt;GameObject&gt; backgrounds;\npublic List&lt;GameObject&gt; Backgrounds =&gt; backgrounds; // Auto-property with get-only access.\n</code></pre>\n<p>To improve the piece of code even more, use property with <code>IEnumerable</code> instead of <code>List</code>: now data is nicely protected inside the object and there is no way to accidentally break the list or modify it from external classes. Usually you want to protect data as much as possible to reduce potential bug count in the future - public fields does not provide such encapsulation.</p>\n<hr />\n<ul>\n<li><code>constbg</code> name is not very descriptive.</li>\n</ul>\n<p>I'd recommend not to be afraid to give long names to variables (although someone might disagree):</p>\n<pre><code>// Property with get and set access and descriptive name\npublic bool IsConstantBackground { get; set; } \n</code></pre>\n<p>The final version could look like this:</p>\n<pre><code>public class Colors : MonoBehaviour\n{\n [SerializeField]\n private List&lt;Color&gt; foregroundColors;\n [SerializeField]\n private List&lt;GameObject&gt; backgrounds;\n\n public bool IsConstantBackground { get; set; }\n public IEnumerable&lt;Color&gt; ForegroundColors =&gt; foregroundColors;\n public IEnumerable&lt;GameObject&gt; Backgrounds =&gt; backgrounds;\n}\n</code></pre>\n<p><code>IReadonlyCollection</code> is another nice immutable wrapper for public collections. Use <code>IEnumerable</code> if you want to get a collection and iterate through it; use <code>IReadonlyCollection</code> when you need access to indexes and <code>Count</code>.</p>\n<p><strong>Warning!</strong> If you're writing performant code inside the <code>Update()</code> which could run hundreds of times per second, you should consider to keep using <code>List</code> instead of abstract wrappers. Immutable wrappers are fantastic when you're writing clean, protected, maintainable code, but they are slightly less performant than <code>List</code> and could <a href=\"https://learn.unity.com/tutorial/fixing-performance-problems\" rel=\"nofollow noreferrer\">generate a little amount of garbage</a>. It's not big deal usually, but inside the <code>Update()</code> it might be crucial when you're targeting low-end devices.</p>\n<hr />\n<p>Now, the <code>Pair</code> class.</p>\n<p>Consider using <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-tuples\" rel=\"nofollow noreferrer\">Tuples</a> instead. They are pretty much the same thing you implemented, build-in into .net, readonly and convenient to use.</p>\n<p>I didn't find in your example the reason to make <code>Pair</code> mutable. Immutable structs are the best data holders for a lot of reasons:</p>\n<ul>\n<li>Hard to break.</li>\n<li>Easy to use.</li>\n<li>More performant than classes.</li>\n<li>Easy to maintain (no need to check all struct's users to find if someone trying to modify the struct).</li>\n</ul>\n<hr />\n<p><code>LevelGenerator</code> class:</p>\n<ul>\n<li>GetComponent is pretty costly function.</li>\n</ul>\n<p>It is better to use it once and store the result inside a variable:</p>\n<pre><code>foreach (GameObject go in gameobjects)\n{\n var colorsHolder = go.GetComponent&lt;Colors&gt;();\n prefabs.Add(go, new Pair(colorsHolder.colors, colorsHolder.backgrounds));\n}\n</code></pre>\n<hr />\n<ul>\n<li><code>LevelGenerator</code>collects some data <strong>and</strong> tracks the player <strong>and</strong> keeps map instantiated only around the player <strong>and</strong> generates tiles.</li>\n</ul>\n<p><a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> states that a class should have only one thing to do. Well, &quot;one thing&quot; is not very accurate term: class can do several actions grouped into one functionality which still considered &quot;a one thing&quot;. Still, I'd try to distribute <code>LevelGenerator</code> functionality into several classes:</p>\n<ul>\n<li>LevelManager - manager that sends commands to other classes to do an actual work.</li>\n<li>TileGenerator - generation functionality.</li>\n<li>PlayerTracker - boundaries detection functionality.</li>\n<li>MapUpdater - receives boundaries and activates/deactivates tiles.</li>\n</ul>\n<p>If classes are kept as small as possible, it is easier to modify or extend existing code. For example, you could implement very complex tile generation inside external class without worry that your <code>LevelGenerator</code> class becomes a nightmare with 1000 lines of code.</p>\n<hr />\n<p>One more thing. <code>MonoBehaviour</code>s are not the only tool for convenient work with data inside the Unity. If you're not familiar with <a href=\"https://docs.unity3d.com/Manual/class-ScriptableObject.html\" rel=\"nofollow noreferrer\">ScriptableObjects</a>, I'm strongly recommend to watch/read some tutorials: they are fantastic tool to work with data.</p>\n<p>In your example you could make <code>Colors</code> class a <code>ScriptableObject</code> instead of <code>MonoBehaviour</code> and track tile prefabs separately or inside it. It's not necessarily a <em>better</em> approach, but definitely an option. It might be more convenient and clean, or might not.</p>\n<p>I'm usually prefer to store data inside <code>ScriptableObject</code>s, not <code>MonoBehaviour</code>s.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-28T14:06:53.683", "Id": "483537", "Score": "1", "body": "Thanks a lot for taking your time checking out my code and writing a very clean and detailed answer. I agree that the LevelGenerator is big and the code could use some more branching. I was mostly just trying to divide to different functions instead of new classes. I will try my best to use more descriptive names. I didn't even know a script could be added multiple times to a gameobject before reading this. I will look into the scriptableobject class and I'll try to learn some more basic c#. Once again thanks for an eye-opening answer" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-28T09:36:57.127", "Id": "246115", "ParentId": "246037", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T13:54:26.753", "Id": "246037", "Score": "5", "Tags": [ "c#", "unity3d" ], "Title": "A level generation script in Unity" }
246037
<p>The function uses the Windows &quot;<a href="https://docs.microsoft.com/en-us/windows/win32/seccng/cng-portal" rel="nofollow noreferrer">Cryptography API: Next Generation</a>&quot; (<code>bcrypt.h</code>)'s <code>BCryptGenRandom</code> function to generate random bytes - one for each character.</p> <p>It returns the number of characters (excluding NUL-terminator) written to the buffer, <code>-1</code> in the case of a bad argument, or <code>-2</code> in the case of an error.</p> <p><strong>Example usage of the function:</strong></p> <pre class="lang-c prettyprint-override"><code>wchar_t str[9]; // 8 chars + NUL rand_alphanum_str(str, sizeof (str)); printf(&quot;8 random alphanumeric characters: %wS\n&quot;, str); </code></pre> <p><strong>Function code:</strong></p> <pre class="lang-c prettyprint-override"><code>int rand_alphanum_str(WCHAR *buffer, size_t buffer_size) { if(!buffer || buffer_size &lt; 2) { return -1; } int chars = buffer_size / sizeof (WCHAR) - 1; // -1 for null terminator // need one random byte per character to be generated unsigned char *rand_bytes = malloc(chars); if(!rand_bytes) { return -2; } // filling rand_bytes buffer if(!NT_SUCCESS(BCryptGenRandom(NULL, rand_bytes, chars, BCRYPT_USE_SYSTEM_PREFERRED_RNG))) { free(rand_bytes); return -2; } for(int i = 0; i &lt; chars; ++i) { // rand_bytes[i] is in range [0, 255]. // need a number in range [0, 61] - as there are 62 alphanumeric // characters // bit-twiddling to attempt to maintain a uniform distribution: // discard 2 least-significant bits - rand_bytes is now in [0, 63] rand_bytes[i] &gt;&gt;= 2; if((rand_bytes[i] &gt;&gt; 5) &amp; 1U) { // if the now most-significant bit is set, rand_bytes[i] &amp;= ~(1UL &lt;&lt; 1); // clear the 2nd least-significant bit // (only cleared if most-significant bit is set so as to avoid // throwing distribution off by having a bit which is never set) } // rand_bytes[i] is now in [0, 61] // of the 62 possible values of rand_bytes[i]: // - [0, 9] represent numeric digits // - [10, 35] represent uppercase letters // - [36, 61] represent lowercase letters // the offset of rand_bytes[i] from the low end of the range it lies in // is added to said range's first ASCII value to give a random character // in that range if(rand_bytes[i] &lt;= 9) { buffer[i] = L'0' + rand_bytes[i]; } else if(rand_bytes[i] &lt;= 35) { // -10 for offset from beginning of numeral range buffer[i] = L'A' + rand_bytes[i] - 10; } else { // -36 for offset from beginning of uppercase range buffer[i] = L'a' + rand_bytes[i] - 36; } } buffer[chars] = L'\0'; free(rand_bytes); return chars; } </code></pre> <p>Thank you!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-28T20:30:41.310", "Id": "483572", "Score": "0", "body": "Nikdaas. why 2 in `buffer_size < 2`?" } ]
[ { "body": "<h1>The output is not uniformly distributed</h1>\n<p>The resulting characters in the output string are not uniformly distributed. In fact, some characters never occur in the output. After shifting a random byte right by two, if the result is larger than or equal to 32, you always clear the second least significant bit. So all values up to 32 are possible, but then it is 32, 33, 36, 37, 40, 41 and so on. And each value <code>&gt;= 32</code> that your algorithm generates is twice as likely as each value <code>&lt; 32</code>.</p>\n<p>The best solution is to first shift the random byte right by two, and then check i it is smaller than 62. If so, use it as it is. Otherwise, generate a new random byte and repeat the process.</p>\n<h1>Avoid allocating an array of random bytes</h1>\n<p>You are allocating an array to store the random bytes in. While it might seem efficient to do this, because you assumed you then only need one call to <code>BCryptGenRandom()</code>, this might be an issue if you want to generate large random strings. Also, if you want to have a proper uniformly distributed output, you might need to generate more random bytes than you originally anticipated.</p>\n<p>Consider having a small array on the stack that you fill with random bytes, and use those to generate the alphanumeric characters. If you used up all the bytes, you fill the array with a new batch of random bytes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T20:10:26.980", "Id": "246049", "ParentId": "246038", "Score": "4" } }, { "body": "<blockquote>\n<p>int rand_alphanum_str(WCHAR *buffer, size_t buffer_size) {</p>\n</blockquote>\n<p><code>buffer_size</code> remains unchanged so it should be a constant.</p>\n<pre><code>if(!buffer || buffer_size &lt; 2) { return -1; }\n</code></pre>\n<p>I'm not sure why the degenerated cases for <code>buffer_size</code> zero and one result in an error. If it is zero then just return <code>0</code> immediately. If it is <code>1</code> continue as normal.</p>\n<pre><code>wchar_t str[9]; // 8 chars + NUL\n...\nint chars = buffer_size / sizeof (WCHAR) - 1; // -1 for null terminator\n</code></pre>\n<p>Sorry, no. This makes it entirely unclear that 8 random characters need to be generated. A programmer would not expect to have to supply <code>9</code> to generate 8 characters. I'd either explicitly specify that the buffer needs to be 1 character bigger than the argument in the documentation to hold NUL, or I'd use a single, NUL-terminated mutable string as parameter (using different characters before the NUL, obviously).</p>\n<pre><code>// need one random byte per character to be generated\n</code></pre>\n<p>Why? I'd use an <strong>alphabet</strong> string as input (remember, <code>const</code>), and then select characters at random from that alphabet.</p>\n<hr />\n<p>You can select a single character by simply asking for a random index in the range <code>[0, size)</code> where <code>size</code> is the size of the alphabet. Most libraries have a function for that (where you simply give the <code>size</code>, not the range). Then you select the character at that position. This makes your random string generator <em>much</em> more flexible and - of course - unbiased. I agree with the other answer that there is probably bias.</p>\n<p>If you want to have it perform better then you can request one number in the range <code>alphabet_size ^ password_size</code>, and then perform <strong>base conversion</strong> using <code>alphabet_size</code> as base.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-14T11:24:56.597", "Id": "247896", "ParentId": "246038", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T14:20:30.070", "Id": "246038", "Score": "3", "Tags": [ "c", "strings", "random", "windows", "bitwise" ], "Title": "Random alphanumeric string generator function (C, Windows, bcrypt.h)" }
246038
<p>The preeminence is to have every method of the formatter return the formatter as a reference. This allows it to add and format text in chain. Such as:</p> <pre><code>ShapeTextFormatter.Create(Shape).AddText(&quot;Hello &quot;).FontSize(16).Bold(True).AddText(&quot;Cruel &quot;).StrikeThrough(msoCTrue).FontSize(6) _ .AddText(&quot;World!&quot;).FontSize(16).Bold(True).StrikeThrough (msoFalse) </code></pre> <p>Note: Formats are applied to the last text block.</p> <p><img src="https://i.stack.imgur.com/tNtRk.png" alt="Hello Cruel World Image" /></p> <p>Overall, I think that it turned out okay. But I did have a few sticky points.</p> <p>In a couple of cases, I had to convert range enum values to their shape counterparts. <code>UnderLineFromRange()</code> had a couple of its values double up. I'm not sure if there is a distinction between them or not.</p> <p>The class has 20 methods and only 2 error handlers. Did I miss any?</p> <p>White-Space, what white-space! Everything is so packed in. It seems like it need more white-space but where to put it? I couldn't think of a spacing pattern that made since.</p> <p>Using <code>.Clear()</code> by itself throws an <code>Invalid Use of Property</code> error.</p> <blockquote> <pre><code>ShapeTextFormatter.Create(wsShapes.Shape1).Clear </code></pre> </blockquote> <p>You will need to use <code>Call</code> if the you use one but not all of the optional parameters. I think <code>Call</code> could be omitted if named parameters are used. I should probably add a big ugly banner warning to the class.</p> <h2>ToDo List</h2> <p>There are always more features that be added. It would be nice to be able to fade text using the Transparency. There are too many text effects to implement. Returning an instance of the the <code>TextFrame2</code> and <code>LastText()</code> would probably make since. I avoided it because I didn't want to break away from the Builder Pattern.</p> <p>Of course naming could almost always be improved.</p> <hr /> <h2>ShapeTextFormatter: Class</h2> <pre><code>Attribute VB_PredeclaredId = True Attribute VB_Exposed = False Option Explicit Private Const InvalidShapeAssingmentErrorNumber As Long = vbObjectError + 513 Private Const InvalidShapeAssingmentErrorDescription As String = &quot;Invalid Shape Assignment. Shape is a Internal Protected Property&quot; Private Const UnderLineOutOfBoundsErrorNumber As Long = InvalidShapeAssingmentErrorNumber + 1 Private Const UnderLineOutOfBoundsDescription As String = &quot;IUnderLine Value is Out of Bounds. Hint: Use UnderLineFromRange for Ranges&quot; Private Const InternalAssignmentPassword = &quot;AllowAssignment&quot; Private Type TMembers LastTextStart As Long ParagraphFormat As ParagraphFormat2 Shape As Shape TextFrame2 As TextFrame2 LineAlignment As MsoParagraphAlignment End Type Private m As TMembers Public Property Get Clear() As ShapeTextFormatter Attribute Clear.VB_Description = &quot;Note: Clear Cannot Be Use by Itself. It Must Be Chained with Another Method&quot; With m.TextFrame2 If .HasText Then .DeleteText .TextRange.Font.Bold = msoFalse .TextRange.ParagraphFormat.Alignment = msoAlignLeft Call FontSize(ActiveSheet.Range(&quot;A1&quot;).Font.Size) Call LineAlignment(msoAlignLeft) End If End With Set Clear = Me End Property Public Property Get Create(ByVal ShapeObject As Shape) As ShapeTextFormatter With New ShapeTextFormatter Set .SetShape(InternalAssignmentPassword) = ShapeObject Set Create = .Self End With End Property Public Property Get Self() As ShapeTextFormatter Set Self = Me End Property Public Property Set SetShape(ByVal Password As String, ByVal Value As Shape) If Not Password = InternalAssignmentPassword Then RaiseInvalidShapeAssingmentError Else With m Set .Shape = Value Set .TextFrame2 = .Shape.TextFrame2 End With End If End Property Public Function AddText(ByVal Text As String, Optional isBold As Boolean, _ Optional Caps As MsoTextCaps = -1, Optional TextAlignment As _ MsoParagraphAlignment = -1) As ShapeTextFormatter Call ApplyCaps(Text, Caps) If Len(Text) &gt; 0 Then m.LastTextStart = m.TextFrame2.TextRange.length Call m.TextFrame2.TextRange.InsertAfter(Text) End If If isBold Then Call Bold(isBold) Set AddText = Me End Function Public Function AppendText(ByVal Text As String, Optional isBold As Boolean, _ Optional Caps As MsoTextCaps = -1, Optional TextAlignment As _ MsoParagraphAlignment = -1) As ShapeTextFormatter Call m.TextFrame2.TextRange.InsertAfter(vbNewLine) Call AddText(Text, isBold, Caps, TextAlignment) Set AppendText = Me End Function Private Sub ApplyCaps(ByRef Text As String, ByRef Caps As MsoTextCaps) Select Case Caps Case MsoTextCaps.msoCapsMixed Text = StrConv(Text, vbProperCase) Case MsoTextCaps.msoNoCaps Text = StrConv(Text, vbLowerCase) Case MsoTextCaps.msoSmallCaps Text = StrConv(Text, vbUpperCase) Case MsoTextCaps.msoAllCaps Text = StrConv(Text, vbUpperCase) End Select End Sub Public Function Bold(ByVal Value As Boolean) As ShapeTextFormatter LastText.Font.Bold = Value Set Bold = Me End Function Public Function DoubleStrikeThrough(ByVal Value As MsoTriState) As ShapeTextFormatter LastText.Font.DoubleStrikeThrough = Value Set DoubleStrikeThrough = Me End Function Public Function FontName(ByVal Value As String) As ShapeTextFormatter LastText.Font.Name = Value Set FontName = Me End Function Public Function FontSize(ByVal Value As Single) As ShapeTextFormatter LastText.Font.Size = Value Set FontSize = Me End Function Public Function ForeColor(ByVal Value As Long) As ShapeTextFormatter LastText.Font.Fill.ForeColor.RGB = Value Set ForeColor = Me End Function Public Function Italic(ByVal Value As MsoTriState) As ShapeTextFormatter LastText.Font.Italic = Value Set Italic = Me End Function Private Function LastText() As TextRange2 If m.TextFrame2.HasText Then Dim length As Long length = m.TextFrame2.TextRange.length - m.LastTextStart Set LastText = m.TextFrame2.TextRange.Characters(m.LastTextStart + 1, length) Else Set LastText = m.TextFrame2.TextRange End If End Function Public Function LineAlignment(ByVal Value As MsoParagraphAlignment) As ShapeTextFormatter Value = Switch(Value = xlLeft, MsoParagraphAlignment.msoAlignLeft, _ Value = xlCenter, MsoParagraphAlignment.msoAlignCenter, _ Value = xlRight, MsoParagraphAlignment.msoAlignRight, _ True, Value) m.LineAlignment = Value If m.TextFrame2.HasText Then LastText.ParagraphFormat.Alignment = Value Set LineAlignment = Me End Function Private Sub RaiseInvalidShapeAssingmentError() Err.Raise Number:=InvalidShapeAssingmentErrorNumber, Description:=InvalidShapeAssingmentErrorDescription End Sub Private Sub RaiseUnderLineOutOfBoundsError() Err.Raise Number:=UnderLineOutOfBoundsErrorNumber, Description:=UnderLineOutOfBoundsDescription End Sub Public Function StrikeThrough(ByVal Value As MsoTriState) As ShapeTextFormatter LastText.Font.StrikeThrough = Value Set StrikeThrough = Me End Function Public Function Underline(ByVal Value As MsoTextUnderlineType) As ShapeTextFormatter On Error GoTo Err_Handler LastText.Font.UnderlineStyle = Value Set Underline = Me Exit Function Err_Handler: RaiseUnderLineOutOfBoundsError End Function Public Function UnderLineFromRange(ByVal Value As XlUnderlineStyle) As ShapeTextFormatter Select Case Value Case XlUnderlineStyle.xlUnderlineStyleDouble, XlUnderlineStyle.xlUnderlineStyleDoubleAccounting Value = MsoTextUnderlineType.msoUnderlineDoubleLine Case XlUnderlineStyle.xlUnderlineStyleNone Value = MsoTextUnderlineType.msoNoUnderline Case XlUnderlineStyle.xlUnderlineStyleSingle, XlUnderlineStyle.xlUnderlineStyleSingleAccounting Value = MsoTextUnderlineType.msoUnderlineSingleLine End Select Set UnderLineFromRange = Underline(Value) End Function </code></pre> <hr /> <h2>wsShapes: Worksheet</h2> <pre><code>Attribute VB_Name = &quot;wsShapes&quot; Attribute VB_PredeclaredId = True Attribute VB_Exposed = True Option Explicit Public Property Get Shape1() As Shape Set Shape1 = Me.Shapes(&quot;Shape1&quot;) End Property Public Property Get ColorRange() As Range Set ColorRange = Me.Range(&quot;A2&quot;).CurrentRegion End Property </code></pre> <h2>Test</h2> <p>I intentionally switched between using <code>Call</code> and not using it, for demonstration purposes.<br /> You will need to use <code>Call</code> if the you use one but not all of the optional parameters. I think <code>Call</code> could be omitted if named parameters are used.</p> <pre><code>Sub Test() Dim ColorRange As Range Set ColorRange = wsShapes.ColorRange With ShapeTextFormatter.Create(wsShapes.Shape1).Clear Dim r As Long AddTextWithFormatsFromCell .Self, ColorRange.Cells(1) For r = 2 To ColorRange.Rows.Count AddTextWithFormatsFromCell .Self, ColorRange.Cells(r, 1), True Call .AddText(vbTab).Underline(msoNoUnderline) Call .StrikeThrough(msoFalse) AddTextWithFormatsFromCell .Self, ColorRange.Cells(r, 2) Next End With End Sub Rem Factory method used to test the ShapeTextFormatter class Sub AddTextWithFormatsFromCell(ByVal Formatter As ShapeTextFormatter, ByRef Cell As Range, Optional ByVal AppendNewLine As Boolean) With Formatter.Create(wsShapes.Shape1) If AppendNewLine Then Call .AppendText(Cell.Text) Else Call .AddText(Cell.Text) End If Call .Bold(Cell.Font.Bold) Call .Italic(Cell.Font.Italic) .FontName Cell.Font.Name .FontSize Cell.Font.Size .ForeColor Cell.Font.Color .LineAlignment Cell.HorizontalAlignment .StrikeThrough Cell.Font.StrikeThrough .UnderLineFromRange Cell.Font.Underline End With End Sub </code></pre> <hr /> <p><img src="https://i.stack.imgur.com/QC50d.png" alt="Demo Output Image" /></p> <p>If you made it this far you deserve an Upvote! I do tend to ramble on.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T14:22:15.380", "Id": "246040", "Score": "6", "Tags": [ "vba", "excel" ], "Title": "Shape Text Formatter Class a Builder Pattern" }
246040
<p>I'm a newbie trying to write my own <code>push()</code> and <code>join()</code>. This isn't very serious, just an exercise.</p> <p>This is what I got so far</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function Errey(...values){ this.name=values } Errey.prototype={ constructor:Errey, //join method myJoin(union = ' '){ let result="" const length = this.name.length for(let i=0; i&lt;length; i++) { i&lt;length-1 ? result += this.name[i] + union: result+=this.name[i] } return result }, //push method myPush(value){ this.name = [...this.name, value] return this.name.length } } //run a few examples const myArray = new Errey("3","blue","1","brown") //we'll mutate myArray anyways using const or let let joined = myArray.myJoin() let a = myArray.myPush("hey") console.log("joined new array: ",joined, "\n\npush-mutated array: ", myArray.name, "\n\npush return value: ", a)</code></pre> </div> </div> </p> <p>I'm aware an object is returned instead of an array. I guess you might help me out there. Should I use factory functions here? I don't know how would I create a prototype for such a thing...</p> <p>Any improvements on the main code you'd suggest?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T05:51:56.343", "Id": "483428", "Score": "0", "body": "Hello, I added the `reinventing-the-wheel` tag to your question." } ]
[ { "body": "<p>first of all you can use the &quot;new&quot; class syntax instead of changing the prototype directly.<br />\nThis is how I would do it:</p>\n<pre><code>class Errey {\n #currentArray;\n\n constructor(...elements) {\n this.#currentArray = elements;\n }\n\n get errey() {\n return this.#currentArray;\n }\n\n push(...elements) {\n const startLength = this.#currentArray.length;\n elements.forEach((curEl, index) =&gt; this.#currentArray[index + startLength] = curEl);\n return this.#currentArray.length;\n }\n\n join(union = &quot; &quot;) {\n return this.#currentArray.reduce((prev, cur) =&gt; prev + union + cur);\n }\n}\n\n//run a few examples\nconst myArray = new Errey(&quot;3&quot;,&quot;blue&quot;,&quot;1&quot;,&quot;brown&quot;)\n\nconsole.log(myArray.join(&quot;, &quot;));\nconsole.log(myArray.push(&quot;Subscribe&quot;, &quot;To&quot;, &quot;Him&quot;));\nconsole.log(myArray.errey);\n</code></pre>\n<p>push:<br />\nthe standard array.prototype.push allows for multiple elements to be added at once, so I allow multiple elements and loop over them using <code>forEach</code>, you could also do <code>[...this.#currentArray, ...elements]</code> (or use <code>Array.prototype.concat()</code>).</p>\n<p>join:<br />\nhere I use reduce to create a join operation. Reduce takes the first 2 elements and applies a function on them (in this case <code>a + union + b</code>), makes them the new first element and repeats that until there is only one element left, our joined erray.</p>\n<p>I also made the internal Array private using the prefixed <code>#</code> and created a getter (<code>get errey()</code>) instead, this way the internal array can only be changed using the push method.</p>\n<p>Using the factory pattern (which I personally prefer):</p>\n<pre><code>const Errey = (...elements) =&gt; {\n \n const push = (...newElements) =&gt; {\n const startLength = elements.length;\n newElements.forEach((curEl, index) =&gt; elements[index + startLength] = curEl);\n return elements.length;\n };\n\n const join = (union = &quot; &quot;) =&gt; elements.reduce((prev, cur) =&gt; prev + union + cur);\n\n const get = () =&gt; elements;\n\n return {\n push,\n join, \n get,\n };\n};\n\nconst myArray = Errey(&quot;3&quot;,&quot;blue&quot;,&quot;1&quot;,&quot;brown&quot;)\n\nconsole.log(myArray.join(&quot;, &quot;));\nconsole.log(myArray.push(&quot;Subscribe&quot;, &quot;To&quot;, &quot;Him&quot;));\nconsole.log(myArray.get());\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T01:55:03.540", "Id": "483424", "Score": "0", "body": "i will take me a couple of days to understand it but will do. thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T02:57:26.573", "Id": "483425", "Score": "0", "body": "@misternobody if you have questions feel free to ask :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-02T21:13:31.077", "Id": "484186", "Score": "0", "body": "Im getting there ! :-)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T00:48:02.307", "Id": "246059", "ParentId": "246054", "Score": "4" } } ]
{ "AcceptedAnswerId": "246059", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T21:16:42.540", "Id": "246054", "Score": "3", "Tags": [ "javascript", "object-oriented", "reinventing-the-wheel" ], "Title": "creating own javascript join and push methods" }
246054
<p>I am new to python and to the StackExchange sites. I made an age calculator but i want to improve it till it's a reliable thing. Can i shorten the code? What can be Done more? Does it need any additions?</p> <p>Thanks in advence.</p> <pre><code>from datetime import datetime print(&quot;A simple program to calculate your age&quot;) print() date = datetime.now() year = int(date.year) month = int(date.month) day = int(date.day) input_year = int(input(&quot;Enter the year you were born: &quot;)) if input_year &lt;= 0 or input_year &gt; 2020: print(&quot;don't you know your birthday??&quot;) exit() input_month = int(input(&quot;Enter the month you were born: &quot;)) if input_month &lt;= 0 or input_month &gt; 12: print(&quot;don't you know your birthday??&quot;) exit() input_day = int(input(&quot;Enter the day you were born: &quot;)) if input_day &lt;= 0 or input_day &gt; 31: print(&quot;don't you know your birthday??&quot;) exit() age_year = year - input_year age_month = month - input_month if age_month &lt; 0: age_year = age_year - 1 age_month = 12 - (input_month - month) age_day = day - input_day if age_day &lt; 0: age_month = age_month - 1 age_day = 31 - (input_day - day) print(&quot;you are &quot; + str(age_year) + &quot; years, &quot; + str(age_month) + &quot; months and &quot; + str(age_day) + &quot; days old.&quot;) </code></pre>
[]
[ { "body": "<ol>\n<li>Use exceptions.</li>\n<li>You are assuming number is entered by the user. What if I enter a character. You need to handle entry other than number and raise an error</li>\n<li>Ask user to enter birth date in format you wanted and then use subtract from today's date. Then convert to years and months. Both dates should be in same format to subtract.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T06:35:53.740", "Id": "246064", "ParentId": "246055", "Score": "3" } }, { "body": "<p>Try using <code>\\n</code> to the end of the <code>print()</code> statement, instead of using multiple statements.</p>\n<p>You also need to think about error handling, what happens if the user enters a blank? or enters an invalid date?</p>\n<p>To get the year, month or day from a date, you should use Python's built in datetime functionality: <code>date.year</code></p>\n<p>Also, when subtracting dates (to find the user's age), instead of figuring out whether the date is negative and subtracting months etc, try using Python's built-in <code>timedelta</code> function: (<a href=\"https://docs.python.org/3.3/library/datetime.html?highlight=datetime#timedelta-objects\" rel=\"nofollow noreferrer\">https://docs.python.org/3.3/library/datetime.html?highlight=datetime#timedelta-objects</a>).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T09:28:51.690", "Id": "246068", "ParentId": "246055", "Score": "2" } }, { "body": "<p>Time deltas in stock Python kind of suck. <code>dateutil</code> will make this easier for you; it has built-in support for total-year, total-month and total-day fields:</p>\n<pre><code>from datetime import date\nfrom dateutil.relativedelta import relativedelta\n\nprint(&quot;A simple program to calculate your age\\n&quot;)\n\nbirth_str = input('Enter the date you were born, in format YYYY-MM-DD: ')\ntry:\n birth = date.fromisoformat(birth_str)\nexcept ValueError:\n print(&quot;Don't you know your birthday?&quot;)\n exit()\n\nage = relativedelta(date.today(), birth)\nprint(f'You are {age.years} years, {age.months} months and {age.days} days old.')\n</code></pre>\n<p>Also note the use of:</p>\n<ul>\n<li>String interpolation (f-strings)</li>\n<li>Parsing a date from user input in one go, rather than as separate fields</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-28T01:08:50.783", "Id": "246105", "ParentId": "246055", "Score": "4" } }, { "body": "<p>Generally, it is often not a good idea to hardcode values. For example, take a look at this piece of code. It won't work correctly from 2021 onwards:</p>\n<pre><code>if input_year &lt;= 0 or input_year &gt; 2020:\n print(&quot;don't you know your birthday??&quot;)\n</code></pre>\n<p>Better do it like this:</p>\n<pre><code>date = datetime.now()\ncurrent_year = int(date.year)\n\nif input_year &lt;= 0 or input_year &gt; current_year:\n print(&quot;don't you know your birthday??&quot;)\n</code></pre>\n<p>This will make your program work in future years without the need to change the value for the current year manually.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-01T14:59:23.803", "Id": "484059", "Score": "0", "body": "Cool suggestion. will try it out!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-28T13:22:59.770", "Id": "246123", "ParentId": "246055", "Score": "4" } }, { "body": "<ol>\n<li>Use exception handling during inputs. You want the user to enter a number each time but it will not always be true. I might enter a blank by mistake. This will make your program to crash.</li>\n</ol>\n<pre><code>try:\n year = int(input('Enter your birth year')\nexcept TypeError:\n print('You have to enter a number')\n # do something\n</code></pre>\n<ol start=\"2\">\n<li><p>Use <code>f-strings</code>. They are faster. <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\">Realpython's guide</a> can be helpful</p>\n</li>\n<li><p>As mentioned by Flursch, it is not a good idea to hardcode values. Quoting directly</p>\n</li>\n</ol>\n<blockquote>\n<p><code>date = datetime.now() current_year = int(date.year)</code></p>\n<pre><code>if input_year &lt;= 0 or input_year &gt; current_year:\n print(&quot;don't you know your birthday??&quot;)\n</code></pre>\n<p>This will make your program work in future years without the need to change the value for\nthe current year manually.</p>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-29T07:30:33.383", "Id": "246157", "ParentId": "246055", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T21:17:35.190", "Id": "246055", "Score": "5", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Age calculator in python" }
246055
<p>Many people tell me that C++ is a significantly better language for writing compilers than JavaScript is. So, I've decided to rewrite the compiler for AEC (the programming language I've made) from JavaScript to C++ before extending it to be able to target WebAssembly (right now, it's only capable of targeting x86). So far, I've only rewritten the tokenizer and the parser, and I was wondering if you could give me some advice on how I can do that better.<br/> File <code>AECforWebAssembly.cpp</code>:</p> <pre class="lang-cpp prettyprint-override"><code>#define NDEBUG #include &quot;parser.cpp&quot; #include &quot;tests.cpp&quot; #include &quot;tokenizer.cpp&quot; #include &lt;iostream&gt; using namespace std; int main(int argc, char **argv) { cout &lt;&lt; &quot;Running the tests...&quot; &lt;&lt; endl; runTests(); cout &lt;&lt; &quot;All the tests passed.&quot; &lt;&lt; endl; return 0; } </code></pre> <p>File <code>parser.cpp</code>:</p> <pre class="lang-cpp prettyprint-override"><code>#include &quot;TreeNode.cpp&quot; #include &lt;algorithm&gt; std::vector&lt;TreeNode&gt; TreeNode::applyBinaryOperators(std::vector&lt;TreeNode&gt; input, std::vector&lt;std::string&gt; operators, Associativity associativity) { using std::regex; using std::regex_match; for (int i = associativity == left ? 0 : int(input.size()) - 1; associativity == left ? i &lt; int(input.size()) : i &gt;= 0; i += associativity == left ? 1 : -1) { if (std::count(operators.begin(), operators.end(), input[i].text) and !input[i].children.size()) { if (!i or i == int(input.size()) - 1) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; input[i].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; input[i].columnNumber &lt;&lt; &quot;, Parser error: The binary operator \&quot;&quot; &lt;&lt; input[i].text &lt;&lt; &quot;\&quot; has less than two operands.&quot; &lt;&lt; std::endl; return input; } if (!regex_match( input[i - 1].text, regex(&quot;(^(\\d|_|[a-z]|[A-Z])*$)|(^(\\d|_|[a-z]|[A-Z])+\\.(&quot; &quot;\\d|_|[a-z]|[A-Z])*$)&quot;)) and !input[i - 1].children.size() and input[i - 1].text.back() != '(') { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; input[i - 1].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; input[i - 1].columnNumber &lt;&lt; &quot;, Parser error: Unexpected token \&quot;&quot; &lt;&lt; input[i - 1].text &lt;&lt; &quot;\&quot;.&quot; &lt;&lt; std::endl; } if (!regex_match( input[i + 1].text, regex(&quot;(^(\\d|_|[a-z]|[A-Z])*$)|(^(\\d|_|[a-z]|[A-Z])+\\.(&quot; &quot;\\d|_|[a-z]|[A-Z])*$)&quot;)) and !input[i + 1].children.size() and input[i - 1].text.back() != '(') { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; input[i + 1].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; input[i + 1].columnNumber &lt;&lt; &quot;, Parser error: Unexpected token \&quot;&quot; &lt;&lt; input[i - 1].text &lt;&lt; &quot;\&quot;.&quot; &lt;&lt; std::endl; } input[i].children.push_back(input[i - 1]); input[i].children.push_back(input[i + 1]); input.erase(input.begin() + i + 1); input.erase(input.begin() + i - 1); i += associativity == left ? -1 : 1; } } return input; } std::vector&lt;TreeNode&gt; TreeNode::parseExpression(std::vector&lt;TreeNode&gt; input) { #ifndef NDEBUG std::cerr &lt;&lt; &quot;DEBUG: Beginning to parse the array of tokens: &quot; &lt;&lt; JSONifyArrayOfTokens(input) &lt;&lt; std::endl; #endif auto parsedExpression = input; for (unsigned int i = 0; i &lt; parsedExpression.size(); i++) if (parsedExpression[i].text.back() == '(' and !parsedExpression[i].children.size()) { unsigned int firstParenthesis = i; unsigned int nextParenthesis = i + 1; unsigned int counterOfOpenParentheses = 1; while (counterOfOpenParentheses) { if (nextParenthesis &gt;= parsedExpression.size()) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; parsedExpression[i].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; parsedExpression[i].columnNumber &lt;&lt; &quot;, Parser error: The parenthesis is not closed!&quot; &lt;&lt; std::endl; break; } if (parsedExpression[nextParenthesis].text.back() == '(') counterOfOpenParentheses++; if (parsedExpression[nextParenthesis].text == &quot;)&quot;) counterOfOpenParentheses--; nextParenthesis++; } std::vector&lt;TreeNode&gt; nodesThatTheRecursionDealsWith; for (unsigned int i = firstParenthesis + 1; i &lt; nextParenthesis - 1; i++) // Don't include the parentheses in the expression passed to the // recursion, otherwise you will end up in an infinite loop. nodesThatTheRecursionDealsWith.push_back(parsedExpression[i]); nodesThatTheRecursionDealsWith = parseExpression(nodesThatTheRecursionDealsWith); if (nodesThatTheRecursionDealsWith.size() &gt; 1 and parsedExpression[i].text == &quot;(&quot;) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; nodesThatTheRecursionDealsWith[1].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; nodesThatTheRecursionDealsWith[1].columnNumber &lt;&lt; &quot;, Parser error: Unexpected token \&quot;&quot; &lt;&lt; nodesThatTheRecursionDealsWith[1].text &lt;&lt; &quot;\&quot;.&quot; &lt;&lt; std::endl; } for (auto iterator = nodesThatTheRecursionDealsWith.begin(); iterator &lt; nodesThatTheRecursionDealsWith.end(); iterator++) if (iterator-&gt;text == &quot;,&quot;) { // Multi-argument function iterator--; nodesThatTheRecursionDealsWith.erase(iterator + 1); } if (parsedExpression[i].text == &quot;(&quot;) { // If it's not a function, but only a parenthesis, delete it. parsedExpression.erase(parsedExpression.begin() + firstParenthesis, parsedExpression.begin() + nextParenthesis); parsedExpression.insert(parsedExpression.begin() + i, nodesThatTheRecursionDealsWith.begin(), nodesThatTheRecursionDealsWith.end()); } else { // If it's the name of a function, don't delete it. parsedExpression.erase(parsedExpression.begin() + firstParenthesis + 1, parsedExpression.begin() + nextParenthesis); parsedExpression[i].children.insert( parsedExpression[i].children.begin(), nodesThatTheRecursionDealsWith.begin(), nodesThatTheRecursionDealsWith.end()); } } for (unsigned int i = 0; i &lt; parsedExpression.size(); i++) if (parsedExpression[i].text.back() == '[' and parsedExpression[i].children.size() == 0) // Array indices { unsigned int nameOfTheArray = i; unsigned int counterOfArrayNames = 1; unsigned int closedBracket = nameOfTheArray + 1; while (counterOfArrayNames) { if (closedBracket &gt;= parsedExpression.size()) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; parsedExpression[i].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; parsedExpression[i].columnNumber &lt;&lt; &quot;, Parser error: The index of the array \&quot;&quot; &lt;&lt; parsedExpression[i].text.substr( 0, parsedExpression[i].text.size() - 1) &lt;&lt; &quot;\&quot; is not closed by \&quot;]\&quot;.&quot; &lt;&lt; std::endl; break; } if (parsedExpression[closedBracket].text == &quot;]&quot;) counterOfArrayNames--; if (parsedExpression[closedBracket].text.back() == '[') counterOfArrayNames++; closedBracket++; } closedBracket--; std::vector&lt;TreeNode&gt; nodesThatTheRecursionDealsWith; for (unsigned int i = nameOfTheArray + 1; i &lt; closedBracket; i++) // Again, it's important not to include brackets in the array // that's passed to the recursion. nodesThatTheRecursionDealsWith.push_back(parsedExpression[i]); nodesThatTheRecursionDealsWith = parseExpression(nodesThatTheRecursionDealsWith); if (nodesThatTheRecursionDealsWith.size() == 0) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; parsedExpression[i].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; parsedExpression[i].columnNumber &lt;&lt; &quot;, Parser error: Array index of the array \&quot;&quot; &lt;&lt; parsedExpression[i].text.substr( 0, parsedExpression[i].text.size() - 1) // Don't print the '[' character at the end // of the array name (as the array name is // visible to the parser). &lt;&lt; &quot;\&quot; is empty!&quot; &lt;&lt; std::endl; break; } if (nodesThatTheRecursionDealsWith.size() &gt; 1) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; nodesThatTheRecursionDealsWith[1].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; nodesThatTheRecursionDealsWith[1].columnNumber &lt;&lt; &quot;, Parser error: Unexpected token \&quot;&quot; &lt;&lt; nodesThatTheRecursionDealsWith[1].text &lt;&lt; &quot;\&quot;!&quot; &lt;&lt; std::endl; } parsedExpression[i].children.insert( parsedExpression[i].children.begin(), nodesThatTheRecursionDealsWith.begin(), nodesThatTheRecursionDealsWith.end()); parsedExpression.erase( parsedExpression.begin() + nameOfTheArray + 1, // It's important to exclude the name of the array from the // portion about to be erased. parsedExpression.begin() + closedBracket + 1 // And it's also important to include the closing bracket into // the portion about to be erased. ); } for (unsigned int i = 0; i &lt; parsedExpression.size(); i++) if (parsedExpression[i].text == &quot;{&quot;) // Array initializer { unsigned int openCurlyBrace = i; unsigned int closedCurlyBrace = i + 1; unsigned int curlyBracesCounter = 1; while (curlyBracesCounter) { if (closedCurlyBrace &gt;= parsedExpression.size()) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; parsedExpression[i].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; parsedExpression[i].columnNumber &lt;&lt; &quot;, Parser error: The curly brace \&quot;{\&quot; isn't closed!&quot; &lt;&lt; std::endl; break; } if (parsedExpression[closedCurlyBrace].text == &quot;}&quot;) curlyBracesCounter--; if (parsedExpression[closedCurlyBrace].text == &quot;{&quot;) curlyBracesCounter++; closedCurlyBrace++; } closedCurlyBrace--; std::vector&lt;TreeNode&gt; nodesThatTheRecursionDealsWith( parsedExpression.begin() + openCurlyBrace + 1, parsedExpression.begin() + closedCurlyBrace); // We aren't in JavaScript, let's use the // features of C++, such as the iterator range // constructors... nodesThatTheRecursionDealsWith = parseExpression(nodesThatTheRecursionDealsWith); nodesThatTheRecursionDealsWith.erase( std::remove_if(nodesThatTheRecursionDealsWith.begin(), nodesThatTheRecursionDealsWith.end(), [](TreeNode node) { return node.text == &quot;,&quot;; }), nodesThatTheRecursionDealsWith.end()); //...and lambda functions. #ifndef NDEBUG std::cerr &lt;&lt; &quot;DEBUG: After std::remove_if, we are dealing with: &quot; &lt;&lt; JSONifyArrayOfTokens(nodesThatTheRecursionDealsWith) &lt;&lt; std::endl; #endif parsedExpression[openCurlyBrace].children.insert( parsedExpression[openCurlyBrace].children.begin(), nodesThatTheRecursionDealsWith.begin(), nodesThatTheRecursionDealsWith.end()); parsedExpression.erase(parsedExpression.begin() + openCurlyBrace + 1, parsedExpression.begin() + closedCurlyBrace + 1); parsedExpression[openCurlyBrace].text = &quot;{}&quot;; } for (int i = parsedExpression.size() - 1; i &gt;= 0; i--) // The unary &quot;-&quot; operator. if (parsedExpression[i].text == &quot;-&quot; and i != int(parsedExpression.size()) - 1 and parsedExpression[i].children.size() == 0 and (!i or (!std::regex_match(parsedExpression[i - 1].text, std::regex(&quot;(^(\\d|_|[a-z]|[A-Z])*$)|(^(\\d|_|[a-z]&quot; &quot;|[A-Z])+\\.(\\d|_|[a-z]|[A-Z])*$)&quot;)) and parsedExpression[i - 1].text.back() != '(' and parsedExpression[i - 1].children.size() == 0))) { parsedExpression[i].children.push_back( TreeNode(&quot;0&quot;, parsedExpression[i].lineNumber, parsedExpression[i].columnNumber)); parsedExpression[i].children.push_back(parsedExpression[i + 1]); parsedExpression.erase(parsedExpression.begin() + i + 1); } std::vector&lt;std::vector&lt;std::string&gt;&gt; leftAssociativeBinaryOperators( {{&quot;*&quot;, &quot;/&quot;}, {&quot;-&quot;, &quot;+&quot;}, {&quot;&lt;&quot;, &quot;&gt;&quot;, &quot;=&quot;}, {&quot;and&quot;}, {&quot;or&quot;}}); parsedExpression = applyBinaryOperators(parsedExpression, {&quot;.&quot;}, Associativity::right); for (unsigned int i = 0; i &lt; leftAssociativeBinaryOperators.size(); i++) parsedExpression = applyBinaryOperators(parsedExpression, leftAssociativeBinaryOperators[i], Associativity::left); for (int i = parsedExpression.size() - 1; i &gt;= 0; i--) // The ternary conditional &quot;?:&quot; operator (it's right-associative). if (parsedExpression[i].text == &quot;:&quot;) { if (i == int(parsedExpression.size()) - 1) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; parsedExpression[i].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; parsedExpression[i].columnNumber &lt;&lt; &quot;, Parser error: The ternary operator \&quot;?:\&quot; has less &quot; &quot;than three operands.&quot; &lt;&lt; std::endl; break; } int colon = i; int questionMark = i - 1; int colonCounter = 1; while (colonCounter) { if (questionMark &lt; 0) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; parsedExpression[colon].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; parsedExpression[colon].columnNumber &lt;&lt; &quot;, Parser error: Unexpected token \&quot;:\&quot;!&quot; &lt;&lt; std::endl; break; } if (parsedExpression[questionMark].text == &quot;?&quot;) colonCounter--; if (parsedExpression[questionMark].text == &quot;:&quot;) colonCounter++; questionMark--; } questionMark++; if (!questionMark) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; parsedExpression[questionMark].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; parsedExpression[questionMark].columnNumber &lt;&lt; &quot;, Parser error: The ternary operator \&quot;?:\&quot; has less &quot; &quot;than three operands.&quot; &lt;&lt; std::endl; break; } std::vector&lt;TreeNode&gt; nodesThatTheRecursionDealsWith; for (int i = questionMark + 1; i &lt; colon; i++) nodesThatTheRecursionDealsWith.push_back(parsedExpression[i]); nodesThatTheRecursionDealsWith = parseExpression(nodesThatTheRecursionDealsWith); if (nodesThatTheRecursionDealsWith.size() &gt; 1) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; nodesThatTheRecursionDealsWith[1].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; nodesThatTheRecursionDealsWith[1].columnNumber &lt;&lt; &quot;, Parser error: Unexpected token \&quot;&quot; &lt;&lt; nodesThatTheRecursionDealsWith[1].text &lt;&lt; &quot;\&quot;!&quot; &lt;&lt; std::endl; break; } if (nodesThatTheRecursionDealsWith.size() == 0) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; parsedExpression[questionMark].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; parsedExpression[questionMark].columnNumber &lt;&lt; &quot;, Parser error: The ternary operator \&quot;?:\&quot; has less &quot; &quot;than three operands!&quot; &lt;&lt; std::endl; break; } parsedExpression[questionMark].text = &quot;?:&quot;; parsedExpression[questionMark].children.push_back( parsedExpression[questionMark - 1]); // Condition parsedExpression[questionMark].children.push_back( nodesThatTheRecursionDealsWith[0]); // Then-clause parsedExpression[questionMark].children.push_back( parsedExpression[colon + 1]); // Else-clause parsedExpression.erase(parsedExpression.begin() + questionMark - 1); parsedExpression.erase(parsedExpression.begin() + questionMark, parsedExpression.begin() + colon + 1); i = questionMark; } parsedExpression = applyBinaryOperators(parsedExpression, {&quot;:=&quot;}, Associativity::right); #ifndef NDEBUG std::cerr &lt;&lt; &quot;DEBUG: Returning the array: &quot; &lt;&lt; JSONifyArrayOfTokens(parsedExpression) &lt;&lt; std::endl; #endif return parsedExpression; } std::vector&lt;TreeNode&gt; TreeNode::parseVariableDeclaration(std::vector&lt;TreeNode&gt; input) { auto inputWithParenthesesParsed = parseExpression(input); if (input.size() &lt; 2) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; inputWithParenthesesParsed[0].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; inputWithParenthesesParsed[0].columnNumber &lt;&lt; &quot;, Parser error: Unexpected token \&quot;&quot; &lt;&lt; inputWithParenthesesParsed[0].text &lt;&lt; &quot;\&quot;!&quot; &lt;&lt; std::endl; return inputWithParenthesesParsed; } for (unsigned i = 0; i &lt; inputWithParenthesesParsed.size(); i++) if (inputWithParenthesesParsed[i].text == &quot;:=&quot;) // Initial assignments. { TreeNode nodeWithVariableName = inputWithParenthesesParsed[i] .children[0]; // Let's assume the parser has done a good job thus // far. TreeNode NodeWithAssignment = inputWithParenthesesParsed[i].children[1]; TreeNode temporaryNode = TreeNode(&quot;:=&quot;, inputWithParenthesesParsed[i].lineNumber, inputWithParenthesesParsed[i].columnNumber); temporaryNode.children.push_back(NodeWithAssignment); nodeWithVariableName.children.push_back(temporaryNode); inputWithParenthesesParsed[i] = nodeWithVariableName; } inputWithParenthesesParsed.erase( std::remove_if(inputWithParenthesesParsed.begin(), inputWithParenthesesParsed.end(), [](TreeNode node) { return node.text == &quot;,&quot;; }), inputWithParenthesesParsed.end()); inputWithParenthesesParsed[0].children.insert( inputWithParenthesesParsed[0].children.begin(), inputWithParenthesesParsed.begin() + 1, inputWithParenthesesParsed.end()); inputWithParenthesesParsed.erase(inputWithParenthesesParsed.begin() + 1, inputWithParenthesesParsed.end()); return inputWithParenthesesParsed; } std::vector&lt;TreeNode&gt; TreeNode::parse(std::vector&lt;TreeNode&gt; input) { typedef std::vector&lt;TreeNode&gt; TreeNodes; #ifndef NDEBUG // Well, constructors and all those object-oriented things in C++ // are only useful if you know what you're doing. If you don't, // you are shooting yourself in the foot, like I did here. if (input.size()) { std::cerr &lt;&lt; &quot;DEBUG: Basic data type sizes are:\n&quot;; for (auto i = input[0].basicDataTypeSizes.begin(); i != input[0].basicDataTypeSizes.end(); i++) std::cerr &lt;&lt; &quot;DEBUG: &quot; &lt;&lt; i-&gt;first &lt;&lt; &quot;\t&quot; &lt;&lt; i-&gt;second &lt;&lt; '\n'; std::flush(std::cerr); } #endif for (unsigned i = 0; i &lt; input.size(); i++) if (input[i].basicDataTypeSizes.count(input[i].text) and input[i].children.empty()) { // Declaration of a variable of a basic // type (Integer32...). #ifndef NDEBUG std::cerr &lt;&lt; &quot;DEBUG: Parsing a variable declaration at line &quot; &lt;&lt; input[i].lineNumber &lt;&lt; &quot; of the type &quot; &lt;&lt; input[i].text &lt;&lt; &quot;.&quot; &lt;&lt; std::endl; #endif unsigned int typeName = i; unsigned int semicolon = i + 1; while (true) { if (semicolon &gt;= input.size()) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; input[typeName].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; input[typeName].columnNumber &lt;&lt; &quot;, Parser error: Expected a semi-colon to end the &quot; &quot;variable declaration of type &quot; &lt;&lt; input[typeName].text &lt;&lt; &quot;!&quot; &lt;&lt; std::endl; break; } if (input[semicolon].text == &quot;;&quot;) break; semicolon++; } TreeNodes nodesThatTheRecursionDealsWith(input.begin() + typeName, input.begin() + semicolon); nodesThatTheRecursionDealsWith = parseVariableDeclaration(nodesThatTheRecursionDealsWith); input[typeName] = nodesThatTheRecursionDealsWith[0]; input.erase(input.begin() + typeName + 1, input.begin() + semicolon); } else if (input[i].text == &quot;InstantiateStructure&quot; and input[i].children.empty()) { if (i == input.size() - 1) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; input[i].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; input[i].columnNumber &lt;&lt; &quot;, Parser error: Unexpected end of file!&quot; &lt;&lt; std::endl; return input; } unsigned int typeName = i; unsigned int semicolon = i + 1; while (true) { if (semicolon &gt;= input.size()) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; input[typeName].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; input[typeName].columnNumber &lt;&lt; &quot;, Parser error: Expected a semicolon to end the &quot; &quot;variable declaration of type &quot; &lt;&lt; input[typeName + 1].text &lt;&lt; &quot;!&quot; &lt;&lt; std::endl; break; } if (input[semicolon].text == &quot;;&quot;) break; semicolon++; } TreeNodes nodesThatTheRecursionDealsWith(input.begin() + typeName + 1, input.begin() + semicolon); nodesThatTheRecursionDealsWith = parseVariableDeclaration(nodesThatTheRecursionDealsWith); input[typeName].children.push_back(nodesThatTheRecursionDealsWith[0]); input.erase(input.begin() + typeName + 1, input.begin() + semicolon); } else if (input[i].text == &quot;Function&quot;) { if (i == input.size() - 1) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; input[i].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; input[i].columnNumber &lt;&lt; &quot;, Parser error: Unexpected end of file!&quot; &lt;&lt; std::endl; return input; } if (input[i + 1].text.back() != '(' or input[i + 1].text.size() == 1) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; input[i + 1].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; input[i + 1].columnNumber &lt;&lt; &quot;, Parser error: Expected a function name instead of \&quot;&quot; &lt;&lt; input[i + 1].text &lt;&lt; &quot;\&quot;!&quot; &lt;&lt; std::endl; return input; } unsigned int functionName = i + 1; unsigned int endOfFunctionSignature = i + 2; unsigned int counterOfParentheses = 1; while (counterOfParentheses) { if (endOfFunctionSignature &gt;= input.size()) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; input[functionName].lineNumber &lt;&lt; &quot;, Column: &quot; &lt;&lt; input[functionName].columnNumber &lt;&lt; &quot;, Parser error: Parenthesis in \&quot;&quot; &lt;&lt; input[functionName].text &lt;&lt; &quot;\&quot; not closed!&quot;; break; } if (input[endOfFunctionSignature].text == &quot;)&quot;) counterOfParentheses--; if (input[endOfFunctionSignature].text.back() == '(') counterOfParentheses++; endOfFunctionSignature++; } TreeNodes functionArguments(input.begin() + functionName + 1, input.begin() + endOfFunctionSignature - 1); input.erase(input.begin() + functionName + 1, input.begin() + endOfFunctionSignature); TreeNodes argument; for (unsigned int i = 0; i &lt; functionArguments.size() + 1; i++) { if (i == functionArguments.size() or functionArguments[i].text == &quot;,&quot;) { input[functionName].children.push_back( parseVariableDeclaration(argument)[0]); argument = TreeNodes(); } else argument.push_back(functionArguments[i]); } if (functionName &gt; input.size() - 5) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; input[functionName].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; input[functionName].columnNumber &lt;&lt; &quot;, Parser error: Expected a function declaration of the format &quot; &quot;\&quot;Function function_name(argument list) Which Returns &quot; &quot;type_name Does\&quot; or \&quot;Function function_name(argument list) &quot; &quot;Which Returns type_name Is External;\&quot;!&quot; &lt;&lt; std::endl; return input; } if (input[functionName + 1].text != &quot;Which&quot;) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; input[functionName + 1].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; input[functionName + 1].columnNumber &lt;&lt; &quot;, Parser error: Expected \&quot;Which\&quot; instead of \&quot;&quot; &lt;&lt; input[functionName + 1].text &lt;&lt; &quot;\&quot;!&quot; &lt;&lt; std::endl; return input; } if (input[functionName + 2].text != &quot;Returns&quot;) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; input[functionName + 2].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; input[functionName + 2].columnNumber &lt;&lt; &quot;, Parser error: Expected \&quot;Returns\&quot; instead of \&quot;&quot; &lt;&lt; input[functionName + 2].text &lt;&lt; &quot;\&quot;!&quot; &lt;&lt; std::endl; return input; } input[functionName - 1].children.push_back(input[functionName]); input[functionName + 2].children.push_back(input[functionName + 3]); input[functionName - 1].children.push_back(input[functionName + 2]); if (input[functionName + 4].text == &quot;Is&quot;) // External function { if (input[functionName + 5].text != &quot;External&quot;) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; input[functionName + 5].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; input[functionName + 5].columnNumber &lt;&lt; &quot;, Parser error: Expected \&quot;External\&quot; instead of \&quot;&quot; &lt;&lt; input[functionName + 5].text &lt;&lt; &quot;\&quot;!&quot; &lt;&lt; std::endl; return input; } if (input[functionName + 6].text != &quot;;&quot;) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; input[functionName + 6].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; input[functionName + 6].columnNumber &lt;&lt; &quot;, Parser error: Expected \&quot;;\&quot; instead of \&quot;&quot; &lt;&lt; input[functionName + 5].text &lt;&lt; &quot;\&quot;!&quot; &lt;&lt; std::endl; return input; } input[functionName - 1].children.push_back(input[functionName + 5]); input.erase( input.begin() + functionName, input.begin() + functionName + 7); // Delete all up to, and including, the semicolon &quot;;&quot;. } else if (input[functionName + 4].text == &quot;Does&quot;) // Function implemented in this file (right here). { unsigned int endOfTheFunction = functionName + 5; while (true) { if (endOfTheFunction &gt;= input.size()) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; input[functionName + 4].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; input[functionName + 5].columnNumber &lt;&lt; &quot;, Parser error: The end of the function is not &quot; &quot;marked with \&quot;EndFunction\&quot;.&quot; &lt;&lt; std::endl; break; } if (input[endOfTheFunction].text == &quot;EndFunction&quot;) break; endOfTheFunction++; } TreeNodes nodesThatTheRecursionDealsWith( input.begin() + functionName + 5, input.begin() + endOfTheFunction); nodesThatTheRecursionDealsWith = parse(nodesThatTheRecursionDealsWith); input[functionName + 4].children.insert( input[functionName + 4].children.begin(), nodesThatTheRecursionDealsWith.begin(), nodesThatTheRecursionDealsWith.end()); input[functionName - 1].children.push_back(input[functionName + 4]); input.erase(input.begin() + functionName, input.begin() + endOfTheFunction + 1); // Because now it's all supposed to be the children // of the &quot;Function&quot; node. } else { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; input[functionName + 4].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; input[functionName + 4].columnNumber &lt;&lt; &quot;, Parser error: Expected either \&quot;Is\&quot; or \&quot;Does\&quot; &quot; &quot;instead of \&quot;&quot; &lt;&lt; input[functionName + 4].text &lt;&lt; &quot;\&quot;.&quot; &lt;&lt; std::endl; return input; } } else if (input[i].text == &quot;While&quot; and input[i].children.empty()) { auto iteratorOfTheLoopToken = std::find_if(input.begin(), input.end(), [](TreeNode node) { return node.text == &quot;Loop&quot;; }); if (iteratorOfTheLoopToken == input.end()) std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; input[i].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; input[i].columnNumber &lt;&lt; &quot;, Parser error: There is a \&quot;While\&quot; token without its &quot; &quot;corresponding \&quot;Loop\&quot; token!&quot; &lt;&lt; std::endl; TreeNodes condition(input.begin() + i + 1, iteratorOfTheLoopToken); condition = parseExpression(condition); if (condition.size() == 0) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; input[i].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; input[i].columnNumber &lt;&lt; &quot;, Parser error: No expression between \&quot;While\&quot; and &quot; &quot;\&quot;Loop\&quot; tokens!&quot; &lt;&lt; std::endl; condition.push_back( TreeNode(&quot;0&quot;, input[i].lineNumber, input[i].columnNumber)); } if (condition.size() &gt; 1) std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; condition[1].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; condition[1].columnNumber &lt;&lt; &quot;, Parser error: Unexpected token \&quot;&quot; &lt;&lt; condition[1].text &lt;&lt; &quot;\&quot;&quot; &lt;&lt; std::endl; input[i].children.push_back(condition[0]); if (iteratorOfTheLoopToken == input.end()) // If there is no &quot;Loop&quot; token... { input.erase(input.begin() + i + 1, input.end()); return input; } auto iteratorOfTheEndWhileToken = iteratorOfTheLoopToken; unsigned int counterOfWhileLoops = 1; do { iteratorOfTheEndWhileToken++; if (iteratorOfTheEndWhileToken == input.end()) break; if (iteratorOfTheEndWhileToken-&gt;text == &quot;While&quot;) counterOfWhileLoops++; if (iteratorOfTheEndWhileToken-&gt;text == &quot;EndWhile&quot;) counterOfWhileLoops--; } while (counterOfWhileLoops); if (iteratorOfTheEndWhileToken == input.end()) std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; iteratorOfTheLoopToken-&gt;lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; iteratorOfTheLoopToken-&gt;columnNumber &lt;&lt; &quot;, Parser error: There is a \&quot;Loop\&quot; token without a &quot; &quot;corresponding \&quot;EndWhile\&quot; token.&quot; &lt;&lt; std::endl; TreeNodes nodesThatTheRecursionDealsWith(iteratorOfTheLoopToken + 1, iteratorOfTheEndWhileToken); nodesThatTheRecursionDealsWith = parse(nodesThatTheRecursionDealsWith); iteratorOfTheLoopToken-&gt;children.insert( iteratorOfTheLoopToken-&gt;children.begin(), nodesThatTheRecursionDealsWith.begin(), nodesThatTheRecursionDealsWith.end()); input[i].children.push_back(*iteratorOfTheLoopToken); input.erase( input.begin() + i + 1, iteratorOfTheEndWhileToken == input.end() ? iteratorOfTheEndWhileToken : iteratorOfTheEndWhileToken + 1); // If the &quot;EndWhile&quot; token exists, delete it now. } else if (input[i].text == &quot;Return&quot; and input[i].children.empty()) { auto iteratorOfTheSemicolon = std::find_if(input.begin() + i, input.end(), [](TreeNode node) { return node.text == &quot;;&quot;; }); if (iteratorOfTheSemicolon == input.end()) std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; input[i].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; input[i].columnNumber &lt;&lt; &quot;, Parser error: The return statement is not terminated &quot; &quot;with a semicolon.&quot; &lt;&lt; std::endl; TreeNodes expression(input.begin() + i + 1, iteratorOfTheSemicolon); expression = parseExpression(expression); if (expression.size() &gt; 1) std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; expression[1].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; expression[1].columnNumber &lt;&lt; &quot;, Parser error: Unexpected token \&quot;&quot; &lt;&lt; expression[1].text &lt;&lt; &quot;\&quot;&quot; &lt;&lt; std::endl; if (expression.size()) input[i].children.push_back( expression[0]); // The function can return nothing at all, the // parser must not segfault then! input.erase(input.begin() + i + 1, (iteratorOfTheSemicolon == input.end()) ? iteratorOfTheSemicolon : iteratorOfTheSemicolon + 1); } else if (input[i].text == &quot;If&quot; and input[i].children.empty()) { auto iteratorPointingToTheThenToken = std::find_if(input.begin() + i, input.end(), [](TreeNode node) { return node.text == &quot;Then&quot;; }); if (iteratorPointingToTheThenToken == input.end()) std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; input[i].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; input[i].columnNumber &lt;&lt; &quot;, Parser error: There is a \&quot;If\&quot; without a &quot; &quot;corresponding \&quot;Then\&quot;!&quot; &lt;&lt; std::endl; TreeNodes condition(input.begin() + i + 1, iteratorPointingToTheThenToken); condition = parseExpression(condition); if (condition.empty()) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; input[i].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; input[i].columnNumber &lt;&lt; &quot;, Parser error: No expression between \&quot;If\&quot; and &quot; &quot;\&quot;Then\&quot; tokens!&quot; &lt;&lt; std::endl; condition.push_back( TreeNode(&quot;0&quot;, input[i].lineNumber, input[i].columnNumber)); } if (condition.size() &gt; 1) std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; condition[1].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; condition[1].columnNumber &lt;&lt; &quot;, Parser error: Unexpected token \&quot;&quot; &lt;&lt; condition[1].text &lt;&lt; &quot;\&quot;!&quot; &lt;&lt; std::endl; input[i].children.push_back(condition.front()); if (iteratorPointingToTheThenToken == input.end()) // If there is no &quot;Then&quot;... { input.erase(input.begin() + i + 1, input.end()); return input; } auto iteratorPointingToTheEndIfToken = iteratorPointingToTheThenToken; int counterOfIfBranches = 1; do { iteratorPointingToTheEndIfToken++; if (iteratorPointingToTheEndIfToken == input.end()) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; iteratorPointingToTheThenToken-&gt;lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; iteratorPointingToTheThenToken-&gt;columnNumber &lt;&lt; &quot;, Parser error: There is a \&quot;Then\&quot; token without the &quot; &quot;corresponding \&quot;EndIf\&quot; token!&quot; &lt;&lt; std::endl; break; } if (iteratorPointingToTheEndIfToken-&gt;text == &quot;EndIf&quot;) counterOfIfBranches--; if (iteratorPointingToTheEndIfToken-&gt;text == &quot;If&quot;) counterOfIfBranches++; // Don't look for &quot;Then&quot; tokens, because they // also come after the &quot;ElseIf&quot; statements. } while (counterOfIfBranches); auto iteratorPointingToTheElseIfToken = iteratorPointingToTheThenToken; counterOfIfBranches = 0; while (iteratorPointingToTheElseIfToken &lt; iteratorPointingToTheEndIfToken) { if (!counterOfIfBranches and iteratorPointingToTheElseIfToken-&gt;text == &quot;ElseIf&quot;) break; // If the &quot;ElseIf&quot; is referring to the &quot;If&quot; token at // &quot;input[i]&quot;, rather than to some nested &quot;If&quot; (which it does if // &quot;counterOfIfBranches&quot; is non-zero). if (iteratorPointingToTheElseIfToken-&gt;text == &quot;If&quot;) counterOfIfBranches++; if (iteratorPointingToTheElseIfToken-&gt;text == &quot;EndIf&quot;) counterOfIfBranches--; iteratorPointingToTheElseIfToken++; } if (iteratorPointingToTheElseIfToken &lt; iteratorPointingToTheEndIfToken) { // If there is an &quot;ElseIf&quot; // referring to this &quot;If&quot;. TreeNodes nodesThatTheRecursionDealsWith( iteratorPointingToTheThenToken + 1, iteratorPointingToTheElseIfToken); nodesThatTheRecursionDealsWith = parse(nodesThatTheRecursionDealsWith); iteratorPointingToTheThenToken-&gt;children.insert( iteratorPointingToTheThenToken-&gt;children.begin(), nodesThatTheRecursionDealsWith.begin(), nodesThatTheRecursionDealsWith.end()); input[i].children.push_back(*iteratorPointingToTheThenToken); iteratorPointingToTheElseIfToken-&gt;text = &quot;Else&quot;; nodesThatTheRecursionDealsWith = TreeNodes(iteratorPointingToTheElseIfToken, iteratorPointingToTheEndIfToken == input.end() ? iteratorPointingToTheEndIfToken : iteratorPointingToTheEndIfToken + 1); nodesThatTheRecursionDealsWith[0].text = &quot;If&quot;; nodesThatTheRecursionDealsWith = parse(nodesThatTheRecursionDealsWith); iteratorPointingToTheElseIfToken-&gt;children.insert( iteratorPointingToTheElseIfToken-&gt;children.begin(), nodesThatTheRecursionDealsWith.begin(), nodesThatTheRecursionDealsWith.end()); input[i].children.push_back( *iteratorPointingToTheElseIfToken); // Will appear as the &quot;Else&quot; // token to the compiler. input.erase( input.begin() + i + 1, iteratorPointingToTheEndIfToken == input.end() ? input.end() : iteratorPointingToTheEndIfToken + 1); // If there is an &quot;EndIf&quot; token, delete it as well. } else // No &quot;ElseIf&quot; token, but maybe there is an &quot;Else&quot; token. Let's // search for it! { auto iteratorPointingToTheElseToken = iteratorPointingToTheThenToken; counterOfIfBranches = 0; while (iteratorPointingToTheElseToken &lt; iteratorPointingToTheEndIfToken) { if (!counterOfIfBranches and iteratorPointingToTheElseToken-&gt;text == &quot;Else&quot;) break; if (iteratorPointingToTheElseToken-&gt;text == &quot;If&quot;) counterOfIfBranches++; if (iteratorPointingToTheElseToken-&gt;text == &quot;EndIf&quot;) counterOfIfBranches--; iteratorPointingToTheElseToken++; } if (iteratorPointingToTheElseToken &lt; iteratorPointingToTheEndIfToken) // If there is an &quot;Else&quot; token... { TreeNodes nodesThatTheRecursionDealsWith( iteratorPointingToTheThenToken + 1, iteratorPointingToTheElseToken); nodesThatTheRecursionDealsWith = parse(nodesThatTheRecursionDealsWith); iteratorPointingToTheThenToken-&gt;children = nodesThatTheRecursionDealsWith; input[i].children.push_back(*iteratorPointingToTheThenToken); nodesThatTheRecursionDealsWith = TreeNodes(iteratorPointingToTheElseToken + 1, iteratorPointingToTheEndIfToken); nodesThatTheRecursionDealsWith = parse(nodesThatTheRecursionDealsWith); iteratorPointingToTheElseToken-&gt;children = nodesThatTheRecursionDealsWith; input[i].children.push_back(*iteratorPointingToTheElseToken); input.erase(input.begin() + i + 1, iteratorPointingToTheEndIfToken == input.end() ? input.end() : iteratorPointingToTheEndIfToken + 1); } else { // There is neither an &quot;Else&quot; nor an &quot;ElseIf&quot; token, so we can // simply pass the tokens between (but not including) &quot;Then&quot; and // &quot;EndIf&quot; token. TreeNodes nodesThatTheRecursionDealsWith( iteratorPointingToTheThenToken + 1, iteratorPointingToTheEndIfToken); nodesThatTheRecursionDealsWith = parse(nodesThatTheRecursionDealsWith); iteratorPointingToTheThenToken-&gt;children = nodesThatTheRecursionDealsWith; input[i].children.push_back(*iteratorPointingToTheThenToken); input.erase(input.begin() + i + 1, iteratorPointingToTheEndIfToken == input.end() ? input.end() : iteratorPointingToTheEndIfToken + 1); } } } else { // Assume that what follows is an expression, presumably including // a &quot;:=&quot;. auto iteratorPointingToTheNextSemicolon = std::find_if(input.begin() + i, input.end(), [](TreeNode node) { return node.text == &quot;;&quot;; }); if (iteratorPointingToTheNextSemicolon == input.end()) std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; input[i].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; input[i].columnNumber &lt;&lt; &quot;, Parser error: The expression starting with \&quot;&quot; &lt;&lt; input[i].text &lt;&lt; &quot;\&quot; is not ended in a semicolon!&quot; &lt;&lt; std::endl; TreeNodes expression(input.begin() + i, iteratorPointingToTheNextSemicolon); expression = parseExpression(expression); if (expression.size() &gt; 1) std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; expression[1].lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; expression[1].columnNumber &lt;&lt; &quot;, Parser error: Unexpected token \&quot;&quot; &lt;&lt; expression[1].text &lt;&lt; &quot;\&quot;!&quot; &lt;&lt; std::endl; input.erase( input.begin() + i, (iteratorPointingToTheNextSemicolon != input.end()) ? iteratorPointingToTheNextSemicolon + 1 : iteratorPointingToTheNextSemicolon); // If there is a semicolon // terminating the // expression, delete it // together with the // expression. input.insert(input.begin() + i, expression.begin(), expression.end()); i += expression.size() - 1; } return input; } </code></pre> <p>File <code>tests.cpp</code>:</p> <pre class="lang-cpp prettyprint-override"><code>#include &quot;TreeNode.cpp&quot; struct test { // When the debugger doesn't work, &quot;cassert&quot; doesn't help a lot. std::string input, expectedResult; }; void tokenizerTests() { std::vector&lt;test&gt; tests( {{&quot;\&quot;/*Comment inside a string*/\&quot;&quot;, &quot;['\&quot;/*Comment inside a string*/\&quot;']&quot;}, {&quot;5+5&quot;, &quot;['5','+','5']&quot;}, {&quot;5+5=10&quot;, &quot;['5','+','5','=','10']&quot;}, {&quot;structureName.structureMember/3.14159265359&quot;, &quot;['structureName','.','structureMember','/','3.14159265359']&quot;}, {&quot;sin(pi/2)=1&quot;, &quot;['sin(','pi','/','2',')','=','1']&quot;}, {&quot;'A'+2='C'&quot;, &quot;['65','+','2','=','67']&quot;}, {&quot;a:=a+1; //Some random comment.\nb:=b-1;&quot;, &quot;['a',':=','a','+','1',';','b',':=','b','-','1',';']&quot;}, {&quot;/*This should be tokenized into\nan empty string*/&quot;, &quot;[]&quot;}, {&quot;a/*Randomly\ninserted\ncomment.*/+/*Another\nrandom\ncomment*/b&quot;, &quot;['a','+','b']&quot;}, {&quot;array_name:={1,1+1,1+1+1}&quot;, &quot;['array_name',':=','{','1',',','1','+','&quot; &quot;1',',','1','+','1','+','1','}']&quot;}}); for (unsigned int i = 0; i &lt; tests.size(); i++) { std::string result = TreeNode::JSONifyArrayOfTokens(TreeNode::tokenize(tests[i].input)); if (result != tests[i].expectedResult) { std::cerr &lt;&lt; &quot;Internal compiler error: Tokenizer test failed: \&quot;&quot; &lt;&lt; tests[i].input &lt;&lt; &quot;\&quot; tokenizes into \&quot;&quot; &lt;&lt; result &lt;&lt; &quot;\&quot; instead of to \&quot;&quot; &lt;&lt; tests[i].expectedResult &lt;&lt; &quot;\&quot;!&quot; &lt;&lt; std::endl; std::exit(1); } } } void simpleParserTests() { std::vector&lt;test&gt; tests( {{&quot;5+3&quot;, &quot;(+ 5 3)&quot;}, {&quot;2+3*4&quot;, &quot;(+ 2 (* 3 4))&quot;}, {&quot;2+2&lt;5 and 3.14159265359&lt;3.2&quot;, &quot;(and (&lt; (+ 2 2) 5) (&lt; 3.14159265359 3.2))&quot;}, {&quot;1-2-3-4&quot;, &quot;(- (- (- 1 2) 3) 4)&quot;}, {&quot;a:=b:=c&quot;, &quot;(:= a (:= b c))&quot;}, {&quot;3.14.16&quot;, &quot;(. 3.14 16)&quot;}, {&quot;1*(2+3)&quot;, &quot;(* 1 (+ 2 3))&quot;}, {&quot;pow(2+2/*A nonsensical expression,\nbut good for &quot; &quot;testing the parser.*/,sin(pi/2))&quot;, &quot;(pow (+ 2 2) (sin (/ pi 2)))&quot;}, {&quot;some_procedure()&quot;, &quot;some_procedure(&quot;}, {&quot;abs(function_returning_pi()-pi)&lt;1/1000&quot;, &quot;(&lt; (abs (- function_returning_pi( pi)) (/ 1 1000))&quot;}, {&quot;not(d=0)?c/d:0&quot;, &quot;(?: (not (= d 0)) (/ c d) 0)&quot;}, {&quot;(2+2&gt;5?3+3&lt;7?1:0-2:2+2-4&lt;1?0:2+2&lt;4?0-1:0-3)&quot;, &quot;(?: (&gt; (+ 2 2) 5) (?: (&lt; (+ 3 3) 7) 1 (- 0 2)) (?: (&lt; (- (+ 2 2) 4) &quot; &quot;1) 0 (?: (&lt; (+ 2 2) 4) (- 0 1) (- 0 3))))&quot;}, {&quot;(2+2&gt;5?3+3&lt;7?1:-2:2+2-4&lt;1?0:2+2&lt;4?-1:-3)&quot;, &quot;(?: (&gt; (+ 2 2) 5) (?: (&lt; (+ 3 3) 7) 1 (- 0 2)) (?: (&lt; (- (+ 2 2) 4) &quot; &quot;1) 0 (?: (&lt; (+ 2 2) 4) (- 0 1) (- 0 3))))&quot;}, {&quot;some_array[i+1]&quot;, &quot;(some_array (+ i 1))&quot;}, {&quot;array_pointer:={1,1+1,1+1+1}&quot;, &quot;(:= array_pointer ({} 1 (+ 1 1) (+ (+ 1 1) 1)))&quot;}}); for (unsigned int i = 0; i &lt; tests.size(); i++) { std::string result = TreeNode::parseExpression(TreeNode::tokenize(tests[i].input))[0] .getLispExpression(); if (result != tests[i].expectedResult) { std::cerr &lt;&lt; &quot;Internal compiler error: Basic parser test failed: \&quot;&quot; &lt;&lt; tests[i].input &lt;&lt; &quot;\&quot; parses into \&quot;&quot; &lt;&lt; result &lt;&lt; &quot;\&quot; instead of to \&quot;&quot; &lt;&lt; tests[i].expectedResult &lt;&lt; &quot;\&quot;!&quot; &lt;&lt; std::endl; std::exit(1); } } } void interpreterTests() { std::vector&lt;test&gt; tests( {{&quot;1+2*3&quot;, &quot;7&quot;}, {&quot;(1+2)*3&quot;, &quot;9&quot;}, {&quot;(2+2=4)?2:0&quot;, &quot;2&quot;}, {&quot;mod(5,2)&quot;, &quot;1&quot;}, {&quot;(2+2&gt;5?3+3&lt;7?1:-2:2+2-4&lt;1?0:2+2&lt;4?-1:-3)+('A'+2='C'?0:-1)&quot;, &quot;0&quot;}}); for (unsigned int i = 0; i &lt; tests.size(); i++) { std::string result = std::to_string( TreeNode::parseExpression(TreeNode::tokenize(tests[i].input))[0] .interpretAsACompileTimeConstant()); if (result != tests[i].expectedResult) { std::cerr &lt;&lt; &quot;Internal compiler error: Interpreter test failed: \&quot;&quot; &lt;&lt; tests[i].input &lt;&lt; &quot;\&quot; interprets into \&quot;&quot; &lt;&lt; result &lt;&lt; &quot;\&quot; instead of to \&quot;&quot; &lt;&lt; tests[i].expectedResult &lt;&lt; &quot;\&quot;!&quot; &lt;&lt; std::endl; std::exit(1); } } } void parsingVariableDeclarationsTests() { std::vector&lt;test&gt; tests( {{&quot;Integer32 some_array[80*23],array_width:=80,array_height:=23&quot;, &quot;(Integer32 (some_array (* 80 23)) (array_width (:= 80)) (array_height &quot; &quot;(:= 23)))&quot;}}); for (unsigned int i = 0; i &lt; tests.size(); i++) { std::string result = TreeNode::parseVariableDeclaration( TreeNode::tokenize(tests[i].input))[0] .getLispExpression(); if (result != tests[i].expectedResult) { std::cerr &lt;&lt; &quot;Internal compiler error: Parser test failed: \&quot;&quot; &lt;&lt; tests[i].input &lt;&lt; &quot;\&quot; parses into \&quot;&quot; &lt;&lt; result &lt;&lt; &quot;\&quot; instead of to \&quot;&quot; &lt;&lt; tests[i].expectedResult &lt;&lt; &quot;\&quot;!&quot; &lt;&lt; std::endl; std::exit(1); } } } void parserTests() { std::vector&lt;test&gt; tests( {{&quot;Integer32 some_array[80*23],array_width:=80,array_height:=23;&quot;, &quot;(Integer32 (some_array (* 80 23)) (array_width (:= 80)) (array_height &quot; &quot;(:= 23)))&quot;}, {&quot;Function log(CharPointer string) Which Returns Nothing Is External;&quot;, &quot;(Function (log (CharPointer string)) (Returns Nothing) External)&quot;}, {&quot;Function foo(Integer32 a:=0, Integer32 c) Which Returns Nothing Does &quot; &quot;//Nonsense &quot; &quot;code, but useful to see if the parser is capable of parsing simple &quot; &quot;functions.\n&quot; &quot;Integer32 b;\n&quot; &quot;b:=a+1;\n&quot; &quot;EndFunction&quot;, &quot;(Function (foo (Integer32 (a (:= 0))) (Integer32 c)) (Returns &quot; &quot;Nothing) (Does &quot; &quot;(Integer32 b) (:= b (+ a 1))))&quot;}, {&quot;Function factorial(Integer32 n) Which Returns Integer64 Does &quot; &quot;Integer64 counter:=1,result:=1;&quot; &quot;While counter&lt;n or counter=n Loop &quot; &quot;result:=result*counter;&quot; &quot;EndWhile &quot; &quot;Return result;&quot; &quot;EndFunction&quot;, &quot;(Function (factorial (Integer32 n)) (Returns Integer64) (Does &quot; &quot;(Integer64 (counter (:= 1)) (result (:= 1))) (While (or (&lt; counter n) &quot; &quot;(= counter n)) (Loop (:= result (* result counter)))) (Return &quot; &quot;result)))&quot;}, {&quot;Function gcd(Integer32 a, Integer32 b) Which Returns Integer32 Does &quot; &quot;//Euclidean Algorithm\n&quot; &quot;While not(b=0) Loop\n&quot; &quot;If a&gt;b Then\n&quot; &quot;a:=a-b;\n&quot; &quot;Else\n&quot; &quot;b:=b-a;\n&quot; &quot;EndIf\n&quot; &quot;EndWhile\n&quot; &quot;Return a;\n&quot; &quot;EndFunction&quot;, &quot;(Function (gcd (Integer32 a) (Integer32 b)) (Returns Integer32) (Does &quot; &quot;(While (not (= b 0)) (Loop (If (&gt; a b) (Then (:= a (- a b))) &quot; &quot;(Else (:= b (- b a)))))) (Return a)))&quot;}, {&quot;If a&lt;b and a&lt;c Then //This is semantically very wrong (an &quot; &quot;if-statement outside of a function), but it should still parse.\n&quot; &quot;If a&gt;0 Then Return a; Else Return 0; EndIf\n&quot; &quot;ElseIf b&lt;a and b&lt;c Then\n&quot; &quot;If b&gt;0 Then Return b; Else Return 0; EndIf\n&quot; &quot;Else\n&quot; &quot;If c&gt;0 Then Return c; Else Return 0; EndIf\n&quot; &quot;EndIf&quot;, &quot;(If (and (&lt; a b) (&lt; a c)) (Then &quot; &quot;(If (&gt; a 0) (Then (Return a)) (Else (Return 0)))) &quot; &quot;(Else (If (and (&lt; b a) (&lt; b c)) (Then &quot; &quot;(If (&gt; b 0) (Then (Return b)) (Else (Return 0)))) &quot; &quot;(Else &quot; &quot;(If (&gt; c 0) (Then (Return c)) (Else (Return 0)))))))&quot;}}); for (unsigned int i = 0; i &lt; tests.size(); i++) { std::string result = TreeNode::parse(TreeNode::tokenize(tests[i].input))[0] .getLispExpression(); if (result != tests[i].expectedResult) { std::cerr &lt;&lt; &quot;Internal compiler error: Parser test failed: \&quot;&quot; &lt;&lt; tests[i].input &lt;&lt; &quot;\&quot; parses into \&quot;&quot; &lt;&lt; result &lt;&lt; &quot;\&quot; instead of to \&quot;&quot; &lt;&lt; tests[i].expectedResult &lt;&lt; &quot;\&quot;!&quot; &lt;&lt; std::endl; std::exit(1); } } } void runTests() { tokenizerTests(); simpleParserTests(); interpreterTests(); parsingVariableDeclarationsTests(); parserTests(); } </code></pre> <p>File <code>tokenizer.cpp</code>:</p> <pre class="lang-cpp prettyprint-override"><code>#include &quot;TreeNode.cpp&quot; std::vector&lt;TreeNode&gt; TreeNode::tokenize(std::string input) { #ifndef NDEBUG std::cerr &lt;&lt; &quot;DEBUG: Tokenizing the string \&quot;&quot; &lt;&lt; input &lt;&lt; &quot;\&quot;...&quot; &lt;&lt; std::endl; #endif using std::regex; using std::regex_match; using std::string; using std::to_string; auto tokenizedExpression = std::vector&lt;TreeNode&gt;(); int currentLine = 1, currentColumn = 1; bool areWeInAString = false, areWeInAComment = false; string stringDelimiter, commentDelimiter; try { for (unsigned int i = 0; i &lt; input.size(); i++) { #ifndef NDEBUG std::cerr &lt;&lt; &quot;DEBUG: Now we are tokenizing the character #&quot; &lt;&lt; i &lt;&lt; &quot;: '&quot; &lt;&lt; input[i] &lt;&lt; &quot;'.&quot; &lt;&lt; std::endl; if (areWeInAString) std::cerr &lt;&lt; &quot;DEBUG: We are in a string.&quot; &lt;&lt; std::endl; if (areWeInAComment) std::cerr &lt;&lt; &quot;DEBUG: We are in a comment.&quot; &lt;&lt; std::endl; #endif if (tokenizedExpression.size() == 0) { if (input.size() - i &gt; 2 and (input.substr(i, 2) == &quot;//&quot; or input.substr(i, 2) == &quot;/*&quot;)) { areWeInAComment = true; commentDelimiter = input.substr(i, 2); tokenizedExpression.push_back(TreeNode(string(), 1, 1)); currentColumn++; continue; } tokenizedExpression.push_back(TreeNode(input.substr(i, 1), 1, 1)); currentColumn++; if (input[i] == '&quot;' or input[i] == '\'') { areWeInAString = true; stringDelimiter = input.substr(i, 1); } } else if ((input[i] == '&quot;' or input[i] == '\'') and !areWeInAComment) { if (areWeInAString and stringDelimiter == input.substr(i, 1) and (i == 0 or input[i - 1] != '\\')) { tokenizedExpression.back().text.push_back(input[i]); tokenizedExpression.push_back( TreeNode(string(), currentLine, currentColumn)); currentColumn++; areWeInAString = false; } else { currentColumn++; areWeInAString = true; stringDelimiter = input.substr(i, 1); tokenizedExpression.push_back( TreeNode(input.substr(i, 1), currentLine, currentColumn)); } } else if (input.size() - i &gt; 2 and (input.substr(i, 2) == &quot;//&quot; or input.substr(i, 2) == &quot;/*&quot;) and !areWeInAString and !areWeInAComment) { areWeInAComment = true; commentDelimiter = input.substr(i, 2); } else if (input[i] == '\n') { // If we came to the end of a line. if (areWeInAString) { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; currentLine &lt;&lt; &quot;, Column &quot; &lt;&lt; tokenizedExpression.back().columnNumber &lt;&lt; &quot;, Tokenizer error: Unterminated string literal!&quot; &lt;&lt; std::endl; areWeInAString = false; } if (areWeInAComment and commentDelimiter == &quot;//&quot;) areWeInAComment = false; else if (areWeInAComment) { currentLine++; currentColumn = 1; continue; } currentLine++; currentColumn = 1; tokenizedExpression.push_back( TreeNode(string(), currentLine, currentColumn)); } else if (regex_match(input.substr(i, 1), regex(&quot;\\s&quot;)) and !areWeInAString and !areWeInAComment) { // If we came to some other whitespace. currentColumn++; tokenizedExpression.push_back( TreeNode(string(), currentLine, currentColumn)); } else if (regex_match(input.substr(i, 1), regex(&quot;\\d|[a-z]|[A-Z]|_&quot;)) and regex_match( tokenizedExpression.back().text, regex(&quot;(^(\\d|_|[a-z]|[A-Z])*$)|(^(\\d|_|[a-z]|[A-Z])+\\.(&quot; &quot;\\d|_|[a-z]|[A-Z])*$)&quot;)) and !areWeInAString and !areWeInAComment) // Names and numbers { currentColumn++; tokenizedExpression.back().text += input[i]; } else if (input[i] == '.' and regex_match(tokenizedExpression.back().text, regex(&quot;^\\d+$&quot;)) and !areWeInAString and !areWeInAComment) // If we are currently // tokenizing a number, a dot // character is a decimal point. { currentColumn++; tokenizedExpression.back().text += input[i]; } else if (!areWeInAString and !areWeInAComment) { currentColumn++; tokenizedExpression.push_back( TreeNode(input.substr(i, 1), currentLine, currentColumn)); } else if (areWeInAString and !areWeInAComment) { currentColumn++; tokenizedExpression.back().text += input[i]; } else if (areWeInAComment and commentDelimiter == &quot;/*&quot; and input.size() - i &gt; 2 and input.substr(i, 2) == &quot;*/&quot; and !areWeInAString) { areWeInAComment = false; currentColumn += 2; tokenizedExpression.push_back( TreeNode(string(), currentLine, currentColumn)); i++; } else if (!areWeInAString and areWeInAComment) { currentColumn++; } else { std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; currentLine &lt;&lt; &quot;, Column &quot; &lt;&lt; currentColumn &lt;&lt; &quot;, Internal compiler error: Tokenizer is in the &quot; &quot;forbidden state!&quot; &lt;&lt; std::endl; } } for (auto iterator = tokenizedExpression.begin(); iterator &lt; tokenizedExpression.end(); iterator++) if (iterator-&gt;text.size() == 3 and iterator-&gt;text.substr(0, 1) == &quot;'&quot; and iterator-&gt;text.substr(2, 1) == &quot;'&quot;) iterator-&gt;text = std::to_string(int(iterator-&gt;text[1])); for (auto iterator = tokenizedExpression.begin(); iterator &lt; tokenizedExpression.end(); iterator++) // Turn escape sequences into numbers. if (iterator-&gt;text == &quot;'\\n'&quot;) iterator-&gt;text = to_string(int('\n')); else if (iterator-&gt;text == &quot;'\\t'&quot;) iterator-&gt;text = to_string(int('\t')); else if (iterator-&gt;text == &quot;'\\''&quot;) iterator-&gt;text = to_string(int('\'')); else if (iterator-&gt;text == &quot;'\\\\'&quot;) iterator-&gt;text = to_string(int('\\')); for (auto iterator = tokenizedExpression.begin(); iterator &lt; tokenizedExpression.end(); iterator++) if (regex_match(iterator-&gt;text, regex(&quot;^\\s*$&quot;))) // Delete empty nodes. { iterator--; tokenizedExpression.erase(iterator + 1); } for (unsigned int i = 1; i &lt; tokenizedExpression.size(); i++) if ((tokenizedExpression[i].text == &quot;(&quot; or // Mark the names of functions... tokenizedExpression[i].text == &quot;[&quot;) and //...and arrays with ending '(' or '[' regex_match( tokenizedExpression[i - 1].text.substr(0, 1), //...for the parser. regex(&quot;_|[a-z]|[A-Z]&quot;))) { tokenizedExpression[i - 1].text += tokenizedExpression[i].text; tokenizedExpression.erase(tokenizedExpression.begin() + i); } for (unsigned int i = 1; i &lt; tokenizedExpression.size(); i++) if (tokenizedExpression[i].text == &quot;=&quot; and tokenizedExpression[i - 1].text == &quot;:&quot;) // The &quot;:=&quot; assignment operator. { tokenizedExpression[i - 1].text = &quot;:=&quot;; tokenizedExpression.erase(tokenizedExpression.begin() + i); } } catch (std::regex_error &amp;error) { std::cerr &lt;&lt; &quot;Internal compiler error in tokenizer: &quot; &lt;&lt; error.what() &lt;&lt; &quot;:&quot; &lt;&lt; error.code() &lt;&lt; std::endl; return std::vector&lt;TreeNode&gt;(); } #ifndef NDEBUG std::cerr &lt;&lt; &quot;DEBUG: Finished tokenizing the string \&quot;&quot; &lt;&lt; input &lt;&lt; &quot;\&quot;.&quot; &lt;&lt; std::endl; #endif return tokenizedExpression; } </code></pre> <p>File <code>TreeNode.cpp</code>:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; #include &lt;map&gt; #include &lt;regex&gt; #include &lt;string&gt; #include &lt;vector&gt; #pragma once class TreeNode { enum Associativity { left, right }; static std::vector&lt;TreeNode&gt; applyBinaryOperators(std::vector&lt;TreeNode&gt; input, std::vector&lt;std::string&gt; operators, Associativity associativity); public: std::map&lt;std::string, int&gt; basicDataTypeSizes; std::vector&lt;TreeNode&gt; children; std::string text; int lineNumber, columnNumber; TreeNode() { basicDataTypeSizes[&quot;Integer32&quot;] = 4; basicDataTypeSizes[&quot;Character&quot;] = 1; basicDataTypeSizes[&quot;Decimal32&quot;] = 4; basicDataTypeSizes[&quot;Integer64&quot;] = 8; basicDataTypeSizes[&quot;Decimal64&quot;] = 8; basicDataTypeSizes[&quot;Integer16&quot;] = 2; for (auto iterator = basicDataTypeSizes.begin(); iterator != basicDataTypeSizes.end(); iterator++) if (iterator-&gt;first.find(&quot;Pointer&quot;) == std::string::npos) basicDataTypeSizes[iterator-&gt;first + &quot;Pointer&quot;] = 4; // JavaScript (WebAssembly) virtual machine is 32-bit (pointers // being 32 bits or 4 bytes long), unless somebody switches to // the 64-bit mode (which is rarely done). lineNumber = columnNumber = 0; } TreeNode(std::string newText, int newLine, int newColumn) { *this = TreeNode(); // For some weird reason, just &quot;TreeNode()&quot; won't do the // trick. text = newText; lineNumber = newLine; columnNumber = newColumn; } static std::vector&lt;TreeNode&gt; tokenize(std::string input); // See &quot;tokenizer.cpp&quot; for the implementation. static std::string JSONifyArrayOfTokens( std::vector&lt;TreeNode&gt; tokenizedString) { // For debugging the tokenizer. std::string ret = &quot;[&quot;; if (!tokenizedString.size()) return &quot;[]&quot;; for (unsigned int i = 0; i &lt; tokenizedString.size(); i++) if (i != tokenizedString.size() - 1) ret += &quot;'&quot; + tokenizedString[i].text + &quot;',&quot;; else ret += &quot;'&quot; + tokenizedString[i].text + &quot;']&quot;; return ret; } static std::vector&lt;TreeNode&gt; parse( std::vector&lt;TreeNode&gt; input); // See &quot;parser.cpp&quot; for the implementation. static std::vector&lt;TreeNode&gt; parseExpression( std::vector&lt;TreeNode&gt; input); // Made public for debugging purposes. std::string getLispExpression() { // Again, for debugging purposes (and maybe, some day, I // will want to compile my language to Lisp). if (children.size() == 0) return text; std::string LispExpression = &quot;(&quot; + ((text.back() == '(' or text.back() == '[') ? (text.substr(0, text.size() - 1)) : (text)) + &quot; &quot;; for (unsigned int i = 0; i &lt; children.size(); i++) if (i == children.size() - 1) LispExpression += children[i].getLispExpression() + &quot;)&quot;; else LispExpression += children[i].getLispExpression() + &quot; &quot;; return LispExpression; } int interpretAsACompileTimeConstant() { if (std::regex_match(text, std::regex(&quot;^\\d+$&quot;))) return std::stoi(text); if (text == &quot;+&quot;) return children[0].interpretAsACompileTimeConstant() + children[1].interpretAsACompileTimeConstant(); if (text == &quot;-&quot;) return children[0].interpretAsACompileTimeConstant() - children[1].interpretAsACompileTimeConstant(); if (text == &quot;*&quot;) return children[0].interpretAsACompileTimeConstant() * children[1].interpretAsACompileTimeConstant(); if (text == &quot;/&quot;) return children[0].interpretAsACompileTimeConstant() / children[1].interpretAsACompileTimeConstant(); if (text == &quot;?:&quot;) return children[0].interpretAsACompileTimeConstant() ? children[1].interpretAsACompileTimeConstant() : children[2].interpretAsACompileTimeConstant(); if (text == &quot;mod(&quot;) return children[0].interpretAsACompileTimeConstant() % children[1].interpretAsACompileTimeConstant(); if (text == &quot;&lt;&quot;) return children[0].interpretAsACompileTimeConstant() &lt; children[1].interpretAsACompileTimeConstant(); if (text == &quot;&gt;&quot;) return children[0].interpretAsACompileTimeConstant() &gt; children[1].interpretAsACompileTimeConstant(); if (text == &quot;=&quot;) return children[0].interpretAsACompileTimeConstant() == children[1].interpretAsACompileTimeConstant(); std::cerr &lt;&lt; &quot;Line &quot; &lt;&lt; lineNumber &lt;&lt; &quot;, Column &quot; &lt;&lt; columnNumber &lt;&lt; &quot;, Interpreter error: \&quot;&quot; &lt;&lt; text &lt;&lt; &quot;\&quot; isn't a valid token in a compile-time integer constant.&quot; &lt;&lt; std::endl; return 0; } static std::vector&lt;TreeNode&gt; parseVariableDeclaration(std::vector&lt;TreeNode&gt; input); }; <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T05:02:42.307", "Id": "483427", "Score": "3", "body": "Can you include a description of your programming language? [Searching for \"AEC\" on Esolangs](https://esolangs.org/w/index.php?search=AEC&title=Special%3ASearch&profile=default&fulltext=1) returns nothing for me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T14:06:19.200", "Id": "483449", "Score": "0", "body": "@L.F. Why would it be an esolang? It's a BASIC-like programming language, just without a GOTO statement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-27T14:34:07.960", "Id": "483451", "Score": "0", "body": "I don't know where to go, so I went to esolang. Do you have a more detailed specification of AEC beyond \"BASIC-like\"? cuz that would probably help reviewers greatly." } ]
[ { "body": "<p>Here are a number of things that may help you improve your code.</p>\n<h2>Separate interface from implementation</h2>\n<p>It makes the code somewhat longer for a code review, but it's often very useful to separate the interface from the implementation. In C++, this is usually done by putting the interface into separate <code>.h</code> files and the corresponding implementation into <code>.cpp</code> files. It helps users (or reviewers) of the code see and understand the interface and hides implementation details. The other important reason is that you might have multiple source files including the <code>.h</code> file but only one instance of the corresponding <code>.cpp</code> file. In other words, split your existing <code>.cpp</code> file into a <code>.h</code> file and a <code>.cpp</code> file. The current code <code>#include</code>s <code>.cpp</code> files which is incorrect and leads to problems.</p>\n<h2>Use include guards</h2>\n<p>There should be an include guard in each <code>.h</code> file. That is, start the file with:</p>\n<pre><code>#ifndef TREENODE_H\n#define TREENODE_H\n// file contents go here\n#endif // TREENODE_H\n</code></pre>\n<p>The use of <code>#pragma once</code> is a common extension, but it's not in the standard and thus represents at least a potential portability problem. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#sf8-use-include-guards-for-all-h-files\" rel=\"nofollow noreferrer\">SF.8</a> Also, it should never go in a <code>.cpp</code> file per the advice above.</p>\n<h2>Omit unused variables</h2>\n<p>Because <code>argc</code> and <code>argv</code> are unused, you could use the alternative form of <code>main</code>:</p>\n<pre><code>int main ()\n</code></pre>\n<h2>Don't use <code>std::endl</code> when '\\n' will do</h2>\n<p>Using <code>std::endl</code> emits a <code>\\n</code> and flushes the stream. Unless you really need the stream flushed, you can improve the performance of the code by simply emitting <code>'\\n'</code> instead of using the potentially more computationally costly <code>std::endl</code>.</p>\n<h2>Use <code>const</code> where practical</h2>\n<p>I would not expect the <code>tokenize</code> or <code>JSONifyArrayOfTokens</code> routines to alter the data structures passed to them and indeed they do not. You should make this expectation explicit by using the <code>const</code> keyword:</p>\n<pre><code>static std::vector&lt;TreeNode&gt; tokenize(const std::string&amp; input);\nstatic std::string JSONifyArrayOfTokens(const std::vector&lt;TreeNode&gt;&amp; tokenizedString);\n</code></pre>\n<p>Similarly, the <code>interpretAsACompileTimeConstant()</code> function does not alter the underlying object, so it should also be declared <code>const</code>. The syntax is a little different for this:</p>\n<pre><code>int interpretAsACompileTimeConstant() const;\n</code></pre>\n<p>Not only will the code become more robust, but it will also likely run faster because it can avoid making temporary copies.</p>\n<h2>Improve your constructors</h2>\n<p>The <code>TreeNode</code> class has this constructor:</p>\n<pre><code>TreeNode::TreeNode(std::string newText, int newLine, int newColumn) {\n *this = TreeNode(); // For some weird reason, just &quot;TreeNode()&quot; won't do the\n // trick.\n text = newText;\n lineNumber = newLine;\n columnNumber = newColumn;\n}\n</code></pre>\n<p>A more modern style for your constructor might be this:</p>\n<pre><code>TreeNode::TreeNode(std::string newText, int newLine, int newColumn) :\n text{newText},\n lineNumber{newLine},\n columnNumber{newColumn}\n{}\n</code></pre>\n<p>The <code>basicDataTypeSizes</code> and <code>children</code> member elements will automatically be initialized to empty containers.</p>\n<h2>Use &quot;range <code>for</code>&quot; and simplify your code</h2>\n<p>Having test code is good, both for you to make sure your code works, and also for reviewers to better understand what you intend. However, these tests could be simplfied a great deal. Here's one of the tests as it exists now, complete with the <code>tests</code> definition:</p>\n<pre><code>struct test { \n std::string input, expectedResult;\n};\n\nvoid tokenizerTests() {\n std::vector&lt;test&gt; tests(\n {{&quot;\\&quot;/*Comment inside a string*/\\&quot;&quot;,\n &quot;['\\&quot;/*Comment inside a string*/\\&quot;']&quot;},\n {&quot;5+5&quot;, &quot;['5','+','5']&quot;},\n {&quot;5+5=10&quot;, &quot;['5','+','5','=','10']&quot;},\n {&quot;structureName.structureMember/3.14159265359&quot;,\n &quot;['structureName','.','structureMember','/','3.14159265359']&quot;},\n {&quot;sin(pi/2)=1&quot;, &quot;['sin(','pi','/','2',')','=','1']&quot;},\n {&quot;'A'+2='C'&quot;, &quot;['65','+','2','=','67']&quot;},\n {&quot;a:=a+1; //Some random comment.\\nb:=b-1;&quot;,\n &quot;['a',':=','a','+','1',';','b',':=','b','-','1',';']&quot;},\n {&quot;/*This should be tokenized into\\nan empty string*/&quot;, &quot;[]&quot;},\n {&quot;a/*Randomly\\ninserted\\ncomment.*/+/*Another\\nrandom\\ncomment*/b&quot;,\n &quot;['a','+','b']&quot;},\n {&quot;array_name:={1,1+1,1+1+1}&quot;, &quot;['array_name',':=','{','1',',','1','+','&quot;\n &quot;1',',','1','+','1','+','1','}']&quot;}});\n for (unsigned int i = 0; i &lt; tests.size(); i++) {\n std::string result =\n TreeNode::JSONifyArrayOfTokens(TreeNode::tokenize(tests[i].input));\n if (result != tests[i].expectedResult) {\n std::cerr &lt;&lt; &quot;Internal compiler error: Tokenizer test failed: \\&quot;&quot;\n &lt;&lt; tests[i].input &lt;&lt; &quot;\\&quot; tokenizes into \\&quot;&quot; &lt;&lt; result\n &lt;&lt; &quot;\\&quot; instead of to \\&quot;&quot; &lt;&lt; tests[i].expectedResult &lt;&lt; &quot;\\&quot;!&quot;\n &lt;&lt; std::endl;\n std::exit(1);\n }\n }\n}\n</code></pre>\n<p>There are a number of ways this could be improved. First, you could use the C++11 &quot;range <code>for</code>&quot; for the loop:</p>\n<pre><code>for (const auto&amp; thisTest : tests) {\n std::string result =\n TreeNode::JSONifyArrayOfTokens(TreeNode::tokenize(thisTest.input));\n if (result != thisTest.expectedResult) {\n std::cerr &lt;&lt; &quot;Internal compiler error: Tokenizer test failed: \\&quot;&quot;\n &lt;&lt; thisTest.input &lt;&lt; &quot;\\&quot; tokenizes into \\&quot;&quot; &lt;&lt; result\n &lt;&lt; &quot;\\&quot; instead of to \\&quot;&quot; &lt;&lt; thisTest.expectedResult &lt;&lt; &quot;\\&quot;!&quot;\n &lt;&lt; std::endl;\n std::exit(1);\n }\n}\n</code></pre>\n<p>If you're using a C++17 compiler, the code can be even nicer:</p>\n<pre><code>for (const auto&amp; [input, expected] : tests) {\n std::string result = TreeNode::JSONifyArrayOfTokens(TreeNode::tokenize(input));\n if (result != expected) {\n std::cerr &lt;&lt; &quot;Internal compiler error: Tokenizer test failed: \\&quot;&quot;\n &lt;&lt; input &lt;&lt; &quot;\\&quot; tokenizes into \\&quot;&quot; &lt;&lt; result\n &lt;&lt; &quot;\\&quot; instead of to \\&quot;&quot; &lt;&lt; expected &lt;&lt; &quot;\\&quot;!&quot;\n &lt;&lt; std::endl;\n std::exit(1);\n }\n}\n</code></pre>\n<h2>Don't Repeat Yourself (DRY)</h2>\n<p>The tests are all doing the same thing. That is, they apply some transformation to the input code and verify that the output is what was expected. Rather than repeating that same code multiple times, better would be to consolidate it into a single location:</p>\n<pre><code>class TestCollection {\n std::string name;\n std::string (*func)(const std::string&amp;);\n struct test {\n std::string input; \n std::string expectedResult;\n };\n std::vector&lt;test&gt; tests;\npublic:\n TestCollection(std::string name, std::string (*func)(const std::string&amp;), std::vector&lt;test&gt; tests) : name{name}, func{func}, tests{tests} {}\n bool operator()() const {\n bool result{true};\n for (const auto&amp; [input, expected] : tests) {\n std::string result = func(input);\n if (result != expected) {\n result = false;\n std::cerr &lt;&lt; &quot;Internal compiler error: &quot; &lt;&lt; name &lt;&lt; &quot; failed: \\&quot;&quot;\n &lt;&lt; &quot;with input \\&quot;&quot; &lt;&lt; input \n &lt;&lt; &quot;\\&quot;, expected \\&quot;&quot; &lt;&lt; expected &lt;&lt; &quot;\\&quot; but got \\&quot;&quot; &lt;&lt; result &lt;&lt; &quot;\\&quot;!\\n&quot;;\n }\n }\n return result;\n }\n};\n</code></pre>\n<p>Using this, the tests each become data structures:</p>\n<pre><code>TestCollection parsingVariableDeclarationsTests{&quot;Variable declarations parser test&quot;,\n [](const std::string&amp; input) -&gt; std::string { \n return TreeNode::parseVariableDeclaration( TreeNode::tokenize(input))[0]\n .getLispExpression();\n },\n {{&quot;Integer32 some_array[80*23],array_width:=80,array_height:=23&quot;,\n &quot;(Integer32 (some_array (* 80 23)) (array_width (:= 80)) (array_height &quot;\n &quot;(:= 23)))&quot;}}\n};\n</code></pre>\n<p>The overall test function then becomes:</p>\n<pre><code>bool runTests() {\n return tokenizerTests() \n &amp;&amp; simpleParserTests() \n &amp;&amp; interpreterTests() \n &amp;&amp; parsingVariableDeclarationsTests()\n &amp;&amp; parserTests();\n}\n</code></pre>\n<p>Note also that the function returns a boolean value instead of calling <code>exit(1)</code>.</p>\n<h2>Make data members <code>private</code></h2>\n<p>None of the data members of the <code>TreeNode</code> class need to be public, so they ought to be made private.</p>\n<h2>Avoid the use of iso646 keywords</h2>\n<p>The alternate keywords <code>&quot;or&quot;</code>, <code>&quot;and&quot;</code>, etc. still exist in C++, but you should probably not use them. Instead use <code>||</code> and <code>&amp;&amp;</code>. See <a href=\"https://codereview.stackexchange.com/questions/68018/bfs-shortest-path-program/68071#68071\">BFS shortest path program</a> for more detail.</p>\n<h2>Write efficient code</h2>\n<p>I was surprised by how slowly this code ran until I looked more closely. Here's just one clause from the tokenizer:</p>\n<pre><code>} else if (regex_match(input.substr(i, 1), regex(&quot;\\\\d|[a-z]|[A-Z]|_&quot;)) and\n regex_match(\n tokenizedExpression.back().text,\n regex(&quot;(^(\\\\d|_|[a-z]|[A-Z])*$)|(^(\\\\d|_|[a-z]|[A-Z])+\\\\.(&quot;\n &quot;\\\\d|_|[a-z]|[A-Z])*$)&quot;)) and\n !areWeInAString and !areWeInAComment) // Names and numbers\n{\n currentColumn++;\n tokenizedExpression.back().text += input[i];\n} \n</code></pre>\n<p>There is a lot going on here, and most of it is extremely inefficient. First, all four of the clauses in the <code>if</code> have to be true to execute the lines below. However, the simple boolean value comparisons are much faster to execute than the <code>regex_match</code> functions. For that reason, it would likely be more efficient to reorder them so that the &quot;cheap&quot; tests are done first.</p>\n<p>Next, let's look at each <code>regex_match</code> individually. The first inefficiency is that a temporary string is created via <code>input.substr(i, 1)</code>. That requires a memory allocation and subsequent deallocation all to simply get a single character. The next inefficiency is that a dynamic regex is created (and destroyed) each time. Third, using a <code>regex</code> for a single character is almost never an efficient solution. So let's rewrite the first clause:</p>\n<pre><code>(std::isalnum(input[i]) || input[i] == '_')\n</code></pre>\n<p>The next clause is this:</p>\n<pre><code>regex_match(tokenizedExpression.back().text,\n regex(&quot;(^(\\\\d|_|[a-z]|[A-Z])*$)|(^(\\\\d|_|[a-z]|[A-Z])+\\\\.(&quot;\n &quot;\\\\d|_|[a-z]|[A-Z])*$)&quot;)) \n</code></pre>\n<p>This is looking at the last word in the tree to decide if it might be an identifier. This complex regex is created and destroyed for every call and that last word is rescanned anew for every character in the input string. That's very inefficient! A better way to do it would be to keep track of the last token's type and simply check that. If it could be an identifier, for instance if we had scanned the &quot;Inte&quot; portion of &quot;Integer32&quot; then it still could be an identifier after we add the qualified character. In other words, just as with the booleans <code>areWeInAString</code> and <code>areWeInAComment</code>, you could keep a boolean <code>inId</code> and rewrite the entire <code>if</code> clause like this:</p>\n<pre><code> } else if (!areWeInAString \n &amp;&amp; !areWeInAComment \n &amp;&amp; (std::isalnum(input[i]) || input[i] == '_')\n &amp;&amp; (inId || (tokenizedExpression.back().text.size() == 0)))\n {\n</code></pre>\n<p>Doing so on my machine drops the execution time from 2.520 seconds to 0.544 seconds, for a 5x speedup.</p>\n<h2>Rethink the approach</h2>\n<p>Tokenizing like this is often much better done via a <em>state machine</em>. See <a href=\"https://codereview.stackexchange.com/questions/171863/overhauled-tokenizer-for-markargs/172391#172391\">this answer</a> for an example of how this can be done. A state machine makes the code neater and easier to reason about as well as much faster than using regex in many cases.</p>\n<h2>Summary</h2>\n<p>I haven't had time to go through the parser, but this should give you plenty to work on for now. C++ is indeed a very useful and efficient language, but it requires some expertise to use it effectively. I'd recommend <a href=\"https://www.stroustrup.com/Tour.html\" rel=\"nofollow noreferrer\">this book</a> if you haven't already studied the language much.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-29T20:32:58.970", "Id": "246199", "ParentId": "246056", "Score": "2" } } ]
{ "AcceptedAnswerId": "246199", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-07-26T21:34:27.103", "Id": "246056", "Score": "3", "Tags": [ "c++", "object-oriented", "parsing" ], "Title": "Parser for AEC in C++" }
246056