body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I came up with the following code by following <a href="https://www.coursera.org/learn/algorithms-part2/lecture/KMCRd/kruskals-algorithm" rel="nofollow noreferrer">Prof. Sedgewick's lecture on Coursera</a>. </p> <p>Please review this code and let me know if there is anything that I got wrong in implementing Kruskal's algorithm. I'd also like to know what is Big-O complexity of this algorithm.</p> <pre><code>import java.util.ArrayDeque; import java.util.PriorityQueue; import java.util.Queue; public class KruskalMST { private class WeightedEdge { public int from, to, weight; public WeightedEdge(int from, int to, int weight) { this.from = from; this.to = to; this.weight = weight; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("From --&gt; "); sb.append(from+1); sb.append(", to --&gt; "); sb.append(to+1); sb.append(", weight --&gt; "); sb.append(weight); return sb.toString(); } } private class UnionFind { private int capacity; private int[] arr; private int[] size; public UnionFind(int capacity) { this.capacity = capacity; this.arr = new int[capacity]; this.size = new int[capacity]; for(int i=0; i &lt; capacity; i++) { this.arr[i] = i; this.size[i] = 1; } } private int root(int i) { while(i != arr[i]) { i = arr[arr[i]]; } return i; } public void union(int i, int j) { int p = root(i); int q = root(j); if(p != q) { if(this.size[p] &lt;= this.size[q]) { this.size[q] += this.size[p]; this.arr[p] = q; } else { this.arr[q] = p; this.size[p] += this.size[q]; } } } public boolean connected(int i, int j) { int p = root(i); int q = root(j); return p == q; } } public Queue&lt;WeightedEdge&gt; findMinCostConnectionToAllCities(int[][] roadNetwork) { int n = roadNetwork.length; PriorityQueue&lt;WeightedEdge&gt; pq = new PriorityQueue&lt;WeightedEdge&gt;(2*n,(WeightedEdge e1, WeightedEdge e2) -&gt; { return e1.weight - e2.weight; }); Queue&lt;WeightedEdge&gt; mst = new ArrayDeque&lt;&gt;(); UnionFind uf = new UnionFind(n); for(int i=0; i &lt; n; i++) { for(int j=0; j &lt; n; j++) { if(i != j &amp;&amp; roadNetwork[i][j] &gt; 0) { WeightedEdge edge = new WeightedEdge(i,j,roadNetwork[i][j]); pq.add(edge); } } } while(!pq.isEmpty() &amp;&amp; mst.size() &lt; n-1) { WeightedEdge edge = pq.remove(); if(!uf.connected(edge.from, edge.to)) { uf.union(edge.from,edge.to); mst.add(edge); } } return mst; } public static void main (String[] args) { int[][] city1 = {{0, 1, 2, 3, 4}, {1, 0, 5, 0, 7}, {2, 5, 0, 6, 0}, {3, 0, 6, 0, 0}, {4, 7, 0, 0, 0}}; int[][] city2 = {{0, 1, 1, 100, 0, 0}, {1, 0, 1, 0, 0, 0}, {1, 1, 0, 0, 0, 0}, {100, 0, 0, 0, 2, 2}, {0, 0, 0, 2, 0, 2}, {0, 0, 0, 2, 2, 0}}; KruskalMST kruskal = new KruskalMST(); Queue&lt;WeightedEdge&gt; mst = kruskal.findMinCostConnectionToAllCities(city2); int totalCost = 0; for(WeightedEdge edge: mst) { totalCost += edge.weight; System.out.println(edge.toString()); } System.out.println("Total cost --&gt; " + totalCost); } } </code></pre>
[]
[ { "body": "<h1>General</h1>\n\n<p>This should probably be three separate classes, unless there's some compelling reason you haven't shared to wrap <code>WeightedEdge</code> and <code>UnionFind</code> inside <code>KruskalMST</code>. If they must be internal, they should be <code>static</code> because they don't rely on context from <code>KruskalMST</code>.</p>\n\n<p>You should use <code>final</code> to indicate classes are not designed for extension and that properties will not change after their initial assignment. This reduces cognitive load on the reader and gives hints to the compiler.</p>\n\n<p>In idiomatic Java, we only declare one variable per line, even if they share a type.</p>\n\n<p>In idiomatic Java, put whitespace between a control flow keyword (<code>for</code>, <code>while</code> and the opening <code>{</code>.</p>\n\n<p>In idomatic Java, <code>else {</code> belongs on the same line as <code>}</code>, not a newline.</p>\n\n<p>It's preferred to include whitespace on both sides of binary operations (<code>+</code>, <code>-</code>, etc).</p>\n\n<p>It's preferred to have whitespace after a <code>,</code>. Please be consistent.</p>\n\n<p>Don't use abbreviations when naming variables. It makes it harder for readers to understand your code. In general, good names are very helpful for increasing readability.</p>\n\n<p>Methods that return a boolean variable typically begin with a predicate such as <code>is</code> or <code>has</code>. In the case of <code>connected</code>, it's arguable whether <code>isConnected</code> (gramatically incorrect, but standard predicate) is preferable to <code>areConnected</code> (gramatically correct, but unusual predicate). I would argue that both\n are preferable to <code>connected</code>, which only loosely suggests it returns a <code>boolean</code> value.</p>\n\n<h1>WeightedEdge</h1>\n\n<p>Member variables should be private unless you have a compelling reason to expose them. This allows your class to control its internal representation of properties without breaking clients if it changes. Use accessor methods to allow clients access the the information. In this case, given that the values are primitives and the class is immutable (its state will not change after object creation), it's not terrible to expose them. However, you definitely should make the values final. Classes should control their own internals.</p>\n\n<p>Since you have a known need for a comparator by weight, it would be cleaner to expose it on WeightedEdge rather than force clients to create it.</p>\n\n<h1>UnionFind</h1>\n\n<p><code>capacity</code> is unused outside the constructor and does not need to be stored as an instance variable.</p>\n\n<p>It's typically considered a poor practice to reassign method parameter variables.</p>\n\n<p>We can gain readability at the cost of some performance by letting <code>union()</code> use <code>connected()</code>. This is often an excellent tradeoff, but varies on a case-by-case basis.</p>\n\n<p>A guard clause might make <code>union</code> a bit easier to read.</p>\n\n<p><code>connected</code> can be simplified to a single line.</p>\n\n<h1>Kruskal MST</h1>\n\n<p>Your comparator can overflow or underflow for extreme values. Presumably this isn't an issue in your case, but it's something to be aware of. Using <code>Integer.compare(int, int)</code> would be preferable.</p>\n\n<p>You can reduce the number of loop iterations in half by adding both edge directions at the same time.</p>\n\n<p>If you made all these changes, your code might look something like:</p>\n\n<pre><code>import java.util.ArrayDeque;\nimport java.util.PriorityQueue;\nimport java.util.Queue;\n\npublic final class KruskalMST {\n\n public Queue&lt;WeightedEdge&gt; findMinimumCostConnectionToAllCities(final int[][] roadNetwork) {\n\n final int n = roadNetwork.length;\n final PriorityQueue&lt;WeightedEdge&gt; edges =\n new PriorityQueue&lt;WeightedEdge&gt;(2 * n, WeightedEdge.WEIGHT_DESCENDING_ORDER);\n\n final Queue&lt;WeightedEdge&gt; minimumSpanningTree = new ArrayDeque&lt;&gt;();\n final UnionFind unionFind = new UnionFind(n);\n\n for (int i = 0; i &lt; n; i++) {\n for (int j = i; j &lt; n; j++) {\n if (roadNetwork[i][j] &gt; 0) {\n edges.add(new WeightedEdge(i, j, roadNetwork[i][j]));\n }\n if (roadNetwork[j][i] &gt; 0) {\n edges.add(new WeightedEdge(j, i, roadNetwork[j][i]));\n }\n }\n }\n\n while (!edges.isEmpty() &amp;&amp; minimumSpanningTree.size() &lt; n - 1) {\n final WeightedEdge edge = edges.remove();\n if (!unionFind.areConnected(edge.from, edge.to)) {\n unionFind.union(edge.from, edge.to);\n minimumSpanningTree.add(edge);\n }\n }\n\n return minimumSpanningTree;\n\n }\n\n public static void main(final String[] args) {\n final int[][] city1 = {\n {0, 1, 2, 3, 4},\n {1, 0, 5, 0, 7},\n {2, 5, 0, 6, 0},\n {3, 0, 6, 0, 0},\n {4, 7, 0, 0, 0}};\n\n final int[][] city2 = {\n {0, 1, 1, 100, 0, 0},\n {1, 0, 1, 0, 0, 0},\n {1, 1, 0, 0, 0, 0},\n {100, 0, 0, 0, 2, 2},\n {0, 0, 0, 2, 0, 2},\n {0, 0, 0, 2, 2, 0}};\n\n final KruskalMST kruskal = new KruskalMST();\n final Queue&lt;WeightedEdge&gt; minimumSpanningTree = kruskal.findMinimumCostConnectionToAllCities(city2);\n\n int totalCost = 0;\n for (final WeightedEdge edge: minimumSpanningTree) {\n totalCost += edge.weight;\n System.out.println(edge.toString());\n }\n System.out.println(\"Total cost --&gt; \" + totalCost);\n }\n\n}\n</code></pre>\n\n<hr/>\n\n<pre><code>import java.util.Comparator;\n\nfinal class WeightedEdge {\n\n /** Sorts edges from greatest weight to least weight. */\n public static final Comparator&lt;WeightedEdge&gt; WEIGHT_DESCENDING_ORDER = \n (final WeightedEdge e1, final WeightedEdge e2) -&gt; Integer.compare(e1.weight, e2.weight);\n\n public final int from;\n public final int to;\n public final int weight;\n\n public WeightedEdge(final int from, final int to, final int weight) {\n this.from = from;\n this.to = to;\n this.weight = weight;\n }\n\n @Override\n public String toString() {\n final StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(\"From --&gt; \");\n stringBuilder.append(from + 1);\n stringBuilder.append(\", to --&gt; \");\n stringBuilder.append(to + 1);\n stringBuilder.append(\", weight --&gt; \");\n stringBuilder.append(weight);\n return stringBuilder.toString();\n }\n}\n</code></pre>\n\n<hr/>\n\n<pre><code>final class UnionFind {\n\n private final int[] arr;\n private final int[] size;\n\n public UnionFind(final int capacity) {\n this.arr = new int[capacity];\n this.size = new int[capacity];\n\n for (int i = 0; i &lt; capacity; i++) {\n this.arr[i] = i;\n this.size[i] = 1;\n }\n }\n\n public void union(final int i, final int j) {\n if (areConnected(i, j)) {\n return;\n }\n\n final int rootOfI = rootOf(i);\n final int rootOfJ = rootOf(j);\n\n if (this.size[rootOfI] &lt;= this.size[rootOfJ]) {\n this.size[rootOfJ] += this.size[rootOfI];\n this.arr[rootOfI] = rootOfJ;\n } else {\n this.arr[rootOfJ] = rootOfI;\n this.size[rootOfI] += this.size[rootOfJ];\n }\n }\n\n public boolean areConnected(final int i, final int j) {\n return rootOf(i) == rootOf(j);\n }\n\n\n private int rootOf(final int i) {\n int parent = i;\n while (parent != arr[parent]) {\n parent = arr[arr[parent]];\n }\n return parent;\n }\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T16:33:33.993", "Id": "433398", "Score": "0", "body": "Thank you so much! This is the best code review I have had so far. The review details are instructive and these are somethings I will watch out for going forward. I have a quick Question: In the context of Kruskal MST, it is better if I make `WeightedEdge` class implement `Comparable` interface to naturally sort edges by weight?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T18:04:14.953", "Id": "433404", "Score": "1", "body": "@BhanuprakashD If there's a natural ordering for the object, then implementing `Comparable` is reasonable. But what if somebody wants to order a collection fo `WeightedEdge`s by their source or destination node? Easy to add another static `Comparator`, but you can only implement `Comparable` once." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T18:06:08.740", "Id": "433405", "Score": "1", "body": "You might also want to give a little more time before accepting this answer. Sometimes it takes folks a couple of days to get a review written, and the US just had a major holiday yesterday. You discourage other answers by accepting quickly, and it's only been 20 hours since you posted your question." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T16:23:34.153", "Id": "223576", "ParentId": "223529", "Score": "3" } } ]
{ "AcceptedAnswerId": "223576", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-04T21:23:04.980", "Id": "223529", "Score": "2", "Tags": [ "java", "algorithm", "graph", "complexity", "union-find" ], "Title": "Kruskal MST algorithm" }
223529
<p>Create a user class with id, name, age. Write a function to get users older than age 20. Group all users with same age and increment users age by 3 Is there a cleaner way to write this? Any comments are appreciated.</p> <pre><code>const userList=[]; const userAboveTwenty= []; class User { constructor(name,id,age){ this.name=name; this.id=id; this.age=age; } addUser(user){ userList.push(user); } getUserListAboveTwenty(list){ userAboveTwenty.push(...list.filter(x=&gt;x.age&gt;20)); } addAge(user){ return user.age = user.age+3; } } let user1 = new User('user1',1,12); let user2 = new User('user2',2,18); let user3 = new User('user3',3,21); let user4 = new User('user4',4,22); user1.addUser(user1); user2.addUser(user2); user3.addUser(user3); user4.addUser(user4); user1.addAge(user1); user1.getUserListAboveTwenty(userList); user1.addAge(user1); <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T11:06:44.367", "Id": "433356", "Score": "0", "body": "Sure. I am fairly new to this. Will add beginner tag moving forward.\nThanks" } ]
[ { "body": "<p>Your <code>User</code> class should only be dealing with things about that user, not about how you store it in a list. You are also referring to a variable outside your class, so you are locked to this, which makes it less reusable, which is one of points of classes in the first place. So get rid of <code>addUser</code> and <code>getUserListAboveTwenty</code> from your class.</p>\n\n<p>You don't need to pass the user to your functions, you can access it with <code>this</code>, like you've done in the constructor. You can also make your <code>addAge</code> function more general by adding age based on a parameter.</p>\n\n<pre><code>addAge(age){\n this.age += age;\n}\n</code></pre>\n\n<p>If you just need to store your users in a list, an array is just fine. But if you want more functionality you could make a UserList class.</p>\n\n<pre><code>class UserList {\n constructor(users = []) {\n this.list = users;\n }\n\n addUser(user) {\n this.list.push(user);\n }\n\n getUserById(id) {\n return this.list.find(user =&gt; user.id == id);\n }\n\n getUsersAboveTwenty() {\n return new UserList(this.list.filter(user =&gt; user.age &gt; 20));\n }\n}\n</code></pre>\n\n<p>I've added an additional function to return a user from an id. I also made <code>getUsersAboveTwenty</code> return a new UserList. You can add more if you need it (A way to add more users at the same time would be useful). Full code:</p>\n\n<pre><code>class User {\n constructor(name, id, age) {\n this.name = name;\n this.id = id;\n this.age = age;\n }\n\n addAge(age){\n this.age += age;\n }\n}\n\nclass UserList {\n constructor(users = []) {\n this.list = users;\n }\n\n addUser(user) {\n this.list.push(user);\n }\n\n getUserById(id) {\n return this.list.find(user =&gt; user.id == id);\n }\n\n getUsersAboveTwenty() {\n return new UserList(this.list.filter(user =&gt; user.age &gt; 20));\n }\n}\n\nlet userList = new UserList();\n\nuserList.addUser(new User('user1',1,12));\nuserList.addUser(new User('user2',2,18));\nuserList.addUser(new User('user3',3,21));\nuserList.addUser(new User('user4',4,22));\n\nuserList.getUserById(1).addAge(3);\nuserList.getUsersAboveTwenty();\nuserList.getUserById(1).addAge(3);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T11:11:50.837", "Id": "433359", "Score": "0", "body": "Thank you. This was helpful." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T09:24:19.590", "Id": "223556", "ParentId": "223532", "Score": "3" } }, { "body": "<h2>Consider a functional approach</h2>\n\n<p>I have been coding Java for a long time before I started with Javascript so I understand the urge to write Object Oriented code, create classes etc. However, why don't you try a functional approach for a change. I bet that once you get the hang of it, you will not want to go back. I know I don't.</p>\n\n<p>Javascript already had some great functional features, but since we got arrow functions it's just become a dream. Just look how much boilerplate we can get rid of once we accept that <em>we don't need</em> user objects to be an instance of some class. In fact, them being just plain objects is a big plus. It makes them easily serializable, To JSON for example.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const users = [];\n\nconst byId = (id) =&gt; (user) =&gt; user.id === id\nconst olderThan = (age) =&gt; (user) =&gt; user.age &gt; age\nconst makeOlder = (user, years) =&gt; user.age += years\n\nlet user1 = { name: 'user1', id: 1, age: 12 }\nlet user2 = { name: 'user2', id: 2, age: 18 }\nlet user3 = { name: 'user3', id: 3, age: 21 }\nlet user4 = { name: 'user4', id: 4, age: 22 }\n\nusers.push(\n user1, \n user2, \n user3, \n user4\n)\n\nconsole.info('users', users)\nconsole.info('id=2', users.filter(byId(2)))\n\nmakeOlder(user1, 3 /* years */)\nconsole.info('user1.age', user1.age)\n\nconst above20 = users.filter(olderThan(20))\nconsole.info('age&gt;20', above20)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Note about the above code that there is less of it, it's using almost only standard constructs (we are not introducing custom list classes etc) and it is in fact more readable. Also, you'll find it is <em>much</em> more reusable because we create small, separate functions that work on <em>any</em> object instead of big classes with many members.</p>\n\n<h2>You can do OO in Javascript</h2>\n\n<p>If you really want object oriented code, the language has enough to make you happy. Study how to do <a href=\"https://crockford.com/javascript/prototypal.html\" rel=\"nofollow noreferrer\">prototypal inheritance</a> and information hiding / <a href=\"https://crockford.com/javascript/private.html\" rel=\"nofollow noreferrer\">private members</a> by learning from one of the masters: Douglas Crockford.</p>\n\n<h2>You just don't need it</h2>\n\n<p>Then... once you've learned it all... liberate yourself from it and discover... You don't need it!</p>\n\n<p>For me, one of the biggest eye openers was how arrays are implemented in Javascript. Did you know, that all the Array methods need to do their work, is a <code>length</code> property? In fact, you can turn any object into an array-like object and have all array methods work, just by adding a length. Let me prove it to you:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var SuperArray = {} // omg, just a plain old object! \nSuperArray.length = 0 // surely, this won't work??\nSuperArray.push = Array.prototype.push // what?\nSuperArray.join = Array.prototype.join // are..you doing???\n\n// Done!\n// No way!\n// Way :)\n\nSuperArray.push('no way!')\nSuperArray.push('way!')\nSuperArray.push('Are you kidding me?')\nSuperArray.push('No i\\'m not.')\nSuperArray.push('You DO NOT NEED CLASSES in Javascript.')\nSuperArray.push('It\\'s way cooler than that!')\n\nconsole.info('SuperArray.length', SuperArray.length)\nconsole.info('SuperArray (joined)', SuperArray.join('\\n'))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>This for me is what is so incredibly cool (and powerful) about Javascript. Consider trying to figure out why and how this works. And maybe see if you can put it into practice.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T22:14:16.717", "Id": "433438", "Score": "0", "body": "Thanks for the comments. I am very comfortable with the functional approach. But when it comes to implementing the same using classes, it gets too confusing.Thanks for the link, the post seems promising." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T22:18:41.017", "Id": "433439", "Score": "0", "body": "In your code example, you are using ES6 classes. The important thing to understand about those is that they are *syntax sugar*. You can build those classes using ES5 and the prototype chain (in fact, behind the curtains, that's still what ES6 classes are doing) but it's cumbersome. But I feel trying to build a 'class' by hand using ES5 syntax only might help you learn how it works. Do you have experience with other OO languages, if you do not mind me asking?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T22:22:19.397", "Id": "433441", "Score": "0", "body": "Do you have experience with other OO languages, if you do not mind me asking --> I am in the process of learning it. Don't have prior experience with other languages." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T22:26:49.283", "Id": "433442", "Score": "0", "body": "@RamaM Ha, I guess in this case, that is a good thing. The way Javascript implements OO is different from other languages. I have a great deal of experience with Java which is a strong-typed OO language. But for me, OO is sort of 'over'. I have gotten to the point where I try to avoid it. Trying to build a class model is like making a folder tree. You will never decide whether it should be `CustomerX/Invoices/2019` or `Invoices/CustomerX/2019` or `2019/CustomerX/Invoices` or..." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T21:56:56.600", "Id": "223589", "ParentId": "223532", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-04T22:54:12.660", "Id": "223532", "Score": "2", "Tags": [ "javascript", "beginner", "object-oriented" ], "Title": "Create User Class" }
223532
<p>The program is a little code about guns with user input. The program is a perfect representation of the beauty of functions. What do you think of it?</p> <pre><code>import sys import time #determines reload time def reloading(reload_time): print('\nReloading', end='') for dot in range(reload_time): time.sleep(1) print('.', end='') #parameters including the numerator/denominator, fire rate, and reload speed def gun(ROUNDS, left, fire_rate, the_reload): print('\nshoot!') #hold enter rounds = ROUNDS print('\n{}/{}'.format(rounds, left)) while rounds &gt; 0 or left &gt; 0: shoot = input() rounds -= 1 #decrement each time input is given print('{}/{}'.format(rounds, left)) if rounds == 0 and left == 0: print('OUT OF AMMO') break elif shoot.upper() == 'DONE': sure = input('Are you sure?\n&gt; ') if sure.lower() == 'y': start() #allocates back to gun selection elif rounds == 0: if left &lt;= ROUNDS: reloading(the_reload) rounds += left left -= left print('\n{}/{}'.format(rounds, left)) #if bullets left is less than the magazine else: reloading(the_reload) rounds += ROUNDS left -= ROUNDS print('\n{}/{}'.format(rounds, left)) time.sleep(fire_rate) #fire rate def start(): firearm = input('CHOOSE YOUR GUN (ENTER to exit)\n&gt; ') if firearm.upper() == 'ASSAULT' or firearm.upper() == 'ASSUALT': gun(40, 130, 0.1, 7) elif firearm.upper() == 'SHOTGUN': gun(6, 30, 2, 12) elif firearm.upper() == 'SMG': gun(40, 200, 0, 5) elif firearm.upper() == 'SNIPER': gun(1, 15, 0, 5) elif firearm.upper() == 'MARKSMAN': gun(20, 100, 0.8, 9) elif firearm.upper() == 'PISTOL': gun(10, 100, 0.6, 3) else: sys.exit() start() </code></pre>
[]
[ { "body": "<p>Apart from that I don't quite get the point of your <em>game</em>, there are a few things that caught my eye:</p>\n\n<hr>\n\n<p><strong>1. User input</strong><br/>\nYour user input system is not particularly intuitive to use. Without the source code the user has virtually no way to see what inputs are acceptable at the moment or what your game does.</p>\n\n<p><strong>2. Documentation</strong><br/>\nYour functions are documented like this at the moment:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>#determines reload time\ndef reloading(reload_time):\n ...\n</code></pre>\n\n<p>Enter the official <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a> (aka PEP8)! There, the official recommendation on how to document function is to use <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\"><code>\"\"\"documentation strings\"\"\"</code></a> like so:</p>\n\n<pre><code>def reloading(reload_time):\n \"\"\"determines reload time\"\"\"\n ...\n</code></pre>\n\n<p>Documentation written in that style helps Python's built-in <code>help(...)</code> function as well as basically all Python IDEs to pick it up. Future-you, and depending on the path you choose also others, will thank you a lot if you learn this early and stick to it.</p>\n\n<p><strong>3. Start</strong><br/>\nThe general notes on user input apply here. But apart from that, there is also a lot of repeated code here. You call <code>firearm.upper()</code> on every branch of the <code>if</code> statement, when a simple <code>firearm = input('CHOOSE YOUR GUN (ENTER to exit)\\n&gt; ').upper()</code> could do that in one place.</p>\n\n<p>It's also common practice to wrap the code that is supposed to be run in a scripty-manner in <code>if __name__ == \"__main__\":</code>. This basically tells the Python interpreter (and also people looking at your code) that this part is meant to be run as script and is not part of the code that's eventually going to be imported into some other script. See also the <a href=\"https://docs.python.org/3/library/__main__.html\" rel=\"nofollow noreferrer\">official documentation</a> or <a href=\"https://stackoverflow.com/q/419163/5682996\">this Stack Overflow post</a> for further details.</p>\n\n<pre><code>if __name__ == \"__main__\":\n # This makes sure you game will not start if you ever import the file\n start()\n</code></pre>\n\n<p><code>sys.exit()</code> is also a bit uncommon here but we will touch on that in a moment.</p>\n\n<p><strong>4. Reloading</strong><br/>\nSlow reloading is quite a killer (pun intended). Especially if it looks like nothing is happening. When I did a test run with your game on my Windows laptop, nothing happened after <code>Reloading</code> appeared on the console until the \"loading\" actually finished. This was what I expected, since at least on Windows <code>print</code> does not automatically flush the buffer so you will see nothing in the reload cycle. Using <code>print('.', end='', flush=True)</code> fixes that.</p>\n\n<p><strong>5. Gun play</strong>\n<code>gun(...)</code> is were the \"fun\" starts. This is actually your main gameplay, so <code>gun</code> is likely not a really good name. Often methods have some kind of action description in their name like <code>fire_gun(...)</code> or something similar. Nouns like <code>gun</code> are usually only used for class names.</p>\n\n<p>Since we are alread nit-picking about names, let's look at the paramters:</p>\n\n<ul>\n<li><code>ROUNDS</code>: all uppercase names are <a href=\"https://www.python.org/dev/peps/pep-0008/#constants\" rel=\"nofollow noreferrer\">by convention usually reserved for global, odule, or class level constant values</a>. Here, the capitalization seems to be used to disambiguate the value from the internal variable <code>rounds</code>. But why not choose a name that seems more appropriate for what the value actually represents like <code>magazine_capacity</code>?</li>\n<li><code>left</code> is very generic here and leaves room for interpretation. <code>total_rounds</code> or <code>reserve_capacity</code> sound like more appropriate names in this context here.</li>\n<li><code>fire_rate</code> is in its own right actually quite okay, although the variable name contradicts the way you use it. A <em>rate</em> is usually defined as something per amount of time, like shots per seconds. In your case it's actually used the other way round as time between two shots. So consider changing either of them to fit the other.</li>\n<li><code>the_reload</code>: Why this name? Why not <code>time_to_reload</code>?</li>\n</ul>\n\n<p>Now that we have sorted this out, let's look at the control flow: On the top-most level you repeat the fire-till-empty-then-reload cycly until you are completely out of ammo. That's fine. There is a little bit of repeated code in <code>rounds == 0</code> where <code>print('\\n{}/{}'.format(rounds, total_rounds))</code> could be used just once outside the inner <code>if</code> statement</p>\n\n<pre><code>elif rounds == 0:\n if total_rounds &lt;= magazine_capacity:\n # if bullets left is less than the magazine\n ...\n else:\n ...\n print('\\n{}/{}'.format(rounds, total_rounds))\n</code></pre>\n\n<p>The first case with <code>if rounds == 0 and total_rounds == 0:</code> is also fine. With <code>elif shoot.upper() == 'DONE':</code> things start to get a little bit troubling. The code in this block is as follows:</p>\n\n<pre><code>elif shoot.upper() == 'DONE':\n sure = input('Are you sure?\\n&gt; ')\n if sure.lower() == 'y':\n start()\n</code></pre>\n\n<p>Since this basically has nothing to do with the gameplay, the code breaks the single responsibility principle which is often recommended when thinking about/designing functions. This a higher level gameplay element and should better be placed in <code>start()</code>. Doing this will also help you to get rid of the yet to surface error caused by exceeding the maximum recursion depth. You can get at that point if you get into that branch of the <code>if</code> statement over and over again, calling <code>start()</code>, which then in turn calls <code>gun(...)</code>, which then calls <code>start()</code> again, and so on and so forth, until the program crashes.</p>\n\n<p>So how to do this in a better way?</p>\n\n<pre><code>def fire_gun(magazine_capacity, reserve_capacity, fire_rate, time_to_reload):\n \"\"\"parameters including the numerator/denominator, fire rate, and reload speed\"\"\"\n\n ...\n\n while rounds &gt; 0 or reserve_capacity &gt; 0:\n shoot = input()\n\n rounds -= 1\n print('{}/{}'.format(rounds, reserve_capacity))\n\n if rounds == 0 and reserve_capacity == 0:\n print('OUT OF AMMO')\n break\n elif shoot.upper() == 'DONE':\n sure = input('Are you sure?\\n&gt; ')\n if sure.lower() == 'y':\n break\n elif rounds == 0:\n ...\n\n time.sleep(fire_rate) # Faster!!\n\n\ndef start():\n while True:\n firearm = input('CHOOSE YOUR GUN (ENTER to exit)\\n&gt; ').upper()\n\n if firearm == 'ASSAULT':\n fire_gun(40, 130, 0.1, 7)\n ...\n else:\n break\n</code></pre>\n\n<p>In this version there is no recursion and you come back to the \"weapons menu\" whenever you are out of ammo of the user chooses to quit before. No recursion, no recursion limit, no crash! Cool.</p>\n\n<p><strong>6. Comments</strong><br/>\nYou are using them wrong! Comments in source code are usually best used to explain <em>why</em> you are doing something, and not <em>what</em> you are doing, especially if it's quite obvious, like e.g.</p>\n\n<pre><code>rounds -= 1\n# decrement each time input is given\n</code></pre>\n\n<p>This is clear from the code. No need to waste a comment on this.</p>\n\n<p>Sometimes you have to do a little bit more to make a comment unnecessary, e.g. there at</p>\n\n<pre><code>if left &lt;= ROUNDS:\n ...\n #if bullets left is less than the magazine\n</code></pre>\n\n<p>If you stick to the naming recommendations from above this can become</p>\n\n<pre><code>if reserve_capacity &lt;= magazine_capacity:\n ...\n</code></pre>\n\n<p>See? No need for that comment any more! The code is now self-explaining.</p>\n\n<p>On a not-strictly Python-related note: you are the first person I get to know who somehow likes to stick their comments below the line they are commenting on. Most people I know (including me) would expect the comment to live on the line above or on the same line as the code that comments belongs to.</p>\n\n<hr>\n\n<p><strong>Advanced ideas</strong><br/></p>\n\n<p>You find that long <code>if</code> statement in <code>start()</code> cumbersome to read and hard to extend? You would like to extend your weapons locker with ease? You are willing to look into Python's magic box? Then read on.</p>\n\n<p>Often this kind of long <code>if</code> statement can be transformed into something that's easier to maintain and extend using a Python <a href=\"https://docs.python.org/3/library/stdtypes.html#dict\" rel=\"nofollow noreferrer\">dictionary</a>. It a so called <em>mapping</em>, which maps a <em>key</em> to a <em>value</em>.</p>\n\n<p>In your concrete example one could use something like this:</p>\n\n<pre><code>def start():\n guns = {\n \"ASSAULT\": lambda: fire_gun(40, 130, 0.1, 7),\n \"SHOTGUN\": lambda: fire_gun(6, 30, 2, 12),\n ... # much more guns here\n }\n\n while True:\n firearm = input('CHOOSE YOUR GUN (ENTER to exit)\\n&gt; ').upper()\n\n try:\n guns[firearm]()\n except KeyError:\n break\n</code></pre>\n\n<p>The gun names are used as keys of the dictionary, this is quite obvious. Depending on your Python knowledge, you might also know something about <a href=\"https://www.w3schools.com/python/python_lambda.asp\" rel=\"nofollow noreferrer\"><code>lambda</code></a> expressions as well. If not, think of them as functions or whatevere you like that can be \"called\", but without a explicit name. That's how <code>guns[firearm]()</code> works: For a given key, say <code>\"ASSAULT\", the dictionary returns a lambda expression like</code>lambda: fire_gun(40, 130, 0.1, 7)<code>in our example. You could also assign this to a variable like</code>parameterized_version_of_fire_gun = guns[firearm]<code>. You can think of</code>parameterized_version_of_fire_gun<code>as a function at that moment that you would call like you call</code>reloading`, for example. If it helps you can also think of it as a \"normal\" Python function:</p>\n\n<pre><code>def parameterized_version_of_fire_gun():\n fire_gun(40, 130, 0.1, 7)\n</code></pre>\n\n<p>So the next logical step is now to call <code>parameterized_version_of_fire_gun()</code> (← Note the opening and closing parenthesis).</p>\n\n<p>As a bonus, this version would allow you to print <code>guns.keys()</code> to easily show the user all the possibilites to choose from.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T00:41:56.340", "Id": "433899", "Score": "0", "body": "UPDATED [gist](https://gist.github.com/tyronewantedsmok/d180b38c0796a6ca71f6f4df7554404b)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T21:51:04.067", "Id": "223771", "ParentId": "223534", "Score": "2" } } ]
{ "AcceptedAnswerId": "223771", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T01:04:30.203", "Id": "223534", "Score": "2", "Tags": [ "python", "beginner", "battle-simulation" ], "Title": "Shooter game simulation" }
223534
<p>I recently cloned a classical Spider Solitaire game from Microsoft Windows XP. I implemented almost all features of the game. Please tell me anything I can do in order to improve my coding style. Other suggestions are welcome.</p> <p>The link to resources here: <a href="https://github.com/Marethyu12/JSpider/tree/a65d1253321c10cae2c3e7d484d15cf216d7558f" rel="nofollow noreferrer">https://github.com/Marethyu12/JSpider</a></p> <pre><code>import java.awt.Color; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Font; import java.awt.Graphics; import java.awt.Image; import java.awt.Insets; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Stack; import java.util.TreeMap; import java.util.stream.Collectors; import javax.imageio.ImageIO; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JEditorPane; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; /** * JSpider (version: 1.0) * By Jimmy Y. (June 25, 2019 to July 3, 2019) * * Problems: * - After multiple resizings of the component, it freezes to fixed size? * * TODO: * - Play game 10 times in a row to catch any potential bugs (make sure you say yes to the dialog for new game and try undo, restart, and newGame buttons) * - Animations? */ @SuppressWarnings("serial") public class JSpider extends JFrame implements ActionListener, ComponentListener, WindowListener { private int width = 1100; private int height = 700; private JMenuBar menuBar; private JMenu menu; private JMenuItem newGame; private JMenuItem restartGame; private JMenuItem undo; private JMenuItem deal; private JMenuItem changeDifficulty; private JMenuItem showStats; private JMenuItem toggleDebugMode; private JMenuItem howto; private JMenuItem about; private JMenuItem exit; private GameBoard board = null; private DataTracker tracker; private ImageIcon icon; private boolean debug; { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } } private JSpider() { super("JSpider"); setMinimumSize(new Dimension(width, height)); setLocationRelativeTo(null); menuBar = new JMenuBar(); menu = new JMenu("Menu"); newGame = new JMenuItem("New game"); restartGame = new JMenuItem("Restart current game"); undo = new JMenuItem("Undo"); deal = new JMenuItem("Deal!"); changeDifficulty = new JMenuItem("Change difficulty"); showStats = new JMenuItem("Show statistics"); toggleDebugMode = new JMenuItem("Enter debug mode"); howto = new JMenuItem("How to play?!?"); about = new JMenuItem("About JSpider"); exit = new JMenuItem("Exit window"); newGame.addActionListener(this); restartGame.addActionListener(this); undo.addActionListener(this); deal.addActionListener(this); changeDifficulty.addActionListener(this); showStats.addActionListener(this); toggleDebugMode.addActionListener(this); howto.addActionListener(this); about.addActionListener(this); exit.addActionListener(this); toggleDebugMode.setEnabled(false); menu.add(newGame); menu.add(restartGame); menu.add(undo); menu.add(deal); menu.add(changeDifficulty); menu.add(showStats); menu.add(toggleDebugMode); menu.add(howto); menu.add(about); menu.add(exit); menuBar.add(menu); setJMenuBar(menuBar); selectDifficulty(); setContentPane(board); board.setInsets(getInsets()); tracker = new DataTracker("stats.db"); icon = new ImageIcon(readImage("images\\icon.png")); setIconImage(icon.getImage()); setDefaultCloseOperation(EXIT_ON_CLOSE); setExtendedState(MAXIMIZED_BOTH); addComponentListener(this); addWindowListener(this); debug = false; } public static void main(String[] args) { EventQueue.invokeLater(() -&gt; { JSpider main = new JSpider(); main.setVisible(true); }); } private Image readImage(String fileName) { Image img = null; try { img = ImageIO.read(new File(fileName)); } catch (IOException ex) { ex.printStackTrace(); } return img; } private void selectDifficulty() { String[] difficulties = {"Easy", "Medium", "Hard"}; String choice = (String) JOptionPane.showInputDialog(this, "Select difficulty:", "New game", JOptionPane.QUESTION_MESSAGE, null, difficulties, difficulties[0]); if (board == null &amp;&amp; choice == null) { board = new GameBoard("Easy"); // if user does not select any (ie. he cancelled), then easy is defaulted at startup } else if (board == null &amp;&amp; choice != null) { board = new GameBoard(choice); } else if (choice != null) { board.clearCards(); board.loadImages(choice); board.newGame(); } // else if choice is null then do nothing } @Override public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if (source == newGame) { board.newGame(); int[] a = tracker.getData(board.getDifficulty()); a[3]++; } else if (source == restartGame) { board.resetGame(); } else if (source == undo) { if (board.canUndo()) { board.undo(); } } else if (source == deal) { board.deal(); } else if (source == changeDifficulty) { selectDifficulty(); } else if (source == showStats) { JDialog dialog = new JDialog(this, true); dialog.setTitle("Statistics"); dialog.setSize(190, 170); dialog.setLocationRelativeTo(null); dialog.setDefaultCloseOperation(DISPOSE_ON_CLOSE); JTabbedPane tabbedPane = new JTabbedPane(); for (String difficulty : new String[]{"Easy", "Medium", "Hard"}) { JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); int[] a = tracker.getData(difficulty); JLabel label1 = new JLabel("Best Score: " + a[0]); JLabel label2 = new JLabel("Best moves: " + a[1]); JLabel label3 = new JLabel("Wins: " + a[2]); JLabel label4 = new JLabel("Quits: " + a[3]); label1.setAlignmentX(JComponent.CENTER_ALIGNMENT); label2.setAlignmentX(JComponent.CENTER_ALIGNMENT); label3.setAlignmentX(JComponent.CENTER_ALIGNMENT); label4.setAlignmentX(JComponent.CENTER_ALIGNMENT); JButton button = new JButton("reset all"); button.addActionListener(evt -&gt; { tracker.resetAll(); dialog.dispose(); }); button.setAlignmentX(JComponent.CENTER_ALIGNMENT); panel.add(label1); panel.add(label2); panel.add(label3); panel.add(label4); panel.add(button); tabbedPane.addTab(difficulty, panel); } dialog.add(tabbedPane); dialog.setVisible(true); } else if (source == toggleDebugMode) { debug = !debug; toggleDebugMode.setText(debug ? "Exit debug mode" : "Enter debug mode"); } else if (source == howto) { JDialog dialog = new JDialog(this, true); dialog.setTitle("Spider solitaire gameplay (shamelessly copied and pasted from Wikipedia)"); dialog.setSize(500, 400); dialog.setLocationRelativeTo(null); dialog.setDefaultCloseOperation(DISPOSE_ON_CLOSE); JEditorPane textRegion = new JEditorPane("text/html", ""); textRegion.setEditable(false); String text = "The game is played with two decks of cards for a total of 104 " + "cards. Fifty-four of the cards are laid out horizontally in ten " + "columns with only the top card showing. The remaining fifty cards " + "are laid out in the lower right hand corner in five piles of ten with " + "no cards showing." + "&lt;p&gt;In the horizontal columns a card may be moved to any other card " + "in the column as long as it is in descending numerical sequence. " + "For example, a six of hearts may be moved to a seven of any suit. " + "However, a sequence of cards can only be moved if they are all of " + "the same suit in numerical descending order. For example, a six " + "and seven of hearts may be moved to an eight of any suit, but a six " + "of hearts and seven of clubs cannot be moved together. Moving the top card in a " + "column allows the topmost hidden card to be turned over. This card then enters " + "into the play. Other cards can be placed on it, and it can be moved to other cards " + "in a sequence or to an empty column.&lt;/p&gt;" + "&lt;p&gt;The object of the game is to uncover all the hidden cards and by moving cards " + "from one column to another to place cards in sequential order from King to Ace " + "using the fewest moves. Each final sequence must be all of the same suit. Once a " + "complete sequence is achieved the cards are removed from the table and 100 " + "points are added to the score. Once a player has made all the moves possible with the current card layout, the player draws a new row of cards from one of the piles of ten in the right lower hand corner by " + "clicking on the cards. Each of the ten cards in this draw lands face up on each of the ten horizontal columns and the player then " + "proceeds to place these in such a way to create a sequence of cards all in one suit.&lt;/p&gt;"; textRegion.setText(text); dialog.add(new JScrollPane(textRegion)); dialog.setVisible(true); } else if (source == about) { JOptionPane.showMessageDialog(this, "JSpider (version: 1.0)\nThis program is built by Jimmy Y. (codingexpert123@gmail.com)", "About JSpider", JOptionPane.INFORMATION_MESSAGE); } else { int[] a = tracker.getData(board.getDifficulty()); a[3]++; tracker.writeToFile(); System.exit(0); } } @Override public void componentResized(ComponentEvent e) { width = e.getComponent().getWidth(); height = e.getComponent().getHeight(); if (debug) { System.err.println("width:" + width + ", height:" + height); } board.calcYCutoff(); board.fixPiles(); board.fixDeck(); board.fixJunk(); board.repaint(); } @Override public void windowClosing(WindowEvent e) { int[] a = tracker.getData(board.getDifficulty()); a[3]++; tracker.writeToFile(); } @Override public void componentMoved(ComponentEvent e) {} @Override public void componentShown(ComponentEvent e) {} @Override public void componentHidden(ComponentEvent e) {} @Override public void windowOpened(WindowEvent e) {} @Override public void windowClosed(WindowEvent e) {} @Override public void windowIconified(WindowEvent e) {} @Override public void windowDeiconified(WindowEvent e) {} @Override public void windowActivated(WindowEvent e) {} @Override public void windowDeactivated(WindowEvent e) {} private class GameBoard extends JComponent implements MouseListener, MouseMotionListener { private final int piles = 10; private final int slots = 6; // deck slots, each slot have 10 (piles) cards private final int margin = 10; private final int cardWidth = 71; private final int cardHeight = 96; private final Color bgColor = new Color(0, 120, 0); private List&lt;Card&gt; allCards; // also it's a junk pile private Image cardBack; private List&lt;Card&gt;[] pile; private List&lt;Card&gt;[] deck; private int top; // pointer to top private int ptr; private int yCutoff; private int score; private int moves; private List&lt;Card&gt; movingPile; private int index; private int prevMX; private int prevMY; private String difficulty; private Stack&lt;GameState&gt; undoStack; private Insets insets; public GameBoard(String difficulty) { cardBack = readImage("images\\back.png"); undoStack = new Stack&lt;&gt;(); insets = new Insets(0, 0, 0, 0); loadImages(difficulty); calcYCutoff(); newGame(); addMouseListener(this); addMouseMotionListener(this); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(bgColor); g.fillRect(0, 0, width, height); int xGap = (width - piles * cardWidth) / (piles + 1); int y = margin; for (int i = 0; i &lt; piles; i++) { int x = xGap + i * cardWidth + i * xGap - insets.left; g.setColor(Color.WHITE); g.fillRect(x, y, cardWidth, cardHeight); // a white rectangle border indicates that there's no cards at that pile g.setColor(bgColor); g.fillRect(x + 1, y + 1, cardWidth - 2, cardHeight - 2); pile[i].stream().forEach(card -&gt; { g.drawImage(card.isFaceDown() ? cardBack : card.getImage(), card.x, card.y, this); }); } for (int i = 0; i &lt;= top; i++) { Card card = deck[i].get(0); g.drawImage(cardBack, card.x, card.y, this); } for (int i = 12; i &lt;= ptr; i += 13) { Card card = allCards.get(i); g.drawImage(card.getImage(), card.x, card.y, this); } g.setColor(bgColor.darker()); g.fillRect(width / 2 - 100 - insets.left, height - cardHeight - margin - insets.bottom - 50, 200, cardHeight); StringBuilder sb = new StringBuilder(); sb.append("Score: ").append(score); sb.append("\nMoves: ").append(moves); g.setColor(Color.WHITE); g.setFont(new Font("consolas", Font.BOLD, 14)); drawString(g, sb.toString(), width / 2 - 50, height - cardHeight - margin - insets.bottom - 50 + 25); if (movingPile != null) { movingPile.stream().forEach(card -&gt; { g.drawImage(card.getImage(), card.x, card.y, this); }); } } public void setInsets(Insets insets) { this.insets = insets; repaint(); } public String getDifficulty() { return difficulty; } public void undo() { GameState state = undoStack.pop(); allCards = state.getAllCards(); pile = state.getPile(); top = state.getTop(); ptr = state.getPtr(); repaint(); score--; moves++; if (!canUndo()) { undo.setEnabled(false); } } public boolean canUndo() { return !undoStack.empty() &amp;&amp; !undoStack.peek().dealed(); } public void resetGame() { if (undoStack.empty()) { return; } while (undoStack.size() &gt; 1) { undoStack.pop(); } GameState state = undoStack.pop(); allCards = state.getAllCards(); pile = state.getPile(); deck = state.getDeck(); top = state.getTop(); ptr = state.getPtr(); repaint(); score = 500; moves = 0; undo.setEnabled(false); } public void clearCards() { collectAllCards(); allCards = null; } /* * This method is an extension of Graphics::drawString, it handles strings with newlines, thanks to SO! */ private void drawString(Graphics g, String str, int x, int y) { for (String line : str.split("\n")) { g.drawString(line, x, y += g.getFontMetrics().getHeight()); } } private void deal() { for (int i = 0; i &lt; piles; i++) { Card card = deck[top].get(i); pile[i].add(card); card.flip(); fixPile(i); } deck[top--] = null; undoStack.push(new GameState()); undo.setEnabled(false); repaint(); } public void calcYCutoff() { yCutoff = height * 3 / 5; } public void fixJunk() { int y = height - cardHeight - margin - 40 - insets.bottom - 16; for (int i = 0; i &lt;= ptr; i++) { Card card = allCards.get(i); card.y = y; } } public void fixDeck() { int y = height - cardHeight - margin - 40 - insets.bottom - 16; for (int i = 0; i &lt;= top; i++) { int x = width - cardWidth - margin - insets.left - 10 - (margin + 2) * i; deck[i].stream().forEach(card -&gt; { card.x = x; card.y = y; }); } } public void fixPiles() { for (int i = 0; i &lt; piles; i++) { fixPile(i); } } private void fixPile(int index) { if (pile[index].size() == 0) { return; } int xGap = (width - piles * cardWidth) / (piles + 1); int topX = xGap + index * cardWidth + index * xGap - insets.left; int yGap = 35; for (int i = 0; i &lt; 6; i++) { int cards = pile[index].size(); Card prevCard = null; yGap -= (i &lt; 4) ? 4 : 1; for (int j = 0; j &lt; cards; j++) { Card card = pile[index].get(j); int topY = (prevCard == null) ? margin : prevCard.y + (prevCard.isFaceDown() ? margin : yGap); card.x = topX; card.y = topY; prevCard = card; } int lastY = pile[index].get(pile[index].size() - 1).y; if (lastY &lt; yCutoff) { break; } } } private void collectAllCards() { if (allCards.size() &lt; 104) { for (int i = 0; i &lt; piles; i++) { int cards = pile[i].size(); for (int j = 0; j &lt; cards; j++) { Card card = pile[i].get(j); if (!card.isFaceDown()) { card.flip(); } allCards.add(card); } } for (int i = 0; i &lt;= top; i++) { List&lt;Card&gt; slot = deck[i]; int size = slot.size(); for (int j = 0; j &lt; size; j++) { allCards.add(slot.get(j)); } } } } /* * preconditions: * - undoStack is !null * - loadImages() is called * - calcYCutoff() is called, otherwise fixPile() will be slow */ public void newGame() { collectAllCards(); Collections.shuffle(allCards); initDeck(); initPiles(); deal(); undoStack.clear(); undo.setEnabled(false); ptr = -1; score = 500; moves = 0; movingPile = null; } @SuppressWarnings("unchecked") private void initDeck() { deck = new List[slots]; top = slots - 1; int y = height - cardHeight - margin - 40 - insets.bottom - 16; for (int i = 0; i &lt; slots; i++) { deck[i] = new ArrayList&lt;&gt;(); int x = width - cardWidth - margin - insets.left - 10 - (margin + 2) * i; for (int j = 0; j &lt; piles; j++) { Card card = draw(); card.x = x; card.y = y; card.width = cardWidth; card.height = cardHeight; deck[i].add(card); } } } @SuppressWarnings("unchecked") private void initPiles() { pile = new List[piles]; for (int i = 0; i &lt; piles; i++) { pile[i] = new ArrayList&lt;&gt;(); int cards = (i &lt; 4) ? 5 : 4; for (int j = 0; j &lt; cards; j++) { Card card = draw(); card.width = cardWidth; card.height = cardHeight; pile[i].add(card); } fixPile(i); } } private Card draw() { Card card = allCards.get(0); allCards.remove(card); return card; } public void loadImages(String difficulty) { this.difficulty = difficulty; int value = -1; if (difficulty.equals("Easy")) { value = 4; } else if (difficulty.equals("Medium")) { value = 3; } else { value = 1; } allCards = new ArrayList&lt;&gt;(); int counter = 0; while (counter &lt; 8) { for (int suit = value; suit &lt;= 4; suit++) { for (int rank = 1; rank &lt;= 13; rank++) { allCards.add(new Card(readImage("images\\" + rank + "" + suit + ".png"), suit, rank, true)); } counter++; } } } private void showPlayAgainDialog() { int[] a = tracker.getData(difficulty); a[0] = Math.max(a[0], score); a[1] = a[1] == 0 ? moves : Math.min(a[1], moves); a[2]++; int resp = JOptionPane.showConfirmDialog(this, "Do you want to play again?", "Game over! You won!", JOptionPane.YES_NO_OPTION); if (resp == JOptionPane.YES_OPTION) { newGame(); } else { tracker.writeToFile(); System.exit(0); } } private boolean checkForCardsToRemove(int index) { int suit = -1; int rank = 1; for (int i = pile[index].size() - 1; i &gt;= 0 &amp;&amp; rank &lt;= 13; i--, rank++) { Card card = pile[index].get(i); if (suit == -1) { suit = card.getSuit(); } if (suit != card.getSuit()) { return false; } if (card.isFaceDown()) { return false; } if (card.getRank() != rank) { return false; } } if (rank == 14) { int y = height - cardHeight - margin - 40 - insets.bottom - 16; Card prevCard = (ptr == -1) ? null : allCards.get(ptr); for (int i = pile[index].size() - 1; i &gt;= 0 &amp;&amp; --rank &gt;= 1; i--) { Card card = pile[index].get(i); card.x = (prevCard == null) ? margin : prevCard.x + margin + 2; card.y = y; card.flip(); // the card must be flipped face down for new game pile[index].remove(card); allCards.add(card); ptr++; } Card last = (pile[index].size() &gt; 0) ? pile[index].get(pile[index].size() - 1) : null; if (last != null &amp;&amp; last.isFaceDown()) { last.flip(); } return true; } return false; } @Override public void mousePressed(MouseEvent e) { int mouseX = e.getX(); int mouseY = e.getY(); prevMX = mouseX; prevMY = mouseY; int index = -1; int startFrom = -1; outer: for (int i = 0; i &lt; piles; i++) { int cards = pile[i].size(); for (int j = cards - 1; j &gt;= 0; j--) { Card card = pile[i].get(j); if (card.contains(mouseX, mouseY)) { index = i; startFrom = j; break outer; } } } if (index != -1) { if (pile[index].get(startFrom).isFaceDown()) { return; } List&lt;Card&gt; touched = pile[index].subList(startFrom, pile[index].size()).stream().collect(Collectors.toCollection(ArrayList::new)); // I know it's ugly but it resolves ConcurrentModificationException if (!debug) { int suit = -1; // ensures that the selected cards have same suite int rank = -1; // ensures that the selected cards follow decreasing numerical order int size = pile[index].size() - startFrom; for (int i = 0; i &lt; size; i++, rank--) { if (suit == -1) { suit = touched.get(i).getSuit(); } if (rank == -1) { rank = touched.get(i).getRank(); } if (suit != touched.get(i).getSuit()) { return; } if (rank != touched.get(i).getRank()) { return; } } } undoStack.push(new GameState(allCards, pile, deck, top, ptr)); pile[index].removeAll(touched); movingPile = touched; this.index = index; repaint(); } else if (top &gt;= 0) { Card topCard = deck[top].get(0); Card botCard = deck[0].get(0); Rectangle rect = new Rectangle(topCard.x, topCard.y, botCard.x + botCard.width - topCard.x, topCard.height); if (rect.contains(mouseX, mouseY)) { // make sure that there's no empty piles for (int i = 0; i &lt; piles; i++) { if (pile[i].size() == 0) { return; } } deal(); } } } @Override public void mouseReleased(MouseEvent e) { if (movingPile != null) { boolean success = false; Card firstCard = movingPile.get(0); Card lastCard = movingPile.get(movingPile.size() - 1); Rectangle dragRegion = new Rectangle(firstCard.x, firstCard.y, firstCard.width, lastCard.y + lastCard.height - firstCard.y); for (int i = 0; i &lt; piles; i++) { if (i == index) { continue; } Card card = (pile[i].size() &gt; 0) ? pile[i].get(pile[i].size() - 1) : null; // last card if (card != null &amp;&amp; card.intersects(dragRegion) &amp;&amp; (!debug ? (card.getRank() == firstCard.getRank() + 1) : true)) { pile[i].addAll(movingPile); if (checkForCardsToRemove(i)) { score += 100; if (allCards.size() == 104) { movingPile = null; repaint(); showPlayAgainDialog(); } } fixPile(i); success = true; break; } else if (card == null &amp;&amp; pile[i].size() == 0) { int xGap = (width - piles * cardWidth) / (piles + 1); int topX = xGap + i * cardWidth + i * xGap - insets.left; Rectangle rect = new Rectangle(topX, margin, cardWidth, cardHeight); // white rectangle border if (rect.intersects(dragRegion)) { pile[i].addAll(movingPile); fixPile(i); success = true; break; } } } if (!success) { pile[index].addAll(movingPile); undoStack.pop(); } else { Card last = (pile[index].size() &gt; 0) ? pile[index].get(pile[index].size() - 1) : null; if (last != null &amp;&amp; last.isFaceDown()) { last.flip(); } score--; moves++; undo.setEnabled(true); } fixPile(index); movingPile = null; repaint(); if (allCards.size() == 104) { showPlayAgainDialog(); } } } @Override public void mouseDragged(MouseEvent e) { if (movingPile != null) { int mouseX = e.getX(); int mouseY = e.getY(); int dx = mouseX - prevMX; int dy = mouseY - prevMY; movingPile.stream().forEach(c -&gt; c.translate(dx, dy)); prevMX = mouseX; prevMY = mouseY; repaint(); } } @Override public void mouseClicked(MouseEvent e) {} @Override public void mouseEntered(MouseEvent e) {} @Override public void mouseExited(MouseEvent e) {} @Override public void mouseMoved(MouseEvent e) {} private class GameState { private List&lt;Card&gt; allCards; private List&lt;Card&gt;[] pile; private List&lt;Card&gt;[] deck; private int top; private int ptr; private boolean dealed; public GameState() { dealed = true; } @SuppressWarnings("unchecked") public GameState(List&lt;Card&gt; allCards, List&lt;Card&gt;[] pile, List&lt;Card&gt;[] deck, int top, int ptr) { this.allCards = new ArrayList&lt;&gt;(); for (Card card : allCards) { this.allCards.add((Card) card.clone()); } this.pile = new List[piles]; for (int i = 0; i &lt; piles; i++) { this.pile[i] = new ArrayList&lt;&gt;(); for (Card card : pile[i]) { this.pile[i].add((Card) card.clone()); } } this.deck = new List[slots]; for (int i = 0; i &lt; slots; i++) { if (deck[i] == null) { this.deck[i] = null; } else { this.deck[i] = new ArrayList&lt;&gt;(); for (Card card : deck[i]) { this.deck[i].add((Card) card.clone()); } } } this.top = top; this.ptr = ptr; dealed = false; } public List&lt;Card&gt; getAllCards() { return allCards; } public List&lt;Card&gt;[] getPile() { return pile; } public List&lt;Card&gt;[] getDeck() { return deck; } public int getTop() { return top; } public int getPtr() { return ptr; } public boolean dealed() { return dealed; } } } private class DataTracker { private String fileName; private Map&lt;String, int[]&gt; map; public DataTracker(String fileName) { this.fileName = fileName; map = new TreeMap&lt;&gt;(); readData(); } public void resetAll() { for (String difficulty : new String[]{"Easy", "Medium", "Hard"}) { int[] a = getData(difficulty); Arrays.fill(a, 0); } } public void writeToFile() { try { DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(fileName))); for (String difficulty : new String[]{"Easy", "Medium", "Hard"}) { int[] a = getData(difficulty); for (int i = 0; i &lt; 4; i++) { dos.writeInt(a[i]); } } dos.close(); } catch (IOException ex) { ex.printStackTrace(); System.exit(1); } } public int[] getData(String difficulty) { return map.get(difficulty); } private void readData() { try { DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(fileName))); for (String difficulty : new String[]{"Easy", "Medium", "Hard"}) { map.put(difficulty, new int[]{dis.readInt(), dis.readInt(), dis.readInt(), dis.readInt()}); } dis.close(); } catch (IOException ex) { ex.printStackTrace(); System.exit(1); } } } private class Card extends Rectangle { private Image cardImage; private int suit; private int rank; private boolean isFaceDown; public Card(Image cardImage, int suit, int rank, boolean isFaceDown) { super(); this.cardImage = cardImage; this.suit = suit; this.rank = rank; this.isFaceDown = isFaceDown; } public void flip() { isFaceDown = !isFaceDown; } public Image getImage() { return cardImage; } public int getSuit() { return suit; } public int getRank() { return rank; } public boolean isFaceDown() { return isFaceDown; } @Override public Object clone() { Card copy = new Card(cardImage, suit, rank, isFaceDown); copy.x = x; copy.y = y; copy.width = width; copy.height = height; return copy; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T07:51:17.617", "Id": "433461", "Score": "1", "body": "What do you mean with cloning the game and implementing features? Is this your code or a mix of existing with your code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T19:44:19.023", "Id": "433541", "Score": "1", "body": "@dfhwze I coded everything by myself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-11T08:25:50.120", "Id": "434248", "Score": "0", "body": "Nice job. Just a quick note: \"Restart current game\" freezes the application." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-13T22:16:48.143", "Id": "434663", "Score": "0", "body": "@JoachimRohde How? It works fine on my computer (Windows)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T09:28:02.347", "Id": "434849", "Score": "0", "body": "@JimmyYang I just checked it again and it worked now. The time I wrote that I had played several games and after trying to restart the game I had to close the application because it was not reacting at all anymore." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T03:33:54.173", "Id": "223536", "Score": "3", "Tags": [ "java", "game", "swing", "playing-cards" ], "Title": "Java implementation of Spider Solitaire" }
223536
<p>How could I make my code follow the <strong>DRY principle?</strong> I feel like they are better ways to do things in my code. So any feedback will help me!</p> <p><strong>js fiddle:</strong> <a href="https://jsfiddle.net/fr6ut238/" rel="nofollow noreferrer">https://jsfiddle.net/fr6ut238/</a></p> <pre><code> /*--------------------------- Variables ---------------------------*/ const $containerGrid = $(".containerGrid"); let boxSide = 16; const $gridLength = $("#gridLength"); const $gradientButton = $("#gradient"); const $randomButton = $("#random"); const $resetButton = $("#reset"); /*-- ------------------------- Buttons &amp; input ---------------------------*/ $gridLength.on("input", gridLength); $gradientButton.on("click", incrementOpacity); $randomButton.on("click", getRandomColors); $resetButton.on("click", () =&gt; { reset(boxSide); }); /*--------------------------- Corresponding to Event listeners ---------------------------*/ function gridLength() { if (event.target.value !== 16) { reset(event.target.value); } } function incrementOpacity() { $(".cell").off("mouseenter"); $(".cell").mouseenter((event) =&gt; { let opacity = parseFloat(event.target.style.opacity); if (opacity &lt;= 0.9) { $(event.target).css({ "opacity": `${opacity + 0.1}`, "backgroundColor": "#f5f5f5"}); } }); } function setRandomColors() { return Math.floor((Math.random() * 256)); } function getRandomColors() { $(".cell").off("mouseenter"); $(".cell").mouseenter((event) =&gt; { $(event.target).css({ "backgroundColor": `rgb(${setRandomColors()}, ${setRandomColors()}, ${setRandomColors()})`, "opacity": "1" }) }); } function reset(length) { boxSide = length; main(); $(".cell").css({ "opacity": "0.1", "border": "0.5px solid black", "backgroundColor": "transparent"}); } /*-- ------------------------- Creates the Grid ------------------------------*/ function main() { $($containerGrid).empty(); for (let row = 0; row &lt; boxSide; row++) { for (let column = 0; column &lt; boxSide; column++) { createCell(); } } $(".cell").css("height", `${(300 / boxSide) - 1}px`); $(".cell").css("width", `${(300 / boxSide) - 1}px`); } function createCell() { const $cell = $('&lt;div class="cell"&gt;&lt;/div&gt;'); $cell.css("opacity", "0.1"); $containerGrid.append($cell); } main(); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T08:08:49.610", "Id": "433332", "Score": "3", "body": "We need to know what your code is doing before we can review it. Please edit your question and explain the code's purpose." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T07:26:28.643", "Id": "223542", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "jQuery - Etch-A-Sketch implementation" }
223542
<p>I developed the function <code>array_includes</code> which checks if an array contains a value and returns it. I would like to know if there is already such a function which is more efficient or how I can make the function more efficient.</p> <pre><code>&lt;?php $params = "colorgroup-b;test;abc"; $paramsArr = explode(";", $params); var_dump(array_includes("colorgroup", $paramsArr)); //outputs: colorgroup-b function array_includes($needle, $arr) { foreach($arr as $param) { if (strpos($param, $needle) !== false) { return $param; } } return false; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T11:00:34.263", "Id": "433352", "Score": "1", "body": "@Dave it sounds like the title but absolutely not like the *code* we are supposed to review here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T11:04:07.820", "Id": "433353", "Score": "0", "body": "I would rather question this function's existence. What it supposed to return for the array like this `\"colorgroup-a;colorgroup-b;test;abc\"` and why?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T12:46:41.950", "Id": "433371", "Score": "0", "body": "↑ The first result. But good hint. The function can be improved to return an array if there are multiple finds. But I would rather create a second function e.g. array_includes_multiple or something similar" } ]
[ { "body": "<p>Your function checks if an array contains a string that contains your given <code>$needle</code>. No, there's no such function in PHP yet. The <a href=\"https://www.php.net/manual/en/function.in-array.php\" rel=\"nofollow noreferrer\">in_array()</a> function does something else.</p>\n\n<p>You could make your function more efficient if you include the <code>explode()</code> inside the function, like this:</p>\n\n<pre><code>function find_parameters($needle, $parameterStr)\n{ \n if (strpos($parameterStr, $needle) !== false) {\n $result = [];\n foreach(explode(\";\", $parameterStr) as $parameter) {\n if (strpos($parameter, $needle) !== false) {\n $result[] = $parameter;\n }\n }\n return $result;\n } \n return false;\n}\n</code></pre>\n\n<p>This function first checks whether the parameter string actually does contain the needle. It can quickly return <code>false</code> when it doesn't. If the needle is present it does what your code does, with the exception that it returns an array. This is done so that it can return multiple results. Suppose your parameter string looks like this:</p>\n\n<pre><code>$params = \"colorgroup-a;colorgroup-b;test;abc\";\n</code></pre>\n\n<p>and you test this:</p>\n\n<pre><code>var_dump(find_parameters(\"colorgroup\", $paramsArr));\n</code></pre>\n\n<p>Then it will not return only <code>colorgroup-a</code>, like your function, but it will return an array with <code>colorgroup-a</code> and <code>colorgroup-b</code>.</p>\n\n<p>So this new function is more efficient, when there are no matching parameters, and it is more correct in that it finds all the parameters.</p>\n\n<p>Yes, it is longer, but shortness of code should not be the main aim when writing code. The use of regular expressions is also very popular for these kind of tasks, and it would result in less code. But the engine behind regular expressions is complex, and would make the code a lot less efficient.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T11:04:04.750", "Id": "223559", "ParentId": "223546", "Score": "2" } }, { "body": "<p>In case you'd like to compare/benchmark the regex technique, it will look like this:</p>\n\n<p>Code: (<a href=\"https://3v4l.org/i3SXX\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n\n<pre><code>$params = \"colorgroup-b;test;abc\";\n\nvar_dump(array_includes(\"colorgroup\", $params)); //outputs: colorgroup-b\n\nfunction array_includes($needle, $params) {\n return preg_match('/[^;]*' . preg_quote($needle, '/') . '[^;]*/', $params, $m) ? $m[0] : false; \n}\n</code></pre>\n\n<p>For small scale execution, no user is going to notice any performance differences.</p>\n\n<p>For large scale executions, there may actually be some advantage in this way because a full length array doesn't need to be generated to begin the searching. Notice that there will potentially be <em>n</em> calls of <code>strpos()</code>.</p>\n\n<p>There is also the versatility of this script. It doesn't take much effort to modify the script to extract multiple matches. Or use case-insensitivity. Or multibyte awareness. Or employ word boundaries (something that non-regex techniques struggle to do simply). These adjustments are so slight that if you wanted individual command over all of the above options, you wouldn't need a separate method for each - just pass additional parameters to the method.</p>\n\n<pre><code>function stringSearch($needle, $params, $singleMatch = true, $caseInsensitive = false, $multibyte = false, $wordBoundaries = 'neither') {\n</code></pre>\n\n<p>(I am thinking wordBoundaries might be <code>neither</code>, <code>left</code>, <code>right</code>, or <code>both</code>.)</p>\n\n<p>Returning an array is as easy as adding four-characters to <code>preg_match</code> to become <code>preg_match_all</code>. <a href=\"https://3v4l.org/Re45d\" rel=\"nofollow noreferrer\">Demo</a></p>\n\n<p>This might also be a timely opportunity to bring up <a href=\"https://stackify.com/premature-optimization-evil/\" rel=\"nofollow noreferrer\">Premature Optimization</a>. Assuming the input string in your application is expected to be a length of tens-of-characters and it is not called thousands of times in an iterative process, the processing time from KIKO's snippet versus my snippet will be entirely unnoticeable.</p>\n\n<p>With that criteria mostly written off as moot, other criteria can be mentioned.</p>\n\n<p>If the idea of regular expressions sends shivers down the spine of you or your development team, that is a perfectly valid justification to use KIKO's technique.</p>\n\n<p>If your code base already contains simple regular expression techniques like my snippet, then my snippet will conform nicely to the project.</p>\n\n<p>I personally never shy away from the convenience that regex affords. I also value the directness and conciseness whenever performance is not noticeably impacted. If a non-regex technique would provide a more brief, direct process, I would opt for that. (Just my opinion of course)</p>\n\n<p>p.s. if your <code>$needle</code> value is already sufficiently sanitized, the <code>preg_quote</code> call may be omittable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T14:59:00.320", "Id": "223572", "ParentId": "223546", "Score": "1" } }, { "body": "<p>After a bit more consideration and soul searching, I suppose the correct technique to use would be the one that avoids an iterative \"guess and check\" technique and avoids changing the input's data type.</p>\n\n<p>The input data type is a string and the output data type is a string; I don't find it very compelling to convert the input temporarily to an array just to return a string. If the input data began as an array, I would probably be more in favor of array type manipulation.</p>\n\n<p>If you don't want a concise regex technique, just whittle down <code>$param</code> until it is what you need and don't generate data that you won't eventually use.</p>\n\n<p>Code: (<a href=\"https://3v4l.org/l6HA6\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n\n<pre><code>$params = \"test;colorgroup-b;test;abc\";\n\nvar_dump(string_includes(\"group\", $params)); //outputs: colorgroup-b\n\nfunction string_includes($needle, $haystack) {\n $needlePosition = strpos($haystack, $needle);\n if ($needlePosition === false) {\n return false;\n }\n $needleEndPosition = strpos($haystack, ';', $needlePosition);\n if ($needleEndPosition !== false) {\n $haystack = substr($haystack, 0, $needleEndPosition);\n }\n $delimiterPosition = strrpos($haystack, ';');\n if ($delimiterPosition === false) {\n return $haystack;\n }\n return substr($haystack, $delimiterPosition + 1);\n}\n</code></pre>\n\n<p>This snippet will call 1 to 5 string function calls no matter how big the input string. This makes the processing time efficient and relatively consistent. </p>\n\n<p>This is much more code bloat than I would welcome into one of my projects, but if you are hellbent on prioritizing efficiency, this should be on your radar to benchmark.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T06:31:19.800", "Id": "223599", "ParentId": "223546", "Score": "1" } } ]
{ "AcceptedAnswerId": "223559", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T08:05:30.700", "Id": "223546", "Score": "1", "Tags": [ "php", "array" ], "Title": "PHP - check if array includes value and return value if true" }
223546
<p>After watching <a href="https://www.youtube.com/watch?v=o9pEzgHorH0&amp;t=1s" rel="noreferrer">this presentation</a>, I decided that it would be a good project for me to undergo to practice my <code>python</code> skills. A summary of the presentation:</p> <blockquote> <p>Jack Diederich, the presenter, talks about the overuse of classes in programming. A phrase he used a lot was &quot;you shouldn't be writing a class if it has two methods, one of which is init&quot;</p> <p>Video description: &quot;Classes are great but they are also overused. This talk will describe examples of class overuse taken from real world code and refactor the unnecessary classes, exceptions, and modules out of them.&quot;</p> </blockquote> <p>Having his phrase as my model, I wrote a <code>python</code> program that read a <code>.py</code> file, and if it has only one method that isn't <code>__init__</code>, the program refactors the code into one method and appends the new code to the end of the file. A more detailed description is available in the <code>docstring</code> at the top of the source code of <code>class_cruncher.py</code>.</p> <p><strong>THIS PROGRAM ASSUMES A LOT</strong></p> <ul> <li>The entire file is a class. If there are any other methods that are not related to the class, but are contained in the file, the program will pick up on those methods and it won't work correctly. It is currently only written for code that it completely wrapped in a class.</li> </ul> <p>I would like feedback on code efficiency and any other nitpicks you can find in my code. It took a couple hours to write, and I'm sure there are areas that can be improved.</p> <p><strong>class_cruncher.py</strong></p> <pre><code>&quot;&quot;&quot; Objective: Take in python file, and determine if class inside can be reduced. This program assumes all methods are inside the class, and are all related to the class. It won't work if there are methods outside the scope of the class; it will count those too. Criteria for reduction: - Two methods, one of which is __init__ - One method - Empty class (has only pass) If reduced: The class should be restrained into one method, who's name will be the name of the only method (other than __init__) in the class. This method will be appended to the file in a docstring. &quot;&quot;&quot; import sys def get_file_lines(): &quot;&quot;&quot; Method written explicitly for not having to loop through and re-open the file each time &quot;&quot;&quot; global file lines = [] with open(file) as f: for line in f: lines.append(line) return lines def get_function_code(method_name): &quot;&quot;&quot; Gets all the code in the method name passed &quot;&quot;&quot; global function_params code = [] lines = get_file_lines() for i in range(len(lines)): if method_name in lines[i]: for j in range(len(lines)): if j &gt; i: if lines[j] != '\n': if &quot;self&quot; in lines[j]: function_params += (&quot;, &quot; + add_to_params(lines[j])) code.append(remove_self(lines[j])) else: code.append(lines[j]) else: break return code def get_function_paramaters(method_name): &quot;&quot;&quot; Gets the parameters for the method name specified &quot;&quot;&quot; for line in get_file_lines(): if method_name in line: length = (len(method_name) * 2) + 6 header = line.strip()[length:] parameters = &quot;&quot; for char in header: if char != &quot;)&quot;: parameters += char else: break return parameters def get_function_name(): &quot;&quot;&quot; Searches through the file and finds the name of the function that will be the base name for the reducing &quot;&quot;&quot; for line in get_file_lines(): if is_function(line): func_line = line.strip()[4:] name = &quot;&quot; for char in func_line: if char != &quot;(&quot;: name += char else: break return name def is_function(line): &quot;&quot;&quot; Checks if line contains &quot;def&quot;, determining if it is a function Also checks if it contains __init__, for which it returns False &quot;&quot;&quot; if &quot;def&quot; in line: if &quot;__init__&quot; in line: return False return True return False def function_count(): &quot;&quot;&quot; Counts how many functions there are in the class &quot;&quot;&quot; count = 0 for line in get_file_lines(): if is_function(line): count += 1 return count def add_to_params(line): &quot;&quot;&quot; Adds a variable to the params of the new function if it's included in the code and has `self` before it. &quot;&quot;&quot; for i in range(len(line)): j = i + 4 if line[i:j] == &quot;self&quot;: cut_line = line[j + 1:] new_param = &quot;&quot; for char in cut_line: if char.isalpha(): new_param += char else: break return new_param def remove_self(line): &quot;&quot;&quot; Removes `self.` from the line, and returns the new formatted line &quot;&quot;&quot; for i in range(len(line)): j = i + 4 if line[i:j] == &quot;self&quot;: new_line = line[:i] + line[j + 1:] return new_line def combine_all(name, params, code): &quot;&quot;&quot; Combines all the collected information into one new method. The `line[1:]` removes the first '\t' for better formatting &quot;&quot;&quot; method = &quot;def &quot; + name + &quot;(&quot; + params + &quot;):\n&quot; for line in code: method += line[1:] return method def appendToFile(content): &quot;&quot;&quot; Appends the new method to the provided file &quot;&quot;&quot; global file with open(file, &quot;a&quot;) as f: f.write(&quot;\n\n########################&quot;) f.write(&quot;\n# REDUCED CLASS BELOW #&quot;) f.write(&quot;\n########################\n&quot;) f.write(content) &quot;&quot;&quot; The below code is all in the main guard and not in a seperate function because I need access to `function_params` in order to add more params should I need to. This was the only solution I could think of. &quot;&quot;&quot; if __name__ == '__main__': file = input(&quot;Enter file path: &quot;) #code/python/class_cruncher/yes_reduce.py # Used as shortcut for testing if function_count() &gt; 1: print(&quot;CLASS DOES NOT NEED TO BE REDUCED&quot;) sys.exit(0) function_name = get_function_name() function_params = get_function_paramaters(function_name) function_code = get_function_code(function_name) new_function = combine_all(function_name, function_params, function_code) appendToFile(new_function) print(&quot;Class successfully reduced!&quot;) </code></pre> <p>Below are two test cases I used. <code>yes_reduce.py</code> is a class that should be reduced by this program, and <code>no_reduce.py</code> is a class that should not be reduced by this program. The code in the two test cases are irrelevant; I wrote random code so that something would be in the methods.</p> <p><strong>yes_reduce.py</strong></p> <pre><code>&quot;&quot;&quot; This is a class that should be reduced &quot;&quot;&quot; class Greeting(): def __init__(self, message=&quot;Hello&quot;): self.message = message def greet(self, person): print(f&quot;{self.message}, {person}!&quot;) print(&quot;Test1&quot;) print(&quot;test2&quot;) </code></pre> <p><strong>no_reduce.py</strong></p> <pre><code>&quot;&quot;&quot; This is a class that should not be reduced &quot;&quot;&quot; class API(): def __init__(self, param1, param2, param3): self.param1 = param1 self.param2 = param2 self.param3 = param3 def method1(self): return self.param1 + self.param2 def method2(self): return True if self.param1 == self.pram2 else False def xyz(self, name): return f&quot;xyz: {self.param3}&quot; </code></pre> <p>Below is what <code>yes_reduce.py</code> looks like after being reduced.</p> <p><strong>yes_reduce.py after compression</strong></p> <pre><code>&quot;&quot;&quot; This is a class that should be reduced &quot;&quot;&quot; class Greeting(): def __init__(self, message=&quot;Hello&quot;): self.message = message def greet(self, person): print(f&quot;{self.message}, {person}!&quot;) print(&quot;Test1&quot;) print(&quot;test2&quot;) ######################## # REDUCED CLASS BELOW # ######################## def greet(person, message): print(f&quot;{message}, {person}!&quot;) print(&quot;Test1&quot;) print(&quot;test2&quot;) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T09:40:16.490", "Id": "433343", "Score": "0", "body": "Why choose to drop the default parameter for `message`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T12:02:12.560", "Id": "433630", "Score": "0", "body": "You should investigate the `inspect` library. It would allow you to get the method names, count and attributes of the class as from python objects, not by reading the file as it's a string." } ]
[ { "body": "<p>That's a difficult problem to attack. Without going into those difficulties, here are some comments on your code.</p>\n\n<p>Global variables are generally frowned upon. They are basically a hidden function parameter, which can make it hard to debug and maintain the software. So, for example, it would be better to explicitly pass <code>file</code> as a parameter of <code>get_file_lines()</code> rather than use a global variable: </p>\n\n<pre><code>def get_file_lines(file):\n \"\"\"\n Method written explicitly for not having to loop through\n and re-open the file each time\n \"\"\"\n lines = []\n with open(file) as f:\n for line in f:\n lines.append(line)\n return lines\n</code></pre>\n\n<p>The doc string for <code>get_file_lines()</code> saya it is so the file doesn't have to be reopened and reread. However, this function is called four times by other functions in the program. Each time the file is being opened and read. To correct this, call <code>get_file_lines()</code> once when initializing the program and saving the <code>lines</code> that gets returned. Then pass <code>lines</code> into whatever other functions need to look at the source code like so:</p>\n\n<pre><code>lines = get_file_lines(file)\nfunction_name = get_function_name(lines)\nfunction_params = get_function_paramaters(lines, function_name)\n....etc....\n</code></pre>\n\n<p>Then instead of <code>for line in get_file_lines():</code> in the other functions use:</p>\n\n<pre><code>for line in lines:\n .... \n</code></pre>\n\n<p>Functions can return more than one value, so instead of making function_params a global variable, it can be passed as an argument and returned. Also, for-loops can have a starting value. So, <code>get_function_code()</code> can be written something like this:</p>\n\n<pre><code>def get_function_code(lines, method_name, function_params):\n \"\"\"\n Gets all the code in the method name passed\n \"\"\"\n code = []\n for i in range(len(lines)):\n if method_name in lines[i]:\n for j in range(i+1, len(lines)): #&lt;-- changed start\n if lines[j] == '\\n':\n break\n\n if \"self\" in lines[j]:\n function_params += (\", \" + add_to_params(lines[j]))\n code.append(remove_self(lines[j]))\n else:\n code.append(lines[j])\n\n return code, function_params\n</code></pre>\n\n<p>There are other things that could be cleaned up, but that's all I've time for right now.</p>\n\n<p>Also, have a look at the <a href=\"https://docs.python.org/3.6/library/pyclbr.html\" rel=\"nofollow noreferrer\">pyclbr</a> module in the standard library. It provides functions to read a python file and return a dictionary of all the classes and functions. For classes, it can be used to find the line number where the class is defined, a list of all its methods, and the lines where the methods are defined.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T08:58:00.853", "Id": "223723", "ParentId": "223548", "Score": "4" } }, { "body": "<h2>Loop like a native</h2>\n\n<p>This:</p>\n\n<pre><code>for i in range(len(lines)):\n if method_name in lines[i]:\n</code></pre>\n\n<p>is an anti-pattern. If you need to iterate over lines, simply</p>\n\n<pre><code>for line in lines:\n</code></pre>\n\n<p>However, since you also do an index comparison, you might need</p>\n\n<pre><code>for i, line in enumerate(lines):\n</code></pre>\n\n<p>Also, that nested i/j loop does not need to be nested. As soon as you find where the method name is, you should break out of the first loop.</p>\n\n<h2>No magic numbers</h2>\n\n<p>What does the <code>4</code> in <code>line.strip()[4:]</code> do? This should be put into a variable for easier understanding.</p>\n\n<h2>The bigger problem</h2>\n\n<p>You've written a Python parser. This is deeply unnecessary. Have a read through <a href=\"https://docs.python.org/3.7/library/ast.html#module-ast\" rel=\"nofollow noreferrer\">https://docs.python.org/3.7/library/ast.html#module-ast</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T13:36:41.003", "Id": "223744", "ParentId": "223548", "Score": "1" } } ]
{ "AcceptedAnswerId": "223723", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T08:22:10.513", "Id": "223548", "Score": "7", "Tags": [ "python", "python-3.x", "object-oriented", "meta-programming" ], "Title": "Python class compressor" }
223548
<p>This is a problem from <strong>Automate the Boring Stuff</strong> from "Pattern Matching with Regular Expression". I am a beginner in Python and the purpose of this program is to match urls which start with <code>http://</code> or <code>https://</code>, with some urls having an optional <code>www.</code> after <code>https://</code></p> <p>How can this code be improved?</p> <pre><code>#! /usr/bin/python3 #websiteURL.py - Find website URLs that begin with http:// or https:// import pyperclip, re #protocol Regex - checks for http:// or https:// protocolRegex = re.compile(r''' https?:// #match http:// or https:// (?:w{3}\.)? #www-dot [a-zA-Z0-9_-]+ #domin name \. #dot [a-zA-Z]{2,3} #extension ''', re.VERBOSE) text = str(pyperclip.paste()) #copying data from document to clipboard and converting it into a string matches = [] #stores all matches in this list for website in protocolRegex.findall(text): #finding website from the string text matches.append(website) if len(matches) &gt; 0: pyperclip.copy('\n'.join(map(str, matches))) #copying result to clipboard after adding newline after each match print('Copied to clipboard:') print('\n'.join(matches)) else: print('No website found') </code></pre> <p>Running code:</p> <pre><code>chmod +x websiteURL.py ./websiteURL.py </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T09:28:06.630", "Id": "433338", "Score": "0", "body": "so `http://www.example.co.uk` is not a valid URL?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T09:31:01.330", "Id": "433340", "Score": "0", "body": "It is is valid." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T09:35:32.977", "Id": "433342", "Score": "3", "body": "Oh, because `findall` and not `match`, right. But this is confusing from the regex alone…" } ]
[ { "body": "<p>There is no need for reinvention of the wheel and complex pattern matching.\nUse <code>urllib.parse.urlparse</code> to check for the URL's scheme.</p>\n\n<pre><code>from urllib.parse import urlparse\n\ndef is_http_or_https(url):\n return urlparse(url).scheme in {'http', 'https'}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T10:51:28.877", "Id": "433351", "Score": "8", "body": "That might be true, but the OP took this from a book to learn Python coding by example, and I'm pretty sure \"use a library\" was not the main goal of that chapter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T13:18:04.257", "Id": "433372", "Score": "2", "body": "I am here to review given code to help improve it. If some random coding learning book insists on not using libraries designed to solve a specific problem, the best purpose it can serve is as a combustible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T13:28:54.487", "Id": "433374", "Score": "2", "body": "No need to get destructive here. The author chose to use the URL scheme as an example to learn something about regular expressions. One might argue if that is the best example to teach them, but it's certainly a recognizable one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-02T14:32:26.983", "Id": "447793", "Score": "0", "body": "Yes, you can offer that feedback, however I think it's easy to argue that this suggestion really doesn't improve the code or its intended use. Especially given that it's tagged *reinventing-the-wheel*, showing that OP specifically intends to circumvent existing libraries to work on a specific skill, which in this case is regex" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T09:02:35.487", "Id": "223555", "ParentId": "223549", "Score": "0" } }, { "body": "<h1>Variable Names</h1>\n\n<p>Variables should be lower-cased and snake-case, meaning that multiple words should look like <code>some_variable</code>, not <code>someVariable</code> or <code>SomeVariable</code>. I think the name you've chosen for your regex is good and expresses exactly what it is:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>protocol_regex = re.compile(...)\n</code></pre>\n\n<h1>Checking length of a list/container data structure</h1>\n\n<p>It is not considered pythonic to check the emptiness of a container in python by using <code>if len(container) == 0</code>, most* containers have a <code>__bool__</code> method built-in that allows you to do <code>if not container</code> for an empty one and <code>if container</code> for non-empty:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from collections import deque\n\nif not {}:\n print(\"empty dict\")\nempty dict\n\nif not []:\n print(\"empty list\")\nempty list\n\nif not '':\n print(\"empty string\")\nempty string\n\nif not deque():\n print(\"empty deque\")\nempty deque\n\nif ['result1']:\n print('non-empty list')\nnon-empty list\n</code></pre>\n\n<p>One of the few that does <em>not</em> behave this way is <a href=\"https://docs.python.org/3/library/queue.html\" rel=\"nofollow noreferrer\"><code>queue.Queue</code></a>, which I've included to give context to the <em>most</em> comment.</p>\n\n<p>With this in mind, change your <code>match</code> check to:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if matches:\n # rest of code\nelse:\n # else code here\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-02T14:38:58.573", "Id": "447794", "Score": "2", "body": "Your point on multi-line strings and the regex would usually be correct, but not in this case: the `re.VERBOSE` flag makes sure that whitespace is ignored and comments are possible, see https://docs.python.org/3/library/re.html#re.VERBOSE" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-02T14:42:37.457", "Id": "447796", "Score": "0", "body": "@RafG ooo, missed that one. Time for some reading. Good catch, I'll make an edit" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-02T14:44:09.417", "Id": "447797", "Score": "0", "body": "@RafG I suppose that raises a question, is it better practice to use `re.VERBOSE` and triple-quote your regex, or to use parentheses and break up the raw strings for multiline statements? Asking for my own enrichment here" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-03T08:11:19.470", "Id": "447908", "Score": "1", "body": "There are some advantages to breaking up the raw strings for sure: syntax highlighting to more easily distinguish comments and no need to escape whitespace characters if the regex contains any. On the other hand,`re.VERBOSE` feels less 'heavy' to me (admittedly this is very subjective) and is somewhat more flexible. E.g., you can 'indent' parts of your regex to make the structure clearer ([example](https://stackoverflow.com/a/49955966/183054)), the string with the regex and comments can be loaded from a file, etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-03T13:46:14.873", "Id": "447950", "Score": "1", "body": "Loading the regex from a file seems extremely advantageous. Never knew that could be a use case, thanks!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-02T14:22:12.210", "Id": "230034", "ParentId": "223549", "Score": "3" } }, { "body": "<p>The regular expression is inadequate for real domain names. Here's a few actual examples that fail:</p>\n\n<pre><code>http://hes.scot/\nhttps://WWW.historicenvironment.scot/\nhttps://www.bbc.co.uk\nhttps://WWW.BBC.CO.UK\n</code></pre>\n\n<p>These are extracted as</p>\n\n<pre><code>http://hes.sco\nhttps://WWW.his\nhttps://www.bbc.co\nhttps://WWW.BBC\n</code></pre>\n\n<p>Domain names are case-insensitive, can contain any number of levels, and need not end in a component having 2 or 3 letters.</p>\n\n<p>(Note that the <em>scheme</em> name - <code>http</code> or <code>https</code> - <em>is</em> case-sensitive, as is the local part of a URL).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-02T15:11:59.710", "Id": "230040", "ParentId": "223549", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T08:23:58.263", "Id": "223549", "Score": "8", "Tags": [ "python", "beginner", "python-3.x", "regex", "reinventing-the-wheel" ], "Title": "Find website URLs that begin with http:// or https://" }
223549
<p>I made a WPF Application, called Palindrome Checker, which checks if what you input is a palindrome. </p> <p>Any and all tips on how to make this code better in all capacities are wanted and appreciated.</p> <pre><code>public class Check { /// &lt;summary&gt; /// Method for checking if the word/text is a palindrome. /// &lt;/summary&gt; public static bool IsPalindrome(string text) { int min = 0; int max = text.Length - 1; while (true) { if (min &gt; max) { return true; } char a = text[min]; char b = text[max]; if (a != b) { return false; } min++; max--; } } } </code></pre> <pre><code>public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); lblInput.Foreground = Brushes.ForestGreen; lblResult.Foreground = Brushes.ForestGreen; lblTitel.Foreground = Brushes.ForestGreen; } /// &lt;summary&gt; /// User input and checking the input if the word a palindrome is. /// &lt;/summary&gt; private void InputText_TextChanged(object sender, TextChangedEventArgs e) { string text = InputText.Text; bool isPalindrome = Check.IsPalindrome(text); OutputText.Text = text + (isPalindrome ? " is a palindrome" : " is NOT a palindrome"); if(InputText.Text == string.Empty) OutputText.Clear(); } } </code></pre>
[]
[ { "body": "<h2>Specification</h2>\n\n<h3>Palindrome</h3>\n\n<p>From <a href=\"https://en.wikipedia.org/wiki/Palindrome\" rel=\"noreferrer\">wikipedia</a>:</p>\n\n<blockquote>\n <p>A palindrome is a word, number, phrase, or other sequence of\n characters which reads the same backward as forward, such as madam or\n racecar or the number 10801. Sentence-length palindromes may be\n written when allowances are made for adjustments to capital letters,\n punctuation, and word dividers, such as \"A man, a plan, a canal,\n Panama!\", \"Was it a car or a cat I saw?\" or \"No 'x' in Nixon\".</p>\n</blockquote>\n\n<p>We can argue that your specification is stricter/simpler than that of wikipedia.</p>\n\n<h3>Unicode compliance</h3>\n\n<p>Your algorithm checks <em>characters</em>, not actual <em>glyphs</em>. This is OK for most applications that use ASCII, ANSI or other encodings that represent characters with 16 bits as limit. But for extended unicode, combining characters and other diacritics, your algorithm is flawed.</p>\n\n<hr>\n\n<h2>Design</h2>\n\n<h3>Guard arguments</h3>\n\n<p>You provide a <code>public</code> method, so argument checks are in place.</p>\n\n<pre><code>if (text == null) throw new ArgumentNullException(nameof(text));\n</code></pre>\n\n<h3>While (true) loops</h3>\n\n<p>Many consider <code>while (true)</code> bad practice, because it can lead to infinite loops in missing edge cases. Specially when code gets more complex, this is the case. Consider refactoring the loop to use a <code>boolean</code>. However, since this is a trivial and simple algorithm, I understand why you have done it like this.</p>\n\n<h3>Unnecessary variables</h3>\n\n<p>Since the variables <code>a</code> and <code>b</code> are only used once, there is no need to create variables.</p>\n\n<blockquote>\n<pre><code>char a = text[min];\nchar b = text[max];\n\nif (a != b) {\n return false;\n}\n</code></pre>\n</blockquote>\n\n<p>Shorter:</p>\n\n<pre><code>if (text[min] != text[max]) {\n return false;\n}\n</code></pre>\n\n<h3>Lack of variables</h3>\n\n<p>Consider creating variables for objects you require on multiple occasions.</p>\n\n<blockquote>\n<pre><code>lblInput.Foreground = Brushes.ForestGreen;\nlblResult.Foreground = Brushes.ForestGreen;\nlblTitel.Foreground = Brushes.ForestGreen;\n</code></pre>\n</blockquote>\n\n<pre><code>public Brush ForegroundColor { get; } = Brushes.ForestGreen;\n\nlblInput.Foreground = ForegroundColor;\nlblResult.Foreground = ForegroundColor;\nlblTitel.Foreground = ForegroundColor;\n</code></pre>\n\n<h3>Normalize user input</h3>\n\n<p>You could argue that whitespace at the start or end of the input is mostly unintentional, so you should trim it. This depends on your guidelines for best practices concerning user experience.</p>\n\n<blockquote>\n <p><code>string text = InputText.Text;</code></p>\n</blockquote>\n\n<pre><code> var text = InputText.Text.Trim();\n</code></pre>\n\n<h3>Formatted strings</h3>\n\n<p>Formatted strings are cleaner and better optimized than concatenating strings.</p>\n\n<blockquote>\n <p><code>OutputText.Text = text + (isPalindrome ? \" is a palindrome\" : \" is NOT a palindrome\");</code></p>\n</blockquote>\n\n<pre><code>OutputText.Text = $\"text is{(isPalindrome ? \" \" : \" NOT \")}a palindrome\";\n</code></pre>\n\n<h3>Unoptimized code flow</h3>\n\n<p>This code clears the output after checking for a palindrome. You should put this before the check, and only calculate the palindrome if any non-empty input is provided.</p>\n\n<blockquote>\n<pre><code>if(InputText.Text == string.Empty)\n OutputText.Clear();\n</code></pre>\n</blockquote>\n\n<h3>WPF design</h3>\n\n<p>For a trivial UI, using the code-behind of a control is fine. Consider using M-V-VM when you decide to extend the design and make it more complex.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T14:21:38.043", "Id": "433377", "Score": "1", "body": "Unless I a mistaken, a C# character can hold all Unicodes up to U+FFFF, that is more than just “ASCII or ANSI.”" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T14:22:42.257", "Id": "433378", "Score": "0", "body": "@MartinR You are right, I should not use the word _only_ here." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T14:14:08.960", "Id": "223568", "ParentId": "223553", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T08:53:18.373", "Id": "223553", "Score": "5", "Tags": [ "c#", "strings", "wpf" ], "Title": "WPF Palindrome Checker Application" }
223553
<p>I am attempting to port a linear function that I designed in a spreadsheet into HTML and Javascript. It's based on <a href="https://en.wikipedia.org/wiki/Linear_least_squares" rel="nofollow noreferrer">linear least squares</a> where I have to take a Matrix and multiply it by its transformation. At any rate. I am attempting to lay out a basic input system in Javascript/HTML where I can enter in variable data. I have to take in quite a few more inputs, so I am looking for a more maintainable code pattern with less duplication.</p> <p>In the name of make it work, then make it better. I came up with the following code.</p> <p>Very new to javascript and the scope is hurting my brain! I am thinking that a dictionary (or similar) where I can pass that to a function then iterate over the values to update my HTML view. But again I am really new to Javascript. </p> <p>The code also in <a href="https://jsbin.com/lanocud/edit?html,js,output" rel="nofollow noreferrer">JS BIN</a>.</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> window.onload = function() { var EnameField = document.getElementById('EnameField'); var ENameValue = undefined; var MnameField = document.getElementById('MnameField'); var MNameValue = undefined; var CnameField = document.getElementById('CnameField'); var CNameValue = undefined; var FnameField = document.getElementById('FnameField'); var FNameValue = undefined; updateNameDisplay(); setInterval(updateNameDisplay, 100); function updateNameDisplay() { var thisEValue = EnameField.value || " "; if (ENameValue != thisEValue) { document.getElementById('EnameDisplay').innerHTML = ENameValue = thisEValue; } var thisMValue = MnameField.value || " "; if (MNameValue != thisMValue) { document.getElementById('MnameDisplay').innerHTML = MNameValue = thisMValue; } var thisCValue = CnameField.value || " "; if (CNameValue != thisCValue) { document.getElementById('CnameDisplay').innerHTML = CNameValue = thisCValue; } var thisFValue = FnameField.value || " "; if (FNameValue != thisFValue) { document.getElementById('FnameDisplay').innerHTML = FNameValue = thisFValue; } } };</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset=utf-8 /&gt; &lt;title&gt;Test Page&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form&gt; How many E's &lt;input type='text' id='EnameField'&gt;&lt;br&gt; How many M's &lt;input type='text' id='MnameField'&gt;&lt;br&gt; How many C's &lt;input type='text' id='CnameField'&gt;&lt;br&gt; How many F's &lt;input type='text' id='FnameField'&gt;&lt;br&gt; &lt;/form&gt; &lt;hr&gt; E's: &lt;span id='EnameDisplay'&gt;??&lt;/span&gt;&lt;br&gt; M's:&lt;span id='MnameDisplay'&gt;??&lt;/span&gt;&lt;br&gt; C's: &lt;span id='CnameDisplay'&gt;??&lt;/span&gt;&lt;br&gt; F's: &lt;span id='FnameDisplay'&gt;??&lt;/span&gt;&lt;br&gt; &lt;/body&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<h1>Handling the Problem</h1>\n\n<p>To make this scalable you need to generate the HTML to fit however many items you want to include. To Render it this way you need a data structure to hold what you want to render. </p>\n\n<p>First Think of the data structure then what functions you need to render this data.</p>\n\n<h1>My Solution</h1>\n\n<p>I picked the following data structure.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>[{\n title: String\n value: Number\n}]\n</code></pre>\n\n<p>Here is the list of render functions I picked.</p>\n\n<ul>\n<li>renderForm -> Render just the form</li>\n<li>renderResults -> Render just the results</li>\n<li>render -> Render the entire screen</li>\n</ul>\n\n<p>And finally, we will need to capture the data changes from the form to update the data structure and then call <code>renderResults</code> so I created the <code>onFormChange</code> function.</p>\n\n<h1>Code</h1>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// Code goes here\n\nconst data = [{\n title: 'E',\n value: 0\n}, {\n title: 'M',\n value: 0\n}, {\n title: 'C',\n value: 0\n}, {\n title: 'F',\n value: 0\n}]\n\nfunction onFormChange (value, i) {\n data[i].value = value;\n renderResults();\n}\n\nfunction renderForm () {\n const elForm = document.getElementById('form');\n let html = '';\n elForm.innerHTML = '';\n data.forEach((d, i) =&gt; {\n html += `\n How many ${d.title}'s \n &lt;input type='text' value=${d.value} onchange=\"onFormChange( this.value, ${i})\"&gt;\n &lt;br&gt;\n `;\n })\n elForm.innerHTML = html;\n}\nfunction renderResults () {\n const elResults = document.getElementById('results');\n let html = '';\n elResults.innerHTML = '';\n // Render Each Element\n data.forEach((d, i) =&gt; {\n html += `\n ${d.title}: ${d.value}&lt;br&gt;\n `;\n })\n // Render Total\n let sum = 0;\n data.forEach((d) =&gt; {\n sum += Number(d.value) || 0\n })\n html += `\n &lt;div&gt;Total is ${sum}&lt;/div&gt;\n `\n elResults.innerHTML = html;\n}\n\nfunction render () {\n renderForm()\n renderResults()\n}\n\nwindow.onload = render;\n </code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;!DOCTYPE html&gt;\n&lt;html&gt;\n &lt;head&gt;\n &lt;/head&gt;\n\n &lt;body&gt;\n &lt;form id=\"form\"&gt;\n &lt;/form&gt;\n &lt;hr&gt;\n &lt;div id=\"results\"&gt;\n &lt;/div&gt;\n &lt;/body&gt;\n\n&lt;/html&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<h1>Final Thoughts</h1>\n\n<p>I did add a total div at the end of the results to show how you can also do some calculations on the entire data set when any of the values change.</p>\n\n<p>Go ahead and add any additional data to the <code>data</code> array and have fun with it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T13:29:38.817", "Id": "223567", "ParentId": "223560", "Score": "2" } } ]
{ "AcceptedAnswerId": "223567", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T11:04:46.720", "Id": "223560", "Score": "3", "Tags": [ "javascript", "beginner", "form", "html5", "dom" ], "Title": "Basic input system for a few form fields" }
223560
<p>So currently I'm working on cleaning up a recently developed project and notice a lot of potentially un-needed code; whereas I create separate functions for very minimal stuff..</p> <p>Here's an example of a module export I've done:</p> <pre><code>//MemCache const Cache = require('memcached-promisify'); const cache = new Cache(); module.exports = { suppression_times: function(key) { let times = { bm_notices: this.secs('1 hour') }; return times[key]; }, suppression_get: async function(_id, key, cb) { let mem_key; if (!this.suppression_times[key]) { return cb(new Error('Suppression key `' + key + '` does not exist')); } mem_key = [_id, key].join(':'); const result = await cache.get(mem_key); if (result !== undefined) { return cb(null, result); } return cb(result); }, suppression_set: async function(_id, key, cb) { let mem_key, secs, time; if (!(secs = suppression_times[key])) { return cb(new Error('Suppression key `' + key + '` does not exist')); } mem_key = [_id, key].join(':'); const result = await cache.set(mem_key, (time = this.time()), secs); if (result !== undefined) { return cb(null, time); } return cb(result); }, secs: function(str) { let result; result = require('english-time-mirror')(str); return Math.round(parseInt(result / 1000)); }, time: function() { let d = new Date().getTime() / 1000; return Math.round(d); } } </code></pre> <p>How could I go about improving this?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T11:47:53.433", "Id": "223561", "Score": "1", "Tags": [ "javascript", "node.js" ], "Title": "Cleaning up get/set functions in Node export" }
223561
<p>I practiced my Java knowledge in the last couple of days. For that, I want to create a Rest API in a trimmed scale, because there a lot of aspects which must be considered in such an API (Login, Session handling ...). A lot of details aren't implemented, but the top priority was to understand the interaction/communication of the different modules and using some best practices.</p> <p>Here is my project so far.</p> <p>The Interface for a Resource:</p> <pre><code>package server; import java.util.HashMap; public interface Resource { public Response run(HttpMethod method, HashMap&lt;String, String&gt; params) throws WebException; } </code></pre> <p>The Base Class for a Resource:</p> <pre><code>package server; import java.util.ArrayList; public abstract class ResourceBase implements Resource { protected List&lt;HttpMethod&gt; allowedMethods = new ArrayList&lt;&gt;(); protected HttpMethod httpMethod; protected HashMap&lt;String, String&gt; params; protected boolean needsAuthentication = true; protected abstract Response runResource() throws WebException; @Override public Response run(HttpMethod method, HashMap&lt;String, String&gt; params) throws WebException { this.httpMethod = method; this.params = params; if(!isMethodAllowed(method)) throw new MethodNotAllowedException("Method not allowed"); if(this.needsAuthentication &amp;&amp; !isUserAuthenticated(params.get("userName"))) throw new UnauthorizedException("no Session for User"); return runResource(); } private boolean isMethodAllowed(HttpMethod method) { return this.allowedMethods.stream().filter(m -&gt; m == method).findAny().isPresent(); } private boolean isUserAuthenticated(String userName) throws UnauthorizedException { return SessionHandler.getInstance().hasSession(userName) ? true : false; } } </code></pre> <p>A concrete Implementation for a Resource. This a Resource for the User's Login:</p> <pre><code>package server; import java.util.Optional; public class LoginResource extends ResourceBase { public LoginResource() { this.needsAuthentication = false; this.allowedMethods.add(HttpMethod.PUT); } @Override protected Response runResource() throws WebException { if(this.httpMethod == HttpMethod.PUT) return runPut(); // will never reached because the allowed methods will be checked before return null; } private Response runPut() throws WebException { String paramUserName = this.params.get("userName"); if(!SessionHandler.getInstance().hasSession(paramUserName)) { SessionHandler.getInstance().createSession(paramUserName); } return new Response(HttpCode.OK, Optional.empty()); } } </code></pre> <p>The Login Resource uses the SessionHandler, which will start/end the connections and will cache them (as a result I used the Singleton Pattern):</p> <pre><code>package server; import java.util.ArrayList; public class SessionHandler { private List&lt;User&gt; sessions = new ArrayList&lt;&gt;(); public static SessionHandler getInstance() { return SingletonHelper.INSTANCE; } private static class SingletonHelper { private static final SessionHandler INSTANCE = new SessionHandler(); } private SessionHandler() {} public void createSession(String userName) throws PermissionDeniedException { User user = UserDatabase.getInstance().getUser(userName).orElseThrow( () -&gt; new PermissionDeniedException( "User doesn't exist!" ) );; sessions.add(user); } public boolean hasSession(String userName) { return sessions.stream().filter(u -&gt; u.getName().equalsIgnoreCase(userName)).findAny().isPresent(); } public void destroySession(String userName) { sessions = sessions.stream().filter(u -&gt; !u.getName().equalsIgnoreCase(userName)).collect(Collectors.toList()); } } </code></pre> <p>The Response Class:</p> <pre><code>package server; import java.util.Optional; public class Response { private HttpCode httpCode; private Optional&lt;String&gt; value; Response(HttpCode httpCode, Optional&lt;String&gt; value) { this.httpCode = httpCode; this.value = value; } public boolean wasSuccessful() { return this.httpCode.getCode() &gt;= 200 &amp;&amp; this.httpCode.getCode() &lt; 300 ? true : false; } public HttpCode getHttpCode() { return httpCode; } public void setHttpCode(HttpCode httpCode) { this.httpCode = httpCode; } public Optional&lt;String&gt; getValue() { return value; } public void setValue(Optional&lt;String&gt; value) { this.value = value; } } </code></pre> <p>The "main" class for the Server's API is this:</p> <pre><code>package server; import java.util.HashMap; public class RestApi { public Response executeResource(String resourceName, HttpMethod method, HashMap&lt;String, String&gt; params) { try { Resource res = getResource(resourceName).orElseThrow(() -&gt; new NotFoundException("Resource" + resourceName + "not found")); return res.run(method, params); } catch (WebException ex) { System.err.printf("Error during request: %s. Http Code: %d.%n", ex.getMessage(), ex.getHttpCode().getCode()); return new Response(ex.getHttpCode(), Optional.empty()); } } private Optional&lt;Resource&gt; getResource(String name) { switch(name) { case "login": return Optional.of(new LoginResource()); case "update-role": return Optional.of(new RoleResource()); default: return Optional.empty(); } } } </code></pre> <p>The concrete Resource will be determined on the passed resourceName.</p> <p>And here are the Exception Types. Starting with the Base Class:</p> <pre><code>package server; public class WebException extends Exception { private static final long serialVersionUID = 1L; private HttpCode httpCode; public WebException(HttpCode httpCode, String errorMessage) { super(errorMessage); this.httpCode = httpCode; } public HttpCode getHttpCode() { return httpCode; } } </code></pre> <p>And here is one subtype (the subtyes differ only in the http code):</p> <pre><code>package server; public class MethodNotAllowedException extends WebException { private static final long serialVersionUID = 1L; public MethodNotAllowedException(String errorMessage) { super(HttpCode.METHOD_NOT_ALLOWED, errorMessage); // TODO Auto-generated constructor stub } } </code></pre> <p>The enum for the possible http codes:</p> <pre><code>package server; public enum HttpCode { OK(200), UNAUTHORIZED(401), PERMISSION_DENIED(403), NOT_FOUND(404), METHOD_NOT_ALLOWED(405); private final Integer code; HttpCode(Integer httpCode) { this.code = httpCode; } public Integer getCode() { return this.code; } } </code></pre> <p>And the enum for the http methods:</p> <pre><code>package server; public enum HttpMethod { PUT, POST, GET, DELETE } </code></pre> <p>And this is a call from the client for this resource:</p> <pre><code>return api.executeResource("login", HttpMethod.PUT, params).wasSuccessful() ? true : false; </code></pre> <p>It would be very nice if someone can check the source code and give me some hints, what an experienced progamer would do in a different way.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T12:21:04.727", "Id": "223562", "Score": "3", "Tags": [ "java", "api", "rest" ], "Title": "Rest API in a trimmed model" }
223562
<p>I tried to solve some Euler's problems, this is the solution I found for problem #3 with Python. The problem asks:</p> <blockquote> <p>The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ?</p> </blockquote> <p>How can I improve my code?</p> <pre><code>def get_largest_prime2(value): start = time.clock() #used to measure the execution time divisors = [] #this list will be filled with all number's divisors i = 1 while value != 1: while value%i == 0: #check if the value can be divided by i and, if so, iterate the process. value = (value // i) divisors.append(i) if i == 1 : break #it's needed to avoid an infinity loop if i &gt;= 3: i += 2 #when i is bigger than 3, search divisors among odd numbers( this reduces the search field) else: i += 1 print( time.clock()-start) return max(divisors) #returns the max prime divisors </code></pre>
[]
[ { "body": "<h1>timing</h1>\n<p>Put the code to time the run time of the function outside of the function.</p>\n<h1>augmented assignment</h1>\n<p><code>value = (value // i)</code> can be expressed as <code>value //= i</code></p>\n<h1><code>divisors</code></h1>\n<p>Why do you need to keep a list of divisors? They only ask for the largest one. The largest one will always be the last one, so you just need to remember that.</p>\n<h1>pep-8</h1>\n<ul>\n<li>Your variable names are clear and in the correct format, apart from <code>i</code>. I would rename that to <code>divisor</code> or <code>prime</code>.</li>\n<li>The spacing around the operators and <code>(</code> is inconsistent.</li>\n<li>the <code>if i &gt;= 3: i += 2</code> on one line is advised against.</li>\n</ul>\n<h1>increments</h1>\n<pre><code> if i &gt;= 3: i += 2 #when i is bigger than 3, search divisors among odd numbers( this reduces the search field)\n else: i += 1 \n</code></pre>\n<p>can be simplified to <code>i += (2 if i &gt;= 3 else 1)</code> or even <code>i += 1 + (i &gt;= 3)</code>, using the fact that <code>int(True)</code> is <code>1</code>. But here you don't use the fact that your divisors are all primes. A quicker process would be to get the next possible divisor from a prime generator, instead of incrementing by 2 manually.</p>\n<h1>while loop</h1>\n<p>You can integrate the <code>if i == 1 : break</code> into the condition for the while loop: <code>while value % prime == 0 and value != 1:</code></p>\n<hr />\n<pre><code>def largest_prime_divisor(value):\n largest_divisor = 1\n for prime in prime_generator():\n while value % prime == 0 and value != 1:\n value //= prime \n largest_divisor = prime \n return largest_divisor\n</code></pre>\n<p>Possible implementations of <code>prime_generator</code> can be found in dozens of SO and Code review posts.</p>\n<h1>shortcut</h1>\n<p>If the divisor is larger than the square root of the value, you know the next divisor will be the value itself, so you can shortcut when the divisor exceeds this.</p>\n<pre><code>def largest_prime_divisor(value):\n largest_divisor = 1\n for prime in prime_generator():\n while value % prime == 0:\n value //= prime \n largest_divisor = prime \n if prime ** 2 &gt; value:\n return max(largest_divisor, value)\n return largest_divisor\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T22:07:10.450", "Id": "433558", "Score": "0", "body": "The special case check for i = 1 can equally be avoided by starting i as 2." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T14:27:32.850", "Id": "223570", "ParentId": "223564", "Score": "4" } }, { "body": "<p>from math import sqrt</p>\n<p>def largest_prime(num):</p>\n<pre><code>list=[]\nnumber=int(sqrt(num))+1\nfor i in range(2,number):\n if num%i==0:\n while num%i==0:\n num/=i\n list.append(i)\n elif num&lt;i:\n break\nreturn max(list)\n</code></pre>\n<p>print(largest_prime(600851475143))</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T09:39:52.787", "Id": "527921", "Score": "4", "body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T07:02:09.750", "Id": "267721", "ParentId": "223564", "Score": "-3" } }, { "body": "<p>Supplement to <a href=\"/a/223570/75307\">Maarten Fabré's answer</a>:</p>\n<p>We don't even need to remember <code>largest_divisor</code>, as we can simply use <code>value</code> itself. When the current prime being considered is too large to be a factor of <code>value</code>, just return <code>value</code>:</p>\n<pre><code>def largest_prime_divisor(value):\n for prime in prime_generator():\n while value &gt; prime and value % prime == 0:\n value //= prime\n if prime * prime &gt; value:\n return value\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T09:57:49.227", "Id": "267723", "ParentId": "223564", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T12:59:56.783", "Id": "223564", "Score": "2", "Tags": [ "python", "beginner", "python-3.x", "programming-challenge" ], "Title": "Project Euler #3 with Python" }
223564
<p>I wrote some code to generate <a href="https://en.wikipedia.org/wiki/Latin_hypercube_sampling" rel="nofollow noreferrer">Latin hypercube samples</a> for interpolation over high-dimensional parameter spaces. Latin hypercubes are essentially collections of points on a hypercube that are placed on a cubic/rectangular grid, which possess the property that no two points share <em>any</em> individual coordinate, and every row/column/higher-dimensional-axis is sampled once. e.g., for 2 dimensions and 4 total samples, this is a Latin hypercube:</p> <pre><code>| | | |x| | |x| | | |x| | | | | | |x| | </code></pre> <p>One algorithm for generating this is to generate D random permutations of the integers 0 through N-1, where D is the number of dimensions and N is the desired number of samples. Concatenating these together into a DxN matrix gives a list of coordinates which will form a Latin hypercube.</p> <p>I am also interested in generating a special type of Latin hypercube called a <em>symmetric</em> Latin hypercube. This property essentially means that the hypercube is invariant under <a href="https://en.wikipedia.org/wiki/Point_reflection" rel="nofollow noreferrer">spatial inversion</a>. One way of expressing this condition, is that (if the samples are zero-indexed) if the hypercube has the sample (i, j, ..., k), for some integer indices i,j,k, then it also has the sample (n-1-i, n-1-j, ..., n-1-k), where n is the number of samples. For 2D and n=4, this is an example of a symmetric Latin hypercube:</p> <pre><code>| |x| | | | | | |x| |x| | | | | | |x| | </code></pre> <p>The condensed version of why I want to do this is that I want to evaluate a function which is expensive to compute, and depends on many parameters. I pre-generate a list of values for this function at a set of points and use interpolation over the parameters to extend this list to any desired point within a set range. Latin hypercube samples are used for the pre-computation instead of a grid, with the idea that they will more efficiently sample the behavior of the function and result in lower interpolation errors.</p> <p>I have tested the code below both using automated tests and by visual inspection of the results for the trivial 2D case. Statistical tests of higher dimensional cases have convinced me it works successfully there as well. The code can produce either random Latin hypercubes or a rather nongeneral set of symmetric ones (I am convinced my second algorithm cannot in principle generate any possible symmetric Latin hypercube, just a specific type). Also, the symmetric algorithm doesn't really work properly for odd numbers of samples, so I have outright blocked such samples from being generated.</p> <p>My code can be seen along with specification and performance tests <a href="https://github.com/dylancromer/supercubos/" rel="nofollow noreferrer">here</a>, although not the visual tests at the moment. </p> <p>I am aware that my project structure is probably overkill for the amount of code here. I am mostly looking for any insights regarding my algorithms, as while they are very fast even for large dimensions and sample sizes, I don't doubt improvements exist. However any comments are welcome.</p> <pre><code>import numpy as np class LatinSampler: def _check_num_is_even(self, num): if num % 2 != 0: raise ValueError("Number of samples must be even") def get_lh_sample(self, param_mins, param_maxes, num_samples): dim = param_mins.size latin_points = np.array([np.random.permutation(num_samples) for i in range(dim)]).T lengths = (param_maxes - param_mins)[None, :] return lengths*(latin_points + 0.5)/num_samples + param_mins[None, :] def get_sym_sample(self, param_mins, param_maxes, num_samples): self._check_num_is_even(num_samples) dim = param_mins.size even_nums = np.arange(0, num_samples, 2) permutations = np.array([np.random.permutation(even_nums) for i in range(dim)]) inverses = (num_samples - 1) - permutations latin_points = np.concatenate((permutations,inverses), axis=1).T lengths = (param_maxes - param_mins)[None, :] return lengths*(latin_points + 0.5)/num_samples + param_mins[None, :] </code></pre> <p>Edit: I glossed over this, but this code doesn't return Latin hypercubes <em>per se</em>, but rather Latin hypercubes stretched/squeezed and shifted so that the points can be over arbitrary ranges of values. However the core code will generate a Latin hypercube if the last manipulation (multiply by <code>lengths</code> and add <code>param_mins</code>) is omitted.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T15:29:28.517", "Id": "433391", "Score": "0", "body": "I don't know if you've checked this already, but you could look at the Eight Queen Problem, which is similar to what you're trying to achieve, and is a pretty popular problem, so there are surely many solutions to the problem." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T16:28:49.570", "Id": "433397", "Score": "3", "body": "@IEatBagels: I cannot speak for the general case and I could be totally wrong, but at least for 2D this looks more like the Eight Rooks Problem since diagonally adjacent samples seem to be allowed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T17:08:00.567", "Id": "433400", "Score": "0", "body": "@AlexV This is correct, diagonal adjacency is not disallowed. Also here the concerns are a bit different from 8 Rooks. I have no interest in counting how many LHs are possible for a given N and D; I just want to generate them. The biggest concerns are speed of this generation, memory usage, and most importantly, if the \"space-filling-ness\" of them can be improved. One such criterion for space-filling-ness is called orthogonal sampling and basically says the density of the samples should be optimally uniform, but this is a far harder problem than just generating a LH." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T13:20:10.393", "Id": "433487", "Score": "0", "body": "I'm not convinced `get_lh_samples` generates latin hypercubes. It looks more like latin hypercuboids. Are you just interested in sampling from a multivariate distribution uniformly, or do you actually want to generate latin hypercubes / symmetrical latin hypercubes?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T17:27:23.587", "Id": "433516", "Score": "0", "body": "@FirefoxMetzger Do you mean in the sense that I am warping the lengths and shifting the minimum values? If so yes, indeed it doesn't actually generate Latin hypercubes. It would generate a cube when all of the parameters span the same range. This is desireable behavior for me; I want a Latin hypercube stretched to fit over the actual parameter ranges I am interested in. I am sorry for glossing over that in the question. If you mean something else I am not sure what, could you clarify?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T17:55:10.233", "Id": "433523", "Score": "0", "body": "Sure. You're looking at a `dim` dimensional hypercube that is being sliced `num_samples-1` times along each dimension, i.e., each variable is chosen from `[0, num_samples-1]` and then scaled to it's actual interval. No two points share individual coordinates and we have exactly `num_samples` many. The problem I have is, if `dim` and `num_samples` are unequal. In this case it's either impossible to find a solution `dim > num_samples` or you choose less than `num_samples` many points (not a LH)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T18:11:46.227", "Id": "433527", "Score": "0", "body": "No, I am wrong. I misunderstood what you are trying to do. Please disregard my last comment." } ]
[ { "body": "<p>Once I understood what you wanted to accomplish, your code became a lot more clear to me and I can provide some thoughts.</p>\n\n<p>Regarding the symmetrical version, you are indeed only sampling from a subset of the available symmetrical latin hypercubes. Half of the parameter space will never be chosen as samples. Consider the 2D example with n=4:</p>\n\n<p><a href=\"https://i.stack.imgur.com/TNVVp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/TNVVp.png\" alt=\"A 4x4 example image of the sampled Hypercube\"></a></p>\n\n<p><code>even_nums = [0, 2]</code> and, hence, A,B,C,D are the 4 possible samples that can be generated with this method. In fact there's two possible Latin Hypercubes: [A,D] and [B,C]. A',B',C',D' denote their respective inverse positions that are then added. As you can see, half of the fields are empty and will never be chosen as a sample.</p>\n\n<p>Instead of permuting indexes, I would sample pairs of symmetrical points directly, as it allows you to control for the constraint while still achieving uniform sampling:</p>\n\n<pre><code>import random\nimport numpy as np\n\nnum_samples = 5\ndim = 2\n\navailable_indices = [set(range(num_samples)) for _ in range(dim)]\nsamples = []\n\n# if num_samples is odd, we have to chose the midpoint as a sample\nif num_samples % 2 != 0:\n k = num_samples//2\n samples.append([k] * dim)\n for idx in available_indices:\n idx.remove(k)\n\n# sample symmetrical pairs\nfor _ in range(num_samples//2):\n sample1 = list()\n sample2 = list()\n\n for idx in available_indices:\n k = random.sample(idx, 1)[0]\n sample1.append(k)\n sample2.append(num_samples-1-k)\n idx.remove(k)\n idx.remove(num_samples-1-k)\n\n samples.append(sample1)\n samples.append(sample2)\n\nsamples = np.array(samples)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T19:58:33.063", "Id": "223644", "ParentId": "223569", "Score": "4" } }, { "body": "<p>You can use the <a href=\"https://scipy.github.io/devdocs/reference/generated/scipy.stats.qmc.LatinHypercube.html\" rel=\"nofollow noreferrer\"><code>LatinHypercube</code></a> class which I added to SciPy in version 1.7. This can replace most of the code here.</p>\n<p>To generate a LHS, one simply can generate a uniform sample U(0, 1) and shift it with random permutations of integers, like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import numpy as np\n\nn, d = ...\nrng = np.random.default_rng()\nsamples = rng.uniform(size=(n, d))\nperms = np.tile(np.arange(1, n + 1), (d, 1))\nfor i in range(d):\n rng.shuffle(perms[i, :])\nperms = perms.T\n\nsamples = (perms - samples) / n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-01T13:20:13.217", "Id": "524625", "Score": "1", "body": "Hej @tupui ... the world is a small place. This is a cool new feature and is certainly related; however, I believe the question here is/was primarily looking for _symmetric_ LatinHypercubes. I checked the docs, but I couldn't figure out if this was an option. If there is the option to constrain samples to this subset, perhaps adding it here would address above comments? (as: the provided code can now be refactored into a one-liner)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-01T13:34:07.090", "Id": "524626", "Score": "0", "body": "@FirefoxMetzger indeed! There is no symmetric option yet. Reading about the problem, it's not really a symmetry but a rotation invariance. If you are interested to add it in SciPy, I would be happy to review a PR ;)\nTobySpeight sorry I should have put a comment I guess. I will edit to add some code at least." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-01T12:30:37.817", "Id": "265597", "ParentId": "223569", "Score": "0" } } ]
{ "AcceptedAnswerId": "223644", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T14:25:45.820", "Id": "223569", "Score": "8", "Tags": [ "python", "python-3.x", "numpy", "statistics" ], "Title": "Generating Latin hypercube samples with numpy" }
223569
<p>Here is the problem: some script is injecting some HTML5 elements (actually a button with the <code>#thebutton</code> ID) to the current DOM. </p> <p>But this is a third party script and I have no control of when this will be injected to the page. I need to click automatically on this button when the button is injected to the DOM. Here is my solution so far. </p> <p>It's actually working but I'm not sure on how fine this code is. My first guess is that I may use the <code>clearTimeout()</code> method. Is there anything else I must do?</p> <pre><code>&lt;script type="text/javascript"&gt; function waitForElementToDisplay(selector, time) { if (document.querySelector(selector) !== null) { document.getElementById("thebutton").click(); return; } else { setTimeout(function () { waitForElementToDisplay(selector, time); }, time); } } // onload (function () { waitForElementToDisplay("#thebutton", 500); })(); &lt;/script&gt; </code></pre> <p>Here is a simulated jsFiddle of the whole process: <a href="https://jsfiddle.net/qxpcj3wm/" rel="nofollow noreferrer">https://jsfiddle.net/qxpcj3wm/</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T14:40:46.657", "Id": "433382", "Score": "0", "body": "Could you provide us a scenario (actual html, script) where you would use this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T14:42:48.353", "Id": "433383", "Score": "0", "body": "Actually it's a video player which is loaded. It has no API to force it loading and the end-user must click to a button to fully load it. I want to save this useless click for all end-users." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T14:44:39.700", "Id": "433384", "Score": "0", "body": "@dfhwze Do you require a jsfiddle of some sort?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T14:45:28.407", "Id": "433385", "Score": "0", "body": "Sure, that would do it :) Also check out mutation observers" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T14:55:36.840", "Id": "433387", "Score": "1", "body": "https://jsfiddle.net/qxpcj3wm/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T12:25:29.140", "Id": "433632", "Score": "0", "body": "Can you say which script or library you’re working with?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T07:18:43.003", "Id": "433709", "Score": "0", "body": "Actually I'm using vanilla javascript but everything is possible (jQuery, etc)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T14:39:04.450", "Id": "223571", "Score": "2", "Tags": [ "javascript", "html", "dom" ], "Title": "Wait for an element to exist in DOM before clicking it" }
223571
<p>I'm new to C++ programming, and I'm building an Image Editor software like Lightroom/CameraRaw from scratch. Apart from procedural code (actually seems that all the functions works correctly) my goal is to improve the Design of my classes. For this I used OpenCV just for basics functions like opening/reading, converting-colorSpace, and Qt creator, for the Ui.</p> <p>as below:</p> <p>ImgHandling.h</p> <pre><code>class ImgHandling { public: ImgHandling(); cv::Mat calculateHist(cv::Mat img, int channel); QImage Mat2Qimg(cv::Mat img); void imgLoad(QString path); void imgSave(QString path); cv::Mat src; cv::Mat dst; }; #endif // IMGHANDLING_H </code></pre> <p>ImgHandling.cpp</p> <pre><code>ImgHandling::ImgHandling() = default; void ImgHandling::imgLoad(QString path){ const std::string imagePath(path.toStdString()); src = cv::imread(imagePath); cvtColor(src, src, CV_BGR2RGB); dst = src.clone(); } void ImgHandling::imgSave(QString path){ QImage qimg = Mat2Qimg(dst); if(!qimg.isNull()) qimg.save(path); else QMessageBox::critical(nullptr, "Errore","Impossibile salvare il file"); } cv::Mat ImgHandling::calculateHist(cv::Mat img, int channel){ int k = 0, r = 255, g = 255, b = 255; switch (channel) { case 0: k = 0; r = 255; g = 0; b = 0; break; case 1: k = 1; r = 0; g = 255; b = 0; break; case 2: k = 2; r = 0; g = 0; b = 255; break; } int hist[256]; for(int i = 0; i &lt; 255; i++) hist[i] = 0; for(int i = 0; i &lt; img.rows; i++) for(int j = 0; j &lt; img.cols; j++) hist[(int)img.at&lt;cv::Vec3b&gt;(i,j)[k]]++; int hist_w = 299; int hist_h = 69; int bin_w = cvRound((double) hist_w/256); cv::Mat histImage(hist_h, hist_w, CV_8UC3, cv::Scalar(50, 50, 50)); int max = hist[0]; for(int i = 1; i &lt; 256; i++) if(max &lt; hist[i]) max = hist[i]; for(int i = 0; i &lt; 255; i++) hist[i] = ((double)hist[i]/max)*histImage.rows; for(int i = 0; i &lt; 255; i++) line(histImage, cv::Point(bin_w*(i), hist_h), cv::Point(bin_w*(i), hist_h - hist[i]), cv::Scalar(r,g,b), 1, 8, 0); return histImage; } QImage ImgHandling::Mat2Qimg(cv::Mat img){ QImage qimg((const uchar*) img.data, img.cols, img.rows, img.step, QImage::Format_RGB888); qimg.bits(); return qimg; } </code></pre> <p>process.h</p> <pre><code>class process{ public: process(cv::Mat&amp; src, cv::Mat&amp; dst); virtual ~process(); virtual void doProcess() = 0; protected: cv::Mat src; cv::Mat dst; }; #endif // PROCESS_H </code></pre> <p>process.cpp</p> <pre><code>process::process(cv::Mat&amp; s, cv::Mat&amp; d) : src(s), dst(d){ } process::~process(){ } </code></pre> <p>flip.h</p> <pre><code>#ifndef FLIP_H #define FLIP_H #include "process.h" class flip : process { public: flip(cv::Mat&amp; src, cv::Mat&amp; dst, bool h = false); void doProcess() override; private: bool is_Horiented; //false = verticale, true orizzontale }; #endif // FLIP_H </code></pre> <p>flip.cpp</p> <pre><code>#include "flip.h" flip::flip(cv::Mat&amp; src, cv::Mat&amp; dst, bool h) : process (src, dst), is_Horiented(h){ } void flip::doProcess(){ if(is_Horiented){ for (int i = 0; i &lt; src.rows; i++) for (int j = 0; j &lt; src.cols; j++) { int x = -i + src.rows; dst.at&lt;cv::Vec3b&gt;(i,j) = src.at&lt;cv::Vec3b&gt;(x,j); } }else { for (int i = 0; i &lt; src.rows; i++) for (int j = 0; j &lt; src.cols; j++) { int y = -j + src.cols; dst.at&lt;cv::Vec3b&gt;(i,j) = src.at&lt;cv::Vec3b&gt;(i,y); } } } </code></pre> <p>blur.h</p> <pre><code>#ifndef BLUR_H #define BLUR_H #include "kernels.h" class Blur : Kernels { public: Blur(cv::Mat&amp; src, cv::Mat&amp; dst); void applyKernel() override; //Still need to implement cpp private: const int Blur_Mat[3][3] = { {1, 2, 1} , {2, 4, 2} , {1, 2, 1} }; }; #endif // BLUR_H </code></pre> <p>hsl_process.h</p> <pre><code>#ifndef HSL_PROCESS_H #define HSL_PROCESS_H #include "process.h" class HSL_process : process { public: HSL_process(cv::Mat&amp; src, cv::Mat&amp; dst, int h = 0, int s = 0, int l = 0); void doProcess() override; private: int hue; int saturation; int luminance; }; #endif // HSL_PROCESS_H </code></pre> <p>hsl_process.cpp</p> <pre><code>#include "hsl_process.h" HSL_process::HSL_process(cv::Mat&amp; src, cv::Mat&amp; dst, int h, int s, int l) : process (src, dst), hue(h), saturation(s), luminance(l){ } void HSL_process::doProcess(){ cv::cvtColor(src, src, CV_RGB2HLS); cv::cvtColor(dst, dst, CV_RGB2HLS); for(int i = 0; i &lt; src.rows; i++) for(int j = 0; j &lt; src.cols; j++) for(int k = 0; k &lt; 3; k++){ if(k == 0) //_H dst.at&lt;cv::Vec3b&gt;(i,j)[k] = cv::saturate_cast&lt;uchar&gt;(src.at&lt;cv::Vec3b&gt;(i,j)[k] + hue); if(k == 1) //_L dst.at&lt;cv::Vec3b&gt;(i,j)[k] = cv::saturate_cast&lt;uchar&gt;(src.at&lt;cv::Vec3b&gt;(i,j)[k] + luminance); if(k == 2) //_S dst.at&lt;cv::Vec3b&gt;(i,j)[k] = cv::saturate_cast&lt;uchar&gt;(src.at&lt;cv::Vec3b&gt;(i,j)[k] + saturation); } cv::cvtColor(src, src, CV_HLS2RGB); cv::cvtColor(dst, dst, CV_HLS2RGB); } </code></pre> <p>rgb_process.h</p> <pre><code>#ifndef RGB_PROCESS_H #define RGB_PROCESS_H #include "process.h" class RGB_process : process { public: RGB_process(cv::Mat&amp; src, cv::Mat&amp; dst, int exp = 0, double c = 1, int r = 0, int g = 0, int b = 0); void doProcess() override; private: int exposure_Val; double contrast_Val; int red_Val; int green_Val; int blue_Val; }; #endif // RGB_PROCESS_H </code></pre> <p>rgb_process.cpp</p> <pre><code>#include "rgb_process.h" RGB_process::RGB_process(cv::Mat&amp; src, cv::Mat&amp; dst, int exp, double c, int r, int g, int b) : process (src, dst), exposure_Val(exp), contrast_Val(c), red_Val(r), green_Val(g), blue_Val(b){ } void RGB_process::doProcess(){ for(int i = 0; i &lt; src.rows; i++) for(int j = 0; j &lt; src.cols; j++) for(int k = 0; k &lt; 3; k++){ if(k == 0) //_R dst.at&lt;cv::Vec3b&gt;(i,j)[k] = cv::saturate_cast&lt;uchar&gt;((src.at&lt;cv::Vec3b&gt;(i,j)[k] + exposure_Val + red_Val )*(259 * (contrast_Val + 255) / (255 * (259 - contrast_Val)))); if(k == 1) //_G dst.at&lt;cv::Vec3b&gt;(i,j)[k] = cv::saturate_cast&lt;uchar&gt;((src.at&lt;cv::Vec3b&gt;(i,j)[k] + exposure_Val + green_Val )*(259 * (contrast_Val + 255) / (255 * (259 - contrast_Val)))); if(k == 2) //_B dst.at&lt;cv::Vec3b&gt;(i,j)[k] = cv::saturate_cast&lt;uchar&gt;((src.at&lt;cv::Vec3b&gt;(i,j)[k] + exposure_Val + blue_Val )*(259 * (contrast_Val + 255) / (255 * (259 - contrast_Val)))); } } </code></pre> <p>kernels.h</p> <pre><code>#ifndef KERNELS_H #define KERNELS_H #include &lt;opencv2/core/core.hpp&gt; #include &lt;opencv2/highgui/highgui.hpp&gt; #include &lt;opencv2/imgproc/imgproc.hpp&gt; #include &lt;opencv2/imgcodecs.hpp&gt; class Kernels{ public: Kernels(cv::Mat&amp; s, cv::Mat&amp; d); virtual ~Kernels(); virtual void applyKernel() = 0; protected: cv::Mat src; cv::Mat dst; }; #endif // KERNELS_H </code></pre> <p>kernels.cpp</p> <pre><code>#include "kernels.h" Kernels::Kernels(cv::Mat&amp; s, cv::Mat&amp; d) : src(s), dst(d){ } Kernels::~Kernels(){ } </code></pre> <p>matrix_filters.h</p> <pre><code> #ifndef MATRIX_FILTERS_H #define MATRIX_FILTERS_H #include "process.h" class Matrix_Filters : process { public: Matrix_Filters(cv::Mat&amp; src, cv::Mat&amp; dst, std::string c = "BW"); void doProcess() override; private: std::string choice; const double sepia_Mat[3][3] = { {0.393, 0.769, 0.189} , {0.349, 0.686, 0.168} , {0.272, 0.534, 0.131} }; const double bw_Mat[3][3] = { {0.2126, 0.7152, 0.0722} , {0.2126, 0.7152, 0.0722} , {0.2126, 0.7152, 0.0722} }; }; #endif // MATRIX_FILTERS_H matrix_filter.cpp #include "matrix_filters.h" Matrix_Filters::Matrix_Filters(cv::Mat&amp; src, cv::Mat&amp; dst, std::string c) : process (src, dst), choice(c) { } void Matrix_Filters::doProcess(){ if(choice == "BW") for(int i = 0; i &lt; src.rows; i++) for(int j = 0; j &lt; src.cols; j++) for(int k = 0; k &lt; 3; k++){ dst.at&lt;cv::Vec3b&gt;(i,j)[k] = 0; for (int m = 0; m &lt; 3; m++) dst.at&lt;cv::Vec3b&gt;(i,j)[k] += (bw_Mat[k][m]*(src.at&lt;cv::Vec3b&gt;(i,j)[m])); } if(choice == "SEPIA") for(int i = 0; i &lt; src.rows; i++) for(int j = 0; j &lt; src.cols; j++) for(int k = 0; k &lt; 3; k++){ dst.at&lt;cv::Vec3b&gt;(i,j)[k] = 0; for (int m = 0; m &lt; 3; m++) dst.at&lt;cv::Vec3b&gt;(i,j)[k] += (sepia_Mat[k][m]*(src.at&lt;cv::Vec3b&gt;(i,j)[m])); } } </code></pre> <p>rotation.h</p> <pre><code>#ifndef ROTATION_H #define ROTATION_H #include "process.h" class rotation : process { public: rotation(cv::Mat&amp; src, cv::Mat&amp; dst, int a = 0); void doProcess() override; protected: int angle; }; #endif // ROTATION_H </code></pre> <p>rotation.cpp</p> <pre><code>#include "rotation.h" rotation::rotation(cv::Mat&amp; src, cv::Mat&amp; dst, int a) : process (src, dst), angle(a){ } void rotation::doProcess(){ float rads = angle*3.1415926/180.0; float _cos = cos(-rads); float _sin = sin(-rads); float xcenter = (float)(src.cols)/2.0; float ycenter = (float)(src.rows)/2.0; for(int i = 0; i &lt; src.rows; i++) for(int j = 0; j &lt; src.cols; j++){ int x = ycenter + ((float)(i)-ycenter)*_cos - ((float)(j)-xcenter)*_sin; int y = xcenter + ((float)(i)-ycenter)*_sin + ((float)(j)-xcenter)*_cos; if (x &gt;= 0 &amp;&amp; x &lt; src.rows &amp;&amp; y &gt;= 0 &amp;&amp; y &lt; src.cols) { dst.at&lt;cv::Vec3b&gt;(i ,j) = src.at&lt;cv::Vec3b&gt;(x, y); } else dst.at&lt;cv::Vec3b&gt;(i ,j) = 128; } } </code></pre> <p>mainwindow.h</p> <pre><code>#ifndef MAINWINDOW_H #define MAINWINDOW_H #include &lt;QMainWindow&gt; #include "ui_mainwindow.h" #include &lt;opencv2/core/core.hpp&gt; #include &lt;opencv2/highgui/highgui.hpp&gt; #include &lt;opencv2/imgproc/imgproc.hpp&gt; #include &lt;opencv2/imgcodecs.hpp&gt; #include "process.h" #include "imghandling.h" #include "rgb_process.h" #include "hsl_process.h" #include "matrix_filters.h" #include "flip.h" #include "rotation.h" #include "blur.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = nullptr); ~MainWindow() override; private slots: void on_open_btn_clicked(); void on_save_btn_clicked(); void on_exposure_slider_valueChanged(); void on_contrast_slider_valueChanged(); void on_red_slider_valueChanged(); void on_green_slider_valueChanged(); void on_blue_slider_valueChanged(); void on_rotate_slider_valueChanged(); void on_flipV_btn_clicked(); void on_flipH_btn_clicked(); void on_hue_slider_valueChanged(); void on_saturation_slider_valueChanged(); void on_luminance_slider_valueChanged(); void on_hsl_btn_clicked(); void on_ok_btn_clicked(); void on_black_and_white_clicked(); void on_sepia_btn_clicked(); void on_tabWidget_currentChanged(){ handling.src = handling.dst.clone(); } private: void updateUi(cv::Mat img); Ui::MainWindow *ui; ImgHandling handling; }; #endif // MAINWINDOW_H </code></pre> <p>mainwindow.cpp</p> <pre><code>#include "mainwindow.h" #include &lt;QFileDialog&gt; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow){ ui-&gt;setupUi(this); } MainWindow::~MainWindow(){ delete ui; } void MainWindow::updateUi(cv::Mat img){ cv::Mat hist_r = handling.calculateHist(img, 0); cv::Mat hist_g = handling.calculateHist(img, 1); cv::Mat hist_b = handling.calculateHist(img, 2); QImage qHr = handling.Mat2Qimg(hist_r); QImage qHg = handling.Mat2Qimg(hist_g); QImage qHb = handling.Mat2Qimg(hist_b); QImage qimg = handling.Mat2Qimg(img); ui-&gt;r_hist-&gt;setPixmap(QPixmap::fromImage(qHr).scaled(ui-&gt;r_hist-&gt;size(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); ui-&gt;g_hist-&gt;setPixmap(QPixmap::fromImage(qHg).scaled(ui-&gt;g_hist-&gt;size(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); ui-&gt;b_hist-&gt;setPixmap(QPixmap::fromImage(qHb).scaled(ui-&gt;b_hist-&gt;size(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); ui-&gt;img_lbl-&gt;setPixmap(QPixmap::fromImage(qimg).scaled(ui-&gt;img_lbl-&gt;size(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); } void MainWindow::on_open_btn_clicked(){ QString path = QFileDialog::getOpenFileName(nullptr, QObject::tr("Open File"), "", QObject::tr(".JPG (*.jpg , *.jpeg) ;; .PNG (*.png) ;; .TIFF (*.tiff , *.tif)")); if(!path.isEmpty()){ handling.imgLoad(path); updateUi(handling.src); ui-&gt;red_slider-&gt;setEnabled(true); ui-&gt;red_spin-&gt;setEnabled(true); ui-&gt;green_slider-&gt;setEnabled(true); ui-&gt;green_spin-&gt;setEnabled(true); ui-&gt;blue_slider-&gt;setEnabled(true); ui-&gt;blue_spin-&gt;setEnabled(true); ui-&gt;exposure_slider-&gt;setEnabled(true); ui-&gt;exposure_spin-&gt;setEnabled(true); ui-&gt;contrast_slider-&gt;setEnabled(true); ui-&gt;contrast_spin-&gt;setEnabled(true); ui-&gt;reset_btn-&gt;setEnabled(true); ui-&gt;hsl_btn-&gt;setEnabled(true); ui-&gt;save_btn-&gt;setEnabled(true); } } void MainWindow::on_save_btn_clicked(){ QString path = QFileDialog::getSaveFileName(this, QObject::tr("Save File"), "", QObject::tr(".JPG (*.jpg) ;; .PNG (*.png) ;; .TIFF (*.tif)")); if(!path.isEmpty()) handling.imgSave(path); } void MainWindow::on_exposure_slider_valueChanged(){ RGB_process m (handling.src, handling.dst, ui-&gt;exposure_slider-&gt;value(), ui-&gt;contrast_slider-&gt;value(), ui-&gt;red_slider-&gt;value(), ui-&gt;green_slider-&gt;value(), ui-&gt;blue_slider-&gt;value()); m.doProcess(); updateUi(handling.dst); } void MainWindow::on_contrast_slider_valueChanged(){ RGB_process m (handling.src, handling.dst, ui-&gt;exposure_slider-&gt;value(), ui-&gt;contrast_slider-&gt;value(), ui-&gt;red_slider-&gt;value(), ui-&gt;green_slider-&gt;value(), ui-&gt;blue_slider-&gt;value()); m.doProcess(); updateUi(handling.dst); } void MainWindow::on_red_slider_valueChanged(){ RGB_process m (handling.src, handling.dst, ui-&gt;exposure_slider-&gt;value(), ui-&gt;contrast_slider-&gt;value(), ui-&gt;red_slider-&gt;value(), ui-&gt;green_slider-&gt;value(), ui-&gt;blue_slider-&gt;value()); m.doProcess(); updateUi(handling.dst); } void MainWindow::on_green_slider_valueChanged(){ RGB_process m (handling.src, handling.dst, ui-&gt;exposure_slider-&gt;value(), ui-&gt;contrast_slider-&gt;value(), ui-&gt;red_slider-&gt;value(), ui-&gt;green_slider-&gt;value(), ui-&gt;blue_slider-&gt;value()); m.doProcess(); updateUi(handling.dst); } void MainWindow::on_blue_slider_valueChanged(){ RGB_process m (handling.src, handling.dst, ui-&gt;exposure_slider-&gt;value(), ui-&gt;contrast_slider-&gt;value(), ui-&gt;red_slider-&gt;value(), ui-&gt;green_slider-&gt;value(), ui-&gt;blue_slider-&gt;value()); m.doProcess(); updateUi(handling.dst); } void MainWindow::on_rotate_slider_valueChanged(){ rotation m(handling.src, handling.dst, ui-&gt;rotate_slider-&gt;value()); m.doProcess(); updateUi(handling.dst); } void MainWindow::on_flipV_btn_clicked(){ flip m(handling.src, handling.dst, true); m.doProcess(); updateUi(handling.dst); handling.src = handling.dst.clone(); } void MainWindow::on_flipH_btn_clicked() { flip m(handling.src, handling.dst, false); m.doProcess(); updateUi(handling.dst); handling.src = handling.dst.clone(); } void MainWindow::on_hue_slider_valueChanged(){ HSL_process process(handling.src, handling.dst, ui-&gt;hue_slider-&gt;value(), ui-&gt;saturation_slider-&gt;value(), ui-&gt;luminance_slider-&gt;value()); process.doProcess(); updateUi(handling.dst); } void MainWindow::on_saturation_slider_valueChanged(){ HSL_process process(handling.src, handling.dst, ui-&gt;hue_slider-&gt;value(), ui-&gt;saturation_slider-&gt;value(), ui-&gt;luminance_slider-&gt;value()); process.doProcess(); updateUi(handling.dst); } void MainWindow::on_luminance_slider_valueChanged(){ HSL_process process(handling.src, handling.dst, ui-&gt;hue_slider-&gt;value(), ui-&gt;saturation_slider-&gt;value(), ui-&gt;luminance_slider-&gt;value()); process.doProcess(); updateUi(handling.dst); } void MainWindow::on_hsl_btn_clicked(){ handling.src = handling.dst.clone(); ui-&gt;red_slider-&gt;setValue(0); ui-&gt;red_slider-&gt;setEnabled(false); ui-&gt;red_spin-&gt;setEnabled(false); ui-&gt;green_slider-&gt;setValue(0); ui-&gt;green_slider-&gt;setEnabled(false); ui-&gt;green_spin-&gt;setEnabled(false); ui-&gt;blue_slider-&gt;setValue(0); ui-&gt;blue_slider-&gt;setEnabled(false); ui-&gt;blue_spin-&gt;setEnabled(false); ui-&gt;exposure_slider-&gt;setValue(0); ui-&gt;exposure_slider-&gt;setEnabled(false); ui-&gt;exposure_spin-&gt;setEnabled(false); ui-&gt;contrast_slider-&gt;setValue(0); ui-&gt;contrast_slider-&gt;setEnabled(false); ui-&gt;contrast_spin-&gt;setEnabled(false); ui-&gt;exposure_slider-&gt;setValue(0); ui-&gt;exposure_slider-&gt;setEnabled(false); ui-&gt;exposure_spin-&gt;setEnabled(false); ui-&gt;hue_slider-&gt;setEnabled(true); ui-&gt;hue_spin-&gt;setEnabled(true); ui-&gt;saturation_slider-&gt;setEnabled(true); ui-&gt;saturation_spin-&gt;setEnabled(true); ui-&gt;luminance_slider-&gt;setEnabled(true); ui-&gt;luminance_spin-&gt;setEnabled(true); ui-&gt;ok_btn-&gt;setEnabled(true); ui-&gt;hsl_btn-&gt;setEnabled(false); } void MainWindow::on_ok_btn_clicked(){ handling.src = handling.dst.clone(); ui-&gt;hue_slider-&gt;setValue(0); ui-&gt;saturation_slider-&gt;setValue(0); ui-&gt;luminance_slider-&gt;setValue(0); ui-&gt;hue_slider-&gt;setEnabled(false); ui-&gt;hue_spin-&gt;setEnabled(false); ui-&gt;saturation_slider-&gt;setEnabled(false); ui-&gt;saturation_spin-&gt;setEnabled(false); ui-&gt;luminance_slider-&gt;setEnabled(false); ui-&gt;luminance_spin-&gt;setEnabled(false); ui-&gt;ok_btn-&gt;setEnabled(false); ui-&gt;hsl_btn-&gt;setEnabled(true); ui-&gt;red_slider-&gt;setEnabled(true); ui-&gt;red_spin-&gt;setEnabled(true); ui-&gt;green_slider-&gt;setEnabled(true); ui-&gt;green_spin-&gt;setEnabled(true); ui-&gt;blue_slider-&gt;setEnabled(true); ui-&gt;blue_spin-&gt;setEnabled(true); ui-&gt;exposure_slider-&gt;setEnabled(true); ui-&gt;exposure_spin-&gt;setEnabled(true); ui-&gt;contrast_slider-&gt;setEnabled(true); ui-&gt;contrast_spin-&gt;setEnabled(true); } void MainWindow::on_black_and_white_clicked(){ Matrix_Filters bw(handling.src, handling.dst, "BW"); bw.doProcess(); updateUi(handling.dst); } void MainWindow::on_sepia_btn_clicked(){ Matrix_Filters sepia(handling.src, handling.dst, "SEPIA"); sepia.doProcess(); updateUi(handling.dst); } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T15:52:05.143", "Id": "223574", "Score": "5", "Tags": [ "c++", "object-oriented", "image", "qt", "opencv" ], "Title": "Interfaces and OOP Design for Image Editor software" }
223574
<p>I decided to implement Conways Game of Life for my first project using Rust. I also haven't had much code review ever, and have been looking for a good critique of my code so I can improve my skills. Here is the code:</p> <pre><code>extern crate glutin_window; extern crate graphics; extern crate piston; extern crate piston_window; use glutin_window::GlutinWindow as Window; use graphics::*; use opengl_graphics::{GlGraphics, OpenGL}; use piston::{ event_loop::*, RenderArgs, RenderEvent, UpdateArgs, UpdateEvent, }; use piston::window::WindowSettings; use rand::prelude::*; //Generate random life and death const WINDOW_WIDTH: f64 = 400.0; const WINDOW_HEIGHT: f64 = 400.0; const BACKGROUND_COLOR: [f32; 4] = [0.5, 0.5, 0.5, 1.0]; const CELL_ALIVE: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; const CELL_DEAD: [f32; 4] = [0.25, 0.25, 0.25, 1.0]; const CELL_SIZE: i32 = 1; #[derive(Clone)] struct Cell { alive: bool, } impl Cell { fn set(&amp;mut self, alive: bool) { self.alive = alive; } } struct CellWorld { rows: i32, columns: i32, map: Box&lt;Vec&lt;Vec&lt;Cell&gt;&gt;&gt;, } impl CellWorld { fn new(window_height: f64, window_width: f64) -&gt; CellWorld { let n_rows = (window_height as i32) / CELL_SIZE; let n_cols = (window_width as i32) / CELL_SIZE; CellWorld { rows: n_rows, columns: n_cols, map: Box::new(Vec::new()), } } } struct PistonApp { gl_context: GlGraphics, world: CellWorld, } impl PistonApp { fn init(&amp;mut self) { let mut rand_life = thread_rng(); for row in 0..self.world.rows { let rand_num: i32 = rand_life.gen(); let mut cell_row = vec![Cell { alive: row / rand_num == rand_life.gen() }; self.world.columns as usize]; for cell in 0..self.world.columns { cell_row[cell as usize].set(cell % 2 == 0); } self.world.map.push(cell_row); } } fn render(&amp;mut self, render_args: &amp;RenderArgs) { let cell_map = &amp;self.world.map; let n_rows = self.world.rows; let n_columns = self.world.columns; self.gl_context.draw(render_args.viewport(), |c, gl| { clear(BACKGROUND_COLOR, gl); for row in 0..n_rows { let cell_row = &amp;cell_map[row as usize]; let row_offset = row * CELL_SIZE; for col in 0..n_columns { let cell = &amp;cell_row[col as usize]; let col_offset = col * CELL_SIZE; let cell_repr = rectangle::square(0.0, 0.0, CELL_SIZE as f64); let trnsfrm = c.transform.trans(col_offset as f64, row_offset as f64); let cell_color = match cell.alive { true =&gt; CELL_ALIVE, false =&gt; CELL_DEAD }; rectangle(cell_color, cell_repr, trnsfrm, gl); } } }); } fn update(&amp;mut self, _update_args: &amp;UpdateArgs) { self.simulate(); } fn simulate(&amp;mut self) { let n_rows = self.world.rows; let n_cols = self.world.columns; for row in 0..n_rows { for col in 0..n_cols { self.update_cell(row as usize, col as usize); } } } fn update_cell(&amp;mut self, row: usize, col: usize) { let world = &amp;mut self.world; let world_map = &amp;mut world.map; let mut alive_neighbors = 0; let has_left_neighbors = if col == 0 { false } else { col - 1 &gt; 0 }; let left_col = if has_left_neighbors { col - 1 } else { 0 }; let has_right_neighbors = col + 1 &lt; world.columns as usize; let right_col = if has_right_neighbors { col + 1 } else { 0 }; let has_top_neighbors = if row == 0 { false } else { row - 1 &gt; 0 }; let top_row = if has_top_neighbors { row - 1 } else { 0 }; let has_btm_neighbors = row + 1 &lt; world.rows as usize; let btm_row = if has_btm_neighbors { row + 1 } else { 0 }; if has_left_neighbors { if world_map[row][left_col].alive { alive_neighbors += 1; } if has_top_neighbors &amp;&amp; world_map[top_row][left_col].alive { alive_neighbors += 1; } if has_btm_neighbors &amp;&amp; world_map[btm_row][left_col].alive { alive_neighbors += 1; } } if has_right_neighbors { if world_map[row][right_col].alive { alive_neighbors += 1; } if has_top_neighbors &amp;&amp; world_map[top_row][right_col].alive { alive_neighbors += 1; } if has_btm_neighbors &amp;&amp; world_map[btm_row][right_col].alive { alive_neighbors += 1; } } if has_top_neighbors { if world_map[top_row][col].alive { alive_neighbors += 1; } } if has_btm_neighbors { if world_map[btm_row][col].alive { alive_neighbors += 1; } } if alive_neighbors &lt; 2 || alive_neighbors &gt; 3 { world_map[row][col].set(false); } if alive_neighbors == 2 || alive_neighbors == 3 || world_map[row][col].alive == false &amp;&amp; alive_neighbors == 3 { world_map[row][col].set(true); } } } fn main() { let opengl_version = OpenGL::V3_2; let mut window: Window = WindowSettings::new( "Cellular Automata!", piston_window::Size::from([WINDOW_WIDTH, WINDOW_HEIGHT]), ).graphics_api(opengl_version).exit_on_esc(true) .resizable(false).fullscreen(true).build().unwrap(); let mut cellular_automata_app = PistonApp { gl_context: GlGraphics::new(opengl_version), world: CellWorld::new(WINDOW_HEIGHT, WINDOW_WIDTH), }; cellular_automata_app.init(); let mut window_events = Events::new(EventSettings::new()); while let Some(event) = window_events.next(&amp;mut window) { if let Some(render_args) = event.render_args() { cellular_automata_app.render(&amp;render_args); } if let Some(update_args) = event.update_args() { cellular_automata_app.update(&amp;update_args); } std::thread::sleep(std::time::Duration::from_millis(10)); } } </code></pre> <p>Let me know what you think about my code!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T19:16:36.730", "Id": "433411", "Score": "0", "body": "While the language is different (Java), you might find some of the algorithmic suggestions I made in [this earlier answer](https://codereview.stackexchange.com/questions/42718/optimize-conways-game-of-life/42790#42790) useful. In particular, not updating the edge cells (or updating them in a separate loop) would let you simplify your `update_cell` function a lot, and making use of the overlap between the neighborhoods of adjacent cells would let you reduce your array accesses roughly by a factor of three." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T12:04:10.107", "Id": "433753", "Score": "0", "body": "Thanks for the comment! I kind of get what you suggested in the other post and I kind of don't. It just seems like you assigned a value(a power of two) to a cells surrounding neighbors. After computing the sum you're able to tell whether the cell is dead/live? Also, what is the reason you suggested using numbers instead of Boolean values to represent the cells? Are checking numbers more efficient?" } ]
[ { "body": "<pre><code>extern crate glutin_window;\nextern crate graphics;\nextern crate piston;\nextern crate piston_window;\n</code></pre>\n\n<p>The new edition of rust, 2018, does not require <code>extern crate</code> statements. Furthermore, you don't have <code>extern crate</code> statements for <code>rand</code> or <code>opengl_graphics</code> suggesting that you are already using Rust 2018, and you just have these extra extern crates for no reason.</p>\n\n<pre><code>const BACKGROUND_COLOR: [f32; 4] = [0.5, 0.5, 0.5, 1.0];\nconst CELL_ALIVE: [f32; 4] = [0.0, 1.0, 0.0, 1.0];\nconst CELL_DEAD: [f32; 4] = [0.25, 0.25, 0.25, 1.0];\n</code></pre>\n\n<p>I suggest that you define a type alias for colors:</p>\n\n<pre><code>type Color = [f32; 4];\n\nconst BACKGROUND_COLOR: Color = [0.5, 0.5, 0.5, 1.0];\nconst CELL_ALIVE: Color = [0.0, 1.0, 0.0, 1.0];\nconst CELL_DEAD: Color = [0.25, 0.25, 0.25, 1.0];\n</code></pre>\n\n<p>It doesn't make a big difference, but it makes it a bit clearer when reading this code what these values are.</p>\n\n<pre><code>const CELL_SIZE: i32 = 1;\n</code></pre>\n\n<p>I think this should be an f64. Its the size of a cell in the OpenGL drawing context which is in f64, not i32. </p>\n\n<pre><code>#[derive(Clone)]\nstruct Cell {\n alive: bool,\n}\n\nimpl Cell {\n fn set(&amp;mut self, alive: bool) {\n self.alive = alive;\n }\n}\n</code></pre>\n\n<p>Instead of a Cell containing a lone bool, it would make more sense to have an enum.</p>\n\n<pre><code>enum Cell {\n Living,\n Dead\n}\n</code></pre>\n\n<p>In Rust, you don't want to think in OO terms where you call on methods on objects to manipulate them. Instead, you want data structures that represent state. That's why it makes more sense to have a Living/Dead enum rather than a struct which you can call.</p>\n\n<pre><code>struct CellWorld {\n rows: i32,\n columns: i32,\n map: Box&lt;Vec&lt;Vec&lt;Cell&gt;&gt;&gt;,\n}\n</code></pre>\n\n<p>I might use <code>usize</code> instead of <code>i32</code> since the sizes correspond to the length of the <code>Vec</code>s. Also there doesn't seem to be any reason to put your Vec into a Box.</p>\n\n<pre><code>impl CellWorld {\n fn new(window_height: f64, window_width: f64) -&gt; CellWorld {\n let n_rows = (window_height as i32) / CELL_SIZE;\n let n_cols = (window_width as i32) / CELL_SIZE;\n\n CellWorld {\n rows: n_rows,\n columns: n_cols,\n map: Box::new(Vec::new()),\n }\n }\n}\n</code></pre>\n\n<p>It is odd that you don't fill in the map here. Typically, we'd have the <code>new</code> function CellWorld produce a fully ready <code>CellWorld</code>. Right now that returned <code>CellWorld</code> is in an inconsistent state, its width/height and actually cells aren't consistent.</p>\n\n<pre><code>impl PistonApp {\n\n fn init(&amp;mut self) {\n let mut rand_life = thread_rng();\n</code></pre>\n\n<p>I wouldn't put <code>life</code> in the name, just because its a general random number generator, its not really life specific.</p>\n\n<pre><code> for row in 0..self.world.rows {\n let rand_num: i32 = rand_life.gen();\n let mut cell_row = vec![Cell { alive: row / rand_num == rand_life.gen() }; self.world.columns as usize];\n</code></pre>\n\n<p>I don't what this is trying to be... but I'm pretty sure this isn't it.</p>\n\n<p><code>vec![]</code> doesn't re-evaluate the expression for each element created, it <code>clone()</code>s the one element repeatedly. So this won't produce different values for the different cells. </p>\n\n<p>I'm not sure what you are trying to with generating the two different random values and then taking a division. As it works out, a random i32 is almost certainly much bigger than your row index so <code>row / rand_num</code> is almost always zero. And its is highly unlikely that the second call to <code>gen()</code> will also produce zero. So this seems like it will just always produce false.</p>\n\n<pre><code> for cell in 0..self.world.columns {\n cell_row[cell as usize].set(cell % 2 == 0);\n }\n</code></pre>\n\n<p>One way or the other, you then throw away everything you did above to set every other cell to true.</p>\n\n<pre><code> self.world.map.push(cell_row);\n }\n }\n</code></pre>\n\n<p>I'd use iterators to actually create this, something like:</p>\n\n<pre><code>self.world.map = (0..self.world.rows).map(|_| \n (0..self.world.columns).map(|_| \n rand_life.rng()\n ).collect()\n).collect();\n</code></pre>\n\n<p>That will create a randomly filled up grid.</p>\n\n<pre><code> fn render(&amp;mut self, render_args: &amp;RenderArgs) {\n let cell_map = &amp;self.world.map;\n let n_rows = self.world.rows;\n let n_columns = self.world.columns;\n\n self.gl_context.draw(render_args.viewport(), |c, gl| {\n clear(BACKGROUND_COLOR, gl);\n\n for row in 0..n_rows {\n let cell_row = &amp;cell_map[row as usize];\n\n let row_offset = row * CELL_SIZE;\n\n for col in 0..n_columns {\n let cell = &amp;cell_row[col as usize];\n</code></pre>\n\n<p>Use iterators</p>\n\n<pre><code>for (row_index, row) in cell_map.iter().enumerate() {\n for (col_index, col) in row.iter().enumerate() {\n</code></pre>\n\n<p>That simplifies access to the index alongside the values.</p>\n\n<pre><code> fn simulate(&amp;mut self) {\n let n_rows = self.world.rows;\n let n_cols = self.world.columns;\n\n for row in 0..n_rows {\n for col in 0..n_cols {\n self.update_cell(row as usize, col as usize);\n }\n }\n }\n</code></pre>\n\n<p>Your implementation seems subtlety incorrect to me. In the GoL, all cells update at once. That is, the state of each cell at time T + 1 depends on the state of all cells at time T. But since you update cell by cell, some cells will already have been updated when you are updating a cell. In order to GoL right, you need to two copies of the map, the previous state and the new state being computed.</p>\n\n<pre><code> fn update_cell(&amp;mut self, row: usize, col: usize) {\n let world = &amp;mut self.world;\n let world_map = &amp;mut world.map;\n let mut alive_neighbors = 0;\n\n let has_left_neighbors = if col == 0 { false } else { col - 1 &gt; 0 };\n let left_col = if has_left_neighbors { col - 1 } else { 0 };\n let has_right_neighbors = col + 1 &lt; world.columns as usize;\n let right_col = if has_right_neighbors { col + 1 } else { 0 };\n let has_top_neighbors = if row == 0 { false } else { row - 1 &gt; 0 };\n let top_row = if has_top_neighbors { row - 1 } else { 0 };\n let has_btm_neighbors = row + 1 &lt; world.rows as usize;\n let btm_row = if has_btm_neighbors { row + 1 } else { 0 };\n\n if has_left_neighbors {\n if world_map[row][left_col].alive {\n alive_neighbors += 1;\n }\n\n if has_top_neighbors &amp;&amp; world_map[top_row][left_col].alive {\n alive_neighbors += 1;\n }\n\n if has_btm_neighbors &amp;&amp; world_map[btm_row][left_col].alive {\n alive_neighbors += 1;\n }\n }\n\n if has_right_neighbors {\n if world_map[row][right_col].alive {\n alive_neighbors += 1;\n }\n\n if has_top_neighbors &amp;&amp; world_map[top_row][right_col].alive {\n alive_neighbors += 1;\n }\n\n if has_btm_neighbors &amp;&amp; world_map[btm_row][right_col].alive {\n alive_neighbors += 1;\n }\n }\n\n if has_top_neighbors {\n if world_map[top_row][col].alive {\n alive_neighbors += 1;\n }\n }\n\n if has_btm_neighbors {\n if world_map[btm_row][col].alive {\n alive_neighbors += 1;\n }\n }\n</code></pre>\n\n<p>So... that was complicated, here's what I'd do:</p>\n\n<pre><code> let mut alive_neighbors = 0;\n // by taking a slice of the vec we get rust to take care of the \n // bounds checking.\n for row in world_map[row-1:row+2] {\n for col in row[col - 1:col + 2] {\n if col.alive {\n alive_neighbors += 1;\n }\n }\n }\n }\n // the above will could the cell itself, so balance that.\n if world_map[row][col].alive {\n alive_neighbors -= 1;\n }\n</code></pre>\n\n<p>That, I think, is easier to follow.</p>\n\n<pre><code> if alive_neighbors &lt; 2 || alive_neighbors &gt; 3 {\n world_map[row][col].set(false);\n }\n\n if alive_neighbors == 2 || alive_neighbors == 3 || world_map[row][col].alive == false &amp;&amp; alive_neighbors == 3 {\n world_map[row][col].set(true);\n }\n</code></pre>\n\n<p>I'd do something like this:</p>\n\n<pre><code>world_map[row][col].set(\n if world_map[row][col] {\n alive_neighbors &gt;= 2 &amp;&amp; alive_neighbors &lt;= 3\n } else {\n alive_neighbors == 3\n });\n</code></pre>\n\n<p>Firstly, this always set the value. This just makes the logic a bit more straightforward, since you don't have to figure out whether or not it changes. Also, by handling the living and dead cell cases seperately, we get a simpler presentation of the rule.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T12:06:54.733", "Id": "433754", "Score": "0", "body": "Awesome! Thanks for the great critique! There's tons to learn from here which is exactly what I was looking for! A lot of stuff I didn't previously know or has a shallow understanding of." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T22:22:42.480", "Id": "223704", "ParentId": "223577", "Score": "3" } } ]
{ "AcceptedAnswerId": "223704", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T17:16:59.293", "Id": "223577", "Score": "5", "Tags": [ "rust", "game-of-life", "cellular-automata" ], "Title": "Game of Life in Rust-lang" }
223577
<p>This code pre-calculates the winning combinations for an n-sized tic tac toe board.</p> <p>I first created my function using an imperative approach. This is just how I naturally write code most of the time. I then tried to think about the problem using a "What I want to accomplish?" approach, rather than "What do I want it to do?" In the end I think I still ended up with an imperative approach, just using STL algorithms as loops. </p> <p>Imperative approach:</p> <pre><code>std::vector&lt;std::vector&lt;int&gt;&gt; rules3(const int x){ using namespace std; vector&lt;vector&lt;int&gt;&gt; seqs; for(int n=0; n&lt;x; ++n){ vector&lt;int&gt; seq; for(int m=0; m&lt;x; ++m){ seq.push_back(n*x+m); } seqs.push_back(seq); } for(int n=0; n&lt;x; ++n){ vector&lt;int&gt; seq; for(int m=0; m&lt;x; ++m){ seq.push_back(n+x*m); } seqs.push_back(seq); } vector&lt;int&gt; seq; for(int n=0; n&lt;x; ++n){ seq.push_back(n*x+n); } seqs.push_back(seq); seq.clear(); for(int n=0; n&lt;x; ++n){ seq.push_back(x-1+n*(x-1)); } seqs.push_back(seq); return seqs; } </code></pre> <p>Getting more functional:</p> <pre><code>std::vector&lt;std::vector&lt;int&gt;&gt; rules2(const int x){ using namespace std; vector&lt;vector&lt;int&gt;&gt; seqs; vector&lt;int&gt; iter(x); iota(iter.begin(), iter.end(), 0); for(auto n: iter){ vector&lt;int&gt; seq; for(auto m: iter){ seq.push_back(n*x+m); } seqs.push_back(seq); } for(auto n: iter){ vector&lt;int&gt; seq; for(auto m: iter){ seq.push_back(n+x*m); } seqs.push_back(seq); } vector&lt;int&gt; seq; seq.clear(); for(auto n: iter){ seq.push_back(n*x+n); } seqs.push_back(seq); seq.clear(); for(auto n: iter){ seq.push_back(x-1+n*(x-1)); } seqs.push_back(seq); return seqs; } </code></pre> <p>Functional approach? (still feels imperative):</p> <pre><code>std::vector&lt;std::vector&lt;int&gt;&gt; rules1(const int x){ using namespace std; vector&lt;vector&lt;int&gt;&gt; seqs; vector&lt;int&gt; iter(x); iota(iter.begin(), iter.end(), 0); transform(iter.begin(), iter.end(), back_inserter(seqs), [&amp;](const int&amp; n){ vector&lt;int&gt; seq; transform(iter.begin(), iter.end(), back_inserter(seq), [&amp;](const int&amp; m){ return n*x+m; }); return seq; }); transform(iter.begin(), iter.end(), back_inserter(seqs), [&amp;](const int&amp; n){ vector&lt;int&gt; seq; transform(iter.begin(), iter.end(), back_inserter(seq), [&amp;](const int&amp; m){ return n+x*m; }); return seq; }); vector&lt;int&gt; seq; transform(iter.begin(), iter.end(), back_inserter(seq), [&amp;](const int&amp; n){ return n*x+n; }); seqs.push_back(seq); seq.clear(); transform(iter.begin(), iter.end(), back_inserter(seq), [&amp;](const int&amp; n){ //return (x-n-1)*x+n; // 6,4,2 return x-1+n*(x-1); // 2,4,6 }); seqs.push_back(seq); return seqs; } </code></pre> <p>Output when printing:</p> <pre><code>rules3 std::vector(0, 1, 2) std::vector(3, 4, 5) std::vector(6, 7, 8) std::vector(0, 3, 6) std::vector(1, 4, 7) std::vector(2, 5, 8) std::vector(0, 4, 8) std::vector(2, 4, 6) rules2 std::vector(0, 1, 2) std::vector(3, 4, 5) std::vector(6, 7, 8) std::vector(0, 3, 6) std::vector(1, 4, 7) std::vector(2, 5, 8) std::vector(0, 4, 8) std::vector(2, 4, 6) rules1 std::vector(0, 1, 2) std::vector(3, 4, 5) std::vector(6, 7, 8) std::vector(0, 3, 6) std::vector(1, 4, 7) std::vector(2, 5, 8) std::vector(0, 4, 8) std::vector(2, 4, 6) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T12:02:39.777", "Id": "433963", "Score": "0", "body": "Is the Ranges library a possibility?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T13:29:40.490", "Id": "433970", "Score": "0", "body": "@L.F. Yes, I have been using boost in other areas of my code. I have been wanting to experiment with that. Did you have something specific in mind?" } ]
[ { "body": "<p>Here are some suggestions. This answers uses the <a href=\"https://github.com/ericniebler/range-v3\" rel=\"nofollow noreferrer\">Range-v3</a> library and assumes</p>\n\n<pre><code>#include &lt;range/v3/all.hpp&gt;\n\nnamespace view = ranges::view;\n</code></pre>\n\n<ol>\n<li><p>Please include the <code>#include</code>s and supply a small test program in the future. You probably have written them anyway, so why not post them to save reviewers' time? :)</p></li>\n<li><p><code>int</code> may be too small for indexes. Consider using <code>std::size_t</code>. You can define a type alias for flexibility.</p>\n\n<pre><code>using index_t = std::size_t;\n</code></pre></li>\n<li><p>The type <code>std::vector&lt;std::vector&lt;index_t&gt;&gt;</code> occurs many times. Save time by writing</p>\n\n<pre><code>using rule_t = std::vector&lt;index_t&gt;\nusing rules_t = std::vector&lt;rule_t&gt;;\n</code></pre></li>\n<li><p>The concept \"<span class=\"math-container\">\\$n \\times n\\$</span> board\" only makes sense when <span class=\"math-container\">\\$n\\$</span> is a positive integer. Therefore, enforce the pre-condition <span class=\"math-container\">\\$n \\ge 1\\$</span>. Also, the name <code>x</code> is a bit vague. <code>size</code> may be better.</p>\n\n<pre><code>rules_t rules(index_t size)\n{\n if (size == 0)\n throw std::invalid_argument{\"...\"};\n // ...\n}\n</code></pre></li>\n<li><p><code>rules(1)</code> currently returns <code>{{0}, {0}, {0}, {0}}</code>, which is definitely wrong. It should return <code>{{0}}</code>. Your general logic is \"<span class=\"math-container\">\\$n\\$</span> rows + <span class=\"math-container\">\\$n\\$</span> columns + <span class=\"math-container\">\\$2\\$</span> diagonals\", which only applies to <span class=\"math-container\">\\$n \\ge 2\\$</span>. The easiest approach would be a special case:</p>\n\n<pre><code>rules_t rules(index_t size)\n{\n // ...\n else if (size == 1)\n return {{0}};\n}\n</code></pre></li>\n<li><p>Following the previous bullet, why not make separate functions to make your logic clear?</p>\n\n<pre><code>rules_t rules(index_t size)\n{\n // ...\n else {\n auto rows = rules_row(size);\n auto columns = rules_column(size);\n auto diagonals = rules_diagonal(size);\n return ranges::to&lt;rules_t&gt;(view::concat(rows, columns, diagonals));\n }\n}\n</code></pre>\n\n<p>where <code>view::concat</code> concatenates the three vectors and <code>ranges::to</code> converts the result to the desired return type. (Note that <code>view::concat</code> is disabled with rvalues to prevent dangling iterators, so we first store the subvectors.)</p></li>\n<li><p>The <code>rules_row</code> function is easy to write:</p>\n\n<pre><code>rules_t rules_row(index_t size)\n{\n return view::ints(index_t(0), size * size) | view::chunk(size);\n}\n</code></pre>\n\n<p><code>view::ints</code> generate a left-inclusive sequence of integers <code>{0, 1, 2, ..., size * size - 1}</code>, and <code>view::chunk(size)</code> breaks it into chunks each of size <code>size</code>.</p></li>\n<li><p>The <code>rules_column</code> function is a bit tricky, because the Range library does not provide a function like <code>chunk</code> that splits like this. We do have a function <code>stride</code>, so we can write a manual \"loop\": (it took me quite a while to figure this out, so tell me if there is a better way!)</p>\n\n<pre><code>rules_t rules_column(index_t size)\n{\n return view::ints(index_t(0), size) |\n view::transform([=](index_t col) {\n return view::ints(index_t(col), size * size) | view::stride(size);\n });\n}\n</code></pre>\n\n<p><code>view::ints(index_t(0), size)</code> generates the column numbers. Each of them is passed to the lambda. The lambda returns the corresponding rule for each column.</p></li>\n<li><p>The <code>rules_diagonal</code> function is moderately simple:</p>\n\n<pre><code>rules_t rules_diagonal(index_t size)\n{\n return {\n view::ints(index_t(0), size) |\n view::transform([=](index_t r) { return r * (size + 1); }),\n view::ints(index_t(1), size + 1) |\n view::transform([=](index_t r) { return r * (size - 1); })\n };\n}\n</code></pre>\n\n<p>Here, we always have two rules: one for the primary diagonal</p>\n\n<pre><code>{0 * size + 0, 1 * size + 1, 2 * size + 2, ..., (size - 1) * size + (size - 1)}\n</code></pre>\n\n<p>which is equivalent to</p>\n\n<pre><code>{0, 1, 2, ..., size - 1} * (size + 1)\n</code></pre>\n\n<p>and the other for the secondary diagonal</p>\n\n<pre><code>{size - 1, 2 * size - 2, 3 * size - 3, ... size * size - (size - 1)}\n</code></pre>\n\n<p>which is equivalent to</p>\n\n<pre><code>{1, 2, 3, ..., size + 1} * (size - 1)\n</code></pre></li>\n<li><p>Putting everything together:</p>\n\n<pre><code>#include &lt;vector&gt;\n#include &lt;range/v3/all.hpp&gt;\n\nnamespace view = ranges::view;\n\nusing index_t = std::size_t;\nusing rule_t = std::vector&lt;index_t&gt;;\nusing rules_t = std::vector&lt;rule_t&gt;;\n\nrules_t rules_row(index_t size)\n{\n return view::ints(index_t(0), size * size) | view::chunk(size);\n}\n\nrules_t rules_column(index_t size)\n{\n return view::ints(index_t(0), size) |\n view::transform([=](index_t col) {\n return view::ints(index_t(col), size * size) | view::stride(size);\n });\n}\n\nrules_t rules_diagonal(index_t size)\n{\n return {\n view::ints(index_t(0), size) |\n view::transform([=](index_t r) { return r * (size + 1); }),\n view::ints(index_t(1), size + 1) |\n view::transform([=](index_t r) { return r * (size - 1); })\n };\n}\n\nrules_t rules(index_t size)\n{\n if (size == 0)\n throw std::invalid_argument{\"A board cannot have size zero\"};\n else if (size == 1)\n return {{0}};\n else {\n auto rows = rules_row(size);\n auto columns = rules_column(size);\n auto diagonals = rules_diagonal(size);\n return view::concat(rows, columns, diagonals);\n }\n}\n</code></pre>\n\n<p>(<a href=\"https://wandbox.org/permlink/Np1OSewSm5HTW2hr\" rel=\"nofollow noreferrer\">live demo</a>, tests the function for <code>size = 1, 2, 3, ..., 10</code>)</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T14:44:36.997", "Id": "434103", "Score": "0", "body": "Thanks for taking a crack at this. You have given a lot to think about." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T02:18:42.460", "Id": "223840", "ParentId": "223578", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T17:39:32.737", "Id": "223578", "Score": "3", "Tags": [ "c++", "functional-programming", "comparative-review", "tic-tac-toe" ], "Title": "Pre-calculate the winning combinations for an n-sized tic tac toe board using C++ functional programming" }
223578
<p>I'm trying to solve <a href="https://codeforces.com/problemset/problem/780/C" rel="nofollow noreferrer">this question</a>:</p> <blockquote> <p>Andryusha goes through a park each day. The squares and paths between them look boring to Andryusha, so he decided to decorate them.</p> <p>The park consists of n squares connected with (n - 1) bidirectional paths in such a way that any square is reachable from any other using these paths. Andryusha decided to hang a colored balloon at each of the squares. The baloons' colors are described by positive integers, starting from 1. In order to make the park varicolored, Andryusha wants to choose the colors in a special way. More precisely, he wants to use such colors that if a, b and c are distinct squares that a and b have a direct path between them, and b and c have a direct path between them, then balloon colors on these three squares are distinct.</p> <p>Andryusha wants to use as little different colors as possible. Help him to choose the colors!</p> <p><strong>Input</strong> The first line contains single integer n (3 ≤ n ≤ 2·10<sup>5</sup>) — the number of squares in the park.</p> <p>Each of the next (n - 1) lines contains two integers x and y (1 ≤ x, y ≤ n) — the indices of two squares directly connected by a path.</p> <p>It is guaranteed that any square is reachable from any other using the paths.</p> <p><strong>Output</strong> In the first line print single integer k — the minimum number of colors Andryusha has to use.</p> <p>In the second line print n integers, the i-th of them should be equal to the balloon color on the i-th square. Each of these numbers should be within range from 1 to k.</p> </blockquote> <p>I have a solution that works, but times out on large inputs:</p> <pre><code>import java.util.* import kotlin.collections.HashMap private fun readLn() = readLine()!! // string line private fun readInt() = readLn().toInt() // single Int private fun readStrings() = readLn().trim().split(&quot; &quot;) // list of strings private fun readInts() = readStrings().map { it.toInt() } // list of Ints fun dfs(color_of: Array&lt;Int&gt;, graph: MutableMap&lt;Int, MutableList&lt;Int&gt;&gt;, current: Int, parent: Int) { var c = 1 for (neb in graph[current] ?: mutableListOf()) { if (color_of[neb] == 0) { while (c == color_of[current] || c == color_of[parent]) { c += 1 } color_of[neb] = c dfs(color_of, graph, neb, current) c += 1 } } } fun main(args: Array&lt;String&gt;) { val n = readInt() val graph = mutableMapOf&lt;Int, MutableList&lt;Int&gt;&gt;() for (i in 0 until n - 1) { val (x, y) = readInts() graph.computeIfAbsent(x - 1) { mutableListOf() } graph.computeIfAbsent(y - 1) { mutableListOf() } graph[x - 1]!!.add(y - 1) graph[y - 1]!!.add(x - 1) } val color_of = Array(n + 1) { 0 } color_of[0] = 1 dfs(color_of, graph, 0, 0) println(color_of.max()!!) for (i in 0 until n) { println(color_of[i]) } } </code></pre> <p>I'd love some pointers on how I can optimize this to pass big test cases.</p> <p>Edit:</p> <p>Here is the equivalent java solution that passes all test cases:</p> <pre><code>// Codeforces Round 403 // Andryusha and Colored Balloons // Problem statement: // http://codeforces.com/problemset/problem/781/A import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.PrintStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStream; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { ArrayList&lt;Integer&gt;[] a; int[] color; int result; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); color = new int[n]; a = new ArrayList[n]; for (int i = 0; i &lt; n; i++) { a[i] = new ArrayList&lt;&gt;(); } for (int i = 0; i &lt; n - 1; i++) { int first = in.nextInt() - 1; int second = in.nextInt() - 1; a[first].add(second); a[second].add(first); } color[0] = 1; result = 1; dfs(0, 0); out.println(result); for (int i = 0; i &lt; n; i++) { out.print(color[i] + &quot; &quot;); } } void dfs(int index, int parentIndex) { // depth first traversal of graph // paint each child node with color in ascending order skipping color of current node and of parent node int currentColor = 1; for (int childIndex : a[index]) { if (color[childIndex] == 0) { while ((currentColor == color[index]) || (currentColor == color[parentIndex])) currentColor++; color[childIndex] = currentColor; result = Math.max(result, currentColor); dfs(childIndex, index); currentColor++; } } } } static class InputReader { private static BufferedReader in; private static StringTokenizer tok; public InputReader(InputStream in) { this.in = new BufferedReader(new InputStreamReader(in)); } public int nextInt() { return Integer.parseInt(next()); } public String next() { try { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } } catch (IOException ex) { System.err.println(&quot;An IOException was caught :&quot; + ex.getMessage()); } return tok.nextToken(); } } } </code></pre> <p>What's wrong with MY solution? :(</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T21:14:45.350", "Id": "433429", "Score": "1", "body": "when you searched the internet for this problem, how did others solve it? Did you already compare your solution to theirs? Especially for time-limit-exceeded problems, this helps in most cases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T21:21:03.273", "Id": "433432", "Score": "0", "body": "@RolandIllig good point, I've added an equivalent java solution that passes all cases" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T06:22:09.150", "Id": "433457", "Score": "0", "body": "all code that you post here must be your own. Since you ask \"what is wrong with MY solution\", this implies that the second code snippet seems to be not yours." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-16T11:08:15.983", "Id": "439601", "Score": "0", "body": "What does profiling show to be the bottleneck?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T18:04:07.907", "Id": "223579", "Score": "1", "Tags": [ "programming-challenge", "time-limit-exceeded", "graph", "depth-first-search", "kotlin" ], "Title": "Graph-coloring solution using depth-first search" }
223579
<p>As many have done on this site, I decided to create a progress indicator using a modeless Userform. However, my goal was to make said progress indicator as generic/reusable as possible.</p> <p>While doing some research, I stumbled upon @MathieuGuindon's post titled <a href="https://rubberduckvba.wordpress.com/2018/01/12/progress-indicator/" rel="nofollow noreferrer">The Reusable Progress Indicator</a>. I quite liked his ideas, so I definitely borrowed a few of them, but instead of writing a predeclared class to interact with the form, I choose to create an interface to expose the Progress Indicator's methods to the client code.</p> <p>The issue I have currently, is the default instance, (albeit useless without being written against the interface), troubles me, but I fear there is no way around it. Also I am looking for general feedback on my code structure, quality, efficiency, and other improvements that could be made.</p> <p>Note: I have only been developing in VBA for just over a year. That being said I am on Stack Overflow quite a bit and I am always seeing and learning from, @MathieuGuindon's code, so naturally my coding style has begun to mirror his.</p> <p><strong><code>IProgressIndicator</code> (Interface):</strong></p> <pre><code>Option Explicit Public Sub UpdateOrphanProgress(ByRef ProgStatusText As Variant, _ ByRef CurrProgCnt As Long, _ ByRef TotalProgCnt As Long): End Sub Public Sub UpdateParentChildProgress(ByRef ParentProgStatusText As Variant, _ ByRef ParentCurrCnt As Long, _ ByRef ParentTotalCnt As Long, _ ByRef ChildProgStatusText As Variant, _ ByRef ChildCurrProgCnt As Long, _ ByRef ChildProgCnt As Long, _ ByRef TotalProgCnt As Long): End Sub Public Sub LoadProgIndicator(Optional ByVal HasParentProccess As Boolean, _ Optional ByVal CanCancel As Boolean, _ Optional ByVal CalculateExecutionTime As Boolean): End Sub Public Property Get ShouldCancel() As Boolean: End Property </code></pre> <p><strong><code>ProgressIndicator</code> Class (Userfrm):</strong></p> <pre><code>Option Explicit Implements IProgressIndicator #If VBA7 Then Private Declare PtrSafe Function GetWindowLong _ Lib "user32" Alias "GetWindowLongA" ( _ ByVal hwnd As LongPtr, _ ByVal nIndex As LongPtr) As LongPtr Private Declare PtrSafe Function SetWindowLong _ Lib "user32" Alias "SetWindowLongA" ( _ ByVal hwnd As LongPtr, _ ByVal nIndex As LongPtr, _ ByVal dwNewLong As LongPtr) As LongPtr Private Declare PtrSafe Function DrawMenuBar _ Lib "user32" ( _ ByVal hwnd As LongPtr) As LongPtr Private Declare PtrSafe Function FindWindowA _ Lib "user32" (ByVal lpClassName As String, _ ByVal lpWindowName As String) As LongPtr Private Declare PtrSafe Function GetTickCount _ Lib "kernel32.dll" () As LongPtr #Else Private Declare Function GetWindowLong _ Lib "user32" Alias "GetWindowLongA" ( _ ByVal hwnd As Long, _ ByVal nIndex As Long) As Long Private Declare Function SetWindowLong _ Lib "user32" Alias "SetWindowLongA" ( _ ByVal hwnd As Long, _ ByVal nIndex As Long, _ ByVal dwNewLong As Long) As Long Private Declare Function DrawMenuBar _ Lib "user32" ( _ ByVal hwnd As Long) As Long Private Declare Function FindWindowA _ Lib "user32" (ByVal lpClassName As String, _ ByVal lpWindowName As String) As Long Private Declare Function GetTickCount _ Lib "kernel32.dll" () As Long #End If Private Const GWL_STYLE = -16 Private Const WS_CAPTION = &amp;HC00000 Private Const PROGINDICATOR_MAXHEIGHT As Integer = 142.75 Private Const PARENTPROCSTATUS_MAXHEIGHT As Integer = 10 Private Const PROCSTATUS_MAXTOP As Integer = 16 Private Const PROGRESSBAR_MAXTOP As Integer = 41 Private Const PROGRESSBAR_MAXWIDTH As Integer = 270 Private Const ELAPSEDTIME_MAXTOP As Integer = 83 Private Const TIMEREMAINING_MAXTOP As Integer = 94 Private Const STARTPOS_LEFT_OFFSET As Single = 0.5 Private Const STARTPOS_RIGHT_OFFSET As Single = 0.5 Private Const ERR_ORPHANPROC_NOPARENT As String = "You specified that this proccess has a parent, " &amp; _ "but you are using the 'UpdateOrphanProgress' method" Private Const ERR_HASPARENT_NOTSPECIFIED As String = "You specified that this proccess does not have a parent, " &amp; _ "but you are using the 'UpdateParentChildProgress' method." Private Const ERR_INVALIDPROGPERCENT As String = "Either the CurrProgCnt equals 0, is greater than 0, or it " &amp; _ "is greater than TotalProgCnt." Private Const ERR_INVALIDPARENTCOUNT As String = "Either the ParentCurrCnt equals 0, is greater than 0, or it " &amp; _ "is greater than ParentTotalCnt." Public Enum ProgressIndicatorError Error_OrphanProcHasParent = vbObjectError + 1001 Error_HasParentProcNotSpecified Error_InvalidProgressPercentage Error_InvalidParentCount End Enum Private Type TProgressIndicator StartTime As Double TimeElapsed As Double SecondsElapsed As Double MinutesElapsed As Double HoursElapsed As Double SecondsRemaining As Double MinutesRemaining As Double HoursRemaining As Double ItemsRemaining As Double ParentChildIterationCount As Long HasParentProccess As Boolean CanCancel As Boolean Cancelling As Boolean CalculateExecutionTime As Boolean PercentComplete As Double End Type Private this As TProgressIndicator '***************************************************************************** 'Properties '***************************************************************************** Private Property Get HasParentProccess() As Boolean HasParentProccess = this.HasParentProccess End Property Private Property Get Cancellable() As Boolean Cancellable = this.CanCancel End Property Private Property Get IsCancelRequested() As Boolean IsCancelRequested = this.Cancelling End Property Private Property Get CalculateExecutionTime() As Boolean CalculateExecutionTime = this.CalculateExecutionTime End Property '***************************************************************************** 'Methods '***************************************************************************** Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer) If CloseMode = 0 Then Cancel = True If Cancellable Then this.Cancelling = True End If End Sub Private Property Get IProgressIndicator_ShouldCancel() As Boolean If IsCancelRequested Then If MsgBox("Would you like to Cancel this operation?", _ vbQuestion + vbYesNo, "Process Dialog") = vbYes Then IProgressIndicator_ShouldCancel = True Me.Hide Else this.Cancelling = False End If End If End Property Private Sub IProgressIndicator_LoadProgIndicator(Optional ByVal HasParentProccess As Boolean, _ Optional ByVal CanCancel As Boolean, _ Optional ByVal CalculateExecutionTime As Boolean) this.CalculateExecutionTime = CalculateExecutionTime If CalculateExecutionTime Then this.StartTime = GetTickCount() HideTitleBar this.HasParentProccess = HasParentProccess: this.CanCancel = CanCancel With Me If this.HasParentProccess Then .Height = PROGINDICATOR_MAXHEIGHT .ParentProcedureStatus.Height = PARENTPROCSTATUS_MAXHEIGHT .ProcedureStatus.Top = PROCSTATUS_MAXTOP .frameProgressBar.Top = PROGRESSBAR_MAXTOP .lblElapsedTime.Top = ELAPSEDTIME_MAXTOP .ElapsedTime.Top = ELAPSEDTIME_MAXTOP .lblTimeRemaining.Top = TIMEREMAINING_MAXTOP .TimeRemaining.Top = TIMEREMAINING_MAXTOP End If .ProgressBar.Width = 0 .StartUpPosition = 0 .Left = Application.Left + (STARTPOS_LEFT_OFFSET * Application.Width) - (STARTPOS_LEFT_OFFSET * .Width) .Top = Application.Top + (STARTPOS_RIGHT_OFFSET * Application.Height) - (STARTPOS_RIGHT_OFFSET * .Height) .Show End With End Sub Private Sub HideTitleBar() Dim lngWindow As Long, lngFrmHdl As Long lngFrmHdl = FindWindowA(vbNullString, Me.Caption) lngWindow = GetWindowLong(lngFrmHdl, GWL_STYLE) lngWindow = lngWindow And (Not WS_CAPTION) Call SetWindowLong(lngFrmHdl, GWL_STYLE, lngWindow) Call DrawMenuBar(lngFrmHdl) End Sub Private Sub IProgressIndicator_UpdateOrphanProgress(ByRef ProgStatusText As Variant, _ ByRef CurrProgCnt As Long, _ ByRef TotalProgCnt As Long) ThrowIfOrphanProcHasParent ThrowIfInvalidProgPercent CurrProgCnt, TotalProgCnt this.PercentComplete = CurrProgCnt / TotalProgCnt With Me .ProcedureStatus.Caption = ProgStatusText &amp; " " &amp; _ CurrProgCnt &amp; " of " &amp; TotalProgCnt .ProgressBar.Width = this.PercentComplete * PROGRESSBAR_MAXWIDTH End With If CalculateExecutionTime Then CalculateTime CurrProgCnt, TotalProgCnt DoEvents If CurrProgCnt = TotalProgCnt Then Me.Hide 'Unload Me ?? End Sub Private Sub IProgressIndicator_UpdateParentChildProgress(ByRef ParentProgStatusText As Variant, _ ByRef ParentCurrCnt As Long, _ ByRef ParentTotalCnt As Long, _ ByRef ChildProgStatusText As Variant, _ ByRef ChildCurrProgCnt As Long, _ ByRef ChildProgCnt As Long, _ ByRef TotalProgCnt As Long) ThrowIfHasParentNotSpecified ThrowIfInvalidParentCount ParentCurrCnt, ParentTotalCnt ThrowIfInvalidProgPercent ChildCurrProgCnt, ChildProgCnt this.ParentChildIterationCount = this.ParentChildIterationCount + 1 this.PercentComplete = ChildCurrProgCnt / ChildProgCnt With Me .ParentProcedureStatus.Caption = ParentProgStatusText &amp; " " &amp; _ ParentCurrCnt &amp; " of " &amp; ParentTotalCnt .ProcedureStatus.Caption = ChildProgStatusText &amp; " " &amp; _ ChildCurrProgCnt &amp; " of " &amp; ChildProgCnt .ProgressBar.Width = this.PercentComplete * PROGRESSBAR_MAXWIDTH End With If CalculateExecutionTime Then CalculateTime this.ParentChildIterationCount, TotalProgCnt DoEvents If ParentCurrCnt = ParentTotalCnt Then If ChildCurrProgCnt = ChildProgCnt Then Me.Hide 'Unload Me ?? End If End Sub '***************************************************************************** 'Time Calulations '***************************************************************************** Private Sub CalculateTime(ByRef CurrProgCntIn As Long, ByRef TotalProgCntIn As Long) With this If CurrProgCntIn = TotalProgCntIn Then Me.ElapsedTime.Caption = "" &amp; .HoursElapsed &amp; " hours, " &amp; _ .MinutesElapsed &amp; " minutes, " &amp; .SecondsElapsed &amp; " seconds" Me.TimeRemaining.Caption = "" &amp; 0 &amp; " hours, " &amp; 0 &amp; _ " minutes, " &amp; 0 &amp; " seconds" Else .TimeElapsed = (GetTickCount() - this.StartTime) .SecondsElapsed = .TimeElapsed / 1000 .MinutesElapsed = RoundTime(.TimeElapsed, 60000) .HoursElapsed = RoundTime(.TimeElapsed, 3600000) .ItemsRemaining = TotalProgCntIn - CurrProgCntIn .SecondsRemaining = (.SecondsElapsed * (TotalProgCntIn / CurrProgCntIn)) - .SecondsElapsed .MinutesElapsed = RoundTime(.SecondsRemaining, 60) .HoursElapsed = RoundTime(.SecondsRemaining, 60) Me.ElapsedTime.Caption = "" &amp; .HoursElapsed &amp; " hours, " &amp; _ .MinutesElapsed &amp; " minutes, " &amp; .SecondsElapsed &amp; " seconds" Me.TimeRemaining.Caption = "" &amp; .HoursRemaining &amp; " hours, " &amp; .MinutesRemaining &amp; _ " minutes, " &amp; .SecondsRemaining &amp; " seconds" End If End With End Sub Private Function RoundTime(ByRef TimeElapsedIn As Double, ByVal IntervalIn As Long) As Double RoundTime = Int(TimeElapsedIn / IntervalIn) End Function '***************************************************************************** 'Error Checking Procedures '***************************************************************************** Private Sub ThrowIfOrphanProcHasParent() If HasParentProccess Then Beep Err.Raise ProgressIndicatorError.Error_OrphanProcHasParent, _ TypeName(Me), ERR_ORPHANPROC_NOPARENT End If End Sub Private Sub ThrowIfHasParentNotSpecified() If Not HasParentProccess Then Beep Err.Raise ProgressIndicatorError.Error_HasParentProcNotSpecified, _ TypeName(Me), ERR_HASPARENT_NOTSPECIFIED End If End Sub Private Sub ThrowIfInvalidProgPercent(ByRef CurrProgCntIn As Long, ByRef TotalProgCntIn As Long) If Not (CurrProgCntIn &gt; 0 And CurrProgCntIn &lt;= TotalProgCntIn) Then Beep Err.Raise ProgressIndicatorError.Error_InvalidProgressPercentage, _ TypeName(Me), ERR_INVALIDPROGPERCENT End If End Sub Private Sub ThrowIfInvalidParentCount(ByRef ParentCurrCntIn As Long, ByRef ParentTotalCntIn As Long) If Not (ParentCurrCntIn &gt; 0 And ParentCurrCntIn &lt;= ParentTotalCntIn) Then Beep Err.Raise ProgressIndicatorError.Error_InvalidParentCount, _ TypeName(Me), ERR_INVALIDPARENTCOUNT End If End Sub </code></pre> <p><strong>Tests:</strong> </p> <pre><code>Public Sub TestingOrphanProccess() Dim i As Long Dim ProgressBar As IProgressIndicator On Error GoTo ErrHandle Set ProgressBar = New ProgressIndicator ProgressBar.LoadProgIndicator CanCancel:=True, CalculateExecutionTime:=True For i = 1 To 10000 'only have to specify this property if boolCanCancel:=True If ProgressBar.ShouldCancel Then Exit Sub Sheet1.Cells(1, 1) = i ProgressBar.UpdateOrphanProgress "Proccessing", i, 10000 Next Exit Sub ErrHandle: Debug.Print Err.Number End Sub </code></pre> <p><a href="https://i.stack.imgur.com/sJLXk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sJLXk.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/ZTNJ4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZTNJ4.png" alt="enter image description here"></a></p> <pre><code>Sub TestingParentChildProccess() Dim ProgressBar As IProgressIndicator Dim dict As Object Dim arryTotalItemCnt() As Variant, arryTemp As Variant Dim lngMaxItems As Long Dim varKey As Variant Dim lngParentCntr As Long, i As Long Set ProgressBar = New ProgressIndicator ProgressBar.LoadProgIndicator HasParentProccess:=True, CanCancel:=True, CalculateExecutionTime:=True Set dict = CreateObject("Scripting.Dictionary") dict("Key1") = Array(1, 2, 3) ReDim Preserve arryTotalItemCnt(UBound(dict("Key1")) + 1) dict("Key2") = Array(1, 2, 3, 4) ReDim Preserve arryTotalItemCnt(UBound(arryTotalItemCnt) + UBound(dict("Key2")) + 1) dict("Key3") = Array(1, 2, 3, 4, 5) ReDim Preserve arryTotalItemCnt(UBound(arryTotalItemCnt) + UBound(dict("Key3")) + 1) lngMaxItems = UBound(arryTotalItemCnt) For Each varKey In dict lngParentCntr = lngParentCntr + 1 arryTemp = dict.Item(varKey) For i = 0 To UBound(arryTemp) ProgressBar.UpdateParentChildProgress "Proccessing Parent", lngParentCntr, dict.Count, _ "Processing Child", i + 1, UBound(arryTemp) + 1, lngMaxItems Application.Wait (Now() + TimeValue("00:00:01")) Next i Next End Sub </code></pre> <p><a href="https://i.stack.imgur.com/8QY4e.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8QY4e.png" alt="enter image description here"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T19:29:53.980", "Id": "433416", "Score": "1", "body": "That looks great, I hope I find the time to review it! Couple questions: Why are all these parameters `ByRef`, why the explicit `Call` keyword in only two out of [didn't count, ...many, many, *many*] call statements? You might have missed [this recent SO answer](https://stackoverflow.com/a/56874163/1188513) ;-) lastly, the indentation feels inconsistent in a few places, are you using an [indenter](http://rubberduckvba.com/indentation)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T19:31:52.923", "Id": "433417", "Score": "0", "body": "Linking the [original progress indicator post](https://codereview.stackexchange.com/q/87818/23788), for context" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T20:04:34.020", "Id": "433420", "Score": "1", "body": "@MathieuGuindon I hope so to for my sake, lol! I chose `ByRef` because I figured that passing `ByVal` would be slower for when using the progress indicator for long running processes. That could very well be a naive assumption, but that's why I did it. As for `Call` in the `HideTitleBar` sub, I originally had the `Call` key word for all the sub procedures, as I prefer to do so to explicitly denote the use of a `Sub`, but I thought it looked clutered in my class, so I got rid of it, but obviously I missed the two in `HideTitleBar`. And I am not using an indenter, but I probably should, lol." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T21:50:30.737", "Id": "433434", "Score": "1", "body": "Don't have time to review at the moment - but a quick UI comment. If you are using the form to allow the user to cancel the operation (which is a good idea in my opinion), then including the `Cancel` button on the form itself is a better UI design choice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T21:51:32.687", "Id": "433435", "Score": "0", "body": "Oh, and having the name of the process is certainly important just in case you have more than one progress bar up!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T12:25:39.827", "Id": "433759", "Score": "0", "body": "@AJD Great suggestions! I am also thinking about implementing some sort of conditional pause functionality as well so for that I would definitely need a visible button." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T19:00:04.573", "Id": "223581", "Score": "4", "Tags": [ "object-oriented", "vba" ], "Title": "Reusable Progress Indicator" }
223581
<p>Are there any efficient ways to solve this problem, for example using bitwise operator?</p> <pre class="lang-java prettyprint-override"><code> public static boolean isPal(long num) { String numStr = Long.toString(num); String rNumStr = ""; boolean result = false; for (int i = numStr.length() - 1; i &gt;= 0 ; --i) rNumStr += numStr.charAt(i); //System.out.println(numStr + "," + rNumStr); try { if (Long.parseLong(numStr) == Long.parseLong(rNumStr)) result = true; else result = false; }catch (NumberFormatException e) { //System.err.println("Unable to format. " + e); } return result; } public static void calcPal(int rangeMin, int rangeMax) { long maxp = 0, maxq = 0, maxP = 0; for (int p = rangeMax; p &gt; rangeMin; p--) for (int q = rangeMax; q &gt; rangeMin; q--) { long P = p * q; if (isPal(P)) if (P &gt; maxP) { maxp = p; maxq = q; maxP = P; } } System.out.println(maxp + "*" + maxq + "=" + maxP); } public static void main(String[] args) { calcPal(10, 99); calcPal(100, 999); calcPal(9000, 9999); calcPal(10000, 99999); calcPal(990000, 999999); } </code></pre> <p>The largest palindrome which can be made from the product of two 2-digit (10 to 99) numbers is 9009 (91 × 99). Write a function to calculate the largest palindromic number from the product of two 6-digit numbers (100000 to 999999).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T19:18:24.640", "Id": "433412", "Score": "0", "body": "it is my interview question" } ]
[ { "body": "<h2>Bug</h2>\n\n<pre><code> for (int p = rangeMax; p &gt; rangeMin; p--)\n for (int q = rangeMax; q &gt; rangeMin; q--)\n</code></pre>\n\n<p>You are not including <code>rangeMin</code> in either of the loops, so you will never test products which involve the lower limit. You want <code>&gt;=</code> in the loop condition:</p>\n\n<pre><code> for (int p = rangeMax; p &gt;= rangeMin; p--)\n for (int q = rangeMax; q &gt;= rangeMin; q--)\n</code></pre>\n\n<h2>Commutativity</h2>\n\n<p>Note that <code>p * q == q * p</code>, so you don't need to test all combinations in the range:</p>\n\n<pre><code> for (int p = rangeMax; p &gt; rangeMin; p--)\n for (int q = rangeMax; q &gt; rangeMin; q--)\n</code></pre>\n\n<p>Only the ones where either <code>p &gt;= q</code> or <code>q &gt;= p</code>, which will reduce your search space by close to 50%! For example, you could change the <code>q</code> range to start at the current <code>p</code> value and go down from there:</p>\n\n<pre><code> for (int p = rangeMax; p &gt;= rangeMin; p--)\n for (int q = p; q &gt;= rangeMin; q--)\n</code></pre>\n\n<h2>Test order: Fastest tests first!</h2>\n\n<p><code>isPal(P)</code> is an involved function which will take a bit of time. In comparison, <code>P &gt; maxP</code> is blazingly fast. So instead of:</p>\n\n<pre><code> if (isPal(P))\n if (P &gt; maxP)\n {\n maxp = p; maxq = q; maxP = P;\n }\n</code></pre>\n\n<p>how about:</p>\n\n<pre><code> if (P &gt; maxP)\n if (isPal(P))\n {\n maxp = p; maxq = q; maxP = P;\n }\n</code></pre>\n\n<h2>Early termination</h2>\n\n<p>If <code>p*q</code> is ever less than <code>maxP</code>, then multiplying <code>p</code> by any smaller value of <code>q</code> is a waste of time; you can break out of the inner loop, and try the next value of <code>p</code>.</p>\n\n<p>If <code>p*p</code> is ever less than <code>maxP</code>, and the inner loop only multiplies <code>p</code> by <code>q</code> values which a not greater than <code>p</code>, then you can break out of the outer loop, too!</p>\n\n<h2>String Manipulation</h2>\n\n<p>The following is inefficient, because temporary objects are being created and destroyed during each iteration.</p>\n\n<pre><code> for (int i = numStr.length() - 1; i &gt;= 0 ; --i)\n rNumStr += numStr.charAt(i);\n</code></pre>\n\n<p>It is much better to use a <a href=\"https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/StringBuilder.html\" rel=\"nofollow noreferrer\"><code>StringBuilder</code></a> to build up strings character by character, because the <code>StringBuilder</code> maintains a mutable buffer for the interm results.</p>\n\n<p>Even better, it includes the <a href=\"https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/StringBuilder.html#reverse()\" rel=\"nofollow noreferrer\"><code>.reverse()</code></a> method, which does what you need in one function call.</p>\n\n<pre><code>StringBuilder sb = new StringBuilder(numStr);\nString rNumStr = sb.reverse().toString();\n</code></pre>\n\n<h2>Unnecessary Operations</h2>\n\n<p>Why convert <code>numStr</code> to a number using <code>Long.parseLong(numStr)</code>? Isn't the result simply <code>num</code>, the value that was passed in to the function?</p>\n\n<p>Why convert <code>rNumStr</code> to a number? If <code>num</code> is a palindrome, then aren't <code>numStr</code> and <code>rNumStr</code> equal?</p>\n\n<pre><code>public static boolean isPal(long num) \n{\n String numStr = Long.toString(num);\n StringBuilder sb = new StringBuilder(numStr);\n String rNumStr = sb.reverse().toString();\n\n return numStr.equals(rNumStr);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T22:53:38.953", "Id": "433444", "Score": "0", "body": "Very minor nitpick: \"Fastest tests first\" is a reasonable heuristic but even from a speed perspective is not the only axis worth considering. \"Most selective test first\" is also a reasonable heuristic, and the interplay between test speed and selectivity is intricate. I suspect without measurement that you're right in this case that the quicker test is a good filter, but perhaps it wants fleshing out why." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T23:00:15.257", "Id": "433445", "Score": "2", "body": "In this particular case, as mentioned \"you could change the q range to start at the current p value and go down from there.\" You could do one better than that, and start `q` at `maxP / p` if larger. That could allow the `P > maxP` test to be removed altogether." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T22:00:10.337", "Id": "223590", "ParentId": "223582", "Score": "4" } }, { "body": "<p>In an interview setting it is quite hard to come with an efficient solution (unless you happen to be very good in mental multiplication; however a <span class=\"math-container\">\\$99 * 91\\$</span> example is a strong hint). The key to an efficient solution is an observation that</p>\n\n<p><span class=\"math-container\">\\$999999 * 999001 = 999000000999\\$</span></p>\n\n<p>is a quite large palindromic product. It means that you don't have to test the entire 6-digit ranges of multiplicands. It is enough to test multiplicands only in <span class=\"math-container\">\\$[999001.. 999999]\\$</span> range. Just <span class=\"math-container\">\\$10^6\\$</span> candidate pairs rather than <span class=\"math-container\">\\$10^{12}\\$</span>.</p>\n\n<p>BTW, a similar identity holds for products of longer numbers as well.</p>\n\n<p>Next, you may notice that there are just one thousand palindromic numbers larger than <span class=\"math-container\">\\$999000000999\\$</span> (they are in form of <code>999abccba999</code>), and to qualify as a solution is must have a 6-digit factor larger than <span class=\"math-container\">\\$999001\\$</span>. This implies the following algorithm (in pseudocode):</p>\n\n<pre><code>base = 999000000999\nabc = 999\nwhile abc &gt;= 0\n cba = reverse_digits(abc)\n number = base + abc * 1000000 + cba * 1000\n for factor in 999001 to sqrt(number)\n if number % factor == 0:\n return number\n abc -= 1\n</code></pre>\n\n<p>The <code>reverse_digits</code> of a 3-digit number could be done extremely fast (a lookup table, for example). Still a <span class=\"math-container\">\\$10^6\\$</span> or so rounds, but no expensive tests for palindromicity.</p>\n\n<p>All that said, since the problem stems from <a href=\"https://projecteuler.net/problem=4\" rel=\"noreferrer\">Project Euler #4</a> it is possible that it admits a more elegant number-theoretical solution.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T23:32:59.470", "Id": "223592", "ParentId": "223582", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T19:08:05.517", "Id": "223582", "Score": "3", "Tags": [ "java", "programming-challenge", "interview-questions", "palindrome" ], "Title": "Calculate the largest palindromic number from the product of two 6-digit numbers (100000 to 999999)" }
223582
<p>How would I go about shortening this code? I'm sure there's a smarter way to write the code. It's working fine, it's just ugly.</p> <p>It is a way to scrape the number of items on an e-commerce site. </p> <pre><code>import requests from bs4 import BeautifulSoup import re url1 = "https://us.pandora.net/en/charms/?sz=30&amp;start={}&amp;format=page-element" url2 = "https://us.pandora.net/en/bracelets/?sz=30&amp;start={}&amp;format=page-element" url3 = "https://us.pandora.net/en/rings/?sz=30&amp;start={}&amp;format=page-element" url4 = "https://us.pandora.net/en/necklaces/?sz=30&amp;start={}&amp;format=page-element" url5 = "https://us.pandora.net/en/earrings/?sz=30&amp;start={}&amp;format=page-element" #res = requests.get(link.format(url1),headers={"User-Agent":"Mozilla/5.0"}) soup1 = BeautifulSoup(requests.get(url1.format(0)).text, 'lxml') soup2 = BeautifulSoup(requests.get(url2.format(0)).text, 'lxml') soup3 = BeautifulSoup(requests.get(url3.format(0)).text, 'lxml') soup4 = BeautifulSoup(requests.get(url4.format(0)).text, 'lxml') soup5 = BeautifulSoup(requests.get(url5.format(0)).text, 'lxml') total_items1 = ''.join(re.findall(r'\d', soup1.select_one('span.products-count').text)) total_items2 = ''.join(re.findall(r'\d', soup2.select_one('span.products-count').text)) total_items3 = ''.join(re.findall(r'\d', soup3.select_one('span.products-count').text)) total_items4 = ''.join(re.findall(r'\d', soup4.select_one('span.products-count').text)) total_items5 = ''.join(re.findall(r'\d', soup5.select_one('span.products-count').text)) #categories = [tag['title'].strip() for tag in soup.select('.refinement-link[title]') #total_items_sale1 = ''.join(re.findall(r'\d', soup1.select_one('.grid-tile .price-standard'))) #total_items_sale1 #total_items_sale1 #total_items_sale1 #total_items_sale1 #print('Categories:') #for category in categories: #print('\t{}'.format(category)) print('\nTotal Charms: {}'.format(total_items1)) print('\nTotal Bracelets: {}'.format(total_items2)) print('\nTotal Rings: {}'.format(total_items3)) print('\nTotal Necklaces: {}'.format(total_items4)) print('\nTotal Earrings: {}'.format(total_items5)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T20:24:40.613", "Id": "433421", "Score": "0", "body": "I'm not sure I spot what you've changed, it still looks the same to me. Could you be more specific?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T20:41:59.827", "Id": "433423", "Score": "0", "body": "I added [tag:python-3.x] and added a final newline. The newline is to make sure that the closing code fences are not shown in the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T20:44:19.857", "Id": "433425", "Score": "0", "body": "Oh, I see. Thanks, AlexV." } ]
[ { "body": "<p>If you find yourself, doing something over and over again, loops are often the answer.</p>\n\n<p>Your code rewritten with a loop:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import re\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nurls = {\n \"Charms\": \"https://us.pandora.net/en/charms/?sz=30&amp;start={}&amp;format=page-element\",\n \"Bracelets\": \"https://us.pandora.net/en/bracelets/?sz=30&amp;start={}&amp;format=page-element\",\n \"Rings\": \"https://us.pandora.net/en/rings/?sz=30&amp;start={}&amp;format=page-element\",\n \"Necklaces\": \"https://us.pandora.net/en/necklaces/?sz=30&amp;start={}&amp;format=page-element\",\n \"Earrings\": \"https://us.pandora.net/en/earrings/?sz=30&amp;start={}&amp;format=page-element\"\n}\n\nfor category, url in urls.items():\n soup = BeautifulSoup(requests.get(url.format(0)).text, 'lxml')\n total_items = ''.join(re.findall(r'\\d', soup.select_one('span.products-count').text))\n print(\"Total {}: {}\".format(category, total_items))\n</code></pre>\n\n<p>So what has changed? The URLs went into a <a href=\"https://docs.python.org/3/tutorial/datastructures.html#dictionaries\" rel=\"noreferrer\">dictionary</a> where the category's name is the key. A simple list would also work here in your case. Now we can iterate over that dictionary. With <code>for category, url in urls.items():</code> you get the key, i.e. the name of the category and the URL at the same time.</p>\n\n<p>The loop body now does what you had written out by hand, namely getting the page, parse the content with BeautifulSoup and than again with a regex.</p>\n\n<p>Since the URL came bundled with the category, we can no print all the results nicely without writing the same code over and over again.</p>\n\n<p>You can also go a step further and make this into a function:</p>\n\n<pre><code>import re\n\nimport requests\nfrom bs4 import BeautifulSoup\n\n\ndef get_total_items(url):\n \"\"\"Parse the product count from the given pandora URL\"\"\"\n soup = BeautifulSoup(requests.get(url).text, 'lxml')\n return ''.join(re.findall(r'\\d', soup.select_one('span.products-count').text))\n\n\nif __name__ == \"__main__\":\n urls = {\n \"Charms\": \"https://us.pandora.net/en/charms/?sz=30&amp;start={}&amp;format=page-element\",\n \"Bracelets\": \"https://us.pandora.net/en/bracelets/?sz=30&amp;start={}&amp;format=page-element\",\n \"Rings\": \"https://us.pandora.net/en/rings/?sz=30&amp;start={}&amp;format=page-element\",\n \"Necklaces\": \"https://us.pandora.net/en/necklaces/?sz=30&amp;start={}&amp;format=page-element\",\n \"Earrings\": \"https://us.pandora.net/en/earrings/?sz=30&amp;start={}&amp;format=page-element\"\n }\n\n for category, url in urls.items():\n print(\"Total {}: {}\".format(category, get_total_items(url.format(0))))\n\n</code></pre>\n\n<p>Now the intermediate variable <code>soup</code> is inside the function and does not clutter the global namespace. You could also now easily change the implementation of <code>get_total_items(...)</code> without the need to adapt the \"application\" code.</p>\n\n<p>I also added the infamous <code>if __name__ == \"__main__\":</code>, which is basically Python's way to tell someone looking at the script: \"This piece of code is supposed to be run if you use this as a script.\" Have a look at the official <a href=\"https://docs.python.org/3/library/__main__.html\" rel=\"noreferrer\">documentation</a> or <a href=\"https://stackoverflow.com/q/419163/5682996\">this Stack Overflow post</a> if you want to learn more.</p>\n\n<hr>\n\n<p>A more subtle change: I reorderd the imports to follow the recommendation of the official <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">Style Guide for Python Code</a> (often just PEP8), which is to have imports from the standard libraries first, then a blank line, and then all the third party libraries.</p>\n\n<p>In general PEP8 is often worth a read, especially if you are not yet familiar with Python.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T20:43:21.653", "Id": "433424", "Score": "0", "body": "Thank you so much!! It has even increased in pace, that's lovely! This is my first time using Stackoverflow and I gotta say, I'm surprised by the good of the community. Never expected people to be so kind, and generous - it is in the end their own time and energy they spend on other peoples code. I also learn alot by looking at the fixes, and different suggestions. Thanks again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T20:53:41.350", "Id": "433426", "Score": "0", "body": "@doomdaam: If you stick to the rules, Code Review is generally a very friendly place where you often can get excellent feedback on your code. It has to be fully functional to the best of your knowledge though. If it's not yet working, [so] is usually more appropriate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T21:13:52.077", "Id": "433428", "Score": "0", "body": "I'm not an expert when it comes to `requests`. So that might be a better question for [so]. From what I know, if you really want to send a user agent header, at least use a [real one](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T21:19:23.273", "Id": "433431", "Score": "0", "body": "I figured out! Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T21:46:19.473", "Id": "433433", "Score": "0", "body": "I have a new question regarding the second part of my scraper. I tried to play around with your solution and somehow ues the same mindset of dicts and lists, but without any luck. Here's the thread: [link]https://codereview.stackexchange.com/questions/223588/e-commerce-scraper-scraping-number-of-items-on-sale-code-needs-shortening[/link]" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T20:40:27.780", "Id": "223586", "ParentId": "223585", "Score": "6" } }, { "body": "<p>Starting from <a href=\"https://codereview.stackexchange.com/a/223586/98493\">the answer</a> by <a href=\"https://codereview.stackexchange.com/users/92478/alexv\">@AlexV</a>, you can reduce the code even more by recognizing that the category name is the only difference in the URLs:</p>\n\n<pre><code>import re\nimport requests\nfrom bs4 import BeautifulSoup\n\n\ndef get_total_items(url):\n \"\"\"Parse the product count from the given pandora URL\"\"\"\n soup = BeautifulSoup(requests.get(url).text, 'lxml')\n return ''.join(re.findall(r'\\d', soup.select_one('span.products-count').text))\n\n\nif __name__ == \"__main__\":\n url_template = \"https://us.pandora.net/en/{}/?sz=30&amp;start={}&amp;format=page-element\"\n categories = \"charms\", \"bracelets\", \"rings\", \"necklaces\", \"earrings\"\n\n for category in categories:\n url = url_template.format(category, 0)\n print(f\"Total {category.title()}: {get_total_items(url)}\")\n</code></pre>\n\n<p>I used an <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\"><code>f-string</code></a> (Python 3.6+) to make the string formatting in the <code>for</code> loop a bit more concise and <a href=\"https://docs.python.org/3/library/stdtypes.html#str.title\" rel=\"nofollow noreferrer\"><code>str.title</code></a> to change the lowercase category name to titlecase.</p>\n\n<hr>\n\n<p>What you can do after this is use the fact that the <code>requests</code> module can build the request parameters for you. This allows you to also check multiple pages:</p>\n\n<pre><code>import re\nimport requests\nfrom bs4 import BeautifulSoup\n\ndef count_items(response):\n \"\"\"Parse the product count from the given response\"\"\"\n soup = BeautifulSoup(response.text, 'lxml')\n return ''.join(re.findall(r'\\d', soup.select_one('span.products-count').text))\n\n\ndef get_total_items(url):\n \"\"\"Get the items 30 at a time, up to 1000\"\"\"\n params = {\"sz\": 30, \"format\": \"page-element\"}\n return sum(count_items(requests.get(url, params=params))\n for params[\"start\"] in range(0, 1000, 30))\n\nif __name__ == \"__main__\":\n url = \"https://us.pandora.net/en/{}/\"\n categories = \"charms\", \"bracelets\", \"rings\", \"necklaces\", \"earrings\"\n\n for category in categories:\n total_items = get_total_items(url.format(category))\n print(f\"Total {category.title()}: {total_items}\") \n</code></pre>\n\n<p>This has the step and maximum page number hardcoded, but you could make it an argument of the function. You could also use a <code>requests.Session</code> to reuse the connection to the server, which speeds it up a bit.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T17:38:56.150", "Id": "433518", "Score": "0", "body": "this works like a charm, thank you for your effort! Do you think you could take a look at this code as well? https://codereview.stackexchange.com/questions/223588/e-commerce-scraper-scraping-number-of-items-on-sale-code-needs-shortening I'm having a hard time shortening it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T21:46:41.227", "Id": "433556", "Score": "0", "body": "@doomdaam I added some possible next steps, which might be similar to what you want to do" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T06:48:12.950", "Id": "433590", "Score": "0", "body": "very appreciated! Thank you." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T10:18:08.080", "Id": "223608", "ParentId": "223585", "Score": "2" } } ]
{ "AcceptedAnswerId": "223586", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T19:50:36.060", "Id": "223585", "Score": "5", "Tags": [ "python", "python-3.x", "web-scraping" ], "Title": "E-commerce scraper needs shortening" }
223585
<p>This post is an update of the one from <a href="https://codereview.stackexchange.com/questions/223439/finding-paths-between-triangles-efficiently-in-3d-geometry">here</a>. I've updated the code and a couple pieces of the post itself.</p> <p>I've been writing some functions used to find paths between two types of triangles - alphas and betas. Alphas are triangles that have been in a zone we consider important, have an "interesting" value above a given threshold, and are "active". Betas are essentially anything that isn't an Alpha. </p> <p>The position of the zone and the geometry of the model can change between invocations. Thus, both alphas and betas change almost every invocation to some extent. This requires a complete re-computation of the paths between them.</p> <p>This is written in C++03, compiled into a MEX file (.mexa64) to be executed by MATLAB R2016B on a Linux machine. <strong>Those are all hard limits I do not have control over. I cannot make it C++11 or later.</strong></p> <p>This code uses a good deal of functions and data from an external libraries and objects. However, most of the methods used are very simple array lookups, nothing performance-hindering. </p> <p>Everything works correctly so far in testing, but performance has become a significant problem.</p> <p><strong>Note on globals:</strong> They're needed because some information must persist between calls to the MEX file. This is the only way to do it, other than perhaps by writing them out to a file, which would be much slower. I know globals aren't ideal - it's just what I have to work with. </p> <p><strong>What the MATLAB Script is providing:</strong></p> <p>I should be clear on this as well. The MATLAB script or the Raytracer (both of which I cannot modify) provide nodeIValues, elemFace, and anything from m_nrt or the CRTWrapper that I use. I can't touch those.</p> <p><strong>The code:</strong></p> <pre><code>// Doxygen block goes here // Various includes // Only needed because ultimately the MATLAB script needs an error code, not a // C++ exception #define SUCCESS 0 #define PTHREAD_ERR 1 typedef std::pair&lt;unsigned int, unsigned int&gt; ABPair; // Useful for multithreading struct ThreadData { CRayTracer* rt; pthread_t threadId; // ID returned by pthread_create unsigned uThreadID; // Index std::vector&lt;ABPair&gt; validPathsThread; // valid pairs that this thread // found unsigned int numTris; // Input argument, the number of // triangles in the mesh double distThreshold; // Input argument, the maximum // distance between triangles }; // Exception for experimentation class PThreadException: public std::exception { virtual const char* what() const throw() { return "Exception occured in a pthread_attr_init or pthread_create\n"; } }; // Data about each individual tri, could be brought intro a vector of structs // Needed to check if geometry has changed since last invokation std::vector&lt;bool&gt; triActive; // Needed to check if alphas have changed since last invokation std::vector&lt;bool&gt; validAlphaIndex; // Needed to keep history of what tris have ever been in the beam, for alphas std::vector&lt;bool&gt; hasBeenInBeam; // A "map" from a given face to the element it resides in. Many faces may share // the same element. std::vector&lt;unsigned int&gt; faceToElementMap; // Not neccesary as a global if it's just getting re-generated each time. // However, if we do decide to append and cull instead of regenerating, this // needs to stay. std::vector&lt;unsigned int&gt; validAlphas; // All valid paths. Must be maintained, because we don't know if // findPaths() will be called. It may not be if geometry hasnt changed. std::vector&lt;ThermalPair&gt; validPaths; unsigned int prevPathNum = 0; // Useful everywhere CRTWrapper* rayTracer = NULL; NanoRTWrapper* m_nrt = NULL; // Function declarations // Not required, but prevents warnings depending on how functions are ordered // and call each other // (Including the mexFunction here would be redundant, as it exists in mex.h) void exitFcn(); bool isTriInZoneRadius(const unsigned int iTri); bool checkForModelChanges(const unsigned int numTris, const float* nodeIValues, const double iValueThreshold ); void initialize(const float* elemFace, const unsigned int numElems, const unsigned int facePerElMax, unsigned int* numTri, unsigned int* numFace ); void* findPathsThread(void *data); void findPathsThreadSpooler(const unsigned int numTris, const double distThreshold ); void mapFacesToElements(const float* elemFace, const unsigned int numElems, const unsigned int facePerElMax ); bool checkPairValid(const unsigned int i, const unsigned int j, const double distThreshold ); bool isTriAlpha(const unsigned int iTri, const float* nodeIValues, const double iValueThreshold ); int mainFunc(some args gohere); /** * @brief exitFcn - Cleans up malloc'd or calloc'd memory if someone in the * MATLAB script calls "clear mexFileName" or "clear all". Does nothing ATM. */ void exitFcn() { // mexPrintf("exitFcn() called\n"); // Does nothing right now, since I don't malloc/calloc anything } /** * @brief Checks if a given tri is currently in the zone's external radius. * @param iTri - The index of the triangle to check * @return True if in the radius, false if not */ bool isTriInZoneRadius(const unsigned int iTri) { // Omitted, relies on some funky external stuff that'd be hard to explain // hasBeenInZone[] gets updated here } /** * @brief Checks if the model has changed (either in terms of alphas or * geometry) and re-generates the vector of alphas * @param numTris - The number of triangles in the mesh * @param nodeIValues - The iValue at each node * @param iValueThreshold - The iValue threshold beyond which an alpha * is interesting enough to be valid * @return True if the list of alphas or the geometry has changed, false if * neither have */ bool checkForModelChanges(const unsigned int numTris, const float* nodeIValues, const double iValueThreshold ) { bool modelChanged = false; bool isAlpha; bool currentlyActive; // Two checks need to happen - geometry changes and for the list of valid // alphas to change // Also regenerates the vector of valid alphas from scratch as it goes for(unsigned int i = 0; i &lt; numTris; i++) { // Active means it has 1 exposed face, not 2 (internal) or 0 (eroded) currentlyActive = m_nrt-&gt;getTriActive(i); // Has the geometry changed? if(currentlyActive != triActive[i]) { modelChanged = true; triActive[i] = currentlyActive; } // Get whether this triangle is an alpha: isAlpha = isTriAlpha(i, nodeIValues, iValueThreshold); // Triangle is a valid alpha now, but wasn't before if((isAlpha == true) &amp;&amp; (validAlphaIndex[i] == false)) { validAlphaIndex[i] = true; modelChanged = true; } // Was valid before, is no longer valid now else if((isAlpha == false) &amp;&amp; (validAlphaIndex[i] == true)) { validAlphaIndex[i] = false; modelChanged = true; //cullalphasFlag = true; } // Generating the set of all valid alphas if(isAlpha) { validAlphas.push_back(i); } } return modelChanged; } /** * @brief Initializes this MEX file for its first run * @param rt - A pointer to the raytracer object * @param numTris - The total number of triangles in the mesh * @param numFaces - The total number of faces in the mesh * @param elemFace - The map of elements to the faces that they have * @param numElems - The number of elements in the mesh * @param facePerElMax - The maximum number of faces per element */ void initialize(const float* elemFace, const unsigned int numElems, const unsigned int facePerElMax, unsigned int* numTri, unsigned int* numFace ) { // Fetch number of tris and faces // Must be done every time, since we're storing locally and not globally // However: // They're never modified // They never change between calls to rtThermalCalculate() // They're used frequently in many functions // I think that's a strong candidate for being a global unsigned int numTris = m_nrt-&gt;getTriCount(); *numTri = numTris; unsigned int numFaces = m_nrt-&gt;getFaceCount(); *numFace = numFaces; /* * Allocate some space for things we need to be persistent between runs of * this MEX file. */ if(triActive.empty()) { triActive.resize(numTris, false); } if(hasBeenInZone.empty()) { hasBeenInZone.resize(numTris, false); } if(validAlphaIndex.empty()) { validAlphaIndex.resize(numTris, false); } if(faceToElementMap.empty()) { faceToElementMap.resize(numFaces); mapFacesToElements(elemFace, numElems, facePerElMax); } return; } /** * @brief Is something that can be used by pthread_create(). Threads will skip * over some of the work, and do isValidPair on others. Thus...multithreading. * @param data - The data structure that will hold the results and arguments */ void* findPathsThread(void *data) { struct ThreadData* thisThreadsData = static_cast&lt;struct ThreadData*&gt;(data); const unsigned uThreadID = thisThreadsData-&gt;uThreadID; const unsigned uNumThreads = rayTracer-&gt;m_uNumThreads; const double distThreshold = thisThreadsData-&gt;distThreshold; const unsigned int numTris = thisThreadsData-&gt;numTris; unsigned int validI; std::vector&lt;ABPair&gt;&amp; validPathsThread = thisThreadsData-&gt;validPathsThread; // Loop over all valid alphas for(unsigned int i = uThreadID; i &lt; validAlphas.size(); i += uNumThreads) { // Get this to avoid needing to index into the array 4 times total // Each time validI = validAlphas[i]; // Loop over all triangles (potential betas) for(unsigned int j = 0; j &lt; numTris; j++) { // Do the easy checks first to avoid function call overhead if(!validAlphaIndex[j] &amp;&amp; triActive[j]) { if(checkPairValid(validI, j, distThreshold)) { validPathsThread.push_back(std::make_pair(validI, j)); } } } } return NULL; } /** * @brief Uses the raytracer object's current state as well as arguments to * generate pairs of unobstructed paths between alphas and betas. Creates * as many threads as the system has available, and then uses pthread_create() * to dish out the work of findPaths() * @param numTris - The number of triangles in the mesh * @param distThreshold - The maximum distance an alpha and beta can be * apart */ void findPathsThreadSpooler(const unsigned int numTris, const double distThreshold ) { std::vector&lt;ThreadData&gt; threadData(rayTracer-&gt;m_nProc); pthread_attr_t attr; int rc; // I think this is checking to make sure something doesn't already exist, // not sure what though if((rc = pthread_attr_init(&amp;attr))) { throw PThreadException(); } // We know how many threads the system supports // So all this does is walk through an array of them and start them up for(unsigned uThread = 0; uThread &lt; rayTracer-&gt;m_uNumThreads; uThread++) { ThreadData&amp; data = threadData[uThread]; data.rt = rayTracer; data.uThreadID = uThread; data.numTris = numTris; data.distThreshold = distThreshold; if(rayTracer-&gt;m_uNumThreads &gt; 1) { if((rc = pthread_create(&amp;data.threadId, &amp;attr, &amp;findPathsThread, &amp;data))) { throw PThreadException(); } } else { findPathsThread(&amp;data); } } // Join all threads for(unsigned uThread = 0; uThread &lt; rayTracer-&gt;m_uNumThreads; uThread++) { std::vector&lt;ABPair&gt;&amp; validPathsThread = threadData[uThread].validPathsThread; if(rayTracer-&gt;m_uNumThreads &gt; 1) { void* res; if((rc = pthread_join(threadData[uThread].threadId, &amp;res))) { throw PThreadException(); } } // validPathsThread is the set of ABPairs that this thread found // while validPaths is the globally maintained set of valid paths // Take each thread's results and merge it into the overall results validPaths.insert(validPaths.end(), validPathsThread.begin(), validPathsThread.end()); } // Useful for preallocation next time prevPathNum = validPaths.size(); return; } /* void cullalphas() { for(unsigned int i = 0; i &lt; validAlphas.size(); i++) { if(!isValidalpha(validAlphas[i])) { validAlphas.erase(i); } } } */ /** * @brief Determines the elements that each face belongs to * @details the MATLAB script maintains a map of all faces per element. * This is the opposite of what we want. Accessing it linearly * walks by column, not by row. Also, MATLAB stores everything 1-indexed. * Finally, the MATLAB script left them stored as the default, which are * singles. * @param elemFace - A MATLAB facePerElMax by numElems array, storing which * faces belong to each element (elements being the row number) * @param numElems - The total number of elements (rows) in the array * @param facePerElMax - The max number of faces per element (the number of * columns) */ void mapFacesToElements(const float* elemFace, const unsigned int numElems, const unsigned int facePerElMax ) { unsigned int i; // elemFace[0] = 1. We don't know how elemFace will be structured precisely, // so we need to keep going until we find a face in it that equals our number // of faces, since it's 1-indexed. for(i = 0; i &lt; (numElems * facePerElMax); i++) { faceToElementMap[static_cast&lt;unsigned int&gt;(elemFace[i]) - 1] = (i % numElems); // Is the next face for that element a NaN? If so, we can skip it. Keep // skipping until the next element WON'T be NaN. // Don't cast here, as NaN only exists for floating point numbers, // not integers. while(((i + 1) &lt; (numElems * facePerElMax)) &amp;&amp; isnan(elemFace[i + 1])) { i++; } } } /** * @brief checkPairValid - Checks if a pair of an alpha index * (of validAlphas), beta index form a valid path * @param i - Index into validAlphas * @param j - Index into all tris (potential beta) * @param distThreshold - The max distance the tri's centers can be apart * @return Whether the pair forms a valid path */ bool checkPairValid(const unsigned int i, const unsigned int j, const double distThreshold ) { double pathDist; double alphaCoords[3]; double betaCoords[3]; nanort::Ray&lt;double&gt; ray; alphaCoords[0] = rayTracer-&gt;m_vecTriFixedInfo[i].center.x(); alphaCoords[1] = rayTracer-&gt;m_vecTriFixedInfo[i].center.y(); alphaCoords[2] = rayTracer-&gt;m_vecTriFixedInfo[i].center.z(); betaCoords[0] = rayTracer-&gt;m_vecTriFixedInfo[j].center.x(); betaCoords[1] = rayTracer-&gt;m_vecTriFixedInfo[j].center.y(); betaCoords[2] = rayTracer-&gt;m_vecTriFixedInfo[j].center.z(); // Determine distance squared between alpha and beta // sqrt((x2-x1)^2 + (y2-y1)^2 +(z2-z1)^2) pathDist = sqrt(pow((betaCoords[0] - alphaCoords[0]), 2) + pow((betaCoords[1] - alphaCoords[1]), 2) + pow((betaCoords[2] - alphaCoords[2]), 2)); // Doing this instead of doing the sqrt to save doing the sqrt when not // needed for performance if(pathDist &lt; distThreshold) { // Set up a nanort::Ray's origin, direction, and max distance ray.org[0] = alphaCoords[0]; // x ray.org[1] = alphaCoords[1]; // y ray.org[2] = alphaCoords[2]; // z ray.dir[0] = (betaCoords[0] - alphaCoords[0]) / pathDist; ray.dir[1] = (betaCoords[1] - alphaCoords[1]) / pathDist; ray.dir[2] = (betaCoords[2] - alphaCoords[2]) / pathDist; // TODO: Subtract some EPSILON here so it doesn't report a hit because it // hit the beta itself (assuming that's how it works) ray.max_t = pathDist; // Call CNmg::ShootRay()'s third form to check if there is a path if(!(m_nrt-&gt;shootRay(ray))) { return true; } else { // There's no path return false; } } else { // The distance is too far between alpha and beta return false; } } /** * @brief Determines if a given triangle is a valid alpha. * @param iTri - The triangle index to check * @return True if it is an alpha, false if it is not */ bool isTriAlpha(const unsigned int iTri, const float* nodeIValues, const double iValueThreshold ) { double triAvgIValue; const unsigned int* triNodes; // Do the simple checks first, as it's more performant to do so // alternate consideration for accuracy //if(triActive[iTri] &amp;&amp; (hasBeenAlpha[iTri] || isTriInZoneRadius(iTri))) if(triActive[iTri] &amp;&amp; (hasBeenInZone[iTri] || isTriInZoneRadius(iTri))) { // Retrieve the average iValue of this triangle triNodes = m_nrt-&gt;getTriNodes(iTri); triAvgIValue = (nodeIValues[triNodes[0]] + nodeIValues[triNodes[1]] + nodeIValues[triNodes[2]]) / 3; if(triAvgIValue &gt; iValueThreshold) { return true; } } return false; } // Doxygen block, omitted int mainFunc(args) { // Some local vars, omitted // Initialize the program if we're on a first run initialize(elemFace, numElems, facePerElMax, &amp;numTris, &amp;numFaces); // Need to see if we need to call findPaths if(checkForModelChanges(numTris, nodeIValues, iValueThreshold)) { validPaths.clear(); validPaths.reserve(prevPathNum); try { findPathsThreadSpooler(numTris, distThreshold); } catch(PThreadException&amp; e) { return PTHREAD_ERR; } } // Loop over all valid paths, use them to do some more calculations..(omitted) // This takes up hundreds of the time findPaths() takes // Clear vector of valid alphas, it'll be re-generated from scratch each time validAlphas.clear() } // Doxygen block goes here, omitted, specific code also omitted as it's // irrelevant void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { // Register exit function // Prep for writing out results // Checking to make sure # of arguments was right from MATLAB // Input argument handling to convert from mxArrays to double*, float*, etc // *errcode = mainFunc(some args) // retrieve execution time in clock cycles, convert to seconds, print // Put the outputs in plhs } </code></pre> <p><strong>Callgraph(?):</strong></p> <p>This isn't exactly a callgraph, but it might be useful to get an idea of the flow of the program.</p> <p><a href="https://i.stack.imgur.com/7oOv7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7oOv7.png" alt="A rough callgraph of the methods"></a></p> <p><strong>The Problem: Performance</strong></p> <p>For medium-size models (104k tris, 204k faces, 51k elems) it can take up to a couple seconds for this to complete, even though the worst of it is multi-threaded on a powerful 4C/8T machine. (roughly 100*104k size loop)</p> <p>For any models where the number of alphas is very large (50K) it can take up to <em>three minutes</em> for a single execution to complete because of how large that double-nested for loop must become. (50k^2 size loop)</p> <p>Pushing the list of betas onto their own vector can help in cases like that, but seems to significantly hurt performance of more normal cases.</p> <p><strong>Possible optimizations:</strong></p> <ul> <li><p>Creating a sphere around all alphas to use in culling betas that are outside of the range of <em>any</em> alpha could potentially provide benefit, but it's an O(alphas^2) operation, and its benefit is extremely variable on the geometry.</p></li> <li><p>Creating a vector of Betas and pushing onto it as the alphas are also created seems to only benefit extreme edge cases like the 50k alpha case. In more "normal" cases of small numbers of alphas, it seems to hurt performance significantly. </p></li> <li><p>Adding to the list of valid alphas and culling it rather than re-building it each time may be an option, however, this will again be dependent on what % are alphas in the geometry.</p></li> <li><p>As well, it's possible something can be done with nanoRT's BVHs, but I'm not very familiar with BVH's or what they'd let me do in this</p></li> </ul> <p><strong>Note: How it's being used:</strong></p> <p>The MATLAB script will likely call this many times. In small models, it may finish its own loop within tenths of a second and then call ours again. In larger ones, there may be half a second between calls. In total, this may be called hundreds of times.</p> <p><strong>Note: How it's being built:</strong></p> <p>This isn't built using the <code>MEX</code> command in MATLAB, nor by using Visual Studio. Instead, g++ is used to create an object file (.o) and then g++ is used again to create the .mexw64 file in a method I'm not entirely familiar with. (This is also a hard limit I cannot touch)</p> <p>I occasionally compiled with very aggressive warnings enabled to catch things like sign conversion, promotions, bad casts, etc.</p> <p><strong>Profiling:</strong></p> <p>I would love to be able to profile this code more in depth. However, it seems impossible. MEX files built using <code>MEX</code> command in MATLAB can be done. MEX files compiled in Visual Studio can be profiled. But we're not doing either of those, and so when I try to profile with either MATLAB or Visual Studio, it just doesn't work.</p> <p>Even if I could, I don't think it would reveal anything surprising. The numbers we're working with are large, so the double-nested loop at the core of it grows very large.</p> <p>I can (and do) measure per-invocation performance and total runtime after the MATLAB script completes. This is mostly stable, ~1% std dev in runtimes. </p> <p><strong>Final Note:</strong></p> <p>While performance is my most major concern, style improvements are always welcome. I'm more familiar with C than C++, and that bleeds into my code sometimes.</p>
[]
[ { "body": "<p>This review doesn't cover performance, but writing cleaner code:</p>\n\n<hr>\n\n<p>Global variables are bad because it's hard to reason about them. They can be used anywhere, and (more frustratingly) at any time, making it harder to understand or change the code and its dependencies.</p>\n\n<p>It would be much easier to understand each function if all the dependencies are passed into it (by value or reference as appropriate). e.g. as well as the existing function arguments, <code>isTriAlpha</code> also depends on <code>triActive</code>, <code>hasBeenInZone</code>, and whatever global or state <code>isTriInZoneRadius</code> also depends on.</p>\n\n<p>While it may be necessary to declare variables at file / namespace scope in this I don't think there's a need to actually use them globally. e.g. They can be placed in a \"Global\" namespace that's only referred to in the top level function, and references to the relevant variables passed down as necessary.</p>\n\n<hr>\n\n<p>This last point might seem like a burden, but grouping data together appropriately will make this much easier. e.g. it looks like all these contain one item per triangle:</p>\n\n<pre><code>// Data about each individual tri, could be brought intro a vector of structs\n// Needed to check if geometry has changed since last invokation\nstd::vector&lt;bool&gt; triActive;\n// Needed to check if alphas have changed since last invokation\nstd::vector&lt;bool&gt; validAlphaIndex;\n// Needed to keep history of what tris have ever been in the beam, for alphas\nstd::vector&lt;bool&gt; hasBeenInBeam;\n</code></pre>\n\n<p>So perhaps they should all be in a struct <code>TriangleData</code> (or something), and we can pass a reference to it down through the function chain.</p>\n\n<hr>\n\n<p>Prefer references to pointers as function arguments for \"passing out\" data. e.g. the <code>numTri</code> and <code>numFace</code> arguments to <code>initialize</code> should be references and not pointers. Pointers can be null, whereas references can only be created from a valid object. Since we don't check for a null value before dereferencing the pointers, it looks like references would be more appropriate.</p>\n\n<hr>\n\n<p>It's better to use constant variables than defines. i.e. <code>SUCCESS</code> and <code>PTHREAD_ERR</code> should be:</p>\n\n<pre><code>static const int SUCCESS = 0;\nstatic const int PTHREAD_ERR = 1;\n</code></pre>\n\n<p>Preprocessor definitions have no scoping, so they can affect your entire project (and any code that may use your project), so are prone to name collisions.</p>\n\n<hr>\n\n<p>Declare variables as close to the point of use as possible and initialize them to the correct value straight away. e.g. in <code>checkForModelChanges</code>, <code>currentlyActive</code> and <code>isAlpha</code> should be declared and initialized inside the loop.</p>\n\n<p>Unless constructing the variables does some very slow resource allocation it's best to let the compiler worry about optimization.</p>\n\n<hr>\n\n<p>Comments should explain why the code does something, not just restate what the code does:</p>\n\n<pre><code>// Get whether this triangle is an alpha:\nisAlpha = isTriAlpha(i, nodeIValues, iValueThreshold);\n</code></pre>\n\n<p>If we have to write a comment that says what the code does because it's not clear from the code itself, we should make the code clearer instead, e.g.:</p>\n\n<pre><code>// Get whether this triangle is an alpha:\nisAlpha = isTriAlpha(i, nodeIValues, iValueThreshold);\n\n// Triangle is a valid alpha now, but wasn't before\nif((isAlpha == true) &amp;&amp; (validAlphaIndex[i] == false))\n{\n validAlphaIndex[i] = true;\n modelChanged = true;\n}\n// Was valid before, is no longer valid now\nelse if((isAlpha == false) &amp;&amp; (validAlphaIndex[i] == true))\n{\n validAlphaIndex[i] = false;\n modelChanged = true;\n //cullalphasFlag = true;\n}\n</code></pre>\n\n<p>Could just be:</p>\n\n<pre><code>const bool wasAlpha = validAlphaIndex[i];\nconst bool isAlpha = isTriAlpha(i, nodeIValues, iValueThreshold);\n\nif (wasAlpha != isAlpha) modelChanged = true;\nvalidAlphaIndex[i] = isAlpha;\n</code></pre>\n\n<hr>\n\n<p>Don't test booleans by comparing them to <code>true</code> or <code>false</code>, just test the boolean directly:</p>\n\n<pre><code>if (isAlpha) { ... }\nif (!isAlpha) { ... }\n</code></pre>\n\n<p>After all, the <code>==</code> operator returns a bool anyway...</p>\n\n<pre><code>if ((isAlpha == true) == true) { ... } // is it really, definitely true?\n</code></pre>\n\n<hr>\n\n<p>Similarly, something like this:</p>\n\n<pre><code>if(!(m_nrt-&gt;shootRay(ray)))\n{\n return true;\n}\nelse\n{\n // There's no path\n return false;\n}\n</code></pre>\n\n<p>is 8 lines of code, where we can really use just one:</p>\n\n<pre><code>return !m_nrt-&gt;shootRay(ray);\n</code></pre>\n\n<hr>\n\n<p>Prefer to return early where possible. This allows us to avoid unnecessary indentation and else clauses:</p>\n\n<pre><code>bool isTriAlpha(const unsigned int iTri,\n const float* nodeIValues,\n const double iValueThreshold\n )\n{\n if (!triActive[iTri])\n return false;\n\n if (!hasBeenInZone[iTri] &amp;&amp; !isInTriZoneRadius(iTri)))\n return false;\n\n const unsigned int* triNodes = m_nrt-&gt;getTriNodes(iTri);\n double triAvgIValue = (nodeIValues[triNodes[0]] + nodeIValues[triNodes[1]] + nodeIValues[triNodes[2]]) / 3.0;\n\n return (triAvgValue &gt; iValueThreshold);\n}\n</code></pre>\n\n<hr>\n\n<p>The <code>rc</code> variable here doesn't seem to have any reason to exist. We could just check the result of the function directly.</p>\n\n<pre><code> int rc;\n\n if((rc = pthread_attr_init(&amp;attr)))\n {\n throw PThreadException();\n }\n</code></pre>\n\n<hr>\n\n<p>Maybe split the initialization that needs to be done only once into a separate function from the initialization that is done every time and call these two functions only when appropriate. I'm guessing a lot of these checks are effectively checking the same thing:</p>\n\n<pre><code> if(triActive.empty())\n {\n triActive.resize(numTris, false);\n }\n if(hasBeenInZone.empty())\n {\n hasBeenInZone.resize(numTris, false);\n }\n</code></pre>\n\n<hr>\n\n<p>The actual triangle data appears to be <code>float</code>s, but the calculations use a lot of <code>double</code>s. Are the <code>double</code>s actually necessary?</p>\n\n<hr>\n\n<p>A decent math library would make stuff like this:</p>\n\n<pre><code>ray.dir[0] = (betaCoords[0] - alphaCoords[0]) / pathDist;\nray.dir[1] = (betaCoords[1] - alphaCoords[1]) / pathDist;\nray.dir[2] = (betaCoords[2] - alphaCoords[2]) / pathDist;\n</code></pre>\n\n<p>Look more like this:</p>\n\n<pre><code>ray.dir = (betaCoords - alphaCoords) / pathDist;\n</code></pre>\n\n<p>I wonder if it would be possible to do this with one of the libraries you're already using, instead of manually declaring arrays each time (e.g. <code>double alphaCoords[3];</code> -> something like <code>vec3&lt;double&gt; alphaCoords</code>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T19:00:56.907", "Id": "433532", "Score": "0", "body": "Globals are necessary due to this being a MEX file and the fact that I need to maintain certain values between invocations from MATLAB. Those don't get wiped from memory upon the MEX file completing, unlike anything local. As for the rest, I'll double check but I think there may be some methods to simplify the vector calculations a bit like you mentioned. I'm curious, why are const globals preferred to a define?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T19:25:48.380", "Id": "433536", "Score": "0", "body": "Clarified some stuff." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T17:20:05.277", "Id": "223636", "ParentId": "223587", "Score": "1" } }, { "body": "<p>Here are a number of suggestions and comments that may help you improve your code.</p>\n\n<h2>Update your compiler</h2>\n\n<p>If you are actually limited to C++03, you're foregoing well over a decade's worth of compiler and language advancement that would have made this code much simpler and probably faster. For instance all of the <code>pthread</code> business could probably be much more elegantly handled using <a href=\"https://en.cppreference.com/w/cpp/thread/async\" rel=\"nofollow noreferrer\"><code>std::async</code></a> and you'd be able to use references for efficiency and clarity. Without that, your path will be much harder and the code much less elegant and less robust than it should be.</p>\n\n<h2>Create and use a 3D point type</h2>\n\n<p>There are many instances in which 3 dimensional points are being used, but calculations for each is written out individually. Instead, I'd suggest that the code would be shorter, simpler and easier to read, understand and maintain if it used a <code>Point3D</code> class. </p>\n\n<h2>Think carefully about performance</h2>\n\n<p>The <code>checkPairValid</code> function is likely to be a performance bottleneck because of its use of floating point operations <code>pow</code> and <code>sqrt</code>. First consider these lines:</p>\n\n<pre><code>// Determine distance squared between alpha and beta\n// (x2-x1)^2 + (y2-y1)^2 +(z2-z1)^2\npathDist = sqrt(pow((betaCoords[0] - alphaCoords[0]), 2)\n + pow((betaCoords[1] - alphaCoords[1]), 2)\n + pow((betaCoords[2] - alphaCoords[2]), 2));\n</code></pre>\n\n<p>The comment and the code don't match. In this case, I'd make them match by omitting <code>sqrt</code> (which should actually be <code>std::sqrt</code>). I'd also suggest that multiplication is likely to be faster than invoking <code>pow</code> (which should be <code>std::pow</code>). I'd use a templated 3D point class (as mentioned above) and define a function like this:</p>\n\n<pre><code>T squaredDist(const Point3D&lt;T&gt;&amp; other) const {\n T dx = loc[0] - other.loc[0];\n T dy = loc[1] - other.loc[1];\n T dz = loc[2] - other.loc[2];\n return dx * dx + dy * dy + dz * dz;\n}\n</code></pre>\n\n<p>Then you can compare with a squared threshold instead of the existing <code>distThreshold</code> for speed.</p>\n\n<p>We also have these three lines:</p>\n\n<pre><code>ray.dir[0] = (betaCoords[0] - alphaCoords[0]) / pathDist;\nray.dir[1] = (betaCoords[1] - alphaCoords[1]) / pathDist;\nray.dir[2] = (betaCoords[2] - alphaCoords[2]) / pathDist;\n</code></pre>\n\n<p>If this is indeed intended to be a direction vector as the name suggests, it is probably not necessary to divide by the <code>pathDist</code> since it's the same direction either way. That would also save some calculation. In short, here's how I'd rewrite that function:</p>\n\n<pre><code>/**\n * @brief checkPairValid - Checks if a pair of points form a valid path\n * @param alpha - An alpha point\n * @param beta - A beta point\n * @param distThreshold - The square of the max distance apart the \n * point's centers can be \n * @param shoot - Function that returns false if there is a path\n * @return Whether the pair forms a valid path\n */\nbool checkPairValid(const Point3D&lt;double&gt; &amp;alpha,\n const Point3D&lt;double&gt; &amp;beta,\n const double squaredDistThreshold,\n bool (*shoot)(nanort::Ray&lt;double&gt;)\n )\n{\n double squaredPathDist = alpha.squaredDist(beta);\n if(squaredPathDist &lt; squaredDistThreshold)\n {\n // Set up a nanort::Ray's origin, direction, and max distance\n nanort::Ray&lt;double&gt; ray(alpha, beta-alpha, std::sqrt(squaredPathDist));\n\n // Call passed shoot function to check for a path\n return !shoot(ray);\n }\n // The distance is too far between alpha and beta\n return false;\n}\n</code></pre>\n\n<p>This is not only easier to read than the original but also no longer has any reliance on global variables.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T23:09:18.233", "Id": "433563", "Score": "0", "body": "As I said in another post, the globals are necessary because, unlike anything else, they don't get wiped when the MEX function exits. I need the information stored to persist between MEX calls. That's how to do it. I could write it out to a file or similar, but that's obviously far slower. Also, as I said in the post, C++03 is a hard limit. It is not flexible for this project, it's not a choice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T23:09:56.447", "Id": "433565", "Score": "0", "body": "Also: division by pathDist is done to produce a unit vector, which is required for the call that uses it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T23:10:21.577", "Id": "433566", "Score": "0", "body": "The points come from the MATLAB script, so they're also not something I have control over. I'll try to clarify that in the post somehow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T00:31:10.237", "Id": "433572", "Score": "0", "body": "Well, I suppose if nothing can be changed, it’s going to be difficult to offer any usable suggestions." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T19:52:01.893", "Id": "223643", "ParentId": "223587", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T21:40:02.807", "Id": "223587", "Score": "3", "Tags": [ "c++", "performance", "matlab", "c++03" ], "Title": "Finding paths between triangles efficiently in 3D geometry #2" }
223587
<p>I have started the Hackerrank interview preparation kit. The <a href="https://www.hackerrank.com/challenges/jumping-on-the-clouds/problem" rel="nofollow noreferrer">first problem</a> I have solved with Swift is as follows:</p> <blockquote> <p>Emma is playing a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. She can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus 1 or 2. She must avoid the thunderheads. Determine the minimum number of jumps it will take Emma to jump from her starting position to the last cloud.</p> <p>For each game, Emma will get an array of clouds numbered 0 if they are safe or 1 if they must be avoided.</p> </blockquote> <pre><code>func jumpingOnClouds(c: [Int]) -&gt; Int { var jump = 0 var location = 0 repeat { if (location + 2 &lt; c.count) &amp;&amp; (c[location + 2] == 0) { location += 2 } else { location += 1 } if location &gt;= c.count { break } jump += 1 } while location &lt; c.count return jump } </code></pre> <p>It's time complexity is <span class="math-container">\$O(n)\$</span>. Are there any ways I could reduce this? I am also interested in improving the code quality. Are there ways I can take better advantage of Swift to improve my code?</p>
[]
[ { "body": "<p>Your program is clearly written, and works correctly (to the best of my knowledge). I don't think that the time complexity is <span class=\"math-container\">\\$O(n)\\$</span> can be improved, because the array must be traversed in order to locate the dangerous thunderheads. Your algorithm already optimizes that by checking only every second element (if that is a safe spot), relying on the fact that a solution is guaranteed.</p>\n\n<p>The program can be improved a bit though. The <code>while location &lt; c.count</code> condition of the main loop will always be true because the loop is always “early left” at</p>\n\n<pre><code>if location &gt;= c.count {\n break\n}\n</code></pre>\n\n<p>As a consequence, the program computes one location beyond the array bounds which is not needed (and not counted). This can be simplified by using a while-loop instead:</p>\n\n<pre><code>while location &lt; c.count - 1 {\n if (location + 2 &lt; c.count) &amp;&amp;\n (c[location + 2] == 0) {\n location += 2\n } else {\n location += 1\n }\n jump += 1\n}\n</code></pre>\n\n<p>This is shorter and easier to understand because there is only one terminating condition for the loop instead of two.</p>\n\n<p>A possible improvement <em>might</em> be to run the loop until one of the last <em>two</em> positions it reached, because then the test against the array count is done only once per iteration and not twice:</p>\n\n<pre><code>while location &lt; c.count - 2 {\n if c[location + 2] == 0 {\n location += 2\n } else {\n location += 1\n }\n jump += 1\n}\nreturn location == c.count - 1 ? jump : jump + 1\n</code></pre>\n\n<p>A further optimization would be to use that if we do a size 1 jump because of a thunderhead, the following jump will always be of size 2:</p>\n\n<pre><code>while location &lt; c.count - 2 {\n if c[location + 2] == 0 {\n // Jump two positions:\n location += 2\n jump += 1\n } else {\n // Jump one position and then two positions:\n location += 3\n jump += 2\n }\n}\nreturn location == c.count - 1 ? jump : jump + 1\n</code></pre>\n\n<p>But the performance increase will probably be negligible since the arrays have at most 100 elements.</p>\n\n<p>Some minor points: The parentheses in</p>\n\n<pre><code>if (location + 2 &lt; c.count) &amp;&amp;\n (c[location + 2] == 0)\n</code></pre>\n\n<p>are not needed because the comparison operators have a higher precedence than the logical operators:</p>\n\n<pre><code>if location + 2 &lt; c.count &amp;&amp; c[location + 2] == 0\n</code></pre>\n\n<p>Finally, I would name the counter variable <code>jumps</code> or <code>jumpCount</code> to better describe its purpose.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T05:13:54.330", "Id": "223596", "ParentId": "223591", "Score": "2" } } ]
{ "AcceptedAnswerId": "223596", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-05T22:59:50.233", "Id": "223591", "Score": "4", "Tags": [ "programming-challenge", "interview-questions", "swift" ], "Title": "Jumping on the clouds" }
223591
<p>Going through <em>Head First C#</em>'s Chapter 8: Enums and Collections, I learned about <code>List&lt;T&gt;</code>, as well as <code>IComparable&lt;T&gt;</code> and <code>IComparer&lt;T&gt;</code>. One exercise near the end asked to make a program to draw cards at random, then sort them.</p> <p>I wanted to go the extra mile and make a fully usable, realistic card deck (their solution just picked 5 values at random from 2 enums, which could result in drawing the same card twice).</p> <p>Any and all advice is welcome, albeit please understand that I have yet to learn LINQ in a coming chapter, so if you suggest to use it for something please at least explain why/advantages over vanilla C#.</p> <p>I'm not including the <code>using</code> statement, they are the default ones that Visual Studio adds when creating a C# console project.</p> <h3>Kind</h3> <pre><code>enum Kind { Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, } </code></pre> <h3>Suit</h3> <pre><code>enum Suit { Clubs, Diamonds, Hearts, Spades, } </code></pre> <h3>Card</h3> <pre><code>class Card : IComparable&lt;Card&gt; { public Kind Kind; public Suit Suit; public Card(Kind kind, Suit suit) { Kind = kind; Suit = suit; } public int CompareTo(Card other) { if (Suit &gt; other.Suit) { return 1; } if (Suit &lt; other.Suit) { return -1; } return Kind &gt; other.Kind ? 1 : -1; } public override string ToString() { return $"{Kind} of {Suit}"; } } </code></pre> <h3>CardDeck</h3> <pre><code>class CardDeck { public List&lt;Card&gt; Cards; public CardDeck() { Cards = new List&lt;Card&gt;(); int numSuits = Enum.GetNames(typeof(Suit)).Length; int numKinds = Enum.GetNames(typeof(Kind)).Length; for (int suit = 0; suit &lt; numSuits; suit++) { for (int kind = 0; kind &lt; numKinds; kind++) { Cards.Add(new Card((Kind)kind, (Suit)suit)); } } } public int CountCardsInDeck =&gt; Cards.Count; public Card DrawTopCard() { Card drawnCard = Cards[0]; Cards.RemoveAt(0); return drawnCard; } public Card DrawBottomCard() { int lastCardIndex = CountCardsInDeck - 1; Card drawnCard = Cards[lastCardIndex]; Cards.RemoveAt(lastCardIndex); return drawnCard; } public Card DrawRandomCard() { Random random = new Random(); int randomCardIndex = random.Next(CountCardsInDeck); Card drawnCard = Cards[randomCardIndex]; Cards.RemoveAt(randomCardIndex); return drawnCard; } public void AddCardOnTop(Card card) { if (!Cards.Contains(card)) { Cards[0] = card; return; } throw new InvalidOperationException($"Deck already contains card {card}."); } public void AddCardOnBottom(Card card) { if (!Cards.Contains(card)) { Cards.Add(card); return; } throw new InvalidOperationException($"Deck already contains card {card}."); } public void AddCardAtRandom(Card card) { if (!Cards.Contains(card)) { Random random = new Random(); Cards[random.Next(CountCardsInDeck)] = card; return; } throw new InvalidOperationException($"Deck already contains card {card}."); } public void Shuffle() { // Fisher-Yates shuffle method Random random = new Random(); int n = CountCardsInDeck; while (n &gt; 1) { n--; int k = random.Next(n + 1); Card randomCard = Cards[k]; Cards[k] = Cards[n]; Cards[n] = randomCard; } } public void Sort() =&gt; Cards.Sort(); public void Sort(IComparer&lt;Card&gt; comparer) =&gt; Cards.Sort(comparer); public void WriteToConsole() { foreach (Card card in Cards) { Console.WriteLine(card); } } } </code></pre> <h3>CardOrderMethod</h3> <pre><code>enum CardOrderMethod { SuitThenKind, KindThenSuit, } </code></pre> <h3>CardSorter</h3> <pre><code>class CardSorter : IComparer&lt;Card&gt; { public CardOrderMethod SortBy = CardOrderMethod.SuitThenKind; public int Compare(Card x, Card y) { if (SortBy == CardOrderMethod.SuitThenKind) { if (x.Suit &gt; y.Suit) { return 1; } if (x.Suit &lt; y.Suit) { return -1; } return x.Kind &gt; y.Kind ? 1 : -1; } if (SortBy == CardOrderMethod.KindThenSuit) { if (x.Kind &gt; y.Kind) { return 1; } if (x.Kind &lt; y.Kind) { return -1; } return x.Suit &gt; y.Suit ? 1 : -1; } throw new NotImplementedException($"CardOrderMethod {SortBy} is not implemented."); } } </code></pre> <h3>Program</h3> <pre><code>class Program { static void Main(string[] args) { CardDeck cardDeck = new CardDeck(); cardDeck.Shuffle(); Console.WriteLine("---Shuffled deck---"); cardDeck.WriteToConsole(); CardSorter sorter = new CardSorter { SortBy = CardOrderMethod.SuitThenKind }; cardDeck.Sort(sorter); Console.WriteLine("---Sorted deck: SuitThenKind---"); cardDeck.WriteToConsole(); cardDeck.Shuffle(); sorter.SortBy = CardOrderMethod.KindThenSuit; cardDeck.Sort(sorter); Console.WriteLine("---Sorted deck: Kind Then Suit---"); cardDeck.WriteToConsole(); // Keep console open until a key is pressed Console.ReadKey(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T03:09:55.187", "Id": "433584", "Score": "0", "body": "Is there a reason `Ace` is ranked below `Two` in the enum? Most games rank the `Ace` as the highest card." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T09:36:43.833", "Id": "433614", "Score": "0", "body": "Your comparison method contains a bug because it fails if you compare a card against itself" } ]
[ { "body": "<h3><code>List&lt;T&gt;</code></h3>\n\n<p>You have just learned about <code>List&lt;T&gt;</code> and are eager to use it. Perfectly understandable, but think about what it is designed for and what alternatives are available for this use case. <a href=\"https://www.go4expert.com/articles/lists-queues-stacks-sets-c-sharp-t30028/#queue\" rel=\"noreferrer\">Here is an overview of common Collections in C#</a></p>\n\n<p>To be fair, there is no common collection available designed for a deck of cards. What you need, is functionality from:</p>\n\n<ul>\n<li><code>HashSet&lt;T&gt;</code> - unique items in the deck</li>\n<li><code>Queue&lt;T&gt;</code> - add card on one end, take card from the other end</li>\n<li><code>Stack&lt;T&gt;</code> - add card on one end, take card from that end</li>\n</ul>\n\n<p>You have opted to use <code>List&lt;T&gt;</code> and added the above functionality yourself. This is not a bad solution, but you should realise it is not optimized for a deck of unique cards.</p>\n\n<h3><code>Card</code></h3>\n\n<p>You can compare enum values the same way you are comparing instances of <code>Card</code>.</p>\n\n<blockquote>\n<pre><code>public int CompareTo(Card other)\n{ \n if (Suit &gt; other.Suit)\n {\n return 1;\n }\n if (Suit &lt; other.Suit)\n {\n return -1;\n }\n return Kind &gt; other.Kind ? 1 : -1;\n}\n</code></pre>\n</blockquote>\n\n<p>The above can be written as:</p>\n\n<pre><code>public int CompareTo(Card other)\n{ \n if (other == null) return -1;\n var index = Suit.CompareTo(other.Suit);\n if (index == 0) index = Kind .CompareTo(other.Kind);\n return index;\n}\n</code></pre>\n\n<p>Since <code>Card</code> is used by <code>CardDeck</code> and the latter uses a <code>List&lt;Card&gt;</code> with unique card items, you should do at least one of either and preferrably both:</p>\n\n<ul>\n<li>override <code>Equals()</code> and <code>GetHashCode()</code></li>\n<li>implement <code>IEquatable&lt;Card&gt;</code></li>\n</ul>\n\n<p>This is because <code>List&lt;T&gt;</code> uses <code>EqualityComparer&lt;T&gt;</code> to check for unique instances (<a href=\"https://referencesource.microsoft.com/#mscorlib/system/collections/generic/equalitycomparer.cs,ac282b3e1817bb9b\" rel=\"noreferrer\">Reference Source</a>).</p>\n\n<p><em>code snippet (only equality snippets)</em>:</p>\n\n<pre><code>class Card : IEquatable&lt;Card&gt;\n{\n public void Equals(Card card)\n {\n if (card == null) return false;\n return card.Suit == Suit &amp;&amp; card.Kind == kind;\n }\n\n public override void Equals(object obj)\n {\n if (!(obj is Card card)) return false;\n return card.Suit == Suit &amp;&amp; card.Kind == kind;\n }\n\n public override int GetHashCode()\n {\n // prefer picking two numbers that are co-prime\n var hash = 23;\n hash = hash * 31 + Suit.GetHashCode();\n hash = hash * 31 + Kind.GetHashCode();\n }\n}\n</code></pre>\n\n<h3><code>CardDeck</code></h3>\n\n<p>In your next lesson you will learn about LINQ. You will be able to write the card generator function as follows:</p>\n\n<pre><code>foreach (var card in (from suit in Enum.GetValues(typeof(Suit)).Cast&lt;Suit&gt;()\n from kind in Enum.GetValues(typeof(Kind)).Cast&lt;Kind&gt;()\n select new { suit, kind }))\n{\n Cards.Add(new Card(card.kind, card.suit));\n}\n</code></pre>\n\n<p>as compared to:</p>\n\n<blockquote>\n<pre><code>int numSuits = Enum.GetNames(typeof(Suit)).Length;\nint numKinds = Enum.GetNames(typeof(Kind)).Length;\n\nfor (int suit = 0; suit &lt; numSuits; suit++)\n{\n for (int kind = 0; kind &lt; numKinds; kind++)\n {\n Cards.Add(new Card((Kind)kind, (Suit)suit));\n }\n}\n</code></pre>\n</blockquote>\n\n<p>For shuffling and drawing random cards, consider declaring the <code>Random</code> as a private variable of the deck rather than inside the methods. This avoids <a href=\"https://stackoverflow.com/questions/1654887/random-next-returns-always-the-same-values\">the not so random Random behavior</a>.</p>\n\n<pre><code>private readonly Random random = new Random();\n</code></pre>\n\n<p>Consider inverting code like this:</p>\n\n<blockquote>\n<pre><code>if (!Cards.Contains(card))\n{\n Cards[0] = card;\n return;\n}\nthrow new InvalidOperationException($\"Deck already contains card {card}.\");\n</code></pre>\n</blockquote>\n\n<p>to this:</p>\n\n<pre><code> if (Cards.Contains(card))\n {\n throw new InvalidOperationException($\"Deck already contains card {card}.\");\n }\n Cards[0] = card;\n</code></pre>\n\n<p>Don't pollute your classes with specific utility methods. Write this as a static method or extension method in your test code.</p>\n\n<blockquote>\n<pre><code>public void WriteToConsole()\n{\n foreach (Card card in Cards)\n {\n Console.WriteLine(card);\n }\n}\n</code></pre>\n</blockquote>\n\n<h3><code>CardSorter</code></h3>\n\n<p>You should prefer <code>CompareTo</code> over comparasion operators.</p>\n\n<blockquote>\n<pre><code>if (x.Suit &gt; y.Suit)\n{\n return 1;\n}\nif (x.Suit &lt; y.Suit)\n{\n return -1;\n}\nreturn x.Kind &gt; y.Kind ? 1 : -1;\n</code></pre>\n</blockquote>\n\n<pre><code>var index = x.Suit.CompareTo(y.Suit);\nif (index == 0) index = x.Kind.CompareTo(y.Kind);\nreturn index;\n</code></pre>\n\n<p>Also include null comparisons.</p>\n\n<pre><code>if (x == null) return (y == null) ? 0 : 1;\nif (y == null) return -1;\n</code></pre>\n\n<h3>General guidelines</h3>\n\n<ul>\n<li>use <code>var</code> as much as you can, specially when the declared type can be inferred from reading the code. <code>var card = new Card();</code> reads better as <code>Card card = new Card();</code> or <code>Dictionary&lt;string, List&lt;int&gt;&gt; collection = new Dictionary&lt;string, List&lt;int&gt;&gt;();</code> vs <code>var collection = new Dictionary&lt;string, List&lt;int&gt;&gt;();</code></li>\n<li>check arguments against <code>null</code> in public methods</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T09:15:18.517", "Id": "433465", "Score": "0", "body": "Can you explain the reason to use var as much as possible?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T09:19:25.577", "Id": "433467", "Score": "0", "body": "@BlackBox edited an explanation" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T09:03:46.483", "Id": "223604", "ParentId": "223593", "Score": "6" } }, { "body": "<pre><code> enum Kind\n {\n ...\n Queen,\n King,\n Joker // ???\n }\n</code></pre>\n\n<p>Jokers is the joker. You're not considering jokers</p>\n\n<hr>\n\n<blockquote>\n<pre><code> class Card : IComparable&lt;Card&gt; \n {\n ...\n</code></pre>\n</blockquote>\n\n<p>I'm not convinced that there is a default comparison for cards? It could be misunderstood by consumers. On the other hand a deck of cards is always sorted by <code>Suit</code> and then <code>Kind</code>, but the comparison of cards is highly context dependent - dependent on the rules of the game. See further below.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>public int CompareTo(Card other)\n{ \n if (Suit &gt; other.Suit)\n {\n return 1;\n }\n if (Suit &lt; other.Suit)\n {\n return -1;\n }\n return Kind &gt; other.Kind ? 1 : -1;\n}\n</code></pre>\n</blockquote>\n\n<p>can be simplified to:</p>\n\n<pre><code>public int CompareTo(Card other)\n{\n if (other == null) return 1;\n if (Suit != other.Suit)\n return Suit.CompareTo(other.Suit);\n return Kind.CompareTo(other.Kind);\n}\n</code></pre>\n\n<hr>\n\n<p><code>CardDeck</code> is maybe a little verbose. IMO <code>Deck</code> is sufficient.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> Cards = new List&lt;Card&gt;();\n int numSuits = Enum.GetNames(typeof(Suit)).Length;\n int numKinds = Enum.GetNames(typeof(Kind)).Length;\n for (int suit = 0; suit &lt; numSuits; suit++)\n {\n for (int kind = 0; kind &lt; numKinds; kind++)\n {\n Cards.Add(new Card((Kind)kind, (Suit)suit));\n }\n }\n</code></pre>\n</blockquote>\n\n<p>There is a simpler way to do this:</p>\n\n<pre><code> Cards = new List&lt;Card&gt;();\n\n foreach (Suit suit in Enum.GetValues(typeof(Suit)))\n {\n foreach (Kind kind in Enum.GetValues(typeof(Kind)))\n {\n Cards.Add(new Card(kind, suit));\n }\n }\n</code></pre>\n\n<hr>\n\n<p><code>CountCardsInDeck</code> again: <code>Count</code> is sufficient. What should it else count if not cards in the deck?</p>\n\n<hr>\n\n<blockquote>\n<pre><code>public Card DrawTopCard()\n{\n Card drawnCard = Cards[0];\n Cards.RemoveAt(0);\n return drawnCard;\n}\n\npublic Card DrawBottomCard()\n{\n int lastCardIndex = CountCardsInDeck - 1;\n Card drawnCard = Cards[lastCardIndex];\n Cards.RemoveAt(lastCardIndex);\n return drawnCard;\n}\n\npublic Card DrawRandomCard()\n{\n Random random = new Random();\n int randomCardIndex = random.Next(CountCardsInDeck);\n Card drawnCard = Cards[randomCardIndex];\n Cards.RemoveAt(randomCardIndex);\n return drawnCard;\n}\n</code></pre>\n</blockquote>\n\n<p>This can be simplified:</p>\n\n<pre><code>public Card DrawCardAt(int index)\n{\n if (index &lt; 0 || index &gt;= Count)\n throw new ArgumentOutOfRangeException(nameof(index));\n\n Card card = Cards[index];\n Cards.RemoveAt(index);\n return card;\n}\n\npublic Card DrawTopCard()\n{\n return DrawCardAt(0);\n}\n\npublic Card DrawBottomCard()\n{\n return DrawCardAt(Count - 1);\n}\n\npublic Card DrawRandomCard()\n{\n Random random = new Random();\n int index = random.Next(Count);\n return DrawCardAt(index);\n}\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> public void AddCardOnTop(Card card)\n {\n if (!Cards.Contains(card))\n {\n Cards[0] = card;\n return;\n }\n throw new InvalidOperationException($\"Deck already contains card {card}.\");\n }\n</code></pre>\n</blockquote>\n\n<p>A cleaner way to make precautions: </p>\n\n<pre><code>public void AddCardOnTop(Card card)\n{ \n if (Cards.Contains(card))\n throw new InvalidOperationException($\"Deck already contains card {card}.\");\n\n //Cards[0] = card;\n Cards.Insert(0, card);\n}\n</code></pre>\n\n<p>You replace the existing first card with a new one. Is that what you want? If so the method should be called <code>SetTop()</code> or <code>ReplaceTop()</code>. My suggestion is that you want to insert? The same could be said about <code>AddCardOnBottom()</code> and <code>AddCardAtRandom()</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>public void WriteToConsole()\n{\n foreach (Card card in Cards)\n {\n Console.WriteLine(card);\n }\n}\n</code></pre>\n</blockquote>\n\n<p>Keep the UI out of your models. You could override <code>ToString()</code> and produce a line-string instead.</p>\n\n<hr>\n\n<p><code>class CardSorter</code> strictly speaking it is not a sorter but a comparer.</p>\n\n<hr>\n\n<p>As discussed above, I maybe think that your comparer is somewhat redundant, because the comparison of cards depends on the game rules. I'm not a huge fan of card games, but I can't image games or situations where a deck of cards should be sorted differently than just by <code>Suit</code> and then <code>Kind</code>. But if you insists, you should consider other sorttypes:</p>\n\n<pre><code> enum CardSortType\n {\n KindOnly, // HH: In some games only the kind matters\n SuitOnly, // HH: I can't image any games where this is used??\n SuitThenKind,\n KindThenSuit,\n }\n\n class CardSorter : IComparer&lt;Card&gt;\n {\n public CardSorter(CardSortType sortBy = CardSortType.SuitThenKind)\n {\n SortBy = sortBy;\n }\n\n public CardSortType SortBy { get; } // HH: Make it readonly\n\n public int Compare(Card x, Card y)\n {\n switch (SortBy)\n {\n case CardSortType.KindOnly:\n return x.Kind.CompareTo(y.Kind);\n case CardSortType.SuitOnly:\n return x.Suit.CompareTo(y.Suit);\n case CardSortType.SuitThenKind:\n if (x.Suit != y.Suit) return x.Suit.CompareTo(y.Suit);\n return x.Kind.CompareTo(y.Kind);\n case CardSortType.KindThenSuit:\n if (x.Kind != y.Kind) return x.Kind.CompareTo(y.Kind);\n return x.Suit.CompareTo(y.Suit);\n default:\n throw new NotImplementedException($\"CardOrderMethod {SortBy} is not implemented.\");\n }\n }\n }\n</code></pre>\n\n<p>In the above, I suggest a simpler comparison.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T11:55:42.267", "Id": "433473", "Score": "1", "body": "Excellent review. Is a joker a `Kind` though? Could you have the Joker of Clubs? Or the Joker of Diamonds? I would either put it as a `Suit` (and preferably set `Kind` to null when used) or keep it as a separate property from both Kind and Suit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T12:01:21.080", "Id": "433475", "Score": "0", "body": "@SimonForsberg: You're probably right. I rarely play cards so I'm not the one to consult. But introducing jokers will give you some extra work anyway. I think, I maybe would have an `abstract class Card` and then two derived: `class NormalCard : Card` and `class Joker : Card`, but I haven't thought that through..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T12:04:36.710", "Id": "433476", "Score": "0", "body": "Personally I feel that abstract classes are often very overused (but maybe that's just in Enterprise), it is a tricky issue to solve that can be solved in many different ways. Again, excellent review :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T15:57:29.097", "Id": "433499", "Score": "1", "body": "There're plenty of games with \"weird\" sorting rules. For example Canasta (https://en.wikipedia.org/wiki/Canasta) ignores suits alltogether pretty much and only cares for kinds. Russian Schnapsen (https://en.wikipedia.org/wiki/Russian_Schnapsen) has weird kind order (A 10 K Q W 9) and different order of suits (hearts diamonds clubs spades if im not mistaken). Rummy (https://en.wikipedia.org/wiki/Rummy) probably should sort suits, but prefers the same kind together. And so on." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T15:59:28.053", "Id": "433500", "Score": "0", "body": "Your Card comparision is slightly different (albeit probably more correct), than OP - his Card will never compare true with itself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T16:11:55.847", "Id": "433502", "Score": "0", "body": "@RadosławCybulski: But aren't you talking about ranking of cards - aka game rules rather than how they should be sorted? In that way you could implement an IComparer<Card>` per game - representing the rules - that'll make sense. I didn't think that way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T16:27:21.580", "Id": "433506", "Score": "2", "body": "Yes, you're right. It depends, what is sorting used for. Is it for drawing hand? Sorting cards by their \"strength\"?. I just mentioned, that in card games there's plenty of \"sensible\" sorting, depending on the game itself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T03:08:41.590", "Id": "433583", "Score": "0", "body": "Joker is illegal for many games. No need to support it unless the games using this code do." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T13:48:30.007", "Id": "433643", "Score": "0", "body": "@SimonForsberg Uniformity is good. So what if a Joker's Suite is completely artificial?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T13:48:50.080", "Id": "433644", "Score": "0", "body": "@Henrik: Are you so sure silently ignoring null cards is a good idea, instead of allowing the exception which is easier to debug?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T16:35:45.867", "Id": "433658", "Score": "0", "body": "It's a bad practice to create a new random every time you need one. See my recent series \"Fixing Random\" on my blog for some thoughts on how to solve this problem." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T07:52:59.320", "Id": "433712", "Score": "0", "body": "@jpmc26 Hey! I've never been banned from any games, I'll have you know that :)" } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T09:05:01.703", "Id": "223605", "ParentId": "223593", "Score": "8" } }, { "body": "<h2>Encapsulation and Mutability</h2>\n\n<p>Your <code>Card</code> class is a perfect candidate for being immutable: make <code>Kind</code> and <code>Suit</code> readonly fields or getter-only properties (prefer the later in most cases):</p>\n\n<pre><code>public Kind Kind { get; }\npublic Suit Suit { get; }\n</code></pre>\n\n<p>You should also hide away the <code>Deck</code> list in <code>CardDeck</code>: making it readonly and <code>private</code> (or <code>protected</code>, if you are happy to commit to (and document) the internal representation) would probably be most sensible. Prevent the user shooting themselves in the foot by messing with state they shouldn't be able to access.</p>\n\n<h2><code>Card..ctor(Kind, Suit)</code></h2>\n\n<p><code>Enums</code> in .NET are very simple, and you have no gaurentee that a <code>Kind</code> is actually one of those you have declared. I would consider adding checks here to ensure that an invalid <code>Kind</code> or <code>Suit</code> is not used: catch the mistake early, because it will go wrong somewhere down the line, and the sooner you throw an exception at the consumer, the easier it will be for them to work out where they went wrong.</p>\n\n<h2>Comparers</h2>\n\n<p>Dfhwze's Answer indirectly addresses this, but your <code>Card.CompareTo(Card)</code> can never return <code>0</code>: this is very bad. It should check if the cards are equivalent, and return <code>0</code> in that instance and that instance only.</p>\n\n<p>As alluded by Henrik Hansen, I would rename <code>CardSorter</code> to <code>CardComparer</code>: it's what everyone will assume, and I would certainly expect a <code>CardSorter</code> to provide a 'Sort' method. Again, the comparisons here don't allow for the same card appearing twice: your code <code>CardDeck</code> class may assume they are never equal, but other people may try to use this class for other purposes. These sorts of things need to be documented.</p>\n\n<h2>Misc</h2>\n\n<ul>\n<li><p>Why should adding an already present card disallowed? Some cards games involve multiple complete 'decks' in a single 'deck'.</p></li>\n<li><p>This all <em>needs</em> documention. As a consumer, I need to know that <code>AddCardOnBottom</code> won't accept an already present card.</p></li>\n<li><p>As discussed by Henrik, <code>CardDeck.Sort</code> is a bit odd: I would remove it, and force the user to specify the type of sort they want (by using the <code>CardSorter</code> class).</p></li>\n<li><p>I would rename <code>CardSorter</code> to <code>CardComparer</code>: it's what everyone will assume, and I would certainly expect a <code>CardSorter</code> to provide a 'Sort' method. Again, the ccomparisons here don't allow for the same card appearing twice: your code may not allow this, but other people may try to use this class for other purposes.</p></li>\n<li><p>To reiterative dfhwze 's point, you should <em>not</em> be creating a new <code>Random</code> instance in <code>Shuffle</code>: either encapsulate one in the class which you take as a parameter to the constructor, or allow the <code>Shuffle</code> and other 'Random' methods to take one as a parameter.</p></li>\n<li><p>You might consider making the type of your <code>enum</code>s explicit (e.g. both fit in a <code>byte</code>), and you could make your <code>Card</code> class an immutable struct with the same semantics, only it would take up less space and reduce the GC overhead.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T12:13:52.750", "Id": "433477", "Score": "0", "body": "Good catch about the immutability. You could even make the `Deck` \"immutable\", so it maintains a set of unused and used cards, which will prevent cheating :-)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T11:45:46.630", "Id": "223616", "ParentId": "223593", "Score": "6" } }, { "body": "<p>Just a few things not already mentioned by other answers:</p>\n\n<p>Are you sure that you will need <code>DrawRandomCard()</code> ? How many card games have you played where you just draw from a random position in the deck? The only times I can think of this is useful is when you do a magic trick, which doesn't really work the same in code as in real life :) Normally in card games, you shuffle the deck and then draw from top or bottom.</p>\n\n<p>Different card games might want to sort the deck in different ways, as others have mentioned already, but there's more options as well. Does Aces count as high or low? (Or both?) Should the sort order of the suits be [Clubs, Diamonds, Hearts, Spades], or [Clubs, Diamonds, Spades, Hearts], or [Diamonds, Hearts, Spades, Clubs] ? This can be dependent on the type of game, and maybe also a player's preferences. Adding more flexible options for Ace low/high and Suit order to your comparer would be good.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T12:01:18.443", "Id": "223617", "ParentId": "223593", "Score": "7" } }, { "body": "<p>First off, this is quite good for beginner code. You'll do well if you keep the good habits you've started following.</p>\n\n<p>A few critiques:</p>\n\n<pre><code>class Card : IComparable&lt;Card&gt;\n</code></pre>\n\n<p>Do you intend this class to be subclassed? If not, seal it. </p>\n\n<p>Are cards comparable by reference? That is, suppose we have two <em>different</em> instances of the queen of spades. Is it possible for the user of the library to tell them apart, or not? If no, then this should be a struct, not a class; force the user to compare by value.</p>\n\n<pre><code>public Kind Kind;\npublic Suit Suit;\n</code></pre>\n\n<p>NEVER DO THIS. Never make a public field. First, because it is a bad practice, and second, because now anyone can have a card in hand and <em>change it</em>. Cards are immutable! This should be</p>\n\n<pre><code>public Kind Kind { get; private set; }\n</code></pre>\n\n<p>And so on.</p>\n\n<pre><code>public int CompareTo(Card other)\n</code></pre>\n\n<p><strong>This code is very wrong.</strong> <code>x.CompareTo(x)</code> must always return zero, <em>always</em>. You never tested that case, otherwise you would have found the bug, so write that test.</p>\n\n<p>If you're going to implement <code>CompareTo</code> it would be a good practice to also implement <code>Equals</code>, <code>operator ==</code>, <code>operator !=</code>, <code>GetHashCode</code>, <code>operator &gt;</code>, <code>operator &lt;</code>, <code>operator &lt;=</code> and <code>operator &gt;=</code>. It is weird that you can compare two cards for rank with <code>CompareTo</code> but not with <code>&lt;</code> or <code>==</code>.</p>\n\n<pre><code>class CardDeck\n</code></pre>\n\n<p>Again, seal it.</p>\n\n<pre><code>public List&lt;Card&gt; Cards;\n</code></pre>\n\n<p>Again, never make a public field. This should be private; it's an implementation detail of the class.</p>\n\n<pre><code>public int CountCardsInDeck =&gt; Cards.Count;\n</code></pre>\n\n<p>Needlessly verbose; just <code>public int Count =&gt; Cards.Count</code> is fine.</p>\n\n<pre><code>public Card DrawTopCard()\n</code></pre>\n\n<p>Throw a better exception if there is no top card.</p>\n\n<pre><code>Random random = new Random();\n</code></pre>\n\n<p>Newer versions of .NET have fixed this, but in older versions this was a bad practice, creating a Random every time you needed it. Instead, make it a field.</p>\n\n<pre><code>public void WriteToConsole()\n</code></pre>\n\n<p>This is a weird way to write this functionality. Normally you'd override <code>ToString</code> and then do <code>Console.WriteLine(deck);</code></p>\n\n<pre><code>class CardSorter : IComparer&lt;Card&gt;\n{\n public CardOrderMethod SortBy = CardOrderMethod.SuitThenKind;\n</code></pre>\n\n<p>Again, seal your classes, and again, no public fields.</p>\n\n<p>But this design is wrong. Don't make one class that can do two things. <strong>Make two classes if you have two things to do</strong>. Make a <code>SuitThenKindSorter</code> and a <code>KindThenSuitSorter</code> class, not one class that has an <code>if</code> in the middle.</p>\n\n<p>And again, the comparison logic is wrong; you are <em>required</em> to have a comparison where things that are equal are equal. You must never assume that the things being compared are unequal. The contract of the comparison is that it can take <em>any two objects of the type</em> and compare them, not any two <em>different</em> objects.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T06:02:16.870", "Id": "433701", "Score": "0", "body": "_seal it_ - I read your article about it here: [Why Are So Many Of The Framework Classes Sealed?](https://blogs.msdn.microsoft.com/ericlippert/2004/01/22/why-are-so-many-of-the-framework-classes-sealed/) and I find that the advantages of `sealed` classes are overrated and thier advantages highly questionable and you have to _break_ them with reflection to get the job done because someone thought they knew better than anyone else how a particular class _should_ and would be used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T14:15:38.847", "Id": "433787", "Score": "4", "body": "@t3chb0t: Do you feel the same way about non-virtual methods? Every non-virtual method is the developer \"thinking they know better about how a method should be used\". What about private methods? For that matter, why have methods at all? Just make all methods into fields of delegate type so that any developer can change the behavior of any method *without* overloading. Why have private members? Private members are developers foolishly believing they know how their classes will be used, right? Where does your argument stop, and why?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T14:31:01.123", "Id": "433794", "Score": "1", "body": "non-sealed classes are more useful because they allow you to create nice _aliases_ for built-in types like for a dictionary or a list. I'm very happy that I can have a oneliner class like `class UserNameDictionary : Dictionary<int, string> {}` that I can easily reuse everywhere without having to write `using`s which a `StringBuilder` disallows so I cannot create a `UserNameBuilder : StringBuilder {}`. non-virtual method can be _forcibly_ overriden with `new` which I think you have added because of the lack of _virtual_ by default like java does that ;-) and there is no `unseal` _spell_." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T21:27:13.953", "Id": "434019", "Score": "4", "body": "@t3chb0t The idea of `class UserNameDictionary : Dictionary<int, string> {}` goes against the concept of \"prefer composition over inheritance\". I bet that when you make such a class, you won't be using *all* of the inherited methods. It's also a lot trickier to change the implementation of it later if you extend from another class." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T21:32:11.920", "Id": "434021", "Score": "4", "body": "@SimonForsberg: I completely agree, but I would make an even more general argument. The position taken here is \"unseal your classes because C# has a crappy mechanism for aliases\". But this is basically the same position as \"use the same password on every site because humans have crappy memory for multiple passwords\". If \"crappy mechanism for aliases\" is the problem then *advocate for fixing that problem*. Don't encourage everyone else to use bad practices to work around it." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T16:56:13.773", "Id": "223685", "ParentId": "223593", "Score": "6" } } ]
{ "AcceptedAnswerId": "223605", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T01:17:22.003", "Id": "223593", "Score": "12", "Tags": [ "c#", "beginner", "sorting", "playing-cards", "shuffle" ], "Title": "Deck of cards with shuffle and sort functionality" }
223593
<p>When I saw this amazing data structure I couldn't stop myself from trying it! I first sought resources such as <a href="https://www.cise.ufl.edu/~sahni/dsaaj/enrich/c13/double.htm" rel="nofollow noreferrer">this</a> and an article about it <a href="https://academic.oup.com/comjnl/article/36/3/209/311525" rel="nofollow noreferrer">here</a>. It basically works as a Max-Heap and a Min-Heap at the same time. I was heavily based on these amazing Java implementations <a href="http://www.keithschwarz.com/interesting/code/interval-heap/IntervalHeap.java.html" rel="nofollow noreferrer">here</a> and <a href="https://github.com/MichalGoly/CS21120-DoubleEndedPriorityQueue/blob/master/src/cs21120/depq/Mwg2DEPQ.java" rel="nofollow noreferrer">here</a>.</p> <p>This implementation is a macro that generates code for whichever data type you wish to work with and it is part of the <a href="https://github.com/LeoVen/C-Macro-Collections" rel="nofollow noreferrer">C Macro Collections</a> library currently hosted on GitHub and further to be improved when needed.</p> <p>The main macro is <code>INTERVALHEAP_GENERATE</code> with the following parameters:</p> <ul> <li><strong>PFX</strong> - Functions prefix</li> <li><strong>SNAME</strong> - The struct name</li> <li><strong>FMOD</strong> - Function modifier (currently only <code>static</code> or empty)</li> <li><strong>V</strong> - Data type you wish to work with</li> </ul> <p>All you need to get started is the header <code>intervalheap.h</code>. Now since a question is limited to 65536 characters I had to strip down a lot of code and lines so that it could fit in this question since the macro takes a lot of characters. The code might seem a bit squished together but you can find the original code (and maybe in the future, updated) <a href="https://github.com/LeoVen/C-Macro-Collections/blob/master/src/ext/intervalheap.h" rel="nofollow noreferrer">here</a>.</p> <p><strong>intervalheap.h</strong></p> <pre class="lang-c prettyprint-override"><code>#ifndef CMC_INTERVALHEAP_H #define CMC_INTERVALHEAP_H #include &lt;stdlib.h&gt; #include &lt;stdbool.h&gt; #include &lt;string.h&gt; #define INTERVALHEAP_GENERATE(PFX, SNAME, FMOD, V) \ INTERVALHEAP_GENERATE_HEADER(PFX, SNAME, FMOD, V) \ INTERVALHEAP_GENERATE_SOURCE(PFX, SNAME, FMOD, V) /* HEADER ********************************************************************/ #define INTERVALHEAP_GENERATE_HEADER(PFX, SNAME, FMOD, V) \ \ /* Heap Structure */ \ typedef struct SNAME##_s \ { \ /* Dynamic array of nodes */ \ struct SNAME##_node_s *buffer; \ /* Current array capacity (how many nodes can be stored) */ \ size_t capacity; \ /* Current amount of nodes in the dynamic array */ \ size_t size; \ /* Current amount of elements in the heap */ \ size_t count; \ /* Element comparison function */ \ int (*cmp)(V, V); \ /* Function that returns an iterator to the start of the heap */ \ struct SNAME##_iter_s (*it_start)(struct SNAME##_s *); \ /* Function that returns an iterator to the end of the heap */ \ struct SNAME##_iter_s (*it_end)(struct SNAME##_s *); \ } SNAME, *SNAME##_ptr; \ \ /* Heap Node */ \ typedef struct SNAME##_node_s \ { \ /* 0 - Value belonging to the MinHeap */ \ /* 1 - Value belonging to the MaxHeap */ \ V data[2]; \ } SNAME##_node, *SNAME##_node_ptr; \ \ /* Heap Iterator */ \ typedef struct SNAME##_iter_s \ { \ /* Target heap */ \ struct SNAME##_s *target; \ /* Cursor's position (index) */ \ size_t cursor; \ /* If the iterator has reached the start of the iteration */ \ bool start; \ /* If the iterator has reached the end of the iteration */ \ bool end; \ } SNAME##_iter, *SNAME##_iter_ptr; \ \ FMOD SNAME *PFX##_new(size_t capacity, int (*compare)(V, V)); \ FMOD void PFX##_clear(SNAME *_heap_); \ FMOD void PFX##_free(SNAME *_heap_); \ FMOD bool PFX##_insert(SNAME *_heap_, V element); \ FMOD bool PFX##_remove_max(SNAME *_heap_, V *result); \ FMOD bool PFX##_remove_min(SNAME *_heap_, V *result); \ FMOD bool PFX##_insert_if(SNAME *_heap_, V element, bool condition); \ FMOD bool PFX##_remove_max_if(SNAME *_heap_, V *result, bool condition); \ FMOD bool PFX##_remove_min_if(SNAME *_heap_, V *result, bool condition); \ FMOD bool PFX##_update_max(SNAME *_heap_, V element); \ FMOD bool PFX##_update_min(SNAME *_heap_, V element); \ FMOD bool PFX##_max(SNAME *_heap_, V *value); \ FMOD bool PFX##_min(SNAME *_heap_, V *value); \ FMOD bool PFX##_contains(SNAME *_heap_, V element); \ FMOD bool PFX##_empty(SNAME *_heap_); \ FMOD bool PFX##_full(SNAME *_heap_); \ FMOD size_t PFX##_count(SNAME *_heap_); \ FMOD size_t PFX##_capacity(SNAME *_heap_); \ \ FMOD SNAME##_iter *PFX##_iter_new(SNAME *target); \ FMOD void PFX##_iter_free(SNAME##_iter *iter); \ FMOD void PFX##_iter_init(SNAME##_iter *iter, SNAME *target); \ FMOD bool PFX##_iter_start(SNAME##_iter *iter); \ FMOD bool PFX##_iter_end(SNAME##_iter *iter); \ FMOD void PFX##_iter_to_start(SNAME##_iter *iter); \ FMOD void PFX##_iter_to_end(SNAME##_iter *iter); \ FMOD bool PFX##_iter_next(SNAME##_iter *iter); \ FMOD bool PFX##_iter_prev(SNAME##_iter *iter); \ FMOD V PFX##_iter_value(SNAME##_iter *iter); \ FMOD size_t PFX##_iter_index(SNAME##_iter *iter); \ \ /* Default Value */ \ static inline V PFX##_impl_default_value(void) \ { \ V _empty_value_; \ \ memset(&amp;_empty_value_, 0, sizeof(V)); \ \ return _empty_value_; \ } #define INTERVALHEAP_GENERATE_SOURCE(PFX, SNAME, FMOD, V) \ \ /* Implementation Detail Functions */ \ static bool PFX##_impl_grow(SNAME *_heap_); \ static void PFX##_impl_float_up_max(SNAME *_heap_); \ static void PFX##_impl_float_up_min(SNAME *_heap_); \ static void PFX##_impl_float_down_max(SNAME *_heap_); \ static void PFX##_impl_float_down_min(SNAME *_heap_); \ static SNAME##_iter PFX##_impl_it_start(SNAME *_heap_); \ static SNAME##_iter PFX##_impl_it_end(SNAME *_heap_); \ \ FMOD SNAME *PFX##_new(size_t capacity, int (*compare)(V, V)) \ { \ SNAME *_heap_ = malloc(sizeof(SNAME)); \ if (!_heap_) \ return NULL; \ \ /* Since each node can store two elements, divide the actual capacity by 2 */ \ /* Round the capacity of nodes up */ \ capacity = capacity % 2 == 0 ? capacity / 2 : (capacity + 1) / 2; \ _heap_-&gt;buffer = malloc(sizeof(SNAME##_node) * capacity); \ \ if (!_heap_-&gt;buffer) \ { \ free(_heap_); \ return NULL; \ } \ memset(_heap_-&gt;buffer, 0, sizeof(SNAME##_node) * capacity); \ _heap_-&gt;capacity = capacity; \ _heap_-&gt;size = 0; \ _heap_-&gt;count = 0; \ _heap_-&gt;cmp = compare; \ _heap_-&gt;it_start = PFX##_impl_it_start; \ _heap_-&gt;it_end = PFX##_impl_it_end; \ return _heap_; \ } \ \ FMOD void PFX##_clear(SNAME *_heap_) \ { \ memset(_heap_-&gt;buffer, 0, sizeof(V) * _heap_-&gt;capacity); \ _heap_-&gt;size = 0; \ _heap_-&gt;count = 0; \ } \ \ FMOD void PFX##_free(SNAME *_heap_) \ { \ free(_heap_-&gt;buffer); \ free(_heap_); \ } \ \ FMOD bool PFX##_insert(SNAME *_heap_, V element) \ { \ if (PFX##_full(_heap_)) \ { \ if (!PFX##_impl_grow(_heap_)) \ return false; \ } \ \ if (PFX##_count(_heap_) % 2 == 0) \ { \ /* Occupying a new node */ \ _heap_-&gt;buffer[_heap_-&gt;size].data[0] = element; \ _heap_-&gt;buffer[_heap_-&gt;size].data[1] = PFX##_impl_default_value(); \ \ _heap_-&gt;size++; \ } \ else \ { \ SNAME##_node *curr_node = &amp;(_heap_-&gt;buffer[_heap_-&gt;size - 1]); \ \ if (_heap_-&gt;cmp(curr_node-&gt;data[0], element) &gt; 0) \ { \ curr_node-&gt;data[1] = curr_node-&gt;data[0]; \ curr_node-&gt;data[0] = element; \ } \ else \ { \ curr_node-&gt;data[1] = element; \ } \ } \ \ _heap_-&gt;count++; \ \ if (PFX##_count(_heap_) &lt;= 2) \ return true; \ \ SNAME##_node *parent = &amp;(_heap_-&gt;buffer[(_heap_-&gt;size - 1) / 2]); \ \ if (_heap_-&gt;cmp(parent-&gt;data[0], element) &gt; 0) \ PFX##_impl_float_up_min(_heap_); \ else if (_heap_-&gt;cmp(parent-&gt;data[1], element) &lt; 0) \ PFX##_impl_float_up_max(_heap_); \ \ return true; \ } \ \ FMOD bool PFX##_remove_max(SNAME *_heap_, V *result) \ { \ if (PFX##_empty(_heap_)) \ return false; \ \ if (PFX##_count(_heap_) == 1) \ { \ *result = _heap_-&gt;buffer[0].data[0]; \ _heap_-&gt;buffer[0].data[0] = PFX##_impl_default_value(); \ _heap_-&gt;count--; \ return true; \ } \ else \ *result = _heap_-&gt;buffer[0].data[1]; \ \ SNAME##_node *last_node = &amp;(_heap_-&gt;buffer[_heap_-&gt;size - 1]); \ \ if (PFX##_count(_heap_) % 2 == 1) \ { \ _heap_-&gt;buffer[0].data[1] = last_node-&gt;data[0]; \ last_node-&gt;data[0] = PFX##_impl_default_value(); \ _heap_-&gt;size--; \ } \ else \ { \ _heap_-&gt;buffer[0].data[1] = last_node-&gt;data[1]; \ \ last_node-&gt;data[1] = PFX##_impl_default_value(); \ } \ \ _heap_-&gt;count--; \ \ PFX##_impl_float_down_max(_heap_); \ \ return true; \ } \ \ FMOD bool PFX##_remove_min(SNAME *_heap_, V *result) \ { \ if (PFX##_empty(_heap_)) \ return false; \ \ *result = _heap_-&gt;buffer[0].data[0]; \ \ if (PFX##_count(_heap_) == 1) \ { \ _heap_-&gt;buffer[0].data[0] = PFX##_impl_default_value(); \ \ _heap_-&gt;count--; \ \ return true; \ } \ \ SNAME##_node *last_node = &amp;(_heap_-&gt;buffer[_heap_-&gt;size - 1]); \ \ _heap_-&gt;buffer[0].data[0] = last_node-&gt;data[0]; \ \ if (PFX##_count(_heap_) % 2 == 1) \ { \ last_node-&gt;data[0] = PFX##_impl_default_value(); \ \ _heap_-&gt;size--; \ } \ else \ { \ last_node-&gt;data[0] = last_node-&gt;data[1]; \ last_node-&gt;data[1] = PFX##_impl_default_value(); \ } \ \ _heap_-&gt;count--; \ \ PFX##_impl_float_down_min(_heap_); \ \ return true; \ } \ \ FMOD bool PFX##_insert_if(SNAME *_heap_, V element, bool condition) \ { \ if (condition) \ return PFX##_insert(_heap_, element); \ \ return false; \ } \ \ FMOD bool PFX##_remove_max_if(SNAME *_heap_, V *result, bool condition) \ { \ if (condition) \ return PFX##_remove_max(_heap_, result); \ \ return false; \ } \ \ FMOD bool PFX##_remove_min_if(SNAME *_heap_, V *result, bool condition) \ { \ if (condition) \ return PFX##_remove_min(_heap_, result); \ \ return false; \ } \ \ FMOD bool PFX##_update_max(SNAME *_heap_, V element) \ { \ if (PFX##_empty(_heap_)) \ return false; \ \ if (PFX##_count(_heap_) == 1) \ { \ _heap_-&gt;buffer[0].data[0] = element; \ } \ else if (_heap_-&gt;cmp(element, _heap_-&gt;buffer[0].data[0]) &lt; 0) \ { \ _heap_-&gt;buffer[0].data[1] = _heap_-&gt;buffer[0].data[0]; \ _heap_-&gt;buffer[0].data[0] = element; \ \ PFX##_impl_float_down_max(_heap_); \ } \ else \ { \ _heap_-&gt;buffer[0].data[1] = element; \ \ PFX##_impl_float_down_max(_heap_); \ } \ \ return true; \ } \ \ FMOD bool PFX##_update_min(SNAME *_heap_, V element) \ { \ if (PFX##_empty(_heap_)) \ return false; \ \ if (PFX##_count(_heap_) == 1) \ { \ _heap_-&gt;buffer[0].data[0] = element; \ } \ else if (_heap_-&gt;cmp(element, _heap_-&gt;buffer[0].data[1]) &gt; 0) \ { \ _heap_-&gt;buffer[0].data[0] = _heap_-&gt;buffer[0].data[1]; \ _heap_-&gt;buffer[0].data[1] = element; \ \ PFX##_impl_float_down_min(_heap_); \ } \ else \ { \ _heap_-&gt;buffer[0].data[0] = element; \ \ PFX##_impl_float_down_min(_heap_); \ } \ \ return true; \ } \ \ FMOD bool PFX##_max(SNAME *_heap_, V *value) \ { \ if (PFX##_empty(_heap_)) \ return false; \ \ if (PFX##_count(_heap_) == 1) \ *value = _heap_-&gt;buffer[0].data[0]; \ else \ *value = _heap_-&gt;buffer[0].data[1]; \ \ return true; \ } \ \ FMOD bool PFX##_min(SNAME *_heap_, V *value) \ { \ if (PFX##_empty(_heap_)) \ return false; \ \ *value = _heap_-&gt;buffer[0].data[0]; \ \ return true; \ } \ \ FMOD bool PFX##_contains(SNAME *_heap_, V element) \ { \ for (size_t i = 0; i &lt; _heap_-&gt;count; i++) \ { \ if (_heap_-&gt;cmp(_heap_-&gt;buffer[i / 2].data[i % 2], element) == 0) \ return true; \ } \ \ return false; \ } \ \ FMOD bool PFX##_empty(SNAME *_heap_) \ { \ return _heap_-&gt;count == 0; \ } \ \ FMOD bool PFX##_full(SNAME *_heap_) \ { \ /* The heap is full if all nodes are completely filled */ \ return _heap_-&gt;size &gt;= _heap_-&gt;capacity &amp;&amp; _heap_-&gt;count % 2 == 0; \ } \ \ FMOD size_t PFX##_count(SNAME *_heap_) \ { \ return _heap_-&gt;count; \ } \ \ FMOD size_t PFX##_capacity(SNAME *_heap_) \ { \ /* Multiply by 2 since each node can store two elements */ \ return _heap_-&gt;capacity * 2; \ } \ \ FMOD SNAME##_iter *PFX##_iter_new(SNAME *target) \ { \ SNAME##_iter *iter = malloc(sizeof(SNAME##_iter)); \ \ if (!iter) \ return NULL; \ \ PFX##_iter_init(iter, target); \ \ return iter; \ } \ \ FMOD void PFX##_iter_free(SNAME##_iter *iter) \ { \ free(iter); \ } \ \ FMOD void PFX##_iter_init(SNAME##_iter *iter, SNAME *target) \ { \ iter-&gt;target = target; \ iter-&gt;cursor = 0; \ iter-&gt;start = true; \ iter-&gt;end = PFX##_empty(target); \ } \ \ FMOD bool PFX##_iter_start(SNAME##_iter *iter) \ { \ return PFX##_empty(iter-&gt;target) || iter-&gt;start; \ } \ \ FMOD bool PFX##_iter_end(SNAME##_iter *iter) \ { \ return PFX##_empty(iter-&gt;target) || iter-&gt;end; \ } \ \ FMOD void PFX##_iter_to_start(SNAME##_iter *iter) \ { \ iter-&gt;cursor = 0; \ iter-&gt;start = true; \ iter-&gt;end = PFX##_empty(iter-&gt;target); \ } \ \ FMOD void PFX##_iter_to_end(SNAME##_iter *iter) \ { \ iter-&gt;cursor = iter-&gt;target-&gt;count - 1; \ iter-&gt;start = PFX##_empty(iter-&gt;target); \ iter-&gt;end = true; \ } \ \ FMOD bool PFX##_iter_next(SNAME##_iter *iter) \ { \ if (iter-&gt;end) \ return false; \ \ iter-&gt;start = false; \ \ if (iter-&gt;cursor == iter-&gt;target-&gt;count - 1) \ iter-&gt;end = true; \ else \ iter-&gt;cursor++; \ \ return true; \ } \ \ FMOD bool PFX##_iter_prev(SNAME##_iter *iter) \ { \ if (iter-&gt;start) \ return false; \ \ iter-&gt;end = false; \ \ if (iter-&gt;cursor == 0) \ iter-&gt;start = true; \ else \ iter-&gt;cursor--; \ \ return true; \ } \ \ FMOD V PFX##_iter_value(SNAME##_iter *iter) \ { \ if (PFX##_empty(iter-&gt;target)) \ return PFX##_impl_default_value(); \ \ return iter-&gt;target-&gt;buffer[iter-&gt;cursor / 2].data[iter-&gt;cursor % 2]; \ } \ \ FMOD size_t PFX##_iter_index(SNAME##_iter *iter) \ { \ return iter-&gt;cursor; \ } \ \ static bool PFX##_impl_grow(SNAME *_heap_) \ { \ size_t new_cap = _heap_-&gt;capacity * 2; \ \ SNAME##_node *new_buffer = realloc(_heap_-&gt;buffer, sizeof(SNAME##_node) * new_cap); \ \ if (!new_buffer) \ return false; \ \ memset(new_buffer + _heap_-&gt;capacity, 0, sizeof(SNAME##_node) * _heap_-&gt;capacity); \ \ _heap_-&gt;buffer = new_buffer; \ _heap_-&gt;capacity = new_cap; \ \ return true; \ } \ \ static void PFX##_impl_float_up_max(SNAME *_heap_) \ { \ size_t index = _heap_-&gt;size - 1; \ \ SNAME##_node *curr_node = &amp;(_heap_-&gt;buffer[index]); \ \ while (index &gt; 0) \ { \ /* Parent index */ \ size_t P_index = (index - 1) / 2; \ \ SNAME##_node *parent = &amp;(_heap_-&gt;buffer[P_index]); \ \ if (index == _heap_-&gt;size - 1 &amp;&amp; PFX##_count(_heap_) % 2 != 0) \ { \ if (_heap_-&gt;cmp(curr_node-&gt;data[0], parent-&gt;data[1]) &lt; 0) \ break; \ \ V tmp = curr_node-&gt;data[0]; \ curr_node-&gt;data[0] = parent-&gt;data[1]; \ parent-&gt;data[1] = tmp; \ } \ else \ { \ if (_heap_-&gt;cmp(curr_node-&gt;data[1], parent-&gt;data[1]) &lt; 0) \ break; \ \ V tmp = curr_node-&gt;data[1]; \ curr_node-&gt;data[1] = parent-&gt;data[1]; \ parent-&gt;data[1] = tmp; \ } \ \ index = P_index; \ curr_node = parent; \ } \ } \ \ static void PFX##_impl_float_up_min(SNAME *_heap_) \ { \ size_t index = _heap_-&gt;size - 1; \ SNAME##_node *curr_node = &amp;(_heap_-&gt;buffer[index]); \ \ while (index &gt; 0) \ { \ size_t P_index = (index - 1) / 2; \ SNAME##_node *parent = &amp;(_heap_-&gt;buffer[P_index]); \ \ if (_heap_-&gt;cmp(curr_node-&gt;data[0], parent-&gt;data[0]) &gt;= 0) \ break; \ \ V tmp = curr_node-&gt;data[0]; \ curr_node-&gt;data[0] = parent-&gt;data[0]; \ parent-&gt;data[0] = tmp; \ index = P_index; \ curr_node = parent; \ } \ } \ \ static void PFX##_impl_float_down_max(SNAME *_heap_) \ { \ size_t index = 0; \ SNAME##_node *curr_node = &amp;(_heap_-&gt;buffer[index]); \ \ while (true) \ { \ if (2 * index + 1 &gt;= _heap_-&gt;size) \ break; \ \ size_t child; \ size_t L_index = index * 2 + 1; \ size_t R_index = index * 2 + 2; \ \ if (R_index &lt; _heap_-&gt;size) \ { \ SNAME##_node *L = &amp;(_heap_-&gt;buffer[L_index]); \ SNAME##_node *R = &amp;(_heap_-&gt;buffer[R_index]); \ \ if (R_index == _heap_-&gt;size - 1 &amp;&amp; PFX##_count(_heap_) % 2 != 0) \ child = _heap_-&gt;cmp(L-&gt;data[1], R-&gt;data[0]) &gt; 0 ? L_index : R_index; \ else \ child = _heap_-&gt;cmp(L-&gt;data[1], R-&gt;data[1]) &gt; 0 ? L_index : R_index; \ } \ else \ child = L_index; \ \ SNAME##_node *child_node = &amp;(_heap_-&gt;buffer[child]); \ \ if (child == _heap_-&gt;size - 1 &amp;&amp; PFX##_count(_heap_) % 2 != 0) \ { \ if (_heap_-&gt;cmp(curr_node-&gt;data[1], child_node-&gt;data[0]) &gt;= 0) \ break; \ \ V tmp = child_node-&gt;data[0]; \ child_node-&gt;data[0] = curr_node-&gt;data[1]; \ curr_node-&gt;data[1] = tmp; \ } \ else \ { \ if (_heap_-&gt;cmp(curr_node-&gt;data[1], child_node-&gt;data[1]) &gt;= 0) \ break; \ \ V tmp = child_node-&gt;data[1]; \ child_node-&gt;data[1] = curr_node-&gt;data[1]; \ curr_node-&gt;data[1] = tmp; \ \ if (_heap_-&gt;cmp(child_node-&gt;data[0], child_node-&gt;data[1]) &gt; 0) \ { \ tmp = child_node-&gt;data[0]; \ child_node-&gt;data[0] = child_node-&gt;data[1]; \ child_node-&gt;data[1] = tmp; \ } \ } \ index = child; \ curr_node = child_node; \ } \ } \ \ static void PFX##_impl_float_down_min(SNAME *_heap_) \ { \ size_t index = 0; \ \ SNAME##_node *curr_node = &amp;(_heap_-&gt;buffer[index]); \ \ while (true) \ { \ if (2 * index + 1 &gt;= _heap_-&gt;size) \ break; \ \ size_t child; \ size_t L_index = index * 2 + 1; \ size_t R_index = index * 2 + 2; \ \ if (R_index &lt; _heap_-&gt;size) \ { \ SNAME##_node *L = &amp;(_heap_-&gt;buffer[L_index]); \ SNAME##_node *R = &amp;(_heap_-&gt;buffer[R_index]); \ child = _heap_-&gt;cmp(L-&gt;data[0], R-&gt;data[0]) &lt; 0 ? L_index : R_index; \ } \ else \ child = L_index; \ \ SNAME##_node *child_node = &amp;(_heap_-&gt;buffer[child]); \ \ if (_heap_-&gt;cmp(curr_node-&gt;data[0], child_node-&gt;data[0]) &lt; 0) \ break; \ \ V tmp = child_node-&gt;data[0]; \ child_node-&gt;data[0] = curr_node-&gt;data[0]; \ curr_node-&gt;data[0] = tmp; \ \ if (child != _heap_-&gt;size - 1 || PFX##_count(_heap_) % 2 == 0) \ { \ if (_heap_-&gt;cmp(child_node-&gt;data[0], child_node-&gt;data[1]) &gt; 0) \ { \ tmp = child_node-&gt;data[0]; \ child_node-&gt;data[0] = child_node-&gt;data[1]; \ child_node-&gt;data[1] = tmp; \ } \ } \ index = child; \ curr_node = child_node; \ } \ } \ \ static SNAME##_iter PFX##_impl_it_start(SNAME *_heap_) \ { \ SNAME##_iter iter; \ PFX##_iter_init(&amp;iter, _heap_); \ PFX##_iter_to_start(&amp;iter); \ return iter; \ } \ \ static SNAME##_iter PFX##_impl_it_end(SNAME *_heap_) \ { \ SNAME##_iter iter; \ PFX##_iter_init(&amp;iter, _heap_); \ PFX##_iter_to_end(&amp;iter); \ return iter; \ } #endif /* CMC_INTERVALHEAP_H */ </code></pre> <p><strong>test.c</strong></p> <pre class="lang-c prettyprint-override"><code>#include "intervalheap.h" #include &lt;stdio.h&gt; /* Generate the Interval Heap */ INTERVALHEAP_GENERATE(h, heap, , int) /* Comparison function */ int intcmp(int a, int b) { return (a &gt; b) - (a &lt; b); } #define TOTAL 100 int main(void) { heap *my_heap = h_new(50, intcmp); for (size_t i = 1; i &lt;= TOTAL; i++) { h_insert(my_heap, i); } size_t half = h_count(my_heap) / 2; for (size_t i = 0; !h_empty(my_heap); i++) { int r; i &lt; half ? h_remove_max(my_heap, &amp;r) : h_remove_min(my_heap, &amp;r); printf("%d ", r); } h_free(my_heap); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T12:57:48.133", "Id": "433482", "Score": "0", "body": "I would say that `intcmp` isn't very straightforward, and it would be more obvious with `if`s and branches. Let the compiler optimize the code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T13:02:40.650", "Id": "433483", "Score": "0", "body": "And don't use `?:` unless it's for a very obvious thing. Function calls aren't very obvious things. A good place for `?:` is GCC's compound expression macros" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T04:06:57.160", "Id": "223595", "Score": "4", "Tags": [ "c", "generics", "collections", "heap" ], "Title": "Generic Macro Generated Interval Heap in C" }
223595
<p>This code moves one element from one <code>unordered_map</code> to another.</p> <p>I would like to ask if my code below can be improved.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;utility&gt; #include &lt;unordered_map&gt; int main() { struct Data { int foo; bool boo; }; std::unordered_map&lt;std::string, Data&gt; map_A = {{"A", {1, true}}, {"B", {2, false}}}; std::unordered_map&lt;std::string, Data&gt; map_B = {{"C", {3, false}}, {"D", {4, true}}};; std::string keyToMove = "C"; map_A.insert({keyToMove, map_B[keyToMove]}); map_B.erase(keyToMove); std::cout &lt;&lt; "map_A" &lt;&lt; std::endl; auto it = map_A.begin(); while(it != map_A.end()) { std::cout&lt;&lt;it-&gt;first&lt;&lt;" :: "&lt;&lt;it-&gt;second.foo&lt;&lt;std::endl; it++; } std::cout &lt;&lt; "map_B" &lt;&lt; std::endl; auto it2 = map_B.begin(); while(it2 != map_B.end()) { std::cout&lt;&lt;it2-&gt;first&lt;&lt;" :: "&lt;&lt;it2-&gt;second.foo&lt;&lt;std::endl; it2++; } return 0; } </code></pre> <p>Result:</p> <pre><code>map_A C :: 3 B :: 2 A :: 1 map_B D :: 4 Program ended with exit code: 0 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T11:57:44.627", "Id": "433474", "Score": "2", "body": "The word `trying` in the first sentence might indicate to some people on this site that the code isn't working. Since the results show that the code is working you might want to remove that word." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T16:22:33.317", "Id": "433504", "Score": "0", "body": "https://en.cppreference.com/w/cpp/container/unordered_map/extract" } ]
[ { "body": "<p><strong>Unused Includes</strong><br>\nThe code is not using <em>std:vector</em>, nor is it using anything from <em>utilities</em>. It might be better not to include these, that can improve your compile time and decrease the size of the generated code.</p>\n\n<p><strong>Don't Repeat Yourself</strong><br>\nThere are two obvious functions that can be written to shorten the code in <code>main()</code>. One function prints the contents of an unordered map and the other moves the contents from one map to the other. When you see code repeating itself in a function that is a good indication that you can create a function to reduce the amount of code in the function to make it simpler.</p>\n\n<p><strong>Program Exit Status</strong><br>\nIn this particular program it isn't necessary to have <code>return 0</code>; in <code>main()</code> C++ will generate it for you. When you have programs that might fail it might be better to include <a href=\"https://en.cppreference.com/w/cpp/utility/program/EXIT_status\" rel=\"nofollow noreferrer\">cstdlib and use the symbolic constants EXIT_SUCCESS and EXIT_FAILURE</a> to indicate success or failure to the calling program.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T12:38:32.143", "Id": "223618", "ParentId": "223597", "Score": "2" } } ]
{ "AcceptedAnswerId": "223618", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T05:55:16.837", "Id": "223597", "Score": "3", "Tags": [ "c++", "hash-map" ], "Title": "Moving an element from one unordered_map to another" }
223597
<p>This is a problem from "Automate the boring stuff".</p> <blockquote> <p>Write a function that uses regular expressions to make sure the password string it is passed is strong. A strong password is defined as one that is at least eight characters long, contains both uppercase and lowercase characters, and has at least one digit. You may need to test the string against multiple regex patterns to validate its strength.</p> </blockquote> <p>How to improve this code?</p> <pre><code>#! /usr/bin/python3 import re def uppercase_check(password): if re.search('[A-Z]', password): #atleast one uppercase character return True return False def lowercase_check(password): if re.search('[a-z]', password): #atleast one lowercase character return True return False def digit_check(password): if re.search('[0-9]', password): #atleast one digit return True return False def user_input_password_check(): password = input("Enter password : ") #atleast 8 character long if len(password) &gt;= 8 and uppercase_check(password) and lowercase_check(password) and digit_check(password): print("Strong Password") else: print("Weak Password") user_input_password_check() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T15:05:58.130", "Id": "433495", "Score": "3", "body": "Please give some feedback to the authors of \"Automate the boring stuff\" that their task is misguided. Hopefully they will remove it then." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T17:09:46.707", "Id": "433515", "Score": "0", "body": "[obXKCD](https://xkcd.com/936/)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T02:44:16.700", "Id": "433581", "Score": "4", "body": "Aside: [Obligatory Security.SE question about above XKCD](https://security.stackexchange.com/q/6095/46979). Also [an article](https://spycloud.com/new-nist-guidelines/) about how NIST changed their recommendations on the matter as well. In brief, this mindset about password \"strength\" is rapidly being outdated. Your question is fine, though, since you're given a problem and asking for a review of the solution. Just realize that this is a toy problem and not something that you should be implementing in production code. (Note that password security is more often done wrong than right, as well.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T18:49:04.103", "Id": "433668", "Score": "0", "body": "@jpmc26 Welp, it's better to have such a check than no check at all. Otherwise 2-character passwords are allowed too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T05:33:40.573", "Id": "433693", "Score": "0", "body": "@Mast Have a length check. That's the minimum. If you're going to do more, filter out common passwords (like at least the 10000 most common) and maybe some patterns or keywords that make the password easier to guess. Put visible recommendations for random passwords and 2-factor auth in your app. The kinds of requirements here actually reduce the password space and encourage poor password choice." } ]
[ { "body": "<p>First, please note that <strong>this security measure has been <a href=\"https://security.stackexchange.com/q/6095/1220\">thoroughly</a> <a href=\"https://nakedsecurity.sophos.com/2016/08/18/nists-new-password-rules-what-you-need-to-know/\" rel=\"noreferrer\">debunked</a></strong> (although the reasons why are complex and psychological). Any code resulting from this exercise is therefore by the standards of the security community following an anti-pattern, and should not be used no matter how polished.</p>\n\n<p>That said:</p>\n\n<ul>\n<li><p>Rather than the</p>\n\n<pre><code>if something:\n return True\nreturn False\n</code></pre>\n\n<p>a more readable pattern is simply <code>return something</code>.</p></li>\n<li>This code would be more scriptable if it either took passwords as arguments (using <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"noreferrer\"><code>argparse</code></a>) or read one password per line from standard input.</li>\n<li><p>Another way to make this more scriptable is to use the really common</p>\n\n<pre><code>if __name__ == \"__main__\":\n sys.exit(main())\n</code></pre>\n\n<p>pattern.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T07:38:12.877", "Id": "223601", "ParentId": "223600", "Score": "7" } }, { "body": "<ul>\n<li>You preform multiple function calls which are all very related. You can cram each of the regex checks into one if statement.</li>\n<li>You should use a <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\">main guard</a> to ensure that the code is only running if this file is the main one, so that any programs importing this file don't have any issues.</li>\n<li>You should also use <a href=\"https://www.geeksforgeeks.org/python-docstrings/\" rel=\"nofollow noreferrer\">docstrings</a>. These allow potential documentation to display information about what the methods(s) are supposed to accomplish.</li>\n<li>Using condensed if statements can clean up the messiness of having <code>if: ... else: ...</code> when there is just one statement being executed in each block.</li>\n</ul>\n\n<p>Here is the updated code:</p>\n\n<pre><code>#! /usr/bin/python3\n\nimport re\n\ndef check(password):\n \"\"\" \n Ensures password has at least one uppercase, one lowercase, and one digit\n \"\"\"\n return False if not re.search('[A-Z]', password) or not re.search('[a-z]', password) or not re.search('[0-9]', password) else True\n\nif __name__ == '__main__':\n password = input(\"Enter password: \")\n print(\"Strong password\") if check(password) else print(\"Weak Password\")\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T13:51:28.103", "Id": "433492", "Score": "6", "body": "`return False if not` isn't the best way to go about this. Instead, cast to `bool`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T15:02:40.620", "Id": "433494", "Score": "2", "body": "You could also refrain from not using less fewer negations in your code. A much more natural way to express the original task is `return has_digits and has_upper and has_lower`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T02:59:48.467", "Id": "433582", "Score": "0", "body": "Use some vertical whitespace in that very long boolean condition. Might even make sense to switch to an `any` call." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T07:49:01.690", "Id": "223602", "ParentId": "223600", "Score": "2" } }, { "body": "<p>Firstly: what @l0b0 said. This is fundamentally misguided, and you're better off doing an actual entropy measurement.</p>\n\n<p>As for your <code>check</code> functions, you can rewrite them as:</p>\n\n<pre><code>def uppercase_check(password: str) -&gt; bool:\n return bool(re.search('[A-Z]', password))\n</code></pre>\n\n<p>Note that it uses proper type-hinting, and doesn't need an <code>if</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T13:57:13.363", "Id": "223622", "ParentId": "223600", "Score": "4" } }, { "body": "<p>I'm submitting this as a different answer because it goes in a different direction from my previous one, eliminating the bool cast as well as individual functions. You can simply define a tuple of regular expressions and apply <code>all</code>.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>rexes = ('[A-Z]', '[a-z]', '[0-9]')\n# ...\nif len(password) &gt;= 8 and all(re.search(r, password) for r in rexes)):\n print('Strong password')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T17:34:05.130", "Id": "433517", "Score": "2", "body": "While it doesn't use regexps just thought it worth pointing out an alternative using `unicodedata.category`. You categorise each letter and then check each of the types you want is present (lower case, upper case and digit), something along the lines of: `if len(password) >= 8 and {'Ll', 'Lu', 'Nd'}.issubset(unicodedata.category(ch) for ch in password)`..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T23:09:26.773", "Id": "433564", "Score": "0", "body": "@JonClements True, and that approach is probably more friendly to i18n" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T14:05:59.667", "Id": "223623", "ParentId": "223600", "Score": "9" } } ]
{ "AcceptedAnswerId": "223623", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T07:12:56.983", "Id": "223600", "Score": "5", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Strong Password Detection in Python" }
223600
<p>I want to execute a python script daily and thereby want to schedules task as follows.</p> <p>The idea is that the script will run once daily, and the script will then decide what tasks to be done today.</p> <p>The reason is that I can't use cron or windows scheduled task on my environment.</p> <p>The question is that, is there any better idea?</p> <pre><code>from datetime import datetime import os from sheduled_tasks import daily_task1, daily_task2, weekly_task, monthly_tasks tasks = {} # or open from saved pickel file schedule = { 1: [daily_task1, daily_task2], 7: [weekly_task], 30: [monthly_tasks], } for delta, stasks in schedule.items(): for task in stasks: name = task.__name__ if ((task not in tasks) or (datetime.now() - tasks[name]).days &gt;= delta): task() tasks[task.name] = datetime.now().replace(hour=6) # pickle tasks </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T12:44:34.627", "Id": "433480", "Score": "2", "body": "does your script get executed once daily, or does it just sit on your OS as a process 24/7?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T13:37:10.347", "Id": "433490", "Score": "1", "body": "What's your environment? Surely there's a better solution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T04:20:30.797", "Id": "433688", "Score": "0", "body": "@FirefoxMetzger: Executed once daily. It doesn't sit on your OS as a process 24/7." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T04:26:51.110", "Id": "433690", "Score": "0", "body": "@Reinderien: Custom python (Linux based) environment without bash or anything. Just once daily python only task. I can request any python module from pypi." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T09:40:22.683", "Id": "433726", "Score": "0", "body": "I see. Should it be 'every week/month/year starting from the first invocation' or 'regularly in a weekly/monthly/yearly interval'?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T11:07:48.380", "Id": "433744", "Score": "0", "body": "@FirefoxMetzger: Regularly in week/monthly/yearly interval. if some day, say during power cut, if it fails to run, if any task to be done on that day should be done on next power on day." } ]
[ { "body": "<p>You can get rid of doing any I/O and make your code cleaner in the process. </p>\n\n<pre><code>from datetime import datetime\nfrom sheduled_tasks import daily_task1, daily_task2, weekly_task, monthly_tasks\n\nschedule = {\n 1: [daily_task1, daily_task2],\n 7: [weekly_task],\n 30: [monthly_tasks],\n}\n\n# this could also be the date of first invocation, just change the timestamp\narbitrary_date = datetime.fromtimestamp(1234567890)\ndays_past = (datetime.now() - arbitrary_date).days\n\nfor delay, tasks in schedule.items():\n if days_past % delay == 0:\n [task() for task in tasks]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T11:42:41.670", "Id": "433750", "Score": "0", "body": "It took a while for me to understand. This is perfect for my continuously running server with power backup. I think for non-power backup server, it may fail. Thanks for simplification." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T12:47:06.697", "Id": "433765", "Score": "0", "body": "@RahulPatel That depends if you expect your server to fail for more than 24h. To comment on that, however, we would need more information about the actual environment than just the snippet and 'it will be executed once a day', because the latter is not the case if you have more than 24h downtime." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T05:00:17.320", "Id": "433911", "Score": "0", "body": "Agreed. Most of the time, the server is not dead for 24 hour." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T10:10:30.190", "Id": "223729", "ParentId": "223603", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T08:18:31.400", "Id": "223603", "Score": "3", "Tags": [ "python", "python-3.x", "scheduled-tasks" ], "Title": "Simple python scheduled tasks script that runs once daily" }
223603
<p>Recently I've been toying around with C# interop and the Vulkan API. Today I discovered the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.safehandle" rel="nofollow noreferrer"><code>SafeHandle</code> class</a> and decided I'd try to wrap the Windows API calls that I depend upon; please see the code below and let me know if I've made any errors during the implementation process.</p> <p><strong>Code:</strong></p> <pre><code>public static class Library { [Flags] public enum LoadLibraryType : uint { NONE = 0x00000000, } [Flags] public enum ModuleHandleType : uint { NONE = 0x00000000, } public sealed class LoadLibrarySafeHandle : SafeHandleZeroIsInvalid { [DllImport("Kernel32.dll", BestFitMapping = false, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true, ThrowOnUnmappableChar = true)] private static extern bool FreeLibrary(IntPtr libraryHandle); [DllImport("Kernel32.dll", BestFitMapping = false, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true, ThrowOnUnmappableChar = true)] private static extern bool GetModuleHandleExW(ModuleHandleType moduleHandleType, [MarshalAs(UnmanagedType.LPWStr)] string libraryName, out IntPtr libraryHandle); [DllImport("Kernel32.dll", BestFitMapping = false, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true, ThrowOnUnmappableChar = true)] private static extern IntPtr GetProcAddress(IntPtr libraryHandle, [MarshalAs(UnmanagedType.LPStr)] string procedureName); [DllImport("Kernel32.dll", BestFitMapping = false, CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true, ThrowOnUnmappableChar = true)] private static extern IntPtr LoadLibraryExW([MarshalAs(UnmanagedType.LPWStr)] string libraryName, IntPtr fileHandle, LoadLibraryType loadLibraryType); public static LoadLibrarySafeHandle New(IntPtr address) =&gt; new LoadLibrarySafeHandle(address); public static LoadLibrarySafeHandle New(string name, IntPtr fileHandle, LoadLibraryType loadLibraryType) { if (GetModuleHandleExW(ModuleHandleType.NONE, name, out IntPtr libraryHandle)) { return New(libraryHandle); } else { libraryHandle = LoadLibraryExW(name, fileHandle, loadLibraryType); if (IntPtr.Zero == libraryHandle) { throw new DllNotFoundException(message: $"unable to find a library named {name}", inner: Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error())); } return New(libraryHandle); } } public static LoadLibrarySafeHandle New(string name) =&gt; New(name, IntPtr.Zero, LoadLibraryType.NONE); private LoadLibrarySafeHandle(IntPtr address) : base(true) { SetHandle(address); } [PrePrepareMethod] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] protected override bool ReleaseHandle() =&gt; FreeLibrary(handle); public bool TryGetDelegateForFunctionPointer&lt;TDelegate&gt;(string functionName, out TDelegate functionDelegate) { var functionHandle = GetProcAddress(handle, functionName); if (IntPtr.Zero == functionHandle) { functionDelegate = default; return false; } else { functionDelegate = Marshal.GetDelegateForFunctionPointer&lt;TDelegate&gt;(functionHandle); } return true; } } } </code></pre> <p><strong>Usage:</strong></p> <pre><code>class Program { private delegate IntPtr vkGetInstanceProcAddr(IntPtr instance, IntPtr pName); static void Main(string[] args) { var vkDllHandle = Library.LoadLibrarySafeHandle.New("vulkan-1.dll"); if (vkDllHandle.TryGetDelegateForFunctionPointer(nameof(vkGetInstanceProcAddr), out vkGetInstanceProcAddr vkGetInstanceProcAddrDelegate)) { // do something with vkGetInstanceProcAddrDelegate } } } </code></pre> <p><strong>References:</strong></p> <p><a href="https://stackoverflow.com/questions/17562295/if-i-allocate-some-memory-with-allochglobal-do-i-have-to-free-it-with-freehglob">https://stackoverflow.com/questions/17562295/if-i-allocate-some-memory-with-allochglobal-do-i-have-to-free-it-with-freehglob</a></p> <p><a href="https://www.codeproject.com/Articles/29534/IDisposable-What-Your-Mother-Never-Told-You-About" rel="nofollow noreferrer">https://www.codeproject.com/Articles/29534/IDisposable-What-Your-Mother-Never-Told-You-About</a></p>
[]
[ { "body": "<h3>Guidelines when dealing with P/Invoke</h3>\n\n<ul>\n<li>move native methods to nested classes (<a href=\"https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2012/ms182161(v=vs.110)\" rel=\"nofollow noreferrer\">Recommendation CA1060</a>)</li>\n<li>define the libraries to import as constants <code>const string Kernel32Lib = \"Kernel32.dll\";</code> -> <code>[DllImport(Kernel32Lib)]</code></li>\n</ul>\n\n<h3>General guidelines</h3>\n\n<p>Avoid unnecessary code blocks.</p>\n\n<blockquote>\n<pre><code>if (IntPtr.Zero == functionHandle) {\n functionDelegate = default;\n\n return false;\n}\nelse {\n functionDelegate = Marshal.GetDelegateForFunctionPointer&lt;TDelegate&gt;(functionHandle);\n}\nreturn true;\n</code></pre>\n</blockquote>\n\n<p>rewritten:</p>\n\n<pre><code>if (IntPtr.Zero == functionHandle) {\n functionDelegate = default;\n return false;\n}\nfunctionDelegate = Marshal.GetDelegateForFunctionPointer&lt;TDelegate&gt;(functionHandle);\nreturn true;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T09:47:11.320", "Id": "223607", "ParentId": "223606", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T09:22:59.937", "Id": "223606", "Score": "2", "Tags": [ "c#", "windows" ], "Title": "\"Safe\" Windows Module API Wrapper" }
223606
<p>I am beginner in python and I am learing about syntax and other functions in python by writing Algorithm and Data Structure programs.</p> <p>How can this code be improved?</p> <pre><code>def get_input(): #to get input from user input_str = input("Enter elements to be sorted: ") try: lst = list(map(int, input_str.split())) #make a list of integers from input string except: raise TypeError("Please enter a list of integers only, seperated by a space!!") return lst def max_heapify(thelist, lst_size, idx): largest = idx left_child = (2 * idx) + 1 right_child = (2 * idx) + 2 if left_child &lt; lst_size and thelist[left_child] &gt; thelist[largest]: largest = left_child if right_child &lt; lst_size and thelist[right_child] &gt; thelist[largest]: largest = right_child if largest != idx: thelist[idx], thelist[largest] = thelist[largest], thelist[idx] max_heapify(thelist, lst_size, largest) def build_max_heap(thelist, lst_size): for curr_idx in range(lst_size // 2 - 1, -1, -1): max_heapify(thelist, lst_size, curr_idx) def heap_sort(thelist): if len(thelist) == 0: print("Empty list!!") elif len(thelist) == 1: print("Only one element!!") else: build_max_heap(thelist, len(thelist)) for curr_idx in range(len(thelist) -1, 0, -1): thelist[curr_idx], thelist[0] = thelist[0], thelist[curr_idx] #swapping max_heapify(thelist, curr_idx, 0) if __name__ == '__main__': input_list = get_input() heap_sort(input_list) print(*input_list, sep = ", ") </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T12:51:02.160", "Id": "433481", "Score": "0", "body": "(I neither considered seriously inspecting [your Quick Sort code](https://codereview.stackexchange.com/q/223332/93149) nor this Heapsort for the same reason: both are \"not\" documented/commented.) Heed the [Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/#comments)" } ]
[ { "body": "<h2>Use standard docstrings</h2>\n\n<p>This comment:</p>\n\n<pre><code>to get input from user\n</code></pre>\n\n<p>is best placed in a docstring:</p>\n\n<pre><code>def get_input():\n \"\"\"\n get input from user\n \"\"\"\n</code></pre>\n\n<h2>Consider using type hints</h2>\n\n<p>You're best to google this, because there's a wealth of information about it, but as an example: the <code>idx</code> argument would be <code>idx: int</code>.</p>\n\n<h2>Operator precedence</h2>\n\n<pre><code>(2 * idx) + 1\n</code></pre>\n\n<p>doesn't need parens, because multiplication has stronger association than addition.</p>\n\n<h2>Never <code>except:</code></h2>\n\n<p>At the least, you should write <code>except Exception</code> instead of <code>except</code>. The latter can prevent user break (Ctrl+C) from working. If possible, replace Exception with something more specific.</p>\n\n<h2>Use a comprehension</h2>\n\n<p><code>map</code> is a little difficult to read. Instead, how about</p>\n\n<pre><code>lst = [int(e) for e in input_str.split()]\n</code></pre>\n\n<h2>Variable naming</h2>\n\n<p><code>lst</code> isn't helpful - rather than naming things based on what type they are, you should be naming them based on what they actually mean to the program - in this case, perhaps \"elements\".</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T13:16:38.350", "Id": "223621", "ParentId": "223609", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T10:36:32.837", "Id": "223609", "Score": "1", "Tags": [ "python", "beginner", "algorithm", "python-3.x" ], "Title": "Python: Heapsort" }
223609
<p>Below is my solution for the <a href="https://leetcode.com/problems/jump-game/" rel="nofollow noreferrer">LeetCode Jump Game</a></p> <blockquote> <p>Given an array of non-negative integers, you are initially positioned at the first index of the array.</p> <p>Each element in the array represents your maximum jump length at that position.</p> <p>Determine if you are able to reach the last index.</p> </blockquote> <p>Example 1:</p> <blockquote> <p>Input: [2,3,1,1,4]</p> <p>Output: true</p> </blockquote> <p>This is my solution. It is correct but timed out the LeetCode code-checker for an array of 25000 elements.</p> <p>Please can someone help me improve this code.</p> <p>It seems to have a time complexity of <code>O(N^2)</code> and a space complexity of O(N). I cannot work out a method faster than <code>O(N^2)</code>.</p> <pre><code>def function(nums): if len(nums) == 1: return True output = [0] * len(nums) last_index = len(nums) - 1 output[0] = 1 for index, number in enumerate(nums): if output[index] == 0: continue if output[index] == 1: stop_at = min(last_index, index + number) for i in range(index, stop_at + 1): output[i] = 1 if output[last_index] == 1: return True return False if __name__ == &quot;__main__&quot;: nums = [3,2,1,0,4] output = function(nums) print(output) </code></pre>
[]
[ { "body": "<h3>Coding style</h3>\n\n<p>Your code passes the <a href=\"http://pep8online.com\" rel=\"nofollow noreferrer\">PEP8 online</a> check without errors or warnings, that's great.</p>\n\n<h3>Naming</h3>\n\n<p>The function name <code>function</code> is pretty non-descriptive. The Leetcode template uses <code>canJump</code>, but according to Python <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a></p>\n\n<blockquote>\n <p>Function names should be lowercase, with words separated by underscores as necessary to improve readability.</p>\n</blockquote>\n\n<p>that would be <code>can_jump</code>. Your <code>output</code> array stores which positions are reachable from the initial position, a better name might be <code>reachable</code>. The <code>index</code> is the current <em>position,</em> and <code>number</code> is the <em>jump width</em> at that position.</p>\n\n<h3>Coding improvements</h3>\n\n<p>The <code>output</code>/<code>reachable</code> array should be an array of <em>boolean</em> values instead of integers. The test</p>\n\n<pre><code>if output[index] == 0:\n continue\n</code></pre>\n\n<p>is not needed, and the test</p>\n\n<pre><code>if output[last_index] == 1:\n return True\n</code></pre>\n\n<p>needs only to be done at reachable positions. Summarizing the suggestions so far, we have</p>\n\n<pre><code>def can_jump(nums):\n if len(nums) == 1:\n return True\n reachable = [False] * len(nums)\n last_pos = len(nums) - 1\n reachable[0] = True\n\n for pos, jump_width in enumerate(nums):\n if reachable[pos]:\n stop_at = min(last_pos, pos + jump_width)\n for i in range(pos, stop_at + 1):\n reachable[i] = True\n if reachable[last_pos]:\n return True\n return False\n</code></pre>\n\n<h3>Performance improvements</h3>\n\n<p>The crucial observation is that the list of reachable positions is always an <em>interval</em> (from position <code>0</code> to some maximal reachable position). This interval can be described by a single integer variable</p>\n\n<pre><code>last_reachable = 0\n</code></pre>\n\n<p>which is updated while traversing the array. I won't deprive you of the satisfaction to program the solution yourself, therefore I'll mention only the general idea. While enumerating the array:</p>\n\n<ul>\n<li>If the current position is not reachable then return <code>False</code>.</li>\n<li>Otherwise, update <code>last_reachable</code> with the maximum of its current value and the greatest position reachable from the current position.</li>\n<li>Return <code>True</code> as soon as the final position turns out to be reachable. </li>\n</ul>\n\n<p>This approach needs less memory (no additional array), and only a simple loop instead of nested loops.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T13:06:26.907", "Id": "433486", "Score": "0", "body": "Thank you for the reply. Yes, this is the method I figured would be much faster. Sorry for deleting it before and thank you for your reply." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T13:04:26.893", "Id": "223620", "ParentId": "223612", "Score": "2" } }, { "body": "<h2>O(n) Solution</h2>\n\n<p>You don't need to keep track of all the places you can reach. You only need to know what is the highest index you can reach, because you can reach any lower index by choosing a shorter jump. Scan the list from 0 to the end keeping track of the maximum reachable index. If you ever reach an index greater than the maximum reachable index, you've hit a block and can't reach the end.</p>\n\n<p>For example, for a jump list = [3,2,1,0,4]. Starting at index 0, we can reach any index up to 0 + 3 = 3. From index 1 we can reach 1 + 2 = 3. From 2, we can reach 2+1 = 3. From index 3, we can reach 3 + 0 = 3. So far the maximum reachable index is 3. So when we reach index 4, 4 > 3 so index 4 is unreachable and we can't get to the end.</p>\n\n<pre><code>def canjump(nums):\n maximum_reachable_index = 0\n\n for index, max_jump in enumerate(nums):\n #print(f\"{index}\", end=' ')\n if index &gt; maximum_reachable_index:\n #print(f\"&gt; {maximum_reachable_index} and is unreachable.\")\n return False\n\n #print(f\"+ {max_jump} =&gt; {index + max_jump} : {maximum_reachable_index} \")\n maximum_reachable_index = max(index + max_jump, maximum_reachable_index)\n\n return True\n</code></pre>\n\n<p>Uncomment the print statements to see how it works.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T07:41:58.237", "Id": "434057", "Score": "0", "body": "That is exactly what I suggested as “Performance improvements” :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T06:15:58.410", "Id": "223846", "ParentId": "223612", "Score": "3" } } ]
{ "AcceptedAnswerId": "223846", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T10:57:41.967", "Id": "223612", "Score": "4", "Tags": [ "python", "performance", "python-3.x", "programming-challenge", "time-limit-exceeded" ], "Title": "Jump Game - Leetcode" }
223612
<p>I have completed my bank ATM application in C# class library project. For simplicity, the data of this version will be stored in the List instead of a database. The basic feature are</p> <ul> <li>Login</li> <li>Check balance</li> <li>Place cash deposit</li> <li>Withdraw cash</li> <li>Make third party transfer</li> <li>View transactions</li> </ul> <p><strong>Entities</strong></p> <pre><code>public class UserBankAccount { public long Id { get; set; } private long cardNumber; public long CardNumber { get; set; } public long CardPin { get; set; } public string FullName { get; set; } public long AccountNumber { get; set; } public decimal AccountBalance { get; set; } public int TotalLogin { get; set; } public bool IsLocked { get; set; } } </code></pre> <hr> <pre><code>public class Transaction { public int TransactionId { get; set; } public DateTime TransactionDate { get; set; } public TransactionType TransactionType { get; set; } public string Description { get; set; } public decimal TransactionAmount { get; set; } } </code></pre> <p><strong>Enum</strong></p> <pre><code>internal enum SecureMenu { [Description("Check balance")] CheckBalance = 1, [Description("Place Deposit")] PlaceDeposit = 2, [Description("Make Withdrawal")] MakeWithdrawal = 3, [Description("Third Party Transfer")] ThirdPartyTransfer = 4, [Description("Transaction")] ViewTransaction = 5, [Description("Logout")] Logout = 6 } </code></pre> <hr> <pre><code>public enum TransactionType { Deposit, Withdrawal, ThirdPartyTransfer } </code></pre> <p><strong>Interface</strong></p> <pre><code>public interface IATMApp { void CheckCardNoPassword(); } </code></pre> <hr> <pre><code>public interface ITransaction { void InsertTransaction(Transaction transaction); void ViewTransaction(); } </code></pre> <hr> <pre><code>public interface IUserBankAccount { void CheckBalance(); void PlaceDeposit(); void MakeWithdrawal(); } </code></pre> <p><strong>StaticClass</strong></p> <pre><code>internal class AtmScreen { internal const string cur = "RM "; internal static void WelcomeATM() { Console.Title = "Meybank ATM System."; Console.WriteLine("Welcome to Meybank ATM.\n"); Console.WriteLine("Please insert your ATM card."); PrintEnterMessage(); } internal static void WelcomeCustomer() { Utility.PrintUserInputLabel("Welcome back, "); } internal static void PrintLockAccount() { Console.Clear(); Utility.PrintMessage("Your account is locked. Please go to " + "the nearest branch to unlocked your account. Thank you.", true); PrintEnterMessage(); Environment.Exit(1); } internal static void LoginProgress() { Console.Write("\nChecking card number and card pin."); Utility.printDotAnimation(); Console.Clear(); } internal static void LogoutProgress() { Console.WriteLine("Thank you for using Meybank ATM system."); Utility.printDotAnimation(); Console.Clear(); } internal static void DisplaySecureMenu() { Console.Clear(); Console.WriteLine(" ---------------------------"); Console.WriteLine("| Meybank ATM Secure Menu |"); Console.WriteLine("| |"); Console.WriteLine("| 1. Balance Enquiry |"); Console.WriteLine("| 2. Cash Deposit |"); Console.WriteLine("| 3. Withdrawal |"); Console.WriteLine("| 4. Third Party Transfer |"); Console.WriteLine("| 5. Transactions |"); Console.WriteLine("| 6. Logout |"); Console.WriteLine("| |"); Console.WriteLine(" ---------------------------"); // The menu selection is tied to Enum:SecureMenu. } internal static void PrintCheckBalanceScreen() { Console.Write("Account balance amount: "); } internal static void PrintMakeWithdrawalScreen() { Console.Write("Enter amount: "); } // This is the only non-static method. // Reason is this method needs to return an object. // ToDo: Find other way to solve this design issue. internal VMThirdPartyTransfer ThirdPartyTransferForm() { var vMThirdPartyTransfer = new VMThirdPartyTransfer(); vMThirdPartyTransfer.RecipientBankAccountNumber = Validator.GetValidIntInputAmt("recipient's account number"); vMThirdPartyTransfer.TransferAmount = Validator.GetValidDecimalInputAmt("amount"); vMThirdPartyTransfer.RecipientBankAccountName = Utility.GetRawInput("recipient's account name"); // no validation here yet. return vMThirdPartyTransfer; } internal static void PrintEnterMessage() { Console.WriteLine("\nPress enter to continue."); Console.ReadKey(); } } </code></pre> <hr> <pre><code>public static class Utility { private static CultureInfo culture = new CultureInfo("ms-MY"); public static string GetRawInput(string message) { Console.Write($"Enter {message}: "); return Console.ReadLine(); } public static string GetHiddenConsoleInput() { StringBuilder input = new StringBuilder(); while (true) { var key = Console.ReadKey(true); if (key.Key == ConsoleKey.Enter) break; if (key.Key == ConsoleKey.Backspace &amp;&amp; input.Length &gt; 0) input.Remove(input.Length - 1, 1); else if (key.Key != ConsoleKey.Backspace) input.Append(key.KeyChar); } return input.ToString(); } #region UIOutput - UX and output format public static void printDotAnimation(int timer = 10) { for (var x = 0; x &lt; timer; x++) { Console.Write("."); Thread.Sleep(100); } Console.WriteLine(); } public static string FormatAmount(decimal amt) { return String.Format(culture, "{0:C2}", amt); } public static void PrintConsoleWriteLine(string msg, bool ConsoleWriteLine = true) { if (ConsoleWriteLine) Console.WriteLine(msg); else Console.Write(msg); AtmScreen.PrintEnterMessage(); } public static void PrintUserInputLabel(string msg, bool ConsoleWriteLine = false) { if (ConsoleWriteLine) Console.WriteLine(msg); else Console.Write(msg); } public static void PrintMessage(string msg, bool success) { if (success) Console.ForegroundColor = ConsoleColor.Yellow; else Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(msg); Console.ResetColor(); AtmScreen.PrintEnterMessage(); } #endregion } </code></pre> <p><strong>ViewModel</strong></p> <pre><code>public class VMThirdPartyTransfer { public decimal TransferAmount { get; set; } public long RecipientBankAccountNumber { get; set; } public string RecipientBankAccountName { get; set; } } </code></pre> <p><strong>Main Class</strong></p> <pre><code>public class AtmApp : IATMApp, ITransaction, IUserBankAccount { // This class in charge of main application where by Initialization and Execute // method will be the only methods to be called when client code run this application. // This list is used in replace of database in this version. private List&lt;UserBankAccount&gt; _accountList; private UserBankAccount selectedAccount; private const decimal minimum_kept_amt = 20; private List&lt;Transaction&gt; _listOfTransactions; public void Initialization() { _accountList = new List&lt;UserBankAccount&gt; { new UserBankAccount() { Id=1, FullName = "Peter Parker", AccountNumber=333111, CardNumber = 123123, CardPin = 111111, AccountBalance = 2000.00m, IsLocked = false }, new UserBankAccount() { Id=2, FullName = "Bruce Bane", AccountNumber=111222, CardNumber = 456456, CardPin = 222222, AccountBalance = 1500.30m, IsLocked = true }, new UserBankAccount() { Id=3, FullName = "Clark Kent", AccountNumber=888555, CardNumber = 789789, CardPin = 333333, AccountBalance = 2900.12m, IsLocked = false } }; } public void Execute() { AtmScreen.WelcomeATM(); CheckCardNoPassword(); AtmScreen.WelcomeCustomer(); Utility.PrintConsoleWriteLine(selectedAccount.FullName, false); _listOfTransactions = new List&lt;Transaction&gt;(); while (true) { AtmScreen.DisplaySecureMenu(); ProcessMenuOption(); } } public void CheckCardNoPassword() { bool isLoginPassed = false; while (isLoginPassed == false) { var inputAccount = new UserBankAccount(); // Actual ATM system will accept and validate physical ATM card. // Card validation includes read card number and check bank account status // and other security checking. inputAccount.CardNumber = Validator.GetValidIntInputAmt("ATM Card Number"); Utility.PrintUserInputLabel("Enter 6 Digit PIN: "); inputAccount.CardPin = Convert.ToInt32(Utility.GetHiddenConsoleInput()); // for brevity, length 6 is not validated and data type. AtmScreen.LoginProgress(); foreach (UserBankAccount account in _accountList) { selectedAccount = account; if (inputAccount.CardNumber.Equals(account.CardNumber)) { selectedAccount.TotalLogin++; if (inputAccount.CardPin.Equals(account.CardPin)) { selectedAccount = account; if (selectedAccount.IsLocked) { // This is when database is used and when the app is restarted. // Even user login with the correct card number and pin, // If IsLocked status is locked, user still will be still blocked. AtmScreen.PrintLockAccount(); } else { selectedAccount.TotalLogin = 0; isLoginPassed = true; break; } } } } if (isLoginPassed == false) { Utility.PrintMessage("Invalid card number or PIN.", false); // Lock the account if user fail to login more than 3 times. selectedAccount.IsLocked = selectedAccount.TotalLogin == 3; if (selectedAccount.IsLocked) AtmScreen.PrintLockAccount(); } Console.Clear(); } } private void ProcessMenuOption() { switch (Validator.GetValidIntInputAmt("your option")) { case (int)SecureMenu.CheckBalance: CheckBalance(); break; case (int)SecureMenu.PlaceDeposit: PlaceDeposit(); break; case (int)SecureMenu.MakeWithdrawal: MakeWithdrawal(); break; case (int)SecureMenu.ThirdPartyTransfer: var screen = new AtmScreen(); var vMThirdPartyTransfer = screen.ThirdPartyTransferForm(); PerformThirdPartyTransfer(vMThirdPartyTransfer); break; case (int)SecureMenu.ViewTransaction: ViewTransaction(); break; case (int)SecureMenu.Logout: AtmScreen.LogoutProgress(); Utility.PrintConsoleWriteLine("You have succesfully logout. Please collect your ATM card."); ClearSession(); Execute(); break; default: Utility.PrintMessage("Invalid Option Entered.", false); break; } } public void CheckBalance() { AtmScreen.PrintCheckBalanceScreen(); Utility.PrintConsoleWriteLine(Utility.FormatAmount(selectedAccount.AccountBalance), false); } public void PlaceDeposit() { // Note: Actual ATM system will just let you // place bank notes into physical ATM machine. Utility.PrintConsoleWriteLine("\nNote: Actual ATM system will just\nlet you " + "place bank notes into physical ATM machine. \n"); var transaction_amt = Validator.GetValidDecimalInputAmt("amount"); Utility.PrintUserInputLabel("\nCheck and counting bank notes."); Utility.printDotAnimation(); Console.SetCursorPosition(0, Console.CursorTop-3); Console.WriteLine(""); if (transaction_amt &lt;= 0) { Utility.PrintMessage("Amount needs to be more than zero. Try again.", false); return; } if (transaction_amt % 10 != 0) { Utility.PrintMessage($"Key in the deposit amount only with multiply of 10. Try again.", false); return; } if (PreviewBankNotesCount(transaction_amt) == false) { Utility.PrintMessage($"You have cancelled your action.", false); return; } // Bind transaction_amt to Transaction object // Add transaction record - Start var transaction = new Transaction() { TransactionDate = DateTime.Now, TransactionType = TransactionType.Deposit, TransactionAmount = transaction_amt }; InsertTransaction(transaction); // Add transaction record - End // Another method to update account balance. selectedAccount.AccountBalance = selectedAccount.AccountBalance + transaction_amt; Utility.PrintMessage($"You have successfully deposited {Utility.FormatAmount(transaction_amt)}. " + "Please collect the bank slip. ", true); } public void MakeWithdrawal() { Console.WriteLine("\nNote: For GUI or actual ATM system, user can "); Console.Write("choose some default withdrawal amount or custom amount. \n\n"); var transaction_amt = Validator.GetValidDecimalInputAmt("amount"); // Input data validation - Start if (transaction_amt &lt;= 0) { Utility.PrintMessage("Amount needs to be more than zero. Try again.", false); return; } if (transaction_amt % 10 != 0) { Utility.PrintMessage($"Key in the deposit amount only with multiply of 10. Try again.", false); return; } // Input data validation - End // Business rules validation - Start if (transaction_amt &gt; selectedAccount.AccountBalance) { Utility.PrintMessage($"Withdrawal failed. You do not have enough fund to withdraw {Utility.FormatAmount(transaction_amt)}", false); return; } if ((selectedAccount.AccountBalance - transaction_amt) &lt; minimum_kept_amt) { Utility.PrintMessage($"Withdrawal failed. Your account needs to have minimum {Utility.FormatAmount(minimum_kept_amt)}", false); return; } // Business rules validation - End // Bind transaction_amt to Transaction object // Add transaction record - Start var transaction = new Transaction() { TransactionDate = DateTime.Now, TransactionType = TransactionType.Withdrawal, TransactionAmount = Math.Abs(transaction_amt) }; InsertTransaction(transaction); // Add transaction record - End // Another method to update account balance. selectedAccount.AccountBalance = selectedAccount.AccountBalance - transaction_amt; Utility.PrintMessage("Please collect your money. You have successfully withdraw " + $"{Utility.FormatAmount(transaction_amt)}. Please collect your bank slip.", true); } public void PerformThirdPartyTransfer(VMThirdPartyTransfer vMThirdPartyTransfer) { if (vMThirdPartyTransfer.TransferAmount &lt;= 0) { Utility.PrintMessage("Amount needs to be more than zero. Try again.", false); return; } // Check giver's account balance - Start if (vMThirdPartyTransfer.TransferAmount &gt; selectedAccount.AccountBalance) { Utility.PrintMessage($"Withdrawal failed. You do not have enough " + "fund to withdraw {Utility.FormatAmount(vMThirdPartyTransfer.TransferAmount)}", false); return; } if (selectedAccount.AccountBalance - vMThirdPartyTransfer.TransferAmount &lt; minimum_kept_amt) { Utility.PrintMessage($"Withdrawal failed. Your account needs to have " + "minimum {Utility.FormatAmount(minimum_kept_amt)}", false); return; } // Check giver's account balance - End // Check if receiver's bank account number is valid. var selectedBankAccountReceiver = (from b in _accountList where b.AccountNumber == vMThirdPartyTransfer.RecipientBankAccountNumber select b).FirstOrDefault(); if (selectedBankAccountReceiver == null) { Utility.PrintMessage($"Third party transfer failed. Receiver bank account number is invalid.", false); return; } if (selectedBankAccountReceiver.FullName != vMThirdPartyTransfer.RecipientBankAccountName) { Utility.PrintMessage($"Third party transfer failed. Recipient's account name does not match.", false); return; } // Bind transaction_amt to Transaction object // Add transaction record (Giver) - Start Transaction transaction = new Transaction() { TransactionDate = DateTime.Now, TransactionType = TransactionType.ThirdPartyTransfer, TransactionAmount = Math.Abs(vMThirdPartyTransfer.TransferAmount), Description = $"Transfered to {selectedBankAccountReceiver.AccountNumber} ({selectedBankAccountReceiver.FullName})" }; _listOfTransactions.Add(transaction); // Add transaction record (Giver) - End // Update balance amount (Giver) selectedAccount.AccountBalance = selectedAccount.AccountBalance - vMThirdPartyTransfer.TransferAmount; // Add transaction record (Receiver) - Start transaction = new Transaction() { TransactionDate = DateTime.Now, TransactionType = TransactionType.ThirdPartyTransfer, TransactionAmount = vMThirdPartyTransfer.TransferAmount, Description = $"Transfered from {selectedAccount.AccountNumber} ({selectedAccount.FullName})" }; _listOfTransactions.Add(transaction); // Add transaction record (Receiver) - End // Update balance amount (Receiver) selectedBankAccountReceiver.AccountBalance = selectedBankAccountReceiver.AccountBalance + vMThirdPartyTransfer.TransferAmount; Utility.PrintMessage($"You have successfully transferred out " + " {Utility.FormatAmount(vMThirdPartyTransfer.TransferAmount)} to {vMThirdPartyTransfer.RecipientBankAccountName}", true); } public void ViewTransaction() { if (_listOfTransactions.Count &lt;= 0) Utility.PrintMessage($"There is no transaction yet.", true); else { var table = new ConsoleTable("Transaction Date", "Type", "Descriptions", "Amount " + AtmScreen.cur); foreach (var tran in _listOfTransactions) { table.AddRow(tran.TransactionDate, tran.TransactionType, tran.Description, tran.TransactionAmount); } table.Options.EnableCount = false; table.Write(); Utility.PrintMessage($"You have performed {_listOfTransactions.Count} transactions.", true); } } public void InsertTransaction(Transaction transaction) { _listOfTransactions.Add(transaction); } private void ClearSession() { // No session is used in this version. } } </code></pre> <p>Any comment on the my coding style and design pattern, for example SOLID principles? My concern is the <code>ThirdPartyTransferForm()</code> method in <code>AtmScreen</code> class. How should I split the UI nicely in this class? Another major issue I notice is that because ATMApp class implement the interface directly, if client code want to run this ATMApp application, those interface methods will be 'open' as well which is not supposed to be.</p> <p><a href="https://www.youtube.com/watch?v=JViV7a0ALFY&amp;list=PLIh_aKrRpW7QMaO9o7xxmasz0pvvvEoU-&amp;index=9" rel="nofollow noreferrer">This video</a> shows a sample run, based on an earlier version of the program.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T18:07:50.543", "Id": "433525", "Score": "2", "body": "There is even a video! How cool is that ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T00:54:23.107", "Id": "433574", "Score": "0", "body": "I will upload my source code to github soon." } ]
[ { "body": "<h3>Class Library</h3>\n\n<blockquote>\n <p>Console-based ATM client as a class library</p>\n</blockquote>\n\n<p>I wouldn't call your application a <em>class library</em>. Class libraries provide a set of reusable classes and interfaces. Your interfaces are black boxes that have no usability purpose other than being a trigger for some action that requires user interactive console interop.</p>\n\n<p>For instance,</p>\n\n<blockquote>\n<pre><code>public interface IUserBankAccount\n{\n void CheckBalance();\n void PlaceDeposit();\n void MakeWithdrawal();\n}\n</code></pre>\n</blockquote>\n\n<p>In a class library, this would be something like:</p>\n\n<pre><code>public interface IUserBankAccount\n{\n Balance CheckBalance();\n Transaction PlaceDeposit(DepositRequest deposit);\n Transaction MakeWithdrawal(WithdrawalRequest withdrawal);\n}\n</code></pre>\n\n<p>Try to refactor your code into several layers (domain, application).</p>\n\n<hr>\n\n<h3>Remarks</h3>\n\n<ul>\n<li>Try to adhere to \"Seperation of Concerns\": don't mix domain flow with user interactive flow. You could even split domain from application flow.</li>\n<li>Provide a member with value 0 for any enum. C# specifies the member with value 0 as default value.</li>\n<li>Create interfaces based on usability attributes, such as proper arguments and return values, rather than providing <code>void</code> operations that take 0 arguments. </li>\n<li>Try to avoid static classes except for some specific situations (<a href=\"https://stackoverflow.com/questions/241339/when-to-use-static-classes-in-c-sharp\">good post about this)</a></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T14:13:09.503", "Id": "433646", "Score": "0", "body": "Thanks a lot for the code review. About static class , are you referring to Utility and validation class? And any post or articles on soc of domain and application flow?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T14:15:38.847", "Id": "433647", "Score": "1", "body": "In this situation, I consider the domain layer the bank account, transactions, and deposit, withdraw operations. The application layer would use the domain layer and provide a presentation layer on top that handles user input/output with the console." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T14:26:48.170", "Id": "433648", "Score": "0", "body": "Okay, I think I got it. I should create multiple projects for each layer like domain driven design architecture right? I thought of adding that when I add database. The application layer is the web api layer right.?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T14:44:01.267", "Id": "433649", "Score": "1", "body": "The application layer could be a service layer (like web api), or could be a console app (like your situation) or any other presentation layer (wpf, asp.net, commandline tool, wcf, winforms, ..)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T11:12:40.997", "Id": "223670", "ParentId": "223613", "Score": "1" } } ]
{ "AcceptedAnswerId": "223670", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T11:14:15.333", "Id": "223613", "Score": "8", "Tags": [ "c#", "object-oriented", "console" ], "Title": "Console-based ATM client as a class library" }
223613
<p>I need to format a double value to three decimal places to a string with length of 9 with leading spaces and no decimal separator. </p> <p>My approach is this</p> <pre><code>NumberFormatInfo nfi = new NumberFormatInfo(); nfi.NumberDecimalSeparator = "a"; nfi.NumberGroupSeparator = ""; double a = 334.44554; Console.WriteLine($"{a.ToString("####0.000", nfi).Replace("a", ""), 9}"); </code></pre> <p>Is there a more elegant way to do this? </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T15:24:13.820", "Id": "433497", "Score": "1", "body": "Do you need to format the number in a human-readable way, or for a computer program? The answer will be entirely different for each of these two cases." } ]
[ { "body": "<p>To truncate a double to 3 decimal places and remove the decimal separator, is I think more easily done by multiplying by 1000 and casting to an int. Padding the result to 9 digits is easily done with a format specifier in the ToString method. It could look something like this:</p>\n\n<pre><code>static string FormatNum(double num) =&gt; ((int)(num * 1000)).ToString(\"D9\");\n</code></pre>\n\n<p>Note I've also put it in a method with an expression body.</p>\n\n<p>I just noticed that you wanted the padding with spaces not zeros here's a version that does that:</p>\n\n<pre><code>static string FormatNum(double num) =&gt; string.Format(\"{0,9:D}\",((int)(num * 1000)));\n</code></pre>\n\n<p>As was pointed out, your solution produced a rounded off number. If that is required here's one way:</p>\n\n<pre><code>static string FormatNum(double num) =&gt; string.Format(\"{0,9:D}\",((int)(Math.Round(num * 1000))));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T00:36:58.377", "Id": "223651", "ParentId": "223614", "Score": "6" } } ]
{ "AcceptedAnswerId": "223651", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T11:25:12.680", "Id": "223614", "Score": "1", "Tags": [ "c#", "formatting" ], "Title": "Format double to 3 decimal places without decimal separator to a certain length" }
223614
<p>I have come across many spell number functions and have reviewed many VBA code available on the net.</p> <p>The core function that gets called repeatedly is the function that converts numbers from 001 to 999 as it is the core function for conversion under the English numeral system. I have seen that this core function is sometime unnecessarily split over sub-functions for converting one, tens, and 20s to 90s.</p> <p>I have developed the following simple VBA function that takes an input as number in a string format from <code>"001"</code> to <code>"999"</code> and returns the output as a string. The function uses the dash <code>"-"</code> for numbers e.g. Forty-Two.</p> <p>The function is easily convertible to other programming languages.</p> <p>With your assistance, I am looking <strong>to further improve or simplifying the function, if possible</strong>.</p> <p>You may test the function like this:</p> <pre><code>Debug.Print Do999("123") Debug.Print Do999("001") Debug.Print Do999("099") </code></pre> <p>Thanks in advance for your contribution.</p> <pre><code>Function Do999(ThreeDigits As String) '----------------------------------------- 'Converts number string from 001 to 999 to Words 'Uses dash for in-between numbers from 21 to 99 for UK/US English 'Mohsen Alyafei 17 Oct 2018 'On Entry: NumIn MUST be a 3 Chars digit string "001" to "999" 'On Exit : String of number in English words '----------------------------------------- Dim Ones(), Tens(), dash As String, h As String, t As String, N1 As Integer, N2 As Integer Ones = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen") Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety", " Hundred") 'Next line is optional for English speaking words (UK, US) If Right(ThreeDigits, 1) &lt;&gt; "0" Then dash = "-" 'dash as per English spelling '------------Code starts here------------ 'Get the hundreds (N1) and tens (N2) N1 = Left(ThreeDigits, 1): N2 = Right(ThreeDigits, 2) If N2 &gt; 19 Then t = Tens(Val(Mid(ThreeDigits, 2, 1))) &amp; dash &amp; Ones(Val(Right(ThreeDigits, 1))) Else t = Ones(N2) Do999 = Trim(IIf(N1 &gt; 0, Ones(N1) &amp; Tens(10), "") &amp; " " &amp; t) End Function </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T11:45:05.273", "Id": "433472", "Score": "0", "body": "I meant programming languages. Sure languages using the Masculine and Feminine such as French and Arabic will need lots of modifications." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T12:21:11.170", "Id": "433478", "Score": "1", "body": "The rules for the conversion are ad-hoc, so fundamental simplification isn't likely. One obvious area of improvement is to extend the functionality so that it applies to more than three digits. A minor improvement would be to make the input `Variant` so that you could pass it either an integer variable containing a 3-digit number or a string variable and have it work in either case without a type mismatch error." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T12:42:19.717", "Id": "433479", "Score": "0", "body": "@JohnColeman Thanks John. This function is a core sub-function that will be called many times from a main function to convert vary large numbers. The main function will take care of the dirty work and will always pass a **3 digit number string** for conversion. Integer conversion happens at the higher level function. The higher function will deal with any length of number from 0 to a Decillion." } ]
[ { "body": "<h3>Code Formatting</h3>\n\n<p>What certainly could be improved is the indentation of your code for better readability:</p>\n\n<pre><code>Function Do999(ThreeDigits As String)\n 'Everything after your function header until End Function should be indented\n ' ...\nEnd Function\n</code></pre>\n\n<p>Same for further conditional code blocks:</p>\n\n<pre><code>N1 = Left(ThreeDigits, 1): N2 = Right(ThreeDigits, 2)\nIf N2 &gt; 19 Then \n t = Tens(Val(Mid(ThreeDigits, 2, 1))) &amp; dash &amp; Ones(Val(Right(ThreeDigits, 1))) \nElse \n t = Ones(N2)\nEnd If\n\nDo999 = Trim(IIf(N1 &gt; 0, Ones(N1) &amp; Tens(10), \"\") &amp; \" \" &amp; t)\n</code></pre>\n\n<h3>Function naming</h3>\n\n<p><code>Do999</code> isn't very clear / self descriptive about what the function does.<br>\n<code>Convert0UpTo999ToWords</code> might be a better choice for example.</p>\n\n<h3>Number output in words</h3>\n\n<blockquote>\n <p>The function uses the dash <code>\"-\"</code> for numbers e.g. Forty-Two.</p>\n</blockquote>\n\n<p>That's not how numbers are naturally written in words. Usually <code>42</code> would be written as <code>forty-two</code>.</p>\n\n<p>Avoid the 1st letter of the number words to be capitalized.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T13:29:21.603", "Id": "433488", "Score": "0", "body": "Thanks. Please check this \"Names of numbers in English\" in Wikipedia. Which says: When writing other numbers between 21 and 99, you must use a hyphen (-).\n\n21: twenty-one\n29: twenty-nine\n64: sixty-four\n99: ninety-nine" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T13:33:35.683", "Id": "433489", "Score": "0", "body": "@MohsenAlyafei OK, the dash seems to be common according this WP article. The capitalized 1st letters not though. I've reflected that in my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T13:37:24.213", "Id": "433491", "Score": "0", "body": "Agree. Capitalised 1st letter is not always common, unless sometimes the number is part of a currency conversion, where some accountants prefer it." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T12:59:38.410", "Id": "223619", "ParentId": "223615", "Score": "3" } }, { "body": "<p>The word \"hundred\" doesn't belong in the <code>Tens</code> array:</p>\n\n<ul>\n<li>It is the only element in the array that starts with a space</li>\n<li>It is only accessed at one place in the code</li>\n<li>It is never accessed from the place in the code where the other elements are accessed</li>\n</ul>\n\n<p>Therefore it is better to either:</p>\n\n<ul>\n<li>Declare it as a single string variable</li>\n<li>Just use the string <code>\" hundred\"</code> literally, directly in the one place where it is needed</li>\n</ul>\n\n<p>Another strange thing is that the <code>dash</code> variable contains a dash in most cases but sometimes also contains nothing at all. In the latter case its variable name <code>dash</code> doesn't accurately describe what the variable contains. Rename it to <code>separator</code> or <code>sep</code> instead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T16:10:25.393", "Id": "433501", "Score": "0", "body": "Thanks Roland for your observations and advice. The reason I put the string \" hundred\" in the array too was because it was the only string that oddly appeared as part of the code. The var \"dash\" could also be named correctly \"hyphen\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T18:40:39.283", "Id": "433531", "Score": "1", "body": "It doesn't matter whether it's hyphen or dash. The confusing part is only when it is called that way but contains something entirely different, in this case an empty string." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T19:05:01.533", "Id": "433533", "Score": "0", "body": "True. It contains an empty string \"\". The Empty String is a valid element in concatenation operation. It is a valid string data type with zero length. It simplifies coding and exists in all programming languages. What code alternative do you suggest? Thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T19:41:28.393", "Id": "433538", "Score": "1", "body": "The empty string is great. It just shouldn't be stored in a variable whose name is `dash` or `hyphen`, since then the name of the variable does not match what the variable contains." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T19:51:53.357", "Id": "433544", "Score": "0", "body": "I did in fact change the var name to \"Separator\" to avoid confusion as suggested by another commentor above. Please see below updates." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-14T10:45:39.700", "Id": "434704", "Score": "0", "body": "the following article uses this function: https://codereview.stackexchange.com/questions/224027/simple-number-to-words-using-a-single-loop-string-triplets-in-vba?noredirect=1&lq=1" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T15:18:19.433", "Id": "223624", "ParentId": "223615", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T11:28:35.420", "Id": "223615", "Score": "6", "Tags": [ "vba", "numbers-to-words" ], "Title": "Very Simple Spell (Number to Words) 001 to 999 in VBA" }
223615
<p>Is there anything wrong with having a file path as an env variable and using that as-is in a require_once?</p> <pre><code>&lt;? $CONSTANTS_FILE = getenv('CONSTANTS_FILE_PATH'); require_once($CONSTANTS_FILE); echo DB_USER ?&gt; </code></pre> <p>And here is how it is set in apache:</p> <pre><code>&lt;VirtualHost *:80&gt; #ServerName #DocumentRoot SetEnv CONSTANTS_FILE_PATH /path/to/file.php # Directory &lt;/VirtualHost&gt; </code></pre> <p>Is there a better way of having variable const files included in the project source code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T16:29:46.063", "Id": "433507", "Score": "0", "body": "Probably OK. But you should show us how the environment variable is set in your Apache configuration so that we can be sure." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T17:49:25.703", "Id": "433521", "Score": "0", "body": "@200_success done" } ]
[ { "body": "<p>You are right, but there are better ways to do that.\nOne way is using dotenv. Trending way for managing configurations.</p>\n\n<p>from dotenv project:</p>\n\n<blockquote>\n <p>Storing configuration in the environment is one of the tenets of a\n twelve-factor app. Anything that is likely to change between\n deployment environments – such as database credentials or credentials\n for 3rd party services – should be extracted from the code into\n environment variables.</p>\n</blockquote>\n\n<p>So what you are doing is right, the way you are doing may not be best.</p>\n\n<p>Since you are doing require_once(), you may want to check if file exists else it would be fatal error.</p>\n\n<p>The problems I see with keeping that path in Apache:</p>\n\n<ol>\n<li>You may need to modify apache config and restart / reload Apache for your new configurations</li>\n<li>Not all developers in your team may have access to Apache config. If the config is in code itself, like .env, it would be easy for developers.</li>\n<li>Debugging would be easy with .env</li>\n<li>If you plan to unit test, mocking would be easy.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-09T07:01:15.783", "Id": "230407", "ParentId": "223625", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T15:20:45.087", "Id": "223625", "Score": "1", "Tags": [ "php", "configuration" ], "Title": "PHP/Apache - Production/staging consts file path" }
223625
<p>I've developed a fully working flash card app for kids. It has a <code>UIImageView</code> that cycles through 26 cards (abcs) via a gesture click and a music button that will play a sound for each image. Right now I have this 100% working, but the sound plays in an IF statement that has added an additional 400 lines of code.</p> <p>How I load each card into the <code>UIImageView</code> from a gesture tap:</p> <pre><code> // if the tapped view is a UIImageView then set it to imageview if (gesture.view as? UIImageView) != nil { if segControl.selectedSegmentIndex == 0 &amp;&amp; segControl2.selectedSegmentIndex == 0 { imageView.image = UIImage(named: "card\(number)") number = number % 26 + 1 } else if segControl.selectedSegmentIndex == 0 &amp;&amp; segControl2.selectedSegmentIndex == 1 { imageView.image = UIImage(named: "upper\(number)") number = number % 26 + 1 } </code></pre> <p>Music button:</p> <pre><code> if (imageView.image?.isEqual(UIImage(named: "card1")))! { do { audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: aSound)) audioPlayer.play() } catch { print("Couldn't load sound file") } } else if (imageView.image?.isEqual(UIImage(named: "card2")))! { do { audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: bSound)) audioPlayer.play() } catch { print("Couldn't load sound file") } } else if (imageView.image?.isEqual(UIImage(named: "card3")))! { do { audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: cSound)) audioPlayer.play() } catch { print("Couldn't load sound file") } } </code></pre> <p>I know I could set a sound array with the sound files in it, but how would I tie it back to the card? I can't set a tag property on an asset image, can I?</p> <p>I'm looking for a way to shorten the current code I have.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T16:53:47.507", "Id": "433512", "Score": "0", "body": "What do `aSound` and `bSound` strings look like?" } ]
[ { "body": "<p>You shouldn't determine the sound to play from the image displayed. Instead you should use the same piece of information to set both the <code>image</code> <code>name</code> and the sound <code>path</code>.</p>\n\n<p>Create a property of your <code>ViewController</code> to keep track of the card number that is being displayed:</p>\n\n<pre><code>var displayedCard = 1\n</code></pre>\n\n<p>and set it whenever you assign a new image to the imageView:</p>\n\n<pre><code>// if the tapped view is a UIImageView then set it to imageview\nif (gesture.view as? UIImageView) != nil {\n if segControl.selectedSegmentIndex == 0 &amp;&amp; segControl2.selectedSegmentIndex == 0 {\n imageView.image = UIImage(named: \"card\\(number)\")\n displayedCard = number\n number = number % 26 + 1\n }\n else if segControl.selectedSegmentIndex == 0 &amp;&amp; segControl2.selectedSegmentIndex == 1 {\n imageView.image = UIImage(named: \"upper\\(number)\")\n displayedCard = number\n number = number % 26 + 1\n }\n</code></pre>\n\n<p>Then use it to create the <code>String</code> you pass to <code>URL(fileWithPath:)</code>:</p>\n\n<pre><code>// create the soundPath using displayedCard\nlet letter = String(UnicodeScalar(96 + displayedCard)!)\nlet soundPath = Bundle.main.path(forResource: \"\\(letter)Sound.m4a\", ofType:nil)!\n\ndo { audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: soundPath))\n audioPlayer.play()\n} catch {\n print(\"Couldn't load sound file\")\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T17:53:20.477", "Id": "433522", "Score": "0", "body": "Sound strings look like this:\n```let aSound = Bundle.main.path(forResource: \"aSound.m4a\", ofType:nil)!```\n\nSo when i set the displayedcard when loading it into the imageview, how would i then tell it that aSound belongs to card1, bSound to card2...etc?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T18:05:04.047", "Id": "433524", "Score": "0", "body": "See edit. `letter` will be `a` to `z` when `displayedCard` is `1` to `26`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T18:19:43.150", "Id": "433528", "Score": "0", "body": "WOW! Worked with literally no edit. Last question, i also have number flash cards 1-10, they are set as below:\n```let num1Sound = Bundle.main.path(forResource: \"num1.m4a\", ofType:nil)!```\n\nWould i just add the displayedcard like i did for the letter cards? And then create different constants for letter and soundPath?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T18:22:26.653", "Id": "433529", "Score": "0", "body": "That's easier because we don't have to map a number to a letter. `let numSound = Bundle.main.path(forResource: \"num\\(displayedCard).m4a\", ofType:nil)!`" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T17:08:59.657", "Id": "223633", "ParentId": "223626", "Score": "2" } } ]
{ "AcceptedAnswerId": "223633", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T15:21:00.797", "Id": "223626", "Score": "2", "Tags": [ "swift", "ios", "audio", "cocoa" ], "Title": "Playing a sound depending on the currently displayed flash card image" }
223626
<p>As my answer to <a href="https://stackoverflow.com/questions/56913324/dont-take-last-record-in-linq-c-sharp">this</a> question, I came up with this solution:</p> <pre><code>static public IEnumerable&lt;T&gt; SkipLast&lt;T&gt;(this IEnumerable&lt;T&gt; data, int count) { if (data == null || count &lt; 0) yield break; Queue&lt;T&gt; queue = new Queue&lt;T&gt;(data.Take(count)); foreach (T item in data.Skip(count)) { queue.Enqueue(item); yield return queue.Dequeue(); } } </code></pre> <p>It returns all items in the set but the <code>count</code> last, but without knowing anything about the size of the data set. I think it's funny and that it's working, but a comment claims that is doesn't. Am I overlooking something?</p> <hr> <p>A version with a circular queue could be:</p> <pre><code>static public IEnumerable&lt;T&gt; SkipLast&lt;T&gt;(this IEnumerable&lt;T&gt; data, int count) { if (data == null || count &lt; 0) yield break; if (count == 0) { foreach (T item in data) yield return item; } else { T[] queue = data.Take(count).ToArray(); int index = 0; foreach (T item in data.Skip(count)) { index %= count; yield return queue[index]; queue[index] = item; index++; } } } </code></pre> <p>Performance wise they seems to be even.</p> <hr> <p>Compared to other solutions like the most obvious:</p> <pre><code>data.Reverse().Skip(count).Reverse() </code></pre> <p>It seems to be at least as fast and for very large set about twice as fast.</p> <p>Test case:</p> <pre><code> int count = 20; var data = Enumerable.Range(1, count); for (int i = 0; i &lt; count + 5; i++) { Console.WriteLine($"Skip: {i} =&gt; {(string.Join(", ", data.SkipLast1(i)))}"); } </code></pre> <p>Any comments are useful. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T16:32:16.933", "Id": "433508", "Score": "1", "body": "Ignore my delete answer. I missed one small detail. I like that version with the queue better because it doesn't require this _complex_ index manipulations and has only one loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T16:37:27.163", "Id": "433509", "Score": "0", "body": "@t3chb0t: but you have a point in that if `count`is large, the queue gets large, resulting in a large memory consumption an the overhead of copying the data." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T16:40:15.713", "Id": "433510", "Score": "1", "body": "I think it'll rarely get larger than `1` so your caching techinique with the `Queue` is very cool :-) if `count` it would get so large that it would cause memory issues then there is a much bigger issue with the application logic. Or can you think of any example when it would make sense to use `SkipLast(1_000_000)`?" } ]
[ { "body": "<blockquote>\n<pre><code>if (data == null || count &lt; 0) yield break;\n</code></pre>\n</blockquote>\n\n<p>This behaviour is somewhat consistent with <code>Take</code>, but not with <code>Skip</code>: <code>Skip</code> treats a negative values as a zero. As, indeed, does the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.skiplast?view=netstandard-2.1\" rel=\"nofollow noreferrer\"><code>SkipLast</code></a> which doesn't appear in .NET Framework.</p>\n\n<p>It should throw on a <code>null</code> argument with an <code>ArgumentNullException</code>.</p>\n\n<hr />\n\n<p>My only other real issue with the methods is that neither will work with <code>IEnumerable</code>s that can't be enumerated multiple times, and will incur overheads in any that can but have to generate the data lazily.</p>\n\n<p>I would go for the slightly more painful:</p>\n\n\n\n<pre class=\"lang-cs prettyprint-override\"><code>if (source == null)\n throw new ArgumentNullException(\"Source Enumeration may not be null\", nameof(source));\n\nif (count &lt;= 0)\n{\n foreach (T item in source)\n yield return item;\n}\nelse\n{\n bool yielding = false;\n T[] buffer = new T[count];\n int index = 0;\n\n foreach (T item in source)\n {\n if (index == count)\n {\n index = 0;\n yielding = true;\n }\n\n if (yielding)\n yield return buffer[index];\n\n buffer[index] = item;\n index++;\n }\n}\n</code></pre>\n\n<p>If I cared about performance, I might consider the following, which reduces the amount of decision making inside the loop (which might make it faster: I'd better benchmark it).</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>// just the bit inside the else\nT[] buffer = new T[count];\n\nusing (var e = source.GetEnumerator())\n{\n // initial filling of buffer\n for (int i = 0; i &lt; buffer.Length; i++)\n {\n if (!e.MoveNext())\n yield break;\n\n buffer[i] = e.Current;\n }\n\n int index = 0;\n while (e.MoveNext())\n {\n yield return buffer[index];\n buffer[index] = e.Current;\n index = (index + 1) % count;\n }\n}\n</code></pre>\n\n<hr />\n\n<blockquote>\n <p>Performance wise they seems to be even.</p>\n</blockquote>\n\n<p>That's encouraging, since <code>Queue&lt;T&gt;</code> is also implemented as a circular buffer. You'd hope that the array based version would be a bit lighter, but may consume more memory is <code>Count &gt; data.Count()</code>.</p>\n\n<p>Having benchmarked your two proposals, my two proposals, and the .NET Core <code>SkipLast</code> (didn't include the <code>Reverse</code> based method), it seems the fastest methods are that built into .NET Core (hurray) and my last one, but the difference between test instance (with different data lengths and skip counts) is great. Unfortunately, I messed up and didn't run a third of the .NET Core tests, so the saga of incompetence on my part continues. The code and data can be found in a <a href=\"https://gist.github.com/VisualMelon/1ab841a5b9204517675236e6645c537d\" rel=\"nofollow noreferrer\">gist</a>. The only real conclusion I would want to draw from this data (aside from 'use the BCL method if you can') is that your first method is consistently the slowest when the input array isn't empty <em>in these tests on my machine with it's current workload</em>. The difference is jolly significant, with your first method requiring twice as much time as others in some cases. <em>Why</em> the methods have different performance is less than clear.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T05:07:04.183", "Id": "433589", "Score": "0", "body": "Interesting new optimized versions and tests. I only tested performance on a couple of counts and length and it didn't show much differences. `GetEnumerator()` has often showed to be much faster than a `foreach` loop, which IMO is strange, because the latter calls `GetEnumerator()`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T22:04:29.317", "Id": "223647", "ParentId": "223627", "Score": "3" } }, { "body": "<p>There are 2 cases for which both your and VisualMelon's implementation can be improved:</p>\n\n<ul>\n<li>If <code>count</code> is less than or equal to 0, then you can return <code>source</code> directly. This speeds up iteration by removing an unnecessary intermediate step. For this to work, the yielding part of the method has to be moved into another method, but that's easy with local functions.</li>\n<li>If <code>source is ICollection&lt;T&gt; collection</code>, then you can return <code>source.Take(collection.Count - count)</code>, which is faster and uses less memory because it doesn't need to buffer anything. The higher <code>count</code> is, the more of a difference this makes.</li>\n</ul>\n\n<p>The first of these is probably not a very useful edge-case, so it might not be worth the extra code, but I would definitely include the second optimization.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T00:53:03.763", "Id": "433573", "Score": "0", "body": "+1 the BCL implementation does a variation on the former - and the different appears to be measureable - but doesn't for the latter, and there would all benefit from some type specialisation. I suspect I'm going to end up spending a lot of time running benchmarks..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T04:26:36.353", "Id": "433588", "Score": "0", "body": "I have actually made a version after my post that is implemented as your first suggestion." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T00:37:02.440", "Id": "223652", "ParentId": "223627", "Score": "5" } }, { "body": "<p>Takning all considerations by VisualMelon and Pieter Witvoet into account a solution could now be:</p>\n\n<pre><code>static public IEnumerable&lt;T&gt; SkipLast&lt;T&gt;(this IEnumerable&lt;T&gt; data, int count)\n{\n if (data == null) throw new ArgumentNullException(nameof(data));\n if (count &lt;= 0) return data;\n\n if (data is ICollection&lt;T&gt; collection)\n return collection.Take(collection.Count - count);\n\n IEnumerable&lt;T&gt; Skipper()\n {\n using (var enumer = data.GetEnumerator())\n {\n T[] queue = new T[count];\n int index = 0;\n\n while (index &lt; count &amp;&amp; enumer.MoveNext())\n queue[index++] = enumer.Current;\n\n index = -1;\n while (enumer.MoveNext())\n {\n index = (index + 1) % count;\n yield return queue[index];\n queue[index] = enumer.Current;\n }\n }\n }\n\n return Skipper();\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Update</strong></p>\n\n<p>In order to optimize when the data set is empty, a <code>MoveNext()</code> call could be made before the allocation of a potentially large queue array:</p>\n\n<pre><code>static public IEnumerable&lt;T&gt; SkipLast2&lt;T&gt;(this IEnumerable&lt;T&gt; data, int count)\n{\n if (data == null) throw new ArgumentNullException(nameof(data));\n if (count &lt;= 0) return data;\n\n if (data is ICollection&lt;T&gt; collection)\n return collection.Take(collection.Count - count);\n\n return Skipper();\n\n IEnumerable&lt;T&gt; Skipper()\n {\n using (var enumer = data.GetEnumerator())\n {\n if (!enumer.MoveNext())\n yield break;\n\n T[] queue = new T[count];\n queue[0] = enumer.Current;\n int index = 1;\n\n while (index &lt; count &amp;&amp; enumer.MoveNext())\n queue[index++] = enumer.Current;\n\n index = -1;\n while (enumer.MoveNext())\n {\n index = (index + 1) % count;\n yield return queue[index];\n queue[index] = enumer.Current;\n }\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T13:08:54.683", "Id": "433636", "Score": "1", "body": "Same benchmark with this (7) and a slight variation (8): [gist](https://gist.github.com/VisualMelon/dfc9b49807ba5e467964fd1dd0af8274). This method consistently out-performs the BCL version, except in the case where the source is empty but the count is high (it uses a `Queue`, so doesn't have to allocate the big array), and performs similarly when the count is otherwise zero with the `Range`. (There is some serious between-test variation, presumably because due to the variable background loading on my machine)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T18:45:41.903", "Id": "433667", "Score": "1", "body": "I'd be cool if `Take` had this behaviour when you specify a negative count." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T05:44:43.257", "Id": "223655", "ParentId": "223627", "Score": "4" } } ]
{ "AcceptedAnswerId": "223647", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T15:24:33.553", "Id": "223627", "Score": "5", "Tags": [ "c#", "comparative-review", "linq", "iterator", "extension-methods" ], "Title": "SkipLast of an IEnumerable<T> - Linq Extension" }
223627
<p>I am working on a console renderer and I want a heap-allocated dynamic texture class. Since I am quite new to C++, I just want to check the memory management, if I destroy all pointers correctly etc.</p> <pre><code>class Texture { private : char** pixels; // heap allocated int width, height; public : Texture(int width, int height, const char* texture) { this-&gt;width = width; this-&gt;height = height; pixels = new char*[width]; for (int x = 0; x &lt; width; x++) { pixels[x] = new char[height]; for (int y = 0; y &lt; height; y++) pixels[x][y] = texture[y*width+x]; } } Texture(int width, int height, char fill) { this-&gt;width = width; this-&gt;height = height; pixels = new char*[width]; for (int x = 0; x &lt; width; x++) { pixels[x] = new char[height]; for (int y = 0; y &lt; height; y++) pixels[x][y] = fill; } } ~Texture() { for (int x = 0; x &lt; width; x++) delete[] pixels[x]; delete pixels; } Texture getSubTexture(int x, int y, int width, int height) { Texture newtex(width, height, '?'); for (int xx = 0; xx &lt; width; xx++) for (int yy = 0; yy &lt; height; yy++) { newtex.setPixel(xx, yy, getPixel(x+xx, y+yy)); } return newtex; } void setPixel(int x, int y, char c) { pixels[x][y] = c; } char getPixel(int x, int y) { return pixels[x][y]; } int getWidth() { return width; } int getHeight() { return height; } }; </code></pre>
[]
[ { "body": "<p><code>getHeight</code> and <code>getWidth</code> should be const.</p>\n\n<pre><code>int getWidth() const { return width; }\nint getHeight() const { return height; }\n</code></pre>\n\n<p>Your destructor does not properly delete the <code>pixels</code> pointer. Since you allocate it with <code>new[]</code> you need to use <code>delete[]</code>.</p>\n\n<pre><code>delete [] pixels;\n</code></pre>\n\n<p>You're storing your textures in column-major order. Depending on how you access them, this can cause performance issues with caching. For example, in the constructor, when you copy in the initial texture values you jump thru memory (one byte every <code>width</code> bytes) rather than reading it sequentially (where <code>x</code> would be the inner loop).</p>\n\n<p>Then there's the inevitable question of why you're using manual memory management, rather than using <code>vector</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T17:45:12.710", "Id": "433519", "Score": "0", "body": "I thought vector is more memory demanding and this is a more lightweight approach." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T17:48:49.933", "Id": "433520", "Score": "1", "body": "@Jacob It might use a few more bytes of memory to keep track of the size of the vector and how big of a buffer is allocated, but it is easier, safer, and more concise to use. With a proper `vector` set up, your \"fill\" constructor body can be reduced to three \"lines\". You'd then be able to use the default destructor. And I didn't even mention the copy and move constructors and assignment operators." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T16:43:42.873", "Id": "223632", "ParentId": "223631", "Score": "1" } } ]
{ "AcceptedAnswerId": "223632", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T16:33:50.743", "Id": "223631", "Score": "2", "Tags": [ "c++", "beginner", "array", "memory-management", "pointers" ], "Title": "A heap-allocated texture class for a console renderer" }
223631
<p>I just learned about Test Driven Development on a podcast yesterday. So I decided to try it out today by writing a roman numerals to integer converter (per their suggestion). I've never written Unit Tests before today.</p> <h1>My process</h1> <p>I wrote the test class with the <code>runAll()</code> function, then I started writing my tests one at a time, from top to bottom, if you look at the RomanTest class below.</p> <p>Between each chunk, I significantly changed the <code>intVal()</code> method of <code>RMC</code>. </p> <ul> <li><code>testI</code> through <code>testM</code>, I merely checked hard-coded values in an array </li> <li><code>testII</code> through <code>testXVII</code>, I looped over all the chars and added values together </li> <li><code>testIV</code> through <code>testIIX</code> required a conditional modification to <code>intVal()</code> </li> <li><code>testXXXIX</code> (to the end) took a complete rewrite of <code>intVal()</code> leading to the code posted below</li> </ul> <p>Before writing the next test, I always confirmed the previous test was passing. Except, I wrote <code>testL</code>-<code>testM</code> all at once as those were VERY simple after getting <code>testI-textX</code> working.</p> <p>At points, when re-writing <code>intVal</code>, my older tests broke. Then I would get all my tests passing again before continuing to the next test.</p> <p>I never altered any previous tests when trying to get the new tests passing.</p> <h1>My questions:</h1> <ol> <li>Is this a good work flow for TDD? If not, what could I improve? </li> <li>Did I run enough tests? Do I need to write more? </li> <li>Is it okay that, during <code>intVal()</code> re-writes, previous tests broke? (considering I got them all passing again before moving to the next test)</li> </ol> <p>I am asking for a review of my TDD code &amp; process.</p> <pre class="lang-php prettyprint-override"><code>class RomanTest { public function runAll(){ echo '&lt;pre&gt;'."\n"; $methods = get_class_methods($this); foreach ($methods as $method){ if ($method=='runAll')continue; $mo = $method; while (strlen($mo)&lt;15){ $mo .='-'; } echo "&lt;b&gt;{$mo}:&lt;/b&gt; "; echo $this-&gt;$method() ? 'true' : 'false'; echo "&lt;br&gt;\n"; } echo "\n&lt;/pre&gt;"; } public function testI(){ $rmc = new RMC("I"); if ($rmc-&gt;intVal()===1){ return TRUE; } return FALSE; } public function testV(){ $rmc = new RMC("V"); if ($rmc-&gt;intVal()===5){ return TRUE; } return FALSE; } public function testX(){ $rmc = new RMC("X"); if ($rmc-&gt;intVal()===10)return TRUE; else return FALSE; } public function testL(){ $rmc = new RMC("L"); if ($rmc-&gt;intVal()===50)return TRUE; return FALSE; } public function testC(){ $rmc = new RMC("C"); if ($rmc-&gt;intVal()===100)return TRUE; return FALSE; } public function testD(){ $rmc = new RMC("D"); if ($rmc-&gt;intVal()===500)return TRUE; return FALSE; } public function testM(){ $rmc = new RMC("M"); if ($rmc-&gt;intVal()===1000)return TRUE; return FALSE; } public function testII(){ $rmc = new RMC("II"); if ($rmc-&gt;intVal()===2)return TRUE; return FALSE; } public function testIII(){ $rmc = new RMC("III"); if ($rmc-&gt;intVal()===3)return TRUE; return FALSE; } public function testVI(){ $rmc = new RMC("VI"); if ($rmc-&gt;intVal()===6)return TRUE; return FALSE; } public function testVII(){ $rmc = new RMC("VII"); if ($rmc-&gt;intVal()===7)return TRUE; return FALSE; } public function testXVII(){ $rmc = new RMC("XVII"); if ($rmc-&gt;intVal()===17)return TRUE; return FALSE; } public function testIV(){ $rmc = new RMC("IV"); return ($rmc-&gt;intVal()===4); } public function testIIV(){ $rmc = new RMC("IIV"); return ($rmc-&gt;intVal()===3); } public function testIIX(){ $rmc = new RMC("IIX"); return ($rmc-&gt;intVal()===8); } public function testXXXIX(){ $rmc = new RMC("XXXIX"); return ($rmc-&gt;intVal()===39); } public function testXXXIIX(){ $rmc = new RMC("XXXIIX"); return ($rmc-&gt;intVal()===38); } public function testMMMCMXCIX(){ return (new RMC("MMMCMXCIX"))-&gt;intVal()===3999; } public function testMLXVI(){ return (new RMC("MLXVI"))-&gt;intVal()===1066; } } </code></pre> <pre class="lang-php prettyprint-override"><code>class RMC { private $numerals; private $vals = [ 'I' =&gt; 1, 'V' =&gt; 5, 'X' =&gt; 10, 'L' =&gt; 50, 'C' =&gt; 100, 'D' =&gt; 500, 'M' =&gt; 1000, ]; public function __construct($numerals){ $this-&gt;numerals = $numerals; } public function intVal(){ $tot = 0; $lastTot = 0; $lastVal = 0; foreach (array_reverse(str_split($this-&gt;numerals)) as $nml){ $value = $this-&gt;vals[$nml]; if ($lastVal&lt;=$value){ $tot +=$value; $lastVal = $value; } else if ($lastVal&gt;$value){ $tot -= $value; } $lastTot = $tot; } return $tot; } } </code></pre> <p>And to run it:</p> <pre class="lang-php prettyprint-override"><code>$test = new RomanTest(); $test-&gt;runAll(); </code></pre>
[]
[ { "body": "<p>It is a good thing you completely seperated your testing code from the code you're testing.</p>\n\n<p>All your tests have the same basic structure, so why not create an array containing: </p>\n\n<pre><code>[1 =&gt; \"I\",\n 2 =&gt; \"II\",\n 3 =&gt; \"III\",\n 4 =&gt; \"IV\",\n 5 =&gt; \"V\",\n ............];\n</code></pre>\n\n<p>And use that array to run your tests. You could even use the same array to test a function that does the inverse.</p>\n\n<p>Moreso, having the inverse function is almost a must. It would further simplify the testing, since you can convert decimals to Roman numerals and back again. That way you don't need an array at all to do many tests.</p>\n\n<p>Please pay attention to the names you choose. To me <code>RMC</code> doesn't mean much. If you encounter this class name two years from now, will you immediately know what it means? I don't think so. Why not give it a proper name like: <code>RomanNumerals</code>? This class could have two methods: <code>toRoman()</code> and <code>toDecimal()</code>. The <code>intVal()</code> method name is confusing because there is already an <a href=\"https://www.php.net/manual/en/function.intval.php\" rel=\"nofollow noreferrer\">intval()</a> function which does something else.</p>\n\n<h1>Your questions</h1>\n\n<blockquote>\n <p>Is this a good work flow for TDD? If not, what could I improve?</p>\n</blockquote>\n\n<p>You understand the basic principle, however I think it would have been possible to write all the tests before writing the real code. This is also often done in real life: The tests are known before the code is written. <em>The writing of the code is driven by the tests.</em> Or, to put it in another way: If you don't know what you're going to test, then how on earth could you write any code?</p>\n\n<blockquote>\n <p>Did I run enough tests? Do I need to write more?</p>\n</blockquote>\n\n<p>As I illustrated before, by writing the inverse function as well, you can do thousands of tests, without having to be very selective about it.</p>\n\n<blockquote>\n <p>Is it okay that, during intVal() re-writes, previous tests broke? </p>\n</blockquote>\n\n<p>Yes, that's fine. That's the whole idea behind test-driver-development: The tests tell you what's wrong.</p>\n\n<p>Remember that there are frameworks for writing tests. It is clearly possible to work without them, but why reinvent the wheel again? See, for instance: <a href=\"https://phpunit.de\" rel=\"nofollow noreferrer\">PHPUnit</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T20:30:16.903", "Id": "433548", "Score": "0", "body": "Thank you for your feedback. I agree about `RMC`. Good points about `toDecimal()` instead of `intVal()`. Writing the inverse would make a lot of sense, and indeed would make it easy to run MANY tests. I'll give PHPUnit a go. Didn't feel like `composer`ing it in for such a simple use case. But I'm sure it (or something similar) is what I should be using going forward. IDK why `RMC`. I was going for `RomanNumeralsConverter` and just wanted to save typing. So it should have been `RNC` lol. I could have done `use RomanNumeralsConverter as RNC;` to have the shorthand." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T20:35:41.647", "Id": "433549", "Score": "0", "body": "So do you think it is, generally, better to write ALL the tests before writing any code? I personally kind of like the incremental fashion of writing one test, failing, writing code to pass the test, then writing the next test, failing, coding, passing, repeat. Breaks the project down into smaller chunks of just building one tiny piece at a time. But I suppose I could write all the tests & then still focus on one test at a time if I need that bite-sized approach." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T20:36:12.210", "Id": "433550", "Score": "0", "body": "I'm rambling a bit because I don't necessarily know what I'm talking about lol" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T21:55:11.997", "Id": "433557", "Score": "1", "body": "Your incremental method clearly works, and it is still test-driven. For bigger projects it is probably the way to do it." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T20:12:49.933", "Id": "223645", "ParentId": "223635", "Score": "3" } } ]
{ "AcceptedAnswerId": "223645", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T17:17:56.047", "Id": "223635", "Score": "1", "Tags": [ "php", "unit-testing" ], "Title": "Test Driven Development Roman Numerals php" }
223635
<p>I'm creating my first real life Nodejs project. I've created some files and all work, but I'm not satisfied about what my files look likes. It's unreadeble.</p> <p>For example, I work of a file to manage JWT sessions and RSA keys.</p> <p>For this file, I need two function to load and save the RSA private key.</p> <p><a href="https://github.com/felixge/node-style-guide#requires-at-top" rel="nofollow noreferrer">This Node.js style guide</a> says to put <code>require</code> at the top of documents.</p> <pre><code>'use strict'; const logger = require('./logger')(module.filename); const NodeRSA = require('node-rsa'); const jwt = require('jsonwebtoken'); const fs = require('fs'); const loadKeyFromDisk = (path) =&gt; new Promise((resolve, reject) =&gt; fs.readFile(path, 'utf-8', (error, data) =&gt; { if (error) { reject(error); return; } resolve(data); })); const saveKeyToDisk = (path, key) =&gt; new Promise((resolve, reject) =&gt; fs.writeFile(path, key, 'utf-8', (error) =&gt; { if (error) { reject(error); return; } resolve(); })); [...] modules.exports = {...}; </code></pre> <p>But, I also learn to put variables into small context as possible </p> <pre><code>'use strict'; const logger = require('./logger')(module.filename); const NodeRSA = require('node-rsa'); const jwt = require('jsonwebtoken'); const { loadKeyFromDisk, saveKeyToDisk } = (() =&gt; { const fs = require('fs'); return { loadKeyFromDisk: (path) =&gt; new Promise((resolve, reject) =&gt; fs.readFile(path, 'utf-8', (error, data) =&gt; { if (error) { reject(error); return; } resolve(data); })), saveKeyToDisk: (path, key) =&gt; new Promise((resolve, reject) =&gt; fs.writeFile(path, key, 'utf-8', (error) =&gt; { if (error) { reject(error); return; } resolve(); })) }; })(); [...] modules.exports = {...}; </code></pre> <p>I've also tried some others style, but I think it's don't look like professionnal and clean code...</p> <pre><code>'use strict'; const logger = require('./logger')(module.filename); const NodeRSA = require('node-rsa'); const jwt = require('jsonwebtoken'); const fs = require('fs'); const loadKeyFromDisk = (path) =&gt; { return new Promise((resolve, reject) =&gt; { fs.readFile(path, 'utf-8', (error, data) =&gt; { if (error) { reject(error); return; } resolve(data); }); }); }; const saveKeyToDisk = (path, key) =&gt; { return new Promise((resolve, reject) =&gt; { fs.writeFile(path, key, 'utf-8', (error) =&gt; { if (error) { reject(error); return; } resolve(); }); }); }; [...] modules.exports = {...}; </code></pre> <p>Did you have somes advices or idea to improve my coding style?</p> <p>My complete code Here : <a href="https://pastebin.com/kXvxNd2k" rel="nofollow noreferrer">https://pastebin.com/kXvxNd2k</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T20:59:41.470", "Id": "433551", "Score": "0", "body": "Thanks 200_success but I don't agree with the new title. The code work and I don't need help to correct It. Question is only about coding style." } ]
[ { "body": "<h1><code>require</code> style</h1>\n\n<p>I (and most of the Node developers I've worked with) prefer the style where <code>require</code> is put on top. As stated in the <a href=\"https://github.com/felixge/node-style-guide#requires-at-top\" rel=\"nofollow noreferrer\">guide you linked</a>, it gives a clearer overview of what are dependencies of the module/file you're writing. No one likes to see that if some condition is successful, then a new module will be loaded. It's just unnatural.</p>\n\n<p>On the other hand, you shouldn't look at <code>const foo = require('bar')</code> as just another variable assignment and treat it as such when you're writing Node or any other JS code. Calling require function will load a file (<strong>if not previously loaded</strong>, <a href=\"http://fredkschott.com/post/2014/06/require-and-the-module-system/\" rel=\"nofollow noreferrer\">read more here</a>) and make its exported object available through the variable in the file you're writing. This same thing in some other language like C/C++ would be expressed as <code>#include &lt;foo&gt;</code>, which exposes the whole file to another file.</p>\n\n<h1>Other things I've noted</h1>\n\n<h2>Usage of <code>fs</code> module</h2>\n\n<p>I see that you have helper functions that wrap <code>fs.readFile</code> and <code>fs.writeFile</code> in promises. I'm not sure if you are aware of 2 things:</p>\n\n<ol>\n<li>There is a <a href=\"https://nodejs.org/docs/latest-v10.x/api/util.html#util_util_promisify_original\" rel=\"nofollow noreferrer\">promisify</a> method which can do this for you.</li>\n<li>There already exist <a href=\"https://nodejs.org/docs/latest-v10.x/api/fs.html#fs_fs_readfilesync_path_options\" rel=\"nofollow noreferrer\">promisifed versions</a> of this functions.</li>\n</ol>\n\n<p>My suggestion is to use <code>fs.readFileSync</code> and <code>fs.writeFileSync</code> instead of wrapping them yourself.</p>\n\n<h2>Line 55</h2>\n\n<p>I'm not sure what was your intention here, but you've just called a function which returns a promise without waiting for the promise to be resolved. Since you're writing to the disk, this operation might not finish once a function from your returned object gets called. I'd just add <code>await</code> here.</p>\n\n<h1>Line 73</h1>\n\n<p>First, add a space between the <code>)</code> and <code>?</code> to be consistent with the style you have for <code>:</code> and stuff around it.\nSecond, break that long condition into either a function, or to a several variables. I'd personally go here with functions: </p>\n\n<pre><code>const notInvalidated = (invalidations, payload) =&gt; !invalidations[payload.userUuid] || payload.invalidationCounter === invalidations[payload.userUuid]\nconst hasValidIat = (invalidBefore, payload) =&gt; payload.iat &gt;= invalidBefore\n</code></pre>\n\n<p>And then your condition could be written as:</p>\n\n<pre><code>notInvalidated(invalidationByUserUUID, payload) &amp;&amp; hasValidIat(invalidBefore, payload) ? payload : false\n</code></pre>\n\n<p>Still long, but more readable.</p>\n\n<h2><code>module.exports</code> mess</h2>\n\n<p>My personal preference is to have <code>module.exports</code> either export a function or an object, so make it as short as possible. But from your code on pastebin, it looks like your core logic is put there. For me, this is unreadable and I would look how to refactor this into something which will return either a single function or just a simple object.\nIn your case, I'd first move that function to a new named function, something like this:</p>\n\n<pre><code>const myJwt = async (keyPath) =&gt; { /* the rest */ }\n\nmodule.exports = myJwt\n</code></pre>\n\n<p>From there, I'd move the functions in the object you are returning to the file level:</p>\n\n<pre><code>const generateNewKeyPair = async () =&gt; { /* ... */ }\n/* also for sign, verify and invalidateOldUserToken */\n\nconst myJwt = async (keyPaht) =&gt; {\n /* whatever goes here */\n return {\n generateNewKeyPair,\n sign,\n verify,\n invalidateOldUserToken,\n }\n}\n\nmodule.exports = myJwt\n</code></pre>\n\n<p>This refactoring will be a bit tricky, because you have these two variables <code>invalidationByUserUUID</code> and <code>invalidBefore</code> which should be shared with the functions that I suggested extracting. You should maybe consider to wrap this in a class and return the class instead of a function. Either that, or you'll have to pass <code>invalidationByUserUUID</code> and <code>invalidBefore</code> with every function call.</p>\n\n<hr>\n\n<p>Hope my comments make sense. I didn't do a whole code refactoring since I'm not 100% sure what you wanted to achieve, but if needed, I can give it a try.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T20:29:46.493", "Id": "433547", "Score": "0", "body": "Thanks for your help and comments. That's make sense for me :D\nI've move the init code and I temporary make this bin : https://pastebin.com/9N6Dtgib . It's more easy to understand.\n\nI will think about class, but I don't see what it will change..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T08:15:07.893", "Id": "433602", "Score": "0", "body": "I finally redid the code. With a class ( https://pastebin.com/fa2RnbkJ ), but I don't like the way I have to manage private. And without a real class (https://pastebin.com/5671MgYC )." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T10:57:39.200", "Id": "433617", "Score": "0", "body": "Yes, private is tricky in JS... At least for now... Anyhow, I'm glad that you find this easier to understand. I can also take a look later today or tomorrow at one of the links you've posted and edit my response to address the code there (or you can create a new question for that). I've already noticed some minor style issues, like not using curly brackets for one line `else`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T18:57:37.190", "Id": "223640", "ParentId": "223637", "Score": "1" } } ]
{ "AcceptedAnswerId": "223640", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T17:35:30.900", "Id": "223637", "Score": "2", "Tags": [ "javascript", "node.js", "comparative-review", "file" ], "Title": "Nodejs functions to load and save RSA keys" }
223637
<p>I am solving the problems for Advent of Code 2016 to learn Rust programming. The prompt for the first problem can be summarized:</p> <p>I start at position 0,0 on a regular grid. I am given a set of directions to get to a location. I can only travel in "steps" on this grid, and I am only given directions in the form (e.g.):</p> <pre class="lang-none prettyprint-override"><code>R5, L2, L1, R1, R3, R3, L3, R3, R4, L2, R4, L4, R4 </code></pre> <p>Where the first character is the direction to turn right or left and the following number is the number of steps to take. I need to compute the Manhattan distance between my starting point and the ending point.</p> <p>The instructions are saved in a text file called "2016-1.txt".</p> <pre><code>use std::fs; struct Pos { facing: char, x: i32, y: i32, } fn split_dir(dir_str: &amp;str) -&gt; Vec&lt;&amp;str&gt; { dir_str.split(", ").collect() } fn update_facing(rel_dir: &amp;char, face_char: &amp;char) -&gt; char { if *rel_dir == 'L' { match face_char { 'N' =&gt; 'W', 'S' =&gt; 'E', 'E' =&gt; 'N', 'W' =&gt; 'S', _ =&gt; 'I', // Is there a better way to handle the catch-all? } } else { match face_char { 'N' =&gt; 'E', 'S' =&gt; 'W', 'E' =&gt; 'S', 'W' =&gt; 'N', _ =&gt; 'I', } } } fn update_x(pos_x: i32, face_char: char, move_num: i32) -&gt; i32 { match face_char { 'E' =&gt; pos_x + move_num, 'W' =&gt; pos_x - move_num, _ =&gt; pos_x } } fn update_y(pos_y: i32, face_char: char, move_num: &amp;i32) -&gt; i32 { match face_char { 'N' =&gt; pos_y + move_num, 'S' =&gt; pos_y - move_num, _ =&gt; pos_y } } fn get_manhattan_dist(pos_x: i32, pos_y: i32, origin_x: i32, origin_y: i32) -&gt; i32 { (pos_x - origin_x).abs() + (pos_y - origin_y).abs() } fn main() { let s = fs::read_to_string("2016-1.txt") .expect("Failed to read file."); let split: Vec&lt;&amp;str&gt; = split_dir(&amp;s); let mut pos: Pos = Pos {x: 0, y: 0, facing: 'N'}; for inst in split { // Update direction let rel_dir = inst.chars().nth(0).unwrap(); // Get first character of the instruction pos.facing = update_facing(&amp;rel_dir, &amp;pos.facing); // Update position let move_num = &amp;inst[1..].parse::&lt;i32&gt;().unwrap(); pos.x = update_x(pos.x, pos.facing, *move_num); pos.y = update_y(pos.y, pos.facing, &amp;move_num); } let dist = get_manhattan_dist(pos.x, pos.y, 0, 0); println!("{}", dist); } </code></pre> <p>I am particularly interested in error handling. Particularly in the <code>update_facing</code> function. This is my first Rust program, so all advice is warranted as well.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T19:47:36.840", "Id": "433542", "Score": "0", "body": "*am particularly interested in error handling* — what do you want to *happen* on errors?" } ]
[ { "body": "<p>Your code looks more complicated than necessary for this task.</p>\n\n<p>The first thing I noticed was the directions N, E, S, W. There is no need to explicitly name them. It is simpler to just define a direction as a 2-dimensional tuple:</p>\n\n<pre><code>struct Direction {\n dx: i32,\n dy: i32\n}\n</code></pre>\n\n<p>That's the essence of a direction. As the next step, I remembered that rotating such a direction by 90 degrees is quite simple. It just involves swapping the coordinates and reversing one of them. To get these right, I manually checked all the combinations after writing this code:</p>\n\n<pre><code>impl Direction {\n fn left(&amp;self) -&gt; Direction { Direction { dx: self.dy, dy: -self.dx } }\n fn right(&amp;self) -&gt; Direction { Direction { dx: -self.dy, dy: self.dx } }\n}\n</code></pre>\n\n<p>By these simple definitions, I avoided dealing with N, E, S, W at all.</p>\n\n<p>When I tested the program using the example you provided, my IDE added a trailing newline to the file, as is usual for text files. Then the program crashed because it could not parse an empty string. Therefore I changed <code>split_dir(&amp;s)</code> into <code>split_dir(s.trim())</code>, and it worked.</p>\n\n<p>To understand the main program, I separated it into the part that deals with input and output, and the processing part in between. To do this, I defined this function:</p>\n\n<pre><code>fn manhattan_distance(s: &amp;str) -&gt; i32 {\n ...\n}\n</code></pre>\n\n<p>I inlined the <code>split_dir</code>, <code>update_x</code>, <code>update_y</code> and <code>get_manhattan_dist</code> functions, and in the end my code became:</p>\n\n<pre><code>use std::fs;\n\nstruct Pos {\n x: i32,\n y: i32,\n dir: Direction,\n}\n\nstruct Direction {\n dx: i32,\n dy: i32,\n}\n\nimpl Direction {\n fn left(&amp;self) -&gt; Direction {\n Direction {\n dx: self.dy,\n dy: -self.dx,\n }\n }\n\n fn right(&amp;self) -&gt; Direction {\n Direction {\n dx: -self.dy,\n dy: self.dx,\n }\n }\n}\n\nfn manhattan_distance(s: &amp;str) -&gt; i32 {\n let steps = s.trim().split(\", \");\n\n let mut pos = Pos {\n x: 0,\n y: 0,\n dir: Direction { dx: 0, dy: -1 },\n };\n\n for step in steps {\n let (turn, dist) = step.split_at(1);\n\n // Update direction\n pos.dir = match turn {\n \"L\" =&gt; pos.dir.left(),\n \"R\" =&gt; pos.dir.right(),\n _ =&gt; panic!(\"invalid turn {} in step {}\", turn, step),\n };\n\n // Update position\n let dist = dist.parse::&lt;i32&gt;().unwrap();\n pos.x += pos.dir.dx * dist;\n pos.y += pos.dir.dy * dist;\n }\n\n pos.x.abs() + pos.y.abs()\n}\n\nfn main() {\n let s = fs::read_to_string(\"2016-1.txt\").expect(\"Failed to read file.\");\n\n println!(\"{}\", manhattan_distance(&amp;s));\n}\n</code></pre>\n\n<p>What's left now are some automatic tests. The function <code>manhattan_distance</code> is well-prepared for that since it has no side-effects, does not need any input or output, gets its parameter as a simple string and just returns its result.</p>\n\n<p>And here are some example tests. You should add some more to explore other interesting cases, like crossing the x or y axis. The current tests might also pass if you omit the calls to <code>abs</code>.</p>\n\n<pre><code>#[cfg(test)]\nmod tests {\n use crate::manhattan_distance;\n\n #[test]\n fn manhattan_distance_example() {\n assert_eq!(11, manhattan_distance(\"R5, L2, L1, R1, R3, R3, L3, R3, R4, L2, R4, L4, R4\"))\n }\n\n #[test]\n fn manhattan_distance_empty() {\n assert_eq!(0, manhattan_distance(\" \\t\\n\"))\n }\n\n #[test]\n fn manhattan_distance_simple() {\n assert_eq!(13, manhattan_distance(\"R8, L5\"))\n }\n\n #[test]\n fn manhattan_distance_rectangle() {\n assert_eq!(0, manhattan_distance(\"R8, L5, L8, L5\"))\n }\n}\n</code></pre>\n\n<p>Your code is a good working base, it was just longer than necessary. I also changed most of the variable names to be a little more precise and easier to grasp for a casual reader of the code. For example, since the task talks about \"steps\", it's only natural to name the corresponding variables in the code also \"steps\" and \"step\".</p>\n\n<p>Since this is my first real program in Rust as well, I don't know what the really idiomatic Rust code looks like, I hope I could improve the code nevertheless.</p>\n\n<p>To check whether I made any typical beginner's mistakes, I ran <code>cargo-clippy</code>, and I didn't get any complaints.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T19:00:16.987", "Id": "434911", "Score": "2", "body": "I think one more thing that'd help with your new `manhattan_distance` function is making a struct named something like `Step` with the `turn` and `dist` fields. Then `manhattan_distance` would take in a `impl Iterator<Type=Step>` instead of a `&str`. This way you separate the input parsing from the algorithm logic, so it can handle input formatted in a variety of ways. Then you could do something like `s.trim().split(\", \").map(Step::from_str)` when passing the input to the function." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T19:38:00.307", "Id": "223642", "ParentId": "223639", "Score": "4" } }, { "body": "<p>I concur with Roland's comments, but wanted to add this: </p>\n\n<pre><code> match face_char {\n 'N' =&gt; 'W',\n 'S' =&gt; 'E',\n 'E' =&gt; 'N',\n 'W' =&gt; 'S',\n _ =&gt; 'I', // Is there a better way to handle the catch-all?\n }\n</code></pre>\n\n<p>Rust has a macro for this scenario: <code>unreachable!()</code>. It is a standard way to indicate that a certain case should never happen in practice.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T01:07:38.540", "Id": "223707", "ParentId": "223639", "Score": "3" } } ]
{ "AcceptedAnswerId": "223642", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T17:37:49.613", "Id": "223639", "Score": "5", "Tags": [ "programming-challenge", "rust", "taxicab-geometry" ], "Title": "Compute Manhattan distance from origin given a set of left-right-step directions" }
223639
<p>I like to collect images for my desktop background, but the problem is sometimes the image names don't represent what the image is. I decided to write a script that reads a text file that contains the source of the images (folders stored in the Pictures directory under the Userprofile (windows)) to be renamed.</p> <p>The full path to the folder listed below are: </p> <pre><code>C:\Users\Kiska\Pictures\Landscape C:\Users\Kiska\Pictures\Batman </code></pre> <p>Rather than have the user type the useprofile path every time they want to add a folder to the list, the <code>Folder.py</code> class does it for them, they just provide the sub directory to be processed. </p> <p><strong>Source (.txt)</strong>:</p> <pre><code>Landscape Batman </code></pre> <p><strong>PathUtilities.py:</strong></p> <pre><code>def verify_parent_directory(parent: str) -&gt; None: parent = parent.strip() path_without_drive_letter = parent[2:] _determine_if_drive_letter_is_valid(file_path=parent) _check_if_string_ends_with_slash(string_to_validate=path_without_drive_letter) if len(path_without_drive_letter) &gt; 2: _check_for_invalid_characters(string_to_validate=path_without_drive_letter) def verify_subdirectory(subdirectory: str) -&gt; None: subdirectory = subdirectory.strip() _check_if_string_starts_with_slash(string_to_validate=subdirectory) _check_for_invalid_characters(string_to_validate=subdirectory) _check_if_string_ends_with_slash(string_to_validate=subdirectory) def _determine_if_drive_letter_is_valid(file_path: str): drive_letter_with_colon = file_path[:2] if not drive_letter_with_colon[0].isalpha(): raise TypeError("Drive Letter is invalid.") if drive_letter_with_colon[1] != ":": raise ValueError(f"Second element is invalid. Character(s): {drive_letter_with_colon[1]}") def _check_for_invalid_characters(string_to_validate : str): """ Determine if the string contains forbidden elements. Raises a ValueError if any forbidden character is found. Args: string_to_validate : str - The string we're going to test. """ forbidden_characters = ["&lt;", "&gt;", ":", "/", '"', "|", "?", "*", "\\\\"] for forbidden_character in forbidden_characters: if forbidden_character in string_to_validate: raise ValueError(f"Invalid characters in path. Character(s): {forbidden_character}") def _check_if_string_starts_with_slash(string_to_validate : str): if string_to_validate.startswith("\\"): raise ValueError("Invalid characters in path. Character(s): \\") def _check_if_string_ends_with_slash(string_to_validate : str): if string_to_validate.endswith("\\"): raise ValueError("Invalid characters in path. Character(s): \\") </code></pre> <p>I created the above module because I might have more projects that require validation of paths. </p> <p><strong>Folder.py</strong>:</p> <pre><code>import pathutilities import os class Folder: def __init__(self, parent: str, subdirectory: str): pathutilities.verify_parent_directory(parent=parent) pathutilities.verify_subdirectory(subdirectory=subdirectory) self._parent = parent self._subdirectory = subdirectory @property def parent(self): return self._parent @property def subdirectory(self): return self._subdirectory def construct_path(self) -&gt; str : return os.path.join(self._parent, self._subdirectory) def __eq__(self, other): if isinstance(other, Folder): return (self.parent, self.subdirectory) == (other.parent, other.subdirectory) return NotImplemented def __hash__(self): return hash((self._parent, self._subdirectory)) </code></pre> <p><strong>Repository.py</strong>:</p> <pre><code>from Folder import Folder import os import shutil class Repository: def __init__(self, source: Folder, destination: Folder): if source == destination: raise ValueError("Source folder cannot be the destination folder") self._source = source self._destination = destination def copy_files_with(self, extension: str): if extension.startswith("."): raise ValueError("extension doesn't require a period") source = self._source.construct_path() destination = self._destination.construct_path() number_of_images_in_source = self._get_number_of_images_in_directory(directory=source) if number_of_images_in_source: print(f"Copying images from {source} to {destination}\nNumber of images: {number_of_images_in_source}") os.makedirs(destination, exist_ok=True) number_of_images_in_destination = self._get_number_of_images_in_directory(directory=destination) + 1 for number, image in enumerate(os.listdir(source), start=number_of_images_in_destination): if image.endswith(extension) or image.endswith(extension.upper()): source_image = os.path.join(source, image) destination_image = os.path.join(destination, self._construct_destination_string(current_number=number, extension=extension)) print(f"Copying {source_image} to {destination_image}") shutil.move(source_image, destination_image) else: print("No images to copy") def _get_number_of_images_in_directory(self, directory: str) -&gt; int: return len(os.listdir(directory)) def _construct_destination_string(self, current_number, extension): return "{0}_{1}.{2}".format(self._source.subdirectory.lower().replace(" ","_"), current_number, extension) </code></pre> <p><strong>Main.py</strong>:</p> <pre><code>import sys import os from Folder import Folder from Repository import Repository def main(): try: source = "{0}\\{1}".format(os.getenv("USERPROFILE"), "Pictures") destination = "R:\\Pictures" source_list = "source.txt" with open(source_list) as folders_from_source: for subfolder in folders_from_source: subfolder = subfolder.strip() source_folder = Folder(parent=source, subdirectory=subfolder) destination_folder = Folder(parent=destination, subdirectory=subfolder) repository = Repository(source=source_folder, destination=destination_folder) repository.copy_files_with(extension="jpg") except (TypeError, ValueError, FileExistsError) as error: print(error) finally: sys.exit() if __name__ == '__main__': main() </code></pre> <p>Suppose there were two images in each of the source folders, it will rename them like this:</p> <pre><code>landscape_1.jpg landscape_2.jpg batman_1.jpg batman_2.jpg </code></pre> <p><strong>Areas of Concern:</strong></p> <ul> <li><p>Is my code clean? Descriptive variable and method methods, small classes and at least for me, it's easy to follow.</p></li> <li><p>I didn't include docstrings to save space, but I'm well aware I should include them. </p></li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T23:11:18.193", "Id": "433567", "Score": "0", "body": "At first glance, `PathUtilities` doesn't seem like it should be necessary; Python does all of that for free." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T12:09:33.510", "Id": "433631", "Score": "0", "body": "Exactly. `PathUtilities` already is implemented in python. If you ask yourself the question: Do you even care about what path user entered or the only thing you care if it the path exists or not? If it is accessible or not? All the checks are not necessary and there is `os.path.exists` command that do all of it for you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-13T06:28:47.630", "Id": "434581", "Score": "0", "body": "Check out pathlib.Path. It does 90% of the path validation" } ]
[ { "body": "<p>First, I'm afraid all the path handling and validation is a common anti-pattern of trying to check every conceivable error condition before trying to do something, in order to avoid lots of error-handling code. The problem is it doesn't work - it is literally impossible to guard against all possible errors, because an error may be introduced after you verify that things are fine, and before you act on that information. For example, you may check for the existence of a directory, but something or something removes or replaces it before you have a chance to use it. So my primary suggestion would be to simply remove all of PathUtilities.py and Folder.py, and to use the file access tools directly in your main code. What will happen then is if you attempt to do something like read a non-existing file you will get an informative uncaught exception from the Python standard library, and those will be easy to debug and/or handle when you see them.</p>\n\n<p>That said:</p>\n\n<ol>\n<li>Repository.py and Main.py belong in the same file, at least until the program becomes a fair bit more complex. This is a common pattern in small Python utilities, since there is a big advantage to having a program be a single file as opposed to several.</li>\n<li>Don't worry about docstrings. If you make your code sufficiently easy to read they just clutter up the place in my experience.</li>\n<li><code>sys.exit()</code> is redundant as it stands. To make it useful you can pass it a number to indicate success or failure of the run. By convention zero indicates success, one often indicates an unknown error, and other numbers indicate application-specific errors. Don't use numbers above 255; exit codes are just a single byte on common platforms. A common pattern here is to <code>sys.exit(main())</code> at the bottom of the file, and have <code>main</code> return an <code>int</code>.</li>\n<li><a href=\"https://github.com/ambv/black\" rel=\"nofollow noreferrer\"><code>black</code></a> can automatically format your code to be more idiomatic.</li>\n<li><p><a href=\"https://gitlab.com/pycqa/flake8\" rel=\"nofollow noreferrer\"><code>flake8</code></a> with a strict complexity limit will give you more hints to write idiomatic Python:</p>\n\n<pre><code>[flake8]\nmax-complexity = 4\nignore = W503,E203\n</code></pre>\n\n<p>That limit is not absolute by any means, but it's worth thinking hard whether you can keep it low whenever validation fails. For example, I'm working with a team on an application since a year now, and our complexity limit is up to 7 in only one place.</p></li>\n<li><p>I would then recommend adding <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">type hints</a> everywhere and validating them using a strict <a href=\"https://github.com/python/mypy\" rel=\"nofollow noreferrer\"><code>mypy</code></a> configuration:</p>\n\n<pre><code>[mypy]\ncheck_untyped_defs = true\ndisallow_untyped_defs = true\nignore_missing_imports = true\nno_implicit_optional = true\nwarn_redundant_casts = true\nwarn_return_any = true\nwarn_unused_ignores = true\n</code></pre></li>\n</ol>\n\n<p>In general the code is easy to read, but could use some simplifying.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T21:55:36.850", "Id": "223646", "ParentId": "223641", "Score": "5" } } ]
{ "AcceptedAnswerId": "223646", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-06T19:03:18.850", "Id": "223641", "Score": "5", "Tags": [ "python", "python-3.x", "file", "file-system" ], "Title": "Python script to rename images based on descriptions in a text file" }
223641
<p>I'm here looking for a review over my current code-base.</p> <p>Please: </p> <ul> <li><p>Ignore using namespace std; this is for educational purposes mostly so <strong>the usage of using namespace std; does not matter for this codebase</strong> as it's a project thrown together for educational purposes.</p></li> <li><p><strong>Look at some parts of my code which I will point out below</strong> and if possible, look at the rest giving me feedback and telling me how to possibly improve/showing me.</p></li> </ul> <p>In my <code>InventorySystem</code>, I have code which reads into a text-file that's structured like so:</p> <pre><code>{ 123, A piece of cheese., 10.19, 4, } { 321, A country flag, 10.00, 1, } </code></pre> <p>Specifically, it has Packet.h's structure which you can see below.</p> <p>This code:</p> <pre><code>string line, line2, line3, line4; int num1; double num2; int num3; while (getline(inFile, line)) { getline(inFile, line); line = line.substr(0, line.size() - 1); num1 = stoi(line); getline(inFile, line2); line2 = line2.substr(0, line2.size() - 1); getline(inFile, line3); line3 = line3.substr(0, line3.size() - 1); num2 = stod(line3); getline(inFile, line4); line4 = line4.substr(0, line4.size() - 1); num3 = stoi(line4); Packet importPacket(num1, line2, num2, num3); inventorySystem.insert(importPacket); getline(inFile, line); getline(inFile, line); } inFile.close(); </code></pre> <p>In the beginning of <code>int main()</code> in <code>Inventory.cpp</code> is supposed to read into it section by section. But looking at the code, as you can see it seems very clunky. Do you have any suggestions for improving it? Note that it tosses out the "," seen at the end of every attribute so that it can read the <code>id</code>, <code>description</code>, <code>price</code>, <code>partCount</code> of <code>Packet.h</code>.</p> <p>There's also this part</p> <pre><code>else if (choice == 'a') { cout &lt;&lt; "Archiving all the information." &lt;&lt; endl; Sleep(1000); cout &lt;&lt; "Archiving all the information.." &lt;&lt; endl; Sleep(1000); cout &lt;&lt; "Archiving all the information..." &lt;&lt; endl; vector &lt;Packet*&gt; getPackets = inventorySystem.extract(); bOutFile.open("C:\\...Put_Your_Path_Here.dat", ios::out | ios::binary); for (int i = 0; i &lt; getPackets.size(); ++i) { bOutFile.write((char*)&amp;getPackets[i], sizeof(getPackets[i])); } bOutFile.close(); } </code></pre> <p>For archiving to binary .dat purposes where I use the extract function on the binary search tree to grab all of its contents and put them into a vector for archiving into <code>.dat</code> purposes. I'm not sure if this is a good way of doing so. Could it be improved? I want to extract still so that I don't have to write more code if possible. This code also uses pretty much the preorder traversal in order to extract contents of <code>BST</code>. It's pretty repetitive. This code can be found in int main() at the if...choice "a." Here's how it executes from <code>BST.cpp</code>:</p> <pre><code>vector &lt;Packet*&gt; BST::extract() const { vector &lt;Packet*&gt; result; if (root != nullptr) { extract(root, result); } return result; } void BST::extract(const Node *p, vector &lt;Packet*&gt; &amp;result) const { if (p != nullptr) { result.push_back(p-&gt;data); extract(p-&gt;llink, result); extract(p-&gt;rlink, result); } } </code></pre> <p>It's recursive. That's all. But if you can look at other parts of the codebase that'd be really great too!</p> <p>This part for <strong>reference purposes:</strong></p> <hr> <p>Inventory.cpp:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;fstream&gt; #include "windows.h" #include "BST.h" #include "Packet.h" using namespace std; /* PURPOSE: Process inventory information for a parts warehouse. 1. Read from txt. file used for storing information between sessions. *Txtfile can be empty. 2. Pop up 5 choices in main menu: enter a new part to system, find and print data for a part when given the part ID number, and find and modify data for a part when given the part ID number, copy all information to a binary archive file, and quit. */ int main() { BST inventorySystem; ifstream inFile("C:\\...Put_Your_Path_Here.txt"); ofstream outFile; fstream bOutFile; if (!inFile) { cerr &lt;&lt; "ERROR: Unable to open the text file." &lt;&lt; endl; } else { string line, line2, line3, line4; int num1; double num2; int num3; while (getline(inFile, line)) { getline(inFile, line); line = line.substr(0, line.size() - 1); num1 = stoi(line); getline(inFile, line2); line2 = line2.substr(0, line2.size() - 1); getline(inFile, line3); line3 = line3.substr(0, line3.size() - 1); num2 = stod(line3); getline(inFile, line4); line4 = line4.substr(0, line4.size() - 1); num3 = stoi(line4); Packet importPacket(num1, line2, num2, num3); inventorySystem.insert(importPacket); getline(inFile, line); getline(inFile, line); } inFile.close(); char choice = 'z'; while (choice != 'q') { cout &lt;&lt; "-----------------------------------------------------" &lt;&lt; endl; cout &lt;&lt; "Program successfully loaded..." &lt;&lt; endl; cout &lt;&lt; "Welcome to the main menu..." &lt;&lt; endl; cout &lt;&lt; "-----------------------------------------------------" &lt;&lt; endl; cout &lt;&lt; "N: Enter new part into the system &gt;&gt;" &lt;&lt; endl; cout &lt;&lt; "F: Find a particular part &gt;&gt;" &lt;&lt; endl; cout &lt;&lt; "A: Archive the information &gt;&gt;" &lt;&lt; endl; cout &lt;&lt; "Q: Quit &gt;&gt;" &lt;&lt; endl; cout &lt;&lt; "Input your choice: "; cin &gt;&gt; choice; choice = tolower(choice); if (choice == 'n') { cout &lt;&lt; "Enter the new part's I.D.: "; int partId = -1; cin &gt;&gt; partId; cin.ignore();; // Flushes the input stream and removes the new line(s) at the end of the stream for the upcoming getline. cout &lt;&lt; "Enter a short description for this new part: "; string description = ""; getline(cin, description); cout &lt;&lt; "Enter the price of this new part: $"; double price = 0.00; cin &gt;&gt; price; cout &lt;&lt; "Enter how many parts the warehouse currently has: "; int partCount = 0; cin &gt;&gt; partCount; if (partId &gt;= 0 &amp;&amp; price &gt;= 0 &amp;&amp; partCount &gt;= 0) { Packet packet(partId, description, price, partCount); inventorySystem.insert(packet); cout &lt;&lt; "Attempted to enter the part into the SYSTEM." &lt;&lt; endl; } else { cout &lt;&lt; "One or more inputs are invalid. You will be prompted back to the menu. Please enter a valid input!" &lt;&lt; endl; cout &lt;&lt; "Usage: PartID should be greater than or equal to 0, price should be similar, and vice versa!" &lt;&lt; endl; } } else if (choice == 'f') { cout &lt;&lt; "Enter the part I.D. that you want to search the database for: "; int partId = -1; cin &gt;&gt; partId; Packet* getPacket = inventorySystem.search(partId); if (getPacket != nullptr) { cout &lt;&lt; "{" &lt;&lt; endl; cout &lt;&lt; "I.D.: " &lt;&lt; getPacket-&gt;getPartId() &lt;&lt; endl; cout &lt;&lt; "Description: " &lt;&lt; getPacket-&gt;getDescription() &lt;&lt; endl; cout &lt;&lt; "Price: " &lt;&lt; getPacket-&gt;getPrice() &lt;&lt; endl; cout &lt;&lt; "Part Count: " &lt;&lt; getPacket-&gt;getPartCount() &lt;&lt; endl; cout &lt;&lt; "}" &lt;&lt; endl; } else { cout &lt;&lt; "ERROR: System could not find the following I.D. as part of the inventory system." &lt;&lt; endl; } } else if (choice == 'a') { cout &lt;&lt; "Archiving all the information." &lt;&lt; endl; Sleep(1000); cout &lt;&lt; "Archiving all the information.." &lt;&lt; endl; Sleep(1000); cout &lt;&lt; "Archiving all the information..." &lt;&lt; endl; vector &lt;Packet*&gt; getPackets = inventorySystem.extract(); bOutFile.open("C:\\...Put_Your_Path_Here.dat", ios::out | ios::binary); for (int i = 0; i &lt; getPackets.size(); ++i) { bOutFile.write((char*)&amp;getPackets[i], sizeof(getPackets[i])); } bOutFile.close(); } } vector &lt;Packet*&gt; getPackets = inventorySystem.extract(); outFile.open("C:\\...Put_Your_Path_Here.txt"); for (int i = 0; i &lt; getPackets.size(); ++i) { outFile &lt;&lt; "{" &lt;&lt; endl; outFile &lt;&lt; getPackets[i]-&gt;getPartId() &lt;&lt; "," &lt;&lt; endl; outFile &lt;&lt; getPackets[i]-&gt;getDescription() &lt;&lt; "," &lt;&lt; endl; outFile &lt;&lt; getPackets[i]-&gt;getPartCount() &lt;&lt; "," &lt;&lt; endl; outFile &lt;&lt; getPackets[i]-&gt;getPrice() &lt;&lt; "," &lt;&lt; endl; outFile &lt;&lt; "}" &lt;&lt; endl &lt;&lt; endl; } outFile.close(); } system("pause"); } </code></pre> <p>BST.h:</p> <pre><code>#pragma once #include "Packet.h" #include &lt;vector&gt; using namespace std; class BST { struct Node { Node() : rlink(nullptr), llink(nullptr) {}; ~Node() {}; Packet *data; Node *rlink, *llink; }; public: BST(); void insert(Packet &amp;p); void insert(Node *&amp;p, Node *newNode); Packet* search(int id); vector &lt;Packet*&gt; extract() const; void preorderTraversal() const; void destroyTree(); ~BST(); private: Node * root; void destroyTree(Node *&amp;p); Packet* search(const Node *p, int id); void extract(const Node *p, vector &lt;Packet*&gt; &amp;result) const; void preorderTraversal(const Node *p) const; }; </code></pre> <p>BST.cpp:</p> <pre><code>#include "BST.h" #include &lt;iostream&gt; BST::BST() : root(nullptr) {} void BST::insert(Packet &amp;p) { if (search(p.getPartId()) == nullptr) { Node *newNode = new Node; newNode-&gt;data = new Packet(p); insert(root, newNode); } else { cout &lt;&lt; "Insertion failed because such packet has already been found to exist." &lt;&lt; endl; } } void BST::insert(Node *&amp;p, Node *newNode) { if (p == nullptr) { p = newNode; } else if (p-&gt;data-&gt;getPartId() &gt; newNode-&gt;data-&gt;getPartId()) { insert(p-&gt;llink, newNode); } else { insert(p-&gt;rlink, newNode); } } Packet* BST::search(int id) { return search(root, id); } Packet* BST::search(const Node *p, int id) { if (p == nullptr) { return nullptr; } else if (p-&gt;data-&gt;getPartId() == id) { return p-&gt;data; } else if (p-&gt;data-&gt;getPartId() &lt; id) { return search(p-&gt;rlink, id); } return search(root-&gt;llink, id); } vector &lt;Packet*&gt; BST::extract() const { vector &lt;Packet*&gt; result; if (root != nullptr) { extract(root, result); } return result; } void BST::extract(const Node *p, vector &lt;Packet*&gt; &amp;result) const { if (p != nullptr) { result.push_back(p-&gt;data); extract(p-&gt;llink, result); extract(p-&gt;rlink, result); } } void BST::preorderTraversal() const { if (root == nullptr) { cerr &lt;&lt; "There is no tree."; } else { preorderTraversal(root); } } void BST::preorderTraversal(const Node *p) const { if (p != nullptr) { cout &lt;&lt; p-&gt;data-&gt;getPartId() &lt;&lt; " "; preorderTraversal(p-&gt;llink); preorderTraversal(p-&gt;rlink); } } void BST::destroyTree(Node *&amp;p) { if (p != nullptr) { destroyTree(p-&gt;llink); destroyTree(p-&gt;rlink); delete p; p = nullptr; } } void BST::destroyTree() { destroyTree(root); } BST::~BST() { destroyTree(root); } </code></pre> <p>Packet.h:</p> <pre><code>#pragma once #include &lt;string&gt; using namespace std; class Packet { public: Packet(int partId, string description, double price, int partCount) : partId(partId), description(description), price(price), partCount(partCount) {} int getPartId() const {return partId;} string getDescription() const {return description;} double getPrice() const {return price;} int getPartCount() const {return partCount;} private: int partId; string description; double price; int partCount; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T01:29:49.450", "Id": "433579", "Score": "2", "body": "It's OK to ask us to ignore something, but `using namespace std;` is for \"educational purposes only\"? I'd say you should particularly avoid them for education purposes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T03:24:35.287", "Id": "433586", "Score": "0", "body": "It would most likely not be used if it's reasonable in a real project. I may have worded it wrong but yeah, please ignore it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T07:13:15.620", "Id": "433591", "Score": "0", "body": "@ii69outof247 If you put code for review here you should be open for _any aspect_ of your code being reviewed. You can't simply exclude certain aspects should be ignored by reviewers. Especially `using namespace std` is a big red flag which should be improved." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T07:18:57.377", "Id": "433592", "Score": "0", "body": "@ii69outof247 See here also: https://codereview.meta.stackexchange.com/questions/5773/is-it-okay-to-give-a-review-without-actually-answering-some-of-the-ops-requests?noredirect=1&lq=1" } ]
[ { "body": "<p>I see a number of things that may help you improve your code.</p>\n\n<h2>Prefer portable code to platform specific code</h2>\n\n<p>The code is currently calling <code>Sleep</code> which is a platform-dependent function. This could be made platform independent by instead using <a href=\"https://en.cppreference.com/w/cpp/thread/sleep_for\" rel=\"nofollow noreferrer\"><code>std::this_thread::sleep_for</code></a></p>\n\n<h2>Don't use <code>system(\"pause\")</code></h2>\n\n<p>There are two reasons not to use <code>system(\"cls\")</code> or <code>system(\"pause\")</code>. The first is that it is not portable to other operating systems which you may or may not care about now. The second is that it's a security hole, which you absolutely <strong>must</strong> care about. Specifically, if some program is defined and named <code>PAUSE</code> or <code>pause</code>, your program will execute that program instead of what you intend, and that other program could be anything. First, isolate these into a seperate functions <code>pause()</code> and then modify your code to call those functions instead of <code>system</code>. Then rewrite the contents of those functions to do what you want using C++. For example:</p>\n\n<pre><code>void pause() {\n getchar();\n}\n</code></pre>\n\n<h2>Don't abuse <code>using namespace std</code></h2>\n\n<p>Putting <code>using namespace std</code> at the top of every program is <a href=\"http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">a bad habit</a> that you'd do well to avoid. It is particularly bad to put it into a header file, so please don't do that.</p>\n\n<h2>Consider the user</h2>\n\n<p>Instead of having a hardcoded filename, it might be nice to allow the user to control the name and location of the input and output files. For this, it would make sense to use a command line argument and then pass the filename to the functions as needed.</p>\n\n<h2>Use better names</h2>\n\n<p>It's baffling that the class containing a part is called <code>Packet</code> instead of <code>Part</code>. Good names are extremely useful in creating and maintaining good code.</p>\n\n<h2>Be careful with signed and unsigned</h2>\n\n<p>In two cases, the code compares an <code>int</code> <code>i</code> with <code>getPackets.size()</code>. However, <code>getPackets.size()</code> is unsigned and <code>i</code> is signed. For consistency, it would be better to declare <code>i</code> as <code>std::size_t</code> which is the type returned by <code>size()</code>.</p>\n\n<h2>Don't use <code>std::endl</code> if you don't really need it</h2>\n\n<p>The difference betweeen <code>std::endl</code> and <code>'\\n'</code> is that <code>'\\n'</code> just emits a newline character, while <code>std::endl</code> actually flushes the stream. This can be time-consuming in a program with a lot of I/O and is rarely actually needed. It's best to <em>only</em> use <code>std::endl</code> when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one. Avoiding the habit of using <code>std::endl</code> when <code>'\\n'</code> will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized.</p>\n\n<h2>Use include guards</h2>\n\n<p>There should be an include guard in each <code>.h</code> file. That is, start the file with:</p>\n\n<pre><code>#ifndef BST_H\n#define BST_H\n// file contents go here\n#endif // BST_H\n</code></pre>\n\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></p>\n\n<h2>Fix the bug</h2>\n\n<p>The current archiving is mostly useless since it writes memory pointer values to the output file. After the program ends, those pointer values are going to be completely useless. What was apparently intended was to write a binary representation of the part, but that's not what's currently happening.</p>\n\n<h2>Be careful with raw pointers</h2>\n\n<p>The <code>BST::extract</code> returns a vector of raw pointers to internal data. This is almost certainly going to be a problem because there is nothing to prevent the <code>BST</code> from being deleted (invalidating all of those pointers) before the returned vector is used. This is not a good design. Better would be instead to allow direct traversal of the <code>BST</code> data structure via iterators. This is safer and much easier to use in conjunction with standard algorithms.</p>\n\n<h2>Prefer a stream inserter to a custom <code>print</code> routine</h2>\n\n<p>Your main routine currently writes all of the detailed inventory data. Instead, it could be written as a stream inserter:</p>\n\n<pre><code>friend std::ostream&amp; operator&lt;&lt;(std::ostream &amp;out, const Packet &amp;p) {\n return out &lt;&lt; \"{\\n\" &lt;&lt; p.partId &lt;&lt; \",\\n\" &lt;&lt; p.description \n &lt;&lt; \",\\n\" &lt;&lt; p.partCount &lt;&lt; \",\\n\" &lt;&lt; p.price &lt;&lt; \"\\n}\\n\\n\";\n}\n</code></pre>\n\n<p>Then the loop in <code>main</code> could be this:</p>\n\n<pre><code>for (std::size_t i = 0; i &lt; getPackets.size(); ++i) {\n outFile &lt;&lt; getPackets[i];\n}\n</code></pre>\n\n<p>Or even better:</p>\n\n<pre><code>std::copy(getPackets.begin(), getPackets.end(), \n std::ostream_iterator&lt;Packet&gt;(outFile));\n</code></pre>\n\n<p>Note that both versions assume that <code>getPackets</code> is a vector of <code>Packet</code> rather than a vector of pointers as mentioned in the previous point. A similar thing can be done to create an extractor using <code>operator&gt;&gt;</code>.</p>\n\n<h2>Don't use console I/O for errors</h2>\n\n<p>The <code>BST</code> class writes to <code>std::cerr</code> or <code>std::cout</code> (it would be nice to be consistent!) when it encounters an error. Better would be to return a flag indicating success or perhaps throwing an exception.</p>\n\n<h2>Don't define redundant functions</h2>\n\n<p>The <code>destroyTree()</code> function is exactly a duplicate of the destructor. Since the destructor must be present, the <code>destroyTree</code> function should be omitted because it is redundant.</p>\n\n<h2>Don't define a default constructor that only initializes data members</h2>\n\n<p>The <code>BST::Node</code> constructor is currently this:</p>\n\n<pre><code>Node() : rlink(nullptr), llink(nullptr) {};\n</code></pre>\n\n<p>Better would be to use in-class member initializers. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-default\" rel=\"nofollow noreferrer\">C.45</a></p>\n\n<h2>Don't define an empty destructor</h2>\n\n<p>The current <code>~Node</code> is empty. Better would be to simply omit it. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-dtor\" rel=\"nofollow noreferrer\">C.30</a>.</p>\n\n<h2>Be careful with interfaces</h2>\n\n<p>The <code>void BST::insert(Node *&amp;p, Node *newNode);</code> function should be <code>private</code> because it requires the use of a <code>Node</code> object.</p>\n\n<h2>Don't leak memory</h2>\n\n<p>At the moment, the <code>data</code> pointer of each <code>BST::Node</code> is never freed which is a memory leak. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c31-all-resources-acquired-by-a-class-must-be-released-by-the-classs-destructor\" rel=\"nofollow noreferrer\">C.31</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T17:23:29.483", "Id": "223686", "ParentId": "223650", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T00:14:37.847", "Id": "223650", "Score": "1", "Tags": [ "c++", "tree", "search", "binary-search" ], "Title": "Inventory system codebase" }
223650
<p>I am working on this problem: <a href="https://www.hackerrank.com/challenges/determining-dna-health/problem" rel="nofollow noreferrer">https://www.hackerrank.com/challenges/determining-dna-health/problem</a> passing some test cases and time-out on others (no wrong answers).</p> <p>The code is here:</p> <pre><code>import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.regex.*; public class Solution { private static final Scanner scanner = new Scanner(System.in); public static void main(String[] args) { int n = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); String[] genesItems = scanner.nextLine().split(" "); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); Map&lt;Integer, String&gt; genes = new HashMap&lt;&gt;(); for (int i = 0; i &lt; n; i++) { genes.put(i, genesItems[i]); } String[] healthItems = scanner.nextLine().split(" "); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); Map&lt;Integer, String&gt; health = new HashMap&lt;&gt;(); for (int i = 0; i &lt; n; i++) { health.put(i, healthItems[i]); } int s = scanner.nextInt(); scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); long min = Long.MAX_VALUE; long max = Long.MIN_VALUE; for (int sItr = 0; sItr &lt; s; sItr++) { String[] firstLastd = scanner.nextLine().split(" "); int first = Integer.parseInt(firstLastd[0]); int last = Integer.parseInt(firstLastd[1]); String d = firstLastd[2]; long sum = 0; for (int i = first; i &lt;= last; i++) { for (int index = d.indexOf(genes.get(i)); index &gt;= 0; index = d.indexOf(genes.get(i), index + 1)) { sum += Integer.parseInt(health.get(i)); } } if (sum &lt; min) { min = sum; } if (sum &gt; max) { max = sum; } } System.out.println(min + " " + max); scanner.close(); } } </code></pre>
[]
[ { "body": "<h1>The Algorithm</h1>\n<p>This has a bad worst-case complexity,</p>\n<pre><code>for (int i = first; i &lt;= last; i++) {\n for (int index = d.indexOf(genes.get(i)); index &gt;= 0; index = d.indexOf(genes.get(i), index + 1)) {\n sum += Integer.parseInt(health.get(i));\n }\n}\n</code></pre>\n<p>Consider a strand <code>&quot;aaaaaaaaaaaaaaaaaaaaaaa&quot;</code> and genes <code>{&quot;aaaaa&quot;, &quot;aaaaa&quot; ...</code></p>\n<p>Now for every gene, at almost every position of the strand, there will be a string comparison. The amount of character comparisons is approximately <code>TotalSize(genes) * strand.length</code>, so that can easily lead to a TLE if the data is a little annoying, which of course it will be.</p>\n<p>Here are a couple of other techniques you could try,</p>\n<ul>\n<li>Building a suffix array and LCP array for the strand, so for every gene the number of occurrences in the strand can be counted in <code>O(geneLength + log strandLength)</code> (so without even visiting the occurrences!) by binary-searching for the start and end of the contiguous range in the SA that contains all those occurrences. A suffix trie is good as well but more dangerous for the memory footprint. SA and suffix trie can both be constructed in linear time (in the length of the string), but it is non-trivial to implement. The LCP array can be given as a secondary result of SA construction (depending on the algorithm) or otherwise created in linear time as well by using the SA.</li>\n<li>Building a trie with the healthy genes, then go over the strand while descending down the trie, backing up as needed. This has a bunch of edge-cases that need to be considered. There are slow cases, for example if a gene is very big (half the length of the strand) and matches nearly everywhere (for example if the strand and gene are both only the same character), which I think is still a quadratic case. Some additional trickery may be able to work around that.</li>\n</ul>\n<p>The solutions that I could find quickly seemed to use the second approach, but I think the first one would be a &quot;safer&quot; choice in terms of avoiding a quadratic worst-case complexity, though the second one seems useful enough in practice (it has been successfully used, after all).</p>\n<h1>Unnecessary Map</h1>\n<p>When the keys of a map are a dense and non-changing range of integers like this,</p>\n<pre><code>Map&lt;Integer, String&gt; genes = new HashMap&lt;&gt;();\nfor (int i = 0; i &lt; n; i++) {\n genes.put(i, genesItems[i]);\n}\n</code></pre>\n<p>Using an <code>ArrayList</code> or plain array is a little more efficient and maybe more convenient (the array <code>genesItems</code> is already available anyway). Though of course this does not significantly contribute to TLEs in competitive programming.</p>\n<p>The skeleton code under the problem uses arrays.</p>\n<h1>Avoid re-parsing</h1>\n<p>The inner loop contains <code>Integer.parseInt(health.get(i))</code>, but that should usually be done up front when reading in the problem data. The skeleton code under the problem parses up front.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T10:36:20.117", "Id": "223666", "ParentId": "223654", "Score": "2" } } ]
{ "AcceptedAnswerId": "223666", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T05:02:35.377", "Id": "223654", "Score": "1", "Tags": [ "java", "performance" ], "Title": "HackerRank Code \"Determining DNA Health\"" }
223654
<p>Just whipped up this quick curry function in Lua, as a building block for partial application and memoization. Any feedback is appreciated.</p> <p>It takes two arguments; <code>n</code> is the number of parameters in the function being curried, and <code>func</code> is the function to curry.</p> <p>Code generation is used to create the curried functions. Because the same code is generated for any given <code>n</code>, the generated functions are cached to offset the runtime cost of code generation.</p> <pre class="lang-lua prettyprint-override"><code>local curryCache = {} local function curryGenerate(n) if curryCache[n] then return curryCache[n] end local src = 'return func(a1%s)' for i = 2, n do src = src:format((', a%i%%s'):format(i)) end src = src:format('') for i = n, 1, -1 do src = ('return function(a%i) %s end'):format(i, src) end src = ('local func = ...; %s'):format(src) curryCache[n] = load(src) return curryCache[n] end local function curry(n, func) return n &lt; 2 and func or curryGenerate(n)(func) end </code></pre> <p>Testing it out:</p> <pre class="lang-lua prettyprint-override"><code>local p4 = curry(4, print) p4 'a' 'b' 'c' 'd' -- prints "a b c d" </code></pre> <p>Looking at some other questions about currying on this site, I noticed some use a more loose definition of the term, where any number of arguments can be passed to the curried function. I'm shooting for a more strict interpretation here, where the curried function, and each function returned by it, only takes a single argument.</p> <p>I'm also more concerned with the performance of the curried functions than the performance of <code>curry</code>, so code generation seems like a logical approach. But of course the performance of <code>curry</code> is also something worth considering for some use cases, so I'm open to alternate suggestions that do away with code generation, as long as the performance of the curried functions isn't impacted too drastically.</p>
[]
[ { "body": "<p>Overall a solid approach.</p>\n\n<p>Here's a few options to consider though:</p>\n\n<p>First of all, you could eliminate the separate <code>curry</code> function and just use the <code>generateCurry</code> function directly, after all, it's already curried itself ;)</p>\n\n<p>An approach that's maybe a bit more in line with Luas metaprogramming philosophy would be to replace your memoized function with a table that generates missing keys on the flies using the <code>__index</code> metamethod, so you'd write code like <code>curry[4](print)</code></p>\n\n<p>Choosing code generation was probably the right choice. For one you say that you care more about the speed of the curried function than the speed of curry; but even then, Lua has one of the quickest parsers among all scripting languages and memoization can get you a long way too.</p>\n\n<p>The one critical thing in your code is that you interpolation strings a lot. Repeated string interpolation and concatenation in Lua are slow because 1) it needs to constantly allocate new space and 2) it needs to hash every intermediate result.</p>\n\n<p>A better solution would be either <code>string.rep(str, n, sep)</code>, which repeats a string <code>n</code> times and puts <code>sep</code> in between each pair of strings; or <code>table.concat(tab, sep)</code> which concatenates all the values of a sequence with <code>sep</code> in between.</p>\n\n<p>Both of these are implemented in C and only hash the end result once all the strings are concatenated together. It also lets Lua allocate space for the entire result string from the start, though I am not sure if it does that for <code>string.concat</code>.</p>\n\n<p>Even this would only be an issue with very large numbers of arguments though, and even then only for the first time, since you cache the generated functions.</p>\n\n<p>Overall I'd say it's a pretty solid implementation.</p>\n\n<hr>\n\n<p>I quickly whipped up an example of how I'd do it, mostly out of boredom, but maybe you can steal the one or other useful idea from it ;)</p>\n\n<pre><code>local function seq(n, ...)\n if n&gt;0 then\n return seq(n-1, n, ...)\n else\n return ...\n end\nend\n\nlocal curry = setmetatable({}, {\n __index = function(self, key)\n if type(key) == 'number' then\n self[key] = assert(load(table.concat{\n \"local fn = ...; return \"\n .. string.rep(\"function(arg_%i) return \", key):format(seq(key))\n .. \"fn(\"\n .. string.rep(\"arg_%i\", key, \", \"):format(seq(key))\n .. \")\"\n .. string.rep(\" end\", key)\n }))\n return self[key]\n end\n end\n})\n</code></pre>\n\n<hr>\n\n<p>Further reading on Lua otimizations:</p>\n\n<ul>\n<li><a href=\"http://lua-users.org/wiki/OptimisationTips\" rel=\"nofollow noreferrer\">http://lua-users.org/wiki/OptimisationTips</a></li>\n<li><a href=\"https://www.lua.org/gems/sample.pdf\" rel=\"nofollow noreferrer\">https://www.lua.org/gems/sample.pdf</a></li>\n<li><a href=\"http://wiki.luajit.org/Numerical-Computing-Performance-Guide\" rel=\"nofollow noreferrer\">http://wiki.luajit.org/Numerical-Computing-Performance-Guide</a></li>\n<li><a href=\"http://wiki.luajit.org/NYI\" rel=\"nofollow noreferrer\">http://wiki.luajit.org/NYI</a></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T21:04:41.427", "Id": "434013", "Score": "0", "body": "Interesting ideas here! I'm targeting LuaJIT and wasn't aware that it had picked up that last argument to `string.rep` from 5.2. That's good to know. Interesting idea about using the cache directly, but I think I prefer the `curry(n, func)` style over `curry[n](func)`. Also I believe you meant to put commas in that table there, instead of concat ops (the result is the same, but the table concat and string concat operators are redundant, one or the other would do). Also unsure about the assert, maybe would suffice to add a check to make sure `key` is positive to that type check. Nice review!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T21:17:19.927", "Id": "434018", "Score": "0", "body": "Another thing I'm curious about now: I was aware of the table.concat trick, but tend to avoid disposable tables because of gc load. It doesn't really matter here, since results are cached, but now I wonder what gc overhead looks like for table.concat vs string concats without a table. Intuitively it seems that at some high number of strings, getting rid of the table would be cheaper than getting rid of the strings, and at some low number, getting rid of the strings would be cheaper. But now I want to test this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T04:44:33.920", "Id": "434040", "Score": "0", "body": "@user11536834 Interesting that you ask about garbage-collection; consider that closures (aka. functions) are also garbage-collected functions, so calling something like `curried_print('a')('b')('c')` will create 2 closures on the fly. Also, know that LuaJIT can't JIT-compile function closing, so your curried functions will *always* run interpreted until the last function call. `string.rep` can easily be replaced with `table.concat`, with a small speed decrease. For small numbers of arguments, the cost of the GC may be higher than the concatenation though, you'd have to benchmark that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T04:47:12.420", "Id": "434041", "Score": "0", "body": "(Updated my answer with two links)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T06:19:26.840", "Id": "434047", "Score": "0", "body": "Hmm, I was aware that closures were GC'd, but had somehow missed the fact that they don't JIT (yet?). That is a serious concern, may have to scrap this approach entirely -- guess I should keep up with LJ's issue tracker." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T06:22:10.787", "Id": "434048", "Score": "0", "body": "Here's a [list](http://wiki.luajit.org/NYI) of features you should avoid in hot loops." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T06:26:51.993", "Id": "434049", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/95955/discussion-between-user11536834-and-darkwiiplayer)." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T16:28:46.927", "Id": "223817", "ParentId": "223656", "Score": "3" } } ]
{ "AcceptedAnswerId": "223817", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T06:59:57.460", "Id": "223656", "Score": "6", "Tags": [ "functional-programming", "lua" ], "Title": "Currying in Lua" }
223656
<p><strong>A thief finds much more loot than his bag can fit. We have to find the most valuable combination of items assuming that any fraction of a loot item can be put into his bag.</strong></p> <p>For example has a bag which can fit at most 50 Kg of items. He has 3 items to choose from: the first item has a total value of $60 for 20 Kg, the second item has a total value of $100 for 50 Kg and the last item has a total value of $120 for 30 Kg.</p> <p>So, if the thief takes the most of the item that costs more per unit Kg, he/she can make a better profit out of his/her thievery. In that case, he/she would take 30 Kgs of the third item, and 20 Kgs of the first item, resulting in a total of 50 Kgs (full capacity) with the total value of $180.</p> <pre><code>// THIS IS AN EXAMPLE OF THE FRACTIONAL KNAPSACK PROBLEM #include&lt;cstdio&gt; #include&lt;iostream&gt; #include&lt;vector&gt; using namespace std; double get_max_index(vector&lt;int&gt;, vector&lt;int&gt;); double get_max_value(vector&lt;int&gt;, vector&lt;int&gt;, int); int main() { int num_items, bag_capacity; cout &lt;&lt; "Enter the number of items: " &lt;&lt; endl; cin &gt;&gt; num_items; cout &lt;&lt; "Enter the total capacity that the bag can support: " &lt;&lt; endl; cin &gt;&gt; bag_capacity; vector&lt;int&gt; values; vector&lt;int&gt; weights; for (int i = 0; i &lt; num_items; i++) { int buff_val = 0, buff_wgt = 0; cout &lt;&lt; "Enter the value and weight of Item " &lt;&lt; i + 1 &lt;&lt; ": " &lt;&lt; endl; cin &gt;&gt; buff_val &gt;&gt; buff_wgt; values.push_back(buff_val); weights.push_back(buff_wgt); } cout.precision(10); cout &lt;&lt; "The maximum loot value that can be acquired is " &lt;&lt; fixed &lt;&lt; get_max_value(values, weights, bag_capacity) &lt;&lt; "." &lt;&lt; endl; // Always display 'precision' number of digits return 0; } double get_max_index(vector&lt;int&gt; vals, vector&lt;int&gt; wgts){ int max_index = 0; double max_val_per_wgt = 0; for (int i = 0; i &lt; wgts.size(); i++) { if (wgts[i] != 0 &amp;&amp; (double) vals[i] / wgts[i] &gt; max_val_per_wgt) { max_val_per_wgt = (double) vals[i] / wgts[i]; max_index = i; } } return max_index; } double get_max_value(vector&lt;int&gt; vals, vector&lt;int&gt; wgts, int capacity){ double max_val = 0.0; for(int i = 0; i &lt; wgts.size(); i++) { if (capacity == 0) { return max_val; // There's no space left in the bag to carry } int max_value_index = get_max_index(vals, wgts); // See which item has the best value per weight index double taken = capacity &gt; wgts[max_value_index] ? wgts[max_value_index] : capacity; // get the minimum of the item's weight and capacity left in the bag max_val += taken * (double) vals[max_value_index] / wgts[max_value_index]; // calculate value for the item's weight taken capacity -= taken; // reduce capacity of the bag by the amount of weight of item taken wgts[max_value_index] -= taken; // reduce the item's weight by the amount taken } return max_val; } </code></pre> <p>Please review this code in terms of complexity or in other areas that might result in this code failing. Also, looking forward to criticism and if you decide to post criticism, kindly include relevant details that a not-so-experienced programmer might find helpful in solving the problem.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T08:01:23.477", "Id": "433598", "Score": "0", "body": "\"in other areas that might result in this code failing\" I assume you tested this though. How? Is the input sanitized or should any-and-all garbage be caught?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T08:06:46.317", "Id": "433600", "Score": "0", "body": "@Mast This code is sanitised and I have verified it with multiple manual input tests. It works in all the test cases that I have found on the web and on those that I designed myself. However, I included your quoted phrase to signify that experienced coders might find out hidden bugs that only surface rarely and might cause the code to fail." } ]
[ { "body": "<h3>The algorithm</h3>\n<p>Your algorithm needs O(n) space (for storing all items), and O(n * k) time (for selecting the best ones) (n = items to choose from, k = items chosen, bounded by n).</p>\n<p>By choosing as you go, you can get that down to O(k') space and O(n * k') time (k' = maximum items chosen at any time, at least k, bounded by n).</p>\n<p>Take a look at <a href=\"https://en.cppreference.com/w/cpp/algorithm/push_heap\" rel=\"nofollow noreferrer\"><code>std::push_heap</code></a>, <a href=\"https://en.cppreference.com/w/cpp/utility/tuple\" rel=\"nofollow noreferrer\"><code>std::tuple</code></a> and <a href=\"https://en.cppreference.com/w/cpp/language/lambda\" rel=\"nofollow noreferrer\">lambdas</a> for implementing the new algorithm.</p>\n<h3>Avoid casting</h3>\n<p>Casting is error-prone, as it circumvents the protections of the type-system. Thus, use the most restricted cast you can, and don't cast at all if reasonably possible. In your case, why not multiply with <code>1.0</code> instead?</p>\n<h3>Floating-point is hard</h3>\n<p>You are calculating the specific value (value per weight) of your items for comparison purposes. Luckily, a double has enough precision that you are extremely unlikely to suffer from rounding-errors when dividing two 32 bit numbers. Still, instead of comparing <code>1.0 * a_value / a_weight &lt; 1.0 * b_value / b_weight</code> you could compare <code>1LL * a_value * b_weight &lt; 1LL * b_value * a_weight</code>, avoiding division and floating-point.</p>\n<h3>All those useless copies</h3>\n<p>While copying small trivial types is generally the right approach, a <code>std::vector</code> is neither small nor trivial; Copying it is rather expensive. If you only need to read it, use a constant reference or preferably a <a href=\"https://en.cppreference.com/w/cpp/container/span\" rel=\"nofollow noreferrer\">C++2a <code>std::span</code></a> for increased flexibility.</p>\n<h2>Gracefully handle all kinds of invalid input</h2>\n<p>No need to assume malice, you are assured your load of garbage anyway.</p>\n<h3>Just the code</h3>\n<ol>\n<li><p>I don't see where you use anything from <code>&lt;cstdio&gt;</code>, so don't include it.</p>\n</li>\n<li><p>Never import a namespace wholesale which isn't designed for it. Especially <code>std</code> is huge and ever-changing, which can silently change the meaning of your code even between minor revisions of your toolchain, let alone using a different one.<br />\nIt cannot be guaranteed to break noisily.</p>\n</li>\n<li><p><code>return 0;</code> is implicit for <code>main()</code>. Make of that what you will.</p>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T11:37:40.787", "Id": "433621", "Score": "0", "body": "Thanks for the tips! They are very useful and will help me improve my coding skills. However, I'm struggling to understand your intent in the **Floating-point is hard** section. I must calculate the maximum value per unit weight and then correspondingly select that item. I don't see how ```(long long)a_value * b_weight < (long long)b_value * a_weight``` helps. I'm most probably missing something. Could you help?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T11:40:39.110", "Id": "433623", "Score": "0", "body": "The point is that if you want to compare the specific value of two items, using floating point division is potentially inaccurate. The alternative I gave in contrast is guaranteed accurate if `long long` is at least twice as wide as `int`, which is likely." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T11:49:09.957", "Id": "433626", "Score": "0", "body": "But I would lose a lot of fractional digits (after the decimal point) with long long. That would be even less accurate than floating point division!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T11:49:44.070", "Id": "433627", "Score": "0", "body": "Your values and weights are integers, specifically `int`. As I only multiply and compare, and that with more doubled width, there is no decimal point introduced." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T11:51:10.687", "Id": "433628", "Score": "0", "body": "Yes, in that case, that's entirely correct. Thanks for the clarification! :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T09:04:54.827", "Id": "223660", "ParentId": "223657", "Score": "3" } }, { "body": "<h3>1. Don't use <code>using namespace std;</code></h3>\n<p>While that would work in your particular case, it's considered bad practice. Especially when you move out your code to separate header files.</p>\n<p>See more details here please:</p>\n<p><a href=\"https://stackoverflow.com/q/1452721/14065\">Why is “using namespace std;” considered bad practice?</a></p>\n<h3>2. Check for valid input</h3>\n<p>You don't check if input was valid here:</p>\n<pre><code>cout &lt;&lt; &quot;Enter the number of items: &quot; &lt;&lt; endl;\ncin &gt;&gt; num_items;\ncout &lt;&lt; &quot;Enter the total capacity that the bag can support: &quot; &lt;&lt; endl;\ncin &gt;&gt; bag_capacity;\n</code></pre>\n<p>Rather use something like</p>\n<pre><code>std::cout &lt;&lt; &quot;Enter the number of items: &quot; &lt;&lt; std::endl;\nwhile(!(cin &gt;&gt; num_items)) {\n std::cout &lt;&lt; &quot;Enter a valid number please.&quot; &lt;&lt; std::endl;\n std::cout.clear();\n std::cout.ignore(std::limit::max);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T11:40:12.347", "Id": "433622", "Score": "0", "body": "Thanks fellow reviewer! (I wouldn't try to write your name). I'd definitely keep these points in mind. They are very helpful." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T09:10:43.433", "Id": "223661", "ParentId": "223657", "Score": "2" } } ]
{ "AcceptedAnswerId": "223660", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T07:36:23.727", "Id": "223657", "Score": "6", "Tags": [ "c++", "algorithm" ], "Title": "Determining the maximum value that can be obtained from a loot" }
223657
<p>The idea is that when we want to create an object of some type, we will only use a robotcreator and enum from the interface. the goal is to decides what type of robot to use internally, based on a parameter supplied by the client at runtime.</p> <p>what's better enum or define? </p> <p>InterfaceRobot.h</p> <pre><code> class InterfaceRobot { public: InterfaceRobot(); enum RobType { Y=0, C=1, D=2, F=3 }; virtual void open() = 0; virtual void close() = 0; }; #endif // INTERFACEROBOT_H </code></pre> <p>RobotCreator.h</p> <pre><code>class RobotCreator :public InterfaceRobot { public: RobotCreator(InterfaceRobot::RobType _robType); void open(); void close(); ~RobotCreator(); private: InterfaceRobot *Robot; /** pointer to InterfaceRobot**/ }; </code></pre> <p>RobotCreator.cpp</p> <pre><code>RobotCreator::RobotCreator(InterfaceRobot::RobType _robType) { switch (_robType) { case InterfaceRobot::C: this-&gt;Robot = new c(); break; case InterfaceRobot::Y: this-&gt;Robot = new y(); break; case InterfaceRobot::D: this-&gt;Robot = new D(); break; case InterfaceRobot::F: this-&gt;Robot = new F(); break; } } void RobotCreator::open() { this-&gt;Robot-&gt;open(); } void RobotCreator::close() { this-&gt;Robot-&gt;close(); } RobotCreator::~RobotCreator() { } </code></pre> <p>Example of robot Y.h: </p> <pre><code>class Y: public InterfaceRobot { public: Y(); // InterfaceRobot interface public: void open(); void close(); }; </code></pre> <p>Example of robot Y.cpp: </p> <pre><code>Y::Y() { } void Y::open() { cout&lt;&lt; "open Y" &lt;&lt;endl; } void Y::close() { cout&lt;&lt; "close Y" &lt;&lt;endl; } </code></pre> <p>use in main:</p> <pre><code>int main() { RobotCreator rob(InterfaceRobot::Y); rob.open(); rob.close(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T08:00:09.793", "Id": "433597", "Score": "1", "body": "What's the difference of those implementations you have for `c`, `y`, `D` and `F`. It's unclear which particular problem should be solved with your code. Generally a _factory_ is for creating new instances that implement an interface, whereas _strategy_ is to choose a specific algorithm." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T08:04:37.557", "Id": "433599", "Score": "0", "body": "@πάνταῥεῖ c,y,d,f are different robot and each one implements the functions in the interface differently." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T08:11:29.530", "Id": "433601", "Score": "0", "body": "All in all it looks like you simply have a flawed and bad design (referring to none of those desgn patterns you mentioned), which violates the [_single reponsibility principle_](https://en.wikipedia.org/wiki/Single_responsibility_principle). Plus some essentially bad practices and simply not working code (using `delete[]` for stuff created with `new`). Generally note that we don't accept any stub or hypothetical code for review here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T08:27:32.683", "Id": "433604", "Score": "1", "body": "Sorry if I sounded harsh in some way, but it's not a question about _being gentle_, just what the [policies](https://codereview.stackexchange.com/help/on-topic) of this site are (see the 2nd bullet specifically)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T08:29:38.790", "Id": "433605", "Score": "0", "body": "@πάνταῥεῖ ok great. i will read the policies." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T08:38:21.937", "Id": "433606", "Score": "0", "body": "@πάνταῥεῖ so I dont need to delete?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T08:42:09.547", "Id": "433607", "Score": "0", "body": "You use `delete[]` only when you've been using `new[]` before. In general avoid manual memory management at all, prefer using [_smart pointers_](https://en.cppreference.com/w/cpp/memory) or [_containers_](https://en.cppreference.com/w/cpp/container)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T09:14:22.393", "Id": "433609", "Score": "0", "body": "No, the main problem is the stub code you posted. Also changing your question which already has an answer is frowned upon." } ]
[ { "body": "<p>Your robot creator is not a factory in the traditional sense, because it never returns the robots it creates, or exposes them publicly. Generally, a factory object would do the same job as a class constructor, with the advantage of being a first-class object that can be passed around, stored in a field somewhere, and so on (without resorting to reflection or other \"magic,\" in languages that support that).</p>\n\n<p>This looks more like a strategy pattern, where it decides what type of robot to use internally, based on a parameter supplied by the client at runtime.</p>\n\n<p>It's difficult to propose an alternate solution, because it's not clear exactly what problem this code attempts to solve.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T07:57:16.817", "Id": "433596", "Score": "0", "body": "Thenks , The idia its like what you said : \"where it decides what type of robot to use internally, based on a parameter supplied by the client at runtime.\"" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T07:46:35.970", "Id": "223659", "ParentId": "223658", "Score": "1" } } ]
{ "AcceptedAnswerId": "223659", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T07:41:43.070", "Id": "223658", "Score": "-4", "Tags": [ "c++", "design-patterns" ], "Title": "Is it a proper implementation strategy pattern? what's better to use enum or define?" }
223658
<p>I wanted a buffer like <code>std::vector&lt;uint8_t&gt;</code> which is very fast at resizing, and it does not require byte initialization (it resizes to 16K, then to 2-4 bytes, then goes back to 16K, and repeat, a lot. std::vector zeroes all the bytes every time it grows back to 16K, I thought I could avoid the zeroing-overhead with a custom implementation)</p> <p>I came up with this:</p> <pre><code>// buffer which should be faster than std::vector&lt;uint8_t&gt; when resizing a lot because it does not do byte initialization when resizing class uint8_fast_buffer { public: uint8_fast_buffer(const size_t initial_size) { if(initial_size == 0) { // .. i don't really like the idea of buf being nullptr, this avoids that issue. this-&gt;internal_reserve(1); } else { this-&gt;internal_reserve(initial_size); this-&gt;buf_size=initial_size; } } ~uint8_fast_buffer() noexcept { free(this-&gt;buf); } size_t size(void) noexcept { return this-&gt;buf_size; } void reserve(const size_t reserve_size) { if(reserve_size &gt; this-&gt;buf_size_real) { this-&gt;internal_reserve(reserve_size); } } // this function is supposed to be very fast when newlen is smaller than the biggest it has ever been before. void resize(const size_t newlen) { if(__builtin_expect(newlen &gt; this-&gt;buf_size_real,0)) { this-&gt;internal_reserve(newlen); } this-&gt;buf_size=newlen; } void append(const uint8_t *data, const size_t len){ const size_t pos=this-&gt;size(); const size_t new_pos=this-&gt;size()+len; this-&gt;resize(new_pos); memcpy(&amp;this-&gt;buf[pos],data,len); } void reset(void) noexcept { this-&gt;buf_size=0; } bool empty(void) noexcept { return (this-&gt;buf_size==0); } uint8_t* data(void) noexcept { return this-&gt;buf; } uint8_t&amp; at(const size_t pos) { if(__builtin_expect(pos &gt;= this-&gt;size(),0)) { throw std::out_of_range(std::to_string(pos)+std::string(" &gt;= ")+std::to_string(this-&gt;size())); } return this-&gt;buf[pos]; } uint8_t&amp; operator[](const size_t pos) noexcept { return this-&gt;buf[pos]; } private: void internal_reserve(const size_t reserve_size) { uint8_t *newbuf=(uint8_t*)realloc(this-&gt;buf,reserve_size); if(__builtin_expect(newbuf == nullptr,0)) { throw std::bad_alloc(); } this-&gt;buf_size_real=reserve_size; this-&gt;buf=newbuf; } size_t buf_size=0; size_t buf_size_real=0; uint8_t *buf=nullptr; }; </code></pre>
[]
[ { "body": "<h3>Using <code>this-&gt;</code> to refer to class members</h3>\n<p>Ditch this. It's unnecessary unless you need to have to refer to inherited members or disambiguate any other variables or parameters.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T10:49:39.580", "Id": "223667", "ParentId": "223664", "Score": "3" } }, { "body": "<p>I prefer using the <a href=\"https://github.com/shlomif/rinutils/blob/master/rinutils/include/rinutils/likely.h\" rel=\"nofollow noreferrer\">likely() macros</a> over <code>__builtin*</code> directly because they may be more portable and they also reduce clutter.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T13:06:51.010", "Id": "433635", "Score": "1", "body": "There are actually attributes [[likely]] and [[unlikely]] coming in C++20. gcc has it in version 9" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T10:54:23.983", "Id": "223668", "ParentId": "223664", "Score": "3" } }, { "body": "<pre><code>// buffer which should be faster than std::vector&lt;uint8_t&gt; when resizing a lot because it does not do byte initialization when resizing\n</code></pre>\n\n<p>This comment line is really long. You should wrap the text so that there is no horizontal scrollbar anymore.</p>\n\n<pre><code>class uint8_fast_buffer\n{\npublic:\n uint8_fast_buffer(const size_t initial_size)\n</code></pre>\n\n<p>Undeclared identifier <code>size_t</code>. You forgot to post the <code>#include</code> lines; they are required for a good code review.</p>\n\n<pre><code> {\n if(initial_size == 0)\n</code></pre>\n\n<p>There's a space missing between the <code>if</code> and the open parenthesis.</p>\n\n<pre><code> {\n // .. i don't really like the idea of buf being nullptr, this avoids that issue.\n this-&gt;internal_reserve(1);\n }\n else\n {\n this-&gt;internal_reserve(initial_size);\n this-&gt;buf_size=initial_size;\n }\n }\n</code></pre>\n\n<p>The above constructor can be written in a shorter way, like this:</p>\n\n<pre><code> uint8_fast_buffer(const size_t initial_size)\n {\n this-&gt;buf_size = initial_size;\n this-&gt;internal_reserve(std::max(initial_size, 1));\n }\n</code></pre>\n\n<p>Continuing with your code:</p>\n\n<pre><code> ~uint8_fast_buffer() noexcept\n {\n free(this-&gt;buf);\n }\n size_t size(void) noexcept\n</code></pre>\n\n<p>The <code>void</code> is not necessary inside the parentheses. Remove it.</p>\n\n<pre><code> {\n return this-&gt;buf_size;\n }\n void reserve(const size_t reserve_size)\n {\n if(reserve_size &gt; this-&gt;buf_size_real)\n {\n this-&gt;internal_reserve(reserve_size);\n }\n }\n // this function is supposed to be very fast when newlen is smaller than the biggest it has ever been before.\n void resize(const size_t newlen)\n {\n if(__builtin_expect(newlen &gt; this-&gt;buf_size_real,0))\n</code></pre>\n\n<p>There's a space missing after the <code>if</code>, and after the comma.</p>\n\n<pre><code> {\n this-&gt;internal_reserve(newlen);\n }\n this-&gt;buf_size=newlen;\n }\n void append(const uint8_t *data, const size_t len){\n</code></pre>\n\n<p>There's a newline missing before the <code>{</code>. You should let your IDE format the source code, to avoid these inconsistencies.</p>\n\n<pre><code> const size_t pos=this-&gt;size();\n const size_t new_pos=this-&gt;size()+len;\n this-&gt;resize(new_pos);\n memcpy(&amp;this-&gt;buf[pos],data,len);\n</code></pre>\n\n<p>Therearespacesmissingallovertheplaceespeciallyaroundtheoperators.</p>\n\n<pre><code> }\n void reset(void) noexcept\n {\n this-&gt;buf_size=0;\n }\n bool empty(void) noexcept\n {\n return (this-&gt;buf_size==0);\n }\n</code></pre>\n\n<p>The parentheses are not necessary.</p>\n\n<pre><code> uint8_t* data(void) noexcept\n {\n return this-&gt;buf;\n }\n uint8_t&amp; at(const size_t pos)\n {\n if(__builtin_expect(pos &gt;= this-&gt;size(),0))\n {\n throw std::out_of_range(std::to_string(pos)+std::string(\" &gt;= \")+std::to_string(this-&gt;size()));\n }\n return this-&gt;buf[pos];\n }\n uint8_t&amp; operator[](const size_t pos) noexcept\n {\n return this-&gt;buf[pos];\n }\nprivate:\n void internal_reserve(const size_t reserve_size)\n {\n uint8_t *newbuf=(uint8_t*)realloc(this-&gt;buf,reserve_size);\n if(__builtin_expect(newbuf == nullptr,0))\n {\n throw std::bad_alloc();\n }\n this-&gt;buf_size_real=reserve_size;\n this-&gt;buf=newbuf;\n }\n size_t buf_size=0;\n size_t buf_size_real=0;\n</code></pre>\n\n<p>To clearly distinguish <code>buf_size</code> and <code>buf_size_real</code>, the Go programming language uses <code>buf_len</code> and <code>buf_cap</code> (for capacity). The word <code>real</code> is rather confusing.</p>\n\n<pre><code> uint8_t *buf=nullptr;\n};\n</code></pre>\n\n<h3>Summary</h3>\n\n<p>On a high level, the code looks good. It works, takes care of exceptional situations and defines a minimal and appropriate API.</p>\n\n<p>On the syntactic level, there are many small details that can be improved, like consistent formatting and variable names.</p>\n\n<p>Let your IDE take care of the formatting, write some unit tests, and you're fine.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T19:12:42.033", "Id": "433672", "Score": "0", "body": "thanks, i'll make sure to properly format the code and add #includes before going here in the future. also `buf_cap` is a much better name than `buf_size_real` (which could be confused with a `real`-typed version of the (size_t-typed) buf_size instead of the buffer capacity. Thanks for taking the time!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T22:21:52.780", "Id": "433679", "Score": "2", "body": "I'm generally uncomfortable with telling people to drop \"unnecessary\" consts. Although it's commonly neglected, especially in function parameters, it is still considered good practice to use const for values that are not supposed to change. E.g. https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rconst-const" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T05:09:29.077", "Id": "433691", "Score": "0", "body": "@Josiah thank you for providing this link, I removed that suggestion. I was still under the influence of Sun Studio CC from about 2006, which generated different mangled names whether or not an int parameter was const." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T11:02:20.643", "Id": "433741", "Score": "0", "body": "I'm guessing that `size_t` was intended to be `std::size_t` (from `<cstdint>`), but without any includes, who knows? Anything is possible!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T11:04:28.993", "Id": "223669", "ParentId": "223664", "Score": "3" } } ]
{ "AcceptedAnswerId": "223669", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T09:53:06.657", "Id": "223664", "Score": "4", "Tags": [ "c++", "performance", "memory-management", "vectors" ], "Title": "Fast-resizing uint8 buffer" }
223664
<p>A while back I came across the issue of having a large delimited file where I wanted to simply parallelize my python code across each line of the file. However, doing so all at once either took up too much RAM, or took too long.</p> <p>So I made a simple Parallel Parser (<a href="https://pypi.org/project/parpar/" rel="nofollow noreferrer"><code>ParPar</code></a>) for sharding such delimited files and auto mapping a function across either each line of the file, or across each file of the shard.</p> <p>It has served me sufficiently well, but I am quite sure it could be improved.</p> <p>I am posting the relevant code here, but there may be snippets left out which can be obtained at the <a href="https://pypi.org/project/parpar/" rel="nofollow noreferrer">repo</a>.</p> <h1>Issues:</h1> <ul> <li><p>The only main performance issue I have faced is that if whatever I am doing takes most / all cores, uses all ram, and then chews through swap, leaving everything in a laggy frozen state. It would be nice to know how to set a mem limit or something for the processes spawned such that if it hits the limit the processes are paused until some of the ongoing ones finish and release memory.</p></li> <li><p>This creates shards by making many sub-directories with one file in the base. It may improve by being able to multi-shard... (shard a shard?) for when the first issue is encountered</p></li> </ul> <h1>Design Goals</h1> <p>I wanted to make a sharding library that was user friendly for the following:</p> <ul> <li>taking a delimited file split it, either by line, or by columns (if columns have <em>n</em>-categories) and putting the subfiles in a directory accordingly</li> <li>being able to restore a file sharded by the library (although not necessarily in the same order)</li> <li>easily allow one to map a function to all of the sharded files, or to each line in the sharded files</li> <li>allow one to have a progress bar for the status of the threaded function</li> </ul> <h1>Resources:</h1> <ul> <li><a href="https://pypi.org/project/parpar/" rel="nofollow noreferrer">repository</a></li> <li><a href="https://pypi.org/project/parpar/" rel="nofollow noreferrer">pypi</a></li> </ul> <h1>Example Usage</h1> <pre class="lang-py prettyprint-override"><code>from parpar import ParPar ppf = ParPar() ppf.shard_by_lines( input_file="./short.csv", output_dir="./short-lines", number_of_lines=3, ) # 3 lines per sharded file ppf.shard( input_file="./short.csv", output_dir="./short-cols", delim=",", columns=[0,5], # assumes column 0 and column 5 are categorical ) def foo(file, a, b, **kwargs): print(file, kwargs["dest"]) ppf.shard_file_apply( './short-lines', # sharded directory foo, args=[1,2], kwargs={ "output_shard_name": 'short-lines-alt', "output_shard_loc": os.path.expanduser('~/Desktop') # creates a new shard (with no files) with corresponding name at the specified loction # in this case `/Desktop/short-lines-alt/&lt;lines&gt;/ # using kwargs["dest"] and kwargs["lock"] user can # safely create a new shard processing each sharded file at a new location } ) </code></pre> <h1>Code</h1> <p>Notes: </p> <ul> <li><p>the following functions are all inside a class called <code>ParPar</code> which takes <em>no</em> arguments for initialization.</p></li> <li><p>This class houses two key variables:</p> <ul> <li><code>_shared_current = Value('i', 0)</code>: shared memory counter </li> <li><code>_shared_lock = Lock()</code>: for race conditions, etc</li> </ul></li> <li><p>this depends on a package called <code>sil</code> for the progress bar</p></li> </ul> <p>subnote: while <code>_shared_current</code> could be written as <code>Value('i', 0, lock=True)</code> and then exclude the <code>Lock</code>, since the <code>Lock</code> is not just for the counter, I opted for excluding that option.</p> <h2>Sharding Files</h2> <pre class="lang-py prettyprint-override"><code>def shard(self, input_file: str, output_dir: str, columns: list, delim: str = '\t', newline: str = '\n', sil_opts:dict = default_sil_options )-&gt;list: ''' Given the `input_file` and the column indicies, reads each line of the `input_file` and dumps the content into a file in the directory: output_dir/&lt;columns[0]&gt;/.../&lt;columns[N]&gt;/basename(&lt;input_file&gt;) where &lt;columns[i]&gt; is the value found in the current line at position i after being split by the specified `delim`. WARNINGS: everything in specified `output_dir` will be PERMANENTLY REMOVED. Arguments: input_file (str): full path to the file to be sharded. output_dir (str): full path to a directory in which to dump. WARNING: everything in specified directory will be PERMANENTLY REMOVED. columns (list): the columns (indices) across which to shard. The values found in these columns will be used as directory names (nested). delim (str): How to split each field in a line of the file. Defaults to '\t'. newline (str): How to split each line of the file. Defaults to '\n'. sil_opts (dict): Defaults to {'length': 40, 'every': 1}. See the Sil package. Returns: sharded_files (list): list of all the sharded files ''' lno = filelines(input_file) # number of lines in the input_file sts = Sil(lno, **sil_opts) # status indicator basename = os.path.basename(input_file) files_made = set({}) file_objs = {} # delete current `output_dir` if it already exists if os.path.isdir(output_dir): shutil.rmtree(output_dir) with open(input_file, 'r') as f: for line in f: fields = linesplit(line, delim, newline) dest = dir_from_cols(fields, columns) files_made.add(dest) dir_path = os.path.join(output_dir, dest) if not os.path.isdir(dir_path): os.makedirs(dir_path) file_objs[dir_path] = open(os.path.join(dir_path, basename), 'a') o = file_objs[dir_path] o.write(linemend(fields, delim, newline)) suffix = '\t{} files made'.format(len(files_made)) sts.tick(suffix=suffix) # close all made file objects for fo in file_objs.values(): fo.close() return self.shard_files(output_dir) def shard_by_lines(self, input_file:str, output_dir:str, number_of_lines:int, sil_opts:dict = default_sil_options )-&gt;list: ''' Given the input_file and the columns, reads each line of the input_file into output files in subdirectories labeled by the line numbers `'start_stop'` based on the value `number_of_lines`: output_dir/&lt;n&gt;_&lt;n+number_of_lines&gt;/basename(&lt;input_file&gt;) WARNINGS: everything in specified `output_dir` will be PERMANENTLY REMOVED. Arguments: input_file (str): full path to the file to be sharded. output_dir (str): full path to a directory in which to dump. WARNING: everything in specified directory will be PERMANENTLY REMOVED. number_of_lines (int): the number of lines which should be at most in each sharded file. sil_opts (dict): Defaults to `{'length': 40, 'every': 1}`. See the Sil package. Returns: sharded_files (list): list of all the sharded files ''' lno = filelines(input_file) sts = Sil(lno, **sil_opts) basename = os.path.basename(input_file) files_made = set({}) file_objs = {} if os.path.isdir(output_dir): shutil.rmtree(output_dir) with open(input_file, 'r') as f: tally = 0 while tally &lt; lno: if tally % number_of_lines == 0: dest = '{}_{}'.format(tally, tally+number_of_lines) files_made.add(dest) dir_path = os.path.join(output_dir, dest) if not os.path.isdir(dir_path): os.makedirs(dir_path) file_objs[dir_path] = open(os.path.join(dir_path, basename), 'a') o = file_objs[dir_path] for i in range(number_of_lines): line = f.readline() if not line: break o.write(line) sts.tick() tally += number_of_lines for fo in file_objs.values(): fo.close() return self.shard_files(output_dir) </code></pre> <h2>retrieving the sharded files:</h2> <pre class="lang-py prettyprint-override"><code>def shard_files(self, directory:str)-&gt;list: ''' Arguments: directory (str): The top-most directory of a shared file. Returns: (list): The list of all files under directory (regardless of depth). ''' file_paths = [] for path, subdirs, files in os.walk(directory): if not files: continue file_paths += [ os.path.join(path, f) for f in files if 'DS_Store' not in f ] return file_paths </code></pre> <h2>restoring a shard:</h2> <pre class="lang-py prettyprint-override"><code> def assemble_shard(self, directory:str, delim:str='\t', newline:str='\n')-&gt;list: ''' Arguments: directory (str): The top-most directory of a shared file. Keyword Arguments: delim (str): Defaults to '\t' newline (str): Defaults to '\n' Returns: (list): The list of lists, where each sub-list is a record found in one of the sharded leaf files after being split by delim. (i.e. all records are returned together) ''' results = [] files = self.shard_files(directory) with Pool(processes=os.cpu_count()) as pool: sarg = [(f, delim, newline) for f in files] lines = pool.starmap(readlines_split, sarg) return list(itertools.chain.from_iterable(lines)) </code></pre> <h2>Shard across lines</h2> <pre class="lang-py prettyprint-override"><code>def shard_line_apply(self, directory:str, function, args:list=[], kwargs:dict={}, processes:int=None, sil_opts:dict=default_sil_options ): ''' Parallelizes `function` across each _line_ of the sharded files found as the leaves of `directory`. Notes: - if `processes` is None, **all** of them will be used i.e. `os.cpu_count()` - Several keywords for `kwargs` are reserved: 1. lock: a lock, if needed, to prevent race conditions. 2. full_path: the full path to the file which was opened. 3. relative_path: the path under (directory) to the file which was opened. 4. output_shard_name: if provided will rename the shard 5. output_shard_loc: if provided will move the shard Arguments: directory (str): The top-most directory of a shared file. function (func): The function which will be parallelized. This function **MUST** be defined so that it can be called as: `function(line, *args, **kwargs)` Keyword Arguments: args (list): arguments to be passed to `function` on each thread. kwargs (dict): key-word arguments to be passed to `function` on each thread. processes (int): The number of processes to spawn. Defaults to **ALL** availble cpu cores on the calling computer. sil_opts (dict): Defaults to `{'length': 40, 'every': 1}`. See the Sil package. Returns: None ''' if processes is None: processes = os.cpu_count() sfiles = self.shard_files(directory) records = self.sharded_records(sfiles) sts = Sil(records, **sil_opts) with Pool(processes=processes) as pool: self._shared_current.value = -1 sargs = [ (directory, file, sts, function, args, kwargs) for file in sfiles ] results = pool.starmap(self._shard_line_apply, sargs) pool.close() pool.join() pool.terminate() return results def _shard_line_apply(self, directory:str, file:str, status, function, args:list, kwargs:dict ): # multiprocessing.Lock kwargs['lock'] = self._shared_lock # multiprocessing.Value (shared memory counter for progress bar) kwargs['shared_current'] = self._shared_current # an instance of Sil kwargs['status'] = status # full path to the current sharded file being processes kwargs['full_path'] = file kwargs['shard_name'] = shardname(file, directory) kwargs['shard_dir'] = sharddir(file, directory) kwargs['shard_loc'] = shardloc(file, directory) kwargs['relative_path'] = os.path.join(*superdirs(file, directory)) kwargs['current_process'] = current_process().name cp = kwargs['current_process'] force_overwrite = kwargs['force_overwrite'] if 'force_overwrite' in kwargs else True os_name = kwargs['output_shard_name'] if 'output_shard_name' in kwargs else None os_loc = kwargs['output_shard_loc'] if 'output_shard_loc' in kwargs else kwargs['shard_loc'] if os_name is not None: dest = os.path.join(os_loc, os_name, os.path.dirname(kwargs['relative_path'])) kwargs['dest'] = dest self._shared_lock.acquire() try: if os.path.isdir(dest): if force_overwrite: shutil.rmtree(dest) else: os.makedirs(dest) finally: self._shared_lock.release() with open(file, 'r') as f: for line in f: function(line, *args, **kwargs) self._shared_lock.acquire() try: self._shared_current.value += 1 suffix = '\tprocess: {}'.format(cp) status.update(current=self._shared_current.value, suffix=suffix) finally: self._shared_lock.release() </code></pre> <h2>Shard across files</h2> <pre class="lang-py prettyprint-override"><code>def shard_file_apply(self, directory:str, function, args:list=[], kwargs:dict={}, processes:int=None, sil_opts:dict=default_sil_options ): ''' Parallelizes `function` across each of the sharded files found as the leaves of `directory`. Notes: - if `processes` is None, **all** of them will be used i.e. `os.cpu_count()` - Several keywords for `kwargs` are reserved: 1. lock: a lock, if needed, to prevent race conditions. 2. full_path: the full path to the file which was opened. 3. relative_path: the path under (directory) to the file which was opened. 4. output_shard_name: if provided will rename the shard 5. output_shard_loc: if provided will move the shard Arguments: directory (str): The top-most directory of a shared file. function (func): The function which will be parallelized. This function **MUST** be defined so that it can be called as: `function(line, *args, **kwargs)` Keyword Arguments: args (list): arguments to be passed to `function` on each thread. kwargs (dict): key-word arguments to be passed to `function` on each thread. processes (int): The number of processes to spawn. Defaults to **ALL** availble cpu cores on the calling computer. sil_opts (dict): Defaults to `{'length': 40, 'every': 1}`. See the Sil package. Returns: None ''' if processes is None: processes = os.cpu_count() sfiles = self.shard_files(directory) records = self.sharded_records(sfiles) sts = Sil(records, **sil_opts) with Pool(processes=processes) as pool: self._shared_current.value = -1 sargs = [ (directory, file, sts, function, args, kwargs) for file in sfiles ] pool.starmap(self._shard_file_apply, sargs) pool.close() pool.join() pool.terminate() def _shard_file_apply(self, directory:str, file:str, status, function, args:list, kwargs:dict ): # multiprocessing.Lock kwargs['lock'] = self._shared_lock # multiprocessing.Value (shared memory counter for progress bar) kwargs['shared_current'] = self._shared_current kwargs['status'] = status kwargs['full_path'] = file kwargs['shard_name'] = shardname(file, directory) kwargs['shard_dir'] = sharddir(file, directory) kwargs['shard_loc'] = shardloc(file, directory) kwargs['relative_path'] = os.path.join(*superdirs(file, directory)) kwargs['current_process'] = current_process().name force_overwrite = kwargs['force_overwrite'] if 'force_overwrite' in kwargs else True os_name = kwargs['output_shard_name'] if 'output_shard_name' in kwargs else None os_loc = kwargs['output_shard_loc'] if 'output_shard_loc' in kwargs else kwargs['shard_loc'] if os_name is not None: dest = os.path.join(os_loc, os_name, os.path.dirname(kwargs['relative_path'])) kwargs['dest'] = dest self._shared_lock.acquire() try: if os.path.isdir(dest): if force_overwrite: shutil.rmtree(dest) else: os.makedirs(dest) finally: self._shared_lock.release() function(file, *args, **kwargs) </code></pre> <h2>random utils</h2> <pre class="lang-py prettyprint-override"><code>import os def filelines(full_filename): """ Quickly returns the number of lines in a file. Returns None if an error is raised. """ with open(full_filename, 'r') as file: return sum(1 for line in file) return None def slices(arr, slcs): ''' Args: arr (list): a list of elements. slcs (list): a list of slice specifications. Returns: (list): A list of elements extracted from arr given all slcs. ''' return [col for slc in slcs for col in arr[slc]] def linesplit(line, delim='\t', newline='\n'): ''' Args: line (str): a line in a file Kwargs: delim (str): Defaults to '\t'. newline (str): Defaults to '\n' Returns: (str): the line split and devoid of newline. ''' return line.rstrip(newline).split(delim) def linemend(line, delim='\t', newline='\n'): ''' Args: line (str): a line in a file Kwargs: delim (str): Defaults to '\t'. newline (str): Defaults to '\n' Returns: (str): the line joined and given a newline. (opposite of linesplit) ''' return delim.join(line)+newline def readsplit(file_object, delim='\t', newline='\n'): ''' Args: file_object (file object): an opened file Kwargs: delim (str): Defaults to '\t'. newline (str): Defaults to '\n' Returns: (str): Calls linesplit on file_object.readline() ''' return linesplit(file_object.readline(), delim, newline) def readslice(file_object, slcs, delim='\t', newline='\n', add_newline_q=True): ''' Args: file_object (file object): an opened file slcs (list):a list of slice specifications. Kwargs: delim (str): Defaults to '\t'. newline (str): Defaults to '\n' add_newline_q (bool): Defaults to True Returns: (str): Reads the line, splits it by slice, and then joins it back together. ''' return delim.join(slices(readsplit(file_object, delim, newline), slcs)) \ + (newline if add_newline_q else '') def lineslice(line, slcs, delim='\t', newline='\n', add_newline_q=True): ''' Args: line (str): a line in a file slcs (list):a list of slice specifications. Kwargs: delim (str): Defaults to '\t'. newline (str): Defaults to '\n' add_newline_q (bool): Defaults to True Returns: (str): Reads the line, splits it by slice, and then joins it back together. ''' return delim.join(slices(linesplit(line, delim, newline), slcs)) \ + (newline if add_newline_q else '') def superdirs(location, up_to): ''' Args: location (str): a full path. up_to (str): a sub-specficiation of full path. e.g. root --&gt; dir_x where full path is: /dir_1/.../dir_x/.../dir_n Returns: (list): list of directories that come after up_to in location ''' relative_path = location.replace(up_to, '').lstrip('/') sups = list(filter(lambda s: s is not '', relative_path.split('/'))) return sups def sharddir(location, up_to): ''' Args: location (str): a full path. up_to (str): a sub-specficiation of full path. e.g. root --&gt; dir_x where full path is: /dir_1/.../dir_x/.../dir_n Returns: (str): all the directories prior to up_to (dir_x) ''' supdirs = os.path.join(*superdirs(location, up_to)) return location.replace(supdirs, '').rstrip('/') def shardname(location, up_to): ''' Args: location (str): a full path. up_to (str): a sub-specficiation of full path. e.g. root --&gt; dir_x where full path is: /dir_1/.../dir_x/.../dir_n Returns: (str): the name of the directory prior to up_to (dir_x). ''' return os.path.basename(sharddir(location, up_to)) def shardloc(location, up_to): ''' Args: location (str): a full path. up_to (str): a sub-specficiation of full path. e.g. root --&gt; dir_x where full path is: /dir_1/.../dir_x/.../dir_n Returns: (str): the name of the directory prior to up_to (dir_x). ''' return os.path.dirname(sharddir(location, up_to)) def readlines_split(file, delim='\t', newline='\n'): lines = [] with open(file, 'r') as f: for line in f: lines.append(linesplit(line, delim, newline)) return lines def dir_from_cols(fields, cols): ''' Args: fields (list): elements in a record. cols (list): list of column indicies to take. Returns: (str): the directory produced by taking fields[cols[i]] for each column. e.g. fields[cols[0]]/.../fields[cols[n]] ''' return os.path.join(*[fields[i] for i in cols]) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T13:41:04.527", "Id": "433638", "Score": "0", "body": "What is `linesplit`? I don't see a definition for it. Please include all of your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T13:42:54.507", "Id": "433639", "Score": "0", "body": "@Reinderien as stated in OP, all code is available on the repo and pypi. I was only including the relevant logic for the parts in question. Linesplit, can be found [here](https://gitlab.com/SumNeuron/parpar/blob/master/parpar/utils.py) and is in essence `line.rstrip(newline).split(delim)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T13:43:23.573", "Id": "433640", "Score": "0", "body": "Policy for StackExchange is that you post everything." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T13:46:21.453", "Id": "433641", "Score": "0", "body": "@Reinderien eh. Sometimes everything is more cumbersome than a jsfiddle, google colab, etc. these util functions just increase the question length without really adding anything of substance especially as the code is provided elsewhere. I added it because you asked for it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T13:47:39.973", "Id": "433642", "Score": "1", "body": "The rationale is shown here: https://codereview.meta.stackexchange.com/a/9069/25834" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T13:49:09.707", "Id": "433645", "Score": "0", "body": "@Reinderien I am not disagreeing with the rational. However, these simple utils e.g. `lineslice` would be the same as if I added code from another package from my point of view (e.g. if I used numpy, I doubt you would ask me to provide numpy source code)" } ]
[ { "body": "<h2>Mutable default arguments</h2>\n\n<p><code>sil_opts:dict = default_sil_options</code></p>\n\n<p>This can create some nasty bugs, and some Python inspectors specifically recommend against doing this. The alternative is to set the default to <code>None</code>, and then write an <code>if</code> in your function to assign the default dictionary if the argument is <code>None</code>.</p>\n\n<h2>Redundant <code>return</code></h2>\n\n<p>It seems like you intend for this to return <code>None</code> if something bad happens. That's not how it actually works - instead, when an exception is thrown, there is no return statement executed at all. </p>\n\n<pre class=\"lang-py prettyprint-override\"><code> with open(full_filename, 'r') as file:\n return sum(1 for line in file)\n return None\n</code></pre>\n\n<p>For this to work as you intend, you need to add a <code>try</code>/<code>except</code>.</p>\n\n<h2>Quote standard</h2>\n\n<p>You use a mix of double-quotes and single-quotes in your docstrings. PyCharm suggests double quotes, but whatever you do, get consistent.</p>\n\n<h2>Meaningful documentation</h2>\n\n<p>It's great that you've added a lot of documentation. The next step is to make it actually mean something. For example, this:</p>\n\n<pre><code>add_newline_q (bool): Defaults to True\n</code></pre>\n\n<p>is deeply unhelpful. The type and default are already obvious, due to the function signature. So what does this actually do?</p>\n\n<h2>Consider using more comprehensions</h2>\n\n<pre><code>sups = list(filter(lambda s: s is not '', relative_path.split('/')))\n</code></pre>\n\n<p>may be more easily expressed as</p>\n\n<pre><code>sups = [s for s in relative_path.split('/') if s != '']\n</code></pre>\n\n<h2>Generators</h2>\n\n<p>In the same <code>sharddir</code> function, rather than returning a list (which forces the use of memory), you can leave it as a generator:</p>\n\n<pre><code>return (s for s in relative_path.split('/') if s != '')\n</code></pre>\n\n<p>This allows the caller to decide whether they want to materialize the generator into memory, or only iterate over it.</p>\n\n<h2>Quickly isn't quickly</h2>\n\n<pre><code>\"\"\"\nQuickly returns the number of lines in a file.\n\"\"\"\n</code></pre>\n\n<p>Unfortunately, this isn't a \"quick\" operation. Given that your focus here is on parallel performance, you need to rethink how to divide up your file into lines. You should <em>not</em> be doing a pre-parse step. Instead, the most reasonable approach is to probably get the file size, divide it by the number of workers, seek to the boundaries in the file between each chunk, find the actual file boundary, and then give each worker its start and end offset. Otherwise, counting each line in a file is both expensive and non-parallel.</p>\n\n<h2>Performance of <code>readlines_split</code></h2>\n\n<pre class=\"lang-py prettyprint-override\"><code>def readlines_split(file, delim='\\t', newline='\\n'):\n\n lines = []\n with open(file, 'r') as f:\n for line in f:\n lines.append(linesplit(line, delim, newline))\n return lines\n</code></pre>\n\n<p>This function is performance-problematic for a few reasons. You're building up a list in memory, when you shouldn't. If you're assembling a \"shard file\" whose contents are totally unmodified from the source file other than being a subset, then this is not a good way to go. If the line count distribution between shards needs to be exact, then each worker should be counting the number of newlines in its chunk. If not, don't even count (and certainly don't create a list). Once the actual boundaries are determined, write out the chunk from the source to the destination, potentially in sub-chunks of a few MB.</p>\n\n<h2>Usage of <code>kwargs</code></h2>\n\n<p>This chunk:</p>\n\n<pre><code>def foo(file, a, b, **kwargs):\n print(file, kwargs[\"dest\"])\n\nppf.shard_file_apply(\n './short-lines', # sharded directory\n foo,\n args=[1,2],\n kwargs={\n \"output_shard_name\": 'short-lines-alt',\n \"output_shard_loc\": os.path.expanduser('~/Desktop')\n</code></pre>\n\n<p>shows you using kwargs in a somewhat awkward way. You should probably change the first instance to</p>\n\n<pre><code>def foo(file, a, b, dest):\n print(file, dest)\n</code></pre>\n\n<p>Any argument can still be a named argument from the caller, including <code>dest</code>.</p>\n\n<p>As to the second instance, probably change to</p>\n\n<pre><code>ppf.shard_file_apply(\n './short-lines', # sharded directory\n foo,\n args=[1,2],\n output_shard_name='short-lines-alt',\n output_shard_loc=os.path.expanduser('~/Desktop')\n</code></pre>\n\n<p>Those last two argument can still be captured in <code>kwargs</code> without you passing a dictionary explicitly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T09:55:58.457", "Id": "433731", "Score": "0", "body": "I appreciate your time and insights. Didn't know about the mutable default arguments or the redundant return. Indeed I should lint to use one or the other :P for quotes and my docs have improved since the util functions (not what I wanted to be evaluated); that said, I disagree with the example you picked out (`add_newline_q (bool)`) is self explanatory. The comprehension idea is something worthwhile for integrating going forward. The \"quickly\" comes from a python question on S.O. regarding fastest way to get line numbers in python." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T10:01:28.517", "Id": "433736", "Score": "0", "body": "regarding `readline_split` this is meant for a derived shard (after applying a function to each subfile / line). Sharding by lines does not require equal line numbers per shard so your recommend approach won't work in that case. The idea there was to get a shard into memory... after maybe applying some functions on it (e.g. via `shard_file_apply`) and writing new files after processing each subfile" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T10:37:53.320", "Id": "433737", "Score": "0", "body": "would appreciate your take on https://codereview.stackexchange.com/questions/223726/python-and-numba-are-wrapper-functions-leaky" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T12:39:30.677", "Id": "433762", "Score": "0", "body": "\"The \"quickly\" comes from a python question on S.O.\" - be that as it may, the problem isn't how you're doing it, the problem is that you're doing it at all. \"Sharding by lines does not require equal line numbers per shard\" - great! In that case, don't do line counting. Split up the source file into chunks by equal byte count." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T14:39:01.717", "Id": "433800", "Score": "0", "body": "So in the design goals I explicitly state that I want to be able to have a progress bar using shared memory so I can see how I progress across the shards and since each line is treated like a record, I do not like the idea of having a record split across more than one file due to byte counts. Not every record is the same number of bytes. While using bytes may be more performant, the costs saved in this instance I am not sure are worth it. However I may very well be wrong. As for the use of args and kwargs I can see what you are saying, somewhat." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T14:40:43.370", "Id": "433802", "Score": "0", "body": "but `shard_file_apply` calls `_shard_file_apply`, which calls `function(file, *args, **kwargs)`. My original approach was to keep it clear what args / kwargs are meant for the threaded function and which are utility variables provided by the class" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T14:08:31.850", "Id": "223674", "ParentId": "223665", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T10:03:49.963", "Id": "223665", "Score": "3", "Tags": [ "python", "performance", "python-3.x", "multithreading", "multiprocessing" ], "Title": "Simple sharding of delimited files to more sophisticated" }
223665
<p>I developed a small package to do matrix math. I just learned Go so I may have done it wrong.</p> <pre><code>package matrix import "fmt" import "errors" import "math" type Matrix [][]float64 func Print(m Matrix) { fmt.Println(m) } func Zeros(rows, cols int) Matrix { m := make([][]float64, rows) for i := 0; i &lt; rows; i++ { m[i] = make([]float64, cols) } return m } func Map(f func(float64) float64, m Matrix) Matrix { mapped := Zeros(len(m), len(m[0])) for i, row := range m { for j, val := range row { mapped[i][j] = f(val) } } return mapped } func Norm(m Matrix) float64 { var norm float64 for _, row := range m { for _, val := range row { norm += math.Abs(val) } } return norm } func Transpose(m Matrix) Matrix { transposed := Zeros(len(m[0]), len(m)) for i, row := range m { for j, val := range row { transposed[j][i] = val } } return transposed } func Multiply(a, b Matrix) (Matrix, error) { if len(a[0]) != len(b) { return nil, errors.New("Multiplication is not defined") } m := Zeros(len(a), len(b[0])) for i := 0; i &lt; len(a); i++ { for j := 0; j &lt; len(b[0]); j++ { for k := 0; k &lt; len(b); k++ { m[i][j] += a[i][k] * b[k][j] } } } return m, nil } </code></pre> <p>And here is a code using the package:</p> <pre><code>package main import "matrix" func main() { m := matrix.Map(func (f float64) float64 { return 1 }, matrix.Zeros(2, 2)) prod, _ := matrix.Multiply(m, m) println(matrix.Norm(prod)) } </code></pre>
[]
[ { "body": "<p>In your code you often use the expressions <code>len(m)</code> and <code>len(m[0])</code>. The code would become clearer if you defined proper names for these expressions, like:</p>\n\n<pre><code>func (m Matrix) Rows() int { return len(m) }\nfunc (m Matrix) Cols() int { return len(m[0]) }\n</code></pre>\n\n<p>This way, you can write <code>zeros := matrix.Zeros(m.Rows(), m.Cols())</code>, which make the code operate in mathematical terms instead of those of the implementing programming language. These additional methods won't affect the performance of your program since the compiler will generate equally efficient code for these method calls. You can verify this by looking at the generated assembly code using <code>go tool objdump</code>. And if there should really be a difference, file a bug report at <a href=\"https://github.com/golang/go/issues\" rel=\"nofollow noreferrer\">https://github.com/golang/go/issues</a>.</p>\n\n<p>To see whether you defined a good API for your matrix package, you should write a corresponding unit test:</p>\n\n<pre><code>package matrix_test\n\nimport \"testing\"\n\nfunc TestZeros(t *testing.T) {\n m := matrix.Zeros(3, 3)\n ...\n}\n</code></pre>\n\n<p>Note that I wrote <code>package matrix_test</code> instead of the usual <code>package matrix</code>. This little change (which is also little-known) makes this test file a black-box test, which can only access the exported things from the <code>matrix</code> package.</p>\n\n<p>At this point I thought that there were no way to access an individual element of the matrix. Therefore you should add another method:</p>\n\n<pre><code>func (m Matrix) At(row, col int) float64 { return m[row][col] }\n</code></pre>\n\n<p>Maybe it is possible to access the matrix elements using the <code>[]</code> operator, but I would not recommend this since you might want to implement the matrix later in a different way. Maybe you will mainly handle sparse matrices, where most of the elements are zero. Then you would need to change the implementation type to be more memory-efficient, and that change should not affect any code that already uses your package.</p>\n\n<p>Another benefit of the <code>At</code> method is that it clearly defines that the ordering of the coordinates is <code>row, col</code>. I don't know whether mathematicians are always consistent about this little detail, so it's better to explicitly document it somewhere. Programmers definitely aren't consistent in this regard, not even after 60 years of confusion. There's <code>(x, y)</code>, <code>(top, left)</code>, <code>(left, top)</code>, <code>(height, width)</code>, <code>(row, col)</code>, <code>(col, row)</code>, and so on.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T17:22:47.677", "Id": "435030", "Score": "1", "body": "Wondeful! Yeah mathematicians always choose the row/col order :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-16T03:59:01.850", "Id": "224265", "ParentId": "223672", "Score": "1" } }, { "body": "<p>As for your multiply algorithm, it’s an <span class=\"math-container\">\\$n^3\\$</span> algorithm. Look at some other implementations for a more efficient way to do this.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-25T13:17:54.863", "Id": "231305", "ParentId": "223672", "Score": "1" } } ]
{ "AcceptedAnswerId": "224265", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T11:29:49.760", "Id": "223672", "Score": "4", "Tags": [ "beginner", "matrix", "go" ], "Title": "Golang matrix package" }
223672
<p>I have started to learn Java for the past 20 days with no prior coding/comp science experience.</p> <p>My brother gave me an idea to make a subnet calc/ping tool to enhance my knowledge and mentored through this.</p> <p>Just wanted to know how can I upgrade this code and if I have used proper language idioms in this code. Any ideas to simplify/features for more learning would be appreciated.</p> <pre><code>import java.util.*; import java.util.regex.Pattern; import java.math.*; import java.text.NumberFormat; import java.text.ParseException; import java.net.*; public class example { public static void main(String[] args) { Scanner Scan = new Scanner(System.in); System.out.print("Enter IP: "); String IP; IP = Scan.nextLine(); String Z = IP.split("\\/")[1]; String Y = IP.split("\\/")[0]; String[] parts = Y.split("\\."); String F1 = parts[0]; String F2 = parts[1]; String F3 = parts[2]; String F4 = parts[3]; int A = Integer.parseInt(F1); int B = Integer.parseInt(F2); int C = Integer.parseInt(F3); int E = Integer.parseInt(F4); { System.out.println(F1 + "." + F2 + "." + F3 + "." + F4); } String X = (IP.substring(IP.lastIndexOf("/") + 1)); { System.out.println(X); } int S = Integer.parseInt(X); double Bits = 32; double TotalBites = Bits - S; double I = Math.pow(2, TotalBites); int D = (int)(I - 2); { System.out.println(D); } List &lt; String &gt; Hosts = new ArrayList &lt; String &gt; (); if (S &gt;= 24) { int val = (int) TotalBites - 0; String bitsda = stringMultiply("0", val); String bitstoconvert = "1" + bitsda; int decimal = Integer.parseInt(bitstoconvert, 2) - 1; //String bits = Strings.repeat("0", val); for (int IPF4 = E; IPF4 &lt;= decimal; IPF4++) { Hosts.add(F1 + "." + F2 + "." + F3 + "." + IPF4); } } else if (S &gt;= 16) { int val = (int) TotalBites - 8; String bitsda = stringMultiply("0", val); String bitstoconvert = "1" + bitsda; int decimal = Integer.parseInt(bitstoconvert, 2) - 1; //String bits = Strings.repeat("0", val); for (int IPF3 = C; IPF3 &lt;= decimal; IPF3++) { for (int IPF4 = E; IPF4 &lt;= 255; IPF4++) Hosts.add(F1 + "." + F2 + "." + IPF3 + "." + IPF4); } } else if (S &gt;= 8) { int val = (int) TotalBites - 16; String bitsda = stringMultiply("0", val); String bitstoconvert = "1" + bitsda; int decimal = Integer.parseInt(bitstoconvert, 2) - 1; //String bits = Strings.repeat("0", val); for (int IPF2 = B; IPF2 &lt;= decimal; IPF2++) { for (int IPF3 = C; IPF3 &lt;= 255; IPF3++) for (int IPF4 = E; IPF4 &lt;= 255; IPF4++) Hosts.add(F1 + "." + IPF2 + "." + IPF3 + "." + IPF4); } } Hosts.forEach(host -&gt; pingIt(host)); } public static void pingIt(String host) { try { String ipAddress = host; InetAddress inet = InetAddress.getByName(ipAddress); System.out.println("Sending Ping Request to " + ipAddress); if (inet.isReachable(5000)) { System.out.println(ipAddress + " is reachable."); } else { System.out.println(ipAddress + " NOT reachable."); } } catch (Exception e) { System.out.println("Exception:" + e.getMessage()); } } public static String stringMultiply(String s, int n) { StringBuilder sb = new StringBuilder(); for (int i = 0; i &lt; n; i++) { sb.append(s); } return sb.toString(); } } </code></pre>
[]
[ { "body": "<p>Splitting the input, parsing the parts, figuring the bits and filling the hosts list should all be seperate methods that return the results to main. <br>\nEvery method should perform a simple task. If you list the steps necessary to perform an action, each step should be a separate method. <br>\nCommenting a methods purpose above it will help you and others understand it's inner workings. <br>\nBits and bites are not the same thing. \n<code> double totalbites = Bits - S; </code><br>\nAlso variable names should not start with a capital unless they are all capitals. <br>\nVariable names like A, B, C, E, X, S are not very helpful.<br> input1, input2,... and num1, num2,... would convey a clearer picture of these variables purpose. <br>\nUse comments to explain the actions taking place. <br></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T15:52:57.240", "Id": "223681", "ParentId": "223677", "Score": "4" } }, { "body": "<h2>Requirements?</h2>\n\n<p>Please state a short bit about what the requirements are, so we can more easily check how your code might be improved accordingly. </p>\n\n<h2>Java Naming Conventions</h2>\n\n<p>Please stick to the <a href=\"https://www.oracle.com/technetwork/java/codeconventions-135099.html\" rel=\"nofollow noreferrer\">Java Naming Conventions</a>! (Classes with capital, variables in lowerCamelCase, etc)</p>\n\n<h2>Don't use String to store information</h2>\n\n<p>Prefer using a custom class to store information, for example, you store ipv4 addresses in a <code>String</code>. Better to create a class for that.</p>\n\n<pre><code>public class IPv4\n{\n String s1,s2,s3,s4;\n\n public IPv4(String s1, String s2, String s3, String s4)\n {\n this.s1 = s1;\n ....\n }\n\n public String toString() \n {\n ...\n }\n}\n</code></pre>\n\n<h2>Reuse</h2>\n\n<p>I noticed this repeating pattern a few times:</p>\n\n<pre><code> F1 + \".\" + F2 + \".\" + F3 + \".\" + IPF4\n</code></pre>\n\n<p>It might be worth extracting a method that does exacly this (for example like so):</p>\n\n<pre><code>public static String toIpV4(String s1, String s2, String s3, String s4)\n{\n return String.format(\"%s.%s.%s.%s\", s1,s2,s3,s4);\n}\n</code></pre>\n\n<h2>Explore Java standard classes and methods</h2>\n\n<p>Java comes with a lot of handy standard methods and classes. Since Java 11 we have <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html\" rel=\"nofollow noreferrer\">String.repeat(int count)</a> , which exactly is what you want in <code>stringMultiply</code>. Just look up the functionality you want, it might already be implemented. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T09:56:13.447", "Id": "223855", "ParentId": "223677", "Score": "4" } } ]
{ "AcceptedAnswerId": "223855", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T14:56:44.627", "Id": "223677", "Score": "2", "Tags": [ "java", "beginner", "networking", "ip-address" ], "Title": "Simple subnet calculator and parser" }
223677
<p>I want to know how to improve the design of Canvas drawing implementation.</p> <h1>Canvas Drawing</h1> <p>This solution is to implement a console-based canvas drawing application.</p> <h2>Problem Statement</h2> <h3>Description</h3> <p>You're given the task of writing a simple console version of a drawing program. At this time, the functionality of the program is quite limited but this might change in the future. In a nutshell, the program should work as follows:</p> <ol> <li>Create a new canvas</li> <li>Start drawing on the canvas by issuing various commands</li> <li>Quit</li> </ol> <h3>Commands</h3> <ul> <li><code>C <em>w h</em></code> Should create a new canvas of width <em>w</em> and height <em>h</em>.</li> <li><code>L <em>x1 y1 x2 y2</em></code> Should create a new line from (<em>x1</em>,<em>y1</em>) to (<em>x2</em>,<em>y2</em>). Currently only horizontal or vertical lines are supported. Horizontal and vertical lines will be drawn using the 'x' character.</li> <li><code>R <em>x1 y1 x2 y2</em></code> Should create a new rectangle, whose upper left corner is (<em>x1</em>,<em>y1</em>) and lower right corner is (<em>x2</em>,<em>y2</em>). Horizontal and vertical lines will be drawn using the 'x' character.</li> <li><code>B <em>x y c</em></code> Should fill the entire area connected to (<em>x</em>,<em>y</em>) with "color" <em>c</em>. The the behavior of this is the same as that of the "bucket fill" tool in paint programs.</li> <li><code>Q</code> Should quit the program.</li> </ul> <p><strong>Sample I/O</strong></p> <p>Below is a sample run of the program. User input is prefixed with entering the command:</p> <pre><code>enter the command: C 20 4 ---------------------- | | | | | | | | ---------------------- enter command: L 1 2 6 2 ---------------------- | | |xxxxxx | | | | | ---------------------- enter command: L 6 3 6 4 ---------------------- | | |xxxxxx | | x | | x | ---------------------- enter command: R 14 1 18 3 ---------------------- | xxxxx | |xxxxxx x x | | x xxxxx | | x | ---------------------- enter the command: B 10 3 o ---------------------- |oooooooooooooxxxxxoo| |xxxxxxooooooox xoo| | xoooooooxxxxxoo| | xoooooooooooooo| ---------------------- enter the command: Q </code></pre> <h2>Design</h2> <h3>Class Overview</h3> <ul> <li>org.draw.paint <ul> <li>CanvasRunner - <strong>Entry Point</strong>.It reads the console command and executes them.</li> </ul></li> <li>org.draw.paint.painter <ul> <li>Painter - Base for all painters</li> <li>BoxPainter - Painter to draw a Box in the canvas.</li> <li>FillPainter - Painter to Fill closed area in the canvas with the given color.</li> <li>LinePainter - Painter to draw a line in the canvas</li> <li>RectanglePainter - Painter to draw a rectangle on the canvas.</li> <li>CanvasPainter - Draws the Canvas with giving width and height.</li> </ul></li> <li>org.draw.paint.canvas <ul> <li>ICanvas - Base for all Canvas</li> <li>Canvas - Area with the given width and Height that holds drawing</li> <li>Pixel - Tiny part of Canvas which hold the draw value.</li> <li>CanvasConstants - Canvas Constants.</li> </ul></li> </ul> <h3>Class Diagram Overview</h3> <hr> <p><a href="https://i.stack.imgur.com/yqsGh.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yqsGh.jpg" alt="Class Diagram"></a></p> <h3>Code</h3> <p><strong>Canvas Runner</strong> </p> <pre><code>package org.draw.paint import org.draw.paint.canvas.Canvas import org.draw.paint.canvas.ICanvas import org.draw.paint.command.CommandParser import org.draw.paint.common.Status import org.draw.paint.exception.CanvasExceptions import org.slf4j.LoggerFactory import java.util.* fun main(args: Array&lt;String&gt;) { val canvasRunner = CanvasRunner() canvasRunner.start() } class CanvasRunner { companion object { private val log = LoggerFactory.getLogger(CanvasRunner::class.java) } private var canvas: ICanvas = Canvas() private fun readLine(): String { val scanner = Scanner(System.`in`) return scanner.nextLine() } internal fun executeCommand(command: String) { val status = CommandParser.parse(cmd = command).paint(canvas = canvas) if(status.isSuccess()) { canvas.printScreen() } Status.statusProcessor(status = status) } private fun executeConsoleCommands() { var command: String do { print("Enter Command :") command = this.readLine() log.trace("Received instruction as $command") this.executeCommand(command = command) } while (true) } fun start() { executeConsoleCommands() } } </code></pre> <p><strong>Command Parser</strong></p> <pre><code>package org.draw.paint.command import org.draw.paint.canvas.ICanvas import org.draw.paint.canvas.Position import org.draw.paint.common.Failed import org.draw.paint.common.Status import org.draw.paint.exception.CanvasExceptions import org.draw.paint.painter.* import org.slf4j.LoggerFactory import kotlin.system.exitProcess object CommandParser { private val createPainterFunList = mutableListOf&lt;(String) -&gt; Painter?&gt; ( this::createCanvasPainter, this::createFillCommandPainter, this::createLineCommandPainter, this::quiteCommandPainter, this::rectangleCommandPainter ) private val log = LoggerFactory.getLogger(CommandParser::class.java) fun parse(cmd: String): Painter { var failed: Painter = object: Painter { override fun validate(canvas: ICanvas): Status = Failed(reason = "Unable to Execute Command") override fun paint(canvas: ICanvas) : Status = Failed(reason = "Unable to Execute Command") } try { this.createPainterFunList.forEach { fn -&gt; val painter = fn(cmd) if(painter != null) return painter } } catch (e: Exception) { failed = object: Painter { override fun validate(canvas: ICanvas): Status = Failed(reason = e.localizedMessage) override fun paint(canvas: ICanvas) : Status = Failed(reason = e.localizedMessage) } } return failed } private fun parseCommand(regex: Regex, string: String): MatchResult.Destructured ? { try { if(regex.matches(string)) { val result = regex.find(string) return result?.destructured ?: throw CanvasExceptions("Unable to parse Canvas Command") } } catch (e: Exception) { log.error("Error Parsing the Canvas Command", e) throw CanvasExceptions(throwable = e) } return null } fun createCanvasPainter(cmd: String):Painter? { val cmdPattern = """[Cc]\s+(\d+)\s+(\d+)""".toRegex() val (width , height) = this.parseCommand(regex = cmdPattern, string = cmd) ?: return null return CanvasPainter(width = width.toInt(), height = height.toInt()) } private fun createFillCommandPainter(cmd: String): Painter? { val templateRegex = """[Bb]\s+(\d+)\s+(\d+)\s+(.)""".toRegex() val (sw,sh,colour) = this.parseCommand(regex = templateRegex, string = cmd) ?: return null return FillPainter(start = Position(x = sw.toInt(), y = sh.toInt()) ,colour = colour) } private fun createLineCommandPainter(cmd:String): Painter? { val templateRegex = """[Ll]\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)""".toRegex() val (sw,sh,ew,eh) = this.parseCommand(regex = templateRegex, string = cmd) ?: return null return LinePainter(start = Position(x = sw.toInt(), y= sh.toInt()), end = Position(x = ew.toInt(), y = eh.toInt())) } private fun quiteCommandPainter(cmd: String) : Painter? { val templateRegex = """[Qq]""".toRegex() if(templateRegex.matches(cmd)) { exitProcess(status = 0) } return null } private fun rectangleCommandPainter(cmd: String): Painter? { val templateRegex = """[Rr]\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)""".toRegex() val (sw,sh,ew,eh) = this.parseCommand(regex = templateRegex, string = cmd) ?: return null return RectanglePainter(start = Position(x = sw.toInt(), y = sh.toInt()), end = Position(x = ew.toInt(), y = eh.toInt())) } } </code></pre> <p><strong>Status Enum</strong></p> <pre><code>package org.draw.paint.common enum class StatusTypes { SUCCESS, FAILED } open class Status(val status: StatusTypes) { companion object{ fun statusProcessor(status: Status) { when(status) { is Success -&gt; println("Done.") is Failed -&gt; println("Err: ${status.reason}") } } } fun isSuccess(): Boolean { return status == StatusTypes.SUCCESS } } class Success: Status(status = StatusTypes.SUCCESS) class Failed(val reason: String):Status(status = StatusTypes.FAILED) </code></pre> <p><strong>Fill Painter</strong></p> <pre><code>package org.draw.paint.painter import org.draw.paint.canvas.ICanvas import org.draw.paint.canvas.Position import org.draw.paint.common.Failed import org.draw.paint.common.Status import org.draw.paint.common.Success import org.slf4j.LoggerFactory class FillPainter(private val start:Position, private val colour: String): Painter { val affectedPositions = mutableListOf&lt;Position&gt;() companion object { private val log = LoggerFactory.getLogger(FillPainter::class.java) } override fun validate(canvas: ICanvas): Status { return if( !canvas.isPositionAvailable(start) ) { Failed("Position Not available") } else if(!canvas.isPositionWritable(start)){ Failed("Position Filled already") } else { Success() } } override fun paint(canvas: ICanvas): Status { var status = this.validate(canvas = canvas) if(status is Failed) { return status } status = this.fillByBreadthFirstSearch(canvas = canvas) log.debug("Affected positions Count = ${affectedPositions.size}") log.trace("Affected positions : $affectedPositions") log.info("Painting of LinePainter completed ") return status } private fun fillByBreadthFirstSearch(canvas: ICanvas) : Success { var temp = start val trackList = mutableListOf&lt;Position&gt;() canvas.setPixelValueAt(pos = temp, value = colour, overwrite = false) affectedPositions.add(temp) var children = canvas.writableChildrenOf(pos = temp) children.forEach { p -&gt; canvas.setPixelValueAt(pos = p, value = colour, overwrite = false) affectedPositions.add(p) trackList.add(p) } while(trackList.size &gt; 0) { temp = trackList.last() trackList.removeAt(trackList.size - 1) children = canvas.writableChildrenOf(pos = temp) children.forEach { p -&gt; canvas.setPixelValueAt(pos = p, value = colour, overwrite = false) affectedPositions.add(p) trackList.add(p) } } return Success() } } </code></pre> <p><strong>Canvas</strong></p> <pre><code>package org.draw.paint.canvas import org.slf4j.LoggerFactory class Canvas(private var width: Int = 0, private var height: Int = 0) : ICanvas { companion object { private val logger = LoggerFactory.getLogger(Canvas::class.java) } private var pixels: Array&lt;Array&lt;Pixel&gt;&gt; init { pixels = initPixel(width = width, height = height) } private fun initPixel(width: Int, height: Int): Array&lt;Array&lt;Pixel&gt;&gt; { return Array(size = height + 2) {i -&gt; Array(size = width + 2){j -&gt; if(i == 0 || i == height + 1) { WidthBorder() } else if(j == 0 || j == width + 1) { HeightBorder() } else { Pixel(txt = CanvasConstants.DEFAULT_DISPLAY_CHAR) } } } } override fun createCanvas(width: Int, height: Int): Boolean { return if(this.width == 0 || this.height == 0) { this.width = width this.height = height this.pixels = initPixel(width = width, height = height) true } else { false } } override fun printScreen() { for(i in this.pixels.indices) { if(i != 0) { println("") } for(j in this.pixels[i].indices) { print(this.pixels[i][j]) } } println() } override fun isPositionAvailable(pos: Position): Boolean { if(this.pixels.isEmpty()) { logger.error("Position is not available") return false } return pos.x &gt; 0 &amp;&amp; pos.y &gt;0 &amp;&amp; this.pixels.size -1 &gt; pos.y &amp;&amp; this.pixels[0].size -1 &gt; pos.x } override fun isPositionWritable(pos: Position): Boolean { return this.isPositionAvailable(pos) &amp;&amp; this.pixels[pos.y][pos.x].isBlank() } override fun getPixelValueAt(pos: Position): String { return if(this.isPositionAvailable(pos)) { this.pixels[pos.y][pos.x].text } else { CanvasConstants.INVALID_TEXT_CHAR } } override fun setPixelValueAt(pos: Position, value: String, overwrite: Boolean) : Boolean { return if(!overwrite &amp;&amp; this.isPositionWritable(pos = pos)) { this.pixels[pos.y][pos.x].text = value true } else if(overwrite){ this.pixels[pos.y][pos.x].text = value true } else { false } } override fun setPixelValueBetween(inclusiveStart: Position, inclusiveEnd: Position, value: String, overwrite: Boolean) : List&lt;Position&gt; { val start = inclusiveStart val end = inclusiveEnd val affectedList = mutableListOf&lt;Position&gt;() if(!this.isPositionAvailable(pos = start) || !this.isPositionAvailable(pos = end)) { return affectedList } val yRange = if (start.y &lt;= end.y) start.y..end.y else start.y downTo end.y val xRange = if (start.x &lt;= end.x) start.x..end.x else start.x downTo end.x for(y in yRange) { for(x in xRange) { val pixel = this.pixels[y][x] pixel.text = value affectedList.add(Position(x = x, y = y)) } } return affectedList } override fun writableChildrenOf(pos: Position): List&lt;Position&gt; { val list = mutableListOf&lt;Position&gt;() if (this.isPositionWritable(Position(x = pos.x, y = pos.y + 1 ))) { list.add(Position(x = pos.x, y = pos.y + 1 )) } if (this.isPositionWritable(Position(x = pos.x, y = pos.y - 1 ))) { list.add(Position(x = pos.x, y = pos.y - 1 )) } if (this.isPositionWritable(Position(x = pos.x + 1, y = pos.y))) { list.add(Position(x = pos.x + 1, y = pos.y)) } if (this.isPositionWritable(Position(x = pos.x - 1, y = pos.y))) { list.add(Position(x = pos.x - 1, y = pos.y)) } return list } } </code></pre> <p><strong>Canvas Interface</strong></p> <pre><code>package org.draw.paint.canvas interface ICanvas { fun createCanvas(width: Int, height:Int): Boolean fun printScreen() fun isPositionAvailable(pos: Position): Boolean fun isPositionWritable(pos: Position): Boolean fun getPixelValueAt(pos: Position): String fun setPixelValueAt(pos: Position, value: String, overwrite: Boolean = true) : Boolean fun setPixelValueBetween(inclusiveStart: Position, inclusiveEnd: Position, value: String, overwrite: Boolean = true) : List&lt;Position&gt; fun writableChildrenOf(pos: Position): List&lt;Position&gt; } </code></pre> <p><strong>Pixel</strong></p> <pre><code>package org.draw.paint.canvas open class Pixel() { var text: String = "" constructor(txt: String): this() { this.text = txt } fun isBlank():Boolean { return this.text.isBlank() } override fun equals(other: Any?): Boolean { return this.text == (other as? Pixel)?.text ?: "UNKNOWN" } override fun hashCode(): Int { return this.text.hashCode() } override fun toString(): String { return this.text } } data class Position(val x: Int, val y:Int) class WidthBorder : Pixel( txt = CanvasConstants.WIDTH_BORDER_CHAR) class HeightBorder : Pixel(txt = CanvasConstants.HEIGHT_BORDER_CHAR) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T15:48:00.253", "Id": "433655", "Score": "0", "body": "Pasted code as suggested. I want to know is there a way to improve the design. I have tried so many time but I could not refactor beyond this. Wanted to know if can be further improved in terms of design" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T15:21:12.963", "Id": "223679", "Score": "2", "Tags": [ "algorithm", "object-oriented", "ascii-art", "interpreter", "kotlin" ], "Title": "Program to draw ASCII art based on commands" }
223679
<p>This is some code that determines if a string of characters is a palindrome or not. My professor says that there is a performance issue with the program, but I can't quite put my finger on it. Can someone find out the 'performance' issue?</p> <p>Initially, I thought maybe the process is slower as it uses two memory containers, as opposed to simply comparing two halves of a single string.</p> <pre><code>int main() { char c; bool check = true; stack&lt;char&gt; cstack; queue&lt;char&gt; cqueue; cout &lt;&lt; "Enter a string and press return." &lt;&lt; endl; cin.get(c); while (c != '\n') { cstack.push(c); cqueue.push(c); cin.get(c); } while (check &amp;&amp; !cqueue.empty()) { if (cstack.top() != cqueue.front()) check = false; cstack.pop(); cqueue.pop(); } if (check) cout &lt;&lt; "Yes it is!" &lt;&lt; endl; else cout &lt;&lt; "No it's not." &lt;&lt; endl; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T16:14:54.207", "Id": "433657", "Score": "0", "body": "Is there a way to combine stack top/pop and queue front/pop in a single statement?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T19:08:14.167", "Id": "433671", "Score": "6", "body": "As an aside, this is nearly a complete program. Consider giving the full program next time in a similar situation (changing this now is inadvisable)." } ]
[ { "body": "<p>I see two improvement points in the code.</p>\n\n<ol>\n<li>It is better to use getLine() and store the input in char* instead of reading each char and appending to a stack</li>\n<li>It is more than enough to iterate till half of the string as the remaining half is checked in the first half iteration <code>cstack.top() != cqueue.front()</code></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T16:15:46.767", "Id": "223683", "ParentId": "223680", "Score": "4" } }, { "body": "<ol>\n<li><p>While it is not quite definitive, it looks like you use <code>using namespace std;</code>.<br>\nThat namespace is not designed for wholesale inclusion, being vast and subject to change at the whim of the implementation, aside from providing what is standardised.<br>\nRead \"<a href=\"https://stackoverflow.com/q/1452721\">Why is “using namespace std” considered bad practice?</a>\" for more detail.</p></li>\n<li><p>Synchronizing C++ iostreams with C stdio, as happens by default, is quite expensive. Call <a href=\"https://en.cppreference.com/w/cpp/io/ios_base/sync_with_stdio\" rel=\"nofollow noreferrer\"><code>std::ios_base::sync_with_stdio(false);</code></a> to fix that.</p></li>\n<li><p>You should desist from using <code>std::endl</code>, as spurious manual flushing flushes any pretense at performance down the drain.<br>\nFor those rare cases where it is actually necessary for correctness, use <a href=\"https://en.cppreference.com/w/cpp/io/manip/flush\" rel=\"nofollow noreferrer\"><code>std::flush</code></a> for explicitness.</p></li>\n<li><p>You assume reading from <code>std::cin</code> always succeeds. That's generally unsupportable, please handle failure gracefully.</p></li>\n<li><p>You are reading character-by-character. Each and every read has significant overhead, which you could simply avoid by using <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/getline\" rel=\"nofollow noreferrer\"><code>std::getline()</code></a>. Using the proper abstraction is also significantly more readable.</p></li>\n<li><p>You are storing the input twice, once in a <code>std::queue</code> and once in a <code>std::stack</code>. Even only storing it in just one <code>std::deque</code> (the underlying implementation for both) would be a considerable improvement.</p></li>\n<li><p>Consider encapsulating the test whether the input is a palindrome into its own reusable function, separate from actually <em>getting</em> it.</p></li>\n<li><p>Testing whether something is a palindrome seems a favorite passtime of many beginners.<br>\nThus, <a href=\"https://codereview.stackexchange.com/questions/tagged/palindrome%20c%2b%2b\">there are a myriad posts on how to efficiently and elegantly do that in C++</a>, for example \"<em><a href=\"https://codereview.stackexchange.com/questions/166121/check-if-a-string-is-palindrome-or-two-strings-are-the-opposite-of-each-other\">Check if a string is palindrome or two strings are the opposite of each other</a></em>\".<br>\nThe important points are avoiding expensive copies, and only comparing each element once.</p></li>\n<li><p>If you want one of two values, conditional on some expression, consider the conditional operator <code>expr ? true_expr : false_expr</code>. It is designed for that.</p></li>\n<li><p><code>return 0;</code> is implicit for <code>main()</code>. Make of that what you will.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T17:49:58.963", "Id": "433856", "Score": "0", "body": "\"You should desist from using std::endl, as spurious manual flushing flushes any pretense at performance down the drain.\" I can't imagine a context in which this would be an issue. If performance is an issue (e.g. printing in a loop), you shouldn't be printing at all. If performance isn't an issue, there's no reason to delay flushing. It could be useful for when debugging a loop, for example. If your program crashes, you know that your log provides an accurate trace of what happened, because all prints were flushed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T20:19:37.220", "Id": "433870", "Score": "0", "body": "@Alexander Not printing at all is certainly faster. But not flushing after every line can also help significantly, even be an order of magnitude or more. The error-stream is unbuffered because there complete output until the crash is paramount." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T20:33:08.997", "Id": "433871", "Score": "0", "body": "@Deduplicator I didn't know that about the error stream, good to know. \"But not flushing after every line can also help significantly, even be an order of magnitude or more.\" but still, it doesn't matter. You shouldn't be printing in a tight loop if performance is an issue. Buffering or not, you shouldn't be doing it at all." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T19:05:05.147", "Id": "223696", "ParentId": "223680", "Score": "11" } }, { "body": "<blockquote>\n <p>Initially, I thought maybe the process is slower as it uses two memory containers, as opposed to simply comparing two halves of a single string.</p>\n</blockquote>\n\n<p>I think you hit on an excellent idea right there. I'd read a line of input into a string, the compare the first half of the string to the second half in reverse order.</p>\n\n<ul>\n<li>You can use <code>std::getline</code> to read the string.</li>\n<li>You can use <code>your_string.size() / 2</code> to get half the length.</li>\n<li>You can use <code>your_string.cbegin()</code> to get an iterator to the beginning of the string.</li>\n<li>You can use <code>your_string.crbegin()</code> to get a reverse iterator to the string (one that iterates through from the end to the beginning).</li>\n<li>You can use <code>std::mismatch</code> to compare the two halves of the string.</li>\n<li>As Deduplicator pointed out, you probably want a function that does nothing but check whether a string is a palindrome.</li>\n</ul>\n\n<p>If you wanted to minimize changes to your code, you could just read the string into the deque, then to do the comparison, pop one element from the front, and one element from the back, and compare them. The input was palindromic if and only if all the elements match until the deque has fewer than two elements.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T14:56:59.463", "Id": "223751", "ParentId": "223680", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T15:37:41.343", "Id": "223680", "Score": "4", "Tags": [ "c++", "performance", "beginner", "strings", "palindrome" ], "Title": "Palindrome test" }
223680
<p>I know there's a similar question to this: <a href="https://codereview.stackexchange.com/questions/71790/design-a-chess-game-using-object-oriented-principles">See here</a>. </p> <p>And I have taken the points mentioned there into consideration. However, I wanted to learn Kotlin and thought of writing OOP based Chess myself. My attempt at writing a simplistic chess game (between White and Black basically, player does not have much to do). </p> <p>Basically I want to know, is my thought process correct for approaching this problem? Have I adhered to OOP principles? I've followed a primitive version of BDD to design and implement this.</p> <p>Also, since this is my first Kotlin program, is there some Kotlin's groovy feature that I am missing?</p> <pre><code> enum class Color { BLACK, WHITE } class Cell(var x: Int, var y: Int) { companion object { /** * Returns Cell if indexes are in boundary of a board. //TODO: Should this be moved to Board class, as it works on constraints of Board. */ fun at(x: Int, y: Int) : Cell? { if(x &lt; 0 || x &gt; 7 || y &lt; 0 || y &gt; 7) return null return Cell(x,y) } /** * Takes a string like "a5" and returns a Cell with zero-indexed row number and column number, or error string */ fun at(string: String) : Either&lt;String,Cell&gt; { val matchResult = "([a-h])(\\d)+".toRegex().matchEntire(string) val chars = listOf("a","b", "c", "d", "e", "f", "g", "h") val extractedValues = matchResult?.groupValues?.takeLast(2) ?: return Either.left("Could not get cell for $string. Try something like a4, b1") try { val row = Integer.parseInt(extractedValues[1]) if(row &lt; 1 || row &gt; 8) return Either.left("Incorrect row number:$row") return Either.right(Cell( row -1, chars.indexOf(extractedValues[0]))) } catch (e: Exception){ return Either.left(e.toString()) } } } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Cell if (x != other.x) return false if (y != other.y) return false return true } override fun hashCode(): Int { var result = x result = 31 * result + y return result } override fun toString(): String { val columns = listOf("a","b", "c", "d", "e", "f", "g", "h") return "${columns[y]}${x+1}" } } abstract class Piece(val color: Color) { var board: Board? = null /** * Useful for calculating valid cells to move. */ val getCellsTillFirstNonEmpty = { from: Cell, rowDir : Int, colDir: Int -&gt; val returnList: MutableList&lt;Cell&gt; = mutableListOf() var i = 1 while (true) { val nextCell = Cell.at(from.x + i*rowDir, from.y + i*colDir) ?: break returnList += nextCell if(board!!.pieceAt(nextCell) != null ) { break } i++ } returnList } open fun calculateTargetSquares(from: Cell) : List&lt;Cell?&gt; { return emptyList() } fun possibleTargetSquares(from: Cell): List&lt;Cell&gt; { return calculateTargetSquares(from) .filterNotNull() .filter { board!!.pieceAt(it)?.color != this.color } //Cannot capture own's color! } } class Pawn(color: Color) : Piece(color) { var forwardStep = { x: Int -&gt; if(color == Color.WHITE) -x else +x} var backwardStep = { x: Int -&gt; if(color == Color.WHITE) +x else -x} /** * Pawn has special moves to capture opponent's pieces. */ private fun capturableCells(from: Cell): List&lt;Cell?&gt; { return listOf(Cell.at(from.x + forwardStep(1), from.y + 1), Cell.at(from.x + forwardStep(1), from.y - 1)) .filter { board!!.pieceAt(it) != null } } private fun forwardMoves(from: Cell): List&lt;Cell&gt; { val firstMove = from.x == 1 || from.x == 6 if(firstMove) { return listOf(Cell(from.x + forwardStep(1), from.y), Cell(from.x + forwardStep(2), from.y)) .takeWhile { board!!.pieceAt(it) == null } } else { return listOf(Cell(from.x + forwardStep(1), from.y)) .takeWhile { board!!.pieceAt(it) == null } } } override fun calculateTargetSquares(from: Cell): List&lt;Cell&gt; { return forwardMoves(from) + capturableCells(from).filterNotNull() } override fun toString(): String { return if(color == Color.BLACK) "♟" else "♙" } } class Knight(color: Color) : Piece(color) { override fun calculateTargetSquares(from: Cell): List&lt;Cell?&gt; { val x = from.x val y = from.y return listOf(Cell.at(x+2, y-1), Cell.at(x+2, y+1), Cell.at(x-2, y-1), Cell.at(x-2, y+1), Cell.at(x-1, y+2), Cell.at(x+1, y+2), Cell.at(x-1, y-2), Cell.at(x+1, y-2)) } override fun toString(): String { return if(color == Color.BLACK) "♞" else "♘" } } class Bishop(color: Color) : Piece(color) { override fun toString(): String { return if(color == Color.BLACK) "♝" else "♗" } override fun calculateTargetSquares(from: Cell): List&lt;Cell?&gt; { return getCellsTillFirstNonEmpty(from, +1, +1) + getCellsTillFirstNonEmpty(from, -1, -1) + getCellsTillFirstNonEmpty(from, +1, -1) + getCellsTillFirstNonEmpty(from, -1, +1) } } class Rook(color: Color) : Piece(color) { override fun toString(): String { return if(color == Color.BLACK) "♜" else "♖" } override fun calculateTargetSquares(from: Cell): List&lt;Cell?&gt; { return getCellsTillFirstNonEmpty(from, 0, +1) + getCellsTillFirstNonEmpty(from, 0, -1) + getCellsTillFirstNonEmpty(from, +1, 0) + getCellsTillFirstNonEmpty(from, -1, 0) } } class Queen(color: Color) : Piece(color) { override fun toString(): String { return if(color == Color.BLACK) "♛" else "♕" } override fun calculateTargetSquares(from: Cell): List&lt;Cell?&gt; { return getCellsTillFirstNonEmpty(from, +1, +1) + getCellsTillFirstNonEmpty(from, -1, -1) + getCellsTillFirstNonEmpty(from, +1, -1) + getCellsTillFirstNonEmpty(from, -1, +1) + getCellsTillFirstNonEmpty(from, 0, +1) + getCellsTillFirstNonEmpty(from, 0, -1) + getCellsTillFirstNonEmpty(from, +1, 0) + getCellsTillFirstNonEmpty(from, -1, 0) } } class King(color: Color) : Piece(color) { override fun toString(): String { return if(color == Color.BLACK) "♚" else "♔" } override fun calculateTargetSquares(from: Cell): List&lt;Cell?&gt; { return getCellsTillFirstNonEmpty(from, +1, +1).take(1) + getCellsTillFirstNonEmpty(from, -1, -1).take(1) + getCellsTillFirstNonEmpty(from, +1, -1).take(1) + getCellsTillFirstNonEmpty(from, -1, +1).take(1) + getCellsTillFirstNonEmpty(from, 0, +1).take(1) + getCellsTillFirstNonEmpty(from, 0, -1).take(1) + getCellsTillFirstNonEmpty(from, +1, 0).take(1) + getCellsTillFirstNonEmpty(from, -1, 0).take(1) } } class Board() { var selectedCell: Cell? = null var cellsToHighlight: List&lt;Cell&gt; = emptyList() fun render() { val ANSI_RED_BACKGROUND = "\u001B[41m"; val ANSI_YELLOW_BACKGROUND = "\u001B[43m"; val ANSI_CYAN_BACKGROUND = "\u001B[46m"; val ANSI_WHITE_BACKGROUND = "\u001B[47m"; val ANSI_RESET = "\u001B[0m"; val backgrounds = arrayOf(ANSI_CYAN_BACKGROUND, ANSI_WHITE_BACKGROUND) var backgroundIndex = 0 val columns = listOf(" ","a ","b ", "c ", "d", "e ", "f ", "g ", "h ") println(columns.joinToString(" ")) val EMPTY_CELL = "\u3000" for (i in 0..7) { val row = (0..7).toList().map {j -&gt; val cell = Cell(i, j) val piece = cellToPieceMap[cell] var backgroundColor = backgrounds[backgroundIndex++%2] if(cell.equals(selectedCell) || cell in cellsToHighlight) backgroundColor = ANSI_YELLOW_BACKGROUND backgroundColor + ( piece ?: EMPTY_CELL)+" "+ANSI_RESET }.joinToString("") println("${i+1} "+row + " "+(i+1)) backgroundIndex++ } println(ANSI_RESET+columns.joinToString(" ")) } private var cellToPieceMap: MutableMap&lt;Cell?, Piece&gt; = mutableMapOf() init { val placePiece = { it: String, piece: Piece -&gt; cellToPieceMap[Cell.at(it).getOrElse { null }] = piece; piece.board = this } listOf("a1", "h1").forEach { placePiece(it, Rook(Color.BLACK)) } listOf("a8", "h8").forEach { placePiece(it, Rook(Color.WHITE)) } listOf("a2", "b2", "c2", "d2", "e2", "f2", "g2", "h2").forEach { placePiece(it, Pawn(Color.BLACK)) } listOf("a7", "b7", "c7", "d7", "e7", "f7", "g7", "h7").forEach { placePiece(it, Pawn(Color.WHITE)) } listOf("b1", "g1").forEach { placePiece(it, Knight(Color.BLACK)) } listOf("b8", "g8").forEach { placePiece(it, Knight(Color.WHITE)) } listOf("c1", "f1").forEach { placePiece(it, Bishop(Color.BLACK)) } listOf("c8", "f8").forEach { placePiece(it, Bishop(Color.WHITE)) } listOf("d8").forEach { placePiece(it, Queen(Color.WHITE)) } listOf("e8").forEach { placePiece(it, King(Color.WHITE)) } listOf("d1").forEach { placePiece(it, Queen(Color.BLACK)) } listOf("e1").forEach { placePiece(it, King(Color.BLACK)) } } private fun isCheckMate(){ } private fun isStaleMate() { } private fun isDraw(){ } fun pieceAt(cell: Cell?): Piece? { return this.cellToPieceMap[cell] } fun setPieceAt(cell: Cell, piece: Piece) { this.cellToPieceMap[cell] = piece } fun removePiece(cell: Cell) { this.cellToPieceMap.remove(cell) } } class Player(private var name: String) { override fun toString(): String { return name } } enum class MoveType { NORMAL, EN_PASSANT, PROMOTION } class Move (val piece: Piece, val from: Cell, val to: Cell, var moveType: MoveType = MoveType.NORMAL) { var capturedPiece: Piece? = null var capturedCell: Cell? = null init { if(piece.color == Color.WHITE &amp;&amp; to.x == 0) moveType = MoveType.PROMOTION if(piece.color == Color.BLACK &amp;&amp; to.x == 7) moveType = MoveType.PROMOTION } fun algebraicNotation(): String { return "" //TODO } } class ChessGame(var playerA: Player, var playerB: Player) { var isRunning = false var moves: MutableList&lt;Move&gt; = mutableListOf() private var turn: Int = 0 val colorA = Color.WHITE val colorB = Color.BLACK private val capturedPieces: Map&lt;Color, MutableList&lt;Piece&gt;&gt; = mapOf( Pair(Color.WHITE, mutableListOf()), Pair(Color.BLACK, mutableListOf()) ) //which color for which player? TODO val board: Board = Board() /** * One-time opportunity for pawn to capture opposite pawn. */ fun enPassantMove(cell: Cell): Move? { val lastMove = moves.lastOrNull() ?: return null val pawnToCapture = lastMove.piece val positionOfCapture = lastMove.to if(pawnToCapture is Pawn &amp;&amp; Math.abs(positionOfCapture.x - lastMove.from.x) == 2 &amp;&amp; //was starting move of pawn &amp;&amp; was 2-step move (cell.x == positionOfCapture.x) &amp;&amp; //on same level Math.abs(cell.y - positionOfCapture.y) == 1) { //on adjacent column val move = Move( board.pieceAt(cell)!!, cell, Cell.at(positionOfCapture.x + pawnToCapture.backwardStep(1), positionOfCapture.y)!!, MoveType.EN_PASSANT ) move.capturedPiece = pawnToCapture move.capturedCell = positionOfCapture return move } return null } private fun validCellsToMove(sourceCell: Cell) : Either&lt;String, List&lt;Cell&gt;&gt; { val selectedPiece = board.pieceAt(sourceCell) ?: return Either.left("No piece at $sourceCell") val selectedColor = selectedPiece.color if(selectedColor != getTurn()) return Either.left("You cannot pick $selectedColor") val possibleTargetSquares = selectedPiece.possibleTargetSquares(sourceCell) if(possibleTargetSquares.isEmpty()) return Either.left("Nowhere to go! Select some other square!") return Either.right(possibleTargetSquares) } fun makeMove(move: Move) : Piece? { val targetCell = move.to val sourceCell = move.from var capturedPiece = board.pieceAt(targetCell) val sourcePiece = board.pieceAt(sourceCell) board.setPieceAt(targetCell, sourcePiece!!) board.removePiece(sourceCell) if(move.moveType == MoveType.EN_PASSANT) { board.removePiece(move.capturedCell!!) capturedPiece = move.capturedPiece } move.capturedPiece = capturedPiece moves.plusAssign(move) val piecesCapturedByThisColor = capturedPieces[getTurn()]!! if(capturedPiece != null) { piecesCapturedByThisColor.plusAssign(capturedPiece) } board.selectedCell = null board.cellsToHighlight = emptyList() return capturedPiece } fun getTurn(): Color { return if(turn == 0) Color.WHITE else Color.BLACK; } fun run() { if(isRunning) return isRunning = true while (true) { this.board.render() val move = getAValidMove(this.board) val capturedPieces = this.makeMove(move) if(capturedPieces != null) { println("You now have bagged: $capturedPieces") } turn = (turn+1) % 2 } } private fun getAValidMove(board: Board): Move { while (true) { println("select square [${this.getTurn()}] &gt;") val sourceCellCmd: String = readLine().orEmpty() if(Cell.at(sourceCellCmd).isLeft()) { println("Invalid cell! Choose something like a8, b4 etc!") continue } val source = Cell.at(sourceCellCmd).get() val cellsToMove = this.validCellsToMove(source) val enPassant: Move? = this.enPassantMove(source) if(cellsToMove.isLeft() &amp;&amp; enPassant == null) { println("Invalid move! $cellsToMove") continue } board.selectedCell = source var possibleTargetCells: List&lt;Cell&gt; = cellsToMove.fold( {x -&gt; emptyList() }, { x -&gt; x} ) if(enPassant != null) { possibleTargetCells += enPassant.to } board.cellsToHighlight = possibleTargetCells board.render() while (true) { println("Type 'undo' to start over your move. Where do you want to move? Choose from $possibleTargetCells") val targetCellCmd = readLine().orEmpty() if(targetCellCmd == "undo") { return getAValidMove(board) } val targetCell = Cell.at(targetCellCmd) if(targetCell.isLeft()) continue if(enPassant != null &amp;&amp; targetCell.get() == enPassant.to) { return enPassant } if(targetCell.get() in possibleTargetCells) { return Move(board.pieceAt(source)!!, source, Cell.at(targetCellCmd).get()) } } } } } </code></pre> <p>Here's my thought process (design considerations) while implementing this:</p> <h3>Requirements Analysis</h3> <p>Core Requirements:</p> <ul> <li>I can create a new game to play with my friend. </li> <li>We can see the board with pieces arranged properly. </li> <li>I get color white. White makes the first move. </li> <li>Black gets his turn. We make turns after each move.</li> <li>If white tries to move black piece, the game does not allow it. Similarly for white piece.</li> <li>When I select a piece, valid moves are shown to me. </li> <li>When I select from valid moves, pieces move appropriately and board is updated. </li> <li>I must be able to save and resume the game. </li> </ul> <p> Extra Requirements (which we can think of in advance): </p> <ul> <li>I can play against the computer. </li> <li>I can undo my moves. </li> <li>I can play online with other people. </li> <li>The UI of the game can be enhanced with rich interface. </li> </ul> <h3>Identify entities:</h3> <p>Some of them clearly obvious are: <code>Game</code>,<code>Board</code>,<code>Square/Cell</code>,<code>Player</code> </p> <h3>How are they related? How will they interact?</h3> <p><ul> <li>A <code>Game</code> will run in a loop, making turns, asking for input from the player. </li> <li>Or, we can make this reactive. game will receive commands from player, and if it is valid a move will be executed. </li> <li>Initially pieces are laid out on the board. <code>Board</code> knows which squares/<code>Cell</code>s has which piece. Board manages the layout of the pieces.</li> <li><code>Piece</code> has certain properties like color. </li> <li><code>Piece</code> needs to move, and for a valid move it needs to have access to <code>Board</code> </li> <li>Different types of pieces have different rules for moves </li> <li>A <code>Piece</code> must be able to figure out where it can go, given access to the <code>Board</code></li> <li>There are certain moves which piece cannot figure out just by looking at the board, e.g. En-Passant which needs to know what was the last move </li> <li>We can clearly see that moves should be stored for various purpose (undoing, validating en-passe etc). Hence we need to model <code>Move</code> </li><br> </ul></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T18:35:06.787", "Id": "433665", "Score": "0", "body": "I would recommend that you post the readme file here as well, it will make your question here more self-contained. Also see [this meta question](//codereview.meta.stackexchange.com/q/1308)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T19:36:23.450", "Id": "433675", "Score": "0", "body": "It looks like some features are still unfinished. You should probably declare what is in scope for this review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T05:25:41.130", "Id": "433692", "Score": "0", "body": "@200_success I expect the review on the thought process and design considerations, do the classes have correct responsibility, is the relationship among them correct as per OOP principles? Also, am I missing something that can cause a huge blow need I have some legit requirement in future." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-05-21T17:12:33.953", "Id": "476310", "Score": "0", "body": "I remember and can relate to your code here, 20 years ago when learning C++ I use chess. Queen is multiple inheritance of bishop and rook. And then, I had to ahead compute the board because it's the only way to validate a move to examine if the king is in check as a result. And then suddenly, somebody commented out why I have a Queen, pawn, Bishop class because for him he wants the classes to be the squares instead such as a1, a2,... e4.. etc and the type of pieces becomes. attributes of the squares. At that time I thought his conception was stupid why he represents the squares." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T16:12:05.390", "Id": "223682", "Score": "3", "Tags": [ "object-oriented", "game", "design-patterns", "chess", "kotlin" ], "Title": "Object Oriented Chess Design In Kotlin" }
223682
<p>I'm in the process of making a website for a friend of mine who wants to display both the tattoos he has made, as well as his paintings. The idea for the layout is to have a gallery for his tattoos, and another gallery for his paintings. I have so far achieved this, but the code is dry and duplicated - so I'm hoping to make it more efficient with less code. It can be seen in action <a href="https://lit-bayou-94489.herokuapp.com/" rel="nofollow noreferrer">here</a>, but the code for the galleries is also below: </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>$(document).ready(function($) { $(".gallery-item-one").click(function(e) { e.preventDefault(); var image_href = $(this) .children("a") .attr("href"); var image = '&lt;img src="' + image_href + '" /&gt;'; $("#lightbox-one").css("display", "flex"); $("#content").html(image); var thisIndex = $(this).index(); $("#next").click(function() { var images = $("#sectionTwo a"); if (thisIndex &gt;= images.length - 1) { thisIndex = 0; } else if (thisIndex &lt; images.length) { thisIndex = thisIndex + 1; } var nn = $(images) .eq(thisIndex) .attr("href"); var nnImg = '&lt;img src="' + nn + '" /&gt;'; $("#content").html(nnImg); }); $("#prev").click(function() { var images = $("#sectionTwo a"); if (thisIndex &lt;= 0) { thisIndex = images.length - 1; } else if (thisIndex &gt; 0) { thisIndex = thisIndex - 1; } var pr = $(images) .eq(thisIndex) .attr("href"); var prImg = '&lt;img src="' + pr + '" /&gt;'; $("#content").html(prImg); }); }); $("#close").on("click", function() { $("#lightbox-one").css("display", "none"); }); }); $(document).ready(function($) { $(".gallery-item-two").click(function(e) { e.preventDefault(); var image_href = $(this) .children("a") .attr("href"); var image = '&lt;img src="' + image_href + '" /&gt;'; $("#lightbox-one").css("display", "flex"); $("#content").html(image); var thisIndex = $(this).index(); $("#next").click(function() { var images = $("#sectionThree a"); if (thisIndex &gt;= images.length - 1) { thisIndex = 0; } else if (thisIndex &lt; images.length) { thisIndex = thisIndex + 1; } var nn = $(images) .eq(thisIndex) .attr("href"); var nnImg = '&lt;img src="' + nn + '" /&gt;'; $("#content").html(nnImg); }); $("#prev").click(function() { var images = $("#sectionThree a"); if (thisIndex &lt;= 0) { thisIndex = images.length - 1; } else if (thisIndex &gt; 0) { thisIndex = thisIndex - 1; } var pr = $(images) .eq(thisIndex) .attr("href"); var prImg = '&lt;img src="' + pr + '" /&gt;'; $("#content").html(prImg); }); }); $("#close").on("click", function() { $("#lightbox-one").css("display", "none"); }); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.container { height: 100vh; width: 95%; margin: auto; position: relative; } .images { width: 95%; display: flex; justify-content: space-between; position: relative; } #tattoos { height: 2500px; } .sectionOne { display: grid; height: 100vh; grid-template-rows: repeat(1, 1fr); grid-template-columns: repeat(1, 1fr); grid-gap: 15px; width: 60%; position: sticky; top: 0; } .overlay { box-shadow: inset 0 0 0 2000px rgba(0, 0, 0, 0.3); } #image-one-mobile, #image-one-mobile-paint { display: none; } .image-one, .image-one-paint { box-shadow: inset 0 0 0 2000px rgba(0, 0, 0, 0.8); margin: 4% 0; } #sectionTwo { width: 37%; display: grid; height: 2440px; grid-template-rows: repeat(10, 1fr); grid-template-columns: repeat(1, 1fr); grid-gap: 30px; margin: 2.5% 0; } .image-one { background-image: url("https://i.ibb.co/HXfG735/tattoo.jpg"); background-size: cover; background-position: 0% 80%; } #image-two { background-image: url("https://i.ibb.co/kBJrryt/7ab34470-9318-4fc1-a6da-656ca31399c5.jpg"); background-size: cover; background-position: 0% 80%; } #image-three { background-image: url("https://i.ibb.co/SKCnT4d/b19aaf2a-84cf-42b4-9ccd-6205ca1be395.jpg"); background-size: cover; background-position: 0% 50%; } #image-four { background-image: url("https://i.ibb.co/xF4Qv50/b5d6695b-2142-42cc-8eef-2963311edfd6.jpg"); background-size: cover; background-position: 0% 60%; } #image-eight { background-image: url("https://i.ibb.co/0nY3VDG/d1ecf205-6b1b-4a1a-b94b-7d75aa177464.jpg"); background-size: cover; background-position: 0% 60%; } #image-nine { background-image: url("https://i.ibb.co/QYf6vDY/48a63fe2-066b-42d1-9211-040c6977ceff.jpg"); background-size: cover; background-position: 0% 40%; } #image-ten { background-image: url("https://i.ibb.co/7RdJqgP/ce30fff2-1679-403f-8431-c6be4f8b1466.jpg"); background-size: cover; background-position: 0% 80%; } #image-twelve { background-image: url("https://i.ibb.co/NTZgKcg/new-image-four.jpg"); background-size: cover; background-position: 0% 50%; } #image-thirteen { background-image: url("https://i.ibb.co/CbpJGD4/new-three.jpg"); background-size: cover; background-position: 0% 40%; } #image-fourteen { background-image: url("https://i.ibb.co/QQLR1y7/new-one.jpg"); background-size: cover; background-position: 0% 80%; } #image-fifteen { background-image: url("https://i.ibb.co/gJ6ZrLq/new-two.jpg"); background-size: cover; background-position: 0% 50%; } #painting { height: 1320px; } #sectionThree { width: 37%; display: grid; height: 1260px; grid-template-rows: repeat(5, 1fr); grid-template-columns: repeat(1, 1fr); grid-gap: 30px; margin: 2.5% 0; } .image-one-paint { background-image: url("https://i.ibb.co/FYT7TTy/one.jpg"); background-size: cover; background-position: 0% 50%; } #image-two-paint { background-image: url("https://i.ibb.co/Qf3VST6/two.jpg"); background-size: cover; background-position: 0% 50%; } #image-three-paint { background-image: url("https://i.ibb.co/4Vn1zwF/three.jpg"); background-size: cover; background-position: 0% 50%; } #image-four-paint { background-image: url("https://i.ibb.co/1ZdCPjQ/four.jpg"); background-size: cover; background-position: 0% 50%; } #image-five-paint { background-image: url("https://i.ibb.co/XygcPPm/five.jpg"); background-size: cover; background-position: 0% 50%; } #image-six-paint { background-image: url("https://i.ibb.co/sVgSQZD/six.jpg"); background-size: cover; background-position: 0% 50%; } .gallery-item, .gallery-item-one, .gallery-item-two { display: flex; justify-content: center; align-items: center; opacity: 1; text-transform: uppercase; font-family: "Lora"; font-weight: 700; color: white; font-size: 9vw; } .gallery-item-one, .gallery-item-two:hover { cursor: pointer; } .container-two { display: flex; justify-content: center; align-items: center; text-align: center; height: 100%; } #lightbox-one { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgb(0, 0, 0, 0.9); text-align: center; z-index: 2; display: none; justify-content: center; align-items: center; text-align: center; } #lightbox-one img { box-shadow: 0 0 25px #111; -webkit-box-shadow: 0 0 25px #111; -moz-box-shadow: 0 0 25px #111; max-width: 80%; max-height: 100%; } #close { position: absolute; color: #ffffff; top: 5%; right: 5%; } #close:hover { cursor: pointer; } #arrowcontainer { width: 100%; height: 100vh; position: absolute; top: 50%; display: flex; justify-content: space-between; } #arrowcontainer div { color: #ffffff; margin: 0 5%; } #arrowcontainer div i:hover { cursor: pointer; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div id="tattoos" class="container images"&gt; &lt;section class="sectionOne"&gt; &lt;div class="image-one gallery-item"&gt; tatuajes &lt;/div&gt; &lt;/section&gt; &lt;section id="sectionTwo"&gt; &lt;div id="image-one-mobile" class="image-one gallery-item"&gt; tatujes &lt;/div&gt; &lt;div id="image-two" class="gallery-item-one overlay fade"&gt; &lt;a href="https://i.ibb.co/kBJrryt/7ab34470-9318-4fc1-a6da-656ca31399c5.jpg"&gt;&lt;/a&gt; &lt;/div&gt; &lt;div id="image-three" class="gallery-item-one overlay slide"&gt; &lt;a href="https://i.ibb.co/SKCnT4d/b19aaf2a-84cf-42b4-9ccd-6205ca1be395.jpg"&gt;&lt;/a&gt; &lt;/div&gt; &lt;div id="image-four" class="gallery-item-one overlay slide"&gt; &lt;a href="https://i.ibb.co/xF4Qv50/b5d6695b-2142-42cc-8eef-2963311edfd6.jpg"&gt;&lt;/a&gt; &lt;/div&gt; &lt;div id="image-eight" class="gallery-item-one overlay slide"&gt; &lt;a href="https://i.ibb.co/0nY3VDG/d1ecf205-6b1b-4a1a-b94b-7d75aa177464.jpg"&gt;&lt;/a&gt; &lt;/div&gt; &lt;div id="image-nine" class="gallery-item-one overlay slide"&gt; &lt;a href="https://i.ibb.co/QYf6vDY/48a63fe2-066b-42d1-9211-040c6977ceff.jpg"&gt;&lt;/a&gt; &lt;/div&gt; &lt;div id="image-ten" class="gallery-item-one overlay slide"&gt; &lt;a href="https://i.ibb.co/7RdJqgP/ce30fff2-1679-403f-8431-c6be4f8b1466.jpg"&gt;&lt;/a&gt; &lt;/div&gt; &lt;div id="image-twelve" class="gallery-item-one overlay slide"&gt; &lt;a href="https://i.ibb.co/NTZgKcg/new-image-four.jpg"&gt;&lt;/a&gt; &lt;/div&gt; &lt;div id="image-thirteen" class="gallery-item-one overlay slide"&gt; &lt;a href="https://i.ibb.co/CbpJGD4/new-three.jpg"&gt;&lt;/a&gt; &lt;/div&gt; &lt;div id="image-fourteen" class="gallery-item-one overlay slide"&gt; &lt;a href="https://i.ibb.co/QQLR1y7/new-one.jpg"&gt;&lt;/a&gt; &lt;/div&gt; &lt;div id="image-fifteen" class="gallery-item-one overlay slide"&gt; &lt;a href="https://i.ibb.co/gJ6ZrLq/new-two.jpg"&gt;&lt;/a&gt; &lt;/div&gt; &lt;/section&gt; &lt;/div&gt; &lt;div id="lightbox-one"&gt; &lt;div id="content" class="container-two"&gt; &lt;img src="" /&gt; &lt;/div&gt; &lt;div id="close"&gt;&lt;i class="fas fa-times"&gt;&lt;/i&gt;&lt;/div&gt; &lt;div id="arrowcontainer"&gt; &lt;div id="prev"&gt;&lt;i class="fas fa-chevron-left"&gt;&lt;/i&gt;&lt;/div&gt; &lt;div id="next"&gt;&lt;i class="fas fa-chevron-right"&gt;&lt;/i&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="painting" class="container images"&gt; &lt;section class="sectionOne"&gt; &lt;div class="image-one-paint gallery-item"&gt; pinturas &lt;/div&gt; &lt;/section&gt; &lt;section id="sectionThree"&gt; &lt;div id="image-one-mobile-paint" class="image-one gallery-item"&gt; pinturas &lt;/div&gt; &lt;div id="image-two-paint" class="gallery-item-two overlay slide"&gt; &lt;a href="https://i.ibb.co/Qf3VST6/two.jpg"&gt;&lt;/a&gt; &lt;/div&gt; &lt;div id="image-three-paint" class="gallery-item-two overlay slide"&gt; &lt;a href="https://i.ibb.co/4Vn1zwF/three.jpg"&gt;&lt;/a&gt; &lt;/div&gt; &lt;div id="image-four-paint" class="gallery-item-two overlay slide"&gt; &lt;a href="https://i.ibb.co/1ZdCPjQ/four.jpg"&gt;&lt;/a&gt; &lt;/div&gt; &lt;div id="image-five-paint" class="gallery-item-two overlay slide"&gt; &lt;a href="https://i.ibb.co/XygcPPm/five.jpg"&gt;&lt;/a&gt; &lt;/div&gt; &lt;div id="image-six-paint" class="gallery-item-two overlay slide"&gt; &lt;a href="https://i.ibb.co/sVgSQZD/six.jpg"&gt;&lt;/a&gt; &lt;/div&gt; &lt;/section&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>As I said, it works, I just to know of a way where the JS code that clicks through the images in the lightbox can be reduced. </p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T16:31:09.797", "Id": "223684", "Score": "1", "Tags": [ "javascript", "html", "css" ], "Title": "Repetitive light-box gallery code" }
223684
<p>My task is to copy data from an Excel sheet into charts on PowerPoint slides. To minimize the interactions between the two, I have an Excel macro insert the data for each slide into that slide's Notes pane. Next I have a PowerPoint macro extract the data from each slide's Notes and insert it into the two charts on that slide.</p> <p>The data in the Notes is a string with the values separated by commas. I use Split to convert the string to an array. I identify the fields by their position in the array; that's the part that embarrasses me. </p> <p>This is an example of the data string:</p> <pre><code>Shawn-MPS/BSC/BP,1,,, June Area Text,Flexible,Diplomatic,Stress Management, June Area Numbers, 3.5,2.1,2.9 </code></pre> <p>And the macro:</p> <pre><code>Sub openChartData() 'Dim ThisWB Dim strSlideNoteText As String 'On each slide, this opens the charts in Item 4 and 13, and lets you edit the underlying data spreadsheet For Each aSlide In ActivePresentation.Slides aSlide.Select 'For debugging only strSlideNoteText = aSlide.NotesPage.Shapes(2).TextFrame.TextRange.Text If InStr(strSlideNoteText, "SAMPLE") &gt; 0 Then GoTo skip 'Skip the Sample slide 'Break the note text into an array of individual words Dim arrSlideNoteText As Variant ' arrSlideNoteText = Split(strSlideNoteText, ",") ' MPS/BSC/BP With aSlide.Shapes(13).Chart.ChartData .Activate With .Workbook.sheets(1) .Cells(2, 2).Value = arrSlideNoteText(1) .Cells(2, 3).Value = arrSlideNoteText(2) .Cells(2, 4).Value = arrSlideNoteText(3) End With .Workbook.Close End With ' First Harrison Score and "Area" names With aSlide.Shapes(4).Chart.ChartData .Activate With .Workbook.sheets(1) .Cells(1, 2).Value = Val(arrSlideNoteText(5)) .Cells(1, 3).Value = Val(arrSlideNoteText(6)) .Cells(1, 4).Value = Val(arrSlideNoteText(7)) .Cells(2, 2).Value = Val(arrSlideNoteText(9)) .Cells(2, 3).Value = Val(arrSlideNoteText(10)) .Cells(2, 4).Value = Val(arrSlideNoteText(11)) End With .Workbook.Close End With skip: Next aSlide MsgBox "Done" End Sub </code></pre> <p>Obviously, if I have to make a change to the order of the fields, I have to change 11 lines of code, and there's always a chance of error. Is there a better way to handle this?</p> <p>(If fixing this code involves revising the format of the string sent by Excel, I'm willing to do that.)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T18:20:04.987", "Id": "433664", "Score": "0", "body": "Why are you not updating powerpoint charts directly from excel data, Is there any reason to paste data to notes area ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T20:01:23.393", "Id": "433676", "Score": "1", "body": "Having the data in a slide's Notes makes it easily visible in one spot. I can confirm that the numbers are on the correct slide, for one thing. Also, if we have to make minor changes to the data, we can do it in the Notes and run the PowerPoint macro without running Excel." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T03:39:36.693", "Id": "433686", "Score": "0", "body": "arrSlideNoteText is array, which will have LBound and UBound use these two functions you have replace celll(2,2).value with loop.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-26T17:36:11.450", "Id": "436564", "Score": "0", "body": "I would suggest updating both macros to use the titles of the data that you are copying. Then you can make the data more dynamic and not dependent on the order of the columns." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T19:20:14.883", "Id": "436732", "Score": "0", "body": "@seadoggie01 Do you mean that every other field would contain the field name of the following field? \"Name,Shawn,City,Los Angeles,Zip,90001\", like that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-28T17:56:56.687", "Id": "436854", "Score": "0", "body": "@ShawnV.Wilson No, like if you create a table in Excel. The first row has headers, the remaining have the data that matches. Then you could parse out only the data you need, and the order wouldn't matter" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T17:36:16.990", "Id": "223688", "Score": "1", "Tags": [ "vba", "powerpoint" ], "Title": "Pulling substrings from a CSV string without knowing position" }
223688
<p>I have written a solution for two sum problem in variation. first is simple with two loops and another one is one loop and hash map.</p> <p>But I wonder why the simple solution is faster than the efficent solution</p> <p>simple solution -</p> <pre><code>func TwoSum(arr []int, s int) [][]int { var sum [][]int for i := 0; i &lt; len(arr); i++ { for j := i + 1; j &lt; len(arr); j++ { if arr[i]+arr[j] == s { sum = append(sum, []int{arr[i], arr[j]}) } } } return sum } </code></pre> <p>Hashmap solution - </p> <pre><code>func TwoSum1(nums []int, target int) [][]int { var r = make([][]int, 0) var m = make(map[int]int, 0) for p, i := range nums { j := target - i if pos, ok := m[j]; ok { if pos != p { r = append(r, []int{j, i}) } } else { m[i] = p } } return r } </code></pre> <p>also, I have written Benchmark </p> <pre><code>type args struct { arr []int s int } var tests = []struct { name string args args want [][]int }{ { "One", args{[]int{3, 5, 2, -4, 8, 11}, 7,}, [][]int{{5, 2}, {-4, 11}}, }, } func BenchmarkTwoSum(b *testing.B) { for i := 0; i &lt; b.N; i++ { for _, tc := range tests{ TwoSum(tc.args.arr, tc.args.s) } } } </code></pre> <blockquote> <p>BenchmarkTwoSum-4 3000000 382 ns/op</p> </blockquote> <pre><code>func BenchmarkTwoSum1(b *testing.B) { for i := 0; i &lt; b.N; i++ { for _, tc := range tests{ TwoSum1(tc.args.arr, tc.args.s) } } } </code></pre> <blockquote> <p>BenchmarkTwoSum1-4 2000000 561 ns/op</p> </blockquote>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T18:16:57.257", "Id": "433663", "Score": "0", "body": "Why don't you run the benchmark for exactly the same amount of operations?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T18:39:08.357", "Id": "433666", "Score": "0", "body": "What happens to the scores when you declare the variables outside of the function? Saves you from allocating memory a couple million times." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T19:28:13.420", "Id": "433674", "Score": "1", "body": "Asymptotic complexity tells you how the performance scales for _large_ inputs. It tells you nothing about the comparative performance for small inputs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T10:59:48.250", "Id": "433740", "Score": "0", "body": "here is the link for more clarity `https://coderbyte.com/algorithm/two-sum-problem`" } ]
[ { "body": "<p>When you ask if your first solution is faster, if you are talking about theory it isn't faster. To understand why you need to understand the the difference between big O complexity and actual run time. <strong>For the purposes of this question, it is important only that you realize that big O complexity does not guarantee that a piece of code with O(n^2) run time will run faster than O(n) for all inputs merely that for some very large inputs O(n^2) will be faster.</strong> More exactly, Big O complexity merely talks about the growth rate of a function at really large values. Without getting into it too much you can imagine that the if we have x^2 and 1000000x, I can guarantee that at some input x^2 will surpass 1000000x. Similarly, if I have x^2 + x I can guarantee that at some point the x^2 term will be so much bigger than the x term that the any increase in in our input will essentially just increase the function by approximately x^2. If that doesn't make sense, then I would suggest brushing up on big O here <a href=\"https://medium.com/karuna-sehgal/a-simplified-explanation-of-the-big-o-notation-82523585e835\" rel=\"nofollow noreferrer\">https://medium.com/karuna-sehgal/a-simplified-explanation-of-the-big-o-notation-82523585e835</a> . </p>\n\n<p>Now for your problem, the big O complexity of the hash map based solution is O(n) the big O for the brute force double loop solution is O(n^2). Now as mentioned about big O does not guarantee that an O(n^2) piece of code will always run faster that an O(n) piece of code for all inputs. Big O is a mathematical guarantee only for large inputs. All big O says is that for some large input O(n^2) will be faster O(n). Let me give you a specific example of why despite a greater big O the double loop solution might be faster for a constrained input. let's say that your two loop solution runs in n^2 time exactly and your hash map solution runs in 1000000000*n time. Well technically your hash map solution would benchmark much much slower for reasonable sized inputs, but eventually if the input were big enough then your hash map solution would run faster. Now, maybe you only care about the performance for a constrained sample size. That's great. This is why you will always have to run a benchmark to compare solutions. Big O is not meant as a tool to guarantee that a certain piece of code will run faster for all inputs, only as a tool to theoretically reason about performance for extremely large inputs. Knowing the time complexity in O notation, won't give you any sort of idea what might be faster for a given constrained input size. That's why in the real world, understanding big O is important, but it is also very important to run performance benchmarks based on how big you actually expect your input to get. I've repeated this central theme in different ways throughout this post but I will summarize again here <strong>Big O only guarantees run time for some extremely large input (think as the limit of your input goes to infinity) it says absolutely nothing about some constrained input.</strong> I could reasonably come up with a Big O problem where an O(n^2) piece of code would never run faster than an O(n) piece of code given the constrained of the amount of memory on your computer. Basically, use big O to get a general idea of run time when writing your code, and then if you see some performance issues benchmark to find improvements. </p>\n\n<p>Now in the case of this question, someone with a little more understanding of what's actually happening in Go might be able to tell you exactly what operation is making your hash map solution slower for those inputs. My guess... when you call <code>make(map[int]int, 0)</code> you are allocating space on the heap, which is likely taking a good amount of time. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-11T05:28:20.300", "Id": "434204", "Score": "0", "body": "Thank you Sam for the answer, I'm still trying to digest the information" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T10:30:07.990", "Id": "434856", "Score": "0", "body": "Thank you same for the explanation" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T14:58:14.557", "Id": "223753", "ParentId": "223689", "Score": "1" } } ]
{ "AcceptedAnswerId": "223753", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T17:44:09.563", "Id": "223689", "Score": "1", "Tags": [ "performance", "comparative-review", "go", "k-sum" ], "Title": "Two solutions to 2-sum" }
223689
<p>Some years ago I made a Monty Hall simulations in Java, and now I decided to give it a go in Python, after learning (yet another) the language at university.</p> <p>I decided to make a generalized, object-oriented and modularized version of the game, in order to see what alterations would impact the results; and to get more comfortable with Object-Oriented code.</p> <p>I mainly have two questions, although all tips, ideas and hints are welcome:</p> <p>1) Would I benefit from making <code>Player</code> a subclass of Game (or the other way around)?</p> <p>2) How would I best analyze the results from my code? I thought about initializing the variables with a <code>numpy</code> range, but I'm not used to working with it. I could then print the results on a graph with <code>mathplotlib</code>, I guess.</p> <pre><code>import random NUMBER_OF_GAMES = 10000 P_SWAP = False P_CAN_SELECT_SAME = False N_DOORS = 5 N_PRIZES = 3 N_PLAYERS = 1 VERBOSE = True PRINT_CANDY = "="*64+"\n" try: assert isinstance(P_SWAP, bool) assert N_DOORS &gt; 0 assert N_PRIZES &gt; 0 assert N_PLAYERS &gt;= 0 assert isinstance(VERBOSE, bool) except (AssertionError, TypeError): print("Invalid value for initialisation values") exit() try: assert N_PRIZES &lt;= N_DOORS except AssertionError: print("Can't have more prizes than doors") exit() try: assert N_PLAYERS &lt; N_DOORS - N_PRIZES except AssertionError: print("Must have at least 2 less players than doors") exit() GIFT = ["CAR"] COAL = ["GOAT", "POOP", "COAL", "CRAP"] win_counter = 0 lose_counter = 0 # overriding print functions def supress_prints(): """ Since print() redirects strings to STDOUT, we can override this to /dev/null, instead of terminal, and thus avoid printing unnecessary information. Speeds up program too. """ import sys, os if VERBOSE: return sys.stdout = open(os.devnull, 'w') def restore_prints(): """ Returns print() to its default value: STDOUT. """ import sys sys.stdout = sys.__stdout__ class Door: def __init__(self, game: "Game", content: str, is_open: bool=False): self.content = content self.is_open = is_open self.index = len(game.doors) # works as long as no doors are deleted from the game print(self) def is_prize(self): if self.content == GIFT: return True else: return False def is_open(self): return self.is_open def is_closed(self): return not self.is_open def open(self): self.is_open = True def close(self): self.is_open = False def __str__(self): return ["Open " if self.is_open else "Closed "][0] + self.content + " @door " + str(self.index) class Game: def __init__(self, swaps: bool=True, number_of_doors: int=3, number_of_prizes: int=1, number_of_players: int=1, players_can_collide: bool=False )-&gt;"Game": self.number_of_doors = number_of_doors self.number_of_prizes = number_of_prizes self.number_of_players = number_of_players self.players_can_collide = players_can_collide self.doors = list() self.prizes = list() self.open_doors = list() # create a Player object for each allowed player in the game print("Creating players...") self.players = list() while len(self.players) &lt; number_of_players: self.players.append( Player(self, swaps) ) print("Done!"); print() # figure out what doors should contain each prize while len(self.prizes) &lt; number_of_prizes: self.winning_door = None while self.winning_door in self.prizes \ or self.winning_door == None: self.winning_door = random.randrange(0,number_of_doors) self.prizes.append(self.winning_door) # create all the Door objects in the game, while adding # their contents simultaneously print("Creating doors...") for new_door in range(number_of_doors): if new_door in self.prizes: self.doors.append( Door(self, random.choice(GIFT)) ) else: self.doors.append( Door(self, random.choice(COAL)) ) print("Done!"); print("Game is configured!") print(PRINT_CANDY) def start_game(self): ############# # round one # ############# print("ROUND ONE: \n") # let all players select a door self.selected_doors = list() for player in self.players: selection = player.select_door() # finding doors which can be opened: must not be selected, nor can't have a GIFT in it self.removable_candidates = list() for player in self.players: for door in self.doors: if door.is_closed(): if self.doors.index(door) not in self.selected_doors: if door.content not in GIFT: self.removable_candidates.append(door) # clear selections for game state (still saved in Player instances) self.selected_doors.clear() print(PRINT_CANDY) #### ## TODO: maybe add some temporary stat printing here #### ############# # round two # ############# print("ROUND TWO: \n") self.pandora_door = random.choice(self.removable_candidates) # a door with evil stuff in it self.pandora_door.open() print("Pandora door:", self.pandora_door) self.open_doors.append(self.pandora_door) # open one COAL door print() # for all players that want to swap door, do so now for player in self.players: if player.swaps: player.select_door(force_change=True) print() ############### # end of game # ############### # print results print("Final results!") for player in self.players: global win_counter, lose_counter print("Player", player.index, end=": ") if self.doors[player.selection].content in GIFT: print("Won a", self.doors[player.selection].content, "at door", player.selection) win_counter += 1 else: print("Got some", self.doors[player.selection].content, "by selecting door", player.selection) lose_counter += 1 class Player: def __init__(self, game: Game, swaps: bool) -&gt; "Player": self.game = game # could possibly be called by with super(), defining Player as a subclass of Game self.swaps = swaps self.selection = None self.index = len(game.players) # non-intuitive, but works as long as players are not removed from game print("Created player", self.index) def select_door(self, force_change: int=False) -&gt; int: """ Allow player to choose any Door from the game which is not opened, and depending on the settings, whether is not already selected by another player. """ self.old_selection = self.selection self.selection = None while (self.selection in self.game.selected_doors and self.game.players_can_collide) \ or self.selection in self.game.open_doors \ or (self.selection == self.old_selection and force_change) \ or self.selection is None: self.selection = random.randrange(0, self.game.number_of_doors) self.game.selected_doors.append(self.selection) print("Player", self.index, "selected door", self.selection) return self.selection # helper, not required supress_prints() for _ in range(NUMBER_OF_GAMES): Monty_Hall_Game = Game(swaps=P_SWAP, number_of_doors=N_DOORS, number_of_prizes=N_PRIZES, number_of_players=N_PLAYERS) Monty_Hall_Game.start_game() print(PRINT_CANDY*2) print() restore_prints() win_percent = win_counter*100//(NUMBER_OF_GAMES*N_PLAYERS) lose_percent = lose_counter*100//(NUMBER_OF_GAMES*N_PLAYERS) print(f""" Statistics: {PRINT_CANDY} With a total of {NUMBER_OF_GAMES} games, configured as: Players: {N_PLAYERS} Swapping: {P_SWAP} Colliding: {P_CAN_SELECT_SAME} Doors: {N_DOORS} Prizes: {N_PRIZES} {win_counter} wins \t ({win_percent}%), {lose_counter} losses \t ({lose_percent}%)! {PRINT_CANDY}""") </code></pre> <p>All in all, how can I improve my code? What makes you cringe?</p>
[]
[ { "body": "<p>You’ve got many errors in your code. </p>\n\n<p>In <code>class Door</code>, you set <code>self.is_open</code> to <code>False</code>, but door already contained the method <code>def is_open(self)</code>, so you’ve overwritten the object’s method, and can no longer call <code>door.is_open()</code>.</p>\n\n<p>The method <code>def is_open(self)</code> returned <code>self.is_open</code>, which would be a method reference if it wasn’t overwritten above, so the method would have always return a “truthy” value. </p>\n\n<p>In <code>class Player</code>, you have <code>def select_door(self, force_change: int=False)</code>. The parameter <code>force_change</code> is given the type <code>int</code>, with a default value of <code>False</code>. Round peg in a square hole. </p>\n\n<hr>\n\n<p>Your code is unnecessarily verbose:</p>\n\n<pre><code> if self.content == GIFT:\n return True\n else:\n return False\n</code></pre>\n\n<p>Could be:</p>\n\n<pre><code> return self.content == GIFT\n</code></pre>\n\n<p>But <code>GIFT</code> is a list of all of the prizes! Shouldn’t there just be one prize behind a door? Maybe:</p>\n\n<pre><code> return self.content in GIFT\n</code></pre>\n\n<p>How does your code actually work? Oh, right, you never call the method <code>door.is_prize()</code>, just like you never call <code>door.is_open()</code>. If you write a function, test it and make sure it works. </p>\n\n<hr>\n\n<blockquote>\n <p>1) Would I benefit from making Player a subclass of Game (or the other\n way around)?</p>\n</blockquote>\n\n<p>Use the “is-a” test. Is a player a game? I’d say “no”. How about is a game a player? Again, I’d say “no”. Unless the answer to one of those is a “yes”, making something a subclass of another thing is a very bad idea.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T05:02:07.240", "Id": "223711", "ParentId": "223692", "Score": "4" } } ]
{ "AcceptedAnswerId": "223711", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T18:27:43.743", "Id": "223692", "Score": "2", "Tags": [ "python", "python-3.x", "simulation" ], "Title": "Monty Hall problem in Python3" }
223692
<p>I've recently started building an API that allows a consumer to create and manipulate musical entities such as notes, intervals, scales and chords.</p> <p>The first step is to create a a foundation of base structures that are later used by the musical entities. One such structure is a <code>Ring</code>. </p> <p><strong>A ring in <a href="https://en.wikipedia.org/wiki/Congruence_relation" rel="nofollow noreferrer">modular arithmic</a></strong></p> <p>A Ring is an integer's representation clamped between <code>0</code> and the ring size. Its <code>Value</code> is the integer it represents. Its <code>Size</code> is the group size. Its <code>Class</code> is the congruent value clamped in the specified range. Its <code>Group</code> determines the number of ranges it's away from the reference group <code>0</code>.</p> <p><strong>A ring from the perspective of Music Theory</strong></p> <blockquote> <p>The way I'm using a ring is to define a musical note. A note consists of a pitch and a degree. The pitch is a number that represents the frequency of a note. A ring with size <code>12</code> is used to represent all semi-tones within a single octave. Each octave is a ring group. Another ring with size <code>7</code> is used to define the degree of the note. Common representations of degrees are <code>{C, D, E, F, G, A, B}</code> or <code>do-re-mi-fa-sol-la-ti</code>. The note <code>C</code> on the <code>5</code>th octave is considered the reference note with pitch <code>0</code> and degree <code>0</code>.</p> </blockquote> <p>I want to be able to change a ring's properties. The example below shows how the pitch of a note could be represented by a ring.</p> <pre><code>val pitch = Ring(0, 12) // the pitch of note 'C5' pitch.Group = 1 // the pitch one octave higher 'C6' pitch.Class = 2 // the pitch class changed to that of note 'D6' println(pitch) // Ring(Value=14, Size=12) </code></pre> <p>The example below shows how the degree of a note could be represented by a ring.</p> <pre><code>val degree = Ring(0, 7) // the degree of note 'C5' degree.Group = 1 // the degree one octave higher 'C6' degree.Class = 1 // the degree class changed to that of note 'D6' println(degree) // Ring(Value=8, Size=7) </code></pre> <p>This means the note <code>D6</code> can be represented by pitch <code>Ring(Value=14, Size=12)</code> and degree <code>Ring(Value=8, Size=7)</code>.</p> <p>I have opted to use a mutable class and data class. I want a mutable class because I require a lot of manipulations to be chained. And I desire a data class because of its nature of hiding boiler-plate code and providing interesting methods such as copy.</p> <pre><code>val ring = someOtherRing.copy().setClass(2).setGroup(1) </code></pre> <p>I did read that <a href="https://medium.com/@DarrenAtherton/intro-to-data-classes-in-kotlin-7f956d54365c" rel="nofollow noreferrer">data classes should be immutable</a>.</p> <blockquote> <p>So my questions are:</p> </blockquote> <ul> <li><p><strong>Is it allowed to use the data class as mutable class?</strong></p></li> <li><p><strong>Does it make sense that I combine mutable and data class for the Ring class?</strong></p></li> <li><p><strong>Are there better alternatives to create an API class?</strong></p></li> </ul> <p>Any additional feedback on Kotlin guidelines, general guidelines, fluent-ish methods and varia is welcome as well.</p> <p>Ring code:</p> <pre><code>import kotlin.math.* data class Ring(var Value: Int, val Size: Int) { var Class: Int get() = modulo(Value) set(value) { Value = Group * Size + modulo(value) } var Group: Int get() = Value / Size set(value) { Value = value * Size + Class } fun setValue(value: Int): Ring { Value = value return this } fun setClass(clazz: Int): Ring { Class = clazz return this } fun setGroup(group: Int): Ring { Group = group return this } private fun modulo(x: Int): Int { return (x % Size + Size) % Size } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T05:56:12.100", "Id": "433698", "Score": "2", "body": "When I first read the yellow paragraph, I did not understand any of the words. Is a \"ring\" a common concept in music? If so, you should link to the Wikipedia article. If it is your own invention, describe it in simple words, not mathematically abstract terms. If you had said \"a ring is the pitch of a single tone, split up into the octave and the half-tone in it, such as c5 or a'3\", it would have been much clearer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T05:59:07.340", "Id": "433699", "Score": "0", "body": "@RolandIllig I get what you mean. A ring is a mathematical concept, used in modular arithmic. I require this class as a base structure to create notes and other musical structures. Perhaps I should describe it from the perspective of music rather than mathematics. I will edit the post and make that point more clear." } ]
[ { "body": "<p>Your concepts look completely misguided.</p>\n\n<p>A <em>ring</em> is a mathematical concept, an algebraic structure. It does have a size, but it doesn't have a value.</p>\n\n<p>The value would be part of a <em>ring element</em>. Such a ring element is a tuple (ring, value).</p>\n\n<p>The pitch of a note is indeed a ring element. A ring element can only be used to store the pitch of a note, but not its octave. If it did, it would not match the mathematical concept of a ring anymore.</p>\n\n<p>To represent a musical note in Western notation, my first idea is:</p>\n\n<pre><code>data class Note(\n val octave: Int,\n val name: NoteName,\n val mod: NoteModifier,\n val duration: NoteDuration\n)\n\nenum class NoteName {\n C, D, E, F, G, A, B\n}\n\nenum class NoteModifier {\n Natural, Sharp, Flat, TwoSharp, TwoFlat\n}\n\nenum class NoteDuration {\n Full, Half, Quarter, Eighth, Sixteenth\n}\n</code></pre>\n\n<p>The above definitions are very rough and limited. To get a grasp of the actual complexity of typesetting music, have a look at LilyPond, it should have a definition of a note somewhere in the code.</p>\n\n<p>If you just want to replay the music, there's no need to distinguish between c# and d<span class=\"math-container\">\\$\\flat\\$</span>, which would make the above definitions much simpler.</p>\n\n<p>In Kotlin you don't need setters since the <code>copy</code> function is more powerful than in Java. You can just say:</p>\n\n<pre><code>val note = other.copy(octave = 3, pitch = 5)\n</code></pre>\n\n<p>This is easier to grasp and less code to write. If you write a setter method in Kotlin, lean back and think twice. Probably you are doing something unusual.</p>\n\n<p>By the way, property names in Kotlin are written in lowercase. Kotlin is based on Java, not C#.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T06:27:37.303", "Id": "433702", "Score": "0", "body": "We concurrently answered and edited the question. Is my edit an invalidation of your answer?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T06:28:05.517", "Id": "433703", "Score": "0", "body": "No, it isn't. Everything's fine. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T06:34:30.990", "Id": "433704", "Score": "0", "body": "I do think you are right about the concept of a _ring_, it does not include the group. What I have created is more of a _coil_ (no reference found in math), where we care about which level we are. I do care about enharmonics though, I will post a next question soon with a full implemenation of _Note_ that will use 2 _Coil_ instances." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T06:23:44.410", "Id": "223714", "ParentId": "223697", "Score": "3" } }, { "body": "<p>I have decided against (ab-)using a mathematical construct <code>Ring</code> for creating musical entities. \nAs Roland pointed out, it just didn't fit the purpose.\nInstead, I have created my own structure <code>Coil</code> which represents a <code>Value</code> with its <code>Index</code> in\na group <code>Group</code> of magnitude <code>Size</code>. I'm still using setters, but only for derived properties.</p>\n\n<p><code>Coil</code> class:</p>\n\n<pre><code>import kotlin.math.*\n\ndata class Coil(var value: Int, val size: Int) {\n\n var index: Int\n get() = modulo(value)\n set(n) { \n value = group * size + modulo(n) \n }\n\n var group: Int\n get() = value / size\n set(n) { \n value = n * size + index \n }\n\n val delta: Int\n get() {\n val d1 = index\n val d2 = size - d1\n return if (d1 &lt;= d2) d1 else -d2\n }\n\n private fun modulo(n: Int): Int {\n return (n % size + size) % size\n } \n}\n</code></pre>\n\n<p>To give you an idea how I am going to use a <code>Coil</code> I have created a simplified version of a <code>Note</code>.\nThe way I want to uses a note is to manipulate them and their role within chords and scales.\nI do not intend to create sheet music, so I don't require a <em>position</em> or <em>duration</em>.\nA note uses one coil to store its <em>pitch</em> and one to store its <em>degree</em>. \nBoth these values are absolutes, meaning the <em>octave</em> is included in the value. Their setters re-sync the <em>octave</em>.\nSetting the <em>pitchClass</em> or <em>degreeClass</em> does not change the <em>octave</em>.\nA note's <em>name</em> consists of its <em>pitchClass</em> in scientific pitch notation, its <em>accidentals</em> (flat, sharp, natural) and <em>octave</em>.</p>\n\n<p><code>Note</code> Usage: (to give an idea about the interaction between Coil and Note)</p>\n\n<pre><code>fun main() {\n\n val note = Note(0, 0, 5) // C5\n note.degreeClass = 1 // Dbb5\n note.pitchClass = 1 // Db5\n note.octave = 6 // Db6\n note.accidentals = 1 // D#6\n\n println(note.name) \n}\n</code></pre>\n\n<p><code>Note</code> class:</p>\n\n<pre><code>import kotlin.math.*\n\nclass Note(var _pitch: Int, var _degree: Int, var _octave: Int) {\n\n private val PITCH_COUNT = 12\n private val DEGREE_COUNT = 7\n private val FLAT = 'b'\n private val SHARP = '#'\n\n private val DIATONIC_PITCH_CLASS_SET \n : IntArray = intArrayOf(0, 2, 4, 5, 7, 9, 11)\n\n private val SCIENTIFIC_PITCH_CLASS_SET \n : CharArray = charArrayOf('C', 'D', 'E', 'F', 'G', 'A', 'B')\n\n private val p = Coil(_pitch, PITCH_COUNT)\n private val d = Coil(_degree, DEGREE_COUNT)\n\n init {\n p.group = _octave\n d.group = _octave\n }\n\n var pitch: Int\n get() = p.value\n set(n) { \n p.value = n \n octave = p.group\n }\n\n var degree: Int\n get() = d.value\n set(n) { \n d.value = n \n octave = d.group\n }\n\n var octave: Int\n get() = p.group\n set(n) { \n p.group = n\n d.group = n\n }\n\n var pitchClass: Int\n get() = p.index\n set(n) { \n p.index = n\n }\n\n var degreeClass: Int\n get() = d.index\n set(n) { \n d.index = n\n }\n\n var accidentals: Int\n get() {\n val delta = pitchClass - DIATONIC_PITCH_CLASS_SET[degreeClass]\n return Coil(delta, PITCH_COUNT).delta\n }\n set(n) { \n pitchClass = DIATONIC_PITCH_CLASS_SET[degreeClass] + n\n }\n\n val name: String\n get() {\n val sb = StringBuilder()\n val d = accidentals\n sb.append(SCIENTIFIC_PITCH_CLASS_SET[degreeClass])\n if (d != 0) {\n sb.append(Character.toString((if (d &gt; 0) SHARP else FLAT)).repeat(abs(d)))\n }\n sb.append(octave)\n return sb.toString()\n } \n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-11T16:55:58.830", "Id": "223962", "ParentId": "223697", "Score": "3" } } ]
{ "AcceptedAnswerId": "223714", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T19:27:48.673", "Id": "223697", "Score": "4", "Tags": [ "api", "kotlin", "music", "reference" ], "Title": "Music Theory: The Basics - a Ring" }
223697
<p>I need help to simplify this code about implicit date calculation.</p> <p>The context: I have sentences with implicit and explicit dates. For instance:</p> <blockquote> <p>"From the 5th to the 7th of September 2017, the 12th, 13th and 15th of June, from the 25th to the 31th December, the 1st and the 2nd of January 2019."</p> </blockquote> <p>A program (not shown here) can parse implicit and explicit dates, so I can get an ordered list (in chronological order) like that:</p> <pre class="lang-py prettyprint-override"><code> history = [ [5], [7, 9, 2017], [12], [13], [15, 6], [25], [31, 12], [1], [2, 1, 2019], ] </code></pre> <p>The purpose of the program below is to calculate the dates.</p> <pre class="lang-py prettyprint-override"><code>import datetime class ImplicitDate(object): def __init__(self, day: int, month: int = None, year: int = None): self.day = day self.month = month self.year = year def __repr__(self): cls = self.__class__.__name__ return f"&lt;{cls}(day={self.day!r}, month={self.month!r}, year={self.year!r})&gt;" def __str__(self): s = [] if self.year: s.append(f"{self.year:04d}") if self.month: s.append(f"{self.month:02d}") if self.day: s.append(f"{self.day:02d}") return "-".join(s) @property def date(self) -&gt; datetime.date or None: if self.year is None or self.month is None or self.day is None: return None return datetime.date(self.year, self.month, self.day) def estimate_date(self, future_date: datetime.date) -&gt; datetime.date: if self.day is None: # weird return future_date elif self.month is None: day = self.day month = future_date.month year = future_date.year date = datetime.date(year, month, day) if date &lt; future_date: return date else: month = future_date.month - 1 if month == 0: month = 12 year = future_date.year - 1 date = datetime.date(year, month, day) return date elif self.year is None: day = self.day month = self.month year = future_date.year date = datetime.date(year, month, day) if date &lt; future_date: return date else: year = future_date.year - 1 date = datetime.date(year, month, day) return date else: day = self.day month = self.month year = self.year date = datetime.date(year, month, day) return date def demo_implicit_dates(): history = [ ImplicitDate(5), ImplicitDate(7, 9, 2017), ImplicitDate(12), ImplicitDate(13), ImplicitDate(15, 6), ImplicitDate(25), ImplicitDate(31, 12), ImplicitDate(1), ImplicitDate(2, 1, 2019), ] curr = history.pop() dates = [curr.date] while history: top = dates[-1] curr = history.pop() estimated = curr.estimate_date(top) dates.append(estimated) dates.reverse() for date in dates: print(date.isoformat()) # 2017-09-05 # 2017-09-07 # 2018-06-12 # 2018-06-13 # 2018-06-15 # 2018-12-25 # 2018-12-31 # 2019-01-01 # 2019-01-02 </code></pre> <p>Do you think this program is complex or over-designed? How to simplify it?</p> <p>Do you think this algorithm is well-implemented? Is there something I am missing?</p>
[]
[ { "body": "<p>Interesting exercise! Some suggestions:</p>\n\n<ul>\n<li>It looks like a cleaner design might be to have a function (as opposed to a method) which takes a <code>List[ImplicitDate]</code> and returns <code>List[datetime.datetime]</code>.</li>\n<li><a href=\"https://docs.python.org/3/library/datetime.html#datetime.datetime\" rel=\"nofollow noreferrer\"><code>datetime.datetime</code> months are one-offset</a>, so I'm puzzled at the <code>month = future_date.month - 1</code> line.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T08:44:45.823", "Id": "433714", "Score": "0", "body": "* Actually, using a function was my first idea. Since `estimate_date` uses `self`, I prefer using a method.\n* months are one-offest, so I use: `if month == 0: month = 12; year = future_date.year - 1` to go one month backward in the past." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T01:36:24.247", "Id": "223708", "ParentId": "223699", "Score": "2" } }, { "body": "<blockquote>\n<pre><code> elif self.month is None:\n day = self.day\n month = future_date.month\n year = future_date.year\n date = datetime.date(year, month, day)\n if date &lt; future_date:\n return date\n else:\n month = future_date.month - 1\n if month == 0:\n month = 12\n year = future_date.year - 1\n date = datetime.date(year, month, day)\n return date ```\n</code></pre>\n</blockquote>\n\n<p>This can be simplified to:</p>\n\n<pre><code>if len(a_date) &gt; 1:\n if (curr_month and a_date[1] &gt; curr_month):\n curr_year -= 1\n curr_month = a_date[1]\n</code></pre>\n\n<p>Also,</p>\n\n<blockquote>\n<pre><code> elif self.year is None:\n day = self.day\n month = self.month\n year = future_date.year\n date = datetime.date(year, month, day)\n if date &lt; future_date:\n return date\n else:\n year = future_date.year - 1\n date = datetime.date(year, month, day)\n return date ```\n</code></pre>\n</blockquote>\n\n<p>Can now use a shared statement such as:</p>\n\n<pre><code>if len(a_date) &gt; 1:\n if (curr_month and a_date[1] &gt; curr_month):\n curr_year -= 1\n curr_month = a_date[1]\n if len(a_date) &gt; 2:\n curr_year = a_date[2]\n</code></pre>\n\n<p>Then,</p>\n\n<blockquote>\n<pre><code>if self.year is None or self.month is None or self.day is None\n</code></pre>\n</blockquote>\n\n<p>Can be simplified using the <code>any()</code> operator which checks a list of items against a condition (in this case if they are not <code>None</code>) then returns true/false depending on if all items satisfied the condition.</p>\n\n<blockquote>\n<pre><code>day = self.day\n month = future_date.month\n year = future_date.year\n date = datetime.date(year, month, day)\n</code></pre>\n</blockquote>\n\n<p>I would turn this into a function as it is repeated again.</p>\n\n<p>The final code after condensing the logic is:</p>\n\n<pre><code>def implicit_dates(history):\n computed_dates = []\n curr_day = None\n curr_month = None\n curr_year = None\n history = reversed(history)\n for a_date in history:\n curr_day = a_date[0] \n if len(a_date) &gt; 1:\n if (curr_month and a_date[1] &gt; curr_month):\n curr_year -= 1\n curr_month = a_date[1]\n if len(a_date) &gt; 2:\n curr_year = a_date[2]\n if (curr_day and curr_month and curr_year):\n computed_dates.append(\n datetime.datetime(curr_year, curr_month, curr_day))\n return reversed(computed_dates)\n\n\nfor historical_date in implicit_dates(history):\n print(historical_date.strftime(\"%Y-%m-%d\"))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-12-06T00:20:20.793", "Id": "233494", "ParentId": "223699", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T20:00:40.823", "Id": "223699", "Score": "7", "Tags": [ "python", "algorithm", "datetime" ], "Title": "Calculate implicit dates" }
223699
<p>I come from this <a href="https://codereview.stackexchange.com/questions/219686/gin-framework-project-with-an-endpoint-to-return-a-list-of-users-based-on-their">question</a>.</p> <p><strong>Project</strong></p> <p>A very simple <a href="https://github.com/josekron/liveops-tool/tree/d1c0307de153b7edb4c5ee22c283e193c7ec2ac8" rel="nofollow noreferrer">project</a> with Gin framework with an endpoint to return a list of users based on their score.</p> <p><strong>Structure</strong></p> <pre><code>liveops-tool -- user ---- model ------ user.go ---- service ------ userService.go ---- dao ------ directory.go (interface) ------ userDirectory.go (mock the db) ------ userPostgresDirectory.go -- main.go </code></pre> <p><strong>main.go</strong></p> <pre><code>r.GET("/competition/users", func(c *gin.Context) { numUsers, err := strconv.Atoi(c.DefaultQuery("numusers", "6")) minScore, err := strconv.Atoi(c.DefaultQuery("minscore", "0")) maxScore, err := strconv.Atoi(c.DefaultQuery("maxscore", "2000")) fmt.Printf("numUsers: %d , minScore: %d , maxScore: %d \n", numUsers, minScore, maxScore) if err == nil { var userDirectoryService = userService.NewService(userDirectory.UserPostgrestDirectory{}) var res = userDirectoryService.GenerateUserListByScore(numUsers, minScore, maxScore) c.JSON(http.StatusOK, gin.H{"users": res}) } else { c.JSON(http.StatusBadRequest, gin.H{"users": "no valid"}) } }) </code></pre> <p><strong>userService.go</strong></p> <pre><code>package user import ( dao "liveops-tool/user/dao" models "liveops-tool/user/models" ) type UserService struct { dir dao.Directory } func NewService(dir dao.Directory) *UserService { var service = &amp;UserService{ dir: dir, } return service } // GenerateUserListByScore returns a list of users for a tournament func (u UserService) GenerateUserListByScore(numUsers, minScore, maxScore int) []models.User { return u.dir.SearchUsers(numUsers, minScore, maxScore) } </code></pre> <p><strong>userPostgresDirectory.go</strong></p> <pre><code>package user import ( "database/sql" "fmt" models "liveops-tool/user/models" "strings" _ "github.com/lib/pq" ) const ( host = "localhost" port = 5432 user = "postgres" password = "XXXX" dbname = "XXXX" ) type UserPostgrestDirectory struct { } func (u UserPostgrestDirectory) getConnection() *sql.DB { psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+"password=%s dbname=%s sslmode=disable", host, port, user, password, dbname) db, err := sql.Open("postgres", psqlInfo) checkErr(err) return db } func (u UserPostgrestDirectory) SearchUsers(numUsers, minScore, maxScore int) []models.User { db := u.getConnection() defer db.Close() err := db.Ping() checkErr(err) fmt.Println("Successfully connected!") rows, err := db.Query("SELECT * FROM users WHERE total_score &gt;= $1 AND total_score &lt;= $2 LIMIT $3", minScore, maxScore, numUsers) if err != nil { panic(err) } var users = []models.User{} for rows.Next() { var id int var name string var country string var total_score int err = rows.Scan(&amp;name, &amp;id, &amp;country, &amp;total_score) checkErr(err) fmt.Println("id | name | country | total_score ") fmt.Printf("%3v | %8v | %6v | %6v\n", id, name, country, total_score) user := models.User{ ID: id, Name: strings.TrimSpace(name), Country: strings.TrimSpace(country), TotalScore: total_score, } users = append(users, user) } return users } func checkErr(err error) { if err != nil { panic(err) } } </code></pre> <p><strong>Questions</strong></p> <ul> <li>Is it possible to retrieve the connection directly open or apply some singleton pattern to avoid creating a connection every time that the method SearchUsers is called? I even tried to pass the connection on the UserPostgrestDirectory constructor from main.go but I always get the error "database is closed".</li> </ul> <p>Any other feedback about the code is well received.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T21:17:43.400", "Id": "223701", "Score": "1", "Tags": [ "beginner", "go", "postgresql", "web-services" ], "Title": "Golang and Gin framework: best practices to connect to Postgresql" }
223701
<p>I have a number of Excel tables that I want to populate into VBA dictionaries. Most of the code is repetitive but there are some unique things for each table that prevent me from making one general purpose routine and calling it for each table. The basic code:</p> <pre><code>Public Sub MakeDictionary( _ ByVal Tbl As ListObject, _ ByRef Dict As Scripting.Dictionary) ' This routine loads an Excel table into a VBA dictionary Dim ThisList As TableHandler Set ThisList = New TableHandler Dim Ary As Variant If ThisList.TryReadTable(Tbl, False, Ary) Then Set Dict = New Scripting.Dictionary pInitialized = True Dim I As Long For I = 2 To UBound(Ary, 1) Dim ThisClass As MyClass Set ThisClass = New MyClass ThisClass.Field1 = Ary(I, 1) ThisClass.Field2 = Ary(I, 2) If Dict.Exists(Ary(I, 1)) Then MsgBox "Entry already exists: " &amp; Ary(I, 1) Else Dict.Add Ary(I, 1), MyClass End If Next I Else MsgBox "Error while reading Table" End If End Sub </code></pre> <p>TableHandler and TryReadTable are a class and function that reads a table into a variant array. Field1 and Field 2 are the columns of the Excel table. My tables range from 1 to 8 columns depending on the table.</p> <p>I don't know how to make these lines generic:</p> <pre><code> Dim ThisClass As MyClass Set ThisClass = New MyClass ThisClass.Field1 = Ary(I, 1) ThisClass.Field2 = Ary(I, 2) </code></pre> <p>At this point I have to make 10-12 versions of MakeDictionary where only the class name and class fields are unique. If that's the best way to do it, I can live with it, but, I'd like to make my code more general. Any suggestions?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T05:52:42.633", "Id": "433695", "Score": "1", "body": "What is `TableHandler` and `TryReadTable`? Perhaps this code is helping confuse the issue." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T05:55:30.763", "Id": "433696", "Score": "0", "body": "Does this compile and run? I would guess not!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T05:56:10.453", "Id": "433697", "Score": "0", "body": "What is `MyClass`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T06:02:13.337", "Id": "433700", "Score": "0", "body": "Missing some context - how is this called? Understanding the code around the call may provide insight how to make it generic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T06:44:27.277", "Id": "433706", "Score": "0", "body": "How do you define each Class type, how do you know which one to use? And, seeing as you don't do anything other than Field1 and Field2, does it really matter?" } ]
[ { "body": "<h2>Option Explicit!</h2>\n\n<p>Suggestion #1: Put <code>Option Explicit</code> at the top of the module. <strong>Always!</strong></p>\n\n<p>This would have prevented the very embarrassing error of <code>Dict.Add Ary(I, 1), MyClass</code>. Upon which I see that this code would neither compile nor run unless this Class is a default instance.</p>\n\n<h2>Function or Sub?</h2>\n\n<p>If you are only returning one value, then you can use a <code>Function</code>, not a <code>Sub</code>.</p>\n\n<h2>Keep it Simple!</h2>\n\n<p>You have made this more complicated than required. You already pass in a <code>ListObject</code>, and you want the <code>DataRange</code>. Just do that instead of calling custom classes that return something that you then have to modify/clean up. </p>\n\n<blockquote>\n<pre><code>Dim ThisList As TableHandler\nSet ThisList = New TableHandler\n\nDim Ary As Variant\n\nIf ThisList.TryReadTable(Tbl, False, Ary) Then\n [...]\n</code></pre>\n</blockquote>\n\n<p>becomes</p>\n\n<pre><code>Dim Ary As Variant\nIf Not Tbl is Nothing then \n Ary = Tbl.DataRange\n [...]\n</code></pre>\n\n<p>In addition, you have <code>pInitialized = True</code> but you don't declare or use <code>pInitialized</code> anywhere else.</p>\n\n<h2>Interface or encapsulate?</h2>\n\n<p>This is a classic example where the use of an interface would greatly assist.\nCreate an interface class which basically sets up a contract for some of the methods to be used. In other words, make sure that all of these 10-12 Classes you mention have the right method or property so that you can call and create as required.</p>\n\n<blockquote>\n<pre><code>Public Sub MakeDictionary( _\n ByVal Tbl As ListObject, _\n ByRef Dict As Scripting.Dictionary)\n</code></pre>\n</blockquote>\n\n<p>Can become</p>\n\n<pre><code>Public Sub MakeDictionary( _\n ByVal Tbl As ListObject, _\n ByRef Dict As Scripting.Dictionary, \n ByVal SomeTag as &lt;whatever type is most appropriate&gt;)\n</code></pre>\n\n<p>And further in the code you can have</p>\n\n<pre><code> For I = LBound(Ary, 1) To UBound(Ary, 1) '&lt;- remember - we fixed this in my comment above!\n Dim ThisClass As IClass\n Select Case SomeTage\n Case TagA\n Set ThisClass = New MyClass1\n Case TagB\n Set ThisClass = New MyClass2\n End Select\n\n 'ThisClass.Field1 = Ary(I, 1)\n 'ThisClass.Field2 = Ary(I, 2)\n ThisClass.RelevantFillMethod(Ary(I, 1),Ary(I, 2))\n\n If Dict.Exists(Ary(I, 1)) Then ' Just in case there is some sort of transform?\n MsgBox \"Entry already exists: \" &amp; Ary(I, 1)\n Else\n Dict.Add Ary(I, 1), ThisClass \n End If\n Next I\n</code></pre>\n\n<p>Now, if the Interface had a factory method which created a new version of the relevant class - you could dispense with the <code>Dim</code> and pass the <code>MyClass1</code> instance as a parameter, calling <code>MyClass1.New</code> as necessary.</p>\n\n<pre><code>' Class IClass\nOption Explicit\n\nPublic Function NewMe() As IClass\nEnd Function\n\nPublic Sub RelevantFillMethod(val1 As Variant, val2 As Variant)\nEnd Sub\n</code></pre>\n\n<p>And</p>\n\n<pre><code>' Class Class1\nOption Explicit\nImplements IClass\n\n\nPrivate p_V1 As Variant\nPrivate P_V2 As String\n\nPublic Function EverythingElse()\n '[...]\nEnd Function\n\n\nPrivate Function IClass_NewMe() As IClass\n Set IClass_NewMe = New Class1\nEnd Function\n\nPrivate Sub IClass_RelevantFillMethod(val1 As Variant, val2 As Variant)\n p_V1 = val1\n P_V2 = CStr(val2)\nEnd Sub\n</code></pre>\n\n<h2>Subs and functions!</h2>\n\n<p>Of course, you can make this a bit easier by addressing the single responsibility concept and using logical functions. However, in the OP there is not enough information to understand where this logic break is.</p>\n\n<pre><code>Identify and loop through tables\n Create array from table '&lt;= can be a function that returns an array - single responsibility\n Identify relevant Class\n Update Dictionary based on array '&lt;= single responsibility, \n 'parameters could be the array, the dictionary and \n 'the instance of the class based on the interface\n</code></pre>\n\n<p>For example</p>\n\n<pre><code>Sub UpdateDictionary(ByVal Ary as Variant, ByRef Dict as Dictionary, ThisClass as IClass) \n For I = LBound(Ary, 1) To UBound(Ary, 1)\n If Dict.Exists(Ary(I, 1)) Then \n MsgBox \"Entry already exists: \" &amp; Ary(I, 1)\n Else\n Set ThisClass = ThisClass.NewMe\n ThisClass.RelevantFillMethod(Ary(I, 1),Ary(I, 2))\n Dict.Add Ary(I, 1), ThisClass \n End If\n Next I\nEnd Sub\n</code></pre>\n\n<h2>Final comments</h2>\n\n<p>What I have suggested above may not be the most elegant - but it is a start. Making something generic is about being able to abstract to the relevant layer.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T07:11:15.960", "Id": "223717", "ParentId": "223702", "Score": "3" } }, { "body": "<p>There is no need to instantiate a new instance of <code>MyClass</code> is it already exists and I personally don't like declaring variables inside loops.</p>\n\n<blockquote>\n<pre><code> Dim ThisClass As MyClass\n\n For I = 2 To UBound(Ary, 1)\n If Dict.Exists(Ary(I, 1)) Then\n MsgBox \"Entry already exists: \" &amp; Ary(I, 1)\n Else\n Set ThisClass = New MyClass\n ThisClass.Field1 = Ary(I, 1)\n ThisClass.Field2 = Ary(I, 2)\n Dict.Add Ary(I, 1), MyClass\n End If\n Next I\n</code></pre>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T19:52:17.130", "Id": "433865", "Score": "0", "body": "But the declarative statement is only there for compiling convenience and not called every loop - thus what you have here is code-equivalent to the original code. Declaring the variable inside the loop tells me that that variable is only used inside the loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T21:07:40.947", "Id": "433875", "Score": "0", "body": "I've gone back and forth on this topic myself. I completely agree with the comment made by @AJD in that declaring the variable inside the loop \"limits\" the scope (but only limits it visually/contextually). In other languages this scope limit is enforced. I will also declare a variable outside the loop as a reminder of the \"actual\" scope of a variable, just in case I want to use it later. YMMV" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T00:37:14.433", "Id": "433898", "Score": "0", "body": "@AJD The reason that I declare my variables outside of the loops is to reduce clutter. The variable declaration does not tell me anything about what the loop is supposed to be doing. I'm pretty up in the air about declaring variables at the point of use altogether using VBA. It makes much more sense to me in languages that allow you to instantiate classes in declarations using constructors." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T11:45:26.857", "Id": "223735", "ParentId": "223702", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T21:52:19.413", "Id": "223702", "Score": "4", "Tags": [ "vba", "excel" ], "Title": "Copy Multiple Excel Tables to VBA Dictionary" }
223702
<p>Here is my code for the <a href="https://leetcode.com/problems/maximum-width-of-binary-tree/solution/" rel="nofollow noreferrer">LeetCode problem</a></p> <blockquote> <p>For a given binary tree, find the maximum width of the binary tree. The width of one level is defined as the length between the end-nodes even if there are <code>None</code> nodes in between</p> </blockquote> <p>My code (in PyCharm) passess all the given tests but does not seem to pass on the LeetCode website. I am not sure why this is, so please don't try plugging it into the website as I assume the way I have built a binary tree is different to their method. </p> <pre><code>class Node: def __init__(self, data): self.data = data self.left = None self.right = None level_width = {0: [0, 0]} def get_width(self, root, level=0, pointer=1): if root.left: if level + 1 not in self.level_width: self.level_width[level + 1] = [pointer * 2, 0] self.level_width[level + 1][0] = min(self.level_width[level + 1][0], pointer * 2) self.get_width(root.left, level + 1, pointer * 2) if root.right: if level + 1 not in self.level_width: self.level_width[level + 1] = [9999, pointer * 2 + 1] self.level_width[level + 1][1] = max(self.level_width[level + 1][1], level + 1, pointer * 2 + 1) self.get_width(root.right, level + 1, pointer * 2 + 1) return def widthOfBinaryTree(self, root): """ :type root: TreeNode :rtype: int """ self.get_width(root) max_distance = 1 for k, v in self.level_width.items(): max_distance = max(max_distance, v[1] - v[0] + 1) return max_distance root = Node(1) root.left = Node(3) root.left.left = Node(5) root.left.left.left = Node(6) root.right = Node(2) root.right.right = Node(9) root.right.right.right = Node(7) print(root.widthOfBinaryTree(root)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T22:30:51.747", "Id": "433680", "Score": "0", "body": "Please tag your Python questions with [tag:python] and [tag:python-3.x]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T01:04:37.583", "Id": "433684", "Score": "1", "body": "This is treading a fine line: if you're asking for the community to identify and fix the test failure, then this doesn't belong on CodeReview, but rather StackOverflow. But if your intent is to disregard (for now) the test failure and improve the code in a generic sense, then you're OK here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T07:01:46.643", "Id": "433708", "Score": "0", "body": "Given I had referenced LeetCode I expected someone to check that website to confirm the performance of my code. I therefore wanted to warn anyone who looked at my code either to review it or to learn from it that this would not be beneficial as the code didn't pass Leetcode. I do not expect anyone to work out why it failed on Leetcode and am fully aware that requesting this is against site rules. I added the addendum that it passed on the Leetcode tests on my computer to let people know that this code does work. Thanks" } ]
[ { "body": "<p>In the above code, you missed counting the in-between null nodes, that is why, the result is wrong for the input [2,1,4,3, null,5].</p>\n\n<p>You approached the problem using DFS(Depth First Search) algorithm which is useful to find the height of a tree. </p>\n\n<p>BFS (Breadth-first search) algorithm would be the best suitable choice for this problem.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T15:37:56.117", "Id": "223816", "ParentId": "223703", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T22:21:35.020", "Id": "223703", "Score": "1", "Tags": [ "python", "python-3.x", "programming-challenge", "tree" ], "Title": "Maximum Width binary tree" }
223703
<p>I am running through an app idea to help improve my knowledge of Javascript. The code attached performs the following:</p> <ul> <li>Performs a regex on the input field to check it is value 0-9 If not,</li> <li><p>it clears the field and shows a warning (Although this only seems to work on FF)</p></li> <li><p>If it passes, updates the styles of the preview box on keyup </p></li> <li>Adds the styles to a text area that the user can copy when selecting the button</li> </ul> <p>I am looking for suggestions where I can improve in terms of writing more efficient code. Or pointers where I have possibly used the wrong method to perform a task. One area where I struggled was getting the value of the input field.</p> <p>This is the first stage for this application as in the near future I plan to add in the ability modify each corner.</p> <p>Feedback is welcomed</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>"use strict" const masterField = document.getElementById('masterField'); const box = document.getElementById('box'); const warn = document.getElementById('warn'); const styleSheet = document.getElementById('styleSheet'); const WARNING_TIME = 2000; var warningTimer; masterField.addEventListener('keyup', updateCss); function updateCss() { let inputVal = this.value; console.log(this.value); const expCase = /[0-9]/; if (expCase.test(inputVal)) { box.style.borderRadius = inputVal + 'px'; styleSheet.textContent = 'border-radius: ' + inputVal + 'px'; } else { this.value = ''; showWarning(); } } function hidewarning() { warn.classList.add('hide-warning'); } function showWarning() { clearTimeout(warningTimer); warningTimer = setTimeout(hidewarning, WARNING_TIME); warn.classList.remove('hide-warning'); } function copyStyles() { styleSheet.select(); document.execCommand('copy'); }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>#box { width: 300px; height: 175px; background-color: red; } #warn { display: block; } #warn.hide-warning { display: none; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="box"&gt;&lt;/div&gt; &lt;div&gt; &lt;label for="masterField"&gt;All Corners&lt;/label&gt; &lt;input id="masterField" class="radius-field" type="number"&gt; &lt;span id="warn" class="hide-warning"&gt;Only numbers 0 - 9 are allowed&lt;/span&gt; &lt;/div&gt; &lt;button onclick="copyStyles()"&gt;Copy Styles&lt;/button&gt; &lt;textarea id="styleSheet"&gt;&lt;/textarea&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<h1>UI</h1>\n\n<p>Instead of a number input, a <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/range\" rel=\"nofollow noreferrer\">range input</a> could be used - with the minimum value being zero and the maximum value being half of the lesser of the height and width - in this case 88 pixels (i.e. 175px / 2). With such an input there is no need to validate user input to ensure non-numeric characters are entered.</p>\n\n<p>With the current interface, the event handler that fires when a key is pressed does not execute when the value changes from other means (e.g. mouse click). To be thorough, it might be better to observe the <code>change</code> event on the input as well.</p>\n\n<h1>Code</h1>\n\n<p>The JavaScript code makes good use of <code>const</code> for values that don't get re-assigned, and uses <code>getElementById()</code> (as I mentioned in <a href=\"https://codereview.stackexchange.com/a/205457/120114\">a review of your <em>Nav scroll</em> code</a>). I like how the constant for the warning time is in all capitals, and all lines are terminated with a semi-colon.</p>\n\n<p>The regular expression could be simplified slightly to use the shorthand character class <code>\\d</code> instead of <code>[0-9]</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-30T21:21:57.970", "Id": "229930", "ParentId": "223705", "Score": "2" } } ]
{ "AcceptedAnswerId": "229930", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-07T22:30:17.967", "Id": "223705", "Score": "6", "Tags": [ "javascript", "performance", "beginner", "css", "ecmascript-6" ], "Title": "Border Radius Preview Tool" }
223705
<p>I am learning to use the new API version of Paypal, and I have some doubts.</p> <blockquote> <p>Note: I've tried this on <a href="https://www.sandbox.paypal.com" rel="nofollow noreferrer">https://www.sandbox.paypal.com</a> and it works, I have not done the tests on Live.</p> </blockquote> <h1>onApprove:</h1> <p>I need to send additional personalized data to Paypal, and once the user makes the payment, I return to a URL on my server, and then retrieve the data I sent.</p> <p>Paypal uses <strong>fetch()</strong> to do to specify the URL and a Json object called headers, there I am adding the additional value called <em>user_ID</em> that I need to recover.</p> <p>I am using the PHP function <strong>getallheaders()</strong>, to retrieve <em>user_ID</em>, which I have specified.</p> <p><strong>My questions are:</strong></p> <ol> <li>Is this a correct way to send personalized data to PayPal and then be recovered?</li> <li>It is safe to use <strong>getallheaders()</strong>, I understand that the headers can be modified before being sent, is there any possibility that these can be altered?</li> <li>Using <strong>$_SERVER['HTTP_REFERER']</strong>, to detect that the referred website is from Paypal, is this still safe or difficult to break?</li> <li>Would this be a secure way to integrate Paypal Checkout?</li> <li>Any recommendation that can give me, please.</li> </ol> <p><em>I would greatly appreciate your help.</em></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;head&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge" /&gt; &lt;/head&gt; &lt;body&gt; &lt;input type="text" id="price" value="100.00"&gt; &lt;input type="hidden" id="user_id" value="15"&gt; &lt;div id="paypal-button-container"&gt;&lt;/div&gt; &lt;script src="https://www.paypal.com/sdk/js?client-id=HERE_CLIENT_ID&amp;currency=USD"&gt;&lt;/script&gt; &lt;script&gt; paypal.Buttons({ createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value: document.getElementById("price").value } }] }); }, onApprove: function(data, actions) { return actions.order.capture().then(function(details) { alert('Transaction completed by ' + details.payer.name.given_name); // Call your server to save the transaction return fetch('https://my-domain.com/payment-from-paypal.php', { method: 'post', headers: { 'content-type': 'application/json', 'user_ID': document.getElementById("user_id").value }, body: JSON.stringify({ orderID: data.orderID }) }); }); } }).render('#paypal-button-container'); &lt;/script&gt; &lt;/body&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T07:14:48.520", "Id": "433916", "Score": "0", "body": "I don't see a great deal of php in your question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T04:10:56.310", "Id": "434036", "Score": "0", "body": "PHP is the example that I also want to see, how can I consume the PHP REST API to obtain data related to a transaction, in all Paypal examples use CURL, does another PHP alternative exist without using CURL? For example, once the transaction has been made or the product has been purchased, with the Paypal token, we can obtain the data that was sent, including the personalized ones." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T04:13:49.393", "Id": "434037", "Score": "1", "body": "When you tag a question with php, I expect to see php code to review." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T00:18:10.100", "Id": "223706", "Score": "3", "Tags": [ "php", "api" ], "Title": "PayPal Checkout API with PHP - Sending and retrieving additional data safely" }
223706
<p>Update: I had not recalled the question correctly and ended up with the wrong question. I have now updated the question and the solution:</p> <p>The question is: Given an array of integers say [8,4,6,12,10] You can pop any two elements at a time and place the sum (chosen sum) back into the array. Repeating until a single element (final sum) is remaining. The task is to minimize the sum of these chosen sums in the end.</p> <p>My approach is:</p> <ul> <li>Pop the two elements with lowest value in the array, push the sum back. </li> <li>Repeat this until a single element is remaining.</li> <li>Maintain a sums, which maintains the running sum</li> </ul> <p>My solution is as follows:</p> <blockquote> <ol> <li>Sort the array</li> <li>Pop first two elements, add them, get the sum</li> <li>Place the sum in the array in such a way that it remains sorted (to avoid sorting again)</li> <li>Repeat steps 2 and 3 until we have less than two elements in the array</li> </ol> </blockquote> <p>JavaScript Code:</p> <pre><code> function join(parts, sums) { if(parts.length &lt; 2) { return sums } sum = parts[0] + parts[1] sliced = parts.slice(2) placed = place(sliced, sum) sums = sums + sum return join(placed, sums) } function place(arr, x) { index = 0 for(i=0;i&lt;arr.length;i++) { if(arr[i]&gt;x) { index = i break } } first = arr.slice(0,i) second = arr.slice(i) return [...first,x,...second] } function process(parts) { parts.sort((a,b)=&gt;a&gt;b) return join(parts, 0) } process([8,4,6,12,10]) </code></pre> <p>Is this best possible approach? Can you think of any better optimized approach?</p> <p>Update: The complexity is O(nlog n) (sort - best case) + O(n)</p> <p>As pointed out in the comments, the ideal solution would be to use a priority queue: <a href="https://www.geeksforgeeks.org/minimize-the-sum-calculated-by-repeatedly-removing-any-two-elements-and-inserting-their-sum-to-the-array/" rel="nofollow noreferrer">https://www.geeksforgeeks.org/minimize-the-sum-calculated-by-repeatedly-removing-any-two-elements-and-inserting-their-sum-to-the-array/</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T04:20:43.337", "Id": "433689", "Score": "4", "body": "Can you show an example of the minimum sum, and how this would be different from the sum of elements?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T05:48:36.133", "Id": "433694", "Score": "1", "body": "No matter how you pop them, the sum will always be the same - unless you have different definition of 'sum'. This is the basis for the commutative and distributive laws of arithmetic that we operate under." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T06:39:18.720", "Id": "433705", "Score": "1", "body": "It could be a misinterpretation of [this problem](https://www.geeksforgeeks.org/minimize-the-sum-calculated-by-repeatedly-removing-any-two-elements-and-inserting-their-sum-to-the-array/) where the sums of the removed elements are accumulated in each step." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T17:20:40.273", "Id": "433852", "Score": "0", "body": "The geeks for geeks page gives you your answer- the best solution you can get in terms of run time would be using a priority queue implemented by some sort of min heap (likely Fibonacci). If you are interested in why this is faster comment and I can write something up as the answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T08:28:53.957", "Id": "433929", "Score": "1", "body": "Let me plug that this is pretty much what is done constructing a static [Huffman code](https://en.m.wikipedia.org/wiki/Huffman_coding#Compression) - the part about using sorting and a simple queue instead of a priority queue starts with `If the symbols are sorted by probability, there is a linear-time (O(n)) method`. (An older comment somehow dissipated?!)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T01:55:56.160", "Id": "223709", "Score": "0", "Tags": [ "javascript", "performance", "algorithm", "array" ], "Title": "Minimum sum of elements, taken 2 at a time" }
223709
<p>This problem is from Automate The Boring Stuff using Python - Chapter 7.</p> <blockquote> <p>Write a function that takes a string and does the same thing as the strip() string method. If no other arguments are passed other than the string to strip, then whitespace characters will be removed from the beginning and end of the string. Otherwise, the characters specified in the second argument to the function will be removed from the string.</p> </blockquote> <p>It takes a string and a character as input and return new stripped string.</p> <pre><code>#regexStrip.py - Regex Version of strip() import re def regex_strip(s, char=None): """ Write a function that takes a string and does the same thing as the strip() string method. If no other arguments are passed other than the string to strip, then whitespace characters will be removed from the beginning and end of the string. Otherwise, the characters specified in the second argu- ment to the function will be removed from the string. """ if not char: strip_left = re.compile(r'^\s*') #string starting with whitespace strip_right = re.compile(r'\s*$') #string ending with whitespace s = re.sub(strip_left, "", s) #replacing strip_left with "" in string s s = re.sub(strip_right, "", s) #replacing strip_right with "" in string s else: strip_char = re.compile(char) s = re.sub(strip_char, "", s) return s if __name__ == '__main__': string_to_be_stripped = input("Enter string to be stripped: ") char_to_be_removed = input("Enter character to be removed, if none press enter: ") print(regex_strip(string_to_be_stripped, char_to_be_removed)) </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>Enter string to be stripped: foo, bar, cat Enter character to be removed, if none press enter: , foo bar cat </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T06:57:25.580", "Id": "433707", "Score": "0", "body": "You should add an automatic test for `regex_strip('[in brackets]', '[]')`. The result should be `'in brackets'`." } ]
[ { "body": "<h2>Pre-compilation</h2>\n\n<p>In theory, you're going to want to call this function more than once. That means that you only want to pay the cost of regex compilation once, and you should move your <code>re.compile</code> calls out of the function, setting your regex variables in the module's global scope.</p>\n\n<h2>Type-hinting</h2>\n\n<p><code>s</code> is <code>s: str</code>, and <code>char</code> is (I think) also <code>char: str</code>.</p>\n\n<h2>'Removed from the string'?</h2>\n\n<p>I think this is the fault of unclear requirements, but - it would make more sense for the <code>char</code> argument to be <em>the character[s] to strip from the string edges</em>, not <em>characters to remove from anywhere in the string</em>. As such, you would need to re-evaluate how you create your regex.</p>\n\n<h2>Combine left and right</h2>\n\n<p>There's no need for two regexes. You can use one with a capturing group:</p>\n\n<pre><code>^\\s*(.*?)\\s*$\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T13:19:01.447", "Id": "223743", "ParentId": "223713", "Score": "4" } }, { "body": "<p>With unsanitized user input, <code>re.compile(char)</code> is dangerous. You should use <code>re.compile(re.escape(char))</code>, which will allow you to strip the asterisks from <code>\"***Winner***\"</code>, instead of crashing with an invalid regular expression. </p>\n\n<p>See also <a href=\"https://codereview.stackexchange.com/q/222372/100620\">this question</a> and related answers for a different interpretation of the question’s intent for stripping other characters. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T16:00:47.757", "Id": "223756", "ParentId": "223713", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T06:22:03.663", "Id": "223713", "Score": "7", "Tags": [ "python", "beginner", "python-3.x", "regex" ], "Title": "Regex Version of strip()" }
223713
<p>Is there anything missing or any pitfall when using <code>BigInt</code>?</p> <pre><code>// Assuming n is an integer and is 0 or greater function factorial(n) { var i, result = BigInt(1); for (i = BigInt(2); i &lt;= n; i++) { result *= i; } return result; } console.log(factorial(69)); console.log(factorial(200)); console.log(factorial(69n)); console.log(factorial(200n)); </code></pre> <p>jsfiddle: <a href="https://jsfiddle.net/adr49tz2/" rel="nofollow noreferrer">https://jsfiddle.net/adr49tz2/</a></p>
[]
[ { "body": "<p>My answer is pretty heavily based on <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt\" rel=\"nofollow noreferrer\">this resource on BigInt</a>, so feel free to explore that a bit first.</p>\n\n<p>With that said, here are some of the key points I saw:</p>\n\n<ol>\n<li><code>BigInt</code> can use all the same types of simple arithmetic as <code>Number</code>, along with 0 being considered <code>falsy</code> as usual</li>\n</ol>\n\n<pre class=\"lang-javascript prettyprint-override\"><code>1n + 3n === 4n // true!\n</code></pre>\n\n<ol start=\"2\">\n<li><code>BigInt</code> is also usable as a JS primitive. Neat!</li>\n</ol>\n\n<pre class=\"lang-javascript prettyprint-override\"><code>typeof 1n === \"bigint\" // true!\n</code></pre>\n\n<ol start=\"3\">\n<li><code>BigInt</code> and <code>Number</code> <em>should not</em> be mixed and matched. The coercion between the two is ambiguous, and as such JavaScript would throw an exception in that circumstance, so you should only either use one or the other.</li>\n</ol>\n\n<pre class=\"lang-javascript prettyprint-override\"><code>1 + 1n // whoops\n</code></pre>\n\n<ol start=\"4\">\n<li><p>If the article still holds true, <code>BigInt</code> doesn't have the luxury of using operations in the built-in <code>Math</code> object. So you would either need to stick to simple arithmetic, or build (or otherwise find) those implementations yourself.</p></li>\n<li><p>Since the supported operations on <code>BigInt</code> are not constant time (according to the article), it is recommended to use <code>BigInt</code> <em>strictly</em> when a use case will frequently involve numbers higher than the largest representable int in <code>Number</code> (2<sup>53</sup>). Your question is one such case, since factorials grow <em>extremely</em> fast, so I think it's fine as is.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T16:03:19.203", "Id": "223758", "ParentId": "223720", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T07:43:29.090", "Id": "223720", "Score": "2", "Tags": [ "javascript", "integer" ], "Title": "Using BigInt in JavaScript, write a factorial function that takes either a Number or BigInt and returns a BigInt" }
223720
<p>In the existing system, we need to rebuild the user's authorization.</p> <p>The database includes Roles and Rights</p> <p>Roles were previously used but will be skipped in the new version</p> <p>All authorization will be based on Rights control</p> <p>I have prepared an attribute that performs such a task</p> <p>Controller:</p> <pre><code>[HasRights(Rights.AddPayer, Rights.DeletePayer)] [HttpPost] public IActionResult AddPayer([FromBody]PayerModel model) { } </code></pre> <p>Attribute:</p> <pre><code>[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = false)] public class HasRightsAttribute : AuthorizeAttribute, IAuthorizationFilter { HashSet&lt;Rights&gt; userRights; public HasRightsAttribute(params Rights[] rights) { userRights = rights.ToHashSet(); } public void OnAuthorization(AuthorizationFilterContext context) { Claim claim = context.HttpContext.User.Claims.FirstOrDefault(); int userId = int.Parse(claim.Value); List&lt;int&gt; rights; using (var myContext = new myDB()) { rights = (from UR in myContext.TblUserRole join RR in myContext.TblRoleRight on UR.RoleID equals RR.RoleID where UR.UserID == userId select RR.RightID) .ToList(); } var permission = rights.Any(x =&gt; userRights.Contains((Rights)Enum.ToObject(typeof(Rights), x))); if (!permission) { //context.Result = new ForbidResult(); Debug.WriteLine("NO ACCESS"); } else { Debug.WriteLine("YOU HAVE ACCESS"); } } } </code></pre> <p>Is this a good direction?</p> <p>What can be corrected / changed?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T10:00:52.867", "Id": "433734", "Score": "0", "body": "I would implement this attribute as a factory, see _Custom Filter Factories_ on [Dependency Injection in action filters in ASP.NET Core](https://www.devtrends.co.uk/blog/dependency-injection-in-action-filters-in-asp.net-core) so that you can also inject your repository." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-11T01:42:34.683", "Id": "434192", "Score": "1", "body": "Correct me if I'm wrong, but this looks like it's going to query the database to check for their permissions on every single request. It might be a better idea to store their rights in their session or signed token instead." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T07:55:24.960", "Id": "223721", "Score": "2", "Tags": [ "c#", "asp.net-core", ".net-core" ], "Title": "Own Authorization attribute" }
223721
<p>I am trying to expose a simple struct via FFI. Is this the best way to do it?</p> <p>I am not 100% sure about the get_text function. This is taking the string out of the struct and cloning it before returning a pointer to it. I suspect this is going to leak. Whats the best idiomatic way around this? Do I need to provide a free_string function? Is there a way to just return a pointer into the Rust string?</p> <pre><code>use std::mem; use std::os::raw::{c_char, c_void}; use std::ffi; #[derive(Debug)] pub struct SomeData { text : String, number : usize, } #[no_mangle] /// Make the structure. Box it to stick on the heap and return a pointer to it. /// This absolves Rust from having to deal with the memory, so it is the callers /// responsibility to free it by calling drop_data. pub extern "C" fn make_some_data (text: *const c_char, number: usize) -&gt; *mut c_void { let cstr = unsafe { assert!(!text.is_null()); ffi::CStr::from_ptr(text) }; let data = cstr.to_str().ok().map(|utf8_str| { Box::into_raw(Box::new(SomeData { text: String::from(utf8_str), number, })) }).unwrap(); data as *mut c_void } #[no_mangle] /// Returns the text field of the struct. pub extern "C" fn get_text(data: *mut c_void) -&gt; *mut c_char { let data = unsafe { assert!(!data.is_null()); Box::from_raw(data as *mut SomeData) }; let text = data.text.clone(); mem::forget(data); ffi::CString::new(text).unwrap().into_raw() } #[no_mangle] /// Returns the number field of the struct. pub extern "C" fn get_number(data: *mut c_void) -&gt; usize { let data = unsafe { assert!(!data.is_null()); Box::from_raw(data as *mut SomeData) }; let number = data.number; mem::forget(data); number } #[no_mangle] /// Frees the memory. pub extern "C" fn drop_data (data: *mut c_void) { mem::drop(data); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T11:40:34.857", "Id": "433749", "Score": "0", "body": "I wonder if it is possible to check rust binaries with valgrind?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T04:19:19.940", "Id": "433908", "Score": "0", "body": "@422_unprocessable_entity BTW yes, https://stackoverflow.com/a/51509672/7076153" } ]
[ { "body": "<p>First of all, you should always run clippy:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>error: this public function dereferences a raw pointer but is not marked `unsafe`\n --&gt; src/lib.rs:20:29\n |\n20 | ffi::CStr::from_ptr(text)\n | ^^^^\n |\n = note: #[deny(clippy::not_unsafe_ptr_arg_deref)] on by default\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#not_unsafe_ptr_arg_deref\n\nerror: calls to `std::mem::drop` with a value that implements Copy. Dropping a copy leaves the original intact.\n --&gt; src/lib.rs:60:4\n |\n60 | mem::drop(data); \n | ^^^^^^^^^^^^^^^\n |\n = note: #[deny(clippy::drop_copy)] on by default\nnote: argument has type *mut std::ffi::c_void\n --&gt; src/lib.rs:60:14\n |\n60 | mem::drop(data); \n | ^^^^\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#drop_copy\n</code></pre>\n\n<p><code>drop(data)</code> is indeed totally useless here pointer don't have drop implementation, you must use <code>Box::from_raw(data as *mut SomeData)</code> (BTW you didn't check for null here hope this is what you want). I also advise you to mark these function as <code>unsafe</code>.</p>\n\n<p>For the style there is two sides as you seem to require the pointer is no null:</p>\n\n<ul>\n<li>You could assume the pointer is always no null, add only a debug panic</li>\n<li>You could panic if the pointer is null</li>\n</ul>\n\n<p>I'm in favor of the first option but it's as you like, if you take the second option I advice to use <code>Option&lt;&amp;T&gt;</code> this will prevent you to forget to check if the pointer is null, it's guarantee by Rust that <code>Option&lt;&amp;c_char&gt;</code> will be <code>None</code> for null pointer value.</p>\n\n<p>Your <code>get_number()</code> and <code>get_text()</code> use <code>Box::from_raw(data as *mut SomeData)</code> for nothing, just use directly the pointer or transform it to reference.</p>\n\n<p>I'm unsure <code>void</code> pointer is necessary.</p>\n\n<blockquote>\n <p>Do I need to provide a free_string function? Is there a way to just return a pointer into the Rust string?</p>\n</blockquote>\n\n<p>yes of course you must use <a href=\"https://doc.rust-lang.org/std/ffi/struct.CString.html#method.from_raw\" rel=\"nofollow noreferrer\"><code>from_raw()</code></a></p>\n\n<p>Final code:</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>use std::ffi;\nuse std::os::raw::{c_char, c_void};\n\n#[derive(Debug)]\npub struct SomeData {\n text: String,\n number: usize,\n}\n\n#[no_mangle]\npub unsafe extern \"C\" fn make_some_data(text: Option&lt;*const c_char&gt;, number: usize) -&gt; *mut c_void {\n ffi::CStr::from_ptr(text.unwrap())\n .to_str()\n .map(|str| {\n Box::into_raw(Box::new(SomeData {\n text: str.to_string(),\n number,\n }))\n })\n .unwrap() as *mut c_void\n}\n\n#[no_mangle]\npub unsafe extern \"C\" fn get_text(data: Option&lt;&amp;c_void&gt;) -&gt; *mut c_char {\n let data = my_real_data(data);\n ffi::CString::new(data.text.clone()).unwrap().into_raw()\n}\n\n#[no_mangle]\npub unsafe extern \"C\" fn get_number(data: Option&lt;&amp;c_void&gt;) -&gt; usize {\n let data = my_real_data(data);\n data.number\n}\n\nunsafe fn my_real_data(data: Option&lt;&amp;c_void&gt;) -&gt; &amp;SomeData {\n &amp;*(data.unwrap() as *const std::ffi::c_void as *const SomeData)\n}\n\n#[no_mangle]\npub unsafe extern \"C\" fn drop_data(data: Option&lt;*mut c_void&gt;) {\n Box::from_raw(data.unwrap() as *mut SomeData);\n}\n\n#[no_mangle]\npub unsafe extern \"C\" fn drop_text(data: Option&lt;*mut c_char&gt;) {\n ffi::CString::from_raw(data.unwrap());\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T15:24:58.107", "Id": "433821", "Score": "0", "body": "Thankyou, very useful. I'm a little unclear about what you mean re Option. Are you suggesting the function parameter as `fn get_text(data: Option<*const c_void>)` instead of `fn get_text(data: *mut c_void)`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T20:42:43.290", "Id": "434011", "Score": "1", "body": "I think you mean `data: Option<&mut c_char>` instead of `Option<*mut c_char>` as the parameters to `drop_data` and `drop_text`? It compiles but crashes as you have it written there.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T01:19:15.777", "Id": "434032", "Score": "0", "body": "@MongusPong Please show the code that make it crash." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T19:07:20.497", "Id": "434137", "Score": "0", "body": "It was the code as you had written here. The data was being passed in as None and so the unwrap was panicking." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T15:00:02.507", "Id": "223754", "ParentId": "223725", "Score": "4" } } ]
{ "AcceptedAnswerId": "223754", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T09:28:48.493", "Id": "223725", "Score": "3", "Tags": [ "memory-management", "rust", "native-code" ], "Title": "Exposing a simple struct using Rust FFI" }
223725
<p>I've written a small script that automates the tasks I previously did manually for deploying onto our kubernetes clusters and I am quite happy with the results I have, but I do think that what my approach was (building a command and executing it at the end) could probably be improved.</p> <p>Especially the <code>fn_magic</code> part is something I dont know could be done better.</p> <pre class="lang-bsh prettyprint-override"><code>team="webdev" project="sick-project" registry="myfancyregistry" tagPrefix="$registry/$team/$project" namespace="webdev-dev" kubectl="kubectl -n=$namespace" declare -A NAME_TO_TAGS declare COMMANDBUILDER declare -A REPLACEMENTS # Colors :) RED='\033[0;31m' GREEN='\033[0;32m' BLUE='\033[0;34m' CYAN='\033[0;36m' YELLOW='\033[1;33m' NC='\033[0m' # No Color function setReplacements() { while IFS= read -r line do [ -z "$line" ] &amp;&amp; continue key=${line%%=*} value=${line#*=} REPLACEMENTS[$key]=$value done &lt; "${BASH_SOURCE%/*}/secrets" } function buildAndPush() { function fn_magic() { local dockerfile=$1 local name=$2 local context=$3 local tag=$(tar cf - --exclude='node_modules' $context | sha1sum | grep -o "\w*") NAME_TO_TAGS["$name"]="$tag" local output=$(docker images $tagPrefix/$project-$name:$tag | awk '{print $2}' | sed 1,1d) printf "SHA1 for ${CYAN}$name${NC} is ${YELLOW}$tag${NC}.\n" if [[ "$output" ]]; then printf "Skipping building ${CYAN}$name${NC} because image already exists locally.\n" COMMANDBUILDER="$COMMANDBUILDER &amp;&amp; printf \"Pushing ${CYAN}$name${NC}.\n\" &amp;&amp; docker push $tagPrefix/$project-$name:$tag" return fi COMMANDBUILDER="$COMMANDBUILDER &amp;&amp; printf \"Building ${CYAN}$name${NC}.\n\" &amp;&amp; docker build -f dockerfiles/$dockerfile.dockerfile -t $tagPrefix/$project-$name:$tag $context" COMMANDBUILDER="$COMMANDBUILDER &amp;&amp; printf \"Pushing ${CYAN}$name${NC}.\n\" &amp;&amp; docker push $tagPrefix/$project-$name:$tag" return } local calls=( "fn_magic ReactNginx frontend ./frontend" "fn_magic DockerfileNode backend ./backend" ) for call in "${calls[@]}"; do eval $call done } function deploy() { local deployName="$1" local tag="$2" local filter="" REPLACEMENTS[TAG]="$tag" for key in "${!REPLACEMENTS[@]}"; do local REPLACE=$(echo ${REPLACEMENTS[$key]} | sed -e 's/\\/\\\\/g; s/\//\\\//g; s/&amp;/\\\&amp;/g') filter="$filter | sed \"s/{{$key}}/$REPLACE/g\"" done COMMANDBUILDER="$COMMANDBUILDER &amp;&amp; cat "${BASH_SOURCE%/*}/$deployName.yaml" $filter | $kubectl apply -f -" } setReplacements buildAndPush for name in "${!NAME_TO_TAGS[@]}"; do deploy $name ${NAME_TO_TAGS[$name]} done COMMANDBUILDER="echo $COMMANDBUILDER" eval "$COMMANDBUILDER" </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T03:02:09.143", "Id": "433905", "Score": "0", "body": "So that we can clearly understand what this code is intended to accomplish, could you include some example inputs and results?" } ]
[ { "body": "<p>Some suggestions in rough order of decreasing importance:</p>\n\n<ul>\n<li><code>eval</code> is evil, and I'm pretty sure you can completely avoid it in your script. Other than a massive gain in sanity, all that <code>sed</code> stuff to escape strings is not going to be necessary if you instead just use plain shell.</li>\n<li>Naming is really important, and comments are a good way to detect things which should be renamed.</li>\n<li><code>set -o errexit -o nounset -o pipefail</code> would be very handy in this script. Just make sure you're aware of the <a href=\"https://mywiki.wooledge.org/BashFAQ/105\" rel=\"nofollow noreferrer\">caveats</a> (that page is needlessly snarky but has some useful bits, and that site is fantastic).</li>\n<li>A simple array is the best way to <a href=\"https://mywiki.wooledge.org/BashFAQ/050\" rel=\"nofollow noreferrer\">build a command</a>. I would thoroughly recommend <em>not</em> building complex commands using a shell script. Instead, run each command as soon as you have all the pieces. Bundling up commands to run isn't going to make things faster; in most cases it'll make things significantly slower by making >50% of the code about <em>building</em> the command rather than just running it.</li>\n<li>Nested functions aren't. There are no closures in Bash, so defining a function within another function just makes it harder to read.</li>\n<li>In Bash the convention is that uppercase names are reserved for <em><code>export</code>ed</em> variables.</li>\n<li>Single use variables can often be inlined without loss of clarity.</li>\n<li><p><code>printf</code> is meant to be used with format strings for readability. So</p>\n\n<pre><code>printf \"SHA1 for ${cyan}$name${end_format} is ${yellow}$tag${end_format}.\\n\"\n</code></pre>\n\n<p>would normally be written as</p>\n\n<pre><code>printf \"SHA1 for %s is %s.\\n\" \"${cyan}${name}${end_format}\" \"${yellow}${tag}${end_format}\"\n</code></pre></li>\n<li><p><code>local</code> is considered a <em>command</em> for exit code purposes, which means that <code>local foo=[variable or command substitution]</code> only gets the exit code of <code>local</code>, <em>not</em> of the variable or command substitution. So if you start using <code>nounset</code> and the like you should declare variables local <em>before</em> assigning them separately:</p>\n\n<pre><code>deploy() {\n local deploy_name tag\n deploy_name=\"$1\"\n tag=\"$2\"\n …\n}\n</code></pre></li>\n<li><a href=\"https://www.shellcheck.net/\" rel=\"nofollow noreferrer\"><code>shellcheck</code></a> can give you more tips.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T11:04:50.913", "Id": "433742", "Score": "0", "body": "Thanks for these suggestions. An array definitely makes more sense to build a command.\n\nHowever I dont quite understand the `local` part. All the other best practices make sense, especially shellcheck is really helpful but as far as I understood, `local` is used to have a variable not in the global scope or did I misunderstand that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T19:52:52.240", "Id": "433867", "Score": "1", "body": "I've added an example to clarify how to use `local`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T11:54:32.470", "Id": "433960", "Score": "0", "body": "Ahhh, wow that's really good to know. Thanks for the inconvenience in helping me out :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T19:26:45.160", "Id": "434007", "Score": "0", "body": "No worries, I wouldn't be doing this unless I got something out of it as well - code reading and review training, writing training, and the pleasure of helping. And it often forces me to rethink what I consider best practices and articulate *why* I think they are preferable to the alternatives." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T10:15:39.920", "Id": "223730", "ParentId": "223727", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T09:47:01.373", "Id": "223727", "Score": "3", "Tags": [ "bash", "shell", "docker" ], "Title": "Deployment Automatization for docker builds, kubernetes deploys and secret injection" }
223727
<ul> <li>Will be very grateful for thoughtful code review. </li> <li>I needed hash table (again) and I wrote one. Code here is <a href="https://gist.github.com/leok7v/e5a5acdf79cc222cbac007b309fd0e01" rel="noreferrer">here</a> or inline:</li> </ul> <pre class="lang-c prettyprint-override"><code> #ifndef HASHTABLE_DEFINITION // single file library cannot use pragma once #define HASHTABLE_DEFINITION // https://en.wikipedia.org/wiki/Header-only // https://github.com/nothings/single_file_libs /* License: "Unlicense" (public domain) see bottom of the file for details. This is brain dead 4 hours implementation of #153 of absolutely non-universal, simple, growing, lineral rehash, key and value retaining hashtable with open read/write access to table entries. What it is NOT: It is not performance champion by any means. It does not use cyptograhically strong hash function. It is not designed for usage convience. Goals: As simple as possible. As reliable as possible. Limitations: key, val cannot exceed 2GB-1 bytes in size (can use int64_t instead of int32_t to make it bigger). Number of entries in a table cannot exceed (2GB - sizeof(hashtable_t)) / sizeof(hashtable_entry_t). Even replacing int32_t by int64_t does NOT make array of entries index 64 bit on the platforms where "int" is 32-bit (most of 64 bits platforms at the time of coding). It will be capable of indexing 2G entries (with some luck in indexof) but not 2^63 entries unless some additional indexing effort is added. Usage example: #define HASHTABLE_IMPLEMENTATION #include "hashtable.h" hashtable_t* ht = hashtable_create(16); if (ht == null) { perror("hashtable_create() failed"); // error is in "errno" } else { hashtable_kv_t key = {}; hashtable_kv_t val = {}; key.data = "Hello World!"; key.bytes = (int32_t)strlen((char*)key.data); val.data = "Good bye cruel Universe..."; val.bytes = (int32_t)strlen((char*)val.data); int r = hashtable_put(ht, &amp;key, &amp;val); // Adding key value pair to hashtable makes ht owned copy of kv data. // Adding can grow hashtable and pointers to entries will migrate to new // addressed. Called must NOT hold pointers to entry over "hashtable_add" call. if (r != 0) { perror("hashtable_put() failed"); // error is in "r" and also in errno } else { hashtable_entry_t* e = hashtable_get(ht, key.data, key.bytes); assert(e != null); assert(e-&gt;key.bytes == key.bytes &amp;&amp; memcmp(e-&gt;key.data, key.data, key.bytes) == 0); assert(e-&gt;val.bytes == val.bytes &amp;&amp; memcmp(e-&gt;val.data, val.data, val.bytes) == 0); // The content of e-&gt;val can be read and written at this point. // It will be very bad idea to touch e-&gt;key or e-&gt;hash here. Treat "key" as being read-only. // Caller should not hold the pointer to the entry over hashtable_add/remove/dispose calls. // See note above and below. hashtable_remove(ht, key.data, key.bytes); // Removal frees the hashtable owned copy of key value pair data. e = hashtable_get(ht, key.data, key.bytes); assert(e == null); hashtable_dispose(ht); // Frees all the memory used by hashtable. } } Inspiration: (nostalgic, obsolete, esoteric and buggy... but still in use) https://www.gnu.org/software/libc/manual/html_node/Hash-Search-Function.html https://github.com/ARM-software/u-boot/blob/master/lib/hashtable.c with the comment in the source code: [Aho, Sethi, Ullman] Compilers: Principles, Techniques and Tools, ***1986*** [Knuth] The Art of Computer Programming, part 3 (6.4) Questions and comments: Leo.Kuznetsov@gmail.com */ #include &lt;stdint.h&gt; #ifdef __cplusplus extern "C" { #endif typedef struct hashtable_kv_s { void* data; int32_t bytes; } hashtable_kv_t; typedef struct hashtable_entry_s { hashtable_kv_t key; hashtable_kv_t val; uint32_t hash; } hashtable_entry_t; typedef struct hashtable_t { int32_t capacity; int32_t n; hashtable_entry_t* entries; // array[capacity] } hashtable_t; enum { HASHTABLE_INT32_MAX = (int32_t)-1U/2 == (int32_t)(-1U/2) ? (int32_t)-1U : (int32_t)(-1U/2), // INT_MAX HASHTABLE_MAX_CAPACITY = (HASHTABLE_INT32_MAX - sizeof(hashtable_t)) / sizeof(hashtable_entry_t) }; hashtable_t* hashtable_create(int capacity); // capacity [16..HASHTABLE_MAX_CAPACITY] hashtable_entry_t* hashtable_get(hashtable_t* ht, const void* key, int32_t bytes); int hashtable_put(hashtable_t* ht, const hashtable_kv_t* key, const hashtable_kv_t* val); void hashtable_remove(hashtable_t* ht, const void* key, int32_t bytes); void hashtable_dispose(hashtable_t* ht); #ifdef __cplusplus } // extern "C" #endif #endif // HASHTABLE_DEFINITION #ifdef HASHTABLE_IMPLEMENTATION #include &lt;stdlib.h&gt; #include &lt;stdbool.h&gt; #include &lt;string.h&gt; #include &lt;errno.h&gt; #include &lt;assert.h&gt; #define byte uint8_t #define null ((void*)0) #define memequ(a, b, n) (memcmp((a), (b), (n)) == 0) #define hashtable_mem_alloc malloc #define hashtable_mem_free free static const byte HASHTABLE_REMOVED_KEY; // unique address designating removed key for linear rehash static inline void hashtable_mem_free_not_removed(void* data) { // since &amp;HASHTABLE_REMOVED_KEY is unique no harm comparing any other address with it if (data != &amp;HASHTABLE_REMOVED_KEY) { hashtable_mem_free(data); } } static inline void hashtable_kv_free(hashtable_kv_t* kv) { if (kv != null) { // unnecessary := null and := 0 assignments will be removed by optimizations hashtable_mem_free_not_removed(kv-&gt;data); kv-&gt;data = null; kv-&gt;bytes = 0; } } static uint32_t hashtable_hash(const byte* key, int bytes); static int hashtable_kv_dup(hashtable_kv_t* d, const hashtable_kv_t* s); static int hashtable_grow(hashtable_t* ht); static int hashtable_indexof(hashtable_t* ht, const hashtable_entry_t* e) { return (int)(e - ht-&gt;entries); } hashtable_t* hashtable_create(int capacity) { // capacity [16..HASHTABLE_MAX_CAPACITY] int r = 0; hashtable_t* ht = null; assert(16 &lt;= capacity &amp;&amp; capacity &lt; HASHTABLE_MAX_CAPACITY); if (16 &lt;= capacity &amp;&amp; capacity &lt; HASHTABLE_MAX_CAPACITY) { ht = (hashtable_t*)hashtable_mem_alloc(sizeof(hashtable_t)); if (ht == null) { r = errno; } else { memset(ht, 0, sizeof(hashtable_t)); int32_t bytes = capacity * sizeof(hashtable_entry_t); ht-&gt;entries = (hashtable_entry_t*)hashtable_mem_alloc(bytes); if (ht-&gt;entries == null) { r = errno; // save to protect against hashtable_mem_free() setting "errno" hashtable_mem_free(ht); ht = null; } else { ht-&gt;capacity = capacity; memset(ht-&gt;entries, 0, bytes); } } } else { r = EINVAL; } if (r != 0) { errno = r; } return ht; } void hashtable_free_entries(hashtable_t* ht) { for (int i = 0; i &lt; ht-&gt;capacity; i++) { hashtable_kv_free(&amp;ht-&gt;entries[i].key); hashtable_kv_free(&amp;ht-&gt;entries[i].val); } } void hashtable_dispose(hashtable_t* ht) { hashtable_free_entries(ht); hashtable_mem_free(ht-&gt;entries); hashtable_mem_free(ht); } static hashtable_entry_t* hashtable_find(hashtable_t* ht, uint32_t hash, const void* key, int32_t bytes) { // Last time I've checked idiv r32:r32 was pretty expensive on most ARM, Intel and AMD // processors, thus loop below uses increment and compare instead of extra "%" operation. // http://uops.info/table.html int ix = (int)(hash % ht-&gt;capacity); // arrays are indexed by "int" in C const int a = ix; // `again` full circle index value after visiting all entries do { hashtable_entry_t* e = &amp;ht-&gt;entries[ix]; if (e-&gt;key.data == null) { break; } if (hash == e-&gt;hash &amp;&amp; e-&gt;key.bytes == bytes &amp;&amp; memequ(e-&gt;key.data, key, bytes)) { return e; } ix++; if (ix == ht-&gt;capacity) { ix = 0; } } while (ix != a); return null; } hashtable_entry_t* hashtable_get(hashtable_t* ht, const void* key, int32_t bytes) { return hashtable_find(ht, hashtable_hash(key, bytes), key, bytes); } int hashtable_put(hashtable_t* ht, const hashtable_kv_t* key, const hashtable_kv_t* val) { int r = 0; assert(key-&gt;data != null &amp;&amp; 1 &lt;= key-&gt;bytes &amp;&amp; key-&gt;bytes &lt; HASHTABLE_INT32_MAX); if (key-&gt;data != null &amp;&amp; 1 &lt;= key-&gt;bytes &amp;&amp; key-&gt;bytes &lt; HASHTABLE_INT32_MAX) { uint32_t hash = hashtable_hash(key-&gt;data, key-&gt;bytes); hashtable_entry_t* e = hashtable_find(ht, hash, key-&gt;data, key-&gt;bytes); if (e != null) { r = hashtable_kv_dup(&amp;e-&gt;val, val); } else { int ix = (int)(hash % ht-&gt;capacity); const int a = ix; while (r == 0) { e = &amp;ht-&gt;entries[ix]; bool removed = e-&gt;key.data == &amp;HASHTABLE_REMOVED_KEY; if (e-&gt;key.data == null || removed) { r = hashtable_kv_dup(&amp;e-&gt;key, key); if (r == 0) { r = hashtable_kv_dup(&amp;e-&gt;val, val); if (r != 0) { // restore key to retained value hashtable_kv_free(&amp;e-&gt;val); e-&gt;key.data = removed ? (void*)&amp;HASHTABLE_REMOVED_KEY : null; } } if (r == 0) { e-&gt;hash = hash; ht-&gt;n++; if (ht-&gt;n &gt; ht-&gt;capacity * 3 / 4) { r = hashtable_grow(ht); } } break; } ix++; if (ix == ht-&gt;capacity) { ix = 0; } // the only way for ix == a is the table previous failure to grow was ignored if (ix == a) { r = ENOMEM; break; } // hit initial value of 'h' again... } } } else { r = EINVAL; } return r; } void hashtable_remove(hashtable_t* ht, const void* key, int32_t bytes) { hashtable_entry_t* e = hashtable_get(ht, key, bytes); if (e != null) { assert(e-&gt;key.data != (void*)&amp;HASHTABLE_REMOVED_KEY); hashtable_kv_free(&amp;e-&gt;key); hashtable_kv_free(&amp;e-&gt;val); int next = hashtable_indexof(ht, e) + 1; if (next == ht-&gt;capacity) { next = 0; } e-&gt;key.data = ht-&gt;entries[next].key.data == null ? null : (void*)&amp;HASHTABLE_REMOVED_KEY; ht-&gt;n--; } } static int hashtable_grow(hashtable_t* ht) { int r = 0; if (ht-&gt;capacity &lt; HASHTABLE_MAX_CAPACITY * 2 / 3) { int capacity = ht-&gt;capacity * 3 / 2; int32_t bytes = capacity * sizeof(hashtable_entry_t); hashtable_entry_t* entries = (hashtable_entry_t*)hashtable_mem_alloc(bytes); if (entries == null) { r = errno; } else { memset(entries, 0, bytes); for (int i = 0; i &lt; ht-&gt;capacity; i++) { hashtable_entry_t* e = &amp;ht-&gt;entries[i]; if (e-&gt;key.data != null &amp;&amp; e-&gt;key.data != &amp;HASHTABLE_REMOVED_KEY) { int ix = (int)(e-&gt;hash % capacity); for (;;) { if (entries[ix].key.data == null) { entries[ix] = *e; break; } ix++; if (ix == capacity) { ix = 0; } } } } hashtable_mem_free(ht-&gt;entries); ht-&gt;entries = entries; ht-&gt;capacity = capacity; } } else { r = E2BIG; } if (r != 0) { errno = r; } return r; } static int hashtable_kv_dup(hashtable_kv_t* d, const hashtable_kv_t* s) { int r = 0; // similar to strdup() but for a (data,bytes) pair if (d-&gt;bytes == s-&gt;bytes) { memcpy(d-&gt;data, s-&gt;data, s-&gt;bytes); } else { void* dup = hashtable_mem_alloc(s-&gt;bytes); if (dup == null) { r = errno; } else { hashtable_mem_free_not_removed(d-&gt;data); d-&gt;data = dup; d-&gt;bytes = s-&gt;bytes; memcpy(d-&gt;data, s-&gt;data, s-&gt;bytes); } } return r; } static uint32_t hashtable_hash(const byte* data, int bytes) { // http://www.azillionmonkeys.com/qed/hash.html #define get16bits(a) (*((const uint16_t*)(a))) uint32_t hash = bytes; uint32_t tmp; if (bytes &lt;= 0 || data == null) { return 0; } int32_t reminder = bytes &amp; 3; bytes &gt;&gt;= 2; while (bytes &gt; 0) { hash += get16bits(data); tmp = (get16bits(data + 2) &lt;&lt; 11) ^ hash; hash = (hash &lt;&lt; 16) ^ tmp; data += 2 * sizeof(uint16_t); hash += hash &gt;&gt; 11; bytes--; } switch (reminder) { /* Handle end cases */ case 3: hash += get16bits(data); hash ^= hash &lt;&lt; 16; hash ^= ((int8_t)data[sizeof(uint16_t)]) &lt;&lt; 18; hash += hash &gt;&gt; 11; break; case 2: hash += get16bits(data); hash ^= hash &lt;&lt; 11; hash += hash &gt;&gt; 17; break; case 1: hash += (int8_t)data[0]; hash ^= hash &lt;&lt; 10; hash += hash &gt;&gt; 1; break; case 0: break; } /* Force "avalanching" of final 127 bits */ hash ^= hash &lt;&lt; 3; hash += hash &gt;&gt; 5; hash ^= hash &lt;&lt; 4; hash += hash &gt;&gt; 17; hash ^= hash &lt;&lt; 25; hash += hash &gt;&gt; 6; return hash; } /* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to &lt;http://unlicense.org/&gt; */ #endif </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T23:44:17.967", "Id": "433890", "Score": "3", "body": "URL shorteners are deprecated on Stack Exchange. To those people who don't want to risk: the link OP posted is https://gist.github.com/leok7v/e5a5acdf79cc222cbac007b309fd0e01, and does not contain malware. To OP: consider replace the URL shortener with the actual link, so everyone can securely visit it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T01:37:44.517", "Id": "433900", "Score": "0", "body": "@L.F. It's better to just suggest an edit for things like this. ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T01:41:23.270", "Id": "433901", "Score": "0", "body": "@jpmc26 OK, I guess I'll do that in the future :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T01:52:14.573", "Id": "433903", "Score": "0", "body": "Is there a reason you don't want to use an existing library? I'm not a C expert, but [uthash](https://troydhanson.github.io/uthash/) appears to be popular and there are others." } ]
[ { "body": "<p>It's been a long time since I've coded in C, so bear with me.</p>\n\n<h2>#define</h2>\n\n<p>Your implementation's <code>#define</code> statements puzzle me. <code>#define</code> is a directive, essentially a macro, best used to define <em>constants</em>. With that said:</p>\n\n<ul>\n<li>You should use <code>typedef</code> for type definitions. <code>#define</code> will only be respected by a preprocessor as a copy/paste directive, and nothing more. <code>typedef</code> will actually name a new type.</li>\n</ul>\n\n<p>Example:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>// using #define\n#define PTR char*\n\nPTR a, b, c; // creates char *a, char b, char c\n</code></pre>\n\n<pre class=\"lang-c prettyprint-override\"><code>// using typedef\ntypedef char* PTR;\n\nPTR a, b, c; // creates char *a, char *b, char *c\n</code></pre>\n\n<ul>\n<li>Why not use <code>NULL</code> for null pointer?</li>\n<li>Why redefine malloc/free? You don't lose any clarity by leaving them as-is</li>\n<li><code>memequ(a, b, n)</code> should just be a function, regardless of how simple it is</li>\n</ul>\n\n<h2>assert</h2>\n\n<p>The <code>assert</code> statement below already necessitates the following condition. Its corresponding <code>else</code> statement will never be executed.</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>assert(16 &lt;= capacity &amp;&amp; capacity &lt; HASHTABLE_MAX_CAPACITY);\nif (16 &lt;= capacity &amp;&amp; capacity &lt; HASHTABLE_MAX_CAPACITY) {\n</code></pre>\n\n<p>And while we're looking at those lines, why is 16 hardcoded here? Wouldn't it make sense to <code>#define</code> that as a minimum capacity?</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#define HASHTABLE_MIN_CAPACITY 16\n</code></pre>\n\n<h2>enum</h2>\n\n<p>On that same note, the <code>enum</code> in HASHTABLE_DEFINITION doesn't make sense. Enums are generally used to define constants <em>of the same enumeration</em>.</p>\n\n<p>Example:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>enum State{SUCCESS, FAILED, INTERRUPTED}\n</code></pre>\n\n<p>I would recommend making them <code>const</code> variables instead.</p>\n\n<p>I haven't read through any of the hashtable logic itself yet, but I felt the rest here was important enough already.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T15:23:20.617", "Id": "433820", "Score": "0", "body": "`assert` shouldn't be used lightly. I don't want a program to break unexpectedly, but instead solve the problems and report them if necessary. `assert` should be used in extreme cases. Read this thread in LKML: http://lkml.iu.edu/hypermail/linux/kernel/1610.0/00878.html" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T15:32:12.893", "Id": "433824", "Score": "0", "body": "@Cacahuete Frito Makes sense! I was specifically referring to how his `assert` statement did not play well with the subsequent conditional logic, but I can see how not using `assert` to begin with would be preferable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T15:34:04.353", "Id": "433826", "Score": "0", "body": "Oh, sorry. I thought you were changing an `if` to an `assert`. I didn't see that the OP used `assert` :-)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T14:36:41.427", "Id": "223748", "ParentId": "223728", "Score": "3" } }, { "body": "<h2><code>typedef</code> <code>_t</code></h2>\n\n<p><a href=\"https://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html\" rel=\"nofollow noreferrer\">POSIX</a> reserves identifiers ending in <code>_t</code>. You should maybe use <code>_s</code> also for the typedef:</p>\n\n<pre><code>struct Foobar {\n void *foo;\n int32_t bar;\n};\ntypedef struct Foobar foobar_s;\n</code></pre>\n\n<p><a href=\"https://www.kernel.org/doc/html/v4.10/process/coding-style.html#typedefs\" rel=\"nofollow noreferrer\">Or not use <code>typedef</code> at all</a>.</p>\n\n<hr>\n\n<h2><code>#define</code> <code>_MAX</code></h2>\n\n<p><a href=\"https://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html\" rel=\"nofollow noreferrer\">POSIX</a> reserves identifiers ending in <code>_MAX</code> or <code>_MIN</code>.</p>\n\n<p>For your macros (or <code>const</code>s, but don't use <code>enum</code> for that) that design maximums or minimums, I recommend using prefixes:</p>\n\n<pre><code>#define MAX_FOO (5)\n</code></pre>\n\n<hr>\n\n<h2>C / C++</h2>\n\n<p>C and C++ are very different languages. Working in the common subset is very difficult, and not always optimum. I recommend writing the program in C, and then writing specialized C++ headers (<code>.hpp</code>) which link to your C code.</p>\n\n<hr>\n\n<h2>ODR</h2>\n\n<p>C17:</p>\n\n<blockquote>\n <p>J.5.11 Multiple external definitions</p>\n \n <p>1 There may be more than one external definition for the identifier of\n an object, with or without the explicit use of the keyword extern ; if\n the definitions disagree, or more than one is initialized, the\n behavior is undefined (6.9.2).</p>\n</blockquote>\n\n<p>Don't define <code>extern</code> functions (non-<code>static</code> functions) in header files. If you include this header from multiple source files, you will have defined your functions more than once, and the linker will (or at least should) complain.</p>\n\n<hr>\n\n<h2><code>static inline</code> vs C99 <code>inline</code></h2>\n\n<p><code>static inline</code> might look as a magic macro: One uses <code>static inline</code> when one wants a function to always be inlined. It has extra safety that a macro doesn't, and all the benefits (in theory).</p>\n\n<p>Problem: <code>inline</code> is only a hint to the compiler; it can decide not to inline a function, and then the bloating starts: being a <code>static</code> function, every file will have its own copy of the same function.</p>\n\n<p>Secondary problem (unlikely to be important for most programs): Two pointers to the same <code>static inline</code> function acquired from different files are unequal even when the function contents are the same.</p>\n\n<p>Solution: C99 <code>inline</code>. The scheme for using C99 <code>inline</code> is the following:</p>\n\n<p><code>file.h</code>:</p>\n\n<pre><code>inline\nint foo(int a);\n\ninline\nint foo(int a)\n{\n /* definition */\n}\n</code></pre>\n\n<p><code>file.c</code>:</p>\n\n<pre><code>extern\nint foo(int a);\n</code></pre>\n\n<p>If you want your function to always be inlined you can use compiler specific extensions. Note: Use <code>always_inline</code> only for very short functions (1 - 3 lines), or when you are 100% sure that most of the code will go away at compile time. I will add an example for GCC, but if you want portability you will have to create a macro that adapts to all the compilers you want to support:</p>\n\n<p><code>file.h</code>:</p>\n\n<pre><code>__attribute__((always_inline))\ninline\nint foo(int a);\n\ninline\nint foo(int a)\n{\n /* definition */\n}\n</code></pre>\n\n<p><code>file.c</code>:</p>\n\n<pre><code>extern\nint foo(int a);\n</code></pre>\n\n<p>Source: <a href=\"http://www.greenend.org.uk/rjk/tech/inline.html\" rel=\"nofollow noreferrer\">http://www.greenend.org.uk/rjk/tech/inline.html</a></p>\n\n<hr>\n\n<h2>magic numbers</h2>\n\n<p><a href=\"https://stackoverflow.com/q/47882/6872717\">What is a magic number, and why is it bad?</a></p>\n\n<p>Don't use any numbers different than 0, 1, or 2 in your code. The only place where numbers deserve to go is in constant macros like this:</p>\n\n<pre><code>#define FOO (5)\n</code></pre>\n\n<hr>\n\n<h2>Don't cast the result of <code>malloc</code></h2>\n\n<p><a href=\"https://stackoverflow.com/a/605858/6872717\">Do I cast the result of malloc?</a></p>\n\n<p>NEVER, in my opinion. (There's a debate in that link. There's people that argues that you should always cast it. Form your own opinion based on what you read there).</p>\n\n<hr>\n\n<h2>Safe usage of malloc</h2>\n\n<p>Malloc is easily misused. Problems that can arise using malloc are the following:</p>\n\n<ul>\n<li><p>casting the result: As said above, never do this.</p></li>\n<li><p><code>sizeof(type)</code> vs <code>sizeof(*foo)</code>:</p></li>\n</ul>\n\n<p><code>foo = malloc(sizeof(*foo) * nmemb);</code> is better because if you ever change the type of <code>foo</code>, this call will still be valid, while if not, you would have to change every line where malloc is called with foo. If you forget any of those lines, good luck.</p>\n\n<ul>\n<li>overflow:</li>\n</ul>\n\n<p>If <code>(sizeof(*foo) * nmemb) &gt; SIZE_MAX</code>, it will silently wrap around, and allocate a very small amount of memory, and you will most likely end up accessing to memory that you shouldn't.</p>\n\n<p>Solution:</p>\n\n<p><a href=\"https://codereview.stackexchange.com/a/223175/200418\">Use this enclosure around <code>malloc</code></a></p>\n\n<hr>\n\n<h2><code>errno</code></h2>\n\n<p><code>free()</code> doesn't set <code>errno</code> so you don't need to save the value of <code>errno</code> in a temp variable .</p>\n\n<p>Source: <a href=\"http://www.man7.org/linux/man-pages/man3/free.3.html\" rel=\"nofollow noreferrer\"><code>man 3 free</code></a></p>\n\n<hr>\n\n<h2>re<code>#define</code> the name of a function</h2>\n\n<p>Don't do this. It is very weird and unexpected. Unless you have a very good reason use an <code>always_inline</code> function:</p>\n\n<pre><code>inline\nvoid hashtable_mem_free(void *p)\n __attribute__((always_inline));\n\n\ninline\nvoid hashtable_mem_free(void *p)\n{\n\n free(p);\n}\n</code></pre>\n\n<hr>\n\n<h2>Right margin at 80 characters</h2>\n\n<p>This is a rule in most coding standards for good reasons.</p>\n\n<p>This (copied from your code) is unreadable:</p>\n\n<pre><code> if (hash == e-&gt;hash &amp;&amp; e-&gt;key.bytes == bytes &amp;&amp; memequ(e-&gt;key.data, key, bytes)) { return e; }\n</code></pre>\n\n<p>And the most important thing is that you are hiding a <code>return</code> statement where most of the screens will not show (unless you scroll).</p>\n\n<p>Solution:</p>\n\n<pre><code> if ((hash == e-&gt;hash) &amp;&amp; (e-&gt;key.bytes == bytes) &amp;&amp;\n memequ(e-&gt;key.data, key, bytes)) {\n return e;\n }\n</code></pre>\n\n<hr>\n\n<h2><code>static</code> in headers</h2>\n\n<p>Don't use <code>static</code> in headers. The reason is basically the same as <code>static inline</code>; given that <code>inline</code> is a hint, they are literally the same (for functions).</p>\n\n<p>In variables, it's even more dangerous, because modifying a variable from one file won't affect the same (actually not the same) variable in another file.</p>\n\n<p>A good compiler should warn about this.</p>\n\n<hr>\n\n<h2><code>assert</code></h2>\n\n<p><code>static_assert</code> (> C11) is a very good thing. <code>assert</code> isn't that much.</p>\n\n<p>A user of a program expects the program to handle errors silently and maybe warn the user when some error is important; but the user expects a program to never break, so a program should only break when there is absolutely no other possibility.</p>\n\n<p>Remember <a href=\"https://en.wikipedia.org/wiki/Blue_Screen_of_Death\" rel=\"nofollow noreferrer\">BSOD</a>? Like it? I hope not.</p>\n\n<p>A good reading about it: <a href=\"http://lkml.iu.edu/hypermail/linux/kernel/1610.0/00878.html\" rel=\"nofollow noreferrer\">LKML thread</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T07:18:35.373", "Id": "433917", "Score": "1", "body": "you should add that people strongly disagree about whether to cast the result of malloc. you may say never, but I would say always" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T07:56:41.613", "Id": "433924", "Score": "0", "body": "@sudorm-rfslash agree to disagree :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T08:04:56.743", "Id": "433926", "Score": "1", "body": "That's a really weird argument against asserts. Personally I prefer programs to crash instead of silently corrupting my data, opening up security exploits or simply doing the wrong thing. Kernel mode is a completely different beast to user mode - are you also going to argue against limited recursion and the use of floating point because both of those things are rarely used in Kernel code? (and even in the Kernel there are very good arguments to simply crash and burn if some important state is corrupted - there's just a higher threshold for that)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T08:11:28.797", "Id": "433928", "Score": "0", "body": "@Voo Those are cases where assert would be OK, but for example: If a program needs to be sure that a data is correct to do an operation: you can assert it and save the data (and abort otherwise), or you can save the data if it is correct, and just not save it if it's not and tell the user why and maybe return to a main menu or something like that. Maybe it's the \"absolutely no other possibility\" threshold that is a bit lower on user programs, but I think the reason is very valid" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T15:07:50.637", "Id": "223755", "ParentId": "223728", "Score": "10" } }, { "body": "<p>The comment</p>\n\n<pre><code> // It will be very bad idea to touch e-&gt;key or e-&gt;hash here. Treat \"key\" as being read-only.\n // Caller should not hold the pointer to the entry over hashtable_add/remove/dispose calls.\n</code></pre>\n\n<p>suggests that <code>hashtable_get</code> should return the value, rather than the entry pointer. The caller already knows the key, there is no point returning it.</p>\n\n<p>In fact, I don't see a legitimate reason for a client to know the entry pointer at all. Consider <code>hashtable_get_and_remove()</code> and <code>hashtable_put_or_replace()</code> interfaces instead.</p>\n\n<hr>\n\n<p>I am not sure I like the idea of partitioning the <code>hashtable.h</code> file by <code>HASHTABLE_DEFINITION</code> and <code>HASHTABLE_IMPLEMENTATION</code> macros. A change in the lower portion of the file will still cause recompilation of the client code, even though it is absolutely irrelevant. Besides, with this organization the client must pay a special attention to <code>#define HASHTABLE_IMPLEMENTATION</code> exactly once ad only once. Consider moving the implementation part into a separate <code>hashtable_impl.c</code></p>\n\n<hr>\n\n<p>Do not throw away what has been computed. <code>find</code> returns <code>null</code> even though it has found an insertion point. Should it return the insertion point instead, you could use this information in <code>put</code>.</p>\n\n<hr>\n\n<p>It is usually a good idea to let the client pick another hash function, which would suite their dataset better. A cost of an indirect function call would be offset by smaller number of collisions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T17:11:29.990", "Id": "223762", "ParentId": "223728", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T09:54:49.417", "Id": "223728", "Score": "10", "Tags": [ "c", "hash-map" ], "Title": "Yet another hash table in C" }
223728
<p>I wrote a blocking serial port library, <a href="https://codereview.stackexchange.com/questions/221870/blocking-serial-port-c-library">Blocking serial port C library</a>, but prefer non-blocking so wrote this library where user can specify callbacks. So it is event driven.</p> <p>The code assumes C99 or better. How could this be improved?</p> <p>The example is fairly custom to working in the UK with the British Telecom Caller ID system: <a href="https://www.btplc.com/SINet/sins/pdf/242v2p5.pdf" rel="nofollow noreferrer">https://www.btplc.com/SINet/sins/pdf/242v2p5.pdf</a></p> <p>serial_port.h:</p> <pre><code>/* Serial port library for unix platform. Uses unix select method and callbacks are used to notify events. Events supported are connection and reads. User must provide connected and/or read callback function(s) to be notified of these events. Author: Angus Comber */ #ifndef SERIAL_PORT_H_ #define SERIAL_PORT_H_ #define READ_BUFFERSIZE 100 #include &lt;stdlib.h&gt; // size_t /* opaque serial port object */ struct serial_port; typedef struct serial_port serial_port_t; // user defined callbacks typedef void (*connect_callback)(serial_port_t* port, void* userdata); typedef void (*read_callback)(serial_port_t* port, char* buffer, int* length, void* userdata); /* port_start opens portname at baudrate. Returns immediately with -1 error code on failure to open port. Interrogate errno for more information. Alternatively, if unable to allocate memory for the port object returns -2 error. if the port setup proceeds successfully, port_start blocks until the process is closed. Arguments: - portname - port identifier for modem - baudrate - speed for connection - connectcb - user defined callback on a successful connection being established - readcb - user defined callback on reading data on port - userdata - user defined data to pass to callback functions (can be NULL) */ int port_start(const char* portname, const int baudrate, connect_callback connectcb, read_callback readcb, void* userdata); /* returns characters written or -1 on error */ int port_write(serial_port_t* port, const char* data, size_t length); /* returns characters read or -1 on error */ int port_read(serial_port_t* port, char* buffer, int buffer_size); /* close port and free allocated resources */ int port_close(serial_port_t* port); #endif // SERIAL_PORT_H_ </code></pre> <p>serial_port.c:</p> <pre><code>/* serial port class for unix platform using callbacks */ #include "serial_port.h" #include &lt;unistd.h&gt; // posix api #include &lt;fcntl.h&gt; // file control operations #include &lt;termios.h&gt; // terminal struct serial_port { int fd; int baudrate; struct termios restore_tty; struct termios current_tty; connect_callback connectcb; read_callback readcb; void* userdata; }; static int set_speed(struct termios tty, int speed) { speed_t sp; switch(speed) { case 1200: sp = B1200; break; case 1800: sp = B1800; break; case 2400: sp = B2400; break; case 4800: sp = B4800; break; case 9600: sp = B9600; break; case 19200: sp = B19200; break; case 38400: sp = B38400; break; case 57600: sp = B57600; break; case 115200: sp = B115200; break; default: return -1; // unsupported } int baudset = cfsetospeed(&amp;tty, sp); baudset = cfsetispeed(&amp;tty, sp); return baudset; } static int get_term(int fd, struct termios* ptty) { /* Upon successful completion, 0 shall be returned. Otherwise, -1 shall be returned and errno set to indicate the error. */ return tcgetattr(fd, ptty); } /* configure tty */ static int set_terminal(int fd, struct termios* ptty) { ptty-&gt;c_cflag |= (CLOCAL | CREAD); /* ignore modem controls */ ptty-&gt;c_cflag &amp;= ~CSIZE; ptty-&gt;c_cflag |= CS8; /* 8-bit characters */ ptty-&gt;c_cflag &amp;= ~PARENB; /* no parity bit */ ptty-&gt;c_cflag &amp;= ~CSTOPB; /* only need 1 stop bit */ ptty-&gt;c_cflag &amp;= ~CRTSCTS; /* no hardware flowcontrol */ /* setup for non-canonical mode */ ptty-&gt;c_iflag &amp;= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON); ptty-&gt;c_lflag &amp;= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN); ptty-&gt;c_oflag &amp;= ~OPOST; /* fetch bytes as they become available */ ptty-&gt;c_cc[VMIN] = 1; ptty-&gt;c_cc[VTIME] = 1; if (tcsetattr(fd, TCSANOW, ptty) != 0) { // Error from tcsetattr- use strerror(errno) return -1; } return 0; } int port_start(const char* portname, const int baudrate, connect_callback connectcb, read_callback readcb, void* userdata) { // open in non-blocking mode and notify as reads and write complete via callbacks int fd = open(portname, O_RDWR | O_NOCTTY | O_NONBLOCK); if (fd == -1) { return -1; } serial_port_t* port = malloc(sizeof(serial_port_t)); if (port) { port-&gt;fd = fd; port-&gt;baudrate = baudrate; port-&gt;connectcb = connectcb; port-&gt;readcb = readcb; port-&gt;userdata = userdata; // cache prior terminal settings for restore later if(get_term(port-&gt;fd, &amp;port-&gt;current_tty) == 0) { // cache previous tty settings port-&gt;restore_tty = port-&gt;current_tty; } else { return -1; } // set port speed if(set_speed(port-&gt;current_tty, port-&gt;baudrate) == -1) { // error setting tty speed return -1; } // set terminal attribs if(set_terminal(port-&gt;fd, &amp;port-&gt;current_tty) &lt; 0) { // error configuring port return -1; } } else { return -2; } if(port-&gt;connectcb) { connectcb(port, userdata); } fd_set readset; // keep looping forever while(1 == 1) { FD_ZERO(&amp;readset); /* clear the set */ FD_SET(fd, &amp;readset); /* add our file descriptor to the set */ // wait for data to be read (infinite timeout) int rv = select(fd + 1, &amp;readset, NULL, NULL, NULL); if(rv &gt; 0) { // we have activity // only working with one fd so no need for for loop for (int i = fd; i &lt; fd + 1; ++i) { if(FD_ISSET(fd, &amp;readset)) { if(readcb) { char data[READ_BUFFERSIZE]; int len = READ_BUFFERSIZE; int bytes_read = port_read(port, data, len); readcb(port, data, &amp;bytes_read, userdata); } } } // if an error occurred, exit } else { return -1; } } // while } int port_write(serial_port_t* port, const char* data, size_t length) { return write(port-&gt;fd, data, length); } int port_read(serial_port_t* port, char* buffer, int buffer_size) { return read(port-&gt;fd, buffer, buffer_size); } int port_close(serial_port_t* port) { if (tcsetattr(port-&gt;fd, TCSANOW, &amp;port-&gt;restore_tty) &lt; 0) { // error restoring attributes } int result = close(port-&gt;fd); free(port); return result; } </code></pre> <p>main.c:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; // strerror #include &lt;errno.h&gt; // errno #include &lt;ctype.h&gt; // isprint #include "serial_port.h" enum stage { RESET, SETCOUNTRY, SETCALLERID, WAITFORCALL }; /* getline_string function args: buffer - buffer to fill with line size - ptr to size of line or -1 if no line extracted source - source bytes end - end of byte stream returns remaining string stream or NULL if at end of string stream */ static const char* getline_stringstream(char* line, int* size, const char* source, const char* end) { const char* s = source; char* t = line; *size = 0; // eat any prepended newlines while (s != end &amp;&amp; *s &amp;&amp; (*s == '\r' || *s == '\n')) s++; while (s != end &amp;&amp; *s &amp;&amp; *s != '\r' &amp;&amp; *s != '\n') { *t++ = *s++; (*size)++; } *t = '\0'; // null terminate string return *size &gt; 0 ? s : NULL; } /* on successful connection we print report header */ void connected(serial_port_t* port, void* userdata) { printf("%-6s%-6s%s\n", "Date", "Time", "Caller ID"); port_write(port, "AT\r\n", 4); } /* use simple state machine to setup modem and when finished, output caller ID */ void readdata(serial_port_t* port, char* buffer, int* length, void* userdata) { enum stage* step = userdata; switch(*step) { case RESET: port_write(port, "ATZ\r\n", 5); // reset modem *step = SETCOUNTRY; break; case SETCOUNTRY: port_write(port, "AT+GCI=B4\r\n", 11); // set country to UK *step = SETCALLERID; break; case SETCALLERID: port_write(port, "AT+VCID=1\r\n", 11); // enables formatted caller report *step = WAITFORCALL; break; case WAITFORCALL: { //parse call data in to caller id etc static char callerid[50] = {0}; static char caller_date[20] = {0}; static char caller_time[20] = {0}; int size; char line[100]; // we assume no lines &gt; 100 chars const char* rest = buffer; char* end = buffer + *length; while ((rest = getline_stringstream(line, &amp;size, rest, end)) != NULL) { if(strncmp(line, "NMBR", 4) == 0 &amp;&amp; strlen(line) &gt; 7) { strcpy(callerid, &amp;line[7]); } if(strncmp(line, "DATE", 4) == 0 &amp;&amp; strlen(line) &gt;= 11) { sprintf(caller_date, "%c%c/%c%c", line[9], line[10], line[7], line[8]); } if(strncmp(line, "TIME", 4) == 0 &amp;&amp; strlen(line) &gt;= 11) { sprintf(caller_time, "%c%c:%c%c", line[7], line[8], line[9], line[10]); } } if(strlen(callerid) &gt; 0 &amp;&amp; strlen(caller_date) &gt; 0 &amp;&amp; strlen(caller_time) &gt; 0) { printf("%-6s%-6s%s\n", caller_date, caller_time, callerid); callerid[0] = caller_date[0] = caller_time[0] = '\0'; } } break; default: fprintf(stderr, "something unexpected happened, aborting...\n"); fflush(stdout); exit(1); // something bad happened - exiting } } // test serial library with modem int main(int argc, char* argv[]) { if(argc != 3) { printf("Usage: %s &lt;port name&gt; &lt;baudrate&gt;\n", argv[0]); exit(EXIT_FAILURE); } const char* portname = argv[1]; const int baudrate = atoi(argv[2]); enum stage step = RESET; // program will block here forever if(port_start(portname, baudrate, connected, readdata, &amp;step) == -1) { fprintf(stderr, "An error occurred starting serial port connection on %s, error: %s\n", portname, strerror(errno)); } } </code></pre> <p>Example output below.</p> <pre><code>acomber@mail:~/Documents/projects/modem/serial/serial_port_select_lib$ sudo ./prog /dev/ttyACM0 9600 Date Time Caller ID 08/07 10:43 07766112233 08/07 10:47 P 08/07 10:48 07766123123 </code></pre> <p>In the output below, the 2nd call at 10:47, had caller id hidden and so the character P is the string to indicate PRIVATE.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T16:13:22.653", "Id": "433835", "Score": "0", "body": "I'm not completely sure that your code does not overrun any buffer. Are you sure about that? I would need to have a deeper look at it, and I don't have enough time. I recommend using `strnlen`, `strscpy` and those safe functions (some of them, such as `strscpy`, are not in the standard library)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T17:27:31.090", "Id": "433854", "Score": "0", "body": "Btw, why do you need `root` to run the program? A little bit unsafe, isn't it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T07:54:02.830", "Id": "433922", "Score": "0", "body": "@CacahueteFrito the reason sudo is required is because otherwise open() call on /dev/ttyACM0 will fail with no permissions error. It would be good if I could work out a way so don't have to run with sudo. Any ideas?" } ]
[ { "body": "<h2><code>typedef</code> <code>_t</code></h2>\n\n<p><a href=\"https://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html\" rel=\"nofollow noreferrer\">POSIX</a> reserves identifiers ending in <code>_t</code>. You should maybe use <code>_s</code> (s for struct) for the typedef:</p>\n\n<pre><code>struct Foobar {\n void *foo;\n int32_t bar;\n};\ntypedef struct Foobar foobar_s;\n</code></pre>\n\n<p>For your typedefs for function types, I would use <code>_f</code> (f for function) to help easily differentiate the type from a normal identifier.</p>\n\n<p>Or not use <code>typedef</code> at all :)</p>\n\n<hr>\n\n<h2>encapsulate into a function</h2>\n\n<p>The following code deserves a function:</p>\n\n<pre><code> // eat any prepended newlines\n while (s != end &amp;&amp; *s &amp;&amp; (*s == '\\r' || *s == '\\n'))\n s++;\n</code></pre>\n\n<p>The following too:</p>\n\n<pre><code> case WAITFORCALL:\n {\n //parse call data in to caller id etc\n static char callerid[50] = {0};\n static char caller_date[20] = {0};\n static char caller_time[20] = {0};\n\n int size;\n char line[100]; // we assume no lines &gt; 100 chars\n const char* rest = buffer;\n char* end = buffer + *length;\n while ((rest = getline_stringstream(line, &amp;size, rest, end)) != NULL) {\n if(strncmp(line, \"NMBR\", 4) == 0 &amp;&amp; strlen(line) &gt; 7) {\n strcpy(callerid, &amp;line[7]);\n }\n if(strncmp(line, \"DATE\", 4) == 0 &amp;&amp; strlen(line) &gt;= 11) {\n sprintf(caller_date, \"%c%c/%c%c\", line[9], line[10], line[7], line[8]);\n }\n if(strncmp(line, \"TIME\", 4) == 0 &amp;&amp; strlen(line) &gt;= 11) {\n sprintf(caller_time, \"%c%c:%c%c\", line[7], line[8], line[9], line[10]);\n }\n }\n if(strlen(callerid) &gt; 0 &amp;&amp; strlen(caller_date) &gt; 0 &amp;&amp; strlen(caller_time) &gt; 0) {\n printf(\"%-6s%-6s%s\\n\", caller_date, caller_time, callerid);\n callerid[0] = caller_date[0] = caller_time[0] = '\\0';\n }\n }\n break;\n</code></pre>\n\n<hr>\n\n<h2>Safe usage of malloc</h2>\n\n<p>Malloc is easily misused.</p>\n\n<ul>\n<li><code>sizeof(type)</code> vs <code>sizeof(*foo)</code>:</li>\n</ul>\n\n<p><code>foo = malloc(sizeof(*foo) * nmemb);</code> is better because if you ever change the type of <code>foo</code>, this call will still be valid, while if not, you would have to change every line where malloc is called with foo. If you forget any of those lines, good luck.</p>\n\n<hr>\n\n<h2>Error checking:</h2>\n\n<pre><code>// set port speed\nif (set_speed(port-&gt;current_tty, port-&gt;baudrate) == -1) {\n // error setting tty speed\n return -1;\n}\n</code></pre>\n\n<p>This is unsafe: if you ever add another error code to <code>set_speed</code>, and forget to update this line, good luck!</p>\n\n<p>Solution: check for any non-zero values:</p>\n\n<pre><code>// set port speed\nif (set_speed(port-&gt;current_tty, port-&gt;baudrate)) {\n // error setting tty speed\n return -1;\n}\n</code></pre>\n\n<hr>\n\n<h2><code>fflush</code></h2>\n\n<pre><code>fprintf(stderr, \"something unexpected happened, aborting...\\n\");\nfflush(stdout);\nexit(1); // something bad happened - exiting\n</code></pre>\n\n<p>This doesn't make any sense:</p>\n\n<ul>\n<li>when the program <code>exit</code>s, <code>stdout</code> is automatically <code>fflush</code>ed (actually, all streams, I think).</li>\n<li>If you wanted to say <code>fflush(stderr);</code> it's not needed: <code>stderr</code> is either unbuffered or line-buffered.</li>\n</ul>\n\n<hr>\n\n<h2><code>EXIT_FAILURE</code></h2>\n\n<p>Use <code>exit(EXIT_FAILURE);</code> when you don't want a specific error code.</p>\n\n<hr>\n\n<h2><code>const</code> non-pointer parameters (just no)</h2>\n\n<p><code>int port_start(const char* portname, const int baudrate, connect_callback connectcb, read_callback readcb, void* userdata);</code></p>\n\n<p><code>const int baudrate</code> adds clutter to the code, and absolutely no difference to the user of the function. A function can't modify its arguments. Only pointers can point to modifiable data, and therefore need the <code>const</code> qualifier if they don't modify the data pointed to.</p>\n\n<p>Use <code>int baudrate</code> instead.</p>\n\n<hr>\n\n<h2>inline</h2>\n\n<p>This is a very good candidate for <code>inline</code>:</p>\n\n<pre><code>int port_write(serial_port_t* port, const char* data, size_t length) {\n return write(port-&gt;fd, data, length);\n}\n</code></pre>\n\n<p>It provides a free optimization with no downsides for one line functions (unless you want to keep its contents secret):</p>\n\n<p><code>serial_port.h</code>:</p>\n\n<pre><code>inline\nint port_write(struct Serial_Port* port, const char* data, size_t length);\n\ninline\nint port_write(struct Serial_Port* port, const char* data, size_t length)\n{\n return write(port-&gt;fd, data, length);\n}\n</code></pre>\n\n<p><code>serial_port.c</code>:</p>\n\n<pre><code>extern\nint port_write(struct Serial_Port* port, const char* data, size_t length);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T16:01:36.623", "Id": "223757", "ParentId": "223731", "Score": "2" } } ]
{ "AcceptedAnswerId": "223757", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T10:28:59.897", "Id": "223731", "Score": "1", "Tags": [ "c", "linux", "serial-port" ], "Title": "Serial port library for unix systems in C using callback model" }
223731
<p>I wrote this program as part of a work-related problem but with a focus on improving my Python skills. The program was needed to do a word count PDF files. The problem was there were a large number of PDF files (over 1000) which were scattered over a drive. I made use of a number of modules to achieve this.</p> <p><strong>Quick description</strong></p> <p>The program uses <code>glob.iglob</code> to search through a directory tree for PDF files. Once it has a PDF file it extracts the content to a list <code>saved_text</code>. Using <code>len</code> it works out the number of pages in the PDF. It then uses the <code>slip()</code> method to do a word count for the full document. It returns to the top of the loop and repeats till all PDF files have been counted.</p> <p>I have heavily commented in my code.</p> <p><strong>Import, file paths input/output</strong></p> <pre><code>import PyPDF2 import glob import xlsxwriter # ------------------------ Input file path ------------------------ # input_file_path = r"\\...pdf" input_file_count_path = r"\\.." # ------------------------ Output file path ----------------------- # output_file_path = "word_count.xlsx" </code></pre> <p><strong>def main</strong></p> <pre><code>def main(input_file_path, output_file_path, file_count): # lists total_words_list = [] # word count total_pages_list = [] # page count file_name_list = [] print('PyPDF2 import complete') for pdfFileObj in glob.iglob(input_file_path): try: # save the file path to list file_name_list.append(pdfFileObj) # To get a PdfFileReader object that represents this PDF, call PyPDF2.PdfFileReader() and pass it pdfFileObj. Store this PdfFileReader object in pdfReader. pdfReader = PyPDF2.PdfFileReader(pdfFileObj) number_of_pages = pdfReader.getNumPages() saved_text = [] # loop to count number pages in document for page_number in range(number_of_pages): page = pdfReader.getPage(page_number) # Once you have your Page object, call its extractText() method to return a string of the page’s text ❸. The text extraction isn’t perfect. page_content = page.extractText() # appned to list saved_text.append(page_content) # count the total number of pages on the document total_pages = len(saved_text) # add number of pages from document 'total_pages' to total_pages_list which will keep record for all documents. total_pages_list.append(total_pages) # print number of pages print("total number of pages are: ", total_pages) # create new var word_count_total = 0 # loop count words and output total words on document for i in saved_text: #The split() method splits a string into a list. which means 'len' can be used to count the number of words per page. word_count = len(i.split()) # Might be some counting issues, need to test futher. #Totals up the count of words for all pages in the PDF. word_count_total = word_count + word_count_total # takes total word count for each document and adds to a list total_words_list.append(word_count_total) print("Total word count for your file is: ", word_count_total) print(pdfFileObj) except: print("------there was a problem with the file, it will be skipped-------") continue # Deals with ENCRYPTED files. return(total_words_list, total_pages_list, file_name_list, input_file_path, output_file_path) </code></pre> <p>There is a separate function to write the data lists to an excel file using <code>xlsxwriter</code>.</p> <p><strong>def save_to_file</strong></p> <pre><code># ----------------- function to save to file ------------------------ # def save_to_file (total_words_list, total_pages_list, file_name_list, input_file_path, output_file_path): print("output to excel started") # makes a new excel file workbook = xlsxwriter.Workbook(output_file_path) # add_worksheet method called on workbook object worksheet = workbook.add_worksheet() # start from first cell row = 1 # loop word count, page count and file location then write to file for a, b, c in zip(total_pages_list, total_words_list, file_name_list): # write to file using write method worksheet.write(row, 0, a ) worksheet.write(row, 1, b ) worksheet.write(row, 2, c ) row += 1 workbook.close() print("---output to excel file complete, program all finished---") main(input_file_path, output_file_path, file_count) </code></pre> <p>Areas of concern:</p> <ul> <li>Is my code clean? could it be more concise? </li> <li>Being new to Python I am sure to overlooked something simple..?</li> <li>Program is very slow when running on deep directory trees e.g. depth 4+ </li> </ul>
[]
[ { "body": "<h2>Performance</h2>\n\n<blockquote>\n <p>The problem was there were a large number of PDF files (over 1000) which were scattered over a drive.</p>\n</blockquote>\n\n<p>This is the perfect scenario for a parallel application. Spin up a few workers and have them run through the files, perhaps sorted by size and evenly distributed so that the workload is also evenly distributed.</p>\n\n<h2>File paths</h2>\n\n<pre><code>input_file_path = r\"\\\\...pdf\"\ninput_file_count_path = r\"\\\\..\"\n</code></pre>\n\n<p>This is puzzling, and probably not what you actually want. Does your filename contain a literal backslash? How many of those dots means the upper directory? You may be better off using some Python path functions to form these paths, especially since you're on Windows (?)</p>\n\n<h2>Function length</h2>\n\n<p>Your <code>main</code> is long and complex, and should be subdivided into more functions.</p>\n\n<h2>Never <code>except:</code></h2>\n\n<p>This is a deadly trap for beginners. Ctrl+C (program break) is represented as an exception, so this effectively prevents the user from killing your program with the keyboard. Use <code>except Exception</code> instead. Also, you should be outputting what went wrong, even if you decide to continue on with the other files.</p>\n\n<h2>Multiple return</h2>\n\n<p>First of all, your return doesn't need parens, because multiple return uses an implicit tuple.</p>\n\n<p>Also, given the large number of return values, you're better off representing this result as an object.</p>\n\n<h2>Clean up after yourself</h2>\n\n<p>This:</p>\n\n<pre><code>workbook.close()\n</code></pre>\n\n<p>won't be executed if there's an exception before it. Instead, put your workbook in a <code>with</code> block.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T14:27:16.930", "Id": "433791", "Score": "0", "body": "Thanks for the feedback. I have tried to parallelise using `concurrent.futures.ProcessPoolExecutor` but have to date not got it working.\n\n Sorry, I cleaned up the file paths to much have now added the \\**\\ back.\n\n Right I will try and break up `main`.\n\n **Multiple return** - great I was not sure how to handle this. Would a namedtuple() be the way to maybe?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T14:36:55.580", "Id": "433799", "Score": "0", "body": "`namedtuple` is a lightweight option, yes. A heavier option is to write a class." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T12:57:42.277", "Id": "223739", "ParentId": "223737", "Score": "6" } }, { "body": "<p>This already has a good answer, but I noticed some other things, that you should be aware of.</p>\n\n<h2>save_to_file</h2>\n\n<ul>\n<li><code>input_file_path</code> is never used</li>\n<li>In simple loops it can be a valid choice to use single-letter names for iteration items. The usage of <code>a</code>, <code>b</code>, <code>c</code> here however is confusing, as it is not clear, that they are what you intend them to be, especially since the order you use differs from the comment directly above and the function signature.</li>\n</ul>\n\n<h2>main</h2>\n\n<ul>\n<li><code>file_count</code> is never used</li>\n<li>The return tuple contains two of the call arguments entirely unchanged. Why should a caller want to have them in the return object? So only three of the return objects are relevant. A namedtuple would be a good choice anyway.</li>\n<li>your try-except construct is flawed: You expect the individual arrays in the return tuple to have an equal number of elements. But if for example an exception ocurrs after <code>file_name_list.append(pdfFileObj)</code>, this is no longer the case, and your <code>save_to_file</code> will crash later. My suggestion would be to move everything in the try-block to a new function (or multiple), that returns a single (named-)tuple, that is added to an array at the end of the try-block. That array should be the only return value of main.</li>\n<li>Your iterations (pdf pages and parsed pages) are a bit clumsy. Always prefer ready-to-use iterators over hand-made ones: Using <code>for page in pdfReader.pages:</code> makes two local variables obsolete. Or - as you asked if you can be more concise - directly use a list comprehension: <code>saved_text = [page.extractText() for page in pdfReader.pages]</code>, and a generator expression for the word count: <code>word_count_total = sum(len(page_text.split()) for page_text in saved_text)</code>.</li>\n</ul>\n\n<h2>general</h2>\n\n<ul>\n<li>You are using way too many comments for my taste. One good thing about Python is, that by choosing good names and structure, it's quite easy to make code explain itself. If you need lots of comments, you should start investing more time in structure (move parts to new methods with expressive names) and names (<code>pdfFileObj</code> is a filepath, why not <code>pdf_filepath</code>?). If your comments just state the obvious, they clutter the reader's view and should be removed (<code># create new var</code> before <code>word_count_total = 0</code>, or <code># write to file using write method</code> before <code>worksheet.write(row, 0, a )</code>).</li>\n<li>the call to <code>main</code> at the end is probably not from your original code, as <code>file_count</code> is undefined. If it is, use an <code>if __name__ == '__main__':</code> block for it. Otherwise it's impossible to import the file without side effects for tests or code-reusage.</li>\n<li>Using <code>ProcessPoolExecutor</code> is a good approach to increase performance. But it won't work in your current structure. You need a function that cares about nothing else outside the current file. If you implement the proposal from my third point in <code>main</code>, this will be a lot easier (filename as call-argument, 3-tuple as return value).</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T09:22:50.957", "Id": "434062", "Score": "0", "body": "Thanks for all the great feedback, looks like I have some coding to do." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T17:39:15.930", "Id": "223763", "ParentId": "223737", "Score": "3" } } ]
{ "AcceptedAnswerId": "223739", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T12:38:27.207", "Id": "223737", "Score": "4", "Tags": [ "python", "beginner", "python-3.x", "pdf" ], "Title": "PDF page & word count, recursive searching of directory tree, output to excel" }
223737
<p>This is an extension of my <a href="https://codereview.stackexchange.com/questions/223581/reusable-progress-indicator">Reusable Progress Indicator</a> post. I realised that I needed to add additional compiler constants for compatibility of the Windows API functions used in the <code>HideTitleBar</code> sub which is called on the <code>Userform_Initialize</code> event; however, I am unsure if they are correct for all cases. I have tested the code on Windows 64-Bit for both 32-Bit Excel and 64-Bit Excel and it worked without issue, but because I have no access to Win 32-Bit OS, I can't really test if my declarations have the correct keywords and data types for that case.</p> <p>So with that I ask, are my declarations correct and is the setup of the API declarations the most general/comprehensive method?</p> <pre><code>#If Win64 And VBA7 Then '64-Bit Windows and 64-Bit Excel Private Declare PtrSafe Function GetWindowLong _ Lib "user32" Alias "GetWindowLongA" ( _ ByVal hwnd As LongPtr, _ ByVal nIndex As LongPtr) As LongPtr Private Declare PtrSafe Function SetWindowLong _ Lib "user32" Alias "SetWindowLongA" ( _ ByVal hwnd As LongPtr, _ ByVal nIndex As LongPtr, _ ByVal dwNewLong As LongPtr) As LongPtr Private Declare PtrSafe Function DrawMenuBar _ Lib "user32" ( _ ByVal hwnd As LongPtr) As LongPtr Private Declare PtrSafe Function FindWindowA _ Lib "user32" (ByVal lpClassName As String, _ ByVal lpWindowName As String) As LongPtr Private Declare PtrSafe Function GetTickCount _ Lib "kernel32.dll" () As LongPtr #ElseIf Win64 And Not VBA7 Then '64-Bit Windows and 32-Bit Excel Private Declare PtrSafe Function GetWindowLong _ Lib "user32" Alias "GetWindowLongA" ( _ ByVal hwnd As Long, _ ByVal nIndex As Long) As Long Private Declare PtrSafe Function SetWindowLong _ Lib "user32" Alias "SetWindowLongA" ( _ ByVal hwnd As Long, _ ByVal nIndex As Long, _ ByVal dwNewLong As Long) As Long Private Declare PtrSafe Function DrawMenuBar _ Lib "user32" ( _ ByVal hwnd As Long) As Long Private Declare PtrSafe Function FindWindowA _ Lib "user32" (ByVal lpClassName As String, _ ByVal lpWindowName As String) As Long Private Declare PtrSafe Function GetTickCount _ Lib "kernel32.dll" () As Long #Else '32-Bit Windows and 32-Bit Excel Private Declare Function GetWindowLong _ Lib "user32" Alias "GetWindowLongA" ( _ ByVal hwnd As Long, _ ByVal nIndex As Long) As Long Private Declare Function SetWindowLong _ Lib "user32" Alias "SetWindowLongA" ( _ ByVal hwnd As Long, _ ByVal nIndex As Long, _ ByVal dwNewLong As Long) As Long Private Declare Function DrawMenuBar _ Lib "user32" ( _ ByVal hwnd As Long) As Long Private Declare Function FindWindowA _ Lib "user32" (ByVal lpClassName As String, _ ByVal lpWindowName As String) As Long Private Declare Function GetTickCount _ Lib "kernel32.dll" () As Long #End If Private Sub HideTitleBar() Dim lngWindow As LongPtr, lngFrmHdl As LongPtr lngFrmHdl = FindWindowA(vbNullString, Me.Caption) lngWindow = GetWindowLong(lngFrmHdl, GWL_STYLE) lngWindow = lngWindow And (Not WS_CAPTION) SetWindowLong lngFrmHdl, GWL_STYLE, lngWindow DrawMenuBar lngFrmHdl End Sub </code></pre> <p><strong>Example (Please See the <a href="https://codereview.stackexchange.com/questions/223581/reusable-progress-indicator">Reusable Progress Indicator</a> post for more details):</strong> </p> <p>In frm Code: </p> <pre><code>Private Sub IProgressIndicator_LoadProgIndicator(Optional ByVal HasParentProccess As Boolean, _ Optional ByVal CanCancel As Boolean, _ Optional ByVal CalculateExecutionTime As Boolean) this.CalculateExecutionTime = CalculateExecutionTime If CalculateExecutionTime Then this.StartTime = GetTickCount() 'CALLED HERE HideTitleBar this.HasParentProccess = HasParentProccess: this.CanCancel = CanCancel With Me If this.HasParentProccess Then .Height = PROGINDICATOR_MAXHEIGHT .ParentProcedureStatus.Height = PARENTPROCSTATUS_MAXHEIGHT .ProcedureStatus.Top = PROCSTATUS_MAXTOP .frameProgressBar.Top = PROGRESSBAR_MAXTOP .lblElapsedTime.Top = ELAPSEDTIME_MAXTOP .ElapsedTime.Top = ELAPSEDTIME_MAXTOP .lblTimeRemaining.Top = TIMEREMAINING_MAXTOP .TimeRemaining.Top = TIMEREMAINING_MAXTOP End If .ProgressBar.Width = 0 .StartUpPosition = 0 .Left = Application.Left + (STARTPOS_LEFT_OFFSET * Application.Width) - (STARTPOS_LEFT_OFFSET * .Width) .Top = Application.Top + (STARTPOS_RIGHT_OFFSET * Application.Height) - (STARTPOS_RIGHT_OFFSET * .Height) .Show End With End Sub </code></pre> <p>In regular Module: </p> <pre><code>Public Sub TestingOrphanProccess() Dim i As Long Dim ProgressBar As IProgressIndicator On Error GoTo ErrHandle Set ProgressBar = New ProgressIndicator ProgressBar.LoadProgIndicator CanCancel:=True, CalculateExecutionTime:=True For i = 1 To 10000 'only have to specify this property if boolCanCancel:=True If ProgressBar.ShouldCancel Then Exit Sub StaticSheet_Sht1.Cells(1, 1) = i ProgressBar.UpdateOrphanProgress "Proccessing", i, 10000 Next Exit Sub ErrHandle: Debug.Print Err.Number End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-13T21:20:29.230", "Id": "434658", "Score": "1", "body": "Your VBA7 declarations are wrong. Seems like you just replaced`Long`with`LongPtr`? Usually, you only change pointers and handles to`LongPtr`everything else stays`Long` I use [Windows API Viewer for MS Excel](https://www.rondebruin.nl/win/dennis/windowsapiviewer.htm) to create Win-API declarations." } ]
[ { "body": "<p>IMO, you're overcomplicating it. For 99% of the cases, you only need something similar to this:</p>\n\n<pre><code>#If VBA7 Then\n 'VBA7 declaration style\n Private Declare PtrSafe Function GetWindowLong _\n Lib \"user32\" Alias \"GetWindowLongA\" ( _\n ByVal hwnd As LongPtr, _\n ByVal nIndex As Long) As Long\n#Else\n 'VBA6 declaration style\n Private Declare Function GetWindowLong _\n Lib \"user32\" Alias \"GetWindowLongA\" ( _\n ByVal hwnd As Long, _\n ByVal nIndex As Long) As Long\n#End If\n</code></pre>\n\n<p>You don't really need to check <code>Win64</code> constant solely for API compatibility. As a matter of fact, you want to prefer using VBA7 API declarations whenever possible because they align much more closely to the actual C++ declarations that the API declarations are based on. </p>\n\n<p>The only reason to use <code>Win64</code><sup>1</sup> is to do something that can be done exclusively in 64-bit Office (which is very rare and I have trouble thinking of a good example beyond simply just checking whether the Office itself is 64-bit. The single anomaly is a certain API function - <code>SetWindowsLongPtr</code> which for some reasons, doesn't have the same declarations between 32-bit Windows and 64-bit Windows OS, in which case, you do have to use <code>Win64</code> for that particular API declaration. But others, just <code>VBA7</code> is sufficient and using VBA7 declaration style means you get more information from reading the declarations than you would have had from VBA6. <code>hWnd As LongPtr</code> is abundantly obvious that it's a pointer, not just an integer like say, <code>nIndex As Long</code>. </p>\n\n<p>Props to <a href=\"https://codereview.stackexchange.com/users/175456/computerversteher\">@computerversteher</a>: </p>\n\n<p>My original post was a blind copy'n'paste from OP to illustrate the correct situation. However, he pointed out that the declarations themselves were incorrect, in particular, the <code>nIndex</code> parameter which was originally a <code>LongPtr</code> but that is not correct since it's just an integer, not a true pointer. Only pointer data types should be assigned <code>LongPtr</code>. As per the comment:</p>\n\n<blockquote>\n <p><a href=\"https://codekabinett.com/rdumps.php?Lang=2&amp;targetDoc=windows-api-declaration-vba-64-bit\" rel=\"nofollow noreferrer\">How to convert Windows API declarations in VBA for 64-bit</a> provides an example for WIN64 (When to use the WIN64 compiler constant in the last third of article (sorry no anchors), that provides basic knowledge). </p>\n</blockquote>\n\n<p>Thanks, @computerversteher!</p>\n\n<hr>\n\n<ol>\n<li>Note that <code>Win64</code> is something of a misnomer. It'll be only <code>True</code> when the Office is a 64-bit install, but will be <code>False</code> even on a 64-bit Windows running 32-bit Office. For sanity's sake, pretend that various <code>WinXX</code> constants are actually named <code>OfficeXX</code>. </li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T13:21:21.193", "Id": "433770", "Score": "0", "body": "Interesting. So just to clarify, my last `Else` directive is unneeded, because my second 'Else' directive, (which is a `VBA6` declaration), also covers `32-bit Windows` and `32-bit Excel`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T13:39:07.097", "Id": "433771", "Score": "1", "body": "Additionally `Win64` evaluates to `True` on Mac OS 64-bit office, `False` on 32 bit (same behaviour as Windows, just even weirder thet `Win...` evaluates to true ever on a Mac)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T13:39:52.383", "Id": "433772", "Score": "0", "body": "It's actually the `#ElseIf Win64 And Not VBA7 Then` that's incorrect and unnecessary. It's incorrect because you have `PtrSafe` which is a VBA7 keyword so it wouldn't even run." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T13:41:05.923", "Id": "433773", "Score": "1", "body": "@Greedo Yep, That's why `Win...` is a bad name - It would have been much more clearer if it was `Office...` instead. Life's a bowl of cherries." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T13:46:43.823", "Id": "433776", "Score": "0", "body": "I wonder, are there any other situations where OS bitness matters - there's that one unusual declaration as you point out. But could a 32-bit Office on 64-bit Windows ever be required to use `LongLong` for pointers. I believe the application keeps its own 32-bit memory with `Long` 32-bit addresses, but what if you want to refer to the address space of some separate 64-bit application, its window handle or something? I know you sometimes require `LongLong`/`ULong` in 32-bit office for other things (`QueryPerformanceCounter` IIRC), but does a 32-bit Office ever require a `LongLong` pointer type?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T13:51:44.180", "Id": "433779", "Score": "0", "body": "The problem is that `LongLong` doesn't exist in a 32-bit Office, IIRC. You cannot actually do `Dim x As LongLong` in that case anyway. `LongPtr` on a 32-bit VBA environment maps to a `Long`. BTW, `LongLong` isn't a true pointer data type. It's just an integer. A pointer scales with the architecture, so its size isn't the same across different architectures. `Long` and `LongLong` means the same thing everywhere but `LongPtr` doesn't." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T14:03:03.003", "Id": "433782", "Score": "0", "body": "@this Yeah I just though about that a minute ago and realized, lol. So then to further clarify for my own understanding, all I need for `Windows 64-Bit` Compatibility with either '32-bit` or `64-Bit` Office, are the declarations under the `#If Win64 And VBA7 Then` directive, (which should be changed to ` #If VBA7 Then`), and for 'Windows 32-Bit' all I need are the declarations under `#Else` directive? Because if that's the case, then what I had in my original Reusable Progress Indicator post was completely fine save the use of `LongPtr` in the calling procedure...." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T14:03:26.467", "Id": "433783", "Score": "0", "body": "...which means I made things waaayyy too complicated, lol." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T14:21:45.053", "Id": "433788", "Score": "0", "body": "Not exactly - most of time, all you care about is compatibility with VBA7 or VBA6. VBA6 never could ever run in 64-bit Office, since it never existed. VBA7 can run both on 64-bit and 32-bit Office, regardless of Windows' bitness. Since a VBA7 style declaration will run for either 64-bit or 32-bit Office, you should just use VBA7 declaration everywhere. The only reason to include a VBA6 declaration is to provide a backward compatibility for Office installs prior to 2010 (when VBA7 and 64-bit Office was introduced) since those version cannot understand VBA7's keywords like `PtrSafe` and so on." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T14:25:11.433", "Id": "433790", "Score": "0", "body": "One more thing that might help clarify the confusion. On a 32-bit Office's VBA7, you could get away with incorrectly using `Long` for where `LongPtr` would be needed because as mentioned, `LongPtr` maps to `Long`... but only on a 32-bit Office. So the declaration will apparently work... Until you try to to use the same code on a 64-bit Office, where it may blow up (or worse, works in an undefined way). Using `LongPtr` correctly will work on both 32-bit and 64-bit Offices without any change to the code, which is why using only the `VBA7` suffices for most cases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T14:31:58.657", "Id": "433795", "Score": "0", "body": "@this Gotcha. Thanks so much for taking to the time to explain!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T14:59:06.707", "Id": "433812", "Score": "2", "body": "@rickmanalexander (@)this FWIW I've tried to collect my thoughts on the whole OS vs Office bitness confusion with [this question](https://stackoverflow.com/q/56937514/6609896)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T15:10:42.370", "Id": "433815", "Score": "0", "body": "@Greedo Excellent Idea! I have really started to use the API functions quite a lot lately and it is difficult to find comprehensive examples on the topic of `OS` / `Host` compatibility with respect to bitness, so I look forward to the discussion your question sparks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-14T19:21:35.577", "Id": "434761", "Score": "1", "body": "Memo to myself: Actually read OP's code. You're actually correct; my post was focusing on the question about structuring the declarations, not the declarations. I've updated the post accordingly. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-15T21:27:28.727", "Id": "434934", "Score": "0", "body": "Do you think maybe op should use [`GetWindowLongPtr`](https://docs.microsoft.com/en-gb/windows/win32/api/winuser/nf-winuser-getwindowlongptra) which has superceded the current approach? Although op only uses the function to get a `GWL_STYLE` attribute which will fit in a `Long`, the function can also return handles or function pointers which probably need more space on 64 bit office (well window handles apparently don't, but the others may) so perhaps a `LongPtr` return value is appropriate. Not sure what conditional compilation is needed to check whether that API version exists though!" } ], "meta_data": { "CommentCount": "15", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T13:05:55.390", "Id": "223740", "ParentId": "223738", "Score": "3" } } ]
{ "AcceptedAnswerId": "223740", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T12:54:26.420", "Id": "223738", "Score": "4", "Tags": [ "vba", "winapi" ], "Title": "Windows API Declarations For Compatibility" }
223738
<p>I want to know if there is a better way to do this function. The function calculates a payback. Basically, the company spend x amount of money and per year they will save some money overtime. They want to count how many years it takes to get the money back.</p> <p>I.E. The company spends 100k. year 1 they save 45k, year 2 save 45k and year 3 save 45k for this investment; therefore, they will get the money back in around 2.22 years.</p> <p>I created a function which works ok, but there is something that tells me is not right. I cannot figure out what is that. It takes 2 parameters:</p> <ul> <li>Array: each year how much the company saves. In the previous example would be something like [45000, 45000, 45000]. Target: Total of money spend. 100k in the previous example</li> </ul> <pre class="lang-php prettyprint-override"><code>// this is a modified version of the previous code that was broken. $years = [1000.00, 2000.00, 3000.00, 4000.00, 5000.00]; $expected = 7500.00; function payback($array, $target) { $total = 0 - $target; for ($i=0; $i &lt; sizeof($array); $i++) { $total += $array[$i]; if($total &lt;= 0) { $previous = $total; } if($total &gt; 0) { echo "Previous: " . $previous; echo "\nArray: " . $array[$i]; $ytd = abs($previous / $array[$i]); $count = $i; break; } } return round($ytd + $count, 2) ; } echo "payback is: " . payback($years, $expected); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T17:09:39.683", "Id": "433847", "Score": "2", "body": "Your code lacks automatic unit tests. Some for simple cases and some for more complex ones. Using these tests you can find out where your code is broken." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T13:47:49.040", "Id": "433971", "Score": "1", "body": "I see... when i enter different numbers is where the problem was starting. I modified the code and it should be working now. Thank you @mickmackusa" } ]
[ { "body": "<p>You should not be calling <code>sizeof()</code> after every iteration. In fact, using <code>foreach()</code> eliminates the need to count at all and provides an incrementing counter variable.</p>\n\n<p>When you want to break out of a loop and immediately return from your custom function, just use <code>return</code>.</p>\n\n<p>Notice in my code below that it is not necessary to write an <code>elseif</code> or <code>else</code> condition.</p>\n\n<p>You can avoid working with negative values and calling <code>abs()</code> by using subtraction instead of adding to the negative initial value.</p>\n\n<p>I also, try to keep the number of declared variables to a minimum.</p>\n\n<p>Code: (<a href=\"https://3v4l.org/CAVsk\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n\n<pre><code>$years = [1000.00, 2000.00, 3000.00, 4000.00, 5000.00];\n$expected = 7500.00;\n\nfunction payback($array, $target) {\n foreach ($array as $i =&gt; $amount) {\n $newTarget = $target - $amount;\n if ($newTarget &lt; 0) {\n return round($i + ($target / $amount), 2);\n }\n $target = $newTarget;\n }\n}\n\necho \"payback is: \" . payback($years, $expected);\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>payback is: 3.38\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T03:39:23.807", "Id": "223843", "ParentId": "223747", "Score": "4" } }, { "body": "<p>I agree with all that mickmackusa has said, but I have four additions:</p>\n\n<ul>\n<li>The return value must be defined for cases where the values in the yearly array add up to less than the total value that was spent. I chose to return <code>false</code> for this. So when the function return <code>false</code> it means that it cannot compute the payback years, given the input. </li>\n<li>When the total value that was spent exactly matched the total sum of the array (15,000), the function of mickmackusa will return nothing. That's because of the <code>if ($newTarget &lt; 0)</code>, this should be <code>if ($newTarget &lt;= 0)</code>.</li>\n<li>The names chosen are not the best possible. What information does <code>$array</code> or <code>$target</code> contain? The first name is chosen based on the type of the variable, and the second seems to be based on what the function needs to do. I've always learned that a variable name should reflect the meaning of the data it contains. The names I use in the code below might be a bit more verbose than the old ones, but they tell you clearly what they contain. Correctly chosen variable names help you to understand your own code, especially if you look at it again after a few years.</li>\n<li>I've done the same thing with the algorithm inside the function. The function of mickmackusa works, but it is not the easiest to read or understand. A <code>$newTarget</code> is created and later replaces the original <code>$target</code>. So the target changes? Well, yes, it does. In the end this is not a complicated function, and it is understandable, but by using better names the algorithm can better explain itself. I use a variable called <code>$totalSaved</code> that keeps track of what was saved in total.</li>\n</ul>\n\n<p>This is new code:</p>\n\n<pre><code>&lt;?php\n\n$savingsPerYear = [1000.00, 2000.00, 3000.00, 4000.00, 5000.00];\n$totalSpent = 7500.00;\n\nfunction getPaybackYears($totalSpent, $savingsPerYear) {\n $totalSaved = 0.00;\n foreach ($savingsPerYear as $yearNo =&gt; $savedThisYear) {\n $totalSaved += $savedThisYear;\n if ($totalSaved &gt;= $totalSpent) {\n $spendingLeftThisYear = $totalSpent - ($totalSaved - $savedThisYear);\n return round($yearNo + $spendingLeftThisYear / $savedThisYear, 2);\n }\n }\n return false;\n}\n\n$payback = getPaybackYears($totalSpent, $savingsPerYear);\n\nif ($payback === false) echo \"payback not reached\";\n else echo \"payback in years: \" . $payback;\n\n?&gt;\n</code></pre>\n\n<p><strong>In summary:</strong> I've corrected two bugs and improved readability.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T07:55:58.183", "Id": "223851", "ParentId": "223747", "Score": "2" } } ]
{ "AcceptedAnswerId": "223851", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T14:17:58.607", "Id": "223747", "Score": "4", "Tags": [ "php" ], "Title": "Calculate payback" }
223747
<p>I am working on a CodeWars titled 'Square into Squares. Protect trees!' it can be found here: <a href="https://www.codewars.com/kata/54eb33e5bc1a25440d000891/train/javascript" rel="nofollow noreferrer">https://www.codewars.com/kata/54eb33e5bc1a25440d000891/train/javascript</a></p> <p>I have a working solution, the issue is that the performance is so horrid that if I run it with an argument higher than around 15 my browser/tab freezes. I would like some suggestions as towards how I could create a more efficient algorithm for this kind of problem, or just improve my current algorithm to be more performant.</p> <p>Codewars times out as a result of its bad performance on the full test kit for the Kata. I am entirely certain that the issue is caused by calculating the square of every number beneath my argument number, but since I'm not particularly talented at math that was my procedural way of finding the correct values. I thought if I could find a way of eliminating many of the values before calculating their square that would solve the problem, but I haven't thought of a way yet.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let sol = [] function decompose(n) { sol = [] let expMap = {} for(let i = 1; i &lt; n; i++){ expMap[i] = Math.pow(i, 2) } for(let prop in expMap){ solutionFinder(prop, expMap, Math.pow(n, 2), []) } if(sol.length &gt; 0) return sol return null } const solutionFinder = (val, set, currentValue, currentSet) =&gt; { const dataArr = [...currentSet] const dataClone = {...set} currentValue -= dataClone[val] dataArr.push(val) delete dataClone[val] if(currentValue &lt; 0) return; if(!(currentValue === 0)){ for(let prop in dataClone){ solutionFinder(prop, dataClone, currentValue, dataArr) } } if(currentValue === 0){ if(sol.length === 0 || arrSum(sol) &lt; arrSum(currentSet)){ sol = dataArr.map(i =&gt; parseInt(i)).sort((a, b) =&gt; a - b) return } } return } const arrSum = arr =&gt; arr.reduce((a,b) =&gt; a + b, 0)</code></pre> </div> </div> </p> <p>I am relatively new to programming (Started in February), and still struggle with developing algorithms with good time complexity, any advice about how to make this algorithm more efficient or an algorithm that would work better for this job would be welcome.</p>
[]
[ { "body": "<h3>Optimization starts from a sound logical process</h3>\n\n<p>Let's think about the problem in particular.</p>\n\n<blockquote>\n <p>Given a positive integral number n, return a strictly increasing sequence (list/array/string depending on the language) of numbers, so that the sum of the squares is equal to n².</p>\n \n <p>If there are multiple solutions (and there will be), return the result with the largest possible values</p>\n</blockquote>\n\n<p>And later, it specifies</p>\n\n<blockquote>\n <p>If no valid solution exists, return nil, null, Nothing, None (depending on the language) or \"[]\" (C) ,{} (C++), [] (Swift, Go).</p>\n</blockquote>\n\n<p>You were on the right track with your solution, but the code does not exemplify that. Your solution iterates through a map of <em>all <img src=\"https://chart.googleapis.com/chart?cht=tx&amp;chl=n%20%5Crightarrow%20n%5E%7B2%7D\" alt=\"n_squared\"> pairings</em> and removes one at a time per iteration of <code>solutionFinder</code>. At worst, this will go through <em>every permutation</em> of 1, ..., <img src=\"https://chart.googleapis.com/chart?cht=tx&amp;chl=%20n-1\" alt=\"sqrt(n)\">. And ideally, you should never reach a case where you're even looking at numbers that have larger squares than your remaining value.</p>\n\n<p>So, how can we improve this? Well, as I said before, optimization starts from a sound logical process. There are 2 conditions in the specifications that can help us build that solution:</p>\n\n<ol>\n<li>The sequence must be <em>strictly increasing</em></li>\n<li>If there are multiple solutions, we must return the result with the <em>largest possible values</em></li>\n</ol>\n\n<p>Because I'm pretty sure you're already within this same line of problem solving for the problem itself, I'll just jump to what I'm thinking:</p>\n\n<blockquote class=\"spoiler\">\n <p> Start with <img src=\"https://chart.googleapis.com/chart?cht=tx&amp;chl=k%3D%20n%5E%7B2%7D\" alt=\"haha\"> and <img src=\"https://chart.googleapis.com/chart?cht=tx&amp;chl=i%20%3D%20%5Cleft%20%5Clfloor%20%5Csqrt%7Bk%7D%20%5Cright%20%5Crfloor\" alt=\"33333\">.<br>\n<br>\n Iterating from j=i down to 1, subtract <img src=\"https://chart.googleapis.com/chart?cht=tx&amp;chl=%20j%5E%7B2%7D\" alt=\"next\"> from <img src=\"https://chart.googleapis.com/chart?cht=tx&amp;chl=%20n%5E%7B2%7D\" alt=\"again!\">. Skip <img src=\"https://chart.googleapis.com/chart?cht=tx&amp;chl=%20n%5E%7B2%7D\" alt=\"againagain\"> particularly.<br>\n<br>\n If that value equals 0, return a list with just i.<br>\n<br>\n Otherwise, recursively call the same method with that value and j. Return a list of that call with j appended to it if it's nonnull, and null otherwise.<br>\n<br>\n If i=0, return <code>null</code>. </p>\n</blockquote>\n\n<p>This methodology guarantees the highest number solution, and doesn't iterate through all permutations. Done right, it'll output the right list or null in order.</p>\n\n<p>So how does this constitute a valid code review? Well, it points out some extraneous points in your solution.</p>\n\n<h3>Couple miscellaneous points</h3>\n\n<p>There is no need to keep a map of integers to their squares. You can iterate down from the highest possible square to 1 and lower your time complexity while maintaining the uniqueness of your output.</p>\n\n<p>You should build the list through return values, rather than modification within a method parameter. The beauty of recursion is the ability to use recursive method evaluations within another call of the same method.</p>\n\n<p>You have 2 variables named <code>sol</code> in different scopes. It's hard to determine where the solution actually goes. I would recommend removing the global scoped <code>sol</code>, and using the above points to return the solution from <code>solutionFinder</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T22:36:38.410", "Id": "433886", "Score": "0", "body": "Thank you for the points you have made here, I will work on reworking the solution with your suggestions, it is still along the same track I was trying to work on. I did want to point out that I do not have two different sol variables, they're both pointing to the globally scoped sol as far as I can tell." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T22:47:19.650", "Id": "433888", "Score": "0", "body": "@CoryHarper ah I see that now. Still an unnecessary global variable though" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T23:47:50.203", "Id": "433891", "Score": "0", "body": "I am a bit confused though, shouldn't i just start j as n - 1? And what method are you referring to when you say, \"recursively call the same method with that value and j\" is it a second method that was called in the for loop where j started as i? Just a bit of clarification, sorry if the questions seem basic" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T23:54:10.710", "Id": "433892", "Score": "0", "body": "Upon writing an answer in code to this problem myself, I would remedy that to be the min of sqrt(k) and i, where i is initialized as n-1. I kinda wrote this all with a train of thought but I was just bored at work between projects so my apologies :) also the list returned when the difference is 0 should have j instead of i. The recursive call should return the answer for the remaining amount where the largest square is j-1. Base case is i=0." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T23:56:23.377", "Id": "433893", "Score": "0", "body": "Don't just use my solution verbatim though, use it as a template for your own. You understand the logical flow you want, take some time to understand _how_ that can translate into code. Plan it out some, don't sweat the details of my answer too much." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T20:27:04.650", "Id": "223767", "ParentId": "223759", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T16:47:36.630", "Id": "223759", "Score": "3", "Tags": [ "javascript", "performance", "algorithm", "programming-challenge", "recursion" ], "Title": "Find A Series of Numbers Who when Squared and Summed are equal to a given Square" }
223759
<h1>Overview</h1> <p>I am attempting to learn Node JS with Express by creating a project.</p> <p>I have seen many examples of setting up an express.js application with functional based programming, like so:</p> <pre><code>// app.js "use strict"; const express = require("express"); const path = require("path"); const mongoose = require("mongoose"); const router = require("./routes/index"); const config = require("../config/config"); const app = express(); // Connect to the database. let dbUser = encodeURIComponent(config.db.username); let dbPass = encodeURIComponent(config.db.password); let dbDatabase = encodeURIComponent(config.db.database); let mongoUri = `mongodb://${dbUser}:${dbPass}@${config.db.host}:${config.db.port}/${dbDatabase}`; mongoose.connect(mongoUri, { useNewUrlParser: true }); app.use(router); // Use the router location. // Set up the views. app.set("views", path.join(__dirname, "views")); app.set("view engine", "ejs"); app.use(express.static(path.join(__dirname, "public"))); // Set the static file location. app.listen(config.server.port); // Start the application on specified port. </code></pre> <h1>Code</h1> <p>Below is the OOP code I have implemented to initialize the express application. The entire project can be found here: <a href="https://github.com/youkergav/MagicConchShellBot" rel="nofollow noreferrer">https://github.com/youkergav/MagicConchShellBot</a></p> <p><em>Please note: While many techniques used in this project are overkill, the overall objective was to better learn Node JS. For all of my questions, please take them as if this were a large scale project, rather than the actual project size.</em></p> <p>App File</p> <pre><code>// app.js "use strict"; const express = require("express"); const Server = require("./lib/server"); let server = new Server; server.initDb(); // Connect to the database. server.initRoutes(); // Use the router location. server.initViews(); // Set up the server views. server.run(); </code></pre> <p>Sever File</p> <pre><code>// lib/server.js "use strict"; class Server { constructor(express) { this.express = express; this.app = this.express(); this.config = require("../../config/config"); } initDb() { const Database = require("./database"); let database = new Database(); database.connect(); } initRoutes() { const Route = require("./route"); const route = new Route(this.app); route.setRoute("../routes/general"); return true; } initViews() { const View = require("./view"); const view = new View(this.express, this.app); view.setViewsLocation("../views"); view.setViewEngine("ejs"); view.setStaticLocation("../public"); return true; } run() { this.app.listen(this.config.server.port); } } module.exports = Server; </code></pre> <p>Database File</p> <pre><code>// lib/database.js "use strict"; class Database { constructor() { this.mongoose = require("mongoose"); this.config = require("../../config/config"); } connect() { let dbUser = encodeURIComponent(this.config.db.username); let dbPass = encodeURIComponent(this.config.db.password); let dbHost = this.config.db.host; let dbPort = this.config.db.port; let dbDatabase = encodeURIComponent(this.config.db.database); let mongoUri = `mongodb://${dbUser}:${dbPass}@${dbHost}:${dbPort}/${dbDatabase}`; this.mongoose.connect(mongoUri, { useNewUrlParser: true }, function(error) { if(error) { console.error(error); return false; } return true; }); } disconnect() { this.mongoose.connection.close(function(error) { if(error) { console.error(error); return false; } return true; }); } } module.exports = Database; </code></pre> <p>Route File</p> <pre><code>// lib/route.js "use strict"; class Routes { constructor(app) { this.app = app; } setRoute(location) { let route = require(location); this.app.use(route); return true; } } module.exports = Routes; </code></pre> <p>View File</p> <pre><code>// lib/view.js "use strict"; class Views { constructor(express, app) { this.express = express; this.app = app; this.path = require("path"); } setViewsLocation(location) { let fullLocation = this.path.join(__dirname, location); this.app.set("views", fullLocation); return true; } setViewEngine(engine) { this.app.set("view engine", engine); return true; } setStaticLocation(location) { let fullLocation = this.path.join(__dirname, location); let staticLocation = this.express.static(fullLocation); this.app.use(staticLocation); return true; } } module.exports = Views; </code></pre> <h1>Questions</h1> <p>I am uncertain if I should be using OOP here. Here are my thoughts and questions...</p> <p>Pros:</p> <ul> <li>Scalable application: <strong>What are some common JS scalability issues? Is this an adequate solution?</strong></li> <li>Cleaner code: <strong>Does this implementation of OOP offer a more obvious way on how the code should function?</strong> </li> <li>Ability to implement JSDocs</li> <li>Ability to perform unit tests</li> </ul> <p>Cons:</p> <ul> <li>JavaScript is a functional based language: <strong>What advantages does a functional implementation have to offer?</strong></li> <li>Added a layer of complexity: <strong>In your opinion, is this code better abstracted, or did I just make it harder to understand?</strong></li> <li>I have not found any online examples of initializing express applications with OOP. <strong>Are there disadvantages to using OOP that I am missing?</strong></li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T07:43:05.663", "Id": "433921", "Score": "0", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T12:28:27.697", "Id": "433967", "Score": "0", "body": "@TobySpeight I have updated the title. Though, I am struggling to make a good title." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T13:26:09.103", "Id": "433969", "Score": "0", "body": "A good title says something about the *purpose* of the code - what it does for its users. \"*Node JS + Express App*\" only tells us about how/where it runs, not about what it's intended to do; the same is true for \"*Implementing OOP*\". What problem does the code solve for the user?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T16:13:42.227", "Id": "433987", "Score": "0", "body": "@TobySpeight By user I'm assuming you mean whoever is looking at the question on this site, and not the user of this specific application. I did not post anything relevant to what the application is doing because my problem can be applied to many applications, not a single application. I guess my actual question would be: Should I be using OOP like this in a node application? Am I over complicating the logic? Or: Am I using OOP in a correct fasion? Why is no one else implement OOP in node like this? Sorry, I don't know how to word this question any better. Am I am the right place here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T16:24:05.360", "Id": "433988", "Score": "0", "body": "No, I meant the person using the program or library. If we have no information about the *real-world purpose* of the program, the question is likely to be closed as having \"insufficient context\" - it appears to be stub or example code rather than a real project. Your specific questions are good ones, and I'd like to see them get answered (that's why I'm trying to help improve it and avoid closure); to achieve that, you need to help reviewers with the context of the code. BTW, sorry my Javascript is too poor to review it myself!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T02:07:51.593", "Id": "434035", "Score": "0", "body": "@TobySpeight Thanks for all the help, I really appreciate it. I have updated my question to best communicate my problems, and provide real-world context. Please let me know what you think." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T14:49:42.437", "Id": "434104", "Score": "0", "body": "You might want to take a look at this site https://medium.com/@andrea.chiarelli/is-javascript-a-true-oop-language-c87c5b48bdf0. At the moment your question is too broad. You might want to create some models for your objects. You also might want to encapsulate a little more in your database model." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T15:18:43.080", "Id": "434111", "Score": "0", "body": "@pacmaninbw Thanks you for the information. While I understand my project is lacking code, I fear that if I add more code I will realize later that the best solution is functional programming. I am trying to pose the question before getting into that predicament. Additionally, question is related to initializing express applications, not what the project's code is doing in the real world. Maybe my question is better suited on Stack Overflow?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T15:31:41.520", "Id": "434114", "Score": "0", "body": "Node.js, jQuery and other JavaScript libraries are object oriented. When I suggested creating models I didn't mean for the question, I meant for yourself. In JavaScript a function is an object, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions. People who only program functionally in JavaScript don't know enough about the language or the problem is too simple to need it." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T18:16:48.530", "Id": "223765", "Score": "2", "Tags": [ "javascript", "object-oriented", "node.js", "express.js" ], "Title": "Initializing a Node JS Express Application with OOP" }
223765
<p>This is the first time I have programmed something that I will actually personally use, so I am happy about that. I tried to write good code whilst applying functional programming concepts. So no state, and a concise function. </p> <p>I know that when making the lists it pulls information from the JSON that doesn't get used later in the program. The data will be used once I get continue to develop the program further.</p> <p>At the end there is a dictionary containing hero ID keys and name values. I cut out most of it to minimize the length of this post. </p> <pre><code>import json import requests def parsestats(herodata): return [(hero['heroId'], hero['pickBan']['pick']['matchCount']/ # Divide by next line herodata['matchPickCount']*1000, hero['pickBan']['ban']['matchCount']/ # Divide by next line herodata['matchBanCount']*1000, hero['pickBan']['pick']['wins']*100, hero['pickBan']['ban']['wins']*100, hero['pickBan']['pickLastWeek']['matchCount']/ # Divide by next line herodata['matchLastWeekPickCount']*1000, hero['pickBan']['banLastWeek']['matchCount']/ # Divide by next line herodata['matchLastWeekBanCount']*1000, hero['pickBan']['pickLastWeek']['wins']*100, hero['pickBan']['banLastWeek']['wins']*100) for hero in herodata['heroes']] print(f"{'Hero,':&lt;20}{'Value':&gt;7}") for hero in sorted( [(uni[0], imm[1]*((uni[3] if uni[3] &gt; imm[3] else imm[3])-50)) for uni, imm in zip( sorted(parsestats(json.loads(requests.get( 'https://api.stratz.com/api/v1/Hero/directory/simple').text))), sorted(parsestats(json.loads(requests.get( 'https://api.stratz.com/api/v1/Hero/directory/simple?rank=8').text)))) ], key=lambda tup: tup[1], reverse = True): print("{:&lt;20}{:&gt;7.2f}".format({1: 'Anti-Mage', 2: 'Axe', 3: 'Bane', 4: 'Bloodseeker', 5: 'Crystal Maiden', 6: 'Drow Ranger', 7: 'Earthshaker', 8: 'Juggernaut', 9: 'Mirana', 10: 'Morphling', 11: 'Shadow Fiend', 12: 'Phantom Lancer', 13: 'Puck', 14: 'Pudge', 15: 'Razor', 16: 'Sand King', 17: 'Storm Spirit', 18: 'Sven', 19: 'Tiny', 20: 'Vengeful Spirit', 21: 'Windranger', 22: 'Zeus', 23: 'Kunkka', 25: 'Lina', 26: 'Lion', 27: 'Shadow Shaman', 28: 'Slardar', 29: 'Tidehunter', 30: 'Witch Doctor', 31: 'Lich', 32: 'Riki', 33: 'Enigma', 34: 'Tinker', 35: 'Sniper', 36: 'Necrophos', 37: 'Warlock', 38: 'Beastmaster',39: 'Queen of Pain', 40: 'Venomancer', 41: 'Faceless Void', 42: 'Wraith King', 43: 'Death Prophet', 44: 'Phantom Assassin', 45: 'Pugna', 46: 'Templar Assassin', 47: 'Viper', 48: 'Luna', 49: 'Dragon Knight', 50: 'Dazzle', 51: 'Clockwerk', 52: 'Leshrac', 53: 'Nature\'s Prophet', 54: 'Lifestealer', 55: 'Dark Seer', 56: 'Clinkz', 57: 'Omniknight', 58: 'Enchantress', 59: 'Huskar', 60: 'Night Stalker', 61: 'Broodmother', 62: 'Bounty Hunter', 63: 'Weaver', 64: 'Jakiro', 65: 'Batrider', 66: 'Chen', 67: 'Spectre', 68: 'Ancient Apparition', 69: 'Doom', 70: 'Ursa', 71: 'Spirit Breaker', 72: 'Gyrocopter', 73: 'Alchemist', 74: 'Invoker', 75: 'Silencer', 76: 'Outworld Devourer', 77: 'Lycan', 78: 'Brewmaster', 79: 'Shadow Demon', 80: 'Lone Druid', 81: 'Chaos Knight', 82: 'Meepo', 83: 'Treant Protector', 84: 'Ogre Magi', 85: 'Undying', 86: 'Rubick', 87: 'Disruptor', 88: 'Nyx Assassin', 89: 'Naga Siren', 90: 'Keeper of the Light', 91: 'Io', 92: 'Visage', 93: 'Slark', 94: 'Medusa', 95: 'Troll Warlord', 96: 'Centaur Warrunner', 97: 'Magnus', 98: 'Timbersaw', 99: 'Bristleback', 100: 'Tusk', 101: 'Skywrath Mage', 102: 'Abaddon', 103: 'Elder Titan', 104: 'Legion Commander', 105: 'Techies', 106: 'Ember Spirit', 107: 'Earth Spirit', 108: 'Underlord', 109: 'Terrorblade', 110: 'Phoenix', 111: 'Oracle', 112: 'Winter Wyvern', 113: 'Arc Warden', 114: 'Monkey King', 119: 'Dark Willow', 120: 'Pangolier', 121: 'Grimstroke', 129: 'Mars'}[hero[0]], hero[1])) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T21:57:49.273", "Id": "433879", "Score": "1", "body": "Do you have a Javascript background? Seems like you are trying to minify your code in order to reduce bandwith usage ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T22:00:39.993", "Id": "433880", "Score": "0", "body": "@AlexV No I don't have any experience with Javascript." } ]
[ { "body": "<p>What a wall of text! Also known as write-only code, or job security.</p>\n\n<p>You want to write understandable code, that you can come back to in 6 months, and within 5 minutes understand enough to change it, if necessary. This has a for-loop over a sorted list comprehension, with embedded if-then-else, of a zip of two sorted json queries, with a lambda thrown in to influence sorting. This isn't functional programming; it's dysfunctional programming.</p>\n\n<hr>\n\n<p>Let me begin with <code>parsestats</code>, because I can at least begin to understand it.</p>\n\n<p>First, the name <code>parsestats</code> is itself a wall of characters. How do I pronounce that word? \"par-sest-ats\"? Oh! \"parse stats\"! Write function names with <code>snake_case</code>, to aid the reader find the words in your compound name. So this function should be called <code>parse_stats</code>.</p>\n\n<p>In this function, you repeat <code>hero['pickBan']</code> 8 times. This is a lot of repetition. It means the Python interpreter is looking up the same element in a dictionary repeatedly, which means the code is not going to win any speed contests. Look up the value once, and reuse that value, instead of relooking it up over and over again. This is awkward to do in a list comprehension, so lets use a helper function:</p>\n\n<pre><code>def parse_stats(herodata):\n\n def stats(hero_id, pick_ban):\n # ... TBD ... \n\n return [ stats(hero['heroId'], hero['pickBan']) for hero in herodata['heroes']]\n</code></pre>\n\n<p>A 14-line list comprehension just got turned into a 1 line list comprehension, and <code>hero['pickBan']</code> got stored in the function argument <code>pick_ban</code>, for reuse multiple times. I'm liking the direction this is going.</p>\n\n<p>Now, what stats are being collected? Looks like you've got 8 stats: 4 from this week, and the same 4 from the previous week. Maybe we could compute those 4 stats in a function, passing in different selectors to grab the correct data?</p>\n\n<pre><code>def parse_stats(herodata):\n\n def stats(hero_id, pick_ban):\n\n def week_stats(pick, ban, pick_count, ban_count):\n\n return pick_ban[pick]['matchCount'] / pick_count * 1000,\n pick_ban[ban]['matchCount'] / ban_count * 1000,\n pick_ban[pick]['wins'] * 100,\n pick_ban[ban]['wins'] * 100\n\n this_week = week_stats('pick', 'ban', this_week_pick, this_week_ban)\n last_week = week_stats('pickLastWeek', 'banLastWeek', last_week_pick, last_week_ban)\n\n return hero_id, *this_week, *last_week\n\n this_week_pick = herodata['matchPickCount']\n this_week_ban = herodata['matchBanCount']\n last_week_pick = herodata['matchLastWeekPickCount']\n last_week_ban = herodata['matchLastWeekBanCount']\n\n return [ stats(hero['heroId'], hero['pickBan']) for hero in herodata['heroes']]\n</code></pre>\n\n<p>Is that the clearest way? Maybe we want to use a <code>when</code> selector, instead:</p>\n\n<pre><code>def parse_stats(herodata):\n\n def stats(hero_id, pick_ban):\n\n def stats_for(when):\n\n pick = pick_ban[f'pick{when}']\n ban = pick_ban[f'ban{when}']\n\n return pick['matchCount'] / herodata[f'match{when}PickCount'] * 1000,\n ban['matchCount'] / herodata[f'match{when}BanCount'] * 1000,\n pick['wins'] * 100,\n ban['wins'] * 100\n\n this_week = stats_for('')\n last_week = stats_for('LastWeek')\n\n return hero_id, *this_week, *last_week\n\n return [ stats(hero['heroId'], hero['pickBan']) for hero in herodata['heroes']]\n</code></pre>\n\n<p>Which would make it easier to select <code>'LastMonth'</code> stats, too.</p>\n\n<hr>\n\n<p>Is a <code>tuple</code> really the best data structure for <code>parse_stats</code> to return? The 0th element is the hero id. What is the 2nd element? Which element is last week's pick win percentage? What is <code>[1]</code>, or <code>[3]</code>?</p>\n\n<p>How about using a <a href=\"https://docs.python.org/3/library/collections.html#collections.namedtuple\" rel=\"nofollow noreferrer\"><code>namedtuple</code></a>?</p>\n\n<pre><code>from collections import namedtuple\n\nStats = named tuple('Stats',\n ('id',\n 'pick_rate', 'ban_rate', 'pick_wins', 'ban_wins',\n 'pick_rate_last_week', 'ban_rate_last_week', 'pick_wins_last_week', 'ban_wins_last_week'))\n\n# ...\n\ndef parse_stats(herodata):\n def stats(hero_id, pick_ban):\n # ...\n return Stats(hero_id, *this_week, *last_week)\n</code></pre>\n\n<p>Or maybe make a tuple of tuples.</p>\n\n<pre><code>Stats = namedtuple('Stats', 'id, this_week, last_week')\nWeekStats = namedtuple('WeekStats', 'pick_rate, ban_rate, pick_wins, ban_wins')\n\ndef parse_stats(herodata):\n def stats(hero_id, pick_ban):\n # ...\n return Stats(hero_id, WeekStats(*this_week), WeekStats(*last_week))\n</code></pre>\n\n<p>And you can refer to <code>uni.id</code> and <code>imm.this_week.pick_rate</code> instead of <code>uni[0]</code> and <code>imm[1]</code>.</p>\n\n<hr>\n\n<p>Ok, the elephant in the program:</p>\n\n<pre><code>print(f\"{'Hero,':&lt;20}{'Value':&gt;7}\")\nfor hero in sorted(ridiculous_list_comprehension, key=lambda tup: tup[1], reverse = True):\n print(\"{:&lt;20}{:&gt;7.2f}\".format(inline_dictionary_definition[hero[0]], hero[1]))\n</code></pre>\n\n<p>First off, this should be a function, not code executed when Python parses the program text. Use a <code>if __name__ == '__main__':</code> guard call the function if you want the code executed immediately upon parsing:</p>\n\n<pre><code>def print_mashup():\n print(f\"{'Hero,':&lt;20}{'Value':&gt;7}\")\n for hero in sorted(ridiculous_list_comprehension, key=lambda tup: tup[1], reverse = True):\n print(\"{:&lt;20}{:&gt;7.2f}\".format(inline_dictionary_definition[hero[0]], hero[1]))\n\nif __name__ == '__main__':\n print_mashup()\n</code></pre>\n\n<p>Of course, name the function according to what it really is doing.</p>\n\n<pre><code>for hero in sorted(...):\n</code></pre>\n\n<p>Uhm, no. The output of <code>sorted()</code> isn't a list of <code>hero</code> objects. You parsed all that <code>hero</code> data in <code>parse_stats</code>, and this is a much condensed summary of two values of those statistics, combined from two different data sets. It is a list of two-value tuples. Give those individual values names:</p>\n\n<pre><code>for hero_id, score in sorted(...):\n</code></pre>\n\n<p>I'm guess the \"value\" is some kind of score. Maybe <code>rating</code> is a better name. At any rate, this is way more descriptive than the <code>hero[0]</code> and <code>hero[1]</code> references made in the print statement of the body of the loop.</p>\n\n<pre><code> print(\"{:&lt;20}{:&gt;7.2f}\".format(inline_dictionary_definition[hero[0]], hero[1]))\n</code></pre>\n\n<p>Is that <code>inline_dictionary_definition</code> being constructed each and every iteration of the body of the <code>for</code> loop, so that one value can be extracted from the dictionary? Be kind. Create it once.</p>\n\n<pre><code>def print_mashup():\n print(f\"{'Hero,':&lt;20}{'Value':&gt;7}\")\n\n HERO_BY_ID = {1: 'Anti-Mage', 2: 'Axe', ... 129: 'Mars'}\n\n for hero_id, score in sorted(ridiculous_list_comprehension, key=lambda tup: tup[1], reverse = True):\n print(f\"{HERO_BY_ID[hero_id]:&lt;20}{score:&gt;7.2f}\")\n</code></pre>\n\n<p>As for the <code>ridiculous_list_comprehension</code>, I haven't a clue what <code>\"simple\"</code> is compared to <code>\"simple?rank=8\"</code>, or what the calculated value is supposed to mean. Or what <code>uni</code> and <code>imm</code> are supposed to be abbreviations for. There are all sorts of unknowns. Do the json queries return exactly the same <code>hero_id</code> sets? Can there be an extra one in either of the sets, in which case sorting and zipping doesn't guarantee the data matches up properly!</p>\n\n<p>I'm happy that you're happy to have written a program that you will personally use. I'd be happier if someone else could understand it, and use it too.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T19:24:26.257", "Id": "434006", "Score": "0", "body": "\"write-only code\" absolutely made my day. When I was looking at the code yesterday I was baffled! Only after letting the auto-formatter work it's magic, I saw light on the horizon." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T01:55:41.677", "Id": "434034", "Score": "0", "body": "Hi I just wanted to tell you that I implemented the changes you have suggested, and also developed the program further. If you want to take a look [here it is](https://github.com/tonijarjour/Dota-Stats/blob/master/parser.py). Still working on it of course. Thank you very much for your help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T17:06:21.743", "Id": "434123", "Score": "0", "body": "Looks much better. When you've made more progress, you can of course make a new post here with the updated code. Be sure to include a link back to this question and add a comment on this question linking to the new question." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T05:07:09.947", "Id": "223781", "ParentId": "223769", "Score": "3" } } ]
{ "AcceptedAnswerId": "223781", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T20:57:07.143", "Id": "223769", "Score": "2", "Tags": [ "python", "parsing", "functional-programming", "json", "api" ], "Title": "JSON Parser, pulls data from a JSON file for analysis" }
223769
<p>I have a model that is in a HABTM relationship with 2 other models:</p> <p>Activity.rb</p> <pre><code> has_and_belongs_to_many :mandates, -&gt; { distinct } has_and_belongs_to_many :contacts, -&gt; { distinct } </code></pre> <p>I had to add the following callbacks, since the models defined above have a 'score algorithm' that must be recomputed if activities are removed completely, or one is created initially:</p> <pre><code> after_commit :increase_contact_scores, :increase_mandate_scores after_destroy :decrease_contact_scores, :decrease_mandate_scores </code></pre> <p>The callbacks code seems horribly the same. Is there a way to simplify this by somehow passing the HABT relation class from the callback to a more 'generic' method that can replace these?</p> <p>I also need to figure out how to ONLY trigger the relevant callback based on the type of the HABTM (ie. not call both increases and both decreases, since if a <code>mandate</code> is destroyed, calling the <code>decrease_contacts_score</code> method will fail).</p> <pre><code> def increase_contact_scores contacts.each do |contact| if contact.activities.count == 1 contact.calculate_score contact.save! end end end def increase_mandate_scores mandates.each do |mandate| if mandate.activities.count == 1 mandate.calculate_score mandate.save! end end end def decrease_contact_scores contacts.each do |contact| if mandate.activities.count.zero? contact.calculate_score contact.save! end end end def decrease_mandate_scores mandates.each do |mandate| if mandate.activities.count.zero? mandate.calculate_score mandate.save! end end end </code></pre>
[]
[ { "body": "<p>In testing this code it turned out there is a chicken-and-egg situation, and more specific requirements. </p>\n\n<p>In order to know which object (<code>Contact</code> or <code>Mandate</code>) to update the score for, the <code>Activity</code> callbacks need more 'knowledge':</p>\n\n<p>eg. 2 cases:</p>\n\n<p>1 <code>Contact A</code> has 0 activities -></p>\n\n<p><em>if an activity is created, recalculate the score for A</em></p>\n\n<p>2 <code>Contact A</code> has > 0 activities -></p>\n\n<p><em>if an activity is created, no need to recalculate the score</em></p>\n\n<p><em>if an activity is deleted, recalculate the score only if activities = 0</em></p>\n\n<p>The same is true for <code>Mandate</code>.</p>\n\n<p>So, I ended up with a cleaner solution, with drier code:</p>\n\n<p>Activity.rb</p>\n\n<pre><code> before_commit :mark_objects_for_rescoring, on: :create\n before_destroy :mark_objects_for_rescoring\n after_commit :rescore_objects, on: [:create, :destroy]\n\n after_initialize do\n self.contacts_to_recalculate = []\n end\n\n private\n\n def mark_objects_for_rescoring\n contacts.each do |contact|\n contacts_to_recalculate &lt;&lt; contact.id if contact.activities.count == 1\n end\n mandates.each do |mandate|\n mandates_to_recalculate &lt;&lt; mandate.id if mandate.activities.count == 1\n end\n end\n\n def rescore_objects\n contacts_to_recalculate.each do |id|\n contact = Contact.find(id)\n contact.calculate_score\n contact.save!\n end\n contacts_to_recalculate.each do |id|\n mandate = Contact.find(id)\n mandate.calculate_score\n mandate.save!\n end\n end\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T07:41:37.843", "Id": "223789", "ParentId": "223770", "Score": "0" } } ]
{ "AcceptedAnswerId": "223789", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T21:45:44.920", "Id": "223770", "Score": "1", "Tags": [ "ruby", "ruby-on-rails", "active-record" ], "Title": "Rails 5.2 callbacks to trigger score recalculation for relationships" }
223770
<p>Improved upon my previous calculator program. This program has the following features:</p> <ol> <li><p>Gives information using session prompts.</p></li> <li><p>Supports all common operators.</p></li> <li><p>Follows operator precedence.</p></li> <li><p>Use of identifiers is supported.</p></li> <li><p>Result of the previous expression can accessed by using the 'r' identifier.</p></li> <li><p>Special commands:</p> <ol> <li>n: Stars a new session. Deletes all previous identifiers.</li> <li>q: Quits the program</li> </ol></li> </ol> <p>The code describes the features in more detail.</p> <p>Issues:</p> <ol> <li>No useful information is given to the user if any error occurred.</li> </ol> <p>Other Information:</p> <ol> <li><p>Ditched the earlier use of <code>eval()</code> to evaluate expressions because of security reasons.</p></li> <li><p>Avoids the endless function call chain used earlier that could hit the recursion limit albeit after a long while by using a loop.</p></li> </ol> <p>My Previous calculator: <a href="https://codereview.stackexchange.com/questions/220098/a-simple-python3-calculator">A simple python3 calculator</a></p> <p>Also uploaded the code on pastebin: <a href="https://pastebin.com/WW25hWn7" rel="nofollow noreferrer">https://pastebin.com/WW25hWn7</a></p> <pre><code>import sys import math usage_notes = """ 1. Session prompts: 1. n: New session 2. c: Current session 2. Supported operators: +, -, *, /, ^, ! 3. Precedence: 1. Parenthesization 2. Factorial 3. Exponentiation 4. Multiplication and Divison 5. Addition and Subtraction 4. Use of identifiers is supported. Use commas to separate them: n: a=10,b=5 c: a+b -&gt; 15 5. Result of the previous expression can accessed by using the 'r' identifier: n: 2+3 -&gt; 5 c: r+10 -&gt; 15 6. Special commands: 1. n: Stars a new session. Deletes all previous identifiers. 2. q: Quits the program """ identifiers = {} def start(): # Creates a prompt dictionary to differentiate sessions. # Starts the main loop of the program. # Takes the input from the user and calls controller(). prompts = { 'n': 'n: ', 'c': 'c: ', } prompt = prompts['n'] while True: expr = input(prompt) if expr == 'q': break elif expr == 'n': prompt = prompts['n'] identifiers.clear() else: res = controller(expr) if res == 'e': print('error: invalid expression\n') elif res == 'i': prompt = prompts['c'] else: print('-&gt; ' + identifiers['r'] + '\n') prompt = prompts['c'] def controller(expr): # Calls create_identifiers or passes the expr to get_postfix() # to be converted into a postfix expression list. And, calls # postfix_eval() for evaluation. All the Exceptions # are terminated, so the main loop keeps running. try: if '=' in expr: return create_identifiers(expr) postfix_expr = get_postfix(expr) return postfix_eval(postfix_expr) except Exception: return 'e' def create_identifiers(expr): # Identifiers are implemented as a global dictionary. First, # the string is split using ',' as a delimiter. The resulting # substring are separated using '='. First substring is assigned # as a key with second substring as the value. expr_list = expr.replace(' ', '').split(',') for stmt in expr_list: var, val = stmt.split('=') identifiers[var] = val return 'i' def get_postfix(expr): # Converts infix expressions to postfix expressions to remove ambiguity. # Example: a+b*c -&gt; abc*+ # Remove all the spaces in the given expression. expr = expr.replace(' ', '') sep_str = '' # Insert spaces only around supported operators, so splitting # can be done easily later. for a_char in expr: if a_char in '+-*/^!()': sep_str += ' %s ' % a_char else: sep_str += a_char # Use the default space as the delimiter and split the string. token_list = sep_str.split() # Only operators are pushed on to the op_stack, digits and identifiers # are appended to the postfix_list. op_stack = [] postfix_list = [] prec = {} prec['!'] = 5 prec['^'] = 4 prec['/'] = 3 prec['*'] = 3 prec['+'] = 2 prec['-'] = 2 prec['('] = 1 # The current operator's precedence in the loop is compared with the # operators in the stack. If it's higher, it's pushed on the stack. # If it less than or equal, the operators are popped until the # precedence of the operator at the top is less than the # current operators'. # When parentheses are used, ')' forces all the operators above '(' # to be popped. # Whenever an operator is popped it's appended to the postfix_list. for token in token_list: if isnum(token) or token.isalpha(): postfix_list.append(token) elif token == '(': op_stack.append(token) elif token == ')': top_token = op_stack.pop() while top_token != '(': postfix_list.append(top_token) top_token = op_stack.pop() else: while op_stack != [] and \ (prec[op_stack[-1]] &gt;= prec[token]): postfix_list.append(op_stack.pop()) op_stack.append(token) while op_stack != []: postfix_list.append(op_stack.pop()) return postfix_list def postfix_eval(postfix_list): # Similar stack based approach is used here for evaluation. If a # identifier or digit is found, push it on the operand_stack. If # an operator is found, use it on the last two operands or the last # in case of '!', and append the result on the stack. operand_stack = [] for val in postfix_list: if isnum(val): operand_stack.append(float(val)) elif val.isalpha(): val = identifiers[val] operand_stack.append(float(val)) elif val in '+-*/^!': if val != '!': op2 = operand_stack.pop() op1 = operand_stack.pop() res = calc(op1, val, op2) operand_stack.append(res) else: op = operand_stack.pop() res = math.factorial(op) operand_stack.append(res) res = operand_stack[-1] int_res = int(res) if int_res == res: res = int_res identifiers['r'] = str(res) def isnum(val): # Used as a helper function to check if the argument is a number. try: float(val) return True except Exception: return False def calc(op1, op, op2): # Performs the operation on the operands and returns the result. if op == '+': return op1 + op2 elif op == '-': return op1 - op2 elif op == '*': return op1 * op2 elif op == '/': return op1 / op2 elif op == '^': return op1 ** op2 if sys.argv[-1] == 'n': print(usage_notes) start() </code></pre> <p>Sample output:</p> <pre><code>n: 1+5 -&gt; 6 c: r -&gt; 6 c: r*10+50*(3-1)-100 -&gt; 60 c: r -&gt; 60 c: a=50,b=10 c: r+a+b -&gt; 120 c: n n: 2^3+5! -&gt; 128 c: 1 +- 2 error: invalid expression c: q </code></pre> <p>I am looking for ways to make the code more readable, minimize redundancy, improving the overall design, performance improvements, etc. Any help would be appreciated!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T00:17:51.900", "Id": "433896", "Score": "2", "body": "Those don't look like postfix expressions to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T09:22:01.830", "Id": "433935", "Score": "0", "body": "@200_success are you talking about the expressions in the sample output? If yes, the calculator takes in infix expressions, converts them to postfix, and then processes them. If you are referring to something else, please let me know." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T19:58:58.863", "Id": "434009", "Score": "0", "body": "@sg7610 Maybe a better title would be \"Calculator with infix to postfix conversion\" ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T16:08:11.613", "Id": "434121", "Score": "0", "body": "@422_unprocessable_entity Yes. My bad." } ]
[ { "body": "<p>First, the most glaring thing I see is your use of catch-all exception handlers:</p>\n\n<pre><code>def controller(expr):\n . . .\n # . . . All the Exceptions\n # are terminated, so the main loop keeps running. \n . . .\n except Exception:\n return 'e'\n\n. . .\n\nres = controller(expr)\n\nif res == 'e':\n print('error: invalid expression\\n')\n</code></pre>\n\n<p>I have to <strong>strongly</strong> caution against this practice. You're treating every exception that may possibly come up as though it's caused by a runtime error stemming from bad user input. This is a very dangerous assumption, and <em>will</em> bite you eventually.</p>\n\n<p>In this case, why is it such a big deal? Inside the <code>try</code>, you're calling three different functions, and all of those functions call several other functions. Lets say in the future you decide to modify one of the many functions that are called as a result of calling <code>controller</code>, and lets say you accidentally introduce a bug. In a normal workflow, you'd try to run <code>controller</code> as a test, it would fail horribly because you wrote something incorrect somewhere, and you can use the resulting stack trace to diagnose what caused the problem.</p>\n\n<p>With how you have it here, you would run it... and it would complain about an invalid expression being entered. How much information does that give you about what happened? Throwing away the clues that help you debug a problem will only make your life more difficult once you start writing larger programs and start encountering hard-to-reproduce bugs.</p>\n\n<p>The better way to approach this is to specify the exact exception that you expect to catch instead of using a catch-all <code>Exception</code>. If you expect a <code>ValueError</code> to be thrown if the expression was poorly formed, catch that. That way any other exception that may be raised will still come through. A broken program crashing is a good thing. Let it fail so you can fix it.</p>\n\n<p>The same problem, but to a lesser extent can be seen in <code>isnum</code> (which I'd rename to at least <code>is_num</code>):</p>\n\n<pre><code>def is_num(val):\n # Used as a helper function to check if the argument is a number.\n try:\n float(val)\n return True\n except Exception:\n return False\n</code></pre>\n\n<p><code>float</code> seems to only throw two types of exceptions; and only one of them seems relevant here. Change the catch to <code>except ValueError</code>. This isn't a big deal right now since only the call to <code>float</code> is inside the <code>try</code>, but if you add anything later you're opening yourself up to silent failings.</p>\n\n<p>In this code, catch-all exceptions won't be the end of the world. They are a bad habit to get into though, and don't encourage a safe mindset. Be aware of what exceptions the code you're using can throw and react accordingly. Catching everything is just a band-aid. </p>\n\n<p>I'd also space your code out a bit. I personally like empty lines after \"bodies\" of code, like the bodies of a <code>if...else</code>, or a <code>try...except</code>:</p>\n\n<pre><code>def is_num(val):\n try:\n float(val)\n return True\n\n except Exception:\n return False\n\ndef controller(expr):\n try:\n if '=' in expr:\n return create_identifiers(expr)\n\n postfix_expr = get_postfix(expr)\n return postfix_eval(postfix_expr)\n\n except Exception:\n return 'e'\n</code></pre>\n\n<p>I like giving discrete parts some breathing room. I find it helps readability.</p>\n\n<hr>\n\n<pre><code>prec = {}\nprec['!'] = 5\nprec['^'] = 4\nprec['/'] = 3\nprec['*'] = 3\nprec['+'] = 2\nprec['-'] = 2\nprec['('] = 1\n</code></pre>\n\n<p>This could be written as a literal, and I think it would be neater as a result:</p>\n\n<pre><code>prec = {'!': 5,\n '^': 4,\n '/': 3,\n '*': 3,\n '+': 2,\n '-': 2,\n '(': 1}\n</code></pre>\n\n<hr>\n\n<p>Your use of global <code>identifiers</code> isn't ideal. I'd prefer to pass a state around using an explicit parameter to any functions that require access to <code>identifiers</code>. That would make testing functions that use <code>identifiers</code> much easier. With how you have it now, whenever you want to test a function like <code>postfix_eval</code> that uses <code>identifiers</code>, you need to make sure to do <code>identifiers = some_test_state</code> before your call. If it were a parameter, its dependencies would be explicit, and it wouldn't require accessing a global mutable state.</p>\n\n<hr>\n\n<p>A lot of your functions start with some comments that describe the action of the function:</p>\n\n<pre><code>def calc(op1, op, op2):\n # Performs the operation on the operands and returns the result.\n</code></pre>\n\n<p>This is a good habit to get in. Python has a standardized convention though to handle comments intended for the end-user of the function: <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstrings</a>. Right after the function \"signature\", have a (triple) String literal instead of using <code>#</code> line comments. IDEs will grab this information and allow it to be accessed easier by callers.</p>\n\n<pre><code>def calc(op1, op, op2):\n \"\"\" Performs the operation on the operands and returns the result. \"\"\"\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T22:57:13.897", "Id": "223775", "ParentId": "223772", "Score": "3" } } ]
{ "AcceptedAnswerId": "223775", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T22:08:17.670", "Id": "223772", "Score": "4", "Tags": [ "python", "python-3.x", "calculator", "math-expression-eval" ], "Title": "Python Calculator using Postfix Expressions" }
223772
<p>I use self-closing bodyless for loop to quickly find an element within an array or collection. Learned it from a Java teacher. But I'm seeing warnings on certain IDEs that have a code inspection tool. For example, IntelliJ deems this construct to be a probable bug and objects to the empty body of the loop.</p> <p>The code below compares a bodied and bodyless <strong>for</strong> loop on an array with ~9,000 String entries. From the output, it seems that there's a 3 x time advantage in having the <strong>for</strong> loop bodyless.</p> <p>But is there a real insecurity in this construct ? I ask as I'm very partial to using it.</p> <pre><code> String[] stArray = {"arsch", "a1", "a2", "b1", "c2", "c1", ..................................... ..................................... ..................................... "arsch", "a1", "a2", "b1", "c2", "c1"}; long startTime1 = System.nanoTime(); int i; for(i = 0; i &lt; stArray.length; i++) if (stArray[i] == "bozo") break; if (i &lt; stArray.length) System.out.println("Item at index #" + i); else System.out.println("Item not in array."); long endTime1 = System.nanoTime(); long duration1 = endTime1 - startTime1; long startTime2 = System.nanoTime(); for(i = 0; i &lt; stArray.length &amp;&amp; stArray[i] != "bozo"; i++); if (i &lt; stArray.length) System.out.println("Item at index #" + i); else System.out.println("Item not in array."); long endTime2 = System.nanoTime(); long duration2 = endTime2 - startTime2; System.out.println("Duration1: " + duration1); System.out.println("Duration2: " + duration2); System.out.println("Array Size: " + stArray.length); OUTPUT ====== Item not in array. Item not in array. Duration1: 765700 Duration2: 221000 Array Size: 9132 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T00:16:40.430", "Id": "433895", "Score": "1", "body": "The way you have currently formulated the question, it seems to be asking for opinions about a particular looping style, with some code thrown in merely as an example. If you want your code to be reviewed, please describe in detail what specific task it accomplishes, and retitle the question according to the [ask] guidelines. (Based on my guess at what you want to accomplish, I'm not convinced that the code actually does the job correctly.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T08:38:52.040", "Id": "433931", "Score": "0", "body": "I apologize if this is the wrong forum. I'd thought that this forum would have readers who were more knowledgeable in code efficiency. As you suggest, this code is just a demonstration snippet as the method it's used in (a sort of *mergeInVocab(. .)* method used in text analysis) is really beside the point for this question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-23T14:27:15.700", "Id": "435973", "Score": "0", "body": "Done detailed comparisons with bodyless and bodied **for** loop plus while loop. Found no significant advantage with bodyless **for**. Perhaps best not used." } ]
[ { "body": "<p>IntelliJ reports:</p>\n\n<blockquote>\n <p>. . . While occasionally intended, this construction is confusing, and often the result of a typo.</p>\n</blockquote>\n\n<p>I agree with the first part, but it's letting you know about this mainly for the second part. It's pretty common on Stack Overflow to see problems arise from people putting a semicolon in weird places and having odd behavior as a result:</p>\n\n<blockquote>\n <p>Why does this code only print once?</p>\n\n<pre><code>for(int i = 0; i &lt; 10; i++); {\n System.out.println(\"Text\");\n}\n</code></pre>\n</blockquote>\n\n<p>An IDE warning would have given hints as to what the problem was.</p>\n\n<hr>\n\n<p>Like I said though, I agree with it pointing this out for reasons other than a typo too. I personally find it to read less explicitly. To me, the body represents what the purpose/action of the loop is, and the parenthesized part before the body states the bounds of the problem being dealt with by the loop.</p>\n\n<p>I find your preferred way to be forcing too much onto one line, and I generally find it less clear. The full version is quite explicit (I added braces to avoid a whole other set of problems that IntelliJ likely warned you about):</p>\n\n<pre><code>// Standard index bounds. Nothing to think about\nfor(i = 0; i &lt; stArray.length; i++) {\n if (stArray[i] == \"bozo\") {\n break; // Break when i points to \"bozo\". Easy\n }\n}\n\n// Loop while i is in bounds... and i doesn't point to \"bozo\"\n// Oh, break when it points to \"bozo\"\nfor(i = 0; i &lt; stArray.length &amp;&amp; stArray[i] != \"bozo\"; i++);\n</code></pre>\n\n<p>It honestly took me longer to mentally verify the correctness of your shorter version.</p>\n\n<p>Also, what if you wanted to add debugging prints or something else to the loop? You'd need to add a body in that case anyway. And are you going to keep the <code>&amp;&amp; stArray[i] != \"bozo\"</code> part once you have a body?</p>\n\n<hr>\n\n<p>I'd also take your benchmarking with a grain of salt. <a href=\"https://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java\">Java is not a simple language to do micro-benchmarking on</a>, and it's more likely that your measured speedup is a result of a fluke, or from the first loop having warmed up the JVM first.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T08:54:39.417", "Id": "433933", "Score": "0", "body": "That JetBrains comment [https://confluence.jetbrains.com/display/GRVY/Inspections] on for-loops reads to me as an admonishment against *assignments* within the top line of a for statement or empty bodied for-loops. I've seen code where people summed or multiplied an index and I agree it's hazardous and quizzical." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-13T20:34:37.090", "Id": "434657", "Score": "0", "body": "Right about JVM sluggishness, @Carci. Just did test on String and int values in an array with up to 100,000,000 entries. Little to choose between bodyless, bodied for loops and the equivalent while. The bodied for loop is ~ 20 ms faster on average for String data and about the same margin slower on int data. Case complete, it seems." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T00:34:54.850", "Id": "223778", "ParentId": "223773", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T22:46:14.983", "Id": "223773", "Score": "-2", "Tags": [ "java", "performance", "security" ], "Title": "Bodyless Self-Closing *for* Loop" }
223773
<p>In language dictionary application users can add new words and do other staff with this word such as adding additional information to the word (description, etymology, speech parts, noun class etc.) I'll count all this information and maybe later create some application gamification based on this information. I decided to create custom model and count all this contribution inside this model. There are one base abstract model which defines common fields:</p> <pre><code>class BaseModel(models.Model, ModelDiffMixin): WORD_MODERATE_STATUS = [ ('UNDER_CONCIDERATION', 'under consideration'), ('PREVIOUSLY_ACCEPTED', 'previously accepted') ] moderate_status = models.CharField( max_length=50, choices=WORD_MODERATE_STATUS, blank=True) created_on = models.DateTimeField(auto_now_add=True) modified_on = models.DateTimeField(auto_now=True) created_by = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, related_name='%(class)s_createdby') modified_by = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, related_name='%(class)s_modifiedby', null=True, blank=True) accepted = models.BooleanField(default=False) accepted_by = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, related_name='%(class)s_acceptedby') class Meta: abstract = True </code></pre> <p>And then I've <a href="https://stackoverflow.com/a/13842223/7986808">found solution</a> how to watch field change and based on this I've created <code>post_save</code> signal which does update desired field value.</p> <pre><code>class ModelDiffMixin(object): """ A model mixin that tracks model fields values and provide some useful api to know what fields have been changed. """ def __init__(self, *args, **kwargs): super(ModelDiffMixin, self).__init__(*args, **kwargs) self.__initial = self._dict @property def diff(self): d1 = self.__initial d2 = self._dict diffs = [(k, (v, d2[k])) for k, v in d1.items() if v != d2[k]] return dict(diffs) @property def has_changed(self): return bool(self.diff) @property def changed_fields(self): return self.diff.keys() def get_field_diff(self, field_name): """ Returns a diff for field if it's changed and None otherwise. """ return self.diff.get(field_name, None) def save(self, *args, **kwargs): """ Saves model and set initial state. """ super(ModelDiffMixin, self).save(*args, **kwargs) self.__initial = self._dict @property def _dict(self): return model_to_dict( self, fields=[field.name for field in self._meta.fields]) </code></pre> <p>Using this mixin I'll be able to check which field values was changed and update the user statistics respectively. Here is the core word model <code>WordCoreModel</code> in which users can do some data manipulations through front-ent(using Django REST Framework):</p> <pre><code>class CoreWordCategoryModel(models.Model): core_abbreviation = models.CharField(max_length=10, blank=True) core_description = models.CharField(max_length=50, blank=True) ru_abbreviation = models.CharField(max_length=10, blank=True) ru_description = models.CharField(max_length=50, blank=True) en_abbreviation = models.CharField(max_length=10, blank=True) en_description = models.CharField(max_length=50, blank=True) def __str__(self): return "{} - {} - {}".format(self.core_description, self.ru_description, self.en_description) class WordCoreModel(BaseModel): NOUN_CLASSESS = [ ('V_CLASS', 'В класс'), ('Y_CLASS', 'Й класс'), ('Y_CLASS_SECOND', 'Й класс II'), ('D_CLASS', 'Д класс'), ('B_CLASS', 'Б класс'), ('B_CLASS_SECOND', 'Д класс II') ] PART_OF_SPEECH = [ ('NOUN', 'Noun'), ('VERB', 'Verb'), ('ADVERB', 'Adverb'), ('ADJECTIVE', 'Adjective'), ('PRONOUN', 'Pronoun'), ('PREPOSITION', 'Preposition'), ('CONJUNCTION', 'Conjunction'), ('INTERJECTION', 'Interjection') ] word_core = models.CharField(max_length=255, default="") word_russian_typed = models.CharField(max_length=255, default="", blank=True) word_english_typed = models.CharField(max_length=255, default="", blank=True) homonyms = models.ManyToManyField('self', blank=True) synonyms = models.ManyToManyField('self', blank=True) antonyms = models.ManyToManyField('self', blank=True) word_category = models.ForeignKey( CoreWordCategoryModel, on_delete=models.CASCADE, related_name='wordcategory', null=True, blank=True) description = models.TextField(default="", blank=True) latin_version = models.CharField(max_length=255, default="", blank=True) transcription = models.CharField(max_length=255, default="", blank=True) ipa = models.CharField(max_length=200, default="", blank=True) root = models.CharField(max_length=80, default="", blank=True) word_class = models.CharField(max_length=20, choices=NOUN_CLASSESS, blank=True) part_of_speech = models.CharField(max_length=20, choices=PART_OF_SPEECH, blank=True) etymology = models.TextField(default="", blank=True) # Declensions Singular declension_singular_absolutive = models.CharField( max_length=255, default="", blank=True) declension_singular_genitive = models.CharField( max_length=255, default="", blank=True) declension_singular_dative = models.CharField(max_length=255, default="", blank=True) declension_singular_ergative = models.CharField( max_length=255, default="", blank=True) declension_singular_allative = models.CharField( max_length=255, default="", blank=True) declension_singular_instrumental = models.CharField( max_length=255, default="", blank=True) declension_singular_locative_stay = models.CharField( max_length=255, default="", blank=True) declension_singular_locative_direction = models.CharField( max_length=255, default="", blank=True) declension_singular_locative_outcome = models.CharField( max_length=255, default="", blank=True) declension_singular_locative_through = models.CharField( max_length=255, default="", blank=True) declension_singular_comparative = models.CharField( max_length=255, default="", blank=True) # Declension Plural declension_plural_absolutive = models.CharField( max_length=255, default="", blank=True) declension_plural_genitive = models.CharField(max_length=255, default="", blank=True) declension_plural_dative = models.CharField(max_length=255, default="", blank=True) declension_plural_ergative = models.CharField(max_length=255, default="", blank=True) declension_plural_allative = models.CharField(max_length=255, default="", blank=True) declension_plural_instrumental = models.CharField( max_length=255, default="", blank=True) declension_plural_locative_stay = models.CharField( max_length=255, default="", blank=True) declension_plural_locative_direction = models.CharField( max_length=255, default="", blank=True) declension_plural_locative_outcome = models.CharField( max_length=255, default="", blank=True) declension_plural_locative_through = models.CharField( max_length=255, default="", blank=True) declension_plural_comparative = models.CharField( max_length=255, default="", blank=True) # Tenses imperative_tense_basic_form = models.CharField(max_length=255, default="", blank=True) imperative_tense_causative = models.CharField(max_length=255, default="", blank=True) imperative_tense_permissive = models.CharField(max_length=255, default="", blank=True) imperative_tense_permissive_causative = models.CharField( max_length=255, default="", blank=True) imperative_tense_potential = models.CharField(max_length=255, default="", blank=True) imperative_tense_inceptive = models.CharField(max_length=255, default="", blank=True) ###### simple_present_tense_basic_form = models.CharField( max_length=255, default="", blank=True) simple_present_tense_causative = models.CharField( max_length=255, default="", blank=True) simple_present_tense_permissive = models.CharField( max_length=255, default="", blank=True) simple_present_tense_permissive_causative = models.CharField( max_length=255, default="", blank=True) simple_present_tense_potential = models.CharField( max_length=255, default="", blank=True) simple_present_tense_inceptive = models.CharField( max_length=255, default="", blank=True) ###### near_preterite_tense_basic_form = models.CharField( max_length=255, default="", blank=True) near_preterite_tense_causative = models.CharField( max_length=255, default="", blank=True) near_preterite_tense_permissive = models.CharField( max_length=255, default="", blank=True) near_preterite_tense_permissive_causative = models.CharField( max_length=255, default="", blank=True) near_preterite_tense_potential = models.CharField( max_length=255, default="", blank=True) near_preterite_tense_inceptive = models.CharField( max_length=255, default="", blank=True) ###### witnessed_past_tense_basic_form = models.CharField( max_length=255, default="", blank=True) witnessed_past_tense_causative = models.CharField( max_length=255, default="", blank=True) witnessed_past_tense_permissive = models.CharField( max_length=255, default="", blank=True) witnessed_past_tense_permissive_causative = models.CharField( max_length=255, default="", blank=True) witnessed_past_tense_potential = models.CharField( max_length=255, default="", blank=True) witnessed_past_tense_inceptive = models.CharField( max_length=255, default="", blank=True) ###### perfect_tense_basic_form = models.CharField(max_length=255, default="", blank=True) perfect_tense_causative = models.CharField(max_length=255, default="", blank=True) perfect_tense_permissive = models.CharField(max_length=255, default="", blank=True) perfect_tense_permissive_causative = models.CharField( max_length=255, default="", blank=True) perfect_tense_potential = models.CharField(max_length=255, default="", blank=True) perfect_tense_inceptive = models.CharField(max_length=255, default="", blank=True) ###### plusquamperfect_tense_basic_form = models.CharField( max_length=255, default="", blank=True) plusquamperfect_tense_causative = models.CharField( max_length=255, default="", blank=True) plusquamperfect_tense_permissive = models.CharField( max_length=255, default="", blank=True) plusquamperfect_tense_permissive_causative = models.CharField( max_length=255, default="", blank=True) plusquamperfect_tense_potential = models.CharField( max_length=255, default="", blank=True) plusquamperfect_tense_inceptive = models.CharField( max_length=255, default="", blank=True) ###### repeated_past_tense_basic_form = models.CharField( max_length=255, default="", blank=True) repeated_past_tense_causative = models.CharField( max_length=255, default="", blank=True) repeated_past_tense_permissive = models.CharField( max_length=255, default="", blank=True) repeated_past_tense_permissive_causative = models.CharField( max_length=255, default="", blank=True) repeated_past_tense_potential = models.CharField( max_length=255, default="", blank=True) repeated_past_tense_inceptive = models.CharField( max_length=255, default="", blank=True) ###### possible_future_tense_basic_form = models.CharField( max_length=255, default="", blank=True) possible_future_tense_causative = models.CharField( max_length=255, default="", blank=True) possible_future_tense_permissive = models.CharField( max_length=255, default="", blank=True) possible_future_tense_permissive_causative = models.CharField( max_length=255, default="", blank=True) possible_future_tense_potential = models.CharField( max_length=255, default="", blank=True) possible_future_tense_inceptive = models.CharField( max_length=255, default="", blank=True) ###### real_future_tense_basic_form = models.CharField( max_length=255, default="", blank=True) real_future_tense_causative = models.CharField(max_length=255, default="", blank=True) real_future_tense_permissive = models.CharField( max_length=255, default="", blank=True) real_future_tense_permissive_causative = models.CharField( max_length=255, default="", blank=True) real_future_tense_potential = models.CharField(max_length=255, default="", blank=True) real_future_tense_inceptive = models.CharField(max_length=255, default="", blank=True) class Meta: indexes = [models.Index(fields=['word_core'])] verbose_name = 'Core Word' verbose_name_plural = 'Core Words' def __str__(self): return self.word_core </code></pre> <p>Adding new word or modifying word triggers <code>post_save</code> signal and executes following method:</p> <pre><code>@receiver(post_save, sender=WordCoreModel) def update_user_statistics(sender, instance, **kwargs): if instance.has_changed and instance.accepted: changed_fields = instance.changed_fields for field in changed_fields: _field = '{}_added'.format(field) if hasattr(UserStats, _field): user_stats = UserStats.objects.get_or_create( user_id=instance.modified_by.id)[0] user_stats.increment(_field) user_stats.save() </code></pre> <p>The custom model to collect all interaction of users <code>UserStats</code> looks like(it's a huge but the fields are almost the same so if I need to change the logic or something just apply it to one field and I'll correct rest of them):</p> <pre><code>class UserStats(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) reputation = models.IntegerField(default=0, blank=True) word_core_added = models.IntegerField(default=0, blank=True) word_russian_typed_added = models.IntegerField(default=0, blank=True) word_english_typed_added = models.IntegerField(default=0, blank=True) description_added = models.IntegerField(default=0, blank=True) latin_version_added = models.IntegerField(default=0, blank=True) transcription_added = models.IntegerField(default=0, blank=True) ipa_added = models.IntegerField(default=0, blank=True) root_added = models.IntegerField(default=0, blank=True) prefix_added = models.IntegerField(default=0, blank=True) suffix_added = models.IntegerField(default=0, blank=True) ending_added = models.IntegerField(default=0, blank=True) syllable_added = models.IntegerField(default=0, blank=True) phraseologism_added = models.IntegerField(default=0, blank=True) source_added = models.IntegerField(default=0, blank=True) word_class_added = models.IntegerField(default=0, blank=True) part_of_speech_added = models.IntegerField(default=0, blank=True) etymology_added = models.IntegerField(default=0, blank=True) declension_singular_absolutive_added = models.IntegerField(default=0, blank=True) declension_singular_genitive_added = models.IntegerField(default=0, blank=True) declension_singular_dative_added = models.IntegerField(default=0, blank=True) declension_singular_ergative_added = models.IntegerField(default=0, blank=True) declension_singular_allative_added = models.IntegerField(default=0, blank=True) declension_singular_instrumental_added = models.IntegerField(default=0, blank=True) declension_singular_locative_stay_added = models.IntegerField(default=0, blank=True) declension_singular_locative_direction_added = models.IntegerField( default=0, blank=True) declension_singular_locative_outcome_added = models.IntegerField( default=0, blank=True) declension_singular_locative_through_added = models.IntegerField( default=0, blank=True) declension_singular_comparative_added = models.IntegerField(default=0, blank=True) declension_plural_absolutive_added = models.IntegerField(default=0, blank=True) declension_plural_genitive_added = models.IntegerField(default=0, blank=True) declension_plural_dative_added = models.IntegerField(default=0, blank=True) declension_plural_ergative_added = models.IntegerField(default=0, blank=True) declension_plural_allative_added = models.IntegerField(default=0, blank=True) declension_plural_instrumental_added = models.IntegerField(default=0, blank=True) declension_plural_locative_stay_added = models.IntegerField(default=0, blank=True) declension_plural_locative_direction_added = models.IntegerField( default=0, blank=True) declension_plural_locative_outcome_added = models.IntegerField(default=0, blank=True) declension_plural_locative_through_added = models.IntegerField(default=0, blank=True) declension_plural_comparative_added = models.IntegerField(default=0, blank=True) imperative_tense_basic_form_added = models.IntegerField(default=0, blank=True) imperative_tense_causative_added = models.IntegerField(default=0, blank=True) imperative_tense_permissive_added = models.IntegerField(default=0, blank=True) imperative_tense_permissive_causative_added = models.IntegerField( default=0, blank=True) imperative_tense_potential_added = models.IntegerField(default=0, blank=True) imperative_tense_inceptive_added = models.IntegerField(default=0, blank=True) simple_present_tense_basic_form_added = models.IntegerField(default=0, blank=True) simple_present_tense_causative_added = models.IntegerField(default=0, blank=True) simple_present_tense_permissive_added = models.IntegerField(default=0, blank=True) simple_present_tense_permissive_causative_added = models.IntegerField( default=0, blank=True) simple_present_tense_potential_added = models.IntegerField(default=0, blank=True) simple_present_tense_inceptive_added = models.IntegerField(default=0, blank=True) near_preterite_tense_basic_form_added = models.IntegerField(default=0, blank=True) near_preterite_tense_causative_added = models.IntegerField(default=0, blank=True) near_preterite_tense_permissive_added = models.IntegerField(default=0, blank=True) near_preterite_tense_permissive_causative_added = models.IntegerField( default=0, blank=True) near_preterite_tense_potential_added = models.IntegerField(default=0, blank=True) near_preterite_tense_inceptive_added = models.IntegerField(default=0, blank=True) witnessed_past_tense_basic_form_added = models.IntegerField(default=0, blank=True) witnessed_past_tense_causative_added = models.IntegerField(default=0, blank=True) witnessed_past_tense_permissive_added = models.IntegerField(default=0, blank=True) witnessed_past_tense_permissive_causative_added = models.IntegerField( default=0, blank=True) witnessed_past_tense_potential_added = models.IntegerField(default=0, blank=True) witnessed_past_tense_inceptive_added = models.IntegerField(default=0, blank=True) perfect_tense_basic_form_added = models.IntegerField(default=0, blank=True) perfect_tense_causative_added = models.IntegerField(default=0, blank=True) perfect_tense_permissive_added = models.IntegerField(default=0, blank=True) perfect_tense_permissive_causative_added = models.IntegerField(default=0, blank=True) perfect_tense_potential_added = models.IntegerField(default=0, blank=True) perfect_tense_inceptive_added = models.IntegerField(default=0, blank=True) plusquamperfect_tense_basic_form_added = models.IntegerField(default=0, blank=True) plusquamperfect_tense_causative_added = models.IntegerField(default=0, blank=True) plusquamperfect_tense_permissive_added = models.IntegerField(default=0, blank=True) plusquamperfect_tense_permissive_causative_added = models.IntegerField( default=0, blank=True) plusquamperfect_tense_potential_added = models.IntegerField(default=0, blank=True) plusquamperfect_tense_inceptive_added = models.IntegerField(default=0, blank=True) repeated_past_tense_basic_form_added = models.IntegerField(default=0, blank=True) repeated_past_tense_causative_added = models.IntegerField(default=0, blank=True) repeated_past_tense_permissive_added = models.IntegerField(default=0, blank=True) repeated_past_tense_permissive_causative_added = models.IntegerField( default=0, blank=True) repeated_past_tense_potential_added = models.IntegerField(default=0, blank=True) repeated_past_tense_inceptive_added = models.IntegerField(default=0, blank=True) possible_future_tense_basic_form_added = models.IntegerField(default=0, blank=True) possible_future_tense_causative_added = models.IntegerField(default=0, blank=True) possible_future_tense_permissive_added = models.IntegerField(default=0, blank=True) possible_future_tense_permissive_causative_added = models.IntegerField( default=0, blank=True) possible_future_tense_potential_added = models.IntegerField(default=0, blank=True) possible_future_tense_inceptive_added = models.IntegerField(default=0, blank=True) real_future_tense_basic_form_added = models.IntegerField(default=0, blank=True) real_future_tense_causative_added = models.IntegerField(default=0, blank=True) real_future_tense_permissive_added = models.IntegerField(default=0, blank=True) real_future_tense_permissive_causative_added = models.IntegerField( default=0, blank=True) real_future_tense_potential_added = models.IntegerField(default=0, blank=True) real_future_tense_inceptive_added = models.IntegerField(default=0, blank=True) word_category_added = models.IntegerField(default=0, blank=True) homonyms_added = models.IntegerField(default=0, blank=True) synonyms_added = models.IntegerField(default=0, blank=True) antonyms_added = models.IntegerField(default=0, blank=True) def increment(self, name): """Increments a counter specified by the 'name' argument.""" self.__dict__[name] += 1 </code></pre> <hr> <p>I'm not sure about this <code>post_save</code> method. I can exclude counting due to minor changes by users like changing 1 letter in word or description etc. through the logic of the field "accepted" in WordCoreModel. Any change will set <code>accepted</code> to <code>false</code> until some of the moderators set it manually to <code>true</code> again and this will prevent counting statistics in minor changes or abuse the statistics. But another thing is that only accepted words will be available in the application and setting it to <code>false</code> each time some one change it not that much good idea.</p>
[]
[ { "body": "<p>Instead of keeping a single version of each word, you can add an integer field for its version/revision. This way you can have multiple versions of the word and keep the last validated available while having pending edits. This will also allows you to more easily review who modified what.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T07:23:59.887", "Id": "223787", "ParentId": "223774", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T22:53:33.923", "Id": "223774", "Score": "2", "Tags": [ "python", "django" ], "Title": "Custom model to count user interaction in application" }
223774
<p>I am trying to check if a class has only numeric values in it and then return a <code>bool</code>, however, some instances there may be non numeric chars in an object that should only contain numeric values.</p> <p>At the present I am using reflection to loop through the object (Which in some cases can have up 200 properties) and then check the property value with <code>Regex</code> to see if it is a numeric value. The reason for the regex instead of <code>Int.TryParse</code> or <code>Int64.TryParse</code> is b/c every now and again a non integer value is mixed in with the text, but I know the file is an all integer file from the way it is setup. This however is not the issue as the Regex is working as expected.</p> <p>The structure of the <code>StringCsv</code> and <code>IntergerCsv</code> Entities are different (What I mean is that the structure of the CSV's with string's and int's are fundamentally different) , but I need to save the data to an Entity that is consistent, which means I need to check which CSV is being imported to differentiate between the methods needed to save to the database. ie, There is a date column, but it differs between the <code>Interger</code> CSV and the <code>String</code> CSV. </p> <p>Also, I can't add the data dirrectly into the Entities <code>StringCsv</code> and <code>IntergerCsv</code> b/c they need an <code>Id</code> which is a <code>Guid</code> and the CSV file does not contain that, which is why I read to the the class <code>GovernmentCsvRecord</code> and then covert the object to the Entity.</p> <p>Below are samples of CSV files, sorry I can't post actual values.</p> <p>The <strong>string</strong> file <a href="https://i.stack.imgur.com/JANXr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JANXr.png" alt="enter image description here"></a></p> <p>The <strong>Int</strong> file <a href="https://i.stack.imgur.com/vpdXG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vpdXG.png" alt="enter image description here"></a></p> <p>I should also mention that the first property will always be a GUID, that also needs to be taken into consideration. (I should probably be skipping that property anyway in my current code, but obviously don't.)</p> <p>I should also mention I am using a <a href="https://joshclose.github.io/CsvHelper/" rel="nofollow noreferrer">custom library</a> to import the CSV files.</p> <p>To check the value is numeric:</p> <pre><code>static bool IsMatch(string str) { return Regex.IsMatch(str, @"^[abcd][\d0-9]{5}$|[\d0-9]", RegexOptions.IgnoreCase | RegexOptions.Multiline); } </code></pre> <p>Loop through each property and use above code to check the value,</p> <pre><code>static bool IsNumericFile&lt;T&gt;(List&lt;T&gt; list) { foreach (var item in list) { List&lt;string&gt; values = typeof(T).GetProperties() .Select(propertyInfo =&gt; propertyInfo.GetValue(item, null)) .Where(s =&gt; s != null) .Select(s =&gt; s.ToString()) .Where(str =&gt; str.Length &gt; 0) .ToList(); foreach (var propertyString in values) { var isNumeric = IsMatch(propertyString); //Jump out if non numeric value is found if (!isNumeric) return false; } } return true; } </code></pre> <p>Reading the file,</p> <pre><code>// Get the data from the CSV static List&lt;T&gt; ImportCsv&lt;T&gt;(string file, string delimeter = ",", bool hasHeader = false) { using (var reader = File.OpenText(file)) { var csv = new CsvReader(reader); csv.Configuration.Delimiter = delimeter; csv.Configuration.HasHeaderRecord = hasHeader; csv.Configuration.MissingFieldFound = null; csv.Configuration.HeaderValidated = null; csv.Configuration.Encoding = Encoding.GetEncoding("Shift_JIS"); return csv.GetRecords&lt;T&gt;().ToList(); } } //Convert the data to the required entities public IEnumerable&lt;StringCsv&gt; ReadStringCsvFromFile(string filePath) { return ImportCsv&lt;GovernmentCsvRecord&gt;(filePath).Skip(3).Select(GovernmentCsvRecord.StringCsvGovernmentToEntity); } public IEnumerable&lt;IntegerCsv&gt; ReadIntCsvFromFile(string filePath) { return ImportCsv&lt;GovernmentCsvRecord&gt;(filePath).Skip(3).Select(GovernmentCsvRecord.IntCsvGovernmentToEntity); } </code></pre> <p>I am purposefully not posting the complete <code>GovernmentCsvRecord</code> object as it is an object with 200 string properties. I have posted the class with limited properties to illustrate how the class is set up with its properties and functions.</p> <p>I convert to each entity via the functions in the <code>GovernmentCsvRecord</code>, <code>StringCsvGovernmentToEntity</code> and <code>IntCsvGovernmentToEntity</code>.</p> <p>The <code>StringCsv</code> entity</p> <pre><code>public class GovernmentCsvRecord { public string Col1 { get; set; } public string Col2 { get; set; } public string Col3 { get; set; } //etc 200 properties in class public static StringCsv StringCsvGovernmentToEntity(GovernmentCsvRecord data) { StringCsv entity = new StringCsv(); entity.Id = Guid.NewGuid(); entity.Col1 = data.Col1; entity.Col2 = data.Col2; //etc until 200 properties are filled } //The `IntegerCsv` entity public static IntegerCsv IntCsvGovernmentToEntity(GovernmentCsvRecord data) { IntegerCsv entity = new IntegerCsv(); entity.Id = Guid.NewGuid(); entity.Col1 = data.Col1; entity.Col2 = data.Col2; //etc until 200 properties are filled } } </code></pre> <p>Then the usage,</p> <pre><code>List&lt;StringCsv&gt; StringList = new List&lt;StringCsv&gt;(); List&lt;IntegerCsv&gt; IntList = new List&lt;IntegerCsv&gt;(); StringList = ReadStringCsvFromFile(FileName).ToList(); if (!IsNumericFile(StringList)) { IntList = ReadIntCsvFromFile(FileName).ToList(); } if (IntList.Count &gt; 0) { //Do stuff with intList } else { //Do stuff with stringList } </code></pre> <p>At present, it takes about 8 to 10ms to complete a check of one object, so performance wise it is not a huge issue, but I was wondering if there maybe was a better approach to do something like this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T12:49:17.223", "Id": "434086", "Score": "1", "body": "I voted to reopen, but some things are still unclear. What's the difference between `StringCsv` and `IntegerCsv`? The name `ReadIntCsvFromFile` implies that it reads numeric data, but it's only called when the input contains non-numeric fields, so what does `IntCsvGovernmentToEntity` do that `StringCsvGovernmentToEntity` does not? And why read into `GovernmentCsvRecord` objects only to convert immediately afterwards - why not read directly into a `StringCsv` object, and convert that to an `IntegerCsv` when necessary?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T13:03:37.877", "Id": "434087", "Score": "1", "body": "@PieterWitvoet, I edited the question to address those issues. Also, I don't know how to get the data into a unknown type and then check values, so I just checked if the object was a string file or not and proceeded from there." } ]
[ { "body": "<ul>\n<li>Instead of throwing away that list of <code>GovernmentCsvRecord</code> objects after converting it to a <code>StringCsv</code> list, you could keep it around so you don't have to read the csv file again if the <code>IsNumericFile</code> check fails.</li>\n<li>It looks like you can validate the list of <code>GovernmentCsvRecord</code> objects directly instead of first converting them to <code>StringCsv</code> objects. However, with the way you're converting them, and taking the numeric check into account, it's probably better to read each row into an array of strings. Apparently the easiest way to do that is to give <code>GovernmentCsvRecord</code> a single <code>string[]</code> property. That lets you validate fields without having to use reflection.</li>\n<li>That regular expression can be simplified a lot. The first part matches strings like <code>\"a12345\"</code> - anything that starts with an a, b, c or d, followed by exactly 5 digits. The second part matches anything that contains at least one digit - which covers everything that the first part covers, and more, so just the second part is sufficient. Also note that <code>\\d</code> matches decimal digits from a variety of scripts, including <code>0-9</code>, so <code>[\\d0-9]</code> can be simplified to just <code>\\d</code>. But you may want to use <code>0-9</code> instead, unless you also want to accept digits like <code>'೬'</code> and <code>'६'</code>.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T23:22:35.727", "Id": "434176", "Score": "1", "body": "+1. And you absolutely correct. As I was re-writing the question, saw I was doing a fair bit of redundant code. As you say, validate the `GovernmentCsvReord` class and then convert to the needed entities. Thanks for the advice on the Regex, I am not very good with it, so that helps enormously as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T23:38:47.290", "Id": "434178", "Score": "2", "body": "Another optimization is to create and reuse a single (compiled) `Regex` instance instead of calling the static `IsMatch` method, so the regex engine doesn't have to parse the pattern each time. Or, for such a simple pattern, `string.Any(char.IsDigit)` (for `\\d`) or `string.Any(c => c >= '0' && c <= '9')` (for `0-9`) is even faster." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-11T00:29:31.377", "Id": "434182", "Score": "1", "body": "Doing that instead of Regex brings 1500 line file with 200 properties down to 20ms from 30ms. One third faster is on just that is awesome. Overall I think I have reduced run time to half its original time it took. Thanks for the help.There are a couple more things I think I can do, but this has got me on the right track." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T15:36:37.817", "Id": "223876", "ParentId": "223776", "Score": "4" } } ]
{ "AcceptedAnswerId": "223876", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-08T23:14:06.023", "Id": "223776", "Score": "2", "Tags": [ "c#", "regex", "validation" ], "Title": "Checking if an object meets certain criteria to amend to certain Entity Objects?" }
223776
<p>I solved this <a href="https://www.geektrust.in/api/pdf/open/PS2" rel="nofollow noreferrer">programming challenge</a> whose objective is to come up with an OO solution to the problem. </p> <p>The problem statement is quite verbose and the tl;dr version would be: </p> <p>Given an enemy army(Falicornia) made up of Horses, Elephants, Armoured Tanks and Sling Guns and our own similar army(Lengaburu). Find out the minimum army required to defeat this based on a few rules as below</p> <p>Our army(Lengaburu) will have 100 Horses, 50 Elephants, 10 Armoured Tanks and 5 Sling Guns</p> <blockquote> <p><strong>Rule #1. The Power Rule:</strong> Each Lengaburu army unit is 2X more powerful than their Falicornia counterpart. </p> <p>Example: 1 Lengaburu Horse can counter 2 Falicornia Horses, 1 Lengaburu Elephant can counter 2 Falicornia Elephants and so on. </p> <p><strong>Rule #2. The Like-to-Like Rule:</strong> Falicornia Horses battalion should be countered with Lengaburu horses battalion, Elephants with elephants and so on. Except when the battalion is completely exhausted (see Rule #3). </p> <p>Example: If Falicornia deploys 2 H, 4 E, 0 AT and 6 SG, Lengaburu should counter with 1 H, 2 E, 0 AT and 3 SG.</p> <p><strong>Rule #3. The Substitution Rule:</strong> When all units of a particular Lengaburu battalion is exhausted, an adjacent battalion can be used. 1 Elephant can replace 2 Horses (and 2 Horses can replace 1 Elephant), 1 Armoured Tank can replace 2 Elephants (and vice versa) and 1 Sling Gun can replace 2 Armoured Tanks (and vice versa). Note that only adjacent battalions can be used for substituting. Horses cannot replace Sling Guns as they are not adjacent. </p> <p>Example: If Falicornia deploys 204 H, 20 E, 0 AT and 0 SG, Lengaburu should counter with 100 H, 11 E (1 Elephant has substituted 2 Horses which got exhausted at 100) </p> <p><strong>Rule #4. The Substitution Choice Rule:</strong> When there are 2 possibilities of substitution, then always a lower ranked battalion should be used (Horses is lower than Elephants, is lower than Armoured Tanks, is lower than Sling Guns) </p> <p>Example: If Falicornia deploys 50 H, 104 E, 6 AT and 2 SG, Lengaburu should counter with 29 H, 50 E, 3 AT and 1 SG (4 Horses substituted for 2 Elephants instead of the higher ranked Armoured Tanks)</p> </blockquote> <p><strong>Sample Input and Output</strong></p> <p>Sample 1</p> <blockquote> <p>Input: Falicornia attacks with 100 H, 101 E, 20 AT, 5 SG</p> <p>Expected Output: Lengaburu deploys 52 H, 50 E, 10 AT, 3 SG and wins</p> </blockquote> <p>Sample 2</p> <blockquote> <p>Input: Falicornia attacks with 250 H, 50 E, 20 AT, 15 SG</p> <p>Expected Output: Lengaburu deploys 100 H, 38 E, 10 AT, 5 SG and loses </p> </blockquote> <p>I am relatively new to OO Python and Python.</p> <p>I'm looking for a review on how OO the solution is, how accurate the modelling is for the problem described and how Pythonic my code is coming from someone who mostly writes C#.</p> <hr> <p>The <code>Army</code> class </p> <pre><code>class Army: """Army holds all the battalions along with their strength. Army can update, add new battalions and their strength """ def __init__(self, **battalions): self.battalion_strength: Dict[BattalionType, int] = {} for k, v in battalions.items(): if BattalionType.is_valid_battalion(k) and isinstance(v, int): self.battalion_strength[BattalionType(k)] = v def get_battalion_strength(self, battalion_type: BattalionType) -&gt; int: """Returns the strength of the battalion in this army Arguments: battalion_type {BattalionType} -- [type of battalion whose strength needs to be found] Raises: KeyError: [Raises when battalion_type is not present in the army] Returns: [int] -- [strength of battalion_type] """ if battalion_type not in self.battalion_strength: raise KeyError("{0} not found".format(battalion_type)) return self.battalion_strength.get(battalion_type) def update_battalion_strength(self, battalion_type: BattalionType, change: int): """adds a new battalion_type battalion if not present else updates the strength of the battalion Arguments: battalion_type {BattalionType} -- [Type of battalion to be added or updated] change {int} -- [represents change in the strength of the battalion] """ if battalion_type not in self.battalion_strength: self.battalion_strength[battalion_type] = change else: self.battalion_strength[battalion_type] += change def get_battalions(self) -&gt; List[BattalionType]: return list(self.battalion_strength.keys()) def has_battalion(self, battalion_type: BattalionType) -&gt; bool: return battalion_type in self.battalion_strength def __eq__(self, other): if not isinstance(other, Army): return False return self.battalion_strength == other.battalion_strength </code></pre> <hr> <p><code>BattalionProcessor</code> class.</p> <p>This class hold the multiplier (Rule 1) and I have extended it to also accept the seniority of battalions so that newer battalions can be added or existing ones can have their seniority changed</p> <p>The substitution order of battalion is modelled as a graph to allow for uni-directional relations (i.e only horse can replace elephants and not vice versa) also to be open to adding additional substitutions (like a horse can replace sling guns)</p> <pre><code>class BattalionProcessor: """[summary] Class to hold the battalion seniority and substitution battalions """ def __init__(self, multiplier: int = 2, **battalions): self.multiplier = multiplier self.battalion_seniority: Dict[BattalionType, int] = {} self.substitution_graph: Dict[BattalionType, List[Tuple[BattalionType, float]]] = {} for k, v in battalions.items(): if BattalionType.is_valid_battalion(k) and isinstance(v, int): self.battalion_seniority[BattalionType(k)] = v def get_battalion_seniority(self, battalion_type: BattalionType) -&gt; int: return self.battalion_seniority.get(battalion_type, 100) def add_battalion_substituation(self, from_battalion_type: BattalionType, to_battalion_type: BattalionType, multiplier: int, bidirectional: bool = True) -&gt; None: """[summary] Arguments: from_battalion_type {BattalionType} -- [from battalion_type] to_battalion_type {BattalionType} -- [to battalion_type] multiplier {int} -- [amount of from_battalion_type required to make 1 to_battalion_type] bidirectional {bool} -- [indicates weather the relationship is bidirectional] (default: {True}) """ from_sub_btn = self.substitution_graph.get(from_battalion_type, []) from_sub_btn.append((to_battalion_type, multiplier)) self.substitution_graph[from_battalion_type] = from_sub_btn if(bidirectional): to_sub_btn = self.substitution_graph.get(to_battalion_type, []) to_sub_btn.append((from_battalion_type, 1/multiplier)) self.substitution_graph[to_battalion_type] = to_sub_btn def get_substitution_battalion(self, battalion_type: BattalionType) -&gt; List[Tuple[BattalionType, float]]: """[summary] Returns the list of Tuple of BattalionType and multipler indicating how much of that battalion is need to make 1 of the input battalion_type Arguments: battalion_type {BattalionType} -- [Input battalion whose substitution order needs to be found] Returns: List[Tuple[BattalionType, float]] -- [substitution order of the input battalion] """ unordered_sub_btn = self.substitution_graph.get(battalion_type, []) return sorted(unordered_sub_btn, key=lambda btn: self.get_battalion_seniority(btn)) </code></pre> <p><code>BattalionType</code> enum</p> <pre><code>from enum import Enum class BattalionType(Enum): HORSES = "horses" ELEPHANTS = "elephants" ARMOUREDTANKS = "armoured_tanks" SLINGGUNS = "sling_guns" @staticmethod def is_valid_battalion(battalion_name: str) -&gt; bool: btn_names = [bat.value for bat in BattalionType] return battalion_name in btn_names </code></pre> <hr> <p>The <code>BattlePlanner</code> class which does the actual computation with the other two as dependencies</p> <pre><code>class BattlePlanner: def __init__(self, battalion_processor: BattalionProcessor, our_army: Army): self.battalion_processor: BattalionProcessor = battalion_processor self.our_army: Army = our_army self.__result_army: Army = Army() def update_battalion_stats(self, our_battalion: BattalionType, our_strength: int, enemy_battalion: BattalionType, enemy_strength: int, resolvable: int) -&gt; int: enemy_strength -= resolvable self.our_army.update_battalion_strength(our_battalion, -our_strength) self.__result_army.update_battalion_strength(our_battalion, our_strength) return enemy_strength def resolve_battalion(self, enemy_battalion: BattalionType, enemy_strength: int) -&gt; bool: remaining_strength: int = self.apply_power_rule(enemy_strength) if self.our_army.has_battalion(enemy_battalion): remaining_strength = self.resolve_with_similar_battalion(enemy_battalion, remaining_strength) if remaining_strength &gt; 0: remaining_strength = self.resolve_with_substitution_battalion(enemy_battalion, remaining_strength) return remaining_strength == 0 def resolve_with_similar_battalion(self, enemy_battalion: BattalionType, enemy_strength: int) -&gt; int: our_strength = self.our_army.get_battalion_strength(enemy_battalion) resolvable_strength = min(our_strength, enemy_strength) resolved_strength = self.update_battalion_stats(enemy_battalion, resolvable_strength, enemy_battalion, enemy_strength, resolvable_strength) return resolved_strength def apply_power_rule(self, enemy_strength: int) -&gt; int: return int(ceil(enemy_strength / self.battalion_processor.multiplier)) def resolve_with_substitution_battalion(self, enemy_battalion: BattalionType, enemy_strength: int) -&gt; int: substitution_battalions = self.battalion_processor.get_substitution_battalion(enemy_battalion) for substitution_battalion in substitution_battalions: if enemy_strength == 0: break required_strength = ceil(substitution_battalion[1] * enemy_strength) actual_strength = self.our_army.get_battalion_strength(substitution_battalion[0]) resolvable_strength = min(required_strength, actual_strength) normalized_resolvable = min(int(ceil(resolvable_strength * (1 / substitution_battalion[1]))), enemy_strength) enemy_strength = self.update_battalion_stats(substitution_battalion[0], resolvable_strength, enemy_battalion, enemy_strength, normalized_resolvable) return enemy_strength def get_winning_army(self, enemy_army: Army) -&gt; Army: """Returns the minimum required army and a bool indicating the result of the battle with the returned army True : Returned army will win False : Returned army will lose Arguments: enemy_army {Army} -- [The army to battle against] Returns: Army -- [Minimum required army to defeat enemy_army] battle_result {bool} -- [boolean indicating the result of the battle] """ battle_result: bool = True for enemy_battalion in enemy_army.get_battalions(): enemy_strength = enemy_army.get_battalion_strength(enemy_battalion) battle_result &amp;= self.resolve_battalion(enemy_battalion, enemy_strength) return battle_result, self.__result_army </code></pre> <hr> <p>The code is in <a href="https://github.com/benneyman/War/tree/4cebc7281db35d8e7357dae4cfa39514f273d595" rel="nofollow noreferrer">Github</a> to be easier to read</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T06:58:57.947", "Id": "433915", "Score": "0", "body": "I don't get the exhaustion rule. Where are the limits defined?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T07:28:40.760", "Id": "433918", "Score": "0", "body": "@MathiasEttinger Sorry, the question was a bit vague. I have edited the question and provided a link to the original question as well. The limit is we start with a pre-defined strength for each battalion" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T04:48:41.717", "Id": "434042", "Score": "0", "body": "I don't quite get `Sample 2` above (quoted from geektrust.in *Sample III*): Why, instead of deploying all elephants or acknowledging inferiority deploy 38 of them?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-11T14:30:49.967", "Id": "434294", "Score": "0", "body": "@greybeard Falicornia has 250 which uses all 100 H and still has 50H to resolve. \nFalicornia has 50E which requires 25E which has to be applied due to the like to like rule. Then for the remaining 50H it applies 13E which brings it to 38H" } ]
[ { "body": "<h2>Dict updates</h2>\n\n<p>This:</p>\n\n<pre><code>if battalion_type not in self.battalion_strength:\n self.battalion_strength[battalion_type] = change\nelse:\n self.battalion_strength[battalion_type] += change\n</code></pre>\n\n<p>can be done more easily in a few different ways. Perhaps the easiest is to make <code>battalion_strength</code> a <code>defaultdict(int)</code>. Then, this <code>if</code> goes away and you can \"naively\" do <code>+=</code>.</p>\n\n<h2>Redundant parens</h2>\n\n<pre><code>if(bidirectional):\n</code></pre>\n\n<p>We aren't in Java anymore :)</p>\n\n<h2>Cache <code>btn_names</code></h2>\n\n<p>This won't change, so you should probably save it as a class constant rather than a variable within the method <code>is_valid_battalion</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T02:27:22.180", "Id": "223780", "ParentId": "223777", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T00:07:42.073", "Id": "223777", "Score": "9", "Tags": [ "python", "algorithm", "python-3.x", "object-oriented", "programming-challenge" ], "Title": "Geektrust: Solve War problem in a OO way in Python" }
223777
<h2>Context</h2> <p>I'm a duck retailer. I rent ducks to farmers, and when they don't need them anymore, I get them back. In order to track which ducks I rented to whom, I have a PostGreSQL database that I keep updated with my operations.</p> <p>When I record a rent operation I need to manipulate two tables: <code>Ducks</code> and <code>RelationDuckFarmer</code>.<br /> Relevant attributes of <code>Ducks</code> in the rent context are <code>id</code> and <code>duck_status</code> (to check whether Ducky is healthy or has an issue of some kind).<br /> Attributes at stake in <code>RelationDuckFarmer</code> are <code>duck_id</code>, <code>farm_id</code>, <code>farmer_id</code> (there may be several farmers in the same structure) and finally <code>start_date</code> and <code>end_date</code> (which delineate the renting period). <strong>When the rental is over, instances in <code>RelationDuckFarmer</code> are not deleted,</strong> we add an <code>end_date</code> instead (so as to keep an history of rents).</p> <h2>Rental conditions</h2> <ul> <li>Duck must be available &amp; healthy for renting -&gt; <code>duck_status == Available</code></li> <li>Duck must not be already allocated -&gt; if <code>start_date</code> is not null then <code>end_date</code> must not be either.</li> <li><code>start_date</code> and <code>end_date</code> are timestamps generated by PostGreSQL <code>CURRENT_TIMESTAMP</code> keyword.</li> </ul> <h2>Code</h2> <pre><code>def allocate_ducks(self, ducks, farm_id, farmer_id): keys = ['farm_id', 'duck_id', 'farmer_id', start_date] # Wrapper for SQL transaction with transaction() as (conn, cur): # Iterate over the given array of duck IDs for d in ducks: row_data = [farm_id, d, farmer_id] if duck_exists(cur, d) and duck_is_available(cur, d): if duck_is_already_rented(cur, d): raise DuckAlreadyRented(d) else: allocate_to_farm = sql.SQL('INSERT INTO {} ({}) VALUES ({}, CURRENT_TIMESTAMP)').format( sql.Identifier('RelationDuckFarm'), sql.SQL(', ').join(map(sql.Identifier, keys)), sql.SQL(', ').join(map(sql.Literal, row_data)) ) cur.execute(allocate_to_farm) change_status_to_rented = sql.SQL('UPDATE {} SET {}={} WHERE {}={}').format( sql.Identifier('Ducks'), sql.Identifier('duck_status'), sql.Literal('Rented'), sql.Identifier(id), sql.Literal(d) ) cur.execute(change_status_to_rented) else: raise DuckDoesNotExist(d) return ducks </code></pre> <p><strong>duck_exists:</strong></p> <pre><code>def duck_exists(self, cur, duck_id): query = sql.SQL('SELECT COUNT(*) FROM {} WHERE {}={};').format( sql.Identifier('Ducks'), sql.Identifier('id'), sql.Literal(duck_id) ) cur.execute(query) return cur.fetchone() </code></pre> <p><strong>duck_is_available:</strong></p> <pre><code> def duck_is_available(self, cur, duck_id): query = sql.SQL('SELECT COUNT(*) FROM {} WHERE {}={} AND {}={}').format( sql.Identifier('Ducks'), sql.Identifier('id'), sql.Literal(duck_id), sql.Identifier('duck_status'), sql.Literal('Available') ) cur.execute(query) return cur.fetchone() </code></pre> <p><strong>duck_is_already_rented:</strong></p> <pre><code>def duck_is_already_allocated(self, cur, duck_id): # Look for rows where the duck has a rental starting date but not an ending date (which would mean it's currently rented to s.o.) query = sql.SQL('SELECT COUNT(*) FROM {} WHERE {}={} AND {} IS NOT NULL AND {} IS NULL').format( sql.Identifier('RelationDuckFarm'), sql.Identifier('duck_id'), sql.Literal(duck_id), sql.Identifier('start_date'), sql.Identifier('end_date') ) cur.execute(query) return cur.fetchone() </code></pre> <h2>Issues</h2> <ul> <li>The functions I use to check whether it is possible to rent Ducky before actually creating a row in <code>RelationDuckFarm</code> already cost me three SQL queries. I can't really combine them in one because I need these checkers somewhere else as well. So that means I have to perform 5 different queries to rent one duck. Functioning, but not very efficient.</li> <li>I use a <em>for</em> loop to go through the array containing all the ducks I'd like to rent. Which means that if I have <strong>n</strong> ducks, I'd then need <strong>5*n</strong> queries to record my operations.</li> </ul> <h2>Question</h2> <p>How to refactor this code to optimize my rental system while still respecting the data model?</p>
[]
[ { "body": "<h2>Query formatting</h2>\n\n<pre><code>query = sql.SQL('SELECT COUNT(*) FROM {} WHERE {}={} AND {} IS NOT NULL AND {} IS NULL').format(\n sql.Identifier('RelationDuckFarm'),\n sql.Identifier('duck_id'),\n sql.Literal(duck_id),\n sql.Identifier('start_date'),\n sql.Identifier('end_date'))\n</code></pre>\n\n<p>You're using format to place constants into the query. Contants like the table name. Why? It makes the query harder to read, and I can imagine it hurts performance (ever so slightly).</p>\n\n<pre><code>query = sql.SQL(\"\"\"\nSELECT COUNT(*) \nFROM RelationDuckFarm \n\nWHERE duck_id={} \nAND start_date IS NOT NULL \nAND end_date IS NULL\n\"\"\").format(\n sql.Literal(duck_id))\n</code></pre>\n\n<h2>Duplicate queries</h2>\n\n<p>Before you update the table, you perform 3 checks: Does the duck exist, is the duck available and is the duck not already rented? You could combine the first two checks into one query: if the duck doesn't exist, the second query will also return 0, because it has the same where-clause and then some. Additionally, when you rent out a duck, you also set that duck's status to <code>'rented'</code>. This means that ducks that are already rented out, will never pass the first filter (because their status is not <code>'available'</code>.</p>\n\n<p>This means that your call to <code>duck_is_available</code> does everything you need to know. <strong>This does assume that you correctly set the duck's status back to available when the rent is over!</strong> I can't check that because you didn't provide the code. At the same time, if it's not consistently updated, why is it even there to begin with?</p>\n\n<h2>Combining queries</h2>\n\n<p>If the check above isn't sufficient, you can still combine the queries into one. I think that it's better to have two queries at different places that do what you need, than to split queries into small chuncks, forcing you to execute three every time.</p>\n\n<pre><code>select \n\ncase when d.duck_status = 'available' then 1 else 0 end IsAvailable,\ncase when rdf.start_date IS NOT NULL AND rdf.end_date IS NULL then 1 else 0 end IsAlreadyRented\n\nfrom Ducks d\n\nleft join RelationDuckFarm rdf on d.duck_id = rdf.duck_id\n\nwhere d.duck_id = {}\n</code></pre>\n\n<p>This does join (and filter) on duck_id. Duck_id is a PK/index right?</p>\n\n<h2>Errors</h2>\n\n<p>You raise a DuckDoesNotExistError, even when a duck exists, but is not available. I'm not sure if you really need that distinction in errors.</p>\n\n<h2>All updates in one go:</h2>\n\n<p>What is your desired behaviour if some ducks exist, and some don't? Will all changes that have been made be rolled back? If so, you can probably update for all ducks at once after you checked whether the ducks were available.</p>\n\n<p>Both the <code>update</code> and the <code>insert</code> statement can be adapted to add/update multiple rows at once. I'm not familiar with the database API you use in Python, so I can't help you much with that, but it shouldn't be too hard.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T07:34:07.893", "Id": "433919", "Score": "0", "body": "You're right, I set the duck's status back when I de-allocate. I didn't want to put too much code in the question body." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T07:12:35.070", "Id": "223786", "ParentId": "223783", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T06:34:17.433", "Id": "223783", "Score": "5", "Tags": [ "python", "python-3.x", "postgresql" ], "Title": "SQL Bulk status update" }
223783
<p>I've never had my C++ code reviewed before so I'd appreciate any feedback. Although my main focus was not on the implementation of the algorithm itself, any suggestions regarding improving it would be welcome. I'm mostly looking for C++ related feedback though.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; using namespace std; class MinHeap { public: void push(int num) { /* add num to end of the heap and rearrange by up-heap */ heap.push_back(num); int ind = heap.size() - 1; if (heap.size() &gt; 1) { int par = parent_index(ind); while (heap[ind] &lt; heap[par]) { swap(heap[ind], heap[par]); ind = par; if (ind == 0) break; par = parent_index(ind); } } } void pop() { /* pop the element at the of the heap and finding a new top by replacing with the last element and performing a down-heap */ if (heap.size() == 1) heap.pop_back(); else if (heap.size() &gt; 1) { swap(heap[0], heap.back()); heap.pop_back(); int ind = 0; int min_c = get_min_child(ind); while (heap[min_c] &lt; heap[ind]) { swap(heap[min_c], heap[ind]); ind = min_c; if (child_count(ind) == 0) break; min_c = get_min_child(ind); } } } int top() { /* return element at the top of the heap (should be the min) */ return heap.front(); } private: vector&lt;int&gt; heap; int get_min_child(int index) { /* find the smaller child of a node given by index */ if (index &lt; heap.size() - 2) { int left = left_child_index(index); int right = right_child_index(index); return (heap[left] &lt; heap[right]) ? left : right; } else if (index &lt; heap.size() - 1) { return left_child_index(index); } else throw invalid_argument("node has no children"); } int parent_index(int index) { /* return index of parent node */ if (index &gt; 0) { return (index - 1) / 2; } else throw out_of_range("Trying to access root parent"); } int child_count(int index) { /* return the number of children a given node has */ if (2*index + 2 &lt; heap.size()) return 2; else if (2*index + 1 &lt; heap.size()) return 1; else return 0; } int left_child_index(int index) { int ind = 2*index + 1; if (ind &lt; heap.size()) return ind; else throw out_of_range("Index out of range"); } int right_child_index(int index) { int ind = 2*index + 2; if (ind &lt; heap.size()) return ind; else throw out_of_range("Index out of range"); } }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T18:39:12.713", "Id": "433998", "Score": "0", "body": "The standard also provides the tools for creating a heap https://en.cppreference.com/w/cpp/algorithm/make_heap The default is max heap but that can easily be changed by providing your own comparator." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T21:34:15.370", "Id": "434022", "Score": "0", "body": "Thanks, I'm aware of the STL implementation. I'm only implementing this as an exercise." } ]
[ { "body": "<p>Here's my two cents:</p>\n\n<ol>\n<li><p>Do not <code>using namespace std;</code>. It causes serious problems and is considered bad practice. See <a href=\"https://stackoverflow.com/q/1452721/9716597\">Why is <code>using namespace std;</code> considered bad practice?</a>.</p></li>\n<li><p>Consider wrapping your class in a header so that it can be reused. Use an include guard.</p></li>\n<li><p><code>MinHeap</code> is a common name that may cause name clash. Consider placing it in a namespace.</p></li>\n<li><p><code>MinHeap</code> only supports <code>int</code>s. You can make <code>MinHeap</code> a template.</p></li>\n<li><p>Right now <code>MinHeap</code> can only be default initialized to empty. Consider adding a constructor to initialize the <code>MinHeap</code> with a list of values.</p></li>\n<li><p>Your comments apply to the function, instead of the first line of the function body. They should really go outside the function.</p>\n\n<pre><code>// this function foos the bar\nvoid foo(int bar)\n{\n ...\n}\n</code></pre></li>\n<li><p>You use <code>int</code> for indexes. This is not good because <code>int</code> may be too narrow &mdash; <code>INT_MAX</code> may be as small as <code>32767</code>. Use <code>std::size_t</code> instead.</p></li>\n<li><p>All of your functions that return an index have the suffix <code>_index</code>, except <code>get_min_child</code>. I would suggest renaming it to <code>min_child_index</code> to be consistent.</p></li>\n<li><p>Don't write the whole branch on the same line. This decreases readability. Instead of</p>\n\n<pre><code>if (2*index + 2 &lt; heap.size()) return 2;\nelse if (2*index + 1 &lt; heap.size()) return 1;\nelse return 0;\n</code></pre>\n\n<p>Do</p>\n\n<pre><code>if (2*index + 2 &lt; heap.size())\n return 2;\nelse if (2*index + 1 &lt; heap.size())\n return 1;\nelse\n return 0;\n</code></pre></li>\n<li><p>In <code>left_child_index</code> and <code>right_child_index</code>, <code>ind</code> can be computed in the <code>if</code> statement. (C++17)</p></li>\n<li><p>You <code>swap(heap[0], heap.back())</code> then immediately <code>heap.pop_back()</code>. You are not doing heap sort, you are popping the value. Just <code>heap[0] = heap.back()</code>.</p></li>\n<li><p>Incidentally, the standard library offers a couple of <a href=\"https://en.cppreference.com/w/cpp/algorithm#Heap_operations\" rel=\"noreferrer\">heap operations</a>, and also <a href=\"https://en.cppreference.com/w/cpp/container/priority_queue\" rel=\"noreferrer\"><code>priority_queue</code></a>. Maybe you can use them to simplify your implementation.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T22:11:53.720", "Id": "434029", "Score": "0", "body": "This is really good! Thank you. I'll go through these and improve my code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T11:26:53.817", "Id": "223801", "ParentId": "223785", "Score": "6" } }, { "body": "<p><a href=\"/u/188857\">L. F.</a> gave a good review, but there is more:</p>\n<ol>\n<li><p>Exceptions are not for programmer errors. That's what asserts are for.</p>\n</li>\n<li><p>Modularise your code:</p>\n<p>Extract <code>down_heap()</code> and <code>up_heap()</code> as free functions, making the algorithm available for anyone wanting to manipulate a heap.<br />\nThey should accept an iterator-range and a comparator, with the default being <code>std::less&lt;&gt;()</code>.</p>\n</li>\n<li><p>Mark things <code>noexcept</code> if you can. Consider conditional <code>noexcept</code> too.</p>\n</li>\n<li><p>Also, make them <code>constexpr</code> if applicable.</p>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T15:12:01.003", "Id": "223874", "ParentId": "223785", "Score": "1" } } ]
{ "AcceptedAnswerId": "223801", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T06:48:57.863", "Id": "223785", "Score": "4", "Tags": [ "c++", "reinventing-the-wheel", "heap" ], "Title": "Min Heap implementation [C++]" }
223785
<p>I've been studying the BST code in Paul Graham's ANSI Common Lisp.</p> <p>He provides (my comments):</p> <pre class="lang-lisp prettyprint-override"><code>(defun bst-min (bst) (and bst ; [3] (or (bst-min (node-l bst)) bst))) ; [4] (defun bst-max (bst) (and bst ; [5] (or (bst-max (node-r bst)) bst))) ; [6] ;; [1] How do you find min and max of a bst? ;; Recall, the core point is that all items in left subtree are lower, ;; and all items in right subtree are higher, &amp; this holds for the whole ;; tree, -otherwise binary search would miss-, and not just within a ;; single parent child relationship. ;; [2] Therefore, to find min, we just need to go left until we can go left ;; no more, &amp; that's the min. If the above property didn't hold, you ;; might go left, then right, then left, and that final one there ;; could be as low as you like; but no, it must be greater than its ;; ancestor of which it is a right child. ;; [3] A null node has no min. The base case. Returns nil if bst is empty. ;; [4] For a non null node, the min is either the min of its left node, or ;; if that's null, then it's this node, instead. ;; [5] A null node has no max. The base case. Returns nil if bst is empty. ;; [6] For a non null node, the max is either the max of its right node, or ;; if that's null, then it's this node, instead. </code></pre> <p>I find this code more or less fine, but I still find it <em>not easy to read</em> or <em>cognitively process</em>.</p> <p>I'm wondering whether that subjective fact is a feature of the code itself (i.e., is the code really hard to read), or whether it's something I need to stick with and then it will become very natural; remembering Hickey's advice about lisp that it is simple but not easy.</p> <p>So, I produced this version by translating from a java implementation. It's easier for me to read (currently).</p> <pre class="lang-lisp prettyprint-override"><code>(defun bst-min (bst) (if (null (node-l bst)) bst (bst-min (node-l bst)))) (defun bst-max (bst) (if (null (node-r bst)) bst (bst-max (node-r bst)))) </code></pre> <p>Is the first version somehow a relic of former days? Would anyone program like that now?</p> <p>Question I would like to ask helpful peeps here is: <strong><em>which version would you favour and why?</em></strong></p>
[]
[ { "body": "<p>The aspect of the code that may cause difficulty to those new to Lisp appears to be the fact that in Common Lisp, <code>nil</code> has two meanings. It's the value of an empty list <code>()</code> and it's also <code>false</code> when used in boolean context. So when we have something like <code>(or '(1 2 3) ())</code> the first non-<code>NIL</code> list is returned. When we use <code>and</code> it returns the last item if all items are true (that is, all lists are nonempty if we pass in lists). If you keep those facts in mind, you'll see that the first code is both consistent and logical. See also <a href=\"https://stackoverflow.com/questions/23826145/what-is-the-exact-difference-between-null-and-nil-in-common-lisp\">https://stackoverflow.com/questions/23826145/what-is-the-exact-difference-between-null-and-nil-in-common-lisp</a></p>\n\n<p>I'd probably write the code the first way because it's a more compact way of expressing what you've done with <code>if</code> and also only evaluates <code>node-l</code> once instead of twice. But then, I'd still write <code>car</code> instead of <code>first</code>, so maybe I'm a relic of former days as well. :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T16:08:53.993", "Id": "433985", "Score": "0", "body": "I do understand that point --the evaluation rules of the boolean operators as you have explained. I was proposing that even though we all understand how the code works (in the sense of being able to work it out if we examine it carefully), nevertheless it is still hard to process at first glance. Can you process code like that in a single glance? That's my really my point." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T16:12:07.110", "Id": "433986", "Score": "1", "body": "When I see logical operators used with lists, yes, it's pretty clear to me what's happening. It's a Lisp idiom that will come to you after more practice. My Lisp is rusty, but that's one thing that I remembered, if that's of any help to you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T18:59:01.090", "Id": "434000", "Score": "0", "body": "I've also updated the answer to hopefully better explain that it's not you personally, but *anyone* new to Lisp that may find this a bit obtuse at first. Like many language idioms, this is acquired through practice and time." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T12:28:29.053", "Id": "223805", "ParentId": "223791", "Score": "6" } }, { "body": "<p>You are asking:</p>\n\n<blockquote>\n <p>which version would you favour and why?</p>\n</blockquote>\n\n<p>Instead of answering directly to your question, I will try to show why that formulation is not, at least in my opinion, “a relic of former days”, but quite idiomatic for Common Lisp (and other “terse” languages). My attempt is done by first recalling an important concept of the language, and then by showing how to apply this concept to your definition of the function, by successive refining of it.</p>\n\n<p>In Common Lisp there is the concept of “Generalized Boolean”: the symbol <code>nil</code> (which represents also the empty list), represents <code>false</code> and <em>all</em> the other objects represent <code>true</code>. The concept is so deeply rooted in the language, and it so frequently used in defining primitive functions and special forms, that it has become an habit of programmers in this language to rely on this concept as much as possible, in order to shorten (and in some way to simplify) the code.</p>\n\n<p>Let’s start from your definition:</p>\n\n<pre><code>(defun bst-min (bst)\n (if (null (node-l bst))\n bst\n (bst-min (node-l bst))))\n</code></pre>\n\n<p>First of all, this definition does not work for the edge case in which the tree is empty. In this case, <code>(node-l bst)</code> causes the error: <code>The value NIL is not of the expected type NODE</code>.</p>\n\n<p>Let’s try to correct it by adding a check before that case:</p>\n\n<pre><code>(defun bst-min (bst)\n (cond ((null bst) nil)\n ((null (node-l bst)) bst)\n (t (bst-min (node-l bst)))))\n</code></pre>\n\n<p>Now we can note that the first two branches of the conditional have the same result: <code>bst</code> (which is <code>nil</code> in the first case), so that we can simplify the code by <code>or</code>ing the two conditions:</p>\n\n<pre><code>(defun bst-min (bst)\n (if (or (null bst) (null (node-l bst)))\n bst\n (bst-min (node-l bst)))))\n</code></pre>\n\n<p>Since both the conditions of the <code>or</code> test the “emptyness” of an object (i.e. if it is equal to <code>nil</code>), for the concept of generalized boolean we can consider that <code>(null x)</code> is equivalent to <code>(not x)</code>, and <code>or</code> with two <code>not</code> can be “simplified” to an <code>and</code> with positive tests and inversion of the branches of the <code>if</code>:</p>\n\n<pre><code>(defun bst-min (bst)\n (if (and bst (node-l bst))\n (bst-min (node-l bst))\n bst))\n</code></pre>\n\n<p>Note that this version is conceptually simpler than the previous versions, correct and more understandable (at least for me!).</p>\n\n<p>However, we can note the presence of still an annoying point: <code>(node-l bst)</code> is called twice. </p>\n\n<p>To remove the double call, we can note that, assuming that <code>bst</code> is not null, now the recursive call, <code>(bst-min (node-l bst))</code> gives the correct result both if <code>(node-l bst)</code> is present or not (in fact we have modified the function to treat the <code>nil</code> case). So we can call only once the selector by first trying <code>bst-min</code> on it, and, if it returns <code>nil</code>, by returning <code>bst</code> instead. This is done with the macro <code>or</code>, that returns the first non-null argument by evaluating them from the left:</p>\n\n<pre><code>(defun bst-min (bst)\n (if bst\n (or (bst-min (node-l bst)) bst)\n bst))\n</code></pre>\n\n<p>which is equivalent to:</p>\n\n<pre><code>(defun bst-min (bst)\n (if bst\n (or (bst-min (node-l bst)) bst)\n nil)) ; &lt;- note this, which is different from the previous definition\n</code></pre>\n\n<p>The idiomatic way of writing the previous definition in Common Lisp is to use <code>when</code> instead of <code>if</code>, since the former returns <code>nil</code> when the condition is false:</p>\n\n<pre><code>(defun bst-min (bst)\n (when bst\n (or (bst-min (node-l bst)) bst)))\n</code></pre>\n\n<p>which is finally equivalent (from the point of view of the computation performed) to the Graham's formulation. In fact, by calling <code>macroexpand-1</code> in SBCL on the two bodies gives exactly the same result:</p>\n\n<pre><code>(IF BST (OR (BST-MIN (NODE-L BST)) BST))\n</code></pre>\n\n<p>So both definitions can be considered “idiomatic”, with that of Graham a little more “lispy”, given the homogenous use of logical operators.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T21:05:07.170", "Id": "434014", "Score": "0", "body": "Nice catch on the bug if there's an empty tree. Good answer!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T22:08:57.323", "Id": "434028", "Score": "0", "body": "A great answer Renzo, thank you. I'll study it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-11T10:18:15.457", "Id": "434268", "Score": "0", "body": "The `when` form is a nice clarification for me at this point, but, onwards! Strangely I think this small function itself tells us a lot about what a BST is..." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T20:31:10.790", "Id": "223830", "ParentId": "223791", "Score": "6" } }, { "body": "<blockquote>\n <p>Can you process code like that in a single glance? That's my really my\n point.</p>\n</blockquote>\n\n<p>Yes, and it is in fact a way of expressing code that I miss in other languages, where the equivalent code feels needlessly verbose to me. This is the same for ternary operators when you are accustomized to <code>if</code>-expressions (as opposed to <code>if</code>-statements). And just like ternary operators, you can abuse the feature to produce unreadable code.</p>\n\n<p>The example you give, however, is quite easy to read sequentially:</p>\n\n<ul>\n<li><p><code>bst-min</code> is given by an expression that depends on <code>bst</code>.</p></li>\n<li><p><code>(and bst ...)</code>: in case <code>bst</code> is nil, I can stop reading here because I know the result is nil. Like an <em>early return</em>, this remove burden on your brain by first taking care of corner cases. Otherwise, the result is whatever <code>...</code> returns. In <code>...</code> I can keep reading while assuming <code>bst</code> is non-nil. I also know from here that any recursive call may evaluate to <code>nil</code>.</p></li>\n<li><p><code>(or (bst-min (node-l bst)) bst)))</code>: I would have added a newline before the second <code>bst</code>, but this is still readable; the min is given by a recursive call with the left node of <code>bst</code>; if however that value is nil, use <code>bst</code> instead.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-12T08:52:54.063", "Id": "224016", "ParentId": "223791", "Score": "2" } } ]
{ "AcceptedAnswerId": "223830", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T08:29:59.073", "Id": "223791", "Score": "3", "Tags": [ "comparative-review", "common-lisp" ], "Title": "Find minimum value in a BST: using boolean operators, and using conditionals" }
223791
<p>I need to make a function like these two, but at least an order of magnitude faster in python. Any tips or tricks?</p> <p>These functions inputs are nested lists, like: <code>request_parameters = [1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, [110, 111, 112, 113, 114]] </code> Their output should be: <code>[[1, 2, 3, 4, 5, 110], [1, 2, 3, 4, 5, 111], [1, 2, 3, 4, 5, 112], [1, 2, 3, 4, 5, 113], [1, 2, 3, 4, 5, 114]]</code></p> <p>OR a numpy.ndarray:</p> <pre><code>[[ 1 2 3 4 5 110] [ 1 2 3 4 5 111] [ 1 2 3 4 5 112] [ 1 2 3 4 5 113] [ 1 2 3 4 5 114]] </code></pre> <p>A unit test is on the way...</p> <p>input:</p> <pre><code>request_parameters = [1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, [110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180]] </code></pre> <p>Output:</p> <pre><code>[[1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 110] ... ... ... [1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 180]] </code></pre> <hr> <pre><code>import numpy as np request_parameters = [1, 2, 3, 4, 5, [10, 11, 12, 13, 14]] def transform_nested_list(request_parameters: list) -&gt; np.ndarray: """ Generate np.ndarray from a nested list """ abc_ids = np.asarray(request_parameters[-1]) #print(abc_ids) all_except_id = np.asarray(request_parameters[0:-1]) #print(all_except_id) all_subrequest = np.hstack([all_except_id, abc_ids[0]]) for element in abc_ids[1:]: row = np.hstack([all_except_id, element]) all_subrequest = np.vstack([all_subrequest, row]) #print(all_subrequest) #print(type(all_subrequest)) return (all_subrequest) import copy def old_transform_nested_list(request_parameters: list) -&gt; list: abc_ids = np.asarray(request_parameters[-1]) all_except_id = (request_parameters[0:-1]) request_list = [] subrequest = [all_except_id] for single_id in abc_ids: #print(single_id) subrequest = copy.deepcopy(all_except_id) subrequest.append(single_id.astype(int)) request_list.append(subrequest) #print(request_list) #print(type(request_list)) return request_list import datetime loop = 10000 start = datetime.datetime.now() for i in range(loop): transform_nested_list(request_parameters) end = datetime.datetime.now() print((end-start).total_seconds()) start = datetime.datetime.now() for i in range(loop): old_transform_nested_list(request_parameters) end = datetime.datetime.now() print((end-start).total_seconds()) </code></pre> <blockquote> <p>> 1.111902, 0.886634 [Finished in 2.2s]</p> </blockquote> <p>Got a bit better results, but still not good enough:</p> <pre><code>import itertools def flatten(container): for i in container: if isinstance(i, (list,tuple)): for j in flatten(i): yield j else: yield i def old_tuple_transform_nested_list(request_parameters: list) -&gt; list: abc_ids = np.asarray(request_parameters[-1]) all_except_id = (request_parameters[0:-1]) request_list = [] subrequest = tuple(all_except_id) for single_id in abc_ids: toupled_subrequest = tuple([subrequest, [single_id]]) chain = list(itertools.chain(*toupled_subrequest)) subrequest_list = list(flatten(chain)) request_list.append(subrequest_list) #print(request_list) #print(type(request_list)) return request_list </code></pre> <p>A better version for longer lists:</p> <pre><code>def longer_vector_transformrequest(requestparameters: list) -&gt; list: ids = np.asarray(requestparameters[-1]) allexceptid = np.asarray(requestparameters[0:-1]) subrequest = np.append(allexceptid, 0) allsubrequest = np.empty((len(ids),len(requestparameters))) for i in range(len(ids)): subrequest[-1] = ids[i] allsubrequest[i] = subrequest return allsubrequest </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T10:47:10.307", "Id": "433941", "Score": "0", "body": "Could you explain what these methods do? Could you provide some unit tests?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T10:49:36.087", "Id": "433943", "Score": "1", "body": "Sure, \n\nThey take a nested list - as above noted - request_parameters\n\nAnd return an other nested list: \n[[1, 2, 3, 4, 5, 10], [1, 2, 3, 4, 5, 11], [1, 2, 3, 4, 5, 12], [1, 2, 3, 4, 5, 13], [1, 2, 3, 4, 5, 14]]\n\nor an numpy.ndarray\n\n[[ 1 2 3 4 5 10]\n [ 1 2 3 4 5 11]\n [ 1 2 3 4 5 12]\n [ 1 2 3 4 5 13]\n [ 1 2 3 4 5 14]]\n\nThis is why i left all the print functions in my function in comments so with the input you can easily test. However, I am going to cover this with a unite test in a minute." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T10:55:53.843", "Id": "433947", "Score": "0", "body": "To make it easier to understand that is why i usually use typehints" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T12:10:29.943", "Id": "433965", "Score": "0", "body": "Yeh, going to update in a sec" } ]
[ { "body": "<p>First and foremost: <strong>Never</strong> use <code>datetime</code> to measure performance! There is <a href=\"https://docs.python.org/3/library/timeit.html\" rel=\"nofollow noreferrer\"><code>timeit</code></a> and <a href=\"https://docs.python.org/3/library/profile.html\" rel=\"nofollow noreferrer\"><code>profile/cProfile</code></a> for that. With that out of the way, let's talk about NumPy.</p>\n\n<p>Python in general does not like loops if you want to go fast. NumPy can help you here since a lot of the heavy lifting can be done by the C backend where loops are orders of magnitudes faster. But you have to allow it to play its strengths. <a href=\"https://jakevdp.github.io/PythonDataScienceHandbook/02.07-fancy-indexing.html\" rel=\"nofollow noreferrer\">Broadcasting and slicing</a> to the rescue!</p>\n\n<pre><code>def slice_transformrequest(request_parameters: list):\n ids = request_parameters[-1]\n allexceptid = request_parameters[:-1]\n\n # create an empty array of the appropriate size\n transformed = np.empty((len(ids), len(allexceptid)+1))\n # fill all but the ID column\n transformed[:, :-1] = allexceptid\n # now fill the ID column\n transformed[:, -1] = ids\n\n return transformed\n</code></pre>\n\n<p>Now to the timing part:</p>\n\n<pre><code>import timeit\n\nn_loops = 10000\nrequest_parameters = [\n 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15,\n [\n 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122,\n 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135,\n 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148,\n 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161,\n 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174,\n 175, 176, 177, 178, 179, 180\n ]\n]\n\nstart = timeit.default_timer()\nfor i in range(n_loops):\n transform_nested_list(request_parameters)\nend = timeit.default_timer()\nprint(f\"transform_nested_list: {end-start:.3f}s\")\n\nstart = timeit.default_timer()\nfor i in range(n_loops):\n old_transform_nested_list(request_parameters)\nend = timeit.default_timer()\nprint(f\"old_transform_nested_list: {end-start:.3f}s\")\n\nstart = timeit.default_timer()\nfor i in range(n_loops):\n longer_vector_transformrequest(request_parameters)\nend = timeit.default_timer()\nprint(f\"longer_vector_transformrequest: {end-start:.3f}s\")\n\nstart = timeit.default_timer()\nfor i in range(n_loops):\n slice_transformrequest(request_parameters)\nend = timeit.default_timer()\nprint(f\"slice_transformrequest: {end-start:.3f}s\")\n\n</code></pre>\n\n<p>And the results:</p>\n\n<pre><code>transform_nested_list: 11.231s\nold_transform_nested_list: 8.375s\nlonger_vector_transformrequest: 0.623s\nslice_transformrequest: 0.140s\n</code></pre>\n\n<p>About 4x faster than your fastest solution and about 80x faster than <code>transform_nested_list</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T12:24:55.750", "Id": "223804", "ParentId": "223795", "Score": "1" } } ]
{ "AcceptedAnswerId": "223804", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T09:40:37.910", "Id": "223795", "Score": "0", "Tags": [ "python", "performance", "numpy" ], "Title": "Nested list performance tuning" }
223795
<h2>Introduction</h2> <p>I used React to write a component, which is meant to be a faithful emulation of the input for "Tags" which you see at the top of every question/topic on SE.</p> <p><strong>Why this project?</strong></p> <p>If you're wondering why I did that, it was because (apart from a chance it might eventually become useful as a live product), it's an example of a data-driven or user-defined content -- not just static HTML pages -- for which e.g. React might be a useful and relatively modern development tool.</p> <p>I wanted to learn React, and to verify that I had learned it. This seemed a suitable project:</p> <ul> <li>Big enough to be interesting</li> <li>Small enough to be feasible</li> <li>The UI design is well-specified (i.e. evident or documented, can be inspected in every detail), so I could concentrate on implementing the UI and not on designing it.</li> </ul> <p>So far as I know there have been <a href="https://meta.stackexchange.com/a/37953/139866">at least a couple of dozen</a> SE clones written over the years -- none of which I've looked at, and for all I know none using React.</p> <p><strong>Why this component?</strong></p> <p>I chose this component for review, as opposed to other source files in the project, for two reasons:</p> <ul> <li>I found this the most difficult to implement -- it surprised me how much code it needed -- and I don't see an obvious way to refactor it to improve its readability or maintainability</li> <li>I know I took some liberties in the other components -- e.g. writing some perhaps-overly-clever hooks, and several functions that aren't "function components" -- if I were reviewing those I suppose I'd find them easy to comment on. But <em>this</em> component is as orthodox as I could make it.</li> </ul> <p><strong>What?</strong></p> <p>"It's an emulation of the tag editor" defines the the functional spec -- or see also the "Appearance and behaviour" section at the top of the component's README included below.</p> <p>The UI output looks e.g. like this when styled:</p> <p><a href="https://i.stack.imgur.com/vCgTJ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/vCgTJ.png" alt="enter image description here"></a></p> <p>If you'd like to try/exercise it, it's running here : <a href="https://react-forum2.herokuapp.com/discussions/new" rel="noreferrer">https://react-forum2.herokuapp.com/discussions/new</a></p> <h2>EditorTags.tsx</h2> <p>Here is the source code for review.</p> <p>I find it hard to read here, with scrollbars -- you may prefer to <a href="https://github.com/cwellsx/react-forum/blob/f058509921d04ac93d12cb589e8d6ae221ed8fc8/src/react/EditorTags.tsx" rel="noreferrer">read it on GitHub</a>.</p> <pre><code>import React from 'react'; import './EditorTags.css'; // this is to display a little 'x' SVG -- a Close icon which is displayed on each tag -- clicking it will delete the tag // also to display a little '(!)' SVG -- an Error icon which is displayed in the element, if there's a validation error import * as Icon from "../icons"; // this simply displays red text if non-empty text is passed to its errorMessage property import { ErrorMessage } from './ErrorMessage'; // these are the properties of an existing tag, used or displayed by the TagDictionary interface TagCount { key: string, summary?: string, count: number } // these are properties to configurare the validation of tags interface Validation { // whether a minimum number of tags must be defined, e.g. 1 minimum: boolean, // whether a maximum number of tags must be defined, e.g. 5 maximum: boolean, // whether the user can create new tags, or whether tags must match what's already in the dictionary canNewTag: boolean, // whether the show validation error messages -- they're hidden until the user first presses the form's submit button showValidationError: boolean, // the href used for the link to "popular tags" in the validation error message -- i.e. "/tags" hrefAllTags: string } // the results are pushed back to the parent via this callback export interface OutputTags { tags: string[], isValid: boolean }; type ParentCallback = (outputTags: OutputTags) =&gt; void; // this defines the properties which you pass to the EditorTags functional component interface EditorTagsProps extends Validation { // the input/original tags to be edited (or an empty array if there are none) inputTags: string[], // the results are pushed back to the parent via this callback result: ParentCallback, // a function to fetch all existing tags from the server (for tag dictionary lookup) getAllTags: () =&gt; Promise&lt;TagCount[]&gt; }; /* This source file is long and has the following sections -- see also [EditorTags](./EDITORTAGS.md) # Defined outside the React function component: - All the type definitions - Assert - ParentCallback - Context - State - RenderedElement - RenderedState - InputElement - InputState - MutableState - TagDictionary - The reducer - action types - reducer - Various helper functions - stringSplice - log and logRenderedState - getInputIndex - getElementStart and getWordStart - assertElements and assertWords - getTextWidth - handleFocus - Functions which construct the RenderedState - renderState - initialState # Defined inside the React function component: - React hooks - errorMessage - assert (a function which uses errorMessage and is required by initialState) - state - inputRef (data which is used by some of the event handlers) - Event handlers (which dispatch to the reducer) - getContext - handleEditorClick - handleDeleteTag - handleTagClick - handleChange - handleKeyDown - handleHintResult - Tag is a FunctionComponent to render each tag - The return statement which yields the JSX.Element from this function component # Other function components to display the drop-down hints - ShowHints - ShowHint */ // you could temporarily change this to enable logging, for debugging const isLogging = false; /* All the type definitions */ type Assert = (assertion: boolean, message: string, extra?: () =&gt; object) =&gt; void; // this is extra data which event handlers pass (as part of the action) from the function component to the reducer interface Context { inputElement: InputElement; assert: Assert; result: ParentCallback; tagDictionary?: TagDictionary; validation: Validation; }; // this is like the input data from which the RenderedState is calculated // these and other state elements are readonly so that event handlers must mutate MutableState instead interface State { // the selection range within the buffer // this may even span multiple words, in which case all the selected words are in the &lt;input&gt; element readonly selection: { readonly start: number, readonly end: number }, // the words (i.e. the tags when this is split on whitespace) readonly buffer: string }; // this interface identifies the array of &lt;input&gt; and &lt;Tag&gt; elements to be rendered, and the word associated with each interface RenderedElement { // the string value of this word readonly word: string; // whether this word is rendered by a Tag element or by the one input element readonly type: "tag" | "input"; // whether this word matches an existing tag in the dictionary readonly isValid: boolean; }; // this interface combines the two states, and is what's stored using useReducer interface RenderedState { // the buffer which contains the tag-words, and the selection within the buffer readonly state: State; // how that's rendered i.e. the &lt;input&gt; element plus &lt;Tag&gt; elements readonly elements: ReadonlyArray&lt;RenderedElement&gt;; // the current ("semi-controlled") value of the &lt;input&gt; element readonly inputValue: string; // the hints associated with the inputValue, taken from the TagDictionary hints: TagCount[]; // the validation error message (zero length if there isn't one) validationError: string; } // this wraps the current state of the &lt;input&gt; control class InputElement { readonly selectionStart: number; readonly selectionEnd: number; readonly isDirectionBackward: boolean; readonly value: string; readonly isLeftTrimmed: boolean; private readonly inputElement: HTMLInputElement; constructor(inputElement: HTMLInputElement, assert: Assert, stateValue?: string) { let { selectionStart, selectionEnd, selectionDirection, value } = inputElement; log("getInput", { selectionStart, selectionEnd, selectionDirection, value }); assert(!stateValue || stateValue === value, "stateValue !== value"); // TypeScript declaration says these may be null, though I haven't seen that in practice? if (selectionStart === null) { assert(false, "unexpected null selectionStart"); selectionStart = 0; } if (selectionEnd === null) { assert(false, "unexpected null selectionEnd"); selectionEnd = 0; } if (selectionStart &gt; selectionEnd) { assert(false, "unexpected selectionStart &gt; selectionEnd"); selectionStart = 0; } // left trim if the user entered leading spaces let isLeftTrimmed = false; while (value.length &amp;&amp; value[0] === " ") { value = value.substring(1); --selectionStart; --selectionEnd; isLeftTrimmed = true; } this.selectionStart = selectionStart; this.selectionEnd = selectionEnd; this.isDirectionBackward = selectionDirection === "backward"; this.value = value; this.isLeftTrimmed = isLeftTrimmed; this.inputElement = inputElement; } focus(): void { this.inputElement.focus(); } setContent(value: string, start: number, end: number): void { // set the value before the selection, otherwise the selection might be invalid this.inputElement.value = value; this.inputElement.setSelectionRange(start, end); // dynammically readjust the width of the input element to match its content const width = getTextWidth(value + "0"); this.inputElement.style.width = `${width}px`; } toJSON(): string { // JSON.stringify cannot handle `inputElement: HTMLInputElement` so the purpose of this is to exclude that const printable: string[] = [ `start: ${this.selectionEnd}`, `end: ${this.selectionEnd}`, `backward: ${this.isDirectionBackward}`, `value: ${this.value}` ]; return printable.join(", "); } } // this combines the state of the &lt;input&gt; control with the position of the &lt;input&gt; within the RenderedState // it exists only to help the KeyDown event handlers determine whether keys like ArrowLeft will change the selected word // beware that, when this runs, the &lt;input&gt; control's value may not yet have been written to the elements[editing].word class InputState { readonly canMoveLeft: boolean; readonly canMoveRight: boolean; readonly currentStart: number; readonly currentEnd: number; get nextLeft(): number { return this.currentStart - 1; } get nextRight(): number { return this.currentEnd + 1; } constructor(state: RenderedState, inputElement: InputElement, assert: Assert) { const { elements } = state; const { inputIndex, isFirst, isLast } = getInputIndex(elements, assert); const elementStart = getElementStart(elements, inputIndex, assert); const { selectionStart, selectionEnd, isDirectionBackward, value } = inputElement; // if a range is selected then which end of the range is moving? const isLeftMoving = (selectionStart === selectionEnd) || isDirectionBackward; const isRightMoving = (selectionStart === selectionEnd) || !isDirectionBackward; // can move left if at the start of the &lt;input&gt; and if there are other &lt;Tag&gt; elements before the &lt;input&gt; element this.canMoveLeft = selectionStart === 0 &amp;&amp; !isFirst &amp;&amp; isLeftMoving; // can move right if at the end of the &lt;input&gt; and if there are other &lt;Tag&gt; elements after the &lt;input&gt; element this.canMoveRight = selectionEnd === value.length &amp;&amp; !isLast &amp;&amp; isRightMoving; this.currentStart = elementStart + selectionStart; this.currentEnd = elementStart + selectionEnd; } removeSelected(mutableState: MutableState): void { mutableState.remove(this.currentStart, this.currentEnd); } } // this is a class which event-handlers use to mutate the current state // its methods are whatever primitive methods are required by the event handlers which use it // it's contructed from the previous RenderedState, then mutated, and then eventually returns the new RenderedState class MutableState { private selection: { start: number, end: number }; private buffer: string; // store the elements as word because until the mutation stops we don't know which will be the input element // e.g. what's currently current input element may be deleted and/or the input may be moved to a different word private words: string[]; private context: Context; constructor(renderedState: RenderedState, context: Context) { // load the data from the previous state into non-readonly elements const { state, elements } = renderedState; this.selection = state.selection; this.buffer = state.buffer; this.words = elements.map(x =&gt; x.word); // use concat with no parameters to convert from ReadonlyArray to [] this.context = context; // stash the input -- i.e. update the buffered data to reflect whatever is currently in the &lt;input&gt; element const { inputIndex } = getInputIndex(elements, context.assert); const { value, selectionStart, selectionEnd } = context.inputElement; this.replaceElement(inputIndex, value, { start: selectionStart, end: selectionEnd }); log("MutableState", { selection: this.selection, buffer: this.buffer, words: this.words }); } // called when the event handler has finished mutating this MutableState getState(): RenderedState { const state: State = { buffer: this.buffer, selection: this.selection }; const { assert, inputElement, tagDictionary, validation } = this.context; const renderedState: RenderedState = renderState(state, assert, validation, inputElement, tagDictionary); logRenderedState("MutableState.getState returning", renderedState); // do a callback to the parent to say what the current tags are (excluding the empty &lt;input&gt; word if there is one) const tags: string[] = renderedState.elements.map(element =&gt; element.word).filter(word =&gt; !!word.length); const isValid = !renderedState.validationError.length; this.context.result({ tags, isValid }); return renderedState; } replaceElement(index: number, newValue: string, selection?: { start: number, end: number }): void { this.invariant(); const editingWord: string = this.words[index]; // a special case is when the input element is empty and the last word -- then it's beyond the end of the buffer const nWords = this.words.length - ((this.words[this.words.length - 1] === "") ? 1 : 0); // if the new word matches the existing word then the replace will do nothing if (editingWord === newValue) { return; } const wordStart = getWordStart(this.words, index, this.context.assert); // possibly insert or delete whitespace before or after the word being added or deleted // if we delete the whole word and this isn't the last word then also delete the space after this word const deleteSpaceAfter = newValue === "" &amp;&amp; index &lt; nWords - 1; if (deleteSpaceAfter) { this.assertSpaceAt(wordStart + editingWord.length); } // if we delete the last word then delete the space before it const deleteSpaceBefore = newValue === "" &amp;&amp; index === nWords - 1 &amp;&amp; index !== 0; if (deleteSpaceBefore) { this.assertSpaceAt(wordStart - 1); } // if we add another word beyond a previous word (i.e. beyond the end of the buffer) then insert the space before it const addSpaceBefore = (wordStart === this.atBufferEnd()) &amp;&amp; index; if (addSpaceBefore) { // assert this word was previously empty and is being changed to non-empty this.context.assert(!editingWord.length &amp;&amp; !!newValue.length, "unexpected at end of buffer"); } log("replaceElement", { deleteSpaceAfter, deleteSpaceBefore, addSpaceBefore }); // calculate the deleteCount, and adjust deleteCount and/or wordStart and/or newValue, to insert or delete spaces const deleteCount: number = editingWord.length + (deleteSpaceAfter || deleteSpaceBefore ? 1 : 0); const spliceStart: number = (deleteSpaceBefore || addSpaceBefore) ? wordStart - 1 : wordStart; const spliceValue: string = (!addSpaceBefore) ? newValue : " " + newValue; // mutate the buffer this.buffer = stringSplice(this.buffer, spliceStart, deleteCount, spliceValue); // mutate the word in the elements array if (newValue.length) { this.words[index] = newValue; } else { this.words.splice(index, 1); } // adjust the selected range after mutating the text if (selection) { // called from constructor where new selection is taken from the &lt;input&gt; element const wordStart = getWordStart(this.words, index, this.context.assert); this.selection.start = selection.start + wordStart; this.selection.end = selection.end + wordStart; } else { // called from onDeleteTag where existing selection must be adjusted to account for the deleted element if (this.selection.start &gt; wordStart) { this.selection.start -= deleteCount; } if (this.selection.end &gt; wordStart) { this.selection.end -= deleteCount; } } this.invariant(); } private invariant() { // we mutate the state but because we make several mutations this asserts that the state remains sane or predictable assertWords(this.words, this.buffer, this.context.assert); } private assertSpaceAt(index: number) { this.context.assert(this.buffer.substring(index, index + 1) === " ", "expected a space at this location"); } remove(start: number, deleteCount: number): void { this.buffer = stringSplice(this.buffer, start, deleteCount, ""); } // the start and end of the selection range are usually the same setSelectionBoth(where: number): void { this.selection.start = where; this.selection.end = where; } setSelectionStart(where: number): void { this.selection.start = where; } setSelectionEnd(where: number): void { this.selection.end = where; } // the location of the selection index beyond the end of the buffer (starting the empty, to-be-defined next tag) atBufferEnd(): number { return (this.buffer.length) ? this.buffer.length + 1 : 0; } selectEndOf(index: number) { const wordStart = getWordStart(this.words, index, this.context.assert); this.setSelectionBoth(wordStart + this.words[index].length); } focus() { this.context.inputElement.focus(); } }; // we want to display a maximum of 6 hints const maxHints = 6; // this is a class to lookup hints for existing tags which match the current input value class TagDictionary { // the current implementation repeatedly iterates the whole dictionary // if that's slow (because the dictionary is large) in future we could partition the dictionary by letter private readonly tags: TagCount[]; constructor(tags: TagCount[]) { this.tags = tags; } getHints(inputValue: string, elements: RenderedElement[]): TagCount[] { if (!inputValue.length) { return []; } // don't want what we already have i.e. what matches other tags const unwanted: string[] = elements.filter(x =&gt; x.type === "tag").map(x =&gt; x.word); // we'll select tags in the following priority: // 1. Tags where the inputValue matches the beginning of the tag // 2. If #1 returns too many tags, then prefer tags with a higher count because they're the more popular/more likely // 3. If #1 doesn't return enough tags, then find tags where the inputValue matches within the tag // 4. If #3 returns too many tags, then prefer tags with a higher count const findTags = (start: boolean, max: number): TagCount[] =&gt; { const found = (this.tags.filter(tag =&gt; start ? tag.key.startsWith(inputValue) : tag.key.substring(1).includes(inputValue))).filter(x =&gt; !unwanted.includes(x.key)); // higher counts first, else alphabetic found.sort((x, y) =&gt; (x.count === y.count) ? x.key.localeCompare(y.key) : y.count - x.count); return found.slice(0, max); } const found = findTags(true, maxHints); return (found.length === maxHints) ? found : found.concat(findTags(false, maxHints - found.length)); } exists(inputValue: string): boolean { return this.tags.some(tag =&gt; tag.key === inputValue); } toJSON(): string { // not worth logging all the elements return `${this.tags.length} elements`; } } /* The reducer */ interface ActionEditorClick { type: "EditorClick", context: Context }; interface ActionHintResult { type: "HintResult", context: Context, hint: string, inputIndex: number }; interface ActionDeleteTag { type: "DeleteTag", context: Context, index: number }; interface ActionTagClick { type: "TagClick", context: Context, index: number }; interface ActionKeyDown { type: "KeyDown", context: Context, key: string, shiftKey: boolean }; interface ActionChange { type: "Change", context: Context }; type Action = ActionEditorClick | ActionHintResult | ActionDeleteTag | ActionTagClick | ActionKeyDown | ActionChange; function isEditorClick(action: Action): action is ActionEditorClick { return action.type === "EditorClick"; } function isHintResult(action: Action): action is ActionHintResult { return action.type === "HintResult"; } function isDeleteTag(action: Action): action is ActionDeleteTag { return action.type === "DeleteTag"; } function isTagClick(action: Action): action is ActionTagClick { return action.type === "TagClick"; } function isKeyDown(action: Action): action is ActionKeyDown { return action.type === "KeyDown"; } function isChange(action: Action): action is ActionChange { return action.type === "Change"; } function reducer(state: RenderedState, action: Action): RenderedState { log("reducer", action); const inputElement = action.context.inputElement; // this function returns a MutableState instance, which is based on the previous state plus the passed-in context // the passed-in context includes the new content of the &lt;input&gt; element function getMutableState(): MutableState { logRenderedState("getMutableState", state); return new MutableState(state, action.context); } // this function returns a InputState instance function getInputState(): InputState { return new InputState(state, inputElement, action.context.assert); } if (isChange(action)) { const mutableState: MutableState = getMutableState(); return mutableState.getState(); } if (isEditorClick(action)) { // click on the &lt;div&gt; =&gt; set focus on the &lt;input&gt; within the &lt;div&gt; inputElement.focus(); const mutableState: MutableState = getMutableState(); mutableState.setSelectionBoth(mutableState.atBufferEnd()); return mutableState.getState(); } if (isHintResult(action)) { // click on a hint =&gt; set focus on the &lt;input&gt; inputElement.focus(); const mutableState: MutableState = getMutableState(); mutableState.replaceElement(action.inputIndex, action.hint); mutableState.setSelectionBoth(mutableState.atBufferEnd()); return mutableState.getState(); } if (isDeleteTag(action)) { const mutableState: MutableState = getMutableState(); mutableState.replaceElement(action.index, ""); return mutableState.getState(); } if (isTagClick(action)) { const mutableState: MutableState = getMutableState(); // want to position the cursor at the end of the selected word mutableState.selectEndOf(action.index); // clicking on the tag made the input lose the focus mutableState.focus(); return mutableState.getState(); } if (isKeyDown(action)) { const { key, shiftKey } = action; switch (key) { case "Home": case "ArrowUp": { // move selection to start of first tag const mutableState: MutableState = getMutableState(); mutableState.setSelectionBoth(0); return mutableState.getState(); } case "End": case "ArrowDown": { // move selection to end of last tag const mutableState: MutableState = getMutableState(); mutableState.setSelectionBoth(mutableState.atBufferEnd()); return mutableState.getState(); } case "ArrowLeft": { const inputState: InputState = getInputState(); // we're at the left of the input so traverse into the previous tag const mutableState: MutableState = getMutableState(); const wanted = inputState.nextLeft; if (shiftKey) { mutableState.setSelectionStart(wanted); } else { mutableState.setSelectionBoth(wanted); } return mutableState.getState(); } case "ArrowRight": { const inputState: InputState = getInputState(); // we're at the right of the input so traverse into the next tag const mutableState: MutableState = getMutableState(); const wanted = inputState.nextRight; if (shiftKey) { mutableState.setSelectionEnd(wanted); } else { mutableState.setSelectionBoth(wanted); } return mutableState.getState(); } case "Backspace": { // same as ArrowLeft except also delete the space between the two tags const inputState: InputState = getInputState(); const mutableState: MutableState = getMutableState(); if (shiftKey) { // also delete whatever is selected inputState.removeSelected(mutableState); } const wanted = inputState.nextLeft; mutableState.remove(wanted, 1); mutableState.setSelectionBoth(wanted); return mutableState.getState(); } case "Delete": { // same as ArrowRight except also delete the space between the two tags const inputState: InputState = getInputState(); const mutableState: MutableState = getMutableState(); if (shiftKey) { // also delete whatever is selected inputState.removeSelected(mutableState); } const wanted = inputState.currentStart; mutableState.remove(wanted, 1); mutableState.setSelectionBoth(wanted); return mutableState.getState(); } default: break; } // switch } // if isKeyDown logRenderedState("reducer returning old state", state); return state; } // reducer /* Various helper functions */ // Helper function analogous to Array.splice -- string has built-in slice but no splice // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice function stringSplice(text: string, start: number, deleteCount: number, insert: string): string { // up to but not including start const textStart = text.substring(0, start); const textEnd = text.substring(start + deleteCount); const after = textStart + insert + textEnd; log("stringSplice", { text, start, deleteCount, insert, after }); return after; } function log(title: string, o: object, force?: boolean): void { if (!isLogging &amp;&amp; !force) { return; } const json = JSON.stringify(o, null, 2); console.log(`${title} -- ${json}`); } function logRenderedState(title: string, renderedState: RenderedState): void { log(title, renderedState); } // this identifies the index of the one-and-only &lt;input&gt; element within the array of RenderedElement function getInputIndex(elements: ReadonlyArray&lt;RenderedElement&gt;, assert: Assert) : { inputIndex: number, isFirst: boolean, isLast: boolean } { let inputIndex: number = 0; let counted = 0; for (let i = 0; i &lt; elements.length; ++i) { if (elements[i].type === "input") { ++counted; inputIndex = i; } } assert(counted === 1, "expected exactly one input element") return { inputIndex, isFirst: inputIndex === 0, isLast: inputIndex === elements.length - 1 }; } // the getElementStart and assertElements functions have two versions // i.e. they work with ReadonlyArray&lt;RenderedElement&gt; or ReadonlyArray&lt;string&gt; // that's because the MutableState class works with ReadonlyArray&lt;string&gt; instead of ReadonlyArray&lt;RenderedElement&gt; // because it doesn't yet know the type associated with each word // Helper function to determine the offset into the buffer associated with a given RenderedElement function getElementStart(elements: ReadonlyArray&lt;RenderedElement&gt;, index: number, assert: Assert): number { return getWordStart(elements.map(x =&gt; x.word), index, assert); } function getWordStart(words: ReadonlyArray&lt;string&gt;, index: number, assert: Assert): number { let wordStart = 0; for (let i = 0; i &lt; index; ++i) { const word = words[i]; // +1 because there's a whitespace between i.e. after each word wordStart += word.length + 1; // assert all words are significant (and visible) // it's OK if the last word is empty i.e. if the &lt;input&gt; element is beyond the end of the buffer // that wouldn't trigger this assertion because we're only testing for all i &lt; index assert(!!word.length, "getWordStart unexpected zero-length word"); } return wordStart; } // assert that the state is as predicted function assertElements(elements: ReadonlyArray&lt;RenderedElement&gt;, buffer: string, assert: Assert): void { assertWords(elements.map(x =&gt; x.word), buffer, assert); getInputIndex(elements, assert); elements.forEach((element, index) =&gt; assert(!!element.word.length || (element.type === "input" &amp;&amp; index === elements.length - 1), "unexpected zero-length word")); } function assertWords(words: ReadonlyArray&lt;string&gt;, buffer: string, assert: Assert): void { for (let i = 0; i &lt; words.length; ++i) { const word = words[i]; const wordStart = getWordStart(words, i, assert); const fragment = buffer.substring(wordStart, wordStart + word.length); assert(word === fragment, "assertElements", // don't bother to call JSON.stringify unless the assertion has actually failed () =&gt; { return { word, fragment, wordStart, length: word.length, buffer, words } }); } } function getTextWidth(text: string) { // https://stackoverflow.com/a/21015393/49942 const getContext = (): CanvasRenderingContext2D | undefined =&gt; { if (!(getTextWidth as any).canvas) { const canvas = document.createElement("canvas"); const context = canvas.getContext("2d"); if (!context) { return undefined; } // matches the font famly and size defined in App.css context.font = '14px Arial, "Helvetica Neue", Helvetica, sans-serif'; (getTextWidth as any).canvas = canvas; (getTextWidth as any).context = context; } return ((getTextWidth as any).context) as CanvasRenderingContext2D; } const context = getContext(); if (!context) { return 20; } return context.measureText(text).width; } // see [Simulating `:focus-within`](./EDITORTAGS.md#simulating-focus-within) function handleFocus(e: React.FocusEvent&lt;HTMLElement&gt;, hasFocus: boolean) { function isElement(related: EventTarget | HTMLElement): related is HTMLElement { return (related as HTMLElement).tagName !== undefined; } // read it const target = e.target; const relatedTarget = e.relatedTarget; // relatedTarget is of type EventTarget -- upcast from that to HTMLElement const related: HTMLElement | undefined = (relatedTarget &amp;&amp; isElement(relatedTarget)) ? relatedTarget : undefined; // get the tagName and className of the element const relatedName = (!relatedTarget) ? "!target" : (!related) ? "!element" : related.tagName; const relatedClass = (!related) ? "" : related.className; // log it const activeElement = document.activeElement; const targetName = target.tagName; const activeElementName = (activeElement) ? activeElement.tagName : "!activeElement"; log("handleFocus", { hasFocus, targetName, activeElementName, relatedName, relatedClass }); // calculate it hasFocus = hasFocus || (relatedClass === "hint"); // write the result const div = document.getElementById("tag-both")!; if (hasFocus) { div.className = "focussed"; } else { div.className = ""; } } /* Functions which construct the RenderedState */ // this function calculates a new RenderedState and sets the InputElement content and selection, for a given State value // it's called from initialState and from MutableState function renderState(state: State, assert: Assert, validation: Validation, inputElement?: InputElement, tagDictionary?: TagDictionary) : RenderedState { const elements: RenderedElement[] = []; let editing: number | undefined = undefined; let inputValue: string = ""; function setInput(text: string, start: number, end: number, inputElement: InputElement): void { log("setInput", { text, start, end }); inputElement.setContent(text, start, end); inputValue = text; assert(start &gt;= 0 &amp;&amp; end &lt;= text.length, `setInput invalid range: ${text} ${start} ${end}`) } function addElement(type: "tag" | "input", word: string): void { const isValid: boolean = !word.length || validation.canNewTag || (!!tagDictionary &amp;&amp; tagDictionary.exists(word)); elements.push({ type, word, isValid }); } // split the buffer const words: string[] = state.buffer.split(" ").filter(word =&gt; word.length); const selection = state.selection; // this is where each word starts, an index into the buffer let wordStart = 0; // this accumulates previous words within the selection, when selection is a range which spans more than one word let accumulated: { wordStart: number, start: number, text: string } | undefined = undefined; for (let wordIndex = 0; wordIndex &lt; words.length; ++wordIndex) { const word = words[wordIndex]; // e.g. if a word's length is 1, then the positions within this word are 0 (start) and 1 (end) const wordEnd = wordStart + word.length; if ((selection.start &gt; wordEnd) || (selection.end &lt; wordStart)) { // selection is not in this word // - selection starts beyond the end of the word // - or selection ends before the start of the word addElement("tag", word); } else { if (!inputElement) { // the initialState function should set the selection at the end of the buffer // i.e. beyond any words (if there are any words) // or at the start of the buffer if there are no words, // so that it isn't necessary to set the selection inside the input element // given that the input element hasn't been created in the DOM yet assert(false, "invalid initial state") continue; } // selection includes some of this word // - selection starts on or before the end of the word // - or selection ends on or after the start of the word if (selection.start &gt;= wordStart) { // selection starts in this word if (selection.end &lt;= wordEnd) { // selection starts and ends in this word setInput(word, selection.start - wordStart, selection.end - wordStart, inputElement); editing = elements.length; addElement("input", word); } else { // starts in this word but ends in a future word assert(!accumulated, "shouldn't accumulate anything previously") accumulated = { wordStart, start: selection.start - wordStart, text: word }; } } else { // selection started before this word if (!accumulated) { assert(false, "should have accumulated something previously"); continue; // this is bad but better than referencing accumulated when it's undefined } // add to what's already accumulated, including inter-word whitespace accumulated.text += " " + word; if (selection.end &lt;= wordEnd) { // selection ends in this word setInput(accumulated.text, accumulated.start, selection.end - accumulated.wordStart, inputElement); editing = elements.length; addElement("input", accumulated.text); accumulated = undefined; } else { // selection ends in a future word (and we already added this word to the accumulator) } } } wordStart += word.length + 1; } if (typeof editing === "undefined") { // we haven't pushed the &lt;input&gt; element yet, so push it now editing = elements.length; // if (initializing) then the `input` and `inputRef` values haven't yet been created because the state is created // before they are, via the call to initialState -- but when it is created it's initially empty so that's alright if (inputElement) { // the &lt;input&gt; element is already part of the DOM; reset it now setInput("", 0, 0, inputElement); } addElement("input", ""); } assertElements(elements, state.buffer, assert); const hints: TagCount[] = !tagDictionary ? [] : tagDictionary.getHints(inputValue, elements); // if logging only log the keyword of each hint, otherwise logging the tags' summaries makes it long and hard to read (hints as any).toJSON = () =&gt; "[" + hints.map(hint =&gt; hint.key).join(",") + "]"; function getValidationError(): string { const nWords: number = elements.filter(element =&gt; !!element.word.length).length; const invalid: string[] = elements.filter(element =&gt; !element.isValid).map(element =&gt; element.word); if (nWords &lt; 1 &amp;&amp; validation.minimum) { return "Please enter at least one tag;"; } if (nWords &gt; 5 &amp;&amp; validation.maximum) { return "Please enter a maximum of five tags."; } if (!!invalid.length) { return (invalid.length === 1) ? `Tag '${invalid[0]}' does not match an existing topic.` : `Tags ${invalid.map(word =&gt; "'" + word + "'").join(" and ")} do not match existing topics.` } return ""; } const validationError = getValidationError(); const renderedState: RenderedState = { state, elements, inputValue, hints, validationError }; return renderedState; } // this function calculates the initial state, calculated from props and used to initialize useState function initialState(assert: Assert, inputTags: string[], validation: Validation): RenderedState { assert(!inputTags.some(found =&gt; found !== found.trim()), "input tags not trimmed", () =&gt; { return { inputTags }; }); const buffer = inputTags.join(" "); const start = buffer.length + 1; const state: State = { buffer, selection: { start, end: start } }; log("initialState starting", { inputTags }) const renderedState: RenderedState = renderState(state, assert, validation); logRenderedState("initialState returning", renderedState) return renderedState; } /* EditorTags -- the functional component */ export const EditorTags: React.FunctionComponent&lt;EditorTagsProps&gt; = (props) =&gt; { const { inputTags, result, getAllTags } = props; const validation: Validation = props; /* React hooks */ // this is an optional error message const [errorMessage, setErrorMessage] = React.useState&lt;string | undefined&gt;(undefined); function assert(assertion: boolean, message: string, extra?: () =&gt; object): void { if (!assertion) { if (extra) { const o: object = extra(); const json = JSON.stringify(o, null, 2); message = `${message} -- ${json}`; } // write to errorMessage state means it's displayed by the `&lt;ErrorMessage errorMessage={errorMessage} /&gt;` element setTimeout(() =&gt; { // do it after a timeout because otherwise if we do this during a render then React will complain with: // "Too many re-renders. React limits the number of renders to prevent an infinite loop." setErrorMessage(message); }, 0); console.error(message); } } // see ./EDITOR.md and the definition of the RenderedState interface for a description of this state // also https://fettblog.eu/typescript-react/hooks/#usereducer says that type is infered from signature of reducer const [state, dispatch] = React.useReducer(reducer, inputTags, (inputTags) =&gt; initialState(assert, inputTags, validation)); // this is a dictionary of existing tags const [tagDictionary, setTagDictionary] = React.useState&lt;TagDictionary | undefined&gt;(undefined); logRenderedState("--RENDERING--", state); // useEffect to fetch all the tags from the server exactly once // React's elint rules demand that getAllTags be specified in the deps array, but the value of getAllTags // (which we're being passed as a parameter) is utimately a function at module scope, so it won't vary React.useEffect(() =&gt; { // get tags from server getAllTags() .then((tags) =&gt; { // use them to contruct a dictionary const tagDictionary: TagDictionary = new TagDictionary(tags); // save the dictionary in state setTagDictionary(tagDictionary); }) .catch((reason) =&gt; { // alarm the user setErrorMessage(`getAllTags() failed -- ${reason}`); }); }, [getAllTags]); /* inputRef (data which is used by some of the event handlers) */ const inputRef = React.createRef&lt;HTMLInputElement&gt;(); /* Event handlers (which dispatch to the reducer) */ function getContext(inputElement: HTMLInputElement): Context { return { inputElement: new InputElement(inputElement, assert), assert, result, tagDictionary, validation }; } function handleEditorClick(e: React.MouseEvent) { const isDiv = (e.target as HTMLElement).tagName === "DIV"; if (!isDiv) { // this wasn't a click on the &lt;div&gt; itself, presumably instead a click on something inside the div return; } dispatch({ type: "EditorClick", context: getContext(inputRef.current!) }); } function handleDeleteTag(index: number, e: React.MouseEvent) { dispatch({ type: "DeleteTag", context: getContext(inputRef.current!), index }); e.preventDefault(); } function handleTagClick(index: number, e: React.MouseEvent) { dispatch({ type: "TagClick", context: getContext(inputRef.current!), index }); e.preventDefault(); } function handleChange(e: React.ChangeEvent&lt;HTMLInputElement&gt;) { dispatch({ type: "Change", context: getContext(e.target) }); } function handleKeyDown(e: React.KeyboardEvent) { if (e.key === "Enter") { // do nothing and prevent form submission e.preventDefault(); return; } // apparently dispatch calls the reducer asynchonously, i.e. after this event handler returns, which will be too // late to call e.preventDefault(), and so we need two-stage processing, i.e. some here and some inside the reducer: // - here we need to test whether the action will or should be handled within the reducer // - later in the reducer we need to actually perform the action function newinputState() { const inputElement: InputElement = new InputElement(e.target as HTMLInputElement, assert); return new InputState(state, inputElement, assert); } function isHandled(): boolean { switch (e.key) { case "Home": case "ArrowUp": // move selection to start of first tag return !getInputIndex(state.elements, assert).isFirst; case "End": case "ArrowDown": // move selection to end of last tag return !getInputIndex(state.elements, assert).isLast; case "ArrowLeft": case "Backspace": { const inputState: InputState = newinputState(); return inputState.canMoveLeft; } case "ArrowRight": case "Delete": { const inputState: InputState = newinputState(); return inputState.canMoveRight; } default: break; } // switch return false; } if (isHandled()) { e.preventDefault(); const context: Context = getContext(e.target as HTMLInputElement); dispatch({ type: "KeyDown", context, key: e.key, shiftKey: e.shiftKey }); } } function handleHintResult(outputTag: string) { const { inputIndex } = getInputIndex(state.elements, assert); dispatch({ type: "HintResult", context: getContext(inputRef.current!), hint: outputTag, inputIndex }); } /* Tag is a FunctionComponent to render each tag */ interface TagProps { text: string, index: number, isValid: boolean }; const Tag: React.FunctionComponent&lt;TagProps&gt; = (props) =&gt; { const { text, index, isValid } = props; // https://reactjs.org/docs/handling-events.html#passing-arguments-to-event-handlers // eslint-disable-next-line const close = &lt;a onClick={(e) =&gt; handleDeleteTag(index, e)} title="Remove tag"&gt;&lt;Icon.Close height="12" /&gt;&lt;/a&gt;; const className = isValid ? "tag" : "tag invalid"; return &lt;span className={className} onClick={(e) =&gt; handleTagClick(index, e)}&gt; {text} {close} &lt;/span&gt; } /* The return statement which yields the JSX.Element from this function component */ function showValidationResult() { const showError = props.showValidationError &amp;&amp; !!state.validationError.length; if (!showError) { return { className: "tag-editor", icon: undefined, validationError: undefined }; } const className = "tag-editor invalid validated"; const icon = &lt;Icon.Error className="error" /&gt;; const validationErrorMessage = state.validationError; // use &lt;a href={}&gt; instead of &lt;Link to={}&gt; -- https://github.com/ReactTraining/react-router/issues/6344 const suffix = (validationErrorMessage[validationErrorMessage.length - 1] !== ";") ? undefined : ( &lt;React.Fragment&gt; {"see a list of "} &lt;a href={props.hrefAllTags} target="_blank" rel="noopener noreferrer"&gt;popular tags&lt;/a&gt;{"."} &lt;/React.Fragment&gt; ); const validationError = &lt;p className="error"&gt;{validationErrorMessage} {suffix}&lt;/p&gt;; return { validationError, icon, className }; } const { validationError, icon, className } = showValidationResult(); function getElement(element: RenderedElement, index: number): React.ReactElement { const isValid = !props.showValidationError || element.isValid; return (element.type === "tag") ? &lt;Tag text={element.word} index={index} key={index} isValid={isValid} /&gt; : &lt;input type="text" key="input" ref={inputRef} className={isValid ? undefined : "invalid"} width={10} onKeyDown={handleKeyDown} onChange={handleChange} onFocus={e =&gt; handleFocus(e, true)} onBlur={e =&gt; handleFocus(e, false)} /&gt; } return ( &lt;div id="tag-both" &gt; &lt;div className={className} onClickCapture={handleEditorClick}&gt; {state.elements.map(getElement)} {icon} &lt;/div&gt; &lt;ShowHints hints={state.hints} inputValue={state.inputValue} result={handleHintResult} /&gt; &lt;ErrorMessage errorMessage={errorMessage} /&gt; {validationError} &lt;/div&gt; ); } /* ShowHints */ interface ShowHintsProps { // hints (from dictionary) hints: TagCount[], // the current value of the tag in the editor inputValue: string, // callback of tag selected from list of hints if user clicks on it result: (outputTag: string) =&gt; void } const ShowHints: React.FunctionComponent&lt;ShowHintsProps&gt; = (props) =&gt; { const { hints, inputValue, result } = props; if (!inputValue.length) { return &lt;div className="tag-hints hidden"&gt;&lt;/div&gt;; } return ( &lt;div className="tag-hints"&gt; {!hints.length ? "No results found." : hints.map(hint =&gt; &lt;ShowHint hint={hint} inputValue={inputValue} result={result} key={hint.key} /&gt;)} &lt;/div&gt; ); } interface ShowHintProps { // hints (from dictionary) hint: TagCount, // the current value of the tag in the editor inputValue: string, // callback of tag selected from list of hints if user clicks on it result: (outputTag: string) =&gt; void } const ShowHint: React.FunctionComponent&lt;ShowHintProps&gt; = (props) =&gt; { const { hint, inputValue, result } = props; function getTag(key: string) { const index = key.indexOf(inputValue); return ( &lt;span className="tag"&gt; {(index === -1) ? key : &lt;React.Fragment&gt; {key.substring(0, index)} &lt;span className="match"&gt;{inputValue}&lt;/span&gt; {key.substring(index + inputValue.length)} &lt;/React.Fragment&gt;} &lt;/span&gt; ); } // the key with the matched letters highlighted const tag = getTag(hint.key); // count the number of times this tag is used elsewhere, if any const count = (hint.count) ? &lt;span className="multiplier"&gt;×&amp;nbsp;{hint.count}&lt;/span&gt; : undefined; // the summary, if any const summary = (hint.summary) ? &lt;p&gt;{hint.summary}&lt;/p&gt; : undefined; // a link to more info i.e. the page which defines this tag function getMore(key: string) { const icon = &lt;Icon.Info width="16" height="16" /&gt;; // we use &lt;a&gt; here instead of &lt;Link&gt; because this link will open a whole new tab, i.e. another instance of this SPA // in future I think it would be better to reimplement this as a split screen (two-column) view const anchor = &lt;a href={`/tags/${key}/info`} target="_blank" rel="noopener noreferrer"&gt;{icon}&lt;/a&gt;; return &lt;p className="more-info"&gt;{anchor}&lt;/p&gt;; } const more = getMore(hint.key); return ( &lt;div className="hint" tabIndex={0} key={hint.key} onClick={e =&gt; result(hint.key)} onKeyDown={e =&gt; { if (e.key === "Enter") result(hint.key); e.preventDefault() }} onFocus={e =&gt; handleFocus(e, true)} onBlur={e =&gt; handleFocus(e, false)} &gt; {tag} {count} {summary} {more} &lt;/div&gt; ); } </code></pre> <h2>EDITORTAGS.md</h2> <p>This is a README for the source file above.</p> <p>You don't have to read this. I wrote it because there a couple of tricky things in the implementation -- design decisions, e.g. to do with "focus-within" -- which I didn't want to document as comments in the source code.</p> <blockquote> <h1><code>EditorTags</code></h1> <p>The <code>EditorTags</code> component lets you edit and select the tags associated with a topic.</p> <ul> <li>Appearance and behaviour</li> <li>Implementation state data</li> <li>Sequence of definitions <ul> <li>Problem constraints</li> <li>Solution as implemented</li> </ul></li> <li>Controlling the <code>&lt;input&gt;</code> element</li> <li>Simulating <code>:focus-within</code></li> </ul> <h2>Appearance and behaviour</h2> <p>It looks like a simple <code>&lt;input type="text"&gt;</code> control, which contains multiple words -- one word per tag -- however all words except the currently-selected word have some visible style applied to them.</p> <p>It's implemented as a <code>&lt;div&gt;</code> like this:</p> <pre><code> function getElement(element: RenderedElement, index: number): React.ReactElement { const isValid = !props.showValidationError || element.isValid; return (element.type === "tag") ? &lt;Tag text={element.word} index={index} key={index} isValid={isValid} /&gt; : &lt;input type="text" key="input" ref={inputRef} className={isValid ? undefined : "invalid"} width={10} onKeyDown={handleKeyDown} onChange={handleChange} onFocus={e =&gt; handleFocus(e, true)} onBlur={e =&gt; handleFocus(e, false)} /&gt; } return ( &lt;div id="tag-both" &gt; &lt;div className={className} onClickCapture={handleEditorClick}&gt; {state.elements.map(getElement)} {icon} &lt;/div&gt; &lt;ShowHints hints={state.hints} inputValue={state.inputValue} result={handleHintResult} /&gt; &lt;ErrorMessage errorMessage={errorMessage} /&gt; {validationError} &lt;/div&gt; ); </code></pre> <p>The <code>&lt;div&gt;</code> -- and the <code>state.elements</code> array shown above -- contains:</p> <ul> <li>Exactly one <code>&lt;input&gt;</code> element, in which you edit the currently-selected word</li> <li>One or more React components of my type <code>&lt;Tag&gt;</code>, which style the other words which you're not currently editing</li> </ul> <p>The <code>&lt;input&gt;</code> element may be:</p> <ul> <li>Alone in the <code>&lt;div&gt;</code></li> <li>The first or the last element in the <code>&lt;div&gt;</code>, either before or after all <code>&lt;Tag&gt;</code> elements</li> <li>In the middle of the <code>&lt;div&gt;</code>, with <code>&lt;Tag&gt;</code> elements to its left and right</li> </ul> <p>When you use the cursor keys (including <kbd>ArrowLeft</kbd> and <kbd>ArrowRight</kbd>) to scroll beyond the edge of the <code>&lt;input&gt;</code> control, then this component detects that and changes its selection of which tag is currently editable.</p> <h2>Implementation state data</h2> <p>There's quite a bit of state (i.e. member data) associated with this component:</p> <ul> <li>A <code>state.buffer</code> string whose value equals the current string or array of words (i.e. tags) being edited</li> <li>A <code>state.selection</code> index or range, that identifies which word is currently being edited -- this is a <code>start</code> and <code>end</code> range, because you can select a range of text, e.g. by pressing the <kbd>Shift</kbd> key when you use the cursor keys</li> <li>The <code>elements</code> array, which is calculated from the buffer and the selection range, and which identifies which word is associated with the <code>&lt;input&gt;</code> element and which other words are associated with the <code>&lt;Tag&gt;</code> elements.</li> <li>The <code>inputValue</code> which identifies the current value of the <code>&lt;input&gt;</code> element</li> <li>A <code>hints</code> array which lists the possible tags which might be a match for the input value</li> <li>A <code>validationError</code> message if the current tags are invalid and deserve an error message</li> </ul> <p></p> <pre><code>// this is like the input data from which the RenderedState is calculated // these and other state elements are readonly so that event handlers must mutate MutableState instead interface State { // the selection range within the buffer // this may even span multiple words, in which case all the selected words are in the &lt;input&gt; element readonly selection: { readonly start: number, readonly end: number }, // the words (i.e. the tags when this is split on whitespace) readonly buffer: string }; // this interface identifies the array of &lt;input&gt; and &lt;Tag&gt; elements to be rendered, and the word associated with each interface RenderedElement { // the string value of this word readonly word: string; // whether this word is rendered by a Tag element or by the one input element readonly type: "tag" | "input"; // whether this word matches an existing tag in the dictionary readonly isValid: boolean; }; // this interface combines the two states, and is what's stored using useReducer interface RenderedState { // the buffer which contains the tag-words, and the selection within the buffer readonly state: State; // how that's rendered i.e. the &lt;input&gt; element plus &lt;Tag&gt; elements readonly elements: ReadonlyArray&lt;RenderedElement&gt;; // the current ("semi-controlled") value of the &lt;input&gt; element readonly inputValue: string; // the hints associated with the inputValue, taken from the TagDictionary hints: TagCount[]; // the validation error message (zero length if there isn't one) validationError: string; } </code></pre> <p>Because there's a lot of data, and the data elements are inter-related, I implement it with <code>useReducer</code> instead of <code>useState</code>.</p> <h2>Sequence of definitions</h2> <p>The sequence in which things are defined in the source file is significant -- and it's fragile, i.e. if you don't do it right then there's a compiler error about using something before it's defined, or a run-time error about using something with an undefined value.</p> <p>I use the following strategy:</p> <ul> <li>Because the <code>initialState</code> and therefore the <code>renderState</code> functions are called when the <code>state</code> is initialized and before <code>inputRef.current</code> exists, this function and anything called from this function cannot reference the state data.</li> <li>To ensure they don't reference the state data, they're defined in the <code>EditorTabs.tsx</code> module (for convenience), but defined outside the <code>EditorTags</code> function component inside which the state data are defined, so that the compiler would error if they were referenced from those functions.</li> </ul> <p>So the following are defined outside the function component:</p> <ul> <li>The <code>initialState</code> and <code>renderState</code> functions</li> <li>Any TypeScript class definitions which these functions use</li> <li>Any other TypeScript type definitions which these functions or classes use -- so, for simplicity, every TypeScript type definition.</li> <li>Any small helper/utility functions which these functions use -- and so, for simplicity, all helper/utility functions</li> <li>Because a reducer should be stateless or pure, it too is defined outside the function component</li> <li>And therefore also the TypeScript type definitions of the action types, and the corresponding user-defined type guards</li> </ul> <p>So the following remain inside the function component:</p> <ul> <li>All state data</li> <li>All event handlers (which delegate to the reducer, and which may reference <code>inputRef.current</code>)</li> <li>The <code>assert</code> function depends on the <code>setErrorMessage</code> function, which is state -- so the <code>assert</code> function too is defined inside the function component, and is passed as a parameter to any function which needs it.</li> </ul> <p>Data that's stored inside the function component, and which isn't stored as state, is passed to the reducer in the "action".</p> <pre class="lang-js prettyprint-override"><code>interface ActionEditorClick { type: "EditorClick", context: Context }; interface ActionHintResult { type: "HintResult", context: Context, hint: string, inputIndex: number }; interface ActionDeleteTag { type: "DeleteTag", context: Context, index: number }; interface ActionTagClick { type: "TagClick", context: Context, index: number }; interface ActionKeyDown { type: "KeyDown", context: Context, key: string, shiftKey: boolean }; interface ActionChange { type: "Change", context: Context }; </code></pre> <p>All the <code>Action</code> types include an <code>InputElement</code> (which is created by the event handler which generates the action), because the <code>MutableState</code> class (called from the reducer) requires an <code>InputElement</code>, in order to update the <code>State</code> (including the <code>buffer</code> and the <code>selection</code>) to match the contents of the <code>&lt;input&gt;</code> element.</p> <p>In fact there's other data too, which the reducer needs and is passed in the action:</p> <pre class="lang-js prettyprint-override"><code>// this is extra data which event handlers pass (as part of the action) from the function component to the reducer interface Context { inputElement: InputElement; assert: Assert; result: ParentCallback; tagDictionary?: TagDictionary; validation: Validation; }; </code></pre> <h2>Controlling the <code>&lt;input&gt;</code> element</h2> <p>The <code>&lt;input&gt;</code> element is a semi-controlled component (see e.g. "<a href="https://www.robinwieruch.de/react-controlled-components/" rel="noreferrer">What are Controlled Components in React?</a>").</p> <p>There's an <code>inputRef</code> as well to access to the underlying HTML element, which is used to set the focus, and to get and set the selection range within the element, but not to get the value of the element -- the value of the element is got via its <code>onChange</code> handler (and the <code>value</code> property of the event's <code>target</code>).</p> <p>Note that React's <code>onChange</code> event handler has redefined (non-standard) semantics -- i.e. it's fired after every change, and not only when it loses focus.</p> <p>I say that it's "semi" controlled, because although its <code>onChange</code> handler writes its value to state ...</p> <pre class="lang-js prettyprint-override"><code>&lt;input type="text" ref={inputRef} onChange={handleChange} ... </code></pre> <p>... it does <strong>not</strong> have a corresponding <code>value</code> property which might read its value from state ...</p> <pre class="lang-js prettyprint-override"><code>&lt;input type="text" ref={inputRef} onChange={handleChange} value={state.inputValue} ... </code></pre> <p>The reason why not is because if the value property is used to write a string into a previously-empty input element, then the selection range within the control is automatically pushed to the end of the new string.</p> <p>This interferes with the desired behaviour of the <kbd>ArrowRight</kbd> key, where we want to copy the next (to the right) tag into the input control, and set the selection range to the <strong>beginning</strong> of the control.</p> <p>So, instead, the <code>setInput</code> function writes into the <code>value</code> property of the underlying <code>HTMLInputElement</code>.</p> <ul> <li>I worried that doing this might trigger another <code>onChange</code> event, but it doesn't seem to.</li> <li>An alternative might be to use <code>useEffect</code> to alter the selection of the input (to match the selection specified in the state), after it's rendered. That seems like even more of a kluge, though -- making it "semi-controlled" instead, i.e. writing to the DOM element, seems neater.</li> </ul> <p>The <code>inputValue</code> element also still exists as an alement of the <code>RenderedState</code> data, but it's write-only -- i.e. it's up-to-date (and a opy of what was written into the DOM element).</p> <h2>Simulating <code>:focus-within</code></h2> <p>There are a couple of effects in <code>EditorTags.css</code> for example ...</p> <pre class="lang-css prettyprint-override"><code>.tag-hints { visibility: hidden; } .tag-both:focus-within .tag-hints { visibility: visible; } </code></pre> <p>... where is would be convenient to use <code>:focus-within</code>. However that's not supported by some browsers (e.g. Edge). Although the "Create React App" setup include <code>postcss</code> modules, they're not configurable -- "<a href="https://github.com/facebook/create-react-app/issues/5749#issuecomment-436852753" rel="noreferrer">You cannot customize postcss rules</a>" -- and the default configuration doesn't enable support for <code>postcss-focus-within</code>.</p> <p>To avoid the complexity or fragility of trying to bypass the CRA default configuration, instead I use <code>onfocus</code> and <code>onBlur</code> handlers to simulate <code>:focus-within</code> (by adding or removing <code>focussed</code> to the <code>class</code> value).</p> <p>There's also complexity in deciding whether something has lost focus.</p> <ul> <li>The problem is that, using React's synthetic events, <code>onBlur</code> fires before <code>onFocus</code> -- so focus seems lost when focus moves from <code>.tag-editor input</code> to one of the <code>.hint</code> elements.</li> <li>The right the right way to support this functionality would be to use the <code>focusin</code> event as described in <a href="https://www.w3.org/TR/2014/WD-DOM-Level-3-Events-20140925/#events-focusevent-event-order" rel="noreferrer">Focus Event Order</a>, however React's synthetic events don't support <code>focusin</code> -- <a href="https://github.com/facebook/react/issues/6410" rel="noreferrer">https://github.com/facebook/react/issues/6410</a></li> </ul> <p>Solutions like ...</p> <ul> <li><a href="https://medium.com/@jessebeach/dealing-with-focus-and-blur-in-a-composite-widget-in-react-90d3c3b49a9b" rel="noreferrer">Dealing with focus and blur in a composite widget in React</a></li> <li>The <a href="https://www.npmjs.com/package/react-focus-within" rel="noreferrer"><code>react-focus-within</code></a> package</li> </ul> <p>... solve this using a timer in some way -- which is probably good, only I'm not certain of the sequence in which events are emitted.</p> <p>So instead I use a solution (see the <code>handleFocus</code> function) which depends on the <code>relatedTarget</code> of the event:</p> <ul> <li>That works on my machine (Windows 10), at least, using Chrome, Firefox, and Edge.</li> <li><a href="https://github.com/facebook/react/issues/3751" rel="noreferrer">https://github.com/facebook/react/issues/3751</a> warns that apparently this won't work with IE 9 through IE 11, though comments there say that document.activeElement might help make it work on IE</li> </ul> <p>Otherwise, if support for IE (not just Edge) is needed, one of the other solutions listed earlier above might be better.</p> </blockquote>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T10:48:49.560", "Id": "433942", "Score": "0", "body": "(Not an expert here) The main behavioral difference I could see at a glance would be that in the SE network the tag recommendations \"hover\" over/hide the button, while your implementation push it towards the bottom of the page. I have to admit that I have not read your whole post, so I might have missed it if you describe this behavior as intentional there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-14T08:54:02.487", "Id": "434689", "Score": "0", "body": "You're right, that is one (unintentional) difference -- presumably a difference in the CSS, e.g. the CSS could `position` the hint-recommendations `div`, to take it out of the normal flow sequence." } ]
[ { "body": "<p><em>Disclaimer: My usage of ReactJS is very limited so there are likely things a developer more experienced with it would point out.</em></p>\n\n<blockquote>\n <p>Are there too many comments in the code?</p>\n</blockquote>\n\n<p>It doesn't look like <em>too many</em> comments. Anything that helps readers (including your future self) is a good thing. It isn't like <a href=\"https://codereview.stackexchange.com/q/10167/120114\">this \"not funny\" code</a> that has excessive, non-constructive comments. It is believed that some object-oriented code can be self-documenting but it would still be necessary to explain what methods/functions do, as well as describe any parameters and return values.</p>\n\n<blockquote>\n <p>It's pretty long: so would it be better split into more than one source file and if so how would that help and how/where should it be split?</p>\n</blockquote>\n\n<p>My natural inclination is to suggest that the code be split so each class/interface is in a separate file. I see that a lot of the code is comprised of functions... some of those could possibly be put into one or more files for helper functions.</p>\n\n<blockquote>\n <p>And/or any other review comment you think appropriate.</p>\n</blockquote>\n\n<p>Most of the methods don't appear to be overly lengthy. I see <code>MutableState:: replaceElement()</code> looks like an outlier so that would be a candidate for being broken up into separate smaller methods. And <code>reducer()</code> is also a bit lengthy, though it may be challenging to break that up. I do see a lot of repeated lines in that function - e.g. calling <code>getMutableState()</code> to create a <code>MutableState</code> object and then ultimately returning the return value from calling <code>getState()</code> on that object.</p>\n\n<hr>\n\n<p>This code makes good use of <code>const</code> for any variable that doesn't get re-assigned and <code>let</code> for variable that may be re-assigned, as well as object destructuring.</p>\n\n<hr>\n\n<p>Correct me if I am wrong, but <code>MutableState::setSelectionBoth()</code> should be able to be simplified from: </p>\n\n<blockquote>\n<pre><code>setSelectionBoth(where: number): void {\n this.selection.start = where;\n this.selection.end = where;\n}\n</code></pre>\n</blockquote>\n\n<p>to:</p>\n\n<pre><code>setSelectionBoth(where: number): void {\n this.selection.end = this.selection.start = where;\n}\n</code></pre>\n\n<hr>\n\n<p>There are some <code>for</code> loops, like the one in <code>renderState()</code> that could be simplified with a <a href=\"https://www.typescriptlang.org/docs/handbook/iterators-and-generators.html#forof-statements\" rel=\"nofollow noreferrer\"><code>for...of</code></a> loop instead - </p>\n\n<p>e.g. </p>\n\n<blockquote>\n<pre><code>for (let wordIndex = 0; wordIndex &lt; words.length; ++wordIndex) {\n const word = words[wordIndex];\n</code></pre>\n</blockquote>\n\n<p>This could be simplified to:</p>\n\n<pre><code>for (const word of words) {\n</code></pre>\n\n<p>That way you don't have to increment <code>wordIndex</code> manually or use it to access <code>word</code> from <code>words</code> with the bracket syntax.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T12:50:53.677", "Id": "435570", "Score": "0", "body": "`getWordStart` compares `i` to `index` (in the `for` expression itself) because it only wants the first few words. I could have done `for (const word of words.slice(0, index)) {` or something like that instead -- it's my old (arguably obsolete) habits have me prefer to use an index, than to instantiate a new array using `slice`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T12:57:30.937", "Id": "435571", "Score": "0", "body": "I realise that one-function-per-file was like the default in C, and one-class-per-file in C++, but ... there are about 50 function and type definitions in this module, I'm not convinced it would be easier to read or understand or anything as 50 different source files -- are you? Admittedly I use the split-screen (i.e. side-by-side) feature of the text editor (i.e. VS Code) sometimes, so see two places at once within the same file (e.g. the new bit I'm coding and the existing bit I'm about to call), and I felt a need for that map or index of identifiers/definitions, nears the top, in a comment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T12:59:38.877", "Id": "435572", "Score": "0", "body": "It's currently physically one module (i.e. one source file) with a narrow public interface (i.e. very little is exported), almost everything is \"private\" to the module -- an implementation detail, not exported." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T14:01:04.737", "Id": "435579", "Score": "0", "body": "Thanks for the reassurance about the comments, at least. I had someone (not very experienced) complain that I comment too much. I know (e.g. from the \"Socratic\" discussion in _Code Complete_) that the topic (i.e. to comment or not) is debatable -- also that it can look inconsistent when there's a code-base with multiple authors, some with a lot of comments and some with none." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-20T14:25:27.657", "Id": "435582", "Score": "0", "body": "I guess that 50 source files is too much of the opposite extreme. I wondered if there's an especially natural or idiomatic way (like a \"fault line\" along which) to split such code, and whether there's a compelling pragmatic consideration." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-22T16:59:06.707", "Id": "435861", "Score": "0", "body": "Ah I was incorrect about that loop in `getWordStart()` - but there are others - e.g. the one in `renderState()`; Yeah ~50 files would feel too many... I bet you could perhaps make a couple - e.g. one for `InputElement`, `InputState`and one for `MutableState`.... taking those three classes out would reduce the one file size dramatically" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T16:12:28.687", "Id": "224423", "ParentId": "223796", "Score": "3" } }, { "body": "<p>Any code should be readable as we read code 90% time in our overall dealing of code, this code doesn't seem very readable, this can be reviewed better after making some basic changes and after that, it can be review to find real problems or can be refactored.</p>\n\n<ol>\n<li>Proper naming like <code>TagCount</code> is not actually a count similarly <code>Validation</code> is not just validation it is validations applicable on tag</li>\n<li>Once your naming is proper no need this much of comments, your code should be self explainable, unnecessary comments are noise</li>\n<li>Functions should be small and composite</li>\n<li>Reducer is not a pure function</li>\n<li>lot of functions created inside other functions these can be put out as an independent method for readability</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-21T23:45:35.717", "Id": "435741", "Score": "0", "body": "Why do you say \"reducer is not a pure function\" -- what does it depend on apart from its input values?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-22T06:27:01.830", "Id": "435762", "Score": "0", "body": "Mutable state and input state are maintaining things on instance, if function is pure then these are just confusing, as I said this can be better reviewed if it is readable" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-22T09:01:23.307", "Id": "435780", "Score": "0", "body": "Thank you. I don't understand or don't agree with your comments re. naming. For example `TagCount` *is* a count -- it contains a `count` member which is the number of times that tag has been used (which affects how the hint is displayed e.g. with a `x 2` next to it, also the more-frequently-used tags with a higher count are prefered). I agree in principle that names are important but I already tried to name things so I don't see how to improve them so \"give things proper names\" isn't actionable advice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-22T09:05:53.543", "Id": "435785", "Score": "0", "body": "Perhaps I'd have to ask you what you think the (better) names should be, but you say you don't want to review until after things are renamed, so ..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-22T09:05:59.910", "Id": "435786", "Score": "0", "body": "I also think it's helpful to have comments as well as code -- that the right kind of comment can make it quicker+easier to understand what's supposed to be happening, instead of the reader having to decypher the code and only being able to see what *is* happening and not also what's *intended*. People might be happier reading code than English, though, and I agree that comments are no substitute for \"self-documenting\" code e.g. with well-named identifiers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-22T09:09:53.707", "Id": "435787", "Score": "0", "body": "Thank you for the comment about `InputState`, that was a good observation. I posted a new question on Statck Overflow about that -- [Must a React reducer be a pure function?](https://stackoverflow.com/q/57142137/49942)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-21T18:13:28.170", "Id": "224623", "ParentId": "223796", "Score": "3" } } ]
{ "AcceptedAnswerId": "224423", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T09:59:25.173", "Id": "223796", "Score": "14", "Tags": [ "functional-programming", "event-handling", "react.js", "typescript" ], "Title": "Emulation of SE's text input control for tags" }
223796
<p>I am creating program which will parse .csv file and I am using <code>FileReader</code> and <code>Scanner</code> classes from java API.</p> <p><code>FileReader</code> throws <code>FileNotFoundException</code>, <code>IOException</code>.</p> <p><code>Scanner</code>'s method <code>hasNextLine()</code> and <code>nextLine()</code> throw <code>IllegalStateException</code> and <code>NoSuchElementException</code>.</p> <p>Should I use 1 <em>try</em> and 4 multiple <em>catch</em> blocks? Or <em>try</em> block nested in another <em>try</em> block(which has 2 <em>catch</em> blocks) with 2 <em>catch</em> blocks?</p> <p>Code 1:</p> <pre><code>import java.io.*; import java.util.Scanner; import java.util.NoSuchElementException; import java.lang.IllegalStateException; public class App { public static void main(String[] args) { try (FileReader file = new FileReader("Doc.csv")) { Scanner sc = new Scanner(file); while (sc.hasNextLine()) { System.out.println(sc.nextLine()); } } catch (IllegalStateException e) { System.out.println(e); } catch (NoSuchElementException e) { System.out.println(e); } catch (FileNotFoundException e) { System.out.println(e); } catch (IOException e) { System.out.println(e); } } } </code></pre> <p>Code 2:</p> <pre><code>import java.io.*; import java.util.Scanner; import java.util.NoSuchElementException; import java.lang.IllegalStateException; public class App { public static void main(String[] args) { try (FileReader file = new FileReader("Doc.csv")) { Scanner sc = new Scanner(file); try { while (sc.hasNextLine()) { System.out.println(sc.nextLine()); } } catch (IllegalStateException e) { System.out.println(e); } catch (NoSuchElementException e) { System.out.println(e); } } catch (FileNotFoundException e) { System.out.println(e); } catch (IOException e) { System.out.println(e); } } } </code></pre> <p>By the way, I know that System.out.println(e) is not best practice for logging exception. So, please don't write about it</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T11:45:42.520", "Id": "433958", "Score": "2", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. 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](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T11:23:27.323", "Id": "434072", "Score": "0", "body": "Welcome to Code Review. Please note that unlike Stack Overflow, in order to give the best possible advice Code Review needs to look at concrete code in a real context. We also prefer general questions like \"Any recommendations for how to improve this code in any way?\" rather than specific questions about \"How should I write my try-catch statement, A or B?\" (where the correct answer often is C - as it was here as well). In this particular case I considered that you essentially have a complete example *project* here, so I'm letting this question pass." } ]
[ { "body": "<p>If you are not going to handle each exception differently just use a multicatch:</p>\n\n<pre><code>public static void main(String[] args) {\n try (FileReader file = new FileReader(\"Doc.csv\")) {\n Scanner sc = new Scanner(file);\n while (sc.hasNextLine()) {\n System.out.println(sc.nextLine());\n }\n } catch (IllegalStateException | NoSuchElementException | IOException e) {\n System.out.println(e);\n }\n}\n</code></pre>\n\n<p>The <code>FileNotFoundException</code> is not catched since alternatives in a multi-catch statement cannot be related by subclassing (<code>FileNotFoundException</code> is a subclass of <code>IOException</code>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T11:27:52.127", "Id": "433957", "Score": "0", "body": "Thanks. So, it is okey to have 1 try and catch(with multiple exceptions) block if I want to handle all exceptions with the same method?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T13:09:13.357", "Id": "433968", "Score": "0", "body": "this is what I meant by \"do the same processing with all exceptions\"" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T11:21:47.763", "Id": "223800", "ParentId": "223797", "Score": "5" } } ]
{ "AcceptedAnswerId": "223800", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T10:35:43.147", "Id": "223797", "Score": "0", "Tags": [ "java", "comparative-review", "exception" ], "Title": "One try with multiple catch blocks vs nested try" }
223797
<p>I had me a code challenge and I was thinking: is there a way to make this more efficient and short? The challenge requires me to scan a string and ...</p> <blockquote> <ul> <li><p>In the first line, print <code>True</code> if it has any alphanumeric characters. Otherwise, print <code>False</code>.</p> </li> <li><p>In the second line, print <code>True</code> if it has any alphabetical characters. Otherwise, print <code>False</code>.</p> </li> <li><p>In the third line, print <code>True</code> if it has any digits. Otherwise, print <code>False</code>.</p> </li> <li><p>In the fourth line, print <code>True</code> if it has any lowercase characters. Otherwise, print <code>False</code>.</p> </li> <li><p>In the fifth line, print <code>True</code> if has any uppercase characters. Otherwise, print <code>False</code>.</p> </li> </ul> </blockquote> <p>Below is my approach :</p> <pre><code>def func_alnum(s): for i in s: if i.isalnum(): return True return False def func_isalpha(s): for i in s: if i.isalpha(): return True return False def func_isdigit(s): for i in s: if i.isdigit(): return True return False def func_islower(s): for i in s: if i.islower(): return True return False def func_isupper(s): for i in s: if i.isupper(): return True return False if __name__ == '__main__': s = input() s=list(s) print(func_alnum(s)) print(func_isalpha(s)) print(func_isdigit(s)) print(func_islower(s)) print(func_isupper(s)) </code></pre> <p>It feels like I made a mountain out of a molehill. But I would defer to your opinions on efficiency and shortness before I live with that opinion.</p>
[]
[ { "body": "<p>This is done using list comprehensions and <code>any()</code> in python.</p>\n\n<p>We can use the following to make it more faster.</p>\n\n<pre><code>print(any([i.isalnum() for i in string]))\n</code></pre>\n\n<p>Since we are only looking for any 1 element in the string being an uppercase,lowercase, etc Any() finds a good use case here.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T16:04:40.497", "Id": "433984", "Score": "2", "body": "`any` can also take an iterator instead of a list. It stops the iteration as soon as it encounters a `True` element. So if you remove the square brackets, it's even faster." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T10:53:48.833", "Id": "223799", "ParentId": "223798", "Score": "1" } }, { "body": "<p>Your five functions only differ by the predicate used to test each character, so you could have a single one parametrized by said predicate:</p>\n\n<pre><code>def fulfill_condition(predicate, string):\n for character in string:\n if predicate(character):\n return True\n return False\n\n\nif __name__ == '__main__':\n s = input()\n print(fulfill_condition(str.isalnum, s))\n print(fulfill_condition(str.isalpha, s))\n print(fulfill_condition(str.isdigit, s))\n print(fulfill_condition(str.islower, s))\n print(fulfill_condition(str.isupper, s))\n</code></pre>\n\n<p>Note that you don't need to convert the string to a list for this to work, strings are already iterables.</p>\n\n<p>Now we can simplify <code>fulfill_condition</code> even further by analysing that it applies the predicate to each character and returns whether any one of them is <code>True</code>. This can be written:</p>\n\n<pre><code>def fulfill_condition(predicate, string):\n return any(map(predicate, string))\n</code></pre>\n\n<p>Lastly, if you really want to have 5 different functions, you can use <a href=\"https://docs.python.org/3/library/functools.html#functools.partial\" rel=\"nofollow noreferrer\"><code>functools.partial</code></a>:</p>\n\n<pre><code>from functools import partial\n\n\nfunc_alnum = partial(fulfill_condition, str.isalnum)\nfunc_isalpha = partial(fulfill_condition, str.isalpha)\nfunc_isdigit = partial(fulfill_condition, str.isdigit)\nfunc_islower = partial(fulfill_condition, str.islower)\nfunc_isupper = partial(fulfill_condition, str.isupper)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T07:11:20.290", "Id": "434054", "Score": "0", "body": "Thanks. It helps to know other efficient approach to solve a problem. :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T16:48:41.927", "Id": "223820", "ParentId": "223798", "Score": "3" } } ]
{ "AcceptedAnswerId": "223820", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T10:39:34.427", "Id": "223798", "Score": "4", "Tags": [ "python", "python-3.x", "strings" ], "Title": "String validation based on multiple criteria" }
223798
<p>I am currently learning JS Frameworks, right now exploring React and wanted to make sure I keep everything in order, as in: the logic of working with React, code quality, any shortcomings, good/bad practices etc?</p> <p>The code renders a simple Search panel that will allow to call an API, get the results (if any) and render the results on the page.</p> <pre><code>import React from "react"; import "./App.css"; import axios from "axios"; var Style = { marginRight: "22px" }; var Style2 = { display: "none" }; const API_CALL = "xxx"; class SearchForm extends React.Component { constructor(props) { super(props); this.state = { value: "", errorValue: "", countryCode: "", VATNumber: "", valid: "", name: "", address: "", isLoading: false, isSubmitted: false }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } renderField() { return ( &lt;form onSubmit={this.handleSubmit}&gt; &lt;label style={Style}&gt;Search VAT:&lt;/label&gt; &lt;input type="text" onChange={this.handleChange} style={Style} /&gt; &lt;input type="submit" value="Submit" /&gt; &lt;/form&gt; ); } render() { return ( &lt;div&gt; &lt;h5&gt;Reference: EE100247019&lt;/h5&gt; {this.renderField()} &lt;div id="results" /&gt; &lt;Loader loading={this.state.isLoading} /&gt; {this.state.isSubmitted &amp;&amp; ( &lt;Result country={this.state.countryCode} number={this.state.VATNumber} name={this.state.name} address={this.state.address} error={this.state.errorValue} valid={this.state.valid} loading={this.state.isLoading} /&gt; )} &lt;/div&gt; ); } handleChange(event) { this.setState({ value: event.target.value.trim() }); } handleSubmit(event) { this.setState({ isLoading: true, isSubmitted: false }); Style2 = { listStyleType: "none", textAlign: "left", display: "block", border: "1px solid white", marginTop: "50px" }; axios .get(API_CALL + this.state.value) .then(res =&gt; this.setState({ countryCode: res.data.CountryCode, VATNumber: res.data.VATNumber, name: res.data.Name, address: res.data.Address, valid: res.data.Valid, isLoading: false, isSubmitted: true }) ) .catch(error =&gt; this.setState({ valid: false, errorValue: this.state.value, isLoading: false, isSubmitted: true }) ); event.preventDefault(); } } function Loader(props) { if (!props.loading) { return null; } return &lt;h6&gt; Loading ... &lt;/h6&gt;; } function Result(props) { if (!props.valid) { return ( &lt;h5&gt; Invalid value "{props.error}" &lt;br /&gt; &lt;br /&gt; Please enter valid VAT Number &lt;/h5&gt; ); } else { return ( &lt;table style={Style2}&gt; &lt;tr&gt; &lt;td&gt;Country code: &lt;/td&gt; &lt;td&gt;{props.country}&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;VAT Number: &lt;/td&gt; &lt;td&gt;{props.number}&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Product name: &lt;/td&gt; &lt;td&gt;{props.name}&lt;/td&gt; &lt;/tr&gt; &lt;td&gt;Address: &lt;/td&gt; &lt;td&gt;{props.address} &lt;/td&gt; &lt;/table&gt; ); } } export default SearchForm; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-11T06:35:48.030", "Id": "434216", "Score": "0", "body": "Looks OK; Code sample can be much shorter for this question; Learn react hooks, they are awesome :)" } ]
[ { "body": "<p>Here is the code after refactor some changes that i think should be good to follow:</p>\n\n<ol>\n<li>use let instead of var.</li>\n<li>I have used style2 as a state as its changing.</li>\n<li>Used arrow function instead of bind.</li>\n<li>Prefer destructuring.</li>\n</ol>\n\n<blockquote>\n<pre><code>import React from \"react\";\nimport \"./App.css\";\nimport axios from \"axios\";\n\nlet Style = {\n marginRight: \"22px\"\n};\n\nconst API_CALL = \"xxx\";\n\nclass SearchForm extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n value: \"\",\n errorValue: \"\",\n countryCode: \"\",\n VATNumber: \"\",\n valid: false,\n name: \"\",\n address: \"\",\n isLoading: false,\n isSubmitted: false,\n Style2: { display: \"none\" }\n };\n }\n\n renderField() {\n return (\n &lt;form onSubmit={this.handleSubmit}&gt;\n &lt;label style={Style}&gt;Search VAT:&lt;/label&gt;\n &lt;input type=\"text\" onChange={this.handleChange} style={Style} /&gt;\n &lt;input type=\"submit\" value=\"Submit\" /&gt;\n &lt;/form&gt;\n );\n }\n\n render() {\n const {\n Style2 = {},\n countryCode = \"\",\n VATNumber = \"\",\n valid = false,\n name = \"\",\n address = \"\",\n isLoading = false,\n isSubmitted = false,\n errorValue = \"\"\n } = this.state;\n return (\n &lt;div&gt;\n &lt;h5&gt;Reference: EE100247019&lt;/h5&gt;\n {this.renderField()}\n &lt;div id=\"results\" /&gt;\n &lt;Loader loading={isLoading} /&gt;\n {isSubmitted &amp;&amp; (\n &lt;Result\n country={countryCode}\n number={VATNumber}\n name={name}\n address={address}\n error={errorValue}\n valid={valid}\n loading={isLoading}\n style={Style2}\n /&gt;\n )}\n &lt;/div&gt;\n );\n }\n\n handleChange = event =&gt; this.setState({ value: event.target.value.trim() });\n\n handleSubmit = event =&gt; {\n this.setState(({ Style2 }) =&gt; ({\n isLoading: true,\n isSubmitted: false,\n Style2: {\n ...Style2,\n listStyleType: \"none\",\n textAlign: \"left\",\n display: \"block\",\n border: \"1px solid white\",\n marginTop: \"50px\"\n }\n }));\n axios\n .get(API_CALL + this.state.value)\n .then(\n ({\n data: {\n CountryCode = \"\",\n VATNumber = \"\",\n Name = \"\",\n Address = \"\",\n Valid = false\n } = {}\n } = {}) =&gt;\n this.setState({\n countryCode: CountryCode,\n VATNumber: VATNumber,\n name: Name,\n address: Address,\n valid: Valid,\n isLoading: false,\n isSubmitted: true\n })\n )\n .catch(error =&gt;\n this.setState({\n valid: false,\n errorValue: this.state.value,\n isLoading: false,\n isSubmitted: true\n })\n );\n\n event.preventDefault();\n };\n}\n\n\nconst Loader = ({ loading = false } = {}) =&gt;\n loading ? null : &lt;h6&gt; Loading ... &lt;/h6&gt;;\n\nconst Result = ({\n valid = false,\n error = \"\",\n style = {},\n country = \"\",\n number = \"\",\n name = \"\",\n address = \"\"\n} = {}) =&gt; {\n if (!valid) {\n return (\n &lt;h5&gt;\n Invalid value \"{error}\"\n &lt;br /&gt; &lt;br /&gt;\n Please enter valid VAT Number\n &lt;/h5&gt;\n );\n } else {\n return (\n &lt;table style={style}&gt;\n &lt;tr&gt;\n &lt;td&gt;Country code: &lt;/td&gt;\n &lt;td&gt;{country}&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt;VAT Number: &lt;/td&gt;\n &lt;td&gt;{number}&lt;/td&gt;\n &lt;/tr&gt;\n &lt;tr&gt;\n &lt;td&gt;Product name: &lt;/td&gt;\n &lt;td&gt;{name}&lt;/td&gt;\n &lt;/tr&gt;\n &lt;td&gt;Address: &lt;/td&gt;\n &lt;td&gt;{address} &lt;/td&gt;\n &lt;/table&gt;\n );\n }\n}\n\n\nexport default SearchForm;\n</code></pre>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T15:21:57.470", "Id": "435453", "Score": "0", "body": "Hi, you should explain why the changes you made to the code makes it better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T17:37:13.070", "Id": "435463", "Score": "0", "body": "the code follows the best practices that we should follow as asked by @Altair312 in the quesion" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-19T08:39:15.340", "Id": "224464", "ParentId": "223803", "Score": "1" } } ]
{ "AcceptedAnswerId": "224464", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T12:17:22.717", "Id": "223803", "Score": "2", "Tags": [ "react.js", "jsx" ], "Title": "ReactJS Calling an API and rendering results" }
223803
<p>I made this huge code (Edit: huge for such a simple task) for transferring data and adding an ID number to every new row of data. The only functionality flaw I see is that it creates new ID numbers if you transfer blank cells. I was wondering if anyone can help me improve this code? I'm very bad at loops so if there is any possibilities for loops that I overlooked please tell me.</p> <p>Edit: also had to add another worksheet for temporarily storing the data, so I could copy it as a range, since it is first saved as a value.</p> <pre><code>Private Sub CommandButton2_Click() 'Variabler for inputs shipFrom = TextBox1.Text shipTo = TextBox2.Text shipDate = TextBox3.Text NP = TextBox4.Text desc = TextBox10.Text gramEx = TextBox6.Text tareWeight = TextBox7.Text weight = TextBox8.Text dims = TextBox9.Text Sheets("test").Range("b2").Value = shipFrom Sheets("test").Range("c2").Value = shipTo Sheets("test").Range("d2").Value = shipDate Sheets("test").Range("e2").Value = NP Sheets("test").Range("f2").Value = desc Sheets("test").Range("g2").Value = gramEx Sheets("test").Range("h2").Value = tareWeight Sheets("test").Range("i2").Value = weight Sheets("test").Range("j2").Value = dims Dim sf As Range Set sf = Sheets("test").Range("b2") Dim st As Range Set st = Sheets("test").Range("c2") Dim d As Range Set d = Sheets("test").Range("d2") Dim l As Range Set l = Sheets("test").Range("e2") Dim i As Range Set i = Sheets("test").Range("f2") Dim g As Range Set g = Sheets("test").Range("g2") Dim t As Range Set t = Sheets("test").Range("h2") Dim w As Range Set w = Sheets("test").Range("i2") Dim di As Range Set di = Sheets("test").Range("j2") Dim nextRowB As Range Set nextRowB = Sheets("Arkiv").Range("B" &amp; Rows.Count).End(xlUp).Offset(1, 0) Dim nextRowC As Range Set nextRowC = Sheets("Arkiv").Range("C" &amp; Rows.Count).End(xlUp).Offset(1, 0) Dim nextRowD As Range Set nextRowD = Sheets("Arkiv").Range("D" &amp; Rows.Count).End(xlUp).Offset(1, 0) Dim nextRowE As Range Set nextRowE = Sheets("Arkiv").Range("E" &amp; Rows.Count).End(xlUp).Offset(1, 0) Dim nextRowF As Range Set nextRowF = Sheets("Arkiv").Range("F" &amp; Rows.Count).End(xlUp).Offset(1, 0) Dim nextRowG As Range Set nextRowG = Sheets("Arkiv").Range("G" &amp; Rows.Count).End(xlUp).Offset(1, 0) Dim nextRowH As Range Set nextRowH = Sheets("Arkiv").Range("H" &amp; Rows.Count).End(xlUp).Offset(1, 0) Dim nextRowI As Range Set nextRowI = Sheets("Arkiv").Range("I" &amp; Rows.Count).End(xlUp).Offset(1, 0) Dim nextRowJ As Range Set nextRowJ = Sheets("Arkiv").Range("J" &amp; Rows.Count).End(xlUp).Offset(1, 0) sf.Copy nextRowB st.Copy nextRowC d.Copy nextRowD l.Copy nextRowE i.Copy nextRowF g.Copy nextRowG t.Copy nextRowH w.Copy nextRowI di.Copy nextRowJ Dim ID As Range Set ID = Sheets("Arkiv").Range("A" &amp; Rows.Count).End(xlUp).Offset(1, 0) If IsEmpty(Sheets("Arkiv").Range("B2").Value) Then MsgBox "Please fill in the &lt;Ship From&gt; box" Else 'Sheets("Arkiv").Range("A" &amp; Rows.Count).End(xlUp).Offset(1, 0) = "1" Sheets("Arkiv").Range("A2").Value = "1" End If If IsEmpty(Sheets("Arkiv").Range("C2").Value) Then Else ID = Sheets("Arkiv").Range("A" &amp; Rows.Count).End(xlUp).Value + 1 End If Sheets("Arkiv").Activate MsgBox "The ID number for this data is: " &amp; Sheets("Arkiv").Range("A" &amp; Rows.Count).End(xlUp).Value End Sub </code></pre>
[]
[ { "body": "<p>Ouch. I say this in a kind way - the code is painful to read.</p>\n\n<ol>\n<li>Use <code>Option Explicit</code> at the top of every module - always!</li>\n<li>Properly indent your code - it makes it easier to read, easier to pick up inconsistent logic and easier to maintain.</li>\n</ol>\n\n<p>Arrays, and Excel's ability to convert values of ranges to arrays is your friend in this instance. No need for loops.</p>\n\n<pre><code>Private Sub CommandButton2_Click()\nDim inputs as Variant 'Variabler for inputs\n inputs = Array(TextBox1.Text, TextBox2.Text, TextBox3.Text, TextBox4.Text, _\n TextBox10.Text, TextBox6.Text, TextBox7.Text, TextBox8.Text, _\n TextBox9.Text)\n ' order is important for you here.\n ' shipFrom, shipTo, shipDate, NP, desc, gramEx, tareWeight, weight, dims\n\nDim nextRowB As Range\n Set nextRowB = Sheets(\"Arkiv\").Range(\"B\" &amp; Rows.Count &amp; \":J\"&amp; Rows.Count).End(xlUp).Offset(1, 0)\n nextRowB.Value = inputs\n\n ' Now that we put everything into the array, the individual ranges and the \".copy\" is not longer required\n ' sf.Copy nextRowB etc &lt;-- not needed, see line of code above!\n\nDim ID As Range\n Set ID = Sheets(\"Arkiv\").Range(\"A\" &amp; Rows.Count).End(xlUp).Offset(1, 0)\n If IsEmpty(Sheets(\"Arkiv\").Range(\"B2\").Value) Then '&lt;-- This is your logic, but not sure if this is really what you want.\n ' Is it really only row 2 that you check?\n MsgBox \"Please fill in the &lt;Ship From&gt; box\"\n Else\n 'Sheets(\"Arkiv\").Range(\"A\" &amp; Rows.Count).End(xlUp).Offset(1, 0) = \"1\"\n Sheets(\"Arkiv\").Range(\"A2\").Value = \"1\"\n End If\n If Not IsEmpty(Sheets(\"Arkiv\").Range(\"C2\").Value) Then ' added \"Not\" here, why have an empty code block?\n 'Else &lt;-- why have an empty code block?\n ID = Sheets(\"Arkiv\").Range(\"A\" &amp; Rows.Count).End(xlUp).Value + 1\n End If\n Sheets(\"Arkiv\").Activate\n MsgBox \"The ID number for this data is: \" &amp; Sheets(\"Arkiv\").Range(\"A\" &amp; Rows.Count).End(xlUp).Value\nEnd Sub\n</code></pre>\n\n<p>Two other things to look at to make this more readable:</p>\n\n<ul>\n<li>Consider assigning \"Sheets(\"Arkiv\")\" to a variable (e.g. <code>ws</code>) and\nusing that throughout.</li>\n<li>Consider using <code>With Sheets(\"Archiv\")</code> block.</li>\n</ul>\n\n<p>And finally, ensure that all references to range objects and methods are fully qualified. This includes the <code>Rows</code> elements within the <code>Range(...)</code> code.</p>\n\n<p><strong>Edit</strong> (From Stack Overflow @AhmedAU, alternate way of inserting the values - this has been tested and works according to OP):</p>\n\n<pre><code>Dim inputs As Variant\ninputs = Array(TextBox1.Text, TextBox2.Text, TextBox3.Text, TextBox4.Text, TextBox10.Text, TextBox6.Text, TextBox7.Text, TextBox8.Text, TextBox9.Text)\nDim nextRowB As Range\nSet nextRowB = Sheets(\"Arkiv\").Range(\"B\" &amp; Rows.Count).End(xlUp).Offset(1, 0)\nnextRowB.Resize(1, UBound(inputs) + 1).Value = inputs\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T05:19:16.843", "Id": "434043", "Score": "0", "body": "Thank you!, this is what I have been looking for, I did not know how to use arrays like that since I have only learnt VBA three days ago. I'll try this now!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T05:35:40.767", "Id": "434044", "Score": "0", "body": "when using the inputs = array(*all textboxes* I get expected list separator on the textboxes that comes after the \"_\" sign on the row below, any idea why?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T06:07:48.080", "Id": "434046", "Score": "0", "body": "Ok, I did the inputs = arrays without _ all in one line, the weird thing is that it only copies the first value over, gives ID number and then stops, any idea why? I could link a picture of my userform and my worksheet \"Arkiv\" if you want?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T20:48:02.660", "Id": "434152", "Score": "0", "body": "@SanderJensen: Post a new question on Stack Overflow - along with any relevant code and a table/image of your data. In that question, describe (using an example data set) what you expect to happen, and what actually happens. What you are describing here does not match the code as written so we must dig into it a bit further." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T22:03:39.463", "Id": "434158", "Score": "0", "body": "@SanderJensen: OK - see you have already done that with a successful outcome. Good!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T22:07:23.633", "Id": "434159", "Score": "0", "body": "@SanderJensen: the reason the \"_\" was causing issue was because I had forgotten to put a comma at the near end of the line, so the line roll-over was not giving the right result. Only required to make the code easier to read." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T22:29:30.013", "Id": "223837", "ParentId": "223806", "Score": "2" } } ]
{ "AcceptedAnswerId": "223837", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T13:13:32.460", "Id": "223806", "Score": "3", "Tags": [ "vba", "excel" ], "Title": "ERP-system with UserForm that transfers data to next available row in an archive spreadsheet" }
223806
<p>Long story short, I have over 180K files that I need to delete. I have all of the file names that need to be deleted in a TXT file, however the files that need deleting are scattered in over 400 folders within this one directory. </p> <p>I'm attempting to design a script that reads a .TXT file, checks if the file exists in any of the sub directories and deletes if found. </p> <p>I'm quite knew to PowerShell / Object-oriented scripts so need some assistance. </p> <pre><code>$WorkingDir = 'D:\TEST\' $txtFile = Get-Content "D:\TEST\Files.txt" #foreach file in the .TXT foreach ($file in $txtFile){ # foreach file in the folders foreach($dir in (Get-ChildItem $WorkingDir -Recurse)){ # if the file name is in directory listed, then delete? If (Test-Path $file){ Remove-Item $file } } } </code></pre> <p>Example of data in TXT file:</p> <pre><code>215865.wav 215864.wav 215875.wav 215887.wav 215885.wav 215884.wav 215902.wav 215906.wav </code></pre> <p>Attempted to run script above on some test data so it didn't have to scan through hundreds of folders...runs successfully but nothing gets deleted.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T14:09:33.037", "Id": "433973", "Score": "0", "body": "Can you confirm that the code is complete and that it functions correctly? If so, I recommend that you [edit] to add a summary of the testing (ideally as reproducible unit-test code). If it's not working, it isn't ready for review (see [help/on-topic]) and the question may be deleted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T14:10:23.467", "Id": "433974", "Score": "0", "body": "Okay, I will read the help center. Thanks @Toby" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-11T11:41:14.860", "Id": "434278", "Score": "0", "body": "Editing posts to include suggestions that are given in answers creates an issue where the answers appear to not make sense. We call this [\"answer invalidation\"](https://codereview.meta.stackexchange.com/questions/1763/for-an-iterative-review-is-it-okay-to-edit-my-own-question-to-include-revised-c). Your edits have been rolled back, and the answer now makes more sense. Unfortunately your question was off-topic to start with. Now that you have working code, though, you may want to post a follow up question. See the same link above for how to do that." } ]
[ { "body": "<p>Your approach is very inefficient </p>\n\n<ul>\n<li>the array <code>$txtfile</code> is already in memory </li>\n<li>iterating it and per entry searching recursivly the directories (the var $dir in fact also includes files) creates a lot of unneccessary overhead.</li>\n</ul>\n\n<pre><code>$WorkingDir = 'D:\\TEST\\'\n$txtFile = Get-Content \"D:\\TEST\\Files.txt\"\n\nGet-ChildItem $WorkingDir -Recurse|ForEach-Object{\n If ($txtFile -contains $_.Name){\n Remove-Item $_.FullName -WhatIf\n }\n}\n\n</code></pre>\n\n<p>If the output looks OK, remove the trailing <code>-WhatIf</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T14:43:22.460", "Id": "223813", "ParentId": "223807", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T13:50:23.357", "Id": "223807", "Score": "1", "Tags": [ "powershell" ], "Title": "Check multiple subdirectories and delete if file exists" }
223807
<blockquote> <p>For the given strings (not containing numbers), print their shortened versions, where each adjacent sequence of the same characters longer than 2, change to an expression consisting of a sign and a number of repetitions.</p> </blockquote> <p><strong>Sample input:</strong></p> <pre><code>4 AAA ABCDEF CCCCCCDDDDDDD ZZAACCCDDDDEEEEEE </code></pre> <p><strong>Sample output:</strong></p> <pre><code>A3 ABCDEF C6D7 ZZAAC3D4E6 </code></pre> <p><strong>My code:</strong></p> <pre><code>#include &lt;algorithm&gt; #include &lt;cstddef&gt; #include &lt;functional&gt; #include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;string&gt; std::string reduce(std::string const&amp; word) { std::string result; for (auto it = word.cbegin(); true;) { auto curr = std::adjacent_find(it, word.cend(), std::not_equal_to&lt;int&gt;()); auto dist = std::distance(it, curr) + (curr != word.cend()); if (dist &lt; 3) { result += std::string(dist, *it); } else { result += *it + std::to_string(dist); } if (curr == word.cend()) { break; } it = 1 + curr; } return result; } int main() { std::size_t tests; std::cin &gt;&gt; tests; while (tests--) { std::string word; std::cin &gt;&gt; word; std::cout &lt;&lt; reduce(word) &lt;&lt; "\n"; } } </code></pre> <p>How could I simplify or improve this code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T15:16:52.810", "Id": "434110", "Score": "1", "body": "Welcome to Code Review! Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers). I have rolled back Rev 4 → 3" } ]
[ { "body": "<p>First impressions: nicely presented code; good use of the appropriate standard library functions and classes.</p>\n\n<p>A minor suggestion would be to change the name, given that <code>reduce</code> is a well-known concept in functional programming (and is a function in <code>&lt;numeric&gt;</code>). Perhaps call it <code>compress</code>?</p>\n\n<p>I'd suggest extracting the constant <code>3</code> to give it a meaningful name.</p>\n\n<p>Can we eliminate the <code>break</code> with some reorganisation of the loop? Perhaps by using <code>std::mismatch(it, it+1)</code> instead of <code>std::adjacent_find()</code>? (I haven't fully thought that through; it might not be better.)</p>\n\n<p>We can avoid constructing a new string here:</p>\n\n<blockquote>\n<pre><code> result += std::string(dist, *it);\n</code></pre>\n</blockquote>\n\n<p>by using the overload of <code>append()</code> that takes two iterators:</p>\n\n<pre><code> result.append(dist, *it);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T15:27:38.917", "Id": "223815", "ParentId": "223812", "Score": "5" } }, { "body": "<p>A few things might be better, but you will need to measure if they actually help. (untested code)</p>\n\n<p>The most costly thing in your program (except the I/O) is properly allocation for the strings. So to avoid continuous reallocation you could try </p>\n\n<pre><code>result.reserve(word.size());\n</code></pre>\n\n<p>and </p>\n\n<pre><code>constexpr int LargeBuffer { 4096 };\nstd::string word;\nword.reserve(LargeBuffer); // reuse the buffer.\nwhile (tests--) {\n std::cin &gt;&gt; word;\n std::cout &lt;&lt; reduce(word) &lt;&lt; \"\\n\"; // this call might use NRVO\n}\n</code></pre>\n\n<p>That might still trigger one allocation per word, so a more drastic rebuild could be</p>\n\n<pre><code>std::string&amp; reduce(std::string const&amp; word, std::string &amp; result)\n</code></pre>\n\n<p>and</p>\n\n<pre><code>constexpr int LargeBuffer { 4096 };\nstd::string word, result;\nword.reserve(LargeBuffer); // reuse the buffer.\nresult.reserve(LargeBuffer);\nwhile (tests--) {\n std::cin &gt;&gt; word;\n result.clear(); // should not dealloc.\n std::cout &lt;&lt; reduce(word, result) &lt;&lt; \"\\n\";\n}\n</code></pre>\n\n<p>The strings will grow and keep their new size if the actual word is larger than expected.</p>\n\n<p>The next most expensive should be the std::to_string</p>\n\n<pre><code> if (dist &lt; 3) {\n result.append(dist, *it); // from Toby's answer\n } else {\n result.append(*it);\n if (dist &lt; 10) {\n result.append('0'+dist);\n } else {\n result.append(std::to_string(dist)); // hopefully we are saved here by short string optimisation\n }\n }\n</code></pre>\n\n<p>The change should work nicely for your example data, less so if the repeats randomly change between &lt;10 and >= 10.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T22:21:00.760", "Id": "223836", "ParentId": "223812", "Score": "1" } } ]
{ "AcceptedAnswerId": "223815", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T14:39:50.133", "Id": "223812", "Score": "6", "Tags": [ "c++", "programming-challenge", "strings", "c++14" ], "Title": "String manipulation with std::adjacent_find" }
223812
<p>I have the following code: </p> <pre><code>import pandas as pd import numpy as np import itertools from pprint import pprint # Importing the data df=pd.read_csv('./GPr.csv', sep=',',header=None) data=df.values res = np.array([[i for i in row if i == i] for row in data.tolist()], dtype=object) # This function will make the subsets of a list def subsets(m,n): z = [] for i in m: z.append(list(itertools.combinations(i, n))) return(z) # Make the subsets of size 2 l=subsets(res,2) l=[val for sublist in l for val in sublist] Pairs=list(dict.fromkeys(l)) # Modify the pairs: mod=[':'.join(x) for x in Pairs] # Define new lists t0=res.tolist() t0=map(tuple,t0) t1=Pairs t2=mod # Make substitions result = [] for v1, v2 in zip(t1, t2): out = [] for i in t0: common = set(v1).intersection(i) if set(v1) == common: out.append(tuple(list(set(i) - common) + [v2])) else: out.append(tuple(i)) result.append(out) pprint(result, width=200) # Delete duplicates d = {tuple(x): x for x in result} remain= list(d.values()) </code></pre> <p>What it does is as follows: First, we import the csv file we want to work with in <a href="https://www.dropbox.com/s/jzholzvyavyyzn3/GPr.csv?dl=0" rel="nofollow noreferrer">here</a>. You can see that it is a list of elements, for each element we find the subsets of size two. We then write a modification to the subsets and call it <code>mod</code>. What it does is to take say <code>('a','b')</code> and convert it to <code>'a:b'</code>. We then, for each pair, go through the original data and where ever we find the pairs we substitute them. Finally we delete all the duplicates as it is given.</p> <p>The code works fine for small set of data. Yet the problem is that the file I have, has 30082 pairs where for each the list of ~49000 list should be scanned and pairs being replaced. I run this in Jupyter and after some time the Kernel dies. I wonder how one can optimise this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T17:33:37.097", "Id": "434129", "Score": "0", "body": "If I don't get this wrong, you expect your double loop to append 30082 * 49000 = 1.4e+9 elements (which are lists of strings, so probably >100 Bytes on average) to your result. That's a _lot_ to hold in memory and to print. Are you sure this code does what you want it to do?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-11T08:39:57.050", "Id": "434249", "Score": "0", "body": "Indeed you're correct about the number. Yes it does work for small sample list. But not for the big dataset I've got." } ]
[ { "body": "<p>How to resolve the output size issue (many GB in memory and console) is highly specific to your overall setting, i.e. how you want to use the data further, so I restrict my answer to look into possible performance gains.</p>\n\n<h2>Performance baseline</h2>\n\n<p>I determine the baseline by restricting you original loop logic to the first 20 pairs:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>t0=res.tolist()\nt0=[tuple(x) for x in t0]\nt1=Pairs\nt2=mod\n\ndef run_loop_original(limit=20):\n # Make substitions\n result = []\n for i_pair, (v1, v2) in enumerate(zip(t1, t2)):\n if i_pair &gt;= limit:\n break\n out = []\n for i in t0:\n common = set(v1).intersection(i)\n if set(v1) == common:\n out.append(tuple(list(set(i) - common) + [v2]))\n else:\n out.append(tuple(i))\n result.append(out)\n return result\n</code></pre>\n\n<pre><code> &gt;&gt;&gt; %timeit run_loop_original(20)\n 1 loops, best of 3: 1.33 s per loop\n</code></pre>\n\n<h2>Performance Sinks</h2>\n\n<p>As far as I can tell, those are:</p>\n\n<ul>\n<li>type conversion of string arrays</li>\n<li>repeated string comparisons to identify the pairs within tuples</li>\n<li>large nested list construction by double for-loop</li>\n</ul>\n\n<h2>Container Type Conversions</h2>\n\n<p>Here I simply leave out the tuple conversion in the nested list construction. Your code does not indicate that order of ingredients matters, so the information is equivalent, whether it is a list, tuple, or set.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>t0=res.tolist()\nt0=[tuple(x) for x in t0]\nt1=Pairs\nt2=mod\n\ndef run_loop_non_tuple(limit=20):\n # Make substitions\n result = []\n for i_pair, (v1, v2) in enumerate(zip(t1, t2)):\n if i_pair &gt;= limit:\n break\n out = []\n for i in t0:\n common = set(v1).intersection(i)\n if set(v1) == common:\n out.append(set(i) - common)\n out[-1].add(v2)\n else:\n out.append(i)\n result.append(out)\n return result\n</code></pre>\n\n<pre><code> &gt;&gt;&gt; %timeit run_loop_non_tuple(20)\n 1 loops, best of 3: 1.09 s per loop\n</code></pre>\n\n<p>This is not all, as the conversion of the individual tuples/lists to sets for the pair finding can be done outside the loop:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>t0=[set(i) for i in res.tolist()]\nt1=Pairs\nt2=mod\n\ndef run_loop_sets(limit=20):\n # Make substitions\n result = []\n for i_pair, (v1, v2) in enumerate(zip(t1, t2)):\n if i_pair &gt;= limit:\n break\n v1 = set(v1)\n out = []\n for i in t0:\n common = v1.intersection(i)\n if v1 == common:\n out.append(i - common)\n out[-1].add(v2)\n else:\n out.append(i)\n result.append(out)\n return result\n</code></pre>\n\n<pre><code> &gt;&gt;&gt; %timeit run_loop_sets(20)\n 1 loops, best of 3: 460 ms per loop\n</code></pre>\n\n<h2>Repeated String Comparisons</h2>\n\n<p>Two things might help speeding up:</p>\n\n<ul>\n<li>instead of comparing strings individually, an index can be built to find the relevant entries</li>\n<li>there is a very limited amount of words overall, so they can be mapped to integers for faster matching</li>\n</ul>\n\n<p>Let's start with a word mapping:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from itertools import chain\nall_words = np.array(list(set(chain(*t0))))\nword_mapping = {word: i for i, word in enumerate(all_words)}\n</code></pre>\n\n<pre><code> &gt;&gt;&gt; len(all_words)\n 381\n</code></pre>\n\n<p>There is no need to convert everything beforehand. Just go directly for creating an index. This can be realized as a numpy 2D-array, where we have a row per element of <code>t0</code> and a column per <code>all_words</code>. The values are just True/False values as uint8 (1 Byte per value).</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>word_index = np.zeros(shape=(len(t0), len(all_words)), dtype=np.uint8)\nfor i_row, row in enumerate(t0):\n for word in row:\n word_index[i_row, word_mapping[word]] = 1\n</code></pre>\n\n<pre><code> &gt;&gt;&gt; word_index.shape, word_index.sum()\n ((48983, 381), 416041)\n</code></pre>\n\n<p>You can now lookup which rows have a pair of words by using the <code>&amp;</code> operator:</p>\n\n<pre><code> &gt;&gt;&gt; word_index[:, word_mapping[Pairs[0][0]]] &amp; word_index[:, word_mapping[Pairs[0][1]]]\n array([0, 0, 0, ..., 0, 0, 0], dtype=uint8)\n</code></pre>\n\n<p>So we rebuild the loop with this advantage:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>t0=[set(i) for i in res.tolist()]\nt1=[set(x) for x in Pairs]\nt2=mod\n\ndef run_loop_indexed(limit=20):\n # Make substitions\n result = []\n for i_pair, (v1, v2) in enumerate(zip(t1, t2)):\n if i_pair &gt;= limit:\n break\n i1 = [word_mapping[x] for x in v1]\n ix_contain_pair = word_index[:, i1[0]] &amp; word_index[:, i1[1]]\n out = []\n for row, contains_pair in zip(t0, ix_contain_pair):\n if contains_pair:\n out.append(row - v1)\n out[-1].add(v2)\n else:\n out.append(row)\n result.append(out)\n return result\n</code></pre>\n\n<pre><code> &gt;&gt;&gt; %timeit run_loop_indexed(20)\n 1 loops, best of 3: 216 ms per loop\n</code></pre>\n\n<h2>Double for Loop</h2>\n\n<p>It would still help to avoid the nested list construction via the double loop. What helps there is, that the nested lists are identical to <code>t0</code> if the pair is missing, and it is missing in the majority of cases. So we first construct a copy of <code>t0</code> and then replace the rows that contain the pair.</p>\n\n<p>To get the indices in <code>t0</code>, flatten and use <code>np.nonzero</code>:</p>\n\n<pre><code> &gt;&gt;&gt; np.ravel(np.nonzero(word_index[:, word_mapping[Pairs[0][0]]] &amp; word_index[:, word_mapping[Pairs[0][1]]]))\n array([ 1915, 1987, 8062, 10593, 10614, 10663, 10879, 11235, 12021,\n 12096, 13445, 13805, 14630, 17658, 17701, 18865, 20712, 22560,\n 23573, 23840, 25379, 25487, 27338, 27690, 28630, 32266, 33259,\n 33884, 34309, 34412, 35430, 35463, 35968, 36326, 36977, 39477,\n 40292, 42138], dtype=int64)\n</code></pre>\n\n<pre class=\"lang-py prettyprint-override\"><code>t0=[set(i) for i in res.tolist()]\nt1=[set(x) for x in Pairs]\nt2=mod\n\ndef run_loop_indexed_2(limit=20):\n # Make substitions\n result = []\n for i_pair, (v1, v2) in enumerate(zip(t1, t2)):\n if i_pair &gt;= limit:\n break\n i1 = [word_mapping[x] for x in v1]\n ix_contain_pair = np.ravel(np.nonzero(word_index[:, i1[0]] &amp; word_index[:, i1[1]]))\n out = t0[:]\n for i in ix_contain_pair:\n out[i] = out[i] - v1\n out[i].add(v2)\n result.append(out)\n return result\n</code></pre>\n\n<pre><code> &gt;&gt;&gt; %timeit run_loop_indexed_2(20)\n 10 loops, best of 3: 43.1 ms per loop\n</code></pre>\n\n<p>I still expect you to run into memory limits on the full set and/or to crash your notebook connection trying to print the results.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-13T14:21:22.107", "Id": "224094", "ParentId": "223818", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T16:35:53.593", "Id": "223818", "Score": "4", "Tags": [ "python", "performance", "time-limit-exceeded", "numpy", "pandas" ], "Title": "Optimising iteration and substitution over large dataset" }
223818
<p><a href="https://www.codewars.com/kata/find-the-stray-number/train/javascript" rel="nofollow noreferrer">https://www.codewars.com/kata/find-the-stray-number/train/javascript</a></p> <p>I solved this challenge by sorting from least to greatest, and checking if the first element in the array matched the second element in the array. </p> <p>If the first element does not match, then the <strong>different</strong> element is the first element. </p> <p>If the first element does match, then the <strong>different</strong> element is the last element.</p> <pre><code>function stray(numbers) { numbers = numbers.sort((a, b) =&gt; a - b); if (numbers[0] !== numbers[1]) { return numbers[0]; } else { return numbers[numbers.length - 1]; } } console.log(stray([17, 17, 3, 17, 17, 17, 17])); </code></pre> <p>I'm wondering if / how this can be done with the <code>filter()</code> method instead? </p>
[]
[ { "body": "<p>You <em>could</em> use the <code>filter</code> method, but I'm not convinced it makes the code any more efficient or readable:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function stray(numbers) {\n return numbers.find(i =&gt; numbers.filter(j =&gt; j === i).length === 1);\n}\nconsole.log(stray([17, 17, 3, 17, 17, 17, 17]));\nconsole.log(stray([17, 17, 23, 17, 17, 17, 17]));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><sup>I've added an example where the \"stray\" number is greater than the others as a sanity check.</sup></p>\n\n<p><code>find</code> is a bit like <code>filter</code> except that it returns the first element in the array that causes the function to return true.</p>\n\n<p><code>filter</code> here is used to find the number which is only found in the array once.</p>\n\n<hr>\n\n<p>Your original code could be shortened by using a conditional operator, along with the <code>slice</code> function (which shortens the code necessary to get the first/last element a little):</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function stray(numbers) {\n numbers = numbers.sort((a, b) =&gt; a - b);\n return numbers.slice((numbers[0] !== numbers[1] ? 0 : -1))[0];\n}\nconsole.log(stray([17, 17, 3, 17, 17, 17, 17]));\nconsole.log(stray([17, 17, 23, 17, 17, 17, 17]));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T07:16:51.710", "Id": "434055", "Score": "1", "body": "Your `filter` code is O(n**2) while OP's code is O(n.log n), right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T09:54:36.433", "Id": "434066", "Score": "0", "body": "Indeed, the performance is horrible compared to this [answer](https://codereview.stackexchange.com/a/223838/139491) (see https://www.measurethat.net/Benchmarks/Show/5561/0/find-the-stray-v2)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T12:02:27.370", "Id": "434076", "Score": "0", "body": "@Eric I completely agree that my solution is not the most efficient. Nor was it meant to be. Perhaps, and this is just me spit-balling here, there is more to coding than speed? Perhaps readability and maintainability have some value? Unless you're running this in a tight loop 36 thousand times a second, the performance difference will be negligible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T12:18:01.470", "Id": "434080", "Score": "0", "body": "Thanks for the comment. Sorry if my words were a bit harsh. I totally agree that readability and maintainability are very important. I don't think the O(n) answer is less readable than yours, so it should be preferred IMHO." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T20:29:01.047", "Id": "223829", "ParentId": "223821", "Score": "1" } }, { "body": "<p>Here is how you could implement it with the <code>filter()</code> method:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const stray = numbers =&gt; +numbers.sort((a, b) =&gt; a - b)\n .filter((n,i,a) =&gt; (i === 0 &amp;&amp; a[0] !==a[1]) || (i === a.length-1 &amp;&amp; a[a.length-1] !== a[a.length-2]));\n\nconsole.log(stray([17, 17, 3, 17, 17, 17, 17]));\nconsole.log(stray([2, 2, 2, 2, 2, 14, 2, 2, 2, 2]));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Or in more a clean way:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const stray = numbers =&gt; numbers.sort((a, b) =&gt; a - b)\n .filter(n =&gt; n === numbers[0]).length === 1 ? numbers[0] : numbers[numbers.length-1]\n\nconsole.log(stray([17, 17, 3, 17, 17, 17, 17]));\nconsole.log(stray([2, 2, 2, 2, 2, 14, 2, 2, 2, 2]));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>But as Heretic Monkey said, this is probably not the best approach...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T20:46:50.887", "Id": "223831", "ParentId": "223821", "Score": "2" } }, { "body": "<p>This is a similar idea to the other answers here, but the implementation is a bit different.</p>\n\n<p>First of all, we can assume that the array's length is at least 3, since it needs to have at least two of the same values and one different value.</p>\n\n<p>Let's start by handling the case where the stray value is not in the first element. We could simply write:</p>\n\n<pre><code>a.find(v =&gt; v != a[0])\n</code></pre>\n\n<p>That is, find an element that's different from the first element. But what if the stray element comes first in the array? We can check if the first two elements differ. If they do, then the stray is either in the first or second position, so the third element is not a stray. In this case, we can check against the third element instead of the first; otherwise we check against the first element as before, thus:</p>\n\n<pre><code>a.find(v =&gt; a[0] != a[1] ? v != a[2] : v != a[0])\n</code></pre>\n\n<p>This is a bit code-golfey and not very readable, so I wouldn't recommend it in production, but it may be of some interest as a curiosity.</p>\n\n<p>It may be worth noting that this solution <a href=\"https://www.measurethat.net/Benchmarks/Show/5560/0/find-the-stray\" rel=\"noreferrer\">appears to perform quite well</a>, and can be <a href=\"https://www.measurethat.net/Benchmarks/Show/5561/0/find-the-stray-v2\" rel=\"noreferrer\">further optimized</a> by doing the inequality check on the first two elements before invoking <code>find</code>, and by using the third parameter to <code>find</code> to access the array, making the callback a pure function and eliminating the need to reference the array via the closed-over variable, for example:</p>\n\n<pre><code>a.find(a[0] != a[1] ?\n (v, i, a) =&gt; v != a[2] :\n (v, i, a) =&gt; v != a[0])\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T07:04:05.110", "Id": "434052", "Score": "3", "body": "This is a lot better than the other solutions, because it only loops over the array once." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T07:23:04.000", "Id": "434056", "Score": "0", "body": "This should be the accepted answer. Especially if it were a bit more readable, possibly with named functions for comparisons." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T09:50:50.353", "Id": "434064", "Score": "1", "body": "One minor nitpick: In your ternary operator, you could avoid the double negation by using `a[0] == a[1]` and reversing the two statements : `return a.find(a[0] == a[1] ? (v, i, a) => v != a[0] : (v, i, a) => v != a[2]);`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T23:32:47.070", "Id": "223838", "ParentId": "223821", "Score": "13" } }, { "body": "<p>There are some improvements that can be made to the already given answers. Especially as \n<strong>user11536834</strong> second example was a surprisingly poor performer.</p>\n\n<p>The following function improves upon given answers in terms of performance doing the same operation in 1/3rd the time </p>\n\n<pre><code>function find(nums) {\n const a = nums[0], b = nums[2];\n return a !== nums[1] ? \n nums.find(v =&gt; v !== b):\n nums.find(v =&gt; v !== a);\n}\n</code></pre>\n\n<h2>Func A</h2>\n\n<p>If we consider he best solution so far</p>\n\n<pre><code>function findA(nums) {\n return nums.find(v =&gt; nums[0] != nums[1] ? v != nums[2] : v != nums[0])\n}\n</code></pre>\n\n<p>We can double the performance by avoiding the cost of the call stack for each iteration by using a standard loop. This halves the processing time.</p>\n\n<h2>Func B</h2>\n\n<pre><code>function findB(nums) {\n var i = 0, val = nums[i++];\n while (i &lt; nums.length - 1) {\n if (nums[i++] !== val) {\n return val !== nums[i] ? val : nums[i - 1];\n }\n }\n return nums[i];\n}\n</code></pre>\n\n<p>Modifying <strong>user11536834</strong> second solution gave a very surprising result being 20 times slower than func A </p>\n\n<h2>Func C</h2>\n\n<pre><code>function findC(nums) {\n return nums.find(nums[0] !== nums[1] ? v =&gt; v !== nums[2] : v =&gt; v !== nums[0])\n}\n</code></pre>\n\n<p>OMDG that is 20 times slower than the first version. The optimizer obviously does not like the function declarations being conditional. So I moved the functions out of the ternary and added some other minor optimizations to get...</p>\n\n<h2>Func D</h2>\n\n<pre><code>function findD(nums = data[(d++) % len]) {\n const a = nums[0], b = nums[2];\n return a !== nums[1] ? \n nums.find(v =&gt; v !== b):\n nums.find(v =&gt; v !== a);\n}\n</code></pre>\n\n<p>Now we are talking, it doubled the performance again by nearly 2 on the while loop version.</p>\n\n<h2>Performance comparison</h2>\n\n<p>Running a comparison performance benchmark on 2000 different arrays with random position of the odd number out and each array 2000 items long. The results as follows.</p>\n\n<pre><code>findA.: 4.239 ±1.723µs OPS 235,919 35% Total 1,170ms 276,000 operations\nfindB.: 2.225 ±1.172µs OPS 449,504 67% Total 714ms 321,000 operations\nfindC.: 38.612 ±10.163µs OPS 25,898 4% Total 11,120ms 288,000 operations\nfindD.: 1.496 ±0.725µs OPS 668,321 *100% Total 471ms 315,000 operations\nOPS is Operations per second (Operation is the function being called)\nµs is 1 / 1,000,000 second\nms is 1 / 1,000 second\n*Best time is 100% of its self\n</code></pre>\n\n<p>Note that Javascript is seldom linear and that the length of the arrays tested was tested to be greater than the point where all 4 function were giving a linear result as the array size grew.</p>\n\n<h3>As tested</h3>\n\n<p>The test where conducted on the modified functions as follows. Data was created with 2 util functions listed below the next snippet.</p>\n\n<pre><code>var a = 0, b = 0, c = 0, d = 0;\nconst len = 2000;\nconst data = $setOf(len, i =&gt; {var b = $setOf(len, k =&gt; i); b[$randI(len)] = i + 1; return b});\n\n// test name findA\nfunction findA(nums = data[(a++) % len]) {\n return nums.find(v =&gt; nums[0] != nums[1] ? v != nums[2] : v != nums[0])\n}\n\n// test name findB\nfunction findB(nums = data[(b++) % len]) {\n var i = 0, val = nums[i++];\n while (i &lt; nums.length - 1) {\n if (nums[i++] !== val) {\n return val !== nums[i] ? val : nums[i - 1];\n }\n }\n return nums[i];\n}\n\n// test name findC\nfunction findC(nums = data[(c++) % len]) {\n return nums.find(nums[0] !== nums[1] ? v =&gt; v !== nums[2] : v =&gt; v !== nums[0])\n}\n\n// test name findD\nfunction findD(nums = data[(d++) % len]) {\n const a = nums[0], b = nums[2];\n return a !== nums[1] ? \n nums.find(v =&gt; v !== b):\n nums.find(v =&gt; v !== a);\n}\n</code></pre>\n\n<h3>Utils</h3>\n\n<pre><code>const $setOf = (count, fn = (i)=&gt;i) =&gt; {var a = [],i = 0; while (i &lt; count) { a.push(fn(i ++)) } return a };\nconst $randI = (min = 2, max = min + (min = 0)) =&gt; (Math.random() * (max - min) + min) | 0;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T13:35:01.060", "Id": "434091", "Score": "0", "body": "Chrome really blew it here. In Firefox the \"optimized\" version is about 20% faster for me, as expected. Maybe worth reporting this on Chromium issue tracker, if it's not there already? +1 for going the extra mile." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T19:08:43.337", "Id": "434138", "Score": "0", "body": "@EricDuminil See comment by said user above yours. that bit of code is why I posted as on chrome it was 20 times slower. Details in my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T19:18:07.717", "Id": "434141", "Score": "0", "body": "@Blindman67: Sorry about that, I thought it was the second version." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-12T19:36:32.277", "Id": "434533", "Score": "0", "body": "For FuncB you should really cache `nums.length-1` if you want a fairer comparison" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-12T20:44:00.243", "Id": "434538", "Score": "0", "body": "@konijn caching length would only help for run once never again function as the optimizer will spot that the value is constant. My performance testing code pre runs the code allowing the optimizer to do its thing. Testing `num.length - 1` against cached `length` results with a consistently slower performance (~40µs per call for same test as in answer (though this is below error rate and I would normally call it no difference)) This is likely due to the need to create the addition constant const `len = nums.length - 1;` on the heap each call" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-12T20:55:43.797", "Id": "434540", "Score": "0", "body": "@konijn Correction on prev comment. The reduced performance is closer to ~300µs per call when caching the length. (still under the error rate)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-14T18:16:37.103", "Id": "434755", "Score": "0", "body": "Odd, jsperf.com disagrees with your findings." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-14T22:53:35.573", "Id": "434784", "Score": "0", "body": "@konijn jspref is flawed. See this test created from the test code in my answer (including cached length Solution B1) and note how all the array functions (solutions A, C,and D) are hugely impacted. I only test chrome. https://jsperf.com/crperfexample/1" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T12:48:31.530", "Id": "223862", "ParentId": "223821", "Score": "4" } }, { "body": "<p>I'll try to offer an alternative solution to your problem.</p>\n\n<p>The linked kata contains the following piece of information</p>\n\n<blockquote>\n <p>You are given an odd-length array of integers, in which all of them are the same, except for one single number</p>\n</blockquote>\n\n<p>This means, that the array is guaranteed to contain <em>even number of same elements</em>. </p>\n\n<p>This fact could be leveraged to achieve a very elegant solution using the XOR operator:</p>\n\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>const arr = [17, 17, 3, 17, 17, 17, 17];\n\n// XOR together every value inside arr\nconst answer = arr.reduce((acc, value) =&gt; acc ^= value, 0);\n\nconsole.log(answer);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>The complexity of this algorithm is <em>O(n)</em>, as opposed to using sort, which runs in <em>O(nlogn)</em> at best (in most cases).</p>\n\n<p>Now, the reason this works is that XOR operator has a useful property of \"cancelling out\" the same elements. In other words:</p>\n\n<blockquote>\n <ol>\n <li>n ^ n = 0</li>\n <li>n ^ 0 = x</li>\n </ol>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T18:19:44.107", "Id": "434134", "Score": "0", "body": "clever, but fails on `[17, 3, 17, 17, 17, 17, 17, 17]` (it returns 18)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T19:10:03.340", "Id": "434139", "Score": "1", "body": "@Brandon \"You are given an odd-length array of integers, ...\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T19:23:47.270", "Id": "434142", "Score": "1", "body": "@AlexanderLomia But his array has an even number of elements! The ordering doesn't matter since XOR is commutative. The reason his example returns 18 is that there's an extra 17 left over, and 17 ^ 3 = 18." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T19:37:49.697", "Id": "434144", "Score": "0", "body": "@Théophile Yes, you're completely right! That example got me really confused, because I assumed that the array had an odd number of elements. Thanks for pointing that out!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T21:20:48.443", "Id": "434155", "Score": "0", "body": "Yeah good point" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-10T16:01:11.127", "Id": "223881", "ParentId": "223821", "Score": "5" } } ]
{ "AcceptedAnswerId": "223838", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T17:26:48.773", "Id": "223821", "Score": "8", "Tags": [ "javascript", "programming-challenge", "array" ], "Title": "Find The One Element In An Array That is Different From The Others" }
223821
<p>About a month ago I made a Tetris game for Windows. After a <a href="/q/216333">helpful review</a>, I improved the code. I want to hear again an opinion about the implementation, how readable the code is, new mistakes or anything that will improve the quality of the code.</p> <h3>Action.h</h3> <pre><code>#pragma once #ifndef ACTIONS_H #define ACTIONS_H /* Possible actions that a player can do */ class Action { public: static constexpr char moveLEFT{ 'a' }; static constexpr char moveRIGHT{ 'd' }; static constexpr char moveDOWN{ 's' }; static constexpr char rotateLEFT{ 'q' }; static constexpr char rotateRIGHT{ 'e' }; }; #endif // !ACTIONS_H </code></pre> <h3>Coordinates.cpp</h3> <pre><code>#include "Coordinates.h" Coordinates::Coordinates(int x, int y) { this-&gt;x = x; this-&gt;y = y; } Coordinates&amp; Coordinates::operator=(const Coordinates &amp;coord) { if (this != &amp;coord) { this-&gt;x = coord.x; this-&gt;y = coord.y; } return *this; } int Coordinates::getX() { return x; } int Coordinates::getY() { return y; } void Coordinates::setX(const int &amp;x) { this-&gt;x = x; } void Coordinates::setY(const int &amp;y) { this-&gt;y = y; } void Coordinates::moveCoordinatesInADirection(char direction) { switch (direction) { case Action::moveLEFT: y--; break; case Action::moveRIGHT: y++; break; case Action::moveDOWN: x++; break; default: break; } } void Coordinates::Draw() { MoveTo(x + Drawable::startPositionX, y + Drawable::startPositionY); cout &lt;&lt; form; } void Coordinates::DeleteDraw() { MoveTo(x + Drawable::startPositionX, y + Drawable::startPositionY); cout &lt;&lt; " "; } </code></pre> <h3>Coordinates.h</h3> <pre><code>#pragma once #ifndef COORDINATES_H #define COORDINATES_H #include "Actions.h" #include "Drawable.h" #include &lt;iostream&gt; using namespace std; class Coordinates : public Drawable { private: int x; int y; public: static constexpr char form{ '*' }; public: Coordinates(int x = 0, int y = 0); Coordinates&amp; operator =(const Coordinates &amp;coord); int getX(); int getY(); void setX(const int &amp;x); void setY(const int &amp;y); // Methods using a coordinate void moveCoordinatesInADirection(char direction); void Draw() override; void DeleteDraw() override; }; #endif // !Coordinates_H </code></pre> <h3>Difficulty.cpp</h3> <pre><code>#include "Difficulty.h" int Difficulty::increaseSpeedAfterXTilesPlayed = 20; int Difficulty::speedOfTiles = 600; void Difficulty::setDifficulty(char numberOfDifficulty) { switch (numberOfDifficulty) { //Easy case '1': increaseSpeedAfterXTilesPlayed = 20; speedOfTiles = 600; break; //Normal case '2': increaseSpeedAfterXTilesPlayed = 15; speedOfTiles = 400; break; //Hard case '3': increaseSpeedAfterXTilesPlayed = 10; speedOfTiles = 200; break; //Impossible case '4': increaseSpeedAfterXTilesPlayed = 5; speedOfTiles = 100; break; } } void Difficulty::increaseSpeedafterXTiles(int&amp; counterNumberOfTilesPlayed) { if ((counterNumberOfTilesPlayed == Difficulty::increaseSpeedAfterXTilesPlayed) &amp;&amp; (Difficulty::speedOfTiles &gt; 20)) { Difficulty::speedOfTiles = Difficulty::speedOfTiles - 20; counterNumberOfTilesPlayed = 0; } } </code></pre> <h3>Difficulty.h</h3> <pre><code>#pragma once #ifndef DIFFICULTY_H #define DEFFICULTY_H class Difficulty { public: static int increaseSpeedAfterXTilesPlayed; static int speedOfTiles; public: static void setDifficulty(char numberOfDifficulty); static void increaseSpeedafterXTiles(int&amp; counterNumberOfTilesPlayed); }; #endif // !DIFFICULTY_H </code></pre> <h3>Drawable.cpp</h3> <pre><code>#include "Drawable.h" int Drawable::getstartPositionX() { return startPositionX; } void Drawable::hideCursor() { CONSOLE_CURSOR_INFO info = { 100,FALSE }; SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &amp;info); } void Drawable::MoveTo(const int &amp;x, const int &amp;y) { COORD coord = { startPositionY + y,startPositionX + x }; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); } </code></pre> <h3>Drawable.h</h3> <pre><code>#pragma once #ifndef DRAWABLE_H #define DRAWABLE_H #include &lt;windows.h&gt; class Drawable { protected: //The position where the table game will be displayed in console static constexpr int startPositionX{ 10 }; static constexpr int startPositionY{ 25 }; public: static int getstartPositionX(); static void hideCursor(); static void MoveTo(const int &amp;x,const int &amp;y); virtual void Draw() = 0; virtual void DeleteDraw() = 0; }; #endif // !DRAWABLE_H </code></pre> <h3>Source.cpp</h3> <pre><code>#include "Table.h" int main() { Table a; try { a.startGame(); } catch (...) { // In case player loses Drawable::MoveTo(Drawable::getstartPositionX() + Table::numberOfLines + 1, 0); cout &lt;&lt; "\n" &lt;&lt; "Good job, you made " &lt;&lt; a.score * 1000 &lt;&lt; " points.\n"; } } </code></pre> <h3>Table.cpp</h3> <pre><code>#include "Table.h" Table::Table() { // When you start the game the table is empty and the score is 0 score = 0; for (int currentLine = 0; currentLine &lt; numberOfLines; currentLine++) { for (int currentColumn = 0; currentColumn &lt; numberOfColumns; currentColumn++) { table[currentLine][currentColumn] = 0; } } } void Table::informationAboutGame() { // General informations about the game and setting the difficulty the player wants to play on cout &lt;&lt; "\n\n\n\t This is a tetris game.The controls for the game are:\n"; cout &lt;&lt; "\n\t a - move the tile left"; cout &lt;&lt; "\n\t d - move the tile right"; cout &lt;&lt; "\n\t s - move the tile down"; cout &lt;&lt; "\n\t e - rotate the tile right"; cout &lt;&lt; "\n\t q - rotate the tile left"; cout &lt;&lt; "\n\n\t The game has 3 difficulties: "; cout &lt;&lt; "\n\t 1. Easy"; cout &lt;&lt; "\n\t 2. Normal"; cout &lt;&lt; "\n\t 3. Hard"; cout &lt;&lt; "\n\t 4. Impossible"; cout &lt;&lt; "\n\n\t Introduce the number of the difficulty you want to play on and good luck: "; char numberOfDifficulty = _getch(); while ((numberOfDifficulty != '1') &amp;&amp; (numberOfDifficulty != '2') &amp;&amp; (numberOfDifficulty != '3') &amp;&amp; (numberOfDifficulty!='4')) { cout &lt;&lt; "\n\tInsert a number between 1-4: "; numberOfDifficulty = _getch(); } Difficulty::setDifficulty(numberOfDifficulty); } void Table::checkingAndDeletingCompletedLines() { // We parse the table and check if there is any line with only 1 on it, and than we delete the line int check = 1; for (int currentLine = 0; currentLine &lt; numberOfLines; currentLine++) { check = 1; for (int currentColumn = 0; currentColumn &lt; numberOfColumns; currentColumn++) { if (table[currentLine][currentColumn] == 0) { check = 0; break; } } if (check) { deleteCompletedLineFromTable(currentLine); score++; } } } void Table::deleteCompletedLineFromTable(const int&amp; line) { // Deleting the line which is completed // We need to actualize the table by replacing every line (starting from the completed line until the second line) with the previous lines // Also we need to draw the actualized lines in the console for (int currentLine = line; currentLine &gt; 0; currentLine--) { for (int currentColumn = 0; currentColumn &lt; numberOfColumns; currentColumn++) { Drawable::MoveTo(currentLine + Drawable::startPositionX, currentColumn + Drawable::startPositionY); if (table[currentLine - 1][currentColumn] == 0) { cout &lt;&lt; " "; } else { cout &lt;&lt; Coordinates::form; } table[currentLine][currentColumn] = table[currentLine - 1][currentColumn]; } } for (int currentColumn = 0; currentColumn &lt; numberOfColumns; currentColumn++) { Drawable::MoveTo(0 + Drawable::startPositionX, currentColumn + Drawable::startPositionY); cout &lt;&lt; " "; table[0][currentColumn] = 0; } } void Table::moveTileDownAutomatically() { //Moving the actual tile down every and checking if the player wants to make a move(right, left, down) or rotate(right, left) the tile actualTile.Draw(); int counterTime = 0; do { counterTime = 0; while (counterTime &lt;= Difficulty::speedOfTiles) { if (_kbhit()) // if the player presses a key on keyboard { possibleMoves(counterTime); } Sleep(1); counterTime = counterTime + 1; } if (checkIfCanMoveInADirection(Action::moveDOWN)) { actualTile.DeleteDraw(); moveTileInADirection(Action::moveDOWN); actualTile.Draw(); } else { break; } } while (true); } void Table::moveTileInADirection(char direction) { // To move the tile in a direction we need to : // - delete the previous tile from the game table // - move the tile to the new coordinates // - actualizate the game table for (int i = 0; i &lt; 4; i++) { table[actualTile.getcoordX(i)][actualTile.getcoordY(i)] = 0; } actualTile.moveTileInADirection(direction); for (int i = 0; i &lt; 4; i++) { table[actualTile.getcoordX(i)][actualTile.getcoordY(i)] = 1; } } void Table::possibleMoves(int &amp;counterTime) { //Possible moves that can be effectuated on a tile (move and rotate) char direction = _getch(); if (checkIfCanMoveInADirection(direction)) { actualTile.DeleteDraw(); // delete old tile moveTileInADirection(direction); // move the tile in the direction the player wanted actualTile.Draw(); // draw the new tile if (direction == Action::moveDOWN) { // If we move the tile down we reset the counter until the tile moves again down by itself counterTime = 1; } } // check if the player wanted to rotate the tile (right, left) if ((direction == Action::rotateRIGHT) || (direction == Action::rotateLEFT)) { actualTile.DeleteDraw(); rotateTileInADirection(direction); actualTile.Draw(); } } void Table::positioningTileInTableAfterRotation() { // This method is used to check and correct a tile if it goes out of boundaries of the game table after a rotation int index = 0; int checkOutOfBoundaries = 0; while (index &lt; 4) { if (actualTile.getcoordY(index) &lt; 0) { // passed left boundary of the game table for (int j = 0; j &lt; 4; j++) { actualTile.setcoordY(j, actualTile.getcoordY(j) + 1); } checkOutOfBoundaries = 1; } if (actualTile.getcoordY(index) &gt; numberOfColumns - 1) { // passed right boundary of the game table for (int j = 0; j &lt; 4; j++) { actualTile.setcoordY(j, actualTile.getcoordY(j) - 1); } checkOutOfBoundaries = 1; } if (actualTile.getcoordX(index) &lt; 0) { // passed top boundary of the game table and there are cases where the player loses for (int j = 0; j &lt; 4; j++) { actualTile.setcoordX(j, actualTile.getcoordX(j) + 1); } for (int j = 0; j &lt; 4; j++) { if ((actualTile.getcoordX(j) &gt; 0) &amp;&amp; (table[actualTile.getcoordX(j)][actualTile.getcoordY(j)] == 1)) { throw 0; } } checkOutOfBoundaries = 1; } if ((actualTile.getcoordX(index) &gt; numberOfLines - 1) || (table[actualTile.getcoordX(index)][actualTile.getcoordY(index)] == 1)) { // passed the down boundary or reached a possition that is occupied for (int j = 0; j &lt; 4; j++) { actualTile.setcoordX(j, actualTile.getcoordX(j) - 1); } checkOutOfBoundaries = 1; } if (checkOutOfBoundaries == 1) { index = 0; checkOutOfBoundaries = 0; } else { index++; } } } void Table::rotateTileInADirection(char direction) { // To rotate the tile in a direction we need to : // - delete the previous tile from the game table // - move the tile to the new coordinates and adjust it so it doesnt pass the boundaries of the game table // - actualizate the game table for (int i = 0; i &lt; 4; i++) { table[actualTile.getcoordX(i)][actualTile.getcoordY(i)] = 0; } actualTile.rotateTileInADirection(direction); positioningTileInTableAfterRotation(); for (int i = 0; i &lt; 4; i++) { table[actualTile.getcoordX(i)][actualTile.getcoordY(i)] = 1; } } void Table::startGame() { Drawable::hideCursor(); informationAboutGame(); DeleteDraw(); Draw(); int counterNumberOfTilesPlayed = 0; // This while will end when the player will lose while (true) { checkingAndDeletingCompletedLines(); actualTile = Tiles::generateRandomTile(); if (checkIfPlayerLost() == false) { moveTileDownAutomatically(); counterNumberOfTilesPlayed++; Difficulty::increaseSpeedafterXTiles(counterNumberOfTilesPlayed); } else { Drawable::MoveTo(Drawable::startPositionX + numberOfLines + 1, 0); cout &lt;&lt; "\n" &lt;&lt; "Good job, you made " &lt;&lt; score * 1000 &lt;&lt; " points.\n"; break; } } } void Table::Draw() { // Method used to draw the table for (int index = -1; index &lt;= numberOfLines; index++) { MoveTo(Drawable::startPositionX + index, Drawable::startPositionY - 1); cout &lt;&lt; char(219); MoveTo(Drawable::startPositionX + index, Drawable::startPositionY + numberOfColumns); cout &lt;&lt; char(219); } for (int index = -1; index &lt;= numberOfColumns; index++) { Drawable::MoveTo(Drawable::startPositionX - 1, Drawable::startPositionY + index); cout &lt;&lt; char(219); Drawable::MoveTo(Drawable::startPositionX + numberOfLines, Drawable::startPositionY + index); cout &lt;&lt; char(219); } } void Table::DeleteDraw() { // Method used to delete the table system("cls"); } bool Table::belongsToActualTile(const int&amp; x, const int&amp; y) { //Checking if a piece(point/coordinate) of a tile belonds to the actual tile for (int currentCoordinate = 0; currentCoordinate &lt; 4; currentCoordinate++) { if ((actualTile.getcoordX(currentCoordinate) == x) &amp;&amp; (actualTile.getcoordY(currentCoordinate) == y)) { return false; } } return true; } bool Table::checkIfCanMoveInADirection(char direction) { for (int i = 0; i &lt; 4; i++) { switch (direction) { // Check if the player can move left case Action::moveLEFT: if ((actualTile.getcoordY(i) - 1 &lt; 0) || ((belongsToActualTile(actualTile.getcoordX(i), actualTile.getcoordY(i) - 1)) &amp;&amp; (table[actualTile.getcoordX(i)][actualTile.getcoordY(i) - 1] == 1))) { return false; } break; // Check if the player can move right case Action::moveRIGHT: if ((actualTile.getcoordY(i) + 1 &gt; numberOfColumns - 1) || ((belongsToActualTile(actualTile.getcoordX(i), actualTile.getcoordY(i) + 1)) &amp;&amp; (table[actualTile.getcoordX(i)][actualTile.getcoordY(i) + 1] == 1))) { return false; } break; // Check if the player can move down case Action::moveDOWN: if ((actualTile.getcoordX(i) + 1 &gt; numberOfLines - 1) || ((belongsToActualTile(actualTile.getcoordX(i) + 1, actualTile.getcoordY(i))) &amp;&amp; (table[actualTile.getcoordX(i) + 1][actualTile.getcoordY(i)] == 1))) { return false; } break; default: break; } } return true; } bool Table::checkIfPlayerLost() { for (int currentCoordinate = 0; currentCoordinate &lt; 4; currentCoordinate++) { if (table[actualTile.getcoordX(currentCoordinate)][actualTile.getcoordY(currentCoordinate)] == 1) { return true; } } return false; } </code></pre> <h3>Table.h</h3> <pre><code>#pragma once #ifndef TABLE_H #define TABLE_H #include "Difficulty.h" #include "Tile.h" #include "Tiles.h" #include &lt;conio.h&gt; #include &lt;random&gt; class Table : public Drawable // class that represents the game table { public: static constexpr int numberOfColumns{ 11 }; static constexpr int numberOfLines{ 21 }; long score; private: int table[numberOfLines][numberOfColumns]; // the game table= a matrix with 0 if there is nothing draw in that point and 1 if there is something draw Tile actualTile; // the tile that moves in the game table(the actual tile) public: Table(); void informationAboutGame(); void checkingAndDeletingCompletedLines(); void deleteCompletedLineFromTable(const int&amp; line); // after a line from the table is completated, it will be deleted from the game table and the score will rise void moveTileDownAutomatically(); void moveTileInADirection(char direction); void possibleMoves(int&amp; counterTime); // possible moves of a player (right, left, down) void positioningTileInTableAfterRotation(); void rotateTileInADirection(char direction); void startGame(); void Draw(); void DeleteDraw(); bool belongsToActualTile(const int&amp; x, const int&amp; y); bool checkIfCanMoveInADirection(char direction); bool checkIfPlayerLost(); }; #endif // !TABLE_H </code></pre> <h3>Tile.cpp</h3> <pre><code>#include "Tile.h" #include "Table.h" Tile::Tile() { for (int index = 0; index &lt; 4; index++) { coordTile[index].setX(0); coordTile[index].setY(0); } centerOfTile = -1; } Tile&amp; Tile::operator=(const Tile &amp;tile) { if (this != &amp;tile) { for (int i = 0; i &lt; 4; i++) { this-&gt;coordTile[i] = tile.coordTile[i]; } this-&gt;centerOfTile = tile.centerOfTile; } return *this; } /* A tile is in tiles.in is saved like this: 0 0 0 2 0 2 2 2 0 0 0 0 0 0 0 0 A tile stores has a array of 4 coordinates(Coordinates) and a center(int) In the array we will save the 4 coordinates ((0,3) (1,1) (1,2) (1,3)) that don't have the value 0 in matrix, and in the centerOfTile the center of the figure */ void Tile::initializationOfTile(ifstream&amp; input) { int counter = 0; int checkValue = 0; for (int x = 0; x &lt; 4; x++) { for (int y = 0; y &lt; 4; y++) { input &gt;&gt; checkValue; if (checkValue != 0) { coordTile[counter].setX(x); coordTile[counter++].setY(Table::numberOfColumns / 2 + 2 - y); // Setting the coordinate for Y in the middle of the table if ((x == 1) &amp;&amp; (y == 2)) { centerOfTile = counter - 1; } } } } } int Tile::getcoordX(const int &amp;position) { return coordTile[position].getX(); } int Tile::getcoordY(const int &amp;position) { return coordTile[position].getY(); } int Tile::getcenterOfTile(const int &amp;position) { return centerOfTile; } void Tile::setcoordX(const int &amp;position, const int &amp;x) { coordTile[position].setX(x); } void Tile::setcoordY(const int &amp;position, const int &amp;y) { coordTile[position].setY(y); } void Tile::setcenterOfTile(const int &amp;centerOfTile) { this-&gt;centerOfTile = centerOfTile; } void Tile::moveTileInADirection(char direction) { for (int currentCoordinate = 0; currentCoordinate &lt; 4; currentCoordinate++) { coordTile[currentCoordinate].moveCoordinatesInADirection(direction); } } void Tile::rotateTileInADirection(char direction) { int dir = 0; switch (direction) { case Action::rotateRIGHT: // to rotate the tile to the right we need +90* check formula down dir = +90; break; case Action::rotateLEFT: // to rotate the tile to the left we need -90* check formula down dir = -90; break; default: return; } // If the tile can be rotated if (centerOfTile != -1) { double centerOfTileX = coordTile[centerOfTile].getX(); double centerOfTileY = coordTile[centerOfTile].getY(); double tileX = 0; double tileY = 0; // Rotate every piece(point/coordinate) from the tile with 90*(to right) or -90*(to left) depends on dir for (int currentCoordinate = 0; currentCoordinate &lt; 4; currentCoordinate++) { tileX = (double) coordTile[currentCoordinate].getX(); tileY = (double) coordTile[currentCoordinate].getY(); coordTile[currentCoordinate].setX((int)round((tileX - centerOfTileX) * cos((3.14 * dir) / 180) + (tileY - centerOfTileY) * sin((3.14 * dir) / 180) + centerOfTileX)); coordTile[currentCoordinate].setY((int)round((centerOfTileX - tileX) * sin((3.14 * dir) / 180) + (tileY - centerOfTileY) * cos((3.14 * dir) / 180) + centerOfTileY)); } } } void Tile::Draw() { for (int currentCoordinate = 0; currentCoordinate &lt; 4; currentCoordinate++) { coordTile[currentCoordinate].Draw(); // Drawing the tile by drawing every piece (point/coordinate) of it } } void Tile::DeleteDraw() { for (int currentCoordinate = 0; currentCoordinate &lt; 4; currentCoordinate++) { coordTile[currentCoordinate].DeleteDraw(); // Deleting the tile by deleting every piece (point/coordinate) of it } } </code></pre> <h3>Tile.h</h3> <pre><code>#pragma once #ifndef TILE_H #define TILE_H #include "Coordinates.h" #include "Drawable.h" #include &lt;fstream&gt; // Class that represents a tile and all its methods class Tile : public Drawable { private: // Every tile is composed of 4 coordinates and a center Coordinates coordTile[4]; int centerOfTile; public: Tile(); Tile&amp; operator=(const Tile &amp;tile); void initializationOfTile(ifstream&amp; input); // Getter and setter int getcenterOfTile(const int &amp;position); int getcoordX(const int &amp;position); int getcoordY(const int &amp;position); void setcenterOfTile(const int &amp;centerOfTile); void setcoordX(const int &amp;position, const int &amp;x); void setcoordY(const int &amp;position, const int &amp;y); // Methods using a tile void moveTileInADirection(char direction); // Moves the tile in a specific direction (right, left, down) void rotateTileInADirection(char direction); // Rotates the tile in a specific direction (right, left) void Draw() override; // Overrides function Draw() from Drawable() and is used to draw the tile in the game table void DeleteDraw() override; // Overrides function DeleteDraw() from Drawable() and is used to delete the tile from the game table }; #endif // !TILE_H </code></pre> <h3>Tiles.cpp</h3> <pre><code>#include "Tiles.h" int Tiles::numberOfTiles = initializationOfNumberOfTiles(); Tile* Tiles::figures = initializationOfFigures(); int Tiles::initializationOfNumberOfTiles() { int numberOfTiles = 0; ifstream input("tiles.in"); input &gt;&gt; numberOfTiles; input.close(); return numberOfTiles; } Tile* Tiles::initializationOfFigures() { Tile* figures; int numberOfTiles = 0; ifstream input("tiles.in"); input &gt;&gt; numberOfTiles; figures = new Tile[numberOfTiles]; for (int currentTile = 0; currentTile &lt; numberOfTiles; currentTile++) { figures[currentTile].initializationOfTile(input); } //The center of a line respectively a square is different than the other figures figures[0].setcenterOfTile(2); figures[3].setcenterOfTile(-1); input.close(); return figures; } Tile Tiles::generateRandomTile() { Tile randomTile; int randomNumber = 0; random_device random; uniform_int_distribution&lt;int&gt;dist(0, numberOfTiles - 1); randomNumber = dist(random); randomTile = figures[randomNumber]; return randomTile; } Tiles::~Tiles() { delete[] figures; } </code></pre> <h3>Tiles.h</h3> <pre><code>#pragma once #ifndef TILES_H #define TILES_H #include "Tile.h" #include &lt;fstream&gt; #include &lt;random&gt; class Tiles // Contains the number of tiles and the tiles possible { private: static int numberOfTiles; static Tile* figures; private: static int initializationOfNumberOfTiles(); static Tile* initializationOfFigures(); ~Tiles(); public: static Tile generateRandomTile(); }; #endif // !TILES_H </code></pre> <h3>tiles.in</h3> <pre><code>7 2 2 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 2 2 2 0 0 0 0 0 0 0 0 0 0 0 2 0 2 2 2 0 0 0 0 0 0 0 0 0 2 2 0 0 2 2 0 0 0 0 0 0 0 0 0 0 0 2 2 0 2 2 0 0 0 0 0 0 0 0 0 0 0 2 0 0 2 2 2 0 0 0 0 0 0 0 0 0 2 2 0 0 0 2 2 0 0 0 0 0 0 0 0 </code></pre> <p>The code is also available: <a href="https://github.com/FirescuOvidiu/Tetris-game-for-Windows" rel="nofollow noreferrer">Github Tetris game</a></p> <p><strong>Edit</strong>: I will respond to both commentaries in this edit, thanks you both for the time spend to respond. <br>So, I managed to move almost all includes in the .cpp files, rearranged the methods and members in classes (pub, prot, priv), modified <code>const&amp; int</code> in <code>int</code>, used const wherever I could, deleted the copy constructor and other destructors that I didn't need, gave better names to the variables, used namespace instead of some classes that had only static methods, made better comments. I didn't modify the prefix for members, because it seemed harder to read the code, and I tried to use namespace on every class but than I modified back without namespace because don't know how to get rid of x::x::A(); and it makes the lines so long and hard to read, tried to don't use namespace std; anywhere, I used it only in one file .cpp out of 15files. Replaced every array with a std::vector, managed to get rid of the try catch block. In Difficulty.cpp I had <code>int&amp; counterNumberOfTilesPlayed;</code> because I change this value in the function. Besides that I had before on every function <code>const type&amp;</code>.<br>I will get rid of the namespace std; totally and try to find a way to use namespace tomorrow I think. Besides that I did everyother observations. I don't know if I should add the code again in this thread, I updated the github and all the changes can be seen in the link above.<br><strong>Edit 2:</strong> @Sandro4912 managed to do the last advice you gave me that I didn't do last night and wrapped all functions and classes into a namespace, stopped using namespace std;</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T21:10:21.060", "Id": "434016", "Score": "1", "body": "Unfortunately your question is off-topic as of now, as the code to be reviewed must be [present in the question.](//codereview.meta.stackexchange.com/q/1308) Code behind links is considered non-reviewable. Please add the code you want reviewed in your question. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T21:15:54.253", "Id": "434017", "Score": "0", "body": "I have 15 different files (.h and .cpp) because I separated declaration and implementation and put one class per file. Should I copy all the code from all the 15 files in the question ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T21:31:51.350", "Id": "434020", "Score": "0", "body": "You could do that or just the most important classes and their interfaces. The more code you supply, generally the more comprehensive and useful the reviews." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T23:00:47.807", "Id": "434031", "Score": "0", "body": "I understand I will edit the question tomorrow morning with the code and everything." } ]
[ { "body": "<p>No time to read through all the code for now. So just some random observations.</p>\n\n<p><strong>In Coordinates.h:</strong></p>\n\n<p><strong>Include as less as poissible in headers:</strong> You include <code>iostream</code> but it is only needed in <code>Coordinates.cpp</code>. Generally you should include as less as possible in header files. If\nyou include <code>iostream</code> in the header every class which includes <code>Coordinates.h</code> also includes <code>iostream</code> even if it is not necessary. This leads to longer compilation times. Same for <code>Actions.h</code></p>\n\n<p><strong>Follow the order public protected private in classes:</strong>\nYou want to read the most important parts of a class at first. Normally this is the functions the user can use, not implementation specific details like private members. </p>\n\n<p><strong>Pass built in types by value</strong>: It is cheaper to copy an int than to pass it by const reference. So in youre setX method you should just pass it as <code>int</code> not <code>const int&amp;</code></p>\n\n<p><strong>Use const when possible</strong>: <code>getX()</code> does not modify its object so declare it const. You should always use const for functions who don't modify the object.</p>\n\n<p><strong>Don't declare a Copy Constructor on trivial classes</strong>: Youre class only has int data members. Therefore youre compiler will happily generate the copy constructor for you. Theres absolutely no need to declare it. Besides if you declare a copy constructor you should also declare the other classes of the rule of five: <a href=\"https://en.cppreference.com/w/cpp/language/rule_of_three\" rel=\"nofollow noreferrer\">https://en.cppreference.com/w/cpp/language/rule_of_three</a>. In the case of youre class its not necessary.</p>\n\n<p><strong>Be consistent with naming</strong>: I would not use capital letters for functions. So <code>Draw()</code> and <code>DeleteDraw()</code> should be <code>draw()</code> and <code>deleteDraw()</code>.</p>\n\n<p><strong>Don't use namespace std:</strong> Especially not in a header file. You force youre user to import all the namespace std if they ever include youre header file. It really is very bad style to use namespace std. <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice</a> </p>\n\n<p><strong>Use a namespace</strong>: You should wrap all youre functions and classes in its own namespace to prevent nameclashes. Otherwise if you write a programm with other libraries theres the danger nameclases happen. <a href=\"https://stackoverflow.com/questions/4211827/why-and-how-should-i-use-namespaces-in-c\">https://stackoverflow.com/questions/4211827/why-and-how-should-i-use-namespaces-in-c</a></p>\n\n<p><strong>Use a prefix for members::</strong> This is a bit controversial but i would use a prefix m for member variables so they are clearly visible as member variables. It also elimnates the need for <code>this-&gt;</code> in youe <code>coordinates.cpp</code></p>\n\n<p><strong>Avoid unessary comments:</strong>: The comment in youre class <code>Methods using a coordinate</code> is just a bloat its pretty obvious that these methods do sth with Coordinates because they are in the Coordinates class.</p>\n\n<p>Putting everything together we get this:</p>\n\n<p><strong>Coordinate.h</strong></p>\n\n<pre><code>#ifndef COORDINATES_H\n#define COORDINATES_H\n\n#include \"Drawable.h\"\n\nnamespace tetris {\n\n class Coordinates : public Drawable\n {\n public:\n Coordinates(int x = 0, int y = 0);\n\n int getX() const;\n int getY() const;\n\n void setX(int x);\n void setY(int y);\n\n // Methods using a coordinate\n void moveCoordinatesInADirection(char direction);\n void draw() override;\n void deleteDraw() override;\n\n private:\n static constexpr char form{ '*' };\n\n int mX;\n int mY;\n };\n}\n\n#endif \n</code></pre>\n\n<p><strong>Coordinates.cpp</strong></p>\n\n<pre><code>#include \"Coordinates.h\"\n\n#include \"Actions.h\"\n\n#include &lt;iostream&gt;\n\nnamespace tetris {\n\n Coordinates::Coordinates(int x, int y)\n :mX{x}, mY{y}\n {\n }\n\n int Coordinates::getX() const\n {\n return mX;\n }\n\n int Coordinates::getY() const\n {\n return mY;\n }\n\n void Coordinates::setX(int x)\n {\n mX = x;\n }\n\n void Coordinates::setY(int y)\n {\n mY = y;\n }\n\n void Coordinates::moveCoordinatesInADirection(char direction)\n {\n switch (direction)\n {\n case Action::moveLEFT:\n mY--;\n break;\n case Action::moveRIGHT:\n mY++;\n break;\n case Action::moveDOWN:\n mX++;\n break;\n default:\n break;\n }\n }\n\n void Coordinates::draw()\n {\n MoveTo(mX + Drawable::startPositionX, mY + Drawable::startPositionY);\n std::cout &lt;&lt; form;\n }\n\n void Coordinates::deleteDraw()\n {\n MoveTo(mX + Drawable::startPositionX, mY + Drawable::startPositionY);\n std::cout &lt;&lt; \" \";\n }\n}\n</code></pre>\n\n<p>I will probaly add more to this answer later when I have time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-14T21:10:53.270", "Id": "434768", "Score": "1", "body": "Thanks again @Sandro4912 for taking your free time to help me improve even more the quality of the code and learn. I posted an response to your answer in the question." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-13T13:42:33.460", "Id": "224091", "ParentId": "223832", "Score": "2" } }, { "body": "<p><strong>Action.h</strong></p>\n\n<ol>\n<li>The <code>Action</code> class only contains public static data members. While it's not illegal, a class might not be the best way to go about it. Consider using <code>struct</code>, which is the same as a <code>class</code> but has <code>public</code>as the default access specifier. Or even better, don't use a <code>class</code> or <code>struct</code> and instead, wrap it inside a namespace, which seems perfect for this kind of thing.</li>\n</ol>\n\n\n\n<pre><code>namespace Action\n{\n static constexpr char moveLEFT{ 'a' };\n static constexpr char moveRIGHT{ 'd' };\n static constexpr char moveDOWN{ 's' };\n static constexpr char rotateLEFT{ 'q' };\n static constexpr char rotateRIGHT{ 'e' }; \n} \n</code></pre>\n\n<p>You can then use it the same way as you're doing now. <code>Action::moveLeft</code> et cetera.</p>\n\n<p><strong>Coordinate.cpp</strong></p>\n\n<ol>\n<li>Use initializer list instead of setting the members in the body of the constructor. Only it doesn't really matter <em>in this case</em>, it's still a good idea to do so. <a href=\"https://stackoverflow.com/questions/926752/why-should-i-prefer-to-use-member-initialization-list\">See here why.</a></li>\n</ol>\n\n\n\n<pre><code>Coordinates::Coordinates(int x_, int y_): x(x_), y(y_) { /* empty */ }\n</code></pre>\n\n<ol start=\"2\">\n<li>Make your getters <code>const</code>. In fact, you should mark all methods that are not modifying your data members <code>const</code>.</li>\n</ol>\n\n\n\n<pre><code>int Coordinates::getX() const\n{\n return x;\n}\n\nint Coordinates::getY() const\n{\n return y;\n}\n</code></pre>\n\n<ol start=\"3\">\n<li>You don't need to do <code>const int&amp; x</code> in the <code>setX()</code> function. The cost of copying an <code>int</code> is negligible. <code>void setX(int x)</code> is fine. We pass by reference when we want to change the value of the argument <code>void changeValueOfX(int&amp; x)</code> or when a structure is large enough the copying it incurs a non-negligible penalty <code>void doStuffWith2DVector(const std::vector&lt;std::vector&lt;int&gt;&gt;&amp; vec)</code>.</li>\n</ol>\n\n<p><strong>Coordinate.h</strong></p>\n\n<ol>\n<li>Since all your constructor is doing is setting the value, you could just put the initializer list in this header instead of putting it in the cpp file. </li>\n</ol>\n\n\n\n<p><code>Coordinates(int x_ = 0, int y_ = 0): x(x_), y(y_) {}</code></p>\n\n<ol start=\"2\">\n<li><p><code>using namespace std;</code> is frowned upon, and using it inside a header is a big no-no. Remember that all the code in the header file is literally copy-pasted whenever you do <code>#include \"Coordinates.h</code>. That means every file where you include this file will contain the line <code>using namespace std;</code> and can lead to some nasty bugs if you're not careful.</p></li>\n<li><p>Don't include headers when you don't need them. The header is not using <code>iostream</code>. Instead, include the file when in the <code>Coordinates.cpp</code> file, when you actually do need to use it. </p></li>\n</ol>\n\n<p><strong>Difficulty.cpp</strong></p>\n\n<ol>\n<li>Again, no need to do <code>int&amp; counterNumberOfTilesPlayed</code>. Just do <code>int counterNumberOfTilesPlayed</code>. Also, your argument list is inconsistent. In the earlier file you did <code>const int&amp; x</code> and now you're doing <code>int&amp; counterNumberOfTilesPlayed</code>, when you're not changing the value of the argument in either of those.</li>\n</ol>\n\n<p><strong>Difficulty.h</strong></p>\n\n<ol>\n<li><p>Spelling error in the include guard.</p></li>\n<li><p>Again, all your class is containing is public static members and member functions. Wrap them inside a namespace rather than a class. C++ contains OOP features, but we don't have to use it all the time.</p></li>\n</ol>\n\n<p><strong>Drawable.cpp</strong></p>\n\n<ol>\n<li><p>Mark methods as <code>const</code>. </p></li>\n<li><p>Don't need to <code>const int&amp; x</code>, et cetera.</p></li>\n</ol>\n\n<p><strong>Drawable.h</strong></p>\n\n<ol>\n<li>You don't need <code>windows.h</code> in this file. Move it over to the implementation. </li>\n</ol>\n\n<p><strong>Source.cpp</strong></p>\n\n<ol>\n<li>I haven't actually looked at the implementation of your code, but there is surely a better way to realize when a player loses than a try catch block. Rethink your logic. A try catch block to decide whether a player loses seems, to be honest, ugly.</li>\n</ol>\n\n<p><strong>Table.cpp</strong></p>\n\n<ol>\n<li>Use member initializer list in the constructor to sets values of your data members. </li>\n</ol>\n\n\n\n<pre><code>Table::Table(): score(0)\n{\n ...\n\n}\n</code></pre>\n\n<p><strong>Table.h</strong></p>\n\n<ol>\n<li>Move the non-required headers into the implementation.</li>\n</ol>\n\n<p><strong>General</strong></p>\n\n<ol>\n<li><p>A lot of your classes contain only or mostly static data. You should reevaluate whether a class is the best choice.</p></li>\n<li><p>Your naming of methods and members is too verbose. While variables should always be named to describe their purpose, too long a variable name can be cumbersome, for the person writing the code and the person who will read it. </p></li>\n</ol>\n\n<p>A few examples:</p>\n\n<ul>\n<li><p><code>moveCoordinatesInADirection(char direction)</code> can be renamed <code>moveCoordinates(char direction)</code>. In both cases, the name describes what the method is doing, but the latter is shorter and more concise.</p></li>\n<li><p><code>counterNumberOfTilesPlayed</code> can be renamed <code>numberOfTilesPlayed</code> or <code>numTilesPlayed</code> or even <code>tilesPlayed</code>. </p></li>\n<li><p><code>informationAboutGame</code> can be renamed <code>gameInfo</code>.</p></li>\n<li><p><code>checkingAndDeletingCompletedLines</code> can be renamed <code>deleteCompletedLines</code></p></li>\n<li><p><code>moveTileDownAutomatically</code> can be renamed <code>moveTileDown</code>. </p></li>\n</ul>\n\n\n\n<p>Any many more..</p>\n\n<ol start=\"3\">\n<li>Comments: I firmly believe code should be self-documenting unless a method or variable or statement requires explicit instructions or programmer's intention. </li>\n</ol>\n\n\n\n<pre><code>void moveTileInADirection(char direction); // Moves the tile in a specific direction (right, left, down)\n</code></pre>\n\n<p>adds nothing to the source code. One could figure it out from the method prototype.</p>\n\n<ol start=\"4\">\n<li>Consider using <code>std::vector</code> or <code>std::array</code> instead of C-style arrays.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-14T21:12:56.323", "Id": "434770", "Score": "0", "body": "Thanks you for your answer @Rish, really helpful, I posted a response in the question. I think to do all the suggestions you posted." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-13T21:59:08.703", "Id": "224122", "ParentId": "223832", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-09T21:05:37.703", "Id": "223832", "Score": "2", "Tags": [ "c++", "object-oriented", "windows", "tetris" ], "Title": "Tetris game for Windows improved version" }
223832