body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I've been taking the Computer Science course on Codecademy. The course includes this project where we have to create a python script to find the cheapest shipping method based on the weight of an item and I'm just wondering if this is the best way to code the solution?</p> <pre><code>def ground_shipping_cost(weight): flat_cost = 20 premium_cost = 125 if weight &lt;= 2: flat_cost += weight * 1.50 elif weight &gt; 2 and weight &lt;= 6: flat_cost += weight * 3.00 elif weight &gt; 6 and weight &lt;= 10: flat_cost += weight * 4.00 elif weight &gt; 10: flat_cost += weight * 4.75 return flat_cost, premium_cost def drone_shipping_cost(weight): cost = 0 if weight &lt;= 2: cost = weight * 4.50 elif weight &gt; 2 and weight &lt;= 6: cost = weight * 9.00 elif weight &gt; 6 and weight &lt;= 10: cost = weight * 12.00 elif weight &gt; 10: cost = weight * 14.25 return cost def cheapest_shipping(weight): ground_cost, premium_cost = ground_shipping_cost(weight) drone_cost = drone_shipping_cost(weight) if drone_cost &lt; ground_cost and drone_cost &lt; premium_cost: return "You should use drone shipping as it will only cost " + str(drone_cost) if ground_cost &lt; drone_cost and ground_cost &lt; premium_cost: return "You should use standard ground shipping as it will only cost " + str(ground_cost) if premium_cost &lt; ground_cost and premium_cost &lt; drone_cost: return "You should use premium shipping as it will only cost " + str(premium_cost) print(cheapest_shipping(4.8)) # You should use standard ground shipping as it will only cost 34.4 print(cheapest_shipping(41.5)) # You should use premium shipping as it will only cost 125 print(cheapest_shipping(1.5)) # You should use drone shipping as it will only cost 6.75 print(cheapest_shipping(4.0)) # You should use standard ground shipping as it will only cost 32.0 </code></pre> <p>The issue I see is maybe there's too many <code>if</code>, <code>elif</code> statements and maybe there is a way to simplify the code</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T09:40:42.253", "Id": "424072", "Score": "4", "body": "Welcome to Code Review! Here, it is more about *best __way__ to code a solution* rather than *best solution* re. usability or resource usage - you may want to narrow down *best*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T09:47:17.317", "Id": "424074", "Score": "1", "body": "Ah! Okay thanks for that - will update the question" } ]
[ { "body": "<h1><code>premium_cost</code></h1>\n\n<p>There is no reason to include the return of this <code>premium_cost</code> in <code>ground_shipping_cost</code>. Use a different method here</p>\n\n<h1>DRY</h1>\n\n<p>You are correct. There are too many <code>if</code> statements. If you want to introduce an new threshold for the cost, this will include a adding an extra clause, and changing the limits for the preceding and following thresholds. This is just waiting for errors to pop up. Better would be to keep a dict of the thresholds, and iterate over them to get this price factor:</p>\n\n<pre><code>def ground_shipping_cost(weight):\n thresholds = {2: 1.5, 6: 3.0, 10: 4.0, float(\"inf\"): 4.75}\n flat_cost = 20\n for threshold, factor in sorted(thresholds.items()):\n if weight &lt;= threshold:\n break\n return flat_cost + weight * factor\n</code></pre>\n\n<p><code>thresholds</code> is a <code>dict</code>, with the cost per weight unit as value, and the threshold as key.</p>\n\n<p>The <code>drone_shipping_cost</code> can be tackled comparably.</p>\n\n<p>Now you have 2 methods that, starting from a list of thresholds, tries to determine the cost factor. We can easily refactor this out:</p>\n\n<pre><code>def get_factor(thresholds, value):\n for threshold, factor in sorted(thresholds.items()):\n if value &lt;= threshold:\n return factor\n\ndef ground_shipping_cost(weight):\n thresholds = {2: 1.5, 6: 3.0, 10: 4.0, float(\"inf\"): 4.75}\n flat_cost = 20\n return flat_cost + get_factor(thresholds, weight)\n\n\ndef drone_shipping_cost(weight):\n thresholds = {2: 4.5, 6: 9.0, 10: 12.0, float(\"inf\"): 14.75}\n return weight * get_factor(thresholds, weight)\n</code></pre>\n\n<h1>Cheapest costs</h1>\n\n<p>Your <code>cheapest_shipping</code> method calculates the costs for the different shipping methods, finds the cheapest one and formats this into a string. This string formatting is also very repetitive, and should be done somewhere else. <code>cheapest_shipping</code> will be the most clear if it only returned which method is the cheapest, and the corresponding cost. This also allow you to test this method with unit tests further on.</p>\n\n<p>Since methods are real objects in Python, and you can pass references to them on and store these in dicts, calculating the costs for the different methods can be simplified a lot:</p>\n\n<pre><code>def cheapest_shipping(weight):\n methods = {\n \"drone\": drone_shipping_cost,\n \"standard ground\": ground_shipping_cost,\n \"premium ground\": lambda weight: 125,\n }\n results = {method: calculation(weight) for method, calculation in methods.items()}\n</code></pre>\n\n<p>To look for the cheapest option among those, you can use the built-in <code>min</code>:</p>\n\n<pre><code>cheapest_method = min(results, key=lambda method: results[method])\n\nreturn cheapest_method, results[cheapest_method]\n</code></pre>\n\n<p>Note: the <code>lambda weight: 125</code> is the equivalent of </p>\n\n<pre><code>def premium_shipping(weight):\n return 125\n</code></pre>\n\n<p>and <code>\"premium ground\": premium_shipping,</code> in the <code>methods</code> dict</p>\n\n<p>And this can be called and formatted using <code>str.format</code> or <code>f-strings</code> in Python 3.6+</p>\n\n<pre><code>method, cost = cheapest_shipping(4)\nf\"You should use {method} shipping as it will only cost {cost}\"\n</code></pre>\n\n<blockquote>\n<pre><code>'You should use standard ground shipping as it will only cost 23.0'\n</code></pre>\n</blockquote>\n\n<h1>Further refactoring</h1>\n\n<p>You can even refactor this one step further, and have 1 generalized cost calculation method that take a <code>flat_cost</code> and <code>thresholds</code> as arguments</p>\n\n<pre><code>def get_shipping_cost(weight, thresholds=None, flat_cost=0):\n if thresholds is None:\n return flat_cost\n return flat_cost + weight * get_factor(thresholds, weight)\n</code></pre>\n\n<p>then you can define the different shipping methods like this:</p>\n\n<pre><code>shipping_methods = {\n \"drone\": {\"thresholds\": {2: 4.5, 6: 9.0, 10: 12.0, float(\"inf\"): 14.75}},\n \"standard ground\": {\n \"flat_cost\": 20,\n \"thresholds\": {2: 1.5, 6: 3.0, 10: 4.0, float(\"inf\"): 4.75},\n },\n \"premium ground\": {\"flat_cost\": 125},\n}\n\ndef cheapest_shipping2(methods, weight):\n results = {\n method: get_shipping_cost(weight, **parameters)\n for method, parameters in methods.items()\n }\n cheapest_method = min(results, key=lambda method: results[method])\n return cheapest_method, results[cheapest_method]\n\nmethod, cost = cheapest_shipping2(shipping_methods, 4)\n</code></pre>\n\n<h1>different <code>min</code></h1>\n\n<p>Instead of using <code>min</code> with the cost as key, you can reverse the <code>results</code> dictionary:</p>\n\n<pre><code>def cheapest_shipping2(methods, weight):\n results = {\n get_shipping_cost(weight, **parameters): method\n for method, parameters in methods.items()\n }\n\n cost, method = min(results.items())\n return method, cost\n</code></pre>\n\n<p>In case of an ex aequo, this can have different results than the other method</p>\n\n<h1>even further refactoring.</h1>\n\n<p>Now all shipping methods are calculated with <code>get_shipping_cost</code>. If you want to use different functions for the different shipping methods, you can do something like this:</p>\n\n<pre><code>def cheapest_shipping3(methods, weight, default_cost_method=get_shipping_cost):\n results = {\n parameters.pop(\"method\", default_cost_method)(\n weight, **parameters\n ): method\n for method, parameters in methods.items()\n }\n cost, method = min(results.items())\n return method, cost\n\nshipping_methods2 = {\n \"drone\": {\"thresholds\": {2: 4.5, 6: 9.0, 10: 12.0, float(\"inf\"): 14.75}},\n \"standard ground\": {\n \"flat_cost\": 20,\n \"thresholds\": {2: 1.5, 6: 3.0, 10: 4.0, float(\"inf\"): 4.75},\n },\n \"premium ground\": {\"method\": lambda weight: 125},\n}\n\nmethod, cost = cheapest_shipping3(shipping_methods2, 4)\n</code></pre>\n\n<p>please note that the <code>parameters.pop</code> mutates the original <code>shipping_methods2</code> after the execution:</p>\n\n<pre><code>{\n \"drone\": {\"thresholds\": {2: 4.5, 6: 9.0, 10: 12.0, inf: 14.75}},\n \"standard ground\": {\n \"flat_cost\": 20,\n \"thresholds\": {2: 1.5, 6: 3.0, 10: 4.0, inf: 4.75},\n },\n \"premium ground\": {},\n}\n</code></pre>\n\n<p>To prevent this, we need to make a copy of the <code>methods</code>:</p>\n\n<pre><code>def cheapest_shipping3(methods, weight, default_cost_method=get_shipping_cost):\n methods_copy = {\n method: parameters.copy()\n for method, parameters\n in methods.items()\n }\n results = {\n parameters.pop(\"method\", default_cost_method)(\n weight, **parameters\n ): method\n for method, parameters in methods_copy.items()\n }\n cost, method = min(results.items())\n return method, cost\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T10:56:42.150", "Id": "424092", "Score": "0", "body": "Thanks for taking your time to give me this very in-depth response I really appreciate it. Although I don't understand everything going on here (as I'm still new to Python) I can certainly say I've learnt a thing or two from it!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T14:20:45.740", "Id": "424115", "Score": "0", "body": "\"`thresholds` is a sorted list with the factor for the weights.\" No it's not. It is a *dictionary* with the thresholds and factors which is sorted *in Python 3.7+* and in arbitrary order before that. `sorted(thresholds.items())` however is a sorted iterable in all Python versions, but it also contains both the threshold and the factor." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T14:31:50.990", "Id": "424117", "Score": "0", "body": "You are correct. First I used a sorted list, then figured a dict would be a better days structure and forgot to change the text. I will correct this when I have the time" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T22:06:20.303", "Id": "424146", "Score": "2", "body": "[I would **not** use a `dict` to represent a range relationship.](https://stackoverflow.com/a/45075450/1394393) This is very unintuitive." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T08:05:11.170", "Id": "424189", "Score": "0", "body": "While this reduces LOC it's not very readable to anyone who isn't all-in on Python in my opinion; like jpmc26 noted, just because you can doesn't mean you should." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T08:19:53.153", "Id": "424193", "Score": "1", "body": "@jpmc26 How about a list of objects that have max_weight and cost properties?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T08:19:57.120", "Id": "424194", "Score": "0", "body": "@lucasgcb Personally, the further refactoring it's something I would use, especially if you want to start later with configuration files instead of hard-coded parameters.. I understand that it can be daunting for newcomers to python, so I totally understand when they don't use it, but I do want to make them aware that this is one of the possibilities. The `if-elif` chain has it advantages in readability, the refactored, generalized method has it's advantages in adaptability and re-usability. The programmer has to choose in his case which is the more appropriate approach." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T08:39:45.943", "Id": "424198", "Score": "1", "body": "I disagree about the \"further refactoring\" sections. IMHO they are violating some principles of the \"Zen of Python\", especially \"simple is better than complex\" and \"readability counts\"." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T10:48:58.643", "Id": "219576", "ParentId": "219572", "Score": "8" } }, { "body": "<p>Welcome to CodeReview! Having others review your code is one of the very best ways to find bugs and improve your coding. And we're going to improve your coding, no matter how much it hurts! :-)</p>\n\n<p>I'm going to repeat many of the points made in Maarten's review, although with slightly different results.</p>\n\n<p>From your post, I know you're still learning. From your code, I believe you have learned: <code>if/elif/else</code> statements, Python <code>tuple</code> types, and functions. So I'm going to focus on these in any improvements.</p>\n\n<h1><code>else</code> means 'Not true'</h1>\n\n<p>The most glaring problem, and one you intuited a little yourself, is that you are doing \"else\" wrong. Consider:</p>\n\n<pre><code>if weight &lt;= 2:\n flat_cost += weight * 1.50\nelif weight &gt; 2 and weight &lt;= 6:\n flat_cost += weight * 3.00\nelif weight &gt; 6 and weight &lt;= 10:\n</code></pre>\n\n<p>In this sequence, you first check <code>if weight &lt;= 2</code>. Now pretend that <code>if</code> statement fails. What do you know? You know that if <strong>any one of the <code>else</code></strong> statements executes, then <code>weight</code> <em>must</em> be <code>&gt; 2</code> because otherwise the <code>if</code> statement would have executed!</p>\n\n<p>So never \"test\" something you know to be true. Or false. If you know a thing, you don't need to test it. (You might <code>assert</code> it for sanity checking, but that's different.)</p>\n\n<p><strong>Note:</strong> With compound statements, like <code>if A and B</code> you might have to (re) test one of the statements when the compound fails:</p>\n\n<pre><code>if A and B:\nelif A:\n</code></pre>\n\n<p>But that's technically different because they are different conditions.</p>\n\n<p>So let's rewrite your conditions:</p>\n\n<pre><code>def drone_shipping_cost(weight):\n cost = 0\n if weight &lt;= 2:\n cost = weight * 4.50\n elif weight &gt; 2 and weight &lt;= 6:\n cost = weight * 9.00\n elif weight &gt; 6 and weight &lt;= 10:\n cost = weight * 12.00\n elif weight &gt; 10:\n cost = weight * 14.25\n return cost\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>def drone_shipping_cost(weight):\n cost = 0\n if weight &lt;= 2:\n cost = weight * 4.50\n elif weight &lt;= 6:\n cost = weight * 9.00\n elif weight &lt;= 10:\n cost = weight * 12.00\n else:\n cost = weight * 14.25\n return cost\n</code></pre>\n\n<p>Note two things: first, the <code>weight &gt; 10</code> case becomes a blanket <code>else</code> statement, since you are covering all the possible numbers; and second, there's no reason to set <code>cost = 0</code> initially, since you cover all possible numbers:</p>\n\n<pre><code>def drone_shipping_cost(weight):\n if weight &lt;= 2:\n cost = weight * 4.50\n elif weight &lt;= 6:\n cost = weight * 9.00\n elif weight &lt;= 10:\n cost = weight * 12.00\n else:\n cost = weight * 14.25\n return cost\n</code></pre>\n\n<h1>Keep separate things separate</h1>\n\n<p>You could rewrite your <code>ground_shipping_cost</code> function in a similar way, but let's take a harder look at that:</p>\n\n<pre><code>def ground_shipping_cost(weight):\n flat_cost = 20\n premium_cost = 125\n if weight &lt;= 2:\n flat_cost += weight * 1.50\n elif weight &gt; 2 and weight &lt;= 6:\n flat_cost += weight * 3.00\n elif weight &gt; 6 and weight &lt;= 10:\n flat_cost += weight * 4.00\n elif weight &gt; 10:\n flat_cost += weight * 4.75\n return flat_cost, premium_cost\n</code></pre>\n\n<p>You're doing a couple of things wrong here. First, you're \"accumulating\" when you should be \"adding\". And second, you're returning a tuple just to get the premium cost. In reality, the premium shipping cost is another form of shipping.</p>\n\n<p>Let's get the low-hanging-fruit out of the way:</p>\n\n<pre><code>def premium_shipping_cost(weight):\n ''' Compute cost of premium shipping for a package. '''\n return 125\n</code></pre>\n\n<p>That was easy, wasn't it!</p>\n\n<p>Now, let's remove the <code>premium_cost</code> from the ground shipping, and fix the if/else statements:</p>\n\n<pre><code>def ground_shipping_cost(weight):\n flat_cost = 20\n if weight &lt;= 2:\n flat_cost += weight * 1.50\n elif weight &lt;= 6:\n flat_cost += weight * 3.00\n elif weight &lt;= 10:\n flat_cost += weight * 4.00\n else:\n flat_cost += weight * 4.75\n return flat_cost\n</code></pre>\n\n<p>This looks better, but you're still \"accumulating\" instead of \"adding.\" In this case, that's the wrong thing to do because you're only going to add one thing. Phrasing the computations as accumulating costs gives the wrong impression to the reader. Let's make it clear that there's a flat charge and a by-weight charge:</p>\n\n<pre><code>def ground_shipping_cost(weight):\n ''' Compute cost of ground shipping for a package. '''\n flat_cost = 20\n if weight &lt;= 2:\n weight_charge = weight * 1.50\n elif weight &lt;= 6:\n weight_charge = weight * 3.00\n elif weight &lt;= 10:\n weight_charge = weight * 4.00\n else:\n weight_charge = weight * 4.75\n return flat_cost + weight_charge\n</code></pre>\n\n<p>This version makes it clear that there's a flat cost and a weight charge. Future-Stephen will thank you.</p>\n\n<h1>You make the call!</h1>\n\n<p>Now here's where I'll diverge from Maarten Fabre's review. The DRY principle tells us that those two chains of <code>if/elif/else</code> statements should be moved into a separate function.</p>\n\n<p>First I have to ask, what's the objective? If you are in part of a class where they are focused on writing functions, then that is <strong>absolutely right</strong> and you should do it.</p>\n\n<p>But if you are in a part of the class where they are starting to focus on classes and objects, and encapsulating behavior, then maybe it would be the <strong>wrong thing to do.</strong> Why? Because maybe the weights and cost multipliers were the same only by coincidence, and maybe the next thing they ask will be for you to separate them!</p>\n\n<p>So you have to use your own judgement. You could write a function that returns the cost multiplier. You could write a function that returns a cost \"category\" and use that to look up the multiplier. Or you could leave the two cost functions with duplicated code, so that you can change the cost layers or cost multipliers independently. </p>\n\n<h1>One built-in function</h1>\n\n<p>Python has a built-in function called <a href=\"https://docs.python.org/3.5/library/functions.html#min\" rel=\"noreferrer\"><code>min</code></a>. By default, <code>min</code> compares objects in a sequence, or objects passed as positional parameters. It compares them using the default Python comparison, and for tuples that comparison compares the elements of the tuple in ascending order. This is discussed nicely in this <a href=\"https://stackoverflow.com/questions/5292303/how-does-tuple-comparison-work-in-python#5292332\">SO answer.</a></p>\n\n<p>What this means for you is that you can use <code>min</code> on a sequence of <code>tuple</code> values, in different ways:</p>\n\n<ul>\n<li>You could compute name, cost tuples for the shipping types, and find the lowest cost.</li>\n<li>You could store name, cost-function tuples and compute the lowest cost using a special <code>key</code> function.</li>\n</ul>\n\n<p>Let's try the most direct approach, since it's easier to understand. And let's put the cost before the name, so that we get the right results (comparison is in tuple order!):</p>\n\n<pre><code>def cheapest_shipping(weight):\n ''' Determine the cheapest shipping method for a package. '''\n drone_cost = drone_shipping_cost(weight)\n ground_cost = ground_shipping_cost(weight)\n premium_cost = premium_shipping_cost(weight)\n\n cheapest_tuple = min((drone_cost, 'drone shipping'),\n (ground_cost, 'ground shipping'),\n (premium_cost, 'premium shipping'))\n return cheapest_tuple\n</code></pre>\n\n<p>At this point, you can do what is called \"tuple unpacking\" (remember the word \"unpacking\" -- you'll want to search for it later). That lets you return multiple values into multiple separate variables:</p>\n\n<pre><code>cost, name = cheapest_shipping(weight)\nprint(f\"You should use {name}, it costs only {cost}!\")\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T18:10:44.237", "Id": "424127", "Score": "0", "body": "Thanks for the detailed answer Austin! This has helped me understand a lot more about what was incorrect with my code like the \"accumulating\" cost.\n\nAgain thank you for taking your time to write such a detailed response I appreciate it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T22:10:27.550", "Id": "424147", "Score": "3", "body": "Another improvement to `ground_shipping_cost` would be to just set `weight_rate` (or a similarly named variable) inside the `if` blocks and then `return flat_cost + weight_rate * weight`. You *could* also bypass the extra variables in the final `cheapest_shipping` method, but I understand why you might want them, especially for a beginning. +1 for solid advice that doesn't make things more convoluted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T08:41:17.670", "Id": "424199", "Score": "0", "body": "This is the better answer compared to the accepted one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T09:39:59.140", "Id": "424208", "Score": "0", "body": "@stefan Yeah I have accepted this one as the answer as it explains the refactor as more beginner friendly than the answer I accepted originally" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T15:56:56.520", "Id": "219592", "ParentId": "219572", "Score": "8" } } ]
{ "AcceptedAnswerId": "219592", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T09:17:17.747", "Id": "219572", "Score": "11", "Tags": [ "python", "python-3.x" ], "Title": "Find the cheapest shipping option based on item weight" }
219572
<p>This is my code to generate all possible <a href="https://everything2.net/index.pl?node_id=1407017&amp;displaytype=printable&amp;lastnode_id=1407017" rel="nofollow noreferrer">Armstrong numbers</a> between the two given numbers. The logic uses string instead of integer to separate the digits to optimize the code.</p> <pre><code>import java.util.Scanner; public class ArmstrongNumberGenerator { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int firstNumber; int lastNumber; int sum = 0; try { System.out.println("\nYou will have to enter initial and final number between which all the armstrong numbers you want to generate\n"); System.out.println("\nEnter the initial number\n"); firstNumber = scanner.nextInt(); System.out.println("\nEnter the final number\n"); lastNumber = scanner.nextInt(); if (firstNumber == lastNumber) { System.out.println("both initian and final numbers are same , no range to generate armstrong numbers"); } else { if (firstNumber &gt; lastNumber) { System.out.println("initial number is greater than final number so i will alter them and make a range from " + lastNumber + " to " + firstNumber); int temp = firstNumber; firstNumber = lastNumber; lastNumber = temp; } do { String s = Integer.toString(firstNumber); char[] c = s.toCharArray(); for (int i = 0; i &lt; s.length(); i++) { sum = ( int ) (sum + Math.pow((c[i] - 48), c.length)); } if (sum == firstNumber) { System.out.println("Number " + firstNumber + " is Armstrong"); } ++firstNumber; sum = 0; } while (firstNumber &lt; lastNumber); } } catch (Exception e) { System.out.println("invalid data"); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T09:54:44.197", "Id": "424077", "Score": "1", "body": "What is an Armstrong number?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T10:02:58.697", "Id": "424080", "Score": "0", "body": "@PeterTaylor: Probably this: https://en.wikipedia.org/wiki/Narcissistic_number ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T10:03:21.613", "Id": "424081", "Score": "0", "body": "https://everything2.net/index.pl?node_id=1407017&displaytype=printable&lastnode_id=1407017" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T06:06:51.393", "Id": "424177", "Score": "1", "body": "Welcome to Code Review! I rolled back your last edit. After getting an answer you are [not allowed to change your code anymore](https://codereview.stackexchange.com/help/someone-answers). This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). Refer to [this post](https://codereview.meta.stackexchange.com/a/1765/120114) for more information" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T06:16:06.013", "Id": "424179", "Score": "0", "body": "@Sᴀᴍ Onᴇᴌᴀ I am new to code review, what should I do now?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T06:18:54.173", "Id": "424180", "Score": "1", "body": "Please read [the meta post that I included a link to](https://codereview.meta.stackexchange.com/a/1765/120114) at the end of [my previous comment](https://codereview.stackexchange.com/questions/219573/armstrong-number-generator?noredirect=1#comment424177_219573)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T06:21:44.430", "Id": "424181", "Score": "0", "body": "Ya but how can I bring my previous code as I don't have that code anymore. And the post gave quite good explanation about the problem of changing code. I would keep this in mind from now on. @Sᴀᴍ Onᴇᴌᴀ" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T06:25:02.737", "Id": "424182", "Score": "0", "body": "you can see it in the [revision history](https://codereview.stackexchange.com/posts/219573/revisions), which you can access via the link above the username of the user who last edited the post" } ]
[ { "body": "<p>The first number is included in the range but the last number is not. That inconsistency is odd. You should document the limitations you set to the input. If your limitations make documentation hard, it's a sign of bad programming.</p>\n\n<p>Knowing what I wrote above, right now you to check for both equality and greater than between firstNumber and lastNumber. Just check <code>if (firstNumber &gt; lasNumber)</code> instead and tell the user that \"firstNumber must be smaller than lastNumber.\"</p>\n\n<p>FirstNumber and lastNumber are not descriptive variable names. <code>LowerLimit</code> and <code>upperLimit</code> would be better.</p>\n\n<p>You're not prepared for negative input.</p>\n\n<p>Using firstNumber as both the lower limit and loop counter makes the variable name to be incorrect in both uses. It's really never the lowerLimit nor the number being checked. Add a separate variable and use a loop <code>for (int candidate = lowerLimit; candidate &lt;= upperLimit; candidate++) { ...</code></p>\n\n<p>You should separate the algorithm from main method that reads the input to a static utility method that operates on integers. Reading code that is nested four deep is difficult.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T09:55:11.413", "Id": "424078", "Score": "2", "body": "You don't seem to understand the purpose of Code Review. We're working together to improve the skills of programmers worldwide by taking working code and making it better. Please see https://codereview.stackexchange.com/tour" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T10:35:29.230", "Id": "424089", "Score": "0", "body": "I agree with most of what is written in your answer but I can't vote it up because of the tone. Is it possible for your reviews to address only the code and not the author of the code by the heavy use of \"you\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T10:41:52.773", "Id": "424090", "Score": "1", "body": "@pacmaninbw It's likely the product of my natural language, which is not english. I'll try to look into it in the future." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T09:49:11.637", "Id": "219575", "ParentId": "219573", "Score": "3" } }, { "body": "<p>Hello and thanks for sharing your code with us.</p>\n\n<h1>Readability/Maintainability</h1>\n\n<ol>\n<li>Variables should only be declared when they are actually used (Unless you are having to work with different scopes). It can become difficult to keep track of what is what when everything is just declared at the top of our scope. </li>\n<li>We should try to stay away from deeply nested structures. Very rarely will you be forced to go even two scopes deep.</li>\n<li>When catching exceptions, it is generally best to catch specific exceptions. Although, in this scenario we can afford to be a bit more liberal.<a href=\"https://stackoverflow.com/questions/21938/is-it-really-that-bad-to-catch-a-general-exception\">Here you can find more details on exception handling</a></li>\n</ol>\n\n<p>Lets look at some refactored code to see what these changes might look like. Also, take note of various comments left throughout the code base.</p>\n\n<pre><code>public static void main(String[] args) {\n System.out.println(\"\\nYou will have to enter initial and final number between which all the armstrong numbers you want to generate\\n\");\n int start;\n int end;\n try {\n start = promptForNextNumber(\"\\nEnter the initial number\\n\");\n end = promptForNextNumber(\"\\nEnter the final number\\n\");\n } catch (InputMismatchException ex) {\n System.out.println(\"Input was not a valid integer.\");\n return;\n }\n\n if (start == end) {\n System.out.println(\"both initial and final numbers are same, no range to generate armstrong numbers\");\n return;\n }\n\n if (start &gt; end) {\n final String message = String.format(\n \"initial number is greater than final number so i will alter them and make a range from %s to %s\", end, start);\n System.out.println(message);\n // This is a strange and not recommended way of handling this situation.\n // But if this functionality is apart of the requirement, by all means.\n int temp = start;\n start = end;\n end = temp;\n }\n\n ...\n}\n</code></pre>\n\n<p>Take notice of the <code>promptForNextNumber(message)</code> method being called. In command line applications it is very common to prompt a user than collect input. We can capitalize on this pattern so that we do not repeat our selves. The method looks like this:</p>\n\n<pre><code>private static int promptForNextNumber(final String message) {\n System.out.println(message);\n return scanner.nextInt();\n}\n</code></pre>\n\n<ol start=\"4\">\n<li>Lets try to keep our functionality separate in their own methods, this way things can be easily reused if needed and gets rid of the giant mother block of code. Code is easier to understand when it is broken up into tinier chunks. We'll see examples of this in just a bit. </li>\n</ol>\n\n<h1>Alternate Solution</h1>\n\n<p>As @TorbenPutkonen has already pointed out, your algorithm for determining if a number is armstrong or not is a bit harder to follow than it should be. Although imperative programming gets the job done it can be on the more verbose side, even when done correctly. I would like to propose a functional solution:</p>\n\n<pre><code>private static boolean isArmstrong(final String number) {\n final int length = number.length();\n final int sum = number.chars()\n .map(Character::getNumericValue)\n .map(digit -&gt; (int) Math.pow(digit, length))\n .sum();\n\n return sum == Integer.parseInt(number);\n}\n</code></pre>\n\n<p>and an overload for easy type converting</p>\n\n<pre><code>// Method overload for easy conversion from int to string.\nprivate static boolean isArmstrong(final int number) {\n return isArmstrong(String.valueOf(number));\n}\n</code></pre>\n\n<p>We now have methods for determining if a given number is an Armstrong number. Lets use them by first generating a range of numbers and then filtering that range with our new methods. After the filtering process, simply print the results.</p>\n\n<pre><code>public static void main(String[] args) {\n ...\n\n\n IntStream.range(start, end)\n .filter(ArmstrongMainRevisioned::isArmstrong)\n .forEach(number -&gt; System.out.println(\"Number \" + number + \" is Armstrong\"));\n}\n</code></pre>\n\n<h1>Bringing It All Together</h1>\n\n<p>This is just one of many possible ways this application could be written using these various mentioned techniques.</p>\n\n<pre><code>import java.util.InputMismatchException;\nimport java.util.Scanner;\nimport java.util.stream.IntStream;\n\npublic class ArmstrongNumberGenerator {\n private static final Scanner scanner = new Scanner(System.in);\n\n public static void main(String[] args) {\n System.out.println(\"\\nYou will have to enter initial and final number between which all the armstrong numbers you want to generate\\n\");\n int start;\n int end;\n try {\n start = promptForNextNumber(\"\\nEnter the initial number\\n\");\n end = promptForNextNumber(\"\\nEnter the final number\\n\");\n } catch (InputMismatchException ex) {\n // Lets display a slightly more descriptive message describing why the given data was invalid.\n System.out.println(\"Input was not a valid integer.\");\n return;\n }\n\n if (start == end) {\n System.out.println(\"both initial and final numbers are same, no range to generate armstrong numbers\");\n return;\n }\n\n if (start &gt; end) {\n // String.format can be used to improve string readability when concatenating a lot of different strings.\n final String message = String.format(\n \"initial number is greater than final number so i will alter them and make a range from %s to %s\", end, start);\n System.out.println(message);\n // This is a strange and not recommended way of handling this situation.\n // But if this functionality is apart of the requirement, by all means.\n int temp = start;\n start = end;\n end = temp;\n }\n\n IntStream.range(start, end)\n .filter(ArmstrongMainRevisioned::isArmstrong)\n .forEach(number -&gt; System.out.println(\"Number \" + number + \" is Armstrong\"));\n }\n\n private static boolean isArmstrong(final String number) {\n final int length = number.length();\n final int sum = number.chars()\n .map(Character::getNumericValue)\n .map(digit -&gt; (int) Math.pow(digit, length))\n .sum();\n\n return sum == Integer.parseInt(number);\n }\n\n // Method overload for easy conversion from int to string.\n private static boolean isArmstrong(final int number) {\n return isArmstrong(String.valueOf(number));\n }\n\n // Helper method to display prompt while acquiring user input\n private static int promptForNextNumber(final String message) {\n System.out.println(message);\n return scanner.nextInt();\n }\n}\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T03:33:08.927", "Id": "424170", "Score": "0", "body": "thanks for your review . I will try to code better ." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T03:25:25.587", "Id": "219617", "ParentId": "219573", "Score": "2" } }, { "body": "<p>Thanks for your reviews everyone. I updated my code using the answers and updates in my new code are as below. </p>\n\n<p>I now use my void main () only to create an object that can run this code , like this. </p>\n\n<pre><code>public static void main(String[] args) {\n new ArmstrongNumberGenerator().mainMethod();\n }\n</code></pre>\n\n<p>I distributed the tasks of getting input and doing calculations by different methods and also included the lastnumber in the range. </p>\n\n<pre><code>private void mainMethod() {\n try {\n System.out.println(\"\\nYou will haveto enter initial and final number between which all the armstrong numbers you want to generate\\n\");\n System.out.println(\"\\nEnter the initial number\\n\");\n firstNumber = scanner.nextInt();\n System.out.println(\"\\nEnter the final number\\n\");\n lastNumber = scanner.nextInt();\n armstrongGenerator(firstNumber, lastNumber);\n } catch (InputMismatchException e) {\n System.out.println(e + \"\\t: Only integers allowed as input\");\n }\n }\nprivate void armstrongGenerator(int firstNumber, int lastNumber) {\n if (firstNumber == lastNumber) {\n System.out.println(\"both initian and final numbers are same , no range to generate armstrong numbers\");\n } else {\n if (firstNumber &gt; lastNumber) {\n System.out.println(\"initial number is greater than final number so i will alter them and make a range from \" + lastNumber + \" to \" + firstNumber);\n int temp = firstNumber;\n firstNumber = lastNumber;\n lastNumber = temp;\n }\n do {\n String s = Integer.toString(firstNumber);\n char[] c = s.toCharArray();\n for (int i = 0; i &lt; s.length(); i++) {\n sum = ( int ) (sum + Math.pow((c[i] - 48), c.length));\n }\nif (sum == firstNumber) {\n System.out.println(\"Number \" + firstNumber + \" is Armstrong\");\n }\n ++firstNumber;\n sum = 0;\n } while (firstNumber &lt;= lastNumber);\n }\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T06:48:47.083", "Id": "219622", "ParentId": "219573", "Score": "0" } } ]
{ "AcceptedAnswerId": "219617", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T09:19:20.270", "Id": "219573", "Score": "2", "Tags": [ "java", "algorithm", "strings", "integer" ], "Title": "Armstrong number generator" }
219573
<p>I have a custom object that is based in the following models:</p> <pre><code>public class Filter&lt;T&gt; where T : new() { public T Object { get; set; } public int Page { get; set; } public int ItemsPerPage { get; set; } } public class TransactionFilter&lt;T&gt; : Filter&lt;T&gt; where T : new() { public DateTime InitialDate { get; set; } public DateTime EndDate { get; set; } public DateTime InitialPayment { get; set; } public DateTime EndPayment { get; set; } public List&lt;string&gt; Filters { get; set; } } public class Transaction&lt;T&gt; : Base where T : new() { public T PaymentObject { get; set; } } public class Base { public bool Sandbox { get; set; } public PaymentMethod PaymentMethod { get; set; } } public class PaymentMethod { public string Code { get; set; } } </code></pre> <p>And is built on:</p> <pre><code>var queryObj = new TransactionFilter&lt;Transaction&lt;object&gt;&gt;() { Object = new Transaction&lt;object&gt; { PaymentMethod = new PaymentMethod { Code = "1" }, Sandbox = false }, InitialDate = new DateTime(2019, 03, 01), EndDate = new DateTime(2019, 04, 01), InitialPayment = new DateTime(2019, 03, 01), EndPayment = new DateTime(2019, 04, 01), Filters = new List&lt;string&gt;() { "ID", "Customer", "Reference", "PaymentMethod", "Application", "Ammount", "Vendor", "Status", "PaymentDate", "CreatedDate" } }; </code></pre> <p>And should be transformed in a querystring like this:</p> <pre><code>?Filter=ID&amp;Filter=Customer&amp;Filter=Reference&amp;Filter=PaymentMethodCode&amp;Filter=Application&amp;Filter=Amount&amp;Filter=Vendor&amp;Filter=Status&amp;Filter=PaymentDate&amp;Filter=CreatedDate&amp;Filter=PaymentMethod&amp;Page1=PaymentMethod&amp;Page=1&amp;ItensPerPage100&amp;Object.Sandbox=False&amp;PaymentMethod.Code=1 </code></pre> <p>Yes, <code>Filter</code> property is correct, the API needs to receive it this way... and that was my big issue to find a way to properly mount as needed based on the models. </p> <p>Based on a lot of research, questions, debugging, exceptions and a lot of coffee, I finally got this as a result to build it as it should be:</p> <pre><code>private string QueryString(object request, string propertyName = null) { if (request == null) throw new ArgumentNullException(nameof(request)); var queryString = new StringBuilder(); var properties = request.GetType().GetProperties() .Where(x =&gt; x.CanRead) .Where(x =&gt; x.GetValue(request, null) != null) .Where(x =&gt; !x.PropertyType.IsClass || x.PropertyType.IsClass &amp;&amp; x.PropertyType.FullName == "System.String") .ToDictionary(x =&gt; x.Name, x =&gt; x.GetValue(request, null)); foreach (var (key, value) in properties) { if (string.IsNullOrEmpty(propertyName)) queryString.AppendFormat("{0}={1}", Uri.EscapeDataString(key), Uri.EscapeDataString(value.ToString())); else queryString.AppendFormat("{0}.{1}={2}", Uri.EscapeDataString(propertyName), Uri.EscapeDataString(key), Uri.EscapeDataString(value.ToString())); queryString.AppendFormat("&amp;"); } var classTypes = request.GetType().GetProperties() .Where(x =&gt; x.CanRead) .Where(x =&gt; x.GetValue(request, null) != null &amp;&amp; x.PropertyType.IsClass &amp;&amp; x.PropertyType.FullName != "System.String" &amp;&amp; !(x.GetValue(request, null) is IEnumerable)) .ToDictionary(x =&gt; x.Name, x =&gt; x.GetValue(request, null)); var collectionTypes = request.GetType().GetProperties() .Where(x =&gt; x.CanRead) .Where(x =&gt; x.GetValue(request, null) != null) .ToDictionary(x =&gt; x.Name, x =&gt; x.GetValue(request, null)) .Where(x =&gt; !(x.Value is string) &amp;&amp; x.Value is IEnumerable) .ToDictionary(x =&gt; x.Key, x =&gt; x.Value); foreach (var (key, value) in collectionTypes) { var valueType = value.GetType(); var valueElemType = valueType.IsGenericType ? valueType.GetGenericArguments()[0] : valueType.GetElementType(); if (valueElemType.IsPrimitive || valueElemType == typeof(string)) { if (!(value is IEnumerable enumerable)) continue; foreach (var obj in enumerable) { if (string.IsNullOrEmpty(propertyName)) queryString.AppendFormat("{0}={1}", Uri.EscapeDataString(key), Uri.EscapeDataString(obj.ToString())); else queryString.AppendFormat("{0}.{1}={2}", Uri.EscapeDataString(propertyName), Uri.EscapeDataString(key), Uri.EscapeDataString(obj.ToString())); queryString.AppendFormat("&amp;"); } } else if (valueElemType.IsClass) { var count = 0; foreach (var className in (IEnumerable) value) { var queryKey = $"{key}[{count}]"; queryString.AppendFormat(QueryString(className, queryKey)); count++; } } } foreach (var (key, value) in classTypes) queryString.AppendFormat(QueryString(value, key)); return "?" + queryString; } </code></pre> <p>It's called in a quite simple way to mount the query and combine with the URL on API request:</p> <pre><code>var query = QueryString(queryObj); var response = await client.GetAsync("https://api_address.com/Transaction/Get" + query); </code></pre> <p>It works as expected and provides the desired result, which is good enough to me, but I believe that it could be achieved on a simple/better way, so I would really appreciate to see a different view about that, if that could be considered as a good approach for this situation, both function and the call for it, to achieve the expected result.</p> <p>Thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T13:10:41.040", "Id": "424110", "Score": "0", "body": "`Filters` should be a `HashSet<string>` instead of a `List`, because it doesn't make sense that it may contain duplicates." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T15:02:26.320", "Id": "424120", "Score": "3", "body": "You should check out https://docs.microsoft.com/en-us/dotnet/api/system.runtime.serialization.objectmanager?view=netframework-4.8 as it has example to walk object tree and catch for recursion. It's not hard to change it to out put nodes with parents to build a tree view. Which then can be used to build your query string." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T19:45:31.407", "Id": "428588", "Score": "0", "body": "You mentioned this code works for your particular scenario. But do you intend to use it for other filters as well? Do you expect your filter classes to change over time?" } ]
[ { "body": "<blockquote>\n<pre><code>private string QueryString(object request, string propertyName = null)\n{\n if (request == null) throw new ArgumentNullException(nameof(request));\n</code></pre>\n</blockquote>\n\n<p>It is fine to check if a parameter is null, but because you call this method recursively, the <code>request</code> parameter may be a property that is null on an object that is otherwise valid:</p>\n\n<pre><code>class ParentObject\n{\n ChildObject Child { get; set; }\n int PrimitiveValue { get; set; }\n}\n\nclass ChildObject\n{\n string Name { get; set; }\n}\n\n\nParentObject po = new { ChildObject = null, PrimitiveValue = 10 }\n</code></pre>\n\n<p>Are you sure this situation should throw an exception, when handling ChildObject recursively?</p>\n\n<hr>\n\n<p>You are not dealing with <code>struct</code> types (value types that are not primitives). They are handled as primitive types, which goes well for <code>DateTime</code>, but what about structs with two or more useful properties?</p>\n\n<hr>\n\n<p>You should be aware of the possibility to go into an infinite recursion if a type have a property of its own kind: a <code>DateTime</code> has the property <code>Date</code> which is of type <code>DateTime</code>, so that is a candidate for an infinite recursion.</p>\n\n<hr>\n\n<p>As CharlesNRice writes in this comment, you should check that each object is only handled once.</p>\n\n<hr>\n\n<blockquote>\n <p><code>return \"?\" + queryString;</code></p>\n</blockquote>\n\n<p>Because you call the method recursively, you end up with '?' more places than just at the beginning. Is that intentionally?</p>\n\n<hr>\n\n<blockquote>\n <p><code>PaymentMethod.Code=1</code></p>\n</blockquote>\n\n<p>When running your example the above is generated. But shouldn't that be <code>Object.PaymentMethod.Code=1</code> ?</p>\n\n<hr>\n\n<p>All in all I think you do too much in the same method, and you query the request for properties unnecessarily many times. I think I would try with an approach like:</p>\n\n<pre><code> IEnumerable&lt;(string key, object value)&gt; CollectProperties(object request, string prefix = null)\n {\n List&lt;(string key, object value)&gt; properties = new List&lt;(string key, object value)&gt;();\n\n if (IsHandled(request)) return properties;\n\n prefix = prefix == null ? \"\" : $\"{prefix}.\";\n\n foreach (PropertyInfo pi in request.GetType().GetProperties().Where(p =&gt; p.CanRead))\n {\n string propertyPrefix = $\"{prefix}{pi.Name}\";\n if (IsPrimitive(pi))\n properties.Add(HandlePrimitive(..., propertyPrefix));\n else if (IsEnumerable(pi))\n properties.AddRange(HandleEnumerable(..., propertyPrefix));\n else if (IsClass(pi))\n properties.AddRange(HandleClass(..., propertyPrefix));\n else if (IsStruct(pi))\n properties.AddRange(HandleStruct(..., propertyPrefix));\n }\n\n return properties; \n }\n</code></pre>\n\n<p>Each of the Handle&lt;...>(...) methods may call the above method recursively. The caller handles the format and url encoding and finally the concatenation to one string using <code>string.Join(\"&amp;\", properties.Select(format...))</code>. In this way you only have one place where the format occur.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-03T19:12:43.390", "Id": "428577", "Score": "2", "body": "Note that .GetProperties().Where(p => p.CanRead) includes indexers. If you don't want to include them, add .Where(p => p.GetIndexParameters().Length == 0). Furthermore, I like the approach for visiting by type of object, but this is not a sinecure. There are nullables, dynamic classes, anonymous classes, tuples, generic collection types, and so on.. This approach requires alot of attention." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T08:28:36.880", "Id": "219691", "ParentId": "219579", "Score": "3" } } ]
{ "AcceptedAnswerId": "219691", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T11:44:58.880", "Id": "219579", "Score": "3", "Tags": [ "c#", ".net-core" ], "Title": "Building QueryString from custom object" }
219579
<p>I have coded an UI from dribble design as a challenge and completed it but I think The CSS I wrote is really bad. I am a beginner. How can I improve my CSS?. One of the main problems is that I am using <code>position: absolute</code> for positioning everything. I want it to be responsive.</p> <p>This is the dribble design I was trying to code <a href="https://i.stack.imgur.com/i8KWw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/i8KWw.png" alt="enter image description here"></a></p> <p>This is what I coded looks (on my machine) <a href="https://i.stack.imgur.com/FyerB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FyerB.png" alt="enter image description here"></a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>* { margin: 0; padding: 0; outline: none; } body { font-family: 'Montserrat', sans-serif; } .dash-container { position: absolute; width: 100%; height: 100%; min-width: 700px; overflow: hidden; } .left-side { position: absolute; width: 25%; height: 100%; float: left; /*background-color: rgb(236, 235, 235, 0.4); background-color: rgb(110, 145, 255 , 0.1);*/ background: white; margin-right: 10px; } .right-side { position: absolute; width: 80%; height: 100%; right: 0; background-color: rgb(164, 171, 195, 0.2); } .logo { position: absolute; /*color: #6FE3FF; */ color: #3bccf6; font-size: 2.2em; font-weight: 900; top: 20px; left: 50px; letter-spacing: 1px; } .profile-pic{ position:absolute; top: 90px; left: 40px; } .profile-pic img { border-radius: 100%; width: 50px; height: 50px; } .profile-name .profile-job-title{ position: absolute; display: block; } .profile-name{ position: absolute; top: 99px; left: 102px; font-weight: bold; font-size: 0.9em; color:gray; } .profile-job-title{ position: absolute; top: 118px; left: 102px; font-size: 0.65em; color: grey; font-weight: lighter; } .sidebar-options { position: absolute; top: 200px; left: 40px; color: gray; font-weight: lighter; } .sidebar-options ul li { font-size: 13px; line-height: 45px; list-style: none; } .sidebar-options ul li.active { color: #6FE3FF; } .sidebar-options ul li i{ position: relative; left: 85px; float: right; top: 15px; } .add-project-btn { position: absolute; top: 380px; left: 0px; width: 185px; font-size: 0.9em; text-align: center; height: 40px; color: white; /*background-color: rgb(7, 104, 104); */ border: none; border-radius: 50px; background-image: linear-gradient(to right, rgb(87, 193, 219) 0%, #2FC7F5 51%, rgb(28, 189, 230) 100%); } .header { display: block; position: absolute; float: left; background: white; top: 0px; height: 70px; width: 100%; } .fa-search{ position: absolute; font-size: 16px; top: 32px; color: lightgray; left: 30px; cursor: pointer; } input::placeholder { color: lightgray; } input{ position: absolute; background-color: white; width: 45%; height: 30px; top: 25px; left: 65px; font-size: 18px; border-radius: 50px; border: none; font-family: 'Montserrat', sans-serif; color: gray; } .header-profile-pic{ position:absolute; top: 22px; left: 550px; } .header-profile-pic img { border-radius: 100%; width: 35px; height: 35px; cursor: pointer; } .green-dot .fa-circle { position: absolute; color: #00ff00; top: 51px; left: 555px; font-size: 8px; } .header-name { position: absolute; color: rgb(3, 3, 3,0.6); top: 31px; left: 595px; font-family: 'Montserrat', sans-serif; font-size: 0.87em; font-weight: lighter; } .dropdown { position: absolute; color: rgb(3, 3, 3,0.6); top: 32px; left: 699px; font-size: 0.87em; cursor: pointer; } .message { position: absolute; color: rgb(3, 3, 3,0.6); top: 32px; left: 770px; font-size: 1em; } .red-dot-1 { position: absolute; color:#ff0000; top: 28px; left: 782px; font-size: 5px; } .notify { position: absolute; color: rgb(3, 3, 3,0.6); top: 32px; left: 840px; font-size: 1em; } .red-dot-2 { position: absolute; color: #ff0000; top: 28px; left: 850px; font-size: 5px; } .burger { position: absolute; color: rgb(3, 3, 3,0.6); top: 32px; right: 60px; font-size: 1em; } .dashboard-heading h1 { position: absolute; color: rgb(128, 128, 128, 1); top: 100px;; left: 100px; font-size: 1.2em; } .blue-rect .fa-tachometer-alt { position: absolute; color: white; background-image: linear-gradient(to right, rgb(87, 193, 219) 0%, #2FC7F5 51%, rgb(28, 189, 230) 100%); padding: 10px 10px 10px 10px; border-radius: 10px; top: 93px; left: 50px; font-size: 1em; } .card-1 .card-icon { position: absolute; font-size: 1.5em; top: 20px; left: 40px; } .card-1 .card-title { position: absolute; font-size: 0.9em; top: 60px; left: 40px; } .card-1 .card-price { position: absolute; font-size: 1.4em; top: 90px; left: 40px; } .card-1 .card-footer { position: absolute; font-size: 0.9em; top: 130px; left: 40px; } .card-1 .card-background-up { position: absolute; height: 130px; width: 130px; top: 0px; left: 220px; z-index: 10; } .card-1 .card-background-down { position: absolute; height: 135px; width: 135px; top: 80px; left: 197px; z-index: 10; } .card-2 .card-background-up { position: absolute; height: 130px; width: 130px; top: 0px; left: 220px; z-index: 10; } .card-2 .card-background-down { position: absolute; height: 135px; width: 135px; top: 80px; left: 197px; z-index: 10; } .card-3 .card-background-up { position: absolute; height: 130px; width: 130px; top: 0px; left: 220px; z-index: 10; } .card-3 .card-background-down { position: absolute; height: 135px; width: 135px; top: 80px; left: 197px; z-index: 10; } .card-2 .card-icon { position: absolute; font-size: 1.5em; top: 20px; left: 40px; } .card-2 .card-title { position: absolute; font-size: 0.9em; top: 60px; left: 40px; } .card-2 .card-price { position: absolute; font-size: 1.4em; top: 90px; left: 40px; } .card-2 .card-footer { position: absolute; font-size: 0.9em; top: 130px; left: 40px; } .card-3 .card-icon { position: absolute; font-size: 1.5em; top: 20px; left: 40px; } .card-3 .card-title { position: absolute; font-size: 0.9em; top: 60px; left: 40px; } .card-3 .card-price { position: absolute; font-size: 1.4em; top: 90px; left: 40px; } .card-3 .card-footer { position: absolute; font-size: 0.9em; top: 130px; left: 40px; } .card-1 { background: linear-gradient(#c694f9 0%, #ab64f4 100%); position: absolute; top: 150px; left: 50px; border-radius: 10px; height: 25vh; width: 23vw; color: white; } .card-2 { background: linear-gradient(#6aa5e3 0%, #6866e9 100%); position: absolute; top: 150px; left: 440px; border-radius: 10px; height: 25vh; width: 23vw; color: white; } .card-3 { background: linear-gradient(#feb683 0%, #ff8993 100%); position: absolute; top: 150px; left: 830px; border-radius: 10px; height: 25vh; width: 23vw; color: white; } .cards { display: inline-block; } .table-container { background-color: white; border-radius: 10px; position: absolute; top: 365px; left: 50px; height: 45%; width: 92%; } .table-container .table-title { color: rgb(29, 27, 27, 0.6); font-size: 1.1em; position: absolute; top: 20px; left: 42px; } .table { position: absolute; top:60px ; left: 40px; width: 90%; text-align: left; height: 77%; font-size: 0.9em; color: black; } td, th { border: none; text-align: left; padding: 5px; } tr:nth-child(even) { background-color: rgba(171, 240, 240, 0.2); } .pending { background: linear-gradient(#c694f9 0%, #ab64f4 100%); border-radius: 5px; color: white; text-align: center; } .approved { background: linear-gradient(#6aa5e3 0%, #6866e9 100%); border-radius: 5px; color: white; text-align: center; } .rejected { background: linear-gradient(#feb683 0%, #ff8993 100%); border-radius: 5px; color: white; text-align: center; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;meta http-equiv="X-UA-Compatible" content="ie=edge"&gt; &lt;link rel="stylesheet" href="style.css"&gt; &lt;link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous"&gt; &lt;link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet"&gt; &lt;title&gt;Dashboard&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;!-- container --&gt; &lt;div class="container"&gt; &lt;!--dash-container--&gt; &lt;div class="dash-container"&gt; &lt;!--left-side--&gt; &lt;div class="left-side"&gt; &lt;div class="logo"&gt; blueBox &lt;/div&gt; &lt;div class="profile-pic"&gt; &lt;img src="profile.jpg" /&gt; &lt;/div&gt; &lt;div class="profile-name"&gt; Gourav Thakur &lt;/div&gt; &lt;div class="profile-job-title"&gt; Project Manager &lt;/div&gt; &lt;!--sidebar options--&gt; &lt;div class="sidebar-options"&gt; &lt;ul&gt; &lt;li class="active"&gt; Dashboard &lt;i class="fas fa-home"&gt;&lt;/i&gt; &lt;/li&gt; &lt;li&gt; UI Elements &lt;i class="fab fa-elementor"&gt;&lt;/i&gt; &lt;/li&gt; &lt;li&gt; Components &lt;i class="fab fa-slack"&gt;&lt;/i&gt; &lt;/li&gt; &lt;li&gt; Forms stuff &lt;i class="fab fa-wpforms"&gt;&lt;/i&gt; &lt;/li&gt; &lt;li&gt; Data table &lt;i class="fas fa-database"&gt;&lt;/i&gt; &lt;/li&gt; &lt;li&gt; Icons &lt;i class="fas fa-tv"&gt;&lt;/i&gt; &lt;/li&gt; &lt;li&gt; Sample Page &lt;i class="fas fa-pager"&gt;&lt;/i&gt; &lt;/li&gt; &lt;li&gt; Extra &lt;i class="fas fa-gopuram"&gt;&lt;/i&gt; &lt;/li&gt; &lt;/ul&gt; &lt;button class="add-project-btn"&gt;Add Project&lt;/button&gt; &lt;/div&gt; &lt;!--end of sidebar-options--&gt; &lt;/div&gt; &lt;!--end of left-side --&gt; &lt;!--right-side--&gt; &lt;div class="right-side"&gt; &lt;!-- header--&gt; &lt;div class="header"&gt; &lt;span class="search"&gt; &lt;i class="fa fa-search"&gt;&lt;/i&gt; &lt;span class="search-box"&gt; &lt;input type="text" name="search" id="search" placeholder="Search Project"&gt;&lt;/input&gt; &lt;/span&gt; &lt;/span&gt; &lt;span class="header-profile-pic"&gt; &lt;img src="profile.jpg" alt=""/&gt; &lt;/span&gt; &lt;span class="green-dot"&gt; &lt;i class="fas fa-circle"&gt;&lt;/i&gt; &lt;/span&gt; &lt;span class="header-name"&gt; Gourav Thakur &lt;/span&gt; &lt;span class="dropdown"&gt; &lt;i class="fa fa-angle-down"&gt;&lt;/i&gt; &lt;/span&gt; &lt;span class="message"&gt; &lt;i class="fa fa-envelope"&gt;&lt;/i&gt; &lt;/span&gt; &lt;span class="red-dot-1"&gt; &lt;i class="fa fa-circle"&gt;&lt;/i&gt; &lt;/span&gt; &lt;span class="notify"&gt; &lt;i class="fa fa-bell"&gt;&lt;/i&gt; &lt;/span&gt; &lt;span class="red-dot-2"&gt; &lt;i class="fa fa-circle"&gt;&lt;/i&gt; &lt;/span&gt; &lt;span class="burger"&gt; &lt;i class="fa fa-bars"&gt;&lt;/i&gt; &lt;/span&gt; &lt;/div&gt; &lt;!--end of header--&gt; &lt;!-- main-content --&gt; &lt;div class="main-content"&gt; &lt;div class="dashboard-heading"&gt; &lt;div class="blue-rect"&gt; &lt;i class="fas fa-tachometer-alt"&gt;&lt;/i&gt; &lt;/div&gt; &lt;h1&gt;Dashboard&lt;/h1&gt; &lt;/div&gt; &lt;!-- card --&gt; &lt;div class="cards"&gt; &lt;div class="card-1"&gt; &lt;span class="card-icon"&gt; &lt;i class="fas fa-dollar-sign"&gt;&lt;/i&gt; &lt;/span&gt; &lt;h1 class="card-title"&gt;Stock Total&lt;/h1&gt; &lt;h1 class="card-price"&gt;$150000&lt;/h1&gt; &lt;h1 class="card-footer"&gt;Increased by 60%&lt;/h1&gt; &lt;img class="card-background-up" src="circle.png"/&gt; &lt;img class="card-background-down" src="circle.png"/&gt; &lt;/div&gt; &lt;div class="card-2"&gt; &lt;span class="card-icon"&gt; &lt;i class="fas fa-database"&gt;&lt;/i&gt; &lt;/span&gt; &lt;h1 class="card-title"&gt;Total Profit&lt;/h1&gt; &lt;h1 class="card-price"&gt;$25000&lt;/h1&gt; &lt;h1 class="card-footer"&gt;Increased by 30%&lt;/h1&gt; &lt;img class="card-background-up" src="circle.png"/&gt; &lt;img class="card-background-down" src="circle.png"/&gt; &lt;/div&gt; &lt;div class="card-3"&gt; &lt;span class="card-icon"&gt; &lt;i class="fa fa-flag"&gt;&lt;/i&gt; &lt;/span&gt; &lt;h1 class="card-title"&gt;Unique Visitors&lt;/h1&gt; &lt;h1 class="card-price"&gt;250000&lt;/h1&gt; &lt;h1 class="card-footer"&gt;Increased by 80%&lt;/h1&gt; &lt;img class="card-background-up" src="circle.png"/&gt; &lt;img class="card-background-down" src="circle.png"/&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- end of card--&gt; &lt;!--table--&gt; &lt;div class="table-container"&gt; &lt;h1 class="table-title"&gt;Standard Table Design&lt;/h1&gt; &lt;table class="table"&gt; &lt;tr&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;Email&lt;/th&gt; &lt;th&gt;User Type&lt;/th&gt; &lt;th&gt;Joined&lt;/th&gt; &lt;th&gt;Status&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Mike Band&lt;/td&gt; &lt;td&gt;Mikeband@gmail.com&lt;/td&gt; &lt;td&gt;Admin&lt;/td&gt; &lt;td&gt;25 Apr, 2018&lt;/td&gt; &lt;td class="pending"&gt;Pending&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Kevin Pietersen&lt;/td&gt; &lt;td&gt;Kevin@kevin.com&lt;/td&gt; &lt;td&gt;Editor&lt;/td&gt; &lt;td&gt;10 Aug, 2018&lt;/td&gt; &lt;td class="approved"&gt;Approved&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Andrew Strauss&lt;/td&gt; &lt;td&gt;Andrew@yahoo.com&lt;/td&gt; &lt;td&gt;Editor&lt;/td&gt; &lt;td&gt;20 Dec, 2019&lt;/td&gt; &lt;td class="approved"&gt;Approved&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Ross Taylor&lt;/td&gt; &lt;td&gt;Rossy@yourmail.com&lt;/td&gt; &lt;td&gt;Admin&lt;/td&gt; &lt;td&gt;13 Sep, 2018&lt;/td&gt; &lt;td class="rejected"&gt;Rejected&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Mike Hussey&lt;/td&gt; &lt;td&gt;Mikey@gmail.com&lt;/td&gt; &lt;td&gt;Subscriber&lt;/td&gt; &lt;td&gt;05 Oct, 2018&lt;/td&gt; &lt;td class="pending"&gt;Pending&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;!--end of table--&gt; &lt;/div&gt; &lt;!--end of main content--&gt; &lt;/div&gt; &lt;!--end of right-side--&gt; &lt;/div&gt; &lt;!--end of dash-container--&gt; &lt;/div&gt; &lt;!--End of container--&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<p>Oh deer. Oh deer. oh deer.</p>\n\n<p>Here you go friend, have a look at this:\n<a href=\"https://jsfiddle.net/d3o2Lex4/56/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/d3o2Lex4/56/</a></p>\n\n<p>Should be easy enough to understand. One thing to keep in mind when making things responsive is using % for widths. You will also have to learn the css @media query to make things adapt at different screen sizes. That's how Bootstrap works. If you haven't heard of Bootstrap check it out, you don't have to use it but it will give you insight as to how some people do things. I have used it in this example to get things going quicker.</p>\n\n<p>HTML</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>\n&lt;div id=\"app\"&gt;\n &lt;header&gt;\n header stuff goes here\n &lt;/header&gt;\n\n &lt;aside&gt;\n &lt;div&gt;user name badge goes here&lt;/div&gt;\n &lt;nav&gt;\n &lt;a href=\"\"&gt;links&lt;/a&gt;\n &lt;a href=\"\"&gt;go&lt;/a&gt;\n &lt;a href=\"\"&gt;here&lt;/a&gt;\n &lt;/nav&gt;\n &lt;/aside&gt;\n\n &lt;main&gt;\n\n &lt;!-- with bootstrap you could do something like this, the classes I have used here: container, row, col, card, mb-4 are all part of the bootstrap library --&gt;\n &lt;!-- see it here: https://getbootstrap.com/docs/4.3/getting-started/introduction/ --&gt;\n &lt;div class=\"container\"&gt;\n &lt;div class=\"row\"&gt;\n &lt;div class=\"col\"&gt;\n &lt;div class=\"card mb-4\"&gt;card 1&lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"col\"&gt;\n &lt;div class=\"card mb-4\"&gt;card 2&lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"col\"&gt;\n &lt;div class=\"card mb-4\"&gt;card 3&lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n\n &lt;div class=\"card\"&gt; this is a card example&lt;/div&gt;\n\n &lt;/div&gt;\n &lt;/main&gt; \n&lt;/div&gt;\n</code></pre>\n\n<p>SASS</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>/* reusable variables */\n$nav-width: 280px;\n$header-height: 65px;\n\n#app {\n width: 100%;\n height: 100vh;\n background: gray;\n overflow-x: hidden;\n}\n\nheader{\n height: $header-height;\n background: white;\n padding: 15px 30px; /* 15 is top and bottom. 30 is left and right */\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n}\n\naside{\n width: $nav-width;\n background: white;\n padding: 30px;\n /* keeping it fixed on the side */\n position: fixed;\n left: 0;\n bottom: 0;\n top: $header-height;\n /* if on small screens it can fit it will have a scroll bar */\n overflow-y: auto;\n}\n\nnav a{\n display: block;\n}\n\nmain {\n padding: 30px;\n margin-top: $header-height;\n margin-left: $nav-width;\n}\n\n.card{\n border-radius: 8px;\n background: white;\n padding: 30px;\n}\n\n* {\n box-sizing: border-box;\n}\n</code></pre>\n\n<p>hope this is helpful!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-08T09:52:32.570", "Id": "424863", "Score": "1", "body": "Welcome to Code Review! First: What's up with those calls to [animals](https://en.wikipedia.org/wiki/Deer) living in the forest? Second: \"Should be easy enough to understand.\" -> This is not what we do here. Explain essential parts of your code and show the reasoning why your approach is better than the original code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-08T10:36:34.417", "Id": "424866", "Score": "0", "body": "Thanks! I might have to delete my post. Unfortunately I am busy at work and have spent enough time putting this example together. I added a bit of personality to my post, obviously not cool. I don't have time to explain everything but figured something would help rather than nothing - seeing as no one has responded to his post in 5 days. I will get in touch with Gourav privately and send him links and answers that way - at least then we can have a discussion and work through it rather than having to provide everything in one long answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-10T15:21:34.217", "Id": "425209", "Score": "0", "body": "@GreggOd Thanks that was really helpful" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-08T09:05:51.847", "Id": "219916", "ParentId": "219581", "Score": "1" } } ]
{ "AcceptedAnswerId": "219916", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T11:46:04.230", "Id": "219581", "Score": "1", "Tags": [ "beginner", "html", "css", "layout" ], "Title": "blueBox dashboard Dribble design challenge" }
219581
<p>I created my first implementation of an arbitrary feed forward neural network with a simple back-propagation training implementation.</p> <pre><code>class NeuralNet(object): learning_rate = .1 # Error function @staticmethod def J(guess, target): return 0.5 * np.linalg.norm(guess - target, 2) ** 2 def __init__(self, structure=tuple(), activation_functions=tuple(), activation_derivatives=tuple()): self.w = [] self.b = [] self.f = list(activation_functions) self.df = list(activation_derivatives) li = len(structure) - 1 while li &gt; 0: self.w.insert(0, np.random.uniform(low=-1.0, high=1.0, size=(structure[li - 1], structure[li]))) self.b.insert(0, np.random.uniform(low=-1.0, high=1.0, size=structure[li])) li -= 1 def forward(self, x): z = [0] * len(self.w) a = [x] for i, (wi, bi, fi) in enumerate(zip(self.w, self.b, self.f)): z[i] = a[i] @ wi + bi a.append(fi(z[i])) return a[-1] def train(self, training_data, labels): # Get a permutation vector for shuffling the inputs and labels in each epoch: permutation = np.random.permutation(len(inputs)) # Keeping track of all MSE values: errors = [] # Training loop: for epoch in range(10000): # Shuffling the inputs and labels for each epoch: X = training_data[permutation] Y = labels[permutation] # n # Keeping track of the error: MSE = 1/n * SUM ||Activation - Target|| ** 2 # i=1 error = 0.0 for xi, yi in zip(X, Y): # Forward pass: z = [0] * len(self.w) a = [xi] for i, (wi, bi, fi) in enumerate(zip(self.w, self.b, self.f)): z[i] = a[i] @ wi + bi a.append(fi(z[i])) # Calculate error for (xi, yi) according to 0.5 * ||xi - yi|| ** 2 error += self.J(a[-1], yi) # Backwards pass: # - Calculate deltas: layer_delta = [] iter_zi = iter(zip(reversed(range(len(z))), reversed(z))) layer_delta.insert(0, (a[-1] - yi) * self.df[1](next(iter_zi)[1])) for i, zi in iter_zi: delta_i = np.multiply(layer_delta[0] @ self.w[i+1].T, self.df[i](z[i])) layer_delta.insert(0, delta_i) # - Calculate weight deltas: weight_delta = [] for i, di in zip(reversed(range(len(layer_delta))), reversed(layer_delta)): delta_wi = a[i].reshape(-1, 1) * layer_delta[i] weight_delta.insert(0, delta_wi) # w[i](new) := w[i](old) - LR * dJ/dw[i] # b[i](new) := b[i](old) - LR * dJ/db[i] for i in range(len(self.w)): self.w[i] = self.w[i] - self.learning_rate * weight_delta[i] self.b[i] = self.b[i] - self.learning_rate * layer_delta[i] errors.append(error / len(X)) # Convergence testing, according to the last N errors: error_delta = sum(reversed(errors[-5:])) if error_delta &lt; 1.0e-6: print("Error delta reached, ", epoch, " exiting.") break return errors </code></pre> <p>This seem to work just fine, at least it successfully learnt the XOR problem:</p> <pre><code># Inputs and their respective labels: inputs = np.array([[0, 0], [0, 1], [1, 0], [1, 1]]) labels = np.array([[0], [1], [1], [0]]) nn = NeuralNet(structure=(2, 2, 1), activation_functions=(lambda x: np.tanh(x), lambda x: .25 * x if x &lt; 0 else x), activation_derivatives=(lambda x: 1.0 - np.tanh(x) ** 2, lambda x: .25 if x &lt; 0 else 1)) nn.learning_rate = 0.1 print("Before training:") print(nn.forward(np.array([0, 0]))) print(nn.forward(np.array([0, 1]))) print(nn.forward(np.array([1, 0]))) print(nn.forward(np.array([1, 1]))) errors = nn.train(inputs, labels) print("After training:") print(nn.forward(np.array([0, 0]))) print(nn.forward(np.array([0, 1]))) print(nn.forward(np.array([1, 0]))) print(nn.forward(np.array([1, 1]))) plt.plot(errors) plt.show() </code></pre> <p>The calculations for layer_deltas seem particularly complicated, but whenever I try to simplify it, I break something. Any tips I could simplify that or any tips for the above code in general?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T15:12:55.510", "Id": "424228", "Score": "1", "body": "I rolled back your last edit. After getting an answer you are [not allowed to change your code anymore](https://codereview.stackexchange.com/help/someone-answers). This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). Refer to [this post](https://codereview.meta.stackexchange.com/a/1765/120114) for more information" } ]
[ { "body": "<h2>The not so arbitrary Network</h2>\n\n<p>Your original claim was that your network is \"arbitrary\". From what I see, I would tend to say that it's not so arbitrary as one might expect.</p>\n\n<p>Arbitrary:</p>\n\n<ul>\n<li>number of neurons per layer (you call it \"structure\")</li>\n<li>activation function</li>\n<li>their derivatives (which means they are not totally arbitrary)</li>\n</ul>\n\n<p>Not arbitrary:</p>\n\n<ul>\n<li>learning rate (<code>0.1</code>)</li>\n<li>network weight initialization</li>\n<li>error function (Somehow set to half of the squared Euclidean distance? Maybe you wanted the <a href=\"https://github.com/keras-team/keras/blob/master/keras/losses.py#L13\" rel=\"nofollow noreferrer\">Mean Squared Error</a> here?)</li>\n<li>number of epochs in training (<code>10000</code>)</li>\n<li>training mode (<a href=\"https://keras.io/getting-started/faq/#what-does-sample-batch-epoch-mean\" rel=\"nofollow noreferrer\">sample vs. batch learning</a>)</li>\n<li>training termination condition (<code>error_delta &lt; 1.0e-6</code>)</li>\n<li>optimizer</li>\n<li>...</li>\n</ul>\n\n<p>Those are all (more or less) important aspects one might like to tune without \"<a href=\"https://stackoverflow.com/questions/5626193/what-is-monkey-patching\">monkey-patching</a>\" them into the original class (if possible). Some of these parameters could easily be set in the constructor or when calling <code>train</code> (for number of epochs etc.). The error function could also easily be set at initialization, especially since it's already a <code>@staticmethod</code> which does not rely on class internals.</p>\n\n<p>I assume a flexible optimizer would be out of scope for what you want to do (and there are a <a href=\"https://keras.io/\" rel=\"nofollow noreferrer\">plethora</a> <a href=\"https://caffe.berkeleyvision.org/\" rel=\"nofollow noreferrer\">of</a> <a href=\"https://pytorch.org/\" rel=\"nofollow noreferrer\">frameworks</a> that can do this).</p>\n\n<h2>The code itself</h2>\n\n<p>The initialization of the network weights and biases is using a <code>while</code> loop and is unnecessarily complicated. You don't need a <code>while</code> loop here since you know exactly how many iterations have to be done. So use a <code>for</code> loop instead, which would lead you to:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>for i in range(len(structure)-1):\n self.w.append(np.random.uniform(low=-1.0, high=1.0, size=(structure[i], structure[i+1])))\n self.b.append(np.random.uniform(low=-1.0, high=1.0, size=(structure[i+1])))\n</code></pre>\n\n<p>Apart from not needing to keep tracking of the indexing variable, you also don't need indexing tricks with negatives indices and you are able to use <code>.append(...)</code> instead of inserting at the front.</p>\n\n<p>Oh and while we are at initialization: there is no need to convert the functions/derivative tuples to lists. You can iterate over/index tuples the same way as over lists.</p>\n\n<hr>\n\n<p>Speaking of iterations, this</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>layer_delta = []\niter_zi = iter(zip(reversed(range(len(z))), reversed(z)))\nlayer_delta.insert(0, (a[-1] - yi) * self.df[1](next(iter_zi)[1]))\nfor i, zi in iter_zi:\n delta_i = np.multiply(layer_delta[0] @ self.w[i+1].T, self.df[i](z[i]))\n layer_delta.insert(0, delta_i)\n</code></pre>\n\n<p>is madness&trade; IMHO (and there is also likely a bug with <code>self.df[1]</code>). See <a href=\"https://stackoverflow.com/questions/529424/traverse-a-list-in-reverse-order-in-python\">this SO post</a> on how to reverse enumerate a Python list, if you really think you need to. I don't think you need to because you use the actual list value only once and the index in all other cases. That would bring that monster down to something like</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>layer_delta = [(a[-1] - yi) * self.df[-1](z[-1])]\nfor i in reversed(range(len(z)-1)):\n delta_i = np.multiply(layer_delta[0] @ self.w[i+1].T, self.df[i](z[i]))\n layer_delta.insert(0, delta_i)\n</code></pre>\n\n<p>You can and should adapt your other appearances of the monster above as well. Work carefully while refactoring these parts of your code, I cannot guarantee that I didn't make a mistake while deciphering them.</p>\n\n<hr>\n\n<p>The implementation of the forward pass is also a little bit to complicated IMHO. Since you're only going through the network once, there is no need to store the activation and output of all layers. You only need the last one.</p>\n\n<p>You also implement the forward pass twice, in it's own <code>forward</code> function and in <code>train</code>. If you stick to your original implementation, think about if you would like to return the other values as well. That would leave you with only one piece of code to fix if something is wrong. If you're concerned about usability since the application phase now sees all the internal values, you could implement an internal function , e.g. <code>_forward</code> which does the heavy-lifting and let <code>forward</code> just return the final output.</p>\n\n<hr>\n\n<p>The comment and variable names at</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># Convergence testing, according to the last N errors:\nerror_delta = sum(reversed(errors[-5:]))\nif error_delta &lt; 1.0e-6:\n print(\"Error delta reached, \", epoch, \" exiting.\")\n break\n</code></pre>\n\n<p>are also a little off. The termination criterion does seem to check if the sum of the last N (where N is hard coded to 5) is below your (arbitrarily chosen) threshold. Also, there is no need to reverse the list here since <a href=\"https://en.wikipedia.org/wiki/Commutative_property\" rel=\"nofollow noreferrer\">sum does not care about the order</a>.</p>\n\n<p>Since you are working in Python 3, you can also use the new f-string syntax for output formatting:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(f\"Error delta reached in {epoch} exiting.\")\n</code></pre>\n\n<hr>\n\n<p>Speaking of comments, the methods of your class all lack user visible documentation. For that, Python programmers usually use so called <a href=\"https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring\" rel=\"nofollow noreferrer\"><code>\"\"\"doc strings\"\"\"</code></a> on their methods/classes/functions. As an example:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def train(self, training_data, labels):\n \"\"\"Train the neural network with all the available data\n\n The training continues until the maximum number of epochs is reached or\n the termination criterion is hit.\n \"\"\"\n # your code here ...\n</code></pre>\n\n<p>Documentation written in this kind of format will be picked up by all major Python IDEs as well as by Python's built-in <code>help(...)</code> function.</p>\n\n<hr>\n\n<p>I know there are common naming conventions in the neural network community, and when you implement it, you should stick to them as closely as possible which you mostly do. <strong>But</strong> bear in mind not to sacrifice the clarity and readability of your code. E.g. <code>z</code> could become <code>activation</code> and <code>a</code> could also be named <code>layer_output</code> (plurals might apply where they are used as list).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T05:28:20.017", "Id": "424173", "Score": "0", "body": "Awesome points! Yeah, that those two loops are atrocious, your proposed solution is a lot cleaner. I'll update my code according to your recommendations and will post the updated solution.\nAlso for that not so arbitrary, true. I don't want to create yet another public facing NN framework, there are already enough of them, this is for me learning what NNs actually do. How they behave for different activation functions etc etc." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T16:18:05.297", "Id": "219593", "ParentId": "219583", "Score": "9" } } ]
{ "AcceptedAnswerId": "219593", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T12:44:54.250", "Id": "219583", "Score": "8", "Tags": [ "python", "python-3.x", "numpy", "neural-network" ], "Title": "Deep Neural Net implementation in Python3" }
219583
<p>Is it a good practice to initialize the <a href="https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html" rel="nofollow noreferrer">BufferedReader</a> and <a href="https://docs.oracle.com/javase/7/docs/api/java/io/DataOutputStream.html" rel="nofollow noreferrer">DataOutputStream</a> in infinite loop?</p> <pre><code> ServerSocket welcomeSocket = new ServerSocket(8080); Socket connectionSocket = welcomeSocket.accept(); while (true) { BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); //close it DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); //close it //... Do read/write stuff } </code></pre> <p>Connection establishes successfully and communication happens normally. Just want to know that whether it is a good practice or not? It is a Java code.</p> <p>Thanks.</p>
[]
[ { "body": "<p>At the very least use a try-with-resources: </p>\n\n<pre><code>while (true) {\n try(BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())),\n DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream())){\n //... Do read/write stuff\n }\n}\n</code></pre>\n\n<p>Then when the loop body is done (by normal control flow or by exception) the streams will be closed normally.</p>\n\n<p>However if you want a lot of clients connecting at a time and you want them all to be able to interact at the same time you will need to delve into the async IO in the java.nio.channels package.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T15:11:36.527", "Id": "424121", "Score": "0", "body": "Hmm, that's better option. It means the approach I mentioned is a poor one." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T14:43:50.870", "Id": "219588", "ParentId": "219584", "Score": "3" } }, { "body": "<p>It seems that this class is responsible for managing control flow (the loop) and establishing connections (the streams) so it breaks the single responsibility principle.</p>\n\n<p>But in the end, theoretically, it doesn't matter if the stream initialization is inside this loop or in another class called from this loop. If the requirements say streams have to be opened in a loop, then they have to be.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T07:40:59.287", "Id": "219624", "ParentId": "219584", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T12:53:35.990", "Id": "219584", "Score": "1", "Tags": [ "java" ], "Title": "Initializing BufferedReader and DataOutputStream in infinite loop" }
219584
<p>I have a simple job class in Laravel, that:</p> <ol> <li>Get all the images in a folder <code>/original</code></li> <li>Perform some image manipulation on each image </li> <li>Save each image in a new folder <code>/preprocessed</code></li> </ol> <p>All of these steps are added to a <code>queue</code>.</p> <p>However, I have taken an alternative approach and is using python to do the actual image manipulation</p> <p>This is my code:</p> <pre><code>$images = Storage::allFiles($this-&gt;document-&gt;path('original')); foreach ($images as $key =&gt; $image) { $file = storage_path() . '/app/' . $image; //token/unique_id/original/1.jpg $savePath = storage_path() . '/app/' . $this-&gt;document-&gt;path('preprocessed'); $filename = $key . '.jpg'; //Scale and save the image in "/preprocessed" $process = new Process("python3 /Python/ScaleImage.py {$file} {$savePath} {$filename}"); $process-&gt;run(); // executes after the command finishes if (!$process-&gt;isSuccessful()) { throw new ProcessFailedException($process); return false; } } </code></pre> <p>In my python file <code>ScaleImage.py</code>, I simply perform some image manipulation and saves the image to the <code>/preprocessed</code> folder. </p> <pre><code> def set_image_dpi(file) //Image manipulation - removed from example //save image in /preprocessed im.save(SAVE_PATH + FILE_NAME, dpi=(300, 300)) return SAVE_PATH + FILE_NAME print(set_image_dpi(FILE_PATH)) </code></pre> <p>Above code works. </p> <p>In the future, I might need to do even more image manipulation such as (noise removal, skew correction, etc.) </p> <p>My final goal is to use <code>Tesseract OCR</code> on the preprocessed image to grap the text content of the image.</p> <p>Now I am sure I could achieve similar stuff with for example <code>ImageMagick</code> in PHP.</p> <p>However, I've read the for image processing and OCR, Python's performance is a lot better.</p> <p>Is above approach a good idea? Anything that can be improved?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T13:05:26.967", "Id": "219585", "Score": "2", "Tags": [ "python", "php", "image", "laravel" ], "Title": "PHP / Laravel - Using Python to image manipulation" }
219585
<p>I wrote a piece of code that included multiple AJAX requests and multiple SetTimeout animations. <br/><br/> I want the code to perform better, <strong>especially the SetTimeout sections.</strong> <br/><br/> <strong>which part of the code should be improved?</strong> <br/><br/></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>window.timer = []; window.timerNum = 1; function amLoading(timer) { var node = document.createElement("mark"), str = "Loading...", len = str.length, i = 0, html = ""; node.classList.add("am-load"); function typing() { console.log("timer &gt; " + timer); if (i &lt; len) { html += str[i]; i++; } else { html = ""; i = 0; } node.innerHTML = html; timer = setTimeout(function () { typing(); }, 160); } typing(); return node; } function requestData(option) { var list = option["list"], xhrType = option["type"], xhrUrl = option["src"], count = option["count"], num = window.timerNum++, xhr = new XMLHttpRequest(), item = document.createElement("li"); window.timer.push(num); // console.log(num); // console.log(window.timer[num-1]); var node = amLoading(window.timer[num - 1]); xhr.open("GET", xhrUrl, true); xhr.onreadystatechange = function () { if (xhr.readyState === 4 &amp;&amp; xhr.status === 200) { if (node) { node.parentNode.removeChild(node); clearTimeout(window.timer[num - 1]); } switch (xhrType) { case "json": var par = document.createElement("p"); par.innerHTML = xhr.responseText; item.appendChild(par); break; case "image": var img = document.createElement("img"); img.src = xhrUrl; item.appendChild(img); break; default: break; } requestData.num++; // console.log(requestData.num); if (requestData.num === count) { list.classList.add("active"); } else { list.classList.remove("active"); } } else { item.appendChild(node); } list.appendChild(item); }; xhr.send(null); } function renderData(option) { var wrapper = document.querySelector(option["selector"]), data = option["data"], requestCount = data.length; wrapper.innerHTML = ""; if (data.length &gt; 0) { data.forEach(function (value, index) { requestData.num = 0; requestData({ "type": value["type"], "src": value["src"], "list": wrapper, "count": requestCount, }); }); } } var data = [{ "type": "json", "src": "/data.json", }, { "type": "image", // "src": "/github-logo.png-error", "src": "/github-logo.png", }, { "type": "image", "src": "/node-logo.png", }, { "type": "image", "src": "/python-logo.png", }, { "type": "image", "src": "/vim-logo.png-error", // "src": "/vim-logo.png", }, { "type": "image", "src": "/vscode-logo.png", }, ]; renderData({ "selector": ".list", "data": data, });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>* { margin: 0; padding: 0; list-style: none; box-sizing: border-box; } body { padding: 1rem; word-break: break-all; word-wrap: break-word; color: #666; } img { display: block; max-width: 100%; } ol { letter-spacing: -8px; } ol&gt;li { display: inline-block; width: 200px; height: 200px; padding: 1rem; letter-spacing: 1px; vertical-align: middle; border: 1px solid #eee; position: relative; } ol&gt;li&gt;.am-load { padding: 10px; height: 36px; line-height: 1; text-align: center; color: #f80; position: absolute; left: 5%; right: 5%; top: 50%; -ms-transform: translate(0, -50%); transform: translate(0, -50%); } ol.active&gt;li { border-color: #fc8; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;meta http-equiv="X-UA-Compatible" content="ie=edge"&gt; &lt;title&gt;Demo-AJAX&lt;/title&gt; &lt;link rel="stylesheet" href="style.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;ol class="list"&gt;&lt;/ol&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T20:41:10.460", "Id": "424141", "Score": "0", "body": "Can you give more context on what this code actually does (instead of just saying it uses multiple timers and XHR calls)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T03:28:32.957", "Id": "424169", "Score": "0", "body": "Your code has bugs that you are aware of as you have `console.log(\"timer > \" + timer);` trying to track down why the timeouts are not cleared. (`amLoading(timer){` `timer` is a copy not a reference) It is also difficult to workout your intent (Why request the images then ignore the data when it has loaded? Why not create an Image and set its src without the redundant fetch?) To get a good review you will need to fix your code and clarify your intent." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T07:50:55.557", "Id": "424321", "Score": "0", "body": "@Joseph This code can be executed normally, no bugs.\nI want to write a JS component." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T07:54:17.733", "Id": "424322", "Score": "0", "body": "@Blindman67 This code can be executed normally. I want to write a JS component." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T15:10:30.883", "Id": "219589", "Score": "2", "Tags": [ "javascript", "performance", "asynchronous", "ajax", "animation" ], "Title": "multiple AJAX requests and multiple SetTimeout animations" }
219589
<p>I did wrote this parallel merge sort with no external dependencies. I tried to make use of modern C++ as much as possible.<br> Can you please tell me how it is?</p> <pre><code>#include &lt;vector&gt; #include &lt;list&gt; #include &lt;thread&gt; #include &lt;memory&gt; #include &lt;mutex&gt; #include &lt;condition_variable&gt; #include &lt;algorithm&gt; #include &lt;utility&gt; #include &lt;exception&gt; #include &lt;cassert&gt; #include &lt;iterator&gt; template&lt;typename T&gt; struct invoke_on_destruct { private: T &amp;m_t; bool m_enabled; public: invoke_on_destruct( T &amp;t ) : m_t( t ), m_enabled( true ) { } ~invoke_on_destruct() { if( m_enabled ) m_t(); } void invoke_and_disable() { m_t(); m_enabled = false; } }; struct sort_exception : public std::exception { }; template&lt;typename InputIt, typename P = std::less&lt;typename std::iterator_traits&lt;InputIt&gt;::value_type&gt;&gt; class parallel_merge_sort { public: parallel_merge_sort( P const &amp;p = P() ); ~parallel_merge_sort(); void sort( InputIt itBegin, size_t n, std::size_t minThreaded ); std::size_t get_buffer_size(); void empty_buffers(); private: typedef typename std::iterator_traits&lt;InputIt&gt;::value_type value_type; typedef typename std::vector&lt;value_type&gt; buffer_type; typedef typename buffer_type::iterator buffer_iterator; struct pool_thread { enum CMD : int { CMD_STOP = -1, CMD_NONE = 0, CMD_SORT = 1 }; enum RSP : int { RSP_ERR = -1, RSP_NONE = 0, RSP_SUCCESS = 1 }; std::thread m_thread; std::mutex m_mtx; std::condition_variable m_sigInitiate; CMD m_cmd; buffer_iterator m_itBegin; std::size_t m_n; std::condition_variable m_sigResponse; RSP m_rsp; std::vector&lt;value_type&gt; m_sortBuf; pool_thread( parallel_merge_sort *pPMS ); ~pool_thread(); void sort_thread( parallel_merge_sort *pPMS ); static std::size_t calc_buffer_size( size_t n ); }; P m_p; std::size_t m_minThreaded; unsigned m_maxRightThreads; buffer_type m_callerSortBuf; std::mutex m_mtxPool; std::list&lt;pool_thread&gt; m_standbyThreads; std::list&lt;pool_thread&gt; m_activeThreads; template&lt;typename InputIt2&gt; void threaded_sort( InputIt2 itBegin, std::size_t n, buffer_iterator itSortBuf ); template&lt;typename InputIt2&gt; void unthreaded_sort( InputIt2 itBegin, std::size_t n, buffer_iterator itSortBuf ); template&lt;typename OutputIt&gt; void merge_back( OutputIt itUp, buffer_iterator itLeft, buffer_iterator itLeftEnd, buffer_iterator itRight, buffer_iterator itRightEnd ); }; template&lt;typename InputIt, typename P&gt; parallel_merge_sort&lt;InputIt, P&gt;::parallel_merge_sort( P const &amp;p ) : m_p( p ) { unsigned hc = std::thread::hardware_concurrency(); m_maxRightThreads = hc != 0 ? (hc - 1) : 0; } template&lt;typename InputIt, typename P&gt; void parallel_merge_sort&lt;InputIt, P&gt;::sort( InputIt itBegin, size_t n, std::size_t minThreaded ) { size_t const MIN_SIZE = 2; if( n &lt; MIN_SIZE ) return; if( (m_minThreaded = minThreaded) &lt; (2 * MIN_SIZE) ) m_minThreaded = 2 * MIN_SIZE; try { std::size_t s = pool_thread::calc_buffer_size( n ); if( m_callerSortBuf.size() &lt; s ) m_callerSortBuf.resize( s ); threaded_sort( itBegin, n, m_callerSortBuf.begin() ); } catch( ... ) { throw sort_exception(); } } template&lt;typename InputIt, typename P&gt; parallel_merge_sort&lt;InputIt, P&gt;::~parallel_merge_sort() { assert(m_activeThreads.size() == 0); } template&lt;typename InputIt, typename P&gt; inline std::size_t parallel_merge_sort&lt;InputIt, P&gt;::pool_thread::calc_buffer_size( std::size_t n ) { for( std::size_t rest = n, right; rest &gt; 2; ) right = rest - (rest / 2), n += right, rest = right; return n; } template&lt;typename InputIt, typename P&gt; parallel_merge_sort&lt;InputIt, P&gt;::pool_thread::~pool_thread() { using namespace std; unique_lock&lt;mutex&gt; threadLock( m_mtx ); m_cmd = pool_thread::CMD_STOP; m_sigInitiate.notify_one(); threadLock.unlock(); m_thread.join(); } template&lt;typename InputIt, typename P&gt; template&lt;typename InputIt2&gt; void parallel_merge_sort&lt;InputIt, P&gt;::threaded_sort( InputIt2 itBegin, std::size_t n, buffer_iterator itSortBuf ) { using namespace std; unique_lock&lt;mutex&gt; poolLock( m_mtxPool ); if( n &lt; m_minThreaded || (m_standbyThreads.empty() &amp;&amp; m_activeThreads.size() &gt;= m_maxRightThreads) ) { poolLock.unlock(); unthreaded_sort( itBegin, n, itSortBuf ); return; } typedef typename list&lt;pool_thread&gt;::iterator pt_it; pt_it itPT; pool_thread *pPT; size_t left = n / 2, right = n - left; if( !m_standbyThreads.empty() ) { pt_it itPTScan; size_t optimalSize = pool_thread::calc_buffer_size( right ), bestFit = (size_t)(ptrdiff_t)-1, size; for( itPT = m_standbyThreads.end(), itPTScan = m_standbyThreads.begin(); itPTScan != m_standbyThreads.end(); ++itPTScan ) if( (size = itPTScan-&gt;m_sortBuf.size()) &gt;= optimalSize &amp;&amp; size &lt; bestFit ) itPT = itPTScan, bestFit = size; if( itPT == m_standbyThreads.end() ) itPT = --m_standbyThreads.end(); m_activeThreads.splice( m_activeThreads.end(), m_standbyThreads, itPT ); poolLock.unlock(); pPT = &amp;*itPT; } else m_activeThreads.emplace_back( this ), itPT = --m_activeThreads.end(), pPT = &amp;*itPT, poolLock.unlock(); auto pushThreadBack = [&amp;poolLock, &amp;itPT, this]() { poolLock.lock(); m_standbyThreads.splice( m_standbyThreads.end(), m_activeThreads, itPT ); }; invoke_on_destruct&lt;decltype(pushThreadBack)&gt; autoPushBackThread( pushThreadBack ); buffer_iterator itMoveTo = itSortBuf; for( InputIt2 itMoveFrom = itBegin, itEnd = itMoveFrom + n; itMoveFrom != itEnd; *itMoveTo = move( *itMoveFrom ), ++itMoveTo, ++itMoveFrom ); buffer_iterator itLeft = itSortBuf, itRight = itLeft + left; unique_lock&lt;mutex&gt; threadLock( pPT-&gt;m_mtx ); pPT-&gt;m_cmd = pool_thread::CMD_SORT; pPT-&gt;m_rsp = pool_thread::RSP_NONE; pPT-&gt;m_itBegin = itRight; pPT-&gt;m_n = right; pPT-&gt;m_sigInitiate.notify_one(); threadLock.unlock(); auto waitForThread = [&amp;threadLock, pPT]() { threadLock.lock(); while( pPT-&gt;m_rsp == pool_thread::RSP_NONE ) pPT-&gt;m_sigResponse.wait( threadLock ); assert(pPT-&gt;m_rsp == pool_thread::RSP_SUCCESS || pPT-&gt;m_rsp == pool_thread::RSP_ERR); }; invoke_on_destruct&lt;decltype(waitForThread)&gt; autoWaitForThread( waitForThread ); threaded_sort( itLeft, left, itSortBuf + n ); autoWaitForThread.invoke_and_disable(); if( pPT-&gt;m_rsp == pool_thread::RSP_ERR ) throw sort_exception(); threadLock.unlock(); merge_back( itBegin, itLeft, itLeft + left, itRight, itRight + right ); } template&lt;typename InputIt, typename P&gt; template&lt;typename InputIt2&gt; void parallel_merge_sort&lt;InputIt, P&gt;::unthreaded_sort( InputIt2 itBegin, std::size_t n, buffer_iterator itSortBuf ) { assert(n &gt;= 2); using namespace std; if( n == 2 ) { if( m_p( itBegin[1], itBegin[0] ) ) { value_type temp( move( itBegin[0] ) ); itBegin[0] = move( itBegin[1] ); itBegin[1] = move( temp ); } return; } buffer_iterator itMoveTo = itSortBuf; for( InputIt2 itMoveFrom = itBegin, itEnd = itMoveFrom + n; itMoveFrom != itEnd; *itMoveTo = move( *itMoveFrom ), ++itMoveTo, ++itMoveFrom ); size_t left = n / 2, right = n - left; buffer_iterator itLeft = itSortBuf, itRight = itLeft + left; if( left &gt;= 2 ) unthreaded_sort( itLeft, left, itSortBuf + n ); if( right &gt;= 2 ) unthreaded_sort( itRight, right, itSortBuf + n ); merge_back( itBegin, itLeft, itLeft + left, itRight, itRight + right ); } template&lt;typename InputIt, typename P&gt; template&lt;typename OutputIt&gt; inline void parallel_merge_sort&lt;InputIt, P&gt;::merge_back( OutputIt itUp, buffer_iterator itLeft, buffer_iterator itLeftEnd, buffer_iterator itRight, buffer_iterator itRightEnd ) { assert(itLeft &lt; itLeftEnd &amp;&amp; itRight &lt; itRightEnd); using namespace std; for( ; ; ) if( m_p( *itLeft, *itRight ) ) { *itUp = move( *itLeft ); ++itUp, ++itLeft; if( itLeft == itLeftEnd ) { for( ; itRight != itRightEnd; *itUp = move( *itRight ), ++itUp, ++itRight ); break; } } else { *itUp = move( *itRight ); ++itUp, ++itRight; if( itRight == itRightEnd ) { for( ; itLeft != itLeftEnd; *itUp = move( *itRight ), ++itUp, ++itLeft ); break; } } } template&lt;typename InputIt, typename P&gt; std::size_t parallel_merge_sort&lt;InputIt, P&gt;::get_buffer_size() { std::size_t s = 0; for( pool_thread &amp;pt : m_standbyThreads ) s += pt.m_sortBuf.capacity(); return s + m_callerSortBuf.capacity(); } template&lt;typename InputIt, typename P&gt; void parallel_merge_sort&lt;InputIt, P&gt;::empty_buffers() { for( pool_thread &amp;pt : m_standbyThreads ) pt.m_sortBuf.clear(), pt.m_sortBuf.shrink_to_fit(); m_callerSortBuf.clear(); m_callerSortBuf.shrink_to_fit(); } template&lt;typename InputIt, typename P&gt; parallel_merge_sort&lt;InputIt, P&gt;::pool_thread::pool_thread( parallel_merge_sort *pPMS ) : m_mtx(), m_sigInitiate(), m_cmd( pool_thread::CMD_NONE ), m_thread( std::thread( []( pool_thread *pPT, parallel_merge_sort *pPMS ) -&gt; void { pPT-&gt;sort_thread( pPMS ); }, this, pPMS ) ) { } template&lt;typename InputIt, typename P&gt; void parallel_merge_sort&lt;InputIt, P&gt;::pool_thread::sort_thread( parallel_merge_sort *pPMS ) { using namespace std; for( ; ; ) { unique_lock&lt;mutex&gt; threadLock( m_mtx ); while( m_cmd == CMD_NONE ) m_sigInitiate.wait( threadLock ); if( m_cmd == CMD_STOP ) return; assert(m_cmd == pool_thread::CMD_SORT); m_cmd = CMD_NONE; threadLock.unlock(); bool success; try { size_t size = calc_buffer_size( m_n ); if( m_sortBuf.size() &lt; size ) m_sortBuf.resize( size ); pPMS-&gt;threaded_sort( m_itBegin, m_n, m_sortBuf.begin() ); success = true; } catch( ... ) { success = false; } threadLock.lock(); m_rsp = success ? RSP_SUCCESS : RSP_ERR, m_sigResponse.notify_one(); } } template&lt;typename InputIt, typename P = std::less&lt;typename std::iterator_traits&lt;InputIt&gt;::value_type&gt;&gt; class ref_parallel_merge_sort { private: struct ref { InputIt it; }; struct ref_predicate { ref_predicate( P p ); bool operator ()( ref const &amp;left, ref const &amp;right ); P m_p; }; public: ref_parallel_merge_sort( P const &amp;p = P() ); void sort( InputIt itBegin, size_t n, std::size_t maxUnthreaded ); std::size_t get_buffer_size(); void empty_buffers(); private: parallel_merge_sort&lt;ref, ref_predicate&gt; m_sorter; }; template&lt;typename InputIt, typename P&gt; inline ref_parallel_merge_sort&lt;InputIt, P&gt;::ref_predicate::ref_predicate( P p ) : m_p ( p ) { } template&lt;typename InputIt, typename P&gt; inline bool ref_parallel_merge_sort&lt;InputIt, P&gt;::ref_predicate::operator ()( ref const &amp;left, ref const &amp;right ) { return m_p( *left.it, *right.it ); } template&lt;typename InputIt, typename P&gt; inline ref_parallel_merge_sort&lt;InputIt, P&gt;::ref_parallel_merge_sort( P const &amp;p ) : m_sorter( ref_predicate( p ) ) { } template&lt;typename InputIt, typename P&gt; void ref_parallel_merge_sort&lt;InputIt, P&gt;::sort( InputIt itBegin, size_t n, std::size_t maxUnthreaded ) { using namespace std; try { typedef typename iterator_traits&lt;InputIt&gt;::value_type value_type; vector&lt;ref&gt; refBuf; InputIt it; int i; refBuf.resize( n ); for( i = 0, it = itBegin; i != n; refBuf[i].it = it, ++i, ++it ); m_sorter.sort( &amp;refBuf[0], n, maxUnthreaded ); vector&lt;value_type&gt; reorderBuf; reorderBuf.resize( n ); for( i = 0, it = itBegin; i != n; reorderBuf[i] = move( *it ), ++i, ++it ); for( i = 0, it = itBegin; i != n; *it = move( reorderBuf[i] ), ++i, ++it ); } catch( ... ) { throw sort_exception(); } } template&lt;typename InputIt, typename P&gt; inline std::size_t ref_parallel_merge_sort&lt;InputIt, P&gt;::get_buffer_size() { return m_sorter.get_buffer_size(); } template&lt;typename InputIt, typename P&gt; inline void ref_parallel_merge_sort&lt;InputIt, P&gt;::empty_buffers() { m_sorter.empty_buffers(); } #include &lt;iostream&gt; #include &lt;cstdlib&gt; #include &lt;functional&gt; #include &lt;random&gt; #include &lt;cstdint&gt; #include &lt;iterator&gt; #include &lt;type_traits&gt; #if defined(_MSC_VER) #include &lt;Windows.h&gt; double get_usecs() { LONGLONG liTime; GetSystemTimeAsFileTime( &amp;(FILETIME &amp;)liTime ); return (double)liTime / 10.0; } #elif defined(__unix__) #include &lt;sys/time.h&gt; double get_usecs() { timeval tv; gettimeofday( &amp;tv, nullptr ); return (double)tv.tv_sec * 1'000'000.0 + tv.tv_usec; } #elif #error no OS-support for get_usecs() #endif using namespace std; void fill_with_random( double *p, size_t n, unsigned seed = 0 ) { default_random_engine re( seed ); uniform_real_distribution&lt;double&gt; distrib; for( double *pEnd = p + n; p != pEnd; *p++ = distrib( re ) ); } template&lt;typename T, typename = typename enable_if&lt;is_unsigned&lt;T&gt;::value, T&gt;::type&gt; string decimal_unsigned( T t ); int main() { typedef typename vector&lt;double&gt;::iterator it_type; size_t const SIZE = (size_t)1024 * 1024 * 1024 / sizeof(double); unsigned hc = thread::hardware_concurrency(); vector&lt;double&gt; v; double t; v.resize( SIZE ); parallel_merge_sort&lt;it_type&gt; sd; fill_with_random( &amp;v[0], SIZE ); t = get_usecs(); sd.sort( v.begin(), SIZE, SIZE / hc ); t = get_usecs() - t; cout &lt;&lt; (t / 1'000'000.0) &lt;&lt; " seconds parallel" &lt;&lt; endl; cout &lt;&lt; decimal_unsigned( sd.get_buffer_size() * sizeof(double) ) &lt;&lt; endl; sd.empty_buffers(); fill_with_random( &amp;v[0], SIZE ); t = get_usecs(); sd.sort( v.begin(), SIZE, SIZE ); t = get_usecs() - t; cout &lt;&lt; (t / 1'000'000.0) &lt;&lt; " seconds sequential" &lt;&lt; endl; cout &lt;&lt; decimal_unsigned( sd.get_buffer_size() * sizeof(double) ) &lt;&lt; endl; sd.empty_buffers(); } #include &lt;sstream&gt; string decify_string( string const &amp;s ); template&lt;typename T, typename&gt; string decimal_unsigned( T t ) { using namespace std; ostringstream oss; return move( decify_string( (oss &lt;&lt; t, oss.str()) ) ); } string decify_string( string const &amp;s ) { using namespace std; ostringstream oss; size_t length = s.length(), head = length % 3, segments = length / 3; if( head == 0 &amp;&amp; segments &gt;= 1 ) head = 3, --segments; oss &lt;&lt; s.substr( 0, head ); for( size_t i = head; i != length; i += 3 ) oss &lt;&lt; "." &lt;&lt; s.substr( i, 3 ); return move( oss.str() ); } </code></pre>
[]
[ { "body": "<p>Design-wise, I don't like the tight coupling of the sort and the thread pool. Users expect a sort to be a plain function; it probably makes sense to be able to pass a thread-pool as an argument (and for it to be defaulted). This coupling makes it hard to use the pool for anything else, or to use the sort with a different implementation of the thread pool.</p>\n<hr />\n<p><code>invoke_on_destruct</code> seems more complex than necessary. We never invoke-and-disable more than once, so we could simply replace the stored function with a no-op rather than having a boolean member:</p>\n<pre><code>#include &lt;functional&gt;\nclass invoke_on_destruct\n{\n std::function&lt;void()&gt; t;\n \npublic:\n invoke_on_destruct(std::function&lt;void()&gt; t)\n : t(std::move(t))\n {}\n\n ~invoke_on_destruct()\n { t(); }\n\n void invoke_and_disable()\n { t(); t = []{}; }\n};\n</code></pre>\n<p>We don't really need <code>invoke_and_disable()</code>: this is the only place it's used:</p>\n<blockquote>\n<pre><code>invoke_on_destruct autoWaitForThread( waitForThread );\n\nthreaded_sort( itLeft, left, itSortBuf + n );\n\nautoWaitForThread.invoke_and_disable();\n</code></pre>\n</blockquote>\n<p>That could reasonably be changed to simply reduce the scope:</p>\n<pre><code>{\n invoke_on_destruct autoWaitForThread( waitForThread );\n\n threaded_sort( itLeft, left, itSortBuf + n );\n}\n</code></pre>\n<p>In any case, we need to be very careful that the invoked function does not throw, since exceptions thrown from destructors will terminate the entire program.</p>\n<hr />\n<p>Please don't hide exception detail like this:</p>\n<blockquote>\n<pre><code> catch( ... )\n {\n throw sort_exception();\n }\n</code></pre>\n</blockquote>\n<p>That loses useful information, and isn't even much convenience to the caller.</p>\n<hr />\n<p>A few minor points of improvement:</p>\n<ul>\n<li><p>There's a couple of functions that have <code>using namespace std;</code> where a more targeted approach (<code>using std::move;</code>) would be safer.</p>\n</li>\n<li><p><code>return std::move(x);</code> is an anti-pattern - trust your compiler to elide return-value copying.</p>\n</li>\n<li><p>The whole <code>decify_string()</code> business is a waste of your effort - just go with the user's preferred format, using <code>std::cout.imbue(std::locale(&quot;&quot;));</code> early on. If you really need that specific formatting, then <a href=\"//stackoverflow.com/a/17530535/4850040\">use a modified user locale</a> instead.</p>\n</li>\n<li><p>Don't use all-caps names (e.g. <code>SIZE</code>) for identifiers - it's conventional to reserve these names for macros, and the &quot;shoutiness&quot; warns that they should be treated with care. That warning is diluted if we use it for non-macro names too.</p>\n</li>\n<li><p>Don't use <code>std::endl</code> where a flush is not required. In fact, it's a good idea to never use it, and explicitly write both <code>\\n</code> and <code>std::flush</code> where you really want the effect of <code>std::endl</code>.</p>\n</li>\n<li><p>Fix the misleading indentation:</p>\n<pre><code> for( pool_thread &amp;pt : m_standbyThreads )\n pt.m_sortBuf.clear(),\n pt.m_sortBuf.shrink_to_fit();\n m_callerSortBuf.clear();\n</code></pre>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T12:17:01.520", "Id": "251704", "ParentId": "219594", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T17:12:58.533", "Id": "219594", "Score": "10", "Tags": [ "c++", "algorithm", "multithreading", "mergesort" ], "Title": "Parallel merge sort with thread- and bufferpooling" }
219594
<p>Python beginner here. Created this program as a project to help learn python. Just ran this in a centos7vm so far to test. What it does is - zip up files containing certain extensions (excluding those defined in the var ext_list), logs the zip up process as it continues through, and when finished, send an email confirming the backup is finished to the person specified to send to. (For sending &amp; receiving the email I have just used gmail) Also it will cleanup existing backups in the destination folder before creating the zip. </p> <p>I would appreciate some suggestions for improvements. Things that I may have missed, things that would make this look more professional. That type of thing.</p> <pre><code>import os, sys, zipfile, fnmatch, glob, sys, time, datetime, smtplib, logging from datetime import date from datetime import time from datetime import datetime import os.path from pathlib import Path from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email import encoders # General variables dir_to_backup = '/home/admin/python' backup_dir = '/tmp/backupdir/' backup_log = '/tmp/backuplog.log' admin_email = 'email' # File extensions to exclude from backupzip ext_list = ('.txt','.jpg', '.py','.pyc', '.rpm') # Dates todays_date = date.today() current_time = datetime.time(datetime.now()) # zip file info zip_name = 'backup.zip' zip_file_name_full = ("%s_%s_%s" %(todays_date, current_time, zip_name)) zip_file_name_abs_path = os.path.join('/tmp/backupdir/', zip_file_name_full) # Delete previous backup zips from backup dir clear_backups = 'yes' # Email variables email_user = 'email' email_send = 'email' email_pass = 'emailpasswd' subject = 'Backup Completed' msg = MIMEMultipart() msg['From'] = email_user msg['To'] = email_send msg['Subject'] = subject body = 'See attached log file for details' msg.attach(MIMEText(body, 'plain')) # filename = '/tmp/backupdir/backuplog.log' # attachment = open(filename, 'rb') email_log_file = 'yes' # End email variables def logging_setup(): """ Configure logging """ logging.basicConfig(filename=backup_log, level=logging.DEBUG, filemode = 'w', format="%(asctime)s:%(levelname)s:%(message)s") logging_setup() def checkdir(): """ Check if the backup dir is present, if not create """ if not os.path.exists(backup_dir): os.makedirs(backup_dir) logging.debug("Backup dir has been created %s" , backup_dir) else: logging.debug("Backup dir exists proceed..") checkdir() def countbackups(): """ Clear all existing backups if the variable is set to yes """ if clear_backups == 'yes': for name in sorted(glob.glob('/tmp/backupdir/*backup*.zip')): logging.debug("Existing backup found: %s" , name) logging.debug("Removing the above backup...") else: logging.debug("No existing backups found") countbackups() def logging_setup(): logging.basicConfig(filename=backup_log, level=logging.DEBUG, filemode = 'w', format="%(asctime)s:%(levelname)s:%(message)s") logging_setup() def back_up_zip(): """ Create the zip file, with the date in the front """ logging.debug("\n\t\t\t\t ###### ZIP FILE CONTENTS #######\n") zip_file_name_abs_path = os.path.join(backup_dir, zip_file_name_full) zip_file_name = zipfile.ZipFile(zip_file_name_abs_path, 'w') for root, dirs, files in os.walk(dir_to_backup): zip_file_name.write(root) logging.debug("Adding directories: %s", root) logging.debug("\t Adding subdirs: %s", dirs) for file in files: if not file.endswith(ext_list): logging.debug("\t \tAdding files: %s ", file) zip_file_name.write(os.path.join(root, file), compress_type=zipfile.ZIP_DEFLATED) zip_file_name.close() logging.debug("\n\t\t\t\t ###### END OF ZIP FILE CONTENTS ######\n") logging.debug("Backup file was created: %s" , zip_file_name_abs_path) print("Backup file created") back_up_zip() def send_email(): """ Send an email to the admin with the log file attached """ filename = backup_log attachment = open(filename, 'rb') if email_log_file == 'yes': part = MIMEBase('application', 'octet-stream') part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment', filename= filename) msg.attach(part) text = msg.as_string() server = smtplib.SMTP('smtp.gmail.com: 587') server.starttls() server.login(email_user, email_pass) server.sendmail(email_user, email_send, text) logging.debug("Backup sent to user: %s", email_send) server.quit() print("Email sent") else: logging.debug("Email option not selected") send_email() </code></pre>
[]
[ { "body": "<pre class=\"lang-py prettyprint-override\"><code>import os, sys, zipfile, fnmatch, glob, sys, time, datetime, smtplib, logging\n</code></pre>\n\n<p>is a prime example why you <a href=\"https://www.python.org/dev/peps/pep-0008/#imports\" rel=\"nofollow noreferrer\">should not cram all your imports on a single line</a>. Why? If you have a closer look, you will see that there is a double import of <code>sys</code>.</p>\n\n<p>It is also good practice to group imports by \"topic\", i.e. imports that have similar purposes. Something like</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import os\nimport glob\nimport zipfile\nimport logging\n\nimport datetime\nfrom datetime import date, datetime\n\nimport smtplib\nfrom email import encoders\nfrom email.mime.text import MIMEText\nfrom email.mime.base import MIMEBase\nfrom email.mime.multipart import MIMEMultipart\n</code></pre>\n\n<p>As you can see some of your imports also got lost on the way. Basically it was my IDE (Visual Studio Code) telling me that they're not used in your program. At the moment I'm under Windows so I cannot test run your code, so take that with a grain of caution.</p>\n\n<hr>\n\n<p>Another common practice is to wrap the parts of the code that are supposed to be run as script, with an <a href=\"https://docs.python.org/3/library/__main__.html\" rel=\"nofollow noreferrer\"><code>if name == \"__main__\":</code></a> clause. In order to do that, you should collect all the loose function falls immediately done after the function definition into that block.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if __name__ == \"__main__\":\n logging_setup()\n checkdir()\n countbackups()\n back_up_zip()\n send_email()\n</code></pre>\n\n<hr>\n\n<p>The major issue of your code is the excessive amount of global variables that make up 100% of your data flow between the functions. You should definitely think about wrapping most of the global variables into a <code>main</code> function or however you want to call it, and let your subroutines accept parameters. </p>\n\n<p>Also please don't store user credentials in script files. Everything that is configurable (username, password, email address, smtp server, smtp port) should be stored in an external configuration file and/or environment variables. This also avoids lot of headaches if you ever get tempted to put your script under version control (think GitHub).</p>\n\n<hr>\n\n<p>I will not write much about the core code of your script, but just give a few hints towards minor improvements. I'm sure if there are major issues, other members of the community will pick them up.</p>\n\n<p>The first thing would be string formatting. I think the style from the logging library carried over to the rest of your code. However, the \"old\" <code>%</code> string formatting can be replaced by the much more convenient <a href=\"https://realpython.com/python-f-strings/#f-strings-a-new-and-improved-way-to-format-strings-in-python\" rel=\"nofollow noreferrer\">f-strings</a> in Python 3. They are as easy to use as <code>zip_file_name_full = f\"{todays_date}_{current_time}_{zip_name}\"</code>.</p>\n\n<p>Another best practice that is around quite a bith longer is to use the <a href=\"https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files\" rel=\"nofollow noreferrer\"><code>with</code> statement</a> when handling resources that need to be closed afterwards, such as files. With <code>attachment = open(filename, 'rb')</code> the file won't be closed when leaving the function (the <a href=\"https://stackoverflow.com/a/1834757/5682996\">garbage collector will eventually take care</a> of it). Using <code>with open(filename, 'rb') as attachment:</code> instead ensures that the file gets closed no matter what, including exceptions of any kind in the code. As a matter of fact, <a href=\"https://docs.python.org/3/library/smtplib.html#smtplib.SMTP\" rel=\"nofollow noreferrer\"><code>smtplib.STMP</code></a> may also be used with <code>with</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T13:42:50.417", "Id": "424594", "Score": "0", "body": "Thanks. Ive made some changes as you suggested. Split this out into 2 files, one basically with the configurations, and the other with the functions" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T21:54:48.057", "Id": "219611", "ParentId": "219596", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T17:44:23.873", "Id": "219596", "Score": "2", "Tags": [ "python", "beginner", "python-3.x", "file-system", "email" ], "Title": "Backup program in Python3 for Linux" }
219596
<p>Debugged my page load (was taking 4s...) and I was running 94 queries. 30 of them were the same. I've refactored a little by caching results, but how can I further refactor this class?</p> <p>The project is only half finished, and its already getting... messy.</p> <pre><code>&lt;?php class User extends Authenticatable { use Notifiable; protected $fillable = [ 'name', 'email', 'password', ]; protected $hidden = [ 'password', 'remember_token', ]; protected $casts = [ 'email_verified_at' =&gt; 'datetime', ]; public function courseEntries() { return $this-&gt;hasMany('App\Models\CourseEntry'); } public function lessonEntries() { return $this-&gt;hasMany('App\Models\CourseLessonEntry'); } public function lastCourseEntry() { $this-&gt;courseEntries()-&gt;orderBy('last_interaction', 'DESC')-&gt;first(); } public function classrooms() { return $this-&gt;hasMany('App\Models\Classroom', 'teacher_id', 'id'); } public function lastLessonEntry() { if ($this-&gt;lastCourseEntry() == null) { return null; } return $this-&gt;lessonEntries()-&gt;whereCourseId($this-&gt;lastCourseEntry()-&gt;course_id)-&gt;orderBy('last_interaction', 'DESC')-&gt;first(); } public function lessonsCompleted() { if ($this-&gt;lastCourseEntry() == null) { return 0; } return $this-&gt;lessonEntries()-&gt;whereCourseId($this-&gt;lastCourseEntry()-&gt;course_id)-&gt;whereNotNull('completed_at')-&gt;count(); } public function lastProgress() { $lastCourse = $this-&gt;lastCourseEntry(); return $lastCourse == null ? 0 : $this-&gt;lessonsCompleted() / $lastCourse-&gt;course-&gt;lessons()-&gt;count() * 100; } public function hasCourse($courseId) { if ($this-&gt;isTeacher()) { if ($this-&gt;lastClassroom() == null) { return null; } return $this-&gt;courseEntries()-&gt;where('course_id', $courseId)-&gt;whereClassroomId($this-&gt;lastClassroom()-&gt;id)-&gt;count() &gt; 0; } return $this-&gt;courseEntries()-&gt;where('course_id', $courseId)-&gt;count() &gt; 0; } public function hasCompletedCourse($courseId) { if ($this-&gt;isTeacher()) { if ($this-&gt;lastClassroom() == null) { return null; } return $this-&gt;courseEntries()-&gt;where('course_id', $courseId)-&gt;whereClassroomId($this-&gt;lastClassroom()-&gt;id)-&gt;whereNotNull('completed_at')-&gt;count() &gt; 0; } return $this-&gt;courseEntries()-&gt;where('course_id', $courseId)-&gt;whereNotNull('completed_at')-&gt;count() &gt; 0; } public function hasLesson($courseId, $lessonId) { if ($this-&gt;isTeacher()) { return $this-&gt;lessonEntries()-&gt;whereClassroomId($this-&gt;lastClassroom()-&gt;id)-&gt;where('course_id', $courseId)-&gt;where('lesson_id', $lessonId)-&gt;count() &gt; 0; } return $this-&gt;lessonEntries()-&gt;where('course_id', $courseId)-&gt;where('lesson_id', $lessonId)-&gt;count() &gt; 0; } public function hasCompletedLesson($courseId, $lessonId) { $entry = $this-&gt;getLessonEntry($courseId, $lessonId); return $entry == null ? false : $entry-&gt;count() &gt; 0; } public function getLessonEntry($courseId, $lessonId) { if ($this-&gt;isTeacher()) { return $this-&gt;lessonEntries()-&gt;where('course_id', $courseId)-&gt;where('lesson_id', $lessonId)-&gt;whereClassroomId($this-&gt;lastClassroom()-&gt;id)-&gt;whereNotNull('completed_at')-&gt;first(); } return $this-&gt;lessonEntries()-&gt;where('course_id', $courseId)-&gt;where('lesson_id', $lessonId)-&gt;whereNotNull('completed_at')-&gt;first(); } public function rankInstance() { return $this-&gt;hasOne('App\Models\UserRank', 'id', 'rank'); } public function completedCourses() { return $this-&gt;courseEntries()-&gt;whereNotNull('completed_at')-&gt;get(); } public function notifications() { return $this-&gt;hasMany('App\Models\UserNotification'); } public function notificationCount() { return $this-&gt;notifications()-&gt;where('seen', false)-&gt;count(); } public function lastClassroom() { $lastClassroomId = Auth::user()-&gt;last_classroom; if ($lastClassroomId != 0) { $classroom = Classroom::find($lastClassroomId); if ($classroom != null) { return $classroom; } } $classroom = $this-&gt;classrooms()-&gt;orderBy('id', 'DESC')-&gt;first(); return $classroom; } public function lastCourseForClassroom() { if ($this-&gt;lastClassroom() == null) { return null; } return $this-&gt;courseEntries()-&gt;whereClassroomId($this-&gt;lastClassroom()-&gt;id)-&gt;orderBy('last_interaction', 'DESC')-&gt;first(); } public function lastLessonForClassroom() { if ($this-&gt;lastCourseForClassroom() == null) { return null; } return $this-&gt;lessonEntries()-&gt;where('course_id', $this-&gt;lastCourseForClassroom()-&gt;course_id)-&gt;whereClassroomId($this-&gt;lastClassroom()-&gt;id)-&gt;orderBy('last_interaction', 'DESC')-&gt;first(); } public function getCourses() { return Auth::user()-&gt;courseEntries()-&gt;where(); } public function lessonsCompletedForClassroom() { if ($this-&gt;lastCourseForClassroom() == null) { return 0; } return $this-&gt;lessonEntries()-&gt;whereClassroomId($this-&gt;lastClassroom()-&gt;id)-&gt;where('course_id', $this-&gt;lastCourseForClassroom()-&gt;course-&gt;id)-&gt;whereNotNull('completed_at')-&gt;count(); } public function lastProgressForClassroom() { if ($this-&gt;lastCourseForClassroom() == null) { return 0; } $lastCourse = $this-&gt;lastCourseForClassroom()-&gt;course; return $lastCourse == null ? 0 : $this-&gt;lessonsCompletedForClassroom() / $lastCourse-&gt;lessons()-&gt;count() * 100; } public function completedCoursesForClassroom() { if ($this-&gt;lastClassroom() == null) { return null; } return $this-&gt;courseEntries()-&gt;whereClassroomId($this-&gt;lastClassroom()-&gt;id)-&gt;whereNotNull('completed_at')-&gt;get(); } public function courseEntriesForClassrooom() { if ($this-&gt;lastClassroom() == null) { return null; } return $this-&gt;courseEntries()-&gt;whereClassroomId($this-&gt;lastClassroom()-&gt;id)-&gt;get(); } public function isAdmin() { return $this-&gt;rankInstance == null ? false : $this-&gt;rankInstance-&gt;is_admin == 1; } public function isTeacher() { return $this-&gt;rankInstance == null ? false : ($this-&gt;rankInstance-&gt;is_admin == 1 || $this-&gt;rankInstance-&gt;is_teacher == 1); } public function classroomEntries() { return $this-&gt;hasMany('App\Models\UserClassroomEntry', 'user_id', 'id'); } public function hasInviteToClass($classId) { $this-&gt;classroomEntries()-&gt;where('classroom_id', $classId)-&gt;count(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T18:04:41.010", "Id": "424126", "Score": "0", "body": "The title is too common of a request for this site, since many users are interested in refactoring their code, and many posts utilize laravel and eloquent. Please make the title of the question describe what the code does via [edit]. Maybe you missed the placeholder on the title element: \"_State the task that your code accomplishes. Make your title distinctive._\". Also from [How to Ask](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T18:44:59.723", "Id": "424129", "Score": "0", "body": "4 seconds is a bit too much for 100 queries. 100000 queries would be a more reasonable number. So it seems the problem is not in the quantity but in the quality. Run Laravel profiler and see what's wrong with your queries." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T01:09:30.440", "Id": "424388", "Score": "1", "body": "If you want to talk about a particular page load then you'll need to include the controller and view code as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T01:15:37.800", "Id": "424389", "Score": "0", "body": "However from the code I'm guessing you might want to look into the difference between the Eloquent relationship methods and dynamic properties. This will allow you to use eager loading properly." } ]
[ { "body": "<p>You are not describing the business logic, so for class <code>User</code> that you provided it's possible to give only very general recommendations.</p>\n\n<p>Do not use Authentication in the Model, it's not understandable. Use it in controller or even better in Route:</p>\n\n<pre><code>Route::group(['middleware' =&gt; ['web', 'auth']], function () {\n //put here all routes that need of authenticated user \n});\n</code></pre>\n\n<p>It will redirect Guests to login page.</p>\n\n<p>The methods for models Course, Lesson, Classroom and Notification are more proper to put into appropriate models. In model class User remain just methods for foreign keys where you used hasMany() relation.</p>\n\n<p>Basing on structure as I offer you'll get data from Models using Controllers and not like now using one 'global' model.</p>\n\n<p>Method <code>courseEntries()</code> is good in controller for getting users with course entries as:</p>\n\n<pre><code>$usersWithCourseEntries = User::with('courseEntries')-&gt;get();\n</code></pre>\n\n<p><a href=\"https://laravel.com/docs/5.8/eloquent-relationships#one-to-many\" rel=\"nofollow noreferrer\">Refer to</a>.\nAlso remember, this query will return from DB all users who have course entries and there may be a huge number of results.</p>\n\n<p>Using this method <em>in model</em> as you made:</p>\n\n<pre><code>public function lastCourseEntry() {\n $this-&gt;courseEntries()-&gt;orderBy('last_interaction', 'DESC')-&gt;first();\n }\n</code></pre>\n\n<p>may drive your program to fail. Maybe it's a <em>bottleneck</em> that gives you 4 seconds query execution, but it's just assumption. I didn't try it.</p>\n\n<p>Next:</p>\n\n<p>If you need data returned by some method, for example, <code>coursesEntriesEnded()</code> and in the same controller the data like <code>lastCourseEntryEnded()</code> as last record of data set and similar operations for other models you may not to call these both methods and use something like this to get data from collection that you already have:</p>\n\n<pre><code>$courseModel = new Course();\n$endedCourses = $courseModel-&gt;coursesEntriesEnded;\n$lastCourseEntryEnded = $endedCourses-&gt;orderBy('last_interaction')-&gt;last();\n</code></pre>\n\n<p>it will reduce the DB queries count.</p>\n\n<p>Of course this review is not complete, but for deeper analysis it's needed to know tasks, business logic and to see the rest code of app.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T17:19:44.240", "Id": "429071", "Score": "1", "body": "Thanks for providing an answer. Some of the comments on the answer also indicate that more information would help provide a better review. In a case like this I would recommend you vote to close as **lacks context** instead of providing an answer. Then after more context/code has been added you can add an answer. Protip: there are many other unanswered questions - e.g. [~345 in PHP alone](https://codereview.stackexchange.com/questions/tagged/php?sort=unanswered&pageSize=50)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T18:56:06.917", "Id": "429088", "Score": "0", "body": "@sam-onela, yes, I agree about vote to close as lacks context and will do it next time" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-06T16:51:22.993", "Id": "221792", "ParentId": "219597", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T17:51:00.860", "Id": "219597", "Score": "1", "Tags": [ "php", "laravel" ], "Title": "Laravel executing 100 queries on page load?" }
219597
<p>I'm writing a log table which contains the summary of the claims. The log table logs the data whenever there is an upload.</p> <p>I have written the following SQL query. Though it serves the purpose, I'm trying to learn whether there is any way to simplify the <code>UPDATE</code>s.</p> <pre><code>CREATE TABLE #1 ( id INT IDENTITY(1, 1), [total no claims] INT, [total claims inserted] INT, [total claims errored out] INT, [erroed claims] VARCHAR(max) ) INSERT INTO #1 ([total no claims]) SELECT Count(DISTINCT [claimnumber]) FROM [Operations Productivity Tool].[dbo].[test_importedauditdata] ta WHERE claimnumber IN (SELECT DISTINCT claimnumber FROM [dbo].[opcod audit information] ts WHERE [final status] IN ( 'Finding', 'No Finding' )) AND id = Scope_identity() UPDATE #1 SET [total claims inserted] = (SELECT Count(DISTINCT [claimnumber]) FROM [Operations Productivity Tool].[dbo].[test_importedauditdata] ta WHERE claimnumber NOT IN (SELECT DISTINCT claimnumber FROM [dbo].[opcod audit information] ts WHERE [final status] IN ( 'Finding', 'No Finding' ) )) WHERE id = Scope_identity() UPDATE #1 SET [total claims errored out] = (SELECT [total no claims] - [total claims inserted] FROM #1) WHERE id = Scope_identity() UPDATE #1 SET [erroed claims] = (SELECT Stuff ((SELECT DISTINCT ',' + claimnumber FROM [Operations Productivity Tool].[dbo].[test_importedauditdata] WHERE claimnumber NOT IN (SELECT DISTINCT claimnumber FROM [dbo].[opcod audit information] ts WHERE [final status] NOT IN ( 'Finding', 'No Finding' )) FOR xml path(''), type).value('text()[1]', 'varchar(max)'), 1, 2, '')) WHERE id = Scope_identity() </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T18:15:30.050", "Id": "219598", "Score": "1", "Tags": [ "sql", "sql-server" ], "Title": "Log table with a summary of claims" }
219598
<h3>Function</h3> <p>This class extends the key class, called <a href="https://github.com/emarcier/usco/tree/cb5bf7ebb05af82210510c9ae28aed2a1beee612/master/cron/equity" rel="nofollow noreferrer"><code>EQ</code></a>, and does basic calculation based on minutely data. It then calculates weight coefficients (e.g., [0, 1]) for sectors of equity exchange markets using data from market movers (e.g., <code>AAPL</code>, <code>GOOG</code>, <code>AMZN</code>, <code>NVDA</code>, <code>FB</code>). </p> <p>It works, I'm not so sure about its OOP. </p> <p>Would you be so kind and review it? </p> <h3>SectorCalculations</h3> <pre><code>class SectorCalculations extends EQ implements ConfigConstants { /** * * @var an array of sector movers */ static $sector_movers; /** * * @var a string of current time */ static $current_time; /** * * @var a string of current time */ static $database_file_permission = 0755; public static function calculateSectorCoeffs() { $base_url_api = self::BASE_URL_API . self::TARGET_QUERY_API; $index_data = array("Overall" =&gt; array("sector_weight" =&gt; 1, "sector_coefficient" =&gt; 1, "sector_value" =&gt; 0)); foreach (self::getSectorMovers() as $sector_mover) { $sector_url_api = $base_url_api . implode("%2C", array_keys($sector_mover["selected_tickers"])) . "&amp;types=quote&amp;range=1m"; $raw_sector_json = file_get_contents($sector_url_api); if (ConfigConstants::WRITING_INDICES_SECTOR_DATA_ON_DATABASE == true) { self::writeIndicesOnDatabase($sector_mover["directory"], $raw_sector_json); } $raw_sector_array = json_decode($raw_sector_json, true); // Calculate the real-time index $index_value = 0; foreach ($raw_sector_array as $ticker =&gt; $ticker_stats) { if (isset($sector_mover["selected_tickers"][$ticker], $ticker_stats["quote"], $ticker_stats["quote"]["extendedChangePercent"], $ticker_stats["quote"]["changePercent"], $ticker_stats["quote"]["ytdChange"])) { $change_amount = ($ticker_stats["quote"]["extendedChangePercent"] + $ticker_stats["quote"]["changePercent"] + $ticker_stats["quote"]["ytdChange"]) / 200; $index_value += $sector_mover["sector_weight"] * $sector_mover["selected_tickers"][$ticker] * $change_amount; } } $index_data[$sector_mover["sector"]] = array("sector_weight" =&gt; $sector_mover["sector_weight"], "sector_coefficient" =&gt; $sector_mover["sector_coefficient"], "sector_value" =&gt; $index_value); $index_data["Overall"]["sector_value"] += $index_data[$sector_mover["sector"]]["sector_value"]; } // Calculate the index factor for better visibility between -1 and +1 $front_index_data = array(); foreach ($index_data as $sector_name =&gt; $sector_index_data) { $index_sign = abs($sector_index_data["sector_value"]); $index_factor = 1; for ($i = 0; $i &lt;= 10; $i++) { $index_factor = pow(10, $i); if (($index_factor * $index_sign) &gt; 1) { $index_factor = pow(10, $i - 1); break; } } $front_index_data[$sector_name] = $sector_index_data["sector_weight"] * $sector_index_data["sector_coefficient"] * $sector_index_data["sector_value"] * $index_factor; } $index_sector_file = self::writeFinalJSONforSectorCoeffsOnDatabase(); self::copyFinalSectorCoeffsToFrontDirectory(); if (EQ::isLocalServer()) {echo "YAAAY! " . __METHOD__ . " updated sector coefficients successfully !\n";} return $front_index_data; } public static function copyFinalSectorCoeffsToFrontDirectory() { $sector_dir = __DIR__ . self::LIVE_DATA_DIR_APP; if (!is_dir($sector_dir)) {mkdir($sector_dir, self::getDatabaseFilePermission(), true);} // if data directory did not exist // if s-1 file did not exist if (!file_exists($sector_dir . self::DIR_FRONT_SECTOR_COEF_FILENAME)) { $handle = fopen($sector_dir . self::DIR_FRONT_SECTOR_COEF_FILENAME, "wb"); fwrite($handle, "d"); fclose($handle); } $sector_coef_file = $sector_dir . self::DIR_FRONT_SECTOR_COEF_FILENAME; copy($index_sector_file, $sector_coef_file); } public static function writeFinalJSONforSectorCoeffsOnDatabase() { // Write the index file $index_sector_dir = __DIR__ . self::INDEX_SECTOR_DIR_PREFIX_APP; if (!is_dir($index_sector_dir)) {mkdir($index_sector_dir, self::getDatabaseFilePermission(), true);} $index_sector_file = $index_sector_dir . self::getCurrentTime() . ConfigConstants::EXTENSION_JSON; $index_sector_json = json_encode($front_index_data, JSON_FORCE_OBJECT); $file_handle = fopen($index_sector_file, "a+"); fwrite($file_handle, $index_sector_json); fclose($file_handle); return $index_sector_file; } public static function writeIndicesOnDatabase($sector_mover_database, $raw_sector_json) { // Write the raw file in the back directories $rawSectorDir = __DIR__ . self::EACH_SECTOR_DIR_PREFIX_APP . $sector_mover_database; // if back directory not exist if (!is_dir($rawSectorDir)) {mkdir($rawSectorDir, self::getDatabaseFilePermission(), true);} // create and open/write/close sector data to back directories $rawSectorFile = $rawSectorDir . ConfigConstants::SLASH . self::getCurrentTime() . ConfigConstants::EXTENSION_JSON; $file_handle = fopen($rawSectorFile, "a+"); fwrite($file_handle, $raw_sector_json); fclose($file_handle); } /** * @return a part of class object */ public static function getSectorMovers() { return ConfigConstants::SECTOR_MOVERS_COEFFS; } /** * @return a part of class object */ public static function getCurrentTime() { return date("Y-m-d-H-i-s"); } /** * @return a part of class object */ public static function getDatabaseFilePermission() { return ConfigConstants::DATABASE_FILE_PERMISSION; } } </code></pre> <h3>json_encode($index_data)</h3> <blockquote> <p>{"Overall":{"sector_weight":1,"sector_coefficient":1,"sector_value":0.0009989048910975919},"IT":{"sector_weight":0.18,"sector_coefficient":4,"sector_value":0.0002908602069845678},"Telecommunication":{"sector_weight":0.12,"sector_coefficient":4,"sector_value":8.05578227057372e-5},"Finance":{"sector_weight":0.1,"sector_coefficient":6,"sector_value":9.958073135395748e-5},"Energy":{"sector_weight":0.1,"sector_coefficient":6,"sector_value":8.529905787700634e-5},"Industrials":{"sector_weight":0.08,"sector_coefficient":8,"sector_value":8.477913513820296e-5},"Materials and Chemicals":{"sector_weight":0.08,"sector_coefficient":8,"sector_value":3.149808669009844e-5},"Utilities":{"sector_weight":0.08,"sector_coefficient":8,"sector_value":5.1996127293426994e-5},"Consumer Discretionary":{"sector_weight":0.08,"sector_coefficient":8,"sector_value":9.118133207158268e-5},"Consumer Staples":{"sector_weight":0.06,"sector_coefficient":8,"sector_value":7.264485191327639e-5},"Defense":{"sector_weight":0.04,"sector_coefficient":10,"sector_value":4.648512175199498e-5},"Health":{"sector_weight":0.04,"sector_coefficient":10,"sector_value":1.474285957230441e-5},"Real Estate":{"sector_weight":0.04,"sector_coefficient":10,"sector_value":4.927955774543618e-5}}</p> </blockquote> <h3>Final Sector Coefficients</h3> <p>Sector Coefficients could be between (0, 1): </p> <blockquote> <p>{"Overall":0.9989048910975918,"IT":0.2094193490288888,"Telecommunication":0.38667754898753853,"Finance":0.5974843881237449,"Energy":0.5117943472620381,"Industrials":0.542586464884499,"Materials and Chemicals":0.20158775481663005,"Utilities":0.33277521467793275,"Consumer Discretionary":0.5835605252581292,"Consumer Staples":0.3486952891837267,"Defense":0.18594048700797994,"Health":0.058971438289217644,"Real Estate":0.19711823098174472}</p> </blockquote> <h3>$ticker_stats sample</h3> <p>Quote array can be viewed in <a href="https://iextrading.com/developer/docs/#quote" rel="nofollow noreferrer">this link</a>:</p> <pre><code>{ "symbol": "AAPL", "companyName": "Apple Inc.", "primaryExchange": "Nasdaq Global Select", "sector": "Technology", "calculationPrice": "tops", "open": 154, "openTime": 1506605400394, "close": 153.28, "closeTime": 1506605400394, "high": 154.80, "low": 153.25, "latestPrice": 158.73, "latestSource": "Previous close", "latestTime": "September 19, 2017", "latestUpdate": 1505779200000, "latestVolume": 20567140, "iexRealtimePrice": 158.71, "iexRealtimeSize": 100, "iexLastUpdated": 1505851198059, "delayedPrice": 158.71, "delayedPriceTime": 1505854782437, "extendedPrice": 159.21, "extendedChange": -1.68, "extendedChangePercent": -0.0125, "extendedPriceTime": 1527082200361, "previousClose": 158.73, "change": -1.67, "changePercent": -0.01158, "iexMarketPercent": 0.00948, "iexVolume": 82451, "avgTotalVolume": 29623234, "iexBidPrice": 153.01, "iexBidSize": 100, "iexAskPrice": 158.66, "iexAskSize": 100, "marketCap": 751627174400, "peRatio": 16.86, "week52High": 159.65, "week52Low": 93.63, "ytdChange": 0.3665, } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-09T18:15:39.317", "Id": "425106", "Score": "1", "body": "Please keep in mind that ordinarily the code within questions should *not* be changed after reviews have arrived. Since in this instance it's on the only answerer's request we'll allow it, but please take a look at *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<p>I don't see a great deal to refine with this snippet -- good work.</p>\n\n<ul>\n<li><p><code>$ticker_stats[\"quote\"],</code> can be safely omitted from the <code>isset()</code> call because the subsequent checks on its subarrays will do the necessary work. Good work supplying multiple parameters to a single <code>isset()</code> call.</p></li>\n<li><p>I may be able to refine the following section, but would need realistic sample input to be sure.</p>\n\n<pre><code>foreach ($raw_sector_array as $ticker =&gt; $ticker_stats) {\n if (isset($sector_mover[\"selected_tickers\"][$ticker], $ticker_stats[\"quote\"], $ticker_stats[\"quote\"][\"extendedChangePercent\"], $ticker_stats[\"quote\"][\"changePercent\"], $ticker_stats[\"quote\"][\"ytdChange\"])) {\n\n $change_amount = ($ticker_stats[\"quote\"][\"extendedChangePercent\"] + $ticker_stats[\"quote\"][\"changePercent\"] + $ticker_stats[\"quote\"][\"ytdChange\"]) / 200;\n $index_value += $sector_mover[\"sector_weight\"] * $sector_mover[\"selected_tickers\"][$ticker] * $change_amount;\n }\n}\n\n$index_data[$sector_mover[\"sector\"]] = array(\"sector_weight\" =&gt; $sector_mover[\"sector_weight\"], \"sector_coefficient\" =&gt; $sector_mover[\"sector_coefficient\"], \"sector_value\" =&gt; $index_value);\n$index_data[\"Overall\"][\"sector_value\"] += $index_data[$sector_mover[\"sector\"]][\"sector_value\"];\n</code></pre></li>\n<li><p>Rather than performing iterated \"guess &amp; check\" arithmetic operations to determine the <code>$index_factor</code>, I think a non-iterative string check should be more direct/efficient. You might write an implementation of Barmar's solution: <a href=\"https://stackoverflow.com/a/19801446/2943403\">PHP - Find the number of zeros in a decimal number</a> or a regex based approach: (though I'll admit it is a little challenging to interpret at a glance)</p>\n\n<pre><code>$float = abs($float);\n$factor = pow(10, preg_match_all('~(?:^0?\\.|\\G(?!^))0~', $float)))\n</code></pre>\n\n<p><a href=\"https://regex101.com/r/SmlRp5/3\" rel=\"nofollow noreferrer\">https://regex101.com/r/SmlRp5/3</a></p>\n\n<p>If the above doesn't work for all of your cases (like <code>$float = 0</code>) you can write a earlier condition to shortcut a precise <code>0</code> to not receive a factor - but I reckon that this is not an expected case.</p>\n\n<p><h2>Hmm, on second thought, there's greater stability to be had from using pure arithmetic. String-based processes are vulnerable to challenges dealing with scientific notation.</h2> I have added <a href=\"https://stackoverflow.com/a/55968143/2943403\">a new answer</a> to the earlier mentioned StackOverflow page that Barmar answered.</p></li>\n<li><p>For consistency, write all <code>if</code> blocks over multiple lines. The reduction in lines is not worth the reduction in readability.</p></li>\n</ul>\n\n<hr>\n\n<p>Some late advice...</p>\n\n<pre><code>$index_data[\"Overall\"][\"sector_value\"] += $index_data[$sector_mover[\"sector\"]][\"sector_value\"];\n</code></pre>\n\n<p>Is easier to read as:</p>\n\n<pre><code>$index_data[\"Overall\"][\"sector_value\"] += $index_value;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T10:01:01.727", "Id": "424211", "Score": "1", "body": "@Emma On second thought, the more I research my advice on finding the `$factor` using string techniques, the more I am worried about running into conflicts with scientific notation. Do you have some sample floats that I can run some tests on?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-09T07:53:59.787", "Id": "425012", "Score": "2", "body": "May I see what associative elements are in a single `$ticker_stats`? More specifically, which keys are in the `quote` subarray." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T22:38:47.447", "Id": "219614", "ParentId": "219601", "Score": "2" } } ]
{ "AcceptedAnswerId": "219614", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T18:59:57.183", "Id": "219601", "Score": "1", "Tags": [ "beginner", "php", "object-oriented", "json", "finance" ], "Title": "Simple calculation of sector coefficients using PHP" }
219601
<p>My Code measures the longest path, not allowing cycles. For the example input below, the longest chain would be 4</p> <p>Please can you review my code?</p> <pre><code>import numpy as np inputgrid = np.array([['.','.','.','.','.'], ['C','-','C','-','C'], ['.','.','|','.','.'], ['.','.','C','.','.'], ['.','.','|','.','.'], ['.','.','C','.','.'], ['.','.','.','.','.']])# This Is Input inputgrid = np.where(inputgrid=='.', 0, inputgrid) inputgrid = np.where(inputgrid=='C', 1, inputgrid) inputgrid = np.where(inputgrid=='-', 9, inputgrid) inputgrid = np.where(inputgrid=='|', 9, inputgrid) np.array(inputgrid).tolist() grid = [[int(item) for item in row] for row in inputgrid] def display(grid): for row in grid: print(row) display(grid) lst = [] for rows, row in enumerate(grid): for cols, col in enumerate(row): if grid[rows][cols] in [1]: lst.append((rows, cols)) bondlst = [] for rows, row in enumerate(grid): for cols, col in enumerate(row): if grid[rows][cols] in [9]: bondlst.append((rows, cols)) print(lst) print(bondlst) bondx = [] bondy = [] for item in bondlst: (bondx).append(item[0]) (bondy).append(item[1]) print(bondx) print(bondy) adjacencylist = [] def adjacentnode(nodea ,nodeb): if nodea[0] == nodeb[0] and nodea[1] == nodeb[1]+2: adjacent = True elif nodea[0] == nodeb[0] and nodea[1] == nodeb[1]-2: adjacent = True elif nodea[1] == nodeb[1] and nodea[0] == nodeb[0]+2: adjacent = True elif nodea[1] == nodeb[1] and nodea[0] == nodeb[0]-2: adjacent = True else: adjacent = False return adjacent print (adjacentnode((1,0),(1,2))) count = 0 tempgraph = {} for node in range(len(lst)): print (node) adjacencylist.append((lst[node] ,[])) for neighbour in range(len(lst)): adjacentnodes = (adjacentnode(lst[node] ,lst[neighbour])) print(adjacentnodes) if adjacentnodes == True: count = count +1 adjacencylist[node][1].append(lst[neighbour]) # adjacencylist.append((lst[node],[])) # adjacencylist.append(lst[node]) # adjacencylist.append(lst[neighbour]) print (count) print (adjacencylist) for item in adjacencylist: tempgraph[str(item[0])] = (item[(1)]) carbongraph = {} for i in tempgraph: carbongraph[i] = [str(k) for k in tempgraph[i]] print(carbongraph) #print(adjacencylist) #print (carbongraph) ''' carbongraph = {'(0, 1)' :['(0, 2)'], '(0, 2)' :['(0, 1)' ,'(0, 3)' ,'(1, 2)'], '(0, 3)' :['(0, 2)'], '(1, 2)' :['(0, 2)', '(2, 2)'], '(2, 2)': ['(1, 2)']} WEIGHTS = 1 ''' def shortestpath(graph, start, end, path=[]): path = path + [start] if start == end: return path if start not in graph: return None for node in graph[start]: if node not in path: newpath = shortestpath(graph, node, end, path) if newpath: return newpath return None LeafArray = [] for leaf in carbongraph: degree = (len(carbongraph[leaf])) if degree == 1: LeafArray.append(leaf) print(LeafArray) chainlist = [] for node in LeafArray: for neighbour in LeafArray: currentpath = (shortestpath(carbongraph, node, neighbour)) carbonchain = len(currentpath) print(currentpath) chainlist.append(carbonchain) longestchain = max(chainlist) print(longestchain) def Prfix(): global prefix if longestchain == 4: prefix = "But" elif longestchain == 5: prefix = "Pent" elif longestchain == 6: prefix = "Hex" elif longestchain == 7: prefix = "Hept" elif longestchain == 8: prefix = "Oct" return prefix print(Prfix()) <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>Welcome back to CodeReview. Your code and your problem seemed familiar, so I searched and found your previous attempt. This version runs to completion on my machine, so congratulations!</p>\n\n<h1>What is this?</h1>\n\n<p>First, I have to ask, what are you doing? The code runs to completion, and prints an answer that looks like what you're trying to get, but that answer is lost in the noise of a bunch of other stuff. This is nuts! When you're asking for review, you want to make sure everything is clear. Please, make your output more clear!</p>\n\n<pre><code>$ python carbon.py\n[0, 0, 0, 0, 0]\n[1, 9, 1, 9, 1]\n[0, 0, 9, 0, 0]\n[0, 0, 1, 0, 0]\n[0, 0, 9, 0, 0]\n[0, 0, 1, 0, 0]\n[0, 0, 0, 0, 0]\n[(1, 0), (1, 2), (1, 4), (3, 2), (5, 2)]\n[(1, 1), (1, 3), (2, 2), (4, 2)]\n[1, 1, 2, 4]\n[1, 3, 2, 2]\nTrue\n0\nFalse\nTrue\nFalse\nFalse\nFalse\n1\nTrue\nFalse\nTrue\nTrue\nFalse\n2\nFalse\nTrue\nFalse\nFalse\nFalse\n3\nFalse\nTrue\nFalse\nFalse\nTrue\n4\nFalse\nFalse\nFalse\nTrue\nFalse\n8\n[((1, 0), [(1, 2)]), ((1, 2), [(1, 0), (1, 4), (3, 2)]), ((1, 4), [(1, 2)]), ((3, 2), [(1, 2), (5, 2)]), ((5, 2), [(3, 2)])]\n{'(1, 0)': ['(1, 2)'], '(1, 2)': ['(1, 0)', '(1, 4)', '(3, 2)'], '(1, 4)': ['(1, 2)'], '(3, 2)': ['(1, 2)', '(5, 2)'], '(5, 2)': ['(3, 2)']}\n['(1, 0)', '(1, 4)', '(5, 2)']\n['(1, 0)']\n['(1, 0)', '(1, 2)', '(1, 4)']\n['(1, 0)', '(1, 2)', '(3, 2)', '(5, 2)']\n['(1, 4)', '(1, 2)', '(1, 0)']\n['(1, 4)']\n['(1, 4)', '(1, 2)', '(3, 2)', '(5, 2)']\n['(5, 2)', '(3, 2)', '(1, 2)', '(1, 0)']\n['(5, 2)', '(3, 2)', '(1, 2)', '(1, 4)']\n['(5, 2)']\n4\nBut\n</code></pre>\n\n<h1>Why use <code>numpy</code>?</h1>\n\n<p>Next question: why are you using <code>numpy</code>? Here's the top of your code:</p>\n\n<pre><code>import numpy as np\ninputgrid = np.array([['.','.','.','.','.'],\n ['C','-','C','-','C'],\n ['.','.','|','.','.'],\n ['.','.','C','.','.'],\n ['.','.','|','.','.'],\n ['.','.','C','.','.'],\n ['.','.','.','.','.']])# This Is Input\n\n\ninputgrid = np.where(inputgrid=='.', 0, inputgrid)\ninputgrid = np.where(inputgrid=='C', 1, inputgrid)\ninputgrid = np.where(inputgrid=='-', 9, inputgrid)\ninputgrid = np.where(inputgrid=='|', 9, inputgrid)\n\nnp.array(inputgrid).tolist()\n\ngrid = [[int(item) for item in row] for row in inputgrid]\n</code></pre>\n\n<p>You import numpy, create a numpy 2d array, process it minimally, and then convert the numpy array into a standard Python list of lists.</p>\n\n<p>My first suggestion is this: stop using numpy. You aren't doing anything (yet) that justifies numpy. (Numpy isn't bad. But numpy is for numbers, and you're doing graphs. Maybe use a graph package instead?)</p>\n\n<h1>Style</h1>\n\n<p>I have two major objections to your code as presented. First, much of your code is \"up against the wall\" -- you are writing code that is executed immediately, rather than put it into functions that allow you to call or not-call your code as you like, and which furthermore logically group related parts of your code together. Please organize your code into descriptive functions!</p>\n\n<p>Second, towards the end you have functions <code>shortestpath</code> and <code>Prfix</code>. Those are both <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP-8</a> violations. They should be <code>shortest_path</code> and <code>prefix</code> respectively. Every time you ask a question on here, you're going to get dinged for not following PEP8, so ... <strong>CONFORM!!!</strong></p>\n\n<h1>Organization</h1>\n\n<p>As I see it, your code does a few things in sequence:</p>\n\n<ul>\n<li><p>Converts a text representation of a molecule into a data structure of some kind.</p></li>\n<li><p>Builds an adjacency graph</p></li>\n<li><p>Computes the length of the longest carbon chain</p></li>\n<li><p>Prints the length of the longest chain</p></li>\n<li><p>Prints a prefix?</p></li>\n</ul>\n\n<p>Let's see if we can improve on those.</p>\n\n<h2>Input</h2>\n\n<p>You represent your input as an ndarray, carefully and meticulously (&amp; painfully) entered, with each element requiring 4 keystrokes: <code>'C',</code> (apostrophe, C, apostrophe, comma). That's not going to scale very well, and it's going to be very prone to errors. </p>\n\n<p>I suggest you use Python's triple-quoted strings to create a single large block of text, and then parse that as a text-processing problem in order to get your data:</p>\n\n<pre><code>Molecule = \"\"\"\n\n C-C-C\n |\n C\n |\n C\n\n\"\"\".strip()\n</code></pre>\n\n<p>You should strip all the starting and stopping whitespace, since that contributes nothing. You should remove tabs, replacing them with spaces in a rational way. The <code>str.expandtabs()</code> method will do that for you. You can then look at <code>textwrap.dedent</code> to evenly remove leading whitespace. This will give you a \"minimal\" ASCII-picture to parse for your graph.</p>\n\n<p>If you have learned classes, I suggest you create an <code>Atom</code> class for your initial data structure. You can use it to build up the graph:</p>\n\n<pre><code>class Atom:\n def __init__(self, element='C', bonds=[]):\n self.element = element\n self.bonds = bonds\n</code></pre>\n\n<p>I don't know if this is meaningful in your case, but some graphs I have seen use multiple lines to indicate bonds, like:</p>\n\n<pre><code>C=C-C\n</code></pre>\n\n<p>Depending on what you're using this for, you may or may not care about that. You could just store that as a tuple in the bonds list, or create a duplicate bond entry, or a separate \"weights\" list to maintain in parallel, or create a <code>Bond</code> class that would represent the link and the number, etc.</p>\n\n<h2>Path length</h2>\n\n<p>There are a lot of ways to do path length. If you want to support large molecules or arbitrary diagrams, you might want to look at a package graph library. For example, what should your code return given this diagram?</p>\n\n<pre><code>C-C C-C-C\n</code></pre>\n\n<p>Is that two molecules? Should it return the longest (3) or a list of the various longest-paths ([2, 3]) or what? It's up to you. I'd suggest that this is an error in input. But if you try to support this, it will change what graphing approach you use, since connectivity is a major concern in most graph traversal algorithms.</p>\n\n<p>If you elect do compute path length yourself, you will likely find that a simple recursive traversal works for most simple cases (depth-first search). Just compute the max length of each outward bond, then sum the two highest.</p>\n\n<h2>Bug</h2>\n\n<p>Beware of this bug in your current code:</p>\n\n<pre><code>C-C\n| |\nC C\n</code></pre>\n\n<p>Your <code>adjacentnode</code> function doesn't check the intervening space, so it considers the bottom two carbons to be \"adjacent\" (which is true) but you're using that for your adjacency list computation (which would be wrong).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T23:26:50.537", "Id": "219615", "ParentId": "219602", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T19:51:19.187", "Id": "219602", "Score": "6", "Tags": [ "python", "algorithm", "graph", "numpy" ], "Title": "Longest carbon chain" }
219602
<p>I have the following code to find the minimum <code>sbyte</code> value in an array. It is using <code>System.Runtime.Intrinsics</code> to perform a SIMD min on chunks of the array, and then loops over the resulting vector to find the true minimum.</p> <pre><code>public static sbyte Min( sbyte[] array ) { if( array.Length &lt;= 0 ) return 0; var length = array.Length; var stepSize = Vector128&lt;sbyte&gt;.Count; fixed ( sbyte* pStep = &amp;array[ 0 ] ) { var i = stepSize; var minVector = Avx.LoadVector128( pStep ); for( ; i &lt;= length - stepSize; i += stepSize ) minVector = Avx.Min( minVector, Avx.LoadVector128( pStep + i ) ); var _ = stackalloc sbyte[ stepSize ]; Avx.Store( _, minVector ); // Find min of minVector var min = sbyte.MaxValue; for( var j = 0; j &lt; stepSize; j++ ) if( min &gt; _[ j ] ) min = _[ j ]; // Evaluate remaining elements if( i &lt; length ) while( i &lt; length ) { if( min &gt; pStep[ i ] ) min = pStep[ i ]; i++; } return min; } } </code></pre> <p>I feel like this is a slightly excessive amount of code, but seeing how this function is meant to handle arrays with lengths that can't be equally partitioned into a 128-bit register, I'm not sure if there's any cleaner way to do this. </p> <p>I do intend to implement this method for all supported primitive types, but it seems like most of the code will just be duplicated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T07:07:47.603", "Id": "424186", "Score": "0", "body": "`var _` - what an _unconventional_ variable name is this? o_O I'm also giving you a -1 for that because it's just impolite to use names like this one and expect people to understand your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T08:15:39.727", "Id": "424191", "Score": "3", "body": "While I don't share t3ch0t's sentiment completely, `_` is a terrible variable name, and is now used as a [discard](https://docs.microsoft.com/en-us/dotnet/csharp/discards), which may create confusion." } ]
[ { "body": "<h2>Correctness</h2>\n\n<pre><code> if( array.Length &lt;= 0 )\n return 0;\n</code></pre>\n\n<p>This piece of code is suspicious. Maybe you should return <code>sbyte.MaxValue</code>, maybe <code>null</code>, or maybe throw <code>ArgumentException</code>. (I can imagine that there were a <code>Max</code> method, both, together is used to find the range of values, then maybe <code>0</code> is a valid return value.) This is one of the rare times I'd appreciate a comment to explain such extrinsic information.</p>\n\n<h2>Useless Code</h2>\n\n<pre><code> if( i &lt; length )\n while( i &lt; length )\n</code></pre>\n\n<p>Lose the <code>if</code>.</p>\n\n<h2>Excessive code</h2>\n\n<p>When you are operating on fixed size chunks, \n - pad the input with some appropriate value (<code>sbyte.MaxValue</code>)\n - handle the last fixed size chunk of the input separately.</p>\n\n<p>The last suggestion should read something like this, (which means I don't even guarantee that it will compile):</p>\n\n<pre><code>if (length &lt; stepSize)\n throw new ArgumentException($\"this method cannot be used for arrays shorter than {stepSize}\") \n\nVector128&lt;sbyte&gt; minVector;\nSetAllVector128(minVector, sbyte.MaxValue);\nfor (var i = 0; i &lt; length - stepSize; i += stepSize)\n minVector = Avx.Min(minVector, Avx.LoadVector128(pStep + i));\n\nminVector = Avx.Min(minVector, Avx.LoadVector128(pStep + length - stepSize));\n</code></pre>\n\n<p>Then you can use the last loop altogether;</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T07:53:46.727", "Id": "424188", "Score": "0", "body": "+1; I don't think there is any need to do the 'padding'; you can just load the first/final vector before the loop, and it will be fine. I think you can put a +1 in the loop condition so that it doesn't run the final block twice if `length % stepSize == 0`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T07:38:23.070", "Id": "219623", "ParentId": "219603", "Score": "3" } }, { "body": "<p>As mentioned by others it's a problem when the size of the input array is lesser than <code>Vector128&lt;sbyte&gt;.Count</code>. You can handle it by taking the min of the two as <code>stepSize</code>:</p>\n\n<pre><code>int stepSize = Math.Min(Vector128&lt;sbyte&gt;.Count, array.Length);\n</code></pre>\n\n<p>This is safe because the first for-loop will only run if <code>stepSize &gt; vector size</code> and the first <code>while-loop</code> will only iterate the actual number of elements in <code>array</code>.</p>\n\n<hr>\n\n<p>Alternatively you can make some proper input checks like:</p>\n\n<pre><code> if (array == null) throw new ArgumentNullException(nameof(array));\n if (array.Length == 0) throw new InvalidOperationException(\"Input must contains data.\");\n\n if (array.Length &lt; Vector128&lt;sbyte&gt;.Count)\n return array.Min();\n</code></pre>\n\n<p>You should do the first two checks anyway...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T08:19:12.807", "Id": "424192", "Score": "0", "body": "You still need to explicitly avoid any calls to `LoadVector128` (e.g. the first in the OP, the last in abuzittin gillifirca's answer). I'm assuming that it could seg-fault (at some level), but even if it doesn't blow up it is not polite to read memory you can't control. I also think an explicit check (like abuzittin gillifirca's, though it needn't throw) would be better because it makes the intention clear, whereas setting up loops so that they implicitly don't run is a bit cryptic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T08:31:12.113", "Id": "424196", "Score": "0", "body": "@VisualMelon: I don't see your point. The minimum stepSize prevents effectively reading uncontrolled memory." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T08:43:22.947", "Id": "424200", "Score": "0", "body": "I mean - for example in the OP's code - that even if the `for` loop cycles, that `var minVector = Avx.LoadVector128( pStep );` will. It's not impossible I'm completely confused." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T08:48:32.250", "Id": "424201", "Score": "0", "body": "@VisualMelon: OK, but if `array.Length < Vector128<sbyte>.Count`, the result is a vector padded with `0´ (defaults). Is seems safe to use by me :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T08:57:56.940", "Id": "424206", "Score": "0", "body": "I don't know, it just feels wrong to me ;) It necessarily involves reading beyond the length of the array, and you can't make assumptions about whether you own that memory or not (maybe the structure of the HEAP in the CLR means it's safe enough, but that's an implementation detail). Your second piece of code would make me much happier indeed!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T08:07:52.083", "Id": "219626", "ParentId": "219603", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T20:12:24.073", "Id": "219603", "Score": "5", "Tags": [ "c#", ".net", "simd" ], "Title": "Finding min value of an array using SIMD" }
219603
<p>I am trying to puzzle out api based user registration for a service I am building, but I have a strong feeling that my code is not optimal.</p> <p>It feels like passing "state" in the way I did prevents the server from being multithreaded, as I have no clue how actix could share data that isn't Send or Sync across multiple threads.</p> <p>I also interact with DynamoDb by using a <code>.sync()</code> call on the request, which means that i block on waiting for Dynamo to respond to me. This seems like it would be bad for performance of a web server but I don't know how to avoid it without something like async/await.</p> <p>Another issue is that I cannot guarantee that a user has a unique email without making a second table in Dynamo. I don't want to expose a user's email to the outside world, so for everything else I would need to use some sort of other unique identifier (here I went with a uuid), but for registration I would still need to check that requirement...somehow. But if I make a second table I introduce the possibility of an inconsistent state since to my knowledge I can't make dynamo affect two tables atomically.</p> <p>I also just returned out the created user id to the client, but is there something more useful I could have done? Should I return a token in this response? More info about the created user?</p> <p>Any and all feedback would be greatly appreciated.</p> <pre class="lang-rust prettyprint-override"><code>use actix_web::error::InternalError; use actix_web::http::StatusCode; use actix_web::{http, server, App, Json, Responder, State}; use bcrypt; use core::borrow::Borrow; use core::fmt; use failure::Error; use hocon::HoconLoader; use log::{info, warn, Level}; use maplit::hashmap; use rusoto_core::{Region, RusotoError}; use rusoto_dynamodb::{ AttributeDefinition, AttributeValue, BatchWriteItemInput, CreateTableInput, DynamoDb, DynamoDbClient, GetItemInput, GetItemOutput, KeySchemaElement, ProvisionedThroughput, PutItemInput, PutRequest, WriteRequest, }; use serde::{Deserialize, Serialize}; use serde_dynamodb; use simple_logger; use std::collections::HashMap; use std::fmt::{Debug, Formatter}; use std::str::FromStr; use uuid::Uuid; type DynamoRecord = HashMap&lt;String, AttributeValue&gt;; /// The info we need from a person in order to create a user for them. #[derive(Serialize, Deserialize)] pub struct UserRegistrationInfo { email: String, password: String, } impl Debug for UserRegistrationInfo { fn fmt(&amp;self, f: &amp;mut Formatter) -&gt; fmt::Result { write!( f, "UserRegistrationInfo {{ email = {:?}, password = &lt;SENSITIVE&gt; }}", self.email ) } } /// The canonical user record that is actually stored in the database. #[derive(Serialize, Deserialize, Debug)] pub struct User { id: String, email: String, hashed_password: String, } impl User { /// Creates a User from the bare minimum info we received from the user. Note that /// this function is not pure as it involves at the very least generation of a unique /// id for the user. pub fn from_registration_info(registration_info: UserRegistrationInfo) -&gt; User { User { id: Uuid::new_v4().to_string(), email: registration_info.email, hashed_password: bcrypt::hash(registration_info.password, bcrypt::DEFAULT_COST) .unwrap(), } } fn to_dynamo(&amp;self) -&gt; serde_dynamodb::error::Result&lt;DynamoRecord&gt; { Ok(serde_dynamodb::to_hashmap(self)?) } fn from_dynamo(m: DynamoRecord) -&gt; serde_dynamodb::error::Result&lt;User&gt; { serde_dynamodb::from_hashmap(m) } } pub struct System { pub config: Config, pub dynamo_db: DynamoDbClient, } impl System { pub fn from_config(config: Config) -&gt; System { let dynamo_db = DynamoDbClient::new(config.aws_region()); System { config, dynamo_db } } } /// The data returned to the user in the event that they successfully register a user #[derive(Serialize)] struct SuccessfulRegistration { user_id: String, } fn register( registration_info: Json&lt;UserRegistrationInfo&gt;, state: State&lt;System&gt;, ) -&gt; Result&lt;impl Responder, failure::Error&gt; { info!("Creating a new user"); let new_user: User = User::from_registration_info(registration_info.into_inner()); let put_result = state .dynamo_db .put_item(PutItemInput { table_name: String::from("chat_users"), item: new_user.to_dynamo().unwrap(), ..PutItemInput::default() }) .sync()?; state .dynamo_db .batch_write_item(BatchWriteItemInput { request_items: hashmap! { state.config.users_table() =&gt; vec![ WriteRequest { put_request: Some(PutRequest { item: new_user.to_dynamo().unwrap() }), ..WriteRequest::default() } ], state.config.login_table() =&gt; vec![ WriteRequest { put_request: Some(PutRequest { item: new_user.to_dynamo().unwrap() }), ..WriteRequest::default() } ] }, ..BatchWriteItemInput::default() }) .sync()?; info!("Successfully created a new user"); Ok(actix_web::HttpResponse::Ok().json(SuccessfulRegistration { user_id: new_user.id, })) } /// Creates the user table. Note: Dynamo doesn't have a "create if not exists" so this needs /// to be externalized to a good ol' cloudformation script or similar. fn create_tables( client: &amp;DynamoDbClient, ) -&gt; rusoto_core::RusotoResult&lt;(), rusoto_dynamodb::CreateTableError&gt; { client .create_table(CreateTableInput { attribute_definitions: vec![AttributeDefinition { attribute_name: "id".to_string(), attribute_type: "S".to_string(), }], provisioned_throughput: Some(ProvisionedThroughput { read_capacity_units: 5, write_capacity_units: 5, }), key_schema: vec![KeySchemaElement { attribute_name: "id".to_string(), key_type: "HASH".to_string(), }], table_name: "chat_users".to_string(), ..CreateTableInput::default() }) .sync()?; Ok(()) } #[derive(Debug, Clone)] pub struct Config { aws_region: Region, users_table: String, login_table: String, } impl Config { pub fn aws_region(&amp;self) -&gt; Region { self.aws_region.clone() } pub fn users_table(&amp;self) -&gt; String { self.users_table.clone() } pub fn login_table(&amp;self) -&gt; String { self.login_table.clone() } fn load() -&gt; Result&lt;Config, failure::Error&gt; { let hocon = HoconLoader::new() .load_file("./application.conf")? .hocon()?; let aws_region = match hocon["aws"]["region"] .as_string() .as_ref() .map(String::as_str) { Some("local") =&gt; { info!("Using \"local\" as our AWS region"); Region::Custom { name: "local".to_string(), endpoint: "http://localhost:8000".to_string(), } } Some(region) =&gt; Region::from_str(region).unwrap_or_else(|_| { warn!("Unknown region: {:?}, defaulting to us-west-2", region); Region::UsWest2 }), None =&gt; { warn!("No region provided, defaulting to us-west-2"); Region::UsWest2 } }; let users_table = hocon["dynamo"]["users_table"].as_string().unwrap(); let login_table = hocon["dynamo"]["login_table"].as_string().unwrap(); Ok(Config { aws_region, users_table, login_table, }) } } fn main() -&gt; Result&lt;(), Box&lt;std::error::Error&gt;&gt; { simple_logger::init_with_level(Level::Info).unwrap(); let config = Config::load()?; server::new(move || { App::with_state(System::from_config(config.clone())).route( "/register", http::Method::POST, register, ) }) .bind("127.0.0.1:8080") .unwrap() .run(); Ok(()) } <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T20:18:29.070", "Id": "219605", "Score": "3", "Tags": [ "api", "rust", "amazon-web-services" ], "Title": "User registration in Actix w/ DynamoDB" }
219605
<p>I'm learning Go and I wrote this for a programming challenge. It is working (building and running) but I feel the code is not what Go code should be.</p> <p>I used an OOP design. Is it correctly implemented in GO ? </p> <p>In my main, I will call the method <code>pod.playTurn(target, speed)</code></p> <pre><code>package main import ( "fmt" "math" "os" "strconv" ) // Dot is king type Dot struct { x, y int } // Pod is life type Pod struct { position Dot vx, vy, angle, nextCpID int hasShieldOn bool } func squaredDist(a, b Dot) int { return (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) } func distance(a, b Dot) float64 { return math.Sqrt(float64(squaredDist(a, b))) } func (pod Pod) getAngle(p Dot) float64 { d := distance(p, pod.position) dx := float64(p.x-pod.position.x) / d dy := float64(p.y-pod.position.y) / d a := math.Acos(dx) * 180.0 / math.Pi // If the point I want is below me, I have to shift the angle for it to be correct if dy &lt; 0 { a = 360.0 - a } return a } func (pod Pod) diffAngle(p Dot) float64 { a := pod.getAngle(p) pangle := float64(pod.angle) right := 0.0 if pangle &lt;= a { right = a - pangle } else { right = 360.0 - pangle + a } left := 0.0 if pangle &gt;= a { left = pangle - a } else { left = pangle + 360.0 - a } if right &lt; left { return right } return -left } func (pod Pod) rotate(p Dot) int { a := pod.diffAngle(p) // Can't turn more than 18° in one turn ! if a &gt; 18.0 { a = 18.0 } else if a &lt; -18.0 { a = -18.0 } pod.angle += int(math.Round(a)) if pod.angle &gt;= 360.0 { pod.angle = pod.angle - 360.0 } else if pod.angle &lt; 0.0 { pod.angle += 360.0 } return pod.angle } func (pod Pod) boost(t int) (int, int) { if pod.hasShieldOn { return pod.vx, pod.vy } pangle := float64(pod.angle) pod.vx += int(math.Round(math.Cos(pangle) * float64(t))) pod.vy += int(math.Round(math.Sin(pangle) * float64(t))) return pod.vx, pod.vy } // t shoud become a float later on func (pod Pod) move(t int) (int, int) { pod.position.x += pod.vx * t pod.position.y += pod.vy * t return pod.position.x, pod.position.y } func (pod Pod) endTurn() (int, int) { // todo rounding position if needed pod.vx = int(float64(pod.vx) * 0.85) pod.vy = int(float64(pod.vy) * 0.85) return pod.vx, pod.vy } func (pod Pod) playTurn(p Dot, t int) { pod.angle = pod.rotate(p) pod.vx, pod.vy = pod.boost(t) pod.position.x, pod.position.y = pod.move(1) pod.vx, pod.vy = pod.endTurn() fmt.Fprintf(os.Stderr, "\nPredicted Pod position : ") fmt.Fprintf(os.Stderr, "\n(%d, %d) speed (%d,%d)", pod.position.x, pod.position.y, pod.vx, pod.vy) } </code></pre> <p>Am I using struct correctly ? Is it acceptable object oriented code ? </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T20:57:36.747", "Id": "424142", "Score": "0", "body": "Splitting my too general previous issue into targeted bit. Reference here : https://codereview.stackexchange.com/questions/216074/writing-go-object-code-that-respects-go-guidelines" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T05:31:38.823", "Id": "424174", "Score": "0", "body": "Did you test it? Does it produce agreeable results?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T12:36:38.103", "Id": "424588", "Score": "0", "body": "Yeah, it's running. But it feels so clumsy to call a method on a pod object to have to assigned the result back to the calling object : `pod.angle = pod.rotate(p)` Am I doing it right? Moreover, I want to optimize later in order to run as many `playTurn` as I can in a limited time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T13:09:55.963", "Id": "424755", "Score": "0", "body": "There's a lot to go through here, but if you have a receiver function like `Pod.rotate`, then I'd expect that to be a pointer receiver (ie a function that changes the state of the type you call it on). I'd also resist the tempation to use a _\"traditional\"_ OOP approach. Go doesn't work that way. I understand that it can feel weird/limiting at first, but trust me: embrace it, and you'll quickly see that the lack of strict classes, the Go compositional and ducktyped interfaces system is hugely powerful when used correctly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T13:31:28.393", "Id": "424757", "Score": "0", "body": "Thanks @EliasVanOotegem for the feedback. Could you be so kind as rewriting the `Pod.rotate` function in that receiver way to provide me with an example ? Right now, I am not sure I understand." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-08T09:13:08.630", "Id": "424854", "Score": "0", "body": "@Poutrathor Added an example as an answer. There's a lot more to be said, so I'll probably revisit periodically with updates" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-08T20:22:59.503", "Id": "424964", "Score": "0", "body": "I read a bit about Go type system. It seems it's more structural typing than duck typing as Python does, right ?" } ]
[ { "body": "<p>As per request in the comment, here's an implementation of the <code>rotate</code> function in a more idiomatic golang way (ie using a pointer receiver):</p>\n\n<pre><code>// let's use constants so code becomes self-documenting\nconst (\n maxRotation float64 = 18 // max rotation as typed constant\n fullCircle int = 360 // just like all hard-coded values, let's use constants\n semiCircle int = fullCirle/2 // do this for all hard-coded values\n)\n\n// note the receiver is a pointer, and there's no return value\nfunc (pod *Pod) rotate(p Dot) {\n a := pod.diffAngle(p)\n\n if a &gt; maxRotation {\n a = maxRotation\n } else if a &lt; -maxRotation {\n a = -maxRotation\n }\n\n pod.angle += int(math.Round(a))\n\n var add int // add this value, defaults to 0\n // you are comparing pod.angle (an int) to a float64 (360.0)\n // that shouldn't be happening. I'd say angle should be a float64\n // but keeping the fields in pod the types they are for now\n if pod.angle &gt;= fullCircle {\n add -= fullCircle\n } else if pod.angle &lt; 0 {\n add = fullCircle\n }\n pod.angle += add // adds 0, 360, or -360 depending on the new value for pod.angle\n}\n</code></pre>\n\n<p>That's all there is to it, really. Instead of calling it like this:</p>\n\n<pre><code>pod.angle = pod.rotate(p)\n</code></pre>\n\n<p>You simply call it like this:</p>\n\n<pre><code>pod.rotate(p)\n</code></pre>\n\n<p>The value of <code>pod.angle</code> will be updated. If you start doing this stuff concurrently, you'll need to ensure that <code>pod.rotate()</code> is <em>\"thread-safe\"</em> (ignoring the fact that goroutines aren't really threads for a second). The easiest way to do this is using a <code>sync.Mutex</code> (or <code>sync.RWMutex</code>), to make sure that you're not accidentally updating <code>pod.angle</code> in 2 routines etc...</p>\n\n<p>I might revisit this stuff to give a more detailed review, so stay tuned for updates.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-08T20:21:44.253", "Id": "424962", "Score": "0", "body": "Excellent! I implemented this and it gives me much more satisfaction. I had to fix my test cases to take into account that the pod is now updated. Nice, nice. It makes sense. I am nowhere close to use Go with gorountine and threading. It's already hard to switch from Java/C# paradigms to Go after work :D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-08T20:22:20.130", "Id": "424963", "Score": "0", "body": "Btw, thanks for reminding me that constants are defined once, even for a small scripting puzzle." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-08T09:12:24.897", "Id": "219917", "ParentId": "219607", "Score": "4" } } ]
{ "AcceptedAnswerId": "219917", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T20:56:56.667", "Id": "219607", "Score": "1", "Tags": [ "object-oriented", "programming-challenge", "go" ], "Title": "Simulating pod racing over a 2D map : am I implementing OOP in a GO-like fashion?" }
219607
<p>I'm learning Go and I wrote this for a programming challenge. It is working (building and running) but I feel the code is not what Go code should be:</p> <p>The code implements the steps a podracer takes to race over a 2D map. I input a target and a speed, and the code calculate where the pod will be at the end of the turn : rotating to point toward the target &amp; moving (counting in previous speed). </p> <ul> <li>In the playTurn() method below, I call each step. I reassign results (else they are not taken into account) because of scope I think. </li> </ul> <p>It feels wrong for OOP code to have to reassign each step answer to the pod's attribute. What am i missing ? </p> <p>Code : </p> <pre><code>package main import ( "fmt" "math" "os" "strconv" ) // Dot is king type Dot struct { x, y int } // Pod is life type Pod struct { position Dot vx, vy, angle, nextCpID int hasShieldOn bool } func squaredDist(a, b Dot) int { return (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) } func distance(a, b Dot) float64 { return math.Sqrt(float64(squaredDist(a, b))) } func (pod Pod) getAngle(p Dot) float64 { d := distance(p, pod.position) dx := float64(p.x-pod.position.x) / d dy := float64(p.y-pod.position.y) / d a := math.Acos(dx) * 180.0 / math.Pi // If the point I want is below me, I have to shift the angle for it to be correct if dy &lt; 0 { a = 360.0 - a } return a } func (pod Pod) diffAngle(p Dot) float64 { a := pod.getAngle(p) pangle := float64(pod.angle) right := 0.0 if pangle &lt;= a { right = a - pangle } else { right = 360.0 - pangle + a } left := 0.0 if pangle &gt;= a { left = pangle - a } else { left = pangle + 360.0 - a } if right &lt; left { return right } return -left } func (pod Pod) rotate(p Dot) int { a := pod.diffAngle(p) // Can't turn more than 18° in one turn ! if a &gt; 18.0 { a = 18.0 } else if a &lt; -18.0 { a = -18.0 } pod.angle += int(math.Round(a)) if pod.angle &gt;= 360.0 { pod.angle = pod.angle - 360.0 } else if pod.angle &lt; 0.0 { pod.angle += 360.0 } return pod.angle } func (pod Pod) boost(t int) (int, int) { if pod.hasShieldOn { return pod.vx, pod.vy } pangle := float64(pod.angle) pod.vx += int(math.Round(math.Cos(pangle) * float64(t))) pod.vy += int(math.Round(math.Sin(pangle) * float64(t))) return pod.vx, pod.vy } // t shoud become a float later on func (pod Pod) move(t int) (int, int) { pod.position.x += pod.vx * t pod.position.y += pod.vy * t return pod.position.x, pod.position.y } func (pod Pod) endTurn() (int, int) { // todo rounding position if needed pod.vx = int(float64(pod.vx) * 0.85) pod.vy = int(float64(pod.vy) * 0.85) return pod.vx, pod.vy } func (pod Pod) playTurn(p Dot, t int) { pod.angle = pod.rotate(p) pod.vx, pod.vy = pod.boost(t) pod.position.x, pod.position.y = pod.move(1) pod.vx, pod.vy = pod.endTurn() fmt.Fprintf(os.Stderr, "\nPredicted Pod position : ") fmt.Fprintf(os.Stderr, "\n(%d, %d) speed (%d,%d)", pod.position.x, pod.position.y, pod.vx, pod.vy) } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T21:07:03.193", "Id": "424143", "Score": "0", "body": "A more targeted question from my previous post which was too broad. Reference : https://codereview.stackexchange.com/questions/216074/writing-go-object-code-that-respects-go-guidelines" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T21:06:33.727", "Id": "219608", "Score": "1", "Tags": [ "object-oriented", "programming-challenge", "go" ], "Title": "Go - avoid result reassignement in OOP" }
219608
<p>I'd like to use basic auth with the WordPress API, but restrict the capability to a single IP address. I've updated the existing code from here: <a href="https://github.com/WP-API/Basic-Auth" rel="nofollow noreferrer">https://github.com/WP-API/Basic-Auth</a> accordingly. </p> <p>It seems to work fine but I would be interested in any comments about security or improvements that could be made.</p> <pre><code>class BasicAuth { public static function addAction(): void { $instance = new static; add_filter('determine_current_user', [$instance, 'json_basic_auth_handler'], 20); add_filter('rest_authentication_errors', [$instance, 'json_basic_auth_error'], 20); } protected $result; /** * Based on: https://github.com/WP-API/Basic-Auth * @param int|bool $user * @return int|bool|null $user */ function json_basic_auth_handler($user) { $this-&gt;result = null; // Don't authenticate twice if (!empty($user)) { return $user; } // Check that we're trying to authenticate if (!isset($_SERVER['PHP_AUTH_USER'])) { return $user; } // Check client IP if (!$this-&gt;checkIpPermitted()) { return $user; } $username = $_SERVER['PHP_AUTH_USER']; $password = $_SERVER['PHP_AUTH_PW']; /** * In multi-site, wp_authenticate_spam_check filter is run on authentication. This filter calls * get_currentuserinfo which in turn calls the determine_current_user filter. This leads to infinite * recursion and a stack overflow unless the current function is removed from the determine_current_user * filter during authentication. */ remove_filter('determine_current_user', 'json_basic_auth_handler', 20); $user = wp_authenticate($username, $password); /** @var WP_User|WP_Error $ */ add_filter('determine_current_user', 'json_basic_auth_handler', 20); // Authentication failure if (is_wp_error($user)) { $this-&gt;result = $user; return null; } // Authentication success $this-&gt;result = true; return $user-&gt;ID; } protected function checkIpPermitted(): bool { $options = get_option(OptionsPage::CONNECT_OPTIONS); $ip = $options['ip'] ?? ''; if (($_SERVER['REMOTE_ADDR'] ?? null) !== $ip) { $this-&gt;result = new WP_Error('ip-blocked', 'Invalid request'); return false; } return true; } function json_basic_auth_error($error) { // Passthrough other errors if (!empty($error)) { return $error; } // WP_Error if authentication error, null if authentication method wasn't used, true if authentication succeeded. return $this-&gt;result; } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T22:07:21.363", "Id": "219612", "Score": "2", "Tags": [ "php", "security", "api", "authentication", "wordpress" ], "Title": "WordPress rest api basic auth with IP check" }
219612
<p>I've been trying to get better at Haskell for a while, and have recently been working on a lot of small projects with it. <a href="https://gitlab.com/jb25uiuc/decision-tree/tree/f128ab2f7ffd0ab6670c480d1b301e95be449768" rel="nofollow noreferrer">This</a> constructs a binary decision tree.</p> <p>The command to run it is: </p> <p><code>stack exec decision-tree-exe &lt;threshold&gt; &lt;training file&gt; &lt;testing file&gt;</code></p> <p>where threshold is in the range (0,1].</p> <p>I think I've gotten a lot better, but I'm still having problems, especially with performance and readability. For this project, I took a more top down approach, implementing functions after using them. src/DecisionTree.hs is where the bulk of the logic is, and the file is pretty much in order of writing. I would love to get some feedback from some more experienced people on where I might improve.</p> <pre><code>module DecisionTree where import Data.List (genericLength, maximumBy, nub) import Data.Map (elemAt, foldlWithKey', fromListWith) import Data.Ord data DecisionTree a b = Node ([a] -&gt; Bool) (DecisionTree a b) (DecisionTree a b) | Leaf b type Dataset cat attrs = [(cat, [attrs])] type Threshold = Double type Splitter c a = ([a] -&gt; Bool, Dataset c a, Dataset c a) apply :: DecisionTree a b -&gt; [a] -&gt; b apply (Leaf b) _ = b apply (Node f l r) a = case f a of False -&gt; apply l a True -&gt; apply r a train :: (Ord c) =&gt; (Dataset c a -&gt; Maybe (Splitter c a)) -&gt; Dataset c a -&gt; DecisionTree a c train splitter dataset = case splitter dataset of Just (partitioner, left, right) -&gt; Node partitioner (train splitter left) (train splitter right) Nothing -&gt; Leaf majority where classCounts = fromListWith (+) $ map (\k -&gt; (fst k, 1)) dataset majority = fst $ foldlWithKey' max (elemAt 0 classCounts) classCounts max acc k v | v &gt; snd acc = (k, v) | otherwise = acc giniSplitter :: (Ord a, Ord c) =&gt; Threshold -&gt; Dataset c a -&gt; Maybe (Splitter c a) giniSplitter threshold dataset = case fst maxDelta &gt; threshold of True -&gt; Just $ snd maxDelta False -&gt; Nothing where attrs = nub . concat . snd . unzip $ dataset partitioner a = (a `elem`) delta a = giniDelta (partitioner a) dataset maxDelta = maximumBy (comparing fst) $ map delta attrs giniDelta :: (Eq c) =&gt; ([a] -&gt; Bool) -&gt; Dataset c a -&gt; (Double, Splitter c a) giniDelta partitioner dataset = ( gini dataset - (d1 / d * gini left + d2 / d * gini right) , (partitioner, left, right)) where left = filter (not . partitioner . snd) dataset right = filter (partitioner . snd) dataset d1 = genericLength left d2 = genericLength right d = genericLength dataset gini :: (Eq c) =&gt; Dataset c a -&gt; Double gini d = 1 - sum [(pj c) ** 2 | c &lt;- nub . fst . unzip $ d] where pj c = genericLength (filter ((== c) . fst) d) / genericLength d </code></pre>
[]
[ { "body": "<p>Just a few random comments:</p>\n\n<ol>\n<li><p>Both <code>elemAt</code> and <code>maximumBy</code> give hints that you're expecting to operate on non-empty structures. Maybe give <code>Data.List.NonEmpty</code> a try.</p></li>\n<li><p>A few places could be more clear with more pattern matching. E.g. <code>max (k1, v1) k2 v2</code> instead of <code>max acc k v</code>. Or <code>(maxDelta, splitter) = maximumBy …</code></p></li>\n<li><p><code>map snd</code> is more conventional than <code>snd . unzip</code>. I suspect it would be more efficient too but I might be wrong.</p></li>\n<li><p>In several places you're traversing the same list multiple times. In general, it's better to avoid this as it's likely to force the spine of the (potentially large) list in memory. You might be able to merge these multiple traversals into one (e.g. using the <code>foldl</code> package). More likely, you should simply use <code>vector</code>.</p></li>\n<li><p>In <code>giniDelta</code> you could use <code>Data.List.partition</code> to construct <code>left</code> and <code>right</code>.</p></li>\n<li><p>Apply top-down ordering in your <code>where</code>-clauses. E.g. in <code>train</code>, <code>majority</code> should come first as it is the declaration that is referenced from the main function body.</p></li>\n</ol>\n\n<p><strong>EDIT:</strong> All in all I think readability is actually pretty good!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T01:28:02.397", "Id": "220689", "ParentId": "219613", "Score": "2" } } ]
{ "AcceptedAnswerId": "220689", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-02T22:28:03.113", "Id": "219613", "Score": "4", "Tags": [ "haskell", "machine-learning" ], "Title": "Simple decision tree in Haskell" }
219613
<p>I have been teaching myself Python (as well as Tkinter) and today one of the sites I was reading, asked us to write a program to covert one value from Fahrenheit to Celsius, once - an easy three line program. As you can read in the comments for the program below, I wanted to expand on this.</p> <p>This program is one of the most complex and best organized for me thus far. I have feed it through a PEP8 program and it returned no errors, and the program itself runs as I intended and I haven't crashed it when passing errors.</p> <p>I would be grateful for any comments on the structure of the program, as well as areas I can improve and/or streamline the code - any and all constructive feedback is welcomed!</p> <pre><code>#!/usr/bin/python """ Program: Temperature Coversion (C to F, or F to C) Date: 02 May 2019 Author: Jason P. Karle Remark: This program was inspired by a Python exercise that asks you to create a program that will convert one Celsius value to Fahrenheit; so a program that can be executed with three lines of code. However, I wanted to make something that would allow the user to convert to and from either C of F, and do so multiple times, until the user decides to end the program. This was also an exercise for me to advance not only my code skills, but how I structure a program. """ def quitContinue(): print("\nDo you want to:\n") print(" 1. Make another conversion; or") print(" 2. Exit the program?\n") answer = input("Make you selection: ") try: if answer == "1": mainProg() else: return except: print("That is not a valid choice.") quitContinue() def CtoF_Calc(): print("\nThank you, please enter the") print("value you want to convert.") print("Enter a value between -273.5°C to") print("+5.5 dectillion °C") value = float(input(": ")) try: if value &lt; -273.5 or value &gt; 5.5**30: print("That is not a valid range.") celciusCalc() else: answer = (value*(9/5))+32 print(f"{value}°C equals: {answer}°F") quitContinue() except: print("Please entet a number!") CtoF_Calc() def FtoC_Calc(): print("\nThank you, please enter the") print("value you want to convert.") print("Enter a value between -273.5°C to") print("+5.5 dectillion °C") value = float(input(": ")) try: if value &lt; -459.5 or value &gt; 42**30: print("That is not a valid entry.") celciusCalc() else: answer = (5/9)*(value-32) print(f"{value}°F equals: {answer}°C") quitContinue() except: print("That is not a number!\n") FtoC_Calc def makeSelection(selection): try: if selection == "1": CtoF_Calc() elif selection == "2": FtoC_Calc() else: return except: print("That is not a valid selection") makeSelection(selection) def mainProg(): print("Please enter the number") print("corresponding to what you") print("want to convert:") print(" 1. Celcius to Farenheit") print(" 2. Farenheit to Celcius") print(" 3. Exit\n") selection = input("Enter 1, 2 or 3: ") makeSelection(selection) if __name__ == "__main__": print("Welcome to the temperature") print("conversion program!\n") mainProg() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T15:00:29.543", "Id": "424226", "Score": "1", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T15:31:40.783", "Id": "424230", "Score": "0", "body": "Understood, because that one was a save/version error, and never should have made it to this post, I mistakenly thought that my action was okay provided that I made note of it in the edit comments. All other comments and suggestions have not and will not be actioned in this post. I have now read (and bookmarked!) the link you provided, thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T17:39:46.043", "Id": "424265", "Score": "0", "body": "No problem, it's confusing for plenty of new users. You get used to it. Feel free to ask a new question once your code has been improved." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T15:43:03.703", "Id": "424460", "Score": "3", "body": "Thank you, everyone, for the quick and fulsome answers - awesome insight and very helpful information. I am digesting all the information I received and will begin a revised version that i look forward to posting as a new question this week for your feedback. Some of the suggested changes flew right over my head (I am researching them today!) and some elicited questions, which I will post to you specifically over the next few days. My heartfelt thanks, what a great welcome to this cleary supportive community!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-16T16:30:45.917", "Id": "489018", "Score": "0", "body": "`value < -273.5 or value > 5.5**30` can be replaced with `-273.5 < value < 5.5**30` which to my eyes is a little more readable." } ]
[ { "body": "<p>At first glance your code looks nice and clean. And even though the naming goes against PEP8 would be near perfect style.</p>\n\n<p>I then entered your code into PyCharm, and then and there I knew this was unfortunately a facade.</p>\n\n<p>Firstly I don't think you've set your linter up correctly. As within seconds I knew your code wasn't PEP8 compliant due to using camel case function names.</p>\n\n<blockquote>\n <p>I have feed it through a PEP8 program and it returned no errors</p>\n</blockquote>\n\n<ol>\n<li>PEP 8 convention is to use <code>snake_case</code> rather than <code>quitContinue</code> or <code>CtoF_Calc</code>.</li>\n<li>You have a couple of miss-spelt words, <code>Prog</code> and \"entet\".</li>\n<li>It's advised against having bare <code>except</code> statements as they catch too many errors and lead to hard to debug errors. This can actually be seen in your program, it's hidden a bug that you probably don't know about.</li>\n<li><code>celciusCalc</code> is undefined, and so is a bug in your program.</li>\n<li>PEP8 and linters are quite finicky when it comes to whitespace. <code>value*(9/5)</code> should have spaces either side of the operators.</li>\n<li>You have a 'pointless statement', <code>FtoC_Calc</code>. This is as you forgot to call the function. And so causes a bug in your program.</li>\n</ol>\n\n<p>And so I recommend you look into configuring your linter to get the maximum amount of warnings possible. I personally use Prospector and Flake 8 with a butt tone of plugins.</p>\n\n<hr>\n\n<ol>\n<li>In <code>FtoC_Calc</code> you state the range in celsius, which is confusing. If I'm using your program I likely won't know what the equivalent in Fahrenheit is.</li>\n<li><p>Keep the code in the <code>try</code> statement to be as small as possible. Looking at the <code>except</code> it looks like the purpose is to handle when you don't enter floating point integer values.</p>\n\n<ol>\n<li>You haven't put the call to <code>float</code> in the <code>try</code> and so you have another bug.</li>\n<li>You should use <code>except ValueError</code>.</li>\n<li>You can put all the code that is currently in the <code>try</code> in an <code>else</code> statement.</li>\n<li>You should replace <code>celciusCalc()</code> with <code>FtoC_Calc</code> and <code>CtoF_Calc</code>.</li>\n</ol></li>\n<li><p>Currently your design is sub-optimal, <code>FtoC_Calc</code> interacts with the user and performs the mathematical calculations.</p>\n\n<p>It also uses recursion rather than loops to cycle through the function calls, leading not only to spaghetti code, but toward getting a <code>RuntimeError</code> where you exceed the recursion depth.</p>\n\n<p>This is all rather easy to deal with. Split the function into three distinct functions:</p>\n\n<ol>\n<li><p>One that gets a floating point integer from the user. And handles interactions with the user if they enter an incorrect value.</p>\n\n<p>If a user enters an incorrect value you'll want to have your <code>try</code> statement in a <code>while</code> loop to continuously ask for input.</p>\n\n<p>By giving a range or an 'is_invalid' function to this function you can reduce the amount of duplicated code.</p></li>\n<li><p>The function to convert C to F.</p></li>\n<li>The function that calls both of these functions.</li>\n</ol></li>\n<li><p>The majority of your code in <code>make_selection</code> is not needed. No exceptions should be raised from these functions, and it isn't the correct place to handle them.</p></li>\n<li><p><code>quit_continue</code> should be changed to a function that returns a boolean. This can be used in <code>mainProg</code> to determine if the user will continue using the program or exit.</p>\n\n<p>This means <code>mainProg</code> should contain a while loop to continuously allow the user to enter values they want to convert.</p>\n\n<p>It should be noted that <code>quit_continue</code> shouldn't need the <code>try</code> and should never reach the except. However adding more code the way you did would make this assumption to be less safe as the program becomes more and more problematic.</p></li>\n<li><p>I changed your string delimiters as one of my tools errors on <code>\"</code>, as I commonly use <code>'</code>. Using <code>\"</code> is perfectly acceptable.</p></li>\n</ol>\n\n<pre><code>#!/usr/bin/python\n\"\"\"\nProgram: Temperature Coversion (C to F, or F to C)\nDate: 02 May 2019\nAuthor: Jason P. Karle\nRemark: This program was inspired by a Python exercise that\nasks you to create a program that will convert one Celsius value to Fahrenheit;\nso a program that can be executed with three lines of code.\nHowever, I wanted to make something that would allow the user to\nconvert to and from either C of F, and do so multiple times, until the user\ndecides to end the program. This was also an exercise for me to\nadvance not only my code skills, but how I structure a program.\n\"\"\"\n\n\ndef input_float(prompt, is_invalid):\n while True:\n try:\n value = float(input(prompt))\n except ValueError:\n print('That is not a number!')\n else:\n if is_invalid(value):\n print('That is not a valid number.')\n continue\n return value\n\n\ndef c_to_f(value):\n return (value * (9 / 5)) + 32\n\n\ndef f_to_c(value):\n return (5 / 9) * (value - 32)\n\n\ndef convert_c_to_f():\n print('\\nThank you, please enter the')\n print('value you want to convert.')\n print('Enter a value between -273.5°C to')\n print('+5.5 dectillion °C')\n celsius = input_float(': ', lambda v: v &lt; -273.5 or 5.5**30 &lt; v)\n fahrenheit = c_to_f(celsius)\n print(f'{celsius}°C equals: {fahrenheit}°F')\n\n\ndef convert_f_to_c():\n print('\\nThank you, please enter the')\n print('value you want to convert.')\n print('Enter a value between -459.5°F to')\n print('+42 dectillion °F')\n celsius = input_float(': ', lambda v: v &lt; -459.5 or 42**30 &lt; v)\n celsius = f_to_c(fahrenheit)\n print(f'{fahrenheit}°F equals: {celsius}°C')\n\n\ndef quit_continue():\n print('\\nDo you want to:\\n')\n print(' 1. Make another conversion; or')\n print(' 2. Exit the program?\\n')\n answer = input('Make you selection: ')\n return answer == '1'\n\n\ndef main():\n while True:\n print('Please enter the number')\n print('corresponding to what you')\n print('want to convert:')\n print(' 1. Celsius to Fahrenheit')\n print(' 2. Fahrenheit to Celsius')\n print(' 3. Exit\\n')\n selection = input('Enter 1, 2 or 3: ')\n if selection == '1':\n convert_c_to_f()\n elif selection == '2':\n convert_f_to_c()\n else:\n return\n if not quit_continue():\n return\n\n\nif __name__ == '__main__':\n print('Welcome to the temperature')\n print('conversion program!\\n')\n main()\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T12:25:19.447", "Id": "424215", "Score": "0", "body": "It would probably be better to have a `input_float(prompt, range=(-float(\"inf\"), float(\"inf\")))` function that can handle both Celsius and Fahrenheit input. Also in `convert_f_to_c()` you give the allowed range in Celsius instead of Fahrenheit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T15:43:10.403", "Id": "424231", "Score": "0", "body": "@Graipher Yeah that's a good suggestion, I thought there was a way to do that, but I was too tired when answering. As for the second thing, this is a problem in the original code too, do you want to write an answer for it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T16:17:53.073", "Id": "424236", "Score": "0", "body": "Ah didn't even see that in the OP. Nah, I think the current answers cover everything I really care about. However it seems like this is not the right way around or the naming is confusing: `if is_valid(value): print('That is not a valid number.')`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T16:23:24.603", "Id": "424237", "Score": "1", "body": "@Graipher That's cool, I'll add it to mine. Oh shoot, yeah that's meant to be the inverse D:" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T16:23:59.157", "Id": "424238", "Score": "0", "body": "Yeah, feel free to do so :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T19:31:33.033", "Id": "424284", "Score": "0", "body": "I wouldn't use so many `print` statements in a row. Just print a single multi-line string. [Like this](https://tio.run/##K6gsycjPM/7/v6AoM69Eg0sBCJRCMjKLFYAoUSG3NKckUzcnMy9VoSS1uCQmTwmiQk9PD84GyxrDuSEZqQqufi5KXJr//wMA). https://stackoverflow.com/a/10660443/2415524" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T19:37:38.623", "Id": "424285", "Score": "0", "body": "@mbomb007 My personal feelings on the print statements wouldn't be constructive for a review. And so I opted to say nothing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T15:57:12.477", "Id": "424463", "Score": "0", "body": "@Peilonrayz PLease do comment, all your comments have been very helpful!\n\nTwo questions for you: \n\n1. In your variation of my code, you wrote: fahrenheit = input_fahrenheit(': ') it looks like it should take a user-entered value and then call the def input_fahrenheit. But I cannot figure out how. Here 'input' is not the function input, but only the part of the name of a function. How is the user value read?\n2. under def quit_continue() you finished with: return answer == '1' - does this mean it only returns the value answer if answer evaluates to \"1\"? Am I understanding that correctly?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T16:02:53.867", "Id": "424466", "Score": "0", "body": "@JKarle Personally I would remove all the `print` statements and use [`cmd`](https://docs.python.org/3/library/cmd.html). Since this is a wildly different design, and picking one over the other is mostly personal choice it's just becomes holy-war bait." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T16:08:30.357", "Id": "424469", "Score": "0", "body": "@JKarle 1. Please re-check my code I've not used `input_fahrenheit`. In the previous version where I did it took a prompt to print and returned a value the user entered. 2. It returns a boolean, `a == b` results in `True` or `False`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T16:31:44.903", "Id": "424472", "Score": "0", "body": "Sorry, very odd. When I printed this on Friday the line is only \"fahrenheit = input_fahrenheit(': '), in fact, it is a different program in many places - did you edit this since Friday? It makes a lot of even more sense to me now, but look at what is up there I can clearly see the additional code. However, even with the new code: celsius = input_float(': ', lambda v: v < -459.5 or 42**30 < v) how does ..... wait I get it after running over the code above a dozen times - thank you! Re: the boolean return am I right in understanding b/c it returned \"1\" which is 'True' the while loop keeps going?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T16:39:07.050", "Id": "424476", "Score": "0", "body": "@Peilonrayz - I left out calling your name in the above response." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T16:45:21.857", "Id": "424477", "Score": "0", "body": "@JKarle Yes I changed it due to Graipher's comments, :) It's good that it makes more sense. Yes for the Boolean it converts `'1'` to `True`. From here using `not` converts it to `False` and since it's falsy it doesn't enter the if meaning it continues looping" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T16:52:49.053", "Id": "424480", "Score": "0", "body": "@Peilonrayz Awesome, thank you for your responses and patience!" } ], "meta_data": { "CommentCount": "14", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T04:54:58.577", "Id": "219619", "ParentId": "219618", "Score": "14" } }, { "body": "<p>I'm pretty happy that you've gone the extra mile to take a simple exercise and make it your own. That truly shows a lot of programming potential and initiative. While python code isn't restricted to any type of casing, let's use the more conventional <code>snake_case</code> for this review.</p>\n\n<p>There are a few times where you print a menu with multiple options. One idea to improve your code would be to write a reusable method that handles the redundancies of a numbered menu:</p>\n\n<pre><code>def numbered_menu(options):\n print(\"Do you want to:\\n\")\n for i, option in enumerate(options):\n print(f\"\\t{i + 1}. {option}\")\n input(\"&gt; \")\n\n# usage example\nnumbered_menu([\"Celsius to Fahrenheit\", \"Fahrenheit to Celsius\", \"Exit\"])\n</code></pre>\n\n<p>This method makes it easy to make a <code>numbered_menu</code> any time you need to print a bunch of options a user can choose from. There are a few fancy python things that may seem new to a reader, so let's break them down. The method <code>enumerate</code> is a convenient method that allows us to iterate with both the index and item of a list; <code>i</code> is the index, and <code>option</code> is the item in the list. Here we want to print the number of the option and the option itself, so <code>enumerate</code> is exactly what we want.</p>\n\n<p>Another tricky doodad is the <code>f\"\"</code> string. The <code>f</code> is short for <em>formatted string</em>. Assuming you are using at least python 3.6, a formatted string allows you to write python code directly in a string. That braced <code>{i+1}</code> executes like python code embedded when the string is formatted. This line is equivalent to:</p>\n\n<pre><code>print(str(i + 1) + \". \" + option)\n</code></pre>\n\n<p>However, many would argue that the f-string syntax is more pythonic.</p>\n\n<p>While we're at it...</p>\n\n<pre><code>def menu(options):\n user_choice = None\n while user_choice not in options:\n print(\"Do you want to:\\n\")\n for key, (option, action) in options.items():\n print(f\"{key}. {option}\")\n user_choice = input(\"&gt; \")\n return options[user_choice][1]\n\n# usage example\nmenu({\n \"1\": (\"Celsius to Fahrenheit\", CtoF_Calc),\n \"2\": (\"Fahrenheit to Celsius\", FtoC_Calc),\n \"q\": (\"Exit\", lambda *args: None) # because q is the first letter in exit\n})()\n</code></pre>\n\n<p>We have achieved python zen. With a fully declarative menu, we can make user menus with minimalist code. This is a dictionary of of tuples. The <code>.items()</code> method is similar to <code>enumerate</code>, but this one gives us the dict keys on the left and the dict values on the right. Since our dict values are tuples the <code>(option, action)</code> syntax destructures the tuples.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T08:12:49.913", "Id": "424190", "Score": "0", "body": "you forgot parenthesis in `return options[user_choice][1]()`…" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T12:28:08.910", "Id": "424216", "Score": "0", "body": "The line `user_choice = input(\"> \")` is indented one level too far, asking the user after every option instead of once after all options have been printed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T12:30:01.463", "Id": "424217", "Score": "0", "body": "Also I don't see how `# because q is the first letter in exit` can ever be true." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T07:44:10.877", "Id": "219625", "ParentId": "219618", "Score": "4" } }, { "body": "<p>While there are a lot of things that could be fixed or improved in your program, the biggest problem with it is your use of functions and control flow.</p>\n\n<p>One thing that was not at all obvious to me at first glance is that your program runs in a loop, requesting input and giving conversions until the user is done. Consider what another developer needs to read to determine that control flow in your program:</p>\n\n<ol>\n<li>Top-level module code that calls <code>mainProg()</code></li>\n<li><code>mainProg()</code> which calls <code>makeSelection()</code></li>\n<li><code>makeSelection()</code>, where it appears (though not in an obvious way) as if it is supposed to loop (via a recursive call) until a valid selection is entered. (This does not work; more on this later.)</li>\n<li>One of <code>CtoF_Calc()</code> or <code>FtoC_Calc()</code> (well, both really, if you want to make sure of what's going on in both cases) where you read through some moderately complex control flow to see that the exit is eventually via <code>quitContinue()</code>.</li>\n<li>At this point your reader may have the idea from the name, or he may read through <code>quitContinue()</code> to see that it could either exit (unwinding the long stack of functions you've called to get to this point) or call <code>mainProg()</code> again, which causes the whole program to loop.</li>\n</ol>\n\n<p>That's a pretty complex procedure, involving reading most of the code of the program, to get the overall control flow!</p>\n\n<p>The idea behind dividing a program into functions is to let developer look at things at a <em>higher level of abstraction</em>, that is, to be able ignore smaller details and look at just the main points. To do this, you need to have those main points together, with only the less important details (for that level) pushed away, which this program does not do. So let's look at how we could do that here.</p>\n\n<p>First, you can divide up the code in any Python script or module into two basic parts: the stuff executed \"now\" as the interpreter reads through the code, and the stuff stored to be executed later. Code at the \"top level\" outside of functions is executed immediately:</p>\n\n<pre><code>print(\"Hello\")\n</code></pre>\n\n<p>will immediately print \"Hello\" to the output. Anything in a function is stored to be executed later:</p>\n\n<pre><code>def printHello():\n print(\"Hello.\")\n</code></pre>\n\n<p>does not immediately print \"Hello,\" but waits until the function is called.</p>\n\n<p>The only code in your program that's immediately executed is the <code>if __name__ == \"__main__\": ...</code> paragraph.</p>\n\n<p>For reasons I won't get into here (but related to importing modules), you want as much code as possible to be stored to execute later so I would change that to just:</p>\n\n<pre><code>if __name__ == '__main__':\n main()\n</code></pre>\n\n<p>leaving out the <code>print</code> statements from that part; move those to be inside your <code>main()</code> function. Now all you have to do is write functions from this point out.</p>\n\n<p>The <code>main()</code> function should show the flow of control of the program at the highest (most <em>abstract</em>) level. With appropriate function naming, this can be read alone to give the overall idea of how the program works:</p>\n\n<pre><code>def main():\n while True:\n selection = read_selection()\n if selection == 'q':\n return\n elif selection == 'c':\n convert_C_to_F()\n elif selection == 'f':\n convert_F_to_C()\n else:\n print('Invalid selection')\n</code></pre>\n\n<p>You'll note that here already, though we don't know the details of how any of the conversions work, it's clear that:\n1. This program loops until it a decision is made to quit (<code>while True:</code>).\n2. It exits (via <code>return</code> from <code>main()</code>) on the user selecting <code>q</code>.\n3. On the user selecting <code>c</code> or <code>f</code> it does the conversion and (because there's no <code>return</code> for either of these) loops to read another selection.\n4. An invalid selection prints and error and, again with no <code>return</code>, loops.</p>\n\n<p>In other words, we have in this one space the full high-level operation of the program. (There are actually some slightly cleaner ways of handling this, but I think that this code best gets the point across to beginners.)</p>\n\n<p>Now all that remains is to write the <code>read_selection()</code>, <code>convert_C_to_F()</code> and <code>convert_F_to_C()</code> functions, which I will leave as an exercise for you. However, one thing I would strongly suggest you do in your initial version of this is to keep all looping control out of these functions. That is, regardless of whether the <code>convert_C_to_F()</code> gets valid input or not, always have it just take input, print something, and return. If it gets an invalid input temperature you can simply print an error message and return, letting the top level take care of letting the user try again. (She'll have to enter <code>c</code> or <code>f</code> again, but that's hardly a huge inconvenience.)</p>\n\n<p>Once you've got that working, you can consider extending those functions to request another temperature if the given one is invalid, but before you do that I'd encourage you to look at the two functions <code>convert_C_to_F()</code> and <code>convert_F_to_C()</code> and see if there's common code in the two that you can factor out into their own functions. As a hint, one of the first things you'll probably see is that getting the number, converting it with <code>float()</code> and handling the potential exception there is common to both and can be extracted to a separate function.</p>\n\n<p>This was long, but I hope that this gives some sense of the need to look at overall program structure. There are lots of small errors, you've made as well, but these both have less effect on overall program readability and are much more easily fixed than problems with the overall program structure.</p>\n\n<hr>\n\n<p>EDIT: Regarding the comments below about having one function get the number to convert and then call another function to do the conversion, here's an abbreviated code sample to explain what I mean by passing one function to another function for the latter to call. I've trimmed this down quite a bit to express just the core idea and give an example of its use; you can work from this idea to add it to the more sophisticated program (which includes user input to select the type of conversion, etc.) in the original question.</p>\n\n<pre><code>def c2f(t):\n ' Convert Celsius temperature `t` to Fahrenheit '\n return t*1.8 + 32\n\ndef f2c(t):\n ' Convert Fahrenheit temperature `t` to Celsius '\n return (t-32)/1.8\n\ndef convert(f):\n ' Read a value and convert it using function `f`. '\n n = float(input(' Enter value: '))\n print(' Converts to: ', f(n))\n\ndef main():\n print('Converting C to F:')\n # Notice here how we give just the function name, `c2f`,\n # without calling it by adding parens () to the end.\n # Convert will bind this function to its parameter `f`\n # and then can later call it with `f(n)`.\n convert(c2f)\n print('Converting F to C:')\n convert(f2c)\n</code></pre>\n\n<p>The ability to pass functions to other functions, return them from functions and assign them to variables is referred to as having <a href=\"https://en.wikipedia.org/wiki/First-class_function\" rel=\"nofollow noreferrer\">\"first class functions\"</a>, and is part of a powerful suite of techniques known as <a href=\"https://en.wikipedia.org/wiki/Functional_programming\" rel=\"nofollow noreferrer\">functional programming</a>. Languages vary in their support for this; some languages (such as <a href=\"https://en.wikipedia.org/wiki/Haskell_(programming_language)\" rel=\"nofollow noreferrer\">Haskell</a>) are built around these techiques, other provide almost no support at all for them.</p>\n\n<p>Python falls in the middle; it wouldn't be considered a full-fledged functional programming language, but it does provide a fair amount of support for functional programming and some techniques, such as this one, are very commonly used. See, for example, the built-in <a href=\"https://docs.python.org/3/library/functions.html#map\" rel=\"nofollow noreferrer\"><code>map()</code></a> function that can replace some types of <code>for</code> loops.</p>\n\n<p>Python decorators, which you probably not heard of yet, are a classic example of something that looks like a special language feature but is in fact just pure functional programming (passing around functions) with only a tiny bit of syntax added. The <a href=\"https://realpython.com/primer-on-python-decorators/\" rel=\"nofollow noreferrer\">realpython.com decorator tutorial</a> goes into a lot more detail about first-class functions and the rest of this, and is well worth reading when you feel ready.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T16:08:24.290", "Id": "424234", "Score": "1", "body": "You have correctly identified the most important problem with the code: functions are being incorrectly treated as goto labels. This is therefore [spaghetti code](https://en.wikipedia.org/wiki/Spaghetti_code), and this bad practice must be fixed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T17:16:42.913", "Id": "424484", "Score": "0", "body": "@Curt J. Sampson Thank you for the response; long it good! I believe I understand all of your points. However for clarity, and building on your statement of trying to group common process in one vice multiple functions. I feel like in the main() function I should have it run 'selection' and the if selection return 'c' or 'f' then run another function value() that takes selection as an argument. Then prompts the user for their value, converts it to a float, and then either goes to convert_f2c(value) or convert_c2f(value) if the value is 'f' or 'c'. Good...bad?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T01:25:18.730", "Id": "424524", "Score": "1", "body": "Yes, what you've described is one reasonable way of factoring out the common \"get value, call conversion function\" code from the details of actually doing the conversion. You can actually just directly pass in the function that does the conversion to be called by the \"read and call convert\" function; this passing of functions to be called by something else is a style known as \"functional programming.\" I'll edit above to add an example." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T10:27:42.977", "Id": "219631", "ParentId": "219618", "Score": "10" } } ]
{ "AcceptedAnswerId": "219619", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T03:25:29.583", "Id": "219618", "Score": "14", "Tags": [ "python", "beginner", "python-3.x", "unit-conversion" ], "Title": "Python 3 - simple temperature program" }
219618
<p>I've written a small package that counts the files and the size by file type in a directory tree. It produces the result as a markdown file. Here is a sample:</p> <pre><code>| directory | type | count | size | | --- | --- | ---: | ---: | | 0_0_root | ALL | 26 | 29.914 MiB | | 0_0_root | .mp3 | 4 | 3.901 MiB | | 0_0_root | .jpg | 5 | 211.019 KiB | | 0_0_root | .blu | 5 | 9.829 MiB | TRUNCATED | 0_0_root/1_2_node | ALL | 6 | 12.852 MiB | | 0_0_root/1_2_node | .jpg | 2 | 53.018 KiB | | 0_0_root/1_2_node | .mp4 | 1 | 7.573 MiB | TRUNCATED </code></pre> <p>I would be interested on how you would have iterated over the files. I'd be especially interested on how you would gain performance (time wise, I don't care about memory).</p> <p>I've decided to use <code>os.walk</code> with the option <code>topdown=False</code> because that way I can iterate only once on each node. The idea is that it iterates over a tree in a way a that a directory is encountered after and only after it has already encountered all of its childs. And in order to include the size of the childs in the parent stats, I store them in a stack.</p> <p>The stack can be modified in three way:</p> <ol> <li>A node add a clone of itself to the stack, waiting to be eaten by its parent</li> <li>A node get itself eaten by the top member of the stack, because it shares the same parent, the node from the stack continue to wait to be eaten by its parent</li> <li>A node eats the top member of the stack because it is its child</li> </ol> <p>He is a first module that I defined to hold the data.</p> <pre><code>from collections import defaultdict from os.path import splitext, join, dirname from os import stat import logging log = logging.getLogger('tree_stat.dm') class DirectoryMeasure: def __init__(self, files, path=None, parent=None): self.path = path self.parent = parent or dirname(path) self.file_type_measures = defaultdict(FilesMeasure) for f in files: ext = splitext(f)[1] file_size = stat(join(path, f)).st_size self.file_type_measures[ext].volume += file_size self.file_type_measures[ext].count += 1 @property def total(self): it = FilesMeasure() for ext in self.file_type_measures.keys(): it.volume += self.file_type_measures[ext].volume it.count += self.file_type_measures[ext].count return it def eat(self, child): for ext in child.file_type_measures.keys(): self.file_type_measures[ext].volume += child.file_type_measures[ext].volume self.file_type_measures[ext].count += child.file_type_measures[ext].count def edible_clone(self): clone = DirectoryMeasure([], parent=dirname(self.path)) clone.eat(self) return clone def __repr__(self): return 'DirectoryMeasure({})' \ .format(', '.join(['{v}={{{v}}}' .format(v=v) for v in vars(self).keys()])) \ .format(**vars(self)) class FilesMeasure: def __init__(self): self.volume = 0 self.count = 0 def __repr__(self): return 'FilesMeasure({})' \ .format(', '.join(['{v}={{{v}}}' .format(v=v) for v in vars(self).keys()])) \ .format(**vars(self)) </code></pre> <p>And here is the main logic:</p> <pre><code>def take_measures(directory): dir_tree = dict() stack = [] for current, sub_dirs, files in os.walk(directory, topdown=False): log.debug('working in {}'.format(current)) measure = dm.DirectoryMeasure(files, path=current) dir_tree[current] = measure log.debug('own measure: {}'.format(measure)) if stack and stack[-1].parent == measure.path: measure.eat(stack.pop()) log.debug('child fed measure: {}'.format(measure)) if stack and stack[-1].parent == measure.parent: stack[-1].eat(measure) else: stack.append(measure.edible_clone()) return dir_tree </code></pre> <p>That's pretty much everything but if you want to play around with it, you're welcome: <a href="https://github.com/AdrienHorgnies/tree_stat/tree/4bd4b8ce2e64abeba06f358767413c5d0db63137" rel="nofollow noreferrer">https://github.com/AdrienHorgnies/tree_stat</a>.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T09:38:01.270", "Id": "219629", "Score": "2", "Tags": [ "python", "performance", "python-3.x", "file-system" ], "Title": "Printing files count and size of a directory tree" }
219629
<p>I have two dataframes: One contains of company and its corresponding texts. The texts are in lists</p> <pre><code>**supplier_company_name Main_Text** JDA SOFTWARE ['Supply chains','The answer is simple -RunJDA!'] PTC ['Hello', 'Solution'] </code></pre> <p>The second dataframe is texts extracted from the company's website. </p> <pre><code> Company Text 0 JDA SOFTWARE About | JDA Software 1 JDA SOFTWARE 833.JDA.4ROI 2 JDA SOFTWARE Contact Us 3 JDA SOFTWARE Customer Support 4 PTC Training 5 PTC Partner Advantage </code></pre> <p>I want to create the new column in second dataframe if the text extracted from the web matches with the any item inside the list in the Main_Text column of the first data frame, fill <code>True</code> else fill <code>False</code>.</p> <p><strong>Code:</strong></p> <pre class="lang-py prettyprint-override"><code>target = [] for x in tqdm(range(len(df['supplier_company_name']))): #company name in df1 #print(x) for y in range(len(samp['Company']): #company name in df2 if samp['Company'][y] == df['supplier_company_name'][x]: #if the company name matches #check if the text matches if samp['Company'][y] in df['Main_Text'][x]: target.append(True) else: target.append(False) </code></pre> <p>How can I change my code to run efficiently?</p>
[]
[ { "body": "<p>I’ll take the hypothesis that your first dataframe (<code>df</code>) has unique company names. If so, you can easily reindex it by said company name and extract the (only one left) <code>Main_Text</code> <code>Series</code> to make it pretty much like a good old <code>dict</code>:</p>\n\n<pre><code>main_text = df.set_index('supplier_company_name')['Main_Text']\n</code></pre>\n\n<p>Now we just need to iterate over each line in <code>samp</code>, fetch the main text corresponding to the first column and generate a truthy value based on that and the second column. This is a job for <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html\" rel=\"nofollow noreferrer\"><code>apply</code></a>:</p>\n\n<pre><code>target = samp.apply(lambda row: row[1] in main_text.loc[row[0]], axis=1)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T12:49:08.760", "Id": "219636", "ParentId": "219632", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T10:51:09.950", "Id": "219632", "Score": "1", "Tags": [ "python", "pandas" ], "Title": "Comparing columns in pandas different data frames and fill in a new column" }
219632
<p>I've got a large macro which calculates diverse things for my job. I work in a contact center.</p> <p>Firstly it writes people and forecast data. With this calculates if there are more/less people than it should (depending on the forecast). After this calculation Uses it to calculate the break time for everyone <code>CalculadoraAux</code>. </p> <p>Once this is all done, the calculation starts(and is the slow block of the code). First for department and then for department and city(this last depends on the department and the number of people working on each city to distribuite things). It calculates for half hours and then 4 totals, grand total, morning, afternoon and night.</p> <p>Hope I've explained myself kind of clearly, but I can answer anything you need to help me speed up this code:</p> <pre><code>Option Explicit Sub Recalcular(Reforecast As Boolean) Dim arrAgentes As Variant, wsTD As Worksheet, Comprueba As Boolean, Col As Integer, ColIAux, ColFAux, Reductores As Single, _ LastRow As Long, x As Long, i As Long, C As Range, y As Long, B As Byte, ColI, ColF, wsP As Worksheet, _ wsObj As Worksheet, arrKPI As Variant, arrKPI2 As Variant, A As Long, arrDescansos, _ DictModoDia As Scripting.Dictionary, arrPronosticos, wsPron As Worksheet, wsDescanso As Worksheet, STRUnion As String Dim Contador '=========================FROM HERE=============================' Dim DictPronosticos As Scripting.Dictionary Dim DictHojaPronosticos As Scripting.Dictionary Dim DictModosDias As Scripting.Dictionary Set DictPronosticos = New Scripting.Dictionary Set DictModos = New Scripting.Dictionary Set DictModoDia = New Scripting.Dictionary Set DictHojaPronosticos = New Scripting.Dictionary Set DictModosDias = New Scripting.Dictionary Set wb = ThisWorkbook Set ws = wb.Sheets("Programaciones") Set wsP = wb.Sheets("Servicio") Set wsObj = wb.Sheets("Objetivos") Set wsPron = wb.Sheets("Pronosticos") If Reforecast Then Set wsPron = wb.Sheets("PronosticosReforecast") With ws i = .Cells(.Rows.Count, 1).End(xlUp).Row .Range("E5:BD" &amp; i).ClearContents End With Call CrearTablaAgentes 'PivotTable Creation Set wsTD = wb.Sheets("TablaProgramados") LastRow = wsTD.Cells(wsTD.Rows.Count, 1).End(xlUp).Row arrAgentes = wsTD.Range("A2:BC" &amp; LastRow).Value 'Store PivotTable into array 'Dictionary For i = LBound(arrAgentes) To UBound(arrAgentes) If arrAgentes(i, 2) = vbNullString Then ElseIf Not arrAgentes(i, 3) = vbNullString Then STRUnion = Application.Proper(arrAgentes(i, 3)) &amp; arrAgentes(i, 1) &amp; arrAgentes(i, 2) &amp; "1.Presentes Programados" DictModosDias.Add STRUnion, i Else STRUnion = "ALL" &amp; arrAgentes(i, 1) &amp; Mid(arrAgentes(i, 2), 7, Len(arrAgentes(i, 2))) &amp; "1.Presentes Programados" DictModosDias.Add STRUnion, i End If Next i Application.DisplayAlerts = False wsTD.Delete ColI = Array(5, 21, 37, 5) ColF = Array(52, 36, 52, 20) ColIAux = Array(13, 109, 205, 13) ColFAux = Array(300, 204, 300, 108) 'Dictionary to know positions on some data For Each C In wsP.Range("C35", wsP.Range("C35").End(xlDown)) If C.Font.Color = 49407 Then DictPronosticos.Add C.Value, 1 End If Next C 'Goal Data With wsObj LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row + 1 .Rows(LastRow &amp; ":1000").Delete arrObjetivos = wsObj.UsedRange.Value End With 'Dictionary to know where the goal positions are For i = 2 To UBound(arrObjetivos) DictModos.Add arrObjetivos(i, 2), i Next i 'Main data to be calculated With ws LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row arrMatriz = .Range("A5:BD" &amp; LastRow).Value End With 'Dictionary to know the position of each group Set DictKPIModoDia = New Scripting.Dictionary For i = 1 To UBound(arrMatriz) DictKPIModoDia.Add arrMatriz(i, 1) &amp; arrMatriz(i, 2) &amp; arrMatriz(i, 3) &amp; arrMatriz(i, 4), i Next i 'Data arrPronosticos = wsPron.UsedRange.Value 'Dictionary to know the position of each group For i = 2 To UBound(arrPronosticos) DictHojaPronosticos.Add arrPronosticos(i, 1) &amp; arrPronosticos(i, 2) &amp; arrPronosticos(i, 3) &amp; arrPronosticos(i, 4), i Next i Dim Centro As String, Modo As String, Fecha As Date, KPI As String, Centros, Multiplicador As Single, CentroFuncion As String For i = 1 To UBound(arrMatriz, 1) 'Rellenamos los pronósticos Centro = arrMatriz(i, 1) Modo = arrMatriz(i, 3) Fecha = CDate(arrMatriz(i, 2)) KPI = arrMatriz(i, 4) If DictPronosticos.Exists(KPI) Then For A = 5 To 56 If DictHojaPronosticos.Exists(Centro &amp; Fecha &amp; Modo &amp; KPI) Then arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; KPI), A) = arrPronosticos(DictHojaPronosticos(Centro &amp; Fecha &amp; Modo &amp; KPI), A) Else arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; KPI), A) = vbNullString End If Next A End If Next i For i = 1 To UBound(arrMatriz, 1) Centro = arrMatriz(i, 1) Modo = arrMatriz(i, 3) Fecha = CDate(arrMatriz(i, 2)) KPI = arrMatriz(i, 4) If KPI = "1.Presentes Programados" Then STRUnion = Centro &amp; Fecha &amp; Modo &amp; KPI For A = 5 To 56 On Error Resume Next arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; KPI), A) = arrAgentes(DictModosDias(STRUnion), A - 1) If arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; KPI), A) = 0 Then arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; KPI), A) = vbNullString On Error GoTo 0 Next A ElseIf KPI = "2.Efectivos" Then For A = 5 To 52 arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; KPI), A) = Formulas(Fecha, Modo, KPI, A, i, arrDescansos, _ DictModoDia, Centro) If arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; KPI), A) = 0 Then arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; KPI), A) = vbNullString Next A For A = 53 To 56 ReDim Contador(ColI(A - 53) To ColF(A - 53)) As Double On Error Resume Next For Col = LBound(Contador) To UBound(Contador) Contador(Col) = arrMatriz(i, Col) Next Col On Error GoTo 0 arrMatriz(i, A) = Application.Sum(Contador) / 2 If arrMatriz(i, A) = 0 Then arrMatriz(i, A) = vbNullString Next A ElseIf KPI = "94.Sobre/Infra" Then For A = 5 To 56 arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; KPI), A) = Formulas(Fecha, Modo, KPI, A, i, arrDescansos, _ DictModoDia, Centro) Next A End If Next i ws.Range("A5:BD" &amp; UBound(arrMatriz) + 4) = arrMatriz Debug.Print Timer &amp; "aux" Outputs.CalculadoraAux Debug.Print Timer &amp; "aux" '=========================TO HERE=============================' Fast Enough '=========================FROM HERE=============================' wb.Sheets("Mapa Turnos").AutoFilterMode = False Set wsDescanso = wb.Sheets("Calculadora AUX") arrDescansos = wsDescanso.UsedRange.Value wsDescanso.Visible = xlSheetHidden For i = 2 To UBound(arrDescansos) If Not DictModoDia.Exists(arrDescansos(i, 1) &amp; arrDescansos(i, 3)) Then DictModoDia.Add arrDescansos(i, 1) &amp; arrDescansos(i, 3), i Else DictModoDia(arrDescansos(i, 1) &amp; arrDescansos(i, 3)) = DictModoDia(arrDescansos(i, 1) &amp; arrDescansos(i, 3)) &amp; ", " &amp; i End If Next i Dim SplitCentros, arrPorcentaje, m As Long, CentroCC As String, DictPorcentajeCentros As Scripting.Dictionary Set DictPorcentajeCentros = New Scripting.Dictionary Erase Contador 'Calculate KPIs but the ones already calculated For i = 1 To UBound(arrMatriz, 1) Centro = arrMatriz(i, 1) Modo = arrMatriz(i, 3) Fecha = CDate(arrMatriz(i, 2)) KPI = arrMatriz(i, 4) If Centro &lt;&gt; "ALL" And KPI = "1.Presentes Programados" Then 'aquí calculamos directamente las capacidades y el % según centro para llamadas y req For A = 5 To 56 If arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; "5.Pronóstico"), A) = 0 And Not A = 56 Then GoTo SiguienteCC SplitCentros = Split(wb.Sheets("Servicio").Cells.Find(Modo).Offset(0, 1), "/") ReDim arrPorcentaje(0 To UBound(SplitCentros)) For m = 0 To UBound(SplitCentros) 'Rellenamos Efectivos Finales para poder hacer el cálculo a todos CentroCC = SplitCentros(m) arrMatriz(DictKPIModoDia(CentroCC &amp; Fecha &amp; Modo &amp; "21.Descansos Finales"), A) = _ Formulas(Fecha, Modo, "21.Descansos Finales", A, i, arrDescansos, DictModoDia, CentroCC) arrMatriz(DictKPIModoDia(CentroCC &amp; Fecha &amp; Modo &amp; "22.Efectivos Finales"), A) = _ Formulas(Fecha, Modo, "22.Efectivos Finales", A, i, arrDescansos, DictModoDia, CentroCC) Next m For m = 0 To UBound(SplitCentros) On Error Resume Next arrPorcentaje(m) = _ (arrMatriz(DictKPIModoDia(SplitCentros(m) &amp; Fecha &amp; Modo &amp; "22.Efectivos Finales"), A) * 1800) / _ arrMatriz(DictKPIModoDia(SplitCentros(m) &amp; Fecha &amp; Modo &amp; "6.TMO"), A) DictPorcentajeCentros.Add SplitCentros(m), m On Error GoTo 0 Next m 'Porcentaje a aplicar On Error Resume Next Multiplicador = 0 Multiplicador = arrPorcentaje(DictPorcentajeCentros(Centro)) / Application.Sum(arrPorcentaje) DictPorcentajeCentros.RemoveAll 'Call Capacity arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; "95.Call Capacity"), A) = _ arrMatriz(DictKPIModoDia("ALL" &amp; Fecha &amp; Modo &amp; "95.Call Capacity"), A) * Multiplicador 'Pronóstico arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; "5.Pronóstico"), A) = Multiplicador * _ arrMatriz(DictKPIModoDia("ALL" &amp; Fecha &amp; Modo &amp; "5.Pronóstico"), A) 'Call Capacity ajustado If arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; "95.Call Capacity"), A) &gt; _ arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; "5.Pronóstico"), A) Then arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; "96.Call Capacity ajustado curva"), A) = _ arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; "5.Pronóstico"), A) Else arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; "96.Call Capacity ajustado curva"), A) = _ arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; "95.Call Capacity"), A) End If 'Requeridos arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; "92.Requeridos"), A) = Multiplicador * _ arrMatriz(DictKPIModoDia("ALL" &amp; Fecha &amp; Modo &amp; "92.Requeridos"), A) 'NDA arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; "3.NA"), A) = Multiplicador * _ (arrMatriz(DictKPIModoDia("ALL" &amp; Fecha &amp; Modo &amp; "3.NA"), A) * _ arrMatriz(DictKPIModoDia("ALL" &amp; Fecha &amp; Modo &amp; "5.Pronóstico"), A)) / arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; "5.Pronóstico"), A) 'NDS arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; "4.SL"), A) = Multiplicador * _ (arrMatriz(DictKPIModoDia("ALL" &amp; Fecha &amp; Modo &amp; "4.SL"), A) * _ arrMatriz(DictKPIModoDia("ALL" &amp; Fecha &amp; Modo &amp; "5.Pronóstico"), A)) / arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; "5.Pronóstico"), A) 'Descubierto If arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; "5.Pronóstico"), A) &gt; 0 And _ arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; "22.Efectivos Finales"), A) = 0 Then _ arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; "93.Descubierto"), A) = "SI" 'Sobre/Infra On Error Resume Next arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; "94.Sobre/Infra"), A) = _ arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; "22.Efectivos Finales"), A) - _ arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; "92.Requeridos"), A) 'Occupancy If A &lt; 53 Then arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; "97.Occ"), A) = _ (arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; "5.Pronóstico"), A) * _ arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; "6.TMO"), A)) / _ (arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; "22.Efectivos Finales"), A) * 1800) If arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; "97.Occ"), A) &gt; 1 Then _ arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; "97.Occ"), A) = 1 'si el occupancy es mayor que 1 ElseIf A = 56 Then KPI = "97.Occ" GoTo Totales: End If SiguienteCC: Next A End If If KPI = "92.Requeridos" Or KPI = "5.Pronóstico" Or DictPronosticos.Exists(KPI) Then GoTo SiguienteKPI If KPI = "1.Presentes Programados" Or KPI = "2.Efectivos" Or Centro = "ALL" And KPI = "94.Sobre/Infra" Then GoTo SiguienteKPI If Centro &lt;&gt; "ALL" And Not arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; "5.Pronóstico"), 53) = 0 Then GoTo SiguienteKPI For A = 5 To 52 arrMatriz(i, A) = Formulas(Fecha, Modo, KPI, A, i, arrDescansos, DictModoDia, Centro) Next A Totales: 'Totals For A = 53 To 56 Select Case KPI Case "93.Descubierto", "94.Sobre/Infra", "96.Call Capacity ajustado curva" arrMatriz(i, A) = Formulas(Fecha, Modo, KPI, A, i, arrDescansos, DictModoDia, Centro) Case "3.NA", "4.SL", "97.Occ" ReDim arrKPI(ColI(A - 53) To ColF(A - 53)) ReDim arrKPI2(ColI(A - 53) To ColF(A - 53)) For Col = ColI(A - 53) To ColF(A - 53) arrKPI2(Col) = arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; "5.Pronóstico"), Col) arrKPI(Col) = arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; KPI), Col) Next Col On Error Resume Next arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; KPI), A) = Application.SumProduct(arrKPI, arrKPI2) / Application.Sum(arrKPI2) On Error GoTo 0 Erase arrKPI Erase arrKPI2 If arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; KPI), A) &gt; 0 And arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; KPI), A) &gt; 1 And Not KPI = "97.Occ" Then arrMatriz(i, A) = 1 Case "21.Descansos Finales" On Error Resume Next Reductores = arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; "7.Formación"), A) + _ arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; "9.Ausencias no programadas"), A) + _ arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; "91.Otros"), A) On Error GoTo 0 Contador = Split(DictModoDia(arrMatriz(i, 2) &amp; arrMatriz(i, 3)), ", ") If UBound(Contador) = -1 Then arrMatriz(i, A) = 0 GoTo SiguienteKPI End If With wsDescanso arrMatriz(i, A) = (Application.Sum(.Range(.Cells(Contador(0), ColIAux(A - 53)), _ .Cells(Contador(UBound(Contador)), ColFAux(A - 53)))) * 60) / _ (Application.Sum(.Range(.Cells(Contador(0), 7), .Cells(Contador(UBound(Contador)), 8))) * 3600) End With If arrMatriz(i, A) = 0 Then arrMatriz(i, A) = vbNullString Case "1.Presentes Programados", "2.Efectivos", "22.Efectivos Finales" ReDim Contador(ColI(A - 53) To ColF(A - 53)) As Double On Error Resume Next For Col = LBound(Contador) To UBound(Contador) Contador(Col) = arrMatriz(i, Col) Next Col On Error GoTo 0 arrMatriz(i, A) = Application.Sum(Contador) / 2 Case Else ReDim arrKPI(ColI(A - 53) To ColF(A - 53)) For Col = ColI(A - 53) To ColF(A - 53) arrKPI(Col) = arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; "95.Call Capacity"), Col) Next Col arrMatriz(i, A) = Application.Sum(arrKPI) If arrMatriz(i, A) = 0 Then arrMatriz(i, A) = vbNullString Erase arrKPI End Select Next A SiguienteKPI: Next i '=========================TO HERE=============================' Very slow and time consuming. 'Paste the array back to the worksheet With ws .Range("A5:BD" &amp; UBound(arrMatriz) + 4) = arrMatriz End With End Sub </code></pre> <p>External functions such as <code>CalculadoraAux</code> or <code>Formulas</code> don't have effect on the executing time.</p> <p>PS: there might be variables not declared here, but they are global variables (When I first started this I didn't know that shouldn't happen...)</p> <p>Edit: <a href="https://wetransfer.com/downloads/20145eb8dc91fd2522b303a33c27d9c920190508150435/206b9a8879e04569b4d3493826297c8b20190508150435/e6ede9" rel="nofollow noreferrer">Sample</a> This will stay up for 7 days. This file takes about 57s to complete the calculation (is one of the fastest) before some changes it was taking 5-10 seconds which was the optimal time since the users click this button often.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T12:59:00.427", "Id": "424219", "Score": "0", "body": "Are there 2 separate code blocks included? I see `From Here` and `To Here` twice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T13:03:32.163", "Id": "424220", "Score": "1", "body": "just to let you know where the process slows down. but its a single procedure." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T16:42:33.810", "Id": "424784", "Score": "1", "body": "Do you have any sample data you can provide that will work with your code above?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-08T11:39:50.477", "Id": "424874", "Score": "0", "body": "@PeterT I uploaded a sample file the link is on my post." } ]
[ { "body": "<p>Performance could improve by merging these two loops into one (inside the <code>For A = 5 To 56</code> loop) and taking two of these <code>DictKPIModoDia</code> values to a variable (since they don't change inside the loop):</p>\n\n<pre><code>Dim upperBound as long\nupperBound = UBound(SplitCentros)\nFor m = 0 To upperBound 'Rellenamos Efectivos Finales para poder hacer el cálculo a todos\n CentroCC = SplitCentros(m)\n arrMatriz(DictKPIModoDia(CentroCC &amp; Fecha &amp; Modo &amp; \"21.Descansos Finales\"), A) = _\n Formulas(Fecha, Modo, \"21.Descansos Finales\", A, i, arrDescansos, DictModoDia, CentroCC)\n arrMatriz(DictKPIModoDia(CentroCC &amp; Fecha &amp; Modo &amp; \"22.Efectivos Finales\"), A) = _\n Formulas(Fecha, Modo, \"22.Efectivos Finales\", A, i, arrDescansos, DictModoDia, CentroCC)\n 'end of original first loop\n On Error Resume Next 'here it is better to check that the denominator arrMatriz(DictKPIModoDia(CentroCC &amp; Fecha &amp; Modo &amp; \"6.TMO\"), A) &lt;&gt; 0 instead of resuming next. If you really need this resume next, place it before the loop.\n arrPorcentaje(m) = _\n (arrMatriz(DictKPIModoDia(CentroCC &amp; Fecha &amp; Modo &amp; \"22.Efectivos Finales\"), A) * 1800) / arrMatriz(DictKPIModoDia(CentroCC &amp; Fecha &amp; Modo &amp; \"6.TMO\"), A)\n DictPorcentajeCentros.Add CentroCC, m\n On Error GoTo 0 'You probably don't need this, specially if you check above calculation for zero in the denominator\n 'end of original second loop\nNext m\n</code></pre>\n\n<p>The other thing that might improve performance would be if you manage to incorporate this <code>Totales: For A = 53 To 56</code> loop <em>in your main A loop</em> so that you don't have to loop again. Something like this:</p>\n\n<pre><code>'Occupancy\nIf A &lt; 53 Then\n arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; \"97.Occ\"), A) = _\n (arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; \"5.Pronóstico\"), A) * _\n arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; \"6.TMO\"), A)) / _\n (arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; \"22.Efectivos Finales\"), A) * 1800)\n If arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; \"97.Occ\"), A) &gt; 1 Then _\n arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; \"97.Occ\"), A) = 1 'si el occupancy es mayor que 1\nElseIf A = 56 Then\n KPI = \"97.Occ\"\n 'GoTo Totales: 'Commented out\nElse '53 to 56\n 'Here, the code to calculate totals from A=53 to 56, ideally a call to a function. Ex:\n CaculateKPI\nEnd If\n</code></pre>\n\n<p>...</p>\n\n<pre><code>Public Sub CalculateKPI()\n Select Case KPI\n Case \"93.Descubierto\", \"94.Sobre/Infra\", \"96.Call Capacity ajustado curva\"\n arrMatriz(i, A) = Formulas(Fecha, Modo, KPI, A, i, arrDescansos, DictModoDia, Centro)\n Case \"3.NA\", \"4.SL\", \"97.Occ\"\n ReDim arrKPI(ColI(A - 53) To ColF(A - 53))\n ReDim arrKPI2(ColI(A - 53) To ColF(A - 53))\n For Col = ColI(A - 53) To ColF(A - 53)\n arrKPI2(Col) = arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; \"5.Pronóstico\"), Col)\n arrKPI(Col) = arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; KPI), Col)\n Next Col\n On Error Resume Next\n arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; KPI), A) = Application.SumProduct(arrKPI, arrKPI2) / Application.Sum(arrKPI2)\n On Error GoTo 0\n Erase arrKPI\n Erase arrKPI2\n If arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; KPI), A) &gt; 0 And arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; KPI), A) &gt; 1 And Not KPI = \"97.Occ\" Then arrMatriz(i, A) = 1\n Case \"21.Descansos Finales\"\n On Error Resume Next\n Reductores = arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; \"7.Formación\"), A) + _\n arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; \"9.Ausencias no programadas\"), A) + _\n arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; \"91.Otros\"), A)\n On Error GoTo 0\n Contador = Split(DictModoDia(arrMatriz(i, 2) &amp; arrMatriz(i, 3)), \", \")\n If UBound(Contador) = -1 Then\n arrMatriz(i, A) = 0\n GoTo SiguienteKPI\n End If\n With wsDescanso\n arrMatriz(i, A) = (Application.Sum(.Range(.Cells(Contador(0), ColIAux(A - 53)), _\n .Cells(Contador(UBound(Contador)), ColFAux(A - 53)))) * 60) / _\n (Application.Sum(.Range(.Cells(Contador(0), 7), .Cells(Contador(UBound(Contador)), 8))) * 3600)\n End With\n If arrMatriz(i, A) = 0 Then arrMatriz(i, A) = vbNullString\n Case \"1.Presentes Programados\", \"2.Efectivos\", \"22.Efectivos Finales\"\n ReDim Contador(ColI(A - 53) To ColF(A - 53)) As Double\n On Error Resume Next\n For Col = LBound(Contador) To UBound(Contador)\n Contador(Col) = arrMatriz(i, Col)\n Next Col\n On Error GoTo 0\n arrMatriz(i, A) = Application.Sum(Contador) / 2\n Case Else\n ReDim arrKPI(ColI(A - 53) To ColF(A - 53))\n For Col = ColI(A - 53) To ColF(A - 53)\n arrKPI(Col) = arrMatriz(DictKPIModoDia(Centro &amp; Fecha &amp; Modo &amp; \"95.Call Capacity\"), Col)\n Next Col\n arrMatriz(i, A) = Application.Sum(arrKPI)\n If arrMatriz(i, A) = 0 Then arrMatriz(i, A) = vbNullString\n Erase arrKPI\n End Select\nEnd Sub\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-08T11:40:16.857", "Id": "424875", "Score": "0", "body": "I uploaded a sample file, the link is on my post." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T12:05:32.460", "Id": "219864", "ParentId": "219633", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T11:23:02.853", "Id": "219633", "Score": "5", "Tags": [ "vba", "excel" ], "Title": "Speed up calculations with arrays/dictionaries" }
219633
<p>We are developing an automatic text Captcha solver in python 3. The solver has a module that is responsible for extracting letters out of captcha images that contain 4 letters each. We would like to get a review of this module and understand if there are any ways to write it more elegantly.</p> <p>Here is an example of a captcha image:</p> <p><br> <img src="https://i.imgur.com/Dg1l2em.png" alt="captcha image"></p> <p><br> Thanks!</p> <pre><code>import os import os.path import cv2 import glob import imutils CAPTCHA_IMAGE_FOLDER = "generated_captcha_images" OUTPUT_FOLDER = "extracted_letter_images" # Get a list of all the captcha images we need to process captcha_image_files = glob.glob(os.path.join(CAPTCHA_IMAGE_FOLDER, "*")) counts = {} # loop over the image paths for (i, captcha_image_file) in enumerate(captcha_image_files): print("[INFO] processing image {}/{}".format(i + 1, len(captcha_image_files))) # Since the filename contains the captcha text (i.e. "2A2X.png" has the text "2A2X"), # grab the base filename as the text filename = os.path.basename(captcha_image_file) captchaCorrectText = os.path.splitext(filename)[0] # Load the image and convert it to grayscale image = cv2.imread(captcha_image_file) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Add some extra padding around the image gray = cv2.copyMakeBorder(gray, 8, 8, 8, 8, cv2.BORDER_REPLICATE) # Threshold the image (convert it to pure black and white) Thresh = cv2.Threshold(gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1] # find the contours (continuous blobs of pixels) the image contours = cv2.findContours(Thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Hack for compatibility with different OpenCV versions if imutils.is_cv2(): contours = contours[0] else: contours = contours[1] letter_image_regions = [] # Now we can loop through each of the four contours and extract the letter # inside of each one for contour in contours: # Get the rectangle that contains the contour (x, y, w, h) = cv2.boundingRect(contour) # Compare the width and height of the contour to detect letters that # are conjoined into one chunk if w / h &gt; 1.25: # This contour is too wide to be a single letter! # Split it in half into two letter regions! half_width = int(w / 2) letter_image_regions.append((x, y, half_width, h)) letter_image_regions.append((x + half_width, y, half_width, h)) else: # This is a normal letter by itself letter_image_regions.append((x, y, w, h)) # If we found more or less than 4 letters in the captcha, our letter extraction # didn't work correcly. Skip the image instead of saving bad training data! if len(letter_image_regions) != 4: continue # Sort the detected letter images based on the x coordinate to make sure # we are processing them from left-to-right so we match the right image # with the right letter letter_image_regions = sorted(letter_image_regions, key=lambda x: x[0]) # Save out each letter as a single image for letter_bounding_box, letter_text in zip(letter_image_regions, captchaCorrectText): # Grab the coordinates of the letter in the image x, y, w, h = letter_bounding_box # Extract the letter from the original image with a 2-pixel margin around the edge letter_image = gray[y - 2:y + h + 2, x - 2:x + w + 2] # Get the folder to save the image in save_path = os.path.join(OUTPUT_FOLDER, letter_text) # if the output directory does not exist, create it if not os.path.exists(save_path): os.makedirs(save_path) # write the letter image to a file count = counts.get(letter_text, 1) p = os.path.join(save_path, "{}.png".format(str(count).zfill(6))) cv2.imwrite(p, letter_image) # increment the count for the current key counts[letter_text] = count + 1 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T12:52:47.947", "Id": "424218", "Score": "0", "body": "Welcome to Code Review! Would it be possible to include one or more example CAPTCHAs so a reviewer can easily test run your code?" } ]
[ { "body": "<p>Without some sample inputs I can only really comment on how the code reads, less on how it runs.</p>\n\n<ul>\n<li><p>First, this should really be a few functions, I'll indicate below where might be good places to separate the code.</p></li>\n<li><p>Why <code>import os</code> and <code>os.path</code>? Just <code>import os</code> then call <code>os.path.&lt;something&gt;</code></p></li>\n<li><p>You don't need to wrap <code>i, captcha_image_file</code> in brackets when using <code>enumerate()</code>; <code>enumerate()</code> also takes an optional start argument; so, using f-strings as well, you can write:</p></li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>for count, captcha_image_file in enumerate(captcha_image_files, 1):\n print(f\"[INFO] processing image {count}/{len(captcha_image_files)}\")\n</code></pre>\n\n<p><code>count</code> typically indicates starting from 1, where <code>pos</code> or <code>index</code> would indicate starting from 0. Avoid using short, non-descriptive variables like <code>i</code>.</p>\n\n<ul>\n<li>The \"Hack\" can be shortened nicely with a ternary operator:</li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>contours = contours[0] if imutils.is_cv2() else contours[1]\n</code></pre>\n\n<ul>\n<li><p>I would separate the block immediately following this into a function, which would yield, rather than append to a list. This will be faster, cleaner, and get rid of dummy variables.</p></li>\n<li><p>I would use itemgetter rather than a lambda function here, entirely a style choice, though.</p></li>\n<li><p>Contrary to what I said earlier, I actually think using <code>x</code>, <code>y</code>, <code>w</code>, <code>h</code> is fine here as they are commonly understood to be the x and y directions, width and height.</p></li>\n<li><p>Again, this last block (<code>for letter_bounding_box, letter_text ...</code>) should be its own function.</p></li>\n<li><p>Really, I think this whole piece of code should be a class, the globals can then be class variables, and you can have three methods. You can then have a <code>main()</code> function which calls these methods and keeps track of which file you're on etc. This <code>main()</code> should sit inside: \n<code>if __name__ == '__main__':</code></p></li>\n<li><p>Overall comments are good, somewhat excessive in parts but better than too sparse.</p></li>\n</ul>\n\n<p>The bulk of the improvements would come from separating out your code into readable methods. Functions / methods should generally have one clear purpose. This also has the advantage of making generators easier to use as you can easily yield rather than constantly making lists.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T13:47:03.023", "Id": "219639", "ParentId": "219637", "Score": "2" } }, { "body": "<p>In captchas, there are times where letters are overlapping, in this case it would be considered to be only one letter because of the algorithms you use. You should consider <a href=\"https://docs.opencv.org/2.4/doc/tutorials/imgproc/erosion_dilatation/erosion_dilatation.html\" rel=\"nofollow noreferrer\">eroding</a> your image to try to detach letters when they are slightly overlapping. If they overlap a lot, you'll need to find another algorithm.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T20:05:42.770", "Id": "219672", "ParentId": "219637", "Score": "0" } } ]
{ "AcceptedAnswerId": "219639", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T12:49:23.130", "Id": "219637", "Score": "4", "Tags": [ "python", "python-3.x", "opencv", "captcha" ], "Title": "Captcha Letter Extraction" }
219637
<p>I have completed my initial version of BlackJack with Javascript and some JQuery. Any thoughts of this version? I can't seem still to implement timer successfully as I have commented out. After implement the timer (delay of 2 seconds for each card dealt, the hit and stand button breaks).</p> <p>I updated my code to fixes some issues and good for testing now. Feel free to check it out from my github, <a href="https://github.com/ngaisteve1/BlackJackJS" rel="nofollow noreferrer">https://github.com/ngaisteve1/BlackJackJS</a> for further review.</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>// Variable/Object declaration and initialization - Start const isDebug = false; //const DELAY = 2000; var gameOver = false; const deck = { cards: [] } var tempCard; const player = { cards: [], handValue: 0, isWinner: false, canHit: true, hasAce: false } const dealer = { cards: [], handValue: 0, isWinner: false, canHit: true, hasAce: false } var result = document.getElementById("gameResult"); const cardSuit = ["hearts", "diams", "clubs", "spades"]; const cardFace = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]; $(".checkmarkDealer").hide(); $(".checkmarkPlayer").hide(); $("#handValueDealer").hide(); //Variable/Object declaration and initialization - End // var x = document.getElementById("myAudio"); // function playAudio() { // x.play(); // } if (!isDebug) { document.getElementById("btnDevelopment").style.display = "none"; document.getElementById("deck").style.display = "none"; document.getElementById("oneDeck").style.display = "none"; document.getElementById("playerCards").style.display = "none"; document.getElementById("dealerCards").style.display = "none"; //document.getElementById("result").style.display = "none"; } else { document.getElementById("btnDevelopment").style.display = "block"; document.getElementById("deck").style.display = "block"; document.getElementById("oneDeck").style.display = "block"; document.getElementById("playerCards").style.display = "block"; document.getElementById("dealerCards").style.display = "block"; //document.getElementById("result").style.display = "block"; } const showGameButtons = (cardDealt) =&gt; { if (cardDealt) { $("#btnDeal").hide(); $("#btnHit").show(); $("#btnStand").show(); //document.getElementById("btnDeal").disabled = true; //document.getElementById("btnHit").disabled = false; //document.getElementById("btnStand").disabled = false; } else { $("#btnDeal").show(); $("#btnHit").hide(); $("#btnStand").hide(); //document.getElementById("btnDeal").disabled = false; //document.getElementById("btnHit").disabled = true; //document.getElementById("btnStand").disabled = true; } if (player.isWinner === true) { document.getElementById("containerDealer").classList.remove("winner"); document.getElementById("containerPlayer").classList.add("winner"); $("#handValueDealer").show(); $(".checkmarkPlayer").show(); $(".checkmarkDealer").hide(); } else if (dealer.isWinner === true) { document.getElementById("containerPlayer").classList.remove("winner"); document.getElementById("containerDealer").classList.add("winner"); $("#handValueDealer").show(); $(".checkmarkPlayer").hide(); $(".checkmarkDealer").show(); } else { } } showGameButtons(false); // In JavaScript, functions are objects. // You can work with functions as if they were objects. function card(suit, face) { this.suit = suit; this.face = face; switch (face) { case "A": this.faceValue = 11; break; case "J": case "Q": case "K": this.faceValue = 10; break; default: this.faceValue = parseInt(face); break; } }; const createDeck = () =&gt; { deck.cards = []; deck.cards.length = 0; cardSuit.forEach(function (suit) { cardFace.forEach(function (face) { deck.cards.push(new card(suit, face)); }); }); } const shuffleDeck = () =&gt; { // Fisher–Yates shuffle algorithm let temp, i, rnd; for (i = 0; i &lt; deck.cards.length; i++) { rnd = Math.floor(Math.random() * deck.cards.length); temp = deck.cards[i]; deck.cards[i] = deck.cards[rnd]; deck.cards[rnd] = temp; } } const newDeck = () =&gt; { createDeck(); shuffleDeck(); document.getElementById("oneDeck").innerHTML = ""; player.cards = []; player.handValue = 0; dealer.cards = []; dealer.handValue = 0; var myNode = document.getElementById("cardContainerPlayer"); var fc = myNode.firstChild.firstChild; while (fc) { myNode.removeChild(fc); fc = myNode.firstChild; } var myNodeDealer = document.getElementById("cardContainerDealer"); var fcDealer = myNodeDealer.firstChild.firstChild; while (fcDealer) { myNodeDealer.removeChild(fcDealer); fcDealer = myNodeDealer.firstChild; } document.getElementById("playerCards").innerHTML = ""; document.getElementById("dealerCards").innerHTML = ""; document.getElementById("oneDeck").innerHTML = JSON.stringify(deck); } const burnOneCard = () =&gt; { // Remove the top deck to burn deck.cards.splice(0, 1); } const showDeck = () =&gt; { document.getElementById("oneDeck").innerHTML = JSON.stringify(deck); } const dealOneCardToPlayer = (x, isHit) =&gt; { // return new Promise(function (resolve) { // setTimeout(function () { // Take a card from the top deck to be assigned to tempcard. tempCard = deck.cards.splice(0, 1); //console.log(tempCard[0].face); //console.log(tempCard[0].faceValue); player.cards.push(tempCard); //console.log(player.handValue); if(tempCard[0].face === "A"){ player.hasAce = true; } player.handValue = countHandValue(tempCard[0], player, isHit); document.getElementById("handValuePlayer").innerHTML = player.handValue; // if (player.cards.length === 5) { // player.canHit = false; // } // conditional (ternary) operator player.canHit = player.cards.length === 5 ? false : true if (player.canHit) { $("#btnHit").show(); } else { $("#btnHit").hide(); } //player.cards.push(new card("Spades","A")); //player.cards.push(new card("Spades","10")); document.getElementById("playerCards").innerHTML = JSON.stringify(player); makeCardPlayer(tempCard[0]); // resolve(); // }, DELAY); // }); } const dealOneCardToDealer = (holeCard, isHit) =&gt; { // return new Promise(function (resolve) { // setTimeout(function () { // Take a card from the top deck to be assigned to tempcard. tempCard = deck.cards.splice(0, 1); //console.log(tempCard[0].face); //console.log(dealer.handValue); if(tempCard[0].face === "A"){ dealer.hasAce = true; } dealer.handValue = countHandValue(tempCard[0], dealer, isHit); document.getElementById("handValueDealer").innerHTML = dealer.handValue; dealer.cards.push(tempCard); //dealer.handValue = countHandValue(tempCard[0]); // conditional (ternary) operator dealer.canHit = dealer.cards.length === 5 ? false : true if (dealer.canHit) { $("#btnHit").show(); } else { $("#btnHit").hide(); } document.getElementById("dealerCards").innerHTML = JSON.stringify(dealer); makeCardDealer(tempCard[0], holeCard); // resolve(); // }, DELAY); // }); } const countAllHandValue = (cardsOnHand) =&gt; { //console.log(hasAceInHand(cardsOnHand)); let sum = 0; for (let key in cardsOnHand) { let arr = cardsOnHand[key]; for (let i = 0; i &lt; arr.length; i++) { let obj = arr[i]; for (let prop in obj) { if (prop === "faceValue") { sum = sum + obj[prop]; } } } } return sum; } const countHandValue = (onecard, person, isHit) =&gt; { if(isHit){ // Only can cover one Ace for this solution. More than one Ace will be a bug. if (person.handValue &gt; 10 &amp;&amp; person.hasAce === true) { person.cards.forEach(card =&gt; { console.log(card[0]); if (card[0].face === 'A') card[0].faceValue = 1; return card[0]; }); person.handValue = countAllHandValue(person.cards); // loop through all the Ace and transform all Ace's face value from 11 to 1 // Recalculate all the cards on hand again. } else { person.handValue = person.handValue + onecard.faceValue; } } else { person.handValue = person.handValue + onecard.faceValue; } //console.log(person.handValue); //console.log(onecard); return person.handValue; } const showHandValue = () =&gt; { document.getElementById("playerCardsHandValue").innerHTML = player.handValue; document.getElementById("dealerCardsHandValue").innerHTML = dealer.handValue; } const getDeckCardCount = () =&gt; { document.getElementById("deckCardCount").innerHTML = deck.cards.length; } const checkGameOver = () =&gt; { if (gameOver) { $(".holeCard &gt; :nth-child(1)").show(); $(".holeCard &gt; :nth-child(2)").show(); $(".holeCard").removeClass("holeCard"); $("#handValueDealer").show(); showGameButtons(false); } } const checkEndGame1 = () =&gt; { gameOver = true; if (player.handValue === 21 &amp;&amp; dealer.handValue !== 21) { result.innerHTML = "BlackJack! Player won."; player.isWinner = true; } else if (player.handValue !== 21 &amp;&amp; dealer.handValue === 21) { result.innerHTML = "BlackJack! Dealer won."; dealer.isWinner = true; } else if (player.handValue === 21 &amp;&amp; dealer.handValue === 21) { result.innerHTML = "Push."; } else { gameOver = false; } } const checkEndGame2 = () =&gt; { if (player.cards.length &lt;= 5 &amp;&amp; player.handValue &gt; 21) { result.innerHTML = "Bust! Dealer won."; dealer.isWinner = true; gameOver = true; } } const checkEndGame3 = () =&gt; { if (player.cards.length &lt;= 5 &amp;&amp; dealer.cards.length &lt;= 5) { // Check bust if (player.handValue &lt;= 21 &amp;&amp; dealer.handValue &gt; 21) { result.innerHTML = "Bust! Player won."; player.isWinner = true; } else if (player.handValue === 21 &amp;&amp; dealer.handValue !== 21) { result.innerHTML = "BlackJack! Player won."; player.isWinner = true; } else if (player.handValue !== 21 &amp;&amp; dealer.handValue === 21) { result.innerHTML = "BlackJack! Dealer won."; dealer.isWinner = true; } else if (player.handValue === dealer.handValue) { result.innerHTML = "Push."; } else if (player.handValue &gt; dealer.handValue) { result.innerHTML = "Player won."; player.isWinner = true; } else if (player.handValue &lt; dealer.handValue) { result.innerHTML = "Dealer won."; dealer.isWinner = true; } else { result.innerHTML = "Error"; } } else { result.innerHTML = "Error"; } gameOver = true; } // This function use JQuery lib function makeCardPlayer(_card) { // .card is created in the template card css class var card = $(".card.templatePlayer").clone(); card.removeClass("templatePlayer"); // .cardFace is created in the template card css class // It will search for this css class and add the content aka innerHTML card.find(".playerCardFace").html(_card.face); // .suit is created in the template card css class // It will search for this css class and add the content aka innerHTML card.find(".playerCardSuit").html("&amp;" + _card.suit + ";"); // &amp;spades; -&gt; ♠, &amp;clubs; -&gt; ♣, &amp;hearts; -&gt; ♥, &amp;diams; -&gt; ♦ // more char, https://www.w3schools.com/charsets/ref_utf_symbols.asp // hearts and diamonds are red color. otherwise, default black color. if (_card.suit === "hearts" || _card.suit === "diams") { card.addClass("red"); } // option: replace previous card with new card (show one card all the time) $("#cardContainerPlayer").append(card); } // This function use JQuery lib function makeCardDealer(_card, _holeCard) { // .card is created in the template card css class var card = $(".card.templateDealer").clone(); card.removeClass("templateDealer"); // .cardFace is created in the template card css class // It will search for this css class and add the content aka innerHTML card.find(".dealerCardFace").html(_card.face); // .suit is created in the template card css class // It will search for this css class and add the content aka innerHTML card.find(".dealerCardSuit").html("&amp;" + _card.suit + ";"); // &amp;spades; -&gt; ♠, &amp;clubs; -&gt; ♣, &amp;hearts; -&gt; ♥, &amp;diams; -&gt; ♦ // more char, https://www.w3schools.com/charsets/ref_utf_symbols.asp // hearts and diamonds are red color. otherwise, default black color. if (_card.suit === "hearts" || _card.suit === "diams") { card.addClass("red"); } if (_holeCard) { card.addClass("holeCard"); } // option: replace previous card with new card (show one card all the time) $("#cardContainerDealer").append(card); $(".holeCard &gt; :nth-child(1)").hide(); $(".holeCard &gt; :nth-child(2)").hide(); } const deal = () =&gt; { newDeck(); // Option: to burn first card before deal a card // to the first player burnOneCard; // dealOneCardToPlayer() // .then(dealOneCardToDealer) // .then(dealOneCardToPlayer) // .then(dealOneCardToDealer(true)); dealOneCardToPlayer("",false); dealOneCardToDealer(false,false); dealOneCardToPlayer("",false); // true for hole card dealOneCardToDealer(true,false); showGameButtons(true); checkEndGame1(); checkGameOver(); } const hit = () =&gt; { dealOneCardToPlayer("", true); checkEndGame2(); checkGameOver(); } const stand = () =&gt; { // Recalculate dealer's hand value //dealer.handValue = countAllHandValue(dealer.cards); // Simple AI to automate dealer's decision to hit or stand if (dealer.handValue &gt;= 17) { checkEndGame3(); } else { // Hit until dealer's hand value is more than 16 while (dealer.handValue &lt; 17) { dealOneCardToDealer(false, true); checkEndGame3(); } } checkGameOver(); }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body{ font-size: 2em; } h3, h5 { text-align: center; } h5{ margin-top:-40px; } /*debugging purpose*/ div#oneDeck { border: 1px solid green; margin: 10px; padding: 10px; } /*debugging purpose*/ div#playerCards { border: 1px solid blue; margin: 10px; padding: 10px; } /*debugging purpose*/ div#dealerCards { border: 1px solid red; margin: 10px; padding: 10px; } #mainContainer { max-width: 600px; margin: 0 auto; } fieldset { margin-top: 30px; border: 1px solid #999; border-radius: 8px; box-shadow: 0 0 10px #999; } legend { background: #fff; } #cardContainerPlayer { display: flex; flex-wrap: wrap; } .card { display: inline-block; vertical-align: top; /*float: left;*/ text-align: center; margin: 5px; padding: 10px; width: 70px; height: 100px; font-size: 26px; background-color: black; border: solid 1px black; color: white; border-radius: 10px; } .holeCard { /*visibility: hidden;*/ border: solid 1px black; background: repeating-linear-gradient( 45deg, #606dbc, #606dbc 10px, #465298 10px, #465298 20px ); } .red { background-color: red; border: solid 1px #8C001A; } .templatePlayer, .templateDealer { display: none; } #btnGame { margin: 10px; } .winner { border: solid 5px #7ac142; } .btnGame { background-color: dodgerblue; /* Green */ border: none; color: white; padding: 15px 32px; /*border-radius:10px;*/ text-align: center; text-decoration: none; display: inline-block; font-size: 16px; cursor: pointer; -webkit-transition-duration: 0.4s; /* Safari */ transition-duration: 0.4s; box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19); } #btnHit { margin-right: 20px; } .flex-container { padding: 0; margin: 0; display: flex; justify-content: space-between; max-width: 100%; overflow: auto; /*border: 1px solid red*/ }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="check.css" rel="stylesheet" /&gt; &lt;link href="BlackJack.css" rel="stylesheet" /&gt; &lt;h3&gt;Simple Javascript BlackJack Game&lt;/h3&gt; &lt;h5&gt;developed by Steve Ngai&lt;/h5&gt; &lt;div id="mainContainer"&gt; &lt;div id="btnDevelopment"&gt; &lt;input type='button' value='Create new Deck' onclick='newDeck();' /&gt; &lt;input type='button' value='Burn a card' onclick='burnOneCard();' /&gt; &lt;input type='button' value='Refresh Deck' onclick='showDeck();' /&gt; &lt;input type='button' value='Deal a card to Player' onclick='dealOneCardToPlayer();' /&gt; &lt;input type='button' value='Deal a card to Dealer' onclick='dealOneCardToDealer();' /&gt; &lt;input type='button' value='Show hand value' onclick='showHandValue();' /&gt; &lt;input type='button' value='Check end game' onclick='checkEndGame();' /&gt; &lt;input type='button' value='Refresh deck remaining cards count' onclick='getDeckCardCount();' /&gt; &lt;/div&gt; &lt;fieldset id="deck"&gt; &lt;legend&gt;Remaining cards in the Deck: &lt;span id="deckCardCount"&gt;&lt;/span&gt;&lt;/legend&gt; &lt;div id="oneDeck"&gt;&lt;/div&gt; &lt;/fieldset&gt; &lt;fieldset id="containerDealer"&gt; &lt;legend&gt;Dealer (Hand Value: &lt;span id="handValueDealer"&gt;&lt;/span&gt;)&lt;/legend&gt; &lt;div style="width:30px"&gt; &lt;svg class="checkmarkDealer" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52"&gt; &lt;circle class="checkmark__circle" cx="26" cy="26" r="25" fill="none" /&gt; &lt;path class="checkmark__check" fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8" /&gt; &lt;/svg&gt; &lt;/div&gt; &lt;div id="dealerCards"&gt;&lt;/div&gt; &lt;div id="cardContainerDealer"&gt; &lt;div class="card templateDealer"&gt; &lt;span class="dealerCardFace"&gt;&lt;/span&gt; &lt;span class="dealerCardSuit"&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="dealerCardsHandValue"&gt;&lt;/div&gt; &lt;/fieldset&gt; &lt;div id="btnGame"&gt; &lt;div class="flex-container"&gt; &lt;div class="btn"&gt; &lt;input type='button' class="btnGame" id="btnDeal" value='Deal' onclick='deal();' /&gt; &lt;/div&gt; &lt;div class="btn"&gt; &lt;input type='button' class="btnGame" id="btnHit" value='Hit' onclick='hit();' /&gt; &lt;input type='button' class="btnGame" id="btnStand" value='Stand' onclick='stand();' /&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;fieldset id="containerPlayer"&gt; &lt;legend&gt;Player (Hand Value: &lt;span id="handValuePlayer"&gt;&lt;/span&gt;)&lt;/legend&gt; &lt;div style="width:30px"&gt; &lt;svg class="checkmarkPlayer" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52"&gt; &lt;circle class="checkmark__circle" cx="26" cy="26" r="25" fill="none" /&gt; &lt;path class="checkmark__check" fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8" /&gt; &lt;/svg&gt; &lt;/div&gt; &lt;div id="playerCards"&gt;&lt;/div&gt; &lt;div id="cardContainerPlayer"&gt; &lt;div class="card templatePlayer"&gt; &lt;span class="playerCardFace"&gt;&lt;/span&gt; &lt;span class="playerCardSuit"&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="playerCardsHandValue"&gt;&lt;/div&gt; &lt;/fieldset&gt; &lt;fieldset id="result"&gt; &lt;legend&gt;Game Result&lt;/legend&gt; &lt;div id="gameResult"&gt;&lt;/div&gt; &lt;/fieldset&gt; &lt;/div&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="BlackJack.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T14:05:59.907", "Id": "424225", "Score": "0", "body": "Just wondering have you thought of using classes or separate files to clean up the logic and context so it's not just 1 big file but multiple small ones that easily follow the flow of the game?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T04:17:33.540", "Id": "424313", "Score": "0", "body": "In my C# BlackJack version, I split into several classes but in Javascript looks like very thing in the the method right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-29T15:09:37.883", "Id": "432449", "Score": "1", "body": "Note that 21 and BlackJack are not the same. BlackJack has priority over 21. BlackJack is 21 with 2 cards." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-18T07:45:43.190", "Id": "439857", "Score": "1", "body": "If you want to add real cards, see https://card-ts.github.io/playingcardts/" } ]
[ { "body": "<p>This looks like it showcases your skills well, and the comments will help anyone looking back to know that you're a programmer who is interested in doing their research and knowing things.</p>\n\n<p>I tested this in Chrome on my local computer.</p>\n\n<p>Your question included a mention about your timeout function not working. You'll need to make a stackoverflow question for that.</p>\n\n<p><strong>Overall:</strong></p>\n\n<p>This was very straight-forward to setup and the game works great! It is a little confusing visually that the cards aren't cleaned up after every game. Since the deck is reshuffled after each play.</p>\n\n<p>If you were to make a more advanced version, I'd suggest creating a way for hard-core blackjack players to count cards. Maybe look into the casino rules and see how often they shuffle cards back into the deck, or how many decks they play with. You may be able to create a more interesting game if the player can use the same strategies on your web-page game as they can in a casino!</p>\n\n<p><strong>Code:</strong></p>\n\n<p>Your HTML:</p>\n\n<ul>\n<li>Place all your .css and .js references in a head div. This is done so that when other developers come along they can see very quickly where all your styling and scripts are coming from.</li>\n</ul>\n\n<blockquote>\n<pre><code>&lt;head&gt;\n &lt;link href=\"check.css\" rel=\"stylesheet\"&gt;\n &lt;link href=\"BlackJack.css\" rel=\"stylesheet\"&gt;\n &lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"&gt;&lt;/script&gt;\n &lt;script src=\"BlackJack.js\"&gt;&lt;/script&gt;\n&lt;/head&gt;\n</code></pre>\n</blockquote>\n\n<p>Your CSS:</p>\n\n<ul>\n<li>Careful with pixel counts for view-sizes in css. Pixel counts are fine for borders, but for viewports and playing surfaces they can cause your code to become outdated, or make your webpage hard to view on a mobile device. Try to limit the amount of times you define a style element in terms of a large pixel count; and instead use percentages. Think about this when you're developing: \"I want my playing surface to take up 70% of the screen, that's 600px right now, but on a 4k display that would be much less; and on some phone displays it would be over 100% of the phone screen.\"</li>\n</ul>\n\n<p>Your JavaScript:</p>\n\n<ul>\n<li>Your logic in your javascript functions for *dealOneCardToPlayer * and *dealOneCardToDealer * is largely the same. This is not efficient and can be confusing for other developers, or you in the future. You need to identify what the difference in variables are in these functions and combine the functions to operate the same way on different data. You can pass in elements, objects, and dictionaries in javascript, so these don't need to be separate. The functions for <em>makeCardPlayer</em> and <em>makeCardDealer</em> could have the same thing happen to them, but it looks like it will require more values and more if/else checks, unless you break it up into smaller functions.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T01:49:25.683", "Id": "424309", "Score": "0", "body": "Thanks for the comment. Yeah, I wanted to reduce repeat code for that 2 methods. Just that, i am still contemplating on it because dealer has a hole card. About the css, I didn't realize that it is not mobile friendly. Ok, will check on it as well." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T14:39:09.983", "Id": "219642", "ParentId": "219638", "Score": "3" } }, { "body": "<p>I found the solution already to the timer issue. </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 deal = () =&gt; {\n init(); // Can be improved by continue to use the remaining card in the deck\n\n newDeck();\n\n // Option: to burn first card before deal a card\n // to the first player\n burnOneCard;\n\n setTimeout(function () {\n dealOneCardToPlayer(\"\", false);\n }, 500);\n\n setTimeout(function () {\n dealOneCardToDealer(false, false);\n }, 1000);\n\n setTimeout(function () {\n dealOneCardToPlayer(\"\", false);\n }, 1500);\n\n // true for hole card\n setTimeout(function () {\n dealOneCardToDealer(true, false);\n }, 2000);\n\n showGameButtons(true);\n checkEndGame1();\n checkGameOver();\n\n getDeckCardCount();\n\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-01T08:25:59.577", "Id": "432606", "Score": "2", "body": "Note that self-answers (like any other answer) are expected to *review the code*, not just present an alternative implementation without any reasoning." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-02T22:21:26.543", "Id": "432880", "Score": "1", "body": "This kind of thing would be for stack overflow. This is code review." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-29T01:12:36.700", "Id": "223178", "ParentId": "219638", "Score": "1" } } ]
{ "AcceptedAnswerId": "219642", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T12:54:05.660", "Id": "219638", "Score": "6", "Tags": [ "javascript", "jquery", "playing-cards" ], "Title": "BlackJack in Javascript" }
219638
<p>I recently discovered to joys of rust programming and I have written a tic-tac-toe game. I was hoping for some feedback on how it is made. (The reason <code>split</code> and <code>input</code> are separate functions is because this is part of a larger collection of games) </p> <pre><code>fn input(prompt: &amp;str) -&gt; String { let mut out = String::new(); print!("{}", prompt); std::io::Write::flush(&amp;mut std::io::stdout()).expect("flush failed!"); std::io::stdin().read_line(&amp;mut out).expect("Err: no input"); return out.trim().to_string(); } fn split(string_in: String, delimiters: Vec&lt;char&gt;) -&gt; Vec&lt;String&gt; { let mut out: Vec&lt;String&gt; = vec!(); let mut start: usize = 0; for (i, c) in string_in.chars().enumerate() { if delimiters.contains(&amp;c) { out.push(string_in[start..i].to_string()); start = i + 1; } if i == string_in.len() - 1 { out.push(string_in[start..i + 1].to_string()); } } return out; } fn tic_tac_toe() { fn get_input(plr: &amp;str) -&gt; (usize, usize) { let mut x; let mut y; loop { let coords = tools::split(tools::input(&amp;format!("{}'s move; Coordinates(x,y): ", plr)[..]), vec!(',')); if coords.contains(&amp;"exit".to_string()) { return (9usize, 9usize); } if coords.len() != 2 { println!("cannot parse coordinates. make sure it is formatted as: x,y\n(only comma, no space)\n"); continue; } match coords[0].parse::&lt;i32&gt;() { Ok(n) =&gt; x = n - 1, Err(_) =&gt; { println!("cannot parse coordinates. make sure it is formatted as: x,y"); continue; } } match coords[1].parse::&lt;i32&gt;() { Ok(n) =&gt; y = -n + 3, Err(_) =&gt; { println!("cannot parse coordinates. make sure it is formatted as: x,y"); continue; } } if x &gt; -1 &amp;&amp; x &lt; 3 &amp;&amp; y &gt; -1 &amp;&amp; y &lt; 3 { return (x as usize, y as usize); } println!("invalid coordinates. valid indices are from 1 to 3"); } } fn vertical(brd: &amp;[[&amp;str; 3]; 3], ind: usize) -&gt; String { let winner = brd[0][ind]; for x in 1usize..3 { if brd[x][ind] != winner || winner == " ".to_string() { return String::new(); } } return winner.to_string(); } fn horizontal(brd: &amp;[[&amp;str; 3]; 3], ind: usize) -&gt; String { let winner = brd[ind][0]; for x in 1usize..3 { if brd[ind][x] != winner || winner == " ".to_string() { return String::new(); } } return winner.to_string(); } let mut board: [[&amp;str; 3]; 3] = [[" "; 3]; 3]; let plrs = ["X", "O"]; let mut current: usize = 0; loop { let mut exit: bool = false; let mut tie: bool = true; for (i, row) in board.iter().enumerate() { print!(" | | \n "); for (j, elem) in row.iter().enumerate() { if j == row.len() - 1 { print!(" {}", elem); } else { print!(" {} |", elem); } } if i == board.len() - 1 { println!("\n | |"); } else { println!("\n ___|___|___"); } } for x in 0usize..3 { let win_v = vertical(&amp;board, x); let win_h = horizontal(&amp;board, x); let mut stop: bool = false; if win_v != "".to_string() { println!("{} wins!", win_v); stop = true; } else if win_h != "".to_string() { println!("{} wins!", win_h); stop = true; } if stop { exit = true; break; } } let winner = board[2][2]; if board[0][0] == winner &amp;&amp; board[1][1] == winner &amp;&amp; winner != " " { println!("{} wins!", winner); break; } let winner = board[2][0]; if board[0][2] == winner &amp;&amp; board[1][1] == winner &amp;&amp; winner != " " { println!("{} wins!", winner); break; } for row in board.iter() { if row.contains(&amp;" ") { tie = false; } } if tie &amp;&amp; !exit { println!("Tie!"); break; } if exit { break; } loop { let mov = get_input(plrs[current]); if mov == (9usize, 9usize) { return; } if board[mov.1][mov.0] == " " { board[mov.1][mov.0] = plrs[current]; break; } else { println!("cant move there"); } } current += 1; current %= 2; } let again = tools::input("Again(y/n)? "); if again == "y".to_string() { tic_tac_toe() } } fn main() { tic_tac_toe(); } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T15:43:53.797", "Id": "219644", "Score": "1", "Tags": [ "tic-tac-toe", "rust" ], "Title": "Tic-Tac-Toe Game in Rust" }
219644
<p>I finally finished the code for a snake game I was working on. I would like it if you were to give me some advice as to things that can be improved.</p> <pre><code>#ifndef UNICODE #define UNICODE #endif #include &lt;iostream&gt; #include &lt;Windows.h&gt; #include &lt;conio.h&gt; #include &lt;ctime&gt; #include &lt;random&gt; #include &lt;queue&gt; #include "Snake_segment.h" typedef std::deque&lt;Snake_segment&gt; Snake_container; const enum direction { UP = 0, RIGHT, DOWN, LEFT }; // Constant variables int nScreenWidth; int nScreenHeight; const int nFieldWidth = 40; const int nFieldHeight = 15; int score = 0; bool bIsHit = true; direction dir = direction::RIGHT; void clear(wchar_t* buf); void update(HANDLE hConsole, Snake_container&amp; body, wchar_t* buf); void directionCheck(char value); void move(Snake_container&amp; body, wchar_t* buf); void genFood(wchar_t* buf); void clearOnly(wchar_t* buf); int main(void) { DWORD dwbyteswritten = 0; HANDLE stdH = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO csbi; GetConsoleScreenBufferInfo(stdH, &amp;csbi); nScreenWidth = csbi.dwSize.X; nScreenHeight = csbi.dwSize.Y; wchar_t* temp = new wchar_t[nScreenWidth * nScreenHeight]; clear(temp); bool bPlay = false; while (true) { int choice; std::wcout &lt;&lt; L"1. Play" &lt;&lt; std::endl; std::wcout &lt;&lt; L"2. Quit" &lt;&lt; std::endl; std::cin &gt;&gt; choice; if (choice == 1) { bIsHit = false; bPlay = true; break; } else if (choice == 2) { return 0; } else { std::wcout &lt;&lt; L"Invalid input!"; WriteConsoleOutputCharacter(stdH, temp, nScreenHeight * nScreenWidth, { 0, 0 }, &amp;dwbyteswritten); } } const HANDLE hConsole = CreateConsoleScreenBuffer( GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL ); // Sets up the snake body Snake_container body; Snake_segment head; head.posx = nFieldWidth / 2; head.posy = nFieldHeight / 2; body.push_back(head); Snake_segment tail = head; --tail.posx; body.push_back(tail); // Builds the game buffer and clears it wchar_t* buffer = new wchar_t[nScreenWidth * nScreenHeight]; SetConsoleActiveScreenBuffer(hConsole); clear(buffer); // Generates food and draws game update(hConsole, body, buffer); genFood(buffer); // Main game loop while (!bIsHit) { if (_kbhit()) directionCheck(_getch()); move(body, buffer); update(hConsole, body, buffer); clear(buffer); Sleep(200); } CloseHandle(hConsole); if (bPlay) { WriteConsoleOutputCharacter(stdH, temp, nScreenHeight * nScreenWidth, { 0, 0 }, &amp;dwbyteswritten); std::wcout &lt;&lt; L"Game over!" &lt;&lt; std::endl; std::wcout &lt;&lt; L"Score: " &lt;&lt; score &lt;&lt; std::endl; Sleep(1000); } CloseHandle(stdH); return 0; } void update(HANDLE hConsole, Snake_container&amp; body, wchar_t* buf) { DWORD dwBytesWritten = 0; // Draws the screen for (int i = 0; i &lt; nFieldHeight; ++i) { for (int j = 0; j &lt; nFieldWidth; ++j) { // Draws top and bottom walls if (i == 0 || i == nFieldHeight - 1) buf[i * nScreenWidth + j] = L'#'; // Draws left and right walls else if (j == 0 || j == nFieldWidth - 1) buf[i * nScreenWidth + j] = L'#'; // Draws free space else if (buf[i * nScreenWidth + j] != L'*') buf[i * nScreenWidth + j] = L' '; // Prints snake for (int k = 0, n = body.size(); k &lt; n; ++k) { // Prints snake if (buf[body[0].posx + body[0].posy * nScreenWidth] == L'#') bIsHit = true; else if (buf[body[0].posx + body[0].posy * nScreenWidth] == L'o') bIsHit = true; else if (body[k].posx == j &amp;&amp; body[k].posy == i) if (k) buf[i * nScreenWidth + j] = L'o'; else buf[i * nScreenWidth + j] = L'@'; } } } for (int i = 0; i &lt; 37; ++i) buf[nFieldHeight * nScreenWidth + i] = L"Use 'w, a, s, d' to change directions"[i]; WriteConsoleOutputCharacter(hConsole, buf, nScreenWidth * nScreenHeight, { 0, 0 }, &amp;dwBytesWritten); } // Clears the buffer void clear(wchar_t* buf) { for (int i = 0; i &lt; nScreenHeight; ++i) { for (int j = 0; j &lt; nScreenWidth; ++j) if(buf[i * nScreenWidth + j] != L'*') buf[i * nScreenWidth + j] = L' '; } } // Changes the directions according to the value void directionCheck(char value) { switch (value) { case 'a': if (dir != direction::RIGHT) dir = direction::LEFT; break; case 'w': if (dir != direction::DOWN) dir = direction::UP; break; case 'd': if (dir != direction::LEFT) dir = direction::RIGHT; break; case 's': if (dir != direction::UP) dir = direction::DOWN; } } // Moves the snake appropriately void move(Snake_container&amp; body, wchar_t* buf) { body[0].prevXpos = body[0].posx; body[0].prevYpos = body[0].posy; switch (dir) { case direction::RIGHT: ++body[0].posx; break; case direction::DOWN: ++body[0].posy; break; case direction::LEFT: --body[0].posx; break; case direction::UP: --body[0].posy; } for (int i = 1, n = body.size(); i &lt; n; ++i) { body[i].prevXpos = body[i].posx; body[i].prevYpos = body[i].posy; body[i].posx = body[i - 1].prevXpos; body[i].posy = body[i - 1].prevYpos; } if (buf[body[0].posx + body[0].posy * nScreenWidth] == L'*') { Snake_segment tail_thing; tail_thing.posx = body[body.size() - 1].prevXpos; tail_thing.posy = body[body.size() - 1].prevYpos; body.push_back(tail_thing); clearOnly(buf); genFood(buf); score += 100; } } // Generates the food void genFood(wchar_t* buf) { int fX; int fY; do { time_t tim = time(NULL); srand(tim + rand()); fX = rand() % (nFieldWidth - 2) + 1; fY = rand() % (nFieldHeight - 2) + 1; } while (buf[fX + fY * nScreenWidth] != L' '); buf[fX + fY * nScreenWidth] = L'*'; } // Only clears * characters void clearOnly(wchar_t* buf) { for (int i = 0; i &lt; nScreenHeight; ++i) { for (int j = 0; j &lt; nScreenWidth; ++j) if (buf[i * nScreenWidth + j] == L'*') buf[i * nScreenWidth + j] = L' '; } } </code></pre> <p>File "Snake_segment.h" looks like this:</p> <pre><code>class Snake_segment { public: int posx, posy, prevXpos, prevYpos; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T16:39:55.243", "Id": "424242", "Score": "0", "body": "Have you run this yet and does it work? If so, what is the development environment and the operating system (include version of the operating system)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T16:41:13.003", "Id": "424243", "Score": "0", "body": "It does indeed work, the ide is VS 2019 and the os is win32" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T17:13:33.823", "Id": "424250", "Score": "0", "body": "I could run it in Win7 x64 VS2017" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T17:54:53.283", "Id": "424266", "Score": "1", "body": "It doesn't run in VS 2015 though" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T18:16:23.673", "Id": "424275", "Score": "0", "body": "I can't run it in either VS 2015 or 2017." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T21:55:40.917", "Id": "424297", "Score": "0", "body": "@pacmaninbw It ran fine in VS2017 for me" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T14:53:16.670", "Id": "424348", "Score": "2", "body": "Could you attach the screenshot of this game?" } ]
[ { "body": "<p>First of all congratulations for this little entertaining console game.</p>\n\n<p>It is simple but entertaining. I felt like I was back in the old mobile games era.</p>\n\n<p>I don't have the time to rewrite all of the code but I still want to give some hints for improvements.</p>\n\n<p>Here are some random observations:</p>\n\n<p>Don't use global variables, they are a maintenance hazard.\nConsider using classes in C++ to share the data between functions (This is C++ not C).</p>\n\n<p>Try to encapsulate concepts in several classes to make the maintenance of the program easier. You could have for example a Class Gameboard which describes the Gameboard and a class Snake which describes the Snake. A class for the Food. You already started doing a Snake_segment. Try to make some more. I suggest to read about C++ classes.</p>\n\n<p>Also you should try to write smaller functions. A Function should ideally only do one thing not several things. This way functions are also easier to test.</p>\n\n<p>Did I say test? I recommend checking out how to write unit tests. By writing tests you will realize that your functions are too big or can get divided into smaller parts. You can use a framework like gtest or sth else.</p>\n\n<p>Why do you use whchar_t* for the buffer? I recommend using <code>std::wstring</code>.</p>\n\n<p>Instead of using a deque you should check out std::vector it is the default container you should use in C++.</p>\n\n<p>Both containers handle memory allocation automatically for you. Only very rarely you should feel the need for using <code>new</code></p>\n\n<p>this:</p>\n\n<pre><code>wchar_t* temp = new wchar_t[nScreenWidth * nScreenHeight];\n</code></pre>\n\n<p>can become this:</p>\n\n<pre><code>std::wstring temp(nScreenWidth * nScreenHeight, ' ');\n</code></pre>\n\n<p>By replacing this you can also simplify your clearOnly function. </p>\n\n<p>This:</p>\n\n<pre><code> void clearOnly(wchar_t* buf) {\n for (int i = 0; i &lt; nScreenHeight; ++i) {\n for (int j = 0; j &lt; nScreenWidth; ++j)\n if (buf[i * nScreenWidth + j] == L'*')\n buf[i * nScreenWidth + j] = L' ';\n }\n}\n</code></pre>\n\n<p>Can become this:</p>\n\n<pre><code>#include &lt;algorithm&gt;\n\n....\n\nvoid clearOnly(std::wstring&amp; buf) \n{\n std::replace(buf.begin(), buf.end(), L'*', L' ');\n}\n</code></pre>\n\n<p>Some Style observations</p>\n\n<p>This:</p>\n\n<pre><code> // Draws top and bottom walls\n if (i == 0 || i == nFieldHeight - 1) buf[i * nScreenWidth + j] = L'#';\n</code></pre>\n\n<p>Should be this:</p>\n\n<pre><code> // Draws top and bottom walls\n if (i == 0 || i == nFieldHeight - 1) {\n buf[i * nScreenWidth + j] = L'#';\n }\n</code></pre>\n\n<p>Reason: Readability</p>\n\n<p>this:</p>\n\n<pre><code>int main(void) {\n ...\n return 0;\n}\n</code></pre>\n\n<p>should be this:</p>\n\n<pre><code>int main() {\n ...\n}\n</code></pre>\n\n<p>Reason: In C++ unlike C it is not common to write explicit <code>void</code> if there are no function parameters. Also for the main function the compiler automatically generates the <code>return 0</code></p>\n\n<p>Feel free to rework the code and post it again. I'm pretty sure you can refactor a lot...</p>\n\n<p><strong>EDIT: Refactored Code:</strong></p>\n\n<p>I ended up having time and refactored all youre code here:</p>\n\n<p><a href=\"https://codereview.stackexchange.com/questions/219886/snake-console-game-in-c\">Snake console game in C++</a></p>\n\n<p>I will edit here later when i find time what other suggestions for improvements i could find while i tryed to understand youre program.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p><strong>use namespaces:</strong> It is good practice in C++ wrapping youre programs into youre own namespace. This avoids name conflicts with existing functions from libraries.</p>\n\n<p><strong>Don't use std::endl:</strong> <code>std::endl</code> adds a newline and flushes the buffer. Most of the time you only want a simple newline. You get it by replacing <code>std::endl</code> with the newline sign '\\n' (like in c). Why bother? <a href=\"https://stackoverflow.com/questions/213907/c-stdendl-vs-n\">https://stackoverflow.com/questions/213907/c-stdendl-vs-n</a></p>\n\n<p><strong>seperate different tasks from each other:</strong> That way parts of youre program can be even reused in other projects. A good example is youre not portable output to the console. The output is all over the place mixed with the other logic of of the program. This way you can't easy port the program to annother output source (for example a gui). When i rewrote the program i packed all the not portable output stuff in one place from the other tasks.</p>\n\n<p>Also by writting everything connected with each other it is a big headache to understand whats going on in the code. Take this code. Forget it for a year and try to figure out what it does. Probaly its hard again to get into it.</p>\n\n<p>It took me quite some time to untie all the knots to reveal what was really going on in youre program.</p>\n\n<p><strong>How could you organize the snake game better? I did the following:</strong></p>\n\n<p>Defining a struct Element:</p>\n\n<pre><code>struct Element {\n bool hasSnakeSegment{ false };\n bool hasSnakeHead{ false };\n bool hasWall{ false };\n bool hasFood{ false };\n};\n</code></pre>\n\n<p>This Element can either have a snakeSegment, a snakeHead, a Wall or food. We can easily check with this whats going on on each field.</p>\n\n<p>Then i defined a Point class for the Elements of the Snake and the SnakeSegment containing the previous and current poition of the segments:</p>\n\n<pre><code>struct Point {\n int x;\n int y;\n};\n\nstruct SnakeSegment\n{\n Point pos{ 0 , 0 };\n Point prev{ pos };\n};\n</code></pre>\n\n<p>This SnakeSegments of course for the Snake:</p>\n\n<pre><code>class Snake\n{\npublic:\n Snake(int boardWidth, int boardHeight);\n\n std::vector&lt;SnakeSegment&gt; getBody() const;\n\n void moveRight();\n void moveDown();\n void moveLeft();\n void moveUp();\n void grow();\n\nprivate:\n void safeCurrentPosToLastOfFirstElement();\n void moveRemainingElements();\n\n std::vector&lt;SnakeSegment&gt; mBody;\n};\n\nstd::vector&lt;SnakeSegment&gt; initSnake(int fieldWidth, int fieldHeight);\n</code></pre>\n\n<p>The Snake class defines were the Snake is on the Board and how to move it arround. Also we can grow the snake.</p>\n\n<p>Then I defined the Board. This is were the game actions take place:</p>\n\n<pre><code>class Board\n{\npublic:\n Board(int width, int height);\n\n void placeFood();\n void updateSnakePosition();\n bool snakeHitFood() const;\n void eatFood();\n void growSnake();\n bool snakeHitWall() const;\n bool snakeHitSnake() const;\n void moveSnake(SnakeDirection snakeDirection);\n\n void debugPrintSnakeCoordinates();\nprivate:\n std::vector&lt;std::vector&lt;Element&gt;&gt; initFieldWithWalls(int width, int height);\n void removeOldSnakePosition(const std::vector&lt;SnakeSegment&gt;&amp; body);\n void addNewSnakePosition(const std::vector&lt;SnakeSegment&gt;&amp; body);\n\n Snake mSnake;\n std::vector&lt;std::vector&lt;Element&gt;&gt; mField;\n\n std::random_device mRandomDevice;\n std::default_random_engine mGenerator;\n std::uniform_int_distribution&lt;int&gt; mWidthDistribution;\n std::uniform_int_distribution&lt;int&gt; mHeightDistribution;\n\n friend std::wostream&amp; operator&lt;&lt;(std::wostream&amp; os, const Board&amp; obj);\n};\n\nstd::wostream&amp; operator&lt;&lt;(std::wostream&amp; os, const Board&amp; obj);\n</code></pre>\n\n<p>Then i defined functions how to display the game in the console. If needed they can be replaced with other functions if we want to dsiplay on annother thing than a console.</p>\n\n<p>The board and the output functions get used by the runGame function. So the main becomes only this:</p>\n\n<pre><code>#include \"Game.h\"\n\n#include &lt;iostream&gt;\n\nint main() \ntry {\n snakeGame::runGame();\n return 0;\n}\ncatch (...) {\n std::wcerr &lt;&lt; \"unknown error \" &lt;&lt; \"\\n\";\n std::wcin.get();\n}\n</code></pre>\n\n<p>So the main logic of the programm can be read in the runGame function:</p>\n\n<pre><code>void runGame()\n{\n for (;;) {\n\n if (askUserToEndGame()) {\n return;\n }\n\n constexpr auto fieldWidth = 40;\n constexpr auto fieldHeight = 15;\n\n Board board{ fieldWidth, fieldHeight };\n board.updateSnakePosition();\n board.placeFood();\n SnakeDirection snakeDirection = SnakeDirection::right;\n\n long long score{ 0 };\n long long points{ 100 };\n auto delay(300);\n\n bool wasPausedInLastLoop{ false };\n for (;;) {\n putCursorToStartOfConsole();\n printBoardWithStats(board, score, delay);\n\n if (wasPausedInLastLoop) {\n // If we don't do this and print pause to the console by \n // pressing p during the game the pause statement will \n // still be printed because during the game the pause \n // statement will still be printed because during the game \n // the pause statement will still be printed because \n // during the game the pause statement will still be \n // printed because we start printing from the beginning of\n // the console and now the total string printed to the \n // console would be one row lower.\n std::wcout &lt;&lt; L\" \\n\";\n wasPausedInLastLoop = false;\n }\n\n if (keyWasPressed()) {\n auto key = getKey();\n\n if (key == 'p') {\n wasPausedInLastLoop = true;\n std::wcout &lt;&lt; L\"#####PAUSED#####\\n\";\n pauseUntilPauseKeyPressedAgain();\n }\n else {\n snakeDirection = updateDirection(key, snakeDirection);\n }\n }\n\n board.moveSnake(snakeDirection);\n\n if (board.snakeHitFood()) {\n board.eatFood();\n board.growSnake();\n board.placeFood();\n score += points;\n points *= 2;\n delay -= 5;\n }\n else if (board.snakeHitWall() || board.snakeHitSnake()) {\n break;\n }\n board.updateSnakePosition();\n\n std::this_thread::sleep_for(std::chrono::milliseconds{ delay });\n }\n\n printGameOverWithScore(score);\n }\n}\n</code></pre>\n\n<p>}</p>\n\n<p>Notice here how the low level stuff doesn't show up because it is encapsulated in other functions the main calls. I don't say my implementation is perfect but i hope it gives some insight how to seperate tasks.</p>\n\n<p>For the full code see this: <a href=\"https://codereview.stackexchange.com/questions/219886/snake-console-game-in-c\">Snake console game in C++</a>\nand feel free to also discuss my solution.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T17:21:37.107", "Id": "424253", "Score": "0", "body": "Thank you for the advice. really the only reason i used new wchar_t* is cause i took inspiration from javidx9(olc) and the global variables were because i didn't know how to setup the class, so i just went the easier route." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T17:27:34.097", "Id": "424255", "Score": "4", "body": "Dont't worry. C++ is a big language you don't learn it on one day. I suggest reading one or two books about it and doing alot of coding to get better. Also it helps if you post more projects to review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T17:30:54.127", "Id": "424256", "Score": "0", "body": "by the way, i cannot initialize a wstring the way you described it. std::string temp(nScreenWidth * nScreenHeight); gives me an error" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T17:31:47.420", "Id": "424257", "Score": "1", "body": "it was a typo it should be std::wstring i changed it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T17:33:47.607", "Id": "424258", "Score": "0", "body": "still an error, to be honest and even when i go look on cppreference i see that wstring constructor doesn't define the size of the string, and if i use [] operators i have to use the keyword new since it's dynamic memory allocation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T17:35:04.550", "Id": "424260", "Score": "1", "body": "did you #inclue <string> ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T17:36:11.823", "Id": "424262", "Score": "0", "body": "i did and it still gives me the error" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T17:38:37.403", "Id": "424264", "Score": "1", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/93200/discussion-between-sandro4912-and-nadpher)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T18:30:41.883", "Id": "424277", "Score": "0", "body": "The only suspect thing is using `std::wstring`. This is an area of memory so I would use `std::vector<wchar_t>`. You are using this as an array not a string. So I would prefer to see the type reflect that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T00:08:51.413", "Id": "424303", "Score": "0", "body": "As of C++11 you shouldn't be using `std::wstring temp(nScreenWidth * nScreenHeight, ' ');`, you should prefer `std::wstring temp { nScreenWidth * nScreenHeight, ' ' };`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T07:37:46.880", "Id": "424319", "Score": "0", "body": "normally i would agree with the {} but in this case you get a initalization with a std::initalizer_list or don't you?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T10:41:56.703", "Id": "424430", "Score": "1", "body": "@Pharap Usually `()` is used with constructors that involve size to clarify and to prevent potential problems." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T17:10:13.900", "Id": "219658", "ParentId": "219645", "Score": "9" } }, { "body": "<p>First on my Windows 10 computer in both Visual Studio 2015 and Visual Studio 2017 the console is killed by this line in the <code>update</code> function.</p>\n\n<pre><code> WriteConsoleOutputCharacter(hConsole, buf, nScreenWidth * nScreenHeight, { 0, 0 }, &amp;dwBytesWritten);\n</code></pre>\n\n<p>This may have to do with settings on my computer.</p>\n\n<p>Second I get this warning message in both VS 2015 and 2017:</p>\n\n<p>warning C4244: 'argument': conversion from 'time_t' to 'unsigned int', possible loss of data</p>\n\n<p>on this line in the <code>genFood()</code> function.</p>\n\n<pre><code> srand(tim + rand());\n</code></pre>\n\n<p>It is generally not a good practice to ignore warning messages or disable warning messages.</p>\n\n<p>Is there only one food item expected? That is all <code>genFood()</code> is placing in the buffer if food is represented by <code>*</code> (asterisk)?</p>\n\n<p>The function <code>srand()</code> only needs to be called once per game after that <code>rand()</code> has been seeded and will generate different numbers each time. The call to <code>srand()</code> can probably be moved to <code>main()</code>.</p>\n\n<p><strong>Class Versus Struct</strong><br>\nC++ has other object types besides classes. One such object type is <code>struct</code>. In a <code>struct</code> by default all fields are public. A struct can also contain methods.</p>\n\n<p>There is no reason to make <code>Snake_segment</code> a class, it has no methods, no constructor and no destructor.</p>\n\n<p><strong>Constants</strong><br>\nHaving global constants such as <code>nFieldWidth</code> and <code>nFieldHeight</code> are good, however, to the person reviewing the code they look like variables. It might be better to make their names all CAPITALS to show that they are global constants.</p>\n\n<p><strong>Complexity</strong><br>\nThis has been discussed in another answer, but there are clearly multiple functions in <code>main()</code> that should be in their own function. The code to get the user input including the <code>while(true)</code> loop should be in it's own function.</p>\n\n<p>Another possible function is the initialization of the board.</p>\n\n<p>The main game loop is also another good function.</p>\n\n<p>As programs grow larger the main function becomes responsible for processing, each action of main should probably be encapsulated in a function. The primary job of main is:<br>\n - process any command line arguements<br>\n - set up for the main processing<br>\n - execute the main processing<br>\n - clean up after the program has finished<br>\n - handle any exceptions that are thrown (this might be handled any multiple levels in the program).</p>\n\n<p><strong>Style</strong><br>\nAs mentioned in another answer, it might be better to have the <code>then</code> clause of an if statement on a second line and to wrap it in braces. This allows for additional code to be added at a later time without changing the structure of the program. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T18:01:42.403", "Id": "219661", "ParentId": "219645", "Score": "5" } }, { "body": "<p>You include the modern random.</p>\n\n<pre><code>#include &lt;random&gt;\n</code></pre>\n\n<p>But in your code you use the old <code>srand()</code> and <code>rand()</code> functions. Also your usage of these functions is not correct.</p>\n\n<pre><code> time_t tim = time(NULL);\n srand(tim + rand());\n fX = rand() % (nFieldWidth - 2) + 1;\n fY = rand() % (nFieldHeight - 2) + 1;\n</code></pre>\n\n<p>Here you are abusing the seeding of rand. The point about seeding is to have a starting point. Once you have established a starting point the following sequence of number <strong>should</strong> have an even distribution and be somewhat randomish (Lets not get into the argument that rand is not good at either that's what it was supposed to be). By re-seeding before each call to rand you are throwing away any chance at even distribution.</p>\n\n<p>The standard argument is that you should use <code>srand()</code> once in the application (just after startup is good). Then simply call <code>rand()</code> when you need a new value.</p>\n\n<pre><code>int main()\n{\n srand(time());\n ...\n // CODE that uses rand()\n}\n</code></pre>\n\n<p>Now coming back to the problem with rand() family. We have all know that rand has been pretty broken for a while (its fine for simple problems (like games like this)). But as a result the modern <code>&lt;random&gt;</code> library was introduced that has a much better random library and it is simply just a much better idea to use this new library (even in small games like this).</p>\n\n<pre><code>int main()\n{\n std::default_random_engine generator;\n std::uniform_int_distribution&lt;int&gt; widthDistribution(1,nFieldWidth-1);\n std::uniform_int_distribution&lt;int&gt; heightDistribution(1,nFieldHeight-1);\n\n // Some stuff\n\n fX = widthDistribution(generator);\n fY = heightDistribution(generator);\n</code></pre>\n\n<hr>\n\n<p>Sure:</p>\n\n<pre><code>typedef std::deque&lt;Snake_segment&gt; Snake_container;\n</code></pre>\n\n<p>The modern way of doing this is:</p>\n\n<pre><code>using Snake_container = std::deque&lt;Snake_segment&gt;;\n</code></pre>\n\n<p>Personally not a fan of \"Snake Case\"</p>\n\n<hr>\n\n<p>These are not const!!!</p>\n\n<pre><code>// Constant variables\nint nScreenWidth;\nint nScreenHeight;\n</code></pre>\n\n<hr>\n\n<p>OK. So this is a C application (that happens to use some C++ features).</p>\n\n<pre><code>void clear(wchar_t* buf);\nvoid update(HANDLE hConsole, Snake_container&amp; body, wchar_t* buf);\nvoid directionCheck(char value);\nvoid move(Snake_container&amp; body, wchar_t* buf);\nvoid genFood(wchar_t* buf);\nvoid clearOnly(wchar_t* buf);\n</code></pre>\n\n<p>If we created some class types we can group these function somewhat more logically and potentially isolate the variables so you don't accidently cause tight coupling between them.</p>\n\n<p>I can see:</p>\n\n<ul>\n<li>Screen Object</li>\n<li>Snake Object (That can be drawn on a screen)\n\n<h2>* There seems to be a <code>wchar_t</code> buffer being passed around.</h2></li>\n</ul>\n\n<p>Manual memory management:</p>\n\n<pre><code> wchar_t* temp = new wchar_t[nScreenWidth * nScreenHeight];\n</code></pre>\n\n<p>This is a bad idea. If there is an exception it leaks (OK in this context maybe not) but it is a bad habit. Get used to using containers (or smart pointers) when you need dynamic allocation. This simply looks like a buffer. So use std::vector</p>\n\n<pre><code> std::vector&lt;wchar_t&gt; temp(nScreenWidth * nScreenHeight);\n</code></pre>\n\n<p>All memory management handeled.</p>\n\n<p>In modern C++ it is very rare to see naked new/delete.</p>\n\n<hr>\n\n<p>Always check that the read worked.</p>\n\n<pre><code> std::cin &gt;&gt; choice;\n\n // Should be:\n\n if ((std::cin &gt;&gt; choice) &amp;&amp; (choice == 1 || choice ==2)) {\n // user question worked.\n }\n else {\n // user input failed.\n</code></pre>\n\n<h2> }</h2>\n\n<p>Looks like a snake constructor:</p>\n\n<pre><code> // Sets up the snake body\n Snake_container body;\n Snake_segment head;\n head.posx = nFieldWidth / 2; head.posy = nFieldHeight / 2;\n body.push_back(head);\n Snake_segment tail = head;\n</code></pre>\n\n<p>You should isolate this code in its own class.</p>\n\n<hr>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T00:15:29.957", "Id": "424305", "Score": "0", "body": "@Pharap \"Shouldn't\"? Why shouldn't I? Are the results different?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T01:07:22.073", "Id": "424307", "Score": "0", "body": "Actually, ignore my comment. It seems that `std::vector` is one case where the new uniform initialisation syntax behaves differently because the curly braces get interpreted as an initialiser list rather than calling the intended constructor. In other cases though, uniform initialiser syntax is now the preferred syntax because it avoids the most vexing parse problem and will give a compiler error if there's any implicit _narrowing_ conversions occurring (which can be fixed by using some explicit casts)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T09:52:24.067", "Id": "424330", "Score": "0", "body": "This is a good answer. I would also add that `Snake_container` is a bad name, it's just like having `class Snake_class` or something like that. No standard container is named `vector_container` or `deque_container` either. So maybe a better name would just be `Snake`, for instance." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T21:54:56.203", "Id": "219678", "ParentId": "219645", "Score": "7" } } ]
{ "AcceptedAnswerId": "219658", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T15:49:52.990", "Id": "219645", "Score": "11", "Tags": [ "c++", "beginner", "console", "snake-game" ], "Title": "My first C++ game (snake console game)" }
219645
<blockquote> <p>Given a binary tree, determine if it is a valid binary search tree (BST).</p> <p>Assume a BST is defined as follows:</p> <p>The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees.</p> </blockquote> <p><strong>Example 1:</strong></p> <pre><code> 2 / \ 1 3 Input: [2,1,3] Output: true </code></pre> <p><strong>Example 2:</strong></p> <pre><code> 5 / \ 1 4 / \ 3 6 Input: [5,1,4,null,null,3,6] Output: false Explanation: The root node's value is 5 but its right child's value is 4. </code></pre> <p>My solution</p> <ol> <li>Do inorder traversal and keep it in stack.</li> <li>Iterate through stack to see if any of the value on top is less than equal to second top. </li> </ol> <p>Definition for a binary tree node.</p> <pre><code> public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } class Solution { public void doInOrderTraversal(TreeNode root, Stack s) { if(root == null) { return; } doInOrderTraversal(root.left, s); s.push(root.val); doInOrderTraversal(root.right, s); } public boolean isValidBST(TreeNode root) { if(root == null) { return true; } Stack&lt;Integer&gt; stack = new Stack&lt;&gt;(); doInOrderTraversal(root, stack); while(!stack.isEmpty()) { int top = stack.pop(); if(stack.isEmpty()) { return true; } int secondTop = stack.peek(); if(top &lt;= secondTop) { return false; } } return true; } } </code></pre> <p>I was thinking to not use stack, but two values current and previous. And keep check if current is less than previous then only break. I am not sure, how to do this. Please suggest.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-13T15:01:26.540", "Id": "425425", "Score": "0", "body": "There is no need for a stack here, simply perform an inorder traversal and check the values as you go" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-13T15:42:24.147", "Id": "425429", "Score": "0", "body": "Please see my edited answer." } ]
[ { "body": "<p><strong>Your solution:</strong></p>\n\n<p>seems legit :)\nOne thing I'd suggest here is to use <code>ArrayDeque</code> instead of <code>Stack</code></p>\n\n<p><strong>Another possible solution</strong>:</p>\n\n<p>Basically, for every subtree we have constrain, that every node in it should be in range (X, Y).</p>\n\n<p>For root this range will be (-inf; +inf) - in other words, there could be any value in root.</p>\n\n<p>For root's left subtree range will be (-inf, value-in-root), for right - (value-in-root, +inf).</p>\n\n<p>Last thing - on each iteration we should check, that value in node is within this range, like so:</p>\n\n<pre><code>public boolean doInOrderTraversal(TreeNode root, int min, int max) {\n if (root == null) {\n return true;\n }\n if (root.val &lt;= min || root.val &gt;= max) {\n return false;\n }\n\n return doInOrderTraversal(root.left, min, root.val) &amp;&amp; doInOrderTraversal(root.right, root.val, max);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T05:59:33.350", "Id": "424687", "Score": "0", "body": "The empty return, when root is null, should be \"true\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T10:33:21.440", "Id": "424707", "Score": "0", "body": "@TorbenPutkonen fixed, thanks" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T22:18:46.027", "Id": "219725", "ParentId": "219646", "Score": "1" } }, { "body": "<p>Your code is correct and IMHO optimal for the algorithm it implements.<br>\nThe only two details I would recommend to change are:</p>\n\n<ul>\n<li>rename the node member <code>val</code> to <code>value</code> – there's no reason to strip the last two characters,</li>\n<li>and make the <code>doInOrderTraversal</code> method private – it seems useful inside this <code>Solution</code> only.</li>\n</ul>\n\n<p>What concerns the algorithm: yes, you can reach the same result without the additional <code>Stack</code> object. \nHere is an example of a full <strong>recursive test without an explicit stack</strong>.</p>\n\n<p>The base case is an empty tree, which is a valid BST.</p>\n\n<p>A left subtree of any node has values bounded from above by that node, similarly a right subtree values are bounded from below. It follows that any subtree is bounded by its closest left- and right-side ancestors (except the left-most branch, which has no left-side ancestor, and the right-most branch, which has no right-side ancestor; and a special case of the root node, which has no ancestor at all).</p>\n\n<p>(Using your <code>TreeNode</code> class.)</p>\n\n<pre><code>class Solution {\n\n public boolean isValidBST(TreeNode root) {\n return isValidBST(null, root, null);\n }\n\n private boolean isValidBST(TreeNode leftAncestor, TreeNode node, TreeNode rightAncestor) {\n // base case\n if (node == null)\n return true;\n\n // bounds by ancestors (duplicated keys not allowed; replace\n // &lt;= and &gt;= with &lt; and &gt;, respectvely, to allow duplicates)\n if (leftAncestor != null &amp;&amp; node.val &lt;= leftAncestor.val)\n return false;\n\n if (rightAncestor != null &amp;&amp; node.val &gt;= rightAncestor.val)\n return false;\n\n // this node valid - validate its subtrees; this node becomes\n // the closest right-side ancestor for its left subtree\n // and the closest left-side ancestor for its right subtree\n return\n isValidBST(leftAncestor, node.left, node) &amp;&amp;\n isValidBST(node, node.right, rightAncestor);\n }\n}\n</code></pre>\n\n<p>At the cost of additional conditions (which obfuscate the code a bit) you can save about a half of recursive calls:</p>\n\n<pre><code> public boolean isValidBST(TreeNode root) {\n return (root == null) || isValidBST(null, root, null);\n }\n\n private boolean isValidBST(TreeNode leftAncestor, TreeNode node, TreeNode rightAncestor) {\n assert node != null;\n\n // bounds by ancestors (duplicated keys not allowed; replace\n // &lt;= and &gt;= with &lt; and &gt;, respectvely, to allow duplicates)\n if (leftAncestor != null &amp;&amp; node.val &lt;= leftAncestor.val)\n return false;\n\n if (rightAncestor != null &amp;&amp; node.val &gt;= rightAncestor.val)\n return false;\n\n // this node valid - validate its subtrees; this node becomes\n // the closest right-side ancestor for its left subtree\n // and the closest left-side ancestor for its right subtree\n return\n (node.left == null || isValidBST(leftAncestor, node.left, node)) &amp;&amp;\n (node.right == null || isValidBST(node, node.right, rightAncestor));\n }\n</code></pre>\n\n<hr>\n\n<p><strong>If you're allowed to modify the tree...</strong></p>\n\n<p>...you can also get rid of the stack by transforming your tree into a list – it's the first stage of the <a href=\"https://en.wikipedia.org/wiki/Day%E2%80%93Stout%E2%80%93Warren_algorithm\" rel=\"nofollow noreferrer\">Day-Stout-Warren algorithm</a> to balance a BST.</p>\n\n<p>The algorithm is a constant-memory – it does not use a stack, it just iterates through the right-most branch of the tree while merging left subtrees into it.</p>\n\n<p>Then you can iterate through the list to check if values make a strictly increasing sequence.</p>\n\n<hr>\n\n<p>Of course you can make the final testing inside the tree-to-list transformation. That would save you one loop in the code structure, but it would also make the code much less readable with virtually no gain in efficiency.</p>\n\n<hr>\n\n<p><strong>I wonder, however,</strong> what do these notes mean:</p>\n\n<pre><code>Input: [2,1,3]\nInput: [5,1,4,null,null,3,6]\n</code></pre>\n\n<p>Are the code expected to read and parse the character line shown?<br>\nOr is it fed with an array?<br>\nIn the latter case, does it mean it's array of <code>Integer</code>s?<br>\nIf it is supposed to be array of <code>int</code>s, what does <code>null</code> represent?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T11:25:49.103", "Id": "219863", "ParentId": "219646", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T16:04:09.563", "Id": "219646", "Score": "1", "Tags": [ "java", "interview-questions", "tree", "stack" ], "Title": "Leetcode - find if BST is valid or not" }
219646
<p>Suppose I have some expensive function <code>expensive_computation</code> which takes a long time to compute but it always returns the same value.</p> <p>I want to avoid paying the cost of computing this function because it may never be called.</p> <p>Here is my solution to this, is there a more obvious or clean way to do it? Or maybe even some function from the standard library? </p> <pre class="lang-py prettyprint-override"><code>def lazy(function): internal_state = None def lazy_evaluation(): nonlocal internal_state if internal_state is None: internal_state = function() return internal_state return lazy_evaluation @lazy def expensive_computation(): print("Working ...") return "that was hard" print(expensive_computation()) print(expensive_computation()) </code></pre> <p>Which prints:</p> <pre><code>Working ... that was hard that was hard </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T16:31:34.237", "Id": "424241", "Score": "0", "body": "Suppose this isn't real code, then it's undeniably off-topic here. Is only `lazy` up for review, and do you want any and all facets of your code reviewed? [Please ensure your question is otherwise on-topic](https://codereview.stackexchange.com/help/on-topic)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T16:42:16.933", "Id": "424244", "Score": "0", "body": "Any review concerning the implementation of `lazy` or the use of such a construct is what I'm looking for. I'm not sure what you mean by \"real code\", it's some working code, where I replaced every piece on which I don't want advice on by dummy code (I don't need advice on the content of `expensive_computation`, that's why I don't provide its implementation). On the other hand, the implementation of `lazy` is the exact one I intend to use. I added the output to make clear what behaviour I expect (because I noticed the term \"lazy evaluation\" is actually broader than this use case)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T17:34:07.513", "Id": "424259", "Score": "0", "body": "Please see *[What to do when someone answers](/help/someone-answers)*. I have rolled back Rev 2 → 1." } ]
[ { "body": "<blockquote>\n<pre><code> if internal_state is None:\n internal_state = function()\n</code></pre>\n</blockquote>\n\n<p>What if <code>function()</code> returns <code>None</code>?</p>\n\n<hr>\n\n<blockquote>\n <p>Or maybe even some function from the standard library?</p>\n</blockquote>\n\n<p><a href=\"https://docs.python.org/3/library/functools.html#functools.lru_cache\" rel=\"nofollow noreferrer\"><code>functools.lru_cache</code></a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T16:48:03.817", "Id": "424247", "Score": "0", "body": "So how do you change the code with regard to the first point if `None` is a valid return?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T17:09:58.800", "Id": "424249", "Score": "0", "body": "My function never return `None`, but in the general case I guess that you would just have a boolean marker beside the `internal_state`, so you can tell if the function has been evaluated or not, but that's just a guess and probably not the best solution either. \nConcerning the cache solution I'll have a look at it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T17:18:32.263", "Id": "424252", "Score": "0", "body": "@Peilonrayz, the obvious approach would be to use a separate Boolean variable. An alternative, which I consider hackier, would be to not have a separate variable for `internal_state` at all: `result = function(); function = lambda () => result; return result`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T16:44:53.587", "Id": "219654", "ParentId": "219647", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T16:07:48.320", "Id": "219647", "Score": "1", "Tags": [ "python", "meta-programming", "lazy" ], "Title": "Lazy evaluation function decorator" }
219647
<p>I've found the following code invaluable in helping me 'handle' None values including "whitespace" characters that should be treated as None based on the situation. I have been using this code for quite some time now:</p> <pre><code>class _MyUtils: def __init__(self): pass def _mynull(self, myval, myalt, mystrip=True, mynullstrings=["", "None"], mynuminstances=(int, float)): # if the value is None, return the alternative immediately. if myval is None: return myalt # if the value is a number, it is not None - so return the original elif isinstance(myval, mynuminstances): return myval # if the mystrip parameter is true, strip the original and test that else: if mystrip: testval = myval.strip() else: testval = myval # if mynullstrings are populated, check if the upper case of the # original value matches the upper case of any item in the list. # return the alternative if so. if len(mynullstrings) &gt; 0: i = 0 for ns in mynullstrings: if ns.upper() == testval.upper(): i = i + 1 break if i &gt; 0: return myalt else: return myval else: return myval def main(): x = _MyUtils() print(x._mynull(None, "alternative_value", True, [""])) if __name__ == '__main__': main() </code></pre> <p>The code requires an input, an alternative to provide if input is found to be Null, whether to 'strip' the input during testing (if not a number), values to treat as 'equivalent' to None and types of number instances to determine if the input is numeric (and hence not none).</p> <p>Essentially, too many processes that we run depend upon not having None values in the data being processed&mdash;whether that be lambda functions, custom table toolsets, etc. This code gives me the ability to handle None values predictably, but I am sure there is a better approach here. Is there a more Pythonic way of doing this? How can this code be improved? How would others approach this problem?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T13:43:47.973", "Id": "424344", "Score": "0", "body": "This kind of imprecision is a reason why JavaScript can be so brittle. JavaScript is very liberal in converting values to other types. It's better to be strict about types and the values you allow for them. An unexpected value is a bug; it should not be silently corrected." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T09:56:51.313", "Id": "424416", "Score": "0", "body": "The 'fault' lies not with me, but with the dataset I am being provided with for analysis. If that dataset is imperfect, I have only limited choices - I can effectively fix the data at source (using similar code) or create a toolset that works relatively predictably across multiple datasets which was my intention here. Hope that clarifies my issue." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T10:05:25.420", "Id": "424422", "Score": "1", "body": "I see. I thought this util class was supposed to be used in regular code. As a data import helper this is very useful and totally appropriate. Fix the data as it enters the system." } ]
[ { "body": "<p>This loop could be rewritten:</p>\n\n<pre><code> if len(mynullstrings) &gt; 0:\n i = 0\n for ns in mynullstrings:\n if ns.upper() == testval.upper():\n i = i + 1\n break\n if i &gt; 0:\n return myalt\n else:\n return myval\n else:\n return myval\n</code></pre>\n\n<p>as:</p>\n\n<pre><code> if testval.upper() in [ns.upper() for ns in mynullstrings]:\n return myalt\n else:\n return myval\n</code></pre>\n\n<p>I would also rewrite this:</p>\n\n<pre><code> if mystrip:\n testval = myval.strip()\n else:\n testval = myval\n</code></pre>\n\n<p>as:</p>\n\n<pre><code> if mystrip:\n myval= myval.strip()\n</code></pre>\n\n<p>and continue to use <code>myval</code>. This seems clearer to me.</p>\n\n<p>Personally, I don't think prepending 'my' is a good style&mdash;variable names should be descriptive in and of themselves.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T16:46:10.990", "Id": "424246", "Score": "2", "body": "also note that [`str.casefold()`](https://docs.python.org/3/library/stdtypes.html#str.casefold) is recommended for comparing strings. see for example https://stackoverflow.com/q/45745661/1358308 and https://stackoverflow.com/q/40348174/1358308" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T10:00:09.547", "Id": "424420", "Score": "0", "body": "I really like how you have crushed my multi-line loops into a far more pythonic version here. Thank you." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T13:16:46.087", "Id": "219650", "ParentId": "219649", "Score": "4" } }, { "body": "<p>Generally I don't think you should have a class for this functionality. There's no state and no particular meaning to <code>MyUtils</code> object here. You can make this into a long function in whatever module you deem appropriate in your codebase.</p>\n\n<p>I think this function as written is a code smell. It 1) doesn't cover a whole lot of types and 2) implies that where you're using it you're not going to have even a rough idea of what type of data you're expecting. In most cases you will have some idea, and even then it's not usually a good idea to do explicit type checking.</p>\n\n<p>Where you're using this for numbers you can replace it with <code>myval if myval is not None else mydefault</code>.</p>\n\n<p>A function like this may be more useful for strings, for which there are a wider range of essentially empty values. Perhaps something like this</p>\n\n<pre><code>def safe_string(s, default=\"\", blacklist=[\"None\"]):\n if s is None or len(s.strip()) == 0:\n return default\n if s.upper() in [b.upper() for b in blacklist]:\n return default\n return s\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T09:58:32.773", "Id": "424419", "Score": "0", "body": "agreed on the Class statement, thank you." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T13:32:21.457", "Id": "219651", "ParentId": "219649", "Score": "6" } }, { "body": "<p>Apart from the \"blacklist\" feature, you can in many cases just use <code>or</code> to use a \"default\" value if the first argument is falsy. Some example:</p>\n\n<pre><code>&gt;&gt;&gt; \"foo\" or \"default\"\n'foo'\n&gt;&gt;&gt; \"\" or \"default\"\n'default'\n&gt;&gt;&gt; None or \"default\"\n'default'\n</code></pre>\n\n<p>And similar for numbers, lists, etc. </p>\n\n<pre><code>for x in list_that_could_be_none or []:\n print(x * (number_that_could_be_none or 0))\n</code></pre>\n\n<p>But note that any non-empty string is truthy (but you can still <code>strip</code>):</p>\n\n<pre><code>&gt;&gt;&gt; \" \" or \"default\"\n' '\n&gt;&gt;&gt; \" \".strip() or \"default\"\n'default'\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T13:37:36.320", "Id": "219652", "ParentId": "219649", "Score": "5" } }, { "body": "<p>further to everything else that's been written I find it's generally better for functions to raise an exception if the wrong data-type is propagated, I'd therefore discourage use of code that special cases things like your checking for <code>int</code>s and <code>float</code>s. I'd write the function as:</p>\n\n<pre><code>def replace_null(text, *, empty_is_null=True, strip=True, nulls=('NULL', 'None')):\n \"\"\"Return None if text represents 'none', otherwise text with whitespace stripped.\"\"\"\n if text is None:\n return None\n if strip:\n text = str.strip(text)\n if empty_is_null and not text:\n return None\n if str.casefold(text) in (s.casefold() for s in nulls):\n return None\n return text\n</code></pre>\n\n<p>The asterisk (<code>*</code>) indicates <a href=\"https://stackoverflow.com/q/14301967/1358308\">keyword-only arguments</a> (see <a href=\"https://www.python.org/dev/peps/pep-3102/\" rel=\"nofollow noreferrer\">PEP 3102</a>) as I think it would help with future readers of the code. For example I would probably have to look at the definition to determine what: </p>\n\n<pre><code>x = myobj._mynull(text, 'default', False)\n</code></pre>\n\n<p>does, especially the unqualified <code>False</code>, when compared to (assuming the above is saved in <code>utils.py</code>):</p>\n\n<pre><code>x = utils.replace_null(text, strip=False) or 'default'\n</code></pre>\n\n<p>which relies more on keyword arguments and standard Python semantics.</p>\n\n<p>I've also added a small <a href=\"https://stackoverflow.com/q/3898572/1358308\">docstring</a>, so that <code>help(replace_null)</code> works.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T18:09:47.690", "Id": "219662", "ParentId": "219649", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T13:02:10.767", "Id": "219649", "Score": "6", "Tags": [ "python", "null" ], "Title": "Handling Null values (and equivalents) routinely in Python" }
219649
<p>This code calculates pi via collisions; it asks for a user input of N which determines the mass of the second block. It is fully working, it just takes forever to run when N >= 2. I want to be able have at least N=5 and have a reasonable runtime. The issue is in the velocity and x1, x2 calculation I believe. There are just so many that need to be appended that it takes forever to run and then just as long to append.</p> <p>My code shows that I have tried to use Numba to speed up the runtime, but that doesn't seem to be helping. I am currently using the RK-4 method to update position, and I previously tried the Verlet method which did not seem to have an affect on the runtime. Any help on this is greatly appreciated.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation import matplotlib.animation as animation from numba import jit import time start = time.time() @jit(nopython=True) def RK4_1(x, vx): return vx @jit(nopython=True) def RK4_2(x, vx): return 0 @jit(nopython=True) def iterate(x1, x2, vx1, vx2, col): k1 = dt*RK4_1(x1, vx1) k2 = dt*RK4_1(x1 + k1/2, vx1) k3 = dt*RK4_1(x1 + k2/2, vx1) k4 = dt*RK4_1(x1 + k3, vx1) x1 += (1/6)*(k1 + 2*k2 + 2*k3 + k4) k1 = dt*RK4_1(x2, vx2) k2 = dt*RK4_1(x2 + k1/2, vx2) k3 = dt*RK4_1(x2 + k2/2, vx2) k4 = dt*RK4_1(x2 + k3, vx2) x2 += (1/6)*(k1 + 2*k2 + 2*k3 + k4) k1 = dt*RK4_2(x1, vx1) k2 = dt*RK4_2(x1, vx1 + k1/2) k3 = dt*RK4_2(x1, vx1 + k2/2) k4 = dt*RK4_2(x1, vx1 + k3) vx1 += (1/6)*(k1 + 2*k2 + 2*k3 + k4) k1 = dt*RK4_2(x2, vx2) k2 = dt*RK4_2(x2, vx2 + k1/2) k3 = dt*RK4_2(x2, vx2 + k2/2) k4 = dt*RK4_2(x2, vx2 + k3) vx2 += (1/6)*(k1 + 2*k2 + 2*k3 + k4) if x1 &lt; 0: x1 = 0 vx1 = -vx1 col += 1 if x2 &lt; x1: x2 = x1 vx1_i = vx1 vx2_i = vx2 vx1 = (2*m2*vx2_i + m1*vx1_i - m2*vx1_i)/(m1+m2) vx2 = (2*m1*vx1_i + m2*vx2_i - m1*vx2_i)/(m1+m2) col += 1 return x1, x2, vx1, vx2, col dt = 0.01 m1 = 1 N = int(input("Enter an integer N that will determine the mass of the second block: ")) m2 = 100**N w1 = 1 w2 = w1*(100**N)**(1/3) x1 = 1 x2 = 1.15 y1 = 1 y2 = 1 vx1 = 0 vx2 = -1 col = 0 x1arr = np.array([]) x2arr = np.array([]) y1arr = np.array([]) y2arr = np.array([]) vx1arr = np.array([]) vx2arr = np.array([]) colarr = np.array([]) t = 0 while (vx2 &lt; 0) or (abs(vx1) &gt; abs(vx2)): x1, x2, vx1, vx2, col = iterate(x1, x2, vx1, vx2, col) #print(vx1, vx2) t += dt x1arr = np.append(x1arr, x1) x2arr = np.append(x2arr, x2) y1arr = np.append(y1arr, y1) y2arr = np.append(y2arr, y2) vx1arr = np.append(vx1arr, vx1) vx2arr = np.append(vx2arr, vx2) colarr = np.append(colarr, col) print("Number of collisions: %f" % (col)) speed = 1000 def update_plot(i, fig, scat1, scat2, txt): last = 0 if(i&gt;int(len(x1arr)/speed)-2): last=1 s = int(speed*i) scat1.set_data(x1arr[s],y1arr[s]) scat2.set_data(x2arr[s],y2arr[s]) #scat.set_sizes(lx1=5, lx2=5*N) txt.set_text('x1= %.3f m1=%.0f\nx2= %.3f m1=%.0f\nCollisions=%.0f\n t=%.3fs' % (x1arr[s],m1,x2arr[s],m2,colarr[s]+last,(s*dt))) #update of legend #print("Frame %d Rendered" % (s)) return scat1, scat2, txt, size = 5*N fig = plt.figure() ax = fig.add_subplot(111) ax.set_xlim([0, 3]) #animation scale ax.set_ylim([0,5]) ax.grid() txt = ax.text(0.05, 0.8, '', transform=ax.transAxes) scat1, = ax.plot([], [],'s', c='r', markersize=5) scat2, = ax.plot([], [],'s', c='r', markersize=5*(N+1)) anim = FuncAnimation(fig, update_plot, fargs = (fig, scat1, scat2, txt), frames = int(len(x1arr)/speed), interval = 1, blit=True, repeat=False) anim.save("originalpi.mp4", fps=30, bitrate=-1) end = time.time() print("Total runtime in seconds: ", end-start) plt.show() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T16:44:28.127", "Id": "424245", "Score": "0", "body": "I'm confused, can `RK4_1(x, vx)` just be replaced with `vx`? so `k1 = dt*RK4_1(x1, vx1)` is `k1 = dt*vx1`. And `k1 = dt*RK4_2(x1, vx1)` is `k1 = 0`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T16:57:53.463", "Id": "424248", "Score": "0", "body": "Yes I believe I could do that, I wrote it this way so that the RK 4 process was visible. Do you think changing it would decrease runtime?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T13:56:48.907", "Id": "424345", "Score": "0", "body": "What exactly do you mean by \"*calculates pi*\"? It certainly doesn't print it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T14:37:56.570", "Id": "424456", "Score": "0", "body": "If you run this code for, say, N=1, an animation will appear that shows the blocks colliding. The number of collisions count out pi. For N=1 the number of collisions is 31, for N=2 it is 314, etc." } ]
[ { "body": "<blockquote>\n <p>I am currently using the RK-4 method to update position</p>\n</blockquote>\n\n<p>Firstly, the naming is unhelpful here. A name like <code>RK4_1</code> implies that the method does the quadrature. I think that function is really <code>dx_dt</code>, <code>RK4_2</code> is really <code>dvx_dt</code>, and there would be room to pull out a function like</p>\n\n<pre><code>def RK4_step(t, x, dx_dt, dt):\n k1 = dt * dx_dt(x, t)\n k2 = dt * dx_dt(x + k1 / 2, t + dt / 2)\n k3 = dt * dx_dt(x + k2 / 2, t + dt / 2)\n k4 = dt * dx_dt(x + k3, t + dt)\n return x + (1/6) * (k1 + 2 * k2 + 2 * k3 + k4)\n</code></pre>\n\n<p>But secondly, RK4 is completely overkill here. If we inline</p>\n\n<blockquote>\n<pre><code>@jit(nopython=True)\ndef RK4_1(x, vx):\n return vx\n\n@jit(nopython=True)\ndef RK4_2(x, vx):\n return 0\n\n@jit(nopython=True)\ndef iterate(x1, x2, vx1, vx2, col):\n k1 = dt*RK4_1(x1, vx1)\n k2 = dt*RK4_1(x1 + k1/2, vx1)\n k3 = dt*RK4_1(x1 + k2/2, vx1)\n k4 = dt*RK4_1(x1 + k3, vx1)\n x1 += (1/6)*(k1 + 2*k2 + 2*k3 + k4)\n\n ...\n\n k1 = dt*RK4_2(x1, vx1)\n k2 = dt*RK4_2(x1, vx1 + k1/2)\n k3 = dt*RK4_2(x1, vx1 + k2/2)\n k4 = dt*RK4_2(x1, vx1 + k3)\n vx1 += (1/6)*(k1 + 2*k2 + 2*k3 + k4)\n</code></pre>\n</blockquote>\n\n<p>we get</p>\n\n<pre><code>def iterate(x1, x2, vx1, vx2, col):\n x1 += dt*vx1\n\n ...\n\n vx1 += 0\n</code></pre>\n\n<p>It seems that it would be <em>much</em> quicker to solve simultaneous linear equations to work out when the collision will happen rather than to use quadrature. In fact, <a href=\"https://tio.run/##bZHJboQwDIbveQprpNEkLNOEisuoHHvtqS/AlKCJhk0QKH16aidiUdUcEtn@/HtJ92MfbfO6LLWKoE4gA3yVlEGQslqRXSsIMcJmDEyz8oRkc0KmS7iqNIJYMfbVVmhLZpoS37Jqc8svIVoXwdj3w1QaPvtR3xjgsRIZ1HuBmGRN6dTfQIKuBg2YxRxXTMhRpZgAn0pdcOealSAFhFAA73/yLQ1hGm5lhJnCe4nGQEac74fOvdf50wPYS5gRE2xlseDuSpyLJkaf@iNq5a7pViY3068wXjWp1wObuJ1sduf371pwv3AovYvxbo0VE20D/@1AJJ6IvdBOsK43jeWnj7G@6x7akoapzGDaZrjBuTjBGTi6hFjJ98GaOre6gCmvRk0pnUG0XFFU5tRHAPKaCiGW5Rc\" rel=\"nofollow noreferrer\">I had a go</a>, and the actual simulation takes less than a second for <code>N = 5</code>.</p>\n\n<hr>\n\n<blockquote>\n <p>My code shows that I have tried to use Numba to speed up the runtime, but that doesn't seem to be helping.</p>\n</blockquote>\n\n<p>The jit is on the wrong parts. I added some debug printing and observed that it slowed down over time, at which point I very quickly spotted the real problem:</p>\n\n<blockquote>\n<pre><code> x1arr = np.append(x1arr, x1)\n x2arr = np.append(x2arr, x2)\n y1arr = np.append(y1arr, y1)\n y2arr = np.append(y2arr, y2)\n vx1arr = np.append(vx1arr, vx1)\n vx2arr = np.append(vx2arr, vx2)\n colarr = np.append(colarr, col)\n</code></pre>\n</blockquote>\n\n<p>This is copying the entire array every time, so the length of a step is proportional to the number of steps taken.</p>\n\n<p>Solution: use normal lists rather than numpy arrays. numpy is not a panacea: it's good for parallel processing, but that's not what you want here.</p>\n\n<p><strong>However</strong>, the one advantage that numpy arrays give you here is that they don't have length bounds. In testing with <code>N = 3</code> using normal Python lists I got a memory error after slightly more than 245 million steps and 3140 collisions. It might need a 2D structure to handle the large quantities of data. Of course, that doesn't prevent the extremely likely problem of the plot running into memory problems too. A complete structural rethink may be necessary.</p>\n\n<hr>\n\n<p>If you do decide to implement RK4, it's more correct to do a single multi-variable quadrature rather than multiple single-variable ones. Here is where there is a good reason to use numpy arrays. What I mean by multi-variable quadrature is something like</p>\n\n<pre><code>k1_x, k1_vx = dt * RK4(x, vx), dt * RK4(vx, ax)\nk2_x, k2_vx = dt * RK4(x + k1_x / 2, vx + k1_vx / 2), dt * RK4(vx + k1_vx / 2, ax)\n</code></pre>\n\n<p>etc. (NB For clarity I separated out the variables. For speed you'd put <code>x</code> and <code>vx</code> in a single numpy array).</p>\n\n<hr>\n\n<p>It makes no sense to start timing before taking the input: the time I take to type <code>3</code> and press <code>Enter</code> is not really runtime.</p>\n\n<hr>\n\n<p>In terms of general readability, the inline mixing of functions and top-level code is not helpful. It's good to put constants like <code>dt</code> at the top, so that when the reader comes to the usage of <code>dt</code> in <code>iterate</code> they've already seen it. The main loop should probably be a function which returns the arrays (or perhaps a single 2D array) with intermediate values; the plot creation should be a function, and then Python best practice is for the \"main\" functionality to go at the end with a guard:</p>\n\n<pre><code>if __name__ == \"__main__\":\n N = int(input(\"Enter an integer N that will determine the mass of the second block: \"))\n start = time.time()\n data = generate_collisions(N)\n plot = graph_collisions(data)\n end = time.time()\n print(\"Total runtime in seconds: \", end - start)\n plot.show()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T09:22:05.763", "Id": "219796", "ParentId": "219653", "Score": "4" } } ]
{ "AcceptedAnswerId": "219796", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T16:34:06.053", "Id": "219653", "Score": "3", "Tags": [ "python", "beginner", "time-limit-exceeded", "numerical-methods", "matplotlib" ], "Title": "Calculating pi via collisions" }
219653
<p>So, I'm in the midst of writing a programming language interpreter in Python, and one of the problems I'm concerned about is that since I've been using a lot of recursions to implement the interpreter, I'll get a stack overflow if the size of the code is too large. For example, I have a piece of code that evaluates an <code>and</code> operation. Since the language I'm implementing is a logic programming language (like Prolog), it needs to try out all the options, so it consumes a generator and loops over it looking at the rest of the <code>and</code> operation. Behold:</p> <pre><code>def evaluate_and(and_clauses, binds={}): if and_clauses == []: yield binds else: head, *tail = and_clauses possible = evaluate(head, binds) for p in possible: yield from evaluate_and(tail, p) </code></pre> <p>The issue with this is that if the <code>and</code> operation is buried deep within the program, and the call stack is already large, then if the <code>and</code> has too many clauses the interpreter will crash.</p> <p>If anyone could suggest a way to make this not possible, that would be amazing!</p> <p>PS: I have an even bigger problem, which is that since recursion is the only way to do looping in a logic programming language if you loop more than a 100 times in my language, it creates a stack overflow in my interpreter.</p>
[]
[ { "body": "<p>A quick search for \"python tail call optimization\" results in <a href=\"https://stackoverflow.com/a/18506625\">this SO answer</a> which has a PyPI package, <a href=\"https://pypi.org/project/tco/\" rel=\"nofollow noreferrer\"><code>tco</code></a>. Converting your code to return lists rather than generators should be all you need.</p>\n\n<blockquote>\n <p>recursion is the only way to do looping in a logic programming language</p>\n</blockquote>\n\n<p>This is wrong.</p>\n\n<p>If you want it to stay as a generator, then you'll have to manually handle the stack. The following doesn't account for order so if you need that then you'll have to figure that out yourself.</p>\n\n<pre><code>def evaluate_and(and_clauses, binds={}):\n stack = [(clauses, binds)]\n while stack:\n and_clauses, binds = stack.pop()\n if and_clauses == []:\n yield binds\n else:\n head, *tail = and_clauses\n possible = evaluate(head, binds)\n for p in possible:\n stack.append((tail, p))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T20:21:40.623", "Id": "424380", "Score": "0", "body": "Awesome, thank you! I was actually in the middle of working on a fairly promising solution but was having problems with what seems to be weird pointer magic? I tried something similar to yours in function, and in the process realized that both your code, my new code, and my old code don't do what I want: it evaluates the entire `and` up to the last clause up front, instead of lazily doing it. Here's what I had: https://gist.github.com/christopherdumas/3877ba10f9e98e0d3f5d6b5dc896dfae." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T20:27:30.067", "Id": "424381", "Score": "0", "body": "Currently, I'm trying to get this to work: https://gist.github.com/christopherdumas/ef745b4c8166df738b83082896c4c30f. However, when the actual final `possibilities` generator is evaluated, it seems to have been set to the result of the final clause `eval`d with a blank possibilities? It's very strange. And if I try to keep track of the possibilities, in a stack, they all turn out to have the exact same contents, and I can't figure out why." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T20:33:34.343", "Id": "424382", "Score": "0", "body": "@Gort I'm not going to help you further. If you post a working question on Code Review I might." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T20:39:19.223", "Id": "424383", "Score": "0", "body": "Okay that's fine. I'm just grateful for any sort of help. Also I did more research and I was indeed wrong about looping (:. I'll continue to try to figure this out and post an answer here when I'm done." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T18:28:31.147", "Id": "219719", "ParentId": "219656", "Score": "2" } } ]
{ "AcceptedAnswerId": "219719", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T16:50:13.347", "Id": "219656", "Score": "2", "Tags": [ "python", "recursion", "interpreter" ], "Title": "Convert Tail-Call Recursive Code to Loop" }
219656
<p>What I need to do is create a new object, modify it using a recursive function, then merge it with another object, and do this all in such a way that the values of the new object take precedence over the values in the object I'm merging it with.</p> <p>Currently, my code works, but I'd like to have more readable code, particularly this statement for the <code>add</code> operation:</p> <blockquote> <pre><code>@set.merge!( update(@set, insert(parent, id), @set[parent][1] + 1) ) </code></pre> </blockquote> <p>I've already refactored quite a bit, but I feel like there's a functional way, or at least more readable way, to write what I current have. I want it to be something like: new object → update it → merge it.</p> <p>Here is the whole class with tests:</p> <pre class="lang-rb prettyprint-override"><code># Nested set for comments, for making it easy to load all comments in a list, sorted according to their nesting, # and for nesting to be indicated. class Database def initialize @set = {} @largest = -1 end def fetch #Need Better syntax for this. @set.to_a.sort { |el1, el2| el1[1][0] &lt;=&gt; el2[1][0] } end def add(parent: nil, id: -1) if parent @set.merge!( update(@set, insert(parent, id), @set[parent][1] + 1) ) else @set[id] = [@largest+1, @largest+2] end @largest += 2 @set end private def insert(parent_id, id) parent_range = @set[parent_id] { parent_id =&gt; [parent_range[0], parent_range[1] + 2], id =&gt; [parent_range[1], parent_range[1] + 1] } end # O(n) * 2^n def update(old_state, state, target) # optimization for this: id,range = old_state.to_a.select{ |entry| entry[1][0] == target || entry[1][1] == target }[0] # better readability for this: if range &amp;&amp; !state[id] state[id] = range.index(target) == 0 ? range.map{|n| n + 2} : [range[0], range[1] + 2] 2.times do |i| update(old_state, state, range[i] + 1) if range[i] != state[id][i] end end state end end d = Database.new d.add({id: 1, parent: nil }) d.add({id: 2, parent: nil }) d.add({id: 3, parent: nil }) p d.fetch == [ [1, [0, 1]], [2, [2,3]], [3, [4,5]], ] d.add({id: 4, parent: 1 }) d.add({id: 5, parent: 2 }) d.add({id: 6, parent: 3 }) p d.fetch == [ [1, [0, 3]], [4, [1, 2]], [2, [4,7]], [5, [5,6]], [3, [8,11]], [6, [9,10]], ] d.add({id: 7, parent: 1 }) d.add({id: 8, parent: 7 }) # Final output. # 1 # 4 # 7 # 8 # 2 # 5 # 3 # 6 p d.fetch == [ [1, [0, 7]], [4, [1, 2]], [7, [3, 6]], [8, [4, 5]], [2, [8,11]], [5, [9,10]], [3, [12,15]], [6, [13,14]], ] </code></pre> <p>UPDATE: Will probably just do this:</p> <pre class="lang-rb prettyprint-override"><code> insert(parent, id) .yield_self { |obj| update(@set, obj, @set[parent][1] + 1) } .yield_self { |updated_set| @set.merge!(updated_set) } </code></pre>
[]
[ { "body": "<h2>Rubocop Report</h2>\n\n<p><a href=\"https://github.com/rubocop-hq/rubocop\" rel=\"nofollow noreferrer\">Rubocop</a> was able to correct a lot of style and layout offenses. 1 file inspected, 59 offenses detected, 53 offenses corrected.</p>\n\n<p>The following offenses remain:</p>\n\n<ul>\n<li>Metrics/LineLength: Line is too long. [112/80]</li>\n<li>Metrics/AbcSize: Assignment Branch Condition size for update is too high. [24.1/15]</li>\n<li>Style/MultipleComparison: Avoid comparing a variable with multiple items in a conditional, use Array#include? instead.</li>\n<li>Metrics/LineLength: Line is too long. [99/80]</li>\n<li>Style/NumericPredicate: Use range.index(target).zero? instead of range.index(target) == 0.</li>\n<li>Metrics/LineLength: Line is too long. [85/80]</li>\n</ul>\n\n<h2>Fixing Offenses</h2>\n\n<p>LineLength and MultipleComparison offense:</p>\n\n<blockquote>\n<pre><code># optimization for this:\nid,range = old_state.to_a.select{ |entry| entry[1][0] == target || entry[1][1] == target }[0]\n</code></pre>\n</blockquote>\n\n<pre><code>id, range = old_state.to_a.select do |entry|\n [entry[1][0], entry[1][1]].include?(target)[0]\nend\n</code></pre>\n\n<p>LineLength + NumericPredicate offense:</p>\n\n<blockquote>\n<pre><code>state[id] = \n range.index(target) == 0 ? range.map{|n| n + 2} : [range[0], range[1] + 2]\n</code></pre>\n</blockquote>\n\n<pre><code> state[id] =\n if range.index(target).zero?\n range.map { |n| n + 2 }\n else\n [range[0], range[1] + 2]\n</code></pre>\n\n<p>After refactoring, we get a new issue that our method got too big. The complexity is still too high.</p>\n\n<ul>\n<li>Metrics/AbcSize: Assignment Branch Condition size for update is too high. [25.06/15]</li>\n<li>Metrics/MethodLength: Method has too many lines. [15/10]</li>\n</ul>\n\n<p>We are adviced to break up this method. It's doing a bit too much. So we'll put the next part in another method.</p>\n\n<blockquote>\n<pre><code> state[id] =\n if range.index(target).zero?\n range.map { |n| n + 2 }\n else\n [range[0], range[1] + 2]\n end\n 2.times do |i|\n update(old_state, state, range[i] + 1) if range[i] != state[id][i]\n end\n</code></pre>\n</blockquote>\n\n<pre><code> def update_range(old_state, state, target, id, range)\n state[id] =\n if range.index(target).zero?\n range.map { |n| n + 2 }\n else\n [range[0], range[1] + 2]\n end\n 2.times do |i|\n update(old_state, state, range[i] + 1) if range[i] != state[id][i]\n end\n end\n</code></pre>\n\n<p>There are no offenses remaining and complexity is within bounds.</p>\n\n<h2>Refactored Code</h2>\n\n<pre><code># frozen_string_literal: true\n\n# Nested set for comments, for making it easy to load all comments in a\n# list, sorted according to their nesting, and for nesting to be indicated.\nclass Database\n def initialize\n @set = {}\n @largest = -1\n end\n\n def fetch\n @set.to_a.sort { |el1, el2| el1[1][0] &lt;=&gt; el2[1][0] }\n end\n\n def add(parent: nil, id: -1)\n if parent\n\n @set.merge!(\n update(@set, insert(parent, id), @set[parent][1] + 1)\n )\n else\n @set[id] = [@largest + 1, @largest + 2]\n end\n @largest += 2\n @set\n end\n\n private\n\n def insert(parent_id, id)\n parent_range = @set[parent_id]\n {\n parent_id =&gt; [parent_range[0], parent_range[1] + 2],\n id =&gt; [parent_range[1], parent_range[1] + 1]\n }\n end\n\n # O(n) * 2^n\n def update(old_state, state, target)\n id, range = old_state.to_a.select do |entry|\n [entry[1][0], entry[1][1]].include?(target)[0]\n end\n update_range(old_state, state, target, id, range) if range &amp;&amp; !state[id]\n state\n end\n\n def update_range(old_state, state, target, id, range)\n state[id] =\n if range.index(target).zero?\n range.map { |n| n + 2 }\n else\n [range[0], range[1] + 2]\n end\n 2.times do |i|\n update(old_state, state, range[i] + 1) if range[i] != state[id][i]\n end\n end\n end\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-21T11:39:55.927", "Id": "224611", "ParentId": "219657", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T16:51:25.623", "Id": "219657", "Score": "3", "Tags": [ "ruby", "recursion", "tree" ], "Title": "Adding an item to a hierarchical data structure" }
219657
<p>this is the first time I've requested a code review. I'm writing a piece of software in C++ that will use HTTP for communication. I wanted to do it myself to learn and then have someone review it and tell me where I could make some improvements. I'm having some problems with class member object initialization. </p> <p>I've broken the code down into http.h , httprequest.cpp , httpresponse.cpp. I would really appreciate it if one of you very smart people could take the time to help me learn! </p> <p>It functions, but I've found some cases where my implementation felt extremely hacked together. I'm trying to make use of the C++ specific operations and language features when I can but my problem is I just don't have the practice to know how and when to use them <strong>appropriately</strong>. I'm more interested in general programming practice improvements; specifically around garbage collection. Because I'm a python programmer at heart, my GC knowledge is minimal and I'm kind of just diving head first. Anyways, here is the code:</p> <h2>http.h</h2> <pre class="lang-cpp prettyprint-override"><code>#ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #ifndef DEFAULT_PORT #define DEFAULT_PORT "80" #endif #ifndef HTTP_VERSION #define HTTP_VERSION "HTTP/1.1" #endif #include &lt;windows.h&gt; #include &lt;winsock2.h&gt; #include &lt;ws2tcpip.h&gt; #include &lt;iphlpapi.h&gt; #include "util.h" #pragma comment(lib, "Ws2_32.lib") #define WEB_PORT "80" #define DEFAULT_BUFLEN 512 class HTTPResponse { std::string response_txt, data, version, reason; std::vector&lt;std::string&gt; header_lines; std::map&lt;std::string, std::string&gt; headers; int http_code; public: HTTPResponse(); HTTPResponse(std::string); std::string get_reason(); std::string get_version(); std::string get_data(); std::string get_response_txt(); std::string get_header_text(); std::string get_header_data(std::string); std::map&lt;std::string, std::string&gt; get_headers(); int get_http_code(); HTTPResponse operator=(const HTTPResponse&amp; _resp) { return _resp; } private: void parse(std::string); void parse_header_line(std::string); void parse_first_line(std::string); }; class HTTPRequest { HTTPResponse resp; std::vector&lt;std::pair&lt;std::string, std::string&gt;&gt; added_headers; std::string hostname, method, data, path, port, req_txt, resp_txt; std::map&lt;std::string, std::string&gt; args, headers; public: HTTPRequest(); HTTPRequest(std::string); HTTPRequest(std::string, std::string); void add_cookie(std::string, std::string); void add_arg(std::string, std::string); void add_header(std::string, std::string); void set_data(std::string); void set_port(std::string); void set_args(std::map&lt;std::string, std::string&gt;); void set_args(std::string); void set_headers(std::map&lt;std::string, std::string&gt;); void set_headers(std::string); void set_method(std::string); void set_path(std::string); void set_hostname(std::string); void reset(); std::string get_request_txt(); std::string get_response_txt(); int send_request(); HTTPResponse get_response(); HTTPRequest operator=(const HTTPRequest&amp; _req) { return _req; } private: std::string build_request(); std::map&lt;std::string, std::string&gt; default_headers(std::string); std::map&lt;std::string, std::string&gt; parse_args(std::string); std::map&lt;std::string, std::string&gt; parse_headers(std::string); std::string random_user_agent(); }; </code></pre> <h2>httprequest.cpp</h2> <pre class="lang-cpp prettyprint-override"><code>#include "http.h" // HTTPRequest implementation HTTPRequest::HTTPRequest() { hostname = "www.yahoo.com"; method = "GET"; path = "/"; args = std::map&lt;std::string, std::string&gt;(); set_headers(default_headers(hostname)); } HTTPRequest::HTTPRequest(std::string _hostname) { hostname = _hostname; method = "GET"; path = "/"; args = std::map&lt;std::string, std::string&gt;(); set_headers(default_headers(hostname)); } HTTPRequest::HTTPRequest(std::string _hostname, std::string _path) { hostname = _hostname; method = "GET"; path = _path; args = std::map&lt;std::string, std::string&gt;(); set_headers(default_headers(hostname)); } void HTTPRequest::reset() { args.clear(); path = "/"; method = "GET"; added_headers.clear(); set_headers(default_headers(hostname)); } std::string HTTPRequest::build_request() { std::string req = ""; if (path.empty()) path = "/"; if (hostname.empty()) throw std::exception("Hostname empty."); std::string path_args = ""; if (!args.empty() &amp;&amp; method == "GET") path_args = path + "?" + Util::serialize_http_args(args); else path_args = path; if (!method.empty()) req += method + " " + path_args + " " + HTTP_VERSION + "\r\n"; else req += "GET " + path_args + " " + HTTP_VERSION + "\r\n"; req += Util::serialize_http_headers(headers); if (method == "POST") req += Util::serialize_http_args(args); else req += data; req_txt = req; return req; } void HTTPRequest::add_cookie(std::string cookie, std::string value) { if (headers.find("Cookie") != headers.end()) { headers.at("Cookie") = Util::trim_copy(headers.at("Cookie")) + ";" + cookie + "=" + value; } else if(headers.find("cookie") != headers.end()) { headers.at("cookie") = Util::trim_copy(headers.at("cookie")) + ";" + cookie + "=" + value; } else { add_header("Cookie", cookie + "=" + value); } } void HTTPRequest::add_arg(std::string arg, std::string value) { args.insert(std::pair&lt;std::string, std::string&gt;(arg, value)); build_request(); } void HTTPRequest::add_header(std::string header, std::string value) { headers.insert(std::pair&lt;std::string, std::string&gt;(header, value)); added_headers.push_back(std::pair&lt;std::string, std::string&gt;(header, value)); build_request(); } void HTTPRequest::set_args(std::map&lt;std::string, std::string&gt; _args) { args = _args; build_request(); } void HTTPRequest::set_args(std::string _args) { args = parse_args(_args); build_request(); } void HTTPRequest::set_port(std::string _port) { port = _port; } void HTTPRequest::set_headers(std::map&lt;std::string, std::string&gt; _headers) { headers = _headers; } void HTTPRequest::set_headers(std::string _headers) { headers = parse_headers(_headers); } void HTTPRequest::set_path(std::string _path) { path = _path; } void HTTPRequest::set_data(std::string _data) { data = _data; headers = default_headers(hostname); } void HTTPRequest::set_hostname(std::string _hostname) { hostname = _hostname; headers = default_headers(hostname); } void HTTPRequest::set_method(std::string _method) { method = _method; build_request(); } std::map&lt;std::string, std::string&gt; HTTPRequest::parse_headers(std::string _headers) { std::vector&lt;std::string&gt; headerz = Util::split(_headers, "\r\n"); std::map&lt;std::string, std::string&gt; headermap; std::vector&lt;std::string&gt; headersplit; for (auto _header : headerz) { headersplit = Util::split(_header, ":"); headermap.insert(std::pair&lt;std::string, std::string&gt;(headersplit.at(0), headersplit.at(1))); } return headermap; } std::map&lt;std::string, std::string&gt; HTTPRequest::parse_args(std::string _args) { std::vector&lt;std::string&gt; argz = Util::split(_args, "&amp;"); std::map&lt;std::string, std::string&gt; argmap; std::vector&lt;std::string&gt; argsplit; for (auto _arg : argz) { argsplit = Util::split_once(_arg, "="); argmap.insert(std::pair&lt;std::string, std::string&gt;(argsplit.at(0), argsplit.at(1))); } return argmap; } std::string HTTPRequest::get_request_txt() { return build_request(); } std::string HTTPRequest::get_response_txt() { return resp_txt; } HTTPResponse HTTPRequest::get_response() { return HTTPResponse(get_response_txt()); } int HTTPRequest::send_request() { WSADATA wsaData; int iResult = WSAStartup(MAKEWORD(2, 2), &amp;wsaData); if (iResult != 0) { printf("WSAStartup failed: %d\n", iResult); return 1; } struct addrinfo* result = NULL, * ptr = NULL, hints; ZeroMemory(&amp;hints, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; // Resolve the server address and port iResult = getaddrinfo(hostname.c_str(), port.c_str(), &amp;hints, &amp;result); if (iResult != 0) { printf("getaddrinfo failed: %d\n", iResult); WSACleanup(); return 1; } ptr = result; SOCKET ConnectSocket = INVALID_SOCKET; ConnectSocket = socket(ptr-&gt;ai_family, ptr-&gt;ai_socktype, ptr-&gt;ai_protocol); if (ConnectSocket == INVALID_SOCKET) { printf("Error at socket(): %ld\n", WSAGetLastError()); freeaddrinfo(result); WSACleanup(); return 1; } iResult = connect(ConnectSocket, ptr-&gt;ai_addr, (int)ptr-&gt;ai_addrlen); if (iResult == SOCKET_ERROR) { closesocket(ConnectSocket); ConnectSocket = INVALID_SOCKET; } freeaddrinfo(result); if (ConnectSocket == INVALID_SOCKET) { printf("Unable to connect to server!\n"); WSACleanup(); return 1; } const int recvbuflen = DEFAULT_BUFLEN; char recvbuf[recvbuflen]; std::string req_text = build_request(); // Send an initial buffer iResult = send(ConnectSocket, req_text.c_str(), (int)req_text.length(), 0); if (iResult == SOCKET_ERROR) { printf("send failed: %d\n", WSAGetLastError()); closesocket(ConnectSocket); WSACleanup(); return 1; } // shutdown the connection for sending since no more data will be sent // the client can still use the ConnectSocket for receiving data iResult = shutdown(ConnectSocket, SD_SEND); if (iResult == SOCKET_ERROR) { printf("shutdown failed: %d\n", WSAGetLastError()); closesocket(ConnectSocket); WSACleanup(); return 1; } std::string out = ""; // Receive data until the server closes the connection do { memset(recvbuf, 0, recvbuflen); iResult = recv(ConnectSocket, &amp;recvbuf[0], recvbuflen - 1, 0); out.append(recvbuf); } while (iResult &gt; 0); resp_txt = std::string(out.c_str()); resp = HTTPResponse(resp_txt); return 0; } std::string HTTPRequest::random_user_agent() { std::vector&lt;std::string&gt; uas; uas.push_back("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36"); uas.push_back("Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)"); uas.push_back("Mozilla/5.0 (Windows NT 5.1; rv:7.0.1) Gecko/20100101 Firefox/7.0.1"); uas.push_back("Opera/9.80 (Android; Opera Mini/12.0.1987/37.7327; U; pl) Presto/2.12.423 Version/12.16"); uas.push_back("Mozilla/5.0 (Linux; U; Android 2.2) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"); uas.push_back("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36 OPR/43.0.2442.991"); uas.push_back("Mozilla/5.0 (Linux; U; Android 6.0.1; zh-CN; F5121 Build/34.0.A.1.247) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/40.0.2214.89 UCBrowser/11.5.1.944 Mobile Safari/537.36"); uas.push_back("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/600.5.17 (KHTML, like Gecko) Version/8.0.5 Safari/600.5.17"); uas.push_back("Microsoft Office/14.0 (Windows NT 6.1; Microsoft Outlook 14.0.7143; Pro)"); uas.push_back("Microsoft Office/14.0 (Windows NT 6.1; Microsoft Outlook 14.0.7162; Pro)"); uas.push_back("Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.2; Win64; x64; Trident/6.0; .NET4.0E; .NET4.0C; Microsoft Outlook 15.0.5023; ms-office; MSOffice 15)"); uas.push_back("Opera/9.80 (J2ME/MIDP; Opera Mini/4.2.20464/28.2144; U; en) Presto/2.8.119 Version/11.10"); uas.push_back("Opera/9.80 (J2ME/MIDP; Opera Mini/7.1.32052/29.3709; U; en) Presto/2.8.119 Version/11.10"); uas.push_back("Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.5.30729; .NET CLR 3.0.30618)"); uas.push_back("Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; Trident/5.0)"); uas.push_back("Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64; Trident/4.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E)"); uas.push_back("Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"); uas.push_back("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36"); uas.push_back("Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"); uas.push_back("Mozilla/5.0 (Windows NT 5.1; rv:7.0.1) Gecko/20100101 Firefox/7.0.1"); return uas.at(Util::randrange(0, uas.size() - 1)); } std::map&lt;std::string, std::string&gt; HTTPRequest::default_headers(std::string _hostname) { std::map&lt;std::string, std::string&gt; dheaders; dheaders.insert(std::pair&lt;std::string, std::string&gt;("Host", _hostname)); dheaders.insert(std::pair&lt;std::string, std::string&gt;("User-Agent", random_user_agent())); dheaders.insert(std::pair&lt;std::string, std::string&gt;("Accept-Language", "en-us")); dheaders.insert(std::pair&lt;std::string, std::string&gt;("Connection", "Keep-Alive")); dheaders.insert(std::pair&lt;std::string, std::string&gt;("Content-Length", Util::int2str(data.length()))); if (added_headers.size() &gt; 0) { for (auto h : added_headers) dheaders.insert(h); } return dheaders; } </code></pre> <h2>httpresponse.cpp</h2> <pre class="lang-cpp prettyprint-override"><code>#include "http.h" HTTPResponse::HTTPResponse() { http_code = 0; } HTTPResponse::HTTPResponse(std::string _response) { HTTPResponse(); response_txt = _response; parse(response_txt); } void HTTPResponse::parse(std::string _response) { std::vector&lt;std::string&gt; blocks = Util::split(_response, "\r\n\r\n"); response_txt = _response; int block_count = blocks.size(); //split into headers and data if (block_count &gt; 0) { header_lines = Util::split(blocks.at(0), "\r\n"); if (block_count &gt; 1) { data = Util::trim_copy(blocks.at(1)); } for (size_t i = 0; i &lt; header_lines.size(); ++i) { if (i == 0) parse_first_line(Util::trim_copy(header_lines.at(i))); else parse_header_line(Util::trim_copy(header_lines.at(i))); } } } void HTTPResponse::parse_header_line(std::string line) { std::vector&lt;std::string&gt; values = Util::split_once(line, ":"); if (values.size() &gt;= 2) { headers.insert(std::pair&lt;std::string, std::string&gt;( Util::lowercase(values.at(0)), Util::ltrim_copy(values.at(1)))); } } void HTTPResponse::parse_first_line(std::string line) { std::vector&lt;std::string&gt; sections = Util::split(line, " "); int size = sections.size(); if (size &gt;= 3) { version = sections.at(0); http_code = std::stoi(sections.at(1).c_str()); reason = sections.at(2); if (size &gt; 3) { for (int i = 3; i &lt; size; ++i) reason += " " + sections.at(i); } } else { throw std::exception("Invalid HTTP response. Looking for 3 header elements, found %d", size); } } std::map&lt;std::string, std::string&gt; HTTPResponse::get_headers() { return headers; } std::string HTTPResponse::get_header_text() { return Util::serialize_http_headers(headers); } std::string HTTPResponse::get_header_data(std::string header) { if (headers.find(Util::lowercase(header)) != headers.end()) { return headers.at(Util::lowercase(header)); } else { return ""; } } std::string HTTPResponse::get_response_txt() { return response_txt; } std::string HTTPResponse::get_data() { return data; } std::string HTTPResponse::get_version() { return version; } std::string HTTPResponse::get_reason() { return reason; } int HTTPResponse::get_http_code() { return http_code; } ``` </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T19:27:02.847", "Id": "424281", "Score": "0", "body": "Welcome to Code Review, unfortunately this question is off-topic because it has to be working code, please see the guidelines at https://codereview.stackexchange.com/help/dont-ask and https://codereview.stackexchange.com/help/how-to-ask. Since it is partially working you might try our sister website stackoverflow.com, they help debug code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T19:29:37.583", "Id": "424282", "Score": "0", "body": "No you're misunderstanding, it works and I'm not looking for debugging help. I can do that myself. I'm looking for someone to review the code and tell me where fundamental improvements can be made to the style or whatever. I'll do my own unit testing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T19:51:22.090", "Id": "424288", "Score": "0", "body": "Welcome to Code Review! You stated \"`It functions, but I've found some cases that it fails.`\". In what cases does it fail?? Please read [this meta post explaining why \"_It functions, but I've found some cases that it fails._\" is off-topic](https://codereview.meta.stackexchange.com/a/3650/120114)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T20:20:14.927", "Id": "424290", "Score": "0", "body": "I guess I used the wrong wording. Better would be to say, I feel like I had to hack it together. It works as I need it to, but I think it's sloppy and I think I'm missing some garbage collection stuff but the code is working as expected. You provide it a hostname in the constructor, set the path, args, headers, cookies, and you send the request and get a response. The response gets parsed into an object and is accessible by elements of the HTTP response. If you guys are saying it's off-topic still I'll take my merry ass to stack overflow like you suggested and bring it back when it's ontopic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T20:33:52.600", "Id": "424292", "Score": "3", "body": "Thanks for clarifying. I would advise you to [edit]your post and remove any wording that makes it sound like there are cases where it fails. We just want to make sure the code works before reviewing it. Also, please remember there is a [Code of Conduct](Code of Conduct) on this network that should be followed. FWIW I have [opted to not VTC but instead leave this post open](https://codereview.stackexchange.com/review/close/115931) based on your response." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T22:54:12.890", "Id": "424300", "Score": "0", "body": "Is it possible for you to add the code for the Util class as well?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T17:33:07.860", "Id": "424367", "Score": "0", "body": "You might want to join this community as well https://softwareengineering.stackexchange.com/" } ]
[ { "body": "<p><strong>Initialization in Constructors</strong><br>\nCurrently the constructors perform the initialization within the body of the constructor, this isn't necessary for simple variables, C++ has a shorthand form for initializing variables</p>\n\n<pre><code>HTTPRequest::HTTPRequest(std::string _hostname)\n : hostname{_hostname}, method{\"GET\"}, path{\"/\"}\n{\n set_args();\n set_default_headers();\n}\n</code></pre>\n\n<p>As show in the example above, there is no need to pass <code>hostname</code> to the function that sets the default headers because <code>hostname</code> is a class member. Since it is a class member every function in the class has access to it. Therefore setting the default headers can be written like this:</p>\n\n<pre><code>void HTTPRequest::set_default_headers()\n{\n headers.insert(std::pair&lt;std::string, std::string&gt;(\"Host\", hostname));\n headers.insert(std::pair&lt;std::string, std::string&gt;(\"User-Agent\", random_user_agent()));\n headers.insert(std::pair&lt;std::string, std::string&gt;(\"Accept-Language\", \"en-us\"));\n headers.insert(std::pair&lt;std::string, std::string&gt;(\"Connection\", \"Keep-Alive\"));\n headers.insert(std::pair&lt;std::string, std::string&gt;(\"Content-Length\", Util::int2str(data.length())));\n if (added_headers.size() &gt; 0) {\n for (auto h : added_headers)\n {\n headers.insert(h);\n }\n }\n}\n</code></pre>\n\n<p>Note that set_default_headers() is not returning a map as <code>default_headers(str::string hostname)</code> is. There is no reason to create a local map of headers when the class member <code>headers</code> is declared in the class is available to update. This function replaces both <code>set_headers()</code> and <code>default_headers()</code> in the current implementation. The current implementation of <code>set_headers(default_headers(hostname));</code> wastes memory and execution time.</p>\n\n<p>A similar function should be created to set the <code>args</code> variable as well.</p>\n\n<p><strong>Note:</strong><br>\nMemory allocation for both <code>args</code> and <code>headers</code> is handled by this line in the class declaration:</p>\n\n<pre><code> std::map&lt;std::string, std::string&gt; args, headers;\n</code></pre>\n\n<p>This code in the current constructor is attempting to reallocate that memory and is incorrect:</p>\n\n<pre><code> args = std::map&lt;std::string, std::string&gt;();\n</code></pre>\n\n<p>every argument that is an element of <code>args</code> must be added using an insert statement.</p>\n\n<p><strong>Header Files</strong><br>\nIt would be better if http.h included the <code>map</code>, <code>string</code> and <code>vector</code> headers, otherwise each cpp file that references http.h needs to include those headers prior to including http.h.</p>\n\n<p>It is fairly common for a class to defined in its own header file, for instance <code>HTTPRequest.h</code> and <code>HTTPResponse.h</code> rather than both class definitions being in http.h. In the case where one class requires the definition of another class the other class header file can be included for example <code>HTTPResponse.h</code> could contain: </p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;map&gt;\n#include &lt;vector&gt;\n</code></pre>\n\n<p>Creating a header for each class limits the number of files that need to be recompiled every time there is an edit to a particular class such as adding a method to a class or changing the parameters of a method.</p>\n\n<p>and <code>HTTPRequest.h</code> could contain</p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;map&gt;\n#include &lt;vector&gt;\n#include \"HTTPResponse.h\"\n</code></pre>\n\n<p>Header files generally contain some mechanism to prevent the contents of the header file from being included twice. Microsoft provides <code>#pragma once</code> for this purpose, but a more common and portable method is</p>\n\n<pre><code>#ifndef HTTPRequest_h\n#define HTTPRequest_h\n ...\n#endif\n</code></pre>\n\n<p>Preventing the contents of the header from being included more than once is important because otherwise compiler errors about duplicate definitions will result.</p>\n\n<p>In Visual Studio when a class is added both a header file and a cpp file are generated and the header file starts with <code>#pragma once</code>.</p>\n\n<p><strong>Variable Declarations</strong><br>\nCurrently http.h contains the following:</p>\n\n<pre><code> std::string response_txt, data, version, reason;\n</code></pre>\n\n<p>If for some reason the type of data needed to change it is harder to change it, it needs to be removed from the combined line and inserted on a line by itself. If a variable needs to be added or deleted it is easier to add a single declaration or remove a single line. It might be better if each variable was declared on it's own line both in a class definition in a header file or a local variable in a method. Using a single line improves readability and maintainability.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T01:44:49.867", "Id": "424308", "Score": "0", "body": "Thank you, so about your comment about the headers. I am utilizing a stdafx.h with the:\n`#ifndef STDAFX_INC\n#define STDAFX_INC\n#endif`\npattern, to include headers that are common throughout the larger project, map, vector and string are defined there, what are your thoughts on that? Otherwise, good suggestions and nice catch on the re-initialization in the ctor." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T01:56:57.627", "Id": "424310", "Score": "0", "body": "@leaustinwile Two reasons not to, if at some point you want to port your solution that won't port, as an experienced developer I prefer to see the header files where needed rather than being surprised by compiler errors." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T02:01:44.510", "Id": "424311", "Score": "0", "body": "Fair enough, I'll restructure. Off-topic question: C++ unit testing. I've never done it so I don't really know how, could you point me to a worthy guide?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T02:10:32.383", "Id": "424312", "Score": "0", "body": "@leaustinwile I have primarily written my own tests, but there are unit test frameworks. I've used phpunit. The nice thing about frameworks is that they tell you the coverage, i.e. the percentage of code that was tested.\nhttps://en.wikipedia.org/wiki/CppUnit, http://cppunit.sourceforge.net/doc/1.8.0/, http://cppunit.sourceforge.net/doc/cvs/cppunit_cookbook.html, https://en.wikipedia.org/wiki/List_of_unit_testing_frameworks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T08:14:31.010", "Id": "424323", "Score": "0", "body": "Okay, lastly here's an idea I'm exploring, first let me give you some more background. I work for Nike's adversarial simulation team doing red team ops, this HTTP implementation is going to be used in our custom payload for ops. Do you think that functional programming and using typedef/structs would be better suited for something like this? I've only recently been introduced to the idea of it but after reading some stuff, I am starting to think that for two reasons (my skill level, and the project type) that it may be easier to implement in a functional manner as opposed to object oriented." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T08:14:37.500", "Id": "424324", "Score": "0", "body": "What are your thoughts?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T13:21:44.603", "Id": "424342", "Score": "0", "body": "@leaustinwile pardon the delay but I need to sleep sometime. It would be best if this discussion was continued either in a chatroom, on twitter or by email." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T19:30:52.770", "Id": "424376", "Score": "0", "body": "My email is leaustinwile@gmail.com" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T01:23:22.723", "Id": "219683", "ParentId": "219666", "Score": "2" } }, { "body": "<p>Let me add a few quick comments to the other review(s).</p>\n\n<p>In general, pay attention to const correctness to reduce the chances of making mistakes and also to avoid unnecessary - and potentially expensive - copies.</p>\n\n<ul>\n<li><p>You have plenty of \"getters\" of the form <code>get_...</code> (e.g. <code>get_version()</code>, and so on) that don't modify the state of the object. Write these as <code>get_version() const</code>.</p></li>\n<li><p>It seems that you pass not-cheap-to-copy objects like <code>std::string</code> always by-value meaning they are copied. Is this really necessary? By default, a better instinct is to always write them by const-ref, like <code>add_arg(const std::string&amp; arg, const std::string&amp; value)</code>, and so on. You should have a good reason for <em>not</em> doing this.</p></li>\n<li><p>Your constructors violate good practices. Read through <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#S-ctor\" rel=\"nofollow noreferrer\">the relevant rules for constructors on C++ Core Guidelines</a>.</p></li>\n<li><p>In <code>build_request()</code>, define <code>std::string req</code> just before the line <code>if(!method.empty())</code> to improve readability.</p></li>\n<li><p>In <code>random_user_agent()</code>, you don't need <code>push_back</code> but instead initialize the vector to hold these values directly by a constructor call. You can then make the vector <code>const</code> as well.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T10:17:01.743", "Id": "219693", "ParentId": "219666", "Score": "3" } } ]
{ "AcceptedAnswerId": "219683", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T18:51:49.120", "Id": "219666", "Score": "12", "Tags": [ "c++", "object-oriented", "http", "server", "client" ], "Title": "HTTP C++ Implementation" }
219666
<p>Working on the 2 element subset sum problem (finding two numbers in a list that sum to a given value), I came up with a relatively short solution code-wise. </p> <p>The code could fit on a single line but I'm not super familiar with python so is this is a naive way to solve/implement it?</p> <p>How efficient is creating a set and intersecting it with a list vs using a loop?</p> <pre><code>l = [10, 7, 11, 3, 5, 11] k = 22 #create a set of the differences between K and L including duplicate elements that sum to K diff = {k-x for i, x in enumerate(l) if k != 2*x or x in l[i+1:len(l)]} #Return true if an element of Diff is in L print(bool(diff.intersection(l))) </code></pre>
[]
[ { "body": "<p>Usually Python is not terribly fast when it comes to \"hand-written\" loops. So my prediction (also supported by some preliminary profiling using <a href=\"https://docs.python.org/3/library/timeit.html\" rel=\"nofollow noreferrer\">timeit</a>, see below) would be that a \"hand-written\" loop is slower than the C loop used in the <a href=\"https://github.com/python/cpython/blob/master/Objects/setobject.c#L1238\" rel=\"nofollow noreferrer\">implementation</a> of <code>set.intersection</code>. The effect should/will become more significant for larger lists.</p>\n\n<p>A quick non-performance related note: you can substitute <code>l[i+1:len(l)]</code> by <code>l[i+1:]</code>. This is because the end of a slice defaults to the end of the sequence.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import timeit\n\nSETUP = \"\"\"\nl = [10, 7, 11, 3, 5, 11]\nk = 22\n\ndiff = {k-x for i, x in enumerate(l) if k != 2*x or x in l[i+1:]}\n\"\"\"\nprint(\n sum(timeit.repeat(\"bool(diff.intersection(l))\", setup=SETUP,\n repeat=10, number=100000)) / 10\n)\nprint(\n sum(timeit.repeat(\"bool([i for i in l if i in diff])\", setup=SETUP,\n repeat=10, number=100000)) / 10\n)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T13:52:42.290", "Id": "219704", "ParentId": "219667", "Score": "1" } }, { "body": "<blockquote>\n<pre><code>#create a set of the differences between K and L including duplicate elements that sum to K\ndiff = {k-x for i, x in enumerate(l) if k != 2*x or x in l[i+1:len(l)]}\n</code></pre>\n</blockquote>\n\n<p>The slice can be simplified:</p>\n\n<pre><code>diff = {k-x for i, x in enumerate(l) if k != 2*x or x in l[i+1:]}\n</code></pre>\n\n<p>In my opinion, the <code>or x in l[i+1:]</code> is a bit too tricky to use without further explanation. My immediate reaction on seeing it was that it undermined the whole point of using a set by creating a quadratic worst case. On further reflection I see that (assuming Python is sensibly implemented, which I think is a safe assumption here) it doesn't, but it's better to preempt the doubt with a comment.</p>\n\n<p>Alternatively, handle the special case separately by checking whether <code>k</code> is even and if so counting instances of <code>k // 2</code>.</p>\n\n<hr>\n\n<p>As an optimisation, you can keep only the half of each pair in <code>diff</code>:</p>\n\n<pre><code>diff = {k-x for x in l if 2*x &lt; k}\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>#Return true if an element of Diff is in L\nprint(bool(diff.intersection(l)))\n</code></pre>\n</blockquote>\n\n<p>This is a bit cryptic. I think it might be more pythonic to use <code>any</code>:</p>\n\n<pre><code>print(any(x in l if x in diff))\n</code></pre>\n\n<p>That's also potentially faster, because it can abort on finding the first solution.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T14:29:18.150", "Id": "424347", "Score": "0", "body": "`i` is used in the second condition in the original set construction so it cannot be dropped so easily at this stage in the optimization." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T17:14:46.203", "Id": "424361", "Score": "0", "body": "@AlexV, oops. Thanks." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T14:21:06.903", "Id": "219705", "ParentId": "219667", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T19:14:30.713", "Id": "219667", "Score": "2", "Tags": [ "python", "set", "subset-sum-problem" ], "Title": "Python set based solution to Subset Sum" }
219667
<p>I am writing a clock in / out and payroll app for Android. I am no professional, but I was hoping I could get some feedback on whether my code is spaghetti or not. This is just one of many classes &amp; activities, but I feel like this is one of the ones that is a little complex and I want to make sure I am not learning to write spaghetti code. </p> <p>I particularly dislike the nested if block in the <code>onCreate()</code>, specifically the <code>buttonClockOut.setOnClickListener()</code>. Something feels off to me about this class in general. The code works as intended, I just feel like it could be improved in readability.</p> <pre><code>public class ClockOutActivity extends AppCompatActivity implements DialogAlreadyClockedInOrOut.DialogAlreadyClockedInOrOutListener { public static final int BUNDLE_CODE_CLOCK_OUT = 2; // TextClock private TextClock textClockClockOut, textClockClockOutDate; // EditText input fields private EditText editTextPasswordInput; // Buttons private Button buttonClockOut; // ViewModels private EmployeeViewModel employeeViewModel; private EmployeeWorkLogViewModel employeeWorkLogViewModel; // Local variables // ArrayLists private List&lt;Employee&gt; employeeList = new ArrayList&lt;&gt;(); private List&lt;EmployeeWorkLog&gt; employeesAlreadyClockedIn = new ArrayList&lt;&gt;(); // Strings private String dateOfLastClockInUI; private String employeeNameFromDB; private String employeeClockInTimeUI; // Booleans boolean isClockedInDB; private boolean forcedEmployeeBlunder = false; // ints private int fkEmpIdFromList; // Custom Objects EmployeeWorkLog employeeAlreadyClockedInEntry; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_clock_out); preliminarySetUp(); setEmployeeList(); // employee list from all employee profiles in database // List of employees who are currently clocked in employeeWorkLogViewModel.getEmployeesAlreadyClockedIn().observe(this, new Observer&lt;List&lt;EmployeeWorkLog&gt;&gt;() { @Override public void onChanged(List&lt;EmployeeWorkLog&gt; employeeWorkLogs) { employeesAlreadyClockedIn = employeeWorkLogs; } }); buttonClockOut.setOnClickListener(v -&gt; { if (noEmptyETFields(editTextPasswordInput)) { int employeeIdUI = Integer.parseInt(editTextPasswordInput.getText().toString()); String today = fetchDate(); if (employeeExistsInDB(employeeIdUI)) { if (employeeInAlreadyClockedInList(employeeIdUI) &amp;&amp; employeeAlreadyClockedInEntry.getDate().equals(today)) { // date of clock in matches date of intended clock out normalClockOut(); } else { showAlreadyClockedOutDialog(); } } else { Toast.makeText(this, "ID not matched to Database. Try again.", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(this, "You need to input an ID number first.", Toast.LENGTH_SHORT).show(); } }); } public void preliminarySetUp() { setTitle("Clock Out"); defineViews(); setTextClockFont(); } public void defineViews() { this.editTextPasswordInput = findViewById(R.id.edit_text_employee_id_clock_out); this.buttonClockOut = findViewById(R.id.button_ok_clock_out); // ViewModels too I guess employeeViewModel = ViewModelProviders.of(this).get(EmployeeViewModel.class); employeeWorkLogViewModel = ViewModelProviders.of(this).get(EmployeeWorkLogViewModel.class); } public void setEmployeeList() { employeeViewModel.getAllEmployees().observe(this, new Observer&lt;List&lt;Employee&gt;&gt;() { @Override public void onChanged(List&lt;Employee&gt; employees) { employeeList = employees; } }); } public void setTextClockFont() { textClockClockOut = findViewById(R.id.text_clock_clock_out); textClockClockOutDate = findViewById(R.id.text_clock_clock_out_date); //textClockDateMain.setFormat12Hour("EEEE MMM dd, yyyy"); Typeface gothicFont = ResourcesCompat.getFont(this, R.font.gothic); textClockClockOut.setTypeface(gothicFont); textClockClockOutDate.setTypeface(gothicFont); } public boolean employeeExistsInDB(int employeeIdFromUI) { for (int i = 0; i &lt; employeeList.size(); i++) { if (employeeList.get(i).getEmployeeIdNumber() == employeeIdFromUI) { employeeNameFromDB = employeeList.get(i).getEmployeeFirstName(); fkEmpIdFromList = employeeList.get(i).getPEmpId(); return true; } } return false; } public boolean employeeInAlreadyClockedInList(int employeeIdFromUI) { for (int i = 0; i &lt; employeesAlreadyClockedIn.size(); i++) { if (employeesAlreadyClockedIn.get(i).getEmployeeId() == employeeIdFromUI) { // match, employee is already clocked in employeeAlreadyClockedInEntry = employeesAlreadyClockedIn.get(i); return true; } } return false; // match not found, employee not currently clocked in } public void normalClockOut() { String clockInTimeFromDB = employeeAlreadyClockedInEntry.getClockInTime(); String clockOutTime = fetchTime(); String totalShiftTime = calculateTotalShiftTime(clockInTimeFromDB, clockOutTime); // Sets these variables with the data from the last clock in entry of the employee int pId = employeeAlreadyClockedInEntry.getPId(); int fkEmpId = employeeAlreadyClockedInEntry.getFkEmpId(); String date = employeeAlreadyClockedInEntry.getDate(); boolean isClockedIn = false; boolean employeeBlunder = false; if (forcedEmployeeBlunder) employeeBlunder = forcedEmployeeBlunder; int employeeId = employeeAlreadyClockedInEntry.getEmployeeId(); EmployeeWorkLog employeeWorkLog = new EmployeeWorkLog(fkEmpId, date, clockInTimeFromDB, clockOutTime, totalShiftTime, isClockedIn, employeeBlunder, employeeId); employeeWorkLog.setPId(pId); employeeWorkLogViewModel.updateEmployeeWorkLog(employeeWorkLog); Toast.makeText(this, "Successfully clocked out at " + clockOutTime, Toast.LENGTH_LONG).show(); finish(); } public void forcedEmployeeClockIn() { int fkEmpIdFromLastObj = fkEmpIdFromList; int employeeIdNumberFromLastObj = Integer.parseInt(editTextPasswordInput.getText().toString().trim()); boolean isClockedInCI = true; boolean employeeBlunderCI = true; EmployeeWorkLog forceCI = new EmployeeWorkLog(fkEmpIdFromLastObj, fetchDate(), employeeClockInTimeUI, null, null, isClockedInCI, employeeBlunderCI, employeeIdNumberFromLastObj); employeeWorkLogViewModel.insertEmployeeWorkLog(forceCI); employeeWorkLogViewModel.getEmployeesAlreadyClockedIn().observe(this, new Observer&lt;List&lt;EmployeeWorkLog&gt;&gt;() { @Override public void onChanged(List&lt;EmployeeWorkLog&gt; employeeWorkLogs) { employeesAlreadyClockedIn = employeeWorkLogs; resetList(employeeIdNumberFromLastObj); } }); // old re-attempt code lived here } public void resetList(int employeeIdNumberFromLastObj) { for (int i = 0; i &lt; employeesAlreadyClockedIn.size(); i++) { if (employeesAlreadyClockedIn.get(i).getEmployeeId() == employeeIdNumberFromLastObj) { employeeAlreadyClockedInEntry = employeesAlreadyClockedIn.get(i); forcedEmployeeBlunder = true; // Re-attempt normal clock out normalClockOut(); } } } public String fetchDate() { DateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy"); String date = dateFormat.format(Calendar.getInstance().getTime()); return date; } public String fetchTime() { DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); String time = dateFormat.format(Calendar.getInstance().getTime()); return time; } public boolean noEmptyETFields(EditText editText) { return !editText.getText().toString().trim().isEmpty(); } public String calculateTotalShiftTime(String clockInTime, String clockOutTime) { String totalShiftTime; String[] clockInTimeArray = clockInTime.split(":"); String[] clockOutTimeArray = clockOutTime.split(":"); int timeTotalHours = 0; int timeTotalMinutes = 0; for (int i = 0; i &lt; clockOutTimeArray.length; i++) { int timeCO = Integer.parseInt(clockOutTimeArray[i]); int timeCI = Integer.parseInt(clockInTimeArray[i]); switch (i) { case 0: // Hours slot timeTotalHours = timeCO - timeCI; break; case 1: // minutes slot if (timeCO &gt; timeCI) { timeTotalMinutes = timeCO - timeCI; } else { timeTotalMinutes = timeCO - timeCI; timeTotalMinutes += 60; timeTotalHours--; } break; } } totalShiftTime = timeTotalHours + ":" + timeTotalMinutes; return totalShiftTime; } public void showAlreadyClockedOutDialog() { DialogAlreadyClockedInOrOut dialog = new DialogAlreadyClockedInOrOut(); Bundle bundle = new Bundle(); bundle.putInt("bundleCode", BUNDLE_CODE_CLOCK_OUT); bundle.putString("bundleName", employeeNameFromDB); dialog.setArguments(bundle); dialog.show(getSupportFragmentManager(), "prompt - DialogAlreadyClockedInOrOut - OUT"); } // Will receive the input from the dialog where the user typed in the // time they should've clocked out @Override public void applyUserTimeData(String uTime) { // adding :00 to the end of the string allows the comparison from the calculateTotalShiftTime // to proceed without out of bounds errors employeeClockInTimeUI = uTime + ":00"; forcedEmployeeClockIn(); } } </code></pre>
[]
[ { "body": "<p>Let me know if you ever see an Android activity class that is not spaghetti. I'm eager to learn if it is possible...</p>\n\n<p>When UI code and business logic is combined into one class, the code becomes harder to read as the reader constantly needs to remember whether a field is related to UI or business logic. The code related to maintaining the payroll-related data should be placed into a separate package (putting them into a separate Maven project wouldn't be too extreme) and the Android-part should be reserved for as pure UI code as poosible.</p>\n\n<p>Lambdas should be short and simple. Multi-line lambdas shoul be extracted into standalone classes. For some reason Android Java code heavily promotes anonymous classes. In my opinion they make the code hard to read and if the programmer is not diligent, results in single responsibility violations.</p>\n\n<p>The activity class itself acts both as an activity and a listener. That's a clear single responsibility violation. Every single Android tutorial does it because it makes the sample code shorter. In the real world it's usually just bad practise.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-08T19:48:20.703", "Id": "424961", "Score": "0", "body": "Thank you very much for reviewing my code @TorbenPutkonen! I will do my best to refactor my lambdas on all my classes. As far as separating the business logic from the UI, I am currently using a ViewModel class for my Room library database queries only. I was wondering if other than using Maven, would it be sensible to move my business logic for any clock in/out functions into their own ViewModel classes instead?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-09T05:10:35.583", "Id": "425000", "Score": "0", "body": "It would be sensible." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T05:23:17.917", "Id": "219845", "ParentId": "219668", "Score": "0" } } ]
{ "AcceptedAnswerId": "219845", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T19:20:12.323", "Id": "219668", "Score": "4", "Tags": [ "java", "beginner", "android", "mvvm" ], "Title": "Android clock in/out app" }
219668
<p>This is my first program ever made in C. Before that I programmed just a little bit in C++ (didn't touch OOP so I did only structural programming). This is my second "project" ever made, the first "project" was even bigger joke. I am new to programming.</p> <p>The project is nowhere near to be finished. However, it somehow works, and I don't want to add new features until this mess is cleaned up. I feel like for me the bigger the mess is, the harder it is to find small mistakes.</p> <p>That's why I come here: would you please be able to take a look at my code and tell me what's wrong with it? Especially program structure-wise.</p> <p>Program features:</p> <ul> <li>after execution immedietely starts recording cursor's movements and cursor/keyboard keystrokes</li> <li>if 'W' is pressed the recording stops</li> <li>and 5 seconds later the recording is played-back, simulating what has been recorded</li> </ul> <p>Basically during the recording phase it snapshots the keyboard and mouse state every ~10 miliseconds.</p> <p>Few things to mention:</p> <ul> <li>doubly linked list is not freed yet. I will handle the memory leaks.</li> <li>the program does not and probably will not support simulating multiple keypresses at the same time</li> <li>I will make it more user-friendly and such after I fix this mess</li> </ul> <p>Here is link to the github containing all the code: <a href="https://github.com/Wenox/WinAuto" rel="nofollow noreferrer">https://github.com/Wenox/WinAuto</a></p> <p>For example, I wonder if such function:</p> <pre><code>POINT get_cursor(void) { POINT P = {}; GetCursorPos(&amp;P); return P; } </code></pre> <p>deserves its own <code>input_cursor.c</code> file?</p> <p>The main thing I am curious about is the <code>recording.c</code> file containing:</p> <pre><code>#include ..bunch of files.. #define _GETCURSOR 1 #define _GETKEY 2 #define _SLEEP 3 /** adds cursor's position to the functions queue */ void add_cursor(struct f_queue **head, struct f_queue **tail, POINT P[2]) { P[1] = get_cursor(); if (P[0].x != P[1].x || P[0].y != P[1].y) { // if current cursor pos != previous add_function(head, tail, _GETCURSOR, P[1].x, P[1].y); // add it to the queue P[0] = P[1]; } } /** adds latest keystroke's description to the functions queue */ void add_keystroke(struct f_queue **head, struct f_queue **tail, int key_buff[2]) { key_buff[1] = get_keystroke(); if (key_buff[1] != key_buff[0] &amp;&amp; key_buff[1] != 0) // if there was keystroke add_function(head, tail, _GETKEY, key_buff[1], -1); // then add it to the queue key_buff[0] = key_buff[1]; } /** returns true if newly added node is function of sleep type, false otherwise */ bool is_prev_sleep_func(struct f_queue **head) { return (*head)-&gt;f_type == _SLEEP; } /** adds sleep to functions queue */ void add_sleep(struct f_queue **head, struct f_queue **tail, const int sleep_dur) { Sleep(sleep_dur); if (!is_prev_sleep_func(head)) add_function(head, tail, _SLEEP, sleep_dur, -1); else (*head)-&gt;f_args[0] += sleep_dur; // increment the node rather than add new one } /** keyboard/mouse recording engine */ void record(struct f_queue **head, struct f_queue **tail, const int sleep_dur) { int key_buff[2] = {-1, -1}; // buffer for curr and prev pressed key POINT cursor_buff[2] = {0}; // buffer for curr and prev cursor position while(key_buff[1] != KEY_W) { // stop recording when '3' is pressed add_cursor(head, tail, cursor_buff); add_keystroke(head, tail, key_buff); add_sleep(head, tail, sleep_dur); } } </code></pre> <p>and the <code>play_recording()</code> function from <code>replay.c</code> file:</p> <pre><code>/** function replays the recording */ void play_recording(struct f_queue *tail) { while (tail) { if (tail-&gt;f_type == _GETCURSOR) SetCursorPos(tail-&gt;f_args[0], tail-&gt;f_args[1]); else if (tail-&gt;f_type == _GETKEY) send_input(tail-&gt;f_args[0]); else if (tail-&gt;f_type == _SLEEP) Sleep(tail-&gt;f_args[0]); tail = tail-&gt;prev; } } </code></pre> <p>if it looks neat/readable/understandable to a person who reads it for the first time, and if something is clearly wrong/could be improved/is a bad practice.</p> <p>For all suggestions/advices on any kind of improvements I am gladly thankful. Many thanks.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T19:48:40.990", "Id": "424287", "Score": "3", "body": "Welcome to Code Review. Your question looks already good. It will be perfect if you add the code of the project in the question itself, instead of only linking to GitHub. Since your program consists of multiple files, it's ok if you include an \"interesting subset\" of the code. For those who want to checkout the code the GitHub link provides access to the rest." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T20:00:53.520", "Id": "424289", "Score": "0", "body": "@RolandIllig: Thank you, I have added more code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T22:52:46.267", "Id": "424299", "Score": "0", "body": "I feel like you could avoided a lot of pain by just using C++? Why needlessly use C when it has no language support for linked-lists and other QOL?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T23:00:22.433", "Id": "424301", "Score": "0", "body": "@Rishav: It's a project for my 1st year university programming course. We've been told it has to be done in C. (although all kind of C libraries, portability or lack of portability, etc. allowed)" } ]
[ { "body": "<p>I took a look at your github and I think your code is broken up a bit too much. I think a few files can be consolidated.\nFor instance, consider consolidating the files for; input_cursor.c, pressed_key.c into one file called \"user_input.c\" and do the same for the .h files.</p>\n\n<p>I would also avoid making files named after reserved words in C. like \"structures.h\". Putting all of your structures in one place is fine if they all serve the same purpose, but name the file after the thing's purpose, not the thing. </p>\n\n<p>I see you're not including std.io until the testing functions are declared in the file. This won't affect performance or compile time. It only distracts the programmer. so regardless of the purpose of the include or which functions will use it, put them all at the top. Now, if you're planning on deleting your test code after release then you really should put all your test functions in their own files in a different directory labeled \"test\" and define a makefile that can take in a test flag so that it knows to compile the test objects together with the rest of your code.</p>\n\n<p>I also saw a variable declared in a c-code file called <em>keys_pqueue[25] = {}</em>, this is a configuration, and should go in a header file. leave the c-code files for functional code and the headers for all your different kinds of configurations and namespace management.</p>\n\n<p>That's the only feedback I have for now. Your code looks very well thought-out. And C/C++ are hard languages to begin coding with. So it's all very well done!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T22:17:57.813", "Id": "219680", "ParentId": "219670", "Score": "3" } }, { "body": "<p><strong>Initial position</strong></p>\n\n<p><code>add_cursor()</code> only adds the cursor's position to the function's queue if there is a change.</p>\n\n<p>Depending on needs, I'd expect the initial mouse position to be added too and not assume it is {0,0}. Presently, the true initial mouse position is never saved.</p>\n\n<p>Suggest:</p>\n\n<pre><code>POINT cursor_buff[2] = { get_cursor(), { 0,0}};\nadd_function(head, tail, _GETCURSOR, cursor_buff[0].x, cursor_buff[0].y);\n\nwhile(key_buff[1] != KEY_W) {\n ....\n</code></pre>\n\n<hr>\n\n<p><strong>Backwards?</strong></p>\n\n<p><code>play_recording()</code> looks like <code>tail = tail-&gt;prev;</code> is playing back in reverse order. I'd expect re-play to start at the beginning and play use <code>-&gt;next</code>.</p>\n\n<p>Need to see <code>add_function()</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-08T12:03:45.970", "Id": "424877", "Score": "0", "body": "Thank you for feedback. `add_cursor()` does indeed add cursor if and only if cursor has moved. With an exception for initial cursor position: it is added. I have recorded a short video to demonstrate that: https://streamable.com/1roos\nProblem is there was a small bug you helped me discover: if cursor initial possition is `(0, 0)`, then the program would crash. I have fixed it by initializing `POINT` array with `-1` instead of `0`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-08T12:06:17.273", "Id": "424878", "Score": "0", "body": "Not sure about `play_recording()` part. I am intentionally adding at the start of the queue and then playing from the end-to-start. I guess because it is a doubly linked list I can also quickly keep adding to the tail instead of start, and then play from the start. Yeah makes it more clear I guess." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-08T12:06:27.127", "Id": "424879", "Score": "0", "body": "Real question is what should I choose:\ndoubly linked list (more memory because two pointers for each node)\nor\nsingly linked list (less memory, but requires calling some `reverse_list()` function).\n\nWith singly linked list it could work like that: keep adding to the start, then `reverse_list()`, then play from the start." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-08T23:34:08.183", "Id": "424984", "Score": "0", "body": "@weno Use a single linked list. Carefully detail why you think you need a double linked list. Chances are, in the end a single linked one will do. A single linked list can perform all these in O(1) time: `Add_to_front(), Add_to_end(), Take_from_front(), report_front(), report_end(), Walk_list__forward_step()`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-08T02:07:28.080", "Id": "219902", "ParentId": "219670", "Score": "2" } } ]
{ "AcceptedAnswerId": "219680", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T19:43:14.407", "Id": "219670", "Score": "5", "Tags": [ "c", "linked-list", "windows", "winapi" ], "Title": "First C program: records keyboard/mouse and simulates the recording afterwards" }
219670
<p><strong>Background</strong></p> <p>In many languages we have built-in data types for representing decimal floating point numbers. In .NET that's <code>decimal</code>, and in Java we have <code>BigDecimal</code>.</p> <p>Now these are fundamentally different types. The .NET <code>decimal</code> is a fixed size value type, so its representable range and precision are limited (±1.0 × 10<sup>-28</sup> to ±7.9228 × 10<sup>28</sup>).</p> <p>On the other hand, the Java <code>BigDecimal</code> is <em>arbitrary</em> range and precision. Due to this it's not fixed size, but the length of its internal byte array depends on the size and precision of the represented number.</p> <p>Due to this it's impossible to implement guaranteed lossless conversion between these two types (it's possible in the .NET→Java direction, but not the other way around).</p> <p>What I want to implement is a "best effort" conversion, which throws an exception if the Java <code>BigDecimal</code> doesn't fit into a .NET <code>decimal</code>.</p> <p><strong>Requirements</strong></p> <p>The language is Java.<br> I have the following type, which models the internal representation of a .NET <code>decimal</code>.</p> <pre class="lang-java prettyprint-override"><code>public class DotNetDecimal { public final int mantissaLsb; public final long mantissaMsb; public final int exponentAndSign; public DotNetDecimal(int mantissaLsb, long mantissaMsb, int exponentAndSign) { this.mantissaLsb = mantissaLsb; this.mantissaMsb = mantissaMsb; this.exponentAndSign = exponentAndSign; } } </code></pre> <p>This is based on a suggestion for a Protobuf representation (which is also the motivation for this whole conversion story) described <a href="https://stackoverflow.com/a/371690/974733">here</a>.</p> <p>What I'd like to have is a class with the following signature.</p> <pre class="lang-java prettyprint-override"><code>public class DecimalHelper { public static BigDecimal fromDotNetDecimal(DotNetDecimal value) { ... } public static DotNetDecimal toDotNetDecimal(BigDecimal value) throws Exception { ... } } </code></pre> <p>And the requirements are the following.</p> <ul> <li><code>fromDotNetDecimal</code> should convert to a <code>BigDecimal</code>, which is always possible, and it's implementation is relatively straightforward.</li> <li><code>toDotNetDecimal</code> is trickier, we have the following cases: <ul> <li>If <code>value</code> can be exactly represented as a .NET <code>decimal</code>, then convert it.</li> <li>If <code>value</code> is in the range of what a .NET <code>decimal</code> can represent, but its fractional part has more digits (too high precision), then convert it, and round it so that it fits into a .NET <code>decimal</code>. This is where we lose precision.</li> <li>If <code>value</code> is out of the range of what a .NET <code>decimal</code> can represent, then all bets are off, throw an exception.</li> </ul></li> </ul> <p><strong>Implementation</strong></p> <p>This is my implementation, with a fair amount of comments.</p> <pre class="lang-java prettyprint-override"><code>public class DecimalHelper { public static final BigDecimal minValue; public static final BigDecimal maxValue; static { minValue = new BigDecimal(BigInteger.valueOf(0xffffffffL).shiftLeft(32).add(BigInteger.valueOf(0xffffffffL)) .shiftLeft(32).add(BigInteger.valueOf(0xffffffffL)).negate()); maxValue = new BigDecimal(BigInteger.valueOf(0xffffffffL).shiftLeft(32).add(BigInteger.valueOf(0xffffffffL)) .shiftLeft(32).add(BigInteger.valueOf(0xffffffffL))); } public static BigDecimal fromDotNetDecimal(DotNetDecimal value) { long mantissaMsbUpper = value.mantissaMsb &gt;&gt;&gt; 32; long mantissaMsbLower = value.mantissaMsb &amp; 0xffffffffL; BigInteger integer = BigInteger.valueOf(mantissaMsbUpper).shiftLeft(32) .add(BigInteger.valueOf(mantissaMsbLower)).shiftLeft(32) .add(BigInteger.valueOf(value.mantissaLsb &amp; 0xffffffffL)); BigDecimal decimal = new BigDecimal(integer, (value.exponentAndSign &amp; 0xff0000) &gt;&gt; 16); if (value.exponentAndSign &lt; 0) { decimal = decimal.negate(); } return decimal; } public static DotNetDecimal toDotNetDecimal(BigDecimal value) throws Exception { if (value.compareTo(minValue) &lt; 0) { throw new Exception("Input number is out of range."); } if (value.compareTo(maxValue) &gt; 0) { throw new Exception("Input number is out of range."); } // The largest representable number with DotNetDecimal has 29 decimal digits. if (value.precision() &gt; 29) { // If the precision of the BigDecimal is more than 29, we have to decrease it to // 29, and do rounding. With this we're losing some precision, but this only // happens to either very large numbers, or numbers with a lot of fraction digits. // In this case it's certainly not a round number, otherwise the previous range // checks would've failed. // This call will remove (with rounding) as many digits from the fractional // parts as needed to make the total number of digits 29. value = value.setScale(value.scale() - (value.precision() - 29), BigDecimal.ROUND_HALF_UP); } // The representation of the mantissa in DotNetDecimal has 96 bits, so we cannot // represent more. if (value.unscaledValue().bitLength() &gt; 96) { // Even if we're inside the range of the min and max DotNetDecimal, and we don't // have more than 29 decimal digits, it might be that the unscaled value is // still more than 96 bits, which can not be represented with a DotNetDecimal. // This is the case for a number like 9.9999999999999999999999999999 (exactly 29 // digits). // In this case, we decrease the scale with one more. value = value.setScale(value.scale() - 1, BigDecimal.ROUND_HALF_EVEN); } // At this point we know that value is in the range of what DotNetDecimal can // represent, with the same precision, so the last thing to do is to transform // to the representation. boolean isNegative = value.compareTo(BigDecimal.valueOf(0)) &lt; 0; if (value.scale() &gt;= 0) { // In this case the unscaled value is the mantissa, and the scale and the sign // has to go into the exponent_and_sign. // For simplicity, we negate the number if it's negative. if (isNegative) { value = value.negate(); } var bytes = value.unscaledValue().toByteArray(); long msb = unscaledBytesToMsb(bytes); int lsb = unscaledBytesToLsb(bytes); int exponentAndSign = value.scale() &lt;&lt; 16; if (isNegative) { // We have to set the first (MSB) bit to 1. exponentAndSign = exponentAndSign | 0x80000000; } return new DotNetDecimal(lsb, msb, exponentAndSign); } else { // In this case the unscaled value is not the real mantissa, we have to scale it // up, and the exponent will be zero. if (isNegative) { value = value.negate(); } // We create a new BigInteger by multiplying the original number by ten to the // power of the negation of the scale. var scaledUp = value.unscaledValue().multiply(BigInteger.valueOf(10).pow(-value.scale())); var bytes = scaledUp.toByteArray(); long msb = unscaledBytesToMsb(bytes); int lsb = unscaledBytesToLsb(bytes); // Since scale() is negative, we know it's a round number, so the exponent is 0. int exponentAndSign = 0; if (isNegative) { // We have to set the first (MSB) bit to 1. exponentAndSign = exponentAndSign | 0x80000000; } return new DotNetDecimal(lsb, msb, exponentAndSign); } } // NOTE: When we build the mantissa MSB and the LSB, before bitwise ORing the // byte to the accumulator in every iteration, // we need to interpret the byte as an unsigned number. // So instead of simply doing (msb | bytes[i]), we do (msb | ((long)bytes[i] &amp; 0xFF)) // Otherwise the byte would be automatically casted to a long, and interpreted // as a negative number, so all its higher bits would be set to 1. private static int unscaledBytesToLsb(byte[] bytes) { var bytesLength = bytes.length; // If the first byte in the array is 0, then it was included only for the sign // bit, we have to ignore it. int startIndex = bytes[0] == 0 ? 1 : 0; int lsb = 0; int j = 0; // Convert the LSB part: for (int i = bytesLength - 1; i &gt;= startIndex &amp;&amp; i &gt;= bytesLength - 4; i--) { lsb = lsb | ((int) bytes[i] &amp; 0xFF) &lt;&lt; (j * 8); j++; } return lsb; } private static long unscaledBytesToMsb(byte[] bytes) { var bytesLength = bytes.length; // If the first byte in the array is 0, then it was included only for the sign // bit, we have to ignore it. int startIndex = bytes[0] == 0 ? 1 : 0; long msb = 0; int j = 0; // Convert the MSB part: for (int i = bytesLength - 5; i &gt;= startIndex; i--) { msb = msb | ((long) bytes[i] &amp; 0xFF) &lt;&lt; (j * 8); j++; } return msb; } } </code></pre> <p>(The <code>fromDotNetDecimal</code> implementation is based on <a href="https://stackoverflow.com/a/43373185/974733">this answer</a>.)</p> <p>I'm pretty confident the implementation is mostly correct, because I tested it with a wide range of inputs. I know the code is probably rather naive in terms of optimizations, but I'm not worried about perf too much.</p> <p>What I'd be interested in is any suggestions/mistakes you can see in terms of the correctness of the code, if you can think of any edge case that's not correctly covered.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T21:13:52.243", "Id": "219675", "Score": "3", "Tags": [ "java", ".net", "bitwise", "serialization", "fixed-point" ], "Title": "Java code to convert BigDecimal to/from .NET decimal" }
219675
<p>This is a <code>bash</code> library intended to be used in a CI/CD pipeline to make finding the next release number for a Debian package semi-automatic. I figured out how to use a JSON file as a metadata store since the CI/CD pipeline I'm working with doesn't provide any metadata storage across jobs.</p> <p>I'm basically happy with how this is working. We've used it for a few weeks without finding any bugs yet. I'm happy that it passes <a href="https://www.shellcheck.net/" rel="nofollow noreferrer">shellcheck</a>, but I'd also like to have some linting for ensuring that the code is documented adequately. I'm not sure if my use of <code>jq</code> makes this too hard to maintain or if it just that using <code>jq</code> like this is so new to me.</p> <h1>deblib.sh</h1> <pre><code>#!/bin/bash # TODO: generate $PKGJSON from Debian repo metadata PKGJSON=/opt/org_foo/var/packaging/packaging.json # deb-release-number # ------------------ # # Arguments: # 1. (required) package name # 2. (required) package version ("upstream" version) # 3. (optional) architecture (defaults to amd64) # 4. (optional) packager (defaults to 1org_foo) # # Testing: # Test by running # bash deblib.sh debug # or passing any argumenet in to activate the "verification" section below function deb-release-number { # read arguments PKGNAME=${1?provide package name as first argument} PKGVER=${2?provide package version as second argument} PKGARCH=${3:-amd64} PACKAGER=${4-1org_foo} # find latest release of this package/version RELEASE=$(jq -r ".\"latest_version\".\"${PKGNAME}\".\"${PKGVER}\"" &lt;"$PKGJSON" ) if [[ "$RELEASE" == "null" ]]; then # start at 0 so the first release ends up being 1 after the increment below RELEASE=0 fi ## echo RELEASE=$RELEASE # increment RELEASE=$(( RELEASE + 1 )) LONGPKGVER="${PKGVER}-${PACKAGER}-${RELEASE}" # seperated with dashes PKGFILENAME="${PKGNAME}_${LONGPKGVER}_${PKGARCH}.deb" # seperated with underscores echo "new release $RELEASE of $PKGNAME creates filename $PKGFILENAME" # backup cp "$PKGJSON" "${PKGJSON}.bak" # update release_version (into tmp file) jq ".\"latest_version\".\"${PKGNAME}\".\"${PKGVER}\" = \"${RELEASE}\"" &lt;"$PKGJSON" &gt;"${PKGJSON}.tmp" ## grep "$PKGVER" "${PKGJSON}.tmp" # update built_packages (out of tmp file into main file) jq ".\"built_packages\" += [\"${PKGFILENAME}\"]" &lt;"${PKGJSON}.tmp" &gt;"$PKGJSON" ## grep "$PKGNAME" "$PKGJSON" return $RELEASE } # verification if [[ $# -gt 0 ]]; then deb-release-number librdkafka1 1.0.0 deb-release-number foo 1.1.0 noarch fi </code></pre> <h1>Example</h1> <p>An example of usage:</p> <pre><code>source deblib.sh deb-release-number 'foo-stuff' "${GIT_TAG#v}" 'amd64' PKGRELEASE=$? </code></pre>
[]
[ { "body": "<p>Some lints:</p>\n\n<ul>\n<li>Uppercase names are by convention only for <code>export</code>ed variables.</li>\n<li>You can use <code>getopt</code> to parse parameters. This should make it easier to handle optional parameters, and also makes it easy to avoid positional parameters (which makes commands more self-documenting).</li>\n<li><a href=\"https://mywiki.wooledge.org/Quotes\" rel=\"nofollow noreferrer\">Use More Quotes™</a></li>\n<li>I would guard against errors and accidents by using <code>set -o errexit -o noclobber -o nounset -o pipefail</code> at the top of the script.</li>\n<li><code>return</code>ing anything other than an <em>exit code</em> is a problem. You function should instead <em>output</em> the value (and ensure other output goes to standard error). One issue is the semantics of conflating exit codes. The other is the lingering bug because exit codes <em>wrap around</em> after 255.</li>\n<li>You can use <code>mktemp --directory</code> to create a temporary directory to store intermediate results. Even better would be to pass results in a pipeline to avoid any temporary files.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T12:08:52.183", "Id": "424335", "Score": "0", "body": "Thanks for this. I'm ok with the limit of 255 on exit values for this use case, but I probably should add some error checking for that. Turning it into something that returns by output would mess with the other stuff printed out in there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T12:10:18.960", "Id": "424336", "Score": "0", "body": "Shellcheck strongly encourages quoting to avoid problems so I thought I was doing pretty well there. Is there some line that bothers you in my code or would you prefer to see almost everything quoted?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-22T05:27:54.533", "Id": "426401", "Score": "0", "body": "returning by output has other problems too, like it's slow, and you can't error exit because the function is running inside `$( )` and will only exit the subshell, not the script. A useful idiom is returning via variable name taken as an argument, as in `printf -v$3 %d $RELEASE`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T03:53:32.533", "Id": "219684", "ParentId": "219676", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T21:28:27.863", "Id": "219676", "Score": "2", "Tags": [ "bash" ], "Title": "shell library for Debian package releases" }
219676
<p>I've written <a href="https://github.com/mossrich/PowershellRecipes/blob/master/AsciiMenu.ps1" rel="nofollow noreferrer">a pair of functions</a> that can be added to a module or script that will allow the developer to specify a list of options and let the user select with the up/down arrow and return any selected with <kbd>Enter</kbd>, or abort with <kbd>Esc</kbd>. </p> <p>I haven't used them much yet, and I'm wondering if there are any features that they'd need to be truly useful. </p> <pre><code>&lt;# Shows an ascii menu: highlight with up/down arrows or 1..9, or first letter of option and choose with [Enter]. ┌Choose an option┐ │first │ │second option │ │third │ └────────────────┘ Note that ReadKey (required for up/down arrows) doesn't work in ISE. There is no graceful downgrade for this script. #&gt; function Show-SimpleMenu ([array]$Options, [string]$Title ='Choose an option',$border = '┌─┐│└┘',[int]$highlighted = 0){ $maxLength = [Math]::Max(($Options | Measure -Max -Prop Length).Maximum, $Title.Length) #get longest option or title $MenuTop = [Console]::CursorTop Do{ [Console]::CursorTop = $MenuTop $LeftPad = [string]$border[1] * [Math]::Max(0,[math]::Floor(($maxlength-$Title.Length)/2)) #gets the left padding required to center the title Write-Host "$($border[0])$(($LeftPad + $Title).PadRight($maxLength,$border[1]))$($border[2])" # #top border: ┌Title─┐ left-aligned: Write-Host "$($border[0])$($Title.PadRight($maxLength,$border[1]))$($border[2])" for ($i = 0; $i -lt $Options.Length;$i++) { Write-Host $border[3] -NoNewLine if ($i -eq $highlighted) { Write-Host ([string]$Options[$i]).PadRight($maxLength,' ') -fore ([Console]::BackgroundColor) -back ([Console]::ForegroundColor) -NoNewline } else { Write-Host ([string]$Options[$i]).PadRight($maxLength,' ') -NoNewline } Write-Host $border[3] } Write-Host "$($border[4])$([string]$border[1] * $maxLength)$($border[5])" #bottom border:└─┘ $key = [Console]::ReadKey($true) If ($key.Key -eq [ConsoleKey]::UpArrow -and $highlighted -gt 0 ) {$highlighted--} ElseIf ($key.Key -eq [ConsoleKey]::DownArrow -and $highlighted -lt $Options.Length - 1) {$highlighted++} ElseIf ( (1..9 -join '').contains($key.KeyChar) -and $Options.Length -ge [int]::Parse($key.KeyChar)) { $highlighted = [int]::Parse($key.KeyChar) - 1 }#change highlight with 1..9 Else { (([math]::min($highlighted + 1, $Options.Length) .. $Options.Length) + (0 .. ($highlighted - 1))) | %{ #cycle from highlighted + 1 to end, and restart If($Options[$_] -and $Options[$_].StartsWith($key.KeyChar) ){$highlighted = $_; Continue} #if letter matches first letter, highlight } } }While( -not ([ConsoleKey]::Enter,[ConsoleKey]::Escape).Contains($key.Key) ) If($Key.Key -eq [ConsoleKey]::Enter){ $Options[$highlighted] } } &lt;# Shows an ascii menu: highlight with up/down arrows or 1..9, or first letter of option. Select with space bar and choose with [Enter]. ┌─Select with spacebar─┐ │√first │ │ second │ │√third │ └──────────────────────┘ #&gt; function Show-MultiSelectMenu ([array]$Options, [string]$Title ='Select with spacebar', $border = '┌─┐│└┘', $highlighted = 0, $selected = (New-Object bool[] $Options.Length ) ){ $maxLength = ($Options | Measure-Object -Maximum -Property Length).Maximum + 1 #get longest string length, +padding for √ If($maxLength -lt $Title.Length + 2){$maxLength = $Title.Length + 1} If($selected.Length -lt $Options.Length){$selected += (New-Object bool[] ($Options.Length - $selected.Length)) } $MenuTop = [Console]::CursorTop Do{ [Console]::CursorTop = $MenuTop $LeftPad = [string]$border[1] * [Math]::Max(1,[math]::Floor(($maxlength-$Title.Length)/2)) #Centered, at least one border ─ Write-Host "$($border[0])$(($LeftPad + $Title).PadRight($maxLength + 1,$border[1]))$($border[2])" #top border: ┌─Title─┐ for ($i = 0; $i -lt $Options.Length;$i++) {#draw the menu Write-Host "$($border[3])$(If($selected[$i]){"√"}else{" "})" -NoNewLine if ($i -eq $highlighted) { Write-Host ([string]$Options[$i]).PadRight($maxLength,' ') -fore ([Console]::BackgroundColor) -back ([Console]::ForegroundColor) -NoNewline } else { Write-Host ([string]$Options[$i]).PadRight($maxLength,' ') -NoNewline } Write-Host $border[3] } Write-Host "$($border[4])$($border[1])$([string]$border[1] * ($maxLength))$($border[5])" $key = [Console]::ReadKey($true) If ($key.Key -eq [ConsoleKey]::Spacebar) {$selected[$highlighted] = !$selected[$highlighted] } ElseIf ($key.Key -eq [ConsoleKey]::UpArrow -and $highlighted -gt 0 ) {$highlighted--} ElseIf ($key.Key -eq [ConsoleKey]::DownArrow -and $highlighted -lt $Options.Length - 1) {$highlighted++} ElseIf ( (1..9 -join '').contains($key.KeyChar) -and $Options.Length -ge [int]::Parse($key.KeyChar)) { $highlighted = [int]::Parse($key.KeyChar) - 1 }#change highlight with 1..9 Else { (([math]::min($highlighted + 1, $Options.Length) .. $Options.Length) + (0 .. ($highlighted - 1))) | %{ #cycle from highlighted + 1 to end, and restart If($Options[$_] -and $Options[$_].StartsWith($key.KeyChar) ){$highlighted = $_; Continue} #if letter matches first letter, highlight } } }While(! @([ConsoleKey]::Enter, [ConsoleKey]::Escape ).Contains($key.Key)) #stop if Enter or Esc If($key.Key-eq [ConsoleKey]::Enter){ #return the menu options that are selected $Options | %{$i=0}{ If($selected[$i++]){$_} } #TIL: foreach can have a 'begin' scriptbock that's executed only once } } $lowASCIIBorder = '+-+|++' #are there any consoles or fonts where ASCII box borders won't show? $doubleBorder = '╔═╗║╚╝' Show-SimpleMenu @('first','second option','third','fourth','fifth') -border $doubleBorder Show-MultiSelectMenu @('first','second','third','fourth','fifth') -selected @($true,$false,$true) Show-MultiSelectMenu (Get-ChildItem -Path . -Directory | Select-Object -ExpandProperty FullName) -selected @($true,$false,$true) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-03T22:17:47.813", "Id": "219679", "Score": "3", "Tags": [ "console", "powershell", "ascii-art" ], "Title": "ASCII-Box PowerShell menu" }
219679
<p>This is a script I wrote to:</p> <ul> <li>Combine multiple text files into one CSV</li> <li>Append the source file's name to each line of data</li> </ul> <p>This script currently takes about 3 seconds per 10,000 lines read - this is so long in comparison to a working batch/Perl script I have that I'm wondering what I'm doing wrong.</p> <p>Comments about whether this is even the best approach is welcome - anything that gets me one combined file with the source file name appended to each line is welcome. I chose to use StreamReader because the source files are very large.</p> <p><strong>Powershell</strong></p> <pre><code># Powershell -executionpolicy bypass -file (.ps1 file path) [System.IO.DirectoryInfo]$ResponsesFolder = (folder path) [System.IO.DirectoryInfo]$pathCombinedResponsesCSV = ($ResponsesFolder.Parent.FullName + [IO.Path]::DirectorySeparatorChar + $ResponsesFolder.BaseName + "_Combined_Responses.csv") if (Test-Path $pathCombinedResponsesCSV) { Remove-Item $pathCombinedResponsesCSV } $streamWriter = New-Object System.IO.StreamWriter $pathCombinedResponsesCSV Write-Host $pathCombinedResponsesCSV $files = Get-ChildItem -Path ($ResponsesFolder.ToString() + "*.*") -File $totalFiles = $files.Count $fileindex = 0 $files | ForEach-Object { $streamReader = New-Object System.IO.StreamReader $_.FullName [int]$fileindex = $fileindex + 1 Write-Host ("File " + $fileindex + " of " + $totalFiles) [string]$fileName = $_.Name [int]$lineIndex = 0 while (([string]$line = $streamReader.ReadLine()) -ne $null) { $streamWriter.WriteLine($line + "|" + $fileName) $lineIndex = $lineIndex + 1 if ($lineindex % 10000 -eq 0) { Write-Host $lineindex "lines of" $fileName "loaded" } } $streamReader.Close(); $streamReader.Dispose() } $streamWriter.Close(); $streamWriter.Dispose() </code></pre> <p><strong>Batch/Perl</strong></p> <pre><code>pushd (UNC folder path) copy *.TXT *.csv REM Add filename to end of each record. net use b: /delete /y net use b: (UNC folder path) for /f %%a IN ('dir /b (UNC folder path)*.csv"') do (perl -i.bak -p -e "s/\n/|$ARGV\n/" %%a ) copy *.csv Consolidated_Magic_File.csv </code></pre>
[]
[ { "body": "<p>The Perl approach can be shorter and faster than it already is:</p>\n\n<pre><code>perl -ple\"BEGIN { @ARGV=glob shift } s,$,|$ARGV,\" *.csv &gt; Consolidated_Magic_File.not_an_input\nren *.not_an_input *.csv\n</code></pre>\n\n<p>The best PowerShell approach is not so different from the fast Perl approach. Feed a list of filenames, use <code>Get-Content</code> (or <code>gc</code>) to read them, let PS figure out where the line breaks are, loop through those results and collect all the outputs in one place.</p>\n\n<pre><code>ls \\\\unc\\folder -Filter *.txt | %{ $fn=$_.Basename; gc $_.PSPath | %{ $_ + \"|$fn\" } } | sc out.csv\n</code></pre>\n\n<p><code>$_.Basename</code> is the name without path or extension. You can use <code>$_.Name</code> to get the original name with extension, or <code>$_.Basename + \".csv\"</code> to label the output with CSV-filenames even though your input was TXT files.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T12:24:47.473", "Id": "424586", "Score": "0", "body": "Thank you for writing this up. I won't accept this answer because it recommends Get-Content for large source files, but I appreciate the perl advice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T13:27:41.280", "Id": "424592", "Score": "1", "body": "If they really are that large, just remove the parens around `gc`; see edit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T15:18:59.023", "Id": "424607", "Score": "0", "body": "I'm sure you know more about this than I do, but can you please explain in detail why you recommend Get-Content when [tests](https://stackoverflow.com/questions/44462561/system-io-streamreader-vs-get-content-vs-system-io-file) [consistently](http://www.happysysadm.com/2014/10/reading-large-text-files-with-powershell.html) [show](https://foxdeploy.com/2016/03/23/coding-for-speed/) StreamReader is much faster? This is why I previously said that I would not accept this answer." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T08:07:24.680", "Id": "219687", "ParentId": "219682", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T00:20:13.067", "Id": "219682", "Score": "2", "Tags": [ "powershell" ], "Title": "Combine Medical Response Files Prior To Table Load" }
219682
<p>I am doing a project in plant pest detection using CNN. There are four classes each having about 1400 images. While training the model using Convolution Neural Network, there is a smooth curve for training while for validation there lots of ups and downs in high range. After that,I start using alexnet architecture of CNN. There is smooth curve in both training and validation but overfitting problem occurs.What are the things I should consider for resolving this issues.Is there any other standard CNN architecture for training when there is small data. You can find the code in more detail <a href="https://i.stack.imgur.com/K4tCS.png" rel="nofollow noreferrer">alexnet.</a> </p> <pre><code>EPOCHS = 20 INIT_LR = 1e-5 BS = 8 default_image_size = tuple((256, 256)) image_size = 0 directory_root = '../input/plantvillag/' width=256 height=256 depth=3 </code></pre> <p><strong>Function to convert images to array</strong></p> <pre><code> def convert_image_to_array(image_dir): try: image = cv2.imread(image_dir) if image is not None : image = cv2.resize(image, default_image_size) return img_to_array(image) else : return np.array([]) except Exception as e: print(f"Error : {e}") return None </code></pre> <p><strong>Fetch images from directory</strong></p> <pre><code>image_list, label_list = [], [] try: print("[INFO] Loading images ...") root_dir = listdir(directory_root) for directory in root_dir : # remove .DS_Store from list if directory == ".DS_Store" : root_dir.remove(directory) for plant_folder in root_dir : plant_disease_folder_list = listdir(f"{directory_root}/{plant_folder}") for disease_folder in plant_disease_folder_list : # remove .DS_Store from list if disease_folder == ".DS_Store" : plant_disease_folder_list.remove(disease_folder) for plant_disease_folder in plant_disease_folder_list: print(f"[INFO] Processing {plant_disease_folder} ...") plant_disease_image_list = listdir(f"{directory_root}/{plant_folder}/{plant_disease_folder}/") for single_plant_disease_image in plant_disease_image_list : if single_plant_disease_image == ".DS_Store" : plant_disease_image_list.remove(single_plant_disease_image) for image in plant_disease_image_list[:1000]: image_directory = f"{directory_root}/{plant_folder}/{plant_disease_folder}/{image}" if image_directory.endswith(".jpg") == True or image_directory.endswith(".JPG") == True: image_list.append(convert_image_to_array(image_directory)) label_list.append(plant_disease_folder) print("[INFO] Image loading completed") except Exception as e: print(f"Error : {e}") </code></pre> <p><strong>Get Size of Processed Image</strong></p> <pre><code>image_size = len(image_list) </code></pre> <p><strong>Transform Image Labels uisng Scikit Learn's LabelBinarizer</strong></p> <pre><code> label_binarizer = LabelBinarizer() image_labels = label_binarizer.fit_transform(label_list) pickle.dump(label_binarizer,open('label_transform.pkl', 'wb')) n_classes = len(label_binarizer.classes_) np_image_list = np.array(image_list, dtype=np.float32) / 255.0 </code></pre> <p><strong>Splitting data</strong></p> <pre><code>print("[INFO] Spliting data to train, test") x_train, x_test, y_train, y_test = train_test_split(np_image_list,image_labels, test_size=0.2, random_state = 42) aug = ImageDataGenerator( rotation_range=25, width_shift_range=0.1, height_shift_range=0.1, shear_range=0.2, zoom_range=0.2,horizontal_flip=True, fill_mode="nearest") </code></pre> <p><strong>Model Build</strong></p> <pre><code>from keras import layers from keras.models import Model optss = Adam(lr=INIT_LR, decay=INIT_LR / EPOCHS) def alexnet(in_shape=(256,256,3), n_classes=n_classes, opt=optss): in_layer = layers.Input(in_shape) conv1 = layers.Conv2D(96, 11, strides=4, activation='relu')(in_layer) pool1 = layers.MaxPool2D(3, 2)(conv1) conv2 = layers.Conv2D(256, 5, strides=1, padding='same', activation='relu')(pool1) pool2 = layers.MaxPool2D(3, 2)(conv2) conv3 = layers.Conv2D(384, 3, strides=1, padding='same', activation='relu')(pool2) conv4 = layers.Conv2D(256, 3, strides=1, padding='same', activation='relu')(conv3) pool3 = layers.MaxPool2D(3, 2)(conv4) flattened = layers.Flatten()(pool3) dense1 = layers.Dense(4096, activation='relu')(flattened) drop1 = layers.Dropout(0.8)(dense1) dense2 = layers.Dense(4096, activation='relu')(drop1) drop2 = layers.Dropout(0.8)(dense2) preds = layers.Dense(n_classes, activation='softmax')(drop2) model = Model(in_layer, preds) model.compile(loss="categorical_crossentropy", optimizer=opt,metrics=["accuracy"]) return model model = alexnet() </code></pre> <p><strong>Performing Training</strong></p> <pre><code> history = model.fit_generator( aug.flow(x_train, y_train, batch_size=BS), validation_data=(x_test, y_test), steps_per_epoch=len(x_train) // BS, epochs=EPOCHS, verbose=1 ) </code></pre> <p><strong>Graphs</strong></p> <pre><code>acc = history.history['acc'] val_acc = history.history['val_acc'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(1, len(acc) + 1) #Train and validation accuracy plt.plot(epochs, acc, 'b', label='Training accurarcy') plt.plot(epochs, val_acc, 'r', label='Validation accurarcy') plt.title('Training and Validation accurarcy') plt.legend() plt.figure() #Train and validation loss plt.plot(epochs, loss, 'b', label='Training loss') plt.plot(epochs, val_loss, 'r', label='Validation loss') plt.title('Training and Validation loss') plt.legend() plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/K4tCS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/K4tCS.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/IJb1l.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IJb1l.png" alt="enter image description here"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T07:14:30.953", "Id": "424316", "Score": "1", "body": "Request for clarification: what language are your using?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T07:44:12.483", "Id": "424320", "Score": "0", "body": "I am using python" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T08:48:42.377", "Id": "424325", "Score": "1", "body": "Welcome to Code Review! `I am using python` Use tags to direct attention with regard to (your) questions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T14:18:20.337", "Id": "424346", "Score": "0", "body": "I'm not entirely sure if the question is suited for Code Review. Since this is more of a general neural network question, and not really about improving the code quality, it might be better suited for [Data Science Stack Exchange](https://datascience.stackexchange.com/)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T06:30:11.740", "Id": "219685", "Score": "2", "Tags": [ "python", "machine-learning", "opencv" ], "Title": "Plant pest detection using CNN" }
219685
<p>My relevant work experience is with Java (mostly web development with Dropwizard/Spring) so I can not avoid using the same practices as I do in a Java project. The project is <a href="https://github.com/josekron/liveops-tool/tree/d1c0307de153b7edb4c5ee22c283e193c7ec2ac8" rel="nofollow noreferrer">there</a> but I am going to copy it here:</p> <p><strong>Project</strong></p> <p>A very simple project 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 ------ userDirectory.go (mock the db) -- 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 res = userService.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>user.go</strong></p> <pre><code>package user type User struct { ID string `json:"id"` Name string `json:"name"` Country string `json:"country"` TotalScore int `json:"totalScore"` } </code></pre> <p><strong>userService.go</strong></p> <pre><code>package user import ( user "liveops-tool/user/model" ) // GenerateUserListByScore returns a list of users for a tournament func GenerateUserListByScore(numUsers, minScore, maxScore int) []user.User { return searchUsers(numUsers, minScore, maxScore) } </code></pre> <p><strong>userDirectory.go</strong></p> <pre><code>package user import ( "fmt" userModel "liveops-tool/user/model" ) var users = []userModel.User{} func init() { initUsers() } func searchUsers(numUsers, minScore, maxScore int) []userModel.User { return filterUsersByScore(numUsers, minScore, maxScore) } func filterUsersByScore(numUsers, minScore, maxScore int) []userModel.User { var filteredUsers = []userModel.User{} var countUsers = 0 if len(users) &lt; numUsers { numUsers = len(users) } for i := range users { if users[i].TotalScore &gt;= minScore &amp;&amp; users[i].TotalScore &lt;= maxScore { filteredUsers = append(filteredUsers, users[i]) countUsers++ } if countUsers &gt;= numUsers { break } } return filteredUsers } func initUsers() { user1 := userModel.User{ID: "1", Name: "John", Country: "UK", TotalScore: 500} user2 := userModel.User{ID: "2", Name: "Frank", Country: "ES", TotalScore: 1500} user3 := userModel.User{ID: "3", Name: "Bob", Country: "UK", TotalScore: 2000} user4 := userModel.User{ID: "4", Name: "Anna", Country: "FR", TotalScore: 3000} users = append(users, user1) users = append(users, user2) users = append(users, user3) users = append(users, user4) fmt.Printf("users: %+v\n", users) } </code></pre> <p><strong>Questions</strong></p> <ul> <li><p>I am mocking the user list and I would like the method <em>initUsers</em> would not be accesible from <em>userService</em>. Golang doesn't have public and private methods because the visibility depends on the package. The same for the function <em>filterUsersByScore</em>. How can I improve it?</p></li> <li><p>User (model): I need to put the attributes with the first letter in uppercase to make it exportable when I return the JSON. Is it possible to have the attributes as private to access them through getters and setters and also return them in the JSON response?</p></li> </ul> <p>Any other advice about the code is well received.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-23T23:08:23.707", "Id": "431482", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<p>Let's start by addressing your 2 main questions:</p>\n\n<h2>1. Visibility (exporting) of functions</h2>\n\n<p>Yes, there's a very easy way of doing this, by using receiver functions (methods), and interfaces. Golang interfaces are incredibly powerful if you understand where they actually differ from <em>\"traditional\"</em> languages with a full-blown OOP model. you could have a <code>directory</code> type, and expose an interface to the service, which only declares the functions you want to use. Suppose you want your service to access <code>GetUsers</code>, but not a <code>FilterByX</code>, then just pass this <code>directory</code> type in as an interface type limiting how you can use it:</p>\n\n<pre><code>// in service\ntype Directory interface {\n GetUsers() []User\n}\n\ntype service struct {\n dir Directory // interface type\n}\n\nfunc New(dir Directory) *service {\n return &amp;service{\n dir: dir,\n }\n}\n</code></pre>\n\n<p>The interface is declared in the package that uses it, not in the package implementing said interface. This makes unit-testing a lot easier. There's quite a few articles about this around. It's a bit odd at first, if you're used to OO, but it makes sense quite quickly. Don't try to make go look like C++, C#, or Java... it's its own thing, and though not perfect, it's got a lot of good things going for it.</p>\n\n<p>As for the <code>initUsers</code>: that function is completely pointless. You could move the entire body of that function into your <code>init</code> function from the get-go. But why stop there? You can simply initialise your variable straight up, rather than creating 2 function calls to do the same thing:</p>\n\n<pre><code>var users = []User{\n {\n ID: \"1\",\n Name: \"John\",\n Country: \"UK\",\n TotalScore: 500,\n },\n {\n ID: \"2\",\n Name: \"Frank\",\n Country: \"ES\",\n TotalScore: 1500,\n },\n {\n ID: \"3\",\n Name: \"Bob\",\n Country: \"UK\",\n TotalScore: 2000,\n },\n {\n ID: \"4\",\n Name: \"Anna\",\n Country: \"FR\",\n TotalScore: 3000,\n },\n}\n</code></pre>\n\n<p>That's it, all done.</p>\n\n<h2>2. Marshalling unexported fields.</h2>\n\n<p>Yes, this is possible, but I'd strongly advise against it. However, here's a couple of ways to do it. In both cases, we're relying on the fact that golang supports a JSON Marshaller and Unmarshaller interface out of the box.</p>\n\n<pre><code>type User struct {\n id string\n name string\n country string\n score int\n}\n\n// manually creating a map\nfunc (u User) MarshalJSON() ([]byte, error) {\n data := map[string]interface{}{\n \"id\": u.id,\n \"name\": u.name,\n \"country\": u.country,\n \"score\": u.score,\n }\n return json.Marshal(data)\n}\n\n// now with some pointer magic... mimics the omitempty tag\nfunc (u User) MarshalJSON() ([]byte, error) {\n data := map[string]interface{}{\n \"id\": &amp;u.id,\n \"name\": &amp;u.name,\n \"country\": &amp;u.country,\n \"score\": &amp;u.score,\n }\n return json.Marshal(data)\n}\n</code></pre>\n\n<p>Now for unmarshalling:</p>\n\n<pre><code>// note a pointer receiver is required here, we're changing the receiver state\nfunc (u *User) UnmarshalJSON(v []byte) error {\n data := map[string]interface{}{} // empty map\n if err := json.Unmarshal(v, &amp;data); err != nil {\n return err\n }\n if id, ok := data[\"id\"]; ok {\n // technically we need to check the type assert, I'll do it once:\n strId, ok := id.(string)\n if !ok {\n return errors.New(\"id value is not a string!\")\n }\n u.id = strId\n }\n if name, ok := data[\"name\"]; ok {\n u.name = name.(string)\n }\n if country, ok := data[\"country\"]; ok {\n u.country = country.(string)\n }\n if score, ok := data[\"score\"]; ok {\n u.score = score.(int)\n }\n return nil\n}\n</code></pre>\n\n<p>As you can probably see now, each field you add will add more code that needs to be written, changing the names of fields is a right PITA... it's better to just not bother IMO.</p>\n\n<p>You <em>could</em> use the pointer trick from the marshaller here to avoid the type assertions, though:</p>\n\n<pre><code>func (u *User) UnmarshalJSON(v []byte) error {\n data := map[string]interface{}{\n \"id\": &amp;u.id,\n \"name\": &amp;u.name,\n \"country\": &amp;u.country,\n \"score\": &amp;u.score,\n }\n // unmarshals into map[string]&lt;pointer to fields on struct&gt;\n return json.Unmarshal(v, &amp;data)\n}\n</code></pre>\n\n<p>Still, this doesn't look nice to me. I'd just stick with exported fields + json tags. If you really don't want people to access fields in certain places, just use interfaces as explained above.</p>\n\n<hr>\n\n<p>Something you really ought not to do, is your over-use of package aliases. You may, or may not have noticed that I've always used the <code>User</code> type, without a package name. You've got aliases like:</p>\n\n<pre><code>user \"liveops-tool/user/model\"\n// and the even worse\nuserModel \"liveops-tool/user/model\"\n</code></pre>\n\n<p>This is what sometimes is referred to as stuttering names. Read this aloud and ask yourself whether your package name is giving the user of your code any clearer understanding of what the <code>User</code> type represents:</p>\n\n<pre><code>u := user.User{} // u is an instance of User from the user package\n</code></pre>\n\n<p>What's in the <code>user</code> package? What is this <code>User</code>? I don't know. I'm just annoyed at having to type <code>user</code> twice.</p>\n\n<pre><code>u := userModel.User{} // u us a user from the userModel package\n</code></pre>\n\n<p>OK, now I know <code>User</code> is probably some kind of data structure. Good, but did I really need to know that I'm getting a <code>User</code> form the <code>userModel</code> package? I'm still annoyed at having to type <code>user</code> twice. The file itself is in the directory called <code>model</code> (perhaps <code>models</code> would be better). That's the bit of information that I want, so why not just:</p>\n\n<pre><code>import (\n \"liveops-tool/user/model\"\n)\n\nfunc foo() {\n u := model.User{} // u is a user model\n}\n</code></pre>\n\n<p>That's a lot better, isn't it? You may want to have a look at the <a href=\"https://github.com/golang/go/wiki/CodeReviewComments\" rel=\"nofollow noreferrer\">golang code review comments page</a>. There's a lot of stuff in there that makes your code nicer. It's mainly sensible stuff: keep package aliases to a minimum, keep package names short, but communicative. Avoid name stutter, etc...</p>\n\n<p>A particular bug-bear of mine is when people have a package like <code>handler</code>, and have a <code>New</code> function in there like this:</p>\n\n<pre><code>package handler\n\nfunc NewHandler() (*h, error) {\n return &amp;h{}, nil\n}\n</code></pre>\n\n<p>Forcing me to write <code>handler.NewHandler()</code>. There's a reason why people find Java overly verbose (<code>SomeFooBarImpl foobar = new SomeFooBarImpl();</code>). What else do you expect <code>handler.New()</code> to return, other than a new handler?</p>\n\n<p>/rant...</p>\n\n<p>Might revisit this one later on, I'm heading home for the day now :P</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-23T22:54:55.080", "Id": "431481", "Score": "0", "body": "Apologize for taking so long to reply but I wanted to take enough time to review it properly. Thank you for your answer, it was very helpful. I edited my post to add a refactor following your advice." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-16T17:53:24.847", "Id": "220366", "ParentId": "219686", "Score": "2" } } ]
{ "AcceptedAnswerId": "220366", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T08:05:13.803", "Id": "219686", "Score": "2", "Tags": [ "go", "web-services" ], "Title": "Gin framework project with an endpoint to return a list of users based on their score" }
219686
<p>This is a simple CLI Blackjack game in python3. I saw that there were others already posted here and tried to implement some of their solutions and logic where I understood it. My game is a little different in that I have a "probability mode". This shows probabilities of bust or blackjack if the user takes another hit. It also shows probabilities of the dealer's hidden card revealing a blackjack (no need for bust probability for dealer because you can't bust on just 2 cards).</p> <p>There are three classes used as a way to store variables that I want to access throughout the program. This avoids having to pass in arguments all the time. In my opinion this makes for more easily understandable code, but I'm not very experienced so I don't know if this is best practices. Or if I should use more classes... or expand on these and not have so many functions in the global space?</p> <p>I'm also wondering about my use of try-except in the ask_for_bet() function. Is this the correct usage? Should I use it elsewhere?</p> <pre><code>import random import time from decimal import Decimal import sys class Money: def __init__(self, bank, bet): self._bank = bank self._bet = bet # Getter/setter for player bank @property def bank(self): return round(Decimal(self._bank), 2) @bank.setter def bank(self, amount): self._bank = amount # Getter/setter for bet @property def bet(self): return round(Decimal(self._bet), 2) @bet.setter def bet(self, amount): self._bet = amount m = Money(100, 0) class Prob_mode: def __init__(self, value): self._value = value # Getter/setter for probability mode @property def value(self): return self._value @value.setter def value(self, boolean): self._value = boolean p = Prob_mode(False) class Cards: def __init__(self, dealer_total, player_total): self._deck = [] self._player_hand = [] self._dealer_hand = [] self._dealer_total = dealer_total self._player_total = player_total # Getter/setter for dealer_total @property def dealer_total(self): return self._dealer_total @dealer_total.setter def dealer_total(self, amount): self._dealer_total = amount # Getter/setter for player_total @property def player_total(self): return self._player_total @player_total.setter def player_total(self, amount): self._player_total = amount c = Cards(0, 0) #### Card handling functions #### def draw_card(): popped_card = c.deck.pop(random.randint(0, len(c.deck) - 1)) return popped_card def initial_deal(): for _ in range(0, 2): c.player_hand.append(draw_card()) c.dealer_hand.append(draw_card()) hand_value(c.dealer_hand, 'dealer') hand_value(c.player_hand, 'player') def cardify_full_hand(hand): cardified_hand = [] for i in range(0, (len(hand))): card = f"|{hand[i]}|" cardified_hand.append(card) return ' '.join(cardified_hand) def cardify_dealer_initial(): card1 = f"|{c.dealer_hand[0]}|" card2 = "|≈|" cardified_hand = [card1, card2] return ' '.join(cardified_hand) def hand_value(hand, who=None): sum_of_hand = 0 ace_count = hand.count('A') face_count = hand.count('K') + hand.count('Q') + hand.count('J') for card in hand: if (type(card) == int): sum_of_hand += card sum_of_hand += 10 * face_count if (ace_count &gt; 0): if (sum_of_hand &gt;= 11): sum_of_hand += ace_count else: sum_of_hand += (11 + ace_count - 1) if who == "dealer": c.dealer_total = sum_of_hand elif who == "player": c.player_total = sum_of_hand else: return sum_of_hand #### Display functions #### def line(): sleepy_print('-----------------------------------------------') def sleepy_print(string): time.sleep(.5) print(string) time.sleep(.5) def error_msg(): sleepy_print("\n\t!*** Invalid choice, try again ***!\n") def update_total(): sleepy_print(f"\nNow you have ${m.bank}\n") # Bankrupcy test if (m.bank &lt; 5): input("\n\tYou don't have enough money. Hit ENTER to restart game\n") m.bank = 100 menu() else: player_choice = input('ENTER for new game or "M" to go back to menu\n').upper() if (player_choice == ""): start_game() elif (player_choice == 'M'): time.sleep(.5) menu() else: error_msg() update_total() def display_hands_before_flip(): line() dealer_display = f"\nDealer hand = {cardify_dealer_initial()}" player_display = f"\nPlayer hand = {cardify_full_hand(c.player_hand)}" if p.value: dealer_display += f" --------probability--&gt; {blackjack_prob_msg(hand_value([c.dealer_hand[0]]))}" player_display += f" --------probability--&gt; {blackjack_prob_msg(c.player_total)} {bust_prob_msg(c.player_total)}" print(dealer_display + '\n') print(f" * The bet is ${m.bet} *") print(player_display + '\n') line() def display_hands_after_flip(): line() print("\nDealer's draw...") time.sleep(.5) print(f"\nDealer hand = {cardify_full_hand(c.dealer_hand)}") print(f"Total = {c.dealer_total}\n") print(f"Player hand = {cardify_full_hand(c.player_hand)}") print(f"Total = {c.player_total}\n") #### Probability functions #### def deck_list_to_nums(): deck_of_all_nums = [] for card in c.deck: if ((card == 'K') | (card == 'Q') | (card == 'J')): deck_of_all_nums.append(10) elif (card == 'A'): deck_of_all_nums.append(1) else: deck_of_all_nums.append(card) return deck_of_all_nums def bust_prob_msg(hand_total): danger_card_count = 0 if hand_total &gt;= 12: for i in deck_list_to_nums(): if ((hand_total + i) &gt; 21): danger_card_count += 1 percent = Decimal(danger_card_count/len(c.deck)) * 100 return f"Bust = %{round(percent, 2)}" def blackjack_prob_msg(hand_total): a_count = c.deck.count('A') bj_card_count = 0 if (hand_total == 10): bj_card_count = a_count elif (hand_total &gt;= 11): for i in deck_list_to_nums(): if ((hand_total + i) == 21): bj_card_count += 1 percent = Decimal(bj_card_count/len(c.deck)) * 100 return f"Blackjack = %{round(percent, 2)}" #### Outcomes #### def player_win(): if (c.player_total == 21): blackjack() else: if (c.dealer_total &gt; 21): print("\t\t Dealer BUSTED...\n") m.bank += m.bet * 2 sleepy_print(" ++You win!++\n") def blackjack(): time.sleep(.5) print(" $ $ $ $ $ $ $ $") time.sleep(.05) print(" $ $ BLACKJACK $ $") time.sleep(.05) print(" $ $ 1.5x $ $") time.sleep(.05) print(" $ Win! $") time.sleep(.05) print(" $ $ $") time.sleep(.05) print(" $ $") time.sleep(.05) print(" $") m.bank += (m.bet * Decimal(2.5)) def dealer_win(): sleepy_print(" --Dealer won--\n") def tie(both_bust=False): if both_bust: print(("\t You and the dealer both BUSTED...\n")) elif (c.player_total == 21): print(("\t You and the dealer both got Blackjack...\n")) sleepy_print(" ~~It's a tie~~\n") m.bank += m.bet #### Main gameplay and run functions #### def ask_for_bet(): print(f"\nMax bet = ${m.bank}") add_bet = input("Hit ENTER to bet the minimum ($5.00) or input higher amount: $") if (add_bet == ""): m.bank = m.bank - 5 m.bet = 5 return try: add_bet = round(Decimal(add_bet), 2) if (add_bet &gt; m.bank): sleepy_print("\n\t!*** You don't have enough money to afford that bet! Try again ***!") ask_for_bet() elif (add_bet &lt; 5): sleepy_print("\n\t!*** Bet is too low. Must meet the minimum ***!") ask_for_bet() else: m.bet += add_bet m.bank -= add_bet except: error_msg() ask_for_bet() def player_hit_stand(): # If blackjack if (c.player_total == 21): input("You have 21! Hit ENTER to see what the dealer has...") return player_choice = input('Do you want to hit ("H") or stand ("S")?\nEnter response: ').upper() if (player_choice == 'H'): c.player_hand.append(draw_card()) hand_value(c.player_hand, 'player') # If bust if (c.player_total &gt; 21): display_hands_before_flip() input("You BUSTED! Hit ENTER to see what the dealer has...") return # If still in the game (player total &lt; 21 ) else: time.sleep(.5) display_hands_before_flip() player_hit_stand() elif (player_choice == 'S'): return else: error_msg() player_hit_stand() def dealer_hit_stand(): # Dealer hits until 17 or higher is reached while (c.dealer_total &lt; 17): c.dealer_hand.append(draw_card()) hand_value(c.dealer_hand, 'dealer') def who_wins(): difference = c.player_total - c.dealer_total # Bust outcomes if ((c.player_total &gt; 21) | (c.dealer_total &gt; 21)): if ((c.player_total &gt; 21) &amp; (c.dealer_total &gt; 21)): tie(both_bust = True) elif (c.player_total &gt; 21): dealer_win() else: player_win() # All other outcomes elif (difference == 0): tie() elif (difference &gt; 0): player_win() else: dealer_win() def menu(): # Probability toggle if p.value: prob_indicator = 'on' else: prob_indicator = 'off' # Options menu print(f'\n\n\t Input "P" to toggle probability mode (currently: {prob_indicator})') print('\t Input "X" to exit the game') print('\n\t\t--Hit ENTER to deal a new hand--') input_var = input().upper() if input_var == "": start_game() elif input_var == 'P': time.sleep(.5) p.value = not p.value menu() elif input_var == 'X': sleepy_print('\nExiting...\n') sys.exit() else: error_msg() menu() def start_game(): # Empty hands, zero bet, and new deck at the start of each hand c.dealer_hand = [] c.player_hand = [] m.bet = 0 c.deck = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A'] * 4 sleepy_print('\n\n****************** New Hand ******************') # Play action ask_for_bet() initial_deal() display_hands_before_flip() player_hit_stand() dealer_hit_stand() display_hands_after_flip() # Ouctomes who_wins() update_total() menu() <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>The main problem with your code is that your methods are using the global variables <code>c,p,m</code>. </p>\n\n<p>Firstly, these variable names could use a little love, naming them <code>cards, probabilities</code>and <code>money</code> would be useful, but I'd go one step farther and try to find better class names for those three classes. I'd expect a class <code>Cards</code> to represent a pack of cards, not the hands of two different players. The point is : When naming a class, ask yourself what that class represents and name it this way. Otherwise, it makes the code difficult to understand.</p>\n\n<p>Second of all, I think you should either encapsulate this code in a <code>class</code> where <code>c,p,m</code> would be member variables (<code>self.p, self.m, self.c</code>), which would make it clearer the variables have already been declared and are supposed to be used. Otherwise, you have methods that can't be called before the three global variables have been initialized and while this works in your current situation, if you were to move your code a little bit it might break, which is a pretty big code smell.</p>\n\n<p>Apart from those two points, I think your code is great.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T15:43:29.463", "Id": "226186", "ParentId": "219690", "Score": "2" } } ]
{ "AcceptedAnswerId": "226186", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T08:24:11.787", "Id": "219690", "Score": "5", "Tags": [ "python", "python-3.x", "playing-cards" ], "Title": "Blackjack CLI in Python 3" }
219690
<p>I made a small script to get a list of all download links from an FTP based File Hosting URL. I have tested it on a couple of URLs and it works reasonably well. </p> <p>Can you please point out mistakes and bad practices, suggest ways to improve, and if possible further generalize the code?</p> <p>Also, please suggest ways I could use the Python Standard Library instead of Beautiful Soup without sacrificing too much simplicity, if possible.</p> <pre><code>import requests from bs4 import BeautifulSoup, SoupStrainer url = "http://some_ftp_url.net/movies/" download_links = [] video_file_extensions = ('mkv', 'mp4', 'mpeg4', 'mov', 'avi') def recursiveUrl(url, depth): if depth == 5: return url elif url.endswith(video_file_extensions): download_links.append(url) return else: page = requests.get(url) for link in BeautifulSoup(page.text, parse_only=SoupStrainer('a'), features="html.parser"): if (link.has_attr('href') and link.text != '../'): recursiveUrl(url + link['href'], depth + 1) def getLinks(url): page = requests.get(url) for link in BeautifulSoup(page.text, parse_only=SoupStrainer('a'), features="html.parser"): if (link.has_attr('href') and link.text != '../'): recursiveUrl(url + link['href'], 0) return download_links if __name__ == '__main__': getLinks(url) for download_link in download_links: print('\n') print(download_link) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T12:03:23.393", "Id": "424333", "Score": "1", "body": "Is there a specific reason why you want to stop using Beautiful Soup?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T07:01:44.223", "Id": "424538", "Score": "0", "body": "@AlexV Beautiful Soup is very handy. But I also wanted to know if there is another, feasibly straightforward, way of doing it using just the Python Standard Library. I'm not sure whether Beautiful Soup is a part of the Python Standard Library, but I'm guessing not." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T11:57:09.493", "Id": "219697", "Score": "2", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Python Script to get list of all download links from an FTP based File Hosting URL" }
219697
<p>I implemented the Sieve of Erasthotenes recursively using <code>filter</code> and I was wondering how efficient this implementation is and wether a non-recursive implementation or something without <code>filter</code> would be better. If someone wants to get into micro-optimization etc. - that would be fun too I suppose :)</p> <p>This is my code:</p> <pre class="lang-py prettyprint-override"><code>def sieve (iterable, container): if len(iterable) != 1: container.append(iterable [0]) iterable = [item for item in iterable if item % iterable [0] != 0] print("Filter call:", iterable, container, '\n') return sieve(iterable, container) else: container.append(iterable[0]) print("Return container:", container) return container </code></pre> <p>An example I/O (with the print-Statements) would be:</p> <pre class="lang-py prettyprint-override"><code>#Input lst = list(range(2, 20)) primes = [] print(sieve(lst, primes) #Output Filter call: [3, 5, 7, 9, 11, 13, 15, 17, 19] [2] Filter call: [5, 7, 11, 13, 17, 19] [2, 3] Filter call: [7, 11, 13, 17, 19] [2, 3, 5] Filter call: [11, 13, 17, 19] [2, 3, 5, 7] Filter call: [13, 17, 19] [2, 3, 5, 7, 11] Filter call: [17, 19] [2, 3, 5, 7, 11, 13] Filter call: [19] [2, 3, 5, 7, 11, 13, 17] Return container: [2, 3, 5, 7, 11, 13, 17, 19] #Return Out: [2, 3, 5, 7, 11, 13, 17, 19] </code></pre>
[]
[ { "body": "<h1>Algorithm</h1>\n\n<p>This is not quite the Sieve of Eratosthenes. The true sieve touches only the multiples of each prime, so it has complexity <span class=\"math-container\">\\$n \\log \\log n\\$</span>. Filtering copies the whole list repeatedly, which is equivalent to a different algorithm, <em>trial division</em>, with different complexity (probably <span class=\"math-container\">\\$n^2 / (\\log n)^2\\$</span>). That's a dramatic difference, which led Melissa O'Neill to write a <a href=\"https://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf\" rel=\"nofollow noreferrer\">slightly famous academic rant</a> about this.</p>\n\n<p>But that's not a problem for an educational program. The rest of this review is about your implementation.</p>\n\n<p>Recursing on each prime has depth <span class=\"math-container\">\\$\\pi(n) \\approx n / \\log n\\$</span>, which will overflow the stack for any large <span class=\"math-container\">\\$n\\$</span>. Can you do it iteratively instead?</p>\n\n<h1>Names</h1>\n\n<p><code>iterable</code> is a misleading name: the function uses <code>len(iterable)</code>, but iterables don't necessarily support <code>len</code>. So it doesn't work on all iterables.</p>\n\n<p><code>iterable</code> is also an uninformative name: it doesn't say what the argument <em>means</em>. It isn't just any iterable, it's a list of candidate primes, so it could be called <code>candidates</code>.</p>\n\n<p>Similarly, <code>container</code> isn't just any container, it's a list of primes, so it should be called <code>primes</code>. Also, <code>sieve</code> modifies it, which is unusual enough that it requires a comment, and it could even appear in the name: it could be called <code>output_primes</code>.</p>\n\n<h1>Interface</h1>\n\n<p>Modifying an argument is confusing and error-prone. Why not build a list and return it?</p>\n\n<p>Why does the caller need to provide a list of candidates? Wouldn't it be simpler to just pass <code>n</code> and have <code>sieve</code> take care of building the candidates?</p>\n\n<p>If the recursive function needs a different interface from the caller, you can use one function to do the recursion, and wrap it with another that presents a clean interface to the caller.</p>\n\n<h1>Innards</h1>\n\n<p>Repetition: <code>container.append(iterable[0])</code> appears in both branches of the <code>if</code>. It could be moved before the <code>if</code>.</p>\n\n<p>The program checks <code>len(iterable) != 1</code>, so what happens if <code>len(iterable) == 0</code>? Oops: it tries to use <code>iterable[0]</code> and crashes. It's generally safest to check for 0, not 1. This would also get rid of the repetition.</p>\n\n<h1>Optimization</h1>\n\n<p>Improving the algorithm will help a lot more than micro-optimizing. If you switch to the true Sieve of Eratosthenes and it still isn't fast enough, there are algorithmic improvements like the <a href=\"https://en.wikipedia.org/wiki/Sieve_of_Sundaram\" rel=\"nofollow noreferrer\">Sieve of Sundaram</a>.</p>\n\n<p>Before optimizing, measure performance! Optimization is hard and it's easy to get it wrong, so let measurements guide you.</p>\n\n<h1>Other</h1>\n\n<p>This function should have a docstring saying what it does: <code>\"Prime number sieve: Given a list of candidates, append the primes to output_primes.\"</code></p>\n\n<p>Your question says the program uses <code>filter</code>, but it actually uses a list comprehension to do the same thing. This is not a problem with the program, just slightly confusing.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T18:19:53.970", "Id": "219718", "ParentId": "219699", "Score": "2" } } ]
{ "AcceptedAnswerId": "219718", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T12:01:45.133", "Id": "219699", "Score": "3", "Tags": [ "python", "recursion", "sieve-of-eratosthenes" ], "Title": "Efficiency of a recursive implementation of the Sieve of Erasthotenes in Python" }
219699
<p>Here my attempt was to write a graph algorithm the way a competitive programmer would write under time pressure. The problem to solve was to find a <strong><em>shortest path</em></strong> in a directed, unweighted graph using breadth-first search algorithm (BFS, for short).</p> <p>Basically, I would like to hear comments on my style. Is it effective, for example?</p> <pre><code>import java.util.Arrays; class BFS { static int[] bfs(int[][] graph, int sourceNode, int targetNode) { int[] queue = new int[graph.length]; int[] distance = new int[graph.length]; int[] parents = new int[graph.length]; for (int i = 0; i &lt; parents.length; i++) { parents[i] = -1; } int queueStartIndex = 0; int queueEndIndex = 1; queue[0] = sourceNode; distance[sourceNode] = 0; while (queueStartIndex &lt; queueEndIndex) { int currentNode = queue[queueStartIndex++]; if (currentNode == targetNode) { return buildPath(targetNode, distance[targetNode] + 1, parents); } for (int childNode : graph[currentNode]) { if (parents[childNode] == -1) { parents[childNode] = currentNode; distance[childNode] = distance[currentNode] + 1; queue[queueEndIndex++] = childNode; } } } return null; } private static int[] buildPath(int targetNode, int pathLength, int[] parents) { int[] path = new int[pathLength]; int pathIndex = path.length - 1; int currentNode = targetNode; while (currentNode != -1) { path[pathIndex--] = currentNode; currentNode = parents[currentNode]; } return path; } /* B ----+ / | A E \ / C - D */ public static void main(String[] args) { int a = 0; int b = 1; int c = 2; int d = 3; int e = 4; int[][] graph = new int[5][]; graph[a] = new int[]{ c, b }; graph[b] = new int[]{ e }; graph[c] = new int[]{ d }; graph[d] = new int[]{ c, e }; graph[e] = new int[]{ b, d }; // A -&gt; B -&gt; E int[] path = bfs(graph, a, e); System.out.println(Arrays.toString(path)); // A &lt;- B &lt;- E does not exist: System.out.println(Arrays.toString(bfs(graph, e, a))); } } </code></pre> <p>(See the <a href="https://codereview.stackexchange.com/questions/219758/breadth-first-search-in-java-competitive-style-follow-up">next iteration</a>.)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T16:42:22.413", "Id": "424357", "Score": "1", "body": "Surely the definition of the problem should be given. Please exactly state the definition of the problem the code is to solve. Also if it's competitive there would be some criteria that it is scored under." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T16:51:00.730", "Id": "424358", "Score": "0", "body": "Thanks, @simbo1905. Added the description of the problem being solved." } ]
[ { "body": "<ul>\n<li><p><strong>Correctness</strong>.</p>\n\n<p>The parent of the source node is initially <code>-1</code>, and <code>buildPath</code> relies on that. However, if the source node belongs to a cycle, its parent will be eventually reassigned, breaking the contract. Now <code>buildPath</code> will misbehave.</p></li>\n<li><p><strong>Efficiency</strong>.</p>\n\n<p>Since the algorithm assumes an unweighted graph, the <code>distance</code> array seems redundant. In the implementation only one value is used, only to hint <code>buildPath</code> on the size of the <code>path</code> array. Meanwhile, the distances are incremented likely <span class=\"math-container\">\\$O(V)\\$</span> times, and surely more than <code>P = pathLength</code> times. Instead you can let <code>buildPath</code> to compute P, trading <span class=\"math-container\">\\$O(V)\\$</span> increments for <span class=\"math-container\">\\$O(P)\\$</span> path length computation.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T16:53:02.867", "Id": "219710", "ParentId": "219702", "Score": "2" } } ]
{ "AcceptedAnswerId": "219710", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T12:56:23.930", "Id": "219702", "Score": "1", "Tags": [ "java", "algorithm", "breadth-first-search" ], "Title": "Breadth-first search in Java: competitive style" }
219702
<p><a href="https://codereview.stackexchange.com/q/157527/92478">After my last attempt</a>, I started to learn Rust again. This time I wrote a simple HTTP router. I would appreciate it if you could help me to fix my mistakes. </p> <p><a href="https://github.com/smoqadam/rust-router/tree/98a899c7bf59b2a4f644a0b443089662491c7cec" rel="nofollow noreferrer">Here</a> is the link of the repository</p> <p>main.rs</p> <pre><code>fn main() { let mut router = Router::new(); router.get("/home", home); Server::new(router).run("127.0.0.1:8989"); } fn home(req: request::Request) -&gt; Response { let res = format!("Welcome Home: {}", req.get("name")); Response::html(String::from(res), 200) } </code></pre> <p>src/router.rs</p> <pre><code>pub type Handler = fn(Request) -&gt; Response; pub struct Route { pub pattern: String, pub method: String, pub callback: Handler, } pub struct Router { pub routes: Vec&lt;Route&gt;, } impl Router { pub fn new() -&gt; Router { Router { routes: Vec::new(), } } fn route(&amp;mut self, method: &amp;str, pattern: &amp;str, f: Handler) { let r = Route{method: String::from(method), pattern: String::from(pattern), callback: f} ; self.routes.push(r); } pub fn get(&amp;mut self, pattern: &amp;str, f: Handler) { self.route(Method::GET, pattern, f) } pub fn post(&amp;mut self, pattern: &amp;str, f: Handler) { self.route(Method::POST, pattern, f) } } </code></pre> <p>src/request.rs</p> <pre><code>pub mod method{ pub const GET: &amp;str = "GET"; pub const POST: &amp;str = "POST"; } pub struct Request { path: String, method: String, params: HashMap&lt;String, String&gt;, } impl Request { pub fn parse(stream:&amp;mut TcpStream) -&gt; Request { let mut lines = String::new(); let mut reader = BufReader::new(stream); let _ = reader.read_line(&amp;mut lines); let mut line = lines.split_whitespace(); let method = match line.nth(0) { Some(e) =&gt; e, None =&gt; "GET", }; let path = match line.nth(0) { Some(e) =&gt; e, None =&gt; "/", }; let parts = Request::parse_path(path); let req_path = parts[0]; let query_string = match parts.get(1).or(None) { Some(q) =&gt; { let tags: HashMap&lt;String, String&gt; = q.split('&amp;') .map(|kv| kv.split('=').collect::&lt;Vec&lt;&amp;str&gt;&gt;()) .map(|vec| { assert_eq!(vec.len(), 2); (vec[0].to_string(), vec[1].to_string()) }) .collect(); tags }, None =&gt; HashMap::new(), }; Request { method: method.to_string(), path: req_path.to_string(), params: query_string, } } fn parse_path(line: &amp;str) -&gt; Vec&lt;&amp;str&gt; { let parts: Vec&lt;&amp;str&gt; = line.split("?").collect(); parts } pub fn get(&amp;self, key: &amp;str) -&gt; &amp;str { match self.params.get(key) { Some(e) =&gt; e, None =&gt; "", } } pub fn method(&amp;self) -&gt; String { self.method.to_string() } pub fn path(&amp;self) -&gt; String { self.path.to_string() } } </code></pre> <p>src/response.rs</p> <pre><code>pub struct Server { router: Router, } impl Server { pub fn new(router: Router) -&gt; Server { Server{ router: router} } pub fn run(&amp;self, addr: &amp;str) { let listener = TcpListener::bind(addr).unwrap(); println!("Listening to {}", addr); for stream in listener.incoming() { self.handle(&amp;mut stream.unwrap()); } } fn handle(&amp;self, stream: &amp;mut TcpStream) { let req = Request::parse(stream); for r in &amp;self.router.routes { if r.method == req.method() &amp;&amp; r.pattern == req.path() { self.dispatch(stream, r.callback, req); break; } } } fn dispatch(&amp;self, stream:&amp;mut TcpStream, handler: Handler, req: Request) { let response = (handler)(req); response.result(stream); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T15:15:51.050", "Id": "424349", "Score": "0", "body": "By mistakes, do you mean the code isn’t working and you want us to fix it or you want advice on how to make it better? If it’s the latter you should change your wording to reflect such." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T16:06:45.727", "Id": "424355", "Score": "0", "body": "@DavidWhite: It's working fine. I posted here because I want to make it better. The Codereview exists for this purpose, right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T20:04:13.910", "Id": "424379", "Score": "0", "body": "Correct, but some could view “mistakes” as code that doesn’t work. Wording means a lot when asking a good question" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T13:01:13.453", "Id": "219703", "Score": "4", "Tags": [ "beginner", "http", "rust", "server", "url-routing" ], "Title": "Simple routing in Rust" }
219703
<p>This is my first shot at writing a makefile for a document generation system. Please identify any more ways to refine it. Some pointers on how it works:</p> <ul> <li>The INPUT files initially are templates to be edited and are copied to the "src" directory upon first execution only.</li> <li>The code at the beginning tests for an environment variable equal to the directory path containing the input templates.</li> <li>The desired files will be in the "output" directory</li> <li>The file formats used include mustache templates for asciidoctor (.mst.adoc), asciidoctor (.adoc), HTML, and PDF. One adoc file uses asciidoctor-reveal.js, an HTML slide generator.</li> </ul> <pre><code># Check that given variables are set and all have non-empty values, # die with an error otherwise. # # Params: # 1. Variable name(s) to test. # 2. (optional) Error message to print. check_defined = \ $(strip $(foreach 1,$1, \ $(call __check_defined,$1,$(strip $(value 2))))) __check_defined = \ $(if $(value $1),, \ $(error Undefined $1$(if $2, ($2)))) #TEST ENVIRONMENT VARIABLES $(call check_defined, TEACH_PROJ) #DIRECTORIES: PRJ=$(TEACH_PROJ) OUT=../output/ BLD=../build/ ADC=asciidoctor MST=mustache #OUTPUT HTM_NOT=$(OUT)notes.html HTM_PRS=$(OUT)presentation.html HTM_VOC=$(OUT)vocabulary.html PDF_PRS=$(OUT)presentation.pdf #INTERMEDIATE ADC_PRS=$(BLD)presentation.adoc ADC_VOC=$(BLD)vocabulary.adoc #INPUT YML_VOC=vocabulary.yml FIL_GEM=Gemfile MST_PRS=presentation.mst.adoc MST_VOC=vocabulary.mst.adoc #RECIPES RCP_COPY=cp -an $(PRJ)$@ RCP_MKD=mkdir -p $@ RCP_ADC=$(ADC) $&lt; -o $@ RCP_RJS=bundle exec $(ADC)-revealjs -o $@ $&lt; RCP_PDF=$(RCP_ADC) -r $(ADC)-pdf -b pdf -a pdf-stylesdir=$(PRJ) -a pdf-style=compact RCP_MST=$(MST) $(YML_VOC) $&lt; &gt; $@ all: $(HTM_PRS) $(HTM_NOT) $(PDF_PRS) $(HTM_VOC) $(HTM_PRS): $(ADC_PRS) $(FIL_GEM)|$(OUT); $(RCP_RJS) $(PDF_PRS): $(ADC_PRS)|$(OUT); $(RCP_PDF) TARGETS=$(HTM_NOT) $(HTM_VOC) $(HTM_NOT): $(ADC_PRS)|$(OUT) $(HTM_VOC): $(ADC_VOC)|$(OUT) $(TARGETS): ;$(RCP_ADC) #build: TARGETS=$(ADC_PRS) $(ADC_VOC) $(ADC_PRS): $(MST_PRS) $(YML_VOC)|$(BLD) $(ADC_VOC): $(MST_VOC) $(YML_VOC)|$(BLD) $(TARGETS): ;$(RCP_MST) #input $(YML_VOC) $(MST_VOC) $(MST_PRS) $(FIL_GEM): ; $(RCP_COPY) . $(OUT) $(BLD): ; $(RCP_MKD) clean: ; rm -rf $(BLD) $(OUT) <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T16:31:48.463", "Id": "424356", "Score": "0", "body": "Please note that [YML](https://fdik.org/yml/) and [YAML](https://yaml.org/spec/1.2/spec.html) have been around for about the same time, but are not the same. And the [recommended file extension for **YAML** documents has been `.yaml`](https://yaml.org/faq.html) since 2006. It is unclear if you intended to use `YAML_VOC=vocabulary.yaml` or that you really use YML and is that tag [tag:yaml] incorrect." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T02:10:32.323", "Id": "424391", "Score": "0", "body": "Thanks @Anthon that's good to know and I made the change." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T15:22:45.190", "Id": "219706", "Score": "2", "Tags": [ "makefile", "yaml", "make", "mustache" ], "Title": "Makefile for a document generation system" }
219706
<p>I felt that having a plain red favicon for every youtube tab is a little boring. So, I wrote a TamperMonkey Script with the new ES6 promises that replaces the favicon with the channel's logo. Link to the script <a href="https://openuserjs.org/scripts/KartikSoneji/YouTube_Favicon_to_Channel_logo" rel="nofollow noreferrer">here</a>.</p> <p>The script works by first extracting the channel logo's URL from the window.ytInitialData object. Then, a mutation listener is attached to the title, and whenever the title of the page changes, the script makes a GET request using the window.location.href and then extracts the logo's URL from the responseText.</p> <p>Since this is my first time writing a userscript, I wanted to confirm that I am following best practices and not breaking anything on the site. Also, is there a better way of achieving the same result?</p> <p>Thank you for your time.</p> <p>My code:</p> <pre><code>// ==UserScript== // @name YouTube Favicon to Channel logo // @version 1.1 // @description Changes the YouTube Favicon to the Channel logo // @author Kartik Soneji // @updateURL https://openuserjs.org/meta/KartikSoneji/YouTube_Favicon_to_Channel_logo.meta.js // @match https://www.youtube.com/* // @exclude https://www.youtube.com/ // @exclude https://www.youtube.com/tv* // @exclude https://www.youtube.com/embed/* // @exclude https://www.youtube.com/live_chat* // @grant none // @run-at document-end // @license MIT // ==/UserScript== (function(){ 'use strict'; const urlRegex = /https:\/\/yt3.ggpht.com\/a[/-]{1,2}[A-Za-z\d-_]+/; function isInIframe(){ try{ return window.self !== window.top; } catch(e){ return true; } } if(isInIframe()) return; console.log("Started"); roundImageToDataUrl(JSON.stringify(window.ytInitialData).match(urlRegex)[0]).then(setFavicon); function run(){ getChannelLogo(window.location.href).then(roundImageToDataUrl).then(setFavicon); } async function getChannelLogo(url){ return new Promise((resolve, reject) =&gt; { let xhr = new XMLHttpRequest(); xhr.open("GET", url); xhr.onload = () =&gt;{ let u = xhr.responseText.match(urlRegex)[0]; console.log(u); resolve(u); } xhr.send(); }); } let observer = new MutationObserver(run); function registerUrlChangeListener(){ let e = document.querySelector("title"); if(e){ //observer.observe(e, {attributes: true}); observer.observe(document.querySelector("title"), {attributes: true, characterData: true, childList: true}); return; } setTimeout(registerUrlChangeListener, 250); } registerUrlChangeListener(); async function roundImageToDataUrl(url){ return new Promise((resolve, reject) =&gt; { if(url.src) url = url.src; let img = document.createElement("img"); img.crossOrigin = "anonymous"; img.src = url; img.style = "position: absolute; top: -100000px; left: -100000px;"; img.onload = function(){ let canvas = document.createElement("canvas"), g = canvas.getContext("2d"); canvas.height = img.naturalHeight; canvas.width = img.naturalWidth; g.beginPath(); g.arc(canvas.width/2, canvas.height/2, canvas.width/2, 0, Math.PI * 2); g.clip(); g.drawImage(img, 0, 0); img.parentElement.removeChild(img); resolve(canvas.toDataURL()); } document.body.appendChild(img); }); } function setFavicon(url){ let a = document.querySelectorAll("link[rel *= 'icon']"); if(a.length == 0){ let link = document.createElement('link'); link.type = 'image/x-icon'; link.rel = 'icon'; document.head.appendChild(link); a = [link]; } for(let i of a) i.href = url; } })(); </code></pre>
[]
[ { "body": "<blockquote>\n<pre><code>img.style = \"position: absolute; top: -100000px; left: -100000px;\";\ndocument.body.appendChild(img);\n\nimg.parentElement.removeChild(img);\n</code></pre>\n</blockquote>\n\n<p>This seems weird. The canvas can be drawn from an unattached image and these lines can be removed.</p>\n\n<blockquote>\n<pre><code> if(url.src) url = url.src;\n\n img.src = url;\n</code></pre>\n</blockquote>\n\n<p>A more idiomatic phrasing is <code>img.src = url.src || url</code>.</p>\n\n<blockquote>\n<pre><code> .querySelectorAll(\"link[rel *= 'icon']\");\n</code></pre>\n</blockquote>\n\n<p>Unless you have something specific in mind, I'd use <code>[rel='icon']</code> here. It's faster, and not clear that matching an exotic future variant like <code>&lt;link rel=\"BiscottiConfig\"&gt;</code> is going to be desirable.</p>\n\n<blockquote>\n<pre><code>let\n</code></pre>\n</blockquote>\n\n<p>Except for the final loop, every use of <code>let</code> in your script can be replaced by <code>const</code>. It's a good habit, even if the aesthetics are inferior to <code>let</code> or <code>var</code>.</p>\n\n<blockquote>\n<pre><code>const urlRegex = /https:\\/\\/yt3.ggpht.com\\/a[/-]{1,2}[A-Za-z\\d-_]+/;\n\nroundImageToDataUrl(JSON.stringify(window.ytInitialData).match(urlRegex)[0]).then(setFavicon);\n</code></pre>\n</blockquote>\n\n<p>This looks like a misstep. Youtube avatars have <code>id=img</code>; why not just <code>roundImageToDataUrl( document.getElementById(\"img\").src )</code>? </p>\n\n<p>Dealing with future changes to the host page is a constant challenge with userscripts. There are many things that have to remain unchanged for this to work (the image host, the URL format, the name, content and encoding of <code>ytInitialData</code>) and I'll predict that some of them won't. Selecting the avatar itself with semantic markup is likely to be less brittle, and easier to fix if the markup changes (assuming there will always be an avatar and it will always have some semantics attached to it).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T08:53:48.797", "Id": "424551", "Score": "0", "body": "Thank you for your answer.\nI have removed the `document.body.appendChild(img);` I was not aware that off screen images could be drawn onto a canvas.\n\nI really do not like statements like `img.src = url.src || url` for some reason. They look like javascript \"hacks\".\n\nI am using `.querySelectorAll(\"link[rel *= 'icon']\");` because I need to match both: `<link rel=\"icon\">` and `<link rel=\"shortcut icon\">`. I do not know of a better way to do this.\n\nI do not like to use `const` everywhere, especially while developing the script. You have to make a new variable every time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T09:11:22.000", "Id": "424553", "Score": "0", "body": "About the Youtube avatars. The page does not load the image src till the page is focused. This means that pages in the background will not have a src value. Also, if a video plays with autoplay, then it's img is not loaded until the tab is focused again. This was the first approach that I tried, and almost gave up before realizing that the logo url was in the html of the page. Also, you can copy and paste the entire script into developer tools in a youtube page if you want to try it out. Also, please let me know if you have any suggestions." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T08:32:20.373", "Id": "219794", "ParentId": "219711", "Score": "2" } } ]
{ "AcceptedAnswerId": "219794", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T17:13:42.380", "Id": "219711", "Score": "3", "Tags": [ "javascript", "ecmascript-6", "promise", "youtube" ], "Title": "TamperMonkey Script to replace the YouTube favicon with the channel logo" }
219711
<p>I want to write a function that merges two sorted lists in Python 3.</p> <p>For example:</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt; merge_lists([2, 5, 9], [1, 6, 8, 10]) [1, 2, 5, 6, 8, 9, 10] </code></pre> <p>My implementation is as follows:</p> <pre class="lang-py prettyprint-override"><code>def merge_lists(L1, L2): Outlist = [] while (L1 and L2): if (L1[0] &lt;= L2[0]): item = L1.pop(0) Outlist.append(item) else: item = L2.pop(0) Outlist.append(item) Outlist.extend(L1 if L1 else L2) return Outlist </code></pre> <p>Can I make it better or more readable?</p>
[]
[ { "body": "<ol>\n<li>Python's style guide says to use <code>lower_snake_case</code> for variable names.</li>\n<li>You can use a turnery to assign the desired list to a variable to remove the duplicate code.</li>\n<li><code>L1.pop(0)</code> runs in <span class=\"math-container\">\\$O(n)\\$</span> time, making your code <span class=\"math-container\">\\$O(n^2)\\$</span>. You can fix this by using <code>collections.deque</code>.</li>\n</ol>\n\n<pre><code>import collections\n\n\ndef merge_lists(list_1, list_2):\n list_1 = collections.deque(list_1)\n list_2 = collections.deque(list_2)\n\n outlist = []\n while (list_1 and list_2):\n list_ = list_1 if list_1[0] &lt;= list_2[0] else list_2\n item = list_.popleft()\n outlist.append(item)\n outlist.extend(list_1 if list_1 else list_2)\n return outlist\n</code></pre>\n\n<hr>\n\n<p>As highlighted in <a href=\"https://codereview.stackexchange.com/a/187368\">one of my previous questions</a>, you can replace this with <a href=\"https://docs.python.org/3/library/heapq.html#heapq.merge\" rel=\"nofollow noreferrer\"><code>heapq.merge</code></a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T04:08:35.583", "Id": "424395", "Score": "0", "body": "Did you mean _ternary_ instead of _turnery_?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T04:24:50.490", "Id": "424396", "Score": "0", "body": "The whole point of hand-writing this algorithm was to be fast. Otherwise a simple `out = []; out.extend(a); out.extend(b); sort(out); return out` would have been enough. Converting the lists into deques copies all elements, doesn't it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T07:10:34.927", "Id": "424403", "Score": "0", "body": "The funny thing is that that method will actually be almost as fast as a proper merge. Since python uses TimSort, it will take full advantage of the order already in the data. My guess is that sorting will be the 2nd fastest solution (2nd only to heapq.merge`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T10:08:37.470", "Id": "424425", "Score": "0", "body": "@RolandIllig reread point 2. Each loop you're copying each and every value in the loop anyway. You didn't tag this performance, but sorted and heapq are likely to be tons faster than anything you write." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T17:58:21.023", "Id": "219716", "ParentId": "219712", "Score": "4" } }, { "body": "<p>Since lists are passed by reference, the two lists that are passed as arguments will be half-empty after the function returns.</p>\n\n<pre><code>a = [1, 2, 4]\nb = [3, 5]\n\nmerge_lists(a, b)\n\nprint(a) # is empty now but shouldn't\nprint(b) # only contains 5 now\n</code></pre>\n\n<p>Therefore you should not use <code>list.pop</code> at all but instead iterate over the lists via indexes, since these don't modify the lists.</p>\n\n<p>Instead of the if-then-else expression at the end, you can just write:</p>\n\n<pre><code>Outlist.extend(L1)\nOutlist.extend(L2)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T04:16:47.933", "Id": "219732", "ParentId": "219712", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T17:17:17.443", "Id": "219712", "Score": "4", "Tags": [ "python", "python-3.x", "sorting", "mergesort" ], "Title": "Merge sorted lists" }
219712
<p>I am trying to write simple graph lib in C++, BFS, DFS etc.. I want to create class <code>GraphI</code> which will represent any graph and will include necessary methods so my library could work. Could I add/remove/improve something from my code? </p> <pre><code>#pragma once #include &lt;algorithm&gt; #include "colors.h" struct Vertex; template &lt; typename T &gt; class GraphI { public: struct Vertex { Vertex( const T&amp; k, color col = color::w, int c = -1 ) : key( k ) , color(col) , cost( c ) {} int getCost() const { return cost; } const T&amp; getKey() const { return key; } T&amp; getKey() { return key; } void setColor( color c ) { color = c; } color getColor() { return color; } int cost; color color; T key; bool operator&lt;( const Vertex&amp; v1 ) const { return key &lt; v1.key; } }; using Graph = std::map&lt;Vertex, std::list&lt;Vertex&gt; &gt;; GraphI() = default; virtual ~GraphI() = default; virtual void add_vertex( const T&amp; vertex ) { // if exists then add else do nothing _graph[ vertex ] = {}; ++_size; } virtual void add_edge( const T&amp; from, const T&amp; to, int cost = -1 ) { // if vertices do NOT exist return auto it = _graph.find( from ); if ( it == _graph.end() ) return; auto it2 = _graph.find( to ); if ( it2 == _graph.end() ) return; auto&amp; neighbours = it-&gt;second; auto it_exists = std::find_if( neighbours.begin(), neighbours.end(), [&amp;to]( const Vertex&amp; vertex ) { return vertex.getKey() == to; } ); // if edge already exists if ( it_exists != neighbours.end() ) return; neighbours.emplace_back( Vertex(to, color::w, cost) ); } virtual void remove_vertex( const T&amp; vertex ) { _graph.erase( vertex ); --_size; // remove all edges going TO vertex for ( auto&amp; v : _graph ) { auto it = std::find_if( v.second.begin(), v.second.end(), [&amp;vertex]( const auto&amp; v ) { return vertex == v.getKey(); } ); // if vertex does NOT exist if ( it == v.second.end() ) return; v.second.erase( it ); } } virtual void remove_edge( const T&amp; from, const T&amp; to ) { auto it = _graph.find( from ); if ( it == _graph.end() ) return; auto &amp;edges = it-&gt;second; auto it2 = std::find_if( edges.begin(), edges.end(), [&amp;]( const auto&amp; vertex ) { return vertex.key == to; } ); if ( it2 == edges.end() ) return; edges.erase( it2 ); } const Graph&amp; graph() const { return _graph; } unsigned size() const { return _size; } private: Graph _graph; unsigned _size; }; </code></pre>
[]
[ { "body": "<p>The comment in <code>add_vertex</code> is confusing and at contradicts what the code does. If <code>vertex</code> already exists in <code>_graph</code>, the existing vertex will be replaced with an empty one, then the size increased (causing the internal <code>_size</code> to be incorrect). Depending on what behavior you want when adding a vertex that already exists, you can use <code>_graph.try_emplace</code>, <code>_graph.insert_or_assign</code>, or just <code>_graph[vertex]</code> (to add a new entry if it does not exist, and do nothing if it does).</p>\n\n<p>There is no benefit to maintaining a distinct <code>_size</code> variable. As shown above, it can get out of sync with the actual size. It is better to just call <code>_graph.size()</code> whenever the user calls <code>Graph::size</code>.</p>\n\n<p>In <code>remove_vertex</code>, you should check the return value from <code>_graph.erase</code> to see if something was actually removed. If nothing was removed there's no benefit to running any of the other code in the function. Also, the <code>if (it == v.second.end())</code> check should <em>not</em> return, as you avoid scanning the rest of the vertexes in <code>_graph</code> to remove edges that connect to the vertex that was just removed. Alternatively, you can just replace that whole loop body with a call to either <code>v.second.remove</code> or <code>v.second.remove_if</code>. (The same change can be made in <code>remove_edge</code>.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T18:16:19.643", "Id": "424369", "Score": "0", "body": "Thanks for quick answer. - `_graph[ vertex ] = {};` seemed really weird to me but I tried it and it worked as if nothing happened but I there was some mistake in that code and it really (as I expected originally) replaces vector with the empty one.\n\nIs there any way how to move line `using Graph = std::map<Vertex, std::list<Vertex> >;` to the top ? Because if I move it there now, then the compiler shouts that `Vertex` is incomplete. Thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T18:26:46.613", "Id": "424371", "Score": "1", "body": "Types stored in containers need to be completely defined before you can use them in the container, so you can't declare `Graph` before `Vertex` is defined." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T17:53:04.187", "Id": "219714", "ParentId": "219713", "Score": "3" } }, { "body": "<p>As a general comment, high performance code will not use <code>std::map</code> (or the like) - this has been quite well explained by e.g., Chandler Carruth in several talks. Here's his <a href=\"https://www.youtube.com/watch?v=fHNmRkzxHWs\" rel=\"nofollow noreferrer\">talk from CppCon 2014</a> on the topic.</p>\n\n<p>A typical high performance implementation in the field of (parallel) graph algorithms for an edge list uses two arrays (i.e., continuous chunks of memory). The first one stores all the edges and the second specifies where adjacency (sub)lists for the vertices start. For example, if your graph is the 3-vertex triangle, the first array, call it A, would be <code>0 1 0 2 1 2</code> representing the three edges (0,1), (0,2), and (1,2). The second array would be <code>0 2 4</code> meaning the adjacency list for vertex 0 starts at A[0], the adjacency list for vertex 1 is at A[2], and so on.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-01-26T11:10:02.040", "Id": "462702", "Score": "0", "body": "The edge list could perhaps use an `struct Edge` with two variables of the appropriate type, maybe `int`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T11:33:13.023", "Id": "219748", "ParentId": "219713", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T17:18:01.517", "Id": "219713", "Score": "2", "Tags": [ "c++", "c++11", "graph" ], "Title": "Graph library - graph interface" }
219713
<p>This is a Computer science glossary that I made with Tkinter. The user inputs the word that they want and then the code searches the text file for it and then ouputs it to the user.</p> <pre><code>#My Computer Scienece Glossary project from tkinter import * #key down function def click(): global definition entered_text=textentry.get() #this will collect the text from the text entry box output.delete(0.0, END) try: definition = my_compdictonary[entered_text] except: definition = "Sorry defintion not found" output.insert(END, definition) ### main: window = Tk() window.title("Computer Science Glossary") window.configure(background="black") ### My Photo photo1 = PhotoImage(file="me.gif") Label(window,image=photo1, bg="black") .grid(row=0, column=0, sticky=W) #create label Label(window, text="Enter the word you want the definition for:",bg="black", fg="white", font="none 12 bold").grid(row=1, column=0, sticky=N) #create a text entry box textentry = Entry(window, width=20, bg="white") textentry.grid(row=2, column=0, sticky=N) #add a submit button Button(window, text="SUBMIT", width=6, command=click).grid(row=3, column=0, sticky=N) #create another label Label(window, text="\nDefinition:", bg="black", fg="white", font="none 12 bold").grid(row=4, column=0, sticky=N) #create a textbox output = Text(window, width=60, height=4, wrap=WORD, background="white") output.grid(row=5, column=0, columnspan=1, sticky=N) #the dictionary my_compdictonary = {} with open("glossary.txt", "r+") as file: for line in file: word, defintions = line.strip().split(" : ") my_compdictonary[word] = defintions window.mainloop() </code></pre> <p>I want suggestions on how I can make this computer science glossary better.</p> <p>All suggestions will be greatly appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T06:21:54.463", "Id": "424402", "Score": "0", "body": "(`ouput`, `Scienece` and `defintion` don't show up in any of my glossaries.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T13:02:01.127", "Id": "424453", "Score": "0", "body": "@greybeard what do you mean?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T13:49:28.680", "Id": "424455", "Score": "1", "body": "Conventional spelling: output, science, definition." } ]
[ { "body": "<h2>PEP-8</h2>\n\n<p>As always, follow the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a> coding standards.</p>\n\n<ul>\n<li>Don't exceed 79 characters per line</li>\n<li>You a space around the <code>=</code> assignment operator (you mostly do this, but violate it in <code>entered_text=textentry.get()</code></li>\n</ul>\n\n<h2>Use a main function</h2>\n\n<p>Avoid writing code in the main scope. Move the code into a <code>main</code> function, and call it ... but only if the script is not imported into another file:</p>\n\n<pre><code>def main():\n window = Tk()\n # ...\n window.mainloop()\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<h2>Catch only the exceptions you expect</h2>\n\n<p>The following code:</p>\n\n<pre><code>try:\n definition = my_compdictonary[entered_text]\nexcept:\n definition = \"Sorry definition not found\"\n</code></pre>\n\n<p>will catch any and every exception, and ignore them all, regardless of the correct type. Why is it bad? Imagine you correct the spelling error in your main program, and change <code>my_compdictonary</code> to <code>my_compdictionary</code>, but you don't correct it in this section of code. You test the program, and it doesn't crash, but every definition you look up returns <code>\"Sorry definition not found\"</code>. Where is the bug? How hard is it to debug?</p>\n\n<p>If instead the code was written as:</p>\n\n<pre><code>try:\n definition = my_compdictonary[entered_text]\nexcept KeyError:\n definition = \"Sorry definition not found\"\n</code></pre>\n\n<p>the program would crash with a <code>NameError</code>, with the traceback showing you the exact line in question. Now how hard is it to debug?</p>\n\n<p>In this particular case, the <code>try...except</code> structure is really overkill. You can provide a default argument when getting a key from the dictionary to handle the key not found case. That reduces the above four lines to only one:</p>\n\n<pre><code>definition = my_compdictonary.get(entered_text, \"Sorry definition not found\")\n</code></pre>\n\n<h2>Keep related code together</h2>\n\n<p>You have:</p>\n\n<pre><code>output.delete(0.0, END)\n# Four\n# unrelated\n# lines of\n# code\noutput.insert(END, definition)\n</code></pre>\n\n<p>It would be clearer to keep <code>output.delete()</code> and <code>output.insert()</code> as back to back lines. Eg)</p>\n\n<pre><code>definition = my_compdictonary.get(entered_text, \"Sorry definition not found\")\noutput.delete(0.0, END)\noutput.insert(END, definition)\n</code></pre>\n\n<h2>Avoid <code>global</code></h2>\n\n<p>Avoid using <code>global</code> as much as possible. It is a sign of poorly organized code, and makes it harder to reason about the correctness of the code, and harder to test the code because side-effects increase in scope.</p>\n\n<p>In this case, it is simple to avoid the <code>global definition</code> because <code>definition</code> is never used anywhere except in the <code>click()</code> function. It should not be a global variable; it is local!</p>\n\n<h2>Never ask for more than you need</h2>\n\n<pre><code>with open(\"glossary.txt\", \"r+\") as file:\n</code></pre>\n\n<p>Why are you opening the file for reading plus? Will you ever be writing to it? Can the program now accidentally write to the file because it has write privileges, corrupting the file? You are only reading the file; just open it for reading.</p>\n\n<pre><code>with open(\"glossary.txt\") as file:\n</code></pre>\n\n<h2>Be liberal in what you accept</h2>\n\n<p>The <a href=\"https://en.wikipedia.org/wiki/Robustness_principle\" rel=\"nofollow noreferrer\">Robustness Principle</a> warns us about the input we get from the outside. Be fault tolerant. Or perhaps better, make it so faults can't happen.</p>\n\n<pre><code> word, defintions = line.strip().split(\" : \")\n</code></pre>\n\n<p>What happens when a definition contains a colon?</p>\n\n<pre><code>noun : A person, place, or thing. Can be classified into two groups : common or proper. \n</code></pre>\n\n<p><code>split(\" : \")</code> now returns 3 items, and you've only got variables for two. So you'll get <code>ValueError: too many values to unpack (expected 2)</code>. How can you avoid this? How about telling <code>split()</code> that you only expect to find one delimiter:</p>\n\n<pre><code> word, defintions = line.strip().split(\" : \", 1)\n</code></pre>\n\n<p>Now, <code>word</code> is <code>\"noun\"</code> and <code>defintions</code> is <code>\"A person, place, or thing. Can be classified into two groups : common or proper.\"</code></p>\n\n<p>What about blank lines? They will still crash the program. You might want to test for those as well. What about non-blank lines that don't have a definition? Those, well maybe it would be ok if those result in an exception; that would be really bad input in the \"glossary.txt\".</p>\n\n<hr>\n\n<p>Make it easier for reviewers to run your code. You have an image <code>'me.gif'</code> in your code that we don't have. Running without it crashes the program due to file not found. How big was that image? 32x32? 300x300? It would affect the size of the resulting window. Do we just delete the lines of code so we can test the program?</p>\n\n<p>How about <code>'glossary.txt'</code>? Do we have to guess what the file format is? Perhaps you could have given a sample file with 3 or 4 entries.</p>\n\n<hr>\n\n<h2>Future Improvements</h2>\n\n<p>You might want to allow the user to look up a definition by just pressing \"Enter\" after typing in the word. The way it works right now, the user has to move their hands from the keyboard to the mouse.</p>\n\n<p>What if the user enters with CAPS LOCK on? What if the definition is provided with a capital letter? Is the definition really not found? Could you be a little more liberal in what you accept?</p>\n\n<hr>\n\n<p>Here is a simple refactoring of your original code with some of the suggestions from comments above. No global variables. The <code>click()</code> function is moved into <code>main()</code>, so it has access to the local variables <code>textentry</code>, <code>my_compdictonary</code> and <code>output</code>. The image was deleted, so I could quickly run the program. The dictionary is generated using list comprehension, and will ignore blank lines.</p>\n\n<p>This is by no means the \"best\" code. Many improvements can still be made in naming (can we have something better than <code>click</code>?), spelling of variables, and so on. Perhaps a <code>class</code> may be in order. </p>\n\n<pre><code>from tkinter import *\n\n\"\"\"\nA Computer science glossary made with Tkinter\n\nRequires a \"glossary.txt\" file with definitions, one per line, with a\nspace-colon-space separating the term from the definition. Eg)\n\n word : a fragment of language\n term : a word or phrase used to describe a thing or to express a concept \n\nAlso should require a \"me.gif\" image of approximately 64 x 64 pixels, but\nthat was removed temporarily.\n\"\"\"\n\ndef main():\n \"\"\"Main function.\n\n This function creates the UI, and enters the tkinter mainloop.\n It does not return until the user closes the UI.\"\"\"\n\n def click():\n entered_text = textentry.get()\n definition = my_compdictonary.get(entered_text,\n \"Sorry defintion not found\")\n output.delete(0.0, END)\n output.insert(END, definition)\n\n window = Tk()\n window.title(\"Computer Science Glossary\")\n window.configure(background=\"black\")\n\n Label(window, text=\"Enter the word you want the definition for:\",\n bg=\"black\", fg=\"white\", font=\"none 12 bold\"\n ).grid(row=1, column=0, sticky=N)\n\n textentry = Entry(window, width=20, bg=\"white\")\n textentry.grid(row=2, column=0, sticky=N)\n\n Button(window, text=\"SUBMIT\", width=6, command=click).grid(row=3, column=0, sticky=N)\n\n Label(window, text=\"\\nDefinition:\", bg=\"black\", fg=\"white\",\n font=\"none 12 bold\"\n ).grid(row=4, column=0, sticky=N)\n\n output = Text(window, width=60, height=4, wrap=WORD, background=\"white\")\n output.grid(row=5, column=0, columnspan=1, sticky=N)\n\n with open(\"glossary.txt\", \"r\") as file:\n my_compdictonary = dict( (line.split(\" : \", 1)) for line in file if line )\n\n window.mainloop()\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T05:36:33.610", "Id": "219846", "ParentId": "219715", "Score": "3" } } ]
{ "AcceptedAnswerId": "219846", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T17:57:07.157", "Id": "219715", "Score": "3", "Tags": [ "python", "python-3.x", "tkinter" ], "Title": "Computer Science glossary made with Tkinter" }
219715
<p>I am working on a Chess AI using chess.js, and currently, it can run 3 layers in under 10 seconds, but 4 or more takes minutes. How can I optimize my current code to be able to run 4 or 5 layers, or do I have to implement a different algorithm.</p> <p>Here is my code:</p> <pre><code>function startMinimax(depth, game, isMaximisingPlayer) { var moves = game.moves({ verbose: true }); var bestEval = -9999; var bestMove; for (var i = 0; i &lt; moves.length; i++) { var move = moves[i]; game.move(move); var value = minimax(depth - 1, game, -10000, 10000, !isMaximisingPlayer); game.undo(); if (value &gt;= bestEval) { bestEval = value; bestMove = move; } } return bestMove; } function minimax(depth, game, alpha, beta, isMaximisingPlayer) { if (depth === 0) { return -evaluateBoard(game); } var moves = game.moves({ verbose: true }); if (isMaximisingPlayer) { var bestEval = -9999; for (var i = 0; i &lt; moves.length; i++) { game.move(moves[i]); bestEval = Math.max(bestEval, minimax(depth - 1, game, alpha, beta, !isMaximisingPlayer)); game.undo(); alpha = Math.max(alpha, bestEval); if (beta &lt;= alpha) { return bestEval; } } return bestEval; } else { var bestEval = 9999; for (var i = 0; i &lt; moves.length; i++) { game.move(moves[i]); bestEval = Math.min(bestEval, minimax(depth - 1, game, alpha, beta, !isMaximisingPlayer)); game.undo(); beta = Math.min(beta, bestEval); if (beta &lt;= alpha) { return bestEval; } } return bestEval; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T19:01:26.887", "Id": "424373", "Score": "2", "body": "You should at least weed off the transpositions. Too many move sequences lead to the same position, and you keep inspecting it over and over again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T19:04:31.230", "Id": "424374", "Score": "1", "body": "I tried adding a transposition table, checking if the fen of any move was equal to one in the past, but it picked poor moves with it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T19:06:27.310", "Id": "424375", "Score": "0", "body": "Then I am afraid something else was wrong. And BTW fen is not the best hash." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T19:31:32.523", "Id": "424377", "Score": "0", "body": "I'll try to implement it again. What would you recommend as a hash? Also, does anything else need to be stored beside the hash?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T19:33:47.487", "Id": "424378", "Score": "0", "body": "It is a huge topic. Start [here](https://www.chessprogramming.org/Bitboards)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T18:18:02.150", "Id": "219717", "Score": "4", "Tags": [ "javascript", "performance", "algorithm", "ai", "chess" ], "Title": "Chess AI Using Minimax and Alpha-Beta Pruning" }
219717
<p>Yesterday I had help via Stack Overflow on a program I written some code for, and needed to know if it needed to be improved.</p> <p>After reviewing the responses, I restructured the code into the following...</p> <pre><code>using System; namespace Language { public static class Grammar { /// &lt;summary&gt; /// Returns a string value with non alpha/numeric characters removed. /// &lt;/summary&gt; /// &lt;param name="Sentence"&gt;&lt;/param&gt; public static string RemoveNonAlphaNumeric(string Sentence) { string[] Removed = { " ", ".", "!", "?", "@", "%", "&amp;", "^", "$", "#", "*", "~" }; string[] words = Sentence.Split(Removed, StringSplitOptions.RemoveEmptyEntries); return string.Join(" ", words); } /// &lt;summary&gt; /// Returns the integer value of the number of words in a sentence. /// &lt;/summary&gt; /// &lt;param name="Sentence"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public static int GetWordCount(string Sentence) { string[] Removed = { " " }; string[] Words = Sentence.Split(Removed, StringSplitOptions.RemoveEmptyEntries); return Words.Length; } } } </code></pre> <p>Initally GetWordCount() contained a foreach() loop which was basically counting the number of words in the array. I took the suggestion of someone removed this. Then replaced the return CountWords which was initially a variable declared at 0, with return words.Length. I also took out Stream as a string parameter as someone suggested that it may cause confusion.</p> <p>Here's how the functions can be called from the main()...</p> <pre><code>using System; using Language; namespace ULESConMain { class Program { static void Main(string[] args) { string OldSentence = "@#The dirty dog, was &amp;&amp;walking proudly!"; // output using just Console.WriteLine() without assigning to a varaiable // Console.WriteLine($"{Grammar.RemoveNonAlphaNumeric(OldSentence)}"); Console.WriteLine($"The total number of words in the sentence = {Grammar.GetWordCount(OldSentence)}"); // Output using Console.WriteLine() using returned values // string NewSentence1 = Grammar.RemoveNonAlphaNumeric(OldSentence); int WordCount = Grammar.GetWordCount(NewSentence1); Console.WriteLine(); Console.WriteLine(NewSentence1); Console.WriteLine($"The total number of words in the sentence = {WordCount}"); // Prompt to return control to the Operating System and exit the program. Console.WriteLine("\nPress the ENTRER key to continue..."); Console.ReadKey(); // Get user input to return to the Operating System. } } } </code></pre> <p>If anyone has any ideas or if you think this is good enough since it's working as expected. Please let me know.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T22:07:33.347", "Id": "424385", "Score": "0", "body": "Is it possible that examples of how both functions are called can be added to the review?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T23:00:05.800", "Id": "424386", "Score": "1", "body": "I just re-edited the post which contains the main program with the calling examples. One note though. Normally one of the function parameters for string.split() is System.StringSplitOptions.RemoveEmptyEntries, this was done on purpose because i'm using the System namespace for now which allowed me to remove System from the function parameters." } ]
[ { "body": "<p>The function <code>RemoveNonAlphaNumeric</code> promises to remove non-alphanumeric characters. It does this in an incomplete way.</p>\n\n<ul>\n<li>The comma is not removed.</li>\n<li>The apostrophe is not removed.</li>\n<li>The em-dash — is not removed.</li>\n</ul>\n\n<p>There's probably a function <code>Character.IsDigit</code> and <code>Character.isLetter</code> that is more appropriate. In the end, whether it is appropriate or not depends on what the code is supposed to do at all. What do you need it for, why do you want to remove non-alphanumeric characters in the first place?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T08:51:38.067", "Id": "424409", "Score": "0", "body": "They were actually left out on purpose. The string array variable Removed determines which characters are actually going to be removed from the string and then handled the string.split() method. The punctuation you mentioned will be added later to the array variable as I develop the rest of the code for a language translation program in which some languages doe not include these elements. This code is still in it's early stages and may change in further development of that application. However, thanks for the suggestion I may be able to use that in the rewrite should it come to it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T04:55:38.373", "Id": "219733", "ParentId": "219721", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T19:50:43.587", "Id": "219721", "Score": "3", "Tags": [ "c#" ], "Title": "Class for removing Non Alpha/Numeric Character String and Counting Words" }
219721
<p><a href="https://leetcode.com/problems/maximum-depth-of-n-ary-tree/" rel="nofollow noreferrer">https://leetcode.com/problems/maximum-depth-of-n-ary-tree/</a></p> <p>Given a n-ary tree, find its maximum depth.</p> <p>The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.</p> <p>For example, given a 3-ary tree:</p> <p><a href="https://i.stack.imgur.com/WPko4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WPko4.png" alt="enter image description here"></a></p> <p>We should return its max depth, which is 3.</p> <p>Note:</p> <p>The depth of the tree is at most 1000. The total number of nodes is at most 5000.</p> <p>Here is my code, and also 1 test as an example Please comment about space and time complexity, I also made a recursive answer but I tend to think about BFS in an iterative way while using queue, and DFS in recursive way, although you can use a stack for it as well. so I a real interview I would probably go with BFS with a queue.</p> <pre><code>using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; namespace TreeQuestions { // Definition for a Node. public class Node { public int val; public IList&lt;Node&gt; children; public Node() { } public Node(int _val, IList&lt;Node&gt; _children) { val = _val; children = _children; } } /// &lt;summary&gt; /// https://leetcode.com/problems/maximum-depth-of-n-ary-tree/ /// &lt;/summary&gt; [TestClass] public class MaximumDepthOfN_aryTree { public int MaxDepth(Node root) { if (root == null) { return 0; } int maxDepth = 0; Queue&lt;Node&gt; queue = new Queue&lt;Node&gt;(); queue.Enqueue(root); while (queue.Count &gt; 0) { maxDepth++; var queueSize = queue.Count; for (int i = 0; i &lt; queueSize; i++) { var current = queue.Dequeue(); if (current.children != null) { foreach (var child in current.children) { queue.Enqueue(child); } } } } return maxDepth; } [TestMethod] public void MaximumDepthOfN_aryTreeTest() { List&lt;Node&gt; node3 = new List&lt;Node&gt;(); node3.Add(new Node(5, null)); node3.Add(new Node(6, null)); List&lt;Node&gt; node1 = new List&lt;Node&gt;(); node1.Add(new Node(3, node3)); node1.Add(new Node(2, null)); node1.Add(new Node(4, null)); Node root = new Node(1, node1); int result = MaxDepth(root); Assert.AreEqual(3, result); } } } </code></pre>
[]
[ { "body": "<p>It looks optimized to me, but you can add a check for <code>maxDepth &gt;= 1000</code> and break the while loop if true.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T06:00:31.583", "Id": "219735", "ParentId": "219722", "Score": "1" } }, { "body": "<p>Your solution seems pretty optimal - for breadth-first traversal (see below)</p>\n\n<ol>\n<li>MaxDepth() could/should be static. The containing class too.</li>\n<li>The LeetCode question does not require breadth-first traversal.<br>\nDepth first would not require an(y) additional data structure (no queue, but would implicitly use the stack) \nwhich <em>might</em> be optimised away by tail-recursion (if C# is smart enough).</li>\n</ol>\n\n<p>The following is therefore not criticism but a suggested alternative.<br>\n- I would not expect (much of) a performance difference<br>\n- Space-advantage, if significant (due to tail-recursion optimisation, compiler-and/or run-time environment dependent) would have to be measured<br>\n- So the main consideration in (not) choosing depth-first traversal would be a (probably) religious argument about brevity/readability of code</p>\n\n<pre><code>public static int MaxDepth2(IEnumerator&lt;Node&gt; nodeEnum = null, int depth = 0)\n{\n // No current node\n if (nodeEnum == null || !nodeEnum.MoveNext()) return depth;\n\n // The greater of current and maximum of siblings\n using (var nodeEnumInner = nodeEnum.Current?.children?.GetEnumerator())\n return Math.Max(MaxDepth2(nodeEnumInner, depth + 1), MaxDepth2(nodeEnum, depth));\n}\n\n:\n:\nusing (var nodeEnum = new List&lt;Node&gt; { root }.GetEnumerator())\n depth2 = MaximumDepthOfN_aryTree.MaxDepth2(nodeEnum);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T10:05:22.260", "Id": "424558", "Score": "0", "body": "This code is rather confusing, and isn't an up-to-scratch implementation of an `IEnumerator<T>` consumer. What advantage does this have over using a `foreach` loop or `LINQ`'s `Max`? This code also introduces different `null` checking behaviour (`nodeEnum.Current?.`) which may obscure bugs. Without CTO (which is in no way guaranteed in C#, and can't be performed without an understanding that `Max` is associative), this will have significantly worse memory characteristics than a simple DFS." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T10:24:51.767", "Id": "424562", "Score": "0", "body": "@VisualMelon: On matters religious: Criticism accepted...\n1. It is confusing\n2. Null-checking syntax is inconsistent.\nI should have spent more time on writing \"inspection-worthy code\".\nI don't get your \"up-to-scratch consumption\" chirp... and would be keen to see it improved (by all means with LINQ or foreach, but preserving the point I was trying to make about the - arguably - more intuitive depth-first approach please). \n\nOn matters empirical: I'd need to see something more substantial to support an opinion about \"memory characteristics\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T10:31:02.377", "Id": "424564", "Score": "0", "body": "It's fine to provide an alternative suggestion, but it needs to be clear why you think it would be better option in some way (and ideally identify any deficiencies, which can be hard to see in questions like this because there are no real requirements). You ought to be disposing the `IEnumerator<T>` (e.g. in a `finally` block); I'm afraid I can't find a sensible reference this minute. I suggest we continue this discussion in [chat](https://chat.stackexchange.com/rooms/93285/leetcode-maximum-depth-of-n-ary-tree-discussion) so that we don't flood the comment section." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T10:52:40.757", "Id": "424565", "Score": "0", "body": "@VisualMelon: Keeping it off chat for the moment because the observation about *disposing the enumerator is vital*. Thanks. I've updated my code. \nAs for motivating the suggestion, I think I did that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T11:22:07.070", "Id": "424571", "Score": "0", "body": "Fair enough. I wrote some comments concerning the memory usage [in chat](https://chat.stackexchange.com/rooms/93285/leetcode-maximum-depth-of-n-ary-tree-discussion) if you wanted to see those." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T09:19:12.160", "Id": "219795", "ParentId": "219722", "Score": "2" } }, { "body": "<p>A recursive approach that takes into account the threshold of max depth <code>1000</code>. The threshold of <code>5000</code> nodes is ambigious, because what behavior do you expect when there are more nodes?</p>\n\n<pre><code>using System;\nusing System.Linq;\nusing System.Text;\nusing System.Collections.Generic;\nusing System.Globalization;\nusing System.Text.RegularExpressions;\n\npublic class Program\n{\n public static void Main()\n {\n var node5 = new Node();\n var node6 = new Node();\n var node3 = new Node(0, new List&lt;Node&gt; { node5, node6 });\n var node2 = new Node();\n var node4 = new Node();\n var node1 = new Node(0, new List&lt;Node&gt; { node3, node2, node4 });\n\n Console.WriteLine(\"Max Depth = \" + MaximumDepthOfN_aryTree.MaxDepth(node1, 1000, 1));\n\n Console.ReadKey();\n }\n\n public class MaximumDepthOfN_aryTree\n {\n public static int MaxDepth(Node root, int maxDepthThreshold, int depth) \n {\n if (root.children == null || !root.children.Any()) {\n return depth;\n }\n\n if (depth == maxDepthThreshold) {\n return depth;\n }\n\n return root.children.Max(x =&gt; MaxDepth(x, maxDepthThreshold, depth++));\n }\n }\n\n public class Node\n {\n public int val;\n public IList&lt;Node&gt; children;\n\n public Node() {\n }\n\n public Node(int _val, IList&lt;Node&gt; _children) {\n val = _val;\n children = _children;\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T15:14:25.887", "Id": "220468", "ParentId": "219722", "Score": "1" } } ]
{ "AcceptedAnswerId": "219795", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T19:54:49.920", "Id": "219722", "Score": "3", "Tags": [ "c#", "programming-challenge", "tree", "breadth-first-search" ], "Title": "LeetCode: maximum-depth-of-n-ary-tree" }
219722
<p>I'm working on a personal game project to hone my CSS, HTML, and vanilla JS skills. I would appreciate any feedback on my small dice game project.</p> <p><a href="https://codepen.io/code_blodd/project/editor/XpNRbR#0" rel="noreferrer">ceelo-js Codepen</a></p> <p>The main logic of the game is run by this function:</p> <pre><code>getScore: function(results) { let message = ''; if (results.toString() === WIN) { message = `${WIN} You Win!`; } else if (results.toString() === LOSS) { message = `${LOSS} You Lose`; } else if (results[0] === results[1] &amp;&amp; results[1] === results[2]) { message = `Trips! ${results[0]}`; } else if (results[0] === results[1]) { message = `You scored: ${results[2]}`; } else if (results[1] === results[2]) { message = `You scored: ${results[0]}`; } else { message = 'Roll again...'; } return message; }, </code></pre> <p>Essentially a player rolls until two dice match, the outlier is the player's score. Special cases are: '1,2,3': instant loss '4,5,6': instant win If a player rolls all the same number, the opponent would have to roll three matching numbers that are higher than the first player's score i.e.('4,4,4' > '1,1,1'). The only roll that can beat'6,6,6' is '4,5,6'.</p> <p>I still need to add the logic for playing against a human or NPC.</p> <p>Here is the full code:</p> <p>index.html</p> <pre class="lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8" /&gt; &lt;meta name="description" content="Ceelo: Three Dice" /&gt; &lt;title&gt;Ceelo&lt;/title&gt; &lt;link rel="stylesheet" href="styles.css" /&gt; &lt;link rel="stylesheet" href="dice.css"&gt; &lt;link rel="stylesheet" href="animations.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="score"&gt;Let's Roll&lt;/div&gt; &lt;div class="scene"&gt; &lt;div class="dice-display"&gt; &lt;div class="dice dice-one idle"&gt; &lt;div class="face face-front"&gt; &lt;div class="front-pip-1"&gt;&amp;#11044&lt;/div&gt; &lt;div class="front-pip-2"&gt;&amp;#11044&lt;/div&gt; &lt;div class="front-pip-3"&gt;&amp;#11044&lt;/div&gt; &lt;/div&gt; &lt;div class="face face-back"&gt; &lt;div class="back-pip-1"&gt;&amp;#11044&lt;/div&gt; &lt;div class="back-pip-2"&gt;&amp;#11044&lt;/div&gt; &lt;div class="back-pip-3"&gt;&amp;#11044&lt;/div&gt; &lt;div class="back-pip-4"&gt;&amp;#11044&lt;/div&gt; &lt;/div&gt; &lt;div class="face face-right"&gt; &lt;div class="right-pip-1"&gt;&amp;#11044&lt;/div&gt; &lt;div class="right-pip-2"&gt;&amp;#11044&lt;/div&gt; &lt;div class="right-pip-3"&gt;&amp;#11044&lt;/div&gt; &lt;div class="right-pip-4"&gt;&amp;#11044&lt;/div&gt; &lt;div class="right-pip-5"&gt;&amp;#11044&lt;/div&gt; &lt;/div&gt; &lt;div class="face face-left"&gt; &lt;div class="left-pip-1"&gt;&amp;#11044&lt;/div&gt; &lt;div class="left-pip-2"&gt;&amp;#11044&lt;/div&gt; &lt;/div&gt; &lt;div class="face face-top"&gt; &lt;div class="top-pip-1"&gt;&amp;#11044&lt;/div&gt; &lt;div class="top-blank-1"&gt;&lt;/div&gt; &lt;div class="top-blank-2"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="face face-bottom"&gt; &lt;div class="bottom-pip-1"&gt;&amp;#11044&lt;/div&gt; &lt;div class="bottom-pip-2"&gt;&amp;#11044&lt;/div&gt; &lt;div class="bottom-pip-3"&gt;&amp;#11044&lt;/div&gt; &lt;div class="bottom-pip-4"&gt;&amp;#11044&lt;/div&gt; &lt;div class="bottom-pip-5"&gt;&amp;#11044&lt;/div&gt; &lt;div class="bottom-pip-6"&gt;&amp;#11044&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="dice-display"&gt; &lt;div class="dice dice-two idle"&gt; &lt;div class="face face-front"&gt; &lt;div class="front-pip-1"&gt;&amp;#11044&lt;/div&gt; &lt;div class="front-pip-2"&gt;&amp;#11044&lt;/div&gt; &lt;div class="front-pip-3"&gt;&amp;#11044&lt;/div&gt; &lt;/div&gt; &lt;div class="face face-back"&gt; &lt;div class="back-pip-1"&gt;&amp;#11044&lt;/div&gt; &lt;div class="back-pip-2"&gt;&amp;#11044&lt;/div&gt; &lt;div class="back-pip-3"&gt;&amp;#11044&lt;/div&gt; &lt;div class="back-pip-4"&gt;&amp;#11044&lt;/div&gt; &lt;/div&gt; &lt;div class="face face-right"&gt; &lt;div class="right-pip-1"&gt;&amp;#11044&lt;/div&gt; &lt;div class="right-pip-2"&gt;&amp;#11044&lt;/div&gt; &lt;div class="right-pip-3"&gt;&amp;#11044&lt;/div&gt; &lt;div class="right-pip-4"&gt;&amp;#11044&lt;/div&gt; &lt;div class="right-pip-5"&gt;&amp;#11044&lt;/div&gt; &lt;/div&gt; &lt;div class="face face-left"&gt; &lt;div class="left-pip-1"&gt;&amp;#11044&lt;/div&gt; &lt;div class="left-pip-2"&gt;&amp;#11044&lt;/div&gt; &lt;/div&gt; &lt;div class="face face-top"&gt; &lt;div class="top-pip-1"&gt;&amp;#11044&lt;/div&gt; &lt;div class="top-blank-1"&gt;&lt;/div&gt; &lt;div class="top-blank-2"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="face face-bottom"&gt; &lt;div class="bottom-pip-1"&gt;&amp;#11044&lt;/div&gt; &lt;div class="bottom-pip-2"&gt;&amp;#11044&lt;/div&gt; &lt;div class="bottom-pip-3"&gt;&amp;#11044&lt;/div&gt; &lt;div class="bottom-pip-4"&gt;&amp;#11044&lt;/div&gt; &lt;div class="bottom-pip-5"&gt;&amp;#11044&lt;/div&gt; &lt;div class="bottom-pip-6"&gt;&amp;#11044&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="dice-display"&gt; &lt;div class="dice dice-three idle"&gt; &lt;div class="face face-front"&gt; &lt;div class="front-pip-1"&gt;&amp;#11044&lt;/div&gt; &lt;div class="front-pip-2"&gt;&amp;#11044&lt;/div&gt; &lt;div class="front-pip-3"&gt;&amp;#11044&lt;/div&gt; &lt;/div&gt; &lt;div class="face face-back"&gt; &lt;div class="back-pip-1"&gt;&amp;#11044&lt;/div&gt; &lt;div class="back-pip-2"&gt;&amp;#11044&lt;/div&gt; &lt;div class="back-pip-3"&gt;&amp;#11044&lt;/div&gt; &lt;div class="back-pip-4"&gt;&amp;#11044&lt;/div&gt; &lt;/div&gt; &lt;div class="face face-right"&gt; &lt;div class="right-pip-1"&gt;&amp;#11044&lt;/div&gt; &lt;div class="right-pip-2"&gt;&amp;#11044&lt;/div&gt; &lt;div class="right-pip-3"&gt;&amp;#11044&lt;/div&gt; &lt;div class="right-pip-4"&gt;&amp;#11044&lt;/div&gt; &lt;div class="right-pip-5"&gt;&amp;#11044&lt;/div&gt; &lt;/div&gt; &lt;div class="face face-left"&gt; &lt;div class="left-pip-1"&gt;&amp;#11044&lt;/div&gt; &lt;div class="left-pip-2"&gt;&amp;#11044&lt;/div&gt; &lt;/div&gt; &lt;div class="face face-top"&gt; &lt;div class="top-pip-1"&gt;&amp;#11044&lt;/div&gt; &lt;div class="top-blank-1"&gt;&lt;/div&gt; &lt;div class="top-blank-2"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="face face-bottom"&gt; &lt;div class="bottom-pip-1"&gt;&amp;#11044&lt;/div&gt; &lt;div class="bottom-pip-2"&gt;&amp;#11044&lt;/div&gt; &lt;div class="bottom-pip-3"&gt;&amp;#11044&lt;/div&gt; &lt;div class="bottom-pip-4"&gt;&amp;#11044&lt;/div&gt; &lt;div class="bottom-pip-5"&gt;&amp;#11044&lt;/div&gt; &lt;div class="bottom-pip-6"&gt;&amp;#11044&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="controls"&gt; &lt;button id="roll"&gt;Roll&lt;/button&gt; &lt;/div&gt; &lt;script src="main.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>main.js</p> <pre class="lang-js prettyprint-override"><code>'using-strict'; const LOSS = '1,2,3'; const WIN = '4,5,6'; const INITIAL_TRANSFORM_STATE = 'idle' var roll = function() { let sides = 6; return Math.floor(sides * Math.random()) + 1; }; const view = { roll: document.getElementById('roll'), dice1: {o: document.querySelector('.dice-one'), state: INITIAL_TRANSFORM_STATE}, dice2: {o: document.querySelector('.dice-two'), state: INITIAL_TRANSFORM_STATE}, dice3: {o: document.querySelector('.dice-three'), state: INITIAL_TRANSFORM_STATE}, score: document.querySelector('.score'), updateDice: function(results) { handleDiceAnimation(this.dice1); handleDiceAnimation(this.dice2); handleDiceAnimation(this.dice3); setTimeout(()=&gt;{ showResult(this.dice1, results[0]); showResult(this.dice2, results[1]); showResult(this.dice3, results[2]); },820) }, updateScore: function(message) { this.score.textContent = message; }, }; const game = { turn: function() { let rollResult = [roll(), roll(), roll()]; let resultSorted = [...rollResult].sort(); // sort results and return new array view.updateDice(rollResult); setTimeout(()=&gt;{ view.updateScore(this.getScore(resultSorted)); }, 1000); }, getScore: function(results) { let message = ''; if (results.toString() === WIN) { message = `${WIN} You Win!`; } else if (results.toString() === LOSS) { message = `${LOSS} You Lose`; } else if (results[0] === results[1] &amp;&amp; results[1] === results[2]) { message = `Trips! ${results[0]}`; } else if (results[0] === results[1]) { message = `You scored: ${results[2]}`; } else if (results[1] === results[2]) { message = `You scored: ${results[0]}`; } else { message = 'Roll again...'; } return message; }, }; view.roll.addEventListener('click', () =&gt; game.turn(), false); var handleDiceAnimation = dice =&gt; { if (dice.state === 'idle'){ dice.o.classList.remove('idle'); } dice.o.classList.remove('spin'); void dice.o.offsetWidth; dice.o.classList.add('spin'); } var showResult = (dice, value) =&gt; { dice.o.classList.remove(dice.state); void dice.o.offsetWidth; if (value === 1) { dice.o.classList.add('show-top'); dice.state = 'show-top'; } else if (value === 2) { dice.o.classList.add('show-left'); dice.state = 'show-left'; } else if (value === 3) { dice.o.classList.add('show-front'); dice.state = 'show-front'; } else if (value === 4) { dice.o.classList.add('show-back'); dice.state = 'show-back'; } else if (value === 5) { dice.o.classList.add('show-right'); dice.state = 'show-right'; } else if (value === 6) { dice.o.classList.add('show-bottom'); dice.state = 'show-bottom'; } } </code></pre> <p>animations.css</p> <pre class="lang-css prettyprint-override"><code>.idle { animation: idle linear infinite 6s; } @keyframes idle { from { transform: translateZ(-75px) rotateX(0deg) rotateY(0deg); } to { transform: translateZ(-75px) rotateX(360deg) rotateY(360deg); } } .spin { animation: spin 0.8s linear 1; } @keyframes spin { 0% { -webkit-transform: translateZ(-75px) scale(1) rotate3d(-1, 1, 0, 0deg); transform: translateZ(-75px) scale(1) rotate3d(-1, 1, 0, 0deg); } 50% { -webkit-transform: translateZ(-75px) scale(1.4) rotate3d(-1, 1, 0, 180deg); transform: translateZ(-75px) scale(1.4) rotate3d(-1, 1, 0, 180deg); } 100% { -webkit-transform: translateZ(-75px) scale(1) rotate3d(-1, 1, 0, 360deg); transform: translateZ(-75px) scale(1) rotate3d(-1, 1, 0, 360deg); } } .show-top { transform: translateZ(-75px) rotateX(-90deg); } .show-front { transform: translateZ(-75px) rotateY( 0deg); } .show-right { transform: translateZ(-75px) rotateY( -90deg); } .show-back { transform: translateZ(-75px) rotateY(-180deg); } .show-left { transform: translateZ(-75px) rotateY( 90deg); } .show-top { transform: translateZ(-75px) rotateX( -90deg); } .show-bottom { transform: translateZ(-75px) rotateX( 90deg); } </code></pre> <p>dice.css</p> <pre class="lang-css prettyprint-override"><code>.dice-display { width: 150px; height: 150px; perspective: 450px; } .dice { width: 100%; height: 100%; position: relative; transform-style: preserve-3d; transform: translateZ(-75px); transition: transform 0.4s; } .dice-one { } .dice-two { } .dice-three { } .face { position: absolute; width: 150px; height: 150px; display: grid; grid-template-columns: 50px, 50px, 50px; grid-template-rows: 50px, 50px, 50px; border: 1px solid hsla(0, 100%, 50%, 0.2); color: whitesmoke; font-size: 24pt; } /* 3 */ .face-front { background: hsla(0, 100%, 50%, 0.6); transform: rotateY(0deg) translateZ(75px); } .front-pip-1 { grid-column: 3 / 4; grid-row: 1 / 2; place-self: center; } .front-pip-2 { grid-column: 2 / 3; grid-row: 2 / 3; place-self: center; } .front-pip-3 { grid-column: 1 / 2; grid-row: 3 / 4; place-self: center; } /* 4 */ .face-back { background: hsla(0, 100%, 50%, 0.6); transform: rotateY(180deg) translateZ(75px); } .back-pip-1 { grid-column: 1 / 2; grid-row: 1 / 2; place-self: center; } .back-pip-2 { grid-column: 3 / 4; grid-row: 1 / 2; place-self: center; } .back-pip-3 { grid-column: 1 / 2; grid-row: 3 / 4; place-self: center; } .back-pip-4 { grid-column: 3 / 4; grid-row: 3 / 4; place-self: center; } /* 5 */ .face-right { background: hsla(0, 100%, 50%, 0.6); transform: rotateY(90deg) translateZ(75px); } .right-pip-1 { grid-column: 1 / 2; grid-row: 1 / 2; place-self: center; } .right-pip-2 { grid-column: 3 / 4; grid-row: 1 / 2; place-self: center; } .right-pip-3 { grid-column: 2 / 3; grid-row: 2 / 3; place-self: center; } .right-pip-4 { grid-column: 1 / 2; grid-row: 3 / 4; place-self: center; } .right-pip-5 { grid-column: 3 / 4; grid-row: 3 / 4; place-self: center; } /* 2 */ .face-left { background: hsla(0, 100%, 50%, 0.6); transform: rotateY(-90deg) translateZ(75px); } .left-pip-1 { grid-column: 3 / 4; grid-row: 1 / 2; place-self: center; } .left-pip-2 { grid-column: 1 / 2; grid-row: 3 / 4; place-self: center; } /* 1 */ .face-top { background: hsla(0, 100%, 50%, 0.6); transform: rotateX(90deg) translateZ(75px); } .top-pip-1 { grid-column: 2 / 3; grid-row: 2 / 3; place-self: center; } .top-blank-1 { grid-column: 1 / 4; grid-row: 1 / 2; place-self: center; } .top-blank-2 { grid-column: 1 / 4; grid-row: 3 / 4; place-self: center; } /* 6 */ .face-bottom { background: hsla(0, 100%, 50%, 0.6); transform: rotateX(-90deg) translateZ(75px); } .bottom-pip-1 { grid-column: 1 / 2; grid-row: 1 / 2; place-self: center; } .bottom-pip-2 { grid-column: 1 / 2; grid-row: 2 / 3; place-self: center; } .bottom-pip-3 { grid-column: 1 / 2; grid-row: 3 / 4; place-self: center; } .bottom-pip-4 { grid-column: 3 / 4; grid-row: 1 / 2; place-self: center; } .bottom-pip-5 { grid-column: 3 / 4; grid-row: 2 / 3; place-self: center; } .bottom-pip-6 { grid-column: 3 / 4; grid-row: 3 / 4; place-self: center; } </code></pre> <p>styles.css</p> <pre class="lang-css prettyprint-override"><code>* { box-sizing: border-box; } body { background: repeating-linear-gradient(#071a1e 0%, #274249) fixed; display: grid; grid-template-columns: 20% auto 20%; grid-template-rows: 25% auto 25%; } .score { grid-column: 2 / 3; grid-row: 1 / 2; place-self: center; color: gainsboro; font-size: 30pt; margin-bottom: 15px; } .scene { display: flex; justify-content: space-evenly; grid-column: 2 / 3; grid-row: 2 / 3; } .controls { grid-column: 2 / 3; grid-row: 3 / 4; place-self: center; } #roll { margin-top: 50px; } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T22:03:42.560", "Id": "424384", "Score": "1", "body": "Welcome to Code Review, unfortunately this question seems to be off-topic because it doesn't contain enough code. Please post everything you want reviewed in the question. See https://codereview.stackexchange.com/help/how-to-ask and https://codereview.stackexchange.com/help/dont-ask." } ]
[ { "body": "<h2>Code style</h2>\n\n<ul>\n<li>Its <code>\"use strict\";</code> not <code>'using-strict';</code></li>\n<li>Use object function shorthand for object functions. eg you use <code>{ foo: function() {},}</code>can be <code>{foo(){},}</code></li>\n<li>Avoid long lists of <code>if ... else if ...</code> by using lookups. (see example) </li>\n<li><p>When defining functions that are available across the current scope, if they are arrow functions make them constants <code>const name = (foo) =&gt; {}</code> and put them at the top of the scope (manually hoist them). Or use a function declaration that is automatically hoisted for you. <code>function name(foo){}</code>. </p></li>\n<li><p>Avoid using function expressions eg <code>var roll = function() {</code> should be <code>function roll() {</code></p></li>\n<li><p>When you have variables that only differ by a post-fixed number, <code>dice1</code>, <code>dice2</code>, <code>dice3</code> that is a good sign that they can be better handled in an array. You can still give them names, but keeping an array referencing the same can simplify the code at times.</p></li>\n<li><p>Use variable aliases to reduce noisy and verbose code. For example in the function <code>game.getScore</code> you are repeatedly referencing by literal index into <code>results</code>. If you assigned 3 aliases the code becomes a lot cleaner See example <code>game.roll</code> line starts with <code>const [r1, r2, r3] =</code>...</p></li>\n<li><p>Why the expression <code>void dice.o.offsetWidth</code>? It does nothing but evaluate to <code>undefined</code>. You may as well have added the line <code>undefined;</code> in its place.</p></li>\n</ul>\n\n<h2>Code logic and design</h2>\n\n<p>Your encapsulation of the abstracts used in the game can be improved. </p>\n\n<p>The fundamental working unit is the dice yet you define its behavior all over the place rather than creating an object to encapsulate its state and behavior.</p>\n\n<p>Then you have the <code>view</code> and the <code>game</code> with roles that are a little vague. <code>view</code> calling functions outside its encapsulation, and <code>game</code> creating a (view-able) <code>message</code> rather than setting a state that <code>view</code> would convert to a message.</p>\n\n<h2>CSS, HTML, and animation</h2>\n\n<p>I noticed that as the page width gets small the dice are overlapping. Adding a margin to the dice would separate them, however that would mean you have to change the layout a little.</p>\n\n<p>For this reason and more, I am not reviewing the CSS and HTML as personally animating anything but the most basic FX is severally limiting when done via CSS and HTML. I would have opted for WebGL to render and JS to define and animate as it provides much more flexibility and quality, though I understand its not everyone's cup of tea.</p>\n\n<h2>Example</h2>\n\n<p>I have rewritten your code to better encapsulate the data and behavior. As an example only and is not the only way to go about it. It's main purpose is to give examples of the points in this answer.</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>\"use strict\";\nconst LOSS = '123', WIN = '456';\nconst FACE_NAMES = \",top,left,front,back,right,bottom\".split(\",\");\nconst dice = name =&gt; {\n const el = document.querySelector(\".dice-\" + name);\n const animate = name =&gt; (el.classList.remove(state), el.classList.add(name), name);\n var value, state = \"idle\"; \n return {\n get val() { return \"\" + value },\n roll() { value = Math.floor(6 * Math.random()) + 1 },\n show() { state = animate(\"show-\" + FACE_NAMES[value]) },\n spin() { state = animate(\"spin\") }, \n };\n}\nconst game = {\n score: document.querySelector('.score'),\n dice: [dice(\"one\"), dice(\"two\"), dice(\"three\")],\n roll() { \n game.callEach(\"roll\");\n game.callEach(\"spin\");\n setTimeout(game.callEach ,820, \"show\");\n const [r1,r2,r3] = [game.dice[0].val, game.dice[1].val, game.dice[2].val].sort();\n if (r1 + r2 + r3 === WIN) { return `${WIN} You Win!` }\n if (r1 + r2 + r3 === LOSS) { return `${LOSS} You lose!` }\n if (r1 === r2 &amp;&amp; r2 === r3) { return `Trips! ${r1}` }\n if (r1 === r2) { return `You scored: ${r3}` }\n if (r3 === r2) { return `You scored: ${r1}` }\n return \"Roll Again\";\n },\n callEach(call) { game.dice.forEach(dice =&gt; dice[call]()) },\n turn() {\n const message = game.roll();\n setTimeout(() =&gt; game.score.textContent = message, 1000);\n }\n};\ndocument.getElementById('roll').addEventListener('click', game.turn);</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>* {\n box-sizing: border-box;\n}\n\nbody {\n background: repeating-linear-gradient(#071a1e 0%, #274249) fixed;\n display: grid;\n grid-template-columns: 20% auto 20%;\n grid-template-rows: 25% auto 25%;\n}\n\n.score {\n grid-column: 2 / 3;\n grid-row: 1 / 2;\n place-self: center;\n color: gainsboro;\n font-size: 30pt;\n margin-bottom: 15px;\n}\n\n.scene {\n display: flex;\n justify-content: space-evenly;\n grid-column: 2 / 3;\n grid-row: 2 / 3;\n}\n\n\n.controls {\n grid-column: 2 / 3;\n grid-row: 3 / 4;\n place-self: center;\n}\n\n#roll {\n margin-top: 50px;\n}\n.dice-display {\n width: 150px;\n height: 150px;\n perspective: 450px;\n margin:26px;\n}\n\n.dice {\n width: 100%;\n height: 100%;\n position: relative;\n transform-style: preserve-3d;\n transform: translateZ(-75px);\n transition: transform 0.4s;\n}\n\n.dice-one {\n}\n\n.dice-two {\n}\n\n.dice-three {\n}\n\n.face {\n position: absolute;\n width: 150px;\n height: 150px;\n display: grid;\n grid-template-columns: 50px, 50px, 50px;\n grid-template-rows: 50px, 50px, 50px;\n border: 1px solid hsla(0, 100%, 50%, 0.2);\n color: whitesmoke;\n font-size: 24pt;\n}\n\n/* 3 */\n.face-front {\n background: hsla(0, 100%, 50%, 0.6);\n transform: rotateY(0deg) translateZ(75px);\n}\n\n.front-pip-1 {\n grid-column: 3 / 4;\n grid-row: 1 / 2;\n place-self: center;\n}\n.front-pip-2 {\n grid-column: 2 / 3;\n grid-row: 2 / 3;\n place-self: center;\n}\n.front-pip-3 {\n grid-column: 1 / 2;\n grid-row: 3 / 4;\n place-self: center;\n}\n\n/* 4 */\n.face-back {\n background: hsla(0, 100%, 50%, 0.6);\n transform: rotateY(180deg) translateZ(75px);\n}\n\n.back-pip-1 {\n grid-column: 1 / 2;\n grid-row: 1 / 2;\n place-self: center;\n}\n\n.back-pip-2 {\n grid-column: 3 / 4;\n grid-row: 1 / 2;\n place-self: center;\n}\n\n.back-pip-3 {\n grid-column: 1 / 2;\n grid-row: 3 / 4;\n place-self: center;\n}\n\n.back-pip-4 {\n grid-column: 3 / 4;\n grid-row: 3 / 4;\n place-self: center;\n}\n\n/* 5 */\n.face-right {\n background: hsla(0, 100%, 50%, 0.6);\n transform: rotateY(90deg) translateZ(75px);\n}\n\n.right-pip-1 {\n grid-column: 1 / 2;\n grid-row: 1 / 2;\n place-self: center;\n}\n\n.right-pip-2 {\n grid-column: 3 / 4;\n grid-row: 1 / 2;\n place-self: center;\n}\n\n.right-pip-3 {\n grid-column: 2 / 3;\n grid-row: 2 / 3;\n place-self: center;\n}\n\n.right-pip-4 {\n grid-column: 1 / 2;\n grid-row: 3 / 4;\n place-self: center;\n}\n\n.right-pip-5 {\n grid-column: 3 / 4;\n grid-row: 3 / 4;\n place-self: center;\n}\n\n/* 2 */\n.face-left {\n background: hsla(0, 100%, 50%, 0.6);\n transform: rotateY(-90deg) translateZ(75px);\n}\n\n.left-pip-1 {\n grid-column: 3 / 4;\n grid-row: 1 / 2;\n place-self: center;\n}\n\n.left-pip-2 {\n grid-column: 1 / 2;\n grid-row: 3 / 4;\n place-self: center;\n}\n\n/* 1 */\n.face-top {\n background: hsla(0, 100%, 50%, 0.6);\n transform: rotateX(90deg) translateZ(75px);\n}\n\n.top-pip-1 {\n grid-column: 2 / 3;\n grid-row: 2 / 3;\n place-self: center;\n}\n\n.top-blank-1 {\n grid-column: 1 / 4;\n grid-row: 1 / 2;\n place-self: center;\n}\n\n.top-blank-2 {\n grid-column: 1 / 4;\n grid-row: 3 / 4;\n place-self: center;\n}\n\n/* 6 */\n.face-bottom {\n background: hsla(0, 100%, 50%, 0.6);\n transform: rotateX(-90deg) translateZ(75px);\n}\n\n.bottom-pip-1 {\n grid-column: 1 / 2;\n grid-row: 1 / 2;\n place-self: center;\n}\n\n.bottom-pip-2 {\n grid-column: 1 / 2;\n grid-row: 2 / 3;\n place-self: center;\n}\n\n.bottom-pip-3 {\n grid-column: 1 / 2;\n grid-row: 3 / 4;\n place-self: center;\n}\n\n.bottom-pip-4 {\n grid-column: 3 / 4;\n grid-row: 1 / 2;\n place-self: center;\n}\n\n.bottom-pip-5 {\n grid-column: 3 / 4;\n grid-row: 2 / 3;\n place-self: center;\n}\n\n.bottom-pip-6 {\n grid-column: 3 / 4;\n grid-row: 3 / 4;\n place-self: center;\n}\n.idle {\n animation: idle linear infinite 6s;\n}\n\n@keyframes idle {\n from {\n transform: translateZ(-75px) rotateX(0deg) rotateY(0deg);\n }\n\n to {\n transform: translateZ(-75px) rotateX(360deg) rotateY(360deg);\n }\n}\n\n.spin {\n animation: spin 0.8s linear 1;\n}\n\n@keyframes spin {\n 0% {\n -webkit-transform: translateZ(-75px) scale(1) rotate3d(-1, 1, 0, 0deg);\n transform: translateZ(-75px) scale(1) rotate3d(-1, 1, 0, 0deg);\n }\n 50% {\n -webkit-transform: translateZ(-75px) scale(1.4) rotate3d(-1, 1, 0, 180deg);\n transform: translateZ(-75px) scale(1.4) rotate3d(-1, 1, 0, 180deg);\n }\n 100% {\n -webkit-transform: translateZ(-75px) scale(1) rotate3d(-1, 1, 0, 360deg);\n transform: translateZ(-75px) scale(1) rotate3d(-1, 1, 0, 360deg);\n }\n}\n\n.show-top { transform: translateZ(-75px) rotateX(-90deg); }\n.show-front { transform: translateZ(-75px) rotateY( 0deg); }\n.show-right { transform: translateZ(-75px) rotateY( -90deg); }\n.show-back { transform: translateZ(-75px) rotateY(-180deg); }\n.show-left { transform: translateZ(-75px) rotateY( 90deg); }\n.show-top { transform: translateZ(-75px) rotateX( -90deg); }\n.show-bottom { transform: translateZ(-75px) rotateX( 90deg); }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"score\"&gt;Let's Roll&lt;/div&gt;\n &lt;div class=\"scene\"&gt;\n &lt;div class=\"dice-display\"&gt;\n &lt;div class=\"dice dice-one idle\"&gt;\n &lt;div class=\"face face-front\"&gt;\n &lt;div class=\"front-pip-1\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"front-pip-2\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"front-pip-3\"&gt;&amp;#11044&lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"face face-back\"&gt;\n &lt;div class=\"back-pip-1\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"back-pip-2\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"back-pip-3\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"back-pip-4\"&gt;&amp;#11044&lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"face face-right\"&gt;\n &lt;div class=\"right-pip-1\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"right-pip-2\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"right-pip-3\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"right-pip-4\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"right-pip-5\"&gt;&amp;#11044&lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"face face-left\"&gt;\n &lt;div class=\"left-pip-1\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"left-pip-2\"&gt;&amp;#11044&lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"face face-top\"&gt;\n &lt;div class=\"top-pip-1\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"top-blank-1\"&gt;&lt;/div&gt;\n &lt;div class=\"top-blank-2\"&gt;&lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"face face-bottom\"&gt;\n &lt;div class=\"bottom-pip-1\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"bottom-pip-2\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"bottom-pip-3\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"bottom-pip-4\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"bottom-pip-5\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"bottom-pip-6\"&gt;&amp;#11044&lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"dice-display\"&gt;\n &lt;div class=\"dice dice-two idle\"&gt;\n &lt;div class=\"face face-front\"&gt;\n &lt;div class=\"front-pip-1\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"front-pip-2\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"front-pip-3\"&gt;&amp;#11044&lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"face face-back\"&gt;\n &lt;div class=\"back-pip-1\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"back-pip-2\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"back-pip-3\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"back-pip-4\"&gt;&amp;#11044&lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"face face-right\"&gt;\n &lt;div class=\"right-pip-1\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"right-pip-2\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"right-pip-3\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"right-pip-4\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"right-pip-5\"&gt;&amp;#11044&lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"face face-left\"&gt;\n &lt;div class=\"left-pip-1\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"left-pip-2\"&gt;&amp;#11044&lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"face face-top\"&gt;\n &lt;div class=\"top-pip-1\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"top-blank-1\"&gt;&lt;/div&gt;\n &lt;div class=\"top-blank-2\"&gt;&lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"face face-bottom\"&gt;\n &lt;div class=\"bottom-pip-1\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"bottom-pip-2\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"bottom-pip-3\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"bottom-pip-4\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"bottom-pip-5\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"bottom-pip-6\"&gt;&amp;#11044&lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"dice-display\"&gt;\n &lt;div class=\"dice dice-three idle\"&gt;\n &lt;div class=\"face face-front\"&gt;\n &lt;div class=\"front-pip-1\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"front-pip-2\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"front-pip-3\"&gt;&amp;#11044&lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"face face-back\"&gt;\n &lt;div class=\"back-pip-1\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"back-pip-2\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"back-pip-3\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"back-pip-4\"&gt;&amp;#11044&lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"face face-right\"&gt;\n &lt;div class=\"right-pip-1\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"right-pip-2\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"right-pip-3\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"right-pip-4\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"right-pip-5\"&gt;&amp;#11044&lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"face face-left\"&gt;\n &lt;div class=\"left-pip-1\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"left-pip-2\"&gt;&amp;#11044&lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"face face-top\"&gt;\n &lt;div class=\"top-pip-1\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"top-blank-1\"&gt;&lt;/div&gt;\n &lt;div class=\"top-blank-2\"&gt;&lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"face face-bottom\"&gt;\n &lt;div class=\"bottom-pip-1\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"bottom-pip-2\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"bottom-pip-3\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"bottom-pip-4\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"bottom-pip-5\"&gt;&amp;#11044&lt;/div&gt;\n &lt;div class=\"bottom-pip-6\"&gt;&amp;#11044&lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"controls\"&gt;\n &lt;button id=\"roll\"&gt;Roll&lt;/button&gt;\n &lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T19:53:59.520", "Id": "424495", "Score": "0", "body": "Thanks for the detailed answer! I will take your review under heavy consideration. In regards to your question about `void dice.o.offsetWidth` , its a way to restart a css animation by triggering a reflow. [link](https://css-tricks.com/restart-css-animation/)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T21:52:09.600", "Id": "424519", "Score": "1", "body": "@ArbanNichols Thought that a little strange you where not removing `dice.o.state` from the class list in `handleDiceAnimation `. I have updated the answer to have a running example. Now also remembers `\"spin\"` as a state and you will see that you do not need it (voiding property) as removing the `\"spin\"` class means you are causing a reflow when it is added back on click" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T01:59:08.773", "Id": "424525", "Score": "0", "body": "`const animate = name => (el.classList.remove(state), el.classList.add(name), name);` I'm lost on this line of code. Is it a list of function calls?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T02:20:26.690", "Id": "424527", "Score": "1", "body": "@ArbanNichols \nI am using a comma operator https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator to separate 3 expressions, the last `, name` is the returned value." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T16:38:08.143", "Id": "219757", "ParentId": "219723", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T21:31:20.737", "Id": "219723", "Score": "4", "Tags": [ "javascript", "css", "html5", "dice" ], "Title": "Dice game in HTML, JS, & CSS" }
219723
<p><a href="https://leetcode.com/problems/n-ary-tree-level-order-traversal/" rel="nofollow noreferrer">https://leetcode.com/problems/n-ary-tree-level-order-traversal/</a></p> <p>Given an n-ary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).</p> <p>For example, given a 3-ary tree:</p> <p><a href="https://i.stack.imgur.com/WizMv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WizMv.png" alt="enter image description here"></a></p> <p>We should return its level order traversal:</p> <p>[ [1], [3,2,4], [5,6] ]</p> <p>Note:</p> <p>The depth of the tree is at most 1000. The total number of nodes is at most 5000.</p> <p>Please comment about space and time complexity. Thanks.</p> <pre><code>using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace GraphsQuestions { /// &lt;summary&gt; /// https://leetcode.com/problems/n-ary-tree-level-order-traversal/ /// &lt;/summary&gt; [TestClass] public class N_aryTreeLevelOrderTraversal { [TestMethod] public void N_aryTreeLevelOrderTraversalTest() { List&lt;Node&gt; node3 = new List&lt;Node&gt;(); node3.Add(new Node(5, null)); node3.Add(new Node(6, null)); List&lt;Node&gt; node1 = new List&lt;Node&gt;(); node1.Add(new Node(3, node3)); node1.Add(new Node(2, null)); node1.Add(new Node(4, null)); Node root = new Node(1, node1); var result = LevelOrder(root); IList&lt;IList&lt;int&gt;&gt; expected = new List&lt;IList&lt;int&gt;&gt;(); expected.Add(new List&lt;int&gt;{1}); expected.Add(new List&lt;int&gt;{3,2,4}); expected.Add(new List&lt;int&gt;{5,6}); for (int i = 0; i &lt; 3; i++) { CollectionAssert.AreEqual(expected[i].ToArray(), result[i].ToArray()); } } public IList&lt;IList&lt;int&gt;&gt; LevelOrder(Node root) { IList&lt;IList&lt;int&gt;&gt; result = new List&lt;IList&lt;int&gt;&gt;(); Queue&lt;Node&gt; Q = new Queue&lt;Node&gt;(); if (root == null) { return result; } Q.Enqueue(root); while (Q.Count &gt; 0) { List&lt;int&gt; currentLevel = new List&lt;int&gt;(); int qSize = Q.Count; for (int i = 0; i &lt; qSize; i++) { var curr = Q.Dequeue(); currentLevel.Add(curr.val); if (curr.children != null) { foreach (var child in curr.children) { Q.Enqueue(child); } } } result.Add(currentLevel); } return result; } } } </code></pre>
[]
[ { "body": "<p>Time and space complexity are just the number of nodes in the graph. You can't do better than this with the API given. If the API were open to negotiation, I'd consider <code>IEnumerable&lt;IReadonlyList&lt;int&gt;&gt;</code>, which would permit better memory characteristics for some trees (e.g. if the level-width stays reasonably constant rather than, say, growing exponentially). There is also no need for this to be an instance method.</p>\n\n<hr />\n\n<p>I don't like this:</p>\n\n\n\n<pre class=\"lang-cs prettyprint-override\"><code>if (root == null)\n{\n return result;\n}\n</code></pre>\n\n<p>No-where in the spec is it said that a <code>null</code> input should produce a <code>null</code> output, and this is a design decision which needs to be documented. Without something saying that <code>null</code> should map to <code>null</code>, I'd much prefer an <code>ArgumentNullException</code> which doesn't obscure any assumptions. If this behaviour is wrong, then you'll know the moment you try to use it. If returning <code>null</code> is wrong, it might take you a while to find out where your code messed up. Either behaviour warrents inline documentation. I'd also prefer these sorts of checks were performed straight-away, so that they can't be lost in the other clutter, and in this case avoid unnecessarily allocations.</p>\n\n<p>Similarly, is it specified that <code>Node.children</code> can be <code>null</code>, and that this is supported? If not, then I'd be inclined to remove the check, as it will simplify the code and cause it to blow up if this assumption is violated, forcing the consumer to address the <code>null</code> rather than hoping the behaviour is as expected. (Ideally any constraint would be enforced by the <code>Node</code> class, and I appreciate that isn't yours to change).</p>\n\n<hr />\n\n<p><code>Q</code> isn't a great variable name: it describes what the thing is, which can be confused with its purpose; and because it is capitalised, it feels like a member variable.</p>\n\n<hr />\n\n<p>It would be nicer if the test methods were separated from the functionality. Currently, anyone trying to find <code>aryTreeLevelOrderTraversal.LevelOrder</code> will be confronted with <code>N_aryTreeLevelOrderTraversalTest</code> in their intellisense</p>\n\n<hr />\n\n<p>Personally I don't like this sort of 'staged' consumption of a queue; it just feels fiddily. In this case you can avoid it completely (and save memory) by enumerating over the previous level when you construct the next. This can make the code more-compact, and harder to break (e.g. someone might 'helpfully' inline <code>qSize</code> thinking it's clearer only to break the code completely) with fewer variables whereof to keep track. With a bit of LINQ, we can write (untested):</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>List&lt;int&gt; level = new List&lt;int&gt; { root };\nwhile (level.Count &gt; 0)\n{\n result.Add(level);\n level = level.Where(n =&gt; n.Children != null).SelectMany(n =&gt; n.children).ToList();\n}\n</code></pre>\n\n<p>There is virtually nothing to go wrong here apart from getting those 2 lines inside the loop the wrong way round. You don't need anything more complex unless performance is a real concern, or you want a lazy implementation, in which case you need to be careful you don't <code>yield</code> state you are about to access:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>List&lt;int&gt; level = new List&lt;int&gt; { root };\nwhile (level.Count &gt; 0)\n{\n var previous = level;\n level = previous.Where(n =&gt; n.Children != null).SelectMany(n =&gt; n.children).ToList();\n yield return previous;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T14:25:19.917", "Id": "219812", "ParentId": "219724", "Score": "3" } }, { "body": "<p>The algorithm can be rewritten to use <em>Linq</em> instead of a <em>Queue</em>.</p>\n\n<blockquote>\n<pre><code>public IList&lt;IList&lt;int&gt;&gt; LevelOrder(Node root)\n {\n IList&lt;IList&lt;int&gt;&gt; result = new List&lt;IList&lt;int&gt;&gt;();\n Queue&lt;Node&gt; Q = new Queue&lt;Node&gt;();\n ..\n</code></pre>\n</blockquote>\n\n<p>This increases readability. (At the cost of performance?) I use <code>IEnumerable</code> when mutation of the list is not required and <code>IList</code> otherwise.</p>\n\n<pre><code>public static IEnumerable&lt;IEnumerable&lt;int&gt;&gt; LevelOrder(Node root) \n{\n var valuesByBreadth = new List&lt;IEnumerable&lt;int&gt;&gt;();\n LevelOrder(new[] { root }, valuesByBreadth);\n return valuesByBreadth;\n}\n\nprivate static void LevelOrder(IEnumerable&lt;Node&gt; breadth, IList&lt;IEnumerable&lt;int&gt;&gt; valuesByBreadth) \n{\n if (breadth.Any()) {\n valuesByBreadth.Add(breadth.Select(x =&gt; x.val).ToList());\n LevelOrder(breadth.SelectMany(x =&gt; x.children), valuesByBreadth);\n }\n}\n</code></pre>\n\n<blockquote>\n <p>No-where in the spec is it said that a null input should produce a\n null output, and this is a design decision which needs to be\n documented. - VisualMelon</p>\n</blockquote>\n\n<p>I have asserted the children always be set. No need for boiler-plate <code>null</code> checks, at the expensive of slight <em>object creation</em> overhead.</p>\n\n<pre><code>public class Node\n {\n public int val;\n public IList&lt;Node&gt; children;\n\n public Node() {\n }\n\n public Node(int val, IList&lt;Node&gt; children) {\n this.val = val;\n this.children = children ?? new List&lt;Node&gt;();\n }\n }\n</code></pre>\n\n<p><em>test entrypoint</em> (I used a console app and debugged the results, but you are better of writing a unit test.)</p>\n\n<pre><code>public static void Main()\n {\n var node3 = new List&lt;Node&gt;();\n node3.Add(new Node(5, null));\n node3.Add(new Node(6, null));\n\n var node1 = new List&lt;Node&gt;();\n node1.Add(new Node(3, node3));\n node1.Add(new Node(2, null));\n node1.Add(new Node(4, null));\n\n var root = new Node(1, node1);\n var result = LevelOrder(root);\n\n Console.ReadKey();\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T21:36:24.920", "Id": "426014", "Score": "0", "body": "Thanks for the proposal. Linq at this level does not mean better readability in my opinion. And also under stress in job interview I would never write code like this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T21:52:39.043", "Id": "426015", "Score": "0", "body": "@Gilad It is probably a matter of personal preference and habits, I guess. To me, seeing a 'while' with nested 'for', nested 'if', nested 'foreach' takes me some time to get the feel of the flow. I'm probably no longer used to writing code with this many nested clauses." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T20:11:52.437", "Id": "220487", "ParentId": "219724", "Score": "2" } } ]
{ "AcceptedAnswerId": "219812", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T22:00:40.617", "Id": "219724", "Score": "1", "Tags": [ "c#", "programming-challenge", "breadth-first-search" ], "Title": "LeetCode: N-ary Tree Level Order Traversal" }
219724
<p>I just started using c# and I made this snake game in a console application . It is a bit jittery when i run it in visual studio. How could I improve it to be cleaner and less jittery.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Threading; namespace _2017project1 { class Program { const int SCREEN_MULT = 5; public const int SCREEN_W = 12 * SCREEN_MULT; public const int SCREEN_H = 5 * SCREEN_MULT; static void Main(string[] args) { var s = new Snake(); var f = new Fruit(); bool escape = false; InitGame(s, f); escape = Welcome(escape); while (!escape) { ResetGame(s, f); escape = PlayGame(s, f, escape); if (!escape) { escape = DoGameOver(s, escape); } } } static bool Welcome(bool escape) { ConsoleKeyInfo keyInfo; string[] Instructions = { "Welcome to the snake game", "Your goal is to collect the red fruit", "Use the arrow keys to move around", "Press esc to exit", "Press any key to begin" }; for (int i = 0; i &lt; Instructions.Count(); i++) { Console.SetCursorPosition((SCREEN_W / 2) - ((Instructions[i].Length / 2)), (SCREEN_H / 2) + i - (Instructions.Count() / 2)); Console.WriteLine(Instructions[i]); } if ((keyInfo = Console.ReadKey(true)).Key == ConsoleKey.Escape) { return true; } return false; } static void InitGame(Snake s, Fruit f) { Console.CursorVisible = false; Console.ForegroundColor = ConsoleColor.Green; Console.WindowHeight = SCREEN_H; Console.WindowWidth = SCREEN_W; } static bool PlayGame(Snake s, Fruit f, bool escape) { ConsoleKeyInfo keyInfo; Snake.ShowScore(s); while (true) { s.doGrow = false; Thread.Sleep(Convert.ToInt16(100 / s.speed)); Console.Clear(); if (Console.KeyAvailable == true) { keyInfo = Console.ReadKey(true); switch (keyInfo.Key) { case ConsoleKey.UpArrow: Snake.SetDir(0, -1, s); break; case ConsoleKey.DownArrow: Snake.SetDir(0, 1, s); break; case ConsoleKey.RightArrow: Snake.SetDir(1, 0, s); break; case ConsoleKey.LeftArrow: Snake.SetDir(-1, 0, s); break; case ConsoleKey.Escape: escape = true; return escape; } } Snake.Eat(s, f); Snake.Update(s); if (s.dead) { break; } Snake.ShowScore(s); Fruit.Show(f); Snake.Show(s); } return false; } static bool DoGameOver(Snake s, bool escape) { string[] Instructions = { "Game Over", "Score: " + s.score }; ConsoleKeyInfo keyInfo; for (int i = 0; i &lt; Instructions.Count(); i++) { Console.SetCursorPosition((SCREEN_W / 2) - ((Instructions[i].Length / 2)), (SCREEN_H / 2) + i - (Instructions.Count() / 2)); Console.WriteLine(Instructions[i]); } if (s.score &gt; s.highScore) { s.highScore = s.score; Console.SetCursorPosition((SCREEN_W / 2) - 7, (SCREEN_H / 2) + 2); Console.WriteLine("NEW HIGH SCORE!!!"); } Console.SetCursorPosition((SCREEN_W / 2) - 6, (SCREEN_H / 2) + 3); Console.WriteLine("Highscore: " + s.highScore); Thread.Sleep(3000); if (!escape) { Console.Clear(); Console.SetCursorPosition((SCREEN_W / 2) - 8, (SCREEN_H / 2) - 1); Console.WriteLine("Press esc to exit"); Console.SetCursorPosition((SCREEN_W / 2) - 12, (SCREEN_H / 2) + 1); Console.WriteLine("Or press any key play again"); if ((keyInfo = Console.ReadKey(true)).Key == ConsoleKey.Escape) { return true; } else { return false; } } return true; } static void ResetGame(Snake s, Fruit f) { Fruit.NewPosition(f, s); Snake.InitSnake(s); } } class Snake { const double SPEED_INCREMENT = 0.3; const int START_LENGTH = 10; const char SNAKE_CHAR = '@'; const ConsoleColor SNAKE_COLOUR = ConsoleColor.Green; public int x; public int y; public int xDir; public int yDir; public int score; public int highScore = 0; public double speed; public bool doGrow; public bool dead; public List&lt;int&gt; xPositions = new List&lt;int&gt;(); public List&lt;int&gt; yPositions = new List&lt;int&gt;(); public static void InitSnake(Snake s) { s.x = 9; s.y = 3; s.xDir = 1; s.yDir = 0; s.score = 0; s.speed = 1.2; s.doGrow = false; s.dead = false; s.xPositions.Clear(); s.yPositions.Clear(); for (int i = START_LENGTH - 1; i &gt;= 0; i--) { s.xPositions.Add(s.x - i); s.yPositions.Add(s.y); } } public static void SetDir(int x, int y, Snake s) { if (s.xDir != -x &amp;&amp; s.yDir != -y) { s.xDir = x; s.yDir = y; } } public static void Update(Snake s) { s.x = s.x + s.xDir; s.y = s.y + s.yDir; if (IsGameOver(s)) { s.dead = true; } s.xPositions.Add(s.x); s.yPositions.Add(s.y); if (!s.doGrow) { s.xPositions.RemoveAt(0); s.yPositions.RemoveAt(0); } } public static void Eat(Snake s, Fruit f) { if (s.x == f.x &amp;&amp; s.y == f.y) { s.speed = s.speed + SPEED_INCREMENT; s.score++; Fruit.NewPosition(f, s); s.doGrow = true; } } public static void Show(Snake s) { Console.ForegroundColor = ConsoleColor.Green; for (int i = 0; i &lt; s.xPositions.Count(); i++) { Console.SetCursorPosition(s.xPositions[i], s.yPositions[i]); Console.Write(SNAKE_CHAR); } } public static void ShowScore(Snake s) { Console.ForegroundColor = SNAKE_COLOUR; Console.SetCursorPosition(0, 0); Console.WriteLine("Score: " + s.score); } static bool IsGameOver(Snake s) { if (s.x &lt; 0 || s.x &gt; Program.SCREEN_W - 1 || s.y &lt; 0 || s.y &gt; Program.SCREEN_H - 1) { return true; } for (int i = 0; i &lt; s.xPositions.Count(); i++) { if (s.xPositions[i] == s.x &amp;&amp; s.yPositions[i] == s.y) { return true; } } return false; } } class Fruit { const ConsoleColor FRUIT_COLOUR = ConsoleColor.Red; const ConsoleColor BACK_COLOUR = ConsoleColor.Black; const int fruitPosBuffer = 2; public int x = 10; public int y = 10; public static void Show(Fruit f) { Console.SetCursorPosition(f.x, f.y); Console.BackgroundColor = FRUIT_COLOUR; Console.WriteLine(" "); Console.BackgroundColor = BACK_COLOUR; } public static void NewPosition(Fruit f, Snake s) { int newX; int newY; Random pos = new Random(); do { newX = pos.Next(fruitPosBuffer, Program.SCREEN_W - fruitPosBuffer); newY = pos.Next(fruitPosBuffer, Program.SCREEN_H - fruitPosBuffer); } while (ValidPos(f, s, newX, newY) == false); f.x = newX; f.y = newY; } static bool ValidPos(Fruit f, Snake s, int newX, int newY) { if (newX == f.x || newY == f.y) { return false; } if (s.xPositions.Contains(newX) || s.yPositions.Contains(newY)) { return false; } else { return true; } } } } </code></pre>
[]
[ { "body": "<p>In your main game loop, rather than call <code>Console.Clear()</code> and repainting all your content (which can cause some flicker), just update the previous frame with any changes. This means that initially you'll want to draw everything, but after that you only need to update stuff when it changes. When the fruit moves, erase the old position (unless it is covered by the snake) and draw it in the new one. When the snake is updated, erase from the old location and draw it in the new. If you can have multiple things occupying the same space, then this can be easier to implement if you erase anything that is moving, then redraw the entire screen (since you won't have to consider what to erase a part of the screen with).</p>\n\n<p>Your jerkiness is probably because you call <code>Thread.Sleep</code> with a fixed interval. The actual interval will be the sleep time plus however long it takes to run the rest of the code in your game loop plus variation in the exact duration of the Sleep. Consider using <code>System.Environment.GetTickCount()</code> in the duration calculation. You'd call that right after the sleep ends, save it in a variable (properly initialized before the loop), then the sleep duration would be your current time minus the elapsed time (another call to GetTickCount() minus the previous value), checking for overflow (duration less than 0). Also, the sleep is better positioned at the end of the game loop, rather than the beginning (as you'll get a sleep before the first draw of the game screen with what you have).</p>\n\n<p>In your <code>Fruit</code> class, create a member variable to hold your <code>Random</code> generator. Your current code creates a new one, with a new seed, every time you need a new fruit, which can create less-than-random results if it is called too frequently.</p>\n\n<p>Consider creating a <code>Point</code> class to hold X and Y values.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T04:41:01.343", "Id": "424398", "Score": "0", "body": "Oh no, the [documentation](https://docs.microsoft.com/en-us/dotnet/api/system.random.-ctor?view=netframework-4.8#System_Random__ctor) indeed mention that the seed of the random number generator is solely based on the system time." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T01:06:56.273", "Id": "219730", "ParentId": "219726", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-04T23:41:33.187", "Id": "219726", "Score": "4", "Tags": [ "c#", "beginner", "object-oriented", "console" ], "Title": "Beginner c# snake game" }
219726
<p>Ok, so I have been looking for resources on how to make a registration form work with input validation. I want the error message show up under the table of the registration form and not on top of the website. Here is what I have working so far, but I am still learning and I would like to improve:</p> <pre><code>&lt;?php $host = 'localhost'; $user = 'root'; $pass = ''; $db = 'restaurantdb'; try { $db_conn = new mysqli("$host", "$user", "$pass", "$db"); $db_conn-&gt;set_charset("utf8"); } catch (Exception $e) { echo "Connection failed: " . $e-&gt;getMessage(); } if (isset($_POST['register'])) { session_start(); $forename = filter_input(INPUT_POST, 'forename', FILTER_SANITIZE_STRING); $surname = filter_input(INPUT_POST, 'surname', FILTER_SANITIZE_STRING); $username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING); $password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING); $age = filter_input(INPUT_POST, 'age', FILTER_SANITIZE_STRING); $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING); $password = password_hash($password, PASSWORD_BCRYPT); if(FindErrors($username, $password)) { $query = "INSERT INTO users(firstname, lastname, username, password, age, email) VALUES('$forename', '$surname', '$username', '$password', '$age', '$email')"; $result = $db_conn-&gt;query($query); if(!empty($result)) { $error_message = ""; $success_message = "Registration successful"; unset($_POST); } else die($db_conn-&gt;error); } } $forename = $surname = $username = $password = $age = $email = ""; function FindErrors($username, $password){ if (empty($forename)) { echo "First name is required\n"; } else { $forename = fix_string($_POST["forename"]); } if (empty($surname)) { echo "Last name is required\n"; } else { $surname = fix_string($_POST["surename"]); } if (empty($username)) { echo "Username is required\n"; return false; } else { $password = fix_string($_POST["username"]); } if (empty($password)) { echo "Password is required\n"; return false; } else { $password = fix_string($_POST["password"]); } if (empty($age)) { echo "Age is required\n"; } else { $age = fix_string($_POST["age"]); } if (empty($email)) { echo "Email is required\n"; } else { $email = fix_string($_POST["email"]); } } $fail = validate_forename($forename); $fail .= validate_surname($surname); $fail .= validate_username($username); $fail .= validate_password($password); $fail .= validate_age($age); $fail .= validate_email($email); echo "&lt;!DOCTYPE html\n&lt;html&gt;&lt;head&gt;&lt;title&gt;An Example Form&lt;/title&gt;"; if ($fail == "") { echo "&lt;/head&gt;&lt;body&gt;Form data successfully validated: $forename, $surname, $username, $password, $age, $email.&lt;/body&gt;&lt;/html&gt;"; // This is where you would enter the posted fields into a database. // Preferably using hash encryption for the password. exit; } echo &lt;&lt;&lt;END_OF_BLOCK &lt;!--THIS IS HTML/JAVASCRIPT SECTION --&gt; &lt;style&gt; .signup { border: 1px solid #999999; font: normal 14px helvetica; color: #444444 } &lt;/style&gt; &lt;script&gt; function validate(form) { fail = validateForename(form.forename.value) fail += validateSurname(form.surname.value) fail += validateUsername(form.username.value) fail += validatePassword(form.password.value) fail += validateAge(form.age.value) fail += validateEmail(form.email.value) if (fail == "") return true else { alert(fail); return false } } function validateForename(field) { return (field == "") ? "No forename was entered.\n" : "" } function validateSurname(field) { return (field == "") ? "No surname was entered.\n" : "" } function validateUsername(field) { if (field == "") return "No Username was entered.\n" else if (field.length &lt; 5) return "Usernames must be at least 5 characters.\n" else if (/[^a-zA-Z0-9_-]/.test(field)) return "Only a-z, A-Z, 0-9, - and _ allowed in Usernames.\n" return "" } function validatePassword(field) { if (field == "") return "No password was entered.\n" else if (field.length &lt; 6) return "Passwords must be at least 6 characters.\n" else if (!/[a-z]/.test(field)) || !/[A-Z]/.test(field) || !/[0-9]/.test(field)) return "Passwords require one each of a-z, A-Z and 0-9.\n" return "" } function validateAge(field) { if (field == "" || isNaN(field)) return "No age was entered.\n" else if (field &lt; 18 || field &gt; 110) return "Age must be between 18 and 110.\n" return "" } function validateEmail(field) { if (field == "") return "No email was entered.\n" else if (!((field.indexOf(".") &gt; 0) &amp;&amp; (field.indexOf("@") &gt; 0) || /[^a-zA-Z0-9.@_-]/.test(field))) return "The Email address is invalid.\n" return "" } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;header&gt; &lt;h1&gt;Sun Sun Chinese Restuarant&lt;/h1&gt; &lt;/header&gt; &lt;nav&gt; &lt;hr /&gt; &lt;a href="index.html"&gt;Home&lt;/a&gt; &lt;a href="menu.html"&gt;Menu&lt;/a&gt; &lt;a href="contactus.html"&gt;Contact Us&lt;/a&gt; &lt;a href="validate.html"&gt;Sign Up&lt;/a&gt; &lt;hr /&gt; &lt;/nav&gt; &lt;table class="signup" border="0" cellpadding="2" cellspacing="5" bgcolor="#eeeeee"&gt; &lt;th colspan="2" align="center"&gt;Signup Form&lt;/th&gt; &lt;form method="post" action="adduser.php" onsubmit="return validate(this)"&gt; &lt;tr&gt; &lt;td&gt;Forename&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="30" name="forename" value="" required&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Surname&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="30" name="surname" value="" required&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Username&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="30" name="username" value="" required&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Password&lt;/td&gt; &lt;td&gt;&lt;input type="password" maxlength="30" name="password" value="" required&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Age&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="6" name="age" value="" required&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Email&lt;/td&gt; &lt;td&gt;&lt;input type="text" maxlength="60" name="email" value="" required&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="2" align="center"&gt;&lt;input type="submit" name="register" value="Signup"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/form&gt; &lt;/table&gt; &lt;!-----DISPLAY ERROR OR SUCCESS MESSAGE HERE------&gt; &lt;/body&gt; &lt;footer&gt; &lt;!-- The footer is a block at the bottom of the page. --&gt; &lt;hr /&gt; &lt;center&gt; &lt;p&gt; 5301 Forest Lane&lt;br /&gt; St. Louise, MS 35012&lt;br /&gt; 204-462-4296 &lt;/p&gt; &lt;/center&gt; &lt;/footer&gt; &lt;/html&gt; END_OF_BLOCK; //THE PHP Functions function validate_forename($field) { return ($field == "") ? "No Forename was entered&lt;br&gt;": ""; } function validate_surname($field) { return ($field == "") ? "No Surname was entered&lt;br&gt;" : ""; } function validate_username($field) { if ($field == "") return "No Username was entered&lt;br&gt;"; else if (strlen($field) &lt; 5) return "Usernames must be at least 5 characters&lt;br&gt;"; else if (preg_match("/[^a-zA-Z0-9_-]/", $field)) return "Only letters, numbers, numbers, - and _ in usernames&lt;br&gt;"; return ""; } function validate_password($field) { if ($field == "") return "No Password was entered&lt;br&gt;"; else if (strlen($field) &lt; 6) return "Passwords must be at least 6 characters&lt;br&gt;"; else if (!preg_match("/[a-z]/", $field) || !preg_match("/[A-Z]/", $field) || !preg_match("/[0-9]/", $field)) return "Passwords require 1 each of a-z, A-Z, and 0-9&lt;br&gt;"; return ""; } function validate_age($field) { if ($field == "") return "No age was entered&lt;br&gt;"; else if ($field &lt; 18 || $field &gt; 110) return "Age must be between 18 and 110&lt;br&gt;"; return ""; } function validate_email($field) { if ($field == "") return "No Email was entered&lt;br&gt;"; else if (!((strpos($field, ".") &gt; 0) &amp;&amp; (strpos($field, "@") &gt; 0)) || preg_match("/[^a-zA-Z0-9.@_-]/", $field)) return "The email address is invalid&lt;br&gt;"; return ""; } function fix_string($string) { if (get_magic_quotes_gpc()) $string = stripslashes($string); return htmlentities ($string); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T16:06:57.703", "Id": "424468", "Score": "1", "body": "`FindErrors()` will not work as you expect it to because of \"function scope\". For instance, `$forename` will always be `empty` because that variable does not exist inside the function. Your code is broken, you just don't realize it yet. Consider `function FindErrors($username, $password){` to be interpretted as `function FindErrors($param1, $param2){` ...it won't know what variable you are passing to it." } ]
[ { "body": "<p>There are many improvements you could make, but you're on the right track. In this answer I will only comment on some of the things I immediately notice.</p>\n\n<h2>Coding style</h2>\n\n<p>It is difficult to get an overview of your code. There's <strong>little organization</strong>. I would have split this code up into multiple files. For instance: There will be more PHP files on your server that need the database. Having a separate PHP file that opens the database, and can be included into this one, would help and you would only need to change the database access parameters in one place. Same is true for CSS and Javascript.</p>\n\n<p>Use <strong>indentation</strong> to make your code more readable. See the <a href=\"https://phptherightway.com/#code_style_guide\" rel=\"nofollow noreferrer\">code style guides</a>.</p>\n\n<h2>Handling errors</h2>\n\n<p>If your database connection fails, you do catch the exception to echo a message, but then you just go on as if nothing has happened. What's the point of that? The same is true for the <code>FindErrors()</code> function. It echos after a form submission, but that's all it does. <strong>It just carries on</strong> and gets your code into real trouble.</p>\n\n<h2>User input</h2>\n\n<p>You filter user input at the beginning of your script, that is a good idea. However, it is still user input and should be treated with extra care. It is quite likely you will forget about this, now that you've dumped this input into normal PHP variables. Better put them in an array like <code>$userInput</code> or prefix the names like so: <code>$input_forename</code>. That way you remember to <strong>treat user input with care</strong>.</p>\n\n<p>Another problem in <code>FindErrors()</code> is that you directly access <code>$_POST</code>. What's the point of all the input filtering at the beginning? Don't do this, use the variables, or the array, you created at the beginning.</p>\n\n<p>Do not <code>filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);</code> the password. It could remove things from the password that an user intended to have there. It's a password, the content can be anything and doesn't need filtering.</p>\n\n<h2>Don't repeat yourself</h2>\n\n<p>You've implemented the same validation functions in PHP and in Javascript. I can understand why, but it does feel like <strong>duplication of functionality</strong>. I don't have a quick solution at hand, that would require long code examples, but try to avoid this. See: <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a></p>\n\n<h2>Database</h2>\n\n<p><strong>Do not store plain-text passwords</strong> in a database. See: <a href=\"http://blog.moertel.com/posts/2006-12-15-never-store-passwords-in-a-database.html\" rel=\"nofollow noreferrer\">Never store passwords in a database!</a>. <a href=\"https://php.net/manual/en/faq.passwords.php\" rel=\"nofollow noreferrer\">Store a hash</a> of the password, see: <a href=\"https://php.net/manual/en/function.password-hash.php\" rel=\"nofollow noreferrer\">password_hash()</a>.</p>\n\n<p>An obvious security problem is that your database query is open to <a href=\"https://en.wikipedia.org/wiki/SQL_injection\" rel=\"nofollow noreferrer\">SQL injection attacks</a>. Use <a href=\"https://websitebeaver.com/prepared-statements-in-php-mysqli-to-prevent-sql-injection\" rel=\"nofollow noreferrer\">prepared statements</a> instead. This is <strong>by far the most common problem</strong> we see, and it is actively exploited (because many developers can't be bothered).</p>\n\n<h2>Finally</h2>\n\n<p>That's my list so far. This is not a complete code review. I haven't given proper advice on how the code could be rewritten. Nevertheless I hope there are some useful tips here for you.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-08T15:15:37.037", "Id": "443357", "Score": "0", "body": "To be honest, I do not know why I would want to use the duplicate of the same functionality of php in javascript, why would I want to do that? Is one language better than the other? Wouldn't I be better off removing php code and use the javascript instead? I was following an example, but I did not know why." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-08T21:59:20.783", "Id": "443396", "Score": "0", "body": "@AlejandroH I never said you should duplicate functionality in various languages. I was talking about problems with the coding style, and I meant to say that the same solutions apply to other languages as well. More so, further on I talk about the DRY principle, which says: Do not repeat yourself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-09T22:19:48.233", "Id": "443496", "Score": "0", "body": "Basically, what I am trying to say is that I know I shouldnt repeat myself. Does that mean I would be fine removing javascript code? Shouldnt I just be coding in PHP only and if I am going to code in PHP, and if javascript just code in javascript?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-10T07:51:36.080", "Id": "443528", "Score": "0", "body": "No, most of the time you would use a combination of PHP and Javascript. PHP runs on the server, it has direct access to databases and other server resources. Javascripts runs (normally) in the browser, it can respond quickly to user actions, and manipulate the [DOM](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction). Both have their strengths and you should take advantage of these. What you should try to avoid is implementing the same functionality in PHP and Javascript. That's just unnecessary and complicates any future work on the code." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T11:25:25.900", "Id": "219747", "ParentId": "219728", "Score": "1" } }, { "body": "<p>To add onto KIKO's answer, you are on the right track.</p>\n\n<p>Ultimately there is quite a bit you can change and there's a ton I would fix myself. But I'm not going to re-write the whole thing for you. Hopefully these pointers will help you move in the right direction.</p>\n\n<p>First things first lets answer your question:</p>\n\n<h1>Your Question</h1>\n\n<blockquote>\n <p>How do you put the message below the table?</p>\n</blockquote>\n\n<p>Quite easy actually. You can re-open PHP below that table and echo a variable or message. Right now you have: </p>\n\n<pre><code>if (empty($forename)) {\n echo \"First name is required\\n\";\n} else {\n $forename = fix_string($_POST[\"forename\"]); \n}\n</code></pre>\n\n<p>Instead what you can do is store that error message in a variable</p>\n\n<pre><code>if (empty($forename)) {\n $error = \"First name is required\\n\";\n // You could also unset the variable here too- Not necessary but good for memory clean up\n unset($forename);\n} else {\n $forename = fix_string($_POST[\"forename\"]); \n}\n</code></pre>\n\n<p>then below your table</p>\n\n<pre><code>&lt;?php\nif($error){\n echo $error\n}\n?&gt;\n</code></pre>\n\n<p>With that you can also switch from the empty function to an exclamation mark operator</p>\n\n<pre><code>if(!$forename){\n// error\n}else{\n// Good to go\n}\n</code></pre>\n\n<h2>Now let's get a bit more advanced</h2>\n\n<p>Instead of storing each error in an individual variable, create an array for errors </p>\n\n<p><code>$err = [];</code></p>\n\n<p>Then inside each if statement you can add that message to that array</p>\n\n<p><code>$err[] = \"Some Error\";</code></p>\n\n<p>And below your table use an iterator to get all of the values from that array</p>\n\n<pre><code>foreach($err as $key){\n echo $key;\n}\n</code></pre>\n\n<p>Of course before you do any iteration, check to see if that array even has anything, you can achieve this by using the count function. </p>\n\n<pre><code>$num = count($err);\nif ($num &gt; 0 ){\n // Iterate\n}\n</code></pre>\n\n<h1>Session Start</h1>\n\n<p>First thing you have to change is where you're calling <code>session_start</code> take that and put it right at the very very top. In a vast majority of cases you should have it at the top before anything else. Only when using say for example an login with AJAX. But lets not get to ahead of ourselves. </p>\n\n<h1>Password</h1>\n\n<p>Same thing that KIKO said, you don't need to filter your password, at the very least change the 3rd parameter in it to <code>FILTER_UNSAFE_RAW</code> or just remove it - because you're hashing it there is no chance for a user to do anything. I know you've been taught and told several times to filter ALL inputs, this is the one and only exception to that rule. Once a password is hashed there's nothing left that PHP will mistake for code.</p>\n\n<h1>Functions</h1>\n\n<p>Should be declared before you try to use them. I'm not sure why they are at the bottom of your document, they should be at the top with all the other PHP. Not sure if you just pasted those in from an include file at the bottom just so they were there? If its a separate file just start a new code block with the little tilde's ```</p>\n\n<h1>Finishing Up</h1>\n\n<p>I think I covered everything that you were mainly asking. Like I said there a lot I would personally change. Hopefully that helps though. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-06T22:15:48.760", "Id": "227606", "ParentId": "219728", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T00:33:46.547", "Id": "219728", "Score": "3", "Tags": [ "php", "html", "mysql" ], "Title": "Php registration form input is required validation" }
219728
<h2>Background</h2> <p>A <a href="https://en.wikipedia.org/wiki/Force_field_(chemistry)" rel="nofollow noreferrer">forcefield</a> is a collection of functions and parameters that is used to calculate the potential energy of a complex system. I have text files which contain data about the parameters for a forcefield. The text file is split into many sections, with each section following the same format:</p> <ul> <li>A section header which is enclosed in square brackets </li> <li>On the next line the word <code>indices:</code> followed by a list of integers. </li> <li>This is then followed by 1 or more lines of parameters associated with the section </li> </ul> <p>Here is a made-up example file to showcase the format.</p> <pre><code>############################################ # Comments begin with '#' ############################################ [lj_pairs] # Section 1 indices: 0 2 # ID eps sigma 1 2.344 1.234 5 2 4.423 5.313 5 3 1.573 6.321 5 4 1.921 11.93 5 [bonds] indices: 0 1 2 4.234e-03 11.2 6 -0.134545 5.7 </code></pre> <p>The goal is to parse such files and store all of the information in a <code>dict</code>.</p> <hr> <h2>Code</h2> <p>Main function for review</p> <pre><code>""" Force-field data reader """ import re from dataclasses import dataclass, field from typing import Dict, Iterable, List, TextIO, Tuple, Union, Any def ff_reader(fname: Union[str, TextIO]) -&gt; Dict[str, "FFSections"]: """ Reads data from a force-field file """ try: if _is_string(fname): fh = open(fname, mode="r") own = True else: fh = iter(fname) except TypeError: raise ValueError("fname must be a string or a file handle") # All the possible section headers keywords = ("lj_pairs", "bonds") # etc... Long list of possible sections # Removed for brevity re_sections = re.compile(r"^\[(%s)\]$" % "|".join(keywords)) ff_data = _strip_comments(fh) # Empty dict that'll hold all the data. final_ff_data = {key: FFSections() for key in keywords} # Get first section header for line in ff_data: match = re.match(re_sections, line) if match: section = match.group(1) in_section_for_first_time = True break else: raise FFReaderError("A valid section header must be the first line in file") else: raise FFReaderError("No force-field sections exist") # Read the rest of the file for line in ff_data: match = re.match(re_sections, line) # If we've encounted a section header the next line must be an index list. if in_section_for_first_time: if line.split()[0] != "indices:": raise FFReaderError(f"Missing index list for section: {section}") idx = _validate_indices(line) final_ff_data[section].use_idx = idx in_section_for_first_time = False in_params_for_first_time = True continue if match and in_params_for_first_time: raise FFReaderError( f"Section {section} missing parameters" + "Sections must contain atleast one type coefficients" ) if match: # and not in_section_for_first_time and in_params_for_first_time section = match.group(1) in_section_for_first_time = True continue params = _validate_params(line) final_ff_data[section].coeffs.update([params]) in_params_for_first_time = False # Close the file if we opened it if own: fh.close() for section in final_ff_data.values(): # coeff must exist if use_idx does if section.use_idx is not None: assert section.coeffs return final_ff_data </code></pre> <p>Other stuff for the code to work</p> <pre><code>def _strip_comments( instream: TextIO, comments: Union[str, Iterable[str], None] = "#" ) -&gt; Iterable[str]: """ Strip comments from a text IO stream """ if comments is not None: if isinstance(comments, str): comments = [comments] comments_re = re.compile("|".join(map(re.escape, comments))) try: for lines in instream.readlines(): line = re.split(comments_re, lines, 1)[0].strip() if line != "": yield line except AttributeError: raise TypeError("instream must be a `TextIO` stream") from None @dataclass(eq=False) class FFSections: """ FFSections(coeffs,use_idx) Container for forcefield information """ coeffs: Dict[int, List[float]] = field(default_factory=dict) use_idx: List[int] = field(default=None) class FFReaderError(Exception): """ Incorrect or badly formatted force-Field data """ def __init__(self, message: str, badline: Optional[str] = None) -&gt; None: if badline: message = f"{message}\nError parsing --&gt; ({badline})" super().__init__(message) def _validate_indices(line: str) -&gt; List[int]: """ Check if given line contains only a whitespace separated list of integers """ # split on indices: followed by whitescape split = line.split("indices:")[1].split() # import ipdb; ipdb.set_trace() if not set(s.isdecimal() for s in split) == {True}: raise FFReaderError( "Indices should be integers and seperated by whitespace", line ) return [int(x) for x in split] def _validate_params(line: str) -&gt; Tuple[int, List[float]]: """ Check if given line is valid param line, which are an integer followed by one or more floats seperated by whitespace """ split = line.split() id_ = split[0] coeffs = split[1:] if not id_.isdecimal(): raise FFReaderError("Invalid params", line) try: coeffs = [float(x) for x in coeffs] except (TypeError, ValueError): raise FFReaderError("Invalid params", line) from None return (int(id_), coeffs) </code></pre> <hr> <p>I consider myself a beginner in python and this is my first substantive project. I'd like the review to focus on the <code>ff_reader</code> function, but feel free to comment on the other parts too if there are better ways to do somethings. I feel like the way I've written the <code>ff_reader</code> is kind of ugly and inelegant. I'd be especially interested if there is a better way to read such files, perhaps parsing the whole file instead of line by line.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T05:11:31.163", "Id": "424399", "Score": "0", "body": "What does the 5 in the lj_pairs section mean? It doesn't have a column label." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T05:36:29.867", "Id": "424400", "Score": "0", "body": "For this particular example, it is the cut-off distance beyond which the Lennard-Jones potential is 0. I don't think the physical meaning of the values is relevant here but if it is needed I can provide additional context. Also, I just made these values up they don't correspond to any real systems." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T06:04:53.763", "Id": "424401", "Score": "0", "body": "Thanks. You're right that the physical meaning is not relevant here. I was just missing the name of the column, since the other columns are named so nicely." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T09:06:56.533", "Id": "424412", "Score": "0", "body": "Possible duplicate of - https://codereview.stackexchange.com/questions/219740/parsing-parameters-for-a-potential-function" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T07:01:00.680", "Id": "424537", "Score": "0", "body": "It was a verbatim copy of both your code and your question. So in that sense, yes there can be duplicate questions here. Although usually this happens because someone posts their question again because they have become impatient about not having received an answer yet or people having created an account here after having their question migrated here and getting confused and manually asking the question again. Follow-up questions after having received some answer are perfectly fine (and not duplicates) if something changed in your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T17:03:23.860", "Id": "424623", "Score": "1", "body": "@Graipher huh thanks, that is very weird, especially considering someone else said that they saw my question on SO. I'm pretty sure I just made an account here and posted the question. I have no idea how I could have posted it multiple times." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T17:04:35.103", "Id": "424624", "Score": "0", "body": "@voidlife It was from a different account. Otherwise you probably would have gotten recommendations on how to merge your two accounts ;)" } ]
[ { "body": "<p>I have written parsers for several similar file formats, and one time I started with the same idea as you: iterate over the lines and record the current state in some boolean variables. Over time, these parsers got too large to understand. Therefore I switched to a different strategy: instead of recording the current state in variables, record it implicitly in the code that is currently executed. I structured the parser like this:</p>\n\n<pre><code>def parse_file(lines: Lines):\n sections = []\n while not lines.at_end():\n section = parse_section(lines)\n if section is None:\n break\n sections.append(section)\n return sections\n\ndef parse_section(lines: Lines):\n name = lines.must_match(r\"^\\[(\\w+)\\]$\")[1]\n indices_str = lines.must_match(r\"\\s*indices:\\s*(\\d+(\\s*\\d+))$\")[1]\n data = []\n\n while not lines.at_end():\n row = parse_row(lines)\n if row is None:\n break\n data.append(row)\n\n indices = map(int, indices_str.split())\n return Section(name, indices, data)\n</code></pre>\n\n<p>As you can see, each part of the file structure gets its own parsing function. Thereby the code matches the structure of the file format. Each of the functions is relatively small.</p>\n\n<p>To make these functions useful, they need a source of lines, which I called <code>Lines</code>. This would be another class that defines useful function such as <code>must_match</code>, which makes sure the \"current line\" matches the regular expression, and if it doesn't, it throws a parse error. Using these functions as building blocks, writing and modifying the parser is still possible, even when the file format becomes more complicated.</p>\n\n<p>Another benefit of having these small functions is that you can test them individually. Prepare a Lines object, pass it to the function and see what it returns. This allows for good unit tests.</p>\n\n<p>The <code>Lines</code> class consists of a list of lines and the index of the current line. As you parse the file, the index will advance, until you reach the end of the lines.</p>\n\n<hr>\n\n<p>Regarding your code:</p>\n\n<p>I don't like the union types very much. They make the code more complicated than necessary. For example, when stripping the comments, you actually only need the single comment marker <code>#</code>. Therefore all the list handling can be removed, and the comment character doesn't need to be a parameter at all.</p>\n\n<p>Stripping the comments at the very beginning is a good strategy since otherwise you would have to repeat that code in several other places.</p>\n\n<p>In that comment removal function you declared that the comment may also be <code>None</code>, but actually passing <code>None</code> will throw an exception.</p>\n\n<p>Be careful when opening files. Every file that is opened must be closed again when it is not needed anymore, even in case of exceptions. Your current code does not close the file when a parse error occurs. This is another reason against union types. It would be easier to have separate functions: one that parses from a list of strings and one that parses from a file. How big are the files, does it hurt to load them into memory as a single block? If they get larger than 10 MB, that would be a valid concern.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T16:30:04.543", "Id": "424471", "Score": "0", "body": "Thank you for the review. Recording the current state in some boolean variables is exactly what seemed messy to me but I'm not quite sure I follow your alternative approach especially how the current state is recorded implicitly. Are saying that instead of parsing it line by line, I should try to parse an entire `section` as a whole? Or each part should get it's own function like `parse_name`, `parse_indices` and `parse_data` etc. I'm not sure how this will implicitly record the current state or have mis-understood and it is the `lines` object that somehow records the state? ...." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T16:36:38.197", "Id": "424473", "Score": "0", "body": "You're right that I don't need any other marker than `#`, I made it a parameter because I was worried that someone might decide to use something else as comments in the future. I thought I'd be easier to make it a parameter rather than change the function. The files are typically just 5-8MB so I guess I could load them into memory. But to fix the files not closing if there is an exception, should I add a `finally` block after every `try`? or use a context manager?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T16:47:55.447", "Id": "424478", "Score": "0", "body": "You're right, I didn't write the part about the \"implicit\" state clear enough. By this implicit state I mean: instead of having a boolean variable that saves the state, the code itself contains this information already. If the computer is currently executing the `while not lines.at_end()`, you already know what the current state is: the parser is either at the beginning of the file, or it just finished a section. +++ Regarding the `parse_name`: you could do that, or if it is simple enough, just leave it as the one-liner like in the code I suggested. That's up to you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T16:51:15.643", "Id": "424479", "Score": "0", "body": "Regarding the `try … finally`: It's really difficult with your current code since sometimes you need to close the stream and sometimes you don't. The easiest way of closing files is by using the `with` statement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T16:53:03.400", "Id": "424481", "Score": "0", "body": "Ah ok, I see what you mean now. Thank you!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T05:57:00.170", "Id": "219734", "ParentId": "219729", "Score": "3" } }, { "body": "<p>See, I saw your question on StackOverflow the other day before it was moved here but thought to answer nevertheless. </p>\n\n<p>Imo, the way to go is to write yourself a grammar/parser and a <code>NodeVisitor</code> class. This is formulate little parts in a first step and then glue them all together afterwards.</p>\n\n<pre><code>from parsimonious.grammar import Grammar\nfrom parsimonious.nodes import NodeVisitor\n\ndata = \"\"\"\n############################################\n# Comments begin with '#'\n############################################\n\n[lj_pairs] # Section 1\n indices: 0 2\n# ID eps sigma\n 1 2.344 1.234 5\n 2 4.423 5.313 5\n 3 1.573 6.321 5\n 4 1.921 11.93 5\n\n[bonds]\nindices: 0 1\n 2 4.234e-03 11.2\n 6 -0.134545 5.7\n\"\"\"\n\ngrammar = Grammar(\n r\"\"\"\n expr = (entry / garbage)+\n entry = section garbage indices (valueline / garbage)*\n section = lpar word rpar\n\n indices = ws? \"indices:\" values+\n garbage = ((comment / hs)* newline?)*\n\n word = ~\"\\w+\"\n\n values = float+\n valueline = values newline?\n\n float = hs? ~\"[-.e\\d]+\" hs?\n\n lpar = \"[\"\n rpar = \"]\"\n\n comment = ~\"#.+\"\n ws = ~\"\\s*\"\n hs = ~\"[\\t\\ ]*\"\n\n newline = ~\"[\\r\\n]\"\n \"\"\"\n)\n\ntree = grammar.parse(data)\n\nclass DataVisitor(NodeVisitor):\n def generic_visit(self, node, visited_children):\n return visited_children or node\n\n def visit_int(self, node, visited_children):\n _, value,_ = visited_children\n return int(value.text)\n\n def visit_float(self, node, visited_children):\n _, value, _ = visited_children\n return value.text\n\n def visit_section(self, node, visited_children):\n _, section, _ = visited_children\n return section.text\n\n def visit_indices(self, node, visited_children):\n *_, values = visited_children\n return values[0]\n\n def visit_valueline(self, node, visited_children):\n values, _ = visited_children\n return values\n\n def visit_garbage(self, node, visited_children):\n return None\n\n def visit_entry(self, node, visited_children):\n section, _, indices, lst = visited_children\n values = [item[0] for item in lst if item[0]]\n\n return (section, {'indices': indices, 'values': values})\n\n def visit_expr(self, node, visited_children):\n return dict([item[0] for item in visited_children if item[0]])\n\nd = DataVisitor()\nout = d.visit(tree)\nprint(out)\n</code></pre>\n\n<p>Which will yield</p>\n\n<pre><code>{\n 'lj_pairs': {'indices': ['0', '2'], 'values': [['1', '2.344', '1.234', '5'], ['2', '4.423', '5.313', '5'], ['3', '1.573', '6.321', '5'], ['4', '1.921', '11.93', '5']]}, \n 'bonds': {'indices': ['0', '1'], 'values': [['2', '4.234e-03', '11.2'], ['6', '-0.134545', '5.7']]}\n}\n</code></pre>\n\n<p>If you - or anybody else - are interested, I'd add some explanation as well.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T14:49:38.703", "Id": "424603", "Score": "0", "body": "This would be a great answer on SO, is there anyway you can address the users code to improve it as well as suggesting an alternate implementation. Keep in mind we review code here and don't provide how to answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T17:04:56.560", "Id": "424625", "Score": "0", "body": "Thanks for the answer. I'm not familiar with `parsimonious` so I'd be more than grateful for an explanation especially as this seems somewhat cleaner. If you can't reformulate the answer to be more in line with CR standards. I can ask the same question on SO (if I can modify to be in line for SO) and you can answer there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T17:38:57.383", "Id": "424633", "Score": "0", "body": "@voidlife: Post it on `SO`, add the link here and I'd add some explanation then." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T19:38:34.993", "Id": "424645", "Score": "0", "body": "@Jan sorry, was a bit busy. Posted it on [here](https://stackoverflow.com/questions/56011353/) on SO" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T12:53:36.930", "Id": "219808", "ParentId": "219729", "Score": "1" } } ]
{ "AcceptedAnswerId": "219734", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T00:54:56.537", "Id": "219729", "Score": "5", "Tags": [ "python", "python-3.x", "parsing" ], "Title": "Parsing parameters for a potential function" }
219729
<p>In the picture below, I want to open a modal when a user clicks anywhere within in the yellow block, including if they click on the white ‘+’ sign. The problem is, the click event happens on a different target depending on whether the user clicks on the yellow portion, or on the white ‘+’ sign.</p> <p>In my JavaScript code, I have been handing it like this so far, but I wonder if there is a better, shorter way of doing this that doesn’t require the II operator:</p> <pre><code>function openModal(e) { if (e.target.classList.contains('project-box__picture-box') || e.target.classList.contains('project-box__icon')) { modalEl.classList.add('open'); } } </code></pre> <p><a href="https://i.stack.imgur.com/iL1YL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iL1YL.png" alt="DOM Events"></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T01:36:12.943", "Id": "424390", "Score": "1", "body": "Welcome to code review! When posting code for review it helps to Add a relevant language tag (similar to your DOM tag)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T03:02:01.503", "Id": "424392", "Score": "1", "body": "Welcome to Code Review! So that we can give you proper advice, please include your HTML as well. (Press Ctrl-M in the question editor to make a live demo.)" } ]
[ { "body": "<p>I can give you two ways to approach this: via JavaScript or CSS.</p>\n<h1>JavaScript</h1>\n<p>You can use the <code>.closest()</code> method of the <code>HTMLElement</code> interface. You need to pass it a CSS selector, and it will find you the closest DOM ancestor of the element that matches the given selector, or <code>null</code> if no such ancestor was found.</p>\n<p>In this case, you could use it like this:</p>\n<pre><code>function openModal(e) {\n if (e.target.closest('.project-box__picture-box')) {\n modalEl.classList.add('open');\n }\n}\n</code></pre>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/closest\" rel=\"nofollow noreferrer\">(full method reference here)</a></p>\n<h1>CSS</h1>\n<p>The other option is to use the <code>pointer-events</code> CSS property. If you set this to <code>none</code> on all elements inside the clickable box, then those elements will not be allowed to be the targets of mouse events; instead, the target will be the closest ancestor that has pointer events enabled.</p>\n<p>In this case, you'd need to add this CSS:</p>\n<pre><code>.project-box__picture-box * {\n pointer-events: none;\n}\n</code></pre>\n<p>And this JS:</p>\n<pre><code>function openModal(e) {\n if (e.target.classList.contains('project-box__picture-box')) {\n modalEl.classList.add('open');\n }\n}\n</code></pre>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events\" rel=\"nofollow noreferrer\">(full property reference here)</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T15:19:43.417", "Id": "219750", "ParentId": "219731", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T01:27:37.040", "Id": "219731", "Score": "1", "Tags": [ "javascript", "event-handling", "dom" ], "Title": "Targeting only 1 event in DOM" }
219731
<p>To get a better handle and understanding of how bitfields, unions, and the byte alignment of structures work, I'm simulating a template Register structure.</p> <p>The requirements of my Register are as follows:</p> <ul> <li>Default size or width of a register is 8 bits or 1 byte</li> <li>Larger size registers must be a multiple of 8</li> <li>Registers are in the range of <code>8 &lt;= N &lt;= 64</code> bits in size.</li> </ul> <p>I have a set of structures which build off of each other in a cascading effect starting from the base unit of a <code>Byte</code> down to a <code>QWord</code>.</p> <p>My Registers are template specializations.</p> <h2>main.cpp</h2> <pre><code>#include &lt;iostream&gt; #include "Register.h" int main() { Register r1; std::cout &lt;&lt; "Register&lt;8&gt;\n"; for (i8 i = 0; i &lt; 21; i++) { r1.register_.value_ = i; // make sure to cast to a larger size due to int8_t being defined by char. std::cout &lt;&lt; static_cast&lt;std::uint16_t&gt;(r1.register_.value_) &lt;&lt; "\n"; } std::cout &lt;&lt; '\n'; // Note: my output shows: 0 1 1 0 0 1 0 0 // as I am running on an intel x86-64 bit Quad Core Extreme // this is expected since my machine is little endian. r1.register_.value_ = static_cast&lt;std::int8_t&gt;( 38 ); std::cout &lt;&lt; "Bit Values\n"; std::cout &lt;&lt; static_cast&lt;bool&gt;(r1.register_.b0) &lt;&lt; " " &lt;&lt; static_cast&lt;bool&gt;(r1.register_.b1) &lt;&lt; " " &lt;&lt; static_cast&lt;bool&gt;(r1.register_.b2) &lt;&lt; " " &lt;&lt; static_cast&lt;bool&gt;(r1.register_.b3) &lt;&lt; " " &lt;&lt; static_cast&lt;bool&gt;(r1.register_.b4) &lt;&lt; " " &lt;&lt; static_cast&lt;bool&gt;(r1.register_.b5) &lt;&lt; " " &lt;&lt; static_cast&lt;bool&gt;(r1.register_.b6) &lt;&lt; " " &lt;&lt; static_cast&lt;bool&gt;(r1.register_.b7) &lt;&lt; "\n\n"; Register&lt;16&gt; r2; std::cout &lt;&lt; "Register&lt;16&gt;\n"; for (i16 i = 0; i &lt; 21; i++) { r2.register_.value_ = i; // make sure to cast to a larger size due to int8_t being defined by char. std::cout &lt;&lt; static_cast&lt;std::uint16_t&gt;(r2.register_.value_) &lt;&lt; "\n"; } std::cout &lt;&lt; '\n'; Register&lt;32&gt; r3; std::cout &lt;&lt; "Register&lt;32&gt;\n"; for (i32 i = 0; i &lt; 21; i++) { r3.register_.value_ = i; // make sure to cast to a larger size due to int8_t being defined by char. std::cout &lt;&lt; static_cast&lt;std::uint32_t&gt;(r3.register_.value_) &lt;&lt; "\n"; } std::cout &lt;&lt; '\n'; Register&lt;64&gt; r4; std::cout &lt;&lt; "Register&lt;64&gt;\n"; for (i64 i = 0; i &lt; 21; i++) { r4.register_.value_ = i; // make sure to cast to a larger size due to int8_t being defined by char. std::cout &lt;&lt; static_cast&lt;std::uint64_t&gt;(r4.register_.value_) &lt;&lt; "\n"; } std::cout &lt;&lt; '\n'; return EXIT_SUCCESS; } </code></pre> <h2>Register.h</h2> <pre><code>#pragma once #include &lt;vector&gt; // include for typedefs below. typedef std::int8_t i8; typedef std::int16_t i16; typedef std::int32_t i32; typedef std::int64_t i64; struct MyByte { union { i8 value_; struct { i8 b0 : 1; i8 b1 : 1; i8 b2 : 1; i8 b3 : 1; i8 b4 : 1; i8 b5 : 1; i8 b6 : 1; i8 b7 : 1; }; }; }; struct MyWord { // same as short or i16 union { i16 value_; union { MyByte byte_[2]; struct { MyByte b0_; MyByte b1_; }; }; }; }; struct MyDWord { // same as int or i32 union { i32 value_; struct { MyWord w0_; MyWord w1_; }; union { MyByte byte_[4]; struct { MyByte b0_; MyByte b1_; MyByte b2_; MyByte b3_; }; }; }; }; struct MyQWord { // same as long or i64 union { i64 value_; struct { MyDWord d0_; MyDWord d1_; }; struct { MyWord w0_; MyWord w1_; MyWord w2_; MyWord w3_; }; union { MyByte byte_[8]; struct { MyByte b0_; MyByte b1_; MyByte b2_; MyByte b3_; MyByte b4_; MyByte b5_; MyByte b6_; MyByte b7_; }; }; }; }; template&lt;size_t N = 8&gt; struct Register { MyByte register_; Register() { static_assert( ((N % 8) == 0) &amp;&amp; (N &gt;= 8) &amp;&amp; (N &lt;= 64) ); } }; template&lt;&gt; struct Register&lt;16&gt; { MyWord register_; Register() = default; }; template&lt;&gt; struct Register&lt;32&gt; { MyDWord register_; Register() = default; }; template&lt;&gt; struct Register&lt;64&gt; { MyQWord register_; Register() = default; }; </code></pre> <h2>Output</h2> <pre class="lang-none prettyprint-override"><code>Register&lt;8&gt; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Bit Values 0 1 1 0 0 1 0 0 Register&lt;16&gt; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Register&lt;32&gt; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Register&lt;64&gt; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 </code></pre> <p>I had asked a question on Stack Overflow about specific output due to behavior of <code>std::int8_t</code> being defined from <code>char</code>. That is now fixed.</p> <p>I have a general idea or grasp on unions, bitfields, byte alignment of structs etc. and I am aware of the complications of bitfields especially when it comes to the Endian-ness of a machine. </p> <p>After my question was answered I had dropped a basic general question in the comment of that answer and my question there was this:</p> <blockquote> <p>"Do you see any other issues or major concerns with how the bitfield and nameless unions and structs are coupled together?"</p> </blockquote> <p>I was giving a link to this <a href="https://www.youtube.com/watch?v=sCjZuvtJd-k" rel="nofollow noreferrer">talk</a> as a reply to my question in which I had watched. It has given me some insight and useful information which now leads me to here with a handful of questions and concerns about my code. Some pertain to the video while others don't. Before I start to ask my questions or list my concerns, there are a few things about my code or the particular behavior that I am after.</p> <p>Since I'm simulating what a memory register in a PC would be like I'm trying to model the fact that I had mentioned above about the default and basic unit size is 8 bytes, that a register can be a multiple of 8 and that it has to be in the range of [8,64]. I also like the idea that I would have an 8 bit value at the base level but coupled together with a union and a bitfield only to be able to quickly and easily access the individual bits. And as the size of the registers get larger, the same cascading effect should apply. For example in a 64-bit register the actual single <code>value_</code> is 64 bits or 8 bytes wide in memory, but is coupled with unions to smaller sizes so that one could access a specific <code>DWord</code>, Word or Byte from within a <code>QWord</code> and they can access any one of its 64 bits. This is the behavior of the structure that I am after since I'm trying to model a register in which I would like to use in one of my projects where I'll be emulating a virtual PC. Now that you have the background. I'll go ahead and get to the questions and concerns.</p> <h2>Questions and concerns</h2> <ul> <li>I would like to know what your thoughts and opinions are on the overall structure of my code and its design as is without any influence of my questions and concerns below. Meaning, these replies would be completely dependent on the code itself and independent of any other proposal, another words unbiased. </li> <li>Is there a more simplified and compact way to do this without having to worry about type casting?</li> <li>Since this is a personal project and I'm not overly concerned with the Endian, however I do feel that it should be addressed early on as opposed to later on if I decide to make this portable, what could be done to minimize or alleviate the checks and conversions due to Endian?</li> <li>I would like to have these registers to be trivially copyable. Meaning you can copy one <code>Register&lt;8&gt;</code> to another <code>Register&lt;8&gt;</code> but you wouldn't be able to copy a <code>Register&lt;16&gt;</code> to a <code>Register&lt;32&gt;</code>. I was thinking of maybe making a function that would allow you to copy from one Register type to another.</li> <li>Would using <code>std::bitfield&lt;&gt;</code> and the use of bitstreams be a viable option? <ul> <li>If so how would I be able to incorporate them into this design?</li> <li>If not what is the main cause or reasoning behind why they wouldn't work? Would this be considered Type Punning and if so, would this be a Good or Bad example; please explain either case along with their pros and cons.</li> </ul></li> <li><p>There is only one nuisance to me right now and that is the fact that I have to go an extra level deep to retrieve my values for example:</p> <pre class="lang-cpp prettyprint-override"><code>Register r; r.register_.value_ = 12; </code></pre></li> </ul> <hr> <p><strong>NOTE:</strong> -- My code does not have to be 100% strictly enforced by the standard as I don't have a recent copy of the C++17 standard and only sections of outdated C++11 versions of the standard. However it should at the least be minimally compliant.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T06:28:51.030", "Id": "219736", "Score": "2", "Tags": [ "c++", "template", "bitset" ], "Title": "Emulating Virtual Registers by experimenting with unions, bitfields, structs and template specialization" }
219736
<p>Much of the academic exposition of Dijkstra's Algorithm (such as <a href="https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#Using_a_priority_queue" rel="nofollow noreferrer">Wikipedia</a>, or <a href="https://www.cs.dartmouth.edu/~thc/cs10/lectures/0509/0509.html" rel="nofollow noreferrer">this class page from Darmouth</a>) relies on your priority queue having the ability decrease the key of an entry: the priority queue fills up once at the beginning of the algorithm, and then exclusively shrinks, with one entry being popped at each loop.</p> <p>However, the implementation of <code>PriorityQueue</code> in the Python's <code>queue</code> module has no available decrease-key method. Neither does Java's standard library. Probably as a result of this, <a href="https://bradfieldcs.com/algos/graphs/dijkstras-algorithm/" rel="nofollow noreferrer">many implementations I see online</a> resort to adding all elements immutably to the priorityQueue as they're seen, resulting in an unnecessarily large heap structure with multiple nodes corresponding to a single vertex. This is asymptotically worse: localized decrease-key/siftdown operations with an ever-shrinking heap size should be faster than replacing those operations with <code>heappush</code>ing and <code>heappop</code>ing with a potentially much larger heap.</p> <p>Because I haven't seen many very clear implementations of the <code>IndexedHeap</code> structure required for a Decrease-Key operation, I wrote one myself, with the goal of being able to write the following straight-out-of-a-textbook pseudocode implementation of Dijkstra's Algorithm:</p> <pre class="lang-py prettyprint-override"><code>from collections import defaultdict from math import inf from indexedheap import IndexedHeap class Graph: """ A nonnegatively weighted, directed multigraph. Stored as a list of outgoing edges for each vertex. &gt;&gt;&gt; g = Graph() &gt;&gt;&gt; for source, dest, weight in [ \ ('a', 'b', 7), ('a', 'b', 8), ('a', 'c', 9), ('a', 'f', 14), \ ('b', 'c', 10), ('b', 'd', 15), ('c', 'd', 11), ('c', 'f', 2), \ ('d', 'e', 6), ('e', 'f', 9), ('f', 'g', 100), ('g', 'b', 100), \ ('a', 'a', 100) \ ]: \ g.add_edge(source, dest, weight) &gt;&gt;&gt; g.distance_and_shortest_path('a', 'f') (11, ['a', 'c', 'f']) &gt;&gt;&gt; g.distance_and_shortest_path('b', 'e') (21, ['b', 'd', 'e']) &gt;&gt;&gt; g.distance_and_shortest_path('a', 'a') (0, ['a']) &gt;&gt;&gt; g.distance_and_shortest_path('f', 'a') (inf, None) &gt;&gt;&gt; g.distance_and_shortest_path('garbage', 'junk') (inf, None) """ def __init__(self): self.vertices = set() self.edges = defaultdict(list) def add_edge(self, source, destination, weight): """ Add a weighted edge from source to destination. """ if weight &lt; 0: raise ValueError("Edge weights cannot be negative.") self.vertices |= {destination, source} self.edges[source].append((destination, weight)) def distance_and_shortest_path(self, source, destination): """Find the lightest-weighted path from source to destination. We use Dijkstra's algorithm with an indexed heap. :return: A 2-tuple (d, [v0, v1, ..., vn]), where v0==source and vn==destination. """ if not {source, destination} &lt;= self.vertices: return inf, None # For each vertex v, store the weight of the shortest path to found # so far to v, along with v's predecessor in that path. distance = {v: inf for v in self.vertices} distance[source] = 0 predecessor = {} # A priority queue of exactly the unexplored vertices, h = IndexedHeap((distance[v], v) for v in self.vertices) # Explore until all vertices closer to source have been exhausted, # at which point we will have already found the shortest path (if any) to destination. while h.peek() != destination: v = h.pop() v_dist = distance[v] for neighbor, edge_weight in self.edges[v]: # We've found a new path to neighbor. If the distance along # this new path (through v) is better than previously found, # then "relax" the stored distance to that along the new path. alt_dist = v_dist + edge_weight if alt_dist &lt; distance[neighbor]: distance[neighbor] = alt_dist predecessor[neighbor] = v h.change_weight(neighbor, alt_dist) if distance[destination] == inf: # No path was found. return inf, None # Trace back the predecessors to get the path. path = [destination] while path[-1] != source: path.append(predecessor[path[-1]]) path.reverse() return distance[destination], path if __name__ == "__main__": import doctest doctest.testmod() </code></pre> <p>What follows is my implementation of the <code>IndexedHeap</code>. </p> <pre class="lang-py prettyprint-override"><code>import pyheapq from collections import defaultdict class IndexedHeap(): """A priority queue with the ability to modify existing priority. &gt;&gt;&gt; h = IndexedHeap(['1A', '0B', '5C', '2M']) &gt;&gt;&gt; h.pop() 'B' &gt;&gt;&gt; h.peek() 'A' &gt;&gt;&gt; h.change_weight('M', '6') &gt;&gt;&gt; h.pushpop('W', '7') 'A' &gt;&gt;&gt; h.poppush('R', '8') 'C' &gt;&gt;&gt; [h.pop() for _ in range(len(h))] ['M', 'W', 'R'] """ def __init__(self, iterable=()): self.heap = _IndexedWeightList(map(tuple, iterable)) pyheapq.heapify(self.heap) def __len__(self): return len(self.heap) def __contains__(self, item): return (item in self.heap) def push(self, item, weight): pyheapq.heappush(self.heap, (weight, item)) def pop(self): weight, item = pyheapq.heappop(self.heap) return item def peek(self): weight, item = self.heap[0] return item def pushpop(self, item, weight): # First push, then pop. weight, item2 = pyheapq.heappushpop(self.heap, (weight, item)) return item2 def poppush(self, item, weight): # First pop, then push. weight, item2 = pyheapq.heapreplace(self.heap, (weight, item)) return item2 def change_weight(self, item, weight): i = self.heap.index(item) old_weight, item = self.heap[i] self.heap[i] = weight, item if weight &lt; old_weight: pyheapq.siftdown(self.heap, 0, self.heap.index(item)) elif weight &gt; old_weight: pyheapq.siftup(self.heap, self.heap.index(item)) def __bool__(self): return bool(self.heap) class _IndexedWeightList(list): """A list of (weight, item) pairs, along with the indices of each "item". We maintain an auxiliary dict consisting of, for each item, the set of indices of that item. Each set will typically have just one index, but we do not enforce this because the heapq module updates multiple entries at the same time. You could say that this class has all of the functionality of priority queue, but without the prioritization. &gt;&gt;&gt; arr = _IndexedWeightList(['1A', '0B', '5C', '2M']) &gt;&gt;&gt; arr _IndexedWeightList(['1A', '0B', '5C', '2M']) &gt;&gt;&gt; arr[2] '5C' &gt;&gt;&gt; arr[0], arr[3] = arr[3], arr[0] &gt;&gt;&gt; arr _IndexedWeightList(['2M', '0B', '5C', '1A']) &gt;&gt;&gt; arr.append('6D') &gt;&gt;&gt; arr _IndexedWeightList(['2M', '0B', '5C', '1A', '6D']) &gt;&gt;&gt; [arr.index(x) for x in 'ABCDM'] [3, 1, 2, 4, 0] &gt;&gt;&gt; arr.remove('B') Traceback (most recent call last): ... TypeError: 'NoneType' object is not callable &gt;&gt;&gt; pyheapq.heapify(arr) &gt;&gt;&gt; arr.index('B') 0 """ def __init__(self, iterable=()): super().__init__(iterable) self._index = defaultdict(set) for i, (weight, item) in enumerate(super().__iter__()): self._index[item].add(i) def __setitem__(self, i, pair): weight, item = pair old_weight, old_item = super().__getitem__(i) self._index[old_item].remove(i) self._index[item].add(i) super().__setitem__(i, pair) def index(self, item, start=..., stop=...) -&gt; int: only, = self._index[item] return only def __contains__(self, item): return bool(self._index[item]) def append(self, pair): super().append(pair) weight, item = pair self._index[item].add(len(self) - 1) def extend(self, iterable): for pair in iterable: self.append(pair) def pop(self, i=...): weight, item = super().pop() self._index[item].remove(len(self)) return (weight, item) def __repr__(self): return '{}({})'.format(self.__class__.__qualname__, str(list(self))) insert = None remove = None __delitem__ = None sort = None if __name__ == "__main__": import doctest doctest.testmod() </code></pre> <p>Above, I would rely heavily on Python's standard <code>heapq</code> module, but the C implementation of <code>heapq</code> didn't work with with my overriding of <code>__setattr__</code> subscripting, so I copied its pure-python implementation into a <code>pyheapq.py</code>:</p> <pre class="lang-py prettyprint-override"><code>""" This is all directly copied from heapq.py in the python standard library. This local copy ensures that we use this pure Python implementation so that subscripting can be overridden to maintain an index. Underscores in protected methods have been removed. """ def heappush(heap, item): """Push item onto heap, maintaining the heap invariant.""" heap.append(item) siftdown(heap, 0, len(heap) - 1) ... </code></pre> <p>The rest of the above file is <a href="https://github.com/python/cpython/blob/e42b705188271da108de42b55d9344642170aa2b/Lib/heapq.py" rel="nofollow noreferrer">here</a>.</p> <p><strong><em>My question:</em></strong> Was my overriding of <code>__getattr__</code> in the <code>_IndexedWeightList</code> class an appropriate way of re-using all the existing <code>heapq</code> code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-13T08:16:31.803", "Id": "425395", "Score": "0", "body": "I assume that the doctests work for you? Testing under Windows with Python 3.6.6 I find that `_IndexedWeightList` fails the last test. Apparently `pyheapq.heapify` is bypassing the overridden `__setitem__`. Do you have any idea why?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-13T08:23:16.797", "Id": "425396", "Score": "1", "body": "Ah. \"*The rest of the above file is here*\" but it's necessary to remove the C imports from the end of that file." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-13T10:09:18.187", "Id": "425401", "Score": "0", "body": "As a possible point of interest: https://github.com/coderodde/SearchHeapBenchmark/tree/master/src/main/java/fi/helsinki/coderodde/searchheapbenchmark/support" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-13T11:34:25.210", "Id": "425410", "Score": "0", "body": "Can you provide a link to a possible GitHub project/Gist containing all the source code needed to run your program?" } ]
[ { "body": "<p>Firstly, it's always good to see doctests.</p>\n\n<hr>\n\n<p>I'm not entirely convinced by the name <code>IndexedHeap</code>. The API it exposes has nothing to do with indexes.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> def __bool__(self):\n return bool(self.heap)\n</code></pre>\n</blockquote>\n\n<p>It took a bit of thought to figure out what this is about, but once I got there I appreciate the elegant implementation.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> def pop(self, i=...):\n weight, item = super().pop()\n self._index[item].remove(len(self))\n return (weight, item)\n</code></pre>\n</blockquote>\n\n<p>Probably my biggest criticism: in some use cases this will leak memory by leaving <code>self._index</code> full of empty sets. I'd prefer to see it delete the key when the last index is removed.</p>\n\n<p>Overall, though, the index is quite neat. I must say that it's very nice the way the heap will handle repeated values with different keys but won't allow <code>change_weight</code> of a repeated value. Perhaps a case could be made for giving <code>change_weight</code> an optional <code>current_weight</code> argument to distinguish between repeated values, but YAGNI.</p>\n\n<hr>\n\n<blockquote>\n <p>Was my overriding of <code>__getattr__</code> in the <code>_IndexedWeightList</code> class an appropriate way of re-using all the existing <code>heapq</code> code?</p>\n</blockquote>\n\n<p>I assume you actually mean <code>__setitem__</code> rather than <code>__getattr__</code>.</p>\n\n<p>IMO given that you not only have to copy <code>heapq.py</code> but edit it to make it suitable for your usage, you've lost the advantage of code reuse. It becomes painful to track upstream changes and merge in bugfixes. You might as well go the whole hog and refactor it to suit your needs. It makes more sense to me to add <code>index</code> as an argument to the forked <code>heapq</code> methods<sup>1</sup> and essentially inline <code>_IndexedWeightList</code> away. That has the added advantage that it's compatible with doing the same thing to a fork of the C implementation.</p>\n\n<p><sup>1</sup> Except <code>heapify</code>, because you might as well just rebuild the index after calling that.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-13T09:23:28.863", "Id": "220173", "ParentId": "219737", "Score": "3" } } ]
{ "AcceptedAnswerId": "220173", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T06:34:53.097", "Id": "219737", "Score": "4", "Tags": [ "python", "python-3.x", "inheritance", "heap", "priority-queue" ], "Title": "Overriding List subscription to create IndexedHeap for Classical Dijkstra's Algorithm" }
219737
<p>This is my version of the Huffman Codes.</p> <pre><code>/* Author: Stevan Milic Date: 05.05.2018. Course: Data Structures II Professor: Dr. Claude Chaudet Description: Huffman Codes */ #include &lt;iostream&gt; #include &lt;cstdlib&gt; using namespace std; #define MAX_TREE_HEIGHT 1000 // A Huffman tree node struct MinHeapNode { char codeword; // I chose char because we are inputing alphabetic letters // The reason why I chose unsigned data type is because an unsigned integer can never be negative. // In this case the frequency and the capacity of a character cannot be negative. unsigned freq; // Frequency of the character - how many times does it occur struct MinHeapNode *left, *right; // Left and Right children }; struct MinHeap // Collection of nodes { unsigned size; // Size of the heap unsigned capacity; // Capacity of the heap struct MinHeapNode** array; // Heap node pointers array }; // Function to dynamically alocate a new heap node with provided character (codeword) and its frequency struct MinHeapNode* newHeapNode(char codeword, unsigned freq) { struct MinHeapNode* temp = (struct MinHeapNode*)malloc(sizeof(struct MinHeapNode)); temp-&gt;left = temp-&gt;right = NULL; temp-&gt;codeword = codeword; temp-&gt;freq = freq; return temp; } // Creating a new dynamically allocated min heap with given capacity struct MinHeap* createMinHeap(unsigned capacity) { struct MinHeap* minHeap = (struct MinHeap*)malloc(sizeof(struct MinHeap)); minHeap-&gt;size = 0; // Setting the size to 0 minHeap-&gt;capacity = capacity; // Inserting the given capacity // Inserting into the heap node pointers array minHeap-&gt;array= (struct MinHeapNode**)malloc(minHeap-&gt;capacity * sizeof(struct MinHeapNode*)); return minHeap; } // Swap function to swap two min heap nodes void swap(struct MinHeapNode** a, struct MinHeapNode** b) { struct MinHeapNode* temp2 = *a; *a = *b; *b = temp2; } // minHeapify function void minHeapify(struct MinHeap* minHeap, int index) { int smallest = index; int leftSon = 2 * index + 1; int rightSon = 2 * index + 2; if (leftSon &lt; minHeap-&gt;size &amp;&amp; minHeap-&gt;array[leftSon]-&gt;freq &lt; minHeap-&gt;array[smallest]-&gt;freq) smallest = leftSon; if (rightSon &lt; minHeap-&gt;size &amp;&amp; minHeap-&gt;array[rightSon]-&gt; freq &lt; minHeap-&gt;array[smallest]-&gt;freq) smallest = rightSon; if (smallest != index) { swap(&amp;minHeap-&gt;array[smallest], &amp;minHeap-&gt;array[index]); minHeapify(minHeap, smallest); } } // Checking if the size of the heap is 1 int heapSizeOne(struct MinHeap* minHeap) { return (minHeap-&gt;size == 1); } // Extracting minimum value node from the heap struct MinHeapNode* extractMin(struct MinHeap* minHeap) { struct MinHeapNode* temp = minHeap-&gt;array[0]; minHeap-&gt;array[0] = minHeap-&gt;array[minHeap-&gt;size - 1]; --minHeap-&gt;size; minHeapify(minHeap, 0); return temp; } // Inserting a new node into min heap void insert(struct MinHeap* minHeap, struct MinHeapNode* minHeapNode) { ++minHeap-&gt;size; int i = minHeap-&gt;size - 1; while (i &amp;&amp; minHeapNode-&gt;freq &lt; minHeap-&gt;array[(i - 1) / 2]-&gt;freq) { minHeap-&gt;array[i] = minHeap-&gt;array[(i - 1) / 2]; i = (i - 1) / 2; } minHeap-&gt;array[i] = minHeapNode; } // Build function to build min heap void build(struct MinHeap* minHeap) { int n = minHeap-&gt;size - 1; for (int i = (n - 1) / 2; i &gt;= 0; --i) minHeapify(minHeap, i); } // Display function to print an array void display(int arr[], int n) { int i; for (i = 0; i &lt; n; ++i) cout &lt;&lt; arr[i]; cout &lt;&lt; "\n"; } // Function to check if the node is a leaf int isLeaf(struct MinHeapNode* root) { return !(root-&gt;left) &amp;&amp; !(root-&gt;right); } // Creating a min heap with given capacity equivalent to size and inserts all the codewords and their frequency. struct MinHeap* create(char codeword[], int freq[], int size) { struct MinHeap* minHeap = createMinHeap(size); for (int i = 0; i &lt; size; ++i) minHeap-&gt;array[i] = newHeapNode(codeword[i], freq[i]); minHeap-&gt;size = size; build(minHeap); return minHeap; } // Function that builds the Huffman tree struct MinHeapNode* buildHT(char codeword[], int freq[], int size) { struct MinHeapNode *left, *right, *top; // Creating a min heap with given capacity equivalent to size and inserts all the codewords and their frequency. struct MinHeap* minHeap = create(codeword, freq, size); // while loop runs as long as the size of heap doesn't reach 1 while (!heapSizeOne(minHeap)) { // Getting the two minimums from min heap left = extractMin(minHeap); right = extractMin(minHeap); // The frequency of top is computed as the sum of the frequencies of left and right nodes. top = newHeapNode('_', left-&gt;freq + right-&gt;freq); top-&gt;left = left; top-&gt;right = right; insert(minHeap, top); } // The remaining value is the root node which completes the tree return extractMin(minHeap); } // Prints huffman codes from the root of // Displaying Huffman codes void displayHC(struct MinHeapNode* root, int arr[], int top) { // Left side is given the value 0 if (root-&gt;left) { arr[top] = 0; displayHC(root-&gt;left, arr, top + 1); } // Right side is given the value 1 if (root-&gt;right) { arr[top] = 1; displayHC(root-&gt;right, arr, top + 1); } // If this is a leaf node, print the character and its code. if (isLeaf(root)) { cout &lt;&lt; root-&gt;codeword &lt;&lt; ": "; display(arr, top); } } // Building a Huffman Tree and displaying the codes void HuffmanCodes(char codeword[], int freq[], int size) { // Building a HT struct MinHeapNode* root = buildHT(codeword, freq, size); // Displaying the HT we built int arr[MAX_TREE_HEIGHT], top = 0; displayHC(root, arr, top); } // I used the example from the PP presentation in the Files section - The Hoffman Coding int main() { cout &lt;&lt; "A|4\t B|0\t C|2\t D|1\t C|5\t E|1\t F|0\t G|1\t H|1\t I|0\t J|0\t K|3\t L|2\t M|0\t N|1\t\nO|2\t P|0\t Q|3\t R|5\t S|4\t T|2\t U|0\t V|0\t W|1\t X|0\t Y|0\t Z|0\t _|6\n" &lt;&lt; endl; char arr[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '_' }; int freq[] = { 4, 0, 2, 1, 5, 1, 0, 1, 1, 0, 0, 3, 2, 0, 1, 2, 0, 3, 5, 4, 2, 0, 0, 1, 0, 0, 6}; int size = sizeof(arr) / sizeof(arr[0]); HuffmanCodes(arr, freq, size); cout &lt;&lt; "\n\n"; system("pause"); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T10:36:09.293", "Id": "424427", "Score": "17", "body": "Your code is pretty much \"C with `cout` and `using namespace std;`s\". It doesn't look like C++ at all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T10:40:19.903", "Id": "424429", "Score": "6", "body": "Is this code for an assignment? I'd recommend not putting it online if you haven't yet had it graded." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T20:19:05.113", "Id": "424499", "Score": "10", "body": "You seem to make the same mistakes [over](https://codereview.stackexchange.com/questions/192714/game-of-life-improvement) and [over](https://codereview.stackexchange.com/questions/208100/singly-linked-list-class) again. Could I suggest you consider using some of the answers you are receiving." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T02:32:38.253", "Id": "424528", "Score": "0", "body": "It looks like you have two different things going on here: A min heap data structure, and an implementation of a huffman code algorithm that happens to use a min heap. Don't conflate the two. Build a generic min heap (that'll come in useful in other places), and build a separate huffman code function that uses it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T08:17:24.143", "Id": "424546", "Score": "0", "body": "Which version of C++ are you using? (command line parameters or compiler version would be useful )" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-08T04:26:19.410", "Id": "424842", "Score": "0", "body": "I am using the aspects that I have learned so far in my C++ classes. I am new when it comes to C++, and I am probably not using any of its newer features so far." } ]
[ { "body": "<p>Looks pretty readable and I agree with most of your formatting however there are some things that stand out.</p>\n\n<ul>\n<li><p><code>using namespace std;</code><br>\n<a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Kick this habit before it kicks you.</a></p></li>\n<li><p><code>#define MAX_TREE_HEIGHT 1000</code><br>\nI'd prefer to put this into an anonymous namespace as implementation detail</p></li>\n<li><p><code>unsigned freq;</code><br>\nNot everyone knows this defaults to <code>int</code>. Might be a good idea to add <code>int</code> for readability</p></li>\n<li><p>At a glance this seems to leak memory<br>\nConfirm with valgrind. You're using <code>malloc</code> but no <code>free</code>. Better use <code>new</code>/<code>delete</code>, even better use smart pointers and friends.</p></li>\n<li><p>Braces (highly subjective)<br>\nMany people disagree on this one but I prefer to always include braces where possible</p></li>\n<li><p><a href=\"https://stackoverflow.com/questions/213907/c-stdendl-vs-n\">Prefer using <code>\\n</code> over <code>std::endl</code></a></p></li>\n<li><p><code>system(\"pause\");</code> <a href=\"https://stackoverflow.com/questions/1107705/systempause-why-is-it-wrong\">should be avoided</a></p></li>\n<li><p><a href=\"http://c0x.coding-guidelines.com/5.1.2.2.3.html\" rel=\"noreferrer\">If you don't depend on return values you can omit <code>return 0</code> from main</a> (subjective)</p></li>\n</ul>\n\n<p>Overall this seems very C-ish, not so much like (modern) C++. Are you perhaps prohibited from using certain language features?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T09:02:58.243", "Id": "424411", "Score": "8", "body": "1. It doesn't matter if the `#define` is in a namespace, as it doesn't respect them anyway. 2. Nobody who needs `unsigned int` spelled out can legitimately claim even passing familiarity with C++, so they *should not* be the target audience. 3. `return 0;` can always be omitted from `main()`, but nowhere else." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T10:15:30.580", "Id": "424426", "Score": "9", "body": "\"Not everyone knows this defaults to int.\" - People not knowing that should not touch others code anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T11:23:20.967", "Id": "424572", "Score": "0", "body": "you complain it looks to \"C-ish\" but also that he uses the correct std::endl over the very C-ish \\n. Make up your mind :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T12:57:19.107", "Id": "424590", "Score": "4", "body": "@jwenting How is the character `\\n` related to C at all? How is `std::endl` correct when it has side-effects which are not desirable here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-08T04:27:37.437", "Id": "424843", "Score": "0", "body": "@yuri Thank you very much for your answer, I tried to correct the mistakes you wrote but somehow I still get the wrong output. It seems like I have a logic error in my code and I can't figure it out." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-08T09:18:39.047", "Id": "424856", "Score": "0", "body": "@StevanMilic `still get the wrong output` Can you elaborate on this? Did your program ever run correctly to the best of your knowledge?" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T08:55:56.280", "Id": "219742", "ParentId": "219738", "Score": "17" } }, { "body": "<ul>\n<li><p>NEVER use <code>using namespace std</code>. It can cause hard tracked bugs. Read here why: <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></li>\n<li><p>The code has WAY to much comments. \"Well commented\" does not mean that it should have tons of comments. I have seen well commented code without comments. A problem with comments is that you need to maintain them. Will you remember to change comments when you change the code? Probably not. An example of a completely useless comment is <code>minHeap-&gt;size = 0; // Setting the size to 0</code>. You have a variable called <code>size</code> and you're assigning it to the value <code>0</code>. There's no need for a comment there.</p></li>\n<li><p>If you're coding C++, then code C++. No reason to use <code>malloc</code> in C++, because this language has far easier and secure methods for allocating memory.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T17:02:52.910", "Id": "424482", "Score": "0", "body": "On the other hand, `minHeap->size = 0; // make heap empty` is a comment that *might* be useful" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T17:07:00.740", "Id": "424483", "Score": "0", "body": "@HagenvonEitzen I disagree. Sure, it gives a little information, but it's not worth it. It's just noise. When I am about to write a comment, I always think if I instead can rewrite the code so that the comment is not necessary." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T10:26:08.093", "Id": "219745", "ParentId": "219738", "Score": "10" } }, { "body": "<p><strong>Prefer Constants Over Macros</strong><br>\nThe line </p>\n\n<pre><code>#define MAX_TREE_HEIGHT 1000\n</code></pre>\n\n<p>might be better written as </p>\n\n<pre><code>const size_t MAX_TREE_HEIGHT = 1000;\n</code></pre>\n\n<p>In C++ constants are preferred over macros because constants are type safe and provide more error checking at compile time.</p>\n\n<p><strong>Prefer new Type(); Over malloc()</strong><br>\nThe C++ programming language allowed <code>malloc()</code>, <code>calloc()</code> and <code>free()</code> for backwards comparability with the C programming language, however, it also introduced <code>new Type()</code> and <code>delete()</code>. Generally <code>new</code> and <code>delete</code> are preferred over the older C language functions. Using <code>new</code> has these benefits: </p>\n\n<ul>\n<li>new is an operator, malloc is a function</li>\n<li>new returns the proper type so the cast is not necessary</li>\n<li>new executes constructors to properly initialize the new object, the use of malloc requires additional code to initialize the new object.</li>\n<li>new automatically performs the error checking for failed memory allocation and throws an exception if the allocation failed. For malloc additional code needs to be added to make sure malloc did not return NULL (or nullptr in the case of C++).</li>\n<li>new knows the amount of memory to allocate for the object, malloc requires the programmer to specify the size of the object.</li>\n</ul>\n\n<p>References about new versus malloc can be found <a href=\"https://www.includehelp.com/cpp-tutorial/difference-between-new-and-malloc.aspx\" rel=\"nofollow noreferrer\">here</a>, <a href=\"https://techdifferences.com/difference-between-new-and-malloc.html\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://stackoverflow.com/questions/184537/in-what-cases-do-i-use-malloc-vs-new\">this stackoverflow question</a>.</p>\n\n<p>When allocating arrays in C <a href=\"https://www.geeksforgeeks.org/calloc-versus-malloc/\" rel=\"nofollow noreferrer\"><code>calloc()</code> is preferred over <code>malloc()</code></a> for two reasons, first it is clear that an array is being allocated because there are two arguments, one is the size of the array and the other is the size of the object. The second reason is that calloc() clears the memory of the objects (initializes the entire array contents to zero), malloc() requires the programmer to clear the contents of the array.</p>\n\n<p><strong>Namespaces</strong><br>\nNamespaces were added to the definition of the C++ language to prevent collisions of function names and variables. Operators such as <code>cin</code> and <code>cout</code> can be overloaded to display the contents of objects. In this case the overloaded NAMESPACE::cout may include references to std::cout. Generally <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\"><code>using namespace std;</code> is considered a bad programming practice</a> because it can cause function name or variable name collisions. For maintainability reasons never put <code>using namespace std;</code> into a header file.</p>\n\n<p><strong>Use Container Classes When Possible</strong><br>\nThe array allocated by this line</p>\n\n<pre><code> struct MinHeap* minHeap = createMinHeap(size);\n</code></pre>\n\n<p>might be better as the C++ container class std::vector or even std::vector (does the code really need the pointers).</p>\n\n<p>std::vector is a variable sized array of any type, it grows as needed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T16:00:33.023", "Id": "219755", "ParentId": "219738", "Score": "7" } } ]
{ "AcceptedAnswerId": "219742", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T07:25:52.653", "Id": "219738", "Score": "6", "Tags": [ "c++", "homework", "compression", "heap" ], "Title": "Huffman Code in C++" }
219738
<p>I recreated the game Hangman and I'm decently happy with it, but like always it would be preferable if anyone knew how to improve my code:</p> <p><strong>main.cpp</strong></p> <pre><code>#ifndef UNICODE #define UNICODE #endif #include &lt;iostream&gt; #include &lt;conio.h&gt; #include &lt;Windows.h&gt; #include &lt;ctime&gt; #include "gameInfo.h" // Function declares std::wstring gen(gameInfo&amp; info); void clrscr(); void greet(gameInfo&amp; info); int ask(gameInfo&amp; info, std::wstring&amp; word, std::string&amp; out); void checklives(gameInfo&amp; info); void findindex(std::wstring&amp; str, wchar_t character, std::vector&lt;unsigned int&gt;* vct); void run(gameInfo&amp; info); // Main thread int main() { srand((unsigned int)time(NULL)); gameInfo info; greet(info); clrscr(); // Runs the whole game run(info); } // Returns random word from word list std::wstring gen(gameInfo&amp; info) { return info.dictionary()[rand() % info.dictionary().size()]; } /* Function to get input from user at start of app makes user choose if they want to play or quit */ void greet(gameInfo&amp; info) { while (true) { int choice; std::wcout &lt;&lt; L"1: Play" &lt;&lt; std::endl; std::wcout &lt;&lt; L"2: Quit" &lt;&lt; std::endl; if ((std::cin &gt;&gt; choice) &amp;&amp; (choice == 1 || choice == 2)) { if (choice == 1) { info.run(true); break; } else break; } else std::wcout &lt;&lt; L"Failed to get input from user" &lt;&lt; std::endl; } } /* Asks user for a character and if there is that character in the string then for each of that character push back an index and for each index replace the blank character with the input character and in the end output the string */ int ask(gameInfo&amp; info, std::wstring&amp; word, std::wstring&amp; out) { std::wcout &lt;&lt; L"The word is " &lt;&lt; word.size() &lt;&lt; L" characters long." &lt;&lt; std::endl; std::wcout &lt;&lt; L"You have " &lt;&lt; info.live() &lt;&lt; L" lives." &lt;&lt; std::endl; std::wcout &lt;&lt; "Input a character: " &lt;&lt; std::flush; wchar_t answer; std::vector&lt;unsigned int&gt; index = { }; if (std::wcin &gt;&gt; answer) { for (int i = 0, n = word.size(); i &lt; n; ++i) { if (out[i] == L' ') out[i] = L'_'; } answer = std::tolower(answer); findindex(word, answer, &amp;index); if (!index.size()) { info.live(info.live() - 1); std::wcout &lt;&lt; out &lt;&lt; std::endl; return 1; // Success } for (unsigned int i : index) { out[i] = answer; } if (out == word) { std::wcout &lt;&lt; L"Correct! the word was " &lt;&lt; word &lt;&lt; "." &lt;&lt; std::endl; info.run(false); return 1; // Success } std::wcout &lt;&lt; out &lt;&lt; std::endl; } else { std::wcout &lt;&lt; L"Error getting user input" &lt;&lt; std::endl; return 0; // Failure } return 1; // Returns success } // Shite but does the job void clrscr() { for (int i = 0; i &lt; 10; ++i) std::wcout &lt;&lt; L"\n\n\n\n\n\n\n\n\n" &lt;&lt; std::endl; } // Finds index of a word void findindex(std::wstring&amp; str, wchar_t character, std::vector&lt;unsigned int&gt;* vct) { for (int i = 0, n = str.size(); i &lt; n; ++i) if (str[i] == character) vct-&gt;push_back(i); } // Checks, well, lives. void checklives(gameInfo&amp; info) { if (info.live() &lt; 1) { info.run(false); } } /* Runs the whole game. For each game loop asks the user if they want to retry or quit the game */ void run(gameInfo&amp; info) { while (true) { std::wstring word = gen(info); std::wstring out(word.size(), L' '); while (info.run()) { ask(info, word, out); checklives(info); Sleep(1000); clrscr(); } info.live(5); unsigned int choice; std::wcout &lt;&lt; L"1: Retry" &lt;&lt; std::endl; std::wcout &lt;&lt; L"2: Quit" &lt;&lt; std::endl; if ((std::cin &gt;&gt; choice) &amp;&amp; (choice == 1 || choice == 2)) { if (choice == 1) { info.run(true); clrscr(); } else break; } else { std::wcout &lt;&lt; L"Couldn't process input. " &lt;&lt; std::endl; clrscr(); } } } </code></pre> <p><strong>gameInfo.header</strong></p> <pre><code>#pragma once #include &lt;vector&gt; #include &lt;string&gt; class gameInfo { private: // Main variables bool bRun = false; unsigned int lives = 5; std::vector&lt;std::wstring&gt; vec = { L"banana", L"apple", L"circus", L"baby", L"key", L"cooker", L"bottle", L"keyboard", L"head", L"book", L"robe", L"cup", L"mug", L"box", L"dog", L"horse", L"potato", L"desk", L"winter", L"life", L"death" }; public: // Getters std::vector&lt;std::wstring&gt; dictionary(); bool run(); unsigned int live(); // Setters void run(bool opt); void live(unsigned int opt); }; </code></pre> <p><strong>gameInfo.cpp</strong></p> <pre><code>#include "gameInfo.h" std::vector&lt;std::wstring&gt; gameInfo::dictionary() { return vec; } bool gameInfo::run() { return bRun; } unsigned int gameInfo::live() { return lives; } void gameInfo::live(unsigned int opt) { lives = opt; } void gameInfo::run(bool opt) { bRun = opt; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T10:37:12.843", "Id": "424428", "Score": "0", "body": "Well, you code is not portable. Is there a reason not to stick to standard C++ features?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T10:42:30.230", "Id": "424431", "Score": "0", "body": "Sorry, but i really don't know what you mean by that..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T10:44:28.180", "Id": "424432", "Score": "0", "body": "\"Not portable\" means: you code is good, but can only run on some platforms (in this case, Windows). Did you consider the possibility of writing platform-independent programs?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T10:46:36.970", "Id": "424433", "Score": "0", "body": "I never did really, but i get what you mean. yeah i never liked including stuff like windows.h but it gives so much functionality (like Sleep)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T10:50:02.010", "Id": "424434", "Score": "0", "body": "In the specific case of Sleep, you can use the standard library as well: `std::this_thread::sleep_for(1s);` for waiting for one second. (Don't forget to `#include <chrono>` and `#include <thread>`)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T10:51:55.007", "Id": "424436", "Score": "0", "body": "Also, don't take that too seriously. You are doing a very good job concerning that this is just the second game of yours. ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T10:53:26.170", "Id": "424438", "Score": "0", "body": "Just curious: why do you want to avoid `std::this_thread::sleep_for` on Windows? Does it not work? ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T10:54:20.173", "Id": "424439", "Score": "0", "body": "Thank you. I added some code at the top of the file so that it's platform independant. Pretty much both define a sleep(x) function, but depending on the operating system it changes the definition. For example, if __WIN32 is defined then Windows.h is included and sleep(x) is defined as Sleep(x)\nif not, then <chrono> and <thread> are included and sleep(x) is defined as std::this_thread::sleep_for(x)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T10:55:26.047", "Id": "424440", "Score": "0", "body": "anyways i avoided std::this_thread::sleep_for cause when i put a value inside it didn't work, but now i just cast the parameter value to chrono::milliseconds" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T10:56:09.770", "Id": "424442", "Score": "0", "body": "A tip: you don't need to repetitively delete old comments and replace them with new ones. You can click the Edit button." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T10:57:21.007", "Id": "424443", "Score": "0", "body": "Yeah i just wrote useless stuff. I talked before i thought" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T11:38:03.003", "Id": "424446", "Score": "3", "body": "This question is good. Rather than second game you might want to say `Refactored` or `Improved` in the title. You should also provide a link to your first question in the body of the question. You might want to delete your answer to the first question since it is basically this question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T11:39:33.120", "Id": "424447", "Score": "2", "body": "@L.F. I'd wait a little while in case the question gets edited, but you provided a pretty good answer in your comments, you might want to make it into an answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-11T04:44:09.667", "Id": "425239", "Score": "0", "body": "Only suggestions would be to remove the dependencies on `Windows.h` and `conio.h` and remove those headers in favor of standard library functions for this console application. There are more portable text windowing libraries available, like ncurses, etc.." } ]
[ { "body": "<p><strong>Common File Names</strong>\nThere are 2 generally accepted extensions for C++ header files, they are <code>.h</code> and <code>.hpp</code>. A professional programmer will stick to the common extensions so that others can maintain his code.</p>\n\n<p>Many editing tools will create these files for you, for instance in Visual Studio you can select <code>Add</code> from the solution explorer and then select class. Visual Studio will then generate <code>class.h</code> and <code>class.cpp</code>. Visual Studio will also create the constructor and destructor declarations in the header file and default bodies for the constructor and destructor in the cpp file.</p>\n\n<p><strong>Initializing Classes</strong><br>\nThis line in <code>main()</code> not only creates the gameInfo object in memory, it also calls the default constructor which initializes the variables in gameInfo:</p>\n\n<pre><code> gameInfo info;\n</code></pre>\n\n<p>It is more common to see initialization of private variables within the constructor, rather than in the declaration of the class. If the body of the constructor is in the cpp file this prevents the recompile of all the files that include the header if the value of one of the variable needs to change. This becomes important as your programs grow and multiple classes are required. I've worked on projects where recompiling everything takes more than 30 minutes.</p>\n\n<p>A default constructor for gameInfo might look something like this:</p>\n\n<pre><code>std::vector&lt;std::wstring&gt; initVec = {\n L\"banana\", L\"apple\", L\"circus\", L\"baby\", L\"key\",\n L\"cooker\", L\"bottle\", L\"keyboard\", L\"head\", L\"book\",\n L\"robe\", L\"cup\", L\"mug\", L\"box\", L\"dog\", L\"horse\",\n L\"potato\", L\"desk\", L\"winter\", L\"life\", L\"death\"\n};\n\ngameInfo::gameInfo()\n : bRun{false}, lives{5}\n{\n vec = initVec;\n}\n\nand a parameterized constructor might look something like this:\n\ngameInfo::gameInfo(bool run, unsigned int lifeCount)\n : bRun{run}, lives{lifeCount}\n{\n vec = initVec;\n}\n</code></pre>\n\n<p><strong>Public Before Private</strong><br>\nIt might be better to put all the public methods before the private methods in the class definition. The public methods will be used by the consumers and having them at the top makes it easier to find.</p>\n\n<p>It is possible to put the bodies of functions into the headers, this is necessary for template functions, but it is also useful for simple functions such as the getters and setters in gameInfo.</p>\n\n<p>Using the items discussed above, here is an example how gameInfo might be declared in gameInfo.h: </p>\n\n<pre><code>#include &lt;vector&gt;\n#include &lt;string&gt;\n\nclass gameInfo\n{\npublic:\n gameInfo();\n ~gameInfo() = default;\n\n // Getters\n std::vector&lt;std::wstring&gt; dictionary() const { return vec; };\n bool run() const { return bRun; };\n unsigned int live() const { return lives; };\n\n // Setters\n void run(bool opt) { bRun = opt; };\n void live(unsigned int opt) { lives = opt; };\n\nprivate:\n // Main variables\n bool bRun;\n unsigned int lives;\n\n std::vector&lt;std::wstring&gt; vec;\n};\n</code></pre>\n\n<p>In the declaration above the constructor and destructor have been added, the private variables are declared but their initialization has been moved into the constructor. The bodies of the simpler functions have been moved from the CPP file to the class declaration and the public interfaces have been moved up.</p>\n\n<p>Putting the keyword <code>const</code> before the body of the function when the function doesn't change any values can improve the performance of the program.</p>\n\n<p>The keyword <code>default</code> in the declaration of the destructor indicates that the compiler should generate a default destructor for this class. This is useful when the class doesn't have resources such as files that need to be closed.</p>\n\n<p><strong>Complexity</strong><br>\nMany of the functions in this program are simple, atomic and straight forward (nice work), but both the <code>ask</code> function and the <code>run</code> function in <code>main.cpp</code> might be candidates for simplification into multiple functions.</p>\n\n<p>The program as a whole can be simplified by moving almost all of the functions into the gameInfo class. All the functions that receive <code>info</code> can then access the private members directly and don't require the setter and getter functions. The <code>main()</code> function could be simplified to :</p>\n\n<pre><code>int main() {\n\n srand((unsigned int)time(NULL));\n gameInfo info;\n\n info.greet();\n info.run();\n}\n</code></pre>\n\n<p>The seeding of the random number generator could also be moved to the gameInfo constructor since that is only constructed once.</p>\n\n<p>Most of the functions in gameInfo would then become private functions since they are only required by gameInfo and not other functions or classes.</p>\n\n<p>Examples of simplified functions in gameInfo:</p>\n\n<pre><code>// Returns random word from word list\nstd::wstring gameInfo::gen()\n{\n return vec[rand() % vec.size()];\n}\n\n// Checks, well, lives.\nvoid gameInfo::checklives() {\n if (lives &lt; 1) {\n bRun = false;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T14:19:42.610", "Id": "219811", "ParentId": "219744", "Score": "5" } }, { "body": "<p>I just spotted some random things not mentioned yet.</p>\n\n<p><strong>Make the wait portable</strong></p>\n\n<p>Consider using a modern portable way to replace </p>\n\n<pre><code>#include &lt;windows.h&gt;\n\nSleep(1000);\n</code></pre>\n\n<p>with </p>\n\n<pre><code>#include &lt;chrono&gt;\n#include &lt;thread&gt;\n\nstd::this_thread::sleep_for(std::chrono::milliseconds{ 1000 });\n</code></pre>\n\n<p>This approach works on all platforms were c++11 is available.</p>\n\n<p><strong>Portable the second</strong></p>\n\n<p>Annother thing:</p>\n\n<pre><code>void clrscr();\n</code></pre>\n\n<p>This function comes from the ancient conio.h. It can be replaced with system calls to clean the screen</p>\n\n<pre><code>// somewhere in the program\n#define WINDOWS 1\n\nvoid console_clear_screen() {\n #ifdef WINDOWS\n system(\"cls\");\n #endif\n #ifdef LINUX\n system(\"clear\");\n #endif\n}\n</code></pre>\n\n<p><strong>consider not using unsigned int</strong></p>\n\n<p>Also you should consider if you really really need <code>unsigend int</code>. It can be source for errors. See: <a href=\"https://stackoverflow.com/questions/22587451/c-c-use-of-int-or-unsigned-int\">https://stackoverflow.com/questions/22587451/c-c-use-of-int-or-unsigned-int</a></p>\n\n<p><strong>use better random generator</strong></p>\n\n<p>This: </p>\n\n<pre><code>srand((unsigned int)time(NULL));\n</code></pre>\n\n<p>should be replaced with functions from . See:\n<a href=\"https://stackoverflow.com/questions/52869166/why-is-the-use-of-rand-considered-bad\">https://stackoverflow.com/questions/52869166/why-is-the-use-of-rand-considered-bad</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-11T04:38:52.087", "Id": "425238", "Score": "0", "body": "`clrscr();` is the old DOS clear-screen in `conio.h`. (another portability problem)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-11T07:41:47.190", "Id": "425249", "Score": "0", "body": "a good point. But still he declares the function void clrscr(); himself. See top of the code. anyway i edited my post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-11T07:42:52.877", "Id": "425250", "Score": "0", "body": "Hah, correct you are, but I suspect it is `void clrscr (void) { clrscr(); }` `:)`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-10T19:47:28.800", "Id": "220066", "ParentId": "219744", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "14", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T10:18:12.260", "Id": "219744", "Score": "5", "Tags": [ "c++", "beginner", "hangman" ], "Title": "My second game (Hangman in C++)" }
219744
<p>I'm very new to coding and decided to try a mini-project in python to create a 'guess the number game'. I was just hoping for some feedback on my code-writing to prevent bad habits before they develop. This program runs smoothly but I would like to know if there are improvements I could make. In particular:</p> <ul> <li>How can I improve the efficiency and readability?</li> <li>Is it okay to call a function within its own body?</li> <li>Is there any ugly implementation that I should avoid?</li> </ul> <pre><code>import random number = 0 counter = 0 def start_game(): print("I'm thinking of a number between 1 and 10.") print("Can you guess it?") global number number = random.randint(1,10) global counter counter = 0 check_valid() def check_valid(): global counter counter += 1 guess = input() try: val = int(guess) if int(guess) not in range(0,11): print("Hmmm.. that number is not between 1 and 10! Try again!") check_valid() elif int(guess) &gt; number: print("Too high, try a smaller number") check_valid() elif int(guess) &lt; number: print("Too low, try a bigger number") check_valid() elif int(guess) == number: print("Congratulations, you guessed it! The number was " + str(number) + ".\nIt took you " + str(counter) + " tries!") print("Do you want to play again?") check_replay() except ValueError: print("That's not a number, try again!") check_valid() def check_replay(): answer = input() valid_yes = ["yes", "ye", "y"] valid_no = ["no", "n"] if answer.lower() in valid_yes: start_game() elif answer.lower() in valid_no: print("Thanks for playing!") else: print("Please enter yes or no") check_replay() start_game() </code></pre>
[]
[ { "body": "<p>One thing I notice is that, you use global variables. While they are not necessarily bad and work fine in this particular case, it might be beneficial to read these <a href=\"https://stackoverflow.com/questions/19158339/why-are-global-variables-evil\">answers</a>. It would be better to define these variables in main function and pass them as parameters for other functions.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def start_game(number, counter):\n #Your code here\n\ndef main():\n number = 0\n counter = 0\n start_game(number, counter)\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n\n<p>Calling the function within its body is called a <a href=\"https://en.wikipedia.org/wiki/Recursion\" rel=\"nofollow noreferrer\">recursion</a> and as long as you assure that the calling sequence won't become an infinite loop, it is widely used technique in programming.</p>\n\n<p>One more minor thing: you define <code>val = int(guess)</code> but never use it, maybe delete it?</p>\n\n<p>Other than that, everything looks fine and the code is readable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T14:34:14.887", "Id": "424598", "Score": "0", "body": "Thanks so much for your help! I think I had intended to use val instead of int(guess) but forgot to change it! I did try to pass those variables as parameters but couldn't get the hang of it! Thanks for the link there's a lot of helpful info there! Thanks for taking the time to help me out! Much appreciated!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T16:07:41.073", "Id": "219756", "ParentId": "219749", "Score": "4" } }, { "body": "<p>First, <code>check_replay</code> has a few notable things.</p>\n\n<ul>\n<li><p>Since you're only using <code>valid_yes</code> and <code>valid_no</code> to check for membership, they would be better as sets which have a much more efficient membership lookup. The performance difference won't be noticeable in this case, but it's a good thing to keep in mind.</p></li>\n<li><p>The whole purpose of <code>check_replay</code> is to ask if they want to play again, yet you're printing the <code>\"Do you want to play again?\"</code> message outside of the function. I would just pass it into the initial <code>input</code> call.</p></li>\n<li><p>Even as someone who loves recursion, I agree with @abendrot that recursion isn't the ideal tool for the job here. Using it here means your program could crash if the user enters bad input too many times. I'd just use a <code>while</code> loop.</p></li>\n<li><p>I also think it should return the decision instead of calling <code>start_game</code></p></li>\n</ul>\n\n<p>Taking all that into consideration, I'd write it closer to:</p>\n\n<pre><code>def check_replay():\n valid_yes = {\"yes\", \"ye\", \"y\"} # Using sets instead of lists\n valid_no = {\"no\", \"n\"}\n\n while True:\n answer = input(\"Do you want to play again?: \") # Printing the message here instead\n\n if answer.lower() in valid_yes:\n return True\n # I added blank lines for readability\n elif answer.lower() in valid_no:\n print(\"Thanks for playing!\")\n return False\n\n else:\n print(\"Please enter yes or no\")\n</code></pre>\n\n<hr>\n\n<p>My other concern is that <code>start_game</code> and <code>check_valid</code> don't really make sense as two different functions. <code>start_game</code> is basically just being used to initialize the globals, but the globals aren't necessary in the first place. Normally I'm all for breaking up functions into smaller pieces, but I think here everything works better if you collapse them into one function. I also neatened up a lot of stuff. See the comments:</p>\n\n<pre><code>def play_game():\n # I wrapped the whole thing in a loop to avoid the recursive call\n while True: \n print(\"I'm thinking of a number between 1 and 10.\")\n print(\"Can you guess it?\")\n\n # No more globals \n number = random.randint(1, 10)\n counter = 0\n\n while True:\n counter += 1\n guess = input(\"Your guess: \")\n\n try:\n val = int(guess) # You forgot to use val and were instead writing int(guess) all over\n\n if val not in set(range(0, 11)): # Made into a set as well\n print(\"Hmmm.. that number is not between 1 and 10! Try again!\")\n # Again, I added blank lines for readability\n elif val &gt; number:\n print(\"Too high, try a smaller number\")\n\n elif val &lt; number:\n print(\"Too low, try a bigger number\")\n\n else: # This should just be an else since if the other two checks failed, they must be equal \n print(\"Congratulations, you guessed it! The number was \" + \n str(number) + \".\\nIt took you \" + str(counter) + \" tries!\")\n\n if check_replay():\n break # Break to the outer loop to play again\n\n else:\n return # Else exit\n\n except ValueError:\n print(\"That's not a number, try again!\")\n</code></pre>\n\n<p>If you wanted to break that large function up (which is understandable), I'd factor out the turn-taking loop aspect of it. Something like:</p>\n\n<pre><code>def make_guess(computer_number): # Pass in the target number\n while True:\n guess = input(\"Your guess: \")\n\n try:\n val = int(guess)\n\n if val not in set(range(0, 11)):\n print(\"Hmmm.. that number is not between 1 and 10! Try again!\")\n\n elif val &gt; computer_number:\n print(\"Too high, try a smaller number\")\n\n elif val &lt; computer_number:\n print(\"Too low, try a bigger number\")\n\n else:\n return True # Tell the caller that the player won\n\n return False # Else return that they haven't won yet\n\n except ValueError:\n print(\"That's not a number, try again!\")\n\ndef play_game():\n while True: \n print(\"I'm thinking of a number between 1 and 10.\")\n print(\"Can you guess it?\")\n\n number = random.randint(1, 10)\n counter = 0\n\n while True:\n counter += 1\n\n has_won = make_guess(number)\n\n if has_won:\n print(\"Congratulations, you guessed it! The number was \" + \n str(number) + \".\\nIt took you \" + str(counter) + \" tries!\")\n\n if check_replay():\n break\n\n else:\n return\n</code></pre>\n\n<p>Normally I don't like using <code>while True</code>, but to avoid it here you'd need to use flags all over instead which I don't think would help readability.</p>\n\n<p>Altogether, I have:</p>\n\n<pre><code>import random\n\ndef make_guess(computer_number): # Pass in the target number\n while True:\n guess = input(\"Your guess: \")\n\n try:\n val = int(guess)\n\n if val not in set(range(0, 11)):\n print(\"Hmmm.. that number is not between 1 and 10! Try again!\")\n\n elif val &gt; computer_number:\n print(\"Too high, try a smaller number\")\n\n elif val &lt; computer_number:\n print(\"Too low, try a bigger number\")\n\n else:\n return True # Tell the caller that the player won\n\n return False # Else return that they haven't won yet\n\n except ValueError:\n print(\"That's not a number, try again!\")\n\ndef play_game():\n while True: \n print(\"I'm thinking of a number between 1 and 10.\")\n print(\"Can you guess it?\")\n\n number = random.randint(1, 10)\n counter = 0\n\n while True:\n counter += 1\n\n has_won = make_guess(number)\n\n if has_won:\n print(\"Congratulations, you guessed it! The number was \" + \n str(number) + \".\\nIt took you \" + str(counter) + \" tries!\")\n\n if check_replay():\n break\n\n else:\n return\n\ndef check_replay():\n valid_yes = {\"yes\", \"ye\", \"y\"} # Using sets instead of lists\n valid_no = {\"no\", \"n\"}\n\n while True:\n answer = input(\"Do you want to play again?: \") # Printing the message here instead\n\n if answer.lower() in valid_yes:\n return True\n # I added blank lines for readability\n elif answer.lower() in valid_no:\n print(\"Thanks for playing!\")\n return False\n\n else:\n print(\"Please enter yes or no\")\n\nplay_game()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T14:46:51.180", "Id": "424602", "Score": "0", "body": "Wow I wasn't expecting so much detail that's awesome thanks so much! I think a big problem I had was not really understanding how the while True loop would work, but you've helped a lot! Also some really good advice about code structure!! Thanks a million for the help!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T14:53:56.493", "Id": "424604", "Score": "0", "body": "@Powdie Ya, no problem. I enjoy writing up breakdowns like this." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T17:07:20.717", "Id": "219759", "ParentId": "219749", "Score": "3" } } ]
{ "AcceptedAnswerId": "219759", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T13:57:07.607", "Id": "219749", "Score": "5", "Tags": [ "python", "beginner", "number-guessing-game" ], "Title": "Guess the number game (Python)" }
219749
<p>I have made an exercise where I need to calculate the average per row of a .txt file. (see below)</p> <pre><code>Toa Narumi gradeA 10 8 7 4 6,5 Jean-François Le Clerk gradeB 5 4 7 Joe GradeC 10 10 </code></pre> <p>I only want the numbers behind the name and grade. This is my code:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Linq; namespace RenoD_Oef_Strings { class Program { static void Main(string[] args) { // Variablen StreamReader bestand = new StreamReader(@"F:\RenoD_Oef_Strings\Punten.txt"); string strRow; // String used to read every row of .txt file double?[] dblPoints; // Double array used to store all values List&lt;string&gt; strInput = new List&lt;string&gt;(); // String List used to store all data from .txt // Code while ((strRow = bestand.ReadLine()) != null) // Read row per row in .txt { strInput = strRow.Split(' ').ToList(); // Puts every word in the row in to the list int intX = 0; foreach(string strX in strInput) // Calculate how many strings are in the list { intX++; } dblPoints = new double?[intX]; // Calculate the max number of elements the double array can have intX = 0; foreach(var x in strInput) // Checks if elements in the list can be converted in to a double { try { double dblR = Convert.ToDouble(x); // If element can be converted in to a double, it will be stored in the double array dblPoints[intX] = dblR; intX++; } catch { intX++; // If element CAN NOT be converted in to a double, it will be still be stored in the double array but without any value } } double dblAverage = 0; // Double used to save the total average of one row intX = 0; foreach(var k in dblPoints) { if (k.HasValue) // Elements without value will be ignored { dblAverage += Convert.ToDouble(k); // All double values will be added up intX++; // Used to see how much double values there are to calculate average } } dblAverage = Math.Round(dblAverage/intX, 2); // Calculate average + round up to two decimals Console.WriteLine(dblAverage.ToString()); } bestand.Close(); Console.ReadKey(); } } } </code></pre> <p>What I have done is</p> <ul> <li><p>Read row per row .txt file</p></li> <li><p>Put all elements of that row in a list</p></li> <li><p>Calculate how many elements that the double array will need to store (same number of elements the list has), which I later on use to store all doubles of the list</p></li> <li><p>Check if elements in the list can be converted in to a double array; If the element can be converted in to a double, it will be stored in the double array. </p></li> </ul> <p>If element CAN NOT be converted in to a double, it will be still be stored in the double array but without any value.</p> <ul> <li>Only calculate the average of the elements in my double array that have values.</li> </ul> <p>I have tested the code, and it works without any issue. </p> <p>My question is, have I taken a good approach? What would you have done to make it more efficient?</p> <p>I have tried searching in other threads for solutions. I have seen simular questions, but was unable to find any exactly the same as my exercise.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T15:57:27.110", "Id": "424464", "Score": "1", "body": "Some tips: Dont mix german and english words. You use an object oriented language: Try to structure your code in functions. Then try to structure your code in classes. Dont mention the type of a variable in its name. This is old fashioned style. Dont write unnecessary code - use the appropriate methods of your language. If you explicitly want to implement already implemented features by yourself - use the \"reinventing-the-wheel\"-tag. Good luck and a lot of fun!" } ]
[ { "body": "<ul>\n<li>Enclose the file reading in a <code>using</code> statement</li>\n<li>Use <code>double.TryParse</code> or regex to parse the numbers</li>\n<li>Use Linq extention method <code>Average()</code> to calculate average</li>\n<li>The size of <code>strInput</code> is <code>strInput.Count</code>, no need for a loop </li>\n</ul>\n\n<p>Hear is a simpler code:</p>\n\n<pre><code>using (StreamReader bestand = new StreamReader(@\"F:\\RenoD_Oef_Strings\\Punten.txt\"))\n{\n string strRow; // String used to read every row of .txt file\n // Code\n while ((strRow = bestand.ReadLine()) != null) // Read row per row in .txt\n {\n List&lt;string&gt; strInput = strRow.Split(' ').ToList(); // String List used to store all data from .txt\n List&lt;double&gt; dblPoints = new List&lt;double&gt;(); // Double list used to store all values\n\n foreach (var x in strInput) // Checks if elements in the list can be converted in to a double \n {\n if (double.TryParse(x, out double result))\n {\n dblPoints.Add(result);\n }\n }\n double dblAverage = dblPoints.Average();\n\n Console.WriteLine(dblAverage.ToString());\n }\n}\n\nConsole.ReadKey();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T13:11:15.167", "Id": "424458", "Score": "0", "body": "Thank you for your reply! It is indeed way simpeler." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T16:11:29.537", "Id": "424611", "Score": "0", "body": "Clean and does the trick. There is theoretical edge case where a grade could be NaN, which passes the TryParse check but the average would also be a NaN. If this could be a possibility, it would need to be accounted for." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T12:09:26.857", "Id": "219752", "ParentId": "219751", "Score": "2" } } ]
{ "AcceptedAnswerId": "219752", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T11:37:08.553", "Id": "219751", "Score": "1", "Tags": [ "c#", "console", "io" ], "Title": "Calculate average from .txt file" }
219751
<p>I'm trying to learn python and I'm modeling a simple dice game that a friend and I invented.</p> <p>On any one turn of the game, you must roll a specific combination to stay in the game.</p> <p>The particular rule I'm trying to model is this:</p> <p>Given a previous roll (where the dice are contiguous) make another contiguous roll either above the previous roll or before it. 6 and 1 are considered contiguous. Outside of being contiguous the order of the dice does not matter...</p> <p>some examples</p> <blockquote> <p>existing roll (3, 4) valid subsequent rolls: (1, 2) (5, 6)</p> <p>existing roll (5, 6) valid subsequent rolls: (1, 2) (3, 4)</p> <p>existing roll (6, 1) valid subsequent rolls: (2, 3) (4, 5)</p> </blockquote> <p>I have written the below python3 code to deal with this aspect of the game. However, being new to python, I'd like to know how experienced programmers would deal with this problem. Is there a smarter way to do this programmatically without all the sorting and comparisons and having to make the two arbitrary evaluations? All comments are welcome, readability, efficiency etc. Thanks for your time. </p> <p>arguments:</p> <p>prev = previous/ existing roll</p> <p>curr = current roll to check</p> <p>sides = number of sides of the dice</p> <p>Program:</p> <pre><code>from itertools import cycle, islice def chkStk(prev, curr, sides): def srt(a): return sorted(a, reverse=True if (min(a), max(a)) == (1, sides) else False) def cmp(a): return a == list(x for x in islice(cycle(range(1, sides+1)), a[0]-1, a[0]+len(a)-1)) curr = srt(curr) prev = srt(prev) return cmp(prev+curr) or cmp(curr+prev) # examples print(chkStk([3, 4], [1, 2], 6)) print(chkStk([3, 4], [5, 6], 6)) print(chkStk([5, 6], [1, 2], 6)) print(chkStk([5, 6], [3, 4], 6)) print(chkStk([6, 1], [2, 3], 6)) print(chkStk([6, 1], [4, 5], 6)) # counter examples print(chkStk([6, 1], [6, 1], 6)) print(chkStk([1, 1], [1, 1], 6)) print(chkStk([1, 2], [4, 5], 6)) </code></pre> <p>output:</p> <pre><code>True True True True True True False False False [Finished in 0.1s] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T16:25:50.993", "Id": "424470", "Score": "2", "body": "You should look at the *modulo* operation, which uses the `%` binary operator in most C-inspired languages. You can test for `(a - b) % 6 == 1` to check contiguity, and `abs(a - b) % 6 == 2` to test for adjacency." } ]
[ { "body": "<p>Here is how you might do it.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def tuples_adjacent(a, b, modulus) -&gt; bool:\n def sequential(x, y):\n return (y-x) % modulus == 1\n assert sequential(*a) and sequential(*b)\n return sequential(a[1],b[0]) or sequential(b[1],a[0])\n</code></pre>\n\n<p>This will raise an <code>AssertionError</code> on <code>tuples_adjacent((1,1), (1,1), 6)</code> because the tuples do not meet the precondition of being consecutive pairs. I'm not sure if that is exactly what you want without seeing the surrounding program. You can decide if you actually just want to <code>return False</code> if that precondition is not met.</p>\n\n<p>The other commenter mentioned <code>abs(a-b)%6==2</code> for checking adjacency, but this is incorrect and fails for the case <code>a=5</code>, <code>b=1</code>. You instead have to do <code>(a-b)%m in {2,m-2}</code>. In general, absolute value and modulus do not play well with each other.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T21:41:51.027", "Id": "219775", "ParentId": "219753", "Score": "2" } }, { "body": "<h1>Specification</h1>\n\n<p>I'm having trouble understanding the problem. I <em>think</em> you roll two dice at once, and the results must be distinct and adjacent to each other and to the previous roll.</p>\n\n<h1>Comments</h1>\n\n<p>Your question includes some explanation before the program:</p>\n\n<blockquote>\n <p>I'm modeling a simple dice game that a friend and I invented.</p>\n \n <p>On any one turn of the game, you must roll a specific combination to stay in the game.</p>\n \n <p>The particular rule I'm trying to model is this:</p>\n \n <p>Given a previous roll (where the dice are contiguous) make another contiguous roll either above the previous roll or before it. 6 and 1 are considered contiguous. Outside of being contiguous the order of the dice does not matter...</p>\n</blockquote>\n\n<p>This should be part of the program! It could be a docstring at the beginning of the file.</p>\n\n<blockquote>\n <p>arguments:</p>\n \n <p>prev = previous/ existing roll</p>\n \n <p>curr = current roll to check</p>\n \n <p>sides = number of sides of the dice</p>\n</blockquote>\n\n<p>These should also be part of the program! They should be part of <code>chkStk</code>'s docstring, or better yet, included in the argument names. <code>prev</code> and <code>curr</code> could be called <code>previous_roll</code> and <code>current_roll</code>.</p>\n\n<p><code>srt</code> returns its argument in order, unless it contains both bounds, in which case it's reversed. This is surprising, so it requires an explanation in a comment or docstring.</p>\n\n<h2>Names</h2>\n\n<p>All three function names are inscrutably short.</p>\n\n<ul>\n<li><code>srt</code> sorts its argument (which should be a two-element list) in a cyclic order. So it could be called <code>cyclic_order</code>.\n\n<ul>\n<li><code>srt</code>'s argument <code>a</code> is a 2-die roll (i.e. a pair), so it should be called <code>pair</code> or <code>roll</code>.</li>\n</ul></li>\n<li><code>cmp</code> checks whether its argument is a contiguous ascending sequence (in the same cyclic order). So it could be called <code>contiguous</code> or <code>is_contiguous</code> or <code>is_ascending</code> or even <code>in_order</code>.\n\n<ul>\n<li><code>cmp</code>'s argument <code>a</code> is a list of (1-die) rolls, so it should be called <code>rolls</code>.</li>\n</ul></li>\n<li><code>chkStk</code> checks whether <code>curr</code> is a valid roll after <code>prev</code>, so it should be called something like <code>valid_roll</code> or <code>is_valid_roll</code> or `</li>\n</ul>\n\n<p>(It's confusing to have <code>roll</code> mean a pair of 1-die rolls, so maybe the whole program should switch to something consistent, such as \"roll\" for one die and \"pair\" for two dice.)</p>\n\n<h1>Small simplifications</h1>\n\n<p><code>True if boolean_expression else False</code> can be simplified to just <code>boolean_expression</code>.</p>\n\n<p>[debatable] <code>(min(a), max(a)) == (1, sides)</code> is short, but most people are accustomed to reading <code>min(a) == 1 and max(a) == sides</code>.</p>\n\n<p>Even better: since <code>1</code> and <code>sides</code> are the minimum and maximum values possible, you can skip the <code>min</code> and <code>max</code> and just check whether the values are present: <code>1 in a and sides in a</code>.</p>\n\n<p><code>list(x for x in foo)</code> can be simplified to just <code>list(foo)</code>.</p>\n\n<h1>Simpler ways</h1>\n\n<p>In <code>cmp</code>, instead of building a sequence in cyclic order and comparing to it, it might be simpler to check that each successive pair is in cyclic order.</p>\n\n<p>There are easier ways to solve this problem.</p>\n\n<p>If my restatement of the problem above (\"the results must be adjacent to each other and to the previous roll\") is correct, it can be easily turned into a program. You can simply check each part (possibly in a helper function):</p>\n\n<ul>\n<li>whether two dice of a pair are adjacent to each other</li>\n<li>whether two pairs are adjacent to each other</li>\n</ul>\n\n<p>You can do both of these without any list operations.</p>\n\n<h1>Tests</h1>\n\n<p>Instead of printing out results for you to check, your test cases can check them for you! The simplest way to do this is with <code>assert</code>:</p>\n\n<pre><code>assert chkStk([5, 6], [1, 2], 6)\nassert not chkStk([5, 6], [1, 4], 6)\nassert not chkStk([6, 1], [2, 1], 6), 'overlapping pairs should fail'\n</code></pre>\n\n<p>This won't print anything unless the test fails. You can include an optional error message.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T10:22:12.293", "Id": "424561", "Score": "0", "body": "Thanks, this is a great answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T22:54:21.947", "Id": "219778", "ParentId": "219753", "Score": "3" } } ]
{ "AcceptedAnswerId": "219778", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T15:24:56.930", "Id": "219753", "Score": "2", "Tags": [ "python", "python-3.x", "circular-list" ], "Title": "Checking against a specific sequence in python" }
219753
<p>I have improved my <a href="https://codereview.stackexchange.com/questions/219702/breadth-first-search-in-java-competitive-style">BFS in Java</a> according to vnp's suggestions. Again, we wish to find shortest paths in directed unweighted graphs using BFS, competitive style (no <code>Map</code>s, <code>Set</code>'s or <code>List</code>s):</p> <pre><code>import java.util.Arrays; class BFS { static int[] bfs(int[][] graph, int sourceNode, int targetNode) { int[] queue = new int[graph.length]; int[] parents = new int[graph.length]; for (int i = 0; i &lt; parents.length; i++) { parents[i] = -1; // -1 denotes 'not used' } int queueStartIndex = 0; int queueEndIndex = 1; queue[0] = sourceNode; parents[sourceNode] = -2; while (queueStartIndex &lt; queueEndIndex) { int currentNode = queue[queueStartIndex++]; if (currentNode == targetNode) { return buildPath(targetNode, parents); } for (int childNode : graph[currentNode]) { if (parents[childNode] == -1) { parents[childNode] = currentNode; queue[queueEndIndex++] = childNode; } } } return null; } private static int[] buildPath(int targetNode, int[] parents) { int pathLength = 0; int node = targetNode; while (node &gt;= 0) { pathLength++; node = parents[node]; } int[] path = new int[pathLength]; int pathIndex = path.length - 1; int currentNode = targetNode; while (currentNode &gt;= 0) { path[pathIndex--] = currentNode; currentNode = parents[currentNode]; } return path; } /* B ----+ / | A E \ / C - D */ public static void main(String[] args) { int a = 0; int b = 1; int c = 2; int d = 3; int e = 4; int[][] graph = new int[5][]; graph[a] = new int[]{ c, b }; graph[b] = new int[]{ e }; graph[c] = new int[]{ d }; graph[d] = new int[]{ c, e }; graph[e] = new int[]{ b, d }; // A -&gt; B -&gt; E int[] path = bfs(graph, a, e); System.out.println(Arrays.toString(path)); // A &lt;- B &lt;- E does not exist: System.out.println(Arrays.toString(bfs(graph, e, a))); graph = new int[4][]; graph[a] = new int[]{ b, c }; graph[b] = new int[]{ d }; graph[c] = new int[]{ a, d }; graph[d] = new int[]{ b, c }; /* B / \ A D \ / C */ // A -&gt; B -&gt; D path = bfs(graph, a, d); System.out.println(Arrays.toString(path)); path = bfs(graph, d, a); // D -&gt; C -&gt; A: System.out.println(Arrays.toString(path)); } } </code></pre> <p>Please tell me anything that comes to mind.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T07:45:57.980", "Id": "424690", "Score": "0", "body": "is there any reason why you implement this code in java? one benefit of java is OOP and your code has not much Objects..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T08:53:49.147", "Id": "424695", "Score": "0", "body": "@MartinFrank (1) It's written in competition in mind where people have no time for implementing, say, graph node types, but instead represent them via simple `int` value. (2) The above requires no Objects..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T10:19:45.250", "Id": "424705", "Score": "0", "body": "well, ok, if that is fine for you ... i don't understand that 'competitive style' yet, time to go back on my books..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T10:33:58.540", "Id": "424708", "Score": "1", "body": "@MartinFrank Google up in YouTube \"acm icpc world finals 2018\" ;)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T10:35:34.157", "Id": "424710", "Score": "0", "body": "thank you very very much on how to find that - googling 'competive style' was rather worthless !!!" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T16:47:52.470", "Id": "219758", "Score": "2", "Tags": [ "java", "algorithm", "array", "breadth-first-search" ], "Title": "Breadth-first search in Java: Competitive style - follow-up" }
219758
<p>I have a Tree structure composed by <code>Node</code> class.</p> <p>I have to <code>@tailrec</code> method that are visiting up to the root.</p> <p>Those 2 methods are completely similar, but 1 of those is manipulated a "stats" variable to check the visit and return the root, the other just return the root node.</p> <p>Here the code sample:</p> <pre><code>class Node(parent: Option[Node], var visited: Int) @tailrec def asc(): Node = { parent match { case None =&gt; this case Some(x) =&gt; x.asc() } } @tailrec def ascVisited(deltaInc: Inc): Node = { visited += deltaInc parent match { case None =&gt; this case Some(x) =&gt; x.ascVisited(deltaInc) } } </code></pre> <p>Is there any way to reuse the logic of the parent checking and then call recursively the method? I thought with a higher-order function should be possible, but I am not sure is possible with different input argument in the functions.</p> <p>Any suggestion?</p> <p>Is it possible somehow to DRY out these 2 bits :</p> <pre><code>parent match { case None =&gt; this case Some(x) =&gt; x.asc() } // and parent match { case None =&gt; this case Some(x) =&gt; x.ascVisited(deltaInc) } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T18:29:48.657", "Id": "424486", "Score": "0", "body": "Is this real working code? The braces don't match. What's it for? What's `Inc`? Please provide some context. See [ask]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T20:07:05.140", "Id": "424496", "Score": "0", "body": "Edited. Forgot those closing bracing sorry." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T20:09:37.597", "Id": "424497", "Score": "0", "body": "But what do `asc()` and `ascVisited(…)` do? You can't ask us to combine them if you don't show us that code too!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T20:18:16.803", "Id": "424498", "Score": "0", "body": "That is the code. :/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T20:19:06.060", "Id": "424500", "Score": "0", "body": "One is just traversing until the root node. The other is doing the same while changing a node variable" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T06:08:22.733", "Id": "424531", "Score": "1", "body": "Just make `deltaInc` optional by giving it a default value of `0`. Then you only need one method instead of two." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T14:08:06.290", "Id": "424596", "Score": "0", "body": "yes that could be feasible. My idea was to have it more in a \"pure\" form: Also the recursion is calling a different method, is there a way to generalize this kind of tailrec and call the recursion method on some context with higher-order functions?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T14:33:26.787", "Id": "424597", "Score": "0", "body": "probably what i am asking is how to use a flexible callback that it Either accepting None parameter or 1 for this specific case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-09T22:21:07.883", "Id": "429510", "Score": "0", "body": "basically a Higher order function..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-10T08:50:48.190", "Id": "429547", "Score": "0", "body": "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-06-16T19:17:23.813", "Id": "430436", "Score": "0", "body": "@TobySpeight I am not sure the title is too general, but actually could be too specific. It is asking exactly a DRYed alternative version." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T08:46:04.170", "Id": "430504", "Score": "0", "body": "As you'll have read when you followed the \"Asking Questions\" link above, the question title for a Code Review is to **state the task accomplished**. Focusing on a specific weakness of the code isn't done (and it would imply that you weren't really looking for a **review of all aspects of the code**, and might actually have a \"technique\" question more suitable for [so])." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-17T12:37:09.797", "Id": "430555", "Score": "0", "body": "@TobySpeight in some degree, i agree with you. But it is still true what I am asking and in line with what you are asking for changes. it is not a technique it is a software design that i am looking for, that is cross functional and ood. It is abstract by nature as a deal with functions. Anyway can you help to fix both the question, because you can edit, and also to find a Scala solution on that?" } ]
[ { "body": "<p>I defined a Higher-Order function:</p>\n\n<pre><code>@tailrec\ndef foldAsc(op: Node =&gt; Node): Node = {\n op(this) // &lt;= still this statemnt when x=&gt;x is useless.. \n parent match {\n case None =&gt; this\n case Some(x) =&gt; x.foldAsc(op)\n }\n}\n\ndef asc(): Node = foldAsc(x =&gt; x)\n\n\ndef ascVisited(deltaInc: Inc): Node = foldAsc { x =&gt;\n visited += deltaInc\n x\n}\n</code></pre>\n\n<p>It is not still optimal but DRYed out a little.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-10T08:51:08.420", "Id": "429550", "Score": "0", "body": "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]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-16T19:16:02.340", "Id": "430435", "Score": "0", "body": "@TobySpeight the improvement is using a higher order function and DRY the code as was asked." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-09T22:39:23.257", "Id": "221979", "ParentId": "219760", "Score": "-1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "13", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T17:09:43.730", "Id": "219760", "Score": "0", "Tags": [ "functional-programming", "tree", "scala" ], "Title": "Is it possible to DRY these 2 methods of a tailrec Node Tree?" }
219760
<p>I decided to do an algorithms course (Roughgarden's on Coursera), and am setting out to implement each algorithm as it's introduced, in Lisp. We start with mergesort which is introduced as the canonical example of the divide and conquer paradigm.</p> <p>The point of the paradigm being a problem is divided (into two), and solved, then the results are combined. Thus two steps are involved - the solution step and the combination step. We use induction such that subproblems are assumed solved, then we just need the base case. The base case here is that lists of length zero and of length 1 are already sorted so can just be returned.</p> <p>This leaves us with the need to implement two things. First the divide part, then the combination part. In mergesort this means the functions mergesort and merge respectively.</p> <p>Here's what I came up with for mergesort</p> <pre class="lang-lisp prettyprint-override"><code>(defun mergesort (lst) "mergesort is the canonical example of the divide &amp; conquer paradigm" (if (or (null lst) (eq (length lst) 1)) lst (let* ((len (length lst)) (mid (truncate len 2)) (sorted-lower (mergesort (subseq lst 0 mid))) (sorted-upper (mergesort (subseq lst mid len)))) (merge. sorted-lower sorted-upper nil)))) </code></pre> <p>And for merge</p> <pre class="lang-lisp prettyprint-override"><code>(defun merge. (x y acc) "merge two lists by moving lowest car to output list" (cond ((and (null x) (null y)) (reverse acc)) ((null x) (merge. x (cdr y) (cons (car y) acc))) ((null y) (merge. (cdr x) y (cons (car x) acc))) ((&lt;= (car x) (car y)) (merge. (cdr x) y (cons (car x) acc))) (t (merge. x (cdr y) (cons (car y) acc))))) </code></pre> <p>These functions work fine.</p> <p>Now to the problem.</p> <p>The actual pseudocode given by the instructor, and the subsequent algorithmic analysis we're about to do, presumes that mergesort is done recursively (fine), but that merge is done <em>iteratively</em>.</p> <p>But I naturally wrote merge recursively as above without really contemplating using a loop.</p> <p>The instructor offers the following pseudocode</p> <p><a href="https://i.stack.imgur.com/0KSCH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0KSCH.jpg" alt="slide from coursera"></a></p> <p>My thinking this morning has been, since in the next lecture we are going to study the theory of how to analyse the running time of divide and conquer, (including recursion tree method, generalising to the master method - i don't know what these are yet), that it might be better if I had an implementation which followed the actual pseudocode the instructor is assuming. (He did say at the beginning that any <em>imperative</em> language would be fine). But I would like more chance to use Lisp.</p> <p>So, my implementation of the pseudocode give above is follows.</p> <p>This code also works fine so long as we change the last line of mergesort to call merge- with the appropriate signature, which this time is <code>(merge- len sorted-lower sorted-upper)</code>.</p> <pre class="lang-lisp prettyprint-override"><code>(defun merge- (n a b) (let ((acc nil) (ca 0) (cb 0)) (dotimes (i n (reverse acc)) (cond ((null (nth ca a)) (progn (setf acc (cons (nth cb b) acc)) (setf cb (+ cb 1)))) ((or (null (nth cb b)) (&lt;= (nth ca a) (nth cb b))) (progn (setf acc (cons (nth ca a) acc)) (setf ca (+ ca 1)))) (t (progn (setf acc (cons (nth cb b) acc)) (setf cb (+ cb 1)))))))) </code></pre> <p>But boy, that code isn't half ugly!</p> <p>I also spent at least half an hour simply not having a clue why it wasn't initially working. The reason was that I'd "forgotten" to use <code>setf</code> on <code>acc</code>, a notion totally at odds to the recursive version where instead of altering state we are defining divisions of the function and variables are irrelevant.</p> <p>Since Common Lisp is multi-paradigm, I was wondering if the iterative version can be improved upon? </p> <p>Would it be uncontroversial in the lisp community to observe that the recursive version is simply going to be better &amp; more natural?</p> <p>(and if that's the case, then why does this apply especially to lisp and less so to other languages? but lets not get into that transcendent question just yet! (maybe the answer is because we're using lists... which is maybe the key thing that makes recursion natural ... (?)))</p> <p><strong>Update 1</strong>: In response to Rainer's comment, here's a version using vectors:</p> <pre class="lang-lisp prettyprint-override"><code>(defun merge- (x y) "merge sorted lists (or vectors) x &amp; y into sorted array" (let ((a (make-array (length x) :initial-contents x)) (b (make-array (length y) :initial-contents y)) (c (make-array (+ (length x) (length y)))) (i 0) (j 0)) (dotimes (k (length c) c) (cond ((= i (length a)) (setf (svref c k) (svref b j) j (1+ j))) ((= j (length b)) (setf (svref c k) (svref a i) i (1+ i))) ((&lt; (svref a i) (svref b j)) (setf (svref c k) (svref a i) i (1+ i))) (t (setf (svref c k) (svref b j) j (1+ j))))))) </code></pre> <p>I'm wondering if style in the cond block above can be improved, or if that's how you'd normally do it?</p> <p><strong>Update 2</strong>: In response to Rainer's answer, I've written this new version of mergesort incorporating his suggestions (those I feel I fully understand at this point). Thank you Rainer.</p> <pre class="lang-lisp prettyprint-override"><code>(defun mergesort (lst) "mergesort is the canonical example of the divide &amp; conquer paradigm" (flet ((merge- (a b) "merge sorted arrays a &amp; b into sorted array c" (let ((c (make-array (+ (length a) (length b)))) (i 0) (j 0)) (dotimes (k (length c) c) (when (= i (length a)) ; [1] (setf (subseq c k) (subseq b j)) ; [2] (return c)) ; [3] (when (= j (length b)) (setf (subseq c k) (subseq a i)) (return c)) (setf (aref c k) (if (&lt; (aref a i) (aref b j)) ; [4] (prog1 (aref a i) (incf i)) (prog1 (aref b j) (incf j)))))))) (if (= (length lst) 0) nil (if (= (length lst) 1) (make-array 1 :initial-element (first lst)) ; [5] (let* ((len (length lst)) (mid (truncate len 2))) (merge- (mergesort (subseq lst 0 mid)) (mergesort (subseq lst mid len)))))))) ;; Notes ;; [1] when has an implicit progn ;; [2] use subseq in settable context to fill remaining array ;; [3] return from the implicit nil block created by dotimes ;; [4] the 2nd arg to setf becomes a conditional, with prog1 used to return ;; value of first arg, while tucking in the extra step needed in each case. ;; this is an advance in expressivity compared to c-style languages. ;; you can't do, there, for example: ;; a[3] = if(x &lt; y) 2; else 3; ;; so in c/java you *must* say it this way, which is repetitive: ;; if x &lt; y, a[3] = 2; else a[3] = 3; ;; [5] Base case of mergesort now returns an array, not a list. ;; That meant we can remove conversion of list to array in let. ;; Mergesort now receives list, but generates vector, right from the base case. </code></pre> <p>I'm very intrigued by the syntactical advance(?) over c-style languages which I mention in <code>Note [4]</code> above. </p> <p>Any further discussion on that or any other points would be greatly appreciated :) thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T20:20:57.103", "Id": "424502", "Score": "2", "body": "working with NTH and LENGTH on lists? Does that make sense? The algorithm is for vectors. Lisp has vectors, too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T09:28:27.943", "Id": "424554", "Score": "0", "body": "You're right, maybe it doesn't much. But I had in mind the advice about Lisp that you can usually use lists for a first attempt, then change to other data-structures later. I'll add a version using vectors..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T15:32:33.580", "Id": "424608", "Score": "0", "body": "@RainerJoswig I've added a version using vectors, above." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T15:36:18.770", "Id": "424609", "Score": "0", "body": "I think the four-part cond above could be improved upon, not entirely sure what the best way to do that would be right now. Will update when I get a better idea, unless anyone would care to chip in in the meantime... :)" } ]
[ { "body": "<p>There are some cases to be considered. Though we can write it slightly different:</p>\n\n<pre><code>CL-USER 32 &gt; (let ((a #(1 5 8 10 11)) (b #(1 2 6 7 10)))\n (flet ((merge- (x y\n &amp;aux\n (lx (length x)) (ly (length y)) (lc (+ lx ly))\n (c (make-array lc))\n (i 0) (j 0))\n \"merge sorted vectors x &amp; y\"\n (dotimes (k lc c)\n (when (= i lx)\n (setf (subseq c k) (subseq b j))\n (return c))\n (when (= j ly)\n (setf (subseq c k) (subseq a i))\n (return c))\n (setf (aref c k)\n (if (&lt; (aref a i) (aref b j))\n (prog1 (aref a i) (incf i))\n (prog1 (aref b j) (incf j)))))))\n (merge- a b)))\n#(1 1 2 5 6 7 8 10 10 11)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T10:47:48.043", "Id": "424715", "Score": "0", "body": "Nice use of `subseq` in a settable context to fill in remainder of the output array `c`, when one of the input arrays has been exhausted. This isn't how 'arrays' work in c-style languages! :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T10:57:08.527", "Id": "424718", "Score": "0", "body": "I also note that `when` is exactly the same as `if` but with an implicit `progn`. nice. Plus the `return`s you've added for speed refer to the implicit block named `nil` created by `dotimes` (`when` doesn't create an implicit block of course - there would seem little use in that even if it did(?))." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T16:41:34.770", "Id": "219816", "ParentId": "219761", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T17:20:08.253", "Id": "219761", "Score": "2", "Tags": [ "common-lisp" ], "Title": "merge function for mergesort - recursion vs. iteration" }
219761
<p>I am converting an old Objective-C class into Swift. My actual question is at the very end after all of the code.</p> <p>Here is a cut-down version of the Objective-C class:</p> <p>DateInfo.h:</p> <pre class="lang-c prettyprint-override"><code>#import &lt;Foundation/Foundation.h&gt; @interface RMYearInfo : NSObject // There are also some instance properties but those aren't relevant to the question + (NSInteger)numberOfMonths; + (NSArray *)shortMonthNames; + (NSArray *)longMonthNames; // several other class methods @end </code></pre> <p>DateInfo.m:</p> <pre class="lang-c prettyprint-override"><code>#import "DateInfo.h" static NSArray *shortMonthNames = nil; static NSArray *longMonthNames = nil; // there are several other statics as well @implementation DateInfo + (void)reinitialize { NSCalendar *cal = [NSCalendar currentCalendar]; NSDateFormatter *yearFormatter = [[NSDateFormatter alloc] init]; shortMonthNames = [yearFormatter shortStandaloneMonthSymbols]; longMonthNames = [yearFormatter standaloneMonthSymbols]; // lots of other processing for the other statics } + (void)initialize { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reinitialize) name:NSCurrentLocaleDidChangeNotification object:nil]; [self reinitialize]; } + (NSInteger)numberOfMonths { return shortMonthNames.count; } + (NSArray *)shortMonthNames { return shortMonthNames; } + (NSArray *)longMonthNames { return longMonthNames; } // Lots of other instance and class methods </code></pre> <p>As you can see, the <code>initialize</code> method sets up a notification handler so all of the static variables can be reinitialized if the locale is changed while the app is running.</p> <p>Here is my Swift code. Since there is no <code>initialize</code> in Swift (any more), my solution is to use private backing variables for the public static variables.</p> <pre class="lang-swift prettyprint-override"><code>import Foundation public struct DateInfo { // some normal instance properties irrelevant to the question private static var _formatter: DateFormatter! private static var formatter: DateFormatter { if _formatter == nil { _formatter = DateFormatter() NotificationCenter.default.addObserver(forName: NSLocale.currentLocaleDidChangeNotification, object: nil, queue: nil) { (notification) in _formatter = DateFormatter() _shortMonthNames = nil _longMonthNames = nil // reset all of the other statics as well } } return _formatter } private static var _shortMonthNames: [String]! public static var shortMonthNames: [String] { if _shortMonthNames == nil { _shortMonthNames = formatter.shortStandaloneMonthSymbols } return _shortMonthNames } private static var _longMonthNames: [String]! public static var longMonthNames: [String] { if _longMonthNames == nil { _longMonthNames = formatter.standaloneMonthSymbols } return _longMonthNames } public static var numberOfMonths: Int { return shortMonthNames.count } // lots of other similar private/public pairs of statics } </code></pre> <p>Is this an appropriate way to translate the functionality given the need to be able to reinitialize the statics? I don't like having a private static backing each public static property.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T12:19:03.733", "Id": "424585", "Score": "0", "body": "There is an `init` in swift: https://docs.swift.org/swift-book/LanguageGuide/Initialization.html" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T16:16:33.283", "Id": "424612", "Score": "0", "body": "@muescha I'm not referring to `init`. I'm referring to the Objective-C class method `initialize` which Swift also had until Swift 3 (I think that's when it went away)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T17:20:25.400", "Id": "424801", "Score": "0", "body": "I don't find this objective-c method with Google in older swift releases" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T17:22:59.003", "Id": "424803", "Score": "0", "body": "i just have no idea - can you help me: what is so different between the initialize and the init? Why you like to call an objective-c method in a pure swift implementation..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-08T00:36:37.973", "Id": "424837", "Score": "0", "body": "@muescha See [NSObject +load and +initialize - What do they do?](https://stackoverflow.com/questions/13326435/nsobject-load-and-initialize-what-do-they-do) for an explanation of what the Objective-C `initialize` method does. See [Swift 3.1 deprecates initialize(). How can I achieve the same thing?](https://stackoverflow.com/questions/42824541/swift-3-1-deprecates-initialize-how-can-i-achieve-the-same-thing) for a discussion about Swift eliminating the same method." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-09T13:15:15.527", "Id": "425051", "Score": "0", "body": "Thx for the links" } ]
[ { "body": "<p>Some thoughts:</p>\n\n<ul>\n<li>Make <code>formatter</code> a static <em>stored</em> property (which are guaranteed to be lazily initialized only once). This allows to get rid of the backing property <code>_formatter</code>.</li>\n<li>For more clarity, move the reinitialization code to a separate method, as in your Objective-C version.</li>\n<li>Do not cache the other static properties. For example, returning <code>formatter.shortStandaloneMonthSymbols</code> is only one indirection more than returning <code>_shortMonthNames</code>, but is simpler and allows to get rid of the remaining backing properties. </li>\n<li>A minor point: The notification closure does not access the <code>(notification)</code> argument, which can therefore be replaced by <code>_</code>.</li>\n</ul>\n\n<p>Putting it together, we have the following implementation:</p>\n\n<pre><code>public struct DateInfo {\n\n private static func reinitialize() {\n formatter = DateFormatter()\n }\n\n private static var formatter: DateFormatter = {\n // This closure is executed exactly once, on the first accesss of the `formatter` property.\n NotificationCenter.default.addObserver(forName: NSLocale.currentLocaleDidChangeNotification, object: nil, queue: nil) { _ in\n reinitialize()\n }\n return DateFormatter()\n }()\n\n public static var shortMonthNames: [String] {\n return formatter.shortStandaloneMonthSymbols\n }\n\n public static var longMonthNames: [String] {\n return formatter.standaloneMonthSymbols\n }\n\n public static var numberOfMonths: Int {\n return shortMonthNames.count\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Another option would be to use the typical <a href=\"https://developer.apple.com/documentation/swift/cocoa_design_patterns/managing_a_shared_resource_using_a_singleton\" rel=\"nofollow noreferrer\">Singleton pattern</a>:</p>\n\n<pre><code>public class DateInfo {\n static let shared = DateInfo()\n\n private var formatter: DateFormatter\n\n private init() {\n formatter = DateFormatter()\n NotificationCenter.default.addObserver(forName: NSLocale.currentLocaleDidChangeNotification, object: nil, queue: nil) { _ in\n self.formatter = DateFormatter()\n }\n }\n\n public var shortMonthNames: [String] {\n return formatter.shortStandaloneMonthSymbols\n }\n\n public var longMonthNames: [String] {\n return formatter.standaloneMonthSymbols\n }\n\n public var numberOfMonths: Int {\n return shortMonthNames.count\n }\n}\n</code></pre>\n\n<p>The advantage is that all initialization is clearly done in the init method. A small disadvantage might be that more typing is needed to access the properties (e.g. <code>DateInfo.shared.shortMonthNames</code>).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T20:14:37.823", "Id": "219772", "ParentId": "219765", "Score": "3" } }, { "body": "<p>A few observations:</p>\n\n<ul>\n<li><p>I might suggest that we want to use stored properties, like the original Objective-C code. I would be wary of using computed properties that return collections, as that can introduce non-obvious performance hits if you reference this computed property repeatedly, causing the whole array to be re-retrieved multiple times. Admittedly, this collection is small enough, it’s unlikely to be material, but it is something to be sensitive to when dealing with computed properties and collections. </p></li>\n<li><p>I see no reason to store the <code>DateFormatter</code>. If you are using it for other purposes, then go ahead and do that, but there is nothing in this example that suggests that is the case.</p></li>\n<li><p>I’d personally go towards a singleton, too</p></li>\n</ul>\n\n<p>Thus, perhaps something like:</p>\n\n<pre><code>class DateInfo {\n static let shared = DateInfo()\n\n private(set) var shortMonthNames: [String] = []\n private(set) var longMonthNames: [String] = []\n private(set) var numberOfMonths: Int = 0\n\n private init() {\n NotificationCenter.default.addObserver(forName: NSLocale.currentLocaleDidChangeNotification, object: nil, queue: nil) { [weak self] _ in\n self?.update()\n }\n update()\n }\n\n private func update() {\n let formatter = DateFormatter()\n shortMonthNames = formatter.shortStandaloneMonthSymbols\n longMonthNames = formatter.standaloneMonthSymbols\n numberOfMonths = shortMonthNames.count\n }\n}\n</code></pre>\n\n<p>And, if you have view controllers that are also observing <code>.currentLocaleDidChangeNotification</code>, you might want to eliminate any race conditions by introducing your own notification, e.g. <code>.dateInfoChanged</code>:</p>\n\n<pre><code>extension Notification.Name {\n static let dateInfoChanged = Notification.Name(rawValue: Bundle.main.bundleIdentifier! + \".dateInfoChanged\")\n}\n</code></pre>\n\n<p>And then:</p>\n\n<pre><code>class DateInfo {\n static let shared = DateInfo()\n\n private(set) var shortMonthNames: [String] = []\n private(set) var longMonthNames: [String] = []\n private(set) var numberOfMonths: Int = 0\n\n private init() {\n NotificationCenter.default.addObserver(forName: NSLocale.currentLocaleDidChangeNotification, object: nil, queue: nil) { [weak self] _ in\n self?.update()\n NotificationCenter.default.post(name: .dateInfoChanged, object: nil)\n }\n update()\n }\n\n private func update() {\n let formatter = DateFormatter()\n shortMonthNames = formatter.shortStandaloneMonthSymbols\n longMonthNames = formatter.standaloneMonthSymbols\n numberOfMonths = shortMonthNames.count\n }\n}\n</code></pre>\n\n<p>Then view controllers can observe <code>.dateInfoChanged</code>, and you’ll be confident that they’ll be getting this month info after it was updated.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-15T19:10:47.373", "Id": "425655", "Score": "1", "body": "I like the suggestion about the custom notification. I haven't gotten far enough to actually test the locale changes yet but I can clearly see how this suggestion would be useful." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-14T18:04:22.687", "Id": "220247", "ParentId": "219765", "Score": "3" } } ]
{ "AcceptedAnswerId": "219772", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T18:39:19.927", "Id": "219765", "Score": "4", "Tags": [ "swift", "objective-c", "static" ], "Title": "Translating Objective-C use of static and +(void)initialize to Swift" }
219765
<p>For the <a href="https://en.wikipedia.org/wiki/Readers%E2%80%93writers_problem#First_readers-writers_problem" rel="nofollow noreferrer">first readers-writers problem</a>, in which readers can access a given resource simultaneously, is the following Python3 solution correct?</p> <p>Problem parameters:</p> <ul> <li>One set of data is shared among a number of threads</li> <li>Only one writer may write at a time, and no other thread can read the resource</li> <li>If at least one reader is reading, no other thread can write</li> <li>Multiple readers can read the resource without blocking each other</li> </ul> <pre class="lang-py prettyprint-override"><code>import threading, time from multiprocessing import Condition class SharedResource(): def __init__(self): self.val = 0 # The class solving this problem class RWLock: def __init__(self): self.cond = Condition() self.readers = 0 def read_acquire(self): self.cond.acquire() self.readers += 1 self.cond.release() def read_release(self): with self.cond: self.readers -= 1 if (self.readers == 0): self.cond.notify_all() def write_acquire(self): self.cond.acquire() if (self.readers &gt; 0): self.cond.wait() def write_release(self): self.cond.release() def read(lock, res): while True: lock.read_acquire() print(threading.current_thread().ident, "Reading:",res.val) time.sleep(0.5) lock.read_release() def write(lock, res): while True: lock.write_acquire() print(threading.current_thread().ident, "Writing") res.val += 1 time.sleep(1) lock.write_release() if __name__ == '__main__': lock = RWLock() res = SharedResource() for i in range(10): t = threading.Thread(target=read, args=(lock,res,)) t.start() for i in range(10): t = threading.Thread(target=write, args=(lock,res,)) t.start() </code></pre> <p>I did not find any solution online using a single condition, and have been trying to find a loophole in this one. From what I have gathered, it fulfills the problem's requisites.</p> <p>Two questions:</p> <ul> <li>Does the solution fulfill the problem's requisites?</li> <li>Is the above code correct?</li> </ul> <p>What are your thoughts on this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T19:01:20.790", "Id": "424488", "Score": "1", "body": "Welcome to Code Review! Please post the (abbreviated) challenge description with your question. Also please note that checking the correctness of your code is not [what this site is about](https://codereview.stackexchange.com/help/on-topic)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T18:39:49.863", "Id": "219766", "Score": "1", "Tags": [ "python", "multithreading", "locking", "producer-consumer", "multiprocessing" ], "Title": "First readers-writers problem using a single condition" }
219766
<p>Thank you to everyone for the feedback provided to the initial version of this program <a href="https://codereview.stackexchange.com/questions/219618/python-3-simple-temperature-program">posted here</a>.</p> <p>Please find below the newest version, revised based on the comments provided, for review and comment on how I can further improve my coding.</p> <p>I have removed the portion of the program that checked if the provided value was a legitimate temperature, as this was useless code only showing that I had recently learned what the opposite of absolute zero was....who cares, and who cares what value the user wants to convert!</p> <p>I look forward to your feedback.</p> <pre><code>#!/usr/bin/python """ Program: Temperature Conversion (C to F, or F to C) Date: 05 May 2019 Version: 1.2 Author: Jason P. Karle Remark: This program was inspired by a Python exercise that asks you to create a program that will convert one Celsius value to Fahrenheit; so a program that can be executed with three lines of code. However, I wanted to make something that would allow the user to convert to and from either C of F, and do so multiple times, until the user decides to end the program. This was also an exercise for me to advance not only my code skills, but how I structure a program. version history: 1.0 Initial draft 1.1 Correction of runtime; posted to StackExchange for feedback 1.2 Re-coded based on feedback; trying to improve flow control """ def read_selection(): selection = input('''Welcome to the temperature conversion program! Please make a selection: c to convert from Celcius to Fahrenheit; f to convert from Fahrenheit to Celsius; or q to quit the program. Enter your selection: ''').lower() return selection def value_input(selection): value = input('''\nPlease enter the temperature you want to convert: ''') try: value = float(value) except ValueError: print('That is not a number!\n') else: if selection == 'c': convert_c2f(value) else: convert_f2c(value) # return value def convert_c2f(value): print(f'The answer is: {(value * (9/5)) + 32}°F\n') return def convert_f2c(value): print(f'The answer is: {(value-32) * (5/9)}°C\n') return def main(): while True: selection = read_selection() if selection == 'q': return elif selection == 'c' or selection == 'f': value_input(selection) '''convert_c2f() elif selection == 'f': convert_f2C()''' else: print('Invalid selction. Try again.\n') if __name__ == '__main__': main() </code></pre>
[]
[ { "body": "<p>You're not following PEP8 and you still have a spaghetti mind-set. Each function should have a single responsibility.</p>\n\n<p><code>value_input</code> however is in charge of:</p>\n\n<ol>\n<li>Asking and validating user input.</li>\n<li>Handling how to convert the input.</li>\n<li>Convert and display the input.</li>\n</ol>\n\n<p><br>\nThis should instead only perform the first task I've said above. After this you should have the calling code perform 2 and 3.</p>\n\n<p><code>convert_c2f</code> also is responsible for two things converting and displaying the input.</p>\n\n<p>It can be seen in <code>main</code> that you were originally doing something better than you have now, so it's unclear why you changed this.</p>\n\n<pre><code>def read_selection():\n return input('''Welcome to the temperature conversion program!\n\nPlease make a selection:\n\n c to convert from Celcius to Fahrenheit;\n f to convert from Fahrenheit to Celsius; or\n q to quit the program.\n\nEnter your selection: ''')\n\n\ndef float_input():\n value = input('''\\nPlease enter the temperature you\nwant to convert: ''')\n try:\n return float(value)\n except ValueError:\n print('That is not a number!\\n')\n\n\ndef convert_c2f(value):\n return (value * (9 / 5)) + 32\n\n\ndef convert_f2c(value):\n return (value - 32) * (5 / 9)\n\n\ndef main():\n while True:\n selection = read_selection().lower()\n if selection == 'q':\n return\n elif selection == 'c' or selection == 'f':\n value = float_input(selection)\n if selection == 'c':\n converted = convert_c2f(value)\n print(f'The answer is: {converted}°F\\n')\n else:\n converted = convert_f2c(value)\n print(f'The answer is: {converted}°C\\n')\n else:\n print('Invalid selction. Try again.\\n')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T16:27:10.500", "Id": "424615", "Score": "0", "body": "@Peilonrazy Thank you for the feedback; excellent as always. I am clearly not fully understanding what recursion and iteration is. However, I am researching that now, and once I have done so I will come back with a few questions, or a new version of the program. One question now however - WRT converting the input to a float in the input definition, on top of asking for the input, why is this \"bad?\" It has to be converted somewhere, so whether is done in that def when it is entered, or back in the main() def, what are the advantages or disadvantages?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T17:43:03.813", "Id": "424635", "Score": "1", "body": "@JKarle 1. If you are only allowed to look at the `main`, it's hard to tell what the code is doing in your method. However when it's written the way I suggested it's immediately apparent what it does. And since `input_float` has a good name you can reasonably guess what the code is doing just from the `main` method. 2. If you need to later get a floating point number from the user, but you don't want either of the convert functions to run you either; a. have to make a new function b. hack at the existing function. And so it's better to keep SRP." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T19:34:12.507", "Id": "219768", "ParentId": "219767", "Score": "8" } }, { "body": "<p>Your conversion functions have two notable things:</p>\n\n<ul>\n<li><p>You're printing the result directly. Don't do this. For toy programs like this doing so doesn't create problems. In the real world though, you don't just print data to the screen, you <em>use</em> data. With how you have it now, the caller can't actually use the converted value for anything. What if you wanted to send the raw data over the internet or save it to a file?</p></li>\n<li><p>You're putting an empty <code>return</code> at the end. This is redundant though and unnecessary. <code>None</code> is automatically returned at the end anyways if no <code>return</code> is met, which is equivalent to what you're doing.</p></li>\n</ul>\n\n<p>I would have the functions return the converted value, and print it at the call site:</p>\n\n<pre><code>def value_input(selection):\n value = input('''\\nPlease enter the temperature you\nwant to convert: ''')\n try:\n value = float(value)\n\n except ValueError:\n print('That is not a number!\\n')\n\n else:\n # Save if we're converting to Celsius or not\n is_celsius = selection == 'c' \n\n new_value = convert_c2f(value) if is_celsius else convert_f2c(value)\n unit_str = \"C\" if is_celsius else \"F\"\n\n print(f'The answer is: {new_value}°{unit_str}')\n\n\ndef convert_c2f(value):\n return (value * (9 / 5)) + 32\n\ndef convert_f2c(value):\n return (value - 32) * (5 / 9)\n</code></pre>\n\n<p>I decided to reduce the printing down to a single call to <code>print</code> and just decide what data will be printed ahead of time. This is personal style though. I get an odd thrill out of reducing duplication. Do whatever you feel is more readable. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T16:33:42.193", "Id": "424618", "Score": "0", "body": "Thank you for the feedback. Copy on the empty return (that makes sense), and that I should not print the result directly (that also makes sense after thinking on it for the night.) Rather, and fixing both issues raised, I should calculate the value and return that from the def, to then be display as required." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T16:38:25.773", "Id": "424619", "Score": "1", "body": "@JKarle Yes, let the caller decide how they want to use the data. If they want to print it out, they can do that themselves. Don't force data to be used in a certain way we possible unless you have good reason. You'll limit how easily that function can be used by other code in the future." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T19:44:53.020", "Id": "219769", "ParentId": "219767", "Score": "5" } }, { "body": "<p>@Peilonrayz and @Carcigenicate have great feedback you should definitely follow.</p>\n\n<p>Since you are using Python 3 features like f-string, <code>#!/usr/bin/env python3</code> should be used as <a href=\"https://stackoverflow.com/a/7670338/5682996\">shebang line</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T16:32:30.987", "Id": "424617", "Score": "0", "body": "Thank you, I was thinking about that, but forgot to follow-up and look it up. I will take that for action!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T19:50:13.597", "Id": "219770", "ParentId": "219767", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T19:11:06.117", "Id": "219767", "Score": "6", "Tags": [ "python", "beginner", "python-3.x", "unit-conversion" ], "Title": "Python 3 - simple temperature program version 1.3" }
219767
<p>This is a follow up of <a href="https://codereview.stackexchange.com/q/219736/">my original question</a> in which I'd still like to have some answers, opinions etc. but after looking through some of the standard library's features I have come across <code>std::bitset</code> and was looking at its behavior. </p> <p>I managed to write a simple class template to provide the behavior I was after. This also covers some of the questions and concerns I had previously asked. It helps to remove a lot of the type casting. I believe it helps to make it more generic and portable. It should be trivially copyable as long as <code>std::bitset</code> is in which I'm not 100% sure. It simplifies the code a great deal making it more readable and manageable. </p> <p>Now for accessing individual bits within a Byte, Word, DWord or QWord through a direct member variable within a bitfield, the <code>std::bitset</code> allows you to do so by using the index operator which is fine and actually more convenient if you are trying to use it through an iterative loop. This also removed the need for the inner struct and having to access the value through multiple levels of indirection. </p> <p>The only major difference here is the actual output. It shows the values in its pure binary representation which is okay. There are available functions to convert them to either an integer type or a string type.</p> <p>Here is what I have now compared to my previous code:</p> <p><em>-main.cpp-</em></p> <pre><code>#include &lt;iostream&gt; #include "Register.h" int main() { Register r1; std::cout &lt;&lt; "Register&lt;8&gt;\n"; for (i16 i = 0; i &lt; 21; i++) { r1.register_ = i; std::cout &lt;&lt; r1.register_ &lt;&lt; "\n"; } std::cout &lt;&lt; '\n'; // Note: my output shows: 0 1 1 0 0 1 0 0 // as I am running on an intel x86-64 bit Quad Core Extreme // this is expected since my machine is little endian. r1.register_ = 38; std::cout &lt;&lt; "Bit Values\n"; std::cout &lt;&lt; r1.register_[0] &lt;&lt; " " &lt;&lt; r1.register_[1] &lt;&lt; " " &lt;&lt; r1.register_[2] &lt;&lt; " " &lt;&lt; r1.register_[3] &lt;&lt; " " &lt;&lt; r1.register_[4] &lt;&lt; " " &lt;&lt; r1.register_[5] &lt;&lt; " " &lt;&lt; r1.register_[6] &lt;&lt; " " &lt;&lt; r1.register_[7] &lt;&lt; "\n\n"; Register&lt;16&gt; r2; std::cout &lt;&lt; "Register&lt;16&gt;\n"; for (i16 i = 0; i &lt; 21; i++) { r2.register_ = i; std::cout &lt;&lt; r2.register_ &lt;&lt; "\n"; } std::cout &lt;&lt; '\n'; Register&lt;32&gt; r3; std::cout &lt;&lt; "Register&lt;32&gt;\n"; for (i32 i = 0; i &lt; 21; i++) { r3.register_ = i; std::cout &lt;&lt; r3.register_ &lt;&lt; "\n"; } std::cout &lt;&lt; '\n'; Register&lt;64&gt; r4; std::cout &lt;&lt; "Register&lt;64&gt;\n"; for (i64 i = 0; i &lt; 21; i++) { r4.register_ = i; std::cout &lt;&lt; r4.register_ &lt;&lt; "\n"; } std::cout &lt;&lt; '\n'; return EXIT_SUCCESS; } </code></pre> <p><em>-Output-</em></p> <pre><code>Register&lt;8&gt; 00000000 00000001 00000010 00000011 00000100 00000101 00000110 00000111 00001000 00001001 00001010 00001011 00001100 00001101 00001110 00001111 00010000 00010001 00010010 00010011 00010100 Bit Values 0 1 1 0 0 1 0 0 Register&lt;16&gt; 0000000000000000 0000000000000001 0000000000000010 0000000000000011 0000000000000100 0000000000000101 0000000000000110 0000000000000111 0000000000001000 0000000000001001 0000000000001010 0000000000001011 0000000000001100 0000000000001101 0000000000001110 0000000000001111 0000000000010000 0000000000010001 0000000000010010 0000000000010011 0000000000010100 Register&lt;32&gt; 00000000000000000000000000000000 00000000000000000000000000000001 00000000000000000000000000000010 00000000000000000000000000000011 00000000000000000000000000000100 00000000000000000000000000000101 00000000000000000000000000000110 00000000000000000000000000000111 00000000000000000000000000001000 00000000000000000000000000001001 00000000000000000000000000001010 00000000000000000000000000001011 00000000000000000000000000001100 00000000000000000000000000001101 00000000000000000000000000001110 00000000000000000000000000001111 00000000000000000000000000010000 00000000000000000000000000010001 00000000000000000000000000010010 00000000000000000000000000010011 00000000000000000000000000010100 Register&lt;64&gt; 0000000000000000000000000000000000000000000000000000000000000000 0000000000000000000000000000000000000000000000000000000000000001 0000000000000000000000000000000000000000000000000000000000000010 0000000000000000000000000000000000000000000000000000000000000011 0000000000000000000000000000000000000000000000000000000000000100 0000000000000000000000000000000000000000000000000000000000000101 0000000000000000000000000000000000000000000000000000000000000110 0000000000000000000000000000000000000000000000000000000000000111 0000000000000000000000000000000000000000000000000000000000001000 0000000000000000000000000000000000000000000000000000000000001001 0000000000000000000000000000000000000000000000000000000000001010 0000000000000000000000000000000000000000000000000000000000001011 0000000000000000000000000000000000000000000000000000000000001100 0000000000000000000000000000000000000000000000000000000000001101 0000000000000000000000000000000000000000000000000000000000001110 0000000000000000000000000000000000000000000000000000000000001111 0000000000000000000000000000000000000000000000000000000000010000 0000000000000000000000000000000000000000000000000000000000010001 0000000000000000000000000000000000000000000000000000000000010010 0000000000000000000000000000000000000000000000000000000000010011 0000000000000000000000000000000000000000000000000000000000010100 </code></pre> <p><em>-Register.h-</em></p> <pre><code>#pragma once #include &lt;bitset&gt; #include &lt;vector&gt; // include for typedefs below. typedef std::int8_t i8; typedef std::int16_t i16; typedef std::int32_t i32; typedef std::int64_t i64; template&lt;std::uint64_t N = 8&gt; struct Register { std::bitset&lt;8&gt; register_; Register() { static_assert( ((N % 8) == 0) &amp;&amp; (N &gt;= 8) &amp;&amp; (N &lt;= 64) ); } }; template&lt;&gt; struct Register&lt;16&gt; { std::bitset&lt;16&gt; register_; Register() = default; }; template&lt;&gt; struct Register&lt;32&gt; { std::bitset&lt;32&gt; register_; Register() = default; }; template&lt;&gt; struct Register&lt;64&gt; { std::bitset&lt;64&gt; register_; Register() = default; }; </code></pre> <p>Let me know what you think of this new model compared to my original design and implementation...</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T22:36:23.917", "Id": "424520", "Score": "0", "body": "Thank you for editing. I didn't get a chance to finish proof reading as I was limited on time and I didn't want to lose what I already had so I did quick post(draft)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T21:23:56.353", "Id": "219774", "Score": "4", "Tags": [ "c++", "template", "bitset" ], "Title": "Emulating Virtual Registers Part 2" }
219774
<p>I decided to take up learning c++ recently, so I coded a Huffman compression algorithm. I'm particularly interested in critique of my c++ techniques (pointers, references, best practices, etc), but I am open to any comments you have.</p> <p>Thanks for you time!</p> <pre><code>#include &lt;map&gt; #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;deque&gt; #include &lt;string&gt; #include &lt;algorithm&gt; typedef std::pair&lt;char, int&gt; weight_pair; struct node { int weight; node *parent = NULL; node *children[2] = {NULL, NULL}; std::string content; }; bool compareNodeWeights(const node *node1, const node *node2) { return (node1 -&gt; weight) &lt; (node2 -&gt; weight); } //builds a binary tree from an alphabet and an associated set of weights node *build_tree(const std::map&lt;char, int&gt; &amp;weights){ std::deque&lt;node*&gt; nodes; for (auto const &amp;x : weights) { node *leaf_node = new node; leaf_node -&gt; weight = x.second; leaf_node -&gt; content = std::string(1, x.first); nodes.push_back(leaf_node); } while (nodes.size() &gt; 1) { std::sort(nodes.begin(), nodes.end(), compareNodeWeights); node* new_node = new node; new_node -&gt; weight = nodes[0] -&gt; weight + nodes[1] -&gt; weight; new_node -&gt; content = nodes[0] -&gt; content + nodes[1] -&gt; content; nodes[0] -&gt; parent = new_node; nodes[1] -&gt; parent = new_node; new_node -&gt; children[0] = nodes[0]; new_node -&gt; children[1] = nodes[1]; nodes.erase(nodes.begin()); nodes.erase(nodes.begin()); nodes.push_back(new_node); } return nodes[0]; } //traverses the tree to find the prefix code for a given leaf node in a tree std::deque&lt;bool&gt; find_prefix_code(const node *leaf) { std::deque&lt;bool&gt; result; const node *curr_node = leaf; while (curr_node -&gt; parent != NULL) { if (curr_node -&gt; parent -&gt; children[0] -&gt; content == curr_node -&gt; content) { result.push_front(0); } else { result.push_front(1); } curr_node = curr_node -&gt; parent; } return result; } std::vector&lt;bool&gt; compress(const std::string &amp;message, const node *tree) { std::vector&lt;bool&gt; result; std::vector&lt;const node*&gt; open; open.push_back(tree); std::map&lt;char, std::deque&lt;bool&gt;&gt; prefix_codes; while (open.size() &gt; 0) { const node* curr_node = open[0]; if (curr_node -&gt; content.size() == 1){ prefix_codes.insert( std::pair&lt;char, std::deque&lt;bool&gt;&gt;(curr_node -&gt; content[0], find_prefix_code(curr_node)) ); } else { open.push_back(curr_node -&gt; children[0]); open.push_back(curr_node -&gt; children[1]); } open.erase(open.begin()); } for (const char c : message) { for (const bool &amp;b : prefix_codes[c]) { result.push_back(b); } } return result; } std::string decompress(const std::vector&lt;bool&gt; &amp;data, const node *tree) { const node *curr_node = tree; std::string result = ""; for (const bool b : data) { int direction = b; curr_node = curr_node -&gt; children[direction]; if (curr_node -&gt;content.size() == 1) { result += curr_node -&gt; content; curr_node = tree; } } return result; } void print_compressed(const std::vector&lt;bool&gt; &amp;data) { std::cout &lt;&lt; "Compressed data: "; for (const bool b : data) { std::cout &lt;&lt; b; } std::cout &lt;&lt; std::endl; } void delete_tree(node *tree) { for (int i = 0; i &lt;= 1; i++) { if (tree -&gt; children[i] != NULL) { delete_tree(tree -&gt; children[i]); } } delete tree; } int main() { std::map&lt;char, int&gt; weights; weights.insert(weight_pair(' ', 3)); weights.insert(weight_pair('a', 3)); weights.insert(weight_pair('d', 3)); weights.insert(weight_pair('b', 1)); weights.insert(weight_pair('c', 1)); node *tree = build_tree(weights); std::vector&lt;bool&gt; compressed_message = compress("a cab dab bad", tree); print_compressed(compressed_message); std::string message = decompress(compressed_message, tree); std::cout &lt;&lt; "Decompressed data: " &lt;&lt; message &lt;&lt; std::endl; delete_tree(tree); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T09:44:30.160", "Id": "424555", "Score": "0", "body": "Welcome to Code Review. Do you target a specific C++ version? Your code seems to use C++03 only and none of the more recent C++ features except for the range-based `for` loop." } ]
[ { "body": "<p>You have a typedef for <code>weight_pair</code> but only use it in main to fill the map.</p>\n\n<p><code>node::children</code> should be unique_ptr. That way you don't need delete_tree. However you will need at most 2*n nodes to be allocated so you can preallocate those in a <code>std::vector&lt;node&gt;</code> and avoid calling make_unique on each new node.</p>\n\n<p>In <code>build_tree</code> you pull that map apart to build a <code>node*</code> array so you may as well have just passed a <code>std::vector&lt;weight_pair&gt;</code>.</p>\n\n<p>You can avoid using the <code>std::deck</code> by reverse sorting a <code>std::vector</code> (so the lowest elements end up at the back ready to get popped of). </p>\n\n<pre><code>while (nodes.size() &gt; 1) {\n std::sort(nodes.begin(), nodes.end(), reverseCompareNodeWeights);\n\n unique_ptr&lt;node&gt; new_node = std::make_unique&lt;node&gt;(); \n //or node* new_node = allocated_nodes[next++]; // if preallocated.\n unique_ptr&lt;node&gt;&amp; back1 = nodes[nodes.size()-1];\n unique_ptr&lt;node&gt;&amp; back2 = nodes[nodes.size()-2];\n new_node -&gt; weight = back1 -&gt; weight + back2 -&gt; weight;\n new_node -&gt; content = back2 -&gt; content + back2 -&gt; content;\n back1-&gt;parent = new_node;\n back2-&gt;parent = new_node;\n new_node -&gt; children[0] = std::move(back1);\n new_node -&gt; children[1] = std::move(back2);\n\n nodes.pop_back();\n nodes.back(std::move(new_node));\n\n}\n</code></pre>\n\n<p>Or you could use the std::heap operations</p>\n\n<pre><code>std::make_heap(nodes.begin(), nodes.end(), compareNodeWeights);\n\nwhile (nodes.size() &gt; 1) {\n std::pop_heap(nodes.begin(), nodes.end(), compareNodeWeights);\n std::pop_heap(nodes.begin(), nodes.end()-1, compareNodeWeights);\n\n //identical to above\n\n nodes.pop_back();\n nodes.back() = std::move(new_node);\n std::push_heap(nodes.begin(), nodes.end(), compareNodeWeights);\n}\n</code></pre>\n\n<hr>\n\n<p>Compressing or decompressing bit by bit using this tree is going to be very slow. It will result in a cache miss per bit of output.</p>\n\n<p>instead you can make a lookup table. For compression this is straightforward it will be a <code>std::array&lt;compress_value&gt;</code> where <code>compress_value</code> is </p>\n\n<pre><code>struct compress_value {\n uint code;\n uint code_size;\n}\n</code></pre>\n\n<p>and the compression main loop will be:</p>\n\n<pre><code>std::vector&lt;uint8&gt; output;\n\nuint64 outputbuff; //filled from least significant bit first\nuint filled;\nfor(char c : input){\n compress_value value = compress_table[c];\n outputbuff |= value.code &lt;&lt; filled;\n filled += value.code_size;\n while(filled &gt; 8){\n output.pushback(outputbuff &amp; 0xff);\n outputbuff = outputbuff &gt;&gt; 8;\n filled -= 8;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Decompressing will be similar. But instead you will have a lookup table that is as large as <span class=\"math-container\">\\$ 2^{\\text{max code size}}\\$</span></p>\n\n<p>Each entry in the decompression table will contain at index i the character where <code>i &amp; mask</code> is the code for the value.</p>\n\n<p>That is</p>\n\n<pre><code>for(table_value value : table){\n for(uint c = value.code; c &lt; table_size; c += 1&lt;&lt;value.code_size){\n decompress_table[c].ch = value.ch;\n decompress_table[c].code_size = value.code_size;\n }\n}\n</code></pre>\n\n<p>The decompression main loop will be:</p>\n\n<pre><code>uint64 input_buff = read_up_to_8_bytes(input, end); //reads least significant byte first\nuint filled = 64;\nwhile(input &lt; end){\n decompress_value value = decompress_table[input_buff &amp; decompress_mask];\n output.push_back(value.ch);\n input_buff = input_buff &gt;&gt; value.code_size;\n filled -= value.code_size;\n if(filled &lt; max_code_size){\n while(filled &lt; 56 &amp;&amp; (input != end)){\n input++;\n filled += 8;\n }\n input_buff = read_up_to_8_bytes(input, end);\n if(filled != 0)\n input_buff = input_buff &gt;&gt; (64-filled);\n }\n}\n</code></pre>\n\n<p>instead of all those explicit bounds checks you can add a new symbol that signifies the end of the bit stream and overallocate the input buffer by at least 8 bytes. Though that requires that the stream was not corrupted. The compromise is to only have the bounds check on the outer loop.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T17:32:46.720", "Id": "424630", "Score": "0", "body": "Thanks very much, helpful feedback all around" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T09:51:41.270", "Id": "219799", "ParentId": "219776", "Score": "2" } } ]
{ "AcceptedAnswerId": "219799", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T22:04:48.260", "Id": "219776", "Score": "3", "Tags": [ "c++", "compression" ], "Title": "First Huffman Compression Algorithm in C++" }
219776
<p><strong>The task</strong> is taken from <a href="https://leetcode.com/problems/robot-return-to-origin/" rel="nofollow noreferrer">leetcode</a></p> <blockquote> <p>There is a robot starting at position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves.</p> <p>The move sequence is represented by a string, and the character moves[i] represents its ith move. Valid moves are R (right), L (left), U (up), and D (down). If the robot returns to the origin after it finishes all of its moves, return true. Otherwise, return false.</p> <p>Note: The way that the robot is "facing" is irrelevant. "R" will always make the robot move to the right once, "L" will always make it move left, etc. Also, assume that the magnitude of the robot's movement is the same for each move.</p> <p>Example 1:</p> <p>Input: "UD" Output: true Explanation: The robot moves up once, and then down once. All moves have the same magnitude, so it ended up at the origin where it started. Therefore, we return true. </p> <p>Example 2:</p> <p>Input: "LL" Output: false Explanation: The robot moves left twice. It ends up two "moves" to the left of the origin. We return false because it is not at the origin at the end of its moves.</p> </blockquote> <pre><code>const arr = "UD"; </code></pre> <p><strong>My imperative solution:</strong></p> <pre><code>function judgeCircle(moves) { let horizontal = 0; let vertical = 0; [...moves].forEach(m =&gt; { switch(m) { case "U": ++vertical; break; case "D": --vertical; break; case "R": ++horizontal; break; case "L": --horizontal; break; default: // be a good code } }); return !(horizontal) &amp;&amp; !(vertical); }; console.log(judgeCircle(arr)); </code></pre> <p><strong>My functional solution:</strong></p> <pre><code>const judgeCircle2 = moves =&gt; { const {h, v} = [...moves].reduce((acc,m) =&gt; { switch(m) { case "U": ++acc.v; return acc; case "D": --acc.v; return acc; case "R": ++acc.h; return acc; case "L": --acc.h; return acc; default: // be a good code } }, {h: 0, v: 0}); return !h &amp;&amp; !v; }; console.log(judgeCircle2(arr)); </code></pre>
[]
[ { "body": "<p>It could be made more functional by avoiding the mutation of <code>acc</code>. The effects are contained within <code>judgeCircle</code> so it's not a big deal, but it feels like if you're going to mutate the accumulator, you might as well just use an imperative loop.</p>\n\n<p>I also preferred to be explicit about the final check. I find the intent of <code>!h &amp;&amp; !v</code> isn't quite as clear as <code>h == 0 &amp;&amp; v == 0;</code>.</p>\n\n<p>I ended up with:</p>\n\n<pre><code>const judgeCircle3 = moves =&gt; {\n const [hori, vert] = [...moves].reduce(([h, v], move) =&gt; {\n switch(move) {\n case \"U\":\n return [h, v + 1];\n\n case \"D\":\n return [h, v - 1];\n\n case \"R\":\n return [h + 1, v];\n\n case \"L\":\n return [h - 1, v];\n }\n\n }, [0, 0]);\n\n return hori == 0 &amp;&amp; vert == 0;\n};\n</code></pre>\n\n<p>The need for the <code>switch</code> here is unfortunate, but the only other alternative I could think of was some mess where a you'd do a lookup on a map which returned a function that returned a \"altered\" accumulator state.</p>\n\n<p>I also got rid of the <code>default</code> since it didn't seem to be doing anything. You could have done error handling in there (and should in most cases), but if it's a challenge with predefined input, that's probably not necessary unless it's part of the challenge.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-18T16:10:33.730", "Id": "425979", "Score": "0", "body": "Good point with avoiding the `acc`. I'll keep this in mind for future tasks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T23:21:15.433", "Id": "219780", "ParentId": "219777", "Score": "2" } }, { "body": "<p>You can often replace <code>switch</code> statements with lookup functions. For example </p>\n\n<pre><code>function returnsHome(moves) {\n var v = 0, h = 0;\n const dirs = { \n U() {v++}, \n D() {v--}, \n L() {h--}, \n R() {h++} \n };\n for (const move of moves) { dirs[move]() }\n return !(h || v);\n}\n\n// or\nfunction returnsHome(moves) {\n var v = 0, h = 0;\n const dirs = {U() {v++}, D() {v--}, L() {h--}, R() {h++}};\n for (const m of moves) { dirs[m]() }\n return !(h || v);\n}\n</code></pre>\n\n<p>There is also a very quick way to workout if the result is false by checking if the number of moves is odd. </p>\n\n<pre><code>function returnsHome(moves) {\n var v = 0, h = 0;\n if (moves.length % 2) { return false } \n const dirs = {U() {v++}, D() {v--}, L() {h--}, R() {h++}};\n for (const m of moves) { dirs[m]() }\n return !(h || v);\n}\n</code></pre>\n\n<p>Another early exit can be found if a particular distance moved if greater than the remaining number of moves.</p>\n\n<pre><code>function returnsHome(moves) {\n var v = 0, h = 0, remainingSteps = moves.length;\n if (remainingSteps % 2) { return false }\n const dirs = {U() {v++}, D() {v--}, L() {h--}, R() {h++}};\n for (const m of moves) { \n dirs[m]();\n if (--remainingSteps &lt; (Math.abs(v) + Math.abs(h))) { return false }\n }\n return !(h || v);\n}\n</code></pre>\n\n<p>UPDATE I got that wrong, it does not work for all cases</p>\n\n<p><strike>Finally you could also use <code>String.replace</code> to solve</strike></p>\n\n<pre><code>function returnsHome(m) {\n const rep = dir =&gt; (m = m.replace(dir, \"\")).length;\n return !(\n m.length % 2 || (m.length - rep(/D/g)) - (m.length - rep(/U/g)) || \n m.length % 2 || rep(/L/g) - m.length\n );\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T03:35:49.290", "Id": "219842", "ParentId": "219777", "Score": "1" } } ]
{ "AcceptedAnswerId": "219842", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T22:10:21.630", "Id": "219777", "Score": "3", "Tags": [ "javascript", "algorithm", "programming-challenge", "functional-programming", "ecmascript-6" ], "Title": "Robot Return to Origin" }
219777
<p>I am trying to implement the <strong>Execute Around</strong> pattern described in Kent Beck's Smalltalk Best Practice Patterns. An example in Java could be found <a href="https://stackoverflow.com/a/342016/5192528">here</a>. </p> <p>Basically, I am repeatedly opening and closing a pdf document while performing various operations, something like,</p> <pre><code>public void Parse() { // Open the document PdfLoadedDocument loadedDocument = new PdfLoadedDocument("plan.pdf"); List&lt;string&gt; annotations = Build(loadedDocument); // work with annotations. // Close the document loadedDocument.Save(); loadedDocument.Close(); } </code></pre> <p>I would like to move the opening and closing the document in a centralized place, as I have tens of similar methods. All these methods open the document, perform an action, and close the document, and it's easy to forget to close the document. </p> <p>Here is what I tried:</p> <pre><code>public void BuildAnnotations() { List&lt;string&gt; annotations = null; ExecuteAction("plan.pdf", (PdfLoadedDocument loadedDocument) =&gt; { annotations = Build(loadedDocument); // work with annotations }); } private void ExecuteAction(string path, Action&lt;PdfLoadedDocument&gt; perform) { PdfLoadedDocument loadedDocument = new PdfLoadedDocument(path); try { perform(loadedDocument); } catch(Exception e) { Console.WriteLine($"An error occured. {e}"); } loadedDocument.Save(); loadedDocument.Close(); } </code></pre> <p>My question is, is passing a lambda to an Action delegate a good idea? I am not that familiar with delegates, Actions, and lambdas (other than using them in linq queries). Are there any other better alternatives? </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T06:34:10.627", "Id": "424533", "Score": "0", "body": "The `Parse` method doesn't do any work and you do not use the result of `Build` anywhere. I suppose this is not your real code but some shortened version. Please update your question and post what you currently have and what you are trying to improve. We need to see the real and complete code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T15:17:01.990", "Id": "424606", "Score": "0", "body": "Yes, I have simplified my code example to make it easy to understand. The actual code does indeed manipulate `annotations`." } ]
[ { "body": "<p>IMO there is a problem with the <code>try...catch</code> statement. If an exception is thrown you'll have to deal with communicating the error to the client. You can't rethrow it because then the <code>Save()</code> and <code>Close()</code> aren't called, so you'll have to have a kind of logging or event to notify through and that could make it all unnecessarily complicated. Besides that: if an exception is thrown, you may not want to save the document in an unknown state, but you should close it anyway.</p>\n\n<p>You can handle that in the following way:</p>\n\n<pre><code> try\n {\n perform(loadedDocument);\n loadedDocument.Save();\n }\n finally\n {\n loadedDocument.Close();\n }\n</code></pre>\n\n<p>Here the document is only saved if the process went well, but closed in any case. And the caller can handle the exception as needed.</p>\n\n<hr>\n\n<p>Alternatively you can make a wrapper like:</p>\n\n<pre><code> class PdfDocumentExecuter : IDisposable\n {\n private PdfLoadedDocument document;\n\n public PdfDocumentExecuter(string fileName)\n {\n document = new PdfLoadedDocument(fileName);\n }\n\n public void Execute(Action&lt;PdfLoadedDocument&gt; action)\n {\n action(document);\n document.Save();\n }\n\n public T Execute&lt;T&gt;(Func&lt;PdfLoadedDocument, T&gt; function)\n {\n T result = function(document);\n document.Save();\n return result;\n }\n\n public void Dispose()\n {\n if (document != null)\n {\n document.Close();\n document = null;\n }\n }\n }\n</code></pre>\n\n<p>called as:</p>\n\n<pre><code> using (PdfDocumentExecuter executer = new PdfDocumentExecuter(\"path\"))\n {\n annotations = executer.Execute(Build);\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T07:18:55.617", "Id": "424539", "Score": "1", "body": "`IDisposable` is what I was going to recommend. Let the language do the heavy lifting." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T05:54:52.553", "Id": "219786", "ParentId": "219779", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T23:15:55.193", "Id": "219779", "Score": "1", "Tags": [ "c#", "design-patterns", "lambda", "delegates" ], "Title": "Repeatedly open and close a PDF document to perform various operations" }
219779
<p>I had a code challenge for a class I'm taking that built a NN algorithm. I got it to work but I used really basic methods for solving it. There are two 1D NP Arrays that have values 0-2 in them, both equal length. They represent two different trains and test data The output is a confusion matrix that shows which received the right predictions and which received the wrong (doesn't matter ;). </p> <p>This code is correct - I just feel I took the lazy way out working with lists and then turning those lists into a ndarray. I would love to see if people have some tips on maybe utilizing Numpy for this? Anything Clever? </p> <pre><code>import numpy as np x = [0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 2, 0, 0, 0, 0, 0, 1, 0] y = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] testy = np.array(x) testy_fit = np.array(y) row_no = [0,0,0] row_dh = [0,0,0] row_sl = [0,0,0] # Code for the first row - NO for i in range(len(testy)): if testy.item(i) == 0 and testy_fit.item(i) == 0: row_no[0] += 1 elif testy.item(i) == 0 and testy_fit.item(i) == 1: row_no[1] += 1 elif testy.item(i) == 0 and testy_fit.item(i) == 2: row_no[2] += 1 # Code for the second row - DH for i in range(len(testy)): if testy.item(i) == 1 and testy_fit.item(i) == 0: row_dh[0] += 1 elif testy.item(i) == 1 and testy_fit.item(i) == 1: row_dh[1] += 1 elif testy.item(i) == 1 and testy_fit.item(i) == 2: row_dh[2] += 1 # Code for the third row - SL for i in range(len(testy)): if testy.item(i) == 2 and testy_fit.item(i) == 0: row_sl[0] += 1 elif testy.item(i) == 2 and testy_fit.item(i) == 1: row_sl[1] += 1 elif testy.item(i) == 2 and testy_fit.item(i) == 2: row_sl[2] += 1 confusion = np.array([row_no,row_dh,row_sl]) print(confusion) </code></pre> <p>the result of the print is correct as follow:</p> <pre><code>[[16 10 0] [ 2 10 0] [ 2 0 22]] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T00:15:20.387", "Id": "424522", "Score": "1", "body": "Good thing this got an answer on SO before it was moved. Performance questions for `numpy` are routine on SO." } ]
[ { "body": "<p>This can be implemented concisely by using <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.at.html\" rel=\"noreferrer\"><code>numpy.add.at</code></a>:</p>\n\n<pre><code>In [2]: c = np.zeros((3, 3), dtype=int) \n\nIn [3]: np.add.at(c, (x, y), 1) \n\nIn [4]: c \nOut[4]: \narray([[16, 10, 0],\n [ 2, 10, 0],\n [ 2, 0, 22]])\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T02:04:51.373", "Id": "424526", "Score": "0", "body": "Oh my! I thought there would be something better but i didn't think 1 line of code! Wow. So glad I asked and thank you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T05:39:09.167", "Id": "424530", "Score": "2", "body": "Rule #1 of numpy is if you want to do something, check the docs first to check for a 1 line solution." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T23:41:43.300", "Id": "219782", "ParentId": "219781", "Score": "5" } }, { "body": "<p>For now disregarding that there is a (way) better <code>numpy</code> solution to this, as explained in the <a href=\"https://codereview.stackexchange.com/a/219782/98493\">answer by @WarrenWeckesser</a>, here is a short code review of your actual code.</p>\n\n<ul>\n<li><code>testy.item(i)</code> is a very unusual way to say <code>testy[i]</code>. It is probably also slower as it involves an attribute lookup.</li>\n<li><p><a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">Don't repeat yourself</a>. You test e.g. <code>if testy.item(i) == 0</code> three times, each time with a different second condition. Just nest them in an <code>if</code> block:</p>\n\n<pre><code>for i in range(len(testy)):\n if testy[i] == 0:\n if testy_fit[i] == 0:\n row_no[0] += 1\n elif testy_fit[i] == 1:\n row_no[1] += 1\n elif testy_fit[i] == 2:\n row_no[2] += 1\n</code></pre></li>\n<li><p><a href=\"https://nedbatchelder.com/text/iter.html\" rel=\"nofollow noreferrer\">Loop like a native</a>. Don't iterate over the indices of iterables, iterate over the iterable(s)! You can also use the fact that the value encodes the position you want to increment:</p>\n\n<pre><code>for test, fit in zip(testy, testy_fit):\n if test == 0 and fit in {0, 1, 2}:\n row_no[fit] += 1\n</code></pre></li>\n<li><p>You can even use the fact that the first value encodes the list you want to use and iterate only once. Or even better, make it a list of lists right away:</p>\n\n<pre><code>n = 3\nconfusion_matrix = [[0] * n for _ in range(n)]\nfor test, fit in zip(testy, testy_fit):\n confusion_matrix[test][fit] += 1\n\nprint(np.array(confusion_matrix))\n</code></pre></li>\n<li><p>Don't put everything into the global space, to be run whenever you interact with the script at all. Put your code into functions, document them with a <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\"><code>docstring</code></a>, and execute them under a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a>, which allows you to import from this script from another script without your code running:</p>\n\n<pre><code>def confusion_matrix(x, y):\n \"\"\"Return the confusion matrix for two vectors `x` and `y`.\n x and y must only have values from 0 to n and 0 to m, respectively.\n \"\"\"\n n, m = np.max(x) + 1, np.max(y) + 1\n matrix = [[0] * m for _ in range(n)]\n for a, b in zip(x, y):\n matrix[a][b] += 1\n return matrix\n\nif __name__ == \"__main__\":\n x = ...\n y = ...\n print(np.array(confusion_matrix(x, y)))\n</code></pre></li>\n</ul>\n\n<p>Once you have come this far, you can just swap the implementation of this function to the faster <code>numpy</code> one without changing anything (except that it then directly returns a <code>numpy.array</code> instead of a list of lists).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T06:58:19.890", "Id": "219788", "ParentId": "219781", "Score": "3" } } ]
{ "AcceptedAnswerId": "219782", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-05T23:36:08.483", "Id": "219781", "Score": "5", "Tags": [ "python", "numpy" ], "Title": "Improve Performance of Comparing two Numpy Arrays" }
219781
<p>This is my simple unique_ptr implementation. Anything that could be improved upon or should be added?</p> <pre><code>#include &lt;algorithm&gt; template&lt;typename T&gt; class unique_ptr { private: T * ptr_resource = nullptr; public: // Safely constructs resource. Operator new is called by the user. Once constructed the unique_ptr will own the resource. // std::move is used because it is used to indicate that an object may be moved from other resource. explicit unique_ptr(T* raw_resource) noexcept : ptr_resource(std::move(raw_resource)) {} unique_ptr(std::nullptr_t) : ptr_resource(nullptr) {} // destroys the resource when object goes out of scope ~unique_ptr() noexcept { delete ptr_resource; } // Disables the copy/ctor and copy assignment operator. We cannot have two copies exist or it'll bypass the RAII concept. unique_ptr(const unique_ptr&lt;T&gt;&amp;) noexcept = delete; unique_ptr&amp; operator = (const unique_ptr&amp;) noexcept = delete; public: // releases the ownership of the resource. The user is now responsible for memory clean-up. T* release() noexcept { T* resource_ptr = this-&gt;ptr_resource; this-&gt;ptr_resource = nullptr; return resource_ptr; } // returns a pointer to the resource T* get() const noexcept { return ptr_resource; } // swaps the resources void swap(unique_ptr&lt;T&gt;&amp; resource_ptr) noexcept { std::swap(ptr_resource, resource_ptr.ptr_resource); } // replaces the resource. the old one is destroyed and a new one will take it's place. void reset(T* resource_ptr) noexcept(false) { // ensure a invalid resource is not passed or program will be terminated if (resource_ptr == nullptr) throw std::invalid_argument("An invalid pointer was passed, resources will not be swapped"); delete ptr_resource; ptr_resource = nullptr; std::swap(ptr_resource, resource_ptr); } public: // operators T* operator-&gt;() const noexcept { return this-&gt;ptr_resource; } T&amp; operator*() const noexcept { return *this-&gt;ptr_resource; } // May be used to check for nullptr }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T19:18:49.230", "Id": "424643", "Score": "0", "body": "Please read my series on smart pointers for some help: https://lokiastari.com/series/" } ]
[ { "body": "<ul>\n<li><p>Let me first assume that your <code>unique_ptr</code> is supposed to be movable. Then, any basic test case whould have unrevealed this:</p>\n\n<pre><code>unique_ptr&lt;int&gt; ptr1(new int());\nunique_ptr&lt;int&gt; ptr2 = std::move(ptr1); // Fails to compile\n</code></pre>\n\n<p>Recall that <code>= delete</code>-ing special member functions means user-declaring them. And user-declared copy and copy assignment constructors prevent compiler-generated move (assignment) constructors! You have to manually define them. This case is by the way covered by the <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c21-if-you-define-or-delete-any-default-operation-define-or-delete-them-all\" rel=\"nofollow noreferrer\">rule of five/C.21 Core Guidelines</a>, and also have a look at the table posted in <a href=\"https://stackoverflow.com/a/24512883/9593596\">this SO answer</a> for an overview of compiler-generated/-deleted/not-declared special member functions.</p></li>\n<li><p>Is the non-availability of an implicit conversion to <code>bool</code> intended? Checking if a (smart) pointer is in an empty/null state is so common in ordinary control flow statements that clients will expect this to compile:</p>\n\n<pre><code>unique_ptr&lt;SomeType&gt; ptr = ...;\n\nif (ptr) ... // currently fails to compile\n</code></pre>\n\n<p>But not that this might be debatable. Implicit conversions can cause a lot of pain, so if you intend to not allow them for the sake of a more explicit</p>\n\n<pre><code>if (ptr == nullptr) ... \n</code></pre>\n\n<p>that's a design decision. But one that should be documented in a comment at the top of the class.</p></li>\n<li><p>Except the non-<code>explicit</code>-ness of the second constructor (thanks to @Deduplicator for pointing that out) taking a <code>std::nullptr_t</code>, it is superfluous. You can construct an empty <code>unique_ptr</code> by</p>\n\n<pre><code>unique_ptr&lt;SomeType&gt; empty{nullptr};\n</code></pre>\n\n<p>which simply invokes the first constructor taking a <code>T*</code> argument. I would remove the second constructor.</p></li>\n<li><p>... and add a default constructor that initializes <code>ptr_resource</code> to <code>nullptr</code>, as</p>\n\n<pre><code>unique_tr&lt;SomeType&gt; empty;\n</code></pre>\n\n<p>might be a way of constructing an empty smart pointer that users would expect to compile.</p></li>\n<li><p>Move-constructing the <code>ptr_resource</code> in the constructor initializer by <code>ptr_resource(std::move(raw_resource))</code> doesn't make much sense. Just copy the pointer instead. The comment <code>// std::move is used because it is used to indicate that an object may be moved from other resource.</code> is rather confusing, because <code>T* raw_resource</code> is already a pointer, and hence a <em>handle</em> to a resource, not the resource itself.</p></li>\n<li><p>The <code>release</code> member function can be implemented more conveniently as</p>\n\n<pre><code>T* release() noexcept\n{\n return std::exchange(ptr_resource, nullptr);\n}\n</code></pre></li>\n<li><p>I wouln't let the <code>reset</code> member function throw when the input is a <code>nullptr</code>. Why shouldn't it be allowed to <code>reset</code> a <code>unique_ptr</code> with a <code>nullptr</code>, turning it back into an empty state?</p></li>\n<li><p>The only facilities you use from the standard library are <code>std::move</code> and <code>std::swap</code>. Those are in <code>&lt;utility&gt;</code>, so you don't need to include <code>&lt;algorithm&gt;</code>, which is probably much heavier in terms of compile times.</p></li>\n<li><p>I would omit the <code>this-&gt;</code> prefix, it's unnecessarily verbose. But that might be a matter of taste.</p></li>\n<li><p>Have you considered custom deleters? This makes the class template more reusable in scenarios other than pointers to heap resources, e.g. closing a file upon destruction etc.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T07:15:38.523", "Id": "219790", "ParentId": "219783", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T02:56:31.980", "Id": "219783", "Score": "5", "Tags": [ "c++", "reinventing-the-wheel", "pointers", "raii" ], "Title": "My unique_ptr implementation" }
219783
<p>I created a twitter bot, that can parse a subreddit and post content from there to Twitter. I am running this bot using a cron-job, which starts the app using <code>npm start</code> after a 1-hour interval. Here is the code:</p> <pre><code>const Twit = require("twit"); const request = require("request").defaults({ encoding: null, }); const config = require("./config"); const fs = require("fs"); const path = require("path"); const T = new Twit(config); main(); function getContent () { const options = { url: "https://www.reddit.com/r/freefolk/hot.json", }; return new Promise(function (resolve, reject) { request.get(options, function (err, resp, body) { if (err) { reject(err); } else { resolve(parseSubReddit(JSON.parse(body))); } }); }); } function saveImage (url, path) { const options = { url: url, }; return new Promise(function (resolve, reject) { request.get(options, function (err, resp, body) { if (err) { reject(err); } else { fs.writeFile(path, body, function (err) { if (err) { reject(err); } else { resolve(); } }); } }); }); } function parseSubReddit (response) { let posts = response.data.children; for (let post of posts.reverse()) { if (!post.data.is_self) { let data = { title: post.data.title, url: post.data.url, }; return data; } } } function postTwit (content) { return new Promise(function (resolve, reject) { const localname = "downloaded_image"; const PATH = path.join(__dirname, localname); let imagePromise = saveImage(content.url, PATH); imagePromise.then(function () { T.postMediaChunked({ file_path: PATH, }, function (err, data, response) { if (err) { console.log("upload error"); reject(err); } else { var mediaIdStr = data.media_id_string; var altText = content.title; var metaParams = { media_id: mediaIdStr, alt_text: { text: altText, }, }; T.post("media/metadata/create", metaParams) .catch(function (err) { console.log("error creating media meta data"); reject(err); }) .then(function () { // now we can reference the media and post a tweet (media will attach to the tweet) var params = { status: content.title + " #gameofthrones", media_ids: [ mediaIdStr, ], }; T.post("statuses/update", params) .catch(function (err) { console.log("error in status update"); reject(err); }) .then(function (result) { fs.unlinkSync(PATH); resolve(result.data.text); }); }); } }); }, function (err) { reject(err); }); }); } function main () { const contentPromise = getContent(postTwit); contentPromise.then(function (content) { // parse content to twit const twitted = postTwit(content); twitted.then(function (status) { console.log(status); }, function (err) { console.log("Something went wrong posting the twit: ", err); }); }, function (err) { console.log("Error getting content: ", err); }); } </code></pre> <p><a href="https://github.com/souvikmaji/got-bot" rel="nofollow noreferrer">Link to GitHub Project</a></p> <p>My questions/concerns are:</p> <ol> <li>Are the uses of promises correct? Can it be made better?</li> <li>I may have mixed callbacks and promises (e.g, while using fs). Is it ok to do so?</li> <li>Initially, I was using the top post from the subreddit to post on twitter. But I realized later, top posts remain at the top for more than an hour, creating repeated posts for my bot. So I am using the tenth (10 responses are returned by the Reddit API at a time) response as no post stays at position 10 for too long. I thought of choosing at random from first 10 but was sceptical of that method creating unique posts each time. And posting the last content was easy to implement also. Any other way to ensure uniqueness?</li> <li>How can things be generalized so that it can be extended to post different types of content?</li> <li>Any general suggestion about readability, functionality, style or cleanliness is most welcome. </li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T05:26:42.853", "Id": "424529", "Score": "0", "body": "For `1`: Check https://stackoverflow.com/q/54593453/2902996 maybe?" } ]
[ { "body": "<ol>\n<li><p>Nesting promises defeats the purpose of promises as a whole. Promises can be chained together. This is done by returning a promise to <code>then</code>. </p>\n\n<pre><code>function postTwit() {\n\n return saveImage(content.url, PATH)\n .then(() =&gt; {\n // Return a promise to a then. The promise returned by then\n // will not resolve until this promise resolves.\n return T.postMediaChunkedPromiseVersion()\n })\n .then(data =&gt; {\n const metaParams = {...}\n return T.post(\"media/metadata/create\", metaParams)\n })\n .then(() =&gt; {\n const params = {...};\n\n return T.post(\"statuses/update\", params)\n })\n .then(result =&gt; {\n fs.unlinkSync(PATH);\n resolve(result.data.text);\n })\n .catch(e =&gt; {\n // Log error\n })\n}\n\n// Or even better with async-await:\n\n\nasync function postTwit() {\n try {\n await saveImage(content.url, PATH)\n\n const data = await T.postMediaChunkedPromiseVersion()\n\n const metaParams = {...}\n await T.post(\"media/metadata/create\", metaParams)\n\n const params = {...}\n const results = await T.post(\"statuses/update\", params)\n\n fs.unlinkSync(PATH);\n return result.data.text\n\n } catch (e) {\n // Log the error\n }\n}\n</code></pre>\n\n<p>If you have callback-style APIs that have no promise alternative, wrap them in promises so that you can still do chaining/async-await. Also, your error object should contain enough information so that regardless if you log in between operations or attach <code>catch</code> at the end, you can still extract enough information for the logging to make sense.</p></li>\n<li><p>The <code>request</code> module has a <a href=\"https://www.npmjs.com/package/request-promise\" rel=\"nofollow noreferrer\">promise-based version</a>. You can use that instead of manually wrapping the vanilla API with a promise. The <code>fs</code> module also has a <a href=\"https://nodejs.org/api/fs.html#fs_fs_promises_api\" rel=\"nofollow noreferrer\">promise-based version</a> as well. You can also use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function\" rel=\"nofollow noreferrer\"><code>async</code></a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await\" rel=\"nofollow noreferrer\"><code>await</code></a> instead of promises for less nested code.</p></li>\n<li><p>Not sure how the Reddit API works. But if it works like the site, I suggest you use \"New\" content instead. Also, each item has an ID. Your app could keep a record of ones that have been Tweeted to avoid duplicates. This should work regardless of new or hot content, randomized or not.</p></li>\n<li><p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/extends\" rel=\"nofollow noreferrer\">Inheritance</a> or composition.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T20:03:57.050", "Id": "219889", "ParentId": "219784", "Score": "2" } } ]
{ "AcceptedAnswerId": "219889", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T03:07:02.223", "Id": "219784", "Score": "4", "Tags": [ "javascript", "node.js", "twitter", "reddit" ], "Title": "Twitter bot to post game of thrones memes" }
219784
<p>I created a plugin to update cart automatically on quantity change with some additional options. I want to focus only on the main plugin file, skipping uninstall.php and .js file which are entirely okay.</p> <p>I will start with good things about my code.</p> <p>I am happy with how settings work. After installation, values in plugin settings are pre-filled and plugin can properly read these defaults. If the plugin is deactivated and activated again, defaults don't override settings from database. Seems simple, but wasn't covered in WordPress codex and getting it to work gave me quite a headache.</p> <p>Variable is properly passed to .js file and CSS style correctly applied in head, so I don't need to style one element in separate CSS file.</p> <p>Now I will go with some doubts about my code.</p> <p>I create new class when in admin, but I will need to access this class later to get settings value by calling <code>acau_get_settings</code> function defined in this class. Can I restrict some part of this class to be admin-only or I really need it all to work correctly?</p> <pre><code>&lt;?php /* * Plugin Name: Ajax Cart AutoUpdate for WooCommerce * Description: Automatically updates cart page and mini cart when quantity is changed. Optionally turns off cart page notices. * Version: 1.0 * Author: taisho * Text Domain: ajax-cart-autoupdate * Domain Path: /lang * WC requires at least: 2.6.0 * WC tested up to: 3.6.2 */ // If this file is called directly, abort. if ( ! defined( 'WPINC' ) ) { die; } // Create settings class. class ajax_cart_autoupdate_settings { private $options; private $settings_page_name; private $settings_menu_name; public function __construct() { $this-&gt;settings_page_name = 'ajax-cart-autoupdate'; $this-&gt;settings_menu_name = 'Ajax Cart AutoUpdate'; // Initialize and register settings. add_action( 'admin_init', array( $this, 'register_settings' ) ); // Add settings page. add_action( 'admin_menu', array( $this, 'add_settings_page' ) ); // Add settings link to plugins page. add_action( 'plugin_action_links_' . plugin_basename( __FILE__ ), array( $this, 'add_settings_link' ) ); } public function register_settings() { register_setting( 'acau_settings', 'acau_settings', array( $this, 'sanitize' ) ); // ID / title / callback / page add_settings_section( 'configuration_section', __( 'Configuration', 'ajax-cart-autoupdate' ), array( $this, 'print_section_info' ), $this-&gt;settings_page_name ); // ID / title / callback / page / section add_settings_field( 'acau_update_delay', __( 'Update delay', 'ajax-cart-autoupdate' ), array( $this, 'acau_update_delay_callback' ), $this-&gt;settings_page_name, 'configuration_section' ); add_settings_field( 'acau_positive_qty', __( 'Cart minimum quantity', 'ajax-cart-autoupdate' ), array( $this, 'acau_positive_qty_callback' ), $this-&gt;settings_page_name, 'configuration_section' ); add_settings_field( 'acau_cart_notices_off', __( 'Cart page notices', 'ajax-cart-autoupdate' ), array( $this, 'acau_cart_notices_off_callback' ), $this-&gt;settings_page_name, 'configuration_section' ); } public function add_settings_page() { // This page will be under "Settings" add_options_page( 'Settings Admin', $this-&gt;settings_menu_name, 'manage_options', $this-&gt;settings_page_name, array( $this, 'create_settings_page' ) ); } /** * Get the option that is saved or the default. * * @param string $index. The option we want to get. */ public function acau_get_settings( $index = false ) { $defaults = array ( 'acau_update_delay' =&gt; 1000,'acau_positive_qty' =&gt; true,'acau_cart_notices_off' =&gt; true ); $settings = get_option( 'acau_settings', $defaults ); $settings = wp_parse_args( $settings, $defaults ); if ( $index &amp;&amp; isset( $settings[ $index ] ) ) { return $settings[ $index ]; } return $settings; } public function create_settings_page() { $this-&gt;options = $this-&gt;acau_get_settings(); ?&gt; &lt;div class="wrap"&gt; &lt;h1&gt;Ajax Cart AutoUpdate for WooCommerce&lt;/h1&gt; &lt;form method="post" action="options.php"&gt; &lt;?php // This prints out all hidden setting fields settings_fields( 'acau_settings' ); do_settings_sections( $this-&gt;settings_page_name ); submit_button(); ?&gt; &lt;/form&gt; &lt;/div&gt; &lt;?php } function add_settings_link( $links ) { $links = array_merge( array( '&lt;a href="' . esc_url( admin_url( '/options-general.php?page=' . $this-&gt;settings_page_name ) ) . '"&gt;' . __( 'Settings' ) . '&lt;/a&gt;' ), $links ); return $links; } /** * Sanitize each setting field as needed * * @param array $input Contains all settings fields as array keys */ public function sanitize( $input ) { $new_input = array(); if( isset( $input['acau_update_delay'] ) ) $new_input['acau_update_delay'] = absint( $input['acau_update_delay'] ); if( isset( $input['acau_positive_qty'] ) ) $new_input['acau_positive_qty'] = ( $input['acau_positive_qty'] == 1 ? 1 : 0 ); if( isset( $input['acau_cart_notices_off'] ) ) $new_input['acau_cart_notices_off'] = ( $input['acau_cart_notices_off'] == 1 ? 1 : 0 ); return $new_input; } /** * Print the Section text */ public function print_section_info() { return; // print 'Enter your settings below:'; } /** * Get the settings option array and print one of its values */ public function acau_update_delay_callback() { printf( '&lt;input type="text" id="acau_update_delay" name="acau_settings[acau_update_delay]" value="%1$s" /&gt; &lt;p class="description"&gt;%2$s&lt;/p&gt;', isset( $this-&gt;options['acau_update_delay'] ) ? esc_attr( $this-&gt;options['acau_update_delay']) : '', __( 'Delay in miliseconds since last action affecting product quantity. Low values will trigger update when customers are in the middle of changing quantity. High values will make them wait and wonder why the cart doesn\'t recalculate.', 'ajax-cart-autoupdate' ) ); } public function acau_positive_qty_callback() { printf( '&lt;fieldset&gt; &lt;label&gt;&lt;input id="acau_positive_qty" type="checkbox" name="acau_settings[acau_positive_qty]" value="1" %1$s /&gt;%2$s&lt;/label&gt; &lt;/fieldset&gt;', isset( $this-&gt;options['acau_positive_qty'] ) &amp;&amp; ( 1 == $this-&gt;options['acau_positive_qty'] ) ? 'checked="checked" ':'', __( 'Change minimum product quantity on cart page from 0 to 1. If unchecked, 0 quantity is valid and such products are removed on cart update.', 'ajax-cart-autoupdate' ) ); } public function acau_cart_notices_off_callback() { printf( '&lt;fieldset&gt; &lt;label&gt;&lt;input id="acau_cart_notices_off" type="checkbox" name="acau_settings[acau_cart_notices_off]" value="1" %1$s /&gt;%2$s&lt;/label&gt; &lt;/fieldset&gt;', isset( $this-&gt;options['acau_cart_notices_off'] ) &amp;&amp; ( 1 == $this-&gt;options['acau_cart_notices_off'] ) ? 'checked="checked" ':'', __( 'Turn off notices on cart page. Most common are "Cart updated." and notice about product removed from cart.', 'ajax-cart-autoupdate' ) ); } } if( is_admin() ) $my_settings_page = new ajax_cart_autoupdate_settings(); </code></pre> <p>Here is how this plugin runs on cart page. I'm creating a new instance of settings class within function <code>ajax_cart_autoupdate</code> and access settings with <code>acau_get_settings</code> function. Before adding this function to my class, I could access settings values, but only if they were saved on database. It would lead to situation when on fresh install settings page were filled, but accessing value from class would pick 0 in case of <code>acau_update_delay</code>, as it wasn't stored on db. I think it can be potentially slow, but my biggest hurdle is how I would get value in multiple different functions? Would I need to create a new class instance each time? This is what I need to overcome, in order to be able to create another plugin which will have more different settings used in different functions.</p> <pre><code>// Only if WooCommerce is active (doesn't work for Github installations which have version in folder name). if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) || ( get_site_option('active_sitewide_plugins') &amp;&amp; array_key_exists( 'woocommerce/woocommerce.php', get_site_option('active_sitewide_plugins') ) ) ) { // Run plugin. add_action( 'template_redirect', 'run_acau' ); function run_acau() { if (! is_cart() ) return; // Only if it's cart page. // Enqueue CSS and js file. Localize to use php variables from plugin settings. add_action( 'wp_enqueue_scripts', 'ajax_cart_autoupdate' ); } function ajax_cart_autoupdate( ) { $plugin_abbv_name = 'acau'; $plugin_slug = 'ajax-cart-autoupdate-for-woocommerce'; $plugin_short_slug = 'ajax-cart-autoupdate'; // wp_enqueue_style( $plugin_short_slug . '-style', plugins_url() . '/' . $plugin_slug . '/css/' . $plugin_slug . '.css'); /*don't display default "Update cart" button, its behavior can still be triggered automatically, in WooCommerce 3.4.0 input element type was changed to button, class .button is present in all versions (at least from 2.6 when AJAX cart appeared in WooCommerce core) */ add_action('wp_head', 'hide_update_cart_button', 20); wp_enqueue_script( $plugin_short_slug, plugins_url() . '/' . $plugin_slug . '/js/' . $plugin_slug . '.js', array('jquery'), '', true); $acau_settings_page = new ajax_cart_autoupdate_settings(); // js variable name =&gt; variable value $data = array ( 'acau_update_delay' =&gt; $acau_settings_page-&gt;acau_get_settings('acau_update_delay'), ); wp_localize_script( $plugin_short_slug, 'phpVars', $data ); // Cart page minimum qty = 1 instead of 0. if (1 == $acau_settings_page-&gt;acau_get_settings('acau_positive_qty') ) { add_filter( 'woocommerce_quantity_input_args', 'custom_cart_min_qty', 10, 2 ); } /* Don't display any notices, it includes: - "Cart updated." - removed cart item notice - the one when checkout session expires and cart items disappear (it duplicates no items in cart standard message). */ if (1 == $acau_settings_page-&gt;acau_get_settings('acau_cart_notices_off') ) { WC()-&gt;session-&gt;set( 'wc_notices', null ); } } function hide_update_cart_button() { echo "&lt;style&gt;.button[name='update_cart']{ display: none!important;}&lt;/style&gt;"; } function custom_cart_min_qty( $args, $product ) { $args['min_value'] = 1; return $args; } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T07:04:59.280", "Id": "219789", "Score": "1", "Tags": [ "php", "wordpress", "e-commerce" ], "Title": "Simple cart update WordPress plugin" }
219789
<p>I have made an equivalent of Python's "eval" command in Arduino (which in itself is quite a feat) but the part that decodes the output of it is not small enough to fit in another 30 functions since this will be running on an Arduino Micro.</p> <p>Any suggestions on compacting it? (btw I don't care about the actual function, rather the bit in "void Loop()" since that part is gonna be repeated a lot.)</p> <pre><code>struct evals { int pointer; bool boolout; String stringout; int intout; float floatout; }; String variables[50]; String LocalVariables[50]; void setup() { for (int Variable = 0; Variable &lt; 50; Variable++) { LocalVariables[Variable] = ""; } Serial.begin(9600); LocalVariables[0] = "TestVariable"; variables[0] = "true"; } void loop() { if (Serial.available()) { String read = Serial.readString(); evals read2 = eval(read); switch (read2.pointer) { case 0: Serial.println("NULL"); break; case 1: Serial.print("INT "); Serial.println(read2.intout); break; case 2: Serial.print("FLOAT "); Serial.println(read2.floatout); break; case 3: Serial.print("STRING "); Serial.println(read2.stringout); break; case 4: Serial.print("BOOL "); Serial.println(read2.boolout); break; case 5: read2 = eval(variables[read2.intout]); switch (read2.pointer) { case 0: Serial.println("NULL"); break; case 1: Serial.print("INT "); Serial.println(read2.intout); break; case 2: Serial.print("FLOAT "); Serial.println(read2.floatout); break; case 3: Serial.print("STRING "); Serial.println(read2.stringout); break; case 4: Serial.print("BOOL "); Serial.println(read2.boolout); break; } } } } struct evals eval(String input) { evals output; input.replace("\n", ""); input.replace("\r", ""); char input2[input.length() + 1]; input.toCharArray(input2, input.length() + 1); if (input.length() == 0) { output.pointer = 0; return output; } if (input2[0] == '"' and input2[strlen(input2) - 1] == '"') { input.remove(0, 1); input.remove(strlen(input2) - 2, 1); output.pointer = 3; output.stringout = input; return output; } else if (input == "true") { output.pointer = 4; output.boolout = true; return output; } else if (input == "false") { output.pointer = 4; output.boolout = false; return output; } else { String inputs = input; inputs.replace("0", ""); inputs.replace("1", ""); inputs.replace("2", ""); inputs.replace("3", ""); inputs.replace("4", ""); inputs.replace("5", ""); inputs.replace("6", ""); inputs.replace("7", ""); inputs.replace("8", ""); inputs.replace("9", ""); if (inputs.length() == 0) { output.pointer = 1; output.intout = input.toInt(); return output; } else { if (inputs[0] == '.' and inputs.length() == 1) { output.pointer = 2; output.floatout = input.toFloat(); return output; } else { for (int Variable = 0; Variable &lt; 50; Variable++) { if (LocalVariables[Variable] == "") { continue; } else if (LocalVariables[Variable] == input) { output.pointer = 5; output.intout = Variable; return output; } } output.pointer = 0; return output; } } } } </code></pre>
[]
[ { "body": "<p>I'll focus on the <code>void loop()</code> part as you ask it, even though it can't be reviewed in isolation, especially from the <code>evals</code> structure.</p>\n\n<p>So, what is this <code>loop</code> all about? You want to select the correct behavior based on the way the evaluated data has been tagged. Which mean we have three levers to act upon: the selection mechanism, the tagging mechanism, and the way the data is represented. I believe you can do better with all three:</p>\n\n<ul>\n<li>tagging your data with a <code>char*</code> is a bad idea. The first important thing to note is that comparing a <code>char*</code> with a string literal is undefined behavior. It works with most compilers, but if you enable all warnings, as you should do, you'll see it isn't guaranteed by the standard. It means that you should rely on proper string comparisons instead, character by character -e.g with <code>strcmp</code>- which are of course slow, if you really want to keep the string-tagging. But you don't: there are faster, simpler and more robust mechanisms such as <code>enum</code>s. </li>\n</ul>\n\n<p>For instance:</p>\n\n<pre><code>enum class Type : char { NULL, INTEGER, FLOATING_PRECISION, STRING, BOOL };\n</code></pre>\n\n<ul>\n<li><p>Representing your data with a struct containing as many members as there are possible types is a waste of space you should care about. You can use <code>union</code>s to make it more compact. </p></li>\n<li><p>Selecting the correct behavior can be made in several ways, the one you chose among them. But, not wandering very far, you could have used a <code>switch</code>, which is arguably easier to read and can be optimized by the compiler: the program will go through the <code>if else</code> clauses in succession, whereas a <code>switch</code> can be turned into a jump-table with logarithmic look-up. If you want to explore further, and have a more scalable selection mechanism, you could have a try at a virtual function.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T10:28:45.573", "Id": "424563", "Score": "0", "body": "Thank you a lot! any std thing isn't in Arduino code sadly (i searched a lot when I was trying to use std::any), but the rest of your feedback is very much appreciated!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T11:09:36.733", "Id": "424567", "Score": "0", "body": "Ok I have added your switch case idea, but I can't find very much documentation on how to do the rest of the stuff in Arduino, if possible could you send me some documentation?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T12:04:17.400", "Id": "424579", "Score": "0", "body": "@LiamBogur: you're not supposed to edit your question once it has an answer -though you can answer your own question, or post another, improved question after." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T12:10:40.920", "Id": "424581", "Score": "0", "body": "ok sorry, I don't really know how to use StackExchange" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T12:11:13.873", "Id": "424582", "Score": "0", "body": "@LiamBogur: what do you mean in Arduino? I assumed you were programming in C++ and targeting an Arduino device?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T12:50:53.827", "Id": "424589", "Score": "0", "body": "no I'm coding in Arduino code natively, hence the very messy code (I have the C++ tag since Arduino Code is based on C++ and most C++ scripts normally work with Arduino)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T07:23:48.343", "Id": "424689", "Score": "0", "body": "I have decided to switch to C++ since it has things like std::any and std::variant which would be way easier to use for this project and would compact not only the decoding part of it but also the eval function and really everything." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T10:17:57.080", "Id": "219802", "ParentId": "219791", "Score": "1" } } ]
{ "AcceptedAnswerId": "219802", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T07:19:20.653", "Id": "219791", "Score": "1", "Tags": [ "c++", "memory-optimization", "arduino" ], "Title": "Python's eval command in Arduino" }
219791
<p>I wanted to use <code>&lt;select multiple</code>> but was annoyed by the poor design on desktops which is why I created a version with dropdown:</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>convertSelect("001", "Options"); function convertSelect(el_id, name) { let el = document.getElementById(el_id), opts = Array.from(el.options); let input_el = document.createElement('input'); input_el.setAttribute('id', el_id + '_input'); input_el.setAttribute('type', 'text'); input_el.setAttribute('autocomplete', 'off'); input_el.setAttribute('readonly', 'readonly'); input_el.addEventListener('focus', () =&gt; document.getElementById(el_id + '_span').style.display = ""); input_el.addEventListener('blur', () =&gt; blur(el_id)); el.parentNode.insertBefore(input_el, el.nextSibling); let span_el = document.createElement('span'); span_el.setAttribute('id', el_id + '_span'); span_el.setAttribute('style', `min-width:${(input_el.offsetWidth-2)}px;margin-top:${input_el.offsetHeight}px;margin-left:-${input_el.offsetWidth}px;position:absolute;border:1px solid grey;display:none;z-index:9999;text-align:left;background:white;max-height:130px;overflow-y:auto;overflow-x:hidden;`); span_el.addEventListener('mouseout', () =&gt; blur(el_id)); span_el.addEventListener('click', () =&gt; document.getElementById(el_id + '_input').focus()); input_el.parentNode.insertBefore(span_el, input_el.nextSibling); opts.forEach(opt =&gt; { let i = opts.indexOf(opt); let temp_label = document.createElement('label'); temp_label.setAttribute('for', el_id + '_' + i); let temp_input = document.createElement('input'); temp_input.setAttribute('style', 'width:auto;'); temp_input.setAttribute('type', 'checkbox'); temp_input.setAttribute('id', el_id + '_' + i); temp_input.checked = opt.selected; temp_input.disabled = opt.disabled || el.disabled; temp_input.addEventListener('change', () =&gt; check(el_id, name)); temp_label.appendChild(temp_input); temp_label.appendChild(document.createTextNode(opt.textContent)); span_el.appendChild(temp_label); }); el.style.display = 'none'; check(el_id, name); } function blur(el_id) { let el = document.getElementById(el_id); clearTimeout(parseInt(el.dataset.timer)); el.dataset.timer = setTimeout(() =&gt; { if (document.activeElement.id !== el_id + '_input' &amp;&amp; document.activeElement.id !== el_id + '_span') document.getElementById(el_id + '_span').style.display = "none"; }, 200).toString(); } function check(el_id, name) { let el = document.getElementById(el_id), opts = Array.from(el.options), select_qty = 0, select_name; opts.forEach(opt =&gt; { let i = opts.indexOf(opt), checkbox = document.getElementById(`${el_id}_${i}`); el.options[i].selected = checkbox.checked; if (checkbox.checked) { select_name = checkbox.parentElement.childNodes[1].textContent; select_qty++; } document.getElementById(`${el_id}_input`).value = select_qty &lt; 1 ? '' : (select_qty &gt; 1 ? `${select_qty} ${name}` : select_name); }); el.dispatchEvent(new Event('change', { 'bubbles': true })); }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>label { display: block; } input[type="text"]:hover { cursor: default; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;select id="001" multiple&gt; &lt;option value="2"&gt;Option Two&lt;/option&gt; &lt;option value="4"&gt;Option Four&lt;/option&gt; &lt;option value="6"&gt;Option Six&lt;/option&gt; &lt;option value="8" disabled&gt;Disabled Option&lt;/option&gt; &lt;/select&gt;</code></pre> </div> </div> </p> <p>As I'm not very experienced with DOM-Manipulation I would be glad if someone could check my code for any unnecessary complexion, possible simplifications and mistakes. Any improvement tip or critique is helpful!</p> <p>PS: Especially the blur-function with the timer is bugging me as it feels like a hack.</p> <p><strong>Edit:</strong> The updated version can be found at <a href="https://codepen.io/MiXT4PE/pen/OYLRpz" rel="nofollow noreferrer">https://codepen.io/MiXT4PE/pen/OYLRpz</a></p>
[]
[ { "body": "<h2>Overall Feedback</h2>\n\n<p>The UI looks good. I think the code is okay, but the number of DOM lookups is higher than it needs to be. Those could be reduced by storing the checkboxes in an array. While browsers have come a long way in terms of efficiency, DOM lookups are still not cheap. Since <a href=\"/questions/tagged/ecmascript-6\" class=\"post-tag\" title=\"show questions tagged &#39;ecmascript-6&#39;\" rel=\"tag\">ecmascript-6</a> features like template literals are used, a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes\" rel=\"nofollow noreferrer\">class</a> or else a simple object could be used to store references to the newly created elements, timers, etc. in arrays, rather than querying the DOM to access elements.</p>\n\n<hr>\n\n<h2>Targeted Feedback</h2>\n\n<p>The ES-6 <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"nofollow noreferrer\">spread syntax</a> can be used instead of using <code>Array.from()</code> to put elements into an array. </p>\n\n<p>Lines like this:</p>\n\n<blockquote>\n<pre><code>opts = Array.from(el.options)\n</code></pre>\n</blockquote>\n\n<p>Can be simplified to just:</p>\n\n<pre><code>opts = [...el.options]\n</code></pre>\n\n<p>This requires one less function call. </p>\n\n<hr>\n\n<p>When using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach\" rel=\"nofollow noreferrer\"><code>Array.forEach()</code></a> there are <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Parameters\" rel=\"nofollow noreferrer\">more parameters</a> passed to the callback function than just the current element. Both occurrences of </p>\n\n<blockquote>\n<pre><code>opts.forEach(opt =&gt; {\n let i = opts.indexOf(opt);\n</code></pre>\n</blockquote>\n\n<p>Could have the call to <code>opts.indexOf()</code> eliminated by utilizing the second parameter instead. </p>\n\n<pre><code>opts.forEach((opt, i) =&gt; {\n</code></pre>\n\n<hr>\n\n<p>The code uses <code>let</code> for most all variables. Many of those variables never get re-assigned. It is wise to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\"><code>const</code></a> for any such variable, to avoid accidental re-assignment.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-18T05:09:15.023", "Id": "224382", "ParentId": "219792", "Score": "1" } } ]
{ "AcceptedAnswerId": "224382", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T07:58:50.417", "Id": "219792", "Score": "4", "Tags": [ "javascript", "html", "ecmascript-6", "event-handling" ], "Title": "<select multiple> with dropdown" }
219792
<p>In Main.cs, which is attached to a GameObject that has a MeshRenderer and MeshFilter:</p> <pre><code>using UnityEngine; [RequireComponent(typeof(MeshFilter))] public class Main : MonoBehaviour { public int divisions = 0; public float radius = 1f; private void Awake () { MeshFilter meshFilter = GetComponent&lt;MeshFilter&gt;(); Sphere sphere = SphereCreator.Create(divisions, radius, "World"); meshFilter.mesh = sphere.Render(); } } </code></pre> <p>And then in SphereCreator.cs:</p> <pre><code>using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(MeshFilter))] public class Sphere { public Vector3[] sNormals; public Triangle[] sTriangles; public Vector3[] sVertices; public string sName; public Sphere(Vector3[] aNormals, Triangle[] aTriangles, Vector3[] aVertices, string aName) { sNormals = aNormals; sTriangles = aTriangles; sVertices = aVertices; sName = aName; } public Mesh Render() { // Turn Triangle array into int array of vertices int[] triangles = new int[sTriangles.Length * 3]; int i = 0; foreach (Triangle triangle in sTriangles) { triangles[i + 0] = triangle.vertices[0]; triangles[i + 1] = triangle.vertices[1]; triangles[i + 2] = triangle.vertices[2]; i += 3; } // Create the Mesh Mesh mesh = new Mesh { name = sName, vertices = sVertices, triangles = triangles, normals = sNormals }; return mesh; } } public class Triangle { public int[] vertices; public Triangle(int a, int b, int c) { vertices = new int[] { a, b, c }; } } public class SphereCreator : MonoBehaviour { public static Vector3[] normals; public static Triangle[] triangles; private static List&lt;Vector3&gt; vertices; public static int GetMidPointIndex(Dictionary&lt;int, int&gt; cache, int indexA, int indexB, List&lt;Vector3&gt; vertices) { // Checks if vertice has already been made and creates it if it hasn't int smallerIndex = Mathf.Min(indexA, indexB); int greaterIndex = Mathf.Max(indexA, indexB); int key = (smallerIndex &lt;&lt; 16) + greaterIndex; if (cache.TryGetValue(key, out int ret)) return ret; Vector3 p1 = vertices[indexA]; Vector3 p2 = vertices[indexB]; Vector3 middle = Vector3.Lerp(p1, p2, 0.5f).normalized; ret = vertices.Count; vertices.Add(middle); cache.Add(key, ret); return ret; } public static Sphere Create(int divisions, float radius, string name) { float t = (1.0f + Mathf.Sqrt(5.0f)) / 2.0f; // Initial Vertices and Triangles of Icosahedron vertices = new List&lt;Vector3&gt; { new Vector3(-1, t, 0).normalized, new Vector3(1, t, 0).normalized, new Vector3(-1, -t, 0).normalized, new Vector3(1, -t, 0).normalized, new Vector3(0, -1, t).normalized, new Vector3(0, 1, t).normalized, new Vector3(0, -1, -t).normalized, new Vector3(0, 1, -t).normalized, new Vector3(t, 0, -1).normalized, new Vector3(t, 0, 1).normalized, new Vector3(-t, 0, -1).normalized, new Vector3(-t, 0, 1).normalized }; triangles = new Triangle[] { new Triangle(0, 11, 5), new Triangle(0, 1, 7), new Triangle(0, 5, 1), new Triangle(0, 7, 10), new Triangle(0, 10, 11), new Triangle(1, 5, 9), new Triangle(5, 11, 4), new Triangle(11, 10, 2), new Triangle(10, 7, 6), new Triangle(7, 1, 8), new Triangle(3, 9, 4), new Triangle(3, 4, 2), new Triangle(3, 2, 6), new Triangle(3, 6, 8), new Triangle(3, 8, 9), new Triangle(4, 9, 5), new Triangle(2, 4, 11), new Triangle(6, 2, 10), new Triangle(8, 6, 7), new Triangle(9, 8, 1) }; // Divide faces var midPointCache = new Dictionary&lt;int, int&gt;(); for (int d = 0; d &lt; divisions; d++) { var newTriangles = new List&lt;Triangle&gt;(); for (int f = 0; f &lt; triangles.Length; f++) { // Get current triangle Triangle triangle = triangles[f]; // Get current triangle vertices int a = triangle.vertices[0]; int b = triangle.vertices[1]; int c = triangle.vertices[2]; // Find vertice at centre of each edge int ab = GetMidPointIndex(midPointCache, a, b, vertices); int bc = GetMidPointIndex(midPointCache, b, c, vertices); int ca = GetMidPointIndex(midPointCache, c, a, vertices); // Create new Triangles newTriangles.Add(new Triangle(a, ab, ca)); newTriangles.Add(new Triangle(b, bc, ab)); newTriangles.Add(new Triangle(c, ca, bc)); newTriangles.Add(new Triangle(ab, bc, ca)); } triangles = newTriangles.ToArray(); } // Create Normals normals = new Vector3[vertices.Count]; for (int i = 0; i &lt; vertices.Count; i++) { normals[i] = vertices[i] = vertices[i].normalized; } Sphere sphere = new Sphere(normals, triangles, vertices.ToArray(), name); return sphere; } } </code></pre> <p>I feel like SphereCreator is much more complex than it needs to be. Does anyone have any ideas?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T11:55:41.393", "Id": "219806", "Score": "2", "Tags": [ "c#", "unity3d" ], "Title": "Making a Icosphere in C# and Unity" }
219806
<p>I have one model class as listed here:</p> <pre><code>class Post &lt; ActiveRecord::Base has_many :comments def tags comments.map(&amp;:tag).uniq.sort end end </code></pre> <p>and below is the best rspec as per my understanding:</p> <pre><code>context 'tags' do let(:post) { Post.find_by_code('TX') } it 'returns sorted alphabetically list of available tags' do expect(post.tags).to eq(post.comments.map(&amp;:tag).uniq.sort) end end </code></pre> <p>Do we any better way to test it or even it is nor require to test.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-09T13:05:07.480", "Id": "425048", "Score": "0", "body": "You sould create a post, add comments to it, call the `tags` method and compare to a hardcoded ordered result pre processed based on the input you gave it. Now it's not testing anything, it's will always be true since you have basically the same code on both sides of the expectation." } ]
[ { "body": "<p>Your test code is merely a copy of your model code, so you're not really testing anything.</p>\n\n<p>Rather, your unit test should rely on fixtures, and the expected answer should be hard-coded in the test.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T16:28:38.607", "Id": "424616", "Score": "0", "body": "Yes I have fixture of Post" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T16:14:02.710", "Id": "219815", "ParentId": "219814", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T15:52:27.270", "Id": "219814", "Score": "2", "Tags": [ "ruby", "ruby-on-rails", "rspec" ], "Title": "Rspec test for Rails method to return alphabetically sorted list of tags" }
219814
<p>Powershell has the <code>Split-Path</code> cmdlet which allows you to extract the Parent and Leaf of a file. In PS version 6, you can extract the extension, with the <code>-Extension</code> switch. Why this wasn't a feature of PS version 4 and greater I don't know, so I decided to write my own version in Python.</p> <p><strong>PathUtilities</strong>:</p> <pre><code># PathUtilities.py def parse_file_path(file_path : str): """ The function a user must call if they want to parse a file path. It accepts, validates, and returns a tuple containing the elements (parent, leaf, and extension) of the path. The path doesn't haven't exist. Args: file_path : str - A string representing a file path. Returns: A tuple containing all the parsed elements. """ _determine_if_the_drive_letter_is_valid(file_path=file_path) _determine_if_second_element_is_valid(file_path=file_path) _determine_if_the_string_contains_forbidden_characters(string_to_validate = file_path[2:]) return _construct_path_tuple(file_path=file_path) def _determine_if_the_drive_letter_is_valid(file_path : str): """ Determines if the drive letter is a letter. Raises a TypeError if the first letter is invalid. Args: file_path - see parse_file_path function. Returns: None """ drive_letter = file_path[:1] if not drive_letter.isalpha(): raise TypeError("Drive Letter is invalid.") def _determine_if_second_element_is_valid(file_path : str): """ Determine if the second element in the path is a : Raises a ValueError if the second element is invalid. Args: file_path - see parse_file_path function. Returns: None """ valid_element = ":" second_element = file_path[1] if second_element != valid_element: raise ValueError("Invalid characters in path.") def _determine_if_the_string_contains_forbidden_characters(*additional_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. *additional_characters - To make the function reusable we accept additional elements to be tested in addition to the list of forbidden characters. """ # Contains all the forbidden characters in Windows paths. # Note the 4 slashes, because paths use \\ to seperate folders and drives, we have to validate # if the user entered additional slashes, two slashes is fine, but more are forbidden. # Example: C:\\Users\\Sveta\\\\\emp_list.txt - invalid. forbidden_characters = ["&lt;", "&gt;", ":", "/", '"', "|", "?", "*"," ", "\\\\"] for forbidden_character in forbidden_characters: if forbidden_character in string_to_validate: raise ValueError("Invalid characters in path.") if additional_characters: for character in additional_characters: if character in string_to_validate: raise ValueError("Invalid characters in path.") def _parse_extension(string_to_parse : str): """ Split the file path on the period, validate, and return the extension with the period. Raises a ValueError if the extension contains forbidden characters. Args: file_path - see parse_file_path function Returns: the extension of the file or None, if no file extension is present. """ # file and folder names are allowed to have periods, so we split on that, # but we're only interested in the last element, the extension. split_extension = string_to_parse.split(".")[-1] # if the string doesn't have a file extension, we return None. if len(split_extension) == len(string_to_parse): return None _determine_if_the_string_contains_forbidden_characters("\\", string_to_validate = split_extension) return ".{0}".format(split_extension) def _parse_leaf(file_path : str): """ Split the file path using \\ and returns the last element. Args: file_path - see parse_file_path function. Returns: the last element of the file path, in this case the filename with extension. """ delimiter = "\\" return file_path.split(delimiter)[-1] def _parse_parent(file_path : str, leaf: str): """ Take the leaf, and use it as a delimiter to extract the parent directory, without the trailing slash. Args: file_path - see parse_file_path function. leaf : str - the leaf of our file path. Returns: The first element in our list, our parent directory. """ delimiter = "\\{0}".format(leaf) return file_path.split(delimiter)[0] def _construct_path_tuple(file_path : str): """ Constructs a tuple representing the elements of the file path. Args: file_path - see parse_file_path function. Returns: A tuple that contains the file elements. """ leaf = _parse_leaf(file_path = file_path) extension = _parse_extension(string_to_parse = leaf) parent = _parse_parent(file_path = file_path, leaf=leaf) return (parent, leaf, extension) </code></pre> <p><strong>Main</strong>:</p> <pre><code>import pathutilities def main(): try: path = pathutilities.parse_file_path("C:\\Users\\Sveta\\Employee\\emp_list.txt") except (TypeError, ValueError) as error: print(error) else: parent, leaf, extension = path print(parent, leaf, extension) # Output: # C:\Users\Sveta\Employee emp_list.txt .txt if __name__ == '__main__': main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T17:15:05.097", "Id": "424628", "Score": "1", "body": "Are you aware of the [`os.path`](https://docs.python.org/3/library/os.path.html) module?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T18:04:53.510", "Id": "424638", "Score": "3", "body": "@200_success Since this is Python 3, using [`pathlib`](https://docs.python.org/3/library/pathlib.html) can result in a cleaner interface." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T22:29:15.183", "Id": "424827", "Score": "0", "body": "@200_success - I was aware of it, but I was unaware of the features that allow you to access the parent, leaf, and suffix. Meh, I consider this a learning exercise in writing python code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-08T09:33:03.357", "Id": "424858", "Score": "0", "body": "The second to last line in `_parse_extension` is invalid Python code. When trying to source the file, Python yields a `SyntaxError` in line 155." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-08T14:12:04.690", "Id": "424893", "Score": "0", "body": "@KonradRudolph - This is strange, I'm unable to reproduce this error. My code runs and the correct output is produced." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-08T14:15:13.480", "Id": "424894", "Score": "0", "body": "@nsonline You’re most likely copying the wrong code. The relevant line is obviously a syntax error, it reads `def _determine_if_the_string_contains_forbidden_characters(\"\\\\\", string_to_validate = split_extension)`, which is obviously not meaningful." } ]
[ { "body": "<ol>\n<li><a href=\"https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.drive\" rel=\"noreferrer\"><code>PurePath.drive</code></a> allows UNC drives, but yours doesn't.</li>\n<li><a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"noreferrer\"><code>pathlib</code></a> implements everything you need. Which is available from Python 3.4.</li>\n</ol>\n\n<p>Note: This code doesn't require the drive to be set. That can be achieved by checking <code>PurePath.drive</code> if it is needed.</p>\n\n<pre><code>from pathlib import PurePath\n\n\ndef parse_file_path(path):\n path = PurePath(path)\n return str(path.parent), path.name, path.suffix or None\n</code></pre>\n\n<hr>\n\n<p>If you're not running 3.4+ then <a href=\"https://docs.python.org/3/library/pathlib.html#correspondence-to-tools-in-the-os-module\" rel=\"noreferrer\">the equivalent in <code>os.path</code></a>, is pretty simple too. But IMO is pretty unsightly.</p>\n\n<p>You can also check the drive through <a href=\"https://docs.python.org/3/library/os.path.html#os.path.splitdrive\" rel=\"noreferrer\"><code>os.path.splitdrive</code></a>.</p>\n\n<pre><code>import os.path\n\n\ndef parse_file_path(path):\n name = os.path.basename(path)\n return (\n os.path.dirname(path),\n name,\n os.path.splitext(name)[1] or None\n )\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T22:25:08.267", "Id": "424666", "Score": "2", "body": "So far so good for a better alternative. But it's not much of a code review. And OP could definitely benefit from a code review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T22:26:26.140", "Id": "424667", "Score": "0", "body": "@KonradRudolph What do you feel is lacking in my answer? I may be able to provide it if I know what 'it' is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T10:11:53.323", "Id": "424704", "Score": "0", "body": "Well it’s not a code *review*. As in, you provide no feedback for OP’s code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T10:24:13.737", "Id": "424706", "Score": "1", "body": "Clearly we have a difference of opinion of what \"no feedback\" is. I've clearly shown how the OP's `parse_file_path` can be simplified. Since it seems you're unable to explain your POV, and for some unknown reason limit your explanations to ambiguous statements such as \"this isn't a code review\", then I cannot help you. Please post an answer which fills in the aspects you find lacking in mine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T10:58:23.850", "Id": "424720", "Score": "0", "body": "I have to admit that I’m a bit puzzled as to where the issue is. A *review* gives specific feedback about the code under discussion. Your answer doesn’t do this *at all*. Instead, it suggests an alternative. This is of course entirely valid, but it’s not a review, and it’s not feedback. Examples of specific feedback for OP’s code would be: “Well done on using type hints for the method arguments; don’t forget to also annotate return types”, or “your method names are too verbose”; or “ `_parse_extension` contains invalid syntax”." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T11:05:10.947", "Id": "424725", "Score": "0", "body": "@KonradRudolph I don't know what your definition of 'feedback' is. However this answer provides specific feedback to the code in the question. The note is specific to this question and the code I've provided also is specific to this question. I also wouldn't be able to provide this feedback, verbatim, to another question, as it's specific to this question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T11:13:07.587", "Id": "424731", "Score": "0", "body": "“specific” as in specific to the code posted, rather than general for any code solving the same issue. This is by the way all very well established on this website, see https://codereview.meta.stackexchange.com/a/8410/308" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T11:13:52.100", "Id": "424732", "Score": "0", "body": "@KonradRudolph Why are you referring me to that meta?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T11:15:38.797", "Id": "424734", "Score": "0", "body": "Because it supports my initial comment that your answer, while valuable, lacks the “review” aspect that’s expected. I suggest you actually *read* the linked meta discussion." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T11:18:18.437", "Id": "424735", "Score": "0", "body": "@KonradRudolph I have read it again. What \"review\" aspect is it missing? And again, why have you linked me that meta?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T11:28:51.863", "Id": "424740", "Score": "0", "body": "I suggest giving it a night’s sleep and then reading your answer, the comments and the meta discussion again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T11:30:26.180", "Id": "424741", "Score": "0", "body": "@KonradRudolph Wow, I've asked for the same thing consistently, and you're unable to explain yourself. So you tell me to have some sleep? Wat. If you really feel my answer doesn't follow the rules of Code Review.SE then you can [post a question on our Meta](https://codereview.meta.stackexchange.com/questions/ask)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T11:37:03.117", "Id": "424743", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/93339/discussion-between-peilonrayz-and-konrad-rudolph)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T22:30:56.947", "Id": "424828", "Score": "0", "body": "@KonradRudolph - Were do you see that invalid syntax in `_parse_extension`? My code runs, I tested it before I posted it on CR." } ], "meta_data": { "CommentCount": "14", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T17:58:10.360", "Id": "219823", "ParentId": "219817", "Score": "10" } }, { "body": "<p>Apart from the other alternative of using <code>pathlib</code></p>\n\n<p>Here are some comments on the code:</p>\n\n<h1><code>rsplit</code></h1>\n\n<pre><code>strings have also a method [`str.rsplit`][1] which start at the right side of the string.\n</code></pre>\n\n<p>So extracting the parent and leaf is as simple as:</p>\n\n<pre><code>parent, leaf = path.rsplit(delimiter, maxsplit=1)\n</code></pre>\n\n<h1>delimiter</h1>\n\n<p>Instead of hardcoding the delimiter in a few places, you can define it as a module constant at the top of the file:</p>\n\n<pre><code>DELIMITER = \"\\\\\"\n</code></pre>\n\n<h1>functions</h1>\n\n<p>I would bundle all the checks to validate a path in 1 function. This way you can use tuple unpacking:</p>\n\n<pre><code>def validate_path(path: str):\n drive_letter, colon, *rest = path\n if not drive_letter.isalpha():\n raise TypeError(\"Drive Letter is invalid.\")\n\n if not colon == \":\" or contains_forbidden_characters(rest):\n raise ValueError(\"Invalid characters in path.\")\n</code></pre>\n\n<h1><code>contains_forbidden_characters</code></h1>\n\n<p><code>_determine_if_the_string_contains_forbidden_characters</code> is a ridiculously long name</p>\n\n<p>There is also no reason for the initial <code>_</code>. why would you want to stop your module users from checking for forbidden strings in a path?</p>\n\n<p>This method can also be done in a different way. Instead of checking each individual forbidden character individually, you can use <code>set</code>s to test for containment:</p>\n\n<pre><code>def contains_forbidden_characters(\n path: str, addditional_forbidden_characters=(), forbidden_substrings=()\n):\n forbidden_characters = set(r\"\"\"&lt;&gt;:/\"|?* \"\"\")\n if set(path) &amp; forbidden_characters.union(\n addditional_forbidden_characters\n ):\n return True\n\n forbidden_substrings = {r\"\\\\\"}.union(forbidden_substrings)\n for element in forbidden_substrings:\n if element in path:\n return True\n</code></pre>\n\n<p>In the last part, the <code>for</code>-loop can be replaced by using <code>any</code>:</p>\n\n<pre><code>return any(element in path for element in forbidden_substrings)\n</code></pre>\n\n<p>Here I also used sets to add the possible additional forbidden characters and substrings. I represented <code>\"\\\\\\\\\"</code> as <code>r\"\\\\\"</code></p>\n\n<h1><code>split_path</code></h1>\n\n<p>My version of <code>split_path</code> expects a valid path string. It is up to the caller to make sure of this.</p>\n\n<pre><code>def split_path(path, delimiter=DELIMITER):\n parent, leaf = path.rsplit(delimiter, maxsplit=1)\n *filename, extension = leaf.rsplit(\".\", maxsplit=1)\n\n if not filename:\n extension = None\n return parent, leaf, extension\n</code></pre>\n\n<p>using <code>rsplit</code> twice, this method is a lot simpler and clearer.</p>\n\n<h1>Putting it together</h1>\n\n<pre><code>def test_path(path):\n validate_path(path)\n parent, leaf, extension = split_path(path)\n if contains_forbidden_characters(\n leaf, addditional_forbidden_characters=\"\\\\\"\n ):\n raise ValueError(\"Invalid characters in path.\")\n return parent, leaf, extension\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T11:01:15.970", "Id": "424722", "Score": "0", "body": "“why would you want to stop your module users from checking for forbidden strings in a path?” — Because it’s an implementation detail that’s not part of the module’s API. It may be there now, but it may not be in the module tomorrow. By contrast, once it’s part of the API it effectively can’t be removed without making lots of users angry. I agree with the rest of the feedback, especially the verbose method names." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T22:34:25.093", "Id": "424829", "Score": "0", "body": "*why would you want to stop your module users from checking for forbidden strings in a path?* There is no guarantee that users will check any path that they want to be parsed. Rather than leave it up to the user of my API, I do it for them for free :D. I can make the method public as well as using it when I call `parse_file_path`. What would be a more valid method name instead of `contains_forbidden_characters`? I admit that the method name is my attempt at writing clean code with clear method names." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-08T07:52:33.230", "Id": "424850", "Score": "0", "body": "`There is no guarantee that users will check any path that they want to be parsed. Rather than leave it up to the user of my API, I do it for them for free` Which is why I offered the 3 methods: 1 to verify the path, one to split it, which expects a valid path, and a 3rd, which checks and splits the path." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-08T07:53:06.250", "Id": "424851", "Score": "0", "body": "`contains_forbidden_characters` is already a shortened version of `_determine_if_the_string_contains_forbidden_characters`. It is still long, but not ridiculously so" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T10:38:34.287", "Id": "219861", "ParentId": "219817", "Score": "4" } } ]
{ "AcceptedAnswerId": "219823", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T16:54:55.887", "Id": "219817", "Score": "10", "Tags": [ "python", "python-3.x", "strings", "parsing" ], "Title": "Extracting the parent, leaf, and extension from a valid path" }
219817
<p>Here is my program to find the largest number(s) in a list of elements, possibly non-unique (in Python):</p> <pre><code>item_no = [5, 6, 7, 8, 8] max_no = 0 for i in item_no: if i &gt; max_no: max_no = i high = [i] elif i == max_no: high.append(i) </code></pre> <p>Example input: <code>[5, 6, 7, 8, 8]</code></p> <p>Example output: <code>[8, 8]</code></p> <p>How can I make this program more effective and shorter?</p> <p>Any help would be highly appreciated.</p> <p>This code is based on <a href="https://stackoverflow.com/a/55216309/1305253">help received on Stack Overflow</a>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T17:02:15.740", "Id": "424622", "Score": "1", "body": "That's pretty much as efficient as it gets. If you sorted the list first and got the last element it would be fewer lines of code, but take more computational resources and be less efficient." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T18:21:07.173", "Id": "424641", "Score": "2", "body": "I have added the [performance] tag, if you mean in big-O time, then please change it to the [complexity] tag." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T19:33:57.987", "Id": "424644", "Score": "1", "body": "@Slothario Please see my answer to see how your assumption that sorting the list \"take more computational resources\" is incorrect. Unless you mean `sorted` rather than `list.sort`." } ]
[ { "body": "<p><strong>Note</strong>: After posting my answer I found out that the question <a href=\"https://stackoverflow.com/q/55216278\">is a duplicate of this question</a>.</p>\n\n<h1>Readability</h1>\n\n<ol>\n<li>If you have no values then your code will error when you try to interact with <code>high</code>. You should define <code>high</code> outside the loop.</li>\n<li>You should use a function so it's easier to test your code.</li>\n<li>You should use full words for variable names.</li>\n</ol>\n\n<pre><code>def largest_orig_pretty(values):\n max_no = 0\n highest = []\n for value in values:\n if value &gt; max_no:\n max_no = value\n highest = [value]\n elif value == max_no:\n highest.append(value)\n return highest\n</code></pre>\n\n<h1>Performance</h1>\n\n<p>This however isn't shorter or faster than your code.</p>\n\n<p>When optimizing Python it's almost guaranteed that all C functions are faster than the Python equivalent. And so we can test some changes out:</p>\n\n<ul>\n<li>Remove <code>max_no</code> to make your code smaller.</li>\n<li>Remove <code>max_no</code> and use <code>iter</code> to not incur <span class=\"math-container\">\\$O(n)\\$</span> memory.</li>\n<li>Try using <code>collections.Counter</code>, in the hopes it's written in C.</li>\n<li><p>Use <code>list.sort</code> to sort the input so we can just take the first elements that are the same.</p>\n\n<p>I did this in multiple ways:</p>\n\n<ul>\n<li>Using a for loop. <code>largest_sort</code>.</li>\n<li>Using a functional/iterator approach, but using <code>lambda</code>. <code>largest_sort_semifunctional</code>.</li>\n<li>Using a functional/iterator approach, using <code>functools.partial</code> and <code>operator.eq</code>. <code>largest_sort_functional</code>.</li>\n</ul></li>\n<li>Using <code>sorted</code> to not mutate the input list. And otherwise using the same code as <code>largest_sort</code>.</li>\n<li><p>Using <code>max</code> and build a new list using <code>list.count</code>.</p>\n\n<p>Most of the answers in the duplicate question derive from this method.</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/a/55216417\">Allan's answer</a> is the same as my original one. <code>largest_max_count</code>.</li>\n<li><a href=\"https://stackoverflow.com/a/55216309\">Ev.Kounis's answer</a> suggests using a comprehension to build the output list.</li>\n<li><a href=\"https://stackoverflow.com/a/55216401\">Daweo's answer</a> suggested not using <code>list.count</code> and instead use a list comprehension. There are two varients one when they use <code>max</code> once and one where it's used on every iteration.</li>\n</ul></li>\n<li><a href=\"https://stackoverflow.com/a/55254044\">Grijesh Chauhan's answer</a> suggested storing only the value and a count, rather than building a list.</li>\n</ul>\n\n<p>I have not tested the output of these functions, only the timings. The sample data is also uniform, and so may not accurately describe the expected timings if this assumption is not true.</p>\n\n<p><sub><strong>Disclaimer</strong>, <a href=\"https://pypi.org/project/graphtimer/\" rel=\"noreferrer\"><code>graphtimer</code></a> was written and is maintained by me. It is only to produce the graph.</sub></p>\n\n<pre><code>import collections\nimport itertools\nimport operator\nimport functools\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom graphtimer import Plotter, MultiTimer\n\n\ndef largest_orig(values):\n max_no = 0\n for i in values:\n if i &gt; max_no:\n max_no = i\n high = [i]\n elif i == max_no:\n high.append(i)\n return high\n\n\ndef largest_orig_pretty(values):\n max_no = 0\n highest = []\n for value in values:\n if value &gt; max_no:\n max_no = value\n highest = [value]\n elif value == max_no:\n highest.append(value)\n return highest\n\n\ndef largest_no_max(values):\n if not values:\n return []\n highest = [values[0]]\n for value in values[1:]:\n if value &gt; highest[0]:\n highest = [value]\n elif value == highest[0]:\n highest.append(value)\n return highest\n\n\ndef largest_no_max_iter(values):\n values = iter(values)\n highest = [next(values)]\n for value in values:\n if value &gt; highest[0]:\n highest = [value]\n elif value == highest[0]:\n highest.append(value)\n return highest\n\n\ndef largest_counter(values):\n if not values:\n return []\n c = collections.Counter(values)\n k = max(c)\n return [k] * c[k]\n\n\ndef largest_sort(values):\n if not values:\n return []\n values.sort(reverse=True)\n value = values[0]\n for i, v in enumerate(values):\n if value != v:\n return [value] * i\n return values\n\n\ndef largest_sort_semifunctional(values):\n if not values:\n return []\n values.sort(reverse=True)\n value = values[0]\n return list(itertools.takewhile(lambda i: i == value, values))\n\n\ndef largest_sort_functional(values):\n if not values:\n return []\n values.sort(reverse=True)\n value = values[0]\n return list(itertools.takewhile(functools.partial(operator.eq, value), values))\n\n\ndef largest_sorted(values):\n if not values:\n return []\n values = sorted(values, reverse=True)\n value = values[0]\n for i, v in enumerate(values):\n if value != v:\n return [value] * i\n return values\n\n\n# Same as https://stackoverflow.com/a/55216417\ndef largest_max_count(values):\n if not values:\n return []\n maximum = max(values)\n return [maximum] * values.count(maximum)\n\n\n# Derived from Ev. Kounis' answer: https://stackoverflow.com/a/55216309\ndef largest_max_count_comprehension(values):\n if not values:\n return []\n maximum = max(values)\n return [maximum for _ in range(values.count(maximum))]\n\n\n# Derived from Daweo's answer: https://stackoverflow.com/a/55216401\ndef largest_max_comprehension(values):\n if not values:\n return []\n return [value for value in values if value == max(values)]\n\n\n# Derived from Daweo's answer: https://stackoverflow.com/a/55216401\ndef largest_max_comprehension_once(values):\n if not values:\n return []\n maximum = max(values)\n return [value for value in values if value == maximum]\n\n\n# Grijesh Chauhan's answer: https://stackoverflow.com/a/55254044\ndef largest_grijesh_chauhan(iterable):\n max = None\n count = 0\n for index, value in enumerate(iterable):\n if index == 0 or value &gt;= max:\n if value != max:\n count = 0\n max = value\n count += 1\n return count * [max]\n\n\ndef main():\n fig, axs = plt.subplots()\n axs.set_yscale('log')\n axs.set_xscale('log')\n (\n Plotter(MultiTimer([\n largest_orig,\n largest_orig_pretty,\n largest_no_max,\n largest_no_max_iter,\n largest_counter,\n largest_sort,\n largest_sort_semifunctional,\n largest_sort_functional,\n largest_sorted,\n largest_max_count,\n ]))\n .repeat(10, 10, np.logspace(0, 5), args_conv=lambda n: list(np.random.rand(int(n))))\n .min()\n .plot(axs, title='Maximums')\n )\n fig.show()\n\n fig, axs = plt.subplots()\n axs.set_yscale('log')\n axs.set_xscale('log')\n (\n Plotter(MultiTimer([\n largest_orig_pretty,\n largest_sort,\n largest_max_count,\n largest_max_count_comprehension,\n largest_max_comprehension,\n largest_max_comprehension_once,\n largest_grijesh_chauhan,\n ]))\n .repeat(10, 10, np.logspace(0, 3), args_conv=lambda n: list(np.random.rand(int(n))))\n .min()\n .plot(axs, title='Maximums max count derived')\n )\n fig.show()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>Resulting in the following timings:</p>\n\n<p><a href=\"https://i.stack.imgur.com/qoKQA.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/qoKQA.png\" alt=\"Timings of the functions\"></a></p>\n\n<p>The following is a comparison of the SO answers:</p>\n\n<p><a href=\"https://i.stack.imgur.com/JKJlR.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/JKJlR.png\" alt=\"Comparison of SO answers\"></a></p>\n\n<h1>Conclusion</h1>\n\n<ul>\n<li><p>[Performance] <code>sort</code> is the fastest method when there are ~10 or more elements in the list. Despite the <span class=\"math-container\">\\$O(n\\log{n})\\$</span> big-O time complexity it's the fastest as it's written in C.</p>\n\n<p>It mutates the input which may not be desirable, and using <code>sorted</code> destroys the performance gain.</p>\n\n<p>Using a plain <code>for</code> loop is faster than <code>itertools</code>.</p></li>\n<li>[Performance] Using <code>max</code> and <code>list.count</code> is the fastest method if you are not allowed to mutate the list.</li>\n<li>[Size] Using <code>max</code> and <code>list.count</code> results in the smallest amount of lines of code.</li>\n</ul>\n\n<p>And so depending on your need I'd use either <code>largest_max_count</code> or <code>largest_sort</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T04:27:08.440", "Id": "424683", "Score": "1", "body": "Hmm, my answer flying up with input size. Indeed, Cookbook says \"The `nlargest()` and `nsmallest()` functions are most appropriate if you are trying to find a relatively small number of items. *If you are simply trying to find the single smallest or largest item (N=1), it is faster to use `min()` and `max()`* Similarly, if N is about the same size as the collection itself, it is usually faster to sort it first and take a slice (i.e., use `sorted(items)[: N]` or `sorted(items)[-N:]`\" ... Thanks for the simulation" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T12:26:51.337", "Id": "424746", "Score": "1", "body": "@GrijeshChauhan In case you have misread the graph, your function isn't the worst, but the second worst in the \"Maximums SO comparison\". For the most part it shouldn't matter what you use, unless you pick Daweo's answer which calls `max` every iteration." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T19:27:15.007", "Id": "219826", "ParentId": "219818", "Score": "9" } } ]
{ "AcceptedAnswerId": "219826", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T16:56:11.317", "Id": "219818", "Score": "5", "Tags": [ "python", "performance", "array" ], "Title": "Program to output the same highest numbers in an array" }
219818
<p>Summary: Given a string find the number of anagramic pairs of substrings of it. e.g 'abba' pairs are [a,a],[b,b],[ab,ba],[abb,bba] so we have 4 pairs.</p> <p>I'm wondering if anyone can help me improve my code so that it runs faster. My code passes all test cases when running locally, but times out on hackerrank. Any ideas ?</p> <pre><code>module.exports = (s = '') =&gt; { let count = 0 let pairs = [] for (let wordSize = 1; wordSize &lt; s.length; wordSize++) { for (let wordPosition = 0; wordPosition &lt; s.length; wordPosition++) { const letters = s.substr(wordPosition, wordSize) const wordKeys = letters.split(''); pairs.push({ letters, keys: wordKeys, wordPosition }) } } let pairIndexes = {} for (let i = 0; i &lt; pairs.length; i++) { const word = pairs[i] pairs.forEach((value, index) =&gt; { if (word.wordPosition !== value.wordPosition &amp;&amp; index !== i &amp;&amp; value.keys.length === word.keys.length) { const wordSorted = word.keys.sort().join('') const valueSorted = value.keys.sort().join('') if (wordSorted !== valueSorted) return if (pairIndexes[wordSorted] === undefined) pairIndexes[wordSorted] = {} const pairKeyWord = `${word.wordPosition}-${value.wordPosition}` const pairValueWord = `${value.wordPosition}-${word.wordPosition}` if (pairIndexes[wordSorted][pairValueWord] === pairKeyWord) return pairIndexes[wordSorted][pairKeyWord] = pairValueWord } }) } //console.log(pairs) //console.log(pairIndexes) for (const key in pairIndexes) { if (pairIndexes.hasOwnProperty(key)) { const pairs = pairIndexes[key]; count += Object.keys(pairs).length } } return count } </code></pre> <p>Test cases:</p> <pre><code>test('A - Given a string return pairs of anagrams', () =&gt; { const s = 'mom' const expected = 2 const result = anagrams(s) expect(result).toBe(expected) }) test('B - Given a string return pairs of anagrams', () =&gt; { const s = 'abba' const expected = 4 const result = anagrams(s) expect(result).toBe(expected) }) test('C - Given a string return pairs of anagrams', () =&gt; { const s = 'abcd' const expected = 0 const result = anagrams(s) expect(result).toBe(expected) }) test('D - Given a string return pairs of anagrams', () =&gt; { const s = 'ifailuhkqq' const expected = 3 const result = anagrams(s) expect(result).toBe(expected) }) test('E - Given a string return pairs of anagrams', () =&gt; { const s = 'kkkk' const expected = 10 const result = anagrams(s) expect(result).toBe(expected) }) test('F - Given a string return pairs of anagrams', () =&gt; { const s = 'cdcd' // c,c d,d cd,cd, cd,dc dc,cd const expected = 5 const result = anagrams(s) expect(result).toBe(expected) }) test('G - Given a string return pairs of anagrams', () =&gt; { const s = 'ifailuhkqqhucpoltgtyovarjsnrbfpvmupwjjjfiwwhrlkpekxxnebfrwibylcvkfealgonjkzwlyfhhkefuvgndgdnbelgruel' const expected = 399 const result = anagrams(s) expect(result).toBe(expected) }) test('H - Given a string return pairs of anagrams', () =&gt; { const s = 'gffryqktmwocejbxfidpjfgrrkpowoxwggxaknmltjcpazgtnakcfcogzatyskqjyorcftwxjrtgayvllutrjxpbzggjxbmxpnde' const expected = 471 const result = anagrams(s) expect(result).toBe(expected) }) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T17:39:18.820", "Id": "424634", "Score": "0", "body": "@200_success sorry !" } ]
[ { "body": "<p>Your code does indeed run forever. Regrettably you don't describe the method you're using, so I will have to get that from your code.</p>\n\n<ol>\n<li>You start by getting all possible substring, of all possible sizes, out of the given input string and you store those substrings, its letters and position in an array.</li>\n<li>You do a <strong>full matrix</strong> comparison of each array entry. You test if something is an anagram or not. If it is you store it in a second array.</li>\n<li>You count what you stored in the second array.</li>\n</ol>\n\n<p>Somewhere along the way you lost me there. Why all the complexity? You started out well, by getting all possible substrings, but after that it became somewhat messy. A <strong>full matrix</strong> comparison is certainly not needed. I'll explain.</p>\n\n<p>What are we trying to accomplish here? Let's analyse the problem, taking the simply case of <code>'abba'</code>. The possible substrings are <code>'a','b','b','a'</code>, <code>'ab','bb','ba'</code> and <code>'abb','bba'</code>. nine in total, let's number them 1 to 9. </p>\n\n<p>A full matrix comparison would make 9 x 9 = 81 comparisons. But it is obvious that this would compare the same substrings twice. Comparing 2 to 5 is the same as comparing 5 to 2. So we can leave out at least half of these comparisons, cutting the time we need to do this in half. We also don't need to compare two strings of unequal length, so we won't. </p>\n\n<p>So, in the case of <code>'abba'</code> we have 3 sets we need to compare. For the 1 character set we have to do 6 comparisons, for the 2 character set 3, and for 3 character set 1. That's a total of 10 comparisons where you did 81. This number gets proportionally lower when the size of the input string increases. It is here where we can gain most of our speed.</p>\n\n<p>Finally we get to the comparison itself. Suppose we want to compare <code>'ab'</code> to <code>'ba'</code>. By sorting the characters in both strings we can simply compare them. If they are equal that the strings must be an anagram, and must be counted. This is what you do as well.</p>\n\n<p>So now we know what we will need: We need all possible sorted substrings and perform only the needed comparisons.</p>\n\n<p>In basic Javascript code that would look like this:</p>\n\n<pre><code>function sherlockAndAnagrams(s) {\n var anagrams = 0;\n for (var len = 1; len &lt; s.length; len++) {\n var parts = [];\n for (var pos = 0; pos &lt;= s.length - len; pos++) {\n var part = s.substr(pos, len);\n parts.push(part.split('').sort().join(''));\n }\n for (var index1 = 0; index1 &lt; parts.length; index1++) {\n var part1 = parts[index1];\n for (var index2 = index1 + 1; index2 &lt; parts.length; index2++) {\n var part2 = parts[index2];\n if (part1 == part2) anagrams++;\n }\n }\n }\n return anagrams;\n}\n</code></pre>\n\n<p>Notice how the outer loop goes through all the possible lengths of the substring. By working with one length of string, each time, I will never have to compare two differently sized strings.</p>\n\n<p>The way I build the initial array with substrings looks very similar to what you have, but I only store the sorted substrings. That's all that is needed. By sorting the characters in the substring at this stage I save time.</p>\n\n<p>The comparison of the substrings of one length is now quite simple. Notice how <code>index2</code> starts at <code>index1 + 1</code>, preventing a full matrix comparison of the subset.</p>\n\n<p>And that's it.</p>\n\n<p>So, the major lesson here is to try to reduce the number of comparisons you have to make by <strong>first</strong> carefully analysing the problem. For an input string of 4 characters you did 81 comparisons, I do 10 (12%). If the input is 16 characters long this goes to 18,225 and 680 (4%), 32 characters gives 277,729 and 5,456 (2%). You can see where that is going. Almost all these coding challenges, for which basic solutions run too long, require such a careful analysis. They don't require fancy programming.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T23:59:58.863", "Id": "219833", "ParentId": "219820", "Score": "3" } }, { "body": "<h2>Check each unique sub string once</h2>\n\n<p>I agree with the existing answer, however there is a faster way to solve the problem, there is also an early exit possible that many of the challenges will test for.</p>\n\n<p>The early exit can be found by finding out if there are any two characters that are the same. If not then there are no anagrams that are longer than 1 character an thus you can exit with a result of 0</p>\n\n<p>Using a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map\" rel=\"nofollow noreferrer\">Map</a> you can count unique anagrams as you go. Each time you find an existing anagram you add to the total count the number of that anagram already found, then add one to that anagram.</p>\n\n<p>The solution complexity is set by the number of characters in the input string (ignoring the early exit) and not related to the string length and number of anagrams as your function does</p>\n\n<p>For a 28 character string the solution can be found in 405 iterations compared to your ~550,000 or ~4,059 for the existing answer.</p>\n\n<pre><code>function anagramCounts(str) {\n const found = new Map();\n var i,end, subLen = 1, count = 0, counts;\n while (subLen &lt; str.length) {\n end = (i = 0) + subLen++;\n while (end &lt;= str.length) {\n const sorted = [... str.substring(i++, end++)].sort().join(\"\"); \n if (!found.has(sorted)) { found.set(sorted, [1]) }\n else { count += (counts = found.get(sorted))[0]++ }\n }\n }\n return count;\n}\n</code></pre>\n\n<h2>Some additional optimizations</h2>\n\n<p>The sort is also a where complexity grows. Because you need to pass over whole string once to find single characters you could also optimize the sort as you will know the relative order of each character to its neighbors after the first pass.</p>\n\n<p>After the first pass you will know which characters will not be part of longer anagrams (those that appear only once).</p>\n\n<p>You can replace all single instance characters with a symbol after the first pass. Then replace any sequence of 2 or more symbols with a single symbol. This reduces the total string length that needs to be tested in further passes, and also provides a way to avoid sorting a sub string if it contains the symbol.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T11:18:47.457", "Id": "424736", "Score": "0", "body": "Yes, this is certainly fancier than my answer. I like the idea of using map storage for counting. You get my upvote for that. However, in the end, I cannot measure a real improvement in speed. That surprised me. I used Firefox, a 60 chrs string, and `performance.now();`. Your solution should be faster because it clearly uses less iterations, but it doesn't seem to be. Perhaps because my iterations are so simple? Oh, wait, in Chrome your solution is about twice as fast, but that's basically because Chrome is quite a bit slower for my solution. Clearly Firefox is more optimized." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T14:19:03.843", "Id": "424766", "Score": "0", "body": "@KIKOSoftware I think you will find that it is how I split the string `[...str]` is much slower than `str.split()` due to behavioral differences. For ASCII `str.split` can be used and will give a big improvement in performance (maybe 3 times as fast), For unicode then the safer method is via the string iterator `[...str]`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T15:05:11.170", "Id": "424770", "Score": "0", "body": "Tested that, and I found no significant differences. I didn't try different encodings (standard HTML5 page)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T16:44:24.503", "Id": "424785", "Score": "0", "body": "@Blindman67. I'm afraid your second code did not pass the tests. The first is ok." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T19:41:42.950", "Id": "424815", "Score": "0", "body": "@ThiagoCaramelo thanks for the feedback. I am unsure why the second failed, I will remove it from the answer." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T09:50:09.587", "Id": "219858", "ParentId": "219820", "Score": "2" } } ]
{ "AcceptedAnswerId": "219858", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T17:10:03.160", "Id": "219820", "Score": "5", "Tags": [ "javascript", "algorithm", "programming-challenge", "time-limit-exceeded", "node.js" ], "Title": "Hackerrank.com - Sherlock and Anagrams" }
219820
<p>I have this Java implementation of a Rubik's cube's state. My primary concern is DRYness of my code:</p> <p><strong><code>RubiksCubeNode.java</code></strong></p> <pre><code>package net.coderodde.libid; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * * @author Rodion "rodde" Efremov * @version 1.6 (May 4, 2019) */ public final class RubiksCubeNode { public enum Axis { X, Y, Z } public enum Direction { CLOCKWISE, COUNTER_CLOCKWISE } public enum Layer { LAYER_1(0), LAYER_2(1), LAYER_3(2); private final int layerNumber; private Layer(int layerNumber) { this.layerNumber = layerNumber; } public int toInteger() { return layerNumber; } } private final int[][][] data; private Set&lt;RubiksCubeNode&gt; neighbors; public RubiksCubeNode() { data = new int[3][3][3]; for (int x = 0, value = 0; x &lt; 3; x++) { for (int y = 0; y &lt; 3; y++) { for (int z = 0; z &lt; 3; z++) { data[x][y][z] = value++; } } } } public RubiksCubeNode(RubiksCubeNode other) { this.data = new int[3][3][3]; for (int x = 0; x &lt; 3; x++) { for (int y = 0; y &lt; 3; y++) { for (int z = 0; z &lt; 3; z++) { data[x][y][z] = other.data[x][y][z]; } } } } public RubiksCubeNode rotate(Axis axis, Layer layer, Direction direction) { RubiksCubeNode nextNode = new RubiksCubeNode(this); switch (axis) { case X: rotateAroundXAxis(nextNode, direction, layer.toInteger()); break; case Y: rotateAroundYAxis(nextNode, direction, layer.toInteger()); break; case Z: rotateAroundZAxis(nextNode, direction, layer.toInteger()); break; default: throw new IllegalArgumentException("Unknown axis enum."); } return nextNode; } public Set&lt;RubiksCubeNode&gt; computeNeighbors() { if (neighbors != null) { return neighbors; } neighbors = new HashSet&lt;&gt;(18); for (Layer layer : Layer.values()) { for (Axis axis : Axis.values()) { for (Direction direction : Direction.values()) { neighbors.add(rotate(axis, layer, direction)); } } } return neighbors; } @Override public boolean equals(Object o) { if (o == null) { return false; } if (o == this) { return true; } if (!o.getClass().equals(this.getClass())) { return false; } RubiksCubeNode other = (RubiksCubeNode) o; for (int x = 0; x &lt; 3; x++) { for (int y = 0; y &lt; 3; y++) { for (int z = 0; z &lt; 3; z++) { if (data[x][y][z] != other.data[x][y][z]) { return false; } } } } return true; } @Override public int hashCode() { int i = 1; int hash = 0; for (int x = 0; x &lt; 3; x++) { for (int y = 0; y &lt; 3; y++) { for (int z = 0; z &lt; 3; z++) { hash += data[x][y][z] * i++; } } } return hash; } private static void rotateAroundXAxis(RubiksCubeNode node, Direction direction, int xLayer) { switch (direction) { case CLOCKWISE: rotateAroundXAxisClockwise(node, xLayer); break; case COUNTER_CLOCKWISE: rotateAroundXAxisCounterClockwise(node, xLayer); break; } } private static void rotateAroundYAxis(RubiksCubeNode node, Direction direction, int yLayer) { switch (direction) { case CLOCKWISE: rotateAroundYAxisClockwise(node, yLayer); break; case COUNTER_CLOCKWISE: rotateAroundYAxisCounterClockwise(node, yLayer); break; } } private static void rotateAroundZAxis(RubiksCubeNode node, Direction direction, int zLayer) { switch (direction) { case CLOCKWISE: rotateAroundZAxisClockwise(node, zLayer); break; case COUNTER_CLOCKWISE: rotateAroundZAxisCounterClockwise(node, zLayer); break; } } private static void rotateAroundXAxisClockwise(RubiksCubeNode node, int xLayer) { int[][][] data = node.data; int saveValue1 = data[xLayer][0][0]; int saveValue2 = data[xLayer][1][0]; data[xLayer][1][0] = data[xLayer][0][1]; data[xLayer][0][0] = data[xLayer][0][2]; data[xLayer][0][1] = data[xLayer][1][2]; data[xLayer][0][2] = data[xLayer][2][2]; data[xLayer][1][2] = data[xLayer][2][1]; data[xLayer][2][2] = data[xLayer][2][0]; data[xLayer][2][1] = saveValue2; data[xLayer][2][0] = saveValue1; } private static void rotateAroundXAxisCounterClockwise(RubiksCubeNode node, int xLayer) { int[][][] data = node.data; int saveValue1 = data[xLayer][0][0]; int saveValue2 = data[xLayer][1][0]; data[xLayer][0][0] = data[xLayer][2][0]; data[xLayer][1][0] = data[xLayer][2][1]; data[xLayer][2][0] = data[xLayer][2][2]; data[xLayer][2][1] = data[xLayer][1][2]; data[xLayer][2][2] = data[xLayer][0][2]; data[xLayer][1][2] = data[xLayer][2][1]; data[xLayer][0][2] = saveValue1; data[xLayer][0][1] = saveValue2; } private static void rotateAroundYAxisClockwise(RubiksCubeNode node, int yLayer) { int[][][] data = node.data; int saveValue1 = data[0][yLayer][0]; int saveValue2 = data[0][yLayer][1]; data[0][yLayer][1] = data[1][yLayer][0]; data[0][yLayer][0] = data[2][yLayer][0]; data[1][yLayer][0] = data[2][yLayer][1]; data[2][yLayer][0] = data[2][yLayer][2]; data[2][yLayer][1] = data[1][yLayer][2]; data[2][yLayer][2] = data[0][yLayer][2]; data[1][yLayer][2] = saveValue2; data[0][yLayer][2] = saveValue1; } private static void rotateAroundYAxisCounterClockwise(RubiksCubeNode node, int yLayer) { int[][][] data = node.data; int saveValue1 = data[0][yLayer][0]; int saveValue2 = data[0][yLayer][1]; data[0][yLayer][0] = data[0][yLayer][2]; data[0][yLayer][1] = data[1][yLayer][2]; data[0][yLayer][2] = data[2][yLayer][2]; data[1][yLayer][2] = data[2][yLayer][1]; data[2][yLayer][2] = data[2][yLayer][0]; data[2][yLayer][1] = data[1][yLayer][0]; data[2][yLayer][0] = saveValue1; data[1][yLayer][0] = saveValue2; } private static void rotateAroundZAxisClockwise(RubiksCubeNode node, int zLayer) { int[][][] data = node.data; int saveValue1 = data[0][0][zLayer]; int saveValue2 = data[0][1][zLayer]; data[0][1][zLayer] = data[1][0][zLayer]; data[0][0][zLayer] = data[2][0][zLayer]; data[1][0][zLayer] = data[2][1][zLayer]; data[2][0][zLayer] = data[2][2][zLayer]; data[2][1][zLayer] = data[1][2][zLayer]; data[2][2][zLayer] = data[0][2][zLayer]; data[1][2][zLayer] = saveValue2; data[0][2][zLayer] = saveValue1; } private static void rotateAroundZAxisCounterClockwise(RubiksCubeNode node, int zLayer) { int[][][] data = node.data; int saveValue1 = data[0][0][zLayer]; int saveValue2 = data[0][1][zLayer]; data[0][0][zLayer] = data[0][2][zLayer]; data[0][1][zLayer] = data[1][2][zLayer]; data[0][2][zLayer] = data[2][2][zLayer]; data[1][2][zLayer] = data[2][1][zLayer]; data[2][2][zLayer] = data[2][0][zLayer]; data[2][1][zLayer] = data[1][0][zLayer]; data[2][0][zLayer] = saveValue1; data[1][0][zLayer] = saveValue2; } } </code></pre> <p><strong><code>RubiksCubeNodeTest</code></strong></p> <pre><code>package net.coderodde.libid; import junit.framework.TestCase; import static org.junit.Assert.assertNotEquals; import org.junit.Test; /** * Tests the {@link RubiksCubeNode}. * * @author Rodion "rodde" Efremov * @version 1.6 (May 6, 2019) */ public class RubiksCubeNodeTest extends TestCase { @Test public void testRotation1() { RubiksCubeNode node = new RubiksCubeNode(); node = node.rotate(RubiksCubeNode.Axis.X, RubiksCubeNode.Layer.LAYER_1, RubiksCubeNode.Direction.CLOCKWISE); node = node.rotate(RubiksCubeNode.Axis.Z, RubiksCubeNode.Layer.LAYER_2, RubiksCubeNode.Direction.COUNTER_CLOCKWISE); RubiksCubeNode another = new RubiksCubeNode(node); assertEquals(node, another); assertEquals(another, node); assertEquals(node.hashCode(), another.hashCode()); RubiksCubeNode third = new RubiksCubeNode(node); third = third.rotate(RubiksCubeNode.Axis.Y, RubiksCubeNode.Layer.LAYER_3, RubiksCubeNode.Direction.CLOCKWISE); assertNotEquals(third, node); assertNotEquals(third, another); assertNotEquals(node.hashCode(), third.hashCode()); } } </code></pre> <p>(The idea for the class <code>RubiksCubeNode</code> is that the configurations comprise an undirected, unweighted graph. We put an edge between any two configurations if they are one rotation away from each other.)</p> <p>For demonstration, consider forking <a href="https://github.com/coderodde/LibID/tree/78a55aa36ba56ad57e5754f2eadb8f1d69761b83" rel="nofollow noreferrer">this GitHub repository</a>.</p> <p>Typical output looks like this:</p> <pre><code> Bidirectional BFS path (57684 ms): net.coderodde.libid.RubiksCubeNode@1266 net.coderodde.libid.RubiksCubeNode@1112 net.coderodde.libid.RubiksCubeNode@12da net.coderodde.libid.RubiksCubeNode@12cc net.coderodde.libid.RubiksCubeNode@1488 net.coderodde.libid.RubiksCubeNode@17ac net.coderodde.libid.RubiksCubeNode@1998 BIDDFS path (644 ms): net.coderodde.libid.RubiksCubeNode@1266 net.coderodde.libid.RubiksCubeNode@1112 net.coderodde.libid.RubiksCubeNode@12da net.coderodde.libid.RubiksCubeNode@12cc net.coderodde.libid.RubiksCubeNode@1488 net.coderodde.libid.RubiksCubeNode@17ac net.coderodde.libid.RubiksCubeNode@1998 Algorithms returns correct paths: true</code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-09T08:22:58.077", "Id": "425015", "Score": "1", "body": "i hope i don't step into the same pitfall as last time - but why do you use `int[][][]` instead of proper `Data[][][]`? is it that **'competive style'** thing again? even then, you could name it better. maybe `int[][][] colorSet` instead of `int[][][] data`? - i know it doesn't concern DRY, so it's just a comment ^_^ - happy coding!!" } ]
[ { "body": "<p>I have two comments:</p>\n\n<ol>\n<li><p>regarding DRYness: this is how I would do it: I see that rotation involves assigning values to 8 cells in the 3d array. I would have <code>rotate()</code> calculate the source and target indices of the rotation based on args. then the actual assignment can be performed in one place. now, when you put all index-calculations in one place, you start noticing recurring patterns in all the various rotations so you can further reduce code duplication</p></li>\n<li><p>there are two problems with the overall design: first, I don't like the static rotation methods. I mean, it seems right to me that a cube class should be able to rotate itself. this relates to the 2nd point - IIUC, the <code>RubiksCubeNode</code> is intended to be node in graph. but it is also a <code>RubiksCube</code> that does all the cube's operations. this violates the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">single responsibility principle</a>. a <code>GraphNode</code> is the buliding block of the graph and I would expect it to perform graph related operations, like traversal etc. the data of the <code>GraphNode</code> is an instance of <code>RubiKCube</code> that holds a snapshot of the cube and can perform cube related operations</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T12:44:29.443", "Id": "219865", "ParentId": "219822", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T17:41:11.927", "Id": "219822", "Score": "3", "Tags": [ "java", "algorithm", "breadth-first-search" ], "Title": "Rubik's Cube in Java" }
219822
<p>I write decently sloppy code and piecemeal together various things I find online to help me accomplish what needs to be done. This loop goes through 4 different worksheets to paste a formula in 3 columns. Based on some previous feedback from the site, I removed all of my <code>.Select</code> references and hopefully did things more cleanly. 2 questions that I have:</p> <p>1) Can anyone think of a way I can further optimize this to have it run more quickly?</p> <p>2) Is there a better way to define my RRSData!A2:O10000 formula. I just chose 10,000 because there shouldn't be that many in the future, but its obviously working harder than it needs to now since there are only ~1000 rows currently. </p> <pre><code>Dim LastRow1 As Long, i1 As Long, InxW As Long Dim wsNames As Variant wsNames = Array("Sheet1", "Sheet2", "Sheet3", "Sheet4") For InxW = LBound(wsNames) To UBound(wsNames) With Worksheets(wsNames(InxW)) LastRow = Cells(Rows.Count, "B").End(xlUp).Row For i1 = 25 To LastRow With Range("KA1").Offset(i1 - 1, 0) .Formula = "=IF(SUMIF(RRSData!$A$2:$O$10000,OFFSET($KA$1,CELL(""row"",THIS),-285),RRSData!$M$2:$M$10000)&gt;0,SUMIF(RRSData!$A$2:$O$10000,OFFSET($KA$1,CELL(""row"",THIS),-285),RRSData!$M$2:$M$10000),"""")" .NumberFormat = "0.00" .Value = .Value End With With Range("KB1").Offset(i1 - 1, 0) .FormulaR1C1 = "=IF(RC[-1]="""","""",If(RC[-1]&gt;1.1,""High"",If(RC[-1]&lt;0.8,""Low"",""Neutral"")))" .Value = .Value End With With Range("KC1").Offset(i1 - 1, 0) .FormulaR1C1 = "=IF(RC[-2]="""","""",IF(RC[-2]&gt;1.1,""+5%"",IF(RC[-2]&lt;0.8,""-5%"",""0%"")))" .Value = .Value End With Next i1 End With Next InxW </code></pre> <p>The code works, but it takes probably 2 minutes to loop through the four sheets, and the total number of rows across the four sheets is &lt;500</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T20:08:11.723", "Id": "424649", "Score": "1", "body": "What is the aim of your code? Your title doesn't state that. In the body of your text you can state that looping is slow and with a descriptive title we'd have a better idea of what you're doing and how to best help. https://codereview.meta.stackexchange.com/questions/2436/how-to-get-the-best-value-out-of-code-review-asking-questions/2437#2437 is one of the links available in the top right when you click the `Ask Question` button. With more information we can give you a better and more thorough review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T21:15:50.523", "Id": "424654", "Score": "0", "body": "@IvenBach Thanks for the tip, I have updated the title to be more descriptive." } ]
[ { "body": "<p>A couple of tips.</p>\n\n<p>When using <code>With</code>, make sure that you correctly reference the subordinate lines. Check the following example.</p>\n\n<pre><code>With Range(\"KA1\").Offset(i1 - 1, 0) '&lt;--- You have ...\nWith .Range(\"KA1\").Offset(i1 - 1, 0) ' ... should be\n</code></pre>\n\n<p>Consider using <code>FillDown</code> or some similar command to do bulk edits. This will save looping, especially the loop that flips between the VBA engine and the Excel engine (which is expensive time-wise). Normally I suggest using arrays, but your use of formula suggests this other way.</p>\n\n<p>The following example has not been tested. </p>\n\n<pre><code>Dim formulaOneRange as Range\n Set formulaOneRange = .Range(\"KA25:KA\" &amp; lastRow)\n With formulaOneRange\n .Formula = \"=IF(SUMIF(RRSData!$A$2:$O$10000,OFFSET($KA$1,CELL(\"\"row\"\",THIS),-285),RRSData!$M$2:$M$10000)&gt;0,SUMIF(RRSData!$A$2:$O$10000,OFFSET($KA$1,CELL(\"\"row\"\",THIS),-285),RRSData!$M$2:$M$10000),\"\"\"\")\"\n .NumberFormat = \"0.00\"\n .Value = .Value\n End With\n Set formulaOneRange = .Range(\"KB25:KB\" &amp; lastRow)\n With formulaOneRange\n .FormulaR1C1 = \"=IF(RC[-1]=\"\"\"\",\"\"\"\",If(RC[-1]&gt;1.1,\"\"High\"\",If(RC[-1]&lt;0.8,\"\"Low\"\",\"\"Neutral\"\")))\"\n .Value = .Value\n End With\n Set formulaOneRange = .Range(\"KC25:KC\" &amp; lastRow)\n With formulaOneRange\n .FormulaR1C1 = \"=IF(RC[-1]=\"\"\"\",\"\"\"\",If(RC[-1]&gt;1.1,\"\"High\"\",If(RC[-1]&lt;0.8,\"\"Low\"\",\"\"Neutral\"\")))\"\n .Value = .Value\n End With\n</code></pre>\n\n<p>Of course, the code could be tidies up a bit as per below, but I thought the extra lines will show my thinking a bit more clearly.</p>\n\n<pre><code>' My example code above ... \nSet formulaOneRange = .Range(\"KC25:KC\" &amp; lastRow)\nWith formulaOneRange\n\n' Could be ....\nWith .Range(\"KC25:KC\" &amp; lastRow)\n</code></pre>\n\n<p>Also, defining the range in an easy to manage variable would assist if you wanted to use <code>FillDown</code> or do some other manipulation within each section.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T06:33:00.920", "Id": "219847", "ParentId": "219827", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T19:40:22.973", "Id": "219827", "Score": "0", "Tags": [ "vba", "excel" ], "Title": "VBA Loop through multiple sheets to output formulas in multiple columns" }
219827
<p>I have finished a simple Tic Tac Toe game, and I'd like if anyone was to give advice to how I could improve my code.</p> <p><strong>main.cpp</strong></p> <pre><code>#ifndef UNICODE #define UNICODE #endif #include "gameInfo.h" int main() { // Gets the screen buffer size (for somewhat of compatability) CONSOLE_SCREEN_BUFFER_INFO csbi; GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &amp;csbi); // Run the game gameInfo game(csbi.dwSize); game.start(); } </code></pre> <p><strong>gameInfo.h</strong></p> <pre><code>#pragma once #include &lt;string&gt; #include &lt;Windows.h&gt; class gameInfo { public: gameInfo(COORD size); ~gameInfo(); void start(); private: // MEMBER VARIABLES // Defines the active player const enum playerID { P1 = 0, P2 }; // Defines the state of game over screen const enum gameOverState { PLAYING = -1, WIN, LOSE, STALEMATE }; // Define sizes for screen buffer and board const COORD bufSize; const COORD boardSize; // Array whose elements are outputted in destructor const std::wstring GOArray[3] = { L"P1 wins!", L"P1 loses!", L"Stalemate!" }; // Different member variables gameOverState GOState; COORD mouseCoords; std::wstring screenbuf; playerID activePlayer; HANDLE gameHandle; bool bGameOver; // GAME FUNCTIONS // Clears screen buffer void clrscr(); /* draws map: | | ----- | | ----- | | is how it should look */ void drawMap(); // Moves the cursor void movecursor(char input); // Draws the symbol in the correct cell void drawSymbol(); // Checks the cell and returns a bool if true or false bool checkcell(COORD position) const; // Processes input void processinput(); // Updates screen void update() const; void drawInfo(); // Checks and sets the game over state void checkGameOverState(); }; </code></pre> <p><strong>gameInfo.cpp</strong></p> <pre><code>#include "gameInfo.h" #include &lt;iostream&gt; #include &lt;conio.h&gt; // Class constructor gameInfo::gameInfo(COORD size) : activePlayer(P1), bufSize(size), boardSize({ 5, 5 }), bGameOver(true), mouseCoords({ 0, 0 }), GOState(PLAYING) { int choice; std::wcout &lt;&lt; L"1: Play" &lt;&lt; std::endl; std::wcout &lt;&lt; L"2: Quit" &lt;&lt; std::endl; // Tests if input is correct if (std::cin &gt;&gt; choice &amp;&amp; (choice == 1 || choice == 2)) { if (choice == 1) bGameOver = false; } std::wstring temp(size.X * size.Y, L' '); screenbuf = temp; gameHandle = CreateConsoleScreenBuffer( GENERIC_READ | GENERIC_WRITE, 0, NULL, CONSOLE_TEXTMODE_BUFFER, NULL ); SetConsoleActiveScreenBuffer(gameHandle); } // Class destructor gameInfo::~gameInfo() { CloseHandle(gameHandle); for (int i = 0; i &lt; 10; ++i) std::wcout &lt;&lt; L"\n\n\n\n\n\n\n" &lt;&lt; std::endl; std::wcout &lt;&lt; L"Game over! " &lt;&lt; GOArray[GOState] &lt;&lt; std::endl; Sleep(2000); } // Clears the screen buffer void gameInfo::clrscr() { for (int i = 0; i &lt; bufSize.Y; ++i) { for (int j = 0; j &lt; bufSize.X; ++j) screenbuf[i * bufSize.X + j] = L' '; } } // Outputs the buffer to the console void gameInfo::update() const { DWORD dwBytesWritten = 0; WriteConsoleOutputCharacter( gameHandle, screenbuf.c_str(), bufSize.X * bufSize.Y, { 0, 0 }, &amp;dwBytesWritten ); } // Moves the cursor to the right cell void gameInfo::movecursor(char input) { switch (input) { case 'w': if (mouseCoords.Y - 1 &gt; -1) --mouseCoords.Y; break; case 'd': if (mouseCoords.X + 1 &lt; boardSize.X) ++mouseCoords.X; break; case 's': if (mouseCoords.Y + 1 &lt; boardSize.Y) ++mouseCoords.Y; break; case 'a': if (mouseCoords.X - 1 &gt; -1) --mouseCoords.X; } SetConsoleCursorPosition(gameHandle, mouseCoords); } // Draws the correct symbol void gameInfo::drawSymbol() { if (activePlayer == P1) { screenbuf[mouseCoords.Y * bufSize.X + mouseCoords.X] = L'x'; activePlayer = P2; } else { screenbuf[mouseCoords.Y * bufSize.X + mouseCoords.X] = L'o'; activePlayer = P1; } } // Checks if cell is clear bool gameInfo::checkcell(COORD position) const { if (screenbuf[position.Y * bufSize.X + position.X] == L' ') return true; return false; } // Handles input void gameInfo::processinput() { if (_kbhit()) { if (_getch() == 'x') { if (checkcell(mouseCoords)) drawSymbol(); } else movecursor(_getch()); } } void gameInfo::checkGameOverState() { for (int i = 0; i &lt; boardSize.Y; ++i) { int countx = 0; int counto = 0; for (int j = 0; j &lt; boardSize.X; ++j) { if (screenbuf[i * bufSize.X + j] == L'x') ++countx; else if (screenbuf[i * bufSize.X + j] == L'o') ++counto; } if (countx == 3) { GOState = WIN; bGameOver = true; } else if (counto == 3) { GOState = LOSE; bGameOver = true; } } for (int i = 0; i &lt; boardSize.Y; ++i) { int countx = 0; int counto = 0; for (int j = 0; j &lt; boardSize.X; ++j) { if (screenbuf[j * bufSize.X + i] == L'x') ++countx; else if (screenbuf[j * bufSize.X + i] == L'o') ++counto; } if (countx == 3) { GOState = WIN; bGameOver = true; } else if (counto == 3) { GOState = LOSE; bGameOver = true; } } // This monstrosity checks diagonally if ((screenbuf[0 * bufSize.X + 0] == L'x' &amp;&amp; screenbuf[2 * bufSize.X + 2] == L'x' &amp;&amp; screenbuf[4 * bufSize.X + 4] == L'x') || (screenbuf[0 * bufSize.X + 4] == L'x' &amp;&amp; screenbuf[2 * bufSize.X + 2] == L'x' &amp;&amp; screenbuf[4 * bufSize.X + 0] == L'x')) { GOState = WIN; bGameOver = true; } else if ((screenbuf[0 * bufSize.X + 0] == L'o' &amp;&amp; screenbuf[2 * bufSize.X + 2] == L'o' &amp;&amp; screenbuf[4 * bufSize.X + 4] == L'o') || (screenbuf[0 * bufSize.X + 4] == L'o' &amp;&amp; screenbuf[2 * bufSize.X + 2] == L'o' &amp;&amp; screenbuf[4 * bufSize.X + 0] == L'o')) { GOState = LOSE; bGameOver = true; } // Checks for stalemates int count = 0; for (int i = 0; i &lt; boardSize.Y; ++i) { for (int j = 0; j &lt; boardSize.X; ++j) if (screenbuf[i * bufSize.X + j] != L' ') ++count; } if (count == boardSize.X * boardSize.Y) { GOState = STALEMATE; bGameOver = true; } } void gameInfo::drawInfo() { std::wstring controls = L"Press 'w, a, s, d' to move the cursor. Press x to mark a cell"; for (int i = 0, n = controls.size(); i &lt; n; ++i) { screenbuf[6 * bufSize.X + i] = controls[i]; } } // Draws the map in the buffer void gameInfo::drawMap() { for (int i = 0; i &lt; boardSize.Y; ++i) { for (int j = 0; j &lt; boardSize.X; ++j) { // Draws the right character for each position if (i % 2 != 0) screenbuf[i * bufSize.X + j] = L'-'; else if (j % 2 != 0) screenbuf[i * bufSize.X + j] = L'|'; else screenbuf[i * bufSize.X + j] = L' '; } } } // Starts the game and runs the game loop void gameInfo::start() { drawMap(); while (!bGameOver) { processinput(); drawInfo(); update(); checkGameOverState(); } clrscr(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T19:48:47.510", "Id": "424646", "Score": "0", "body": "I was able to run it on VS 2019, and i am on windows 10 x64, although it should be usable also on x86 machines" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T19:50:57.207", "Id": "424647", "Score": "1", "body": "Oh boy, don't use that ancient stuff: `#include <conio.h>`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T19:51:38.073", "Id": "424648", "Score": "0", "body": "It's the most reliable way i know to get input without interrupting the main thread, really.." } ]
[ { "body": "<p>First, congratulations for writing a complete program. It's certainly the best way to learn, and the most gratifying. But I would also say that it's only the beginning: it's time to look back at your code, at the creative process, and think about what you could do to make your code more maintainable, and easier to improve.</p>\n\n<p>I believe that your code should be more structured. If you look at it closely, you'll see that the screen buffer is way more than a screen buffer: it's a board representation that is also used to apply the game's rules. When you think of it, there's no obvious reason why a screen buffer should be the best tool to implement the game logic with; and when you speak of the monstrosity of the diagonal check, it probably means you have your doubts.</p>\n\n<p>Now if you divide your program into two components: one about the display and other interactions with the user, and one about the game logic itself, you can choose different representations for different uses, provided that you enable communication between both through a well established interface. </p>\n\n<p>So let's keep the screen buffer as a wide character string, but add a different board representation for the game logic part. You could make use of a mere integer to fit all necessary information: nine bits by player and one extra bit to indicate whose turn it is, so 19 bits. It's not about space though (although if you add AI to your game, you'll need to analyze a lot of boards to choose the next move), but about convenience:</p>\n\n<pre><code>constexpr std::array&lt;int, 8&gt; end_games = {\n //lines\n 0b111000000,\n 0b000111000,\n 0b000000111,\n //columns\n 0b100100100,\n 0b010010010,\n 0b001001001,\n //diagonals\n 0b100010001,\n 0b001010100,\n};\n\nconstexpr int stalemate = 0b111111111;\n\nbool check_end_game(int board) {\n return std::any_of(end_games.begin(), end_games.end(), [board](auto end_game) {\n return (end_game &amp; extract_current_player_board(board)) == end_game;\n });\n}\n\nbool check_stalemate(int board) {\n return (extract_first_player_board(board) | extract_second_player_board(board)) == stalemate; \n}\n</code></pre>\n\n<p>Of course, many other representations can be considered. But that's the point: if you separate your game into several components, communicating through a stable minimal interface, you can then modify each component independently, depending only on what is best for the task at hand, be it display or computations.</p>\n\n<p>Communication between both components can also take various forms. One of the most flexible way would be for the user interface part to communicate the intended move to the game logic part:</p>\n\n<pre><code>class Board {\npublic:\n bool intended_move(int row, int col);\n//...\n};\n</code></pre>\n\n<p>If the move is valid, the <code>Board</code> modifies the game data and returns <code>true</code>; on receiving <code>true</code>, the user interface modifies the screen buffer and refreshes the screen. If it isn't valid, it returns <code>false</code> and the user interface component acts accordingly, signaling the move isn't valid and requesting another.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T09:19:11.370", "Id": "219857", "ParentId": "219828", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T19:47:57.323", "Id": "219828", "Score": "6", "Tags": [ "c++", "console", "tic-tac-toe", "winapi" ], "Title": "Tic Tac Toe console game in C++ (w/graphic)" }
219828
<p>I am studying design patterns, I was wondering if my approach makes sense. I am trying to implement the strategy pattern. I think I have captured the essence which is </p> <ul> <li>Define a family of algorithms, </li> <li>encapsulate each one, </li> <li>and make them interchangeable, </li> </ul> <p>as shown in the example code below. </p> <p>Have I captured the intent, am I missing something from the example?</p> <pre><code>#include "stdafx.h" #include &lt;iostream&gt; #include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;string&gt; enum OperationType { Add = 1, Subtract, Multiply, Divide }; class Operation { public: Operation(int Value1, int Value2) : m_Value1(Value1), m_Value2(Value2) { } virtual int Calculate() = 0; private: int m_Result; int m_Value1; int m_Value2; }; class Addition : public Operation { public: Addition(int Value1, int Value2) : Operation(Value1,Value2), m_Value1(Value1), m_Value2(Value2) {} int Calculate() { m_Result = m_Value1 + m_Value2; return m_Result; } private: int m_Result; int m_Value1; int m_Value2; }; class Subtraction : public Operation { public: Subtraction(int Value1, int Value2) : Operation(Value1, Value2), m_Value1(Value1), m_Value2(Value2) {} int Calculate() { m_Result = m_Value1 - m_Value2; return m_Result; } private: int m_Result; int m_Value1; int m_Value2; }; class Multiplication : public Operation { public: Multiplication(int Value1, int Value2) : Operation(Value1, Value2), m_Value1(Value1), m_Value2(Value2) {} int Calculate() { m_Result = m_Value1 * m_Value2; return m_Result; } private: int m_Result; int m_Value1; int m_Value2; }; class Division : public Operation { public: Division(int Value1, int Value2) : Operation(Value1, Value2), m_Value1(Value1), m_Value2(Value2) {} int Calculate() { m_Result = m_Value1 / m_Value2; return m_Result; } private: int m_Result; int m_Value1; int m_Value2; }; class Test { public: Test() { m_Operation = NULL; } void SetOperation(int Value1, int Value2, int Operation) { switch (Operation) { case Add: { m_Operation = new Addition(Value1, Value2); } break; case Subtract: { m_Operation = new Subtraction(Value1, Value2); } break; case Multiply: { m_Operation = new Multiplication(Value1, Value2); } break; case Divide: { m_Operation = new Division(Value1, Value2); } break; } } int PerformOperation() { return m_Operation-&gt;Calculate(); } private: Operation *m_Operation; }; int main() { Test test; test.SetOperation(1, 2, OperationType::Add); std::cout &lt;&lt; test.PerformOperation() &lt;&lt; std::endl; test.SetOperation(2, 3, OperationType::Subtract); std::cout &lt;&lt; test.PerformOperation() &lt;&lt; std::endl; test.SetOperation(3, 4, OperationType::Multiply); std::cout &lt;&lt; test.PerformOperation() &lt;&lt; std::endl; test.SetOperation(40, 10, OperationType::Divide); std::cout &lt;&lt; test.PerformOperation() &lt;&lt; std::endl; int x; std::cin &gt;&gt; x; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T21:28:35.040", "Id": "424655", "Score": "2", "body": "Welcome to Code Review! Are you doing this for a special purpose or as a mere exercise to improve your coding skills? Either way, I hope you will get some great feedback." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T09:43:26.590", "Id": "424701", "Score": "1", "body": "In general: don't write code that may be a solution to something, then afterwards go looking for a problem that it solves. Over-engineering/meta programming is the biggest problem with the C++ language and \"design patterns\" is a common cause for it. Your program could have been written as `cout << 1 + 2 << endl;` and it is _very_ hard to write better code than that. So the question you need to ask yourself is why exactly you need abstraction layers here. Look for the problem to solve, not for the design pattern to use." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T09:52:23.460", "Id": "424702", "Score": "0", "body": "The background is i have written code. That is in production but is really difficult to maintain lots of copy paste. And new features are added. I have only recently started adding unit tests. In one of the answers it has been suggested to use lambdas that seems to be the preferred option." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T14:05:27.273", "Id": "424765", "Score": "0", "body": "I haven't coded C++ for a long time, but imo it looks good (not looking at memleaks etc.). Except the example is a bit weird. Think of this pattern to use it when i.e. to log in with email address, where you can use Gmail, Yahoo, Hotmail or whatever strategy. The input is email + password and are always the same. But the login process can be different, depending on the strategy." } ]
[ { "body": "<h1>Overkill</h1>\n\n<p>This program is using dynamite to crack nuts. Choosing one operation of four is a very simple problem, easily handled with an <code>enum</code> and a <code>switch</code>. Indeed, your program already contains those, so the strategy classes are just unnecessary complexity.</p>\n\n<p>I'm going to ignore that and review this program as just an exercise in using strategies. But if you were actually trying to solve a problem, this would be a horribly complex design.</p>\n\n<p>Unfortunately, this makes it hard to judge how well you're using strategies, because you aren't using them <em>for</em> anything. It's also hard to advise how to simplify the program, because <em>everything</em> is unnecessary complexity.</p>\n\n<h1>How to use strategies</h1>\n\n<p>The Design Patterns movement is not a good guide to how to structure programs. Most of the techniques it teaches are rather specialized, and strategies are one of those. They're a useful tool to know, but they're only one tool of many, and you won't use them regularly.</p>\n\n<p>When implementing strategies, you should <strong>prefer λ to custom classes</strong>. Fall back to classes only if λ isn't available or won't work — for example, if the strategy has more than one operation, or needs to be saved to a file.</p>\n\n<p>Using λ is also a better way to learn to use strategies. If you're comfortable with first-class functions, and use them without thinking they're a Fancy Design Pattern, then strategies look like an obvious (but clumsy) variation, so it will be easy to use them correctly.</p>\n\n<p>If you aren't already comfortable with λ and functional programming, that's <em>far</em> more important to learn than design patterns.</p>\n\n<h1>Repetition</h1>\n\n<p>Now for some actual code review.</p>\n\n<p>The three private members of <code>Operation</code> (<code>m_Result</code>, <code>m_Value1</code>, <code>m_Value2</code>) are unused. And they're private, so the subclasses can't use them either, and must redefine them! If they're part of <code>Operation</code>'s interface, they should be <code>public</code> or at least <code>protected</code>.</p>\n\n<h1>Unnecessary state</h1>\n\n<p>There's no reason for the strategies to store <code>m_Value1</code>, <code>m_Value2</code> or <code>m_Result</code>. <code>Calculate</code> can simply take them as arguments and return the result. The interface could be like this:</p>\n\n<pre><code>class Operation {\n virtual int Calculate(int a, int b) = 0;\n};\n</code></pre>\n\n<p>Similarly, <code>Test::SetOperation</code> modifies <code>this</code> for no good reason. Is this just to have an excuse to store an <code>Operation</code> somewhere? It could simply return an <code>Operation</code>, or it could perform the operation directly without storing it anywhere. Then there's no reason for <code>Test</code> to be a class at all. It could simply be a function.</p>\n\n<h1>C++</h1>\n\n<p>Don't make a habit of using <code>std::endl</code>: it flushes the stream, which is seldom what you want.</p>\n\n<p><code>Test</code> leaks its <code>Operation</code>s. This is harmless in a toy program, but you should habitually use <code>std::unique_ptr</code> for owned data, so you don't have leaks when they matter.</p>\n\n<h1>Superficial details</h1>\n\n<p>I see from <code>stdafx.h</code> that you're writing in Microsoft style, so I won't complain about the <code>m_</code> prefixes.</p>\n\n<p>There are a lot of unnecessary blank lines. I don't know if these are also a deliberate stylistic feature, but they're usually thought to make the program harder to read, because you can't see as much of it at once.</p>\n\n<p>I suppose the <code>std::cin &gt;&gt; x</code> at the end is a hack to make the program's window not disappear instantly? You shouldn't have to do this. If you're running the program from an IDE, it should have an option to fix this for you; if you run it from the command line, this problem should not arise.</p>\n\n<h1>A better strategy problem</h1>\n\n<p>If you'd like a better problem to practice using strategies, try implementing a game like <a href=\"https://en.wikipedia.org/wiki/Fairy_chess_piece\" rel=\"noreferrer\">fairy chess</a>, where there are a wide variety of pieces with unique moves. Don't make a subclass for each one; instead, the constructor should take a strategy (represented as a function) to generate the piece's possible moves. The usage might look like this (with functions that return move generators):</p>\n\n<pre><code>Piece camel(\"camel\", \"L\", Leaper(1, 3));\nPiece rook(\"rook\", \"R\", Rider(1, 0));\n</code></pre>\n\n<p>If that's too complicated or doesn't sound fun, try a simpler game with a variety of pieces or cards or actions, where each one takes a function (not a class) to calculate what it does.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T23:35:23.803", "Id": "219832", "ParentId": "219829", "Score": "13" } }, { "body": "<p>You are potentially missing at least three points:</p>\n\n<ul>\n<li><p>You implement division, but its return type is <code>int</code>. Thus, 1/2 will not be returned as 0.5, which is worth observing at least.</p></li>\n<li><p>You are leaking memory: you call <code>new</code> but never deallocate the memory.</p></li>\n<li><p>Your base class does not provide a virtual destructor, meaning derived classes will not be destructed properly.</p></li>\n</ul>\n\n<p>Some other points:</p>\n\n<ul>\n<li><p>Let me guess that you are compiling and running in a Windows environment. At the end of your main program, you don't have to explicitly <code>return 0</code>, and you might as well just do <code>std::cin.get();</code> instead of reading to an <code>int</code>. But even better, assuming you use Visual Studio, is to go to \"Properties > Linker > System\" page, and set \"SubSystem\" to \"Console\". This keeps the console window open after the program has finished.</p></li>\n<li><p>As mentioned in the other review(s), your example does a lot of unnecessary work. A simpler implementation using what the standard provides of your program could be as follows:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;functional&gt;\n\ntemplate &lt;typename Operation&gt;\nint perform_operation(int x, int y)\n{\n return Operation()(x, y);\n}\n\nint main()\n{\n std::cout &lt;&lt; perform_operation&lt;std::plus&lt;int&gt; &gt;(1, 2) &lt;&lt; \"\\n\";\n std::cout &lt;&lt; perform_operation&lt;std::minus&lt;int&gt; &gt;(2, 3) &lt;&lt; \"\\n\";\n std::cout &lt;&lt; perform_operation&lt;std::multiplies&lt;int&gt; &gt;(3, 4) &lt;&lt; \"\\n\";\n std::cout &lt;&lt; perform_operation&lt;std::divides&lt;int&gt; &gt;(40, 10) &lt;&lt; \"\\n\";\n}\n</code></pre>\n\n<p>This is the strategy pattern at work as well: every operation has a common interface, i.e., takes two parameters and returns one value. No need for dynamic memory allocations either.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T06:43:45.633", "Id": "219848", "ParentId": "219829", "Score": "9" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T20:53:28.417", "Id": "219829", "Score": "7", "Tags": [ "c++", "design-patterns" ], "Title": "Strategy pattern for four arithmetic operations" }
219829
<p>I am relatively new to programming and have been recommended to work through the many tasks in order, in order to better my skills. For some reason, <a href="https://projecteuler.net/problem=42" rel="nofollow noreferrer">problem 42</a> had me stumped for a while:</p> <blockquote> <p>The nth term of the sequence of triangle numbers is given by, <em>t</em><sub><em>n</em></sub> = ½<em>n</em>(<em>n</em>+1); so the first ten triangle numbers are:</p> <p>1, 3, 6, 10, 15, 21, 28, 36, 45, 55, …</p> <p>By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = <em>t</em><sub>10</sub>. If the word value is a triangle number then we shall call the word a triangle word.</p> <p>Using <a href="https://projecteuler.net/project/resources/p042_words.txt" rel="nofollow noreferrer">words.txt</a>, a 16K text file containing nearly two-thousand common English words, how many are triangle words?</p> </blockquote> <p>The following is my beginner-level code, and I was wondering whether any of you wonderful people would help me improve it and give me some tips for the future. In retrospect, I should have probably reused some code from <a href="https://projecteuler.net/problem=22" rel="nofollow noreferrer">problem 22</a> since they involve the same skills.</p> <pre><code>def calculate_total(word): alphabet = {'a':1, 'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,'l':12,'m':13,'n':14,'o':15,'p':16,'q':17,'r':18,'s':19,'t':20,'u':21,'v':22,'w':23,'x':24,'y':25,'z':26} total = 0 index = 1 while word[index] != '"': total += alphabet[word[index].lower()] index += 1 return total def gen_triangles(limit): triangles = [0, 1] index = 1 while triangles[index] &lt;= limit: triangles.append(((index ** 2) + index) // 2) index += 1 return sorted(list(set(triangles))) def binary_search(aList, itemToFind, first, last): if last &lt; first: #print(itemToFind + "not in list") return False else: midpoint = (first + last)//2 if aList[midpoint] &gt; itemToFind: return binarySearch(aList, itemToFind, first, midpoint - 1) else: if aList[midpoint] &lt; itemToFind: return binarySearch(aList, itemToFind, midpoint + 1, last) else: #print(str(itemToFind) + " Found at position: " + str(midpoint)) return True def solution(): myFile = open('Words.txt', 'r') wordsArray = myFile.read().split(',') for i in range(0, len(wordsArray)): wordsArray[i] = calculate_total(wordsArray[i]) triangles = gen_triangles(max(wordsArray)) wordTriangles = [] lengthTriangles = len(triangles) - 1 for i in range(0, len(wordsArray)): #print('i:', i, 'current index:', wordsArray[i]) if binarySearch(triangles, wordsArray[i], 0, lengthTriangles) == True: wordTriangles.append(wordsArray[i]) print(len(wordTriangles)) solution() </code></pre> <p>I have been teaching myself some computing theory and have seen that Python's built-in searching keyword <code>in</code> performs a linear search on the array so I decided to branch out and see if I can make my own binary search, which seemed to have worked :D</p> <p>What was a surprise to me was that this actually runs really quickly. To all of you guys, though, this is probably a huge mess, but hey, that's why I'm here!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T23:53:50.837", "Id": "424671", "Score": "0", "body": "I'm unsure why this has been downvoted. If someone has a reason I'd like to know. Welcome to programming, Python and Code Review. I hope you get some good reviews :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T00:01:49.330", "Id": "424673", "Score": "0", "body": "To add, are you running on Python 2 or 3? You can add a tag accordingly to help out reviewers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-08T00:14:19.697", "Id": "424835", "Score": "0", "body": "This question is asking to calculate square root of 2*triangle with binary formats." } ]
[ { "body": "<p>A Python solution can be much more succinct than what you wrote.</p>\n\n<ul>\n<li><strong>Reading the file:</strong> The file is a degenerate CSV file with double-quoted values. You can use the <a href=\"https://docs.python.org/3/library/csv.html\" rel=\"nofollow noreferrer\"><code>csv</code></a> module to split on commas and discard the double-quotes.</li>\n<li><strong>Opening the file:</strong> You can use the <a href=\"https://docs.python.org/3/library/fileinput.html\" rel=\"nofollow noreferrer\"><code>fileinput</code></a> module to avoid hard-coding the filename. The program will either open the filename given as a command-line argument, or read from <code>stdin</code>.</li>\n<li><strong>Generating triangle numbers:</strong> You used the given formula ½<em>n</em>(<em>n</em>+1), but if you want to generate the triangle numbers in sequence, you can just add 1+2+3+…, as per the definition. Calling <code>sorted(list(set(…)))</code> is superfluous, since each appended number should be unique and increasing — if you initialize <code>triangles = [0]</code> instead of <code>triangles = [0, 1]</code>.</li>\n<li><p><strong>Binary search:</strong> Using a binary search overcomplicates the solution. A linear search is not necessarily that bad, if the list is short — as it will be in this case. Furthermore, you could have just used a <a href=\"https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset\" rel=\"nofollow noreferrer\"><code>set</code></a>, whose <code>in</code> operator works in O(1) time, instead of a list. Writing less code means fewer opportunities to introduce bugs.</p>\n\n<p>Personally, I wouldn't even bother pre-generating the triangular numbers. Testing whether a number is triangular can be done using a simple arithmetic loop — the sort of thing that a CPU is very good at doing. For small numbers, it's likely to be even faster than looking up entries in a data structure, since the CPU doesn't have to access memory to perform arithmetic.</p>\n\n<p>If I had to test a large number <em>t</em> for triangularity in O(1) time, I'd use the formula in this form:</p>\n\n<p><span class=\"math-container\">$$\\lfloor \\sqrt{2t} \\rfloor \\lceil \\sqrt{2t} \\rceil \\stackrel{?}{=} 2t$$</span></p>\n\n<p>… verifying that <span class=\"math-container\">\\$\\sqrt{2t}\\$</span> is not integer.</p></li>\n<li><strong>Scoring:</strong> Use the built-in <a href=\"https://docs.python.org/3/library/functions.html\" rel=\"nofollow noreferrer\"><code>sum()</code></a> function with a <a href=\"https://docs.python.org/3/tutorial/classes.html#generator-expressions\" rel=\"nofollow noreferrer\">generator expression</a>. The words appear to be all uppercase already; no need to <code>.lower()</code>. I would use <a href=\"https://docs.python.org/3/library/functions.html#ord\" rel=\"nofollow noreferrer\"><code>ord()</code></a> to convert letters to numbers.</li>\n<li><strong>Counting words that meet the criterion:</strong> Again, use the <code>sum()</code> function, which will treat <code>True</code> values as <code>1</code>, effectively acting as a counter. In my solution below, <code>print(sum(is_triangular(score(w)) for w in words(fileinput.input())))</code> effectively summarizes the purpose of the entire program in one line.</li>\n</ul>\n\n<p>With those suggestions, the solution can just consist of a few one-liner functions, and a loop. It would be a good idea to write <a href=\"https://docs.python.org/3/library/doctest.html\" rel=\"nofollow noreferrer\"><code>doctest</code>s</a> to verify that the behavior is consistent with the examples given in the challenge.</p>\n\n\n\n<pre><code>import csv\nimport fileinput\nfrom itertools import count\n\ndef is_triangular(number):\n \"\"\"\n Test whether number is of the form n(n+1)/2.\n\n &gt;&gt;&gt; is_triangular(1)\n True\n &gt;&gt;&gt; is_triangular(55)\n True\n &gt;&gt;&gt; is_triangular(56)\n False\n \"\"\"\n counter = count(1)\n while number &gt; 0:\n number -= next(counter)\n return number == 0\n\ndef score(word):\n \"\"\"\n Calculate the word value by converting 'A'=1, 'B'=2, ..., 'Z'=26, and\n adding. Characters must all be uppercase letters.\n\n &gt;&gt;&gt; score('SKY')\n 55\n \"\"\"\n return sum(ord(c) - (ord('A') - 1) for c in word)\n\ndef words(fileinput):\n return next(csv.reader(fileinput))\n\nif __name__ == '__main__':\n print(sum(is_triangular(score(w)) for w in words(fileinput.input())))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T02:00:08.147", "Id": "424675", "Score": "1", "body": "Great answer! As this is Python I have reason to believe that `is_triangle` is not faster than a set lookup. But Python likes to be arbitrary with regards to speed. On a less superfluous point, you should `try:finally: f.close` or use `with` with fileinput, to ensure the file is closed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T13:33:14.673", "Id": "424758", "Score": "0", "body": "@Peilonrayz To construct the set, you would have to find the maximum score first (as the original code did). I don't think it's worthwhile to uglify the code in that way to chase that performance gain, since my solution is fast enough. (Premature optimization is evil.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T13:37:53.207", "Id": "424760", "Score": "0", "body": "Ah, you're right. Re-reading the question, after your comment it makes sense to me. I originally thought it'd be a simple `triangular = set(accumulate(range(1, 24)))`, so it'd safely contain A-Z. But the limit may have to be larger, and so isn't as easy." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T00:50:40.803", "Id": "219835", "ParentId": "219831", "Score": "7" } }, { "body": "<p>(I wrote this months ago and forgot to post it, so it may no longer matter, but I'll post it anyway.)</p>\n\n<p><code>wordsArray</code> is used for two different things. At first it's an array of words, but then it becomes an array of the words' values. This tends to be confusing, so it's better to use a new variable.</p>\n\n<p>The first loop in <code>solution</code> goes through a list and collects an output value for each value in the list. Python has a special kind of loop for this: a <em>list comprehension</em>. It makes calculating <code>wordValues</code> very easy:</p>\n\n<pre><code>wordValues = [calculate_total(w) for w in wordsArray]\n</code></pre>\n\n<p><code>open</code>'s mode defaults to <code>'r'</code>, so you don't need to specify it.</p>\n\n<p>Apparently <code>calculate_total</code> expects each word to end (and also begin?) with <code>\"</code>. Instead of skipping them in the loop, you can just remove them by <code>word[1:-1]</code> or <code>word.strip('\"')</code>.</p>\n\n<p><code>alphabet</code> is written out by hand instead of calculated. You could generate it automatically. But there's already a built-in function that does almost what <code>alphabet</code> does: <code>ord</code> returns the Unicode codepoint for a character. Can you find a way to use that to calculate the value of each letter?</p>\n\n<p>Instead of iterating over the indexes of <code>word</code>, you can iterate over its characters directly, without mentioning the indexes:</p>\n\n<pre><code>for c in word:\n total += alphabet[c.lower()]\n</code></pre>\n\n<p>But there's an even easier way: this loop computes the sum of a sequence of values. There's a built-in function for this: <code>sum</code>.</p>\n\n<p>With <code>ord</code>, <code>sum</code> and a comprehension, it's possible to write <code>calculate_total</code> in one line.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-05T20:23:03.787", "Id": "227534", "ParentId": "219831", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-06T23:00:13.547", "Id": "219831", "Score": "4", "Tags": [ "python", "beginner", "programming-challenge", "binary-search" ], "Title": "Project Euler Task 42 Solution" }
219831
<p>I am self thought c# kiddy and wonder if little projects like one here, are worth showing to potential employers when looking for junior developer position. This code has some issues that i do not know how to tackle, and error handling is poor. What do you think ?</p> <p><a href="https://github.com/moment93/SimpleServerClientApplication" rel="nofollow noreferrer">https://github.com/moment93/SimpleServerClientApplication</a></p> <p>Program is very simple, it is server that accepts incoming connections and spawn two threads for every connection. One to handle incoming packets other to handle outbound packets.</p> <pre><code> static void Main(string[] args) { Server server = new Server(8000, 30); server.Start(); } </code></pre>
[]
[ { "body": "<p>I looked at your code. I like that you're thinking about improving for your future career! Because this is for a new position, we have to assume they're looking for the basics. So of course, comment your code. Another thing I noticed is that the entire project was uploaded in one commit. Now, I know that if you were told to upload your code to a public repository for review, it would would all be one big <em>git add .</em>, but as a technical reviewer for some potential employer, I'd also like to see some git history. This would show me that you know version control already. A hiring manager won't look at your code, and a technical someone may want to see someone who is easy to work with. Who leaves a history and some code comments. </p>\n\n<p>This is a great example program. Web sockets are an advanced topic these days. I've been developing web apps for a year, and I haven't even touched the stuff. The guy at my job who does understand web sockets? <em>legend...</em></p>\n\n<p>That being said, in a couple places I can pick up three lines of your code and find the websites that helped you build this program.</p>\n\n<p><a href=\"https://docs.microsoft.com/en-us/dotnet/framework/network-programming/listening-with-sockets\" rel=\"nofollow noreferrer\">Listening with sockets</a>\n<a href=\"http://www.java2s.com/Tutorial/CSharp/0580__Network/TcpclientUseStreamReaderandStreamWritertoreadandwritetoaserver.htm\" rel=\"nofollow noreferrer\">Tcp Client</a></p>\n\n<p>It's a good thing you're resourceful and can build a program from ideas and google searches into reality. It's not bad that I could find these websites, but I'm going to suggest you build upon the functionality that is currently in your repo.</p>\n\n<p>A good demonstration of your ability to engineer solutions for a potential employer would be to leave this repo's master branch as it is, and then make some dev branches in this repo that <em>use</em> this server to make new clients. </p>\n\n<ul>\n<li>Make a branch called \"battleship\", use it to have a client connect to the server and play battleship with the server.</li>\n<li>Make a branch called \"banking-app\", use it to remember user's names and, money, interest. maybe even have it calculate interest in terms of dates.</li>\n<li>if you have any programs from a programming class, shoe-horn them in to a new branch and just host the input-output needed to make the program work.</li>\n</ul>\n\n<p>When you present your repo, include a description that shows what you're done, give the technical instructions on cloning which branch to get which piece of functionality. and make sure to frame the entire thing as you being this amazing builder of customer-facing services that can manipulate technology to do whatever you want.</p>\n\n<p>I would hire that candidate and I would definitely give them a sign-on bonus!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T02:34:47.823", "Id": "424680", "Score": "5", "body": "Please don't answer off-topic questions." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T02:04:43.000", "Id": "219839", "ParentId": "219836", "Score": "-4" } } ]
{ "AcceptedAnswerId": "219839", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T01:14:13.440", "Id": "219836", "Score": "-4", "Tags": [ "c#", ".net" ], "Title": "Would you consider this little project to be worth showing to potential employers?" }
219836
<p>I am writing my own 3D engine. I initially made the code quick and dirty but after a while the code became pretty messy and it have a lot of repeating code so I am currently cleaning up some of the code that I have written previously, one thing I didn't do originally was creating a base class for my 3D objects and I did not use inheritance for the different 3D object types even though they share a lot of properties and methods, but now when I am cleaning up the code and want to do it as "proper/best possible", I have created a cleaned up version of the class objects by using a base object class and the inheriting from it, but I want to know if I can improve upon it further.</p> <p><strong>Screenshot of my 3D engine:</strong></p> <p><a href="https://i.stack.imgur.com/9S5wb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9S5wb.png" alt=""></a></p> <p>I am not using any third party library, drawing viewport with <code>System.Drawing;</code> and <code>Bitmap.SetPixel</code>, rendering is multi-threaded.</p> <p>I feel like this code could be even cleaner and inherit more from the base class.</p> <ol> <li><p>For example I have a static "<code>Add</code>" method in the derived classes that are basically the same for all object types with just some additional parameters that differ, but I am not sure how I would inherit a static method, or perhaps there is a smarter way to do it that creates a similar "user programming experience"? In terms of how to use it, i.e <code>Box.Add(), Quad.Add()</code></p></li> <li><p>For the derived classes could I write the constructor in some cleaner way? Because currently it's a very long line of arguments, and most are the arguments from the base class.</p></li> </ol> <p><strong>BaseClass</strong>:</p> <pre><code>public abstract class BaseObject { protected BaseObject(Mat4 _tm, Vec3 _pos, Vec3 _rot, double _scl, Color _col, string _name, string _type) { tm = _tm; pos = _pos; rot = _rot; dir = tm.GetForwardVec(); scl = _scl; col = _col; name = _name; type = _type; } public Mat4 tm { get; } public Vec3 pos { get; } public Vec3 rot { get; } public Vec3 dir { get; } public double scl { get; } public Color col { get; } public string name { get; set; } public string type { get;} private Vec3[] verticesLocal; protected abstract Vec3[] SetVertices(); private Vec3[] p_verticesGlobal; public Vec3[] verticesGlobal { get { return p_verticesGlobal; } protected set { p_verticesGlobal = value; } } private void UpdateVerticesGlobal() { for (int i = 0; i &lt; verticesLocal.Length; i++) { verticesGlobal[i] = tm * verticesLocal[i]; } } private Line3[] p_edges; public Line3[] edges { get { return p_edges; } protected set { p_edges = value; } } protected abstract void UpdateEdges(); protected void Initialize() { verticesLocal = SetVertices(); verticesGlobal = verticesLocal; UpdateVerticesGlobal(); UpdateEdges(); } } </code></pre> <p><strong>Example Of a couple "3D Object Types" classes:</strong></p> <p><em>(I have a lot of different ones, spheres, cylinders, mesh, points, etc..)</em></p> <p><strong>Box:</strong></p> <pre><code>public class Box2 : BaseObject { private Box2(Mat4 _tm, Vec3 _pos, Vec3 _rot, double _scl, Color _col, string _name, string _type, double _width, double _height, double _depth) : base(_tm, _pos, _rot, _scl, _col, _name, _type) { width = _width; height = _height; depth = _depth; edges = new Line3[12]; base.Initialize(); } public double width { get; } public double height { get; } public double depth { get; } protected override Vec3[] SetVertices() { Vec3[] v = new Vec3[8] { new Vec3(-1, -1, -1), new Vec3(1, -1, -1), new Vec3(-1, 1, -1), new Vec3(1, 1, -1), new Vec3(-1, -1, 1), new Vec3(1, -1, 1), new Vec3(-1, 1, 1), new Vec3(1, 1, 1) }; for (int i = 0; i &lt; 8; i++) { v[i] = new Vec3(v[i].x * width * 0.5, v[i].y * height * 0.5, v[i].z * depth * 0.5); } return v; } protected override void UpdateEdges() { Vec3[] v = verticesGlobal; edges[0] = new Line3(v[0], v[1], col); edges[1] = new Line3(v[2], v[3], col); edges[2] = new Line3(v[4], v[5], col); edges[3] = new Line3(v[6], v[7], col); edges[4] = new Line3(v[0], v[2], col); edges[5] = new Line3(v[1], v[3], col); edges[6] = new Line3(v[4], v[6], col); edges[7] = new Line3(v[5], v[7], col); edges[8] = new Line3(v[0], v[4], col); edges[9] = new Line3(v[1], v[5], col); edges[10] = new Line3(v[2], v[6], col); edges[11] = new Line3(v[3], v[7], col); } public static Box2 Add(Vec3? _pos = null, Vec3? _rot = null, double _scl = 1, Color? _col = null, string _name = "Box_", bool _add = true, double _width = 100, double _height = 100, double _depth = 100) { Vec3 p = _pos ?? new Vec3(0, 0, 0); Vec3 r = _rot ?? new Vec3(0, 0, 0); Color c = _col ?? Color.FromArgb(0, 0, 0); Mat4 tm = Mat4.PosRotScaleTM(p, r, new Vec3(_scl, _scl, _scl)); Box2 o = new Box2(tm, p, r, _scl, c, _name, "Box", _width, _height, _depth); if (_add) { RenderEngine.scene.baseObjects.Add(o); } return o; } </code></pre> <p><strong>Quad:</strong></p> <pre><code>public class Quad : BaseObject { private Quad(Mat4 _tm, Vec3 _pos, Vec3 _rot, double _scl, Color _col, string _name, string _type, double _width, double _height) : base(_tm, _pos, _rot, _scl, _col, _name, _type) { width = _width; height = _height; edges = new Line3[4]; base.Initialize(); } public double width{ get; } public double height { get; } protected override Vec3[] SetVertices() { Vec3[] v = new Vec3[4] { new Vec3(-1, -1, 0), new Vec3(1, -1, 0), new Vec3(-1, 1, 0), new Vec3(1, 1, 0) }; for (int i = 0; i &lt; 4; i++) { v[i] = new Vec3(v[i].x * width * 0.5, v[i].y * height * 0.5, 0); } return v; } protected override void UpdateEdges() { Vec3[] v = verticesGlobal; edges[0] = new Line3(v[0], v[1], col); edges[1] = new Line3(v[2], v[3], col); edges[2] = new Line3(v[0], v[2], col); edges[3] = new Line3(v[1], v[3], col); } public static Quad Add(Vec3? _pos = null, Vec3? _rot = null, double _scl = 1, Color? _col = null, string _name = "Quad", bool _add = true, double _width = 100, double _height = 100) { Vec3 p = _pos ?? new Vec3(0, 0, 0); Vec3 r = _rot ?? new Vec3(0, 0, 0); Color c = _col ?? Color.FromArgb(0, 0, 0); Mat4 tm = Mat4.PosRotScaleTM(p, r, new Vec3(_scl, _scl, _scl)); Quad o = new Quad(tm, p, r, _scl, c, _name, "Quad", _width, _height); if (_add) { RenderEngine.scene.baseObjects.Add(o); } return o; } } </code></pre> <p><strong>Program:</strong></p> <pre><code>Box.Add(); // Creates object with default parameters Quad.Add(_pos: new Vec3 (0,200,50), _col:Color.Yellow) // Override selected default parameters </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T09:02:18.347", "Id": "424697", "Score": "0", "body": "Why is your coding style the opposite of the usual C# one? (I'm taking about using underscores for parameters.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-08T00:05:05.293", "Id": "424834", "Score": "0", "body": "@BCdotWEB I do it to separate local variables from parameters, easier for me to read , also it helps a bit with code completion, e.g typing Box(_) shows all available parameters." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-08T09:51:51.950", "Id": "424862", "Score": "1", "body": "But your style is the opposite of the conventional C# style, where an underscore indicates a private variable and parameters do not have this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-08T17:53:33.977", "Id": "424944", "Score": "0", "body": "True, I should probably change to be more conventional." } ]
[ { "body": "<blockquote>\n <p>I am not sure how I would inherit a static method</p>\n</blockquote>\n\n<p>As I'm sure you've figured out, you can't. I also don't think this would make any sense in your case, since the APIs is not the same. If you are just wanting to reduce the amount of code that these <code>Add</code> methods have in common, then hopefully some of my suggestions below will help.</p>\n\n<h2><code>tm</code> Redundancy</h2>\n\n<p>Why do you need <code>pos</code>, <code>rot</code>, and <code>scl</code> along with <code>tm</code>? As best I can tell, these are redundant, and redundancy requires effort to maintain. However, I'm guessing you have a good reason (e.g. <code>tm</code> is useful for computing vertices for actual rendering, while the others are useful for querying and diagnostic rendering). I would be inclined to think very hard about whether <code>tm</code> will always contain the same information as the others, and if every class is going to include <code>Mat4 tm = Mat4.PosRotScaleTM(p, r, new Vec3(_scl, _scl, _scl));</code> I would consider packaging all this information up in a <code>struct</code>, maybe called <code>Orientation</code> or something (only suggesting a name because I use it below).</p>\n\n<p>This will reduce the number of little parameters being passed around, reduce code-duplication a little (maybe not-insignificantly if you have other classes which use the same sort of information), and replace those long lines which are full of confusion with something that says \"I'm just packaging these up so that I can supply them to the base-class\" without any risk of getting it wrong. There is a risk that this will just create unnecessary structures, but I think it's worth considering. It would be most useful if you could change the orientation of objects (because you could swap-out everything at once, or provide (potentially efficient) mutator methods for common operations which maintain consistency), but it looks like that isn't a concern here.</p>\n\n<h2>Correctness</h2>\n\n<p>This line is suspect:</p>\n\n\n\n<pre class=\"lang-cs prettyprint-override\"><code>verticesGlobal = verticesLocal;\n</code></pre>\n\n<p>I'm guessing you really meant something like <code>verticesGlobal = verticesLocal.ToArray()</code> (LINQ style copy). Currently have the same array in 2 variables and change the contents across 2 methods and it's all very confusing and misleading and I'm sure it's not what you intended.</p>\n\n<h2>Initialisation</h2>\n\n<p>It's weird that <code>SetVerticies</code> doesn't set anything, generally that it has a different API from <code>UpdateEdges</code>, when they perform the same kind of role.</p>\n\n<p>Should <code>verticesGlobal._set</code> be <code>private</code> rather than protected?</p>\n\n<h2>Separation of concerns</h2>\n\n<p>Note that none of your derived classes (those that I can see) ever look at anything they send down to <code>BaseObject</code>'s constructor: there isn't really a dependency here (only <code>Edges</code> is shared). Generally, the whole thing feels like you are packing too much logic into <code>BaseObject</code>: would it make sense to separate 'objects' from their 'geometry'? That way, you could construct some <code>Quad</code> geometry, which doesn't care about position or scaling, and simply provides methods to obtain some verticies and some edges (maybe defines edges as indexes into the vertex array so you don't need any fancy initialisation?). Then your object class can just combine some position information (<code>tm</code> and such) with some geometry info, all of which could be performed in the constructor, because the 'geometry' object is initialised before the 'object' object.</p>\n\n<p>There are many ways you could facilitate such a separation; I'd be inclined to create one well-defined layer of abstraction for geometry, so you have the freedom to hide whatever you want behind it.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public interface IGeometry\n{\n /// &lt;summary&gt; Generates model-space vertices for the geometry &lt;/summary&gt;\n Vec3[] GetVertices();\n\n /// &lt;summary&gt; Generates edges for the geometry from world-space coordinates &lt;/summary&gt;\n Line3[] GetEdges(Vec3[] vertices, Color col);\n}\n</code></pre>\n\n<p>The <code>object</code> class constructor might then look more like:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public Object(Orientation _orientation, IGeometry _geometry string _name, string _type)\n{\n orientation = _orientation;\n geometry = _geometry;\n col = _col;\n name = _name;\n type = _type;\n\n verticesLocal = geometry.GetVertices();\n verticesGlobal = transform(orientation, verticesLocal);\n edges = geometry.GetEdges(verticesGlobal, col);\n}\n</code></pre>\n\n<p>... in fact that would be the entire class excepting the <code>transform</code> method (which could be provided by <code>Orientation</code>, or indeed the <code>Mat4</code>): it's just drawing together the different concerns for a particular object.</p>\n\n<p>I'm not convinced <code>col</code> really fits in here... but I'd expect material information to be separated from the geometry and position information somehow, but without changing how <code>Edges</code> are consumed that will be difficult.</p>\n\n<p>If you still want to be able to pass around a <code>Box</code> object and interrogate its <code>Box</code>ness, then you can make the 'object' class generic on the type of geometry. The downside is that to pass around an 'object' whose geometric type you <em>don't</em> care about you need an interface, either a geometry independent one, or a covariant one (but that isn't necessarily a bad thing).</p>\n\n<p>I should stress that I've not thought about this very hard, and this change may not fit into your complete project, or indeed it may not go far enough in separating the concerns: it's hard to tell without more context.</p>\n\n<h2>Naming</h2>\n\n<p>What is <code>tm</code>? Transformation matrix? Is it world space or camera space or model space or what?</p>\n\n<p>What is <code>scl</code>? Scale?</p>\n\n<p>Why is it a <code>Box2</code>? I can't see anything <code>2</code> about it.</p>\n\n<p>Typical .NET naming conventions make all public members <code>ProperCamelCase</code>, e.g. <code>VerticesGlobal</code>, <code>Scl</code>, <code>Vec3.X</code>. Underscores are also usually reserved for private fields and throw-away variables.</p>\n\n<h2>Documentation</h2>\n\n<p>It would be nice to see some more inline documentation (<code>///</code>) on some of these methods, in particular the ones which are to be inherited. For example, how can someone implementing <code>UpatedEdges</code> be sure that <code>verticesGlobal</code> is in a useful state? It's not written anywhere, so they shouldn't rely upon it, but it's clearly your intention to provide this option. If you want to keep short and familiar variable names like <code>rot</code> and <code>scl</code>, then documentation would also provide a way to expand upon exactly what these things are, so that people less familiar with the system can work out how to use it more easily.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T23:57:03.137", "Id": "424833", "Score": "0", "body": "**#0** storing pos, rot,scl, +tm is mostly for user interaction but, also is an issue extraction euler rotation angles from a transformation matrix.\n**#1** yes should be`verticesGlobal = verticesLocal.ToArray()` was a miss by me, would for sure have became an issue later .\n**#2** Box2 was just a temp name so I would not mess up the rest of my code that is dependent on the original box class, I was meant to change that after I pasted the code here.\nI posted a new version of my code as an answer, but I was not sure how i would use the interface, would be nice if you elaborated a bit on it" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T09:02:37.163", "Id": "219855", "ParentId": "219837", "Score": "3" } }, { "body": "<p>Here is an attempt at an updated version based on <a href=\"https://codereview.stackexchange.com/users/39858/visualmelon\">@visualmelon</a> suggestions, but not sure If I just ended up making bigger mess of it then before or not, partly because I'm not very familiar with interfaces and not sure how to properly use it to make this simpler <em>(I would happily take some more suggestions)</em>, though this version is a bit more fleshed out then last version with the ability to modify and move the object after it is constructed, so is going to be a bit more code for the extra functionality. <em>(though the extra functionally is not really working yet because I'm not sure how I am going to update the vertices )</em></p>\n\n<p>This code is a mess, going to have to re-think it a bit more, but I'll post this for now.</p>\n\n<p><strong>Changes:</strong></p>\n\n<ul>\n<li><p>I created a <code>Transform class</code> containing position, rotation, scale,\nand transform matrix.</p></li>\n<li><p>I created a <code>Edge struct</code> and define them as vertex index.</p></li>\n<li><p>I created a <code>Geometry class</code> containing worldSpaceVertices, localSpaceVertices, and edges.\n<em>(storing both world, and local space vertices for performance reasons)</em></p></li>\n<li><p>Change my viewpoint draw function to be able to draw the edges</p></li>\n<li><p>Change my naming convention a bit and use more descriptive naming instead of shorthands </p></li>\n</ul>\n\n<p><strong>BaseObject:</strong></p>\n\n<pre><code>public abstract class BaseObject\n{\n protected BaseObject(Transform _transform, Geometry _geometry, string _type, Color _wirecolor, string _name)\n {\n transform = _transform;\n geometry = _geometry;\n wirecolor = _wirecolor;\n name = _name;\n type = _type;\n }\n\n public Transform transform { get; }\n public Geometry geometry { get; }\n public Color wirecolor { get; set; }\n public string name { get; set; }\n public string type { get; }\n}\n</code></pre>\n\n<p><strong>Transform Class:</strong></p>\n\n<pre><code>public class Transform\n{\n public Transform(Vec3 _positon, Vec3 _rotation, double _scale)\n {\n position = _positon;\n rotation = _rotation;\n scale = _scale;\n UpdateTransformMatrix();\n }\n\n public Transform(Mat4 _tm)\n {\n matrix = _tm;\n UpdateTransform(_tm);\n }\n\n public Vec3 position { get; private set; }\n public Vec3 rotation { get; private set; }\n public double scale { get; private set; }\n public Mat4 matrix { get; private set; }\n\n public void SetTransform(Vec3? _position = null, Vec3? _rotation = null, double? _scale = null)\n {\n position = _position ?? position;\n rotation = _rotation ?? rotation;\n scale = _scale ?? scale;\n UpdateTransformMatrix();\n }\n\n public void SetTransform(Mat4 _tm)\n {\n matrix = _tm;\n UpdateTransform(_tm);\n }\n\n private void UpdateTransformMatrix()\n {\n matrix = Mat4.PosRotScaleTM(position, rotation, scale);\n // need to add a way to update vertecies\n }\n\n private void UpdateTransform(Mat4 _tm)\n {\n position = Mat4.GetPos(matrix);\n rotation = Mat4.GetRot(matrix);\n scale = Mat4.GetScl(matrix);\n // need to add a way to update vertecies\n }\n\n public Vec3 GetDir()\n {\n return (matrix.GetForwardVec());\n }\n}\n</code></pre>\n\n<p><strong>Edge Struct:</strong></p>\n\n<pre><code>public struct Edge\n{\n /// &lt;summary&gt; Edge start and end, worldSpaceVertex index. &lt;/summary&gt;\n public Edge(int _startVertexIDX, int _endVertexIDX)\n {\n startVertexIDX = _startVertexIDX;\n endVertexIDX = _endVertexIDX;\n }\n\n public int startVertexIDX { get; }\n public int endVertexIDX { get; }\n}\n</code></pre>\n\n<p><strong>Geometry Class:</strong></p>\n\n<pre><code>public class Geometry\n{\n public Geometry(Vec3[] _verticesLocal, Edge[] _edges, Mat4 _tm)\n {\n verticesLocal = _verticesLocal;\n verticesGlobal = _verticesLocal.ToArray();\n edges = _edges;\n UpdateGlobalVertices(_tm);\n }\n\n private Vec3[] p_verticesLocal;\n public Vec3[] verticesLocal\n {\n get { return p_verticesLocal; }\n private set { p_verticesLocal = value; }\n }\n\n public void SetLocalVertices(Mat4 _tm, Vec3[] _verticesLocal)\n {\n p_verticesLocal = _verticesLocal;\n UpdateGlobalVertices(_tm);\n }\n\n private Vec3[] p_verticesGlobal;\n public Vec3[] verticesGlobal\n {\n get { return p_verticesGlobal; }\n private set { p_verticesGlobal = value; }\n }\n\n public void UpdateGlobalVertices(Mat4 _tm)\n {\n for (int i = 0; i &lt; verticesLocal.Length; i++)\n {\n verticesGlobal[i] = _tm * verticesLocal[i];\n }\n }\n\n private Edge[] p_edges;\n public Edge[] edges\n {\n get { return p_edges; }\n private set { p_edges = value; }\n }\n} \n</code></pre>\n\n<p><strong>Quad:</strong></p>\n\n<pre><code> public class Quad : BaseObject\n {\n private Quad(Transform _transform, Geometry _geometry, string _type, Color _wirecolor, string _name, double _width, double _height) : base(_transform, _geometry, _type, _wirecolor, _name)\n {\n width = _width;\n height = _height;\n UpdateVertices();\n }\n\n private double p_width;\n public double width\n {\n get {return p_width; }\n set\n {\n p_width = value;\n UpdateVertices();\n }\n }\n\n private double p_height;\n public double height\n {\n get { return p_height; }\n set\n {\n p_height = value;\n UpdateVertices();\n }\n }\n\n public static Vec3[] ShapeVertices { get; } = new Vec3[4]\n {\n new Vec3(-1, -1, 0),\n new Vec3(1, -1, 0),\n new Vec3(-1, 1, 0),\n new Vec3(1, 1, 0)\n };\n\n public static Edge[] ShapeEdges { get; } = new Edge[4]\n {\n new Edge(0, 1),\n new Edge(2, 3),\n new Edge(0, 2),\n new Edge(1, 3)\n };\n\n private void UpdateVertices()\n {\n Vec3[] v = ShapeVertices.ToArray();\n for (int i = 0; i &lt; 4; i++)\n {\n v[i] = new Vec3(v[i].x * width * 0.5, v[i].y * height * 0.5, 0);\n }\n geometry.SetLocalVertices(transform.matrix, v);\n }\n\n public static Quad Add(Vec3? _position = null, Vec3? _rotation = null, double _scale = 1, Color? _wirecolor = null, string _name = \"Quad\", bool _add = true, double _width = 100, double _height = 100)\n {\n Vec3 p = _position ?? new Vec3(0, 0, 0);\n Vec3 r = _rotation ?? new Vec3(0, 0, 0);\n Color c = _wirecolor ?? Color.Black;\n Transform tm = new Transform(p, r, _scale);\n Geometry geo = new Geometry(ShapeVertices, ShapeEdges, tm.matrix);\n Quad o = new Quad(tm, geo, \"Quad\", c, _name, _width, _height);\n if (_add)\n {\n RenderEngine.scene.baseObjects.Add(o);\n }\n return o;\n }\n\n }\n</code></pre>\n\n<p><strong>Box:</strong></p>\n\n<pre><code>public class Box : BaseObject\n{\n private Box(Transform _transform, Geometry _geometry, string _type, Color _wirecolor, string _name, double _width, double _height, double _depth) : base(_transform, _geometry, _type, _wirecolor, _name)\n {\n width = _width;\n height = _height;\n depth = _depth;\n\n UpdateVertices();\n }\n\n private double p_width;\n public double width\n {\n get { return p_width; }\n set\n {\n p_width = value;\n UpdateVertices();\n }\n }\n\n private double p_height;\n public double height\n {\n get { return p_height; }\n set\n {\n p_height = value;\n UpdateVertices();\n }\n }\n\n private double p_depth;\n public double depth\n {\n get { return p_depth; }\n set\n {\n p_depth = value;\n UpdateVertices();\n }\n }\n\n public static Vec3[] ShapeVertices { get; } = new Vec3[8]\n {\n new Vec3(-1, -1, -1),\n new Vec3(1, -1, -1),\n new Vec3(-1, 1, -1),\n new Vec3(1, 1, -1),\n new Vec3(-1, -1, 1),\n new Vec3(1, -1, 1),\n new Vec3(-1, 1, 1),\n new Vec3(1, 1, 1)\n };\n\n public static Edge[] ShapeEdges { get; } = new Edge[12]\n {\n new Edge(0, 1),\n new Edge(2, 3),\n new Edge(4, 5),\n new Edge(6, 7),\n new Edge(0, 2),\n new Edge(1, 3),\n new Edge(4, 6),\n new Edge(5, 7),\n new Edge(0, 4),\n new Edge(1, 5),\n new Edge(2, 6),\n new Edge(3, 7)\n };\n\n private void UpdateVertices()\n {\n Vec3[] v = ShapeVertices.ToArray();\n for (int i = 0; i &lt; 8; i++)\n {\n v[i] = new Vec3(v[i].x * width * 0.5, v[i].y * height * 0.5, v[i].z * depth * 0.5);\n }\n geometry.SetLocalVertices(transform.matrix, v);\n }\n\n public static Box Add(Vec3? _position = null, Vec3? _rotation = null, double _scale = 1, Color? _wirecolor = null, string _name = \"Box\", bool _add = true, double _width = 100, double _height = 100, double _depth = 100)\n {\n Vec3 p = _position ?? new Vec3(0, 0, 0);\n Vec3 r = _rotation ?? new Vec3(0, 0, 0);\n Color c = _wirecolor ?? Color.Black;\n Transform tm = new Transform(p, r, _scale);\n Geometry geo = new Geometry(ShapeVertices, ShapeEdges, tm.matrix);\n Box o = new Box(tm, geo, \"Box\", c, _name, _width, _height, _depth);\n if (_add)\n {\n RenderEngine.scene.baseObjects.Add(o);\n }\n return o;\n }\n}\n</code></pre>\n\n<p><strong>Draw:</strong></p>\n\n<pre><code> public static class Draw\n {\n public static void Line(Vec3 _p0, Vec3 _p1, Pen _pen)\n {\n Camera.WorldLineToScreen(_p0, _p1, ref xySS0, ref xySS1); \n RenderEngine.g.DrawLine(_pen, (float)xySS0.x, (float)xySS0.y, (float)xySS1.x, (float)xySS1.y);\n }\n\n private static Pen basePen = new Pen(Color.Black);\n public static void BaseObject(BaseObject _obj)\n {\n basePen.Color = _obj.wirecolor;\n foreach (Edge e in _obj.geometry.edges)\n {\n Draw.Line(_obj.geometry.verticesGlobal[e.startVertexIDX], _obj.geometry.verticesGlobal[e.endVertexIDX], basePen);\n }\n }\n}\n</code></pre>\n\n<p><strong>Program:</strong></p>\n\n<pre><code> Box.Add();\n Quad.Add(_wirecolor:Color.Yellow, _position:new Vec3(200,50,0));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-08T09:21:17.110", "Id": "424857", "Score": "0", "body": "If you would like more detailed feedback on your new code, then you should probably post it as a new question; though you'd have to get it working first. The Q&A format doesn't really support a running conversation: see [this help-centre article](https://codereview.stackexchange.com/help/someone-answers) for more info. All that said, the `Geometry` class wasn't really what I had in mind (though I rather like it), and it's more complicated if you to be able to change the geometry without manually invoking an update." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T23:44:04.593", "Id": "219896", "ParentId": "219837", "Score": "1" } } ]
{ "AcceptedAnswerId": "219855", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T01:38:37.277", "Id": "219837", "Score": "5", "Tags": [ "c#", "inheritance", "graphics", "coordinate-system" ], "Title": "Class hierarchy for objects in a 3D engine" }
219837
<p>I have a class that I'm using to find the shortest <a href="https://en.wikipedia.org/wiki/Word_ladder" rel="nofollow noreferrer">word ladder</a> between two words. Each "Step" in that ladder is returned as a <code>String</code> element in a <code>LinkedList</code>. If it can't find one, it returns an empty <code>LinkedList</code>. The class is only intended to work with capital letters.</p> <p>A step can only be formed from a word in the <code>HashSet&lt;String&gt;</code> dictionary variable.</p> <p>I haven't made anything like this before, and I'm posting here because I'd appreciate help making it run faster and advice regarding how to make the code itself more easily read by other humans.</p> <pre><code>public class WordLadder { private HashSet&lt;String&gt; dictionary; public WordLadder(HashSet&lt;String&gt; dictionary) { this.dictionary = dictionary; } /** * This method finds the shortest word ladder between two words and returns * it as a LinkedList of Strings. * * @return LinkedList of Strings. */ @SuppressWarnings("unchecked") public LinkedList&lt;String&gt; findLadder(String input) { // this method relies on deleting entries from a HashSet HashSet&lt;String&gt; tempDict = (HashSet&lt;String&gt;) this.dictionary.clone(); // create LinkedLists LinkedList&lt;Integer&gt; distances = new LinkedList&lt;&gt;(); LinkedList&lt;LinkedList&lt;String&gt;&gt; ladders = new LinkedList&lt;&gt;(); LinkedList&lt;String&gt; words = new LinkedList&lt;&gt;(); // split the input line into the starting and ending words String startWord = input.substring(0, input.indexOf(" ")); String endWord = input.substring(input.indexOf(" ") + 1); // holds the shortest ladder found LinkedList&lt;String&gt; shortestLadder = new LinkedList&lt;&gt;(); words.add(startWord); distances.add(1); ladders.add(new LinkedList&lt;&gt;(Arrays.asList(startWord))); while (!words.isEmpty()) { Integer distance = distances.pop(); LinkedList&lt;String&gt; ladder = ladders.pop(); String word = words.pop(); // has the shortest ladder been found? if (word.equals(endWord)) { shortestLadder = ladder; } for (int i = 0; i &lt; word.length(); i++) { char[] currCharArr = word.toCharArray(); for (char c = 'A'; c &lt;= 'Z'; c++) { currCharArr[i] = c; LinkedList&lt;String&gt; currentPathQueueTemp = new LinkedList&lt;&gt;(ladder); String newWord = new String(currCharArr); if (tempDict.contains(newWord)) { words.add(newWord); ladders.add(currentPathQueueTemp); tempDict.remove(newWord); distances.add(distance + 1); currentPathQueueTemp.add(newWord); } } } } return shortestLadder; } } </code></pre>
[]
[ { "body": "<p>Fist of all, the code doesn't work. here's my test method. I get an empty response.</p>\n\n<pre><code>public static void main(String... args) {\n\n HashSet&lt;String&gt; dictionary = new HashSet&lt;&gt;();\n dictionary.add(\"abcd\");\n dictionary.add(\"abce\");\n dictionary.add(\"abcf\");\n dictionary.add(\"abcg\");\n dictionary.add(\"abch\");\n dictionary.add(\"abxd\");\n dictionary.add(\"abxh\");\n\n WordLadder wd = new WordLadder(dictionary);\n System.out.println(wd.findLadder(\"abcd abch\"));\n\n}\n</code></pre>\n\n<p>However, assuming you fix this, here is my review</p>\n\n<ol>\n<li>API definition: the api you chose is counter-intuitive. why not accept two string words?</li>\n<li><a href=\"https://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface\">code to the interface</a>: if you meant <code>words</code> to be a LIFO stack, use the <code>Stack</code> interface of <code>push()</code> and <code>pop()</code>. there are two reason for that: one is that it makes the usage of <code>words</code> clearer to another human. more importantly - how do you that <code>LinkedList</code> <code>add()</code> is doing the same as <code>push()</code>? </li>\n<li>the method violates the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">single responsibility principle</a>. it is parsing the input, it searches for a word in the dictionary and all the other stuff. what if you wanted to have another data structure for the dictionary? or put it in a DB?</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T13:37:36.163", "Id": "424759", "Score": "1", "body": "Sorry, I only intended it to work with uppercase letters, but I forgot to make that clear. My bad. If you run it with capital letters it will work. I will edit my question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T13:44:55.503", "Id": "424762", "Score": "0", "body": "Also, the LinkedLists are not utilized as Stacks, but as Queues." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T13:53:10.033", "Id": "424763", "Score": "0", "body": "all the more reason to use the proper interface. queue does not have `pop()`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T08:36:29.253", "Id": "219854", "ParentId": "219840", "Score": "4" } }, { "body": "<p>My few problems: </p>\n\n<ol>\n<li>Instead <code>HashSet&lt;String&gt; tempDict = (HashSet&lt;String&gt;) this.dictionary.clone();</code> you could simply use <code>Set&lt;String&gt; tempDict = new HashSet&lt;&gt;( this.dictionary );</code>. You will avoid ugly <code>@SuppressWarnings(\"unchecked\")</code>.</li>\n<li>Parsing input could be performed in other method while this one would accept two strings: initial and final word. That way it's much more versatile like Sharon Ben Asher mentioned.</li>\n<li>Code most likely works but you just can't see what is really doing. Either commenting or extracting vital parts of algorithm into named methods would most likely shed some light.</li>\n</ol>\n\n<p>I would really suggest trying to implement graph based algorithm where nodes are words and edges connect words with distance of 1. That way you could construct Graph once and use for example Dijkstra's algorithm to determine shortest path between two given nodes if it exists. Complexity would be O(n^2) where n is number of words. It could be a bit more intuitive with a bit of an explanation and possibly faster on multiple runs.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-09T11:50:58.887", "Id": "219981", "ParentId": "219840", "Score": "2" } } ]
{ "AcceptedAnswerId": "219981", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T02:10:11.443", "Id": "219840", "Score": "4", "Tags": [ "java", "performance" ], "Title": "Word ladder finding class" }
219840
<p>For my code, up to the 5th row, the formatting of my triangle is fine. But once I hit the 6th row, the formatting turns funny because I start having double digits. Is there any way to fix this?</p> <p>Also is my code optimized? Any way I can make it better?</p> <p>Thanks!</p> <pre><code>function pascals(num) { var result = [[1],[1,1]]; if (num === 0) { console.log(0); } if (num === 1) { console.log(1); } else { for (var i = 2; i &lt; num; i++) { result[i] = []; result[i][0] = 1; for (var j = 1; j &lt; i; j++) { result[i][j] = result[i - 1][j - 1] + result[i - 1][j]; } result[i][j] = 1 } } for (var i = 0; i &lt; result.length; i++) { console.log(' '.repeat(result.length - i) + result[i]); } } pascals(6) </code></pre> <pre><code> 1 1,1 1,2,1 1,3,3,1 1,4,6,4,1 1,5,10,10,5,1 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T03:06:56.017", "Id": "424681", "Score": "0", "body": "Welcome to Code Review. Since you explicitly ask to change the behavior of your code (to fix the formatting), that part of the question is off-topic for Code Review — but [it has been addressed before in a previous answer](/a/43285/9357)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-11T01:26:30.737", "Id": "425231", "Score": "0", "body": "@200_success \nHi, I just wanted to clarify for next time.\n\nI'm not too sure why this code is not implemented or working as intended. It works but I had some questions about it. \n\nSo it does fulfill this requirement, right?\n\n\"We require that the code be working correctly, to the best of the author's knowledge, before proceeding with a review.\" \n\nAlso I did see the question/answer you referred to but I'm still learning and haven't gotten to python yet. Sorry :(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-11T01:28:42.473", "Id": "425232", "Score": "0", "body": "The question specifically asks to fix the formatting to accommodate larger numbers. Therefore the code is not working correctly _as intended_, and is not ready to be reviewed, according to the rules in the [help/on-topic]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-11T01:33:04.040", "Id": "425234", "Score": "0", "body": "@200_success Sorry I totally thought I was on Stack Overflow!! Makes sense now! Thank you!!" } ]
[ { "body": "<p>Multi-digit number is what is throwing it off. I typically fix this by opting to find the highest number and then offset the rest of them appropriately. I did this back when I was messing around with polynomial triangles.</p>\n\n<h1>Fixing the spacing issue</h1>\n\n<p>I started by getting the longest possible number and then prepending the space before it to make it line up properly.</p>\n\n<p>Nextly, you have to fix the preappend so it looks better over size 2. This is accomplished over a fairly odd algorithm.</p>\n\n<p>As for the rest of the code, I did not have time to look at it, but will in a bit.</p>\n\n<h1>Fixing structure</h1>\n\n<p>Overall, your code looked pretty good. Here are just some suggestions.</p>\n\n<p>I went ahead and moved the pascal array generation to another function. The idea of a function is that it performs a task. Logically breaking up these tasks into multiple functions limits the size of each function and increases readability. From there, we can assign it to a variable inside the <code>pascal</code> function. I used the intuitive name <code>generatePascalArrays</code>, so you can get the gist of what the function does from the variable assignment.</p>\n\n<p>Secondly, I noticed you split the 1 and 0 exception cases, I combined that into one <code>if</code> and <code>console.log(num)</code>.</p>\n\n<p>Additionally, I did use some arrow functions. In other languages, you may have heard of them as lambda functions. If you are not familiar with them, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions\" rel=\"nofollow noreferrer\">here is a link</a>.</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 generatePascalArrays(num) {\n var result = [[1],[1,1]];\n for (var i = 2; i &lt; num; i++) {\n result[i] = [];\n result[i][0] = 1;\n for (var j = 1; j &lt; i; j++) {\n result[i][j] = result[i - 1][j - 1] + result[i - 1][j];\n }\n result[i][j] = 1;\n }\n return result;\n}\n\nfunction pascals(num) { \n if (num &lt;= 1) {\n console.log(num);\n }\n var result = generatePascalArrays(num), \n width = Math.max(...result[result.length-1]).toString().length; \n for (var i = 0; i &lt; result.length; i++) {\n let preOffsetter = result[result.length-i-1].length * Math.floor(width/3) + result.length - i\n console.log(' '.repeat(preOffsetter) + result[i].map((x) =&gt; ' '.repeat(width - x.toString().length) + x));\n }\n}\n\npascals(5)\npascals(6)\npascals(10)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-11T01:29:16.597", "Id": "425233", "Score": "0", "body": "Thank you! I haven't quite learned most of the stuff at the end, but I will definitely look it up now!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T04:28:58.010", "Id": "219844", "ParentId": "219841", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-07T02:40:18.170", "Id": "219841", "Score": "3", "Tags": [ "javascript" ], "Title": "Pascal's triangle JS formatting" }
219841