body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>Problem statement is from <a href="https://cses.fi/problemset/task/1646/" rel="noreferrer">CSES</a></p> <p>This is a standard question where we are given a list of numbers and a number of queries. For each query, you have to give the sum of numbers in the given range.</p> <p>My implementation in python:</p> <pre><code>def solve(): n,q = [int(a) for a in input().split(' ')] arr = [int(a) for a in input().split(' ')] cumulativeArray = [0] # Initial entry added to make 1 based indexing sum = 0 for i in range(len(arr)): sum += arr[i] cumulativeArray.append(sum) for i in range(q): x,y = [int(a) for a in input().split(' ')] print(cumulativeArray[y] - cumulativeArray[x-1]) solve() </code></pre> <p>This gives the required answers correctly for all my custom test cases. But gives TLE for huge test cases.</p> <p>I believe this is happening due to <code>split()</code> method in my code. Any leads are welcome.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T16:15:12.233", "Id": "494069", "Score": "1", "body": "Instead of building `cumulativeArray` manually, consider `np.cumsum` or `itertools.accumulate`." } ]
[ { "body": "<p>You are already using the optimal solution algorithm for the problem. A few things, which might speed-up the computations (<code>.split</code> should not be the limiting factor in most likeliness)</p>\n<h2>Variable naming</h2>\n<p>Use names which match the problem description, so that it becomes easier to follow your code. So, instead of <code>x, y</code> it'd be <code>a, b</code>. Also, in python, it is a good practice to name your variables in <code>lower_snake_case</code>.</p>\n<p><code>sum</code> is an builtin function. Do not override this.</p>\n<h2>Computing <code>len</code></h2>\n<p>You do not need to iterate over indices as the index is not really being used anyway. Lists can be iterated over their values itself.</p>\n<h2>Lazy iterators</h2>\n<p>Instead of generating list inline, you can use generators so that the values are yielded when iterating, and not consuming memory.</p>\n<h2><code>.split</code></h2>\n<p>Not passing a parameter to <code>.split</code> is same as providing whitespace as parameter.</p>\n<hr />\n<p>Rewrite:</p>\n<pre><code>def solve():\n n, q = map(int, input().split())\n arr = map(int, input().split())\n \n cumulative_summation = [0]\n running_sum = 0\n # Not calculating `len` of `arr`, also, you don't need to calculate it.\n # the length is known to be `n`.\n for value in arr:\n running_sum += value\n cumulative_summation.append(running_sum)\n \n for i in range(q):\n a, b = map(int, input().split())\n print(cumulative_summation[b] - cumulative_summation[a - 1])\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T04:55:00.280", "Id": "493997", "Score": "0", "body": "Thank you so much for all the recommendations.\nUnfortunately, it's still giving TLE. \nThe reason I suspect `split` to be time-consuming is the fact that initially a string is read and split into n elements. Other languages like java/C++ have an option to read individual numbers directly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T05:01:07.273", "Id": "493998", "Score": "0", "body": "Additionally, I used `stdin` to speed up reading. But that didn't help either." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T05:12:41.450", "Id": "493999", "Score": "0", "body": "Update: I've added stdout for outputting and converting the same array in place to cumulative sum. Still TLE." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T11:35:32.290", "Id": "494030", "Score": "1", "body": "You can do a performance check to get which operation is consuming the most time. Most likely cause could be the `.append` operation @AdityaGupta" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T13:52:09.047", "Id": "494050", "Score": "0", "body": "I disagree with the move to `map`. I think the OP's input method is fine, though he should be using a generator and not a list for those lines. The generator is much clearer to read." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T14:38:43.183", "Id": "494059", "Score": "0", "body": "Thanks for the recommendation @hjpotter92. I'll do performance check when I get some free cycles. Will get back to you guys shortly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T14:39:23.747", "Id": "494060", "Score": "1", "body": "@Reinderien I will do performance evaluation and comment further" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T14:08:08.920", "Id": "494247", "Score": "0", "body": "How would that \"breaks on empty input\" look like, exactly?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T16:18:40.750", "Id": "494264", "Score": "0", "body": "@HeapOverflow `while line := input():`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T17:07:37.793", "Id": "494270", "Score": "0", "body": "@hjpotter92 But how do you handle the `EOFError: EOF when reading a line` caused by that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T17:16:46.807", "Id": "494273", "Score": "0", "body": "@HeapOverflow ah, you're correct. Although, as mentioned in reply above, with a while loop `while True: line = input(); if not input: break`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T17:37:38.003", "Id": "494276", "Score": "0", "body": "@hjpotter92 That gives the same error." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T07:15:00.600", "Id": "494303", "Score": "0", "body": "@HeapOverflow the first suggested implementation works for me: https://i.stack.imgur.com/jNg8X.png" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T11:36:40.883", "Id": "494329", "Score": "1", "body": "@hjpotter92 You additionally entered an empty line, didn't you? That's not guaranteed to exist in the input, and in fact there isn't one. If you submit it with that way, you'll get that error." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T17:05:21.477", "Id": "494379", "Score": "0", "body": "I see your edit. It has nothing to do with being piped. It's solely about whether there's an empty line. If what you pipe in has an empty line, that works. If you enter manually and end the input (probably you can do that by pressing ctrl-d) without an empty line, then you get the error." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T17:38:08.093", "Id": "494386", "Score": "0", "body": "@HeapOverflow I think the automated evaluators do use stdin redirection pipes to feed input data (dockerised run of code)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T17:42:13.173", "Id": "494389", "Score": "0", "body": "I think so, too. But how is that relevant?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T17:44:47.807", "Id": "494390", "Score": "0", "body": "@HeapOverflow that is what i was thinking when i put in that edit above. hadn't tested with the same though. will remove the entire section now." } ], "meta_data": { "CommentCount": "18", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T04:47:18.000", "Id": "251049", "ParentId": "251038", "Score": "5" } }, { "body": "<p>To add on to @hjpotter92's answer:</p>\n<ul>\n<li>If you're not using <code>i</code> in <code>for i in range(q)</code>, replace it with <code>_</code>, i.e. <code>for _ in range(q)</code> to indicate that you are not using the variable.</li>\n<li>It turns out the actual bottleneck is the many calls to <code>print()</code> in a for loop. If you tweak your code so it instead builds a string of all the answers to the queries in memory and prints it out in one go, it will pass all the test cases. I verified this by submitting the code below.</li>\n</ul>\n<pre class=\"lang-python prettyprint-override\"><code>#!/usr/bin/env python3\n\nn, q = map(int, input().split())\narr = map(int, input().split())\n\ncumulative_sums = [0]\ncurrent_sum = 0\nfor num in arr:\n current_sum += num\n cumulative_sums.append(current_sum)\n\nqueries = (tuple(map(int, input().split())) for _ in range(q))\nprint(\n &quot;\\n&quot;.join(\n f&quot;{cumulative_sums[b] - cumulative_sums[a - 1]}&quot; for a, b in queries\n )\n)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T14:52:09.037", "Id": "494358", "Score": "0", "body": "Nice catch!! We all missed this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T17:39:14.600", "Id": "494388", "Score": "0", "body": "Ah yes! Buffer cleanups." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T13:41:33.660", "Id": "251125", "ParentId": "251038", "Score": "4" } }, { "body": "<p><strong>Your solution is alright and I got it accepted as-is. Just had to choose &quot;PyPy3&quot; instead of &quot;CPython3&quot;.</strong></p>\n<p>Anyway...</p>\n<p>I'd use <code>accumulate</code> and a helper function to reduce code duplication and make the interesting code clearer:</p>\n<pre><code>from itertools import accumulate\n\ndef input_ints():\n return map(int, input().split())\n\ndef solve():\n _, q = input_ints()\n cumulative = [0, *accumulate(input_ints())]\n \n for _ in range(q):\n a, b = input_ints()\n print(cumulative[b] - cumulative[a - 1])\n\nsolve()\n</code></pre>\n<p>This still gets TLE with CPython3, though, and gets accepted in PyPy3 in the same 0.81 seconds as yours.</p>\n<p>As @setris <a href=\"https://codereview.stackexchange.com/a/251125/219610\">pointed out</a> you can get it accepted by using a single <code>print</code>. Here's my version of that, not mixing the calculations with the printing, which I find clearer. Got accepted with CPython3 in 0.69 seconds.</p>\n<pre><code>from itertools import accumulate\n\ndef input_ints():\n return map(int, input().split())\n\ndef solve():\n _, q = input_ints()\n cumulative = [0, *accumulate(input_ints())]\n\n results = []\n for _ in range(q):\n a, b = input_ints()\n results.append(cumulative[b] - cumulative[a - 1])\n\n print('\\n'.join(map(str, results)))\n\nsolve()\n</code></pre>\n<p>If you don't mind the asymmetry of <code>solve</code> reading the input itself but not printing the output itself, you could also make it a generator:</p>\n<pre><code>from itertools import accumulate\n\ndef input_ints():\n return map(int, input().split())\n\ndef solve():\n _, q = input_ints()\n cumulative = [0, *accumulate(input_ints())]\n\n for _ in range(q):\n a, b = input_ints()\n yield cumulative[b] - cumulative[a - 1]\n\nprint('\\n'.join(map(str, solve())))\n</code></pre>\n<p>I <em>do</em> mind that asymmetry, though. Another symmetric way, instead of <code>solve</code> doing both input and output, would be to <code>solve</code> doing <em>neither of them</em>:</p>\n<pre><code>from itertools import accumulate\n\ndef input_ints():\n return map(int, input().split())\n\ndef solve(x, queries):\n cumulative = [0, *accumulate(x)]\n\n for a, b in queries:\n yield cumulative[b] - cumulative[a - 1]\n\n_, q = input_ints()\nx = input_ints()\nqueries = (input_ints() for _ in range(q))\nresults = solve(x, queries)\nprint('\\n'.join(map(str, results)))\n</code></pre>\n<p>Granted, now the &quot;main block&quot; doesn't look nice. But <code>solve</code> is now very nice, and it can also be tested nicely by just calling it with data, for example:</p>\n<pre><code>&gt;&gt;&gt; list(solve([3, 2, 4, 5, 1, 1, 5, 3],\n [[2, 4], [5, 6], [1, 8], [3, 3]]))\n[11, 2, 24, 4]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T14:30:37.357", "Id": "251129", "ParentId": "251038", "Score": "3" } } ]
{ "AcceptedAnswerId": "251125", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-22T20:22:30.923", "Id": "251038", "Score": "9", "Tags": [ "python", "performance", "algorithm", "programming-challenge" ], "Title": "CSES standard solution for range query problem giving TLE" }
251038
<p>I'm very new to jQuery and I managed to make this code work but I'm pretty sure that it could be made in a more efficient way. For example, it should be a way to send the id as a parameter instead of writing the same code for each id.</p> <p>But beside of that, are there other things that could be made in a better way?</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>// selecting elements $('#0') .find('.cart-quantity-input') .change(function () { var quantity = parseFloat($('#0').find('.cart-quantity-input').val()); var price = parseFloat( $('#0').find('.cart-price').text().replace('€', '') ); $('#0') .find('.cart-subtotal') .text(quantity * price + '€'); }); $('#1') .find('.cart-quantity-input') .change(function () { var quantity = parseFloat($('#1').find('.cart-quantity-input').val()); var price = parseFloat( $('#1').find('.cart-price').text().replace('€', '') ); $('#1') .find('.cart-subtotal') .text(quantity * price + '€'); }); $('#2') .find('.cart-quantity-input') .change(function () { var quantity = parseFloat($('#2').find('.cart-quantity-input').val()); var price = parseFloat( $('#2').find('.cart-price').text().replace('€', '') ); $('#2') .find('.cart-subtotal') .text(quantity * price + '€'); }); // compute subtotal sum function subTotal(element) { var quantity = element.siblings('.cart-quantity-input').val(); var price = parseFloat( element.closest('.cart-row').find('.cart-price').text().replace('€', '') ); $(element) .closest('.cart-row') .find('.cart-subtotal') .text(price * quantity + '€'); } // compute total sum and number of items function computeTotalValues() { var total = [...$('.cart-items .cart-subtotal')] .map((subtotalElm) =&gt; Number(subtotalElm.textContent.replace('€', ''))) .reduce((a, b) =&gt; a + b, 0); $('.cart-total-price').text(total + '€'); const totalQuantity = $.map( $('.cart-items .cart-quantity-input'), (input) =&gt; +input.value ).reduce((a, b) =&gt; a + b, 0); $('.items-number').text(totalQuantity + ' items'); } // increase number of items $('.plus').on('click', function () { var increment = parseInt($(this).siblings('input').val()); increment++; $(this).siblings('input').val(increment); subTotal($(this)); computeTotalValues(); }); // decrease number of items $('.minus').on('click', function () { var decrement = parseInt($(this).siblings('input').val()); if (decrement) { decrement--; } $(this).siblings('input').val(decrement); subTotal($(this)); computeTotalValues(); }); // checkout button clicked $('.btn-primary').on('click', function () { if ( confirm('Are you sure you want to checkout? \nYour products will disappear') ) { $('.cart-total-price').text('0 €'); $('.items-number').text('0 items'); $('.cart-quantity-input').val('0'); } });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>* { box-sizing: border-box; font-family: sans-serif; color: #777; } html, body { margin: 0; padding: 0; min-height: 100%; background-color: #261741; } .container { display: flex; width: 55%; min-width: 700px; margin: 0 auto; border-radius: 10px; overflow: hidden; margin-top: 50px; min-height: 500px; } .first-section { background-color: #ffffff; position: relative; width: 70%; padding-left: 40px; padding-top: 10px; } .second-section { background-color: #f3f3f3; position: relative; width: 30%; padding: 10px 20px 20px 20px; } .section-header { font-weight: bold; color: #333; font-size: 18px; } .summary-title { display: flex; } .cart-items { margin-bottom: 60px; } .btn { text-align: center; vertical-align: middle; padding: 0.67em 0.67em; cursor: pointer; } .btn-primary { color: white; position: absolute; background-color: #9100ff; border: none; border-radius: 4px; font-weight: bold; display: block; font-size: 16px; bottom: 20px; width: 83%; } .btn-primary:hover { background-color: #000099; } .main-line { margin-right: 20px; } .cart-header { font-weight: bold; font-size: 15 px; } .cart-column { display: flex; align-items: center; color: black; margin-right: 1.5em; padding-bottom: 10px; margin-top: 10px; } .cart-column-title { display: flex; align-items: center; color: lightgray; margin-right: 1.5em; padding-bottom: 10px; margin-top: 10px; } .cart-row { display: flex; } .cart-item { width: 55%; font-size: 14px; text-transform: uppercase; } .cart-price { display: flex; justify-content: center; width: 15%; font-size: 14px; text-transform: uppercase; } .cart-quantity { display: flex; justify-content: center; width: 15%; font-size: 14px; text-transform: uppercase; } .cart-subtotal { display: flex; justify-content: center; width: 15%; font-size: 14px; text-transform: uppercase; } .item-info { display: flex; flex-direction: column; } .cart-item-title { color: #bc6cff; margin-left: 10px; font-size: 15px; font-weight: bold; } .cart-item-description { color: lightslategray; margin-left: 10px; font-size: 10px; } .cart-item-image { width: 75px; height: auto; border-radius: 10px; } .cart-quantity-input { height: 34px; width: 34px; border-radius: 5px; border: 2px solid lightgray; color: #333; padding: 0; text-align: center; font-size: 1.2em; margin-right: 15px; margin-left: 15px; } .cart-row:last-child .cart-column { border: none; } .cart-total { text-align: end; margin-top: 10px; margin-right: 10px; } .cart-total-title { font-size: 14px; color: black; margin-right: 20px; text-transform: uppercase; } .cart-total-price { color: #333; font-size: 1.1em; } .numerical-values { color: #bc6cff; font-size: 34px; } .numerical-values:hover { cursor: pointer; } .items-number { display: flex; } .items-and-total { display: flex; flex-direction: row; justify-content: space-between; padding: 17px 0px 0px 17px; } .items-and-total-final { display: flex; flex-direction: row; justify-content: space-between; padding: 0px 0px 0px 0px; } .items-discount { display: flex; text-transform: uppercase; padding-top: 15px; } .final-part { margin-bottom: 70px; bottom: 0px; position: absolute; width: 82%; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Shopping cart&lt;/title&gt; &lt;meta name="description" content="This is the description" /&gt; &lt;link rel="stylesheet" href="styles.css" /&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;div class="first-section"&gt; &lt;h2 class="section-header"&gt;Shopping cart&lt;/h2&gt; &lt;hr class="main-line" /&gt; &lt;div class="cart-row"&gt; &lt;span class="cart-item cart-header cart-column-title" &gt;Product details&lt;/span &gt; &lt;span class="cart-quantity cart-header cart-column-title" &gt;Quantity&lt;/span &gt; &lt;span class="cart-price cart-header cart-column-title"&gt;Price&lt;/span&gt; &lt;span class="cart-subtotal cart-header cart-column-title"&gt;Total&lt;/span&gt; &lt;/div&gt; &lt;div class="cart-items"&gt; &lt;div class="cart-row" id="0"&gt; &lt;div class="cart-item cart-column"&gt; &lt;img class="cart-item-image" src="Images/goku.png" width="100" height="100" /&gt; &lt;div class="item-info"&gt; &lt;span class="cart-item-title"&gt;Goku POP&lt;/span&gt; &lt;span class="cart-item-description"&gt;Product code GOKU&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="cart-quantity cart-column"&gt; &lt;div class="numerical-values minus"&gt;-&lt;/div&gt; &lt;input class="cart-quantity-input" disabled type="text" value="0" /&gt; &lt;div class="numerical-values plus"&gt;+&lt;/div&gt; &lt;/div&gt; &lt;span class="cart-price cart-column"&gt;5€&lt;/span&gt; &lt;span class="cart-subtotal cart-column"&gt;0€&lt;/span&gt; &lt;/div&gt; &lt;div class="cart-row" id="1"&gt; &lt;div class="cart-item cart-column"&gt; &lt;img class="cart-item-image" src="Images/naruto.png" width="100" height="100" /&gt; &lt;div class="item-info"&gt; &lt;span class="cart-item-title"&gt;Naruto POP&lt;/span&gt; &lt;span class="cart-item-description"&gt;Product code NARUTO&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="cart-quantity cart-column"&gt; &lt;div class="numerical-values minus"&gt;-&lt;/div&gt; &lt;input class="cart-quantity-input" id="naruto" disabled type="text" value="0" /&gt; &lt;div class="numerical-values plus"&gt;+&lt;/div&gt; &lt;/div&gt; &lt;span class="cart-price cart-column"&gt;20€&lt;/span&gt; &lt;span class="cart-subtotal cart-column"&gt;0€&lt;/span&gt; &lt;/div&gt; &lt;div class="cart-row" id="2"&gt; &lt;div class="cart-item cart-column"&gt; &lt;img class="cart-item-image" src="Images/luffy.png" width="100" height="100" /&gt; &lt;div class="item-info"&gt; &lt;span class="cart-item-title"&gt;Luffy POP&lt;/span&gt; &lt;span class="cart-item-description"&gt;Product code LUFFY&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="cart-quantity cart-column"&gt; &lt;div class="numerical-values minus"&gt;-&lt;/div&gt; &lt;input class="cart-quantity-input" id="luffy" disabled type="text" value="0" /&gt; &lt;div class="numerical-values plus"&gt;+&lt;/div&gt; &lt;/div&gt; &lt;span class="cart-price cart-column"&gt;7.5€&lt;/span&gt; &lt;span class="cart-subtotal cart-column"&gt;0€&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="second-section"&gt; &lt;div class="cart-total"&gt; &lt;h2 class="section-header summary-title"&gt;Order Summary&lt;/h2&gt; &lt;hr /&gt; &lt;div class="items-and-total"&gt; &lt;span class="items-number"&gt;0 items&lt;/span&gt; &lt;span class="cart-total-price"&gt;0€&lt;/span&gt; &lt;/div&gt; &lt;hr /&gt; &lt;div class="final-part"&gt; &lt;hr /&gt; &lt;div class="items-and-total-final"&gt; &lt;div class="cart-total-title"&gt;Total cost&lt;/div&gt; &lt;span class="cart-total-price"&gt;0€&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;button class="btn btn-primary" type="button"&gt;Checkout&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous" &gt;&lt;/script&gt; &lt;script src="store.js" async&gt;&lt;/script&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<p><strong>DRYing</strong></p>\n<ul>\n<li><p>The separate numeric-indexed IDs are used only to get to their children <code>.cart-quantity-input</code> elements, so you can just select those elements directly instead and remove the IDs. When you have to select something else in the same row, first use:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const $row = $(this).closest('.cart-row');\n</code></pre>\n<p>and you'll get to the row, from which you can, with <code>.find</code>, navigate to the price, quantity, and total elements, whichever is needed.</p>\n<p>That said, given only the code in the question, the change handler looks to be entirely superfluous, since the plus and minus buttons already calculate and render the new item subtotals - there doesn't seem to be any need for a separate handler on top of those, unless some other part of the page can change it too.</p>\n</li>\n<li><p>Also, rather than having a separate handler for plus and minus buttons, you can combine those into a single handler instead, and check the class of the clicked element to determine whether to add or subtract one from the current quantity:</p>\n<pre class=\"lang-js prettyprint-override\"><code>$('.plus, .minus').on('click', function () {\n const currentValue = parseInt($(this).siblings('input').val());\n const addValue = $(this).is('.plus') ? 1 : -1;\n $(this).siblings('input').val(Math.max(0, currentValue + addValue));\n</code></pre>\n</li>\n</ul>\n<p>Other suggestions:</p>\n<p><strong>The <code>+</code> and <code>-</code> buttons are <em>selectable</em></strong> currently, which looks weird if one clicks more than once in quick succession. They act as buttons, not as plain text, so having the text in the button be selectable doesn't seem right. Consider adding:</p>\n<pre class=\"lang-css prettyprint-override\"><code>.numerical-values {\n user-select: none;\n}\n</code></pre>\n<p><strong>After content?</strong> Rather than having to add and replace out <code>€</code> every time you want to set or get a price, consider using <code>:after</code> instead:</p>\n<pre class=\"lang-css prettyprint-override\"><code>.cart-price:after, .cart-subtotal:after {\n content: &quot;€&quot;;\n}\n</code></pre>\n<p><strong>Precise names</strong> Imagine you hadn't seen the code before and saw this line: <code>subTotal($(this));</code> What does it do? It's not very clear. Consider calling it something more precise, like <code>calculateAndRenderSubtotal</code>, also making the comment above the function entirely superfluous:</p>\n<pre class=\"lang-js prettyprint-override\"><code>// (Current code is:)\n\n// compute subtotal sum\nfunction subtotal(element) {\n</code></pre>\n<p><strong>Use modern syntax everywhere</strong> You're using ES2015 in a number of places in the code. If you want to use it (which you should, it makes things readable and concise!), best to use ES2015+ syntax everywhere you can - in particular, use <code>const</code> instead of <code>var</code> (or, use <code>let</code> when the variable needs to be reassigned).</p>\n<p><strong>Checkout bug?</strong> You have:</p>\n<pre class=\"lang-js prettyprint-override\"><code>$('.btn-primary').on('click', function () {\n if (\n confirm('Are you sure you want to checkout? \\nYour products will disappear')\n ) {\n $('.cart-total-price').text('0 €');\n $('.items-number').text('0 items');\n $('.cart-quantity-input').val('0');\n }\n});\n</code></pre>\n<p>But this doesn't clear the item subtotals. Reset them all to 0.</p>\n<pre class=\"lang-js prettyprint-override\"><code>$('.cart-subtotal').text(0);\n</code></pre>\n<p>Also consider replacing the <code>confirm</code> with a proper modal - the browsers built-in alert boxes <em>block</em> the browser, preventing JavaScript from running on the page, and making the page inaccessible until the box is cleared. It's not user-friendly.</p>\n<p><strong>Combine select + <code>.find</code></strong> I refactored it out while DRYing, but whenever you have code like:</p>\n<pre class=\"lang-js prettyprint-override\"><code>$('#0')\n .find('.cart-quantity-input')\n</code></pre>\n<p>This simplifies to:</p>\n<pre class=\"lang-js prettyprint-override\"><code>$('#0 .cart-quantity-input')\n</code></pre>\n<p>using a space, the <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/Descendant_combinator\" rel=\"nofollow noreferrer\">descendant combinator</a>.</p>\n<p>Suggested new code:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>/*\n// This section can be removed entirely if \n// calculateAndRenderSubtotal is the only place\n// where a row's quantity can change from\n\n$('.cart-quantity-input').on('change', function() {\n const quantity = this.value;\n const $row = $(this).closest('.cart-row');\n const price = $row.find('.cart-price').text();\n $row.find('.cart-subtotal').text(quantity * price);\n});\n*/\n\nfunction calculateAndRenderSubtotal(element) {\n const quantity = element.siblings('.cart-quantity-input').val();\n const price = parseFloat(\n element.closest('.cart-row').find('.cart-price').text()\n );\n\n $(element)\n .closest('.cart-row')\n .find('.cart-subtotal')\n .text(price * quantity);\n}\n\n// compute total sum and number of items\nfunction computeTotalValues() {\n const total = [...$('.cart-items .cart-subtotal')]\n .map((subtotalElm) =&gt; Number(subtotalElm.textContent))\n .reduce((a, b) =&gt; a + b, 0);\n\n $('.cart-total-price').text(total);\n\n const totalQuantity = $.map(\n $('.cart-items .cart-quantity-input'),\n (input) =&gt; +input.value\n ).reduce((a, b) =&gt; a + b, 0);\n\n $('.items-number').text(totalQuantity + ' items');\n}\n\n// increase number of items\n$('.plus, .minus').on('click', function() {\n const currentValue = parseInt($(this).siblings('input').val());\n const addValue = $(this).is('.plus') ? 1 : -1;\n $(this).siblings('input').val(Math.max(0, currentValue + addValue));\n calculateAndRenderSubtotal($(this));\n computeTotalValues();\n});\n\n// checkout button clicked\n$('.btn-primary').on('click', function() {\n if (\n confirm('Are you sure you want to checkout? \\nYour products will disappear')\n ) {\n $('.cart-total-price').text('0');\n $('.items-number').text('0 items');\n $('.cart-quantity-input').val('0');\n $('.cart-subtotal').text(0);\n }\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>* {\n box-sizing: border-box;\n font-family: sans-serif;\n color: #777;\n}\n\nhtml,\nbody {\n margin: 0;\n padding: 0;\n min-height: 100%;\n background-color: #261741;\n}\n\n.container {\n display: flex;\n width: 55%;\n min-width: 700px;\n margin: 0 auto;\n border-radius: 10px;\n overflow: hidden;\n margin-top: 50px;\n min-height: 500px;\n}\n\n.first-section {\n background-color: #ffffff;\n position: relative;\n width: 70%;\n padding-left: 40px;\n padding-top: 10px;\n}\n\n.second-section {\n background-color: #f3f3f3;\n position: relative;\n width: 30%;\n padding: 10px 20px 20px 20px;\n}\n\n.section-header {\n font-weight: bold;\n color: #333;\n font-size: 18px;\n}\n\n.summary-title {\n display: flex;\n}\n\n.cart-items {\n margin-bottom: 60px;\n}\n\n.btn {\n text-align: center;\n vertical-align: middle;\n padding: 0.67em 0.67em;\n cursor: pointer;\n}\n\n.btn-primary {\n color: white;\n position: absolute;\n background-color: #9100ff;\n border: none;\n border-radius: 4px;\n font-weight: bold;\n display: block;\n font-size: 16px;\n bottom: 20px;\n width: 83%;\n}\n\n.btn-primary:hover {\n background-color: #000099;\n}\n\n.main-line {\n margin-right: 20px;\n}\n\n.cart-header {\n font-weight: bold;\n font-size: 15 px;\n}\n\n.cart-column {\n display: flex;\n align-items: center;\n color: black;\n margin-right: 1.5em;\n padding-bottom: 10px;\n margin-top: 10px;\n}\n\n.cart-column-title {\n display: flex;\n align-items: center;\n color: lightgray;\n margin-right: 1.5em;\n padding-bottom: 10px;\n margin-top: 10px;\n}\n\n.cart-row {\n display: flex;\n}\n\n.cart-item {\n width: 55%;\n font-size: 14px;\n text-transform: uppercase;\n}\n\n.cart-price:after,\n.cart-subtotal:after {\n content: \"€\";\n}\n\n.cart-price {\n display: flex;\n justify-content: center;\n width: 15%;\n font-size: 14px;\n text-transform: uppercase;\n}\n\n.cart-quantity {\n display: flex;\n justify-content: center;\n width: 15%;\n font-size: 14px;\n text-transform: uppercase;\n}\n\n.cart-subtotal {\n display: flex;\n justify-content: center;\n width: 15%;\n font-size: 14px;\n text-transform: uppercase;\n}\n\n.item-info {\n display: flex;\n flex-direction: column;\n}\n\n.cart-item-title {\n color: #bc6cff;\n margin-left: 10px;\n font-size: 15px;\n font-weight: bold;\n}\n\n.cart-item-description {\n color: lightslategray;\n margin-left: 10px;\n font-size: 10px;\n}\n\n.cart-item-image {\n width: 75px;\n height: auto;\n border-radius: 10px;\n}\n\n.cart-quantity-input {\n height: 34px;\n width: 34px;\n border-radius: 5px;\n border: 2px solid lightgray;\n color: #333;\n padding: 0;\n text-align: center;\n font-size: 1.2em;\n margin-right: 15px;\n margin-left: 15px;\n}\n\n.cart-row:last-child .cart-column {\n border: none;\n}\n\n.cart-total {\n text-align: end;\n margin-top: 10px;\n margin-right: 10px;\n}\n\n.cart-total-title {\n font-size: 14px;\n color: black;\n margin-right: 20px;\n text-transform: uppercase;\n}\n\n.cart-total-price {\n color: #333;\n font-size: 1.1em;\n}\n\n.numerical-values {\n color: #bc6cff;\n font-size: 34px;\n user-select: none;\n}\n\n.numerical-values:hover {\n cursor: pointer;\n}\n\n.items-number {\n display: flex;\n}\n\n.items-and-total {\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n padding: 17px 0px 0px 17px;\n}\n\n.items-and-total-final {\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n padding: 0px 0px 0px 0px;\n}\n\n.items-discount {\n display: flex;\n text-transform: uppercase;\n padding-top: 15px;\n}\n\n.final-part {\n margin-bottom: 70px;\n bottom: 0px;\n position: absolute;\n width: 82%;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"container\"&gt;\n &lt;div class=\"first-section\"&gt;\n &lt;h2 class=\"section-header\"&gt;Shopping cart&lt;/h2&gt;\n &lt;hr class=\"main-line\" /&gt;\n &lt;div class=\"cart-row\"&gt;\n &lt;span class=\"cart-item cart-header cart-column-title\"&gt;Product details&lt;/span\n &gt;\n &lt;span class=\"cart-quantity cart-header cart-column-title\"\n &gt;Quantity&lt;/span\n &gt;\n &lt;span class=\"cart-price cart-header cart-column-title\"&gt;Price&lt;/span&gt;\n &lt;span class=\"cart-subtotal cart-header cart-column-title\"&gt;Total&lt;/span&gt;\n &lt;/div&gt;\n &lt;div class=\"cart-items\"&gt;\n &lt;div class=\"cart-row\" id=\"0\"&gt;\n &lt;div class=\"cart-item cart-column\"&gt;\n &lt;img class=\"cart-item-image\" src=\"Images/goku.png\" width=\"100\" height=\"100\" /&gt;\n &lt;div class=\"item-info\"&gt;\n &lt;span class=\"cart-item-title\"&gt;Goku POP&lt;/span&gt;\n &lt;span class=\"cart-item-description\"&gt;Product code GOKU&lt;/span&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"cart-quantity cart-column\"&gt;\n &lt;div class=\"numerical-values minus\"&gt;-&lt;/div&gt;\n &lt;input class=\"cart-quantity-input\" disabled type=\"text\" value=\"0\" /&gt;\n &lt;div class=\"numerical-values plus\"&gt;+&lt;/div&gt;\n &lt;/div&gt;\n &lt;span class=\"cart-price cart-column\"&gt;5&lt;/span&gt;\n &lt;span class=\"cart-subtotal cart-column\"&gt;0&lt;/span&gt;\n &lt;/div&gt;\n &lt;div class=\"cart-row\" id=\"1\"&gt;\n &lt;div class=\"cart-item cart-column\"&gt;\n &lt;img class=\"cart-item-image\" src=\"Images/naruto.png\" width=\"100\" height=\"100\" /&gt;\n &lt;div class=\"item-info\"&gt;\n &lt;span class=\"cart-item-title\"&gt;Naruto POP&lt;/span&gt;\n &lt;span class=\"cart-item-description\"&gt;Product code NARUTO&lt;/span&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"cart-quantity cart-column\"&gt;\n &lt;div class=\"numerical-values minus\"&gt;-&lt;/div&gt;\n &lt;input class=\"cart-quantity-input\" id=\"naruto\" disabled type=\"text\" value=\"0\" /&gt;\n &lt;div class=\"numerical-values plus\"&gt;+&lt;/div&gt;\n &lt;/div&gt;\n &lt;span class=\"cart-price cart-column\"&gt;20&lt;/span&gt;\n &lt;span class=\"cart-subtotal cart-column\"&gt;0&lt;/span&gt;\n &lt;/div&gt;\n &lt;div class=\"cart-row\" id=\"2\"&gt;\n &lt;div class=\"cart-item cart-column\"&gt;\n &lt;img class=\"cart-item-image\" src=\"Images/luffy.png\" width=\"100\" height=\"100\" /&gt;\n &lt;div class=\"item-info\"&gt;\n &lt;span class=\"cart-item-title\"&gt;Luffy POP&lt;/span&gt;\n &lt;span class=\"cart-item-description\"&gt;Product code LUFFY&lt;/span&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"cart-quantity cart-column\"&gt;\n &lt;div class=\"numerical-values minus\"&gt;-&lt;/div&gt;\n &lt;input class=\"cart-quantity-input\" id=\"luffy\" disabled type=\"text\" value=\"0\" /&gt;\n &lt;div class=\"numerical-values plus\"&gt;+&lt;/div&gt;\n &lt;/div&gt;\n &lt;span class=\"cart-price cart-column\"&gt;7.5&lt;/span&gt;\n &lt;span class=\"cart-subtotal cart-column\"&gt;0&lt;/span&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div class=\"second-section\"&gt;\n &lt;div class=\"cart-total\"&gt;\n &lt;h2 class=\"section-header summary-title\"&gt;Order Summary&lt;/h2&gt;\n &lt;hr /&gt;\n &lt;div class=\"items-and-total\"&gt;\n &lt;span class=\"items-number\"&gt;0 items&lt;/span&gt;\n &lt;span class=\"cart-total-price\"&gt;0€&lt;/span&gt;\n &lt;/div&gt;\n &lt;hr /&gt;\n &lt;div class=\"final-part\"&gt;\n &lt;hr /&gt;\n &lt;div class=\"items-and-total-final\"&gt;\n &lt;div class=\"cart-total-title\"&gt;Total cost&lt;/div&gt;\n &lt;span class=\"cart-total-price\"&gt;0€&lt;/span&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;button class=\"btn btn-primary\" type=\"button\"&gt;Checkout&lt;/button&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n&lt;/body&gt;\n&lt;script src=\"https://code.jquery.com/jquery-3.5.1.min.js\" integrity=\"sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=\" crossorigin=\"anonymous\"&gt;&lt;/script&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T00:35:19.040", "Id": "251046", "ParentId": "251040", "Score": "3" } } ]
{ "AcceptedAnswerId": "251046", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-22T20:53:16.910", "Id": "251040", "Score": "3", "Tags": [ "javascript", "jquery", "html", "css" ], "Title": "Iterate through multiple elements with different IDs in jQuery" }
251040
<p>I'm working on setting up an app backend that's deployed automatically using infrastructure-as-code and a ci/cd pipeline. As a result of that I need the app server to gather DB credentials automatically. This is my first time working with the AWS Go SDK and I want to get the code as close to production ready as possible.</p> <p>Credentials to use the AWS SDK are set when instances are spun-up so this only needs to set a base parameters for the file root (e.g. <code>/app/db/</code>) and the aws region to connect which are both pulled form a .env file. The sdk is then used to pull encrypted strings from the AWS SSM Parameter Store and use them to write a connection string and connect to the database. I also included a small server that pings the db and tells the user if it's connected.</p> <p>dbConnector.go:</p> <pre><code>package main import ( &quot;context&quot; &quot;time&quot; _ &quot;github.com/jackc/pgx/v4/stdlib&quot; &quot;github.com/jmoiron/sqlx&quot; ) const timeout = 5 // Database abstracts sqlx connection type Database struct{ *sqlx.DB } // ConnectToDB creates a db connection with a predefined timeout func ConnectToDB(ctx context.Context) (*Database, error) { ctx, cancelFn := context.WithTimeout(ctx, timeout*time.Second) defer cancelFn() conn, err := sqlx.ConnectContext(ctx, &quot;pgx&quot;, configString(ctx)) if err != nil { return nil, err } return &amp;Database{conn}, nil } // Connected pings server and returns bool response status func (db *Database) Connected(ctx context.Context) bool { err := db.PingContext(ctx) if err != nil { return false } return true } </code></pre> <p>dbConfig.go:</p> <pre><code>package main import ( &quot;context&quot; &quot;fmt&quot; &quot;log&quot; &quot;strconv&quot; &quot;github.com/spf13/viper&quot; &quot;github.com/aws/aws-sdk-go/aws&quot; &quot;github.com/aws/aws-sdk-go/aws/session&quot; &quot;github.com/aws/aws-sdk-go/service/ssm&quot; ) const ( baseRegion = &quot;AWS_REGION&quot; baseRoot = &quot;AWS_ROOT&quot; baseConfig = &quot;base_config&quot; basePath = &quot;.&quot; ssmHost = &quot;host&quot; ssmDB = &quot;postgres&quot; ssmPort = &quot;port&quot; ssmUser = &quot;user&quot; ssmPassword = &quot;password&quot; ) type awsSSM struct { *ssm.SSM } // Create database connection string based on AWS_ROOT and remote SSM parameters func configString(ctx context.Context) string { loadBaseConfig() sess := session.New() svc := awsSSM{ssm.New(sess, &amp;aws.Config{ Region: aws.String(viper.GetString(baseRegion)), })} configString := fmt.Sprintf(&quot;database=%s host=%s port=%d user=%s password = %s&quot;, ssmDB, svc.param(ctx, ssmHost), atoui(svc.param(ctx, ssmPort)), svc.param(ctx, ssmUser), svc.param(ctx, ssmPassword), ) return configString } // Pull AWS_ROOT and AWS_REGION from .env file, all other config happens on instance spin-up func loadBaseConfig() { viper.SetConfigName(baseConfig) viper.AddConfigPath(basePath) err := viper.ReadInConfig() if err != nil { log.Println(err) } } // Get SSM Parameter with context timeout func (svc *awsSSM) param(ctx context.Context, p string) string { output, err := svc.GetParameterWithContext(ctx, &amp;ssm.GetParameterInput{ Name: aws.String(viper.GetString(baseRoot) + p), WithDecryption: aws.Bool(true), }) if err != nil { log.Println(err) return &quot;&quot; } return aws.StringValue(output.Parameter.Value) } // String to unsigned int16 func atoui(s string) uint16 { n, err := strconv.ParseUint(s, 10, 64) if err != nil { log.Println(err) return 0 } return (uint16)(n) } </code></pre> <p>main.go:</p> <pre><code>package main import ( &quot;context&quot; &quot;fmt&quot; &quot;log&quot; &quot;net/http&quot; &quot;os&quot; &quot;github.com/julienschmidt/httprouter&quot; ) // Server struct for storing database, mux, and logger type Server struct{ db *Database mux *httprouter.Router log *log.Logger } // Create router and environment then serve func main() { s := Server{ log: log.New(os.Stdout, log.Prefix(), log.Flags()), mux: httprouter.New(), } db, err := ConnectToDB(context.Background()) if err != nil { s.log.Println(err) } s.db = db s.mux.GET(&quot;/&quot;, s.index()) log.Fatal(http.ListenAndServe(&quot;:8050&quot;, s.mux)) } // Index is a closure that returns a function that checks the database connection and writes status to user func (s *Server) index() httprouter.Handle { return func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { if s.db.Connected(r.Context()) { fmt.Fprint(w, &quot;Connected!&quot;) } else { http.Error(w, &quot;Error connecting to database&quot;, http.StatusNotFound) s.log.Println(&quot;Error connectiong to database&quot;) } } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-22T22:37:28.950", "Id": "251044", "Score": "1", "Tags": [ "sql", "go", "postgresql", "amazon-web-services" ], "Title": "Golang DB connection with AWS SSM Parameters and context" }
251044
<p>I'm using the Bogus for .NET: C#, F#, and VB.NET library.</p> <p>What would be a more efficient way to generate a list of unique random longs?</p> <pre><code>public IEnumerable&lt;long&gt; GenerateRandomNumbers(int count = 1) { var f = new Faker(); List&lt;long&gt; temporaryList = new List&lt;long&gt;(); for (int i = 0; i &lt; 10000; i++) { var number = f.Random.Long(5000000000, 8000000000); temporaryList.Add(number ); } return temporaryList.Distinct().Take(count).ToList(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T08:30:46.617", "Id": "494011", "Score": "7", "body": "Add them to a `HashSet<long>` and if `Add` returns `false` you know it was a duplicate. That way you can generate the fewest that you need to meet the `count`. If the range were smaller, I'd say add them all to a list, shuffle and then take the first `count` but that's not practical for your range." } ]
[ { "body": "<p>I doubt that algorithmic efficiency can be improved but you may consider an implementation similar to this which leverages idiomatic LINQ.</p>\n<pre><code>public IEnumerable&lt;long&gt; GenerateRandomNumbers()\n{\n var f = new Faker();\n\n return \n Enumerable.Range(0, int.MaxValue)\n .Select(\n _ =&gt; f.Random.Long(5000000000, 8000000000))\n .Distinct();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T05:06:41.040", "Id": "251191", "ParentId": "251052", "Score": "1" } }, { "body": "<p>I have to say that the 10000 iterations loop is both inefficient and incorrect. It always generate 10000 numbers no matter how many you need, so if you need less than 10000 you likely will throw away a good part of them (that's inneficient). And if you request more than 10000, you only get at most 10000 (that's a bug). The actual impact depends on your usage.</p>\n<p>I would suggest to do what's suggested in comments: use a HashSet to store unique numbers and fill it up to until you've reached the count asked for, that way you generate the bare minimum required and nothing more than just to avoid possible duplicates.</p>\n<p>Change it to something like this:</p>\n<pre><code>public IEnumerable&lt;long&gt; GenerateRandomNumbers(int count = 1)\n{\n var f = new Faker();\n //Initialize the HashSet internal size to the final size (note the constructor parameter)\n //This prevents realocations as we add numbers.\n HashSet&lt;long&gt; numbers = new HashSet&lt;long&gt;(count);\n\n //Keep adding numbers until we reach the asked count\n //This ensures that we return no less than requested and we don't generate more numbers than needed\n while (numbers.Count &lt; count)\n {\n var number = f.Random.Long(5000000000, 8000000000);\n //Add the generated number to the HashSet\n //It prevents duplicates and don't adds it if it happens to be a dupe\n //That's why we check the count every time\n numbers.Add(number);\n }\n \n return numbers;\n}\n</code></pre>\n<p>That'll improve its efficiency and fixes the bug.</p>\n<p>But we can still improve it somewhat more, by using another feature of C#, the iterator blocks. By using <code>yield return</code> we only generate numbers as they're consumed by calling code, so if the caller ask for 10 numbers and only iterates over 3 of them, we generate enough random numbers for returning 3, and not 10. This is the very same thing LINQ does all over the place, stream its results. Here is a possible implementation:</p>\n<pre><code>public IEnumerable&lt;long&gt; GenerateRandomNumbers(int count = 1)\n{\n var f = new Faker();\n //We return numbers immediately, but keep track of them only to avoid duplicates\n HashSet&lt;long&gt; numbers = new HashSet&lt;long&gt;(count);\n\n //Only keep returning until we've meet the number asked for\n while (numbers.Count &lt; count)\n {\n var number = f.Random.Long(5000000000, 8000000000);\n //Yield the generated value only if not seen before, we need to know the result of the `Add` operation for this\n bool added = numbers.Add(number);\n if (added) yield return number;\n }\n}\n</code></pre>\n<p>As a small improvement, slightly unrelated to the question, you may want to add the argument validation in the method, so that if a negative count is passed, you immediately error out with an <code>ArgumentOutOfRangeException</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-24T15:55:58.780", "Id": "252601", "ParentId": "251052", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T08:23:22.393", "Id": "251052", "Score": "2", "Tags": [ "c#" ], "Title": "Generating a list of unique random longs" }
251052
<h2>Context</h2> <p>I am following <a href="https://towardsdatascience.com/implementing-neural-machine-translation-with-attention-using-tensorflow-fc9c6f26155f" rel="noreferrer">this tutorial</a> .</p> <p>My mission is to convert an English sentence to a German sentence using Bahdanau Attention.</p> <h2>Summary of the Code</h2> <p>I first took the whole English and German sentence in <code>input_english_sent</code> and <code>input_german_sent</code> respectively. Applied an Embedding Layer on both of them. Passed the <code>input_english_sent</code>, i.e. the whole English sentence, to encoder. And then, I have used a <code>for</code> loop, for implementing decoder with Bahdanau Attention. Inside the <code>for</code> loop, I first take the <code>i</code> word of the whole German Sentence, and declare it as the input to the decoder, i.e. in the first run of the loop, the input to the decoder will be the first word (which is 'start_seq_'), and in the next run, the input would be the second word and so on. And, then in the next lines of the <code>for</code> loop, I compute the Attention and concatenate it with the input of the decoder. And then, in the last line of the <code>for</code> loop, I append the decoder output to an array named <code>final_stage</code>, so that I could apply the <code>Dense()</code> Layer, to predict all the words altogether.</p> <h2>Questions</h2> <p>The code works fine, and it does not produces any error. I just wanna be sure that my implementation is really Bahdanau Attention implementation.</p> <p>The Code inside the <code>for</code> loop has to be checked, as that is the part that implements the Bahdanau attention.</p> <h2>Code</h2> <p>You can ignore all the <code>tf.expand_dims()</code> and <code>tf.reshape()</code> layers as they are just there to avoid any errors regarding shapes.</p> <p>This is my code:</p> <pre><code>input_english_sent = Input(shape=(english_max_len,)) input_german_sent = Input(shape=(german_max_len,)) encoder_inputs = Embedding(english_vocab_size, 256)(input_english_sent) decoder_inputs = Embedding(german_vocab_size, 256)(input_german_sent) encoder = LSTM(256, return_sequences=True, return_state=True) encoder_outputs, encoder_state_h, encoder_state_c = encoder(encoder_inputs) decoder_state_h = encoder_state_h decoder = LSTM(256, return_sequences=True, return_state=True) attention_layer1 = Dense(10) attention_layer2 = Dense(10) final_attention_layer = Dense(1) final_stage = [] for i in range(german_max_len): decoder_input = tf.expand_dims(decoder_inputs[:,i], axis=1) attention_weights = Activation('tanh')(attention_layer1(encoder_outputs) + tf.expand_dims(attention_layer2(decoder_state_h), axis=1)) attention_weights = Activation('softmax')(final_attention_layer(attention_weights)) Context_Vector = encoder_outputs * attention_weights decoder_input = Concatenate(axis=1)([decoder_input, Context_Vector]) decoder_outputs, decoder_state_h, _ = decoder(decoder_input) final_stage.append(Flatten()(decoder_outputs)) output = Dense(german_vocab_size, activation='softmax')(tf.expand_dims(final_stage, axis=1)) output = tf.reshape(output, (-1, german_max_len, german_vocab_size)) model = Model(inputs=[input_english_sent, input_german_sent], outputs=output) </code></pre> <h2>The Entire Code</h2> <pre><code>import string import re from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow.keras.models import Model from tensorflow.keras.layers import Embedding, LSTM, RepeatVector, Dense, Dropout, BatchNormalization, TimeDistributed, AdditiveAttention, Input, Concatenate, Flatten from tensorflow.keras.layers import Activation, LayerNormalization from numpy import array from tensorflow.keras.utils import plot_model from sklearn.utils import shuffle import time import tensorflow as tf import numpy as np def load_data(filename): file = open(filename, 'r') text = file.read() file.close() return text def to_lines(text): return text.split('\n') def clean_data(pair, lang): if lang == 'ger_input': pair = 'start_seq_ ' + pair if lang == 'ger_output': pair = pair + ' end_seq_' if lang == 'ger': pair = 'start_seq_ ' + pair + ' end_seq_' re_print = re.compile('[^%s]' % re.escape(string.printable)) table = str.maketrans('', '', string.punctuation) tokens = [token.translate(table) for token in pair.split()] tokens = [token.lower() for token in tokens] tokens = [re_print.sub('', token) for token in tokens] tokens = [token for token in tokens if token.isalpha()] return tokens lines = to_lines(load_data('/content/drive/My Drive/deu.txt')) english_pair = [] german_pair = [] german_pair_input = [] german_pair_output = [] for line in lines: if line != '': pairs = line.split('\t') english_pair.append(clean_data(pairs[0], 'eng')) german_pair.append(clean_data(pairs[1], 'ger')) german_pair_input.append(clean_data(pairs[1], 'ger_input')) german_pair_output.append(clean_data(pairs[1], 'ger_output')) english_pair = array(english_pair) german_pair = array(german_pair) german_pair_input = array(german_pair_input) german_pair_output = array(german_pair_output) english_pair, german_pair, german_pair_input, german_pair_output = english_pair[-10000:], german_pair[-10000:], german_pair_input[-10000:], german_pair_output[-10000:] def create_tokenizer(data): tokenizer = Tokenizer() tokenizer.fit_on_texts(data) return tokenizer def max_len(lines): length = [] for line in lines: length.append(len(line)) return max(length) english_tokenizer = create_tokenizer(english_pair) german_tokenizer = create_tokenizer(german_pair) english_vocab_size = len(english_tokenizer.word_index) + 1 german_vocab_size = len(german_tokenizer.word_index) + 1 english_max_len = max_len(english_pair) german_max_len = max_len(german_pair) def create_sequences(sequences, tokenizer, max_len): sequences = tokenizer.texts_to_sequences(sequences) sequences = pad_sequences(sequences, maxlen=max_len, padding='post') return sequences X1 = create_sequences(english_pair, english_tokenizer, english_max_len) X2 = create_sequences(german_pair_input, german_tokenizer, german_max_len) Y = create_sequences(german_pair_output, german_tokenizer, german_max_len) X1, X2, Y = shuffle(X1, X2, Y) train_x1, train_x2, train_y = X1[:7000], X2[:7000], Y[:7000] test_x1, test_x2, test_y = X1[7000:], X2[7000:], Y[7000:] train_y, test_y = train_y.reshape(7000, german_max_len, 1), test_y.reshape(3000, german_max_len, 1) </code></pre> <p>And then I implement the Model. The code of implementing the Model is above in the <i>Code Section</i></p> <p>And then I compile the model and train it.</p> <pre><code>model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['acc']) model.fit([train_x1, train_x2], train_y, epochs=10, batch_size=32, validation_data=([test_x1, test_x2], test_y)) </code></pre> <p>Data can be downloaded from <a href="https://raw.githubusercontent.com/jbrownlee/Datasets/master/deu.txt" rel="noreferrer">here</a></p> <p><strong>Note - I have also implemented the teacher forcing method in it</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T13:15:40.933", "Id": "494037", "Score": "2", "body": "Welcome to the Code Review site. The title should state what the code does and not your concerns about the code. The code for any functions that are used in the rest of the code should be presented in the question unless they are standard library functions otherwise there is a lack of code context. The more code presented in the question the better the answers will be because we better understand what the code does. Please read [How do I ask a good question](https://codereview.stackexchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T13:34:47.437", "Id": "494042", "Score": "0", "body": "@pacmaninbw Thanks a lot for editing my question, and making it more clearer. Sorry for the title, as this is my first time on Code Review Site. Should I add more code? As I have written the code of the whole model." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T13:38:45.710", "Id": "494044", "Score": "0", "body": "Questions on code review can contain 64K characters so size is not a major issue. If the code is less than about 400 lines add it, if it is longer add what is necessary." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T13:40:37.337", "Id": "494046", "Score": "1", "body": "First glance there's zero structure to your code and too many magic number/strings. Use functions and variables" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T13:45:45.573", "Id": "494047", "Score": "0", "body": "@Coupcoup By magic numbers, are you referring to the hyperparameters of the model?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T13:49:24.050", "Id": "494049", "Score": "0", "body": "@pacmaninbw The reason I have not added the whole code is because I thought that adding the whole code is not necessary, as the rest of the code is just preparing data, and my question is about the model, so it would be will require less time to read the code of just the model." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T13:52:51.903", "Id": "494051", "Score": "0", "body": "By magic numbers I mean all the numbers and strings hardcoded in. Overall your code looks a copy-pasted jupiter notebook or something, not usable code in any larger program" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T13:56:59.517", "Id": "494052", "Score": "0", "body": "@Coupcoup Thanks a lot for reading the code. I have not used any magic numbers, except the hyperparameters of the model. And the hyperparameters are just a random choice which can be tuned. Sorry if my code looks like a copy-pasted version, but, the whole code is written all by me, and it can be used in any larger program too. Just, the input to the models will be changed. Again, thanks a lot for investing your valuable time in helping me," }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T14:00:36.620", "Id": "494054", "Score": "1", "body": "Generally code review is about improving code ability, checking whether the code follows a particular implementation may not be possible if no one else knows that implementation. Please check the help center like I first suggested, it should answer most of your questions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T11:27:49.963", "Id": "494234", "Score": "0", "body": "Please add the rest of the program as well. I'm missing a lot of definitions and imports here, too many to start a review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T11:44:48.487", "Id": "494241", "Score": "1", "body": "@Mast I have added the entire code, you can see it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T11:51:00.063", "Id": "494243", "Score": "0", "body": "Thank you, much better." } ]
[ { "body": "<h2>File operations</h2>\n<p>This:</p>\n<pre><code>def load_data(filename):\n file = open(filename, 'r')\n text = file.read()\n file.close()\n return text\n</code></pre>\n<p>is such a common and simple operation that it doesn't deserve to be a function. This doesn't lend you anything that you can't already do with <code>open(filename).read()</code>. Even if it were to remain, it should use <code>with</code> instead of an explicit <code>close()</code>, and <code>filename</code> should be marked <code>: str</code>.</p>\n<p>It's also not a good idea to separate <code>load_data</code> and <code>to_lines</code>. When you get an open file handle, it's already an iterator over the file's lines, and using it as such is more efficient than loading the entire file into memory. So <code>to_lines</code> doesn't deserve to be a function, either.</p>\n<h2>Data cleaning</h2>\n<p><code>lang</code> captures two-ish things, in a somewhat awkward way:</p>\n<ul>\n<li>What is the language? This should be a string, and should use ISO-639-1 codes (&quot;en&quot;) which are more common than ISO-639-2 or -3 codes (&quot;eng&quot;).</li>\n<li>Is this the end of a sequence? This should be a <code>bool</code>.</li>\n<li>Is this the start of a sequence? This should also be a <code>bool</code>.</li>\n</ul>\n<h2>Regex pre-compilation</h2>\n<pre><code>re_print = re.compile('[^%s]' % re.escape(string.printable))\n</code></pre>\n<p>should not appear within <code>clean_data</code>. The entire purpose of Python exposing the <code>compile</code> method is to support pre-compilation, where this would be performed typically at the global scope, only once. Otherwise, there's no advantage to doing this over a direct <code>re.sub()</code>.</p>\n<h2>Successive list formation</h2>\n<p>If you really want to separate this into multiple statements:</p>\n<pre><code>tokens = [token.translate(table) for token in pair.split()]\ntokens = [token.lower() for token in tokens]\ntokens = [re_print.sub('', token) for token in tokens]\ntokens = [token for token in tokens if token.isalpha()]\n</code></pre>\n<p>you can, but this isn't the best way. To avoid re-re-recreating the list, simply</p>\n<pre><code>for token in pair.split():\n token = token.translate(table)\n token = token.lower()\n # ...\n yield token\n</code></pre>\n<p>Or otherwise, a two-pass approach in &quot;fluent&quot; style:</p>\n<pre><code>tokens = (\n re_print.sub(\n '',\n token.translate(table)\n .lower()\n )\n for token in pair.split()\n)\n</code></pre>\n<p>with a second pass for <code>isalpha</code>.</p>\n<h2><code>max</code> on a generator</h2>\n<pre><code>length = []\nfor line in lines:\n length.append(len(line))\nreturn max(length)\n</code></pre>\n<p>should be</p>\n<pre><code>return max(len(line) for line in lines)\n</code></pre>\n<p>or even better (thanks @hjpotter92)</p>\n<pre><code>return len(max(lines, key=len))\n</code></pre>\n<p>No intermediate list is needed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T02:19:17.980", "Id": "494610", "Score": "0", "body": "`max(map(len, lines))` is more efficient than `max(len(line) for line in lines)` but a bit less readable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T03:48:27.843", "Id": "494613", "Score": "1", "body": "Thanks a lot for your answer. _The Code inside the for loop has to be checked, as that is the part that implements the Bahdanau attention._ I wrote this in the _question_ section. All the other code that I wrote may not be the most efficient code, but it works fine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T19:44:20.430", "Id": "494684", "Score": "0", "body": "It's fine that it works fine. CR expects that _all_ of your code works fine, and all code submitted is open to review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-30T19:37:09.050", "Id": "494775", "Score": "2", "body": "@GZ0 `max(lines, key=len)` :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-30T19:42:49.130", "Id": "494777", "Score": "0", "body": "@NITINAGARWAL also, most of the work inside the for loop is to call `clean_data`, which is unoptimised currently due to regex compilation on each call along with other points already raised in this reply." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-30T19:47:00.683", "Id": "494778", "Score": "1", "body": "@hjpotter92 Close but not quite. With `max` and a `key`, you end up with the item whose length is maximal; we're actually looking for the maximal length." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T01:12:41.340", "Id": "251283", "ParentId": "251056", "Score": "2" } }, { "body": "<p>Had a quick look and I can see there are some foundamental issues of the model implementation besides the problems mentioned in other answer(s) and comment(s).</p>\n<ul>\n<li><p>The German sentences should not be the decoder input. They are analogous to 'labels' of training data in classification tasks, which are not available for testing &amp; future data. Therefore it does not make sense to feed them into the model. They should only be used to calculate loss values during training and evaluation.</p>\n</li>\n<li><p>It is incorrect to apply the same decoder sequence to the inputs <code>german_max_len</code> times in the loop. A correct implementation should go cell by cell, feeding the output of the each cell to the next cell as part of its input. Here you need to create <code>LSTMCell</code>s and chain them together with customized inputs, rather than utilizing an entire <code>LSTM</code> sequence (technically, an <code>LSTM</code> with sequence length = 1 can also be used as a single cell, but <code>LSTMCell</code> serves better for that purpose).</p>\n</li>\n<li><p>It would be better to wrap the attention-enabled decoder into a customized layer so that the code is better structured and can be reused conveniently.</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-01T15:15:10.960", "Id": "251426", "ParentId": "251056", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T11:51:41.660", "Id": "251056", "Score": "10", "Tags": [ "python", "machine-learning", "tensorflow", "keras" ], "Title": "Convert an English sentence to German using Bahdanau Attention" }
251056
<p>I've been trying out React for a couple of days and I tried to build a button component with some conditionals. Everything works but I feel like I am not doing it the right way.</p> <p>Could anyone review my code and give me some advice and tell me what I am doing wrong or what i could do better. I think I am using too many return statements.</p> <p>I use Typescript for type checking.</p> <p>Would appreciate any help!</p> <pre><code>import { Link } from &quot;gatsby&quot;; interface Props { content: string, color: string, path?: string, type?: string } export default function Button(props: Props): JSX.Element { let elementType; const checkProps = () =&gt; { const availableColors = ['blue', 'grey', 'dark-grey', 'white']; const borderColors = ['']; let buttonStyle; // Check if props.color exists in availableColors if(!availableColors.includes(props.color)) { console.error(`&quot;${props.color} color key not available for button style`); return; } buttonStyle = buttonStyles[`button--${props.color}`]; // Check if props.content is valid if(!props.content) { console.error(`&quot;${props.content} is not valid as content`); return; } // Check if props.type exists if(!props.type) { elementType = &lt;button className={ buttonStyle }&gt;{ props.content }&lt;/button&gt; return; } if(props.type !== 'link') { console.error(`&quot;${props.type} is not a valid type, use 'link' instead or use nothing for default button`); return; } else { elementType = &lt;Link to={ props.path } className={ buttonStyle }&gt;{ props.content }&lt;/Link&gt; } } checkProps(); return ( &lt;React.Fragment&gt; { elementType } &lt;/React.Fragment&gt; ); }``` </code></pre>
[]
[ { "body": "<p><strong>Narrow types with TypeScript instead of erroring</strong> There are many places in the code where you check a condition based on how the Button is being called, and if it isn't fulfilled, you log an error and return nothing. This is a reasonable approach in JavaScript, but in TypeScript, you have a much better option, which is to use types to require <em>only certain</em> arguments. This way, rather than an error being thrown at runtime, an error will be thrown by TypeScript at compile-time when a user of <code>Button</code> attempts to pass props that aren't valid. Turning typos / accidental incorrect function calls into compile-time errors is one of the greatest advantages of TypeScript, and it's great that you're using TypeScript already, so go ahead and take advantage of it.</p>\n<p>For example, rather than:</p>\n<pre><code>const availableColors = ['blue', 'grey', 'dark-grey', 'white'];\nconst borderColors = [''];\nlet buttonStyle;\n\n// Check if props.color exists in availableColors\nif(!availableColors.includes(props.color)) {\n console.error(`&quot;${props.color} color key not available for button style`);\n return;\n}\n</code></pre>\n<p>You can make <code>availableColors</code> as a <em>type</em> instead, and require that the <code>color</code> prop matches it:</p>\n<p><code>'blue' | 'grey' | 'dark-grey' | 'white'</code></p>\n<p>Similarly, rather than</p>\n<pre><code>if(!props.content) {\n console.error(`&quot;${props.content} is not valid as content`);\n</code></pre>\n<p>you can require that the <code>content</code> property is of type:</p>\n<pre><code>T &amp; (T extends '' ? 'Content must not be empty' : {})\n</code></pre>\n<p>and instead of</p>\n<pre><code>if(props.type !== 'link') {\n</code></pre>\n<p>require a <code>type</code> of <code>'link' | ''</code> exactly.</p>\n<p>Using the above methods will also let you declare <code>buttonStyle</code> and <code>elementType</code> with <code>const</code> - or you could even inline their values into the props.</p>\n<p><strong>Default export?</strong> You have:</p>\n<pre><code>export default function Button\n</code></pre>\n<p>This will mean that the imported button is not really tied to its <code>Button</code> name anymore. For example, it would be easy for someone to initially type:</p>\n<pre><code>import button from './Button';\n</code></pre>\n<p>only to run into problems since they forgot to capitalize it. Using named exports makes these sorts of typos more difficult, because one has to <em>intentionally</em> rename it to get something other than Button:</p>\n<pre><code>// Natural import\nimport { Button } from './Button';\n</code></pre>\n<p>or</p>\n<pre><code>// Deliberate renaming\nimport { Button as RenamedVariableName } from './Button';\n</code></pre>\n<p><strong>Destructure immediately</strong> Rather than referencing <code>props</code> multiple times in the function body, you might consider extracting the properties from the props immediately in the function definition - it makes the logic later less noisy.</p>\n<p><strong>Let TS infer types when possible</strong> There's no need to note that a function returns a particular type if</p>\n<ul>\n<li>TypeScript can already infer the type automatically, and</li>\n<li>The type is obvious to a reader of a code at a glance</li>\n</ul>\n<p>So, you may consider removing the <code>JSX.Element</code> from <code>(props: Props): JSX.Element</code>.</p>\n<p><strong><code>buttonStyles</code>?</strong> It sounds like <code>buttonStyles</code> is an object that contains strings, where the strings are class names. So <code>buttonStyles</code> isn't a very precise variable name - it doesn't contain <em>styles</em>, it contains <em>class names</em>. Maybe instead call it <code>buttonClassNamesByColor</code>?</p>\n<p><strong>Fragments</strong> In newer versions of React, you may use <code>&lt;&gt;</code> and <code>&lt;/&gt;</code> instead of <code>&lt;React.Fragment&gt;</code> <code>&lt;/React.Fragment&gt;</code>. Or, even better, since you're returning <em>only a single JSX element</em> regardless, you can use the conditional operator to return either one or the other element, without wrapping everything in a fragment.</p>\n<pre><code>export const Button = &lt;T extends string&gt;({\n content,\n color,\n path,\n type,\n}: {\n content: T &amp; (T extends '' ? 'Content must not be empty' : {});\n color: 'blue' | 'grey' | 'dark-grey' | 'white';\n path?: string;\n type: '' | 'link';\n}) =&gt; {\n const buttonClassName = buttonClassNamesByColor[`button--${color}`];\n return type === ''\n ? &lt;button className={buttonClassName}&gt;{content}&lt;/button&gt;\n : &lt;Link to={path} className={buttonClassName}&gt;{content}&lt;/Link&gt;;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T14:16:45.553", "Id": "251061", "ParentId": "251058", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T12:15:38.890", "Id": "251058", "Score": "3", "Tags": [ "react.js", "typescript", "jsx" ], "Title": "How can I re-write the conditionals for this button" }
251058
<p>Sometimes you need to do things when a condition changes, here is a simple class to keep track of the state of the last call and execute callbacks when the state changes.</p> <pre><code> #include &lt;functional&gt; #include &lt;cassert&gt; /// latch is a class that contains of a test function and a couple of callbacks, when the return /// value of the test function changes the approrpiate callback gets called, as long as the return /// value of the test function stays the same no callbacks will be called. Callbacks may be nullptr template&lt;class...Args&gt; class Latch { public: Latch(std::function&lt;bool(Args ...)&gt; shouldLatch, std::function&lt;void(Args...)&gt; onLatch = nullptr, std::function&lt;void(Args...)&gt; onUnlatch = nullptr) : m_shouldLatch(std::move(shouldLatch)), m_onLatch(std::move(onLatch)), m_onUnlatch(std::move(onUnlatch)) {} bool latched() const noexcept { return m_isLatched; } explicit operator bool() const noexcept { return m_isLatched; } void update(Args&amp;&amp; ... args) { if (m_shouldLatch &amp;&amp; m_isLatched != m_shouldLatch(std::forward&lt;Args&gt;(args)... )) { m_isLatched = !m_isLatched; auto&amp; call = (m_isLatched) ? m_onLatch : m_onUnlatch; if (call) call(std::forward&lt;Args&gt;(args)...); } } private: bool m_isLatched = false; std::function&lt;bool(Args ...)&gt; m_shouldLatch; std::function&lt;void(Args ...)&gt; m_onLatch; std::function&lt;void(Args ...)&gt; m_onUnlatch; }; int main() { int onLatch = 0; int onUnlatch = 0; int latchVal = 1; Latch&lt;int&gt; l1([&amp;latchVal](auto val){return val == latchVal;}, [&amp;onLatch](auto val){++onLatch;}, [&amp;onUnlatch](auto val){++onUnlatch;}); assert(!l1); l1.update(0); assert(!l1); assert(onLatch == 0 &amp;&amp; onUnlatch == 0); l1.update(1); assert(l1.latched()); assert(onLatch == 1 &amp;&amp; onUnlatch == 0); l1.update(1); assert(onLatch == 1 &amp;&amp; onUnlatch == 0); l1.update(0); assert(onLatch == 1 &amp;&amp; onUnlatch == 1); Latch l2 = l1; } </code></pre> <p>This is also at <a href="https://www.godbolt.org/z/z4b934" rel="nofollow noreferrer">https://www.godbolt.org/z/z4b934</a></p> <p>Thanks for the input</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T16:18:03.513", "Id": "494070", "Score": "2", "body": "What are you looking to improve?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T21:59:08.970", "Id": "494200", "Score": "0", "body": "Wasn’t looking for any specifics, just a general review. checking the use of variable template arguments and forwarding for example." } ]
[ { "body": "<p>There is not much to improve in my opinion, except:</p>\n<h1>Unnecessary use of <code>std::move()</code></h1>\n<p>You are passing <code>shouldLatch</code>, <code>onLatch</code> and <code>onUnlatch</code> by value to the constructor, so there is no reason to use <code>std::move()</code> in the member initializer list.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T21:00:17.953", "Id": "251074", "ParentId": "251059", "Score": "3" } } ]
{ "AcceptedAnswerId": "251074", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T12:21:21.857", "Id": "251059", "Score": "3", "Tags": [ "c++", "c++17" ], "Title": "Simple Boolean \"Latch\" with state" }
251059
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/251021/231235">A TransformAll Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>. The following code is the improved version based on <a href="https://codereview.stackexchange.com/a/251041/231235">G. Sliepen's answer</a>. In order to match the conventions of the STL, the function named <code>recursive_transform</code> here uses the <code>is_iterable</code> concept and the <code>is_element_iterable</code> concept. Moreover, the copy operation of the input is avoided by updating <code>[_Func](auto element)-&gt;auto</code> into <code>[_Func](auto&amp; element)</code> and the redundant part in this lambda function <code>-&gt;auto</code> has been removed. Although the code is improved, I found that there are some cases which the previous version <code>TransformAll</code> function is hard to deal with. One of those cases is the nested iterable ranges with <code>std::variant</code>. I want to focus on this case, such as <code>std::vector&lt;std::variant&lt;long double&gt;&gt;</code>. First of all, the additional concept <code>is_element_variant</code> is included for determining the type of elements in iterable container is <code>std::variant</code> or not. I think there may be another better implementation to this <code>is_element_variant</code> concept. However, the method I surveyed <a href="https://stackoverflow.com/q/57134521/6667035">How to check if template argument is std::variant?</a> isn't deal with this with c++-concepts. I prefer to work with concept here and the experimental code is as below. If there is any suggestion about how to improve this <code>is_element_variant</code> concept, please let me know.</p> <pre><code>template&lt;typename T&gt; concept is_element_variant = requires(T x) { x.begin()-&gt;index(); x.begin()-&gt;valueless_by_exception(); }; </code></pre> <p>The part of the template function <code>recursive_transform</code> which handle the <code>std::variant</code> structure:</p> <pre><code>template&lt;class T, class _Fn&gt; requires is_iterable&lt;T&gt; &amp;&amp; is_element_variant&lt;T&gt; static T recursive_transform(const T _input, _Fn _Func); // Deal with the iterable case which its element is std::variant template&lt;class T, class _Fn&gt; requires is_iterable&lt;T&gt; &amp;&amp; is_element_variant&lt;T&gt; static inline T recursive_transform(const T _input, _Fn _Func) { T returnObject = _input; std::transform(_input.begin(), _input.end(), returnObject.begin(), [_Func](typename std::iterator_traits&lt;typename T::iterator&gt;::value_type x)-&gt; typename std::iterator_traits&lt;typename T::iterator&gt;::value_type { return std::visit([_Func](auto&amp;&amp; arg) -&gt; typename std::iterator_traits&lt;typename T::iterator&gt;::value_type { return _Func(arg); }, x); }); return returnObject; } </code></pre> <p>The other parts:</p> <pre><code>template&lt;typename T&gt; concept is_iterable = requires(T x) { x.begin(); // must have `x.begin()` x.end(); // and `x.end()` }; template&lt;typename T&gt; concept is_element_iterable = requires(T x) { x.begin()-&gt;begin(); x.end()-&gt;end(); }; template&lt;class T, class _Fn&gt; requires is_iterable&lt;T&gt; static T recursive_transform(const T _input, _Fn _Func); // Deal with the iterable case like &quot;std::vector&lt;long double&gt;&quot; template&lt;class T, class _Fn&gt; requires is_iterable&lt;T&gt; static inline T recursive_transform(const T _input, _Fn _Func) { T returnObject = _input; std::transform(_input.begin(), _input.end(), returnObject.begin(), _Func); return returnObject; } template&lt;class T, class _Fn&gt; requires is_iterable&lt;T&gt; &amp;&amp; is_element_iterable&lt;T&gt; static T recursive_transform(const T _input, _Fn _Func); template&lt;class T, class _Fn&gt; requires is_iterable&lt;T&gt; &amp;&amp; is_element_iterable&lt;T&gt; static inline T recursive_transform(const T _input, _Fn _Func) { T returnObject = _input; std::transform(_input.begin(), _input.end(), returnObject.begin(), [_Func](auto&amp; element) { return recursive_transform(element, _Func); } ); return returnObject; } int main() { std::vector&lt;long double&gt; testVector1; testVector1.push_back(1); testVector1.push_back(20); testVector1.push_back(-100); std::cout &lt;&lt; recursive_transform(testVector1, [](long double x)-&gt;long double { return x + 1; }).at(0) &lt;&lt; std::endl; std::vector&lt;long double&gt; testVector2; testVector2.push_back(10); testVector2.push_back(90); testVector2.push_back(-30); std::vector&lt;std::vector&lt;long double&gt;&gt; testVector3; testVector3.push_back(testVector1); testVector3.push_back(testVector2); std::cout &lt;&lt; recursive_transform(testVector3, [](long double x)-&gt;long double { return x + 1; }).at(1).at(1) &lt;&lt; std::endl; std::vector&lt;std::variant&lt;long double&gt;&gt; testVector4; testVector4.push_back(1); testVector4.push_back(20); testVector4.push_back(-100); auto operation_to_element = [](long double number) { return number + 2; }; std::visit([](auto&amp;&amp; arg) {std::cout &lt;&lt; arg; }, // For printing recursive_transform(testVector4, operation_to_element).at(0) ); return 0; } </code></pre> <p>All suggestions are welcome.</p> <p>The summary information:</p> <ul> <li><p>Which question it is a follow-up to?</p> <p><a href="https://codereview.stackexchange.com/q/251021/231235">A TransformAll Function For Various Type Arbitrary Nested Iterable Implementation in C++</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <ul> <li>Rename function to <code>recursive_transform</code> to match the conventions of the STL.</li> <li>The copy operation of the input is avoided by updating <code>auto &amp;element</code>.</li> <li>Remove the redundant part in lambda function <code>-&gt;auto</code></li> </ul> </li> <li><p>Why a new review is being asked for?</p> <p>I think the concept <code>is_element_variant</code> may be improved and I am looking forward to any suggestion for possible improvement ways. Moreover, in my opinion of the part of the template function <code>recursive_transform</code> which handle the <code>std::variant</code> structure, implementation here is complex, there are two nested lambda function. If there is any possible to simplify this, please let me know.</p> </li> </ul>
[]
[ { "body": "<p>You are now making your algorithms more specialized again. Personally, I would avoid this and leave recursively transforming up to <code>recursive_transform()</code>, and handling visiting the variant up to the caller. Perhaps there are ways to make it easier for the caller to do this, but in this answer I'll just comment on your implementation.</p>\n<h1>Be as precise as possible with your concepts</h1>\n<p>The concepts you are using should test exactly that which you need. In your code, you are not calling <code>index()</code> nor <code>valueless_by_exception()</code>, so this should not be tested for in the concepts you require. Instead, what you need to test for is whether you can call <code>std::visit()</code> on an element, like so:</p>\n<pre><code>template&lt;typename T&gt;\nconcept is_element_visitable = requires(T x)\n{\n std::visit([](auto){}, *x.begin());\n};\n</code></pre>\n<h1>Simplify the way you write types</h1>\n<p>Use <code>auto</code> and <code>decltype()</code> where applicable to avoid writing types in a roundabout way. This also has the advantage that you are not requiring that there are proper <code>iterator_traits</code> and other type aliases defined for the containers that might be used. For example:</p>\n<pre><code>template&lt;class T, class Fn&gt; requires is_iterable&lt;T&gt; &amp;&amp; is_element_visitable&lt;T&gt;\nstatic inline T recursive_transform(const T input, Fn func)\n{\n T result = input;\n \n std::transform(input.begin(), input.end(), result.begin(), \n [func](auto x) -&gt; decltype(x) {\n return std::visit([_Func](auto&amp;&amp; arg) -&gt; decltype(x) {\n return func(arg);\n }, x);\n }\n );\n\n return result;\n}\n</code></pre>\n<p>There is no need to explicitly specify the type of <code>x</code>, at best it is the same as the type of argument it gets passed, at worst you make a mistake that compiles without errors but causes some subtle cast. And since you want to return a value that has the same type as <code>x</code> (so that we cast the result of <code>func()</code> back to a <code>std::variant</code>, just write <code>-&gt; decltype(x)</code> as the trailing return type. You can do the same for the trailing return type of the lambda passed to <code>std::visit()</code>.</p>\n<p>Well, that would be true, except the above example is only so compact because you are copying by value, which leads me to:</p>\n<h1>Avoid unnecessary copies</h1>\n<p>I missed this in my previous review, but there are more places where you cause a copy to be made: anytime a function takes a parameter by value, it is copied. So to avoid the costly copies of large containers, be sure to pass the inputs as much as possible by <code>const</code> <em>reference</em>, both for the templated function parameters and for the parameters passed to the lambda functions.</p>\n<p>Now we need a way to ensure the trailing return types don't become references. To do this, you can use <a href=\"https://en.cppreference.com/w/cpp/types/remove_reference\" rel=\"nofollow noreferrer\"><code>std::remove_reference</code></a>. It becomes a bit messier, so I would use a <code>using</code> declaration:</p>\n<pre><code>template&lt;class T, class Fn&gt; requires is_iterable&lt;T&gt; &amp;&amp; is_element_visitable&lt;T&gt;\nstatic inline T recursive_transform(const T &amp;input, Fn func)\n{\n using value_type = std::remove_reference&lt;decltype(*input.begin())&gt;::type;\n T result = input;\n \n std::transform(input.begin(), input.end(), result.begin(), \n [func](const auto &amp;x) -&gt; value_type {\n return std::visit([_Func](auto&amp;&amp; arg) -&gt; value_type {\n return func(arg);\n }, x);\n }\n );\n\n return result;\n}\n</code></pre>\n<h1>Remove redundant forward declarations</h1>\n<p>Every template definition is preceded by a forward declaration. In general, you should avoid unnecessary forward declarations, as it is repeating yourself and allows for accidental differences in the forward declaration and the actual definition. This is much more important for templates, because there the chance of the compiler noticing a conflict is much smaller.</p>\n<h1>Don't use <code>long double</code> unless you really need that extra precision</h1>\n<p>I see you use <code>long double</code> consistently in your code, but if you don't need the extra precision it <em>might</em> have over a <code>double</code>, that you probably pay the price in lower performance. The reason is that on x86 and x86_64, <code>long double</code> operations can only be done with <a href=\"https://en.wikipedia.org/wiki/X87\" rel=\"nofollow noreferrer\">x87 FPU</a> registers and instructions, and not with SSE registers and instructions. There is also a large overhead storing <code>long double</code>s.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T20:33:38.693", "Id": "251072", "ParentId": "251060", "Score": "2" } } ]
{ "AcceptedAnswerId": "251072", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T13:15:49.313", "Id": "251060", "Score": "2", "Tags": [ "c++", "recursion", "lambda", "c++20" ], "Title": "A recursive_transform Function For Various Type Nested Iterable With std::variant Implementation in C++" }
251060
<p>Before anyone marks this as <a href="https://codereview.stackexchange.com/questions/173338/calculate-mean-median-and-mode-in-rust">duplicate</a>, my question is only towards the median, and my approach is different from what the answer suggested. On getting the mode from a vector of values, I have the below:</p> <pre class="lang-rust prettyprint-override"><code>fn get_mode(list_of_numbers: &amp;[i32]) -&gt; i32 { // most common occurrence of item from vector use std::collections::HashMap; //* using structs.More readable struct Mode { number: i32, frequency: u32, }; let mut occurence = HashMap::new(); let mut most_common: Mode = Mode { number: 0, frequency: 0, }; for number in list_of_numbers { let count = occurence.entry(number).or_insert(0); *count += 1; } for (&amp;key, val) in occurence { if val &gt; most_common.frequency { most_common = Mode { number: key, frequency: val, }; } } most_common.number } </code></pre> <p>For readability, the function uses a <code>struct</code>. My question comes down to :</p> <pre class="lang-rust prettyprint-override"><code> for (&amp;key, val) in occurence { </code></pre> <p>Why can't I borrow the value <code>val</code> from the HashMap given <strong>I might as well be passing the values and keys to another function</strong> in this loop? The error when I try:</p> <pre class="lang-rust prettyprint-override"><code>for (&amp;key, &amp;val) in occurence { </code></pre> <p>would be : <code>expected integer, found reference</code>. How come?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T17:44:15.483", "Id": "494088", "Score": "0", "body": "Welcome to the Code Review site where we review code that is working as expected, if the code is resulting in errors than the question is off-topic for this site." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T17:52:26.297", "Id": "494090", "Score": "0", "body": "The code @pacmaninbw works. My question is why it would not work if the borrowing happened." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T16:05:31.640", "Id": "251063", "Score": "1", "Tags": [ "rust", "statistics", "scope" ], "Title": "Get mode of elements in a vector with rust - For loop borrowing and referencing" }
251063
<p>Anyone here who uses Python for solving bioinformatics problems. This is the code I have written for counting the number of k-mers like monomers, dimers to hexamers from the fasta file. You just have to give the ncbi accession number for the fasta sequence and then it counts the number of k-mers. If you've time, please check the code as I think it's a bit long one and I have used try/except for solving IndexError. Your suggestions would be valuable. Thanks.</p> <pre><code> from Bio import Entrez Entrez.email = 'roshanpra@gmail.com' monomers = list('ATGC') dimers = [] for i in monomers: for j in monomers: dimers.append(i+j) trimers = [] for i in monomers: for j in monomers: for k in monomers: trimers.append(i+j+k) tetramers = [] for i in monomers: for j in monomers: for k in monomers: for l in monomers: tetramers.append(i+j+k+l) pentamers = [] for i in monomers: for j in monomers: for k in monomers: for l in monomers: for m in monomers: pentamers.append(i+j+k+l+m) hexamers = [] for i in monomers: for j in monomers: for k in monomers: for l in monomers: for m in monomers: for n in monomers: hexamers.append(i+j+k+l+m+n) file = input('Enter the ncbi accession number: ') handle = Entrez.efetch(db = 'nucleotide', id = file,rettype=&quot;fasta&quot;, retmode=&quot;text&quot;) record = handle.read() fasta_string = ''.join(record.split('\n')[1:]) k = int(input('Enter the value of k: ')) print('The sequence is',fasta_string) fasta_list = [] if k == 1: a = True while a: try: for i in range(0,len(fasta_string),1): fasta_list.append(fasta_string[i]) except: break a = False for i in monomers: print('count of' ,i, 'is' , fasta_list.count(i)) elif k == 2: a = True while a: try: for i in range(0,len(fasta_string),2): fasta_list.append(fasta_string[i]+fasta_string[i+1]) except: break a = False for i in dimers: print('count of' ,i, 'is' , fasta_list.count(i)) elif k == 3: a = True while a: try: for i in range(0,len(fasta_string),3): fasta_list.append(fasta_string[i]+fasta_string[i+1]+fasta_string[i+2]) except: break a = False for i in trimers: print('count of' ,i, 'is' , fasta_list.count(i)) elif k == 4: a = True while a: try: for i in range(0,len(fasta_string),4): fasta_list.append(fasta_string[i]+fasta_string[i+1]+fasta_string[i+2]+fasta_string[i+3]) except: break a = False for i in tetramers: print('count of' ,i, 'is' , fasta_list.count(i)) elif k == 5: a = True while a: try: for i in range(0,len(fasta_string),5): fasta_list.append(fasta_string[i]+fasta_string[i+1]+fasta_string[i+2]+fasta_string[i+3]+fasta_string[i+4]) except: break a = False for i in pentamers: print('count of' ,i, 'is' , fasta_list.count(i)) elif k == 6: a = True while a: try: for i in range(0,len(fasta_string),6): fasta_list.append(fasta_string[i]+fasta_string[i+1]+fasta_string[i+2]+fasta_string[i+3]+fasta_string[i+4]+fasta_string[i+5]) except: break a = False for i in hexamers: print('count of' ,i, 'is' , fasta_list.count(i)) Counting the number of k-mers like monomers, dimers to hexamers from the fasta file </code></pre>
[]
[ { "body": "<p>The code can be simplified quite a bit.</p>\n<p>Using <code>itertools.product</code>, the code like this:</p>\n<pre><code>trimers = []\n for i in monomers:\n for j in monomers:\n for k in monomers:\n trimers.append(i+j+k)\n</code></pre>\n<p>can be reduced to:</p>\n<pre><code>k_mers = list(''.join(t) for t in itertools.product('ACGT', repeat=k))\n</code></pre>\n<p>A common Python idiom for grouping a sequence is</p>\n<pre><code>zip(*[iter(sequence)]*k)\n</code></pre>\n<p>it generates k-tuples from the sequence. Which can be counted using a <code>collections.Counter</code>. So this code:</p>\n<pre><code>a = True\nwhile a:\n try:\n for i in range(0,len(fasta_string),3):\n fasta_list.append(fasta_string[i]+fasta_string[i+1]+fasta_string[i+2])\n\n except:\n break\n a = False\nfor i in trimers:\n print('count of' ,i, 'is' , fasta_list.count(i))\n</code></pre>\n<p>can be simplified to:</p>\n<pre><code>counts = Counter(''.join(t) for t in zip(*[iter(fasta_string)]*k))\n</code></pre>\n<p>The code asks for <code>k</code>, so it doesn't make sense to generate all the other k-mers.</p>\n<p>The final code could look like:</p>\n<pre><code>from collections import Counter\nfrom itertools import product\n\nfile = input('Enter the ncbi accession number: ')\nk = int(input('Enter the value of k: '))\n\nhandle = Entrez.efetch(db = 'nucleotide', id = file,rettype=&quot;fasta&quot;, retmode=&quot;text&quot;)\nrecord = handle.read()\nfasta_string = ''.join(record.split('\\n')[1:])\n\nprint('The sequence is',fasta_string)\n\ncounts = Counter(''.join(t) for t in zip(*[iter(fasta_string)]*k))\n\nfor k_mer in (''.join(t) for t in itertools.product('ACGT', repeat=k)):\n print(f&quot;count of {k_mer} is {counts[k_mer]}&quot;)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T01:36:31.453", "Id": "251076", "ParentId": "251068", "Score": "5" } }, { "body": "<h1>A Quick Preface</h1>\n<p>A <em>monomer</em> can mean different things in different contexts; it's just a way of referring to the most relevant &quot;unit&quot; element of the current context. This usually means amino acids when you're doing sequence alignments, but I suppose it could also mean nucleotides<sup>1</sup>, although I've never seen that myself.</p>\n<p>If you have a FASTA file with the base pairs, though, you're usually<sup>2</sup> trying to parse the order and type of the <a href=\"https://en.wikipedia.org/wiki/DNA_codon_table\" rel=\"nofollow noreferrer\" title=\"DNA Codon Table - Wikipedia\">codons</a> in the sequence. From there, you either compare the sequence against others to determine the impact of mutations. Some mutations might be harmless, since different base codons sometimes code for the same amino acid, but others can be extremely problematic, to say the least. For example, a deletion or an insertion can cause a <a href=\"https://en.wikipedia.org/wiki/Frameshift_mutation\" rel=\"nofollow noreferrer\" title=\"Frameshift Mutation - Wikipedia\">frameshift</a>, moving the entire sequence forward or backwards.</p>\n<p>There are two reasons I bring this up. First, I think calling each base a <em>k-mer</em> will be confusing to researchers expecting a monomer to represent codons/amino acids. Second, since codons are three bases long, searching for all substrings of a length that isn't a multiple of three won't be very helpful.</p>\n<p>The key point is that the counts of each substring of length three aren't really what matters. Each of these substrings is called a codon, which in turn represents an amino acid or stop command; it's the combination of multiple amino acids in a particular order that result in the production of a specific protein.</p>\n<p>The last point I want to make about the code before providing feedback on the actual code itself is that if you limit your search to only substrings of length 3, you could implement the parsing mechanism as a <a href=\"https://en.wikipedia.org/wiki/Deterministic_finite_automaton\" rel=\"nofollow noreferrer\" title=\"DFA - Wikipedia\">deterministic finite automaton</a>. There are only twenty-two amino acids and three stop codons, so writing a <a href=\"https://en.wikipedia.org/wiki/State-transition_table\" rel=\"nofollow noreferrer\" title=\"State Transition Table - Wikipedia\">state transition table</a> wouldn't take too long, and it would reduce the runtime complexity of the parsing the sequence to <span class=\"math-container\">\\$O\\left(n\\right)\\$</span>, since it would depend only on how long the single pass takes, which itself is a factor of only the length of the input sequence.</p>\n<p>Anyways, on to the actual review.</p>\n<hr />\n<h1>Recommendations</h1>\n<p>The following recommendations are focused on your actual code, not the suggestions made above.</p>\n<h2>Defer the Preprocessing</h2>\n<p>Since you are searching for only one kind of <span class=\"math-container\">\\$k\\$</span>-mer, but you don't know the value of <span class=\"math-container\">\\$k\\$</span> until the user chooses, I would suggest creating all of the possible permutations of length <span class=\"math-container\">\\$k\\$</span> <em>beforehand</em> is a waste of effort.</p>\n<h2>Don't Print the Sequence</h2>\n<p>FASTA files can be ginormous (meaning several Gigabytes long), so printing the sequence is not very practical, since it would take both a ton of time and a ton of memory.</p>\n<p>It also isn't super useful, since no one is going to be checking all several Gigabytes of the sequence to make sure it's the right one. Certainly not while it's scrolling by in the console at lightspeed. The user selected the sequence by its sequence number, so I would assume they know what sequence they wanted.</p>\n<h2>Use argparse Instead of Standard Input</h2>\n<p>Bioinformatics happens on the central supercomputer, not the researchers' computers a lot of the time. Since you can't interact with the program as its running (you usually submit a slurm request via a bash script with the execution parameters), you're better off relying on the <code>argv</code> contents so the script execution can be defined when the request is submitted.</p>\n<p>You could also define the input using a redirection operator, but I like the argparse route better, although this really is just a personal preference. It seems less &quot;clean&quot; to me, but if it works, it works.</p>\n<h2>Use a Separate Resource Download Script</h2>\n<p>I'm not sure if the <code>Entrez.Bio</code> package includes a built-in caching mechanism, where it will know not to re-download a file you previously requested, but I also kind of feel like that's irrelevant.</p>\n<p>Bioinformatics research depends on access to the supercomputer, and I've even seen grants come in the form of not money but the amount of computing hours that the grant money would have cost. In other words, I would not waste that precious time downloading a file, when you can do that for free and just include it in the slurm request.</p>\n<p>Not to mention, (I'm breaking out in cold sweat even considering this possibility) can you imagine submitting a job request with an incorrect sequence ID? These jobs can take days to complete (and we're talking about programs written in C and/or Fortran, who knows about Python?), so accidentally submitting an incorrect job request... I'm not saying the PI would murder you for it, but if they did, a jury of bioinformatics researchers would probably not convict them for it.</p>\n<p>Furthermore, there are a lot of things that have to be done before actual analysis can take place. You need to have done some analysis before hand to be able to conduct some kind of regression testing on the results you get back.</p>\n<p>Separating the downloading and processing of a sequence file allows you to be able to analyze arbitrary files, even contrived ones you wrote yourself. This then allows you to perform basic unit testing on the script, to ensure you didn't accidentally count adenine twice and forget guanine or something.</p>\n<h2>Don't Build the k-mers in Memory</h2>\n<p>Since by the time you start parsing the input sequence you already know the value of <span class=\"math-container\">\\$k\\$</span>, there's no need to actually build a list of <span class=\"math-container\">\\$k\\$</span>-mers. What I would do is use an input buffer <span class=\"math-container\">\\$k\\$</span>-characters long and then print out the <span class=\"math-container\">\\$k\\$</span>-mer once the buffer is full<sup>3</sup>.</p>\n<p>More specifically, I would open an output file and write out the specific <span class=\"math-container\">\\$k\\$</span>-mer found. Remember, it's the ordering, not necessarily the counts, of the coding sequences that matter.</p>\n<hr />\n<ol>\n<li>To be clear, however, a nucleotide is not the same thing as the A/T/G/C bases we're parsing here. When these bases combine with a five-carbon sugar, they form a nucleoside, which is itself still only a subcomponent of a nucleotide.</li>\n<li>I've never seen anything else, but I'm not a microbiologist. I was just an intern studying math, so feedback from actual experts is always welcome.</li>\n<li>If you were parsing codons, as I suggest in the first section, I would use a lookup table here to output the resulting amino acid/codon character. Each one has a single-character representation, so you can output a result file 1/3 the length of the input, allowing for easier post-processing.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T04:59:17.420", "Id": "494210", "Score": "0", "body": "Days on the supercomputer? Wow. I know very little about the actual bio-chem. Nice to hear from someone with some knowledge of the problem domain." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T14:54:42.233", "Id": "251094", "ParentId": "251068", "Score": "2" } } ]
{ "AcceptedAnswerId": "251076", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T18:48:41.393", "Id": "251068", "Score": "3", "Tags": [ "python", "bioinformatics" ], "Title": "Counting the number of k-mers like monomers, dimers to hexamers from the fasta file" }
251068
<p>I have some data being returned to me in the form of a deeply nested Dict and I need to parse multiple values from it which may or may not be there. I saw <a href="https://github.com/akesterson/dpath-python" rel="nofollow noreferrer">the <code>dpath</code> library</a> and tried to come up with a simplified version that fits into one function.</p> <p>I think it's pretty good but I'm wondering if I missed something or there's some small way to improve it?</p> <pre><code>from typing import Dict, Union import re import copy def dict_query(d: Dict, path: str) -&gt; Union[object, None]: &quot;&quot;&quot; # Example usage: &gt;&gt;&gt; d = {'a': [{}, {'b': 9}]} &gt;&gt;&gt; print( dict_query(d, 'a/[1]/b') ) 9 &quot;&quot;&quot; keys = path.split(&quot;/&quot;) val = copy.deepcopy(d) for key in keys: idx = re.search(&quot;\[(\d+)\]&quot;, key) if idx: # handle list index if isinstance(val, (list, tuple)): idx = int(idx.group(1)) val = val[idx] else: return None elif isinstance(val, dict): # handle dict key val = val.get(key) else: return None return val # tests of searching nested dicts d = {'a': {'b': 1}} print( dict_query(d, 'a/b') ) # 1 print( dict_query(d, 'a/c') ) # None print( dict_query(d, 'a/') ) # None print( dict_query(d, 'c/b') ) # None # tests of searching nested dicts + lists d = {'a': [{}, {'b': 1}]} print( dict_query(d, 'a/[0]') ) # {} print( dict_query(d, 'a/[1]') ) # {'b': 1} print( dict_query(d, 'a/[1]/b') ) # 1 print( dict_query(d, 'a/[1]/c') ) # None print( dict_query(d, 'a/[0]/a') ) # None print( dict_query(d, '[1]/b') ) # None </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T23:25:40.663", "Id": "494113", "Score": "2", "body": "The code doesn't change the dict, So, it's not necessary to make a deep copy of it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T08:32:48.513", "Id": "494123", "Score": "0", "body": "Please provide sample input and output" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T11:04:26.533", "Id": "494132", "Score": "0", "body": "@AryanParekh I already did, its at the bottom of the post" } ]
[ { "body": "<p>I would skip the <code>[]</code> in the path. Just presume <code>val</code> is a dict with strings for keys (the usual case). It that doesn't work, try converting the key to an <code>int</code>.</p>\n<pre><code>def dict_query(d: Dict, path: str) -&gt; Union[object, None]:\n &quot;&quot;&quot;\n # Example usage:\n &gt;&gt;&gt; d = {'a': [{}, {'b': 9}]}\n &gt;&gt;&gt; print( dict_query(d, 'a/1/b') )\n 9\n &quot;&quot;&quot;\n keys = path.split(&quot;/&quot;)\n val = d\n\n try:\n for key in keys:\n try:\n val = val[key]\n \n except (KeyError, TypeError):\n val = val[int(key)]\n \n return val\n \n except (IndexError, KeyError, TypeError, ValueError):\n return None\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T02:13:51.857", "Id": "494114", "Score": "0", "body": "`except (IndexError, KeyError, TypeError): return None` this seems a bit risky to me" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T06:17:46.273", "Id": "494118", "Score": "0", "body": "The outer `try-except` block really only covers one line: `val = val[int(key)]`. The errors correspond to `val` being a list and `key` being out of range; `val` being a dict and missing the `key`; `val` not being a Mapping or Sequence. Ooops, I forgot the ValueError for `key` not being an int." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T00:00:53.313", "Id": "251075", "ParentId": "251073", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T20:43:31.150", "Id": "251073", "Score": "4", "Tags": [ "python", "python-3.x", "hash-map" ], "Title": "Function for accessing and searching dictionaries using /slashed/paths (like xpath)" }
251073
<p>I'm posting two solutions for LeetCode's &quot;Defanging an IP Address&quot;. If you'd like to review, please do. Thank you!</p> <h3><a href="https://leetcode.com/problems/defanging-an-ip-address/" rel="noreferrer">Problem</a></h3> <p>Given a valid (IPv4) IP address, return a defanged version of that IP address.</p> <p>A defanged IP address replaces every period &quot;.&quot; with &quot;[.]&quot;.</p> <h3>Example 1:</h3> <pre><code>Input: address = &quot;1.1.1.1&quot; Output: &quot;1[.]1[.]1[.]1&quot; </code></pre> <h3>Example 2:</h3> <pre><code>Input: address = &quot;255.100.50.0&quot; Output: &quot;255[.]100[.]50[.]0&quot; </code></pre> <h3>Constraints:</h3> <ul> <li>The given address is a valid IPv4 address.</li> </ul> <h3>Code 1</h3> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; static const char* defangIPaddr( char* address ) { char* ipv4_memory = calloc(1, sizeof(&quot;###[.]###[.]###[.]###&quot;)); char* defanged = ipv4_memory; for (char* character = address; *character; character++) { if (*character == '.') { *ipv4_memory++ = '['; *ipv4_memory++ = '.'; *ipv4_memory++ = ']'; } else { *ipv4_memory++ = *character; } } return defanged; } int main() { printf (&quot;%s \n&quot;, defangIPaddr(&quot;1.1.1.1&quot;)); printf (&quot;%s \n&quot;, defangIPaddr(&quot;255.100.50.0&quot;)); return 0; } </code></pre> <h3>Code 2 without changing the input:</h3> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; static const char* defangIPaddr( const char* address ) { char* cloned_address = NULL; cloned_address = strdup(address); char* ipv4_memory = calloc(1, sizeof(&quot;###[.]###[.]###[.]###&quot;)); char* defanged = ipv4_memory; for (char* character = cloned_address; *character; character++) { if (*character == '.') { *ipv4_memory++ = '['; *ipv4_memory++ = '.'; *ipv4_memory++ = ']'; } else { *ipv4_memory++ = *character; } } return defanged; } int main() { printf (&quot;%s \n&quot;, defangIPaddr(&quot;1.1.1.1&quot;)); printf (&quot;%s \n&quot;, defangIPaddr(&quot;255.100.50.0&quot;)); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T13:47:45.833", "Id": "494141", "Score": "4", "body": "The (very good) reviews notwithstanding, the code is exceptionally clean — honestly well done! I’m not sure I understand why you think the two implementations materially differ: neither changes the input, and you seem to have actually noticed that yourself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T09:31:34.507", "Id": "494226", "Score": "2", "body": "I don't see either function storing through the `char* address` arg, so neither one modifies its input. You could change it to `const char *address` and it would still compile. Some answers made that point implicitly, but I didn't see a clear mention of that important point that seems to be a sign of some kind of misunderstanding. (Although it seemed too small to post a separate answer.)" } ]
[ { "body": "<p>Watch your memory allocations and deallocations. In both cases, you've got <code>defangIPaddr</code> returning a <code>const char *</code> to heap-allocated memory, which needs to be freed by the caller... but it can't be freed, because <code>free</code> expects a <em>non-const</em> <code>void*</code> as its argument.</p>\n<p>Functions that return ownership-of-a-heap-allocation to the caller should (A) return <code>char*</code>, not <code>const char*</code>, and (B) be clearly documented.</p>\n<p>In Code 2, you're not just leaking the returned pointer; you're also leaking the <code>strdup</code>'ed original pointer. There's no reason to call <code>strdup</code> here.</p>\n<p>What you want is simply</p>\n<pre><code>char *defangIPaddr(const char *address) {\n char *defanged = calloc(sizeof(&quot;###[.]###[.]###[.]###&quot;), 1);\n char *q = defanged;\n for (const char *p = address; *p != '\\0'; ++p) {\n if (*p == '.') {\n *q++ = '[';\n *q++ = '.';\n *q++ = ']';\n } else {\n *q++ = *p;\n }\n }\n return defanged;\n}\n</code></pre>\n<p>I've shortened your names <code>character</code> and <code>ipv4_memory</code> to just <code>p</code> and <code>q</code>. My <code>p</code> is for &quot;pointer&quot;; it's not a character at all, so <code>character</code> is a misleading name for it. <code>q</code> is simply what comes after <code>p</code>.</p>\n<p>You got the arguments to <code>calloc</code> in the wrong order. In practice this doesn't matter; but getting it correct is easy and free. If you're unsure about an interface, <a href=\"https://linux.die.net/man/3/calloc\" rel=\"noreferrer\">check the man page</a>.</p>\n<p>In your original code, you did this:</p>\n<pre><code>char* cloned_address = NULL;\ncloned_address = strdup(address);\n</code></pre>\n<p>That's a verbose way of writing</p>\n<pre><code>char* cloned_address = strdup(address);\n</code></pre>\n<p>Always initialize your variables — but initialize them to the right values! Don't initialize to a nonsense or garbage value and then <em>later</em> assign the right value over it; just initialize with the right value to begin with.</p>\n<hr />\n<p><code>sizeof(&quot;###[.]###[.]###[.]###&quot;)</code> is a mildly sneaky way of computing the maximum possible length. It might be better to allocate simply <code>3*strlen(address)+1</code> bytes, so that you can't possibly buffer-overflow, even if the caller passes in <code>&quot;..................&quot;</code> as their input.</p>\n<p>Alternatively, you could compute the exact right buffer length and malloc exactly that much.</p>\n<pre><code> int len = 0;\n for (const char *p = address; *p != '\\0'; ++p) {\n len += (*p == '.') ? 3 : 1;\n }\n char *defanged = calloc(len+1, 1);\n [...]\n</code></pre>\n<hr />\n<p>Consider throwing in an <code>if (defanged == NULL) return NULL;</code> just in case the allocation fails.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T09:26:23.420", "Id": "494128", "Score": "2", "body": "You should check whether `calloc()` returned `NULL`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T03:34:56.530", "Id": "251078", "ParentId": "251077", "Score": "12" } }, { "body": "<h1>Consider using <code>asprintf()</code></h1>\n<p>Just like you are using <a href=\"https://en.cppreference.com/w/c/experimental/dynamic/strdup\" rel=\"noreferrer\"><code>strdup()</code></a> to simplify making a copy of a string, consider using <a href=\"https://man7.org/linux/man-pages/man3/asprintf.3.html\" rel=\"noreferrer\"><code>asprintf()</code></a> to print a string without having to worry about allocating memory yourself. This will greatly simplify your code:</p>\n<pre><code>char* defangIPaddr(const char* address)\n{\n char* defanged;\n int ip[4];\n\n if (sscanf(address, &quot;%d.%d.%d.%d&quot;, &amp;ip[0], &amp;ip[1], &amp;ip[2], &amp;ip[3]) != 4)\n return NULL;\n\n if (asprintf(&amp;defanged, &quot;%d[.]%d[.]%d[.]%d&quot;, ip[0], ip[1], ip[2], ip[3]) == -1)\n return NULL;\n\n return defanged;\n}\n</code></pre>\n<p>Not all platforms support <code>asprintf()</code> though, and this solution has worse performance than your solution, but on the other hand it's simpler (no <code>for</code>-loops or manual memory allocation necessary), and can be adapted easily to other problems where you have to transform an input string to an output string, as long as they can easily be represented by format strings.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T10:58:15.267", "Id": "494229", "Score": "2", "body": "I have to strongly disagree with this suggestion. It is preferable to write portable code unless you are already constrained to that particular platform for some reason (like hardware dependencies). Relying on Gnu-specific functions just doesn't make sense when you can write portable C almost just as easily." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T11:30:51.860", "Id": "494235", "Score": "1", "body": "@CodyGray We can agree to disagree :) I don't like ignoring a perfectly good function just for the sake of portability. I've seen too many mistakes with people mucking about with `strlen()+malloc()+strcpy()` when they could've just used `strdup()`. And if it turns out your platform doesn't support those functions, you can just write a drop-in replacement for that platform. Of course only do this if the non-portable function you want to use is a very good fit for your problem in the first place." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T09:23:23.167", "Id": "251084", "ParentId": "251077", "Score": "8" } }, { "body": "<p>Here is my take on the problem, a function which accepts any string length and only allocates exactly enough memory:</p>\n<pre class=\"lang-c prettyprint-override\"><code>//#include &lt;malloc/_malloc.h&gt;\n#include &lt;stdlib.h&gt; // malloc, free\n#include &lt;assert.h&gt; // assert\n#include &lt;stdio.h&gt; // printf, fprintf\n\n/**\n * &quot;Defangs&quot; a string by replacing all `.` with `[.]`.\n *\n * @param str The string to defang\n * @return A pointer to a heap-allocated, defanged version of the string. The\n * pointer may be `NULL` if the allocation failed. The caller is responsible for\n * freeing the pointed-to memory (via `free()`) when they are done with it.\n */\nchar* defang(const char* str) {\n size_t str_len = 0; // without null terminator\n size_t new_len = 1; // with null terminator\n\n for (const char* c = str; *c; c++) {\n str_len++;\n\n if (*c == '.') {\n new_len += 3;\n } else {\n new_len++;\n }\n }\n\n char* new = malloc(new_len);\n\n if (new) {\n char* ptr = new;\n for (size_t i = 0; i &lt; str_len; i++) {\n const char* c = &amp;str[i];\n\n if (*c == '.') {\n *ptr++ = '[';\n *ptr++ = '.';\n *ptr++ = ']';\n } else {\n *ptr++ = *c;\n }\n }\n\n *ptr++ = 0;\n\n assert(ptr - new == new_len);\n }\n\n return new;\n}\n\nint main() {\n char* defanged1 = defang(&quot;1.1.1.1&quot;);\n if (defanged1) {\n printf(&quot;%s\\n&quot;, defanged1);\n free(defanged1);\n } else {\n fprintf(stderr, &quot;Failed to allocate memory for defanged1\\n&quot;);\n return 1;\n }\n\n char* defanged2 = defang(&quot;255.100.50.0&quot;);\n if (defanged2) {\n printf(&quot;%s\\n&quot;, defanged2);\n free(defanged2);\n } else {\n fprintf(stderr, &quot;Failed to allocate memory for defanged2\\n&quot;);\n return 1;\n }\n\n return 0;\n}\n</code></pre>\n<p>When memory cannot be allocated, it returns a null pointer to the caller to allow them to handle the situation, rather than attempting to continue and causing a segfault immediately.</p>\n<p>Additionally, the function has a documentation comment which explains exactly what it does, what it takes, what it returns and what is expected of the caller. In my opinion, those four elements are essential to any documentation.</p>\n<p>Then, the included <code>main</code> function is an example of how one would use the <code>defang</code> function, freeing the memory if it was allocated and failing with an error message if it was not.</p>\n<p>Feel free to look over this code as an example of how to apply the advice that others have given.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T09:28:21.613", "Id": "494225", "Score": "4", "body": "Using `new` as a var name make it less convenient to port to C++ (where it's a keyword). If you regularly work with both languages, usually good to avoid that. Not that you should make your C worse so it can actually compile as C++, e.g. don't cast malloc, but otherwise-neutral things you might as well do." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T10:59:26.097", "Id": "494230", "Score": "0", "body": "You would not have the `new` problem if you used the much-maligned Hungarian notation, `pNew`. :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T12:08:27.930", "Id": "494245", "Score": "0", "body": "You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and **why it is better than the original**) so that the author and other readers can learn from your thought process." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T14:02:39.073", "Id": "494349", "Score": "0", "body": "@Mast You're right, I did not review the original code. This answer was intended to add to the existing reviews, not necessarily stand on its own as a review. There is a doc comment though, those are important so I did detail that at least. ;)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T17:03:10.663", "Id": "251101", "ParentId": "251077", "Score": "2" } } ]
{ "AcceptedAnswerId": "251078", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T02:22:49.893", "Id": "251077", "Score": "9", "Tags": [ "performance", "beginner", "algorithm", "c", "programming-challenge" ], "Title": "LeetCode 1108: Defanging an IP Address" }
251077
<p><strong>Goal</strong></p> <p>To determine the coordinates of some signal source in a 3D space, given the coordinates of four observers and the time at which each saw the signal, as well as the velocity of the signal.</p> <p><strong>Algorithm</strong></p> <p>The algorithm is more-or-less comprised of two pieces: the <em>approximation search</em> algorithm, and the <em>localization</em> algorithm. Approximation search can be described simply as follows:</p> <p>Suppose we have some function, <code>f(x)</code>, and we want to find an <code>x</code> such that <code>f(x) = y</code>. We begin by choosing some search interval, <code>[xi, xf]</code>, and we probe some evenly-spaced points along this interval with some step, <code>da</code>. We remember the point with the least error, and feed that error back into the algorithm. We recursively increase accuracy, reducing <code>da</code> and restricting the search interval to around each progressively better solution. We stop when we've reached the maximum number of iterations (configurable).</p> <p>The localization bit is simply the computation of the error. I could explain it, however I find that the code does so itself far better than I could hope to in words.</p> <p><strong>Issues</strong></p> <p>In my opinion, the code is a bit messy and slightly more difficult to read than I'd like. Similarly, I'm not sure how I feel about the nested loops. Of course, I don't want to overcomplicate things simply to get rid of nested loops, however if there's a nicer way to do this, I'm all ears.</p> <p>It's also <em>slow</em>. This is <code>Python</code>, of course, so I shouldn't expect it to perform like a similarly implemented algorithm in, say, <code>C/C++</code>, however I'm certainly interested in increasing search speed.</p> <p>Lastly, it's been a while since I've done anything in <code>Python</code>, so I'm interested in a critique of my style. The goal is readability, and not necessarily 'standards' compliance.</p> <p>Tear it apart. Don't hold back!</p> <pre><code>import math from dataclasses import dataclass @dataclass class Approximate: ai: float; af: float da: float; n : int # Default values aa: float = 0 ei: float = -1 a : float = 0 e : float = 0 i : int = 0 done: bool = False stop: bool = False def step(self): if (self.ei &lt; 0) or (self.ei &gt; self.e): self.ei = self.e self.aa = self.a if (self.stop): self.i += 1 if (self.i &gt;= self.n): self.done = True self.a = self.aa return # Max iter # Restrict to window around 'solution' self.ai = self.aa - self.da self.af = self.aa + self.da self.a = self.ai # Increase accuracy self.da *= 0.1 self.ai += self.da self.af -= self.da self.stop = False else: # Probe some points in [ai,af] with step da self.a = self.a + self.da if (self.a &gt; self.af): self.a = self.af self.stop = True def localize(recv): ax = Approximate(0, 5000, 32, 10) ay = Approximate(0, 5000, 32, 10) az = Approximate(0, 5000, 32, 10) dt = [0, 0, 0, 0] while not ax.done: ay = Approximate(0, 5000, 32, 10, 0, 0) while not ay.done: az = Approximate(0, 5000, 32, 10, 0, 0) while not az.done: for i in range(4): x = recv[i][0] - ax.a y = recv[i][1] - ay.a z = recv[i][2] - az.a baseline = math.sqrt((x * x) + (y * y) + (z * z)) dt[i] = baseline / 299800000 # Normalize times into deltas from zero baseline = min(dt[0], dt[1], dt[2], dt[3]) for j in range(4): dt[j] -= baseline error = 0 for k in range(4): error += math.fabs(recv[k][2] - dt[k]) ay.e = error ax.e = error az.step() ay.step() ax.step() # Found solution print(ax.aa) print(ay.aa) print(az.aa) <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T06:35:30.827", "Id": "494119", "Score": "0", "body": "Sample input and output would be helpful." } ]
[ { "body": "<p>Remove empty lines after if/else. Remove empty lines in general, this has too many. Use the new <code>math.dist</code>. Add comments about how the approximation works. Add docstrings.</p>\n<p>If you want to make it more readable, pull out sub-loops into functions. That reduces nesting depth, which is just too high here--it's a problem you don't run into often. Also, don't use names like 'ei'.</p>\n<p>One approach to make it more readable (but maybe slower), rewrite 'approximate' as a function taking in: a function to compute, an interval to search, and a maximum number of iterations. Also, you could use scipy or another specialized package which has this built-in.</p>\n<p>If you want to make it more readable AND fast, don't use this solution. Use some other maximization method, for example gradient descent. These are also available as prebuilt tools, so it should be readable.</p>\n<p>Last, in this case, I think there is probably a very direct answer specific to the problem. Look up GPS algorithms, because this is more or less how they work (although the speed is always the speed of light)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-04T02:25:20.500", "Id": "495306", "Score": "0", "body": "No, I don't know how gradient descent works. If you can take the derivative, do that--it looks like you should be able to here. I think you should be able to approximate the derivative by sampling at very small offsets around your current point, and dividing by the distance. Or since 3D is a low dimensionality, you can also just sample at offsets, move to the smallest, and repeat, without mucking with derivatives. This depends on avoiding local minima." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-04T02:20:10.750", "Id": "251576", "ParentId": "251079", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T03:42:30.243", "Id": "251079", "Score": "4", "Tags": [ "python", "algorithm", "python-3.x", "recursion" ], "Title": "Approximation search source reconstruction localization algorithm" }
251079
<h2>Context</h2> <p>I was solving a task on CodeSignal <a href="https://app.codesignal.com/arcade/intro/level-12/uRWu6K8E7uLi3Qtvx" rel="noreferrer">here</a></p> <p>You can view the task on the link I provided above.</p> <p>I have also put the task at the bottom of the post.</p> <h2>Code</h2> <pre><code>def check(matrix, num): for arr in matrix: for number in arr: if number != num: return True return False def spiralNumbers(n): array = [] array_dup = [] for i in range(n): arr1 = [] for j in range(n): arr1.append(j) array.append(arr1) for i in range(n): arr1 = [] for j in range(n): arr1.append(j) array_dup.append(arr1) selected_row, selected_num_pos = 0, -1 count = 1 run = True while run: its_neg = False for i in range(selected_num_pos+1, n): if array_dup[selected_row][i] == -1: its_neg = True break array[selected_row][i] = count array_dup[selected_row][i] = -1 count += 1 if its_neg: selected_num_pos = i-1 else: selected_num_pos = i its_neg = False for i in range(selected_row+1, n): if array_dup[i][selected_num_pos] == -1: its_neg = True break array[i][selected_num_pos] = count array_dup[i][selected_num_pos] = -1 count += 1 if its_neg: selected_row = i-1 else: selected_row = i its_neg = False for i in range(selected_num_pos-1, -1, -1): if array_dup[selected_row][i] == -1: its_neg = True break array[selected_row][i] = count array_dup[selected_row][i] = -1 count += 1 if its_neg: selected_num_pos = i+1 else: selected_num_pos = i its_neg = False for i in range(selected_row-1, -1, -1): if array_dup[i][selected_num_pos] == -1: its_neg = True break array[i][selected_num_pos] = count array_dup[i][selected_num_pos] = -1 count += 1 if its_neg: selected_row = i+1 else: selected_row = i run = check(array_dup, -1) return array </code></pre> <h2>Question</h2> <p>The Code I wrote works without any error and returns the expected output, but the code seems a bit long for this problem. I wanted to know how can I make this code shorter and more efficient?</p> <h2>The Task</h2> <p><a href="https://i.stack.imgur.com/r6S7Q.png" rel="noreferrer"><img src="https://i.stack.imgur.com/r6S7Q.png" alt="enter image description here" /></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T16:09:17.157", "Id": "494153", "Score": "0", "body": "Are there no lower/upper limits for N?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T16:14:38.457", "Id": "494155", "Score": "0", "body": "An outline describing your method would be helpful." } ]
[ { "body": "<ul>\n<li>You're using non-standard names. Usual names are A for the matrix, i for the row index, and j for the column index.</li>\n<li>List repetition and comprehension make the initialization shorter and faster.</li>\n<li>Using deltas for the four directions can avoid quadrupling code.</li>\n<li>You can know when to change direction by checking whether the next element in the current direction is already set.</li>\n<li>Your <code>check</code> is inefficient. Instead of searching the matrix for an unset spot, just do <code>while count &lt;= n**2:</code>. Or, try to loop through the <code>range</code> of numbers.</li>\n<li>Your current code crashes for <code>n = 0</code> because it always enters the loop, as you compute <code>run</code> only at the end. With <code>while count &lt;= n**2:</code> you'd succeed.</li>\n</ul>\n<pre><code>def spiralNumbers(n):\n A = [[0] * n for _ in range(n)]\n i = j = di = 0\n dj = 1\n for A[i][j] in range(1, n**2 + 1):\n if A[(i+di) % n][(j+dj) % n]:\n di, dj = dj, -di\n i += di\n j += dj\n return A\n</code></pre>\n<p>The <code>% n</code> is just a little trick to avoid checking for index-out-of-bounds.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T16:26:22.843", "Id": "251100", "ParentId": "251081", "Score": "5" } } ]
{ "AcceptedAnswerId": "251100", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T06:35:06.673", "Id": "251081", "Score": "8", "Tags": [ "python", "python-3.x", "programming-challenge" ], "Title": "Making an array of spiral numbers" }
251081
<p>These extensions create an <code>IObservable&lt;T&gt;</code> that creates a long running task that can be cancelled. It runs the <code>Func&lt;T&gt;</code> after each interval of time and passes the result to <code>OnNext()</code> until the task is ended by the <code>CancellationToken</code>. The important thing here is that only one task is created with one loop. I'd prefer to use <code>Observable.Create</code> reactive extension, but I cannot find the equivalent.</p> <p><strong>What are the issues with this implementation?</strong></p> <pre><code>using System; using System.Collections.Generic; using System.Reactive.Disposables; using System.Threading; using System.Threading.Tasks; namespace Observables { internal class BasicObservable&lt;T&gt; : IObservable&lt;T&gt; { readonly List&lt;IObserver&lt;T&gt;&gt; _observers = new List&lt;IObserver&lt;T&gt;&gt;(); public BasicObservable( Func&lt;T&gt; getData, TimeSpan? interval = null, CancellationToken cancellationToken = default ) =&gt; Task.Run(async () =&gt; { while (!cancellationToken.IsCancellationRequested) { try { await Task.Delay(interval ?? new TimeSpan(0, 0, 1)); _observers.ForEach(o =&gt; o.OnNext(getData())); } catch (Exception ex) { _observers.ForEach(o =&gt; o.OnError(ex)); } } _observers.ForEach(o =&gt; o.OnCompleted()); }, cancellationToken); public IDisposable Subscribe(IObserver&lt;T&gt; observer) { _observers.Add(observer); return Disposable.Create(observer, (o) =&gt; _observers.Remove(o)); } } public static class ObservableExtensions { public static IObservable&lt;T&gt; CreateObservable&lt;T&gt;( this Func&lt;T&gt; getData, CancellationToken cancellationToken = default) =&gt; new BasicObservable&lt;T&gt;(getData, default, cancellationToken); public static IObservable&lt;T&gt; CreateObservable&lt;T&gt;( this Func&lt;T&gt; getData, TimeSpan? interval = null, CancellationToken cancellationToken = default) =&gt; new BasicObservable&lt;T&gt;(getData, interval, cancellationToken); } } </code></pre> <p><strong>Usage</strong></p> <pre><code>using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Diagnostics; using System.Reactive.Linq; using System.Threading; using System.Threading.Tasks; namespace Observables { class Subscriber { public string Name; //Listen for OnNext and write to the debug window when it happens public Subscriber(IObservable&lt;string&gt; observable, string name) { Name = name; var disposable = observable.Subscribe((s) =&gt; Debug.WriteLine($&quot;Name: {Name} Message: {s}&quot;)); } } [TestClass] public class UnitTest1 { string GetData() =&gt; &quot;Hi&quot;; [TestMethod] public async Task Messaging() { var cancellationSource = new CancellationTokenSource(); var cancellationToken = cancellationSource.Token; Func&lt;string&gt; getData = GetData; var publisher = getData.CreateObservable(cancellationToken); new Subscriber(publisher, &quot;One&quot;); new Subscriber(publisher, &quot;Two&quot;); for (var i = 0; true; i++) { if (i &gt;= 5) { cancellationSource.Cancel(); } await Task.Delay(1000); } } } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T06:38:07.687", "Id": "251082", "Score": "3", "Tags": [ "c#", "observer-pattern", "system.reactive" ], "Title": "Create IObservable<T> From Func<T>" }
251082
<p>I've written the following function to produce n realizations of a <a href="https://en.wikipedia.org/wiki/Cox%E2%80%93Ingersoll%E2%80%93Ross_model" rel="nofollow noreferrer">CIR process</a> for a given set of parameters:</p> <pre><code>def cir_simulations(alpha, mu, sigma, delta_t, n, num_sims): x = np.reshape(np.array([mu] * num_sims), (-1, 1)) for i in range(0, n): x = np.concatenate((x, np.reshape(x[:, -1], (-1, 1)) + alpha * ( mu - np.reshape(x[:, -1], (-1, 1))) * delta_t + sigma * np.sqrt( np.reshape(x[:, -1], (-1, 1))) * np.sqrt(delta_t) * np.random.normal(0, 1, size=(num_sims, 1))), axis=1) return x </code></pre> <p>This code works, but I am now wondering whether it would be possible to remove the loop and fully vectorize it. I've struggled to find a way of doing this, as the operation being performed in the loop is recursive (the values in the next column of the matrix are non-linearly dependent on the previous columns values).</p> <p>Additionally, could this code be simplified? In particular, I feel like there may be needless complexity in the way that I am accessing the last column of the array using</p> <p><code>np.reshape(x[:, -1], (-1, 1))</code></p>
[]
[ { "body": "<p>Since the output of each step depends on the previous step, it is impossible to entirely eliminate the loop unless the formula can be simplified to allow a multi-step computation. However, the code can definitely still be improved.</p>\n<ul>\n<li><p>Calling <code>np.concatenate</code> is generally inefficient since it requires\nmemory reallocation and data copying. As long as possible, one should\npreallocate all the needed memory and update it iteratively.</p>\n</li>\n<li><p>Some computation can be moved out of the loop to improve efficiency.\nE.g., the <code>np.random.normal</code> call can be done only once. Same with <code>alpha * delta_t</code>.</p>\n</li>\n<li><p>More meaningful variable names could be chosen.</p>\n</li>\n<li><p>It is always a good practice to have docstrings and type hints in your code.</p>\n</li>\n</ul>\n<p>Here is one version of improved code:</p>\n<pre><code>def cir_simulations(alpha: float, mu: float, sigma: float, delta_t: float, sim_steps: int, num_sims: int):\n &quot;&quot;&quot;\n Simulate the CIR process.\n\n Parameters:\n Input\n ...\n\n Output\n ...\n &quot;&quot;&quot;\n output_shape = (num_sims, sim_steps + 1)\n sim_results = np.empty(output_shape)\n sigma_dW = np.random.normal(0, sigma * np.sqrt(delta_t), size=output_shape) \n alpha_dt = alpha * delta_t\n sim_results[0, :] = r_prev = mu\n\n for r_t, sigma_dWt in zip(sim_results[1:], sigma_dW):\n r_t[:] = r_prev = (mu - r_prev) * alpha_dt + np.sqrt(r_prev) * sigma_dWt\n\n return sim_results\n</code></pre>\n<p>I'm not very familiar with the meaning of all the parameters in the formula. There are two things that I have doubts in your computation:</p>\n<ul>\n<li>The rate <span class=\"math-container\">\\$r\\$</span> in the formula is initialized with the same parameter <code>mu</code> used in the iterative computation. Is it expected?</li>\n<li>The increment <span class=\"math-container\">\\$dW_t\\$</span> used a fixed variance of <code>1</code>. Is this supposed to be the case or should it be another function parameter?</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T11:38:03.423", "Id": "494238", "Score": "0", "body": "Cheers for the answer. The CIR model should produce stochastic processes which are mean-reverting, and so I chose the initial value to be mu as this is the mean of the process. My next step will be to plug this into the Heston model (which is used to simulate stochastic volatility) so I'll think harder about whether the initial value of the processes should be mu when I've understood the context of the CIR model as used in the Heston model." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T11:42:32.697", "Id": "494239", "Score": "0", "body": "With regards to the $dW_t$'s having fixed variance 1, the actual variance should be $dt$. I have accounted for this by multiplying the simulated standard normal values by $\\sqrt{dt}$." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T23:18:56.020", "Id": "494290", "Score": "0", "body": "OK. I just corrected some mistakes in the code." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T14:24:47.563", "Id": "251092", "ParentId": "251087", "Score": "2" } } ]
{ "AcceptedAnswerId": "251092", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T12:03:25.753", "Id": "251087", "Score": "4", "Tags": [ "python", "python-3.x", "numpy", "vectorization" ], "Title": "Can this numpy code be vectorized?" }
251087
<h1>Update: link to corresponding release</h1> <p>The code presented here is tagged as release version <a href="https://github.com/hungrybluedev/bump/releases/tag/v0.1.0" rel="nofollow noreferrer">v0.1.0</a> on Github for easy reference.</p> <h1>Introduction</h1> <p><code>bump</code> is a command-line utility that I use to &quot;bump&quot; up the <a href="https://semver.org/" rel="nofollow noreferrer">semantic version</a> numbers present in any text file. It is written entirely in C and doesn't use malloc anywhere. Here's a table describing how the various bump levels work:</p> <pre><code>| Bump | Release | Result on 3.2.6 | |-------|--------------------|-----------------| | Patch | x.y.z -&gt; x.y.(z+1) | 3.2.7 | | Mnior | x.y.z -&gt; x.(y+1).0 | 3.3.0 | | Major | x.y.z -&gt; (x+1).0.0 | 4.0.0 | </code></pre> <p>The CLI can be used in two ways:</p> <ol> <li>Interactive mode - when the user simply types <code>bump</code> and does not provide any command-line arguments. In this case the program will prompt the user for input.</li> <li>Silent mode - when the user passes in the command line arguments like <code>bump -i version.h</code> and the program verifies the argument, deduces the default value for the other arguments and proceeds silently.</li> </ol> <p>The full source code is available on <a href="https://github.com/hungrybluedev/bump/" rel="nofollow noreferrer">Github</a> under the MIT License.</p> <h1>Overview of the code</h1> <p>Here's how the algorithm works:</p> <ol> <li>Read the input from the file line-by-line.</li> <li>Process every line character-by-character.</li> <li>If we read a digit, start a greedy search for the <code>x.y.z</code> pattern.</li> <li>Proceed until no characters left to read.</li> </ol> <p>The main logic is contained in <code>bump.h</code> and <code>bump.c</code>.</p> <h2><code>bump.h</code></h2> <pre><code>#ifndef BUMP_H #define BUMP_H #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; typedef struct version_struct { size_t major; size_t minor; size_t patch; } Version; typedef struct line_state_struct { const char *input; char *output; size_t input_index; size_t output_index; size_t limit; } LineState; typedef struct file_state_struct { FILE *input; FILE *output; size_t limit; const char *bump_level; } FileState; char *initialize_version(Version *version, size_t major, size_t minor, size_t patch); char *initialize_line_state(LineState *state, const char *input, char *output, size_t limit); char *initialize_file_state(FileState *state, const char *input_path, const char *output_path, const char *bump_level, size_t limit); char *bump_major(Version *version); char *bump_minor(Version *version); char *bump_patch(Version *version); char *convert_to_string(Version *version, char *output_buffer, size_t *length); char *process_line(LineState *state, const char *bump_level); char *process_file(FileState *state); #endif//BUMP_H </code></pre> <h2><code>bump.c</code></h2> <pre><code>#include &lt;bump/bump.h&gt; #include &lt;bump/fileutil.h&gt; #include &lt;ctype.h&gt; #include &lt;stdbool.h&gt; #include &lt;stdint.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; char *initialize_version(Version *version, const size_t major, const size_t minor, const size_t patch) { if (!version) { return &quot;Empty pointer received.&quot;; } version-&gt;major = major; version-&gt;minor = minor; version-&gt;patch = patch; return NULL; } static char *sanity_check(Version *version) { if (!version) { return &quot;Empty pointer received.&quot;; } if (version-&gt;major == SIZE_MAX) { return &quot;Major version number is too big.&quot;; } if (version-&gt;minor == SIZE_MAX) { return &quot;Minor version number is too big.&quot;; } if (version-&gt;patch == SIZE_MAX) { return &quot;Patch version number is too big.&quot;; } return NULL; } char *bump_major(Version *version) { char *message = sanity_check(version); if (message) { return message; } version-&gt;major++; version-&gt;minor = 0; version-&gt;patch = 0; return NULL; } char *bump_minor(Version *version) { char *message = sanity_check(version); if (message) { return message; } version-&gt;minor++; version-&gt;patch = 0; return NULL; } char *bump_patch(Version *version) { char *message = sanity_check(version); if (message) { return message; } version-&gt;patch++; return NULL; } char *convert_to_string(Version *version, char *output_buffer, size_t *length) { if (!version) { return &quot;Empty version pointer value.&quot;; } if (!output_buffer) { return &quot;Empty output buffer pointer.&quot;; } *length = 0; int count = sprintf(output_buffer, &quot;%zu.%zu.%zu&quot;, version-&gt;major, version-&gt;minor, version-&gt;patch); if (count &lt; 0) { return &quot;Error occurred while trying to write to string buffer.&quot;; } *length = (size_t) count; return NULL; } char *initialize_line_state(LineState *state, const char *input, char *output, const size_t limit) { if (!state) { return &quot;Empty pointer received for state&quot;; } if (!input) { return &quot;Input buffer is null&quot;; } if (!output) { return &quot;Output buffer is null&quot;; } state-&gt;input = input; state-&gt;output = output; state-&gt;input_index = 0; state-&gt;output_index = 0; // The minimum length needed for a version string is 5. // If we have a string length limit smaller than that, we clamp the limit to 0. state-&gt;limit = limit &lt; 5 ? 0 : limit; return NULL; } static void keep_going(LineState *state) { if (state-&gt;input_index == state-&gt;limit) { return; } state-&gt;output[state-&gt;output_index] = state-&gt;input[state-&gt;input_index]; state-&gt;input_index++; state-&gt;output_index++; } static size_t extract_decimal_number(LineState *state) { char c; size_t value = 0; while (state-&gt;input_index &lt; state-&gt;limit &amp;&amp; isdigit(c = state-&gt;input[state-&gt;input_index])) { value *= 10; value += c - '0'; state-&gt;input_index++; } return value; } char *process_line(LineState *state, const char *bump_level) { if (!state) { return &quot;Null value received for state&quot;; } if (state-&gt;limit == 0 || state-&gt;input_index == state-&gt;limit) { return NULL; } while (state-&gt;input_index &lt; state-&gt;limit) { char c = state-&gt;input[state-&gt;input_index]; if (isdigit(c)) { // Start a greedy search for the pattern of &quot;x.y.z&quot; where x, y, and z are decimal numbers size_t major = extract_decimal_number(state); c = state-&gt;input[state-&gt;input_index]; if (c != '.') { // We have a normal number. Dump it to the output and proceed normally. int chars_printed = sprintf(state-&gt;output + state-&gt;output_index, &quot;%zu&quot;, major); if (chars_printed &lt; 1) { return &quot;Error occurred while trying to write to output buffer&quot;; } state-&gt;output_index += chars_printed; keep_going(state); continue; } state-&gt;input_index++; if (state-&gt;input_index == state-&gt;limit) { return NULL; } c = state-&gt;input[state-&gt;input_index]; if (!isdigit(c)) { // We have a x. followed by a non-digit int chars_printed = sprintf(state-&gt;output + state-&gt;output_index, &quot;%zu.&quot;, major); if (chars_printed &lt; 1) { return &quot;Error occurred while trying to write to output buffer&quot;; } state-&gt;output_index += chars_printed; keep_going(state); continue; } size_t minor = extract_decimal_number(state); if (state-&gt;input_index == state-&gt;limit) { return NULL; } c = state-&gt;input[state-&gt;input_index]; if (c != '.') { // We have an input of the form x.y only. No period follows the y int chars_printed = sprintf(state-&gt;output + state-&gt;output_index, &quot;%zu.%zu&quot;, major, minor); if (chars_printed &lt; 1) { return &quot;Error occurred while trying to write to output buffer&quot;; } state-&gt;output_index += chars_printed; keep_going(state); continue; } state-&gt;input_index++; c = state-&gt;input[state-&gt;input_index]; if (!isdigit(c)) { // We have a x.y. followed by a non-digit int chars_printed = sprintf(state-&gt;output + state-&gt;output_index, &quot;%zu.%zu.&quot;, major, minor); if (chars_printed &lt; 1) { return &quot;Error occurred while trying to write to output buffer&quot;; } state-&gt;output_index += chars_printed; keep_going(state); continue; } size_t patch = extract_decimal_number(state); c = state-&gt;input[state-&gt;input_index]; if (c == '.') { // We have x.y.z. which is invalid. int chars_printed = sprintf(state-&gt;output + state-&gt;output_index, &quot;%zu.%zu.%zu&quot;, major, minor, patch); if (chars_printed &lt; 1) { return &quot;Error occurred while trying to write to output buffer&quot;; } state-&gt;output_index += chars_printed; keep_going(state); continue; } // We now have all three numbers. Version version = {0}; initialize_version(&amp;version, major, minor, patch); if (strcmp(bump_level, &quot;major&quot;) == 0) { bump_major(&amp;version); } else if (strcmp(bump_level, &quot;minor&quot;) == 0) { bump_minor(&amp;version); } else if (strcmp(bump_level, &quot;patch&quot;) == 0) { bump_patch(&amp;version); } else { return &quot;Invalid bump level&quot;; } size_t version_len; char *error = convert_to_string(&amp;version, state-&gt;output + state-&gt;output_index, &amp;version_len); state-&gt;output_index += version_len; if (error) { return error; } if (state-&gt;input_index &lt; state-&gt;limit) { strcpy(state-&gt;output + state-&gt;output_index, state-&gt;input + state-&gt;input_index); } // We are done so we exit early return NULL; } else { keep_going(state); } } return NULL; } char *initialize_file_state(FileState *state, const char *input_path, const char *output_path, const char *bump_level, const size_t limit) { if (!state) { return &quot;Null pointer received for FileState&quot;; } if (!input_path) { return &quot;Empty file path provided for input&quot;; } if (!output_path) { return &quot;Empty file path provided for output&quot;; } if (!bump_level) { return &quot;Invalid value received for bump level&quot;; } if (!file_is_valid(input_path, &quot;r&quot;)) { return &quot;Cannot open input file for reading&quot;; } if (!file_is_valid(output_path, &quot;w&quot;)) { return &quot;Cannot open output file for writing&quot;; } state-&gt;input = fopen(input_path, &quot;r&quot;); state-&gt;output = fopen(output_path, &quot;w&quot;); state-&gt;bump_level = bump_level; state-&gt;limit = limit; return NULL; } char *process_file(FileState *state) { if (!state) { return &quot;File state is null&quot;; } char input_buffer[state-&gt;limit + 1]; char output_buffer[state-&gt;limit + 1]; size_t len; bool keep_going = true; while (1) { char *error; error = read_line(state-&gt;input, input_buffer, &amp;len, state-&gt;limit); if (error) { keep_going = false; } memset(output_buffer, 0, state-&gt;limit); LineState line_state = {0}; error = initialize_line_state(&amp;line_state, input_buffer, output_buffer, state-&gt;limit); if (error) { return error; } while (line_state.input_index &lt; len) { error = process_line(&amp;line_state, state-&gt;bump_level); if (error) { return error; } } if (keep_going) { fprintf(state-&gt;output, &quot;%s\n&quot;, output_buffer); return NULL; } else { fprintf(state-&gt;output, &quot;%s&quot;, output_buffer); fclose(state-&gt;input); fclose(state-&gt;output); return &quot;End of file reached&quot;; } } } </code></pre> <h2><code>fileutil.h</code></h2> <pre><code>#ifndef BUMP_FILEUTIL_H #define BUMP_FILEUTIL_H #include &lt;stdio.h&gt; #include &lt;stdbool.h&gt; bool file_is_valid(const char *input_path, const char *mode); char *read_line(FILE *input, char *buffer, size_t *length, size_t limit); #endif//BUMP_FILEUTIL_H </code></pre> <h2><code>fileutil.c</code></h2> <pre><code>#include &lt;bump/fileutil.h&gt; #include &lt;memory.h&gt; #include &lt;stdbool.h&gt; #include &lt;stdio.h&gt; bool file_is_valid(const char *input_path, const char *mode) { FILE *input_file = fopen(input_path, mode); bool result = input_file != NULL; if (result) { fclose(input_file); } return result; } static char *validate(FILE *input, const char *buffer) { if (!input) { return &quot;Empty pointer for input file.&quot;; } if (!buffer) { return &quot;Storage buffer is empty.&quot;; } return NULL; } char *read_line(FILE *input, char *buffer, size_t *length, size_t limit) { char *error = validate(input, buffer); if (error) { return error; } int ch; *length = 0; memset(buffer, 0, limit); while (*length &lt; limit &amp;&amp; (ch = fgetc(input)) != '\n' &amp;&amp; ch != EOF) { buffer[*length] = (char) ch; (*length)++; } buffer[*length] = '\0'; return ch == EOF ? &quot;End of file reached&quot; : NULL; } </code></pre> <h2><code>main.c</code></h2> <p>This file handles all the cases where we need to process the arguments provided or we need to obtain inputs from the user. These are essential for the executable, but not the library, so that's why I've separated the components this way.</p> <pre><code>#include &lt;bump/bump.h&gt; #include &lt;bump/fileutil.h&gt; #include &lt;bump/version.h&gt; #include &lt;ctype.h&gt; #include &lt;stdbool.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #define MAX_LINE_LENGTH 511 #define INCORRECT_USAGE &quot;Incorrect usage. Type bump --help for more information.&quot; #define INTERMEDIATE_FILE &quot;intermediate.temp&quot; /** * Convert the characters stored in the source string to lowercase and store * them in the destination buffer. Additionally, store the number of characters * processed in the len pointer. * * @param destination The buffer to store the lowercase string in. * @param source The source string to convert to lowercase. * @param len The size_t pointer to store the number of characters processed. */ static void convert_to_lowercase_and_store_length(char *destination, const char *source, size_t *len) { *len = 0; for (char *p = (char *) source; *p; p++, (*len)++) { destination[*len] = (char) tolower(*p); } } static void store_file_name_in(const char *prompt, char *file_name_buffer, bool for_input) { bool we_have_file = false; while (true) { printf(&quot;%s&quot;, prompt); char buffer[MAX_LINE_LENGTH + 1]; size_t len = 0; char *error = read_line(stdin, buffer, &amp;len, MAX_LINE_LENGTH); if (error) { printf(&quot;Could not read line. The following error occurred: %s\nTry again.\n&quot;, error); continue; } we_have_file = file_is_valid(buffer, for_input ? &quot;r&quot; : &quot;w&quot;); if (we_have_file) { memcpy(file_name_buffer, buffer, len + 1); break; } printf(&quot;Could not location file with path: \&quot;%s\&quot;\nTry again.\n&quot;, buffer); } } static void store_bump_level_in(char *bump_level_buffer) { bool we_have_bump = false; while (true) { printf(&quot;Enter bump level (major/minor/[patch] or M/m/[p]): &quot;); char buffer[MAX_LINE_LENGTH + 1]; size_t len = 0; char *error = read_line(stdin, buffer, &amp;len, MAX_LINE_LENGTH); if (error) { printf(&quot;Could not read line. The following error occurred: %s\nTry again.\n&quot;, error); continue; } if (len == 0) { strcpy(bump_level_buffer, &quot;patch&quot;); len = strlen(&quot;patch&quot;); we_have_bump = true; } else if (len == 1) { bool major = buffer[0] == 'M'; bool minor = buffer[0] == 'm'; bool patch = buffer[0] == 'p'; if (major || minor || patch) { we_have_bump = true; } if (major) strcpy(bump_level_buffer, &quot;major&quot;); if (minor) strcpy(bump_level_buffer, &quot;minor&quot;); if (patch) strcpy(bump_level_buffer, &quot;patch&quot;); } else { if (strcmp(buffer, &quot;major&quot;) == 0 || strcmp(buffer, &quot;minor&quot;) == 0 || strcmp(buffer, &quot;patch&quot;) == 0) { we_have_bump = true; } memcpy(bump_level_buffer, buffer, len + 1); } if (we_have_bump) { break; } printf(&quot;Could not identify bump level; use major/minor/patch or M/m/p.\nTry again.\n&quot;); } } static bool read_confirmation() { while (true) { printf(&quot;Modify the input file? ([yes]/no or [y]/n): &quot;); char buffer[MAX_LINE_LENGTH + 1]; size_t len = 0; char *error = read_line(stdin, buffer, &amp;len, MAX_LINE_LENGTH); if (error) { printf(&quot;Could not read line. The following error occurred: %s\nTry again.\n&quot;, error); continue; } convert_to_lowercase_and_store_length(buffer, buffer, &amp;len); if (len == 0) { return true; } else if (len == 1) { if (buffer[0] == 'y') { return true; } if (buffer[0] == 'n') { return false; } } else { if (strcmp(buffer, &quot;yes&quot;) == 0) { return true; } if (strcmp(buffer, &quot;no&quot;) == 0) { return false; } } printf(&quot;Could not understand input.\nTry again.\n&quot;); } } static void print_help_message() { const char *help_message = &quot;Bump semantic version value\n&quot; &quot;===========================\n&quot; &quot;Version : &quot; BUMP_VERSION &quot;\n&quot; &quot;Author : Subhomoy Haldar (@hungrybluedev)\n&quot; &quot;Details : A command-line utility that bumps up the semantic version\n&quot; &quot; number of all instances it detects in a file. It can work\n&quot; &quot; in-place and bump the patch, minor, or major version number.\n\n&quot; &quot;Usage :\n&quot; &quot;1. bump\n&quot; &quot; Starts the program in interactive mode.\n&quot; &quot;2. bump [--help|-h]\n&quot; &quot; Displays this help message.\n&quot; &quot;3. bump [--version|-v]\n&quot; &quot; Shows the current version of this program.\n&quot; &quot;4. bump [--input|-i] path/to/file.txt [[--level|-l] [major|minor|patch]]? \\\n&quot; &quot; [[--output|-o] path/to/output_file.txt]?\n&quot; &quot; Performs the processing on the file path provided if it exists.\n\n&quot; &quot; The level switch and value is optional. The values allowed are:\n&quot; &quot; a. patch or p - a.b.c -&gt; a.b.(c + 1)\n&quot; &quot; b. minor or m - a.b.c -&gt; a.(b + 1).0\n&quot; &quot; c. major or M - a.b.c -&gt; (a + 1).0.0\n\n&quot; &quot; The default level is \&quot;patch\&quot;.\n\n&quot; &quot; The output switch and value pair is also optional. By default\n&quot; &quot; the result is stored in-place, in the input file.&quot;; printf(&quot;%s\n&quot;, help_message); } static char *process_input_path_value(char *input_file_name, bool *we_have_input_path, const char *file_path) { if (*we_have_input_path) { return &quot;Repeated input file switch.&quot;; } if (!file_is_valid(file_path, &quot;r&quot;)) { return &quot;The input file path provided is not valid.&quot;; } strcpy(input_file_name, file_path); *we_have_input_path = true; return NULL; } static char *process_output_path_value(char *output_file_name, bool *we_have_output_path, const char *file_path) { if (*we_have_output_path) { return &quot;Repeated output file switch.&quot;; } if (!file_is_valid(file_path, &quot;w&quot;)) { return &quot;The output file path provided is not valid.&quot;; } strcpy(output_file_name, file_path); *we_have_output_path = true; return NULL; } static char *process_single_switch(const char *switch_value) { char command[MAX_LINE_LENGTH] = {0}; size_t len; convert_to_lowercase_and_store_length(command, switch_value, &amp;len); if (len == 2) { // We have an abbreviated switch. It must begin with a '-' if (command[0] != '-') { return INCORRECT_USAGE; } switch (command[1]) { case 'h': print_help_message(); return NULL; case 'v': printf(&quot;Bump version : %s\n&quot;, BUMP_VERSION); return NULL; default: return INCORRECT_USAGE; } } if (len == 6 &amp;&amp; strcmp(command, &quot;--help&quot;) == 0) { print_help_message(); return NULL; } if (len == 9 &amp;&amp; strcmp(command, &quot;--version&quot;) == 0) { printf(&quot;Bump version : %s\n&quot;, BUMP_VERSION); return NULL; } // If we reached here, we must have had no matching switch return INCORRECT_USAGE; } static char *process_bump_value(char *bump_level, bool *we_have_bump_value, const char *bump_level_argument) { char buffer[MAX_LINE_LENGTH + 1]; size_t value_len; convert_to_lowercase_and_store_length(buffer, bump_level_argument, &amp;value_len); if (*we_have_bump_value) { return &quot;Repeated patch level switch.&quot;; } if (value_len == 1) { switch (bump_level_argument[0]) { case 'p': // No need to copy, it is already the default. break; case 'm': strcpy(bump_level, &quot;minor&quot;); break; case 'M': strcpy(bump_level, &quot;major&quot;); break; default: return &quot;Unrecognised patch value. Valid levels are major(M), minor(m), or patch(p).&quot;; } } else if (value_len == 5) { if (strcmp(bump_level_argument, &quot;major&quot;) == 0) { strcpy(bump_level, &quot;major&quot;); } else if (strcmp(bump_level_argument, &quot;minor&quot;) == 0) { strcpy(bump_level, &quot;minor&quot;); } else if (strcmp(bump_level_argument, &quot;patch&quot;) == 0) { // No need to copy } else { return &quot;Unrecognised patch value. Valid levels are major(M), minor(m), or patch(p).&quot;; } } *we_have_bump_value = true; return NULL; } int main(int argc, char const *argv[]) { char input_file_name[MAX_LINE_LENGTH + 1] = {0}; char output_file_name[MAX_LINE_LENGTH + 1] = {0}; char bump_level[MAX_LINE_LENGTH + 1] = {0}; char *error; // Process command-line arguments if (argc == 1) { // There are no arguments. We need to obtain the values required through user input. store_file_name_in(&quot;Enter file name to process : &quot;, input_file_name, true); store_bump_level_in(bump_level); if (read_confirmation()) { strcpy(output_file_name, input_file_name); } else { store_file_name_in(&quot;Enter output file name : &quot;, output_file_name, false); } } else if (argc == 2) { // Help and version commands. // In all cases, the program will never execute code afterwards outside this block. error = process_single_switch(argv[1]); if (error) { puts(error); return EXIT_FAILURE; } else { return EXIT_SUCCESS; } } else if (argc % 2 == 0) { // The pairs are mismatched puts(INCORRECT_USAGE); return EXIT_FAILURE; } else { // The parameters should be present in pairs. // The count must be odd because the name of the executable is the first argument. bool we_have_input_path = false; bool we_have_bump_value = false; bool we_have_output_path = false; strcpy(bump_level, &quot;patch&quot;); // Iterate pair wise. We do not care about the order in which // the pairs appear. We are only interested in the values, and // if they are valid for the switch given. for (size_t index = 1; index &lt; argc; index += 2) { // The first of the pair should be a switch if (argv[index][0] != '-') { puts(INCORRECT_USAGE); return EXIT_FAILURE; } size_t arg_len = strlen(argv[index]); if (arg_len == 2) { // Abbreviated switch switch (argv[index][1]) { case 'i': error = process_input_path_value(input_file_name, &amp;we_have_input_path, argv[index + 1]); if (error) { puts(error); return EXIT_FAILURE; } break; case 'l': error = process_bump_value(bump_level, &amp;we_have_bump_value, argv[index + 1]); if (error) { puts(error); return EXIT_FAILURE; } break; case 'o': error = process_output_path_value(output_file_name, &amp;we_have_output_path, argv[index + 1]); if (error) { puts(error); return EXIT_FAILURE; } break; default: puts(INCORRECT_USAGE); return EXIT_FAILURE; } } else { // Switch is not abbreviated if (strcmp(argv[index], &quot;--input&quot;) == 0) { error = process_input_path_value(input_file_name, &amp;we_have_input_path, argv[index + 1]); if (error) { puts(error); return EXIT_FAILURE; } } else if (strcmp(argv[index], &quot;--level&quot;) == 0) { error = process_bump_value(bump_level, &amp;we_have_bump_value, argv[index + 1]); if (error) { puts(error); return EXIT_FAILURE; } } else if (strcmp(argv[index], &quot;--output&quot;) == 0) { error = process_output_path_value(output_file_name, &amp;we_have_output_path, argv[index + 1]); if (error) { puts(error); return EXIT_FAILURE; } } } } if (!we_have_input_path) { puts(&quot;Input file not specified.&quot;); return EXIT_FAILURE; } if (!we_have_output_path) { strcpy(output_file_name, input_file_name); } } bool inplace = strcmp(input_file_name, output_file_name) == 0; if (inplace) { // Check if we can create the file for writing if (!file_is_valid(INTERMEDIATE_FILE, &quot;w&quot;)) { puts(&quot;Could not create temporary file for writing.&quot;); return EXIT_FAILURE; } // Mark the output as the temporary. strcpy(output_file_name, INTERMEDIATE_FILE); } FileState state = {0}; initialize_file_state(&amp;state, input_file_name, output_file_name, bump_level, MAX_LINE_LENGTH); while (!process_file(&amp;state)) ; if (inplace) { int c; FILE *temp = fopen(INTERMEDIATE_FILE, &quot;r&quot;); FILE *dump = fopen(input_file_name, &quot;w&quot;); while ((c = fgetc(temp)) != EOF) { fputc(c, dump); } fclose(temp); fclose(dump); remove(INTERMEDIATE_FILE); } return EXIT_SUCCESS; } </code></pre> <h1>Unit tests</h1> <p>I use <a href="https://nemequ.github.io/munit/" rel="nofollow noreferrer">µnit</a> for unit testing. These are the tests that I have in place for CI/CD checks on Github</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;bump/bump.h&gt; #include &lt;bump/version.h&gt; #include &lt;munit.h&gt; /* * * UNIT TEST FUNCTIONS * =================== * * All unit tests are of the form: * * MunitResult &lt;test_name&gt;(const MunitParameter params[], * void *user_data_or_fixture) { * // perform tests. * // use the munit_assert_... macros. * return MUNIT_OK; * } * * It is necessary for the unit test functions to be added to * the `test` array. */ MunitResult bump_patch_0_0_1() { Version version = {0}; munit_assert_null(initialize_version(&amp;version, 0, 0, 1)); bump_patch(&amp;version); munit_assert(version.major == 0); munit_assert(version.minor == 0); munit_assert(version.patch == 2); return MUNIT_OK; } MunitResult bump_patch_0_0_15() { Version version = {0}; munit_assert_null(initialize_version(&amp;version, 0, 0, 15)); bump_patch(&amp;version); munit_assert(version.major == 0); munit_assert(version.minor == 0); munit_assert(version.patch == 16); return MUNIT_OK; } MunitResult bump_minor_0_0_23() { Version version = {0}; munit_assert_null(initialize_version(&amp;version, 0, 0, 23)); bump_minor(&amp;version); munit_assert(version.major == 0); munit_assert(version.minor == 1); munit_assert(version.patch == 0); return MUNIT_OK; } MunitResult bump_major_0_2_8() { Version version = {0}; munit_assert_null(initialize_version(&amp;version, 0, 2, 8)); bump_major(&amp;version); munit_assert(version.major == 1); munit_assert(version.minor == 0); munit_assert(version.patch == 0); return MUNIT_OK; } MunitResult convert_0_0_1() { char line[16]; Version version = {0}; munit_assert_null(initialize_version(&amp;version, 0, 0, 1)); size_t len; munit_assert_null(convert_to_string(&amp;version, line, &amp;len)); munit_assert_string_equal(line, &quot;0.0.1&quot;); munit_assert(len == 5); return MUNIT_OK; } MunitResult convert_4_23_56() { char line[16]; Version version = {0}; munit_assert_null(initialize_version(&amp;version, 4, 23, 56)); size_t len; munit_assert_null(convert_to_string(&amp;version, line, &amp;len)); munit_assert_string_equal(line, &quot;4.23.56&quot;); munit_assert(len == 7); return MUNIT_OK; } MunitResult process_line_0_1_1() { char line[10] = {0}; const char *input_line = &quot;v0.1.1&quot;; LineState state = {0}; initialize_line_state(&amp;state, input_line, line, strlen(input_line)); munit_assert_null(process_line(&amp;state, &quot;patch&quot;)); munit_assert_string_equal(line, &quot;v0.1.2&quot;); munit_assert_size(state.input_index, ==, 6); munit_assert_size(state.output_index, ==, 6); return MUNIT_OK; } MunitResult process_line_1_1_51() { char line[40] = {0}; const char *input_line = &quot;2.5 is a number 1.1.51 is the version&quot;; LineState state = {0}; initialize_line_state(&amp;state, input_line, line, strlen(input_line)); munit_assert_null(process_line(&amp;state, &quot;minor&quot;)); munit_assert_string_equal(line, &quot;2.5 is a number 1.2.0 is the version&quot;); munit_assert_size(state.input_index, ==, 22); munit_assert_size(state.output_index, ==, 21); return MUNIT_OK; } MunitResult process_two() { char line[50] = {0}; char buffer[50] = {0}; const char *input_line = &quot;First we (12) have 1.6.84, then we have 8.16.3!&quot;; LineState state = {0}; initialize_line_state(&amp;state, input_line, line, strlen(input_line)); munit_assert_null(process_line(&amp;state, &quot;patch&quot;)); munit_assert_string_equal(line, &quot;First we (12) have 1.6.85, then we have 8.16.3!&quot;); munit_assert_size(state.input_index, ==, 25); munit_assert_size(state.output_index, ==, 25); strcpy(buffer, line); munit_assert_null(process_line(&amp;state, &quot;major&quot;)); munit_assert_string_equal(line, &quot;First we (12) have 1.6.85, then we have 9.0.0!&quot;); munit_assert_size(state.input_index, ==, 46); munit_assert_size(state.output_index, ==, 45); return MUNIT_OK; } MunitResult process_test_cases() { // Things to update: // 1. the `count` variable - stores the number of test cases // 2. the `input_lines` array - stores the input lines // 3. the `expected_lines` array - stores 3 types of outputs for each input line. The order is patch, minor, major const size_t count = 5;// &lt;- update this const size_t max_line_width = 256; char line[max_line_width]; char copy[max_line_width]; const char *bump_levels[] = {&quot;patch&quot;, &quot;minor&quot;, &quot;major&quot;}; const char *input_lines[] = { &quot;&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;&quot;, &quot;#define VERSION \&quot;0.3.56\&quot;&quot;, &quot;2.5 is a number but 1.0.7 is a version&quot;, &quot;8.0. is not a version&quot;, &quot;Let's put one at the end 9.&quot;, }; // ^ // +-- Add new input lines at the end const char *expected_lines[] = { &quot;&lt;modelVersion&gt;4.0.1&lt;/modelVersion&gt;&quot;, &quot;&lt;modelVersion&gt;4.1.0&lt;/modelVersion&gt;&quot;, &quot;&lt;modelVersion&gt;5.0.0&lt;/modelVersion&gt;&quot;, &quot;#define VERSION \&quot;0.3.57\&quot;&quot;, &quot;#define VERSION \&quot;0.4.0\&quot;&quot;, &quot;#define VERSION \&quot;1.0.0\&quot;&quot;, &quot;2.5 is a number but 1.0.8 is a version&quot;, &quot;2.5 is a number but 1.1.0 is a version&quot;, &quot;2.5 is a number but 2.0.0 is a version&quot;, &quot;8.0. is not a version&quot;, &quot;8.0. is not a version&quot;, &quot;8.0. is not a version&quot;, &quot;Let's put one at the end 9.&quot;, &quot;Let's put one at the end 9.&quot;, &quot;Let's put one at the end 9.&quot;, }; // ^ // +-- Add the three variations of the outputs at the end. Remember, the order is // patch, minor, major for (size_t index = 0; index &lt; count; ++index) { strcpy(line, input_lines[index]); for (size_t bump_index = 0; bump_index &lt; 3; ++bump_index) { memset(copy, 0, max_line_width); LineState state = {0}; munit_assert_null(initialize_line_state(&amp;state, line, copy, max_line_width)); while (state.input_index &lt; state.limit) { process_line(&amp;state, bump_levels[bump_index]); } munit_assert_string_equal(expected_lines[index * 3 + bump_index], copy); } } return MUNIT_OK; } /* * MUNIT TEST CONFIGURATION * ======================== * * Boilerplate code for the munit testing library. * The last NULL test item acts as a sentinel. */ MunitTest tests[] = { {&quot;/bump_patch_0_0_1&quot;, bump_patch_0_0_1, NULL, NULL, MUNIT_TEST_OPTION_NONE, NULL}, {&quot;/bump_patch_0_0_15&quot;, bump_patch_0_0_15, NULL, NULL, MUNIT_TEST_OPTION_NONE, NULL}, {&quot;/bump_minor_0_0_23&quot;, bump_minor_0_0_23, NULL, NULL, MUNIT_TEST_OPTION_NONE, NULL}, {&quot;/bump_major_0_2_8&quot;, bump_major_0_2_8, NULL, NULL, MUNIT_TEST_OPTION_NONE, NULL}, {&quot;/convert_0_0_1&quot;, convert_0_0_1, NULL, NULL, MUNIT_TEST_OPTION_NONE, NULL}, {&quot;/convert_4_23_56&quot;, convert_4_23_56, NULL, NULL, MUNIT_TEST_OPTION_NONE, NULL}, {&quot;/process_line_0_1_1&quot;, process_line_0_1_1, NULL, NULL, MUNIT_TEST_OPTION_NONE, NULL}, {&quot;/process_line_1_1_51&quot;, process_line_1_1_51, NULL, NULL, MUNIT_TEST_OPTION_NONE, NULL}, {&quot;/process_two&quot;, process_two, NULL, NULL, MUNIT_TEST_OPTION_NONE, NULL}, {&quot;/process_test_cases&quot;, process_test_cases, NULL, NULL, MUNIT_TEST_OPTION_NONE, NULL}, {NULL, NULL, NULL, NULL, MUNIT_TEST_OPTION_NONE, NULL}}; static const MunitSuite suite = {&quot;/bump-test-suite&quot;, tests, NULL, 1, MUNIT_SUITE_OPTION_NONE}; /* * MAIN FUNCTION * ============= */ int main(int argc, char *argv[]) { printf(&quot;Bump project version: %s\n\n&quot;, BUMP_VERSION); return munit_suite_main(&amp;suite, NULL, argc, argv); } </code></pre> <h1>Specific concerns</h1> <ol> <li>The <code>process_line</code> function seems a bit repetitive but that's the best I could think of. Any suggestions to improve this?</li> <li>Are there any potential security issues? Does anything seem like blasphemy?</li> <li>What could I do to improve the project in general?</li> </ol> <h1>Edit: Agreement with <a href="https://codereview.stackexchange.com/a/251095/37479">G. Sliepen</a></h1> <p>My main intention was to make a working prototype and get some eyeballs on this project as soon as possible. This is one of the reasons why I didn't jump the gun and release it as version 1.0.0. It's still at <a href="https://github.com/hungrybluedev/bump/releases/" rel="nofollow noreferrer">0.0.8</a>.</p> <p>I will create a follow-up post addressing (some of) the following issues:</p> <ol> <li>Writing error messages to <code>stderr</code>. This was an oversight on my part.</li> <li>Checking the error messages returned by my functions. Overconfidence and tiredness. Will fix.</li> <li>Avoiding TOCTOU. I wasn't aware of this. I will consider it from now on.</li> <li>Writing to buffers blindly. I will use the size safe variants of the functions.</li> <li>Check for overflows when reading in values. I will prefer using <code>strtoull</code> and other related functions properly.</li> <li>About hard-coding file lengths: this I mean to change eventually. I want the interactive input file length to be limited, while the actual files being operated on can have any arbitrary file length.</li> <li>Processing files in chunks instead of byte-by-byte. This is just a prototype and I will eventually work on improving the performance. I will take care of this as well.</li> <li>More rigorous error-checking in general. Won't hurt; will help a lot.</li> </ol> <p>There are a few reasons why I do not want to use third-party libraries:</p> <ol> <li>While I agree that using a regular expression library will make my code easier to read, I doubt it will be faster. Also, I'm learning about Automata Theory - this is practice for my future projects.</li> <li>Finding compatible licenses is difficult. Best to avoid controversy and write everything myself. Less hoops to jump through if something needs fixing.</li> <li>I know I'm re-inventing the wheel. I've been told this several times. But it's the only way I've ever learned a lot really quickly.</li> <li>I try to <a href="https://github.com/nothings/stb/blob/master/docs/stb_howto.txt" rel="nofollow noreferrer">avoid using malloc</a>.</li> <li>I'm writing this for all the three major OS's: Windows, MacOS and Linux.</li> </ol> <p>I'm open to more suggestions and recommendations. I take all relevant feedback into account.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T17:18:11.140", "Id": "494167", "Score": "0", "body": "Compiled regular expressions will often beat hand-rolled parsers. It's not that hard to find MIT and BSD licensed libraries, you really should not try to implement everything yourself. While it's great to do that to learn things, it's not great for maintainability of your software projects. And consider the art of finding and using libraries also something worth learning ;) Avoiding *unnecessary* `malloc()` calls is great, but don't make this a religion. And it's great that you try to write cross-platform code!" } ]
[ { "body": "<p>There is quite a lot to remark. In general, I think you spend too much time implementing things by hand, when the functionality is also found in the standard library or other commonly available libraries. Furthermore, your program does not do proper error checking, possibly causing silent data corruption. Here is a list of issues I found:</p>\n<h1>Typedefs</h1>\n<p>When creating a <code>struct</code> and <code>typedef</code>'ing, I would ensure the names are the same. There is nothing to gain from making the <code>struct</code>'s name snake_case with a <code>_struct</code> at the end, but <code>typedef</code> it to something PascalCase. Just write:</p>\n<pre><code>typedef struct Version {\n ...\n} Version;\n</code></pre>\n<h1>Don't <code>return</code> error messages</h1>\n<p>Instead of <code>return</code>ing a string to indicate an error, I strongly recommend you return a <code>bool</code> instead to signal success, and either print the error message right where it happens, or possibly store it in a global variable.</p>\n<p>Note that you are also casting away the <code>const</code>ness of the string literals by having the return values be <code>char *</code>. Consider using the <code>-Wwrite-strings</code> option if you are using Clang or GCC to have it warn about this.</p>\n<p>If you want to keep your code short you can still write one-liners for both methods mentioned:</p>\n<pre><code>extern const char *errmsg;\n...\nbool some_function(...) {\n ...\n if (/* error condition */)\n return fprintf(stderr, &quot;An error occurred!\\n&quot;), false;\n if (/* some other error */)\n return errmsg = &quot;Another error occurred!&quot;, false;\n else\n return true;\n}\n</code></pre>\n<h1>Write error messages to <code>stderr</code></h1>\n<p>Don't write error messages to the standard output, as this can cause undesired behaviour if, for example, the regular output is also written to standard output, or if it is redirected somewhere else. Consider for example the following, slightly contrived example:</p>\n<pre><code>bump -i input.txt -l minor -o /dev/stdout &gt;output.txt\n</code></pre>\n<h1>Actually check the return value of your functions</h1>\n<p><code>intialize_file_state()</code> returns a value indicating whether an error occured or not, but you ignore it when calling that function from <code>main()</code>.</p>\n<h1>Avoid <a href=\"https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use\" rel=\"noreferrer\">TOCTOU</a> bugs</h1>\n<p>You first call <code>file_is_valid()</code> to check if a file can be opened, and then call the real <code>fopen()</code>. Something can happen between the check if the file is valid and the second call to <code>fopen()</code>, so that latter can still fail. The proper way is to not use <code>file_is_valid()</code> at all, but do the error checking on the other calls to <code>fopen()</code>.</p>\n<h1>Never write to buffers you don't know the size of</h1>\n<p>In <code>convert_to_string()</code>, you are happily writing to <code>output_buffer</code> without knowing its size. Ensure you pass the length of the output buffer as a parameter to the function. You can reuse <code>length</code> for that: have the caller set it to the size of the output buffer. Use <code>snprintf()</code> instead of <code>sprintf()</code> to ensure you don't write past the end of the output buffer. You also need to check the return value for both negative values and values larger than the size of the output buffer, since that will indicate that not every character could be written.</p>\n<h1>Check for numbers larger than can fit in a <code>size_t</code></h1>\n<p>In <code>extract_decimal_numbers()</code>, you will happily read in a number with hundreds of digits, overflowing <code>value</code> in the process. It is better to avoid doing this kind of parsing yourself, and instead use <a href=\"https://en.cppreference.com/w/c/string/byte/strtoul\" rel=\"noreferrer\"><code>strtoul()</code></a>, paying close attention to its return value to check if it signals an overflow.</p>\n<h1>Consider using regular expressions to parse the input</h1>\n<p>The task of finding a version number string in a line of text is easier if you can use regular expressions. On POSIX systems, you can use <a href=\"https://man7.org/linux/man-pages/man3/regcomp.3.html\" rel=\"noreferrer\"><code>regcomp()</code></a>, <code>regexec()</code> and related functions to do this. Alternatively, you can use an external library, such as <a href=\"https://www.pcre.org/\" rel=\"noreferrer\">PCRE</a>. This will greatly simplify your code, and will likely be much more efficient.</p>\n<h1>Avoid hardcoding line lengths</h1>\n<p>Are you absolutely sure no file will have lines longer than 511 bytes? What about 1023 bytes? There is no way to tell. Do you want your program to be responsible for inadvertently cutting of parts of long lines? Either exit with an error message and non-zero exit code if you couldn't handle the input correctly, or ensure your program handles arbitrary line lengths in some way. There are various ways to do the latter:</p>\n<ul>\n<li>Resize the line buffers when you detect they are not large enough.</li>\n<li>Keep a small buffer, but after processing the contents of the buffer, read in the next part of the line in the buffer and process that. Of course, you need to handle the case of a version number crossing the boundary of the buffer correctly.</li>\n<li>Use <a href=\"https://man7.org/linux/man-pages/man2/mmap.2.html\" rel=\"noreferrer\"><code>mmap()</code></a> to map the whole file into memory. This might not be possible for multi-gigabyte files on a 32-bit platform though.</li>\n</ul>\n<h1>Use <code>getopt()</code> to parse command-line arguments</h1>\n<p>On POSIX systems, you can use <a href=\"https://man7.org/linux/man-pages/man3/getopt.3.html\" rel=\"noreferrer\"><code>getopt()</code></a> and likely also <a href=\"https://man7.org/linux/man-pages/man3/getopt_long.3.html\" rel=\"noreferrer\"><code>getopt_long()</code></a> to parse command-line arguments. This is vastly simpler than hand-rolling your own argument parser. If you are compiling for Windows, try to find a <a href=\"https://stackoverflow.com/questions/10404448/getopt-h-compiling-linux-c-code-in-windows\">library implementing <code>getopt()</code></a> and use that.</p>\n<h1>Make <code>process_file()</code> process the whole file</h1>\n<p>Why does <code>process_file()</code> only process a single line? It already has a <code>while</code>-loop, just don't call <code>return NULL</code> after processing each line. Also, when you have processed the whole file, that is expected behaviour and not an error, so you shouldn't return an error in that case. With that changed, you no longer need to call it from inside a <code>while</code>-loop in <code>main()</code>.</p>\n<h1>Avoid processing files byte by byte</h1>\n<p>There are several places where you read one byte at a time from a file. That is quite inefficient. Even though the data is cached, the overhead of the function calls will slow down your program unnecessarily. This is especially the case when copying the intermediate file back to the original file. Try to use a large buffer (4 kilobytes is a nice value for various reasons), and use <a href=\"https://en.cppreference.com/w/c/io/fread\" rel=\"noreferrer\"><code>fread()</code></a> and <a href=\"https://en.cppreference.com/w/c/io/fwrite\" rel=\"noreferrer\"><code>fwrite()</code></a> to read a whole buffer at a time.</p>\n<h1>Also check whether writing the output succeeded</h1>\n<p>While you have some error checking when reading the input file, there is no error checking done while writing to the output file after you have opened it. Check the return value of <code>fprintf()</code> when writing a line to the output file, and also <a href=\"https://stackoverflow.com/questions/1954273/fclose-return-value-check\">check the return value of <code>fclose()</code></a>!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T16:25:54.990", "Id": "494158", "Score": "0", "body": "Thank you for taking the time to post a detailed answer! I agree with your answer for the most part. I wanted to ask a few questions: Why should the struct name and the typedef name be the same? Why is it bad to return `char *` (or more appropriately `const char *`) instead of the `bool` and global variable combination you mentioned? And besides having decades of field experience, are there any books or whitepapers you recommend for people in academia (like me) to learn the best practices for C programming? (I will update my post to acknowledge the other points you have mentioned shortly.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T17:04:00.013", "Id": "494165", "Score": "0", "body": "But why would you make the struct and typedef name different? There is no point in adding possible confusion. The problem with returning an error message is that the error message is just for human consumption. Error codes, booleans and so on are easier for the program to deal with internally. With strings, there is also possible confusion, like what if a function returns `\"\"`, or `\"Success\"` instead of `NULL`? You'll also note that the standard library and many other libraries never return error strings." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T17:09:53.617", "Id": "494166", "Score": "1", "body": "My own decades of field experience, a large part of them in academia as well, have told me that there is no single source of knowledge that will teach you everything. As for books I've only read [K&R's C 2nd edition](https://en.wikipedia.org/wiki/The_C_Programming_Language), while a great book it's not exactly the best source for software engineering practices. Maybe someone else can give better advice. But keep programming, look at how other software is written, and send your code for reviews :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T18:51:10.223", "Id": "494192", "Score": "0", "body": "I suppose the `bool` approach does seem more robust. Need to do some aggressive refactoring now. I'll inform you when I write a follow up to this post." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T15:02:07.700", "Id": "251095", "ParentId": "251090", "Score": "4" } } ]
{ "AcceptedAnswerId": "251095", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T13:29:08.567", "Id": "251090", "Score": "5", "Tags": [ "c", "file", "console" ], "Title": "Command-line utility to bump semantic version numbers in an input file" }
251090
<p>This is the follow-up question for <a href="https://codereview.stackexchange.com/q/251060/231235">A recursive_transform Function For Various Type Nested Iterable With std::variant Implementation in C++</a>. As <a href="https://codereview.stackexchange.com/a/251072/231235">G. Sliepen's answer</a> mentioned, leaving only recursively transforming operation for <code>recursive_transform()</code> may be a better idea. As the result, the implementation of <code>recursive_transform</code> function is kept in the following form. Moreover, the forward declarations have been removed.</p> <pre><code>template&lt;class T, class _Fn&gt; requires is_iterable&lt;T&gt; static inline T recursive_transform(const T input, _Fn func) { T returnObject = input; std::transform(input.begin(), input.end(), returnObject.begin(), func); return returnObject; } template&lt;class T, class _Fn&gt; requires is_iterable&lt;T&gt; &amp;&amp; is_element_iterable&lt;T&gt; static inline T recursive_transform(const T input, _Fn func) { T returnObject = input; std::transform(input.begin(), input.end(), returnObject.begin(), [func](const auto&amp; element) { return recursive_transform(element, func); } ); return returnObject; } </code></pre> <p>However, I still want to handle the compound structure with ranges and <code>std::variant</code>, such as <code>std::vector&lt;std::variant&lt;double&gt;&gt;</code>. A new function <code>get_from_variant</code> comes up in my mind in order to focus on the operations with these things.</p> <pre><code>template&lt;typename T_variant, typename T&gt; static inline auto get_from_variant(T_variant input_variant) { T return_val; std::visit([&amp;](auto&amp;&amp; arg) { return_val = static_cast&lt;T&gt;(arg); return arg; }, input_variant); return return_val; } </code></pre> <p>The tests of this <code>get_from_variant</code> function:</p> <pre><code>int main() { // get_from_variant function test std::variant&lt;double&gt; testNumber = 1; std::cout &lt;&lt; get_from_variant&lt;decltype(testNumber), double&gt;(testNumber); // The usage of recursive_transform function and get_from_variant function std::variant&lt;double&gt; variant_number = 3.14; std::vector&lt;decltype(variant_number)&gt; testVector1; testVector1.push_back(variant_number); testVector1.push_back(variant_number); testVector1.push_back(variant_number); std::cout &lt;&lt; get_from_variant&lt;std::variant&lt;double&gt;, double&gt;(recursive_transform(testVector1, [](auto x){ return get_from_variant&lt;std::variant&lt;double&gt;, double&gt;(x) + 1; }).at(0)) &lt;&lt; std::endl; return 0; } </code></pre> <p>All suggestions are welcome.</p> <ul> <li><p>Which question it is a follow-up to?</p> <p><a href="https://codereview.stackexchange.com/q/251060/231235">A recursive_transform Function For Various Type Nested Iterable With std::variant Implementation in C++</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <p>In order to handle the compound structure with ranges and <code>std::variant</code>, such as <code>std::vector&lt;std::variant&lt;double&gt;&gt;</code> in a better way, a new function <code>get_from_variant</code> has been created.</p> </li> <li><p>Why a new review is being asked for?</p> <p>In my opinion, I am not sure whether the design of the function <code>get_from_variant</code> is good? Is the idea or the usage good or not? Any comment is welcome.</p> </li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T21:06:50.880", "Id": "494197", "Score": "1", "body": "`get_from_variant()` might not be the best name, as there's already [`std::get()`](https://en.cppreference.com/w/cpp/utility/variant/get) for variants. Some languages already have a `variant_cast`, but that casts between two different variants. Maybe `get_as()` is better?" } ]
[ { "body": "<p>I haven't been following this thread from the beginning, so I'm more confused than you expect readers to be by this point. It would be a good idea for you to provide a complete compilable example each time — even just as a Godbolt link, if you want to keep the question's focus on some little piece of the code.</p>\n<p>In fact, I <em>prefer</em> to see a Godbolt link (<em>in addition</em> to seeing the code in the question as you correctly have done), as it saves me the trouble of pasting your code into Godbolt myself. :) Here's a link to your code: <a href=\"https://godbolt.org/z/5PqxPx\" rel=\"nofollow noreferrer\">Godbolt</a>.</p>\n<hr />\n<pre><code>std::variant&lt;double&gt; testNumber = 1;\n</code></pre>\n<p>This doesn't compile in C++20. Did it use to? If so, yikes, that's a pretty big API break for C++... but not your problem. Anyway, change it to <code>1.0</code> and recompile.</p>\n<hr />\n<pre><code>template&lt;typename T_variant, typename T&gt;\nstatic inline auto\n</code></pre>\n<p>Lose the <code>static inline</code>. Templates are effectively inline by definition, and you don't <em>want</em> this template to be static — you don't <em>want</em> to force each translation unit to keep its own unique copy (in the case that it's not optimized away by the inliner).</p>\n<p>I'm not a fan of <code>Giraffe_case</code>. Template parameter names should be short and <code>CamelCase</code>; here I recommend <code>V</code>.</p>\n<p>Your <code>std::visit</code> lambda has a useless <code>return arg;</code>. In fact, this entire function should look more like</p>\n<pre><code>template&lt;class V, class T&gt;\nauto get_from_variant(V input) {\n return std::visit([&amp;](auto&amp;&amp; arg) {\n return static_cast&lt;T&gt;(arg);\n }, input);\n}\n</code></pre>\n<p>With the cruft removed, we have brain cells free to focus on the next level of pedantry: You're taking <code>arg</code> by forwarding reference (<code>auto&amp;&amp;</code>), but you're not actually forwarding it to the <code>static_cast</code>. Maybe we should use <code>static_cast&lt;T&gt;(static_cast&lt;decltype(arg)&gt;(arg))</code> here, so that if <code>arg</code> is an rvalue reference, it'll get moved into <code>T</code>'s constructor?</p>\n<p>But wait; <code>arg</code> will <em>never</em> be an rvalue reference, because we're visiting an lvalue <code>input</code>! So maybe we shouldn't expect to modify the <code>arg</code> we visit — we could take it as <code>const auto&amp; arg</code>. But if we don't expect to modify <code>input</code>, maybe <em>it</em> should be taken by— yeah, wait a minute, why are we making a copy of <code>input</code> here? Just take it by const reference to begin with!</p>\n<pre><code>template&lt;class V, class T&gt;\nauto get_from_variant(const V&amp; input) {\n return std::visit([](const auto&amp; arg) {\n return static_cast&lt;T&gt;(arg);\n }, input);\n}\n</code></pre>\n<p>I've dropped the <code>[&amp;]</code> from the lambda, since it doesn't require any captures.</p>\n<p>We should also look at the template parameters to <code>get_from_variant</code>. <code>V</code> can be deduced and <code>T</code> can't; it always always always makes sense to put non-deducible parameters first.</p>\n<pre><code>template&lt;class T, class V&gt;\nauto get_from_variant(const V&amp; input) {\n return std::visit([](const auto&amp; arg) {\n return static_cast&lt;T&gt;(arg);\n }, input);\n}\n</code></pre>\n<p>Now our main driver looks like <a href=\"https://godbolt.org/z/qxoac1\" rel=\"nofollow noreferrer\">this</a>:</p>\n<pre><code>std::variant&lt;double&gt; testNumber = 1.0;\nstd::cout &lt;&lt; get_from_variant&lt;double&gt;(testNumber);\n \nstd::vector testVector1 = {\n std::variant&lt;double&gt;(3.14),\n std::variant&lt;double&gt;(3.14),\n std::variant&lt;double&gt;(3.14),\n};\nstd::cout &lt;&lt; get_from_variant&lt;double&gt;(\n recursive_transform(testVector1, [](const auto&amp; x){\n return get_from_variant&lt;double&gt;(x) + 1;\n }).at(0)\n) &lt;&lt; std::endl;\n</code></pre>\n<hr />\n<p>Meanwhile, in <code>recursive_transform</code>, you have a typo: <code>const T input</code> when you meant <code>const T&amp; input</code>. <a href=\"https://quuxplusone.github.io/blog/2019/01/03/const-is-a-contract/\" rel=\"nofollow noreferrer\">You can mechanically grep for these typos,</a> and you should!</p>\n<ul>\n<li><p>Again, remove <code>static inline</code> from templates.</p>\n</li>\n<li><p>The name <code>_Fn</code> is reserved for the implementation; just use <code>F</code>.</p>\n</li>\n<li><p>Copying <code>func</code> into the lambda isn't necessary; you should use <code>[&amp;]</code> as your default for every lambda you write (unless, as above, you can get away with plain <code>[]</code>).</p>\n</li>\n<li><p>Honestly, unless you are <em>rabid</em> about following STL idioms, just pass the callback <code>F</code> by const reference and avoid ever copying it. There is a place in C++ for stateful, mutable callbacks, but <code>transform</code> is not that place.</p>\n</li>\n<li><p>Your base case is more complicated than it needs to be. Let's fix that.</p>\n</li>\n</ul>\n<p>Putting it all together:</p>\n<pre><code>template&lt;class T, class F&gt;\nT recursive_transform(const T&amp; input, const F&amp; f) {\n return f(input);\n}\n\ntemplate&lt;class T, class F&gt; requires is_iterable&lt;T&gt;\nT recursive_transform(const T&amp; input, const F&amp; f) {\n T returnObject = input;\n std::transform(input.begin(), input.end(), returnObject.begin(),\n [&amp;](const auto&amp; element) {\n return recursive_transform(element, f);\n }\n );\n return returnObject;\n}\n</code></pre>\n<p>And then, it really seems to me that using <code>std::transform</code> here is overkill: it reads from <code>input</code> <em>twice</em>, once to make the copy and again to do the transform. Suppose we just open-coded it, like this?</p>\n<pre><code>template&lt;class T, class F&gt; requires is_iterable&lt;T&gt;\nT recursive_transform(const T&amp; input, const F&amp; f) {\n T output = input;\n for (auto&amp;&amp; elt : output) {\n elt = recursive_transform(elt, f);\n }\n return output;\n}\n</code></pre>\n<p>Of course we <em>could</em> use C++20 Ranges to do something like <a href=\"https://godbolt.org/z/xzYddq\" rel=\"nofollow noreferrer\">this</a>:</p>\n<pre><code>template&lt;class T, class F&gt; requires is_iterable&lt;T&gt;\nT recursive_transform(const T&amp; input, const F&amp; f) {\n auto transformed = input | std::views::transform([&amp;](auto&amp;&amp; x) {\n return recursive_transform(x, f);\n });\n return T(transformed.begin(), transformed.end());\n}\n</code></pre>\n<p>That's slower to compile and generates bigger code — but it might indeed be faster at runtime, if <code>T::value_type</code> is expensive to copy, because we're eliminating the copy-assignments on <code>T::value_type</code> — we're just constructing directly in place.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T00:27:35.750", "Id": "494205", "Score": "0", "body": "Thank you for answering. I've not noticed that `std::variant<double> testNumber = 1;` doesn't compile in GCC and I just tested that it can be compiled in MSVC v19.27. https://godbolt.org/z/9Trv9z" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T00:40:39.690", "Id": "494207", "Score": "1", "body": "@JimmyHu Protip: Clang on Godbolt uses libstdc++ by default (because Linux). If you want to test the LLVM project's libc++, you have to pass `-stdlib=libc++`, [like so](https://godbolt.org/z/z11jaj). (It also fails to compile with libc++.) The cpplang Slack tells me that this is known fallout from [P0608](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p0608r3.html), and so it's MSVC that is lagging the other vendors here." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T16:08:41.013", "Id": "251098", "ParentId": "251091", "Score": "2" } } ]
{ "AcceptedAnswerId": "251098", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T14:23:15.530", "Id": "251091", "Score": "2", "Tags": [ "c++", "c++20" ], "Title": "A get_from_variant function in C++" }
251091
<p>CodeReview Community! I was hoping you'd be able to review my basic OOP program. Last year I did a strictly procedural one and now I’ve incorporated OOP techniques. Ignore the commented out piece of code. The Hungarian Notation is a requirement for my university course so please don’t criticise the fact I’ve used it. I’d like to know what I’ve done well vs what I haven’t and any suggestions in making my code better. Many thanks in advance. The following scenario is what I’ve based the program on:</p> <blockquote> <p>Scenario A reputable bank has asked you to create a personal finance management program. The program will need to be able to take the user's monthly wage, their monthly bills, and any weekly bills that they may occur. This will then be broken down to find out how much of their wages they will then have left to save.</p> <p>The user should be able to enter any amount of monthly bills and weekly bills. The user should also have the option to add other users from their household to be handled within the calculations.</p> <p>Once all of the relevant information has been included, an overview of the bills against a weekly, monthly and yearly cost should be output.</p> <p>Inputs User's Name (Must be more than 1) Monthly Wage (Must be more than 1) The different bills the user has to pay (Per Person) Outputs User's Name Weekly, Monthly, Yearly Wage Total Weekly, Monthly, Yearly Bills Total Total Spent on Bills Total left to Save 10% over and under the total that can be saved How much can be saved per month 10% over and under the total that can be saved per month</p> </blockquote> <pre><code>// Personal Finance Tool.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;memory&gt; #include &quot;Utils.h&quot; class Bill { private: std::string m_sBillName; double m_dMonthlyBill; public: Bill(std::string sBillName, double dMonthlyBill) :m_sBillName(sBillName),m_dMonthlyBill(dMonthlyBill) {} double GetMonthlyBill() { return m_dMonthlyBill; } }; class User { private: std::string m_sName; double m_dMonthlyWage; std::vector&lt;Bill&gt;objBillsToPay; public: User(std::string sName, double dMonthlyWage) :m_sName(sName), m_dMonthlyWage(dMonthlyWage) {} void AddBill(std::string sBillName, double dMonthlyBill) { objBillsToPay.push_back({ sBillName, dMonthlyBill }); } double WeeklyWage() { return m_dMonthlyWage / 4; } double YearlyWage() { return m_dMonthlyWage * 12; } double TotalSpentOnBills() { double dTotal = 0; for (Bill &amp;objBill : objBillsToPay) { dTotal += objBill.GetMonthlyBill(); } return dTotal; } double LeftToSaveMonthly() { return (YearlyWage() / 12) - (TotalSpentOnBills() / 12); } double TotalLeftToSaveYearly() { return YearlyWage() - TotalSpentOnBills(); } double OverSaved() { return TotalLeftToSaveYearly() * 0.10; } double UnderSaved() { return TotalLeftToSaveYearly() - (TotalLeftToSaveYearly() * 0.10); } }; void DisplayResults(std::vector&lt;User&gt;&amp; objUsers) { for (User&amp; objUser : objUsers) { std::cout &lt;&lt; &quot;***&quot; &lt;&lt; std::endl; std::cout &lt;&lt; &quot;Weekly wage: &quot; &lt;&lt; objUser.WeeklyWage() &lt;&lt; std::endl; std::cout &lt;&lt; &quot;Yearly wage: &quot; &lt;&lt; objUser.YearlyWage() &lt;&lt; std::endl; std::cout &lt;&lt; &quot;10% over total that can be saved: &quot; &lt;&lt; objUser.OverSaved() &lt;&lt; std::endl; std::cout &lt;&lt; &quot;10% under total that can be saved: &quot; &lt;&lt; objUser.UnderSaved() &lt;&lt; std::endl; std::cout &lt;&lt; &quot;Total left to save yearly: &quot; &lt;&lt; objUser.TotalLeftToSaveYearly() &lt;&lt; std::endl; std::cout &lt;&lt; &quot;Total spent on bills: &quot; &lt;&lt; objUser.TotalSpentOnBills() &lt;&lt; std::endl; } std::cout &lt;&lt; std::endl; } void TestData(std::vector&lt;User&gt;&amp; objUsers) { objUsers.push_back({ &quot;Jack Kimmins&quot;, 764}); objUsers.at(0).AddBill(&quot;Water Bill&quot;, 65); objUsers.push_back({ &quot;George Bradley&quot;, 332}); objUsers.push_back({ &quot;Jason Hill&quot;, 343 }); objUsers.push_back({ &quot;Sean Shearing&quot;, 374 }); } int main() { std::vector&lt;User&gt;objUsers; TestData(objUsers); //CreateUser(objUsers); Will need to be wrapped in a while loop if uncommented DisplayResults(objUsers); system(&quot;pause&quot;); //Ignore this, I know using system isn't good, just to stop it } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T16:58:10.607", "Id": "494162", "Score": "0", "body": "Welcome, you have a huge block of code that is commented out, do you really need it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T17:32:23.740", "Id": "494170", "Score": "0", "body": "Probably not. I just didn’t get round to getting rid of it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T17:35:00.333", "Id": "494174", "Score": "2", "body": "Not a problem, I have removed it for you. Remember that you can always [edit] your question for errors. But avoid doing this after a review. For example, if someone suggests you to do `x` after reading your code. You should never edit and add `x` to your code since this will nullify his review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T08:45:42.100", "Id": "494312", "Score": "0", "body": "Hi, I don’t suppose you could give me fancy algorithm library suggestions for my code? Such as lambda expressions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T11:13:22.220", "Id": "494325", "Score": "0", "body": "Hey, I didn't understand what you meant?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-03T21:03:27.557", "Id": "495259", "Score": "0", "body": "Consider accepting any answer if it helps you :)" } ]
[ { "body": "<p>Welcome to the CR community!</p>\n<h1>Avoid making copies for non-builtin types</h1>\n<p>As a good rule of thumb, pass large objects that you don't need to modify by a constant reference. <br>This will make sure that you don't create extra copies. However, you don't need to do this for the built-in types like <code>int</code>, <code>float</code>, <code>char</code>, <code>double</code>...</p>\n<p>If you have a variable <code>x</code>. Passing it by constant reference means <code>const type&amp; x</code>. What you do here is basically pass the memory address, which gets copied into <code>x</code>. This way you aren't passing the whole <code>string</code> class. But just an address in the memory, which points to an existing string class.</p>\n<p>If you wanted something to get delivered to your house, would you give the company your address or your house?</p>\n<p>Why <code>const</code>? This makes sure that you don't accidentally modify the value of <code>x</code>. Because if you do, the value will change everywhere.</p>\n<p>everywhere? I mean the value you used to call the function.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>void fun(int&amp; x)\n{\n x = 5;\n}\n\nint x = 10;\nfun(); // x is now 5!\n</code></pre>\n<p>Using <code>const</code> will tell the compiler, <em>&quot;If you see me modifying this, say something so I can avoid a nightmare &quot;</em>.</p>\n<h1><a href=\"https://stackoverflow.com/questions/213907/stdendl-vs-n\">Prefer using <code>'\\n'</code> over <code>std::endl</code></a></h1>\n<p><code>std::endl</code> calls <code>std::flush</code> everytime. This makes it less efficient than printing <code>'\\n'</code>. They both will achieve the job here, except one will be faster.</p>\n<p>For example</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>std::cout &lt;&lt; &quot;***&quot; &lt;&lt; std::endl;\n</code></pre>\n<p>This calls the <code>&lt;&lt;</code> operator twice + calls <code>std::flush</code>. The same newline can be achieved with</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>std::cout &lt;&lt; &quot;***\\n&quot;;\n</code></pre>\n<p>This will be more efficient</p>\n<h1><a href=\"https://codebeautify.org/cpp-formatter-beautifier\" rel=\"nofollow noreferrer\">Maintain consistent formatting</a></h1>\n<p>Your code has some inconsistent formatting. Your IDE should easily be able to format code into different styles, or even a <a href=\"https://codebeautify.org/cpp-formatter-beautifier\" rel=\"nofollow noreferrer\">site like this one</a> can do the job.</p>\n<hr />\n<h1>Re-format code into different files</h1>\n<p>As your code grows, you will realize that you cannot have all your code in <code>main.cpp</code>. Doing that makes your code just less readable. You will find it tougher to maintain your code later on too. What if you just had <code>Bill.h</code> and <code>User.h</code>! This way every time you have a problem, you can easily navigate to these files. Moreover, your code looks much cleaner</p>\n<p>re-formatted into separate files</p>\n<h1><code>Bill.h</code></h1>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;string&gt;\n\nclass Bill \n{\n private:\n std::string m_sBillName;\n double m_dMonthlyBill;\n \n public:\n Bill(std::string,double);\n double GetMonthlyBill();\n};\n</code></pre>\n<h1><code>Bill.cpp</code></h1>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &quot;Bill.h&quot;\n\n\nBill::Bill(std::string sBillName, double dMonthlyBill)\n :m_sBillName(sBillName),m_dMonthlyBill(dMonthlyBill) \n \n {}\n\ndouble Bill::GetMonthlyBill() {\n return m_dMonthlyBill;\n}\n\n</code></pre>\n<hr />\n<h1><code>User.h</code></h1>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;string&gt;\n#include &lt;vector&gt;\n#include &quot;Bill.h&quot;\n\nclass User \n{\n private:\n std::string m_sName;\n double m_dMonthlyWage;\n std::vector &lt;Bill&gt; objBillsToPay;\n \n public:\n User(std::string,double);\n void AddBill(std::string,double);\n double WeeklyWage();\n double YearlyWage();\n double TotalSpentOnBills();\n double LeftToSaveMonthly();\n double TotalLeftToSaveYearly();\n double OverSaved();\n double UnderSaved();\n \n};\n</code></pre>\n<h1><code>User.cpp</code></h1>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &quot;User.h&quot;\n\n\n\nUser::User(std::string sName, double dMonthlyWage)\n :m_sName(sName), m_dMonthlyWage(dMonthlyWage) \n {}\n \nvoid User::AddBill(std::string sBillName, double dMonthlyBill) \n{\n objBillsToPay.push_back({ sBillName, dMonthlyBill });\n}\n\ndouble User::WeeklyWage() {\n return m_dMonthlyWage / 4;\n}\n\ndouble User::YearlyWage() {\n return m_dMonthlyWage * 12;\n}\n\ndouble User::TotalSpentOnBills()\n{\n double dTotal = 0;\n for (Bill &amp;objBill : objBillsToPay) \n {\n dTotal += objBill.GetMonthlyBill();\n }\n return dTotal;\n}\n\ndouble User::LeftToSaveMonthly()\n{\n return (YearlyWage() / 12) - (TotalSpentOnBills() / 12);\n}\n\ndouble User::TotalLeftToSaveYearly() \n{\n return YearlyWage() - TotalSpentOnBills();\n}\n\ndouble User::OverSaved() \n{\n return TotalLeftToSaveYearly() * 0.10;\n}\n\ndouble User::UnderSaved() {\n return TotalLeftToSaveYearly() - (TotalLeftToSaveYearly() * 0.10);\n}\n</code></pre>\n<hr />\n<ul>\n<li>What is <code>std::string m_sBillName;</code> doing in <code>Bill</code>? You have declared it <code>private</code> but you aren't using it in any of the member functions, and since it is private it won't be accessible outside either.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T17:32:58.047", "Id": "251103", "ParentId": "251096", "Score": "5" } }, { "body": "<h1>Avoid Hungarian notation</h1>\n<p>You should <a href=\"https://stackoverflow.com/questions/111933/why-shouldnt-i-use-hungarian-notation\">avoid using Hungarian notation</a>, especially if you are going to prefix everything that is not a primitive type with <code>obj</code>. It becomes really useless at that point. You also fail to distinguish between objects passed by value and by reference.</p>\n<p>Using the <code>m_</code> prefix to mark member variables is something that is done correctly though, so no problem in keeping that.</p>\n<h1>Why does a <code>Bill</code> have a name?</h1>\n<p>You give <code>Bill</code>s names, but you can never read back the name. It is useless information at that point. If you don't store the name, then the only thing left is the variable <code>dMonthlyBill</code>, which is just a <code>double</code>. If that's all there is to it, I would say that this class doesn't do anything usefull, and should be removed. Instead, in <code>class User</code> you can write:</p>\n<pre><code>std::vector&lt;double&gt; monthly_bills;\n</code></pre>\n<p>But, the same goes for <code>class User</code>. There's no way to get the name or the list of bills out of it. The only thing it really needs to store is the monthly wage and the sum of the monthly bills:</p>\n<pre><code>class User\n{\n double m_monthly_wage;\n double m_monthly_bills = 0;\n\npublic:\n User(double monthly_wage): m_monthly_wage(monthly_wage) {}\n\n void AddBill(double monthly_bill) {\n m_monthly_bills += monthly_bill;\n }\n\n ...\n}\n</code></pre>\n<h1>Be careful converting between time periods</h1>\n<p>You cannot blindly convert monthly wages to weekly wages by dividing by four. After all, a year has 52.1775 weeks, not 48!</p>\n<p>Furthermore, the calculation in <code>LeftToSaveMonthly()</code> is wrong: <code>TotalSpentOnBills()</code> is already per month, so you shouldn't divide it by 12. And there is no need to call <code>YearlyWage()</code> and then divide the answer by 12 again. You can just write:</p>\n<pre><code>double LeftToSaveMonthly()\n{\n return m_dMonthlyWage - TotalSpentOnBills();\n}\n</code></pre>\n<h1>Avoid using <code>system()</code></h1>\n<p><a href=\"https://stackoverflow.com/questions/1107705/systempause-why-is-it-wrong\">Don't use <code>system()</code></a> unless you really need it, it is very inefficient and not portable. In this case, you can simply write:</p>\n<pre><code>std::cin.get();\n</code></pre>\n<p>This might require the user to press Enter though instead of any key (if the input is line-buffered), but that should be fine.</p>\n<p>You already write in the comments in the code that you know it is bad, but why do it anyway then?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T17:54:35.303", "Id": "494180", "Score": "0", "body": "He did mention that the Hungarian notation is a necessity for his university" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T18:00:11.587", "Id": "494181", "Score": "2", "body": "@AryanParekh That's true, but I'm going to comment on everything in the code anyway, because otherwise others trying to learn from this review might get the wrong idea. And if it's required, it's still used incorrectly. I sincerely hope it was not the university that actually taught this incorrect way, but it wouldn't surprise me." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T17:52:32.363", "Id": "251104", "ParentId": "251096", "Score": "3" } }, { "body": "<p>Instead of DisplayResults, opt to overload the <code>&lt;&lt;</code> operator for your <code>User</code> class</p>\n<pre><code>std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, User&amp; const u) {\n os &lt;&lt; &quot;***&quot; &lt;&lt; '\\n';\n os &lt;&lt; &quot;Weekly wage: &quot; &lt;&lt; u.WeeklyWage() &lt;&lt; '\\n';\n os &lt;&lt; &quot;Yearly wage: &quot; &lt;&lt; u.YearlyWage() &lt;&lt; '\\n';\n os &lt;&lt; &quot;10% over total that can be saved: &quot; &lt;&lt; u.OverSaved() &lt;&lt; '\\n';\n os &lt;&lt; &quot;10% under total that can be saved: &quot; &lt;&lt; u.UnderSaved() &lt;&lt; '\\n';\n os &lt;&lt; &quot;Total left to save yearly: &quot; u.TotalLeftToSaveYearly() &lt;&lt; '\\n';\n os &lt;&lt; &quot;Total spent on bills: &quot; &lt;&lt; u.TotalSpentOnBills() &lt;&lt; '\\n';\n return os;\n}\n</code></pre>\n<p>Advantages:</p>\n<ul>\n<li>No longer beholden to outputting only through <code>std::cout</code>, can output to file instead.</li>\n<li>Easy to read</li>\n<li>Enables outputting a single or multiple users</li>\n<li>Can now use the <code>std::copy</code> and std::copy_if-to-output-iterator if you want</li>\n</ul>\n<p>Don't forget to add <code>friend ostream&amp; operator&lt;&lt;(ostream&amp; os, User const&amp; u);</code> to your class!</p>\n<p>You can also do this for the <code>Bill</code> class.</p>\n<p>Additionally, after you split out the users</p>\n<pre><code>double User::TotalSpentOnBills()\n{\n return std::accumulate(\n objBillsToPay.cbegin(),\n objBillsToPay.cend(),\n 0.0,\n [](auto const &amp; accumulator, auto const &amp; item){\n return accumulator + item;\n });\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-04T17:02:00.497", "Id": "495408", "Score": "0", "body": "I appreciate your edit, if you have a suggestion, I hoe you can add it to your own answer rather than to add it on my own since it was YOUR idea, not mine :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-04T17:07:56.277", "Id": "495410", "Score": "1", "body": "I would have to research about `std::accumulate`, If you have a suggestion like this one it is fine if you suggest through the comments, however, if you are correcting bad grammar, or making the post more readable in any way you can edit it instead" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-04T17:12:36.923", "Id": "495411", "Score": "0", "body": "If I were to justify my edit, I had just improved the formatting of the post and added `std::`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-04T17:15:55.450", "Id": "495412", "Score": "0", "body": "Side note, why would you like to complicate things here with `std::accumulate`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-04T17:47:25.517", "Id": "495419", "Score": "0", "body": "I'm glad you asked!\n\nRanges are coming, and currently most devs are only starting to dip their toes into the current Standard Library. If everyone keeps doing things \"same as usual\", then C++ won't improve. Second, while accumulate seems scary, it's really not. It indicates intent rather quickly, and using `reduce` is even more obvious - you're reducing a range into a single value; whether that's an accumulation, a max operation, Kadane's or the Max-Profit Algorithm, as a reader clued into what's happening. Third, you'd be surprised how often STL algorithms trivialize classes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-04T19:17:50.067", "Id": "495430", "Score": "0", "body": "Seems really scary to someone who isn't familiar with STL algorithms too much, I would have to be more informed to argue about that. But does your solution have any + in terms of efficiency? Because 1 for loop is much more readble according to me" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-04T19:42:38.830", "Id": "495440", "Score": "0", "body": "Almost all STL algorithms have the same speed or faster than their for-loop equivalent, but it's compiler dependent. Even sub-optimal STL approaches tend to be on the same time-scale. Additionally, if you use `reduce` from C++17, the compiler is allowed to parallelize everything, but your lambda must be commutative." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-04T14:34:44.940", "Id": "251603", "ParentId": "251096", "Score": "1" } } ]
{ "AcceptedAnswerId": "251103", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T15:52:07.477", "Id": "251096", "Score": "4", "Tags": [ "c++", "c++11" ], "Title": "Personal Finance Management Tool (OOP version)" }
251096
<p>Recently I thought about what a program would look like if all its characters that could become trigraphs became trigraphs. For example</p> <pre><code>int main(void) { int array[10]; } </code></pre> <p>would become</p> <pre><code>int main(void) ??&lt; int array??(10??); ??&gt; </code></pre> <p>As a result I decided to make a program using ANSI C89 that takes a file in and converts each character to its corresponding trigraph if it has one and outputs the result to another file.</p> <pre><code>#include &lt;errno.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; #define BUFFER_SIZE 1024 #define WRITE_BUFFER(x, size) \ do { \ memcpy(buffer + BUFFER_SIZE + write_buffer_length, (x), (size)); \ write_buffer_length += (size); \ } while(0) \ int main(int argc, char **argv) { int j; /* ignore the first argument */ --argc; ++argv; /* check for invalid arguments */ if(argc % 2 != 0) { fprintf(stderr, &quot;Error: invalid arguments\n&quot;); fprintf(stderr, &quot;Usage: %s input output ...\n&quot;, argv[-1]); fprintf(stderr, &quot;Example: %s main.c result.c \n&quot;, argv[-1]); return -1; } for(j = 0; j &lt; argc; j += 2) { char buffer[BUFFER_SIZE + BUFFER_SIZE * 3]; FILE *read_file, *write_file; size_t bytes_read = BUFFER_SIZE; if(strcmp(argv[j], argv[j + 1]) == 0) { printf(&quot;Warning: using the same file for input and output is not supported\n&quot;); continue; } /* open a file for reading */ if((read_file = fopen(argv[j], &quot;r&quot;)) == NULL) { fprintf(stderr, &quot;Error: could not open %s\n%s&quot;, argv[j], strerror(errno)); return -2; } /* open a file for writing */ if((write_file = fopen(argv[j + 1], &quot;w&quot;)) == NULL) { fprintf(stderr, &quot;Error: could not open %s\n%s&quot;, argv[j + 1], strerror(errno)); return -3; } /* read the file in BUFFER_SIZE chunks */ while (bytes_read == BUFFER_SIZE) { size_t i, write_buffer_length; bytes_read = fread(buffer, 1, BUFFER_SIZE, read_file); /* process each character in the buffer * and if needed convert it to a trigraph */ write_buffer_length = 0; for (i = 0; i &lt; bytes_read; ++i) { char const ch = buffer[i]; switch (ch) { case '#': WRITE_BUFFER(&quot;\?\?=&quot;, 3); break; case '[': WRITE_BUFFER(&quot;\?\?(&quot;, 3); break; case ']': WRITE_BUFFER(&quot;\?\?)&quot;, 3); break; case '{': WRITE_BUFFER(&quot;\?\?&lt;&quot;, 3); break; case '}': WRITE_BUFFER(&quot;\?\?&gt;&quot;, 3); break; case '\\': WRITE_BUFFER(&quot;\?\?/&quot;, 3); break; case '^': WRITE_BUFFER(&quot;\?\?'&quot;, 3); break; case '~': WRITE_BUFFER(&quot;\?\?-&quot;, 3); break; case '|': WRITE_BUFFER(&quot;\?\?!&quot;, 3); break; default: WRITE_BUFFER(&amp;ch, 1); break; } } fwrite(buffer + BUFFER_SIZE, 1, write_buffer_length, write_file); } fclose(read_file); fclose(write_file); } return 0; } </code></pre>
[]
[ { "body": "<p>Your program could be a lot shorter and simpler if you followed the &quot;Unix philosophy.&quot;</p>\n<ul>\n<li><p>Read from <code>stdin</code> and write to <code>stdout</code>. This eliminates your need to process arguments, and eliminates the <code>for(j)</code> loop.</p>\n</li>\n<li><p>Trust <code>fread</code> and <code>fwrite</code> to do I/O buffering on their own. (They do.)</p>\n</li>\n</ul>\n<p>Then your entire program would be something like</p>\n<pre><code>#include &lt;stdio.h&gt;\n\nvoid trigraph(char c) {\n putchar('?');\n putchar('?');\n putchar(c);\n}\n\nint main() {\n int c;\n while ((c = getchar()) != EOF) {\n switch (c) {\n case '\\\\': trigraph('/'); break;\n case '#': trigraph('='); break;\n [...]\n default: putchar(c); break;\n }\n }\n}\n</code></pre>\n<p>Then if you want to transform a bunch of files at once, that's as easy as</p>\n<pre><code>for i in *.c ; do ./a.out &lt; &quot;$i&quot; &gt; &quot;${i%.c}.trigraphed.c&quot; ; done\n</code></pre>\n<p>For more on the Unix philosophy of writing simple &quot;pipeline&quot; programs that compose well, I recommend the book <a href=\"https://amzn.to/2J3jfJk\" rel=\"nofollow noreferrer\"><em>Software Tools</em>, by Kernighan and Plauger</a>; or for that matter <a href=\"https://amzn.to/3e1PZOr\" rel=\"nofollow noreferrer\"><em>The C Programming Language</em>, by Kernighan and Ritchie</a>.</p>\n<p>For an additional exercise, you might try writing a program to <em>reverse</em> this operation: replace every trigraph with its corresponding ASCII character.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T15:27:39.313", "Id": "494259", "Score": "0", "body": "For fun, it would be interesting to also see this code with trigraphs applied." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T15:32:07.367", "Id": "494260", "Score": "0", "body": "Well, you can run it through itself. ;) But that does remind me: perhaps the cases should cutely be written as `case '??/': trigraph('/'); break; case '??=': trigraph('='); break;` and so on. This would be either more self-documenting or less self-documenting, depending on your point of view. :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T05:53:12.757", "Id": "251115", "ParentId": "251097", "Score": "4" } }, { "body": "<ul>\n<li><p>There is absolutely no reason why <code>WRITE_BUFFER</code> should be a macro and not a function.</p>\n</li>\n<li><p>Don't do exotic stuff like <code>--argc; ++argv;</code>. C programmers expect argument 0 to be the name of the executable. Similarly, <code>argc % 2</code> is weird, why would you check for an even amount of arguments? Check for an <em>exact</em> amount of arguments, no more, no less.</p>\n</li>\n<li><p>Similarly, you should be able to keep all error handling out of the loops and just do it once. Keep it simple.</p>\n</li>\n<li><p>I'd expect the various valid trigraph sequences to be stored in some manner of table, rather than a big <code>switch</code>. For example, you could sacrifice 128 bytes data for a fast lookup table based on 7 bit ASCII:</p>\n<pre><code>const char trigraph [128] = \n{\n ['#'] = '=',\n ['['] = '(',\n ...\n};\n\nchar in = ... // input from file\nchar out = trigraph[in];\nif(out != 0) // was it a candidate for trigraph replacement?\n{ \n // printf(&quot;??%c&quot;, out); etc\n</code></pre>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T15:00:05.727", "Id": "494362", "Score": "0", "body": "the reason I check for an even amount of arguments is so every file read has a corresponding file to write to and that will not be true when there is an odd amount of arguments." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T07:25:46.830", "Id": "494425", "Score": "0", "body": "@nullptr And why would someone ever use the program with more than 2 files? That's not a very good UI and you gain no performance from it either, since the massive bottleneck here is the file i/o and everything else is negligible. It's a potential security hole too." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T14:51:01.570", "Id": "251168", "ParentId": "251097", "Score": "1" } } ]
{ "AcceptedAnswerId": "251115", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T15:58:48.933", "Id": "251097", "Score": "4", "Tags": [ "c", "c89" ], "Title": "Trigraph translator" }
251097
<p>Autodidact and inspired by David Beazley code (to improve my skills in Python) i would like to get your feed back on this Parser code.</p> <p>NB: The lazy property let the code be computed only one time if used (<a href="https://github.com/dabeaz/python-cookbook/blob/master/src/8/lazily_computed_attributes/example1.py" rel="nofollow noreferrer">https://github.com/dabeaz/python-cookbook/blob/master/src/8/lazily_computed_attributes/example1.py</a>)</p> <pre><code> class lazyproperty: def __init__(self, func): self.func = func def __get__(self, instance, cls): if instance is None: return self else: value = self.func(instance) setattr(instance, self.func.__name__, value) return value class PDFParser(): &quot;&quot;&quot; &quot;&quot;&quot; def __init__(self,filepath,page_num=0): self.filepath = filepath try: self._doc = fitz.open(filepath) self.page_num = page_num self._page = self._doc[page_num] except Exception as e: print(&quot;Lecture PDF impossible. {}&quot;.format(e)) @lazyproperty def text(self): return self._page.getText() @lazyproperty def _pixs(self): imgs = self._doc.getPageImageList(self.page_num) pixs =[] for img in imgs: xref = img[0] pix = fitz.Pixmap(self._doc, xref) pixs.append(pix) return pixs @lazyproperty def _pixpage(self): pix = self._page.getPixmap(colorspace=fitz.csGRAY) return pix @property def img(self): return self.imgs[0] @lazyproperty def imgs(self): pixs = self._pixs imgsarray = [] for pix in pixs: img = self.pix2np(pix) imgsarray.append(img) return imgsarray def write(self,outputdir,fullpage=False): filename = os.path.basename(self.filepath).split('.pdf')[0] def writePNG(pix,filepath): # This is GRAY or RGB try: pix.writePNG(filepath) # CMYK: convert to RGB first except: pix = fitz.Pixmap(fitz.csRGB, pix) pix.writePNG(filepath) pix = None if fullpage: filepath = os.path.join(outputdir,'{}_p{}.png'.format(filename,self.page_num)) pix = self._pixpage writePNG(pix,filepath) return pixs = self._pixs for i,pix in enumerate(pixs): filepath = os.path.join(outputdir,'{}_p{}_i{}.png'.format(filename,self.page_num,i)) writePNG(pix,filepath) return @staticmethod def pix2np(pix): &quot;&quot;&quot; Convert pixmap to image np.ndarray https://stackoverflow.com/questions/53059007/python-opencv param pix: pixmap &quot;&quot;&quot; import numpy as np #https://stackoverflow.com/questions/22236749/numpy-what-is-the-difference-between-frombuffer-and-fromstring im = np.frombuffer(pix.samples, dtype=np.uint8).reshape(pix.h, pix.w, pix.n) try: im = np.ascontiguousarray(im[..., [2, 1, 0]]) # rgb to bgr except IndexError: #Trick to convert Gray rto BGR, (im.reshape) logger.warning(&quot;Shape of image array is {}&quot;.format(im.shape)) im = cv2.cvtColor(im,cv2.COLOR_GRAY2RGB) im = np.ascontiguousarray(im[..., [2, 1, 0]]) return im </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T16:38:30.853", "Id": "494159", "Score": "2", "body": "Hi, welcome to code review, I have edited your title so that it states what your code does, rather than what you expect to improve. this is given in [ask]" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T16:12:31.920", "Id": "251099", "Score": "1", "Tags": [ "python-3.x" ], "Title": "PDF parser in Python" }
251099
<h1>TL;DR</h1> <p>I'm wondering how to organise test functions using mocks for GoLang drier &amp; easier to follow.</p> <h2>Function</h2> <p>I have a template function that is very similar to ACF's getField:</p> <ul> <li>It take's in a string (field name) &amp; the post ID.</li> <li>It checks if the ID exists and the obtains the post by ID (the <code>f.store.Posts</code> belongs to the <code>fields</code> struct)</li> <li>If the post doesn't exist or if the fields could not be unmarshalled it will return an empty string.</li> </ul> <pre><code>func (f *fields) getField(field string, id ...int) interface{} { fields := f.fields if len(id) &gt; 0 { post, err := f.store.Posts.GetById(id[0]) if err != nil { return &quot;&quot; } var m map[string]interface{} if err := json.Unmarshal(*post.Fields, &amp;m); err != nil { return &quot;&quot; } fields = m } val, found := fields[field] if !found { return &quot;&quot; } return val } </code></pre> <h2>Testing</h2> <p>From the function, presumably I need to test if, The post exists, the json could be unmarshalle or if the field exists. I have started to use <a href="https://github.com/golang/mock/gomock" rel="nofollow noreferrer">github.com/golang/mock/gomock</a> but am finding it confusing! In each of the test functions below I create a new controller and mockPost, add assigning the fields <code>Post</code> to it.</p> <pre><code> func TestGetField(t *testing.T) { f, err := helper(`{&quot;text&quot;: &quot;content&quot;}`) if err != nil { t.Error(err) } if field := f.getField(&quot;text&quot;); field == &quot;&quot; { t.Errorf(test.Format(&quot;content&quot;, nil)) } if field := f.getField(&quot;wrongval&quot;); field != &quot;&quot; { t.Errorf(test.Format(&quot;&quot;, field)) } } func TestGetField_Post(t *testing.T) { f, err := helper(&quot;{}&quot;) if err != nil { t.Error(err) } controller := gomock.NewController(t) defer controller.Finish() data := []byte(`{&quot;posttext&quot;: &quot;postcontent&quot;}`) mockPost := domain.Post{ Id: 2, Fields: (*json.RawMessage)(&amp;data), } posts := mocks.NewMockPostsRepository(controller) f.store.Posts = posts posts.EXPECT().GetById(2).Return(mockPost, nil) field := f.getField(&quot;posttext&quot;, 2) if field != &quot;postcontent&quot; { t.Errorf(test.Format(&quot;postcontent&quot;, field)) } } func TestGetField_No_Post(t *testing.T) { f, err := helper(&quot;{}&quot;) if err != nil { t.Error(err) } controller := gomock.NewController(t) defer controller.Finish() posts := mocks.NewMockPostsRepository(controller) var mockErr = fmt.Errorf(&quot;No post&quot;) posts.EXPECT().GetById(gomock.Any()).Return(domain.Post{}, mockErr) f.store.Posts = posts field := f.getField(&quot;text&quot;, 1) if field != &quot;&quot; { t.Errorf(test.Format(&quot;&quot;, field)) } } func TestGetField_Invalid_JSON(t *testing.T) { f, err := helper(&quot;{}&quot;) if err != nil { t.Error(err) } controller := gomock.NewController(t) defer controller.Finish() data := []byte(`&quot;text &quot;content&quot;`) mockPost := domain.Post{ Id: 1, Fields: (*json.RawMessage)(&amp;data), } posts := mocks.NewMockPostsRepository(controller) posts.EXPECT().GetById(1).Return(mockPost, nil) f.store.Posts = posts field := f.getField(&quot;text&quot;, 1) if field != &quot;&quot; { t.Errorf(test.Format(&quot;&quot;, field)) } } </code></pre> <h2>Feedback</h2> <ul> <li>Without using the mock package, how would you approach this?</li> <li>Are there any areas for improvement with the current codebase?</li> <li>Is there away to consolidate any of the testing methods? It seems quite long winded for such a short function</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T18:41:30.697", "Id": "494190", "Score": "0", "body": "is [this](https://codereview.stackexchange.com/users/232328/ainsley-clark) your account?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-31T20:43:13.957", "Id": "494860", "Score": "0", "body": "I'm surprised you don't choose to return `(interface{}, error)` so that your errors can have qualities (and so empty string does not have special meaning, though granted, your posts are probably never empty)" } ]
[ { "body": "<p>I don't know exactly what your <code>fields</code> type is, but from the code you've shared, there's a couple of strong recommendations I'd like to make about the code itself, before getting in to the testing aspect.</p>\n<pre><code>post, err := f.store.Posts.GetById(id[0])\n</code></pre>\n<p>From this line, and the fact that you're mocking <code>store</code>, I'm deducing your <code>fields</code> constructor looks something like this:</p>\n<pre><code>func New(store SomeStoreT) *fields {\n return &amp;fields{\n store: store,\n }\n}\n</code></pre>\n<p>Because you're accessing <code>store.Posts</code> directly, the <code>SomeStoreT</code> is going to be the actual type, complete with exposed fields. This means you can't really mock the <code>store</code> type as a whole, you have to ensure that whatever the exported fields are, is safe for concurrent use, and that no other code either on purpose or accidentally assigns anything to said fields. An extreme example would be:</p>\n<pre><code>func main () {\n store := storage.New()\n f := fields.New(store)\n store.Posts = nil\n f.GetPosts() // panic\n}\n</code></pre>\n<p>It's therefore better to either replace the <code>store</code> dependency with an interface that exposes what you need through getters, so the fields needn't be exported. It'd be as simple as changing the line</p>\n<pre><code>post, err := f.store.Posts.GetById(id[0])\n</code></pre>\n<p>to:</p>\n<pre><code>post, err := f.store.Posts().GetById(id[0])\n</code></pre>\n<p>Still, there's something that I find a lot more disturbing than this: the use of <code>interface{}</code> and the <code>json.Unmarshal()</code> calls. Your <code>store</code> field has a <code>Posts</code> field. That tells me you <em>know</em> what data you're fetching, or saving. Why would you let code other than the storage layer deal with the marshalling and unmarshalling of that data? Your code should pass around a type that represents a post, and it's the job of the storage layer to handle the marshalling. If you decide JSON isn't the right format, and want to opt for something faster (like a binary format), or you want to switch to a completely different type of DB like Postgres, then you don't want to be forced to change the code throughout your application. You just should be able to swap out you storage adapter, optionally change the tags on the data types, and update the package to handle the new marshalling and be done with it:</p>\n<pre><code>package domain\n\ntype Post struct {\n ID int `json:&quot;id&quot;` // preferred ID in all-caps\n Content string `json:&quot;content&quot;`\n}\n</code></pre>\n<p>Then, in the storage package:</p>\n<pre><code>package storage\n\ntype Posts struct {\n // whatever fields to access the storage used\n}\n\nfunc (p *Posts) GetByID(id int) (*domain.Post, error) {\n record, err := p.db.Get(id) // whatever you need to do here\n if err != nil {\n return nil, err\n }\n ret := domain.Post{}\n if err := json.Unmarshal(record, &amp;ret); err != nil {\n return nil, err\n }\n return &amp;ret, nil\n}\n</code></pre>\n<p>So with this, you can change your function in fields to not have to do any unmarshalling at all. It's all handled in the storage. Now, getting a field by string isn't possible with this code, of course. I'm not sure of that's actually a good idea, but that's more of an X-Y problem. You can quite easily implement something that makes getting fields by string ridiculously easy, in fact. All you need to do is create a wrapper type and custom unmarshalling:</p>\n<pre><code>package domain\n\ntype Post struct {\n PostRecord // embedded struct\n postMap map[string]interface{}\n}\n\ntype PostRecord struct {\n ID int `json:&quot;id&quot;`\n Content string `json:&quot;content&quot;`\n}\n\nfunc (p *Post) UnmarshalJSON(data []byte) error {\n // unmarshal into embedded type\n if err := json.Unmarshal(data, &amp;p.PostRecord); err != nil {\n return err\n }\n if err := json.Unmarshal(data, &amp;p.postMap); err != nil {\n return err\n }\n return nil\n}\n\nfunc (p Post) MarshalJSON() ([]byte, error) {\n return json.Marshal(p.PostRecord) // marshal the embedded type\n}\n\nfunc (p Post) GetField(f string) (interface{}, bool) {\n v, ok := p.postMap[f]\n return v, ok\n}\n</code></pre>\n<p>Now your fields function would look something like this:</p>\n<pre><code>// you're only ever using `id[0]`, so I don't understand the variadic argument here\n// it's also important to note that there's a lot of calls that can error happening here\n// and you need to return those errors. It'll make debugging a lot easier\nfunc (f *fields) getField(field string, id int) (interface{}, error) {\n post, err := f.store.Posts().GetByID(id)\n if err != nil {\n return nil, err\n }\n v, ok := post.GetField(field)\n if !ok {\n return nil, errors.New(&quot;unknown field for post type&quot;)\n }\n return v, nil\n}\n</code></pre>\n<p>You'll note that I'm returning <code>nil</code> in case of an error. That's because an empty string is the nil value for a string, but it could just as well be a valid value for an existing record in some cases. It's best to indicate an error by returning said error, and <code>nil</code> for values that are just not defined. If a field doesn't exist, it has no value, and so <code>nil</code> is the only correct thing to return. Of course, the nil value for an int is 0, and an empty string for a string, but your function looks to me like it's written to be non-type-specific. If the <code>Post</code> type had a timestamp field, stored either as <code>time.Time</code> or <code>int64</code>, and you don't return an error, just an empty string, then the caller might do something like this:</p>\n<pre><code>tval := fields.getField(&quot;timestamp&quot;, 123)\nts, ok := tval.(int64)\nif !ok {\n return errors.New(&quot;invalid timestamp value&quot;)\n}\n</code></pre>\n<p>Now why is the timestamp value invalid? Becuase the field didn't exist (a typo in the string I passed)? Because the ID doesn't exist? Or because the timestamp field has since been updated to another type? I don't know...</p>\n<p>This also assumes that the caller has the sense to check whether the type assertion worked. There's no reason why the caller might just have:</p>\n<p>ts := tval.(int64)</p>\n<p>and continue to use <code>ts</code> assuming it was the correct value, while in reality it'll default to 0. Write your functions to account for sloppy use. Errors are more likely to be checked than boolean indicators. Return values should be unequivocal when it comes to distinguishing between an error and success. An emtpy string is a perfectly valid return value on success, so don't rely on it to communicate failure.</p>\n<hr />\n<p>I'll update this review gradually. I think this is a reasonable amount of information to digest, and get to work with. I've written all of the code snippets above off the cuff, untested, etc... there may be typo's and omissions, so don't assume they're copy-paste ready.</p>\n<hr />\n<h1>TL;DR answers to your questions</h1>\n<ul>\n<li>You have to mock dependencies in unit tests. that's what unit tests are/do</li>\n<li>I've started this review with some suggestions/recommendations to improve on your code - so yes, there are things that you can do there</li>\n<li>with the changes I've proposed, the <code>getFields</code> function is basically a call to the storage package (which is tested separately), and a call on the domain object's <code>GetField</code> function, which is something you unit-test separately. you can still write tests for the function here, but it's just having a mock return either an error or a <code>Post</code> instantce, which you can hard-code in your test. It's far less cumbersome to set up, and test as a result.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T11:20:00.973", "Id": "252244", "ParentId": "251102", "Score": "1" } } ]
{ "AcceptedAnswerId": "252244", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T17:06:56.907", "Id": "251102", "Score": "2", "Tags": [ "unit-testing", "go", "mocks" ], "Title": "Testing a template function in GoLang using mocking - making it DRY & easy to follow" }
251102
<p>Recently I had a python test and, unfortunately, I failed. I'm going to re-do my test and the teacher gave me the tip to work more efficiently and clean. To practice this I made a blackjack game about 2 weeks ago with python and sent it to him to check. he has yet responded and my test is next week. Can anyone take a look and maybe point things out that need improvement? please, I really want to pass this test.</p> <pre><code>import itertools import random as rd from time import sleep as s #making 3 decks with playing cards and assign them 2 to 14 cards1 = list(itertools.product(range(2, 15),['spade', 'heart', 'diamond', 'club'])) cards2 = list(itertools.product(range(2, 15),['spade', 'heart', 'diamond', 'club'])) cards3 = list(itertools.product(range(2, 15),['spade', 'heart', 'diamond', 'club'])) #combine the 3 decks to make 1 cards = list(cards1+cards2+cards3) #shuffle deck rd.shuffle(cards) def blackjack(cards): money = 10 while True: print('you have', money, 'money') bet = int(input('select amount to bet: \n')) if money &lt; bet: print('you dont have that much money....') else: playing = True #draw first card and remove it from the deck fcard = rd.choice(cards) cards.remove(fcard) first_point, first_name = fcard #check if first card is 11 points or more (to change back to 10 points unless it's ace) if first_point == 11: first_point = 10 first_name = str('Jack'+' of '+first_name) elif first_point == 12: first_point = 10 first_name = str('Queen'+' of '+first_name) elif first_point == 13: first_point = 10 first_name = str('King'+' of '+first_name) elif first_point == 14: first_point = 11 first_name = str('Ace'+' of '+first_name) #show the first drawn card print(first_point, first_name) s(0.7) #draw second card and remove it from the deck scard = rd.choice(cards) cards.remove(scard) second_point, second_name = scard #checking second card for the same if second_point == 11: second_point = 10 second_name = str('Jack'+' of '+second_name) elif second_point == 12: second_point = 10 second_name = str('Queen'+' of '+second_name) elif second_point == 13: second_point = 10 second_name = str('King'+' of '+second_name) elif second_point == 14: second_point = 11 second_name = str('Ace'+' of '+second_name) #show second card print(second_point, second_name) s(0.7) points = first_point + second_point #check if first 2 cards make a blackjack if points == 21: print('Blackjack!') bet *= 2 print('you won', bet, 'money') money += bet playing = False print(points, 'points out of 21') if money == 0: print('you are broke!') exit() #after the first 2 cards i need to determine if the player wants more cards while playing: card = input('press enter to draw a card or type x to stop') if card != 'x': a = rd.choice(cards) x, y = a #going through the same checking system as the first 2 cards if x == 11: y = str('Jack'+' of '+second_name) x = 10 elif x == 12: y = str('Queen'+' of '+second_name) x = 10 elif x == 13: y = str('King'+' of '+second_name) x = 10 elif x == 14: y = str('Ace'+' of '+second_name) x = 11 print(x, y) s(0.7) cards.remove(a) points += x if points &gt; 21: print('BUST') points = 0 playing = False #if the player has x as input the player stops drawing elif card == 'x': playing = False print(points, 'points') #let the dealer do the same card drawing result = dealer_draw(cards) print('you scored: ', points, '\n', 'the bank scored: ', result) s(0.7) #compare obtained points with the dealer's points if points &gt; result: print('you win!') money += bet elif points == result: print('draw') elif points &lt; result: print('you lose') money -= bet elif points == 0 and result == 0: print('you lose') money -= bet def dealer_draw(cards): #2 empty prints to maintain clear overview print() print() a = 0 #first 2 cards (same as for the player until.....) cd1 = rd.choice(cards) cards.remove(cd1) points_first, name_first = cd1 if points_first == 11: name_first = str('Jack'+' of '+name_first) points_first = 10 elif points_first == 12: name_first = str('Queen'+' of '+name_first) points_first = 10 elif points_first == 13: name_first = str('King'+' of '+name_first) points_first = 10 elif points_first == 14: name_first = str('Jack'+' of '+name_first) points_first = 11 print(points_first, name_first) s(0.7) cd2 = rd.choice(cards) cards.remove(cd2) points_second, name_second = cd2 if points_second == 11: name_second = str('Jack'+' of '+name_second) points_second = 10 elif points_second == 12: name_second = str('Queen'+' of '+name_second) points_second = 10 elif points_second == 13: name_second = str('King'+' of '+name_second) points_second = 10 elif points_second == 14: name_second = str('Ace'+' of '+name_second) points_second = 11 print(points_second, name_second) s(0.7) #..... here (scroll up) full_points = points_first + points_second a += full_points #have the minimal bank draw set at 16 while a &lt; 16: print(&quot;bank's total = &quot;, a) s(0.7) draw = rd.choice(cards) cards.remove(draw) add_number, full_name = draw if add_number == 11: full_name = str('Jack'+' of '+full_name) add_number = 10 elif add_number == 12: full_name = str('Queen'+' of '+full_name) add_number = 10 elif add_number == 13: full_name = str('King'+' of '+full_name) add_number = 10 elif add_number == 14: full_name = str('Ace'+' of '+full_name) add_number = 11 print(add_number, full_name) s(0.7) a += add_number print(&quot;bank's total = &quot;, a) s(0.7) #check if bank scored more than 21 and if so, return 0 if a &gt; 21: return 0 else: return a blackjack(cards) </code></pre> <p>Any comments are welcome but please keep in in mind that this is my first programming language and I still have a lot to learn. Thanks!</p>
[]
[ { "body": "<p>I'm sorry but my knowledge in card games is rusty. Please correct me if something is wrong!</p>\n<h1>Always catch invalid input</h1>\n<p>Assume that the user is going to enter something, that is prompted to him from this line of code</p>\n<pre class=\"lang-py prettyprint-override\"><code>print('you have', money, 'money')\nbet = int(input('select amount to bet: \\n'))\n</code></pre>\n<blockquote>\n<p>select amount to bet:</p>\n</blockquote>\n<p>Now, what if the user accidentally entered <strong>E</strong>. In this case, your program will fail since it expects input in form of an integer. This is why you should always catch invalid input using <a href=\"https://docs.python.org/3/tutorial/errors.html\" rel=\"nofollow noreferrer\"><strong>Try and Except in Python</strong></a></p>\n<pre class=\"lang-py prettyprint-override\"><code>try: \n bet = int(input(&quot;select amount to be: &quot;)) \nexcept Exception: \n print(&quot;Invalid input! Please enter a number\\n&quot;)\n</code></pre>\n<p>This way, if the user entered</p>\n<blockquote>\n<p>select amount to be: I like python</p>\n</blockquote>\n<p>It would give the user</p>\n<blockquote>\n<p>Invalid input! Please enter a number</p>\n</blockquote>\n<h1>Don't exit after invalid / bad input</h1>\n<p>In your program, if the user enters a bet which is more than the money he has, the program just stops. It won't play again, why should this happen?</p>\n<p>You should ask the user to enter valid input again, so that any mistake by him won't result in the immediate termination of the program</p>\n<pre class=\"lang-py prettyprint-override\"><code>while True:\n try: \n bet = int(input(&quot;select amount to be: &quot;)) \n except Exception: \n print(&quot;Invalid input! Please enter a number\\n&quot;)\n continue\n\n if bet &gt; money:\n print(&quot;Bet placed higher than balance!&quot;)\n continue\n break\n</code></pre>\n<p>The best thing to do now is to move this to a separate function called <code>take_input()</code>, so your <code>blackjack()</code> function can remain clean, and now taking input is easy</p>\n<pre class=\"lang-py prettyprint-override\"><code>bet = take_input()\n</code></pre>\n<p>Yes, you have written a few more lines of code. But now you know your program will do the right thing when Exceptions occur.</p>\n<h1>Simplify code - 1</h1>\n<pre class=\"lang-py prettyprint-override\"><code>first_name = str('Jack'+' of '+first_name)\n</code></pre>\n<p>Is the same as</p>\n<pre class=\"lang-py prettyprint-override\"><code>first_name = &quot;Jack of &quot; + first_name\n</code></pre>\n<p>You don't need to convert to <code>str</code> as <code>first_name</code> is already a string.</p>\n<p>The same applies to the following lines that I have extracted from your code.</p>\n<pre class=\"lang-py prettyprint-override\"><code>first_name = str('Queen'+' of '+first_name)\nfirst_name = str('King'+' of '+first_name)\nfirst_name = str('Ace'+' of '+first_name)\n</code></pre>\n<h1>Avoid <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">Magic Numbers</a></h1>\n<p>Take this example</p>\n<pre class=\"lang-py prettyprint-override\"><code>if first_point == 11:\n first_point = 10\n first_name = str('Jack'+' of '+first_name)\nelif first_point == 12:\n first_point = 10\n first_name = str('Queen'+' of '+first_name)\nelif first_point == 13:\n first_point = 10\n first_name = str('King'+' of '+first_name)\nelif first_point == 14:\n first_point = 11\n first_name = str('Ace'+' of '+first_name)\n</code></pre>\n<p><code>10</code>, <code>11</code>, <code>12</code>... are known as <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">magic numbers</a>. I had to think while to understand what they were doing here until I finally understood that they were cards.</p>\n<p>The good way to deal with this is to use Python's <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"nofollow noreferrer\">enums</a>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from enum import Enum\n\nclass Card(Enum):\n jack = 11\n queen = 12\n king = 13\n ....\n</code></pre>\n<p>Correct the values if they are wrong.</p>\n<p>Now your if-else thread looks so much clearer to the reader</p>\n<pre class=\"lang-py prettyprint-override\"><code>if first_point == Card.jack.value:\n ...\n\nelif first_point == Card.queen.value:\n ...\n\nelif first_point = Card.king.value:\n ....\n</code></pre>\n<p>Another plus point is that what if you want to change the value of the king from <code>x</code> to <code>y</code>. Would you go to the hundreds of places to find where you might have used a numeric constant in context to the king?</p>\n<p>here you can just set <code>king.value</code> to whatever you want.</p>\n<h1><s><code>import sleep as s</code></s></h1>\n<p><code>s(0.5)</code>\nThis also had me confused in the beginning, I had to found out what <code>s</code> meant. <code>s</code> isn't meaningful at all, it just confuses anyone who reads your code. However, <code>sleep</code> clearly implies that you want to... Sleep! Always use meaningful names</p>\n<h1>Split work into functions</h1>\n<p>Currently, your <code>blackjack()</code> function is cluttered with a lot of tasks that should be moved to their own functions. Just like we moved the input procedure into a separate <code>take_input()</code> function, you can create a lot of meaningful functions like <code>draw_new_card()</code> that can return a new card from the deck.</p>\n<h1><a href=\"https://medium.com/jl-codes/dry-vs-wet-code-589c564aa5aa\" rel=\"nofollow noreferrer\">Is your code DRY or WET</a></h1>\n<p>Excuse my knowledge of card games</p>\n<p>You have the procedure</p>\n<ol>\n<li>draw a card</li>\n<li>check if the card is <code>&gt;=</code> 11 points</li>\n<li>print the point and name</li>\n</ol>\n<p>Then why repeat the same thing again for the second card? You have written the same thing twice. Once for the first card, and next for the second. you have repeated yourself. The best way is to factor repetition out into a function. So that all you need to do is</p>\n<pre class=\"lang-py prettyprint-override\"><code>def new_card():\n card = draw_new_card()\n point, name = card\n process_card(point, name)\n return point, name\n\n# in the blackjack function #\n\nfirst_point, first_name = new_card()\nprint(first_point, first_name)\nsleep(0.5)\n\nsecond_point, second_name = new_card()\nprint(second_point, second_name)\n\n......\n\n</code></pre>\n<p>You can see that using functions has helped a lot.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T20:12:38.543", "Id": "494283", "Score": "1", "body": "thanks a bunch! i'm going to take a look at your comments 1 by 1 and see if I can improve!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T20:39:53.247", "Id": "251110", "ParentId": "251106", "Score": "6" } }, { "body": "<h2>Naming conventions</h2>\n<p>Just to reinforce the point made by @Aryan Parekh:\nDon't use meaningless abbreviations eg:</p>\n<pre><code>import random as rd\nfrom time import sleep as s\n</code></pre>\n<p>There is no benefit, you've made the code harder to read and understand.\nSo: use <code>random.choice(cards)</code> instead of: <code>rd.choice(cards)</code>. random.choice is self-explanatory.</p>\n<p>Good code should be intuitive, that begins with proper naming conventions. Even if you are lazy you should use longer and more descriptive names, your IDE should have autocomplete anyway.</p>\n<p>You have variables like a, cd2, x, y that remind me of spaghetti Basic from the 80s. I totally suck at card games so I can't comment much on the algo but I can comment on the code.</p>\n<p>Fortunately, you put some comments.</p>\n<h2>Consistency</h2>\n<p>You use the choice function a couple times but with very different variables names:</p>\n<pre><code>a = rd.choice(cards)\nx, y = a\n</code></pre>\n<p>and later:</p>\n<pre><code>draw = rd.choice(cards)\ncards.remove(draw)\nadd_number, full_name = draw\n</code></pre>\n<p>I think more <strong>consistency</strong> is called for here. If you reuse some statements you might as well use the same variable names elsewhere or at least stick to some naming patterns that make sense. draw is a name that makes sense. But add_number really looks like a function name, so I would call it card_number or something like that (even though you are effectively using that variable for incrementing another value).</p>\n<h2>Repetition</h2>\n<p>There is <strong>repetition</strong> in your code eg:</p>\n<pre><code>#making 3 decks with playing cards and assign them 2 to 14\ncards1 = list(itertools.product(range(2, 15),['spade', 'heart', 'diamond', 'club']))\ncards2 = list(itertools.product(range(2, 15),['spade', 'heart', 'diamond', 'club']))\ncards3 = list(itertools.product(range(2, 15),['spade', 'heart', 'diamond', 'club']))\n</code></pre>\n<p>First off, some statements are redundant:</p>\n<pre><code>#combine the 3 decks to make 1\ncards = list(cards1+cards2+cards3)\n</code></pre>\n<p>Since you are concatenating three lists the resulting object is a list object too.\nSo, <code>cards = cards1 + cards2 + cards3</code> is sufficient and yields the same result.</p>\n<p>cards1/2/3 are exactly the same, so you are repeating the exact same thing 3 times in a row. This is obviously wrong and can be simplified. You could simply write:</p>\n<pre><code>cards2 = cards1\ncards3 = cards1\n</code></pre>\n<p>even though that is not elegant but at least you avoid repetition and your range is declared just once.</p>\n<p>A better way:</p>\n<pre><code>cards = list(itertools.product(range(2, 15), ['spade', 'heart', 'diamond', 'club'])) *3\n</code></pre>\n<p>Thus, you've repeated your sequence three times and created a new list.\nSince you are using itertools, you could also use itertools.repeat, which gives you a generator, whereas <code>* n</code> gives you a list, which is just fine here.</p>\n<h2>Concatenation</h2>\n<pre><code> draw = rd.choice(cards)\n cards.remove(draw)\n add_number, full_name = draw\n if add_number == 11:\n full_name = str('Jack'+' of '+full_name)\n add_number = 10\n</code></pre>\n<p>full_name is a string, so you can safely concatenate all these items. Or better yet, use an <strong>F-string</strong> (Python &gt;= 3.6):</p>\n<pre><code>full_name = f&quot;Jack of {full_name}&quot;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T00:19:36.110", "Id": "494204", "Score": "2", "body": "In your Repetition section, you should clarify that your way of creating `cards` creates only 52 distinct card objects in memory with each reference to a card object repeated three times, whereas the original creates a list of 52*3 distinct card objects in memory; see [this interactive example](https://repl.it/repls/GrizzledFunnyFunctions#main.py). It doesn't affect anything in this case because the cards are modeled as immutable tuples, but if they were mutable and being changed as part of the program flow, this would lead to surprising results." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T22:43:38.900", "Id": "251113", "ParentId": "251106", "Score": "3" } } ]
{ "AcceptedAnswerId": "251110", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-23T14:08:21.537", "Id": "251106", "Score": "2", "Tags": [ "python", "game", "homework", "playing-cards" ], "Title": "Blackjack script in Python" }
251106
<p>Well, my intention here is to allow users to execute Unity methods/properties in other threads by using this Dispatcher implementation:</p> <pre class="lang-cs prettyprint-override"><code> using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Threading.Tasks; using UnityEngine; namespace DepotToolkit.Utils { /// &lt;summary&gt; /// A thread-safe class which holds a queue with actions to execute on the next Update() method. It can be used to make calls to the main thread for /// things such as UI Manipulation in Unity. It was developed for use in combination with the Firebase Unity plugin, which uses separate threads for event handling /// &lt;/summary&gt; public class UnityDispatcher : MonoBehaviour // : MonoSingleton&lt;UnityDispatcher&gt; { // TODO: Add timeout from https://gist.github.com/phizaz/f67f1ba7d25d30d8972c13b7b6a29319 private static readonly ConcurrentQueue&lt;Action&gt; _executionQueue = new ConcurrentQueue&lt;Action&gt;(); public static ObservableCollection&lt;Exception&gt; Exceptions { get; } = new ObservableCollection&lt;Exception&gt;(); // TODO //private static readonly Queue&lt;Action&lt;object&gt;&gt; _executionQueue1 = new Queue&lt;Action&lt;object&gt;&gt;(); //private static readonly Queue&lt;Action&lt;object, object&gt;&gt; _executionQueue2 = new Queue&lt;Action&lt;object, object&gt;&gt;(); private void Exceptions_OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { foreach (var newItem in e.NewItems) { var item = newItem as Exception; Debug.LogError(item); } } public void Update() { while (_executionQueue.Count &gt; 0) { if (_executionQueue.TryDequeue(out var act)) act.Invoke(); } } /// &lt;summary&gt; /// Locks the queue and adds the IEnumerator to the queue /// &lt;/summary&gt; /// &lt;param name=&quot;action&quot;&gt;IEnumerator function that will be executed from the main thread.&lt;/param&gt; public void Enqueue(Action action) { _executionQueue.Enqueue(() =&gt; { StartCoroutine(ActionWrapper(action)); }); } public void Enqueue(EnumeratorJobWrapper job) { _executionQueue.Enqueue(() =&gt; { StartCoroutine(JobWrapper(job)); }); } public void Enqueue(JobWrapper job) { _executionQueue.Enqueue(() =&gt; { StartCoroutine(JobWrapper(job)); }); } public void Enqueue(JobWrapper&lt;object&gt; job) { _executionQueue.Enqueue(() =&gt; { StartCoroutine(JobWrapper(job)); }); } public void Enqueue&lt;T&gt;(JobWrapper&lt;T&gt; job) { _executionQueue.Enqueue(() =&gt; { StartCoroutine(JobWrapper(job)); }); } public void Enqueue&lt;T1, TTResult&gt;(JobWrapper&lt;T1, TTResult&gt; job) { _executionQueue.Enqueue(() =&gt; { StartCoroutine(JobWrapper(job)); }); } public void Enqueue&lt;T&gt;(JobEnumeratorWrapper&lt;T&gt; job) { _executionQueue.Enqueue(() =&gt; { StartCoroutine(JobWrapper(job)); }); } /// &lt;summary&gt; /// Locks the queue and adds the Action to the queue /// &lt;/summary&gt; /// &lt;param name=&quot;action&quot;&gt;function that will be executed from the main thread.&lt;/param&gt; public void Invoke(Action action) { Enqueue(action); } // Alias for Enqueue public void Invoke(EnumeratorJobWrapper job) { Enqueue(job); } public void Invoke(JobWrapper job) { Enqueue(job); } public void Invoke(JobWrapper&lt;object&gt; job) { Enqueue(job); } public void Invoke&lt;T&gt;(JobWrapper&lt;T&gt; job) { Enqueue(job); } public void Invoke&lt;T1, TResult&gt;(JobWrapper&lt;T1, TResult&gt; job) { Enqueue(job); } /// &lt;summary&gt; /// Locks the queue and adds the Action to the queue, returning a Task which is completed when the action completes /// &lt;/summary&gt; /// &lt;param name=&quot;action&quot;&gt;function that will be executed from the main thread.&lt;/param&gt; /// &lt;returns&gt;A Task that can be awaited until the action completes&lt;/returns&gt; public Task EnqueueAsync(Action action) { var tcs = new TaskCompletionSource&lt;bool&gt;(); void WrappedAction() { try { action(); tcs.TrySetResult(true); } catch (Exception ex) { tcs.TrySetException(ex); } } Enqueue(WrappedAction); return tcs.Task; } private IEnumerator ActionWrapper(Action a) { a(); yield return null; } private IEnumerator JobWrapper(EnumeratorJobWrapper wrap) { var enumerator = wrap.Callback; while (enumerator.MoveNext()) { object obj = null; bool isException = false; try { obj = enumerator.Current; } catch (Exception ex) { Debug.LogException(ex); isException = true; } if (!isException) yield return obj; else yield break; } wrap.Finished.Set(); } private IEnumerator JobWrapper(JobWrapper wrap) { try { wrap.Callback(); } catch (Exception ex) { Debug.LogException(ex); //Exceptions.Add(ex); } yield return null; wrap.Finished.Set(); } private IEnumerator JobWrapper(JobWrapper&lt;object&gt; wrap) { object result = null; try { wrap.Job.Invoke(out result); } catch (Exception ex) { Debug.LogException(ex); //Exceptions.Add(ex); } wrap.Result = result; yield return null; wrap.Finished.Set(); } private IEnumerator JobWrapper&lt;T&gt;(JobWrapper&lt;T&gt; wrap) { T result = default; try { wrap.Job.Invoke(out result); } catch (Exception ex) { Debug.LogException(ex); //Exceptions.Add(ex); } wrap.Result = result; yield return null; wrap.Finished.Set(); } private IEnumerator JobWrapper&lt;T1, TResult&gt;(JobWrapper&lt;T1, TResult&gt; wrap) { TResult result = default; try { wrap.Job.Invoke(wrap.Value, out result); } catch (Exception ex) { Debug.LogException(ex); //Exceptions.Add(ex); } wrap.Result = result; yield return null; wrap.Finished.Set(); } private IEnumerator JobWrapper&lt;T&gt;(JobEnumeratorWrapper&lt;T&gt; wrap) { var enumerator = wrap.Job.Invoke(out var result); while (enumerator.MoveNext()) yield return null; wrap.Result = result; wrap.Finished.Set(); } private static UnityDispatcher _instance; public static UnityDispatcher Instance { get { if (_instance == null) { try { // Search for existing instance. _instance = (UnityDispatcher)FindObjectOfType(typeof(UnityDispatcher)); // Create new instance if one doesn't already exist. if (_instance == null) { // Need to create a new GameObject to attach the singleton to. var singletonObject = new GameObject(); _instance = singletonObject.AddComponent&lt;UnityDispatcher&gt;(); singletonObject.name = $&quot;{nameof(UnityDispatcher)} (Singleton)&quot;; //((MonoSingleton&lt;T&gt;)_instance).IsStarted = false; // Make instance persistent. if (Application.isPlaying) DontDestroyOnLoad(singletonObject); } } catch { // This is not thread safe throw new Exception( &quot;UnityMainThreadDispatcher could not find the UnityMainThreadDispatcher object. Please ensure you have added the MainThreadExecutor Prefab to your scene.&quot;); } } return _instance; } } private void Awake() { Exceptions.CollectionChanged += Exceptions_OnCollectionChanged; if (_instance == null) { _instance = this; DontDestroyOnLoad(this.gameObject); } } private void OnDestroy() { _instance = null; } } } </code></pre> <p>Where the <code>JobWrapper</code> class is this:</p> <pre class="lang-cs prettyprint-override"><code>using System; using System.Collections; using System.Threading; namespace DepotToolkit.Utils { public class EnumeratorJobWrapper { public IEnumerator Callback { get; } public ManualResetEvent Finished { get; } private EnumeratorJobWrapper() { } public EnumeratorJobWrapper(IEnumerator callback, ManualResetEvent finished) { Callback = callback; Finished = finished; } } public class JobWrapper { public Action Callback { get; } public ManualResetEvent Finished { get; } private JobWrapper() { } public JobWrapper(Action callback, ManualResetEvent finished) { Callback = callback; Finished = finished; } } public class JobWrapper&lt;T&gt; { public delegate void DelegateJob(out T result); public DelegateJob Job { get; } public ManualResetEvent Finished { get; } public T Result { get; set; } private JobWrapper() { } public JobWrapper(DelegateJob job, ManualResetEvent finished) { Job = job; Finished = finished; } } public class JobWrapper&lt;T1, TResult&gt; { public delegate void DelegateJob(T1 t1, out TResult result); public DelegateJob Job { get; } public ManualResetEvent Finished { get; } public T1 Value { get; } public TResult Result { get; set; } private JobWrapper() { } public JobWrapper(T1 value, DelegateJob job, ManualResetEvent finished) { Value = value; Job = job; Finished = finished; } } } </code></pre> <p>An example of what I'm doing:</p> <pre class="lang-cs prettyprint-override"><code>using System; using System.Threading; using DepotToolkit.Utils; using UnityEngine; using UnityEngine.Core; using Object = UnityEngine.Object; namespace DepotToolkit.CommonCode { public static class ThreadSafeUtils { internal class ThreadChecker : MonoSingleton&lt;ThreadChecker&gt; { public Thread UnityThread { get; private set; } private void Awake() { UnityThread = Thread.CurrentThread; } } public static bool IsMainThread =&gt; Thread.CurrentThread.Equals(ThreadChecker.Instance.UnityThread); public static T[] ThreadSafe_GetComponentsInChildren&lt;T&gt;(this GameObject obj) { if (IsMainThread) return obj.GetComponentsInChildren&lt;T&gt;(); var mre = new ManualResetEvent(false); var job = new JobWrapper&lt;GameObject, T[]&gt;(obj, Impl_GetComponentsInChildren, mre); UnityDispatcher.Instance.Invoke(job); mre.WaitOne(); return job.Result; } private static void Impl_GetComponentsInChildren&lt;T&gt;(GameObject obj, out T[] result) { result = obj.GetComponentsInChildren&lt;T&gt;(); } // Object.Instantiate public static GameObject Instantiate(GameObject obj) { if (IsMainThread) return Object.Instantiate(obj); var mre = new ManualResetEvent(false); var job = new JobWrapper&lt;GameObject, GameObject&gt;(obj, Impl_Instantiate, mre); UnityDispatcher.Instance.Invoke(job); mre.WaitOne(); return job.Result; } private static void Impl_Instantiate(GameObject obj, out GameObject result) { result = Object.Instantiate(obj); } } } </code></pre> <p>As you can see I'm checking If I'm in the current thread by creating a MonoSingleton instance of a <code>MonoBehaviour</code>:</p> <pre class="lang-cs prettyprint-override"><code>using System; using System.Threading; using DepotToolkit.Utils; using uzLib.Lite.ExternalCode.Extensions; using uzSourceToolkit.ThirdParty.uSrcTools.Extensions; namespace UnityEngine.Core { #if UNITY_2020 || UNITY_2019 || UNITY_2018 || UNITY_2017 || UNITY_5 /// &lt;summary&gt; /// Inherit from this base class to create a singleton. /// e.g. public class MyClassName : Singleton&lt;MyClassName&gt; {} /// &lt;/summary&gt; public class MonoSingleton&lt;T&gt; : MonoBehaviour // , IStarted where T : MonoBehaviour { // Check to see if we're about to be destroyed. private static bool m_ShuttingDown; private static readonly object m_Lock = new object(); protected static T m_Instance; /// &lt;summary&gt; /// Access singleton instance through this propriety. /// &lt;/summary&gt; public static T Instance { get { if (m_ShuttingDown) { // FIX: Shutting down takes affect after playing a scene, this makes (ie) SteamWorkshopWrapper unavailable on Editor // (check for ExecuteInEditrMode attribute, if available, shutthing down shuld not be performed) // ReSharper disable once ConditionIsAlwaysTrueOrFalse // if (MonoSingletonSettings.ShowWarning) //#pragma warning disable 162 // // ReSharper disable once HeuristicUnreachableCode // Debug.LogWarning(&quot;[Singleton] Instance '&quot; + typeof(T) + // &quot;' already destroyed. Returning null.&quot;); //#pragma warning restore 162 return null; } lock (m_Lock) { if (m_Instance == null) { // Search for existing instance. try { m_Instance = (T)FindObjectOfType(typeof(T)); } catch (UnityException) { // Call with the Dispatcher... var mre = new ManualResetEvent(false); var job = new JobWrapper&lt;T&gt;(Impl_GetInstance, mre); UnityDispatcher.Instance.Invoke(job); mre.WaitOne(); m_Instance = job.Result; } // Create new instance if one doesn't already exist. if (m_Instance == null) { // Need to create a new GameObject to attach the singleton to. try { var singletonObject = new GameObject(); m_Instance = singletonObject.AddComponent&lt;T&gt;(); singletonObject.name = typeof(T).Name + &quot; (Singleton)&quot;; //((MonoSingleton&lt;T&gt;)m_Instance).IsStarted = false; // Make instance persistent. if (IsPlaying()) DoAction(() =&gt; DontDestroyOnLoad(singletonObject)); // TODO } catch (UnityException) { var singletonObject = CreateGameObject(); m_Instance = AddComponent&lt;T&gt;(singletonObject); DoAction(() =&gt; singletonObject.name = typeof(T).Name + &quot; (Singleton)&quot;); } } } return m_Instance; } } protected set =&gt; m_Instance = value; } private static void Impl_GetInstance(out T result) { result = (T)FindObjectOfType(typeof(T)); } private static void Impl_CreateInstance(out GameObject obj) { obj = new GameObject(); } private static void Impl_IsPlaying(out bool result) { result = Application.isPlaying; } private static void Impl_AddComponent&lt;TMethod&gt;(GameObject obj, out TMethod result) where TMethod : Component { result = obj.AddComponent&lt;TMethod&gt;(); } private static GameObject CreateGameObject() { var mre = new ManualResetEvent(false); var job = new JobWrapper&lt;GameObject&gt;(Impl_CreateInstance, mre); UnityDispatcher.Instance.Invoke(job); mre.WaitOne(); return job.Result; } private static TMethod AddComponent&lt;TMethod&gt;(GameObject gameObject) where TMethod : Component { var mre = new ManualResetEvent(false); var job = new JobWrapper&lt;GameObject, TMethod&gt;(gameObject, Impl_AddComponent, mre); UnityDispatcher.Instance.Invoke(job); mre.WaitOne(); return job.Result; } private static void DoAction(Action action) { var mre = new ManualResetEvent(false); var job = new JobWrapper(action, mre); UnityDispatcher.Instance.Invoke(job); mre.WaitOne(); } private static bool IsPlaying() { var mre = new ManualResetEvent(false); var job = new JobWrapper&lt;bool&gt;(Impl_IsPlaying, mre); UnityDispatcher.Instance.Invoke(job); mre.WaitOne(); return job.Result; } public bool ExecuteInEditMode =&gt; GetType().IsExecutingInEditMode(); public bool IsStarted { get; set; } public static T Create() { var go = new GameObject(typeof(T).Name); return go.GetOrAddComponent&lt;T&gt;(); } private void OnApplicationQuit() { if (!ExecuteInEditMode) m_ShuttingDown = true; } private void OnDestroy() { if (!ExecuteInEditMode) m_ShuttingDown = true; } } #endif } </code></pre> <p>As you can see, the <code>MonoSingleton</code> class is already protected from external thread calls by using <em>try/catch</em> blocks with <code>UnityExceptions</code>.</p> <p>My main three concerns about my implementation are the following:</p> <ul> <li>I'm not able to figure out how to make easier the implementation of the <code>JobWrapper</code>, as you can see every time I need to create a thread-safe method I use the following four lines that are repeated lots and lots of times:</li> </ul> <pre class="lang-cs prettyprint-override"><code>var mre = new ManualResetEvent(false); var job = new JobWrapper&lt;GameObject, T[]&gt;(obj, Impl_GetComponentsInChildren, mre); UnityDispatcher.Instance.Invoke(job); mre.WaitOne(); return job.Result; </code></pre> <ul> <li>On the attached code from above you can see <code>Impl_GetComponentsInChildren</code> which is the alias for doing this simple thing (<strong>THAT IS EXECUTED ON THE UNITY THREAD</strong>):</li> </ul> <pre class="lang-cs prettyprint-override"><code>private static void Impl_GetComponentsInChildren&lt;T&gt;(GameObject obj, out T[] result) { result = obj.GetComponentsInChildren&lt;T&gt;(); } </code></pre> <p>My question here is there a nicer way to do this?</p> <ul> <li><p>Has my Unity Dispatcher a good design on the memory / CPU usage part? I mean, this will be called lots and lots of times and I didn't benchmark this yet. So, can you suggest to me something lighter or a tip to keep in mind for this topic?</p> </li> <li><p>Other problems could be the loss of the stack trace. Can somebody give a tip for this?</p> </li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-09T00:57:20.773", "Id": "511331", "Score": "0", "body": "How did you get on with this, and what are you polling at a higher rate? Am trying to solve the problem of detecting input at far faster rates than update/fixedUpdate, and thinking to use threads... too...." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T20:27:56.857", "Id": "251108", "Score": "2", "Tags": [ "design-patterns", "thread-safety", "unity3d" ], "Title": "Is this a good pattern design for a Unity dispatcher for creating thread safe methods?" }
251108
<p>A dataframe and a right-sided formula are given:</p> <pre><code>dat &lt;- data.frame( A = c(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;), B = c(&quot;x&quot;, &quot;y&quot;, &quot;z&quot;), NotUsed = c(1, 2, 3) ) frml &lt;- ~ A + B + A:B </code></pre> <p>From them, I want to get this list:</p> <pre><code># [[1]] # [1] a b c # Levels: a b c # # [[2]] # [1] x y z # Levels: x y z # # [[3]] # [1] a:x b:y c:z # Levels: a:x b:y c:z </code></pre> <p>Here is how I get this list:</p> <pre><code>library(lazyeval) # to use 'as.lazy' and 'lazy_eval' tf &lt;- terms.formula(frml) factors &lt;- rownames(attr(tf, &quot;factors&quot;)) tvars &lt;- attr(tf, &quot;variables&quot;) tlabs &lt;- attr(tf, &quot;term.labels&quot;) used &lt;- lapply(eval(tvars, envir = dat), as.factor) names(used) &lt;- factors lapply(tlabs, function(tlab){ droplevels(lazy_eval(as.lazy(tlab), data = used)) }) </code></pre> <p>Do you have a better way to propose?</p>
[]
[ { "body": "<h1>Code Quality</h1>\n<h2>Blank Lines</h2>\n<p>Generally, your code quality needs some improvement. For example, insert blank lines. So instead of</p>\n<pre><code>factors &lt;- rownames(attr(tf, &quot;factors&quot;))\ntvars &lt;- attr(tf, &quot;variables&quot;)\ntlabs &lt;- attr(tf, &quot;term.labels&quot;)\n</code></pre>\n<p>I would suggest</p>\n<pre><code>factors &lt;- rownames(attr(tf, &quot;factors&quot;))\n\ntvars &lt;- attr(tf, &quot;variables&quot;)\n\ntlabs &lt;- attr(tf, &quot;term.labels&quot;)\n</code></pre>\n<h2>Order Within A Script or Source Code</h2>\n<p>Generally, one puts package <em>import statements</em> at the top of a file. Which you are not doing, and you also give no reason why you are doing it. So I would put <code>library(lazyeval)</code> at the top.</p>\n<p>Further, you set variables before you use them. For example, <code>factors &lt;- rownames(attr(tf, &quot;factors&quot;))</code>.</p>\n<p>These observations lead to the following script.</p>\n<pre><code># to use 'as.lazy' and 'lazy_eval'\nlibrary(lazyeval)\n\n\ndat &lt;- data.frame(\n A = c(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;),\n B = c(&quot;x&quot;, &quot;y&quot;, &quot;z&quot;),\n NotUsed = c(1, 2, 3))\n\n\nfrml &lt;- ~ A + B + A:B\ntf &lt;- terms.formula(frml)\n\n\ntvars &lt;- attr(tf, &quot;variables&quot;)\nused &lt;- lapply(eval(tvars, envir = dat), as.factor)\nnames(used) &lt;- rownames(attr(tf, &quot;factors&quot;))\n\n\ntlabs &lt;- attr(tf, &quot;term.labels&quot;)\n\nlapply(tlabs, function(tlab){\n droplevels(lazy_eval(as.lazy(tlab), data = used))\n})\n</code></pre>\n<p>Please pay attention to how a grouped the code lines.</p>\n<h1>A Better Way</h1>\n<p>Regarding a better way, for which you have asked, I would propose the following.</p>\n<pre><code>dat &lt;- data.frame(A = c(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;),\n B = c(&quot;x&quot;, &quot;y&quot;, &quot;z&quot;),\n NotUsed = c(1, 2, 3))\n\ndat &lt;- subset(x = dat, select = -NotUsed)\n\ndat$c &lt;- as.factor(paste(dat$A, dat$B, sep = &quot;:&quot;))\n\nmy.list &lt;- lapply(dat,\n FUN = function(column)\n {\n return(column)\n })\n</code></pre>\n<p>In my view, this is a better way because it expresses your intention better. If you would have given me your code without any comments I would have a hard time explaining what it does or what it's purpose is. In addition, it does not require an additional package.</p>\n<p>HTH!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-13T13:25:41.340", "Id": "496462", "Score": "1", "body": "Welcome to the Code Review Community. The purpose of the code review community is to help coders improve their coding skills by reading through their code and suggesting how the code can be improved. Unlike stack overflow, instead of posting solutions we post meaningful observations about the code. Code only alternate solutions are considered poor answers and may be deleted by the community. Please read [How do I write a good answer?](https://codereview.stackexchange.com/help/how-to-answer)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-16T11:31:49.127", "Id": "496766", "Score": "0", "body": "Your \"better way\" is specific to this example. I need something general." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-16T13:27:54.890", "Id": "496773", "Score": "0", "body": "@StéphaneLaurent And what should be more general? Selecting the columns?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-16T14:33:30.153", "Id": "496783", "Score": "0", "body": "E.g. `~ A + B + C/A + A*B + A:B:C + ...`. Moreover I want to use a formula, which disappeared in your code." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-13T11:11:57.940", "Id": "252049", "ParentId": "251109", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-24T20:37:42.367", "Id": "251109", "Score": "3", "Tags": [ "r" ], "Title": "Construct list from a dataframe and a formula" }
251109
<p>In order to improve the performance of this code fragment, I have speeded up some code fragments by using the numba. However, a frustrating thing is that the performance of this decision tree is bad. For example, in the below code fragment, the performance of the decision tree is nearly 70 times slower than the implementation in Scikit-learn (220 ms vs 3 ms). Therefore, how can I achieve better performance by modifying this code?</p> <pre class="lang-py prettyprint-override"><code>import time import numpy as np from numba import njit from sklearn.base import BaseEstimator from sklearn.datasets import make_hastie_10_2 from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier class Node: def __init__(self, left, right, rule): self.left = left self.right = right self.feature = rule[0] self.threshold = rule[1] class Leaf: def __init__(self, value): &quot;&quot;&quot; `value` is an array of class probabilities if classifier is True, else the mean of the region &quot;&quot;&quot; self.value = value class DecisionTree(BaseEstimator): def __init__( self, classifier=True, max_depth=None, n_feats=None, criterion=&quot;entropy&quot;, seed=None, regularized=False, ): &quot;&quot;&quot; A decision tree model for regression and classification problems. Parameters ---------- classifier : bool Whether to treat target values as categorical (classifier = True) or continuous (classifier = False). Default is True. max_depth: int or None The depth at which to stop growing the tree. If None, grow the tree until all leaves are pure. Default is None. n_feats : int Specifies the number of features to sample on each split. If None, use all features on each split. Default is None. criterion : {'mse', 'entropy', 'gini'} The error criterion to use when calculating splits. When `classifier` is False, valid entries are {'mse'}. When `classifier` is True, valid entries are {'entropy', 'gini'}. Default is 'entropy'. seed : int or None Seed for the random number generator. Default is None. &quot;&quot;&quot; if seed: np.random.seed(seed) self.depth = 0 self.root = None self.n_feats = n_feats self.criterion = criterion self.classifier = classifier self.max_depth = max_depth if max_depth else np.inf self.factor = 1.2 self.regularized = regularized self.feature_importances_ = None if not classifier and criterion in [&quot;gini&quot;, &quot;entropy&quot;]: raise ValueError( &quot;{} is a valid criterion only when classifier = True.&quot;.format(criterion) ) if classifier and criterion == &quot;mse&quot;: raise ValueError(&quot;`mse` is a valid criterion only when classifier = False.&quot;) def fit(self, X, Y): &quot;&quot;&quot; Fit a binary decision tree to a dataset. Parameters ---------- X : :py:class:`ndarray &lt;numpy.ndarray&gt;` of shape `(N, M)` The training data of `N` examples, each with `M` features Y : :py:class:`ndarray &lt;numpy.ndarray&gt;` of shape `(N,)` An array of integer class labels for each example in `X` if self.classifier = True, otherwise the set of target values for each example in `X`. &quot;&quot;&quot; self.n_classes = max(Y) + 1 if self.classifier else None self.feature_importances_ = np.zeros(X.shape[1]) self.used_variables = np.zeros(X.shape[1]) self.n_feats = X.shape[1] if not self.n_feats else min(self.n_feats, X.shape[1]) self.root = self._grow(X, Y) self.feature_importances_ = self.feature_importances_ / np.sum(self.feature_importances_) def predict(self, X): &quot;&quot;&quot; Use the trained decision tree to classify or predict the examples in `X`. Parameters ---------- X : :py:class:`ndarray &lt;numpy.ndarray&gt;` of shape `(N, M)` The training data of `N` examples, each with `M` features Returns ------- preds : :py:class:`ndarray &lt;numpy.ndarray&gt;` of shape `(N,)` The integer class labels predicted for each example in `X` if self.classifier = True, otherwise the predicted target values. &quot;&quot;&quot; return np.array([self._traverse(x, self.root) for x in X]) def predict_class_probs(self, X): &quot;&quot;&quot; Use the trained decision tree to return the class probabilities for the examples in `X`. Parameters ---------- X : :py:class:`ndarray &lt;numpy.ndarray&gt;` of shape `(N, M)` The training data of `N` examples, each with `M` features Returns ------- preds : :py:class:`ndarray &lt;numpy.ndarray&gt;` of shape `(N, n_classes)` The class probabilities predicted for each example in `X`. &quot;&quot;&quot; assert self.classifier, &quot;`predict_class_probs` undefined for classifier = False&quot; return np.array([self._traverse(x, self.root, prob=True) for x in X]) def _grow(self, X, Y, cur_depth=0): # if all labels are the same, return a leaf if len(set(Y)) == 1: if self.classifier: prob = np.zeros(self.n_classes) prob[Y[0]] = 1.0 return Leaf(prob) if self.classifier else Leaf(Y[0]) # if we have reached max_depth, return a leaf if cur_depth &gt;= self.max_depth: v = np.mean(Y, axis=0) if self.classifier: v = np.bincount(Y, minlength=self.n_classes) / len(Y) return Leaf(v) cur_depth += 1 self.depth = max(self.depth, cur_depth) N, M = X.shape feat_idxs = np.random.choice(M, self.n_feats, replace=False) # greedily select the best split according to `criterion` feat, thresh, best_gain = _segment(self.criterion, self.regularized, self.used_variables, self.factor, X, Y, feat_idxs) self.feature_importances_[feat] += len(X) * best_gain self.used_variables[feat] = 1 l = np.argwhere(X[:, feat] &lt;= thresh).flatten() r = np.argwhere(X[:, feat] &gt; thresh).flatten() # grow the children that result from the split left = self._grow(X[l, :], Y[l], cur_depth) right = self._grow(X[r, :], Y[r], cur_depth) return Node(left, right, (feat, thresh)) def _traverse(self, X, node, prob=False): if isinstance(node, Leaf): if self.classifier: return node.value if prob else node.value.argmax() return node.value if X[node.feature] &lt;= node.threshold: return self._traverse(X, node.left, prob) return self._traverse(X, node.right, prob) @njit() def _segment(criterion, regularized, used_variables, factor, X, Y, feat_idxs): &quot;&quot;&quot; Find the optimal split rule (feature index and split threshold) for the data according to `self.criterion`. &quot;&quot;&quot; best_gain = -np.inf split_idx, split_thresh = None, None for i in feat_idxs: vals = X[:, i] levels = np.unique(vals) thresholds = (levels[:-1] + levels[1:]) / 2 if len(levels) &gt; 1 else levels gains = np.array([_impurity_gain(criterion, Y, t, vals) for t in thresholds]) if regularized and used_variables[i]: gains = gains * factor if gains.max() &gt; best_gain: split_idx = i best_gain = gains.max() split_thresh = thresholds[gains.argmax()] return split_idx, split_thresh, best_gain @njit() def _impurity_gain(criterion, Y, split_thresh, feat_values): &quot;&quot;&quot; Compute the impurity gain associated with a given split. IG(split) = loss(parent) - weighted_avg[loss(left_child), loss(right_child)] &quot;&quot;&quot; if criterion == &quot;entropy&quot;: parent_loss = entropy(Y) elif criterion == &quot;gini&quot;: parent_loss = gini(Y) elif criterion == &quot;mse&quot;: parent_loss = mse(Y) else: raise Exception # generate split left = np.argwhere(feat_values &lt;= split_thresh).flatten() right = np.argwhere(feat_values &gt; split_thresh).flatten() if len(left) == 0 or len(right) == 0: return 0 # compute the weighted avg. of the loss for the children n = len(Y) n_l, n_r = len(left), len(right) if criterion == &quot;entropy&quot;: e_l, e_r = entropy(Y[left]), entropy(Y[right]) elif criterion == &quot;gini&quot;: e_l, e_r = gini(Y[left]), gini(Y[right]) else: raise Exception child_loss = (n_l / n) * e_l + (n_r / n) * e_r # impurity gain is difference in loss before vs. after split ig = parent_loss - child_loss return ig @njit() def mse(y): &quot;&quot;&quot; Mean squared error for decision tree (ie., mean) predictions &quot;&quot;&quot; return np.mean((y - np.mean(y)) ** 2) @njit() def entropy(y): &quot;&quot;&quot; Entropy of a label sequence &quot;&quot;&quot; hist = np.bincount(y) ps = hist / np.sum(hist) # return -np.sum([p * np.log2(p) for p in ps if p &gt; 0]) return -np.array([p * np.log2(p) for p in ps if p &gt; 0]).sum() @njit() def gini(y): &quot;&quot;&quot; Gini impurity (local entropy) of a label sequence &quot;&quot;&quot; hist = np.bincount(y) N = np.sum(hist) return 1 - np.array([(i / N) ** 2 for i in hist]).sum() if __name__ == '__main__': n_samples = 1000 X, y = make_hastie_10_2(n_samples=n_samples) y[y &lt; 0] = 0 X = X.astype(np.float) y = y.astype(np.int) test_size = 0.2 print(X.shape) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size) ts = time.time() tree = DecisionTree(seed=0, criterion='gini', max_depth=3) tree.fit(X_train, y_train) print(accuracy_score(y_train, tree.predict(X_train))) print(accuracy_score(y_test, tree.predict(X_test))) te = time.time() print('%2.2f ms' % ((te - ts) * 1000)) ts = time.time() tree = DecisionTree(seed=0, criterion='gini', max_depth=3) tree.fit(X_train, y_train) print(accuracy_score(y_train, tree.predict(X_train))) print(accuracy_score(y_test, tree.predict(X_test))) te = time.time() print('%2.2f ms' % ((te - ts) * 1000)) ts = time.time() tree = DecisionTreeClassifier(random_state=0, max_depth=3) tree.fit(X_train, y_train) print(accuracy_score(y_train, tree.predict(X_train))) print(accuracy_score(y_test, tree.predict(X_test))) te = time.time() print('%2.2f ms' % ((te - ts) * 1000)) <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T07:21:35.700", "Id": "494215", "Score": "1", "body": "Welcome to CR, please [edit] your title so that it only states what your code does and not what you would expect in a review. Also, try to give a better description of your what your code does in the question body as your current description is a little broad" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-04T02:28:51.370", "Id": "495307", "Score": "0", "body": "Please add more tags (ex scipy, numpy)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T01:51:50.100", "Id": "251114", "Score": "1", "Tags": [ "python", "machine-learning" ], "Title": "How to speed up this numba based decision tree?" }
251114
<p>Basically, the server gives me a <code>token</code> object. I am planning to check the <code>token</code> on the client if it is expired/valid before making a request to the server.</p> <p>The function below works as expected. I just want to know if my code catch-all edge cases? I don't want, even 1 second that will request will fail due to an expired access token.</p> <p>I am using <code>moment</code> for comparing dates. I also converted the current date and expiry date to UTC so that I'm making sure that they are in the same timezone before comparing them.</p> <pre class="lang-javascript prettyprint-override"><code>const moment = require('moment'); /** The token object passed in the function looks like this: { access_token: '2hbssMdXDpwQX5WcnZ-iJlO754MLkEeDCmF-f1A-MaU', token_type: 'Bearer', expires_in: 604800, refresh_token: 'VxnN9uBVIcNMpuwRVpvXo2YxWuNFEayHqfnCM7aCTSI', scope: 'public', created_at: 1603604241 } */ export default function tokenValid(token = {}) { const currentDate = moment().utc(); const expiryDate = moment.unix(token.created_at).add(token.expires_in, 'seconds').utc(); return currentDate &lt; expiryDate; } </code></pre> <p><strong>EDIT (based on @hjpotter92's comment)</strong></p> <pre class="lang-js prettyprint-override"><code>export default function tokenValid(token = {}) { const currentDate = moment().unix(); const expiryDate = token.created_at + token.expires_in; return currentDate &lt; expiryDate; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T06:56:31.593", "Id": "494212", "Score": "1", "body": "epoch (or unix time) is always timezone insensitive. you can treat it as a normal number." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T07:28:48.567", "Id": "494217", "Score": "0", "body": "@hjpotter92 I have updated the code based on your comment." } ]
[ { "body": "<p>Welcome to Code Review!</p>\n<p>As I already mentioned in comments, epoch values can be treated as normal numerals, without having to involve momentjs or other external libraries.</p>\n<p>In js, you can get current epoch value in milliseconds accuracy using <code>Date.now()</code>. The value in token is with seconds accuracy. It is only a factor of 1000.</p>\n<h2>Rewrite</h2>\n<pre class=\"lang-js prettyprint-override\"><code>/**\nThe token object passed in the function looks like this:\n{\n access_token: '2hbssMdXDpwQX5WcnZ-iJlO754MLkEeDCmF-f1A-MaU',\n token_type: 'Bearer',\n expires_in: 604800,\n refresh_token: 'VxnN9uBVIcNMpuwRVpvXo2YxWuNFEayHqfnCM7aCTSI',\n scope: 'public',\n created_at: 1603604241\n}\n*/\n\nexport default function tokenValid(token = {}) {\n const now = Date.now() / 1000;\n const expiry = token.created_at + token.expires_in;\n return now &lt; expiry;\n}\n</code></pre>\n<hr />\n<h2>EDIT</h2>\n<p>In response to the comment:</p>\n<p>Changed</p>\n<pre><code>// from\nparseInt(Date.now() / 1000)\n// to\nDate.now() / 1000\n</code></pre>\n<p>In the case here, <code>Math.floor</code> or <code>Math.round</code> are more suitable. <code>parseInt</code> is usually called when you want to convert from string to integer. We already know that <code>Date.now()</code> is giving a number and not a string. Also, the conversion/rounding is not really needed here.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T07:47:07.460", "Id": "494220", "Score": "0", "body": "I have seen that most use `Math.floor()` to remove the millisecond in `Date.now()` instead of `parseInt`, is there any advantages on using `parseInt`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T08:03:48.443", "Id": "494222", "Score": "1", "body": "I also changed this `token.created_at + token.expires_in` to `token.created_at + token.expires_in - 60`, the `60` seconds is for fail-safe. The use case would be if there is only 1 second before the expiration time the client will mark it as valid, but if the request to server took longer that 1 second, it will be expired when it reaches the server." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T07:42:36.787", "Id": "251119", "ParentId": "251116", "Score": "3" } }, { "body": "<p>You seem to ignore two facts.</p>\n<ol>\n<li><p>The client clock can be out of sync with the server clock.</p>\n</li>\n<li><p>The transport of the request from client to server takes more then zero time.</p>\n</li>\n</ol>\n<p>Both these cases mean that no matter how hard you try on the client side, there is always a chance that the server will evaluate the token as expired during its processing.</p>\n<p>What you should do is have the client take the same action when server refuses the token as you do when your client side validation fails.</p>\n<p>In general, client side validation</p>\n<ul>\n<li>is not necesary</li>\n<li>is not reliable</li>\n<li>reduces network traffic</li>\n<li>increases user experience</li>\n</ul>\n<p>Whereas backend side validation</p>\n<ul>\n<li>is necesary</li>\n<li>is the only source of truth</li>\n</ul>\n<p>Clients should understand and handle possible server side validation errors prior to deploying their own validation logic.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T08:13:46.140", "Id": "251120", "ParentId": "251116", "Score": "5" } } ]
{ "AcceptedAnswerId": "251119", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T06:16:30.667", "Id": "251116", "Score": "3", "Tags": [ "javascript", "datetime" ], "Title": "Checking if the access token is valid or expired" }
251116
<p>I am learning C++ programming and just learned about basic OOP and decided to create a simple project to test my understanding and practice what I've learned. The idea I came up with is an event tracking system where you add events into a calendar and then you get all of your events displayed. I have 2 classes: <code>Event</code>, where your events are created, and <code>Calendar</code>, which holds a vector of all Events. Could you please review my code saying what are the most efficient ways of doing things and the best practices to be followed?</p> <hr /> <h1><code>Main.cpp</code></h1> <pre class="lang-cpp prettyprint-override"><code>#include &quot;Calendar.h&quot; int main() { Calendar calendar {}; calendar.add_event(&quot;Exam&quot;, &quot;urgent&quot;, &quot;10/12/2020&quot;, &quot;10:30&quot;); calendar.add_event(&quot;Meeting&quot;, &quot;non-urgent&quot;, &quot;08/11/2020&quot;, (&quot;12:20&quot;)); calendar.display_events(); } </code></pre> <h1><code>Event.h</code></h1> <pre class="lang-cpp prettyprint-override"><code>#include &lt;string&gt; class Event { private: std::string event_type; std::string event_priority; std::string event_date; std::string event_time; public: Event(std::string eventType, std::string eventPriority, std::string eventDate, std::string eventTime); bool display_event() const; ~Event(); }; </code></pre> <h1><code>Event.cpp</code></h1> <pre class="lang-cpp prettyprint-override"><code>#include &quot;Event.h&quot; #include &lt;iostream&gt; #include &lt;utility&gt; Event::Event(std::string eventType, std::string eventPriority, std::string eventDate, std::string eventTime) : event_type(std::move(eventType)), event_priority(std::move(eventPriority)), event_date(std::move(eventDate)), event_time(std::move(eventTime)) { } bool Event::display_event() const { std::cout &lt;&lt; &quot;You have &quot; &lt;&lt; event_type &lt;&lt; &quot; on &quot; &lt;&lt; event_date &lt;&lt; &quot; at &quot; &lt;&lt; event_time &lt;&lt; &quot; it's &quot; &lt;&lt; event_priority &lt;&lt; &quot;\n&quot;; return true; } Event::~Event() = default; </code></pre> <h1><code>Calendar.h</code></h1> <pre class="lang-cpp prettyprint-override"><code>#include &quot;Event.h&quot; #include &lt;vector&gt; class Calendar { private: std::vector&lt;Event&gt; calendar; public: bool display_events() const; bool add_event(std::string event_type, std::string event_priority, std::string event_date, std::string event_time); const std::vector&lt;Event&gt; &amp;getCalendar() const; bool is_event_valid(const std::string&amp; event_date, const std::string&amp; event_time); ~Calendar(); }; </code></pre> <h1><code>Calendar.cpp</code></h1> <pre class="lang-cpp prettyprint-override"><code>#include &quot;Calendar.h&quot; #include &lt;iostream&gt; #include &lt;utility&gt; const std::vector&lt;Event&gt; &amp;Calendar::getCalendar() const { return calendar; } bool Calendar::display_events() const { if (!getCalendar().empty()) { for (const auto &amp;event : calendar) { event.display_event(); } return true; } else { std::cout &lt;&lt; &quot;Your calendar is empty \n&quot;; return false; } } bool Calendar::add_event(std::string event_type, std::string event_priority, std::string event_date, std::string event_time) { if (is_event_valid(event_date, event_time)) { Event event {std::move(event_type), std::move(event_priority), std::move(event_date), std::move(event_time)}; calendar.push_back(event); return true; } else { std::cout &lt;&lt; &quot;Event is not valid\n&quot;; return false; } } bool Calendar::is_event_valid(const std::string&amp; event_date, const std::string&amp; event_time) { int day{}, month{}, year{}, hours{}, minutes{}; day = std::stoi(event_date.substr(0,2)); month = std::stoi(event_date.substr(3, 2)); year = std::stoi(event_date.substr(6, 4)); hours = std::stoi(event_time.substr(0, 2)); minutes = std::stoi(event_time.substr(3, 2)); bool is_date_valid = (day &gt; 0 &amp;&amp; day &lt;= 24) &amp;&amp; (month &gt; 0 &amp;&amp; month &lt;= 12) &amp;&amp; (year &gt;= 2020 &amp;&amp; year &lt;= 3030); bool is_time_valid = (hours &gt;= 0 &amp;&amp; hours &lt;= 24) &amp;&amp; (minutes &gt;= 0 &amp;&amp; minutes &lt;= 60); if (is_date_valid &amp;&amp; is_time_valid) { return true; } else { std::cout &lt;&lt; &quot;The event's time or date is not valid\n&quot;; return false; } } Calendar::~Calendar() = default; </code></pre> <p>I am also thinking about adding a feature where you can sort the events by date.</p>
[]
[ { "body": "<p>Looking at your program, I would say that you have done a pretty good job considering that you are just a beginner.</p>\n<hr />\n<h1><code>private</code> or <code>public</code>?</h1>\n<p>Let's have a look at your <code>Event</code> class</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>class Event {\nprivate:\n std::string event_type;\n std::string event_priority;\n std::string event_date;\n std::string event_time;\n\npublic:\n Event(std::string eventType, std::string eventPriority, std::string eventDate,\n std::string eventTime);\n\n bool display_event() const;\n\n ~Event();\n};\n</code></pre>\n<p>The 4 main parts of your event, which are the type, priority, date, and time are declared <code>private</code>. <br>\nThe problem with this is that now once you have set the <code>Event</code>, there is no way the user can modify it. What if the user's boss decides to re-schedule a meeting, he realizes that he would have to create an entirely new event, and delete the previous one. This wouldn't\nbe as convenient as simply being able to change any attribute of <code>Event</code>. <br></p>\n<p>Another scenario, you have mentioned in your question</p>\n<blockquote>\n<p>I am also thinking about adding a feature where you can sort the events by date.</p>\n</blockquote>\n<p>This means that your <code>Calendar</code> should be able to see the events' dates. But the way you have designed your class, this would be impossible.</p>\n<p>For those reasons, I believe making the 4 main attributes of <code>Event</code> public would make sense.</p>\n<hr />\n<h1>Don't encode date/time as <code>std::string</code>.</h1>\n<pre class=\"lang-cpp prettyprint-override\"><code>day = std::stoi(event_date.substr(0,2));\nmonth = std::stoi(event_date.substr(3, 2));\nyear = std::stoi(event_date.substr(6, 4));\nhours = std::stoi(event_time.substr(0, 2));\nminutes = std::stoi(event_time.substr(3, 2));\n</code></pre>\n<p>All numbers here are known as <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\"><b>magic numbers</b></a>. <br>\nThe problem with encoding date/time as <code>std::string</code> is that now if you want to extract any information, you will have to do</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>std::stoi(event_time.substr(3, 2));\n</code></pre>\n<p>I suggest that you create your own <code>date/time</code> class or even use one already defined in the <a href=\"https://en.cppreference.com/w/cpp/chrono\" rel=\"nofollow noreferrer\">std::chrono library</a> ( C++ 20).</p>\n<p>Here is a very very simple date class</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>struct Date\n{\n int day;\n int month;\n int year;\n \n date(int day, int month, int year)\n : day(day),month(month),year(year)\n {}\n};\n</code></pre>\n<p>Now instead of having to do <code>substr</code> again and again which can get weird. You can easily access specific parts of a date</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>Date date(25,9,2020)\n// boss says push the meeting \n\ndate.day = 30;\n</code></pre>\n<p>Note that this is just an example. You also need to validate the date. An example of a nice feature might be <code>post_pone()</code> which can extend a date by a certain number of days.</p>\n<p>The sample applies for time, a simple <code>struct</code> will let you get more control of things and also simplify stuff at the same <em>time</em>.</p>\n<hr />\n<h1>Extend <code>Event</code></h1>\n<p>Your <code>Event</code> misses a few attributes.</p>\n<ul>\n<li>Place of the event</li>\n<li>Description of the event</li>\n<li>Duration</li>\n</ul>\n<hr />\n<h1>If-else logic</h1>\n<pre class=\"lang-cpp prettyprint-override\"><code>bool Calendar::add_event(std::string event_type, std::string event_priority, std::string event_date,\n std::string event_time) {\n\n if (is_event_valid(event_date, event_time))\n {\n Event event {std::move(event_type), std::move(event_priority), std::move(event_date), std::move(event_time)};\n calendar.push_back(event);\n return true;\n } else {\n std::cout &lt;&lt; &quot;Event is not valid\\n&quot;;\n return false;\n }\n}\n</code></pre>\n<p>If you simply reverse the conditions, you can simplify the code and remove one branch</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>bool Calendar::add_event(std::string event_type, std::string event_priority, std::string event_date,\n std::string event_time) {\n\n if (!is_event_valid(event_date, event_time))\n {\n std::cout &lt;&lt; &quot;Event is not valid\\n&quot;;\n return false;\n } \n Event event {std::move(event_type), std::move(event_priority), std::move(event_date), std::move(event_time)};\n calendar.push_back(event);\n return true;\n}\n</code></pre>\n<ul>\n<li>Furthermore, I would suggest that you display the event after saying <code>Event is not valid</code>. Because if you added more than 5-6 events to your calendar, and all you say was <code>Event is not valid</code>, you would have to do a search to track down which event</li>\n</ul>\n<hr />\n<h1>Extend <code>Calendar</code></h1>\n<p>Your <code>Calendar</code> class misses some key functions.</p>\n<ul>\n<li>Ability to delete/remove an event</li>\n<li>Modify an event</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T17:33:13.073", "Id": "494275", "Score": "0", "body": "[This article](https://queue.acm.org/detail.cfm?id=3372264) doesn't directly answer your question but it does answer your question. If the body of the function isn't available where it is called, then the compiler can't consider inlining." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T21:42:38.253", "Id": "494286", "Score": "0", "body": "`std::chrono` is C++11, it's just the conversion to/from calendar dates that is added in `C++20`. The best thing to do now is to store dates internally as [`std::chrono::time_point`](https://en.cppreference.com/w/cpp/chrono/time_point)s and only do the conversion to/from human readable form during input and output." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T11:35:42.933", "Id": "494328", "Score": "0", "body": "Downvoter can I know your reason?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T15:06:06.910", "Id": "251133", "ParentId": "251123", "Score": "5" } }, { "body": "<h2>General Observations</h2>\n<p>Welcome to the Code Review Site. Nice starting question, very good for a begining C++ programmer and a new member of the Code Review Community.</p>\n<p>The functions follow the Single Responsibility Principle (SRP) which is excellent. The classes also follow the SRP which is very good as well. You aren't making a fairly common beginner mistake by using the <code>using namespace std;</code> statement. Good use of <code>const</code> in many of the functions.</p>\n<p>The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> states:</p>\n<blockquote>\n<p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n<p>The SRP is the S in the SOLID programming principles below.</p>\n<p>The object oriented design needs some work, for instance the <code>Event</code> class should have an <code>is_valid()</code> method to let each event validate itself, this would be useful when creating a new event. The <code>Calendar</code> class could use this method and doesn't need to know about the private members of the event class. Including access to the private members of the <code>Event</code> class in the <code>Calendar</code> class prevents this from being a <a href=\"https://en.wikipedia.org/wiki/SOLID\" rel=\"nofollow noreferrer\">SOLID</a> object oriented design.</p>\n<blockquote>\n<p>In object-oriented computer programming, SOLID is a mnemonic acronym for five design principles intended to make software designs more understandable, flexible and maintainable.</p>\n</blockquote>\n<h2>Include Guards</h2>\n<p>In C++ as well as the C programming language the code import mechanism <code>#include FILE</code> actually copies the code into a temporary file generated by the compiler. Unlike some other modern languages C++ (and C) will include a file multiple times. To prevent this programmers use include guards which can have 2 forms:</p>\n<ol>\n<li><p>the more portable form is to embed the code in a pair of pre-processor statements</p>\n<p>#ifndef SYMBOL<br />\n#define SYMBOL<br />\n// All other necessary code<br />\n#endif // SYMBOL</p>\n</li>\n<li><p>A popular form that is supported by most but not all C++ compilers is to put <code>#pragma once</code> at the top of the header file.</p>\n</li>\n</ol>\n<p>Using one of the 2 methods above to prevent the contents of a file from being included multiple times is a best practice for C++ programming. This can improve compile times if the file is included multiple times, it can also prevent compiler errors and linker errors.</p>\n<h2>Class Declarations in Header Files</h2>\n<p>For both the <code>Event</code> and <code>Calendar</code> classes you define a destructor for the object in the class declaration and then set that destructor in the <code>.cpp</code> file, it would be better to do this in the class declarations themselves. For simple or single line functions such as <code>display_event()</code> you should also include the body of the function to allow the optimizing compiler to decide if the function should be <code>inlined</code> or not.</p>\n<p>In C++ the section of the class immediately following <code>class CLASSNAME {</code> is private by default so the keyword <code>private</code> isn't necessary where you have it in your code. Current conventions in object oriented programming are to put <code>public</code> methods and variables first, followed by <code>protected</code> methods and variables with <code>private</code> methods and variables last. This convention came about because you may not be the only one working on a project and someone else may need to be able to quickly find the public interfaces for a class.</p>\n<p>Example of <code>Event</code> class refactored</p>\n<pre><code>#include &lt;iostream&gt; \n#include &lt;string&gt;\n\nclass Event {\npublic:\n Event(std::string eventType, std::string eventPriority, std::string eventDate,\n std::string eventTime);\n\n bool display_event() const {\n std::cout &lt;&lt; &quot;You have &quot; &lt;&lt; event_type &lt;&lt; &quot; on &quot; &lt;&lt; event_date &lt;&lt; &quot; at &quot; &lt;&lt; event_time &lt;&lt; &quot; it's &quot; &lt;&lt; event_priority &lt;&lt; &quot;\\n&quot;;\n return true;\n }\n\n ~Event() = default;\n\nprivate:\n std::string event_type;\n std::string event_priority;\n std::string event_date;\n std::string event_time;\n\n};\n</code></pre>\n<h2>Object Oriented Design</h2>\n<p>The <code>Calendar</code> class has dependencies on the private fields of the <code>Event</code> class, the problem with this is it limits the expansion of the code of both classes and makes it difficult to reuse the code which is a primary function of object oriented code. It also makes the code more difficult to maintain. Each class should be responsible for a particular function / job.</p>\n<p>You mention sorting the events by date as a possible expansion of the program, in this case you need to add an <code>&lt;=</code> operator to decide what order the events should be in, that operator should be in the <code>Event</code> class, but it looks like you would implement it in the Calendar class.</p>\n<p>The following code does not belong in a <code>Calendar</code> class method, it belongs in an <code>Event</code> class method:</p>\n<pre><code> day = std::stoi(event_date.substr(0, 2));\n month = std::stoi(event_date.substr(3, 2));\n year = std::stoi(event_date.substr(6, 4));\n hours = std::stoi(event_time.substr(0, 2));\n minutes = std::stoi(event_time.substr(3, 2));\n</code></pre>\n<p>Currently the only way to create a new event is to try to add it to the calendar, it would be better to create each event on it's own, check the validity of the even and then call the add_event() method in the calendar.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T17:01:05.887", "Id": "494269", "Score": "1", "body": "Great answer +1, I wanted to clarify something, will the compiler only consider inlining if I have the definition in the header file too?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T07:54:43.327", "Id": "494305", "Score": "0", "body": "@AryanParekh Usually yes. You need the function definition in the header file for inlining. I say \"usually\" because there is also the \"link time optimization\" feature of many compilers where all functions may get inlined whether they are in the curent translation unit or not. But that has to be enabled manually and slows down compilation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T11:11:12.247", "Id": "494323", "Score": "0", "body": "Nice answer. Just a comment: I think you got a typo (a missing `n`) in the `#ifdef SYMBOL`, when explaining header guards." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T11:58:05.483", "Id": "494332", "Score": "0", "body": "@magnus Thank you, fixed." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T16:45:15.863", "Id": "251139", "ParentId": "251123", "Score": "9" } }, { "body": "<p>To add to the answers of Aryan Parekh and pacmaninbw, which I agree with:</p>\n<h1>Avoid repeating the name of a class in its member variables</h1>\n<p>For example, in <code>class Event</code>, all the member variable names are prefixed with <code>event_</code>, but that is redundant. I would just remove that prefix.</p>\n<h1>Avoid using <code>std::string</code> unless something is really text</h1>\n<p>Apart from date/time information, <code>event_priority</code> is something that probably also should not be a <code>std::string</code>, but rather something the C++ language can more easily work with, like an <code>enum class</code>:</p>\n<pre><code>class Event {\npublic:\n enum class Priority {\n LOW,\n NORMAL,\n URGENT,\n ...\n };\n\nprivate\n std::string type; // this really look like text\n Priority priority;\n ...\n};\n</code></pre>\n<p>Using this type consistenly, you should then be able to write something like:</p>\n<pre><code>Calendar calendar;\ncalendar.add_event(&quot;Exam&quot;, Event::Priority::URGENT, ...);\n</code></pre>\n<p>An enum is stored as an integer, so it is very compact and efficient. There is also no longer a possibility of accidentily adding an invalid or misspelled priority name, like <code>&quot;ugrent&quot;</code>. Of course, now you have to add some functions to convert <code>Priority</code>s to/from human readable text, so it is a bit more work on your part.</p>\n<h1>Pass <code>Event</code>s directly to member functions of <code>Calendar</code></h1>\n<p>Instead of having to pass four parameters to <code>add_event()</code>, just pass a single parameter with type <code>Event</code>. This simplifies the implementation of <code>add_event()</code>, and will make it future-proof. Consider for example adding ten more member variables to <code>Event</code>, this way you avoid adding ten more parameters to <code>add_event()</code> as well! Of course, be sure to pass the parameter as a <code>const</code> reference:</p>\n<pre><code>class Calendar {\n ...\n bool add_event(const Event &amp;event);\n ...\n};\n</code></pre>\n<p>And then you can use it like so:</p>\n<pre><code>Calendar calendar;\ncalendar.add_event({&quot;Exam&quot;, Event::Priority::URGENT, ...});\n</code></pre>\n<h1>Move <code>is_event_valid()</code> to <code>Event</code></h1>\n<p>Checking whether an <code>Event</code> is valid is the responsibility of <code>Event</code>. However, instead of having a (static) member function <code>is_valid()</code> in <code>class Event</code>, consider checking for valid parameters in its constructor, and have it <code>throw</code> a <a href=\"https://en.cppreference.com/w/cpp/error/runtime_error\" rel=\"noreferrer\"><code>std::runtime_error</code></a> if it cannot construct it. That way, <code>Calendar::add_event()</code> doesn't have to do any checking anymore: if you managed to pass it an <code>Event</code>, it can only be a valid one at that point.</p>\n<p>The caller of <code>add_event()</code> has to handle the possibility of the constructor of <code>class Event</code> throwing, but it already had to handle <code>add_event()</code> returning an error anyway, so it is not much more work.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T22:05:32.543", "Id": "251148", "ParentId": "251123", "Score": "7" } } ]
{ "AcceptedAnswerId": "251139", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T12:31:25.887", "Id": "251123", "Score": "10", "Tags": [ "c++", "beginner", "object-oriented" ], "Title": "Event tracking system" }
251123
<p>I've found my app, which uses the <code>SortedList</code>, has a poor performance.<br /> So I decided to try to improve the performance of my app.<br /> I created the <code>FastSortedList</code> class which I think is faster than the original one.</p> <pre class="lang-cs prettyprint-override"><code>public class FastSortedList&lt;TKey, TValue&gt; { IComparer&lt;TKey&gt; _comparer; List&lt;KeyValuePair&lt;TKey, TValue&gt;&gt; _list = new List&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;(); Dictionary&lt;TKey, TValue&gt; _dict = new Dictionary&lt;TKey, TValue&gt;(); public FastSortedList(IComparer&lt;TKey&gt; comparer) { _comparer = comparer ?? Comparer&lt;TKey&gt;.Default; } public int Count =&gt; _list.Count; public IEnumerable&lt;TValue&gt; Values =&gt; _list.Select(i =&gt; i.Value); public void Add(TKey key, TValue value) { if (_dict.ContainsKey(key)) throw new ArgumentException(&quot;An entry with the same key already exists.&quot;); int index = BinarySearch(key); if (index &lt; 0) { _list.Insert(~index, new KeyValuePair&lt;TKey, TValue&gt;(key, value)); } else { _list.Insert(index, new KeyValuePair&lt;TKey, TValue&gt;(key, value)); } _dict[key] = value; } public int IndexOfKey(TKey key) { if (_dict.ContainsKey(key)) return BinarySearch(key); return -1; } public void RemoveAt(int index) { if (index &lt; 0) return; var item = _list[index]; _list.RemoveAt(index); _dict.Remove(item.Key); } private int BinarySearch(TKey key) { int lo = 0; int hi = _list.Count - 1; while (lo &lt;= hi) { int i = GetMedian(lo, hi); int c = _comparer.Compare(_list[i].Key, key); if (c == 0) return i; if (c &lt; 0) { lo = i + 1; } else { hi = i - 1; } } return ~lo; } private int GetMedian(int lo, int hi) { return lo + ((hi - lo) &gt;&gt; 1); } } </code></pre> <p>The used comparer:</p> <pre class="lang-cs prettyprint-override"><code>public class TestComparer : IComparer&lt;string&gt; { public int Compare(string x, string y) { return string.Compare(x, y); } } </code></pre> <h3>Comparing with <code>Stopwatch</code>:</h3> <pre class="lang-cs prettyprint-override"><code>private static void CompareWithStopwatch() { int index; IEnumerable&lt;int&gt; values; FastSortedList&lt;string, int&gt; fast = new FastSortedList&lt;string, int&gt;(new TestComparer()); Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i &lt; 1000000; i++) { fast.Add($&quot;test{i}&quot;, i); } sw.Stop(); Console.WriteLine($&quot;FastSortedList: Populate records: elapsed time: {sw.Elapsed.TotalSeconds} sec, total records: {fast.Count}&quot;); sw.Start(); index = fast.IndexOfKey(&quot;test745723&quot;); sw.Stop(); Console.WriteLine($&quot;FastSortedList: IndexOfKey: key: 'test745723', index: {index}, elapsed time: {sw.Elapsed.TotalSeconds} sec&quot;); sw.Start(); fast.RemoveAt(index); sw.Stop(); Console.WriteLine($&quot;FastSortedList: RemoveAt: key: 'test745723', index: {index} elapsed time: {sw.Elapsed.TotalSeconds} sec&quot;); sw.Start(); values = fast.Values; sw.Stop(); Console.WriteLine($&quot;FastSortedList: Get values, elapsed time: {sw.Elapsed.TotalSeconds} sec&quot;); SortedList&lt;string, int&gt; sorted = new SortedList&lt;string, int&gt;(new TestComparer()); sw.Start(); for (int i = 0; i &lt; 1000000; i++) { sorted.Add($&quot;test{i}&quot;, i); } sw.Stop(); Console.WriteLine($&quot;SortedList: Populate records: elapsed time: {sw.Elapsed.TotalSeconds} sec, total records: {sorted.Count}&quot;); sw.Start(); index = sorted.IndexOfKey(&quot;test745723&quot;); sw.Stop(); Console.WriteLine($&quot;SortedList: IndexOfKey: key: 'test745723', index: {index}, elapsed time: {sw.Elapsed.TotalSeconds} sec&quot;); sw.Start(); sorted.RemoveAt(index); sw.Stop(); Console.WriteLine($&quot;SortedList: RemoveAt: key: 'test745723', index: {index} elapsed time: {sw.Elapsed.TotalSeconds} sec&quot;); sw.Start(); values = sorted.Values; sw.Stop(); Console.WriteLine($&quot;SortedList: Get values, elapsed time: {sw.Elapsed.TotalSeconds} sec&quot;); FastSortedList&lt;string, int&gt; fastRevrese = new FastSortedList&lt;string, int&gt;(new TestComparer()); sw.Start(); for (int i = 999999; i &gt;= 0; i--) { fastRevrese.Add($&quot;test{i}&quot;, i); } sw.Stop(); Console.WriteLine($&quot;FastSortedList: fastRevrese - Populate records: elapsed time: {sw.Elapsed.TotalSeconds} sec, total records: {fastRevrese.Count}&quot;); sw.Start(); index = fastRevrese.IndexOfKey(&quot;test745723&quot;); sw.Stop(); Console.WriteLine($&quot;FastSortedList: fastRevrese - IndexOfKey: key: 'test745723', index: {index}, elapsed time: {sw.Elapsed.TotalSeconds} sec&quot;); sw.Start(); fastRevrese.RemoveAt(index); sw.Stop(); Console.WriteLine($&quot;FastSortedList: fastRevrese - RemoveAt: key: 'test745723', index: {index} elapsed time: {sw.Elapsed.TotalSeconds} sec&quot;); sw.Start(); values = fastRevrese.Values; sw.Stop(); Console.WriteLine($&quot;SortedList: fastRevrese - Get values, elapsed time: {sw.Elapsed.TotalSeconds} sec&quot;); SortedList&lt;string, int&gt; sortedRevrese = new SortedList&lt;string, int&gt;(new TestComparer()); sw.Start(); for (int i = 999999; i &gt;= 0; i--) { sortedRevrese.Add($&quot;test{i}&quot;, i); } sw.Stop(); Console.WriteLine($&quot;SortedList: sortedRevrese Populate records: elapsed time: {sw.Elapsed.TotalSeconds} sec, total records: {sortedRevrese.Count}&quot;); sw.Start(); index = sortedRevrese.IndexOfKey(&quot;test745723&quot;); sw.Stop(); Console.WriteLine($&quot;SortedList: sortedRevrese - IndexOfKey: key: 'test745723', index: {index}, elapsed time: {sw.Elapsed.TotalSeconds} sec&quot;); sw.Start(); sortedRevrese.RemoveAt(index); sw.Stop(); Console.WriteLine($&quot;SortedList: sortedRevrese - RemoveAt: key: 'test745723', index: {index} elapsed time: {sw.Elapsed.TotalSeconds} sec&quot;); sw.Start(); values = sortedRevrese.Values; sw.Stop(); Console.WriteLine($&quot;SortedList: sortedRevrese - Get values, elapsed time: {sw.Elapsed.TotalSeconds} sec&quot;); } </code></pre> <p>Results: <a href="https://i.stack.imgur.com/0Wvdd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0Wvdd.png" alt="withStopwatch" /></a></p> <h3>Comparing with Benchmark.NET:</h3> <pre class="lang-cs prettyprint-override"><code>public class RaceBenchmark { const int LENGTH = 100000; [Benchmark] public void InsertToSortedList() { SortedList&lt;string, int&gt; sorted = new SortedList&lt;string, int&gt;(new TestComparer()); for (int i = 0; i &lt; LENGTH; i++) { sorted.Add($&quot;test{i}&quot;, i); } } [Benchmark] public void InsertToFastSortedList() { FastSortedList&lt;string, int&gt; fast = new FastSortedList&lt;string, int&gt;(new TestComparer()); for (int i = 0; i &lt; LENGTH; i++) { fast.Add($&quot;test{i}&quot;, i); } } [Benchmark] public void SortedListIndexOfKey() { SortedList&lt;string, int&gt; sorted = new SortedList&lt;string, int&gt;(new TestComparer()); for (int i = 0; i &lt; LENGTH; i++) { sorted.Add($&quot;test{i}&quot;, i); } var sortedListIndex = sorted.IndexOfKey(&quot;test4321&quot;); } [Benchmark] public void FastSortedListIndexOfKey() { FastSortedList&lt;string, int&gt; fast = new FastSortedList&lt;string, int&gt;(new TestComparer()); for (int i = 0; i &lt; LENGTH; i++) { fast.Add($&quot;test{i}&quot;, i); } var fastIndex = fast.IndexOfKey(&quot;test4321&quot;); } [Benchmark] public void SortedListRemoveAt() { SortedList&lt;string, int&gt; sorted = new SortedList&lt;string, int&gt;(new TestComparer()); for (int i = 0; i &lt; LENGTH; i++) { sorted.Add($&quot;test{i}&quot;, i); } var sortedListIndex = sorted.IndexOfKey(&quot;test4321&quot;); sorted.RemoveAt(sortedListIndex); } [Benchmark] public void FastSortedListRemoveAt() { FastSortedList&lt;string, int&gt; fast = new FastSortedList&lt;string, int&gt;(new TestComparer()); for (int i = 0; i &lt; LENGTH; i++) { fast.Add($&quot;test{i}&quot;, i); } var fastIndex = fast.IndexOfKey(&quot;test4321&quot;); fast.RemoveAt(fastIndex); } [Benchmark] public void SortedListGetValues() { SortedList&lt;string, int&gt; sorted = new SortedList&lt;string, int&gt;(new TestComparer()); for (int i = 0; i &lt; LENGTH; i++) { sorted.Add($&quot;test{i}&quot;, i); } var values = sorted.Values; } [Benchmark] public void FastSortedLisGetValues() { FastSortedList&lt;string, int&gt; fast = new FastSortedList&lt;string, int&gt;(new TestComparer()); for (int i = 0; i &lt; LENGTH; i++) { fast.Add($&quot;test{i}&quot;, i); } var values = fast.Values; } } </code></pre> <p>Results:<br /> <a href="https://i.stack.imgur.com/YiJdD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YiJdD.png" alt="withBenchmark.NET" /></a></p> <p>I will be glad for getting a code review for this implementation.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T20:06:28.213", "Id": "494282", "Score": "0", "body": "Unsorted data insertion into SortedList Is an O(n) operation as opposed to that of a similar class called SortedDictionary which has insertion of O(log(n)). Maybe you just want to use that one?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T11:44:55.757", "Id": "494330", "Score": "0", "body": "(@slepic: not far-fetched seeing `_dict = new Dictionary<TKey, TValue>()` & `if (_dict.ContainsKey(key)) throw`.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T11:53:46.770", "Id": "494331", "Score": "0", "body": "I see neither `implements IList<T>` nor `IDictionary<TKey,TValue>`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T12:44:23.067", "Id": "494340", "Score": "1", "body": "Is this homework or are you trying to rediscover the wheel?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T15:29:28.507", "Id": "494369", "Score": "3", "body": "What is your point from doing that? by the way, mixing `List` and `Dictionary` is a bad practice. If you want a sorted `Dictionary` use `SortedDictionary` instead, which would save you the trouble !" } ]
[ { "body": "<p><code>GetMedian</code> -- (Please don't call it &quot;median&quot;; though it is the median of the indexes, it is not the median key.)</p>\n<pre><code>return lo + ((hi - lo) &gt;&gt; 1);\n</code></pre>\n<p>--&gt;</p>\n<pre><code>return (hi + lo) &gt;&gt; 1;\n</code></pre>\n<p>Do you know if your compile will &quot;inline&quot; functions automatically? If it does not, then do the inlining yourself:</p>\n<pre><code>int i = GetMedian(lo, hi);\n</code></pre>\n<p>--&gt;</p>\n<pre><code>int i = (hi + lo) &gt;&gt; 1;\n</code></pre>\n<p>Consider frequency...</p>\n<pre><code> if (c == 0) ...\n if (c &lt; 0) ...\n else ...\n</code></pre>\n<p>If the number of items is low, it is good to test for 0 first; but I don't think that is the 'typical' case. So, rearrange the 2 tests and the else.</p>\n<p>Furthermore, the particular key &quot;test745723&quot; will go down exactly N levels each time. When N is small, your code is &quot;fast&quot;. So, I dispute the results of the benchmark runs that involve just one key.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T20:46:19.187", "Id": "510548", "Score": "0", "body": "Your first suggestion is poor, because you've taken a well-behaved function and broken it when the sum is too large for the range of `int`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T20:55:54.000", "Id": "510552", "Score": "0", "body": "@TobySpeight - OK, add an Assert at the beginning somewhere that aborts if the size of the list is more than half of MAX_INT (or whatever). Executing that _once_ will be a lot more performant than repeatedly performing the extra subtract." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T21:02:33.803", "Id": "510555", "Score": "0", "body": "Abort? Well, I suppose that's one possible choice..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T21:05:28.293", "Id": "510556", "Score": "0", "body": "If INT is 32 bits, fiddling with a list of more than 2^31 items will take a bit of time; that would move the user into a different level of \"performance\" issues. Anyway, what happens if he goes over 2^32? And then there is signed vs unsigned. Etc." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T18:33:38.340", "Id": "258931", "ParentId": "251127", "Score": "-1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T14:25:59.043", "Id": "251127", "Score": "5", "Tags": [ "c#", "performance" ], "Title": "SortedList performance" }
251127
<p>This is the follow-up question for <a href="https://codereview.stackexchange.com/q/251060/231235">A recursive_transform Function For Various Type Nested Iterable With std::variant Implementation in C++</a> and <a href="https://codereview.stackexchange.com/q/251091/231235">A get_from_variant function in C++</a>. Thanks to <a href="https://codereview.stackexchange.com/a/251072/231235">G. Sliepen</a> and <a href="https://codereview.stackexchange.com/a/251098/231235">Quuxplusone</a> provide detailed review suggestions. However, the existed version of <code>recursive_transform</code> function assumes the return type is always the same as the input type. In other words, it works well with the lambda function like <code>[](double x)-&gt;double { return x + 1; }</code> (the type of both input and output are <code>double</code>) or <code>[](int x)-&gt;int { return x + 1; }</code> (the type of both input and output are <code>int</code>). In the next step, I want to focus on the case which the return type is <strong>different from</strong> the input type. For example, <code>[](int x)-&gt;std::string { return std::to_string(x); }</code>. Because the origin return type of <code>recursive_transform</code> is specified in <code>T</code>, it can not handle the case which the type of the processed output from the lambda function <code>f</code> is different from <code>T</code>. Let's change type <code>T</code> into <code>auto</code> as below. This <code>auto</code> syntax used here makes type deriving adaptive.</p> <pre><code>template&lt;class T, class F&gt; auto recursive_transform(const T&amp; input, const F&amp; f) { return f(input); } </code></pre> <p>The another part of this <code>recursive_transform</code> is the recursive structure and it is more complex than above. The container has been specified in <code>std::vector</code> here first.</p> <pre><code>template&lt;class T, class F&gt; requires is_iterable&lt;T&gt; auto recursive_transform(const T&amp; input, const F&amp; f) { typedef typename std::iterator_traits&lt;typename T::iterator&gt;::value_type value_type; std::vector&lt;decltype(recursive_transform(std::declval&lt;value_type&amp;&amp;&gt;(), f))&gt; output(input.size()); std::transform(input.begin(), input.end(), output.begin(), [f](auto&amp; element) { return recursive_transform(element, f); } ); return output; } </code></pre> <p>The test of the above template function <code>recursive_transform</code>.</p> <pre><code>std::vector&lt;int&gt; test_vector = { 1, 2, 3 }; auto recursive_transform_result = recursive_transform( test_vector, [](int x)-&gt;std::string { return std::to_string(x); }); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result.at(0) &lt;&lt; std::endl; // recursive_transform_result.at(0) is a std::string std::vector&lt;decltype(test_vector)&gt; test_vector2 = { test_vector, test_vector, test_vector }; auto recursive_transform_result2 = recursive_transform( test_vector2, [](int x)-&gt;std::string { return std::to_string(x); }); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result2.at(0).at(0) &lt;&lt; std::endl; // recursive_transform_result.at(0).at(0) is also a std::string </code></pre> <p><a href="https://godbolt.org/z/Tn4qfs" rel="noreferrer">A Godbolt link is here.</a></p> <p>All suggestions are welcome.</p> <ul> <li><p>Which question it is a follow-up to?</p> <p><a href="https://codereview.stackexchange.com/q/251060/231235">A recursive_transform Function For Various Type Nested Iterable With std::variant Implementation in C++</a> and</p> <p><a href="https://codereview.stackexchange.com/q/251091/231235">A get_from_variant function in C++</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <p>In the previous version of <code>recursive_transform</code> function, it works well when the return type is as same as the input type. The main idea in this question is trying to implement a extended version which the return type is different from the input type.</p> </li> <li><p>Why a new review is being asked for?</p> <p>The previous version <code>recursive_transform</code> function assumes the return type is always the same as the input type. I am trying to focus on the case which the return type is <strong>different from</strong> the input type to make the function more generic. However, I know that I make my algorithms more specialized in <code>std::vector</code> again in this version of code. I have no idea how to implement a more generic <code>recursive_transform</code> function in both various output type and various container type in a simple and smart way. If there is any suggestion or possible idea about this, please let me know.</p> </li> </ul>
[]
[ { "body": "<p>I'm afraid this is reaching the limits of my knowledge about templates in C++, but I'll try to answer it anyway as best as I can:</p>\n<h1>Use <code>std::back_inserter()</code> to fill the vectors</h1>\n<p>Instead of constructing a vector of a given size, just declare an empty vector, but reserve enough capacity, and then use <a href=\"https://en.cppreference.com/w/cpp/iterator/back_inserter\" rel=\"nofollow noreferrer\"><code>std::back_inserter()</code></a> to fill it:</p>\n<pre><code>std::vector&lt;decltype(recursive_transform(std::declval&lt;value_type&amp;&amp;&gt;(), f))&gt; output;\noutput.reserve(input.size());\n\nstd::transform(input.begin(), input.end(), std::back_inserter(output),\n [f](auto&amp; element)\n {\n return recursive_transform(element, f);\n }\n);\n</code></pre>\n<p>However, if you don't use <code>std::vector</code> but a different container type, <code>reserve()</code> and/or <code>std::back_inserter()</code> might not be appropriate.</p>\n<h1>Determining the container type</h1>\n<p>So ideally, we don't want to declare a <code>std::vector</code>, but rather the outer container of type <code>T</code>. You can use <a href=\"https://en.cppreference.com/w/cpp/language/template_parameters#Template_template_parameter\" rel=\"nofollow noreferrer\">template template parameters</a> to deconstruct templated types:</p>\n<pre><code>template&lt;template&lt;class&gt; class Container, class ValueType, class Function&gt;\nrequires is_iterable&lt;Container&lt;ValueType&gt;&gt;\nauto recursive_transform(const Container&lt;ValueType&gt; &amp;input, const Function &amp;f)\n{\n // You want to be able to write this:\n using TransformedValueType = decltype(recursive_transform(*input.begin(), f));\n Container&lt;TransformedValueType&gt; output;\n ...\n}\n</code></pre>\n<p>Unfortunately, that doesn't work, at least not with Clang, because a <a href=\"https://en.cppreference.com/w/cpp/container/vector\" rel=\"nofollow noreferrer\"><code>std::vector</code></a> actually has two template parameters, and other containers might have more or less template parameters. So the <a href=\"https://stackoverflow.com/questions/55083010/substitution-failure-for-template-template-argument\">solution to that problem</a> is to declare <code>ValueType</code> as a template parameter pack:</p>\n<pre><code>template&lt;template&lt;class...&gt; class Container, class Function, class Ts...&gt;\nrequires is_iterable&lt;Container&lt;Ts...&gt;&gt;\nauto recursive_transform(const Container&lt;Ts...&gt; &amp;input, const Function &amp;f)\n{\n using TransformedValueType = decltype(recursive_transform(*input.begin(), f));\n Container&lt;TransformedValueType&gt; output;\n ...\n}\n</code></pre>\n<p>Although of course this doesn't forward the second template parameter. Putting everything so far together:</p>\n<pre><code>template&lt;typename T&gt;\nconcept is_iterable = requires(T x)\n{\n *std::begin(x);\n std::end(x);\n};\n\ntemplate&lt;class T, class Function&gt;\nauto recursive_transform(const T &amp;input, const Function &amp;f)\n{\n return f(input);\n}\n\ntemplate&lt;template&lt;class...&gt; class Container, class Function, class... Ts&gt;\nrequires is_iterable&lt;Container&lt;Ts...&gt;&gt;\nauto recursive_transform(const Container&lt;Ts...&gt; &amp;input, const Function &amp;f)\n{\n using TransformedValueType = decltype(recursive_transform(*input.begin(), f));\n Container&lt;TransformedValueType&gt; output;\n\n std::transform(std::begin(input), std::end(input), std::back_inserter(output),\n [&amp;](auto &amp;element)\n {\n return recursive_transform(element, f);\n }\n );\n\n return output;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T19:58:24.413", "Id": "494399", "Score": "1", "body": "It turns out that you can just have a generic overload that handles single variables, and a specialization that handles anything that matches `is_iterable`. I had a stray `typename` in a template parameter that caused some compiler errors with very unhelpful error messages. I updated the answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T16:24:18.850", "Id": "251138", "ParentId": "251132", "Score": "2" } } ]
{ "AcceptedAnswerId": "251138", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T15:00:08.000", "Id": "251132", "Score": "4", "Tags": [ "c++", "recursion", "c++20" ], "Title": "A recursive_transform for std::vector with various return type" }
251132
<p>I'm a beginner in Django3 and just wrote an overview function to pass on some data to the template in a context variable.</p> <p>I am definitely passing a lot more than I should as I only need only a few fields from each of these variables. Also, it might not be the most Django-esque way of doing things as it isn't using GenericViews or any of the more advanced Django features.</p> <p>please review, comment, and provide suggestions or modifications:</p> <pre><code>def overview_page(request): user = request.user org = Organization.objects.filter(user=user) projects = Project.objects.filter(organization=org[0]) # get first is_active project, as this is only allowed once per # Organization. The model will need to be fixed post MVP for better # design active_project = Project.objects.filter(organization=org[0], is_active=True)[0] assets = Asset.objects.filter(project=active_project) functional_classes = FuncClass.objects.filter(project=active_project) conditions = Condition.objects.filter(project=active_project) det_curves = DetCurve.objects.filter(project=active_project) func_classes = FuncClass.objects.filter(project=active_project) model_settings = ModelSettings.objects.filter(project=active_project) scenarios = Scenario.objects.filter(project=active_project) surface_types = SurfaceType.objects.filter(project=active_project) treatments = Treatment.objects.filter(project=active_project) context = {'user': user, 'my_org': org[0], 'func_class': functional_classes, 'projects': projects, 'active_project': active_project, 'assets': assets, 'conditions': conditions, 'det_curves': det_curves, 'func_classes': func_classes, 'model_settings': model_settings, 'scenarios': scenarios, 'surface_types': surface_types, 'treatments': treatments, } return render(request, 'asset_manager/overview.html', context) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T15:22:17.947", "Id": "251134", "Score": "1", "Tags": [ "python-3.x", "django" ], "Title": "Django: View method that outputs large context data into an html dashboard template" }
251134
<p>The purpose of this project is to generate an interactive <a href="https://en.wikipedia.org/wiki/Logistic_map" rel="nofollow noreferrer">logistic map</a>. The user can click on the produced picture to magnify the picture at that point.</p> <p>Here is the logistic map equation:</p> <p><a href="https://i.stack.imgur.com/VTtk5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VTtk5.png" alt="enter image description here" /></a></p> <p>Here is my program:</p> <pre><code>public class LogisticMap { public static double returnLogisticEquation(double x, double r) { return r * x * (1 - x); } public static double ignoreFirstIterations(int numberOfIterations, double x, double r) { for (int i = 0; i &lt; numberOfIterations; i++) { x = returnLogisticEquation(x, r); } return x; } public static void drawLogisticMap(int numberOfHorizontalPoints, int numberOfVerticalPoints, double leftOfRInterval, double rightOfRInterval, double x) { StdDraw.setYscale(0, 1); StdDraw.enableDoubleBuffering(); double subintervalLength = (rightOfRInterval - leftOfRInterval) / numberOfHorizontalPoints; int numberOfIterations = 1000; for (double r = leftOfRInterval; r &lt; rightOfRInterval; r += subintervalLength) { x = ignoreFirstIterations(numberOfIterations, x, r); for (int p = 0; p &lt; numberOfVerticalPoints; p++) { x = returnLogisticEquation(x, r); StdDraw.point(r, x); } } StdDraw.show(); } public static void interactiveLogisticMap(int numberOfHorizontalPoints, int numberOfVerticalPoints, double leftOfRInterval, double rightOfRInterval, double x) { StdDraw.setXscale(leftOfRInterval, rightOfRInterval); drawLogisticMap(numberOfHorizontalPoints, numberOfVerticalPoints, leftOfRInterval, rightOfRInterval, x); double r = 0; double y = 0; double scale = 0.05; while (true) { if (StdDraw.isMousePressed()) { r = StdDraw.mouseX(); y = StdDraw.mouseY(); double newLeftOfRInterval = r - scale; double newRightOfRInterval = r + scale; double belowRInterval = y - scale; double aboveRInterval = y + scale; StdDraw.setXscale(newLeftOfRInterval, newRightOfRInterval); StdDraw.setYscale(belowRInterval, aboveRInterval); StdDraw.clear(); drawLogisticMap(numberOfHorizontalPoints, numberOfVerticalPoints, newLeftOfRInterval, newRightOfRInterval, x); scale /= 10; } } } public static void main(String[] args) { StdDraw.setCanvasSize(850, 850); int numberOfHorizontalPoints = 800; int numberOfVerticalPoints = 1000; double leftOfRInterval = 2.4; double rightOfRInterval = 4; double x = Math.random(); interactiveLogisticMap(numberOfHorizontalPoints, numberOfVerticalPoints, leftOfRInterval, rightOfRInterval, x); } } </code></pre> <p><a href="https://introcs.cs.princeton.edu/java/stdlib/javadoc/StdDraw.html" rel="nofollow noreferrer">StdDraw</a> is a simple API written by the authors of the book <em>Computer Science An Interdisciplinary Approach</em>. I checked my program and it works. Here is one instance of it.</p> <p>Output (actually a succession of outputs):</p> <p><a href="https://i.stack.imgur.com/ljTSC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ljTSC.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/BbwaR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BbwaR.png" alt="enter image description here" /></a></p> <p>Is there any way that I can improve my program?</p> <p>Thanks for your attention.</p>
[]
[ { "body": "<pre class=\"lang-java prettyprint-override\"><code>public static double returnLogisticEquation(double x, double r) {\n</code></pre>\n<p>The name is not quite correct, as it does return the result of equation, not the equation itself, so more like <code>calculateLogisticEquation</code>.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> public static double returnLogisticEquation(double x, double r) {\n return r * x * (1 - x);\n }\n</code></pre>\n<p>I'm torn on this one. Normally, I say that you are only allowed to use single-letter variables when dealing with dimensions (yes, that disallows &quot;i&quot;, &quot;j&quot;, &quot;k&quot; too). However, when implementing mathematical functions there <em>might</em> be a reason to use them. However, using the long names might still be an improvement:</p>\n<pre class=\"lang-java prettyprint-override\"><code> public static double returnLogisticEquation(double populationRatio, double reproductionate) {\n return reproductionRate * populationRatio * (1 - populationRatio);\n }\n</code></pre>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>for (int i = 0; i &lt; numberOfIterations; i++) {\n</code></pre>\n<p>That's what I meant:</p>\n<pre class=\"lang-java prettyprint-override\"><code>for (int counter = 0; counter &lt; numberOfIterations; counter++) {\n</code></pre>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>public static double ignoreFirstIterations(int numberOfIterations, double x, double r) {\n</code></pre>\n<p>I'm not sure about the name here, maybe <code>forward(int numberOfIterations, ...)</code> would be a better name, as normally, I'd not assume a function that ignores something to return something.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> public static double ignoreFirstIterations(int numberOfIterations, double x, double r) {\n for (int i = 0; i &lt; numberOfIterations; i++) {\n x = returnLogisticEquation(x, r);\n }\n return x;\n }\n</code></pre>\n<p>Assigning to a parameter is bad style. Even though you <em>can</em> treat it as just another declaration, it might lead to confusion down the line. For example if you have an object as parameter and the following line:</p>\n<pre class=\"lang-java prettyprint-override\"><code>thisIsAParameter.setValue(&quot;value&quot;);\n</code></pre>\n<p>If you have the habit of assigning parameters, you now need to check whether there was a different object assigned to the parameter before that function call. Ideally, parameters would be <code>final</code>, but that is quite noisy, though. Threat them as <code>final</code>.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>int numberOfIterations = 1000;\n</code></pre>\n<p>It's not the number of iterations, it's the number of <em>ignored</em> iterations.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>r += subintervalLength\n</code></pre>\n<p>For the record: <code>+=</code> and other shorthand operators are not short for <code>a = a + b</code>, but for <code>a = (TYPE_A)(a+b)</code>, which might yield unexpected results. For example, <code>intA = intA + 5.5d</code> will yield an error that a <code>double</code> is truncated to an <code>int</code>. <code>intA += 5.5d</code> will yield no such error.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> public static void drawLogisticMap(int numberOfHorizontalPoints, int numberOfVerticalPoints, double leftOfRInterval, double rightOfRInterval, double x) {\n StdDraw.setYscale(0, 1);\n StdDraw.enableDoubleBuffering();\n double subintervalLength = (rightOfRInterval - leftOfRInterval) / numberOfHorizontalPoints;\n int numberOfIterations = 1000;\n for (double r = leftOfRInterval; r &lt; rightOfRInterval; r += subintervalLength) {\n x = ignoreFirstIterations(numberOfIterations, x, r);\n for (int p = 0; p &lt; numberOfVerticalPoints; p++) {\n x = returnLogisticEquation(x, r);\n StdDraw.point(r, x);\n }\n }\n StdDraw.show();\n }\n</code></pre>\n<p>A few more empty lines to group logic would be nice (like you've done in other functions).</p>\n<pre class=\"lang-java prettyprint-override\"><code> public static void drawLogisticMap(int numberOfHorizontalPoints, int numberOfVerticalPoints, double leftOfRInterval, double rightOfRInterval, double x) {\n StdDraw.setYscale(0, 1);\n StdDraw.enableDoubleBuffering();\n \n double subintervalLength = (rightOfRInterval - leftOfRInterval) / numberOfHorizontalPoints;\n int numberOfIterations = 1000;\n \n for (double r = leftOfRInterval; r &lt; rightOfRInterval; r += subintervalLength) {\n x = ignoreFirstIterations(numberOfIterations, x, r);\n \n for (int p = 0; p &lt; numberOfVerticalPoints; p++) {\n x = returnLogisticEquation(x, r);\n \n StdDraw.point(r, x);\n }\n }\n \n StdDraw.show();\n }\n</code></pre>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>while (true) {\n</code></pre>\n<p>If you can include a dynamic break condition, do so (like listening for ESC).</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> double r = 0;\n double y = 0;\n</code></pre>\n<p>Declare variables where they are used, to limit the scope in which they exist to limit possible errors.</p>\n<pre class=\"lang-java prettyprint-override\"><code> double r = StdDraw.mouseX();\n double y = StdDraw.mouseY();\n</code></pre>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>double scale = 0.05;\n</code></pre>\n<p>Seems more like this should either be a parameter, or a class-level constant.</p>\n<hr />\n<p>I haven't tested your code or verified the mathematical correctness, but looks good so far.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T19:58:19.420", "Id": "251145", "ParentId": "251135", "Score": "4" } } ]
{ "AcceptedAnswerId": "251145", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T15:39:45.147", "Id": "251135", "Score": "3", "Tags": [ "java", "performance", "beginner" ], "Title": "Interactive logistic map" }
251135
<p>I was trying to figure out <a href="http://www.usaco.org/index.php?page=viewproblem2&amp;cpid=963" rel="nofollow noreferrer">this</a> problem, and I did. However, my code is so abhorrently ugly that I want to tear out my eyeballs when I look at it:</p> <pre><code>with open(&quot;gymnastics.in&quot;, &quot;r&quot;) as fin: rounds, cows = [int(i) for i in fin.readline().split()] nums = [tuple(map(int, line.split())) for line in fin] def populatePairs(cows): pairs = [] for i in range(cows): for j in range(cows): if i != j: pairs.append((i+1,j+1)) return pairs def consistentPairs(pairs, nums): results = [] for i in pairs: asdf = True for num in nums: for j in num: if j == i[1]: asdf = False break if j == i[0]: break if not asdf: break if asdf: results.append(i) return results pairs = populatePairs(cows) with open(&quot;gymnastics.out&quot;, &quot;w+&quot;) as fout: print(len(consistentPairs(pairs, nums)), file=fout) </code></pre> <p>I feel like that there should definitely be a better solution that is faster than <span class="math-container">\$O(n^3)\$</span>, and without the triple nested for-loop with the if-statements trailing behind them, but I cannot, for the love of god, think of a better solution.</p> <p><strong>Problem synopsis:</strong></p> <p>Given an <span class="math-container">\$n\$</span> by <span class="math-container">\$m\$</span> grid of points, find the number of pairs in which number is consistently placed before the other.</p> <p><strong>Example:</strong></p> <p>Input:</p> <pre><code>3 4 4 1 2 3 4 1 3 2 4 2 1 3 </code></pre> <p>Output: 4</p> <p>Explanation: The consistent pairs of cows are (1,4), (2,4), (3,4), and (3,1), in which case 4 is consistently greater than all of them, and 1 is always greater than 3.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T17:12:28.527", "Id": "494272", "Score": "0", "body": "Do you have test cases with this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T22:28:48.367", "Id": "494288", "Score": "0", "body": "@Mast yes. i'm going to edit the question with the test case included" } ]
[ { "body": "<p>Suggestions:</p>\n<ul>\n<li>Use the variable names from the problem specification instead of inventing your own (just make them lower-case since that's preferred in Python code). Makes it easier to see the connections. Unless yours are much better.</li>\n<li>I guess <code>nums</code> is plural so <code>num</code> is a single number, but you can iterate it? Bad name. And wth does <code>asdf</code> mean?</li>\n<li>Python prefers <code>snake_case</code> for function names.</li>\n<li>To be honest, the lack of any explanation of your method, the name <code>asdf</code> and the highly convoluted code made me give up reading it. But here's my solution, simply counting occurring pairs and then the result is the number of pairs that appeared K times:</li>\n</ul>\n<pre><code>from itertools import combinations\nfrom collections import Counter\n\nctr = Counter()\nwith open('gymnastics.in') as f:\n k, _ = map(int, next(f).split())\n for session in f:\n cows = session.split()\n ctr.update(combinations(cows, 2))\n\nwith open('gymnastics.out', 'w') as f:\n print(list(ctr.values()).count(k), file=f)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T00:10:04.173", "Id": "494291", "Score": "0", "body": "respect for the brutal honesty; i was incredibly tired when i was writing the code so i didnt put even an iota of thought into writing the variable/function names." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T00:15:06.983", "Id": "494292", "Score": "1", "body": "WAIT UR SOLUTION IS SO SMART WTF. jesus christ, mr. superb rain, you are incredibly cool" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T23:41:44.837", "Id": "251150", "ParentId": "251136", "Score": "2" } } ]
{ "AcceptedAnswerId": "251150", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T15:41:52.217", "Id": "251136", "Score": "1", "Tags": [ "python", "complexity" ], "Title": "Most efficient solution for USACO: Cow Gymnastics - Python" }
251136
<p>I wrote a script that parses API on schedule (Tuesday-Saturday), downloading everything for the previous day.</p> <hr /> <pre class="lang-py prettyprint-override"><code>import requests import pandas as pd from datetime import date, timedelta # # This is what I'd normally use, but since there would be no data today, # # I assign specific date myself # DATE = (date.today() - timedelta(days=1)).strftime(&quot;%Y-%m-%d&quot;) DATE = &quot;2020-10-23&quot; URL = &quot;https://spending.gov.ua/portal-api/v2/api/transactions/page/&quot; def fetch(session, params): next_page, last_page = 0, 0 while next_page &lt;= last_page: params[&quot;page&quot;] = next_page data = session.get(URL, params=params).json() yield pd.json_normalize(data.get(&quot;transactions&quot;))\ .assign(page=params.get(&quot;page&quot;)) next_page, last_page = next_page+1, data[&quot;count&quot;] // data[&quot;pageSize&quot;] def fetch_all(): with requests.Session() as session: params = {&quot;page&quot;: 0, &quot;pageSize&quot;: 100, &quot;startdate&quot;: DATE, &quot;enddate&quot;: DATE} yield from fetch(session, params) if __name__ == &quot;__main__&quot;: data = fetch_all() pd.concat(data).to_csv(f&quot;data/{DATE}.csv&quot;, index=False) </code></pre> <hr /> <p>Here I’m wondering about a couple of things.</p> <p><em>Firstly</em>, if I’m using <code>requests.Session</code> correctly.</p> <p>I read in the documentation that:</p> <blockquote> <p>The Session object allows you to persist certain parameters across requests. ... So if you’re making several requests to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase.</p> </blockquote> <p>I'm not sure whether that's the case here as I didn't notice any changes in the performance.</p> <p><em>Secondly</em>, if splitting code into two functions instead of one was a good idea.</p> <p>Here I thought that it would be easier to maintain -- the underlying function <code>fetch</code> doesn't change while <code>fetch_all</code> potentially could. For example, I could feed a range of dates instead of a singe date, changing <code>fetch_all</code> to:</p> <pre class="lang-py prettyprint-override"><code>def fetch_all(date_range): with requests.Session() as session: for date in date_range: params = {&quot;page&quot;: 0, &quot;pageSize&quot;: 100, &quot;startdate&quot;: date, &quot;enddate&quot;: date} yield from fetch(session, params) </code></pre> <p>Also, the <code>yield</code> and <code>yield from</code> -- could've used <code>.append</code> and returned a list instead. Not sure which approach is better.</p>
[]
[ { "body": "<blockquote>\n<p>Here I’m wondering about a couple of things.</p>\n<p><em>Firstly</em>, if I’m using <code>requests.Session</code> correctly.</p>\n</blockquote>\n<p>Yes, you are. In <a href=\"https://codereview.stackexchange.com/a/236925\">one of my other reviews</a>, using <code>requests.Session</code> in the same way for iterating over a paginated API almost halved the total execution time.</p>\n<p>I did some quick testing by downloading the last 7 pages (pages 1625-1631) for &quot;2020-10-23&quot; and it did marginally better than making requests with <code>requests.get</code>:</p>\n<ul>\n<li><code>requests.get</code>: 23.2 seconds</li>\n<li><code>requests.Session</code>: 17.7 seconds</li>\n</ul>\n<blockquote>\n<p><em>Secondly</em>, if splitting code into two functions instead of one was a good idea.</p>\n</blockquote>\n<p>I think it's fine to have it split into two functions. That said, I do have some comments about the responsibilities and interface of <code>fetch</code> and how to better take advantage of your usages of <code>yield</code> and <code>yield from</code> down below.</p>\n<hr />\n<p>Overall the code looks clean and is easy to read. Here's how I think it can be improved:</p>\n<ul>\n<li><p>I think all the low-level details of how to issue requests to the API should be abstracted away from the caller of <code>fetch</code>. That is, <code>fetch</code>'s function signature should look something like this:</p>\n<pre class=\"lang-python prettyprint-override\"><code>def fetch(\n session: requests.Session,\n start_date: date,\n end_date: date,\n starting_page: int = 0,\n page_size: int = 100,\n) -&gt; Iterator[pd.DataFrame]:\n pass\n</code></pre>\n<p>So now creating an appropriate <code>params</code> would be <code>fetch</code>'s responsibility, not <code>fetch_all</code>'s. Notice also that <code>start_date</code> and <code>end_date</code> are of type <code>datetime.date</code>, not <code>str</code>. Similarly, <code>fetch_all</code> should not have to be concerned with what date string serialization format the API accepts; this is <code>fetch</code>'s responsibility.</p>\n</li>\n<li><p>Within <code>fetch</code>, instead of maintaining variables <code>next_page</code> and <code>last_page</code> on each request, I think it would be better to calculate the total number of pages (n) only once with the first request (page k), then use a for loop for pages k+1..n-1:</p>\n<pre class=\"lang-python prettyprint-override\"><code>def to_dataframe(json_data: Dict[str, Any], page: int) -&gt; pd.DataFrame:\n return pd.json_normalize(json_data[&quot;transactions&quot;]).assign(page=page)\n\n\ndef fetch(\n session: requests.Session,\n start_date: date,\n end_date: date,\n starting_page: int = 0,\n page_size: int = 100,\n) -&gt; Iterator[pd.DataFrame]:\n params = {\n &quot;startdate&quot;: start_date.isoformat(),\n &quot;enddate&quot;: end_date.isoformat(),\n &quot;page&quot;: starting_page,\n &quot;pageSize&quot;: page_size,\n }\n\n data = session.get(URL, params=params).json()\n page_count = math.ceil(data[&quot;count&quot;] / data[&quot;pageSize&quot;])\n last_page = page_count - 1\n if starting_page &gt; last_page:\n return\n print(f&quot;{starting_page} / {last_page}&quot;)\n yield to_dataframe(data, starting_page)\n\n for page in range(starting_page + 1, page_count):\n params[&quot;page&quot;] = page\n data = session.get(URL, params=params).json()\n print(f&quot;{page} / {last_page}&quot;)\n yield to_dataframe(data, page)\n</code></pre>\n<p>The tradeoff here is that there's a small duplication of code because the first request is handled a little differently, but now we've delegated responsibility of page number iteration to the for loop.</p>\n</li>\n<li><p>I recommend adding an <a href=\"https://requests.readthedocs.io/en/latest/user/advanced/#event-hooks\" rel=\"nofollow noreferrer\">event hook</a> to the <code>session</code> object so that it always calls <code>raise_for_status()</code> on the response object. This ensures that all requests made with the session raise <code>requests.HTTPError</code> if the server gives us a 4xx or 5xx response, and prevents us from converting an error response's <code>.json()</code> data into a dataframe:</p>\n<pre class=\"lang-python prettyprint-override\"><code>session.hooks[&quot;response&quot;].append(\n lambda r, *args, **kwargs: r.raise_for_status()\n)\n</code></pre>\n</li>\n<li><p>Currently the program is combining all dataframes in memory before exporting it to a CSV file. To take advantage of <code>fetch_all</code> being an <code>Iterator[pd.DataFrame]</code>, I think it would be better to write each dataframe to the CSV immediately, so we don't need to hold it in memory any longer than necessary:</p>\n<pre class=\"lang-python prettyprint-override\"><code>output_path = Path(f&quot;data/{DATE}.csv&quot;)\noutput_path.unlink(missing_ok=True)\ndata = fetch_all()\nfor i, dataframe in enumerate(data):\n write_header = True if i == 0 else False\n dataframe.to_csv(\n output_path, header=write_header, index=False, mode=&quot;a&quot;\n )\n</code></pre>\n</li>\n</ul>\n<hr />\n<p>Refactored version:</p>\n<pre class=\"lang-python prettyprint-override\"><code>#!/usr/bin/env python3\n\nimport math\nfrom datetime import date, timedelta\nfrom pathlib import Path\nfrom typing import Any, Dict, Iterator\n\nimport pandas as pd # type: ignore\nimport requests\n\n# # This is what I'd normally use, but since there would be no data today,\n# # I assign specific date myself\n# DATE = date.today() - timedelta(days=1)\nDATE = date.fromisoformat(&quot;2020-10-23&quot;)\nURL = &quot;https://spending.gov.ua/portal-api/v2/api/transactions/page/&quot;\n\n\ndef to_dataframe(json_data: Dict[str, Any], page: int) -&gt; pd.DataFrame:\n return pd.json_normalize(json_data[&quot;transactions&quot;]).assign(page=page)\n\n\ndef fetch(\n session: requests.Session,\n start_date: date,\n end_date: date,\n starting_page: int = 0,\n page_size: int = 100,\n) -&gt; Iterator[pd.DataFrame]:\n params = {\n &quot;startdate&quot;: start_date.isoformat(),\n &quot;enddate&quot;: end_date.isoformat(),\n &quot;page&quot;: starting_page,\n &quot;pageSize&quot;: page_size,\n }\n\n data = session.get(URL, params=params).json()\n page_count = math.ceil(data[&quot;count&quot;] / data[&quot;pageSize&quot;])\n last_page = page_count - 1\n if starting_page &gt; last_page:\n return\n print(f&quot;{starting_page} / {last_page}&quot;)\n yield to_dataframe(data, starting_page)\n\n for page in range(starting_page + 1, page_count):\n params[&quot;page&quot;] = page\n data = session.get(URL, params=params).json()\n print(f&quot;{page} / {last_page}&quot;)\n yield to_dataframe(data, page)\n\n\ndef fetch_all() -&gt; Iterator[pd.DataFrame]:\n with requests.Session() as session:\n session.hooks[&quot;response&quot;].append(\n lambda r, *args, **kwargs: r.raise_for_status()\n )\n yield from fetch(session, start_date=DATE, end_date=DATE)\n\n\nif __name__ == &quot;__main__&quot;:\n output_path = Path(f&quot;data/{DATE}.csv&quot;)\n output_path.unlink(missing_ok=True)\n data = fetch_all()\n for i, dataframe in enumerate(data):\n write_header = True if i == 0 else False\n dataframe.to_csv(\n output_path, header=write_header, index=False, mode=&quot;a&quot;\n )\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T06:18:03.797", "Id": "494422", "Score": "0", "body": "Thank you for such a detailed answer. I learnt a lot!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T09:02:59.393", "Id": "494429", "Score": "1", "body": "Though I intentionally used while loop to avoid code duplication in fetch function. But I agree that your approach is more explicit, so I’ll use it instead. Thanks once again." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T01:45:55.263", "Id": "251187", "ParentId": "251140", "Score": "2" } } ]
{ "AcceptedAnswerId": "251187", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T17:06:36.353", "Id": "251140", "Score": "3", "Tags": [ "python", "web-scraping" ], "Title": "Fetching API with requests.Session" }
251140
<p>This is a problem from CodeSignal which can be founded over <a href="https://app.codesignal.com/arcade/intro/level-11/pwRLrkrNpnsbgMndb" rel="noreferrer">here</a></p> <p>Here is an image on what we have to do:</p> <p><a href="https://i.stack.imgur.com/Bd7uw.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Bd7uw.png" alt="enter image description here" /></a></p> <h2>Code</h2> <pre class="lang-py prettyprint-override"><code>def map(cell): new_cell1 = '' for i in cell: if i == 'a': new_cell1 += '1' if i == 'b': new_cell1 += '2' if i == 'c': new_cell1 += '3' if i == 'd': new_cell1 += '4' if i == 'e': new_cell1 += '5' if i == 'f': new_cell1 += '6' if i == 'g': new_cell1 += '7' if i == 'h': new_cell1 += '8' new_cell1 += cell[-1] return new_cell1 def chessKnight(cell): cell = map(cell) num_of_moves = 0 if (int(cell[0])+1 &lt;= 8 and int(cell[0])+1 &gt; 0) and (int(cell[1])+2 &lt;= 8 and int(cell[1])+2 &gt; 0): num_of_moves += 1 if (int(cell[0])-1 &lt;= 8 and int(cell[0])-1 &gt; 0) and (int(cell[1])+2 &lt;= 8 and int(cell[1])+2 &gt; 0): num_of_moves += 1 if (int(cell[0])+1 &lt;= 8 and int(cell[0])+1 &gt; 0) and (int(cell[1])-2 &lt;= 8 and int(cell[1])-2 &gt; 0): num_of_moves += 1 if (int(cell[0])-1 &lt;= 8 and int(cell[0])-1 &gt; 0) and (int(cell[1])-2 &lt;= 8 and int(cell[1])-2 &gt; 0): num_of_moves += 1 if (int(cell[0])+2 &lt;= 8 and int(cell[0])+2 &gt; 0) and (int(cell[1])+1 &lt;= 8 and int(cell[1])+1 &gt; 0): num_of_moves += 1 if (int(cell[0])-2 &lt;= 8 and int(cell[0])-2 &gt; 0) and (int(cell[1])+1 &lt;= 8 and int(cell[1])+1 &gt; 0): num_of_moves += 1 if (int(cell[0])+2 &lt;= 8 and int(cell[0])+2 &gt; 0) and (int(cell[1])-1 &lt;= 8 and int(cell[1])-1 &gt; 0): num_of_moves += 1 if (int(cell[0])-2 &lt;= 8 and int(cell[0])-2 &gt; 0) and (int(cell[1])-1 &lt;= 8 and int(cell[1])-1 &gt; 0): num_of_moves += 1 return num_of_moves </code></pre> <h2>Question</h2> <p>The Code works as expected and returns the right answer, but I have just put a bunch of <code>if</code> conditions which doesn't look nice to me. Is there any way to implement the problem but without so much <code>if</code> blocks?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T19:10:47.410", "Id": "494280", "Score": "0", "body": "Please note that when you link a question from code signal, the question is locked for all of those who haven't solved the first problems, due to which the higher-level questions are locked" } ]
[ { "body": "<h1>Never use existing function names for new functions</h1>\n<p>Python already has a function called <code>map()</code> <br>Defining your new <code>map()</code> function can cause a lot of confusion, and undefined behaviour in your program.</p>\n<h1>By cheating</h1>\n<p>Since you have asked for an alternate solution, here it is</p>\n<p>Being a chess engine developer, I would never calculate something trivial like the number of knight attacks since a simple array of size <code>64</code> with the pre-calculated ones can easily work. All you need is a simple function that converts a square like <code>a1</code> to 0 and <code>h8</code> to 63.</p>\n<p>Here is the implementation,</p>\n<pre class=\"lang-py prettyprint-override\"><code>def str_sq_to_int(sq):\n return (ord(sq[0])-97) + ((ord(sq[1])-49) * 8);\n\ndef knightAttacks(cell):\n attacks = [\n 2, 3, 4, 4, 4, 4, 3, 2,\n 3, 4, 6, 6, 6, 6, 4, 3,\n 4, 6, 8, 8, 8, 8, 6, 4,\n 4, 6, 8, 8, 8, 8, 6, 4,\n 4, 6, 8, 8, 8, 8, 6, 4,\n 4, 6, 8, 8, 8, 8, 6, 4,\n 3, 4, 6, 6, 6, 6, 4, 3,\n 2, 3, 4, 4, 4, 4, 3, 2\n ]\n return attacks[str_sq_int(cell)]\n</code></pre>\n<p>The explanation is simple, the function <code>str_sq_to_int()</code> takes a square like <code>'a1'</code> and returns an index using the <a href=\"http://www.asciitable.com/\" rel=\"nofollow noreferrer\">ASCII value of the character</a> to calculate the index. You can also use a simple dictionary to map each square to an index, but this one is easy</p>\n<p>Then, it uses a pre-calculated set of values, to return the correct answer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T20:32:57.020", "Id": "494284", "Score": "2", "body": "Lol. This answer is very cool," }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T20:49:54.620", "Id": "494285", "Score": "1", "body": "@fartgeek yeah , I kind of copy pasted the str_to_int function from my chess engine though xD. I would recommend bit manipulation but since it's python, doesn't make sense" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T09:20:50.307", "Id": "494315", "Score": "0", "body": "To improve this answer, I would suggest making `str_sq_to_int`, `ord` and `sq` more explicit and making the casing consistent. Also the magic numbers (97, 49, 8) could use some names." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T11:12:31.647", "Id": "494324", "Score": "0", "body": "@RaimundKrämer Is that why you downvoted? It is good advice, I will remove the magic numbers but I'm not sure what name I could get for them since they are based on the ascii values" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T11:18:12.513", "Id": "494327", "Score": "0", "body": "@RaimundKrämer I'm a little unsure as to what you expect more in this answer, may i suggest you edit it yourself? I would like to see what I missed that deserved a downvote" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T19:27:51.427", "Id": "251144", "ParentId": "251141", "Score": "4" } }, { "body": "<p>Alright. This is an interesting question. If you think about it, the moves of a knight have a few conditions (excluding checks and whether a friendly piece is on the destination square):</p>\n<ul>\n<li><p>The move has to be on the board (this is one is obvious)</p>\n</li>\n<li><p>The absolute value of the distance moved to the side subtracted from the absolute value of the distanced moved up must either equal one or -1.</p>\n</li>\n<li><p>The absolute value of the distance moved to the side must be one or two.</p>\n</li>\n<li><p>The absolute value of the distance moved up or down must be either one or two.</p>\n</li>\n</ul>\n<p>The code is as follows :</p>\n<pre><code>def knight_move_counter(position_on_board):\n possibleMoves = 0\n # here we could use ASCII values to convert the letters to numbers, but a dict is easier to visualize\n letterToNumbers = {\n &quot;a&quot; : 0,\n &quot;b&quot; : 1,\n &quot;c&quot; : 2,\n &quot;d&quot; : 3,\n &quot;e&quot; : 4,\n &quot;f&quot; : 5,\n &quot;g&quot; : 6,\n &quot;h&quot; : 7\n }\n start_letter = letterToNumbers[position_on_board[0]]\n start_number = int(position_on_board[1]) - 1 # note that this line and the preceding one will only work if they are valid algebraic notation.\n for iterator in range(8):\n for second_iterator in range(8): # these two for loops assure our answers will be on the board.\n if abs( abs(start_letter - iterator) - abs(start_number - second_iterator)) == 1: # point #2\n if abs(start_letter - iterator) == 1 or abs(start_letter - iterator) == 2: # point #3\n if abs(start_number - second_iterator) == 1 or abs(start_number - second_iterator) == 2: # point #4\n possibleMoves += 1\n return possibleMoves\n\n\nprint(knight_move_counter(&quot;a1&quot;)) # you can replace the &quot;a1&quot; with whatever you would like, as long as it is valid algebraic notation.\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T05:44:05.107", "Id": "494296", "Score": "0", "body": "[this](https://www.chessprogramming.org/Knight_Pattern) article on knight patterns is really cool" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T21:18:22.303", "Id": "251146", "ParentId": "251141", "Score": "0" } } ]
{ "AcceptedAnswerId": "251144", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T17:15:17.557", "Id": "251141", "Score": "5", "Tags": [ "python", "python-3.x", "programming-challenge", "chess" ], "Title": "Finding the number of moves a knight can perform while standing on a given square" }
251141
<p>This is my first C program that is not &quot;Hello World&quot; level; I would welcome ideas to make it more efficient and readable.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;math.h&gt; #include &lt;time.h&gt; #include &lt;stdbool.h&gt; #define FALSE 0 #define TRUE 1 bool incircle(double x, double y); int main (int argc, char *argv[]) { unsigned long long loops, cpoints, i; double approx, cpu_time_used; int seed; clock_t start, end; cpoints = 0; loops = atoll(argv[1]); seed = time(NULL); srand(seed); start = clock(); for (i = 0; i &lt; loops; ++i) { double x = (rand() + 1.0) / (RAND_MAX+2.0); double y = (rand() + 1.0) / (RAND_MAX+2.0); if ( incircle(x,y) !=FALSE ) cpoints+=1; } end = clock(); cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC; approx=4*(cpoints/(double)i); printf (&quot;%llu&quot; &quot;%s&quot; &quot;%llu&quot; &quot;%s&quot; &quot;%0.9f&quot; &quot;%s&quot; &quot;%0.3f\n&quot;, i, &quot; &quot;, cpoints, &quot; &quot;, approx, &quot; &quot;, cpu_time_used); return 0; } bool incircle(double x, double y) { return ( x * x + y * y &lt;= 1 ); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T13:17:51.353", "Id": "494343", "Score": "1", "body": "or, just `print(\"355/113\")` :-) . But, of serious interest, might be fun to , , compare this algorithm with the \"Drop sticks onto a grid\" method, aka Buffon's Needle https://en.wikipedia.org/wiki/Buffon%27s_needle_problem" } ]
[ { "body": "<h2>General Observations</h2>\n<p>There is a real lack of communications with the user of the program. There is no error checking performed on the possible input. While the code really doesn't do that much it is too complex and very hard to maintain.</p>\n<h2>Communications With the User</h2>\n<p>Unless the user knows exactly how to call the program, the program will crash with no indication of what went wrong. This is because the code uses <code>argv[1]</code> for input and doesn't check that <code>argv[1]</code> actually exists. The following code would be better for the user of the program because it check that an <code>argv[1]</code> actually exists first before using it and reports an error if there is no <code>argv[1]</code>:</p>\n<pre><code> if (argc &gt; 1)\n {\n loops = atoll(argv[1]);\n }\n else\n {\n fprintf(stderr, &quot;USAGE MESSAGE&quot;);\n return EXIT_FAILURE;\n }\n</code></pre>\n<p>It is also unclear what is being printed in the following statement:</p>\n<pre><code> printf (&quot;%llu&quot; &quot;%s&quot; &quot;%llu&quot; &quot;%s&quot; &quot;%0.9f&quot; &quot;%s&quot; &quot;%0.3f\\n&quot;,\n i, &quot; &quot;, cpoints, &quot; &quot;, approx, &quot; &quot;, cpu_time_used);\n</code></pre>\n<p>It might be better if the the previous statement was something like this:</p>\n<pre><code> printf (&quot;i = %llu cpoints = %llu approx = %0.9f cpu_time_used = %0.3f\\n&quot;,\n i, cpoints, approx, cpu_time_used);\n</code></pre>\n<p><em>Note: Use the formatting capabilities of the <code>printf</code> statement rather than using &quot;%s&quot; to print spaces. Rather than using the variable <code>i</code> in the statement it would be more understandable to use the variable <code>loops</code>, <code>i</code> and <code>loops</code> should be the same at this point.</em></p>\n<h2>Declare and Initialize the Variables as Needed</h2>\n<p>C is not the nicest language to program in because there is no default value assigned to local variables so it is always best to initialize the variable when it is declared, each variable should be declared and initialized on its own line to make the code easier to read, write, maintain and debug.</p>\n<pre><code> unsigned long long loops = 0;\n unsigned long long cpoints = 0;\n unsigned long long i = 0;\n</code></pre>\n<p>If the variable <code>loops</code> is used for the calculations and printing then the variable <code>i</code> can actually be declared in the for loop.</p>\n<pre><code> for (unsigned long long i = 0; i &lt; loops; ++i)\n {\n double x = (rand() + 1.0) / (RAND_MAX+2.0);\n double y = (rand() + 1.0) / (RAND_MAX+2.0);\n if ( incircle(x,y) !=FALSE )\n cpoints+=1;\n }\n</code></pre>\n<h2>Unnecessary Code</h2>\n<p>Since <code>stdbool.h</code> is included the <code>#defines</code> for <code>TRUE</code> and <code>FALSE</code> are unnecessary because <code>stdbool.h</code> defines <code>true</code> and <code>false</code>. In the if statement where <code>FALSE</code> is used you have a double negative, which is as bad in programming as it is in English. The if statement can be simplified to</p>\n<pre><code> if (incircle(x,y))\n cpoints += 1;\n</code></pre>\n<h2>Code Complexity</h2>\n<p>##Complexity\nThe function <code>main()</code> is too complex (does too much). As programs grow in size the use of <code>main()</code> should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.</p>\n<p>There is also a programming principle called the Single Responsibility Principle that applies here. The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"noreferrer\">Single Responsibility Principle</a> states:</p>\n<blockquote>\n<p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n<p>The <code>main()</code> function can be broken up into the following functions</p>\n<ol>\n<li>Get the user input from the command line and report any errors</li>\n<li>Set up the random number generator.</li>\n<li>The loop that is currently doing the calculations should be in its own function.</li>\n</ol>\n<h2>Compiler Warnings</h2>\n<p>Make sure you enable the compiler warnings when you compile some of the casts in the code are questionable and my compiler is reporting warnings. It might be best to compile with the -wall switch (enable all warnings).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T04:04:17.217", "Id": "494295", "Score": "0", "body": "You have been writing some great answers!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T06:51:38.053", "Id": "494302", "Score": "1", "body": "Also, `cpoints += 1` statement can be simplified to `cpoints++` (or `++cpoints`, the latter will be more efficient since you're not using the old value of `cpoints`, however the compiler will probably optimise it anyway)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T10:50:38.847", "Id": "494320", "Score": "0", "body": "I am using -Wall with gcc in Debian 10." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T00:24:46.053", "Id": "251151", "ParentId": "251149", "Score": "11" } } ]
{ "AcceptedAnswerId": "251151", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-25T22:06:36.197", "Id": "251149", "Score": "9", "Tags": [ "c" ], "Title": "C - approximate pi (Monte Carlo)" }
251149
<p>I created a simple guessing game where the player can choose whether the player is guessing the number or the computer.</p> <p>If the player is guessing the number, then the computer will generate a random number between 1 to 100. Then, the player must guess the computer's number.</p> <p>First, the player will type their guessed number. If it is too high than the computer's number, then the program will print out that the player's number is too high if it is too low, vice versa.</p> <p>If it is correct, then the computer will congratulate the player and ask if the player wants to play again or no. If the player wants to play again, the program will restart, but if the player does not want to play again, the program will exit.</p> <p>If the computer is guessing the number, then the player will think of a number. The computer will print out a number and ask if the player's number is higher or lower. The computer will keep doing this until it finds the number.</p> <p>I'm looking for feedback on absolutely everything that could make me a better programmer, especially a better C++ programmer, such as:</p> <ul> <li>Optimization</li> <li>Bad practice and good practice</li> <li>Code structure</li> <li>Functions and variable naming (to be honest, I'm not really good at naming, lol)</li> <li>Bugs</li> <li>etc</li> </ul> <p><strong>Thank you very much!</strong></p> <p><em>I'm using Visual Studio Community 2019 ver 16.7.6</em></p> <p><strong>Globals.h</strong></p> <pre><code>#ifndef GUARD_GLOBALS_H #define GUARD_GLOBALS_H static const char COMPUTER_GUESSER = 'c'; static const char PLAYER_GUESSER = 'p'; static const char QUIT = 'q'; static const char ANSWER_IS_YES = 'y'; static const char ANSWER_IS_NO = 'n'; static const int MAX_NUMBER = 100; static const int MIN_NUMBER = 1; #endif </code></pre> <p><strong>BracketingSearch.h</strong></p> <pre><code>#ifndef GUARD_BRACKETINGSEARCH_H #define GUARD_BRACKETINGSEARCH_H int randomNumGenerator(const int max, const int min); int rangeNumToGuess(const int max, const int min); int rangeNum(const int max, const int min); bool startGame(); bool computerOrPlayer(const char userchoice); bool computerGuesser(); bool playerGuesser(); bool restart(); #endif </code></pre> <p><strong>BracketingSearch.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include &quot;Globals.h&quot; #include &quot;BracketingSearch.h&quot; int randomNumGenerator(const int max, const int min) { return rand() % max + min; } int rangeNumToGuess(const int max, const int min) { return ((max - min) / 2) + min; } int rangeNum(const int max, const int min) { return max - min; } bool startGame() { char userChoice{}; std::cout &lt;&lt; &quot;Who will be the guesser?\n&quot; &quot;C - for computer\n&quot; &quot;P - for player\n&quot; &quot;Q - for quit\n&quot; &quot;Type one of the choice: &quot;; std::cin &gt;&gt; userChoice; computerOrPlayer(tolower(userChoice)); restart(); return true; } bool computerOrPlayer(const char userchoice) { if (userchoice == COMPUTER_GUESSER) { return computerGuesser(); } else if (userchoice == PLAYER_GUESSER) { return playerGuesser(); } else if (userchoice == QUIT) { std::cout &lt;&lt; &quot;Thank you for playing\n&quot;; } } bool computerGuesser() { char userInput{}; int maxNum = MAX_NUMBER; int minNum = MIN_NUMBER; int guessNum{}; int guessCount{ 1 }; int range; std::cout &lt;&lt; &quot;Think of a number between 1 to 100\n&quot;; while(maxNum != minNum) { ++guessCount; range = rangeNum(maxNum, minNum); if (range == 1) { guessNum = maxNum; } else { guessNum = rangeNumToGuess(maxNum, minNum); } std::cout &lt;&lt; &quot;Is your number less than: &quot; &lt;&lt; guessNum &lt;&lt; &quot;?(y/n): &quot;; std::cin &gt;&gt; userInput; switch (userInput) { case ANSWER_IS_YES: maxNum = guessNum - 1; break; case ANSWER_IS_NO: minNum = guessNum; break; default: std::cout &lt;&lt; &quot;That is a wrong option\n&quot;; guessCount -= 1; break; } if (maxNum == minNum) { std::cout &lt;&lt; &quot;Your number is: &quot; &lt;&lt; maxNum &lt;&lt; std::endl; std::cout &lt;&lt; &quot;It took &quot; &lt;&lt; guessCount &lt;&lt; &quot; guesses for me to guess&quot; &lt;&lt; std::endl; } } return true; } bool playerGuesser() { int userGuess{}; int guessCount{ 1 }; int number = randomNumGenerator(MAX_NUMBER, MIN_NUMBER); std::cout &lt;&lt; &quot;Enter your guess number: &quot;; while (std::cin &gt;&gt; userGuess) { ++guessCount; if (userGuess &gt; number) { std::cout &lt;&lt; &quot;Too high!\n&quot;; } else if (userGuess &lt; number) { std::cout &lt;&lt; &quot;Too low!\n&quot;; } else if (userGuess == number) { std::cout &lt;&lt; &quot;Your guess is correct!\n&quot; &quot;It took you: &quot; &lt;&lt; guessCount &lt;&lt; &quot; guesses\n&quot;; break; } std::cout &lt;&lt; &quot;Guess another number: &quot;; } return true; } bool restart() { char userChoice{}; std::cout &lt;&lt; &quot;Play again? (y/n): &quot;; std::cin &gt;&gt; userChoice; char lowerUserChoice = tolower(userChoice); if (lowerUserChoice == ANSWER_IS_YES) { startGame(); } else if (lowerUserChoice == ANSWER_IS_NO) { computerOrPlayer(QUIT); } else { std::cout &lt;&lt; &quot;Please choose the available option\n&quot;; restart(); } return true; } </code></pre> <p><strong>main.cpp</strong></p> <pre><code>#include &quot;BracketingSearch.h&quot; #include &lt;cstdlib&gt; #include &lt;ctime&gt; int main() { srand((unsigned)time(0)); startGame(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T06:18:11.240", "Id": "494299", "Score": "3", "body": "Good first question! However, you should [edit] your title so that it states what your code does, you don't have to describe your code in the title. Something like \"Number guessing game in C++\" sounds like a good idea to me, you can decide :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T06:19:39.593", "Id": "494300", "Score": "1", "body": "Oh, ok, thanks, Mate!" } ]
[ { "body": "<h1>General observations</h1>\n<p>To be honest, your code is extremely clear and readable to me. I wouldn't guess that you were a beginner from reading your code. You have eliminated the use of magic numbers, and use global constants instead which is good!</p>\n<hr />\n<h1><a href=\"https://stackoverflow.com/questions/357404/why-are-unnamed-namespaces-used-and-what-are-their-benefits\">Anonymous namespaces</a></h1>\n<p>The keyword <code>static</code> in this context means that it has <a href=\"https://www.learncpp.com/cpp-tutorial/internal-linkage/\" rel=\"nofollow noreferrer\">internal linkage</a>. An <a href=\"https://stackoverflow.com/questions/357404/why-are-unnamed-namespaces-used-and-what-are-their-benefits\">anonymous namespace</a> also does the same thing, but they are considered to be somewhat <a href=\"https://stackoverflow.com/questions/4422507/superiority-of-unnamed-namespace-over-static\">superior</a> to the <code>static</code> keyword in C++.</p>\n<p>The link I cited has some great answers.<br> But mainly,</p>\n<ul>\n<li><code>static</code> will only work for functions and objects, an anonymous namespace on the other hand can let you have your own type definitions, classes, structs (almost everything)...</li>\n</ul>\n<pre class=\"lang-cpp prettyprint-override\"><code>// Globals.h\n\nnamespace \n{\n // constants\n}\n</code></pre>\n<h1>Prefer using <code>constexpr</code></h1>\n<p><a href=\"https://docs.microsoft.com/en-us/cpp/cpp/constexpr-cpp?view=vs-2019#:%7E:text=The%20keyword%20constexpr%20was%20introduced,to%20functions%20and%20class%20constructors.\" rel=\"nofollow noreferrer\"><strong>constexpr in C++</strong></a></p>\n<blockquote>\n<p>The keyword <code>constexpr</code> was introduced in C++11 and improved in C++14.\nIt means constant expression. Like <code>const</code>, it can be applied to\nvariables: A compiler error is raised when any code attempts to modify\nthe value. Unlike <code>const</code>, <code>constexpr</code> can also be applied to functions\nand class constructors. constexpr indicates that the value, or return\nvalue, is constant and, where possible, is computed at compile time.</p>\n</blockquote>\n<p>Use <code>constexpr</code> when you can, it tells the compiler that it's literally just a constant. <br> It forces the compiler to calculate the value of something at compile-time. Moreover, you can pass it as a template argument too</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>namespace \n{\n constexpr char COMPUTER_GUESSER { 'c' };\n}\n</code></pre>\n<hr />\n<h1>Use an <code>enum</code></h1>\n<p>This point can depend according to your style, but I think that an <a href=\"https://en.cppreference.com/w/cpp/language/enum\" rel=\"nofollow noreferrer\">enum</a> is called for here.</p>\n<p>I am talking about these variables</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>COMPUTER_GUESSER = 'c';\nPLAYER_GUESSER = 'p';\nQUIT = 'q';\nANSWER_IS_YES = 'y';\nANSWER_IS_NO = 'n';\n</code></pre>\n<p>I believe that having an <code>enum</code> here makes sense because you can group these variables as they all are related to the user's <strong>choice</strong>, this is what it would look like</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>enum Choice : char \n{\n COMPUTER_GUESSER = 'c',\n PLAYER_GUESSER = 'p',\n QUIT = 'q',\n ANSWER_IS_YES = 'y',\n ANSWER_IS_NO = 'n',\n};\n</code></pre>\n<pre class=\"lang-cpp prettyprint-override\"><code>if (input == Choice::QUIT) //...\n\nelse if (input == Choice::ANSWER_YES) //...\n</code></pre>\n<hr />\n<h1>Generating a random <code>int</code></h1>\n<p>C++ has <a href=\"https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution\" rel=\"nofollow noreferrer\"><code>std::uniform_int_distribution</code></a> which is better than C's <code>rand()</code>.</p>\n<hr />\n<h1>Consider <a href=\"https://en.cppreference.com/w/cpp/language/inline#:%7E:text=The%20inline%20specifier%2C%20when%20used,is%20implicitly%20an%20inline%20function.\" rel=\"nofollow noreferrer\"><code>inlining</code></a> smaller functions</h1>\n<pre class=\"lang-cpp prettyprint-override\"><code>int randomNumGenerator(const int max, const int min)\n{\n return rand() % max + min;\n}\n\nint rangeNumToGuess(const int max, const int min)\n{\n return ((max - min) / 2) + min;\n}\n\nint rangeNum(const int max, const int min)\n{\n return max - min;\n}\n</code></pre>\n<p>Inlining these functions can improve the performance a lot, but you need to place the definition of these functions in the <strong>header file</strong>, you can specify <code>inline</code> but it's likely that the compiler will inline them itself.</p>\n<blockquote>\n<p>instead of executing the function call CPU instruction to transfer\ncontrol to the function body, a copy of the function body is executed\nwithout generating the call.</p>\n</blockquote>\n<hr />\n<h1>Always handle invalid input</h1>\n<pre class=\"lang-cpp prettyprint-override\"><code>std::cout &lt;&lt; &quot;Enter your guess number: &quot;;\n\nwhile (std::cin &gt;&gt; userGuess)\n{\n //...\n}\n</code></pre>\n<p>Here, <code>std::cin</code> is expecting an integer, if the user accidentally enters something else, <code>std::cin</code> will <strong>fail</strong>, leading to strange behavior in your program</p>\n<p>There are a few ways, <a href=\"https://www.learncpp.com/cpp-tutorial/5-10-stdcin-extraction-and-dealing-with-invalid-text-input/\" rel=\"nofollow noreferrer\">this</a> article is worth reading.</p>\n<h1>A small bug</h1>\n<p>In your <code>restart()</code> function</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>bool restart()\n{\n char userChoice{};\n std::cout &lt;&lt; &quot;Play again? (y/n): &quot;;\n std::cin &gt;&gt; userChoice;\n\n char lowerUserChoice = tolower(userChoice);\n\n if (lowerUserChoice == ANSWER_IS_YES)\n {\n startGame();\n }\n else if (lowerUserChoice == ANSWER_IS_NO)\n {\n computerOrPlayer(QUIT);\n }\n else\n {\n std::cout &lt;&lt; &quot;Please choose the available option\\n&quot;;\n restart();\n }\n\n return true;\n}\n</code></pre>\n<p>Since you recursively call <code>restart()</code> on invalid input, you should <code>return</code> the value you get. Otherwise, the function won't return anything</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>else \n{ \n std::cout &lt;&lt; &quot;Please choose a valid option!\\n&quot;;\n return restart();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T10:12:29.430", "Id": "494318", "Score": "1", "body": "I've been struggling learning C++ but your compliment really boost my confidence. Honestly, I don't know what \"static\" does. I just saw someone uses it and then I think, why not, lol. I don't understand about the inline part but I'll definitely learn more about it. Thank you very much, Mate, your feedback will greatly help me become a much better programmer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T11:16:02.963", "Id": "494326", "Score": "1", "body": "@SirBroccolia Not a problem, If you want me to recommend some good resources, I would say that you pick up a good C++ book or follow or follow [this](https://www.learncpp.com/) site. Moreover, [this](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb&app=desktop) person on youtube has some amazing content for C++ topics" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T12:14:38.023", "Id": "494334", "Score": "0", "body": "I'm currently reading **C++ Primer** and **Principle and Practice Using C++** I'm still not fully understand about function, pointer, and class, thus I stop reading those books for the moment and making a project to help me understand more about those three things. Because of this project, I understand much more better about function. But, pointer and class still haven't got any clue." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T12:18:45.457", "Id": "494335", "Score": "0", "body": "I have a question, you said that I should've use the namespace instead of the static. And you also said that I could use enum to group the choices together? So, how do I combine those two? \n`namespace\n{\nenum class Choice : char\n{\n//Some things\n}\n}`\n\nlike that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T12:19:49.670", "Id": "494336", "Score": "1", "body": "@SirBroccolia yes! What made you doubt that structure?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T12:32:24.933", "Id": "494339", "Score": "0", "body": "I don't know, I just never see that kind of code before. But then again, it's only been a month since I learn C++. Anyway, thanks for the tips, Mate!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T14:40:13.783", "Id": "494355", "Score": "0", "body": "@AryanParekh: I would be very careful of recommending anonymous namespaces _in hearder_ (though `static` is also problematic there, of course)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T14:43:45.620", "Id": "494356", "Score": "0", "body": "@MatthieuM. Yes it will be a problem, but this is a small-scale project so I didn't say anything, personally I would just keep it in the `.cpp` file" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T18:30:02.090", "Id": "494396", "Score": "0", "body": "\"leading to strange behavior in your\"...?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T18:31:06.273", "Id": "494397", "Score": "1", "body": "@S.S.Anne Oops! Thanks for catching that mistake, I surely forgot to type `program`" } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T07:17:09.233", "Id": "251155", "ParentId": "251154", "Score": "14" } }, { "body": "<p>As has been mentioned, your code is generally pretty good.</p>\n<h3>Turn on warnings, and fix them.</h3>\n<p><code>computerOrPlayer</code> is supposed to return a <code>bool</code>, yet it doesn't always.</p>\n<p>Unfortunately, <em>by default</em> C++ compilers do not warn about this undesirable mistake, but they do generally can detect it -- if you have activate the corresponding warnings.</p>\n<p>For gcc and clang, my recommendation is to add the following flags to your command line: <code>-Werror -Wall -Wextra</code>. In details:</p>\n<ul>\n<li><code>-Werror</code>: treat warnings as errors.</li>\n<li><code>-Wall</code>: activate many warnings (not all, despite the name).</li>\n<li><code>-Wextra</code>: activate another batch of warnings (still not all).</li>\n</ul>\n<p>Other options include using linters, such as cppcheck.</p>\n<p>Compiler warnings and linters are like automated reviewers, they're invaluable, and much more responsive than humans.</p>\n<h3>What are your return types for?</h3>\n<p>Many of your functions return a <code>bool</code>, but often times you don't check the return value of your function calls.</p>\n<p>You have to decide whether the function has important information to return, or not, and then stick to the decision:</p>\n<ul>\n<li>If it has: then it should return a value, and this value should be checked at the call site.</li>\n<li>If it has nothing to report: then it should not return anything (<code>void</code>).</li>\n</ul>\n<p>The <code>[[nodiscard]]</code> attribute will enlist the help of the compiler to ensure that you don't forget to check a return value:</p>\n<pre><code>[[nodiscard]] bool yourfunction();\n</code></pre>\n<h3>Use namespaces.</h3>\n<p>Defining symbols in the global namespace is not idiomatic in C++; the global namespace is already fairly crowded with all the C symbols, no need to add to the mess.</p>\n<p>Instead it is recommended that each project have its own namespace, and possibly sub-namespaces if there are multiple modules -- though here it would be overkill.</p>\n<pre><code>namespace guessing_game {\n}\n</code></pre>\n<h3>What is public, what is private?</h3>\n<p>Your <code>BracketingSearch.h</code> exposes many signatures, but the client only uses <em>one</em>.</p>\n<p>A well-defined module will typically expose only a subset of its types and functions -- this is its public interface -- and the rest should be &quot;hidden&quot;, and inaccessible to the rest of the world.</p>\n<p>In your case, we can see that <code>main</code> only ever calls <code>startGame</code>: it seems this is your public API, and anything else is an implementation detail.</p>\n<p>In this case, the <code>BracketingSearch.h</code> header should only expose <code>startGame</code>: not the other functions, not the constants either.</p>\n<p>The other functions and constants can be declared in <em>private</em> headers, which are only included either by other <em>private</em> headers, or by source files.</p>\n<p>An example of organization:</p>\n<pre><code>include/\n guessing_game/ &lt;-- matches namespace\n BracketingSearch.h\nsrc/\n guessing_game/\n BracketingSearchImpl.hpp\n BracketingSearchImpl.cpp\n BracketingSearch.cpp\n</code></pre>\n<p>Then <code>BracketingSearch.cpp</code> will look like:</p>\n<pre><code>#include &quot;guessing_game/BracketingSearch.h&quot;\n#include &quot;guessing_game/BracketingSearchImpl.h&quot;\n\nnamespace guessing_game {\n\nvoid startGame() {\n ...\n}\n\n} // namespace guessing_game\n</code></pre>\n<p>And <code>BracketingSearchImpl.cpp</code> will look like:</p>\n<pre><code>#include &quot;guessing_game/BracketingSearchImpl.h&quot;\n\nnamespace guessing_game {\n\nnamespace {\n // ... constants ...\n} // anonymous namespace\n\nint randomNumGenerator(const int max, const int min)\n{\n return rand() % max + min;\n}\n\nint rangeNumToGuess(const int max, const int min)\n{\n return ((max - min) / 2) + min;\n}\n\nint rangeNum(const int max, const int min)\n{\n return max - min;\n}\n\n// ... other functions ...\n\n} // namespace guessing_game\n</code></pre>\n<p>And the interface is clear to uses -- they can only use what is declared in the (public) header.</p>\n<p><em>Note: this public/private game is recursive; for example if <code>randomNumGenerator</code> is not used outside <code>BracketingSearchImpl.cpp</code>, then it should NOT be declared in <code>BracketingSearchImpl.hpp</code> and should be moved into the anonymous namespace.</em></p>\n<h3>Avoid global variables</h3>\n<p>Relying on global variables causes issues with testing, multi-threading, etc... it's best avoided.</p>\n<p>In your case you relying on 3 global variables:</p>\n<ol>\n<li>The state of <code>rand()</code>.</li>\n<li><code>std::cin</code>.</li>\n<li><code>std::cout</code>.</li>\n</ol>\n<p>C++11 introduced the <code>&lt;random&gt;</code> header, which is the recommended way to generate random numbers, it will avoid your reliance on <code>rand()</code>:</p>\n<ul>\n<li>Passing the seed to <code>startGame</code>.</li>\n<li>Use a distribution from the <code>&lt;random&gt;</code> header.</li>\n</ul>\n<p>For the I/O streams, there are 2 possibilities:</p>\n<ul>\n<li>Just take <code>std::ostream&amp;</code> and <code>std::istream&amp;</code> as argument to <code>startGame</code>.</li>\n<li>Separate the I/O behind its own interface, and pass the interface to <code>startGame</code>.</li>\n</ul>\n<p>Given the small scale of this game; I'd advise going with just passing the streams.</p>\n<p><em>Note: when you are more comfortable with C++, you should look into Sans IO design, or Hexadecimal Architecture, the idea is that I/O should be moved to the edge of the application, and everything within the application should only interact with business-oriented interfaces. It goes hand in hand with Dependency Injection, too.</em></p>\n<h3>Tests</h3>\n<p>You should test your code.</p>\n<p>As written it's hard to test due to the use of global variables; once they are removed (see previous point) it becomes much easier.</p>\n<p>Testing will allow you to ensure that:</p>\n<ul>\n<li>Invalid input is correctly handled.</li>\n<li>Edge cases are correctly handled.</li>\n<li>...</li>\n</ul>\n<p>And will give you more confidence that you are not breaking everything when changing your code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T21:20:39.287", "Id": "494401", "Score": "0", "body": "This is really a lot to think about. Thanks, Mate, for the advice!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T06:58:21.813", "Id": "494511", "Score": "0", "body": "I fixed a little error, you missed a `s` in `[[nodiscard]]` (`[[nodicard]]`)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T11:32:58.897", "Id": "494532", "Score": "1", "body": "@AryanParekh: Thanks!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T16:36:26.920", "Id": "251175", "ParentId": "251154", "Score": "6" } }, { "body": "<p>You have quite a nice structure. And while it is a bit much for this size of project, it's good training for bigger things.</p>\n<p>Still, <code>static const</code> is strictly inferior where <code>constexpr</code> is a choice. Enum constants are also a nice option.</p>\n<p>Marking parameters <code>const</code> can be useful for definitions of lengthier functions, which you commendably avoid. But for forward-declarations, especially in a header-file, they are just useless clutter grabbing attention better invested elsewhere.</p>\n<p>Your range is curious:</p>\n<ol>\n<li>You are using a closed interval. That is rare in programming, and especially C++, as it is cumbersome and error-prone. Closed number-ranges may not be quite as rare as iterator- and pointer-ranges, but the same principle holds.<br />\nAnd who would have thought, your calculation for the size of the range <code>max - min + 1</code> is often off by one, which you partially compensate for with additional code.</li>\n<li>Giving the end before the beginning is very unexpected, not only in programming, especially using C++, but also for natural language, not that the latter is always a reliable guide.</li>\n</ol>\n<p><code>rand()</code> is generally an awful RNG. Which is not too surprising, considering it is often backwards-compatible to some antediluvian ancestor, and the standard interface is a bit restrictive. If you want a better one with more reliable quality, consider upgrading to <a href=\"https://en.cppreference.com/w/cpp/numeric/random\" rel=\"nofollow noreferrer\"><code>&lt;random&gt;</code></a>.</p>\n<p><code>randomNumGenerator()</code> is wrong. <code>max</code> is only the size of the output range if <code>min</code> is 1, generally it is <code>(max - min + 1)</code>. Not that this method of mapping the randomness you have to the interval you need isn't generally dubious. There is a reason <code>&lt;random&gt;</code> also provides <a href=\"https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution\" rel=\"nofollow noreferrer\"><code>std::uniform_int_distribution</code></a>.</p>\n<p>Not sure what <code>rangeNum()</code> should calculate. If it should be the size of the range, it is wrong, see above. Anyway, fixing <code>rangeNumToGuess()</code> will eliminate the need for the one caller, allowing it to be pruned too.</p>\n<p>I suggest making function-names actions: <code>rangeNumGenerator()</code> becomes <code>getRandomNumber()</code>, and <code>rangeNumGuess()</code> becomes <code>guessNumber()</code>.</p>\n<p><a href=\"//stackoverflow.com/questions/21805674/do-i-need-to-cast-to-unsigned-char-before-calling-toupper-tolower-et-al\">The argument to <code>tolower()</code> must be non-negative</a>. And yes, that means you have to cast to <code>unsigned char</code>.<br />\nActually, consider extracting a new function for getting a <code>char</code> from the user and transforming it to lower-case. You need it in at least two places, and only transform it in one, badly. That also allows you to eliminate a variable in both callers.</p>\n<p>You could use <code>switch</code> in <code>computerOrPlayer()</code> too.</p>\n<p>If a function always returns the same result, consider making it a <code>void</code>-function.</p>\n<p>You have unrestricted recursion in <code>restart()</code>.<br />\nDon't depend on the compiler to do tail-call optimization, especially as you forgot to <code>return</code> the result of the recursive call to make it a tail-call. At least there are no non-trivial dtors involved, but the escape-analysis involved might still be too much if even attempted.<br />\nDon't depend on the user to be too impatient to accumulate enough frames to cause a stack overflow.</p>\n<p><code>main()</code> has an implicit <code>return 0;</code> at the end. For whatever that is worth.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T21:25:43.527", "Id": "494497", "Score": "0", "body": "Thanks for the advice, Mate! I will definitely keep it in mind for my next exercise" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T17:10:25.530", "Id": "251222", "ParentId": "251154", "Score": "1" } } ]
{ "AcceptedAnswerId": "251155", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T06:13:17.923", "Id": "251154", "Score": "15", "Tags": [ "c++", "beginner", "number-guessing-game" ], "Title": "C++ Number Guessing Game" }
251154
<p>I have surrounded my initials with a circle. This is intended to be a re-usable component in a responsive layout. (When it is re-used the text will always be two letters, and the font won't change. It behaves sensibly when the browser zooms in and out, but I haven't yet considered if a different component size is needed for very small screens.)</p> <p><a href="https://i.stack.imgur.com/ZKlcm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZKlcm.png" alt="enter image description here" /></a></p> <p>I tried two approaches, firstly with flex layout, and secondly using the box model, and I'm not sure which I prefer.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.flex-profile-icon { display: flex; flex: 0 0 auto; width: 6em; height: 6em; border-style: solid; border-radius: 50%; justify-content: center; } .flex-profile-icon-text { align-self: center; /* center on cross-axis, i.e. vertically */ font-size: 300%; } .trad-profile-icon { width: 6em; border-style: solid; border-radius: 50%; line-height: 0; position: relative; } .trad-profile-icon:after { content: ""; display: block; padding-bottom: 100%; /* hack for equal height to width */ } .trad-profile-icon-text { position: absolute; bottom: 50%; width: 100%; text-align: center; font-size: 300%; } /* Copyright 2019-2020 by dcorking and Code Boxx */</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;p&gt; Aim is for the text to be centered in the circle &lt;/p&gt; &lt;h2&gt;Flexbox layout&lt;/h2&gt; &lt;div class="flex-profile-icon"&gt; &lt;a class="flex-profile-icon-text"&gt; DC &lt;/a&gt; &lt;/div&gt; &lt;h2&gt;Traditional box layout&lt;/h2&gt; &lt;div class="trad-profile-icon"&gt; &lt;div class="trad-profile-icon-text"&gt; DC &lt;/div&gt; &lt;/div&gt; &lt;p&gt; Credit for the traditional box layout approach due to &lt;a href="https://code-boxx.com/css-circles-text/#sec-text"&gt;&lt;em&gt;How to Create CSS Circles (And Add Text To It)&lt;/em&gt;, W.S. Toh of Code Boxx &lt;/a&gt; &lt;/p&gt;</code></pre> </div> </div> </p> <p>I will be interested in your recommendations on maintainability, cross-browser compatibility, and compatibility with layout frameworks such as Foundation (XY Grid or Float Grid) and Bootstrap.</p> <p><a href="https://codepen.io/dcorking/pen/BazWyOj" rel="nofollow noreferrer">Codepen</a></p>
[]
[ { "body": "<p>Try this approach. It uses <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout\" rel=\"nofollow noreferrer\">CSS Grid layout</a>. It requires less code and is easier to maintain.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.circle {\n display: grid;\n place-content: center;\n border: 0.3em solid black;\n border-radius: 50%;\n width: 6em;\n height: 6em;\n}\n\n.initials {\n font-size: 300%;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"circle\"&gt;\n &lt;div class=\"initials\"&gt;DC&lt;/div&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": "2021-01-05T13:22:20.780", "Id": "501576", "Score": "2", "body": "Welcome.\nInstead of presenting an alternative approach, on this community we are looking to improve existing provided solutions" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-05T16:23:24.793", "Id": "501594", "Score": "2", "body": "Then again, Pi314 offered two measures according to which s/he thinks this alternative preferable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-05T19:17:47.527", "Id": "501618", "Score": "0", "body": "You have simplified 4 lines of my layout code to just 2. I particularly like that all the layout code is in the circle class: so clearly easier to maintain." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-05T12:56:43.033", "Id": "254341", "ParentId": "251160", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T11:48:40.673", "Id": "251160", "Score": "3", "Tags": [ "css", "comparative-review", "layout", "portability" ], "Title": "Text centered in a circular component" }
251160
<p>I am building a doctor appointment app with Django and Django Rest Framework. The app will have the functionality for secretaries to add appointments to a Doctor's calendar, and each Doctor may have more than one clinic (and multiple secretaries).</p> <p>I built this <code>Calendar</code> Model to store the availability information of a doctor, which needs to basically inform:</p> <ul> <li>on a given day, at what time the doctor starts and finishes work</li> <li>on a given day, at what time the doctor starts and finishes their break time (if they do).</li> </ul> <p>Is this the optimal way to do it?</p> <pre><code>class Calendar(models.Model): doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE, related_name=&quot;appointments&quot;) clinic = models.ForeignKey(Clinic, on_delete=models.CASCADE, related_name=&quot;appointments&quot;) monday_start = models.TimeField() monday_end = models.TimeField() monday_break_start = models.TimeField() monday_break_end = models.TimeField() # continues for every single day of the week </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T12:48:35.960", "Id": "494341", "Score": "0", "body": "What happens when same doctor is attending multiple clinics?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T13:04:23.393", "Id": "494342", "Score": "0", "body": "A doctor will have a unified calendar for all of their clinics... I guess I'm planning on blocking different times in the front end" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T13:19:56.047", "Id": "494344", "Score": "0", "body": "no, what i meant was: doctor D has clinics C1 and C2. Do you have 2 rows in `Calendar` with all those columns for D-C1 and D-C2 combinations?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T13:39:08.437", "Id": "494348", "Score": "0", "body": "there'll be a Calendar for each doctor-clinic" } ]
[ { "body": "<p>This is relatively simple solution you have here and it could in theory work, but in my experience in a real word you need something more flexible. Also you dont think about redundancy of the data.</p>\n<p>What if a doctor for example works only one day in a week. Most of the columns would then be empty. Or if a doctor can work only in the morning? Then there would be no break_start or end in any of the calendar fields. What if, for example, the doctor works every second week? Then you will not have an easy way how to store this information. Also there would be a lot of redundant information. If you will have each doctor working from 8:00 AM to 4:00 PM, you will have this data stored there redundantly. Much less space is needed, if you can store such information as a relation to some kind of duration record.</p>\n<p>If I were you, I would create more generic design where you can store up to 365 records (for each day in the year), for each calendar. Then each day would have a relation to a list of intervals, that could later be of required activity. That way you would end up with <strong>more flexible</strong> design.</p>\n<p>The draft could look something like this:</p>\n<pre><code>class Calendar(models.Model):\n doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE)\n clinic = models.ForeignKey(Clinic, on_delete=models.CASCADE)\n\nclass CalendarDay(models.Model):\n date = model.DateField()\n calendar = models.ForeignKey(Calendar, on_delete=models.CASCADE)\n\nclass TimeInterval(models.Model):\n activity = models.Integer(choices = [(1, 'Working'), (2,'Lunch Break'), (3, 'Afternoon Break') ...])\n start = models.TimeField()\n end = models.TimeField()\n calendar_day = models.ForeignKey(CalendarDay, on_delete=models.CASCADE)\n</code></pre>\n<p>In order to ensure <strong>data integrity</strong>, then you could add an unique constraint on the combination of date and calendar columns in the CalendarDay table. That way each calendar can have only one record for particular date in the CalendarDay table.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T18:41:29.723", "Id": "251265", "ParentId": "251161", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T12:13:58.397", "Id": "251161", "Score": "3", "Tags": [ "python", "django" ], "Title": "Django Calendar Model" }
251161
<p>I have put together a <strong><a href="https://github.com/Ajax30/XPressBlog" rel="nofollow noreferrer">blogging application</a></strong> with <a href="https://expressjs.com/" rel="nofollow noreferrer">Express</a>, <a href="https://ejs.co/" rel="nofollow noreferrer">EJS</a> and MongoDB.</p> <p>There is a public, front-end part and a dashboard. In index.js I have:</p> <pre><code>// Bring the Dashboard const dashboardRoute = require(&quot;./routes/admin/dashboard&quot;); // Register Dashboard Routes app.use('/dashboard', dashboardRoute); // Bring the Posts Routes const postsRoute = require('./routes/front-end/posts'); // Register Posts Routes app.use('/', postsRoute); </code></pre> <p>In <code>routes\admin\dashboard.js</code> I have:</p> <pre><code>const express = require('express'); const imageUploader = require('../../utils/imageupload.js'); const validator = require('../../utils/validation.js'); const dashboardController = require('../../controllers/admin/dashboard'); const categoriesController = require('../../controllers/admin/categories'); // Express router const router = express.Router(); // Display Dashboard router.get('/', dashboardController.displayDashboard); // Render add Post Form router.get('/addpost', dashboardController.addPostForm); // Add Post router.post('/post/add', imageUploader.upload, validator.addPostCheck, dashboardController.addPost); // Edit Post router.get('/post/edit/:id', dashboardController.editPost); // Update Post router.post('/post/update/:id', imageUploader.upload, validator.addPostCheck, dashboardController.updatePost); // Delete Post router.delete('/post/delete/:id', dashboardController.deletePost); // Display Categories router.get('/categories', categoriesController.showCategories); // Render add Categories Form router.get('/categories/addcategory', categoriesController.addCategoryForm); // Add Category router.post('/category/add', validator.addCategoryCheck, categoriesController.addCategory); // Edit Post router.get('/category/edit/:id', categoriesController.editCategory); // Update Category router.post('/category/update/:id', validator.addCategoryCheck, categoriesController.updateCategory); // Delete Category router.delete('/category/delete/:id', categoriesController.deleteCategory); module.exports = router; </code></pre> <p>I am concerned especially about the controllers &quot;under&quot; the dashboard (<code>controllers\admin\dashboard.js</code>):</p> <pre><code>const Post = require('../../models/post'); const Category = require('../../models/categories'); const {upload} = require('multer'); const {validationResult} = require('express-validator'); exports.displayDashboard = async (req, res, next) =&gt; { const posts = await Post.find({}, (err, posts) =&gt; { if (err) { console.log('Error: ', err); } else { res.render('admin/index', { layout: 'admin/layout', website_name: 'MEAN Blog', page_heading: 'Dashboard', posts: posts }); } }).populate('category'); }; exports.addPostForm = async (req, res, next) =&gt; { const categories = await Category.find({}, (err, categories) =&gt; { if (err) { console.log('Error: ', err); } else { res.render('admin/addpost', { layout: 'admin/layout', website_name: 'MEAN Blog', page_heading: 'Dashboard', page_subheading: 'Add New Post', categories: categories }); } }); } exports.addPost = (req, res, next) =&gt; { const form = { titleholder: req.body.title, excerptholder: req.body.excerpt, bodyholder: req.body.body }; const errors = validationResult(req); const post = new Post(); post.title = req.body.title; post.short_description = req.body.excerpt post.full_text = req.body.body; post.category = req.body.category; if (req.file) { post.post_image = req.file.filename; } if (!errors.isEmpty()) { const categories = Category.find({}, (err, categories) =&gt; { req.flash('danger', errors.array()) res.render('admin/addpost', { layout: 'admin/layout', website_name: 'MEAN Blog', page_heading: 'Dashboard', page_subheading: 'Add New Post', categories: categories, form: form }); }); } else { post.save(function(err) { if (err) { console.log(err); return; } else { req.flash('success', &quot;The post was successfully added&quot;); req.session.save(() =&gt; res.redirect('/dashboard')); } }); } } exports.editPost = async (req, res, next) =&gt; { const postId = req.params.id; Post.findById(postId, function(err, post) { const categories = Category.find({}, (err, categories) =&gt; { if (err) { console.log('Error: ', err); } else { res.render('admin/editpost', { layout: 'admin/layout', website_name: 'MEAN Blog', page_heading: 'Dashboard', page_subheading: 'Edit Post', categories: categories, post: post }); } }); }); } exports.updatePost = (req, res, next) =&gt; { const query = { _id: req.params.id } const form = { titleholder: req.body.title, excerptholder: req.body.excerpt, bodyholder: req.body.body }; const errors = validationResult(req); const post = {}; post._id = req.params.id; post.title = req.body.title; post.short_description = req.body.excerpt post.full_text = req.body.body; post.category = req.body.category; if (req.file) { post.post_image = req.file.filename; } if (!errors.isEmpty()) { req.flash('danger', errors.array()); const categories = Category.find({}, (err, categories) =&gt; { res.render('admin/editpost', { layout: 'admin/layout', website_name: 'MEAN Blog', page_heading: 'Dashboard', page_subheading: 'Edit Post', categories: categories, form: form, post: post }); }); } else { Post.update(query, post, function(err) { if (err) { console.log(err); return; } else { req.flash('success', &quot;The post was successfully updated&quot;); req.session.save(() =&gt; res.redirect('/dashboard')); } }); } } exports.deletePost = (req, res, next) =&gt; { const postId = req.params.id; Post.findByIdAndRemove(postId, function(err) { if (err) { console.log('Error: ', err); } res.sendStatus(200); }); } </code></pre> <p>The controller concerning the <strong>categories</strong>:</p> <pre><code>const Category = require('../../models/categories'); const { validationResult } = require('express-validator'); exports.showCategories = async (req, res, next) =&gt; { const categories = await Category.find({}, (err, categories) =&gt; { if(err){ console.log('Error: ', err); } else { res.render('admin/categories', { layout: 'admin/layout', website_name: 'MEAN Blog', page_heading: 'Dashboard', page_subheading: 'Categories', categories: categories }); } }); }; exports.addCategoryForm = (req, res, next) =&gt; { res.render('admin/addcategory', { layout: 'admin/layout', website_name: 'MEAN Blog', page_heading: 'Dashboard', page_subheading: 'Add New Category', }); } exports.addCategory = (req, res, next) =&gt; { var form = { categoryholder: req.body.cat_name }; const errors = validationResult(req); const category = new Category(); category.cat_name = req.body.cat_name; if (!errors.isEmpty()) { req.flash('danger', errors.array()) res.render('admin/addcategory',{ layout: 'admin/layout', website_name: 'MEAN Blog', page_heading: 'Dashboard', page_subheading: 'Add New Category', form:form } ); } else { category.save(function(err) { if (err) { console.log(err); return; } else { req.flash('success', &quot;The category was successfully added&quot;); req.session.save(() =&gt; res.redirect('/dashboard/categories')); } }); } } exports.editCategory = (req, res, next) =&gt; { const catId = req.params.id; Category.findById(catId, function(err, category){ if (err) { console.log('Error: ', err); } else { res.render('admin/editcategory', { layout: 'admin/layout', website_name: 'MEAN Blog', page_heading: 'Dashboard', page_subheading: 'Edit Category', category: category }); } }); } exports.updateCategory = (req, res, next) =&gt; { const query = {_id:req.params.id} var form = { categoryholder: req.body.cat_name }; const errors = validationResult(req); const category = {}; category._id = req.params.id; category.cat_name = req.body.cat_name; if (!errors.isEmpty()) { req.flash('danger', errors.array()) res.render('admin/editcategory',{ layout: 'admin/layout', website_name: 'MEAN Blog', page_heading: 'Dashboard', page_subheading: 'Edit Category', form: form, category: category } ); } else { Category.update(query, category, function(err){ if(err){ console.log(err); return; } else { req.flash('success', &quot;The category was successfully updated&quot;); req.session.save(() =&gt; res.redirect('/dashboard/categories')); } }); } } exports.deleteCategory = (req, res, next) =&gt; { const catId = req.params.id; Category.findByIdAndRemove(catId, function(err){ if (err) { console.log('Error: ', err); } res.sendStatus(200); }); } </code></pre>
[]
[ { "body": "<h2>Shorthand Property Definition Notation</h2>\n<p>As I mentioned <a href=\"https://codereview.stackexchange.com/a/232969/120114\">in an answer</a> to one of your previous posts, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Property_definitions\" rel=\"nofollow noreferrer\">The shorthand property definition notation</a> can be used to simplify the lines like these where the key is the same as the name of the variable being referenced:</p>\n<blockquote>\n<pre><code> categories: categories,\n posts: posts\n</code></pre>\n</blockquote>\n<p>To simply:</p>\n<pre><code> categories,\n posts\n</code></pre>\n<h2>Waiting with <code>await</code></h2>\n<p>With async / await the code that is typically in the promise callback can be moved out- so take this section for example:</p>\n<blockquote>\n<pre><code> const posts = await Post.find({}, (err, posts) =&gt; {\n if (err) {\n console.log('Error: ', err);\n } else {\n res.render('admin/index', {\n layout: 'admin/layout',\n website_name: 'MEAN Blog',\n page_heading: 'Dashboard',\n posts: posts\n });\n }\n }).populate('category');\n</code></pre>\n</blockquote>\n<p>I haven’t tested this code but my guess is that the call to <code>.populate('category')</code> comes <em>after</em> the callback where <code>res.render()</code> is called - so that <strong>may be a bug</strong>.</p>\n<p>It can be like simplified to something like this:</p>\n<pre><code>const posts = await Post.find({}).populate('category').catch(err =&gt; {\n console.log('Error: ', err);\n });\nres.render('admin/index', {\n layout: 'admin/layout',\n website_name: 'MEAN Blog',\n page_heading: 'Dashboard',\n posts\n});\n</code></pre>\n<p>Though maybe the call to populate the category needs to come after the value from <code>Post.find({})</code> Is assigned to <code>posts</code>.</p>\n<p>And similarly for the other functions called with <code>await</code>. This way the value assigned to <code>posts</code> from can be used properly.</p>\n<h2>Useless <code>else</code> keyword after <code>return</code></h2>\n<p>In the callback to <code>post.save()</code>:</p>\n<blockquote>\n<pre><code> if (err) {\n console.log(err);\n return;\n } else {\n req.flash('success', &quot;The post was successfully added&quot;);\n req.session.save(() =&gt; res.redirect('/dashboard'));\n }\n</code></pre>\n</blockquote>\n<p>The code in the <code>else</code> block can be moved out because in the first case there is a <code>return</code> statement. This can reduce the indentation level.</p>\n<h2>variable declared with <code>var</code></h2>\n<p>The <a href=\"https://codereview.stackexchange.com/a/250919/120114\">answer by CertainPerformance</a> to your previous post recommends avoiding the <code>var</code> keyword. Yet this code uses it:</p>\n<blockquote>\n<pre><code>exports.addCategory = (req, res, next) =&gt; {\n\n var form = {\n categoryholder: req.body.cat_name\n };\n</code></pre>\n</blockquote>\n<p>That variable is never reassigned so it can be declared with <code>const</code>.\nAnd similarly for <code>updateCategory()</code> - it has a variable declared with <code>var</code> named <code>form</code> that never gets re-assigned.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-19T05:19:18.020", "Id": "530883", "Score": "0", "body": "Please have a look at **[this question](https://codereview.stackexchange.com/q/269122/178805)**, I appreciate your competence." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-31T07:20:44.693", "Id": "251368", "ParentId": "251164", "Score": "2" } } ]
{ "AcceptedAnswerId": "251368", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T13:55:51.110", "Id": "251164", "Score": "5", "Tags": [ "javascript", "mongodb", "express.js", "modules", "ecmascript-8" ], "Title": "Express.js blogging application" }
251164
<p>I have a big python data-frame and I am trying to add a column to it with average number of missing values by row. I have inherited some code that is working but I'd like to reduce memory usage by removing intermediary values.</p> <p>Here is a toy exemple :</p> <pre><code>students = [ ('jack', np.NaN, 'Sydeny' , 'Australia') , ('Riti', np.NaN, 'Delhi' , 'India' ) , ('Vikas', 31, np.NaN , 'India' ) , ('Neelu', 32, 'Bangalore' , 'India' ) , ('John', 16, 'New York' , 'US') , ('John' , 11, np.NaN, np.NaN ) , (np.NaN , np.NaN, np.NaN, np.NaN ) ] dfObj = pd.DataFrame(students, columns = ['Name' , 'Age', 'City' , 'Country']) </code></pre> <p>And the code I inherited :</p> <pre><code>print('NanCounter -&gt; transform') nan_count = pd.DataFrame(data = np.mean(dfObj.isna().values, axis=1).astype('float32'), columns=['nan_count']).set_index(dfObj.index) X_ = pd.concat([dfObj, nan_count], axis=1) X_.set_index(dfObj.index, inplace=True) </code></pre> <p>It seems quite a convoluted way to just write :</p> <pre><code>print('NanCounter -&gt; transform') dfObj['nan_count'] = np.mean(dfObj.isna().values, axis=1).astype('float32') </code></pre> <p>Plus it seems to consume more memory. I am concerned I am missing something about calculcations. Are those expression equivalent ? Namely, what would be the interest with working with a supplementary variable ?</p>
[]
[ { "body": "<p>The difference between the two code snippets is that the first creates a new DataFrame while the second modifies the original DataFrame in-place.</p>\n<p>The first snippet can be simplified to</p>\n<pre><code>X_ = dfObj.assign(nan_count=dfObj.isna().mean(axis=1).astype('float32'))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-07T15:17:35.100", "Id": "251761", "ParentId": "251166", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T14:09:37.943", "Id": "251166", "Score": "4", "Tags": [ "python", "pandas", "memory-optimization" ], "Title": "Python : adding a columns with count of missing values by row" }
251166
<p>This program takes text input and evaluates the expression. This is meant to be an exercise.</p> <p>I reinvented a stack class though I know C++ provides one in the standard library but it isn&quot;t meant for production use but to solidify my knowledge on linked list data structure</p> <p>I also made an infix postfix converter which converts 2 + 2 to 22+ which seems easier for a computer to evaluate.</p> <p>My major concerns are</p> <ol> <li>Optimization</li> <li>Potential pitfalls</li> <li>General bad practice</li> <li>Readability</li> <li>Ease of use</li> </ol> <h2>main.cc</h2> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;cassert&gt; #include &lt;cmath&gt; #include &quot;stack.hh&quot; /* function prototypes */ bool isOperator( const char c ); std::string strip( const std::string &amp;s ); std::string parse( const std::string &amp;A, const std::string &amp;B, const char op ); double eval( const std::string &amp;s); int prec( const char c ); std::string postfix( const std::string &amp;s ); /* main function */ int main() { std::string s; while ( true ) { try { std::cout &lt;&lt; &quot;Enter text evaluate ( press $ to end ): \n&quot;; std::cout &lt;&lt; &quot;&gt; &quot;; std::getline( std::cin, s ); if ( s == &quot;$&quot; ) break; std::cout &lt;&lt; eval( s ) &lt;&lt; &quot;\n&quot;; } catch ( std::runtime_error &amp;e ) { std::cout &lt;&lt; &quot;Invalid expression&quot; &lt;&lt; std::endl; } } } bool isOperator( const char c ) { const char op[] = &quot;+*/-()^&quot;; static constexpr size_t size = sizeof( op ) / sizeof(op[0]); for( unsigned i = 0; i != size; ++i ) { if ( c == op[ i ] ) return true; } return false; } std::string strip( const std::string &amp;s ) { /* remove all invalid characters */ std::string n; for( auto &amp;c : s ) { if( isdigit( c ) || isOperator( c ) ) { n += c; } } return n; } int prec( const std::string &amp;c ) { if ( c == &quot;^&quot; ) return 3; if ( c == &quot;*&quot; || c == &quot;/&quot; ) return 2; if ( c == &quot;+&quot; || c == &quot;-&quot; ) return 1; return -1; } std::string postfix( const std::string &amp;s ) { /* convert to postfix */ emptyStack(); push(&quot;N&quot;); int l = s.size(); std::string ns, temp; for( int i = 0; i != l; ++i ) { temp = &quot;&quot;; temp.push_back( s[ i ]); if( isdigit( s[i] ) ) { ns += temp; } else if( temp == &quot;(&quot; ) { push(&quot;(&quot;); } else if( temp == &quot;)&quot; ) { // if closing parentheses is found, pop the stack till equivalent opening parentheses; while( peek() != &quot;N&quot; &amp;&amp; peek() != &quot;(&quot; ) { std::string c = peek(); pop(); ns += c; } if( peek() == &quot;(&quot; ) { pop(); } } else if( peek() == &quot;(&quot; ) { push( temp ); } else { while( peek() != &quot;N&quot; &amp;&amp; prec( temp ) &lt;= prec( peek() ) ) { /* use precedence rule to compare operators */ std::string c = peek(); pop(); ns += c; } push( temp ); } } while( peek() != &quot;N&quot; ) { // pop remaining element from the stack std::string c = peek(); pop(); ns += c; } return ns; } std::string parse( const std::string &amp;A, const std::string &amp;B, const char op ) { std::string result; switch (op) { case '^': result = std::to_string( std::pow( std::stod( A ), std::stod( B ) ) ) ; std::cout &lt;&lt; result; break; case '*': result = std::to_string( std::stod( A ) * std::stod( B ) ); break; case '/': result = std::to_string( std::stod( A ) / std::stod( B ) ); break; case '+': result = std::to_string( std::stod( A ) + std::stod( B ) ); break; case '-': result = std::to_string( std::stod( A ) - std::stod( B ) ); break; default: throw std::invalid_argument(&quot;Invalid operator.&quot;); break; } return result; } double eval( const std::string &amp;s) { std::string newStr = s; newStr = strip( newStr ); newStr = postfix( newStr ); emptyStack(); // deletes all contents in the stack and prepares stack for reuse std::string temp; // temp string to store each character for evaluation std::string result; size_t l = newStr.size(); for( size_t i = 0; i != l; ++i ) { temp = &quot;&quot;; // reset the string temp for reuse in the next evaluation if( isdigit( newStr[i] ) ) { temp.push_back( newStr[ i ] ); push( temp ); } if( isOperator( newStr[ i ] ) ) { // If an operator is found, pop out 2 operands from the stack // and evaluate them std::string A = peek(); pop(); std::string B = peek(); pop(); result = parse( B, A, newStr[ i ] ); push(result); } } result = peek(); // The result is the top of the stack pop(); return std::stod( result ); } </code></pre> <h2>stack.hh</h2> <pre><code>#ifndef STACK__ #define STACK__ struct Stack{ std::string data; Stack *link; }; void push( std::string x ); void pop(); std::string peek(); void insertAtBottom( std::string x ); void reverse(); int size(); bool isEmpty(); void emptyStack(); void display(); #endif; </code></pre> <h2>stack.cc</h2> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &quot;stack.hh&quot; Stack *top = nullptr; void push( std::string x ) { Stack *newNode = new Stack; newNode-&gt;data = x; newNode-&gt;link = top; top = newNode; } void pop() { if( top == nullptr ) { throw std::runtime_error(&quot;List is empty&quot;); } Stack *temp = top; top = top-&gt;link; delete temp; } std::string peek() { if( top == nullptr ) { throw std::runtime_error(&quot;List is empty&quot;); } Stack *temp = top; std::string x = temp-&gt;data; return x; } void insertAtBottom( std::string x ) { if ( top == nullptr ) push( x ); else { std::string a = peek( ); pop( ); insertAtBottom( x ); push( a ); } } void reverse() { if( top == nullptr ) return; else { std::string a = peek(); pop( ); reverse( ); insertAtBottom( a ); } } int size() { Stack *temp = top; int count = 0; while( temp != nullptr ) { temp = temp-&gt;link; ++count; } return count; } bool isEmpty() { return ( top == nullptr ); } void emptyStack() { while( isEmpty() == false ) { pop(); } } void display() { Stack *temp = top; while( temp != nullptr ) { std::cout &lt;&lt; temp-&gt;data &lt;&lt; &quot; &quot;; temp = temp-&gt;link; } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T14:52:08.950", "Id": "494357", "Score": "1", "body": "Is it intentional that when I enter a number with multiple digits only the last digit is retained? For example 465 becomes 5. If not then you might want to fix this behavior. I'm working on Windows 10 using Visual Studio 2019 Professional." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T14:59:51.740", "Id": "494360", "Score": "0", "body": "It can calculate just one digit only" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T16:56:42.860", "Id": "494475", "Score": "1", "body": "Does not look like you implement operator precedence? `2+3*4` Should be `14`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T16:57:27.553", "Id": "494476", "Score": "1", "body": "Have you thought about using flex and bison to do the work for you?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T19:27:57.433", "Id": "494491", "Score": "0", "body": "@Martin York it works on my machine though." } ]
[ { "body": "<h1>Avoid unnecessary forward declarations</h1>\n<p>Instead of forward-declaring function prototypes, you can change the order in which you define the functions in main.cc. This means less duplication, and less chance of errors.</p>\n<h1>Be aware that string literals contain a terminating NUL-byte</h1>\n<p>When you try to get the length of the string <code>op</code> in <code>isOperator()</code>, <code>size</code> will be 8, since it will also include the NUL-byte that terminates the string literal <code>&quot;+*/-()^&quot;</code>. It turns out to be harmless here, but it is better to avoid this. Since in this case, <code>op</code> is not meant to be a single string but really an array of individual characters, I would initialize it like so:</p>\n<pre><code>const char op[] = {'+', '*', ...};\n</code></pre>\n<p>Then <code>size</code> will also automatically be correct.</p>\n<h1>Avoid using <code>std::endl</code></h1>\n<p>Prefer using <a href=\"https://stackoverflow.com/questions/213907/stdendl-vs-n\">'&quot;\\n&quot;<code>instead of</code>std::endl`</a>. The latter is equivalent to the former, but it also forces the output to be flushed, which can be bad for performance.</p>\n<p>However, you do need to explictly flush the output if you don't end a line with a newline character, in case the output is line-buffered. So:</p>\n<pre><code>std::cout &lt;&lt; &quot;&gt; &quot; &lt;&lt; std::flush;\n</code></pre>\n<h1>Avoid excessive conversions to and from strings</h1>\n<p>When you evaluate a subexpression, you return the result as a string again. This means that the CPU is mostly spending its time converting values to and from strings. It would be much more efficient to parse the whole expression first into <a href=\"https://stackoverflow.com/questions/5639177/what-exactly-is-a-token-in-relation-to-parsing\">tokens</a>, converting any numbers into <code>double</code>s, and then do the actual evaluation on the tokens.</p>\n<p>You would need to find some way to store a token, which can be either a number or an operator. You could use <a href=\"https://en.cppreference.com/w/cpp/utility/variant\" rel=\"nofollow noreferrer\"><code>std::variant</code></a> for this if you can use C++17, otherwise you could use a tagged <code>union</code>.</p>\n<h1>About your stack implementation</h1>\n<p>There are several things that could be improved in your implementation of a stack, apart from just using <code>std::stack</code> of course:</p>\n<h2>Make it a proper <code>class</code></h2>\n<p>You have a lot of global functions to manipulate the single instance of the stack. However, you could easily make these functions member functions of <code>struct Stack</code>.</p>\n<h2>Use <code>std::unique_ptr</code> to manage memory for you</h2>\n<p>I know you wanted to implement a stack container from scratch, so maybe you also wanted to do the memory allocation from scratch. However, it is easy to get this wrong. Consider using <a href=\"https://en.cppreference.com/w/cpp/memory/unique_ptr\" rel=\"nofollow noreferrer\"><code>std::unique_ptr</code></a> to manage pointers to stack elements.</p>\n<h2>Consider making it look like a STL container</h2>\n<p>Try to make the names of your stack (member) functions similar to those used by STL containers. This makes them easier to remember, and will also make it easier to change container types in your program without having to modify all the sites calling member functions operating on container variables. So for example, instead of <code>peek()</code>, use <code>top()</code>.</p>\n<h2>Is it just a stack or more than that?</h2>\n<p>Since your stack also has <code>insertAtBottom()</code> and <code>reverse()</code>, it is not really just a stack anymore, but more like a reversible queue or linked list. However, since the internal data structure is still that of a stack, the operations <code>insertAtBottom()</code> and <code>reverse()</code> are actually quite expensive operations. Especially <code>reverse()</code>, which looks <span class=\"math-container\">\\$\\mathcal{O}(N^2)\\$</span> to me: it recursively calls itself, but then also calls <code>insertAtBottom()</code> which also recursively calls itself.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T18:08:30.460", "Id": "494395", "Score": "0", "body": "Great..... I thought making an STL container or implementing a full featured stack would be an overkill." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T19:59:40.613", "Id": "494400", "Score": "1", "body": "@theProgrammer I thought you wanted the exercise ;)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T14:53:28.760", "Id": "251169", "ParentId": "251167", "Score": "7" } }, { "body": "<h2>Code Review of Stack</h2>\n<p>Why is this not all a class?</p>\n<hr />\n<p>Why are you not using a namespace?</p>\n<hr />\n<p>Double underscore on an identifier is reserved for the implementation in all situations. Don't do this:</p>\n<pre><code>#ifndef STACK__\n#define STACK__\n</code></pre>\n<p>Note: A single trailing underscore is fine. But I usually add the <code>_H</code> at the end (to distinguish it from <code>_TPP</code> guards).</p>\n<p>While we are on guards. I can see the identifier <code>STACK</code> potentially being overloaded. I would add a namespace to the guard.</p>\n<pre><code>#ifndef THE_PROGRAMMER_STACK_H\n#define THE_PROGRAMMER_STACK_H\n\nnamespace TheProgrammer\n{\n // Stuff\n}\n</code></pre>\n<hr />\n<p>I would say this is a node in a stack.</p>\n<pre><code>struct Stack{\n std::string data;\n Stack *link;\n};\n</code></pre>\n<p>I would have done:</p>\n<pre><code>class Stack\n{\n struct Node\n {\n std::string data;\n Node* link;\n };\n Node* root;\n \n public:\n\n // STUFF\n};\n</code></pre>\n<hr />\n<p>Pass strings by const reference:</p>\n<pre><code>void push( std::string x );\n</code></pre>\n<p>Here you are passing by value and as such you are making a copy. If you want to be advanced allow a push using an r-value.</p>\n<pre><code>void push(std::string const&amp; x); // Copy into stack\nvoid push(std::string&amp;&amp; x); // Move into stack\n</code></pre>\n<hr />\n<p>Here I would return a reference.</p>\n<pre><code>std::string peek();\n</code></pre>\n<p>That way you can take a copy if you want to. Or if you don't want to then you can use it directly. You want to have a normal and a const version so you can use the stack in const context.</p>\n<pre><code>std::string&amp; Stack::peek();\nstd::string const&amp; Stack::peek() const;\n</code></pre>\n<hr />\n<p>Sure. But if these are a member of a class you want to mark them as const.</p>\n<pre><code>int size();\nbool isEmpty();\n</code></pre>\n<hr />\n<p>Display is great. But usually we use <code>operator&lt;&lt;</code> to stream an object to an output stream. So I would add this. It can use <code>display()</code> internally.</p>\n<pre><code>void display();\n</code></pre>\n<p>I would do this:</p>\n<pre><code>void Stack::display(std::ostream&amp; = std::cout);\nfriend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; str, Stack&amp; stack)\n{\n stack.display(str);\n return str;\n}\n</code></pre>\n<hr />\n<pre><code>void push( std::string x ) {\n Stack *newNode = new Stack;\n newNode-&gt;data = x;\n newNode-&gt;link = top;\n top = newNode;\n}\n</code></pre>\n<p>You can simplify this:</p>\n<pre><code>void push( std::string x ) {\n Stack *newNode = new Stack{x, top};\n top = newNode;\n}\n</code></pre>\n<hr />\n<p>Normally I would not add this test.</p>\n<pre><code>void pop() {\n if( top == nullptr ) {\n throw std::runtime_error(&quot;List is empty&quot;);\n }\n</code></pre>\n<p>The user code should alsready by testing with <code>isEmpty()</code> before calling this. If they are not that needs to be found during testing. If you need a checked <code>pop()</code> then add a seprate function.</p>\n<hr />\n<p>Excessive copying:</p>\n<pre><code>std::string peek() {\n Stack *temp = top;\n std::string x = temp-&gt;data; // Copy into temp\n return x; // Copy back to caller\n}\n</code></pre>\n<p>I would simplify to:</p>\n<pre><code>std::string&amp; peek() {\n return temp-&gt;data;\n}\n</code></pre>\n<hr />\n<p>This ultimately works.</p>\n<pre><code>void insertAtBottom( std::string x ) {\n if ( top == nullptr )\n push( x );\n else {\n std::string a = peek( );\n pop( );\n insertAtBottom( x );\n push( a );\n }\n}\n</code></pre>\n<p>But seems a bit complex (as you are modifying all the links).\nWhy not simply find the last item then add the new item.</p>\n<pre><code>void insertAtBottom(std::string const&amp; x)\n{\n if ( top == nullptr ) {\n return push( x );\n }\n Stack* loop = top;\n for(;loop-&gt;link != nullptr; loop = loop-&gt;link) {}\n loop-&gt;link = new Stack{x, null};\n}\n</code></pre>\n<hr />\n<p>Sure.\nBut if you make <code>Stack</code> a class you can store the number of items. This way you don't have to calculate it each time.</p>\n<pre><code>int size() {\n Stack *temp = top;\n int count = 0;\n while( temp != nullptr ) {\n temp = temp-&gt;link;\n ++count;\n }\n return count;\n}\n</code></pre>\n<hr />\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T19:30:44.673", "Id": "494492", "Score": "1", "body": "your insertAtBottom implementation seems great and less expensive" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T18:21:43.547", "Id": "251224", "ParentId": "251167", "Score": "3" } } ]
{ "AcceptedAnswerId": "251169", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T14:15:52.607", "Id": "251167", "Score": "6", "Tags": [ "c++" ], "Title": "Arithmetic Expression evaluator" }
251167
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/251132/231235">A recursive_transform for std::vector with various return type</a>. Thanks to <a href="https://codereview.stackexchange.com/a/251138/231235">G. Sliepen</a> provide further review suggestions. After digging into the topic of achieving a more generic <code>recursive_transform</code> function in both various output type and various container type, I still have no simple solution. However, based on <a href="https://codereview.stackexchange.com/a/251138/231235">G. Sliepen's answer</a>, the case of the <code>std::vector</code>, <code>std::deque</code> and <code>std::list</code> container types may be resolved. I am trying to implement additional another overload <code>recursive_transform</code> function for <code>std::array</code>. Here's my implementation.</p> <pre><code>template&lt;class T, std::size_t S, class F&gt; auto recursive_transform(std::array&lt;T, S&gt;&amp; input, const F&amp; f) { using TransformedValueType = decltype(recursive_transform(*input.cbegin(), f)); std::array&lt;TransformedValueType, S&gt; output; std::transform(input.cbegin(), input.cend(), output.begin(), [f](auto&amp; element) { return recursive_transform(element, f); } ); return output; } </code></pre> <p>The test case of <code>std::array</code>:</p> <pre><code>// std::array&lt;int, 10&gt; -&gt; std::array&lt;std::string, 10&gt; std::array&lt;int, 10&gt; test_array; for (int i = 0; i &lt; 10; i++) { test_array[i] = 1; } auto recursive_transform_result5 = recursive_transform( test_array, [](int x)-&gt;std::string { return std::to_string(x); }); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result5.at(0) &lt;&lt; std::endl; </code></pre> <p><a href="https://godbolt.org/z/qs3b4r" rel="nofollow noreferrer">Here's the Godbolt link</a>. The code in this link including the test cases for <code>std::vector</code>, <code>std::deque</code> and <code>std::list</code>.</p> <p>All suggestions are welcome.</p> <p>The summary information:</p> <ul> <li><p>Which question it is a follow-up to?</p> <p><a href="https://codereview.stackexchange.com/q/251132/231235">A recursive_transform for std::vector with various return type</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <p>The handleable container type in the previous version of <code>recursive_transform</code> function is <code>std:vector</code>. With <a href="https://codereview.stackexchange.com/a/251138/231235">G. Sliepen's answer</a>, this handleable container type list is extended to <code>std::vector</code>, <code>std::deque</code> and <code>std::list</code>. Then, I am trying to deal with <code>std::array</code> here.</p> </li> <li><p>Why a new review is being asked for?</p> <p>In this version of <code>recursive_transform</code> function, it seems that working well in the mentioned test case <code>std::array&lt;int, 10&gt; -&gt; std::array&lt;std::string, 10&gt;</code>. However, there is some issues when it comes to the more complex case like <code>std::array&lt;std::array&lt;int, 10&gt;, 10&gt; -&gt; std::array&lt;std::array&lt;std::string, 10&gt;, 10&gt;</code> (the scalability to be improved!) If there is any suggestion or possible idea about this, please let me know.</p> </li> </ul>
[]
[ { "body": "<h1>Ensure you pass by <code>const</code> reference consistently</h1>\n<p>The main problem with your code was that you didn't make the <code>std::array</code> overload take the input by <code>const</code> reference:</p>\n<pre><code>auto recursive_transform(std::array&lt;T, S&gt;&amp; input, const F&amp; f)\n</code></pre>\n<p>Just add <code>const</code>! See <a href=\"https://godbolt.org/z/n139o1\" rel=\"nofollow noreferrer\">this Godbolt link</a> with the nested <code>std::array</code>s working.</p>\n<h1>Prefer using <code>std::begin()</code> and <code>std::end()</code></h1>\n<p>It doesn't really matter if you only want to support containers from the standard library, but when writing templates, prefer using <a href=\"https://en.cppreference.com/w/cpp/iterator/begin\" rel=\"nofollow noreferrer\"><code>std::begin()</code></a> and <a href=\"https://en.cppreference.com/w/cpp/iterator/end\" rel=\"nofollow noreferrer\"><code>std::end()</code></a> instead of <code>-&gt;begin()</code> and <code>-&gt;end()</code>. The advantage is that if you are using a non-standard container somewhere that doesn't provide <code>begin()</code> and <code>end()</code> member functions, it will still be possible to overload the out-of-class <code>std::begin()</code> and <code>std::end()</code> functions to add iterator support to that class. If you use it in your algorithm templates, then your algorithms will also support those non-standard classes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T20:37:08.477", "Id": "251179", "ParentId": "251171", "Score": "1" } } ]
{ "AcceptedAnswerId": "251179", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T15:52:48.063", "Id": "251171", "Score": "2", "Tags": [ "c++", "array", "lambda", "c++20" ], "Title": "A recursive_transform for std::array with various return type" }
251171
<p>This is my prime sieve based on the Sieve of Eratosthenes.</p> <pre class="lang-py prettyprint-override"><code>import itertools sieve = itertools.count(2) primes = [] nprime = 0 for _ in range(10000): nprime = next(sieve) primes.append(nprime) sieve = filter(eval(f&quot;lambda x: x % {nprime} != 0&quot;), sieve) </code></pre> <p>On my computer this code takes 13.4 seconds to generate 10,000 primes.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T17:22:00.667", "Id": "494383", "Score": "47", "body": "[This is not the sieve of Eratosthenes](https://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T05:42:40.913", "Id": "494419", "Score": "4", "body": "@trentcl: One of my favorite papers, which should be much more widely known." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T18:42:31.977", "Id": "494485", "Score": "1", "body": "You could still use the `lambda` without relying on `eval`; you just need to prebind `nprime` as a defaulted argument: `sieve = filter(lambda x, nprime=nprime: x % nprime != 0, sieve)`. That said, if you need a Python defined function (`def` or `lambda`) to use `filter`, you're better off just using an equivalent listcomp or genexpr (sadly, harder here due to late binding), or finding a way to make it actually use a built-in implemented in C. In this case, you could just do `sieve = filter(nprime.__rmod__, sieve)` with the same effect (given `nprime` and all `sieve` elements are `int`)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T23:06:41.880", "Id": "494501", "Score": "0", "body": "@ShadowRanger Hmm, both lambda with default and `__rmod__` were already in my second answer. And have you tried it with genexpr? When I did, I quickly got a recursion limit error. Not so with `filter`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T23:33:24.557", "Id": "494502", "Score": "0", "body": "Btw, [Computerphile video](https://www.youtube.com/watch?v=5jwV3zxXc8E) where the professor used the same method, and I think that's where I first saw the paper mentioned above (somewhere in the comments)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T00:36:38.090", "Id": "494504", "Score": "0", "body": "@HeapOverflow I think filter is implemented in c (I'm not sure though)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T08:02:12.123", "Id": "494515", "Score": "0", "body": "Great question for the quality of the answers! Now I just need lumpy Cyrenian flour." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T16:43:23.133", "Id": "494556", "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](http://meta.codereview.stackexchange.com/a/1765)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T16:59:50.123", "Id": "494560", "Score": "0", "body": "@Vogel612 I incorporated the code from a suggestion on a comment, not the answer (which later included my approach)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T18:00:40.277", "Id": "494570", "Score": "0", "body": "@Vogel612 Why did you remove their `asmod` version? That was added **before** there were answers. And now people won't know what I'm talking about in my answer that refers to that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-31T11:08:51.900", "Id": "494816", "Score": "0", "body": "@JörgWMittag Excellent paper, indeed. I'm not familiar at all with Haskell. The explanation for the sieve with wheel is very succinct, and every other implementation I've seen is much longer. Is `wheel2357 = 2:4:2:4:6:2:6:4:2:4:6:6:2:6:4:2:6:4:6:8:4:2:4:2:4:8:6:4:6:2:4:6:2:6:6:4:2:4:6:2:6:4:2:4:2:10:2:10:wheel2357;spin (x:xs) n = n : spin xs (n + x);primes = 2 : 3 : 5 : 7 : sieve (spin wheel2357 11)` pseudocode or is it an actual implementation? In Ruby, I tried with just 2 and 4 in the wheel, and the corresponding code was either long or broken." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-31T11:13:00.410", "Id": "494817", "Score": "0", "body": "@EricDuminil: That looks like valid Haskell to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-14T00:01:56.867", "Id": "496529", "Score": "1", "body": "@EricDuminil I guess the Python version would use `itertools` to do `wheel2357 = cycle([2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2, 6, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6, 2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 10, 2, 10])` and `primes = chain([2, 3, 5, 7], sieve(accumulate(wheel2357, initial=11)))`.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-14T07:50:57.567", "Id": "496549", "Score": "0", "body": "@HeapOverflow very interesting and promising! Did you test it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-14T11:07:49.080", "Id": "496557", "Score": "0", "body": "@EricDuminil Well, with `sieve = iter`, `list(takewhile((11**2).__gt__, primes))` correctly produces the primes under \\$11^2\\$. And in my `improved2`, using it instead of `count(2)` works. But I don't have a Python-equivalent of the paper's `sieve` function, as I don't understand Haskell. And I think in my solutions using the paper's idea I can't simply use it instead of `count(2)`. I think I'd have to adapt the marking of future multiples, since the wheel skips some multiples. Didn't think that through yet. My `twostep` version already uses the tiny wheel2, but that was simple to adapt to." } ]
[ { "body": "<p>Bonus points for coming up with something that is both &quot;interesting&quot; and &quot;technically correct&quot;; but that's about where it stops. It's certainly not fast.</p>\n<p>Think about what's happening here: for every single call of <code>eval</code> or <code>asmod</code>, you're chaining another layer of filter - with a new function - on your generator. That simply won't scale. You're better off with the simple approach, having a single data structure that stores your filter. Experiment with a <code>list</code> or <code>array</code> of booleans, or <code>set</code> of integers, to see which one has the best performance.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T17:13:59.077", "Id": "494381", "Score": "0", "body": "How would you write it with list/array/set?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T17:15:36.367", "Id": "494382", "Score": "0", "body": "@HeapOverflow That's such a common question that there's an entire tag dedicated to it: https://codereview.stackexchange.com/questions/tagged/sieve-of-eratosthenes" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T17:30:04.433", "Id": "494384", "Score": "0", "body": "But they're not really doing the sieve of Eratosthenes. I was wondering about your version of their fake one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T17:38:09.423", "Id": "494387", "Score": "0", "body": "@Reinderien I was mostly thinking to make a generator that can go indefinitely, which would not work with a list, array, etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T17:55:22.933", "Id": "494393", "Score": "2", "body": "@jayjayjay It's possible to have a segmented, progressive sieve that can go indefinitely but is still data-structure-based." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T17:01:20.917", "Id": "251176", "ParentId": "251173", "Score": "8" } }, { "body": "<h3>That's not the sieve of Eratosthenes</h3>\n<p>It's rather prime trial division.</p>\n<p>Your filter for 2 lets 1/2 of all numbers through, your filter for 3 lets 2/3 of all remaining numbers through, etc. So <code>1/2 * 2/3 * 4/5 * 6/7 = 22%</code> of all numbers make it through your filters for 2, 3, 5 and 7, so your filter for 11 will have to check 22% of all numbers. The real sieve of Eratosthenes treats 11 by marking off every 11th number, i.e., only 9% of all numbers. Less than half of your percentage. And yours gets worse for the larger primes. For example your filters for the primes from 2 to 89 let ~12% of all numbers through, so your filter for 97 checks ~12% of all numbers. While the real sieve of Eratosthenes treats 97 by marking off only about 1% of all numbers.</p>\n<p>So that's why it's slow. It's doing way too much work.</p>\n<h3>An improvement</h3>\n<p>You can make it a bit faster by not stacking filters but simply doing the trial divisions at the current number, using the primes you're collecting anyway:</p>\n<pre><code>from itertools import count\n\ndef primes(n):\n primes = []\n sieve = (x for x in count(2) if all(x % p for p in primes))\n for _ in range(n):\n primes.append(next(sieve))\n return primes\n</code></pre>\n<p>Or using <code>islice</code>:</p>\n<pre><code>from itertools import count, islice\n\ndef primes(n):\n primes = []\n sieve = (x for x in count(2) if all(x % p for p in primes))\n primes += islice(sieve, n)\n return primes\n</code></pre>\n<p>Demo:</p>\n<pre><code>&gt;&gt;&gt; primes(25)\n[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]\n</code></pre>\n<h3>The real thing</h3>\n<p>But here's a genuine lazy one based on the <a href=\"https://www.cs.hmc.edu/%7Eoneill/papers/Sieve-JFP.pdf\" rel=\"nofollow noreferrer\">paper</a> mentioned by trentcl. I add each prime to the list of its next multiple. When the list of the next <code>x</code> is empty, it's thus a prime. Otherwise, I move the primes from the list to their next multiples.</p>\n<pre><code>from itertools import count\nfrom collections import defaultdict\n\ndef primes(n):\n marked = defaultdict(list)\n primes = []\n for x in count(2):\n if x in marked:\n for p in marked.pop(x):\n marked[x + p].append(p)\n else:\n primes.append(x)\n if len(primes) == n:\n return primes\n marked[x * x].append(x)\n</code></pre>\n<h3>Benchmark 1</h3>\n<p>Times for <code>n = 10000</code> (benchmark code at the end of the answer):</p>\n<pre><code>9.330 s original\n3.502 s improved1\n3.499 s improved2\n0.065 s genuine\n</code></pre>\n<p>That said, your original and my improved version can be made much faster by using fewer filters (only up to the square root of the current number), as I've done in my <a href=\"https://codereview.stackexchange.com/a/251209/219610\">later answer</a>.</p>\n<h3>To infinity and beyond</h3>\n<p>As <a href=\"https://codereview.stackexchange.com/questions/251173/why-is-my-sieve-of-eratosthenes-using-generators-so-slow/251178?noredirect=1#comment494578_251178\">Eric Duminil showed</a>, it's trivial to make the latter an infinite generator, which also makes it shorter. No need to build a result list and check whether you're done, just yield the primes:</p>\n<p><strong>infinite:</strong></p>\n<pre><code>def primes():\n marked = defaultdict(list)\n for x in count(2):\n if x in marked:\n for p in marked.pop(x):\n marked[x + p].append(p)\n else:\n yield x\n marked[x * x].append(x)\n</code></pre>\n<p>The other solutions can similarly be turned into infinite generators, but meh, they're no good anyway. Plus in my <code>improved1</code> and <code>improved2</code>, the <code>primes</code> list is not just the result but is also used for filtering, so I need to build it anyway.</p>\n<p>As infinite generator, it's more versatile. You can still get a list of the first n if you want to:</p>\n<pre><code>&gt;&gt;&gt; list(islice(primes(), 20))\n[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]\n</code></pre>\n<p>You can also get all primes up to a desired limit:</p>\n<pre><code>&gt;&gt;&gt; *itertools.takewhile(72 .__gt__, primes()),\n(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71)\n</code></pre>\n<p>Or if you neither know how many you need nor how big you need but you need &quot;enough&quot; somehow, for example enough so that their product exceeds a million:</p>\n<pre><code>&gt;&gt;&gt; result, product = [], 1\n&gt;&gt;&gt; it = primes()\n&gt;&gt;&gt; while product &lt; 10**6:\n p = next(it)\n result.append(p)\n product *= p\n\n&gt;&gt;&gt; result\n[2, 3, 5, 7, 11, 13, 17, 19]\n</code></pre>\n<p>Or if you just want the millionth prime:</p>\n<pre><code>&gt;&gt;&gt; next(islice(primes(), 999999, None))\n15485863\n</code></pre>\n<p>Or if you have a prime and want to know the &quot;how manyth&quot; prime it is:</p>\n<pre><code>&gt;&gt;&gt; from operator import indexOf\n&gt;&gt;&gt; indexOf(primes(), 15485863) + 1\n1000000\n</code></pre>\n<p>Or if you have a prime and want to know the next larger one (granted, there are more efficient ways to do that):</p>\n<pre><code>&gt;&gt;&gt; it = primes()\n&gt;&gt;&gt; 89 in it and next(it)\n97\n</code></pre>\n<p>Note that in the last few cases, you don't want a list of primes at all, so building one is wasted memory.</p>\n<p>Speaking of memory, though... the generator (and also my version) do take a lot of memory. Here are memory measurements and benchmarks for up to n=1,000,000 for the above &quot;infinite&quot; solution and the solutions I'll show below:</p>\n<pre><code> | time for the first... | tracemalloc for 1,000,000\n | 10,000 100,000 1,000,000 | size peak\n------------+------------------------------+--------------------------\n infinite | 0.068 s 0.971 s 12.450 s | 231,866,275 312,793,599\n no_lists | 0.035 s 0.574 s 8.065 s | 143,870,959 226,554,527\n lazier | 0.033 s 0.456 s 6.016 s | 36,500,174 36,535,742\n recursive | 0.032 s 0.473 s 6.116 s | 72,169 109,109\n twostep | 0.015 s 0.217 s 2.897 s | 71,986 108,926\n</code></pre>\n<p>The memory usage was measured like this:</p>\n<pre><code>import tracemalloc\ntracemalloc.start()\nit = primes()\nprime = next(islice(it, 9999999, None))\nsize, peak = tracemalloc.get_traced_memory()\n</code></pre>\n<p>So the above &quot;infinite&quot; solution takes hundreds of megabytes to generate the first million primes, i.e., hundreds of bytes per prime. Quite a lot. Let's see why, by doing <code>global marked</code> first thing in the <code>primes()</code> function so we can inspect it afterwards. We'll see that almost a million composites are marked and the dictionary takes 84 MB:</p>\n<pre><code>&gt;&gt;&gt; it = primes()\n&gt;&gt;&gt; next(islice(it, 999999, None))\n15485863\n&gt;&gt;&gt; from sys import getsizeof\n&gt;&gt;&gt; len(marked), getsizeof(marked)\n(999919, 83886176)\n</code></pre>\n<p>The lists of primes total 88 MB, and almost all of them contain only a single prime marking the composite:</p>\n<pre><code>&gt;&gt;&gt; sum(map(getsizeof, marked.values()))\n87992872\n&gt;&gt;&gt; from collections import Counter\n&gt;&gt;&gt; Counter(map(len, marked.values()))\nCounter({1: 999845, 2: 69, 3: 4, 4: 1})\n</code></pre>\n<p>The marked composites take 32 MB and the marking primes take 28 MB:</p>\n<pre><code>&gt;&gt;&gt; sum(map(getsizeof, marked))\n31983680\n&gt;&gt;&gt; from itertools import chain\n&gt;&gt;&gt; sum(map(getsizeof, chain.from_iterable(marked.values())))\n27999972\n</code></pre>\n<p>Together that's indeed 232 MB as reported by tracemalloc in the table above:</p>\n<pre><code>&gt;&gt;&gt; 84 + 88 + 32 + 28\n232\n</code></pre>\n<p>Since most lists of marking primes just contain a single prime anyway, let's store only the <em>first</em> prime at the composite. If more primes want to mark that composite, then instead move them ahead to their <em>next</em> multiple:</p>\n<p><strong>no_lists</strong>:</p>\n<pre><code>def primes():\n marked = {}\n for x in count(2):\n if x in marked:\n p = marked.pop(x)\n while (x := x + p) in marked:\n pass\n marked[x] = p\n else:\n yield x\n marked[x * x] = x\n</code></pre>\n<p>As the above table showed, this made it faster and saved a lot of memory.</p>\n<p>In my other answer, I showed that prematurely setting <code>marked[x * x]</code> as soon as you discover a new prime <code>x</code> is wasteful. Let's rewrite the better version from there as an infinite generator as well. Here <code>m</code> is the next marking prime, and it will start marking as soon as we reach <code>m2</code>=<code>m</code><sup>2</sup>.</p>\n<p><strong>lazier:</strong></p>\n<pre><code>def primes():\n yield 2\n primes = [2]\n markers = iter(primes)\n marked = {}\n m = next(markers)\n m2 = m * m\n for x in count(3):\n if x == m2:\n while (x := x + m) in marked:\n pass\n marked[x] = m\n m = next(markers)\n m2 = m * m\n elif x in marked:\n p = marked.pop(x)\n while (x := x + p) in marked:\n pass\n marked[x] = p\n else:\n yield x\n primes.append(x)\n</code></pre>\n<p>This brought it down to under 37 MB, as <code>marked</code> got <em>much</em> smaller. However, it creates a <code>primes</code> <em>list</em> again, in order to update <code>m</code> to the next next marking prime.</p>\n<p>Can we get the best of both worlds? <em>Not</em> prematurely enter <code>marked[x * x]</code> <em>and not</em> build a <code>primes</code> list? Yes we can!</p>\n<p>What do we use the primes list for? Just as a more slowly used stream of primes. But that's what we're writing! A generator of primes. So we can use it recursively. Our main generator iterator of primes will use a slower generator iterator of primes. But where does that slower one get its marker primes from? From yet another even more slowly progressing one, if needed. And so on. A potentially infinite stack of infinite iterators.</p>\n<p><strong>recursive:</strong></p>\n<p>(also see the addendum at the end of the answer for better versions of this)</p>\n<pre><code>def primes():\n yield 2\n marked = {}\n markers = primes()\n m = next(markers)\n m2 = m * m\n for x in count(3):\n if x == m2:\n while (x := x + m) in marked:\n pass\n marked[x] = m\n m = next(markers)\n m2 = m * m\n elif x in marked:\n p = marked.pop(x)\n while (x := x + p) in marked:\n pass\n marked[x] = p\n else:\n yield x\n</code></pre>\n<p>Let's see the levels by storing each iterator's <code>marked</code> in a global <code>levels</code> list by doing <code>levels.append(marked)</code> right after <code>marked = {}</code>. Then:</p>\n<pre><code>&gt;&gt;&gt; levels = []\n&gt;&gt;&gt; millionth = next(islice(primes(), 999999, None))\n&gt;&gt;&gt; for marked in levels:\n print(len(marked), max(marked.values()))\n\n546 3931\n18 61\n4 7\n2 3\n1 2\n</code></pre>\n<p>We see that there are five levels of iterators. The top-level iterator, the one we're using directly, has 546 marking primes, the largest being 3931. That makes sense, as the next larger prime is 3943, which starts marking at 3943<sup>2</sup>, which is larger than the millionth prime:</p>\n<pre><code>&gt;&gt;&gt; it = primes()\n&gt;&gt;&gt; 3931 in it and next(it)\n3943\n&gt;&gt;&gt; 3943**2\n15547249\n&gt;&gt;&gt; millionth\n15485863\n</code></pre>\n<p>The next-lower level so far only needed to yield the 18 primes up to 61. Which is correct, as the next-larger prime 67 will only start marking at 67<sup>2</sup>=4489, well above the prime 3943 needed next by the top-level iterator. And so on, until the fifth and lowest level only needed its initial <code>yield 2</code> so far.</p>\n<p>With only a few hundred primes in all levels combined, it's no wonder this solution takes faaar less memory than our first &quot;infinite&quot; one, about 3000 times less, only around 100 KB. And its advantage will increase for larger numbers of primes, as the earlier solutions need O(n) memory while the recursive ones take something like O(sqrt(n)) memory (not sure how the density of primes affects it).</p>\n<p>Last but not least, here's a little variation where I handle the prime 2 separately and then move everything twice as fast, which makes the overall solution about twice as fast (again see the table above):</p>\n<p><strong>twostep</strong>:</p>\n<pre><code>def primes():\n yield 2\n yield 3\n marked = {}\n markers = primes()\n next(markers)\n m = next(markers)\n m2 = m * m\n for x in count(5, 2):\n if x == m2:\n marked[m2 + 2*m] = 2*m\n m = next(markers)\n m2 = m * m\n elif x in marked:\n step = marked.pop(x)\n while (x := x + step) in marked:\n pass\n marked[x] = step\n else:\n yield x\n</code></pre>\n<p>Code for benchmark 1:</p>\n<pre><code>from timeit import repeat\nfrom itertools import count, islice\nfrom collections import defaultdict\n\ndef original(n):\n sieve = count(2)\n primes = []\n nprime = 0\n for _ in range(n):\n nprime = next(sieve)\n primes.append(nprime)\n sieve = filter(eval(f&quot;lambda x: x % {nprime} != 0&quot;), sieve)\n return primes\n\ndef improved1(n):\n primes = []\n sieve = (x for x in count(2) if all(x % p for p in primes))\n for _ in range(n):\n primes.append(next(sieve))\n return primes\n\ndef improved2(n):\n primes = []\n sieve = (x for x in count(2) if all(x % p for p in primes))\n primes += islice(sieve, n)\n return primes\n\ndef genuine(n):\n marked = defaultdict(list)\n primes = []\n for x in count(2):\n if x in marked:\n for p in marked.pop(x):\n marked[x + p].append(p)\n else:\n primes.append(x)\n if len(primes) == n:\n return primes\n marked[x * x].append(x)\n\nfuncs = original, improved1, improved2, genuine\n\nn = 10000\n\nexpect = funcs[0](n)\nfor func in funcs[1:]:\n print(func(n) == expect, func.__name__)\n\nfor _ in range(3):\n for func in funcs:\n t = min(repeat(lambda: func(n), number=1))\n print('%.3f s ' % t, func.__name__)\n print()\n</code></pre>\n<h3>Addendum - better recursive generators</h3>\n<p>I came up with a nicer way later, don't want to rewrite the answer using this now but want to share. This goes through the primes of the underlying generator in an outer loop and from one prime's square to the next prime's square in an inner loop. It's less code and makes the structure of the procedure clearer.</p>\n<pre><code>def primes():\n yield 2\n marks = {}\n i = 2\n for p in primes():\n for i in range(i+1, p*p):\n if i not in marks:\n yield i\n else:\n m = marks.pop(i)\n j = i + m\n while j in marks:\n j += m\n marks[j] = m\n marks[p*p] = p\n</code></pre>\n<p>And a version with the paper's way of potentially storing several primes at the same common multiple:</p>\n<pre><code>def primes():\n yield 2\n marks = defaultdict(set)\n i = 2\n for p in primes():\n for i in range(i+1, p*p):\n if i not in marks:\n yield i\n else:\n for m in marks.pop(i):\n marks[i+m].add(m)\n marks[p*p] = {p}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T14:03:31.423", "Id": "494537", "Score": "0", "body": "To be clear, the first improvement is converting the algorithm from recursion to iteration, avoiding the overhead of calling all the lambdas, the actual test operations are the same. I feel like the phrasing isn't super clear since \"lets 2/3 of all numbers through\" can suggest that 6 would be checked by filter_2 AND filter_3 rather than being ejected at the filter_2 test. I had to re-read a couple of times to twig that you describe each filter in isolation then show the result of stacking them. Really, it's more of a grammar complaint than anything." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T15:22:47.130", "Id": "494544", "Score": "0", "body": "@Kaithar Yes, the operations are the same. Just instead of stacked filters that filter on their own, I use the corresponding primes and filter with the `all(...)`. About \"lets 2/3 of all numbers through\": It's both in isolation and in combination. If you use filter_3 on all integers, then every third integer gets filtered out. If you use filter_3 on what filter_2 let through (i.e., odd integers), then filter_3 also removes every third number (i.e. 3 but not 5 or 7, then 9 but not 11 or 13, then 15 but not 17 or 19, etc). For filter_5 it's less regular, but it still lets 4 out of 5 numbers ..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T15:23:07.810", "Id": "494545", "Score": "0", "body": "... through. Try `len([i for i in range(30, 60) if i%2 and i%3])`, it'll tell you that 10 of the 30 numbers made it through filter_2 and filter_3. Then try `len([i for i in range(30, 60) if i%2 and i%3 and i%5])`, it'll tell you that only 8 remain after including filter_5. And 8/10 is 4/5. And you get the same counts 10 and 8 for any 30 consecutive integers, as 30=2*3*5 and thus any block of 30 consecutive integers gets filtered equally by those three filters." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T16:23:21.780", "Id": "494553", "Score": "1", "body": "That's what I mean by changing it from recursive to iterative. The way I double checked the percents was the opposite way... since 1/3rd of multiples of 2 are multiples of 3 (obviously), the proportion of multiples in the removed and remaining is the same, thus each filter is independent of its predecessors if the input set is uniform. But like I said, it's purely the pedantic difference between implicit \"tests all numbers\" and explicit \"tests remaining numbers\". What's really important is how elegant the marking-next-square approach to the genuine really is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T18:17:26.510", "Id": "494575", "Score": "0", "body": "Excellent answer. Note that your \"real thing\" isn't the real Sieve of Eratosthenes: it's better! The Sieve finds all the primes up to n. The updated version described in the paper, which you implemented, finds the n first primes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T18:30:23.283", "Id": "494578", "Score": "1", "body": "As a bonus, you can easily convert it to an infinite prime generator : https://tio.run/##bY/NasMwEITveoqBYiI1JiTNLZB36L2UYqx1u1SWFlkBpS/v@ie1E@jepG9mdlau6Sv4Y983MbTgRDGF4DpwKyEm1OHik5pYHZyjOnHwC7XUVBeXLNdJqeGByrkPidxSp81JYZi2it9kcb7XasddMhNuQkQG@3mRfrm5xuFmJnPC@v9nkxXuJIjO5lGzbn/L2ELed5UIeavFLDpyHT26rkzOIqt/U56Rl5RslJpqlOCxyQ@Lvj@/RKz8J@nDfm9uzQY03Lh5HRV4Ko4WJxR2gwKat4cSYozq@18" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-31T13:22:01.760", "Id": "494831", "Score": "0", "body": "@EricDuminil I'll see your infinite generator and raise you **infinitely many** (see the whole added section \"To infinity and beyond\")." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-31T14:19:18.823", "Id": "494832", "Score": "0", "body": "@HeapOverflow Truly excellent answer. Congrats." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-01T11:24:59.040", "Id": "494921", "Score": "0", "body": "Just curious: did you try to integrate the wheel described in the paper?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-01T11:32:50.870", "Id": "494923", "Score": "1", "body": "@EricDuminil I didn't read that part of the paper, partly because I don't understand Haskell so at some point didn't understand anymore what they're saying. I did try a mini-wheel with just 2 and 3 and I considered a larger wheel, but then felt like the solutions grew complicated enough already. That said, I found another improvement that made it a bit faster and simpler, so maybe I'll try to incorporate a wheel with that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-01T19:22:21.507", "Id": "494986", "Score": "0", "body": "@HeapOverflow: Interesting! I cannot read Haskell either, and the implementation in the paper seems really concise to anything else I've seen in Ruby or Python." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-09T22:00:35.747", "Id": "507402", "Score": "1", "body": "@EricDuminil Didn't manage to incorporate larger wheels, but added the improved version(s) at the end now." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T18:57:37.217", "Id": "251178", "ParentId": "251173", "Score": "38" } }, { "body": "<h3>Back to the roots - be lazier!</h3>\n<p>(Taking this in another direction than my first answer, and it's different/long enough that I don't want to mix them.)</p>\n<p>We can vastly improve your approach by not eagerly adding filters and instead only adding filters up to the square root of the current candidate number. And I found an in my opinion neat way to do that. Benchmark results:</p>\n<pre><code> n: 10,000 100,000 1,000,000 2,000,000 \n original_rooted_eval 0.075 s 2.036 s 59.669 s 162.764 s \n original_rooted_asmod 0.081 s 2.128 s 56.001 s 151.860 s \n original_rooted_default1 0.082 s 2.095 s 56.286 s 151.667 s \n original_rooted_default2 0.075 s 1.895 s 50.088 s 134.353 s \n original_rooted_rmod 0.041 s 1.050 s 28.101 s 75.745 s \n improved_rooted 0.033 s 0.806 s 21.825 s 55.485 s \n genuine_rooted 0.060 s 0.799 s 10.073 s 21.809 s \n genuine 0.073 s 0.952 s 12.662 s 27.009 s \n</code></pre>\n<p>At n=10,000, this makes your original and improved versions about as fast or even up to twice as fast as my genuine sieve of Eratosthenes version. That's about a hundred times faster than they were before. But at n=1,000,000, the genuine one has already turned the table.</p>\n<p>As the <a href=\"https://www.cs.hmc.edu/%7Eoneill/papers/Sieve-JFP.pdf\" rel=\"noreferrer\">paper</a> also points out, part of the slowness (much of it) comes from doing trial division with <em>all</em> primes lower than the current candidate number. It's similar to this single-number primality check:</p>\n<pre><code>def is_prime(x):\n return all(x % d for d in range(2, x))\n</code></pre>\n<p>We should instead only try the primes up the the square root of the candidate. If candidate <span class=\"math-container\">\\$x\\$</span> had a divisor <span class=\"math-container\">\\$d&gt;\\sqrt{x}\\$</span>, then e=<span class=\"math-container\">\\$\\frac{x}{d}&lt;\\sqrt{x}\\$</span> would be another divisor, and we would've already found it below <span class=\"math-container\">\\$\\sqrt{x}\\$</span>.</p>\n<pre><code>def is_prime(x):\n return x &gt;= 2 and all(x % d for d in range(2, isqrt(x)+1))\n</code></pre>\n<p>Now how do we do that in our solutions? In your <code>original</code>, it means only creating the filters up to the square root of the current number. In my <code>improved</code>, it means not going through all <code>primes</code> but only to the square root. So: start filtering for 2 when you're at 4, start filtering for 3 when you're at 9, start filtering for 5 when you're at 25, etc. For this, keep track of the next prime square (i.e., 4, 9, 25, etc) and the index <code>i</code> of that prime in <code>primes</code>. Whenever you reach the next prime square, <em>don't</em> count it as prime but instead add the next filter.</p>\n<p><strong>Rooting yours:</strong></p>\n<pre><code>def original_rooted_eval(n):\n sieve = count(2)\n primes = []\n next_prime_square, i = 4, 0\n for _ in range(n):\n while (nprime := next(sieve)) == next_prime_square:\n sieve = filter(eval(f&quot;lambda x: x % {primes[i]} != 0&quot;), sieve)\n i += 1\n next_prime_square = primes[i] ** 2\n primes.append(nprime)\n return primes\n</code></pre>\n<p>Or with your <code>asmod</code>:</p>\n<pre><code> sieve = filter(asmod(primes[i]), sieve)\n</code></pre>\n<p>Or with a <code>lambda</code> with default argument:</p>\n<pre><code> sieve = filter(lambda x, p=primes[i]: x % p != 0, sieve)\n</code></pre>\n<p>And btw the <code>!= 0</code> isn't necessary and only slows it down. We can just use the truth of the remainder:</p>\n<pre><code> sieve = filter(lambda x, p=primes[i]: x % p, sieve)\n</code></pre>\n<p>And now it's obvious that we can simply use the prime's right-side modulo method:</p>\n<pre><code> sieve = filter(primes[i].__rmod__, sieve)\n</code></pre>\n<p>That's all the different versions of your original that you see in the benchmark results above.</p>\n<p><strong>Rooting my improvement:</strong></p>\n<p>I could've kept <code>for p in primes</code> and added some <code>if p*p &gt; x: break</code>, but that would be an extra cost at every innermost iteration. So instead I build an extra list of already filtering primes:</p>\n<pre><code>def improved_rooted(n):\n primes = []\n filters = []\n next_prime_square, i = 4, 0\n for x in count(2):\n if x == next_prime_square:\n filters.append(primes[i])\n i += 1\n next_prime_square = primes[i] ** 2\n else:\n for p in filters:\n if not x % p:\n break\n else:\n primes.append(x)\n if len(primes) == n:\n return primes\n</code></pre>\n<p><strong>Rooting <code>genuine</code>:</strong></p>\n<p>My <code>genuine</code> already added a new prime <span class=\"math-container\">\\$x\\$</span> into <code>marked[x * x]</code> so that it won't start filtering until <span class=\"math-container\">\\$x^2\\$</span> is reached. So in that sense, <code>genuine</code> is already rooted. But if we never go as far as <span class=\"math-container\">\\$x^2\\$</span>, then even that is wasted. So delay putting it into <code>marked</code> at all until its square is reached. And then put it into its <em>next</em> multiple, <code>x + primes[i]</code> (where that <code>x</code> is now the <em>square</em> of the original, which is <code>primes[i]</code>, so that's really <code>primes[i]**2 + primes[i]</code>).</p>\n<pre><code>def genuine_rooted(n):\n primes = []\n marked = defaultdict(list)\n next_prime_square, i = 4, 0 \n for x in count(2):\n if x == next_prime_square:\n marked[x + primes[i]].append(primes[i])\n i += 1\n next_prime_square = primes[i] ** 2\n elif x in marked:\n for p in marked.pop(x):\n marked[x + p].append(p)\n else:\n primes.append(x)\n if len(primes) == n:\n return primes\n</code></pre>\n<p>Benchmark code including full solutions:</p>\n<pre><code>from timeit import timeit\nfrom itertools import count\nfrom collections import defaultdict\nfrom math import isqrt\n\ndef original_rooted_eval(n):\n sieve = count(2)\n primes = []\n next_prime_square, i = 4, 0\n for _ in range(n):\n while (nprime := next(sieve)) == next_prime_square:\n sieve = filter(eval(f&quot;lambda x: x % {primes[i]} != 0&quot;), sieve)\n i += 1\n next_prime_square = primes[i] ** 2\n primes.append(nprime)\n return primes\n\ndef original_rooted_asmod(n):\n sieve = count(2)\n primes = []\n next_prime_square, i = 4, 0\n def asmod(a):\n def inner(x):\n return x % a != 0\n return inner\n for _ in range(n):\n while (nprime := next(sieve)) == next_prime_square:\n sieve = filter(asmod(primes[i]), sieve)\n i += 1\n next_prime_square = primes[i] ** 2\n primes.append(nprime)\n return primes\n\ndef original_rooted_default1(n):\n sieve = count(2)\n primes = []\n next_prime_square, i = 4, 0\n for _ in range(n):\n while (nprime := next(sieve)) == next_prime_square:\n sieve = filter(lambda x, p=primes[i]: x % p != 0, sieve)\n i += 1\n next_prime_square = primes[i] ** 2\n primes.append(nprime)\n return primes\n\ndef original_rooted_default2(n):\n sieve = count(2)\n primes = []\n next_prime_square, i = 4, 0\n for _ in range(n):\n while (nprime := next(sieve)) == next_prime_square:\n sieve = filter(lambda x, p=primes[i]: x % p, sieve)\n i += 1\n next_prime_square = primes[i] ** 2\n primes.append(nprime)\n return primes\n\ndef original_rooted_rmod(n):\n sieve = count(2)\n primes = []\n next_prime_square, i = 4, 0\n for _ in range(n):\n while (nprime := next(sieve)) == next_prime_square:\n sieve = filter(primes[i].__rmod__, sieve)\n i += 1\n next_prime_square = primes[i] ** 2\n primes.append(nprime)\n return primes\n\ndef improved_rooted(n):\n primes = []\n filters = []\n next_prime_square, i = 4, 0\n for x in count(2):\n if x == next_prime_square:\n filters.append(primes[i])\n i += 1\n next_prime_square = primes[i] ** 2\n else:\n for p in filters:\n if not x % p:\n break\n else:\n primes.append(x)\n if len(primes) == n:\n return primes\n\ndef genuine_rooted(n):\n primes = []\n marked = defaultdict(list)\n next_prime_square, i = 4, 0 \n for x in count(2):\n if x == next_prime_square:\n marked[x + primes[i]].append(primes[i])\n i += 1\n next_prime_square = primes[i] ** 2\n elif x in marked:\n for p in marked.pop(x):\n marked[x + p].append(p)\n else:\n primes.append(x)\n if len(primes) == n:\n return primes\n\ndef genuine(n):\n marked = defaultdict(list)\n primes = []\n for x in count(2):\n if x in marked:\n for p in marked.pop(x):\n marked[x + p].append(p)\n else:\n primes.append(x)\n if len(primes) == n:\n return primes\n marked[x * x].append(x)\n\nfuncs = [\n original_rooted_eval,\n original_rooted_asmod,\n original_rooted_default1,\n original_rooted_default2,\n original_rooted_rmod,\n improved_rooted,\n genuine_rooted,\n genuine,\n ]\n\n# Correctness check\nn = 10**4\nexpect = funcs[0](n)\nfor func in funcs[1:]:\n print(func(n) == expect, func.__name__)\nprint()\n\nwidth = max(len(func.__name__) for func in funcs) + 2\n\nsizes = 10**4, 10**5, 10**6, 2 * 10**6\nrounds = 5\n\n# tss[s][f] := list of times for size #s and function #f.\ntsss = []\nfor n in sizes:\n tss = [[] for _ in funcs]\n tsss.append(tss)\n for r in range(rounds):\n print(f'{n=:,} round={r+1}/{rounds}')\n for func, ts in zip(funcs, tss):\n # t = n / 1e5 # fake for faster development\n t = timeit(lambda: func(n), number=1)\n ts.append(t)\n # print(func.__name__, t) # Show results as they happen\n print('n:'.rjust(width), *(f'{n:8,} ' for n in sizes))\n for f, func in enumerate(funcs):\n print(func.__name__.rjust(width), end=' ')\n for tss in tsss:\n print(' %.3f s ' % min(tss[f]), end='')\n print()\n print()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T14:34:33.997", "Id": "251209", "ParentId": "251173", "Score": "13" } }, { "body": "<p>&quot;Purist&quot; in me says that any solution which is not starting with building finite table of numbers is not sieve of Eratosthenes, as well as any solutions which don't keep all information (numbers, cross-offs) in one table (datastructure).</p>\n<p>Why? Back in Eratosthenes days he had to create table, after he finished creating table he started crossing off numbers (not\ndeleting them from table). End result was the same table except non-primes (while present) were 'crossed off'.</p>\n<p>Keeping this interpretation in mind following is more akin representation of operations Eratosthenes made:</p>\n<ul>\n<li>create finite 'table'. For that abstraction one can use np.array. It will be one row one column table where array values represent 'cross off' and indices represent numbers. In initial state all numbers are not crossed off i.e. True:</li>\n</ul>\n<pre><code>sieve = np.ones(max_value + 1, dtype=np.bool)\n</code></pre>\n<ul>\n<li>'cross off' numbers until first prime (2) by setting values to 'False'</li>\n</ul>\n<pre><code>sieve[:2] = False\n</code></pre>\n<ul>\n<li>go through all numbers starting from first prime (2) up to integer part of square root + 1, if number is not 'crossed off' (i.e value of corresponding index is True),\n'cross off' numbers starting of square of number with step of number.</li>\n</ul>\n<pre><code>for i in range(2, isqrt(max_value)+1): \n if sieve[i]:\n sieve[i*i::i] = False\n</code></pre>\n<p>We have 'table' where indices which are 'crossed off' have value False and all 'non-crossed off' indices values are True.</p>\n<p>For me this way is more mimicking paper-and-pencil (or clay and stylus) counterpart of original sieve of Eratosthenes (your mileage may vary). As simple function:</p>\n<pre><code>import numpy as np\nfrom math import isqrt\n\n\ndef primes(max_value):\n sieve = np.ones(max_value + 1, dtype=np.bool)\n sieve[:2] = False\n for i in range(2, isqrt(max_value)+1): \n if sieve[i]:\n sieve[i*i::i] = False\n return np.nonzero(sieve)[0] # return only primes\n\n</code></pre>\n<p>And now something completely different: on holy page of Life, Universe and Everything else (python.org) there is <a href=\"https://wiki.python.org/moin/SimplePrograms\" rel=\"nofollow noreferrer\">SimplePrograms</a>: &quot;20 lines: Prime numbers sieve w/fancy generators&quot;:</p>\n<pre><code>import itertools\n\ndef iter_primes():\n # an iterator of all numbers between 2 and +infinity\n numbers = itertools.count(2)\n\n # generate primes forever\n while True:\n # get the first number from the iterator (always a prime)\n prime = next(numbers)\n yield prime\n\n # this code iteratively builds up a chain of\n # filters...slightly tricky, but ponder it a bit\n numbers = filter(prime.__rmod__, numbers)\n\nfor p in iter_primes():\n if p &gt; 1000:\n break\n print (p)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-02T12:52:01.580", "Id": "251473", "ParentId": "251173", "Score": "0" } } ]
{ "AcceptedAnswerId": "251178", "CommentCount": "15", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T16:26:01.907", "Id": "251173", "Score": "21", "Tags": [ "python", "primes", "sieve-of-eratosthenes" ], "Title": "Why is my Sieve of Eratosthenes using generators so slow" }
251173
<p>Bit of a pointless program (at the moment). It's intended more as practice for myself rather than anything else.</p> <p>General idea is that you add details of a particular cat or dog, and it'll update a TreeView. A dog or cat can then be removed based on their assigned number.</p> <p>Many thing I wasn't too sure on when creating this, such as best practices for creating a new form, accessing a class's parent attributes, and just general structure.</p> <p>There's a lot more I want to add here (e.g. filters) - however I worry I'm repeating myself a lot throughout the code, and hardcoding things too much. The more functionality I try to add, the messier it seems to get.</p> <pre><code>import tkinter as tk from tkinter import ttk class App(tk.Frame): def __init__(self, master = None): self.master = master self.my_storage = Storage() # Setup Frames. self.f1 = ttk.Frame(self.master) self.f2 = ttk.Frame(self.master, padding = (10, 10, 10, 10)) self.f1.pack(fill = tk.X) self.f2.pack(fill = tk.BOTH, expand = True) # Setup GUI widgets. self.widgets() def widgets(self): # Setup Tree widget to store animal objects. self.tree = ttk.Treeview(self.f2) headings = [&quot;Type&quot;, &quot;Name&quot;, &quot;Breed&quot;, &quot;Colour&quot;, &quot;Size&quot;, &quot;Bark&quot;, &quot;Aggression&quot;, &quot;Cuteness&quot;] self.tree[&quot;columns&quot;] = (0, 1, 2, 3, 4, 5, 6, 7) self.tree.column(&quot;#0&quot;, width = 45) self.tree.heading(&quot;#0&quot;, text = &quot;No.&quot;) for index in range(len(headings)): self.tree.column(index, width = 110) self.tree.heading(index, text = headings[index]) # Setup Buttons and Entry widgets. self.position = tk.IntVar() self.add_dog = ttk.Button(self.f1, text = &quot;Add Dog&quot;, command = lambda: self.add_window(&quot;Dog&quot;)) self.add_cat = ttk.Button(self.f1, text = &quot;Add Cat&quot;, command = lambda: self.add_window(&quot;Cat&quot;)) self.remove_animal = ttk.Button(self.f1, text = &quot;Remove by ID&quot;, command = self.remove_animal) self.remove_animal_pos = ttk.Entry(self.f1, textvariable = self.position, width = 3) # Add Widgets to GUI. self.add_dog.pack(side = tk.LEFT) self.add_cat.pack(side = tk.LEFT) self.remove_animal.pack(side = tk.LEFT) self.remove_animal_pos.pack(side = tk.LEFT) self.tree.pack(expand = True, fill = tk.BOTH) # Remove entry from library based on it's index / No def remove_animal(self): self.my_storage.remove_animal(self.position.get()) self.update_tree() # Update the tree with the latest version of our storage list. def update_tree(self): self.tree.delete(*self.tree.get_children()) for i, x in enumerate(self.my_storage.storage): obj_type = x.__class__.__name__ if obj_type == &quot;Dog&quot;: self.tree.insert(&quot;&quot;, &quot;end&quot;, text = i, values = (obj_type, x.name, x.breed, x.colour, x.size, x.bark_sound, &quot;n/a&quot;, &quot;n/a&quot;)) else: self.tree.insert(&quot;&quot;, &quot;end&quot;, text = i, values = (obj_type, x.name, x.breed, x.colour, x.size, &quot;n/a&quot;, x.aggression, x.cuteness)) # Add a new window which allows us to input paramaters for our animal objects. def add_window(self, type_of_animal): self.window = tk.Toplevel(self.master) AddAnimal(self.window, type_of_animal, self.my_storage, self.tree) class AddAnimal(App): def __init__(self, master, type_of_animal, my_storage, my_tree): self.tree = my_tree self.my_storage = my_storage self.master = master self.type_of_animal = type_of_animal self.widgets() def widgets(self): # Set titles depending on type of animal we're adding. if self.type_of_animal == &quot;Dog&quot;: self.titles = [&quot;Name&quot;, &quot;Breed&quot;, &quot;Colour&quot;, &quot;Size&quot;, &quot;Bark Sound&quot;] else: self.titles = [&quot;Name&quot;, &quot;Breed&quot;, &quot;Colour&quot;, &quot;Size&quot;, &quot;Aggression&quot;, &quot;Cuteness&quot;] # From titles, create the relevant entry boxes and labels. self.entries = {} for x in self.titles: frame = tk.Frame(self.master) frame.pack(side = &quot;top&quot;, fill = &quot;x&quot;) label = tk.Label(frame, width = 20, text = x, anchor = 'w') entry = tk.Entry(frame) label.pack(side = &quot;left&quot;) entry.pack(side = &quot;right&quot;, expand = True, fill = &quot;x&quot;) self.entries[x] = entry self.add_bttn = tk.Button(self.master, text = &quot;Add&quot;, command = lambda: self.add_to_tree(self.titles)) self.add_bttn.pack() def add_to_tree(self, fields): # Store all entry values in list. lis = [self.entries[title].get() for title in self.titles] # Depending on type of animal, create new animal object with relevant entry values. if self.type_of_animal == &quot;Dog&quot;: name = lis[0]; breed = lis[1]; colour = lis[2]; size = lis[3]; bark_sound = lis[4]; obj = Dog(name, breed, colour, size, bark_sound) else: name = lis[0]; breed = lis[1]; colour = lis[2]; size = lis[3]; aggression = lis[4]; cuteness = lis[5] obj = Cat(name, breed, colour, size, aggression, cuteness) # Add object to our strorage list, update the tree with this list, and clos form. self.my_storage.add_animal(obj) self.update_tree() self.master.destroy() class Storage: def __init__(self): self.storage = [] def add_animal(self, animal): self.storage.append(animal) def remove_animal(self, position): self.storage.pop(position) class Animal: def __init__(self, name, breed, colour, size): self.name = name self.breed = breed self.colour = colour self.size = size class Dog(Animal): def __init__(self, name, breed, colour, size, bark_sound): super().__init__(name, breed, colour, size) self.bark_sound = bark_sound class Cat(Animal): def __init__(self, name, breed, colour, size, aggression, cuteness): super().__init__(name, breed, colour, size) self.aggression = aggression self.cuteness = cuteness root = tk.Tk() App(master = root) root.mainloop() </code></pre> <p><a href="https://i.stack.imgur.com/PJmYi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/PJmYi.png" alt="gui" /></a></p>
[]
[ { "body": "<p>A little for the styling of the GUI</p>\n<h1>Add an icon to your application</h1>\n<p>Tkinter has made it very easy to add an icon to any of our windows, it's a single line that makes your GUI look good.</p>\n<p>All you need to do is go to a website like <a href=\"https://icon-icons.com/\" rel=\"nofollow noreferrer\">this</a> one and download any <code>.ico</code> file of size <code>16x16</code>, I haven't tested it with other sizes and formats, but usually, you'll find plenty in this size!</p>\n<p>Once you have your <code>.ico</code> file, you need to place it in the same directory as your source files.</p>\n<ul>\n<li>Tip: place them in a folder relative to the source files, so you just have to do <code>images/</code>, this keeps your project directory clean!</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>window.iconbitmap(&quot;path to your file&quot;)\n</code></pre>\n<p>That's all there is!</p>\n<hr />\n<h1>Add a title</h1>\n<p>This one is even easier, all you need to do is</p>\n<pre class=\"lang-py prettyprint-override\"><code>window.title(&quot; your title &quot; )\n</code></pre>\n<hr />\n<h1>Avoid unnecessary classes</h1>\n<p>you have a class <code>Storage</code>, but all it really does is hold a list of animals. You don't need to create a new class for this, a simple list in <code>App</code> works.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def __init__(...):\n self.animals = []\n</code></pre>\n<p>Since you have inherited your <code>AddAnimal</code> class from <code>App</code>, you can easily add an animal to <code>self.animals</code>, It's easier that way</p>\n<hr />\n<h1>Why is <code>AddAnimal</code> a class?</h1>\n<p>I understand what you are trying to do, but I don't see why <code>AddAnimal</code> should be a class</p>\n<p>It should just be a function in your <code>App class</code>, it is very important that you structure your Tkinter application right otherwise it looks extremely convoluted, let me show you how this program should be structured ( or can be )</p>\n<p>First, let's start with the animal structure</p>\n<p><a href=\"https://i.stack.imgur.com/Bv0YX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Bv0YX.png\" alt=\"animal class\" /></a></p>\n<p>The good point is, your program follows this perfectly. <code>Animal</code> has</p>\n<ul>\n<li>name</li>\n<li>breed</li>\n<li>dog</li>\n<li>size</li>\n</ul>\n<p><code>Dog</code> has</p>\n<ul>\n<li>bark sound</li>\n</ul>\n<p><code>Cat</code> has</p>\n<ul>\n<li>Agression <sup> what? </sup></li>\n<li>Cuteness</li>\n</ul>\n<p>It is a good structure, you have re-used <code>Animal</code> attributes in <code>Cat</code> and <code>Dog</code>, but now when you have to have the main application, your program is a little convoluted</p>\n<p><strong> <strong>Here is how it can be structured better</strong> </strong></p>\n<p><a href=\"https://i.stack.imgur.com/9QsuC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9QsuC.png\" alt=\"Main\" /></a></p>\n<p>After this, there won't be a need for extra classes like <code>Storage</code> and <code>AddAnimal</code></p>\n<hr />\n<h2>Animal</h2>\n<pre class=\"lang-py prettyprint-override\"><code>f self.type_of_animal == &quot;Dog&quot;:\n self.titles = [&quot;Name&quot;, &quot;Breed&quot;, &quot;Colour&quot;, &quot;Size&quot;, &quot;Bark Sound&quot;]\nelse:\n self.titles = [&quot;Name&quot;, &quot;Breed&quot;, &quot;Colour&quot;, &quot;Size&quot;, &quot;Aggression&quot;, &quot;Cuteness&quot;]\n</code></pre>\n<p>These <strong>don't</strong> belong to <code>AddAnimal</code>, these should be a part of your <code>Animal</code> class since these are attributes of <code>Animal</code>, so your class misses one thing</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Animal:\n def __init__(self, name, breed, colour, size):\n self.name = name\n self.breed = breed\n self.colour = colour\n self.size = size\n self.all_attributes = [self.name, self.breed, self.colour, self.size]\n\nclass Dog(Animal):\n\n def __init__(self, name, breed, colour, size, bark_sound):\n super().__init__(name, breed, colour, size)\n self.bark_sound = bark_sound\n self.all_attributes.append(self.bark_sound)\n\nclass Cat(Animal):\n\n def __init__(self, name, breed, colour, size, aggression, cuteness):\n super().__init__(name, breed, colour, size)\n self.aggression = aggression\n self.cuteness = cuteness\n self.all_attributes.append(aggression)\n self.all_attributes.append(cuteness)\n</code></pre>\n<p>This way when you create a new animal, you already have its <code>titles</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>my_cat = Cat(&quot;milo&quot;,&quot;turkish&quot;,&quot;brown&quot;,&quot;small&quot;,aggression = &quot;0&quot;,cuteness = &quot;100&quot;)\nprint(my_cat.all_attributes)\n\n</code></pre>\n<blockquote>\n<p>['milo', 'turkish', 'brown', 'small', '0', '100']</p>\n</blockquote>\n<hr />\n<h2>App</h2>\n<p>As I said, <code>App</code> should hold a list of <code>Animal</code> objects, so everytime you need to add a new animal, it's extremely simple</p>\n<pre class=\"lang-py prettyprint-override\"><code>class App:\n def new_cat():\n # get all input through the GUI widgets \n self.animals.append( Cat(attributes...) )\n def new_dog():\n self.animals.append( Dog(attributes...) )\n</code></pre>\n<p><sup> It is heavily nerfed to show only the important stuff, other Tk stuff remains </sup>\n<br><br></p>\n<hr />\n<h1>Avoid Magic Numbers</h1>\n<pre class=\"lang-py prettyprint-override\"><code>name = lis[0]; breed = lis[1]; colour = lis[2]; size = lis[3]; bark_sound = lis[4]; \n</code></pre>\n<p>All are <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">magic numbers</a>, an <a href=\"https://www.tutorialspoint.com/enum-in-python#:%7E:text=Enum%20is%20a%20class%20in,enum%20has%20the%20following%20characteristics.\" rel=\"nofollow noreferrer\">enum</a> would be perfect here</p>\n<pre class=\"lang-py prettyprint-override\"><code>from enum import Enum\n\nclass Columns(Enum):\n name = 0\n breed = 1\n ...\n</code></pre>\n<p>Since the values change for <code>Cat</code> and <code>Dog</code> , the <code>Enum</code> can be a part of the respective class so there isn't any problem</p>\n<hr />\n<h1>Nitpicks</h1>\n<ul>\n<li>There still are many magic constants in your program like width, padding, etc</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>headings = [&quot;Type&quot;, &quot;Name&quot;, &quot;Breed&quot;, &quot;Colour&quot;, &quot;Size&quot;, &quot;Bark&quot;, &quot;Aggression&quot;, &quot;Cuteness&quot;]\nself.tree[&quot;columns&quot;] = (0, 1, 2, 3, 4, 5, 6, 7)\n</code></pre>\n<p>I think you should change this to</p>\n<pre class=\"lang-py prettyprint-override\"><code>self.headings = (&quot;Type&quot;, &quot;Name&quot;, &quot;Breed&quot;, &quot;Colour&quot;, &quot;Size&quot;, &quot;Bark&quot;, &quot;Aggression&quot;, &quot;Cuteness&quot;)\nself.tree[&quot;columns&quot;] = self.headings\n</code></pre>\n<p>Since <code>headings</code> is a part of our <code>App</code> , it should be a member</p>\n<ul>\n<li>After adding a record to the tree, the details don't seem to be centered with the column heading, you should use <code>anchor</code> to center them</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T09:41:20.580", "Id": "494433", "Score": "0", "body": "Thanks! First I'm hearing from Enum's. I'm not sure this would definitely work - as the number's change depending on whether it's a `Cat` or `Dog` object (e.g. 4 equals aggression in cats and bark sound for dogs). Regarding the `AddAnimal` class. I read somewhere that new windows should be a separate class - but this may have been wrong. For the `Storage` class, I kept this has a class as I planned on having extra functionality associated with it (e.g. filters). Adding the `all_attributes` attribute makes a lot of sense. I hadn't thought of this!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T09:47:15.733", "Id": "494434", "Score": "0", "body": "@AaronWright Yes, you can keep then enum as a part of the `Cat` or `Animal` class, that way there isn't any confusion, I'll add that to my answer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T10:14:58.680", "Id": "494435", "Score": "0", "body": "Perekh Thanks for that. Regarding the `AddAnimal` class - how would I structure this if it wasn't a class? As in, should the `widgets` method under this class remain as a method, along with the 'add_window' method in the `MainApp` class. The only way I've been shown regarding the creation of new windows, is to add them as their own class." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T11:07:46.530", "Id": "494439", "Score": "0", "body": "@AaronWright [Join this chat room](https://chat.stackexchange.com/rooms/115566/tkinter-discussion) We can discuss here" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T11:31:14.363", "Id": "494444", "Score": "0", "body": "Thanks Aryan! I'm at work right now, but I'll join the chat room tonight once I'm finished." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T05:27:26.697", "Id": "251192", "ParentId": "251180", "Score": "5" } }, { "body": "<p>It is often good practice to put the main program controller in an <code>if __name__ == &quot;__main__&quot;:</code> so that in case you would want to import this program in another file you would not open the window up immediately, only if you run this file directly. In your case, that controller would be the last three lines:</p>\n<pre class=\"lang-py prettyprint-override\"><code>...\n self.aggression = aggression\n self.cuteness = cuteness\n\nif __name__ == &quot;__main__&quot;:\n root = tk.Tk()\n App(master = root)\n root.mainloop()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T10:16:33.730", "Id": "494523", "Score": "1", "body": "Thanks! I'll add this in. I was always a bit confused as to what was meant by `if __name__ == \"__main__\"`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T11:38:51.500", "Id": "494533", "Score": "0", "body": "@AaronWright no problem! [here's](https://docs.python.org/3/library/__main__.html) the official documentation on it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T16:36:40.703", "Id": "494554", "Score": "0", "body": "It is like the `main()` function of python" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T11:48:49.057", "Id": "251204", "ParentId": "251180", "Score": "0" } } ]
{ "AcceptedAnswerId": "251192", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T21:53:40.557", "Id": "251180", "Score": "6", "Tags": [ "python-3.x", "object-oriented", "tkinter", "gui", "graphics" ], "Title": "Animal Storage TreeView - Tkinter" }
251180
<p>I am working on an application that is required to be constantly running, and as a requirement should make multiple attempts for particular processes such as web API/database calls, just in case network connectivity goes down for a moment, or something similar.</p> <p>In this case, I'm constantly having to write a basic algorithm:</p> <pre><code>for (int attempt = 0; i &lt; Config.AttemptCount; i++) { try { doSomething...; return true; } catch (Exception e) { Log(e); } finally { if (Config.WaitTimeForRetry &gt; 0) Thread.Sleep(Config.WaitTimeForRetry); } } return false; </code></pre> <p>This of course is the most basic example, but there are others where I'm returning actual objects, performing heavy operations, etc. I recently got the idea to make a single method that could perform this algorithm for me so I can focus on the overall functionality with each implementation instead. With that said, I present to you, a method I need a better name for, and probably needs a much better implementation, or should be replaced by something pre-existing if such a thing exists because I re-invent the wheel a lot, but none-the-less, it's here .</p> <pre><code>public static TOut RunProcessWithMultipleAttempts&lt;TIn, TOut&gt;(int numberOfAttempts, int waitTimeInMilliseconds, TIn input, Func&lt;TIn, TOut&gt; process) { TOut result = default; while (numberOfAttempts-- &gt; 0) { try { result = process.Invoke(input); break; } catch (Exception e) { Log(e); } finally { if (waitTimeInMilliseconds &gt; 0) Thread.Sleep(waitTimeInMilliseconds); } } return result; } </code></pre> <p>To use this, I would write a method that does the work I wish to be performed:</p> <pre><code>static int attempts = 0; private static string TrySomething(int i) { for (int index = 0; index &lt; i; index++) if (attempts++ &lt; 2) throw new Exception(&quot;Your request was denied.&quot;); return &quot;Your request was successful.&quot;; } </code></pre> <p>I would then utilize the <code>RunProcessWithMultipleAttempts</code> method to execute it:</p> <pre><code>static void Main(string[] args) { Console.WriteLine(RunProcessWithMultipleAttempts(3, 1000, 10, TrySomething)); // Prevent the console from closing. Console.ReadKey(); } </code></pre> <p>In this example, replace the <code>Log(e)</code> call with <code>Console.WriteLine(e)</code> to allow it to work on your local machine.</p> <hr /> <p>A few questions in my mind:</p> <ul> <li>How hard is this to scale?</li> <li>What are the downsides to this method?</li> <li>What alternatives are available?</li> <li>Is this code easy to understand?</li> <li>Not only in final usage, but initial implementation?</li> </ul> <p>Oh, and perhaps my biggest question if I were to keep this implementation around:</p> <blockquote> <p>What would a more concise and clear name be for this method?</p> </blockquote>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T04:31:54.937", "Id": "494417", "Score": "1", "body": "I'd highly recommend using [Polly](https://github.com/App-vNext/Polly) which solves this particular use case and more." } ]
[ { "body": "<h3>How hard is this to scale?</h3>\n<p>Sorry but I don't understand what do you mean here. How do you want to scale a method?</p>\n<h3>What are the downsides to this method?</h3>\n<ul>\n<li><p>It does not work with <code>Action</code></p>\n</li>\n<li><p>It does not work with <code>Func&lt;T1, T2, TResult&gt;</code></p>\n</li>\n<li><p>It does not work with <code>Func&lt;Task&gt;</code></p>\n</li>\n<li><p>It does not work with <code>Func&lt;Task&lt;T&gt;&gt;</code></p>\n</li>\n<li><p>It blocks the calling thread unnecessary (<code>Thread.Sleep</code>)</p>\n</li>\n<li><p>You must throw exception to enforce retry (can't use any other condition, like <code>Result != true</code>)</p>\n</li>\n<li><p>It swallows the exception</p>\n<ul>\n<li>in the worst case if all attempts fail then it will return a <code>default</code> instead of the exception</li>\n</ul>\n</li>\n<li><p>It does not allow to use exponential back-off algorithm</p>\n</li>\n<li><p>It does not allow infinite retry (performing yet another attempt until it succeeds)</p>\n</li>\n<li><p>It does not utilize <em>Cancellation</em> concept</p>\n</li>\n<li><p>It does not provide debug information (like how many times the retry has been performed)</p>\n</li>\n</ul>\n<h3>What alternatives are available?</h3>\n<ul>\n<li><a href=\"https://github.com/App-vNext/Polly/wiki/Retry\" rel=\"nofollow noreferrer\">Polly's Retry</a> &lt;&lt; The suggested</li>\n<li><a href=\"https://github.com/Dixin/EnterpriseLibrary.TransientFaultHandling.Core\" rel=\"nofollow noreferrer\">EnterpriseLibrary.TransientFaultHandling.Core</a></li>\n</ul>\n<h3>Is this code easy to understand?</h3>\n<p>For me, yes.</p>\n<h3>Not only in final usage, but initial implementation?</h3>\n<p>Is this a question?</p>\n<h3>What would a more concise and clear name be for this method?</h3>\n<ul>\n<li><code>ExecuteWithRetry</code></li>\n<li><code>ExecuteAtMostNTimes</code></li>\n<li><code>RetryFunction</code></li>\n<li><code>PerformCallWithRetryPolicy</code></li>\n<li>etc.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T11:32:05.140", "Id": "494445", "Score": "1", "body": "To start properly, thank you for the feedback! To answer some of your questions: Scalable, you answered this in the next section, just as I thought with how it doesn't implement `Action`, `Func<T1, T2, TResult>`, etc; Putting the thread to sleep was a defined requirement, which is the only reason it's there. The same rings true for swallowing the exception and preventing infinite retry. Throwing an exception was just for testing purposes, as ideally the executing functionality would succeed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T11:34:07.927", "Id": "494446", "Score": "1", "body": "With that out of the way now, I need to read up on the links you sent, as well as exponential back-off. I like the idea of providing the debug information too. Regarding the cancellation concept, are you referring to the caller cancelling the execution? Thank you again for all of your time! This was an awesome answer!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T13:13:56.250", "Id": "494453", "Score": "1", "body": "@Taco The cancellation token can help you to stop the execution at any point. For example you can define a global timeout, if the threshold is exceeded then no further retry should be instantiated. Or you can provide a button on a UI to allow user cancellation. Or you can combine several tokens. etc." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T07:48:53.047", "Id": "251199", "ParentId": "251181", "Score": "2" } } ]
{ "AcceptedAnswerId": "251199", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T22:05:45.097", "Id": "251181", "Score": "1", "Tags": [ "c#" ], "Title": "Retry method execution on failure?" }
251181
<p>I want to organize mapping for my Angular app so that code structure would clear for other developers and I want to have as less code as possible.</p> <p>I have an api service that is responsible for communicating with API. I create separate data services, which utilize the api service, to get backend data. The same data can be used in different features. I want to provide the data to some feature. But the feature needs a more complex model than backend provides. So, I want to do a complex mapping specific for the particular feature which extends the backend model. But I also do a basic mapping that is required for every feature like property naming ('_name' to 'name') or type converting (string to Date). What is your recommendation on how to approach this?</p> <p>My current idea is the following. I put the data services in the app/core folder and do the basic mapping on this level. I have feature related models and mapper services in the app/feature folders. It looks OK in terms of separation of concerns. But I have doubts about the number of mapping functions and services. Looks wordy, doesn't it?</p> <p><strong>app/core/lesson</strong></p> <p><em>lesson-dto.model.ts</em></p> <pre><code>export interface LessonDto { id: string; _departmentId: string; begin: string; end: string; } </code></pre> <p><em>get-lessons-response.model.ts</em></p> <pre><code>export interface GetLessonsResponse { lessons: LessonDto[]; } </code></pre> <p><em>lesson.model.ts</em></p> <pre><code>export interface Lesson { id: string; departmentId: string; begin: Date; end: Date; } </code></pre> <p><em>lesson-basic-mapping.ts</em></p> <pre><code>export function mapLessonDtoToLesson(lessonDto: LessonDto): Lesson { return { id: lessonDto.id, departmentId: lessonDto._departmentId, begin: new Date(lessonDto.begin), end: new Date(lessonDto.end) }; } </code></pre> <p><em>lesson.data.service.ts</em></p> <pre><code>export class LessonDataService { constructor(private readonly apiService: ApiService) { } public getLessons( departmentId: string ): Observable&lt;Lesson[]&gt; { const requestUrl = `/departments/${departmentId}/lessons`; return this.apiService.get(requestUrl).pipe( map((response: GetLessonsResponse) =&gt; response.lessons .map(mapLessonDtoToLesson)) ); } } </code></pre> <p><strong>app/features/schedule</strong></p> <p><em>schedule-lesson.model.ts</em></p> <pre><code>export interface ScheduleLesson { id: string; name: string; begin: Date; end: Date; description: string; } </code></pre> <p><em>scheduler-mapping.ts</em></p> <pre><code>export function mapLessonToScheduleLesson(lesson: Lesson): ScheduleLesson { return { id: lesson.id, name: calculateName(lesson.id, lesson.departmentId), begin: new Date(lessonDto.begin), end: new Date(lessonDto.end), description: doSomeOtherComplexMappingHere(lesson.departmentId) }; } </code></pre> <p><em>lesson-mapped-data.service.ts</em></p> <pre><code>export class LessonMappedDataService { constructor(private readonly lessonDataService: LessonDataService) { } public getLessons( departmentId: string ): Observable&lt;ScheduleLesson[]&gt; { return this.lessonDataService.get(departmentId).pipe( map((lessons: Lesson[]) =&gt; lessons .map(mapLessonToScheduleLesson)) ); } } </code></pre> <p>One more thing that concerns me is that the more models I have or the longer they are the more similar code I have. I did some analysis. I like the <a href="https://blog.usejournal.com/how-to-map-rest-api-data-using-decorator-pattern-in-angular-6-94eb49ba16b1" rel="nofollow noreferrer">approach with decorators</a>. It looks similar to Newtonsoft in C# and hides the implementation of basic mapping. But it requires some hacky solutions to align it with TypeScript. And the feature of decorators is still unclear. So, I don't use it.</p> <p>Do you have any ideas on how to make the code better (more clear and less to read)? And what do you think of the file/folder structure?</p> <p>Thank you in advance.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T00:16:19.977", "Id": "494407", "Score": "0", "body": "Welcome to the Code Review Site where we review working code from your project and provide suggestions on how to improve that code. Is this code implemented and working yet, if not then the question is [off-topic](https://codereview.stackexchange.com/help/dont-ask). If you are still in the design stage then try software engineering but read [their guidelines for asking](https://softwareengineering.stackexchange.com/help/how-to-ask) first." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T07:53:44.307", "Id": "494427", "Score": "0", "body": "Thank you for your message. Indeed, even though it is an implemented code, the main question is about design. But I see in the description of the community the first mentioned topic is 'Application of best practices and design pattern usage'. That is exactly I am asking for. So, I think, this question can be here. If there is no any answer in a short time, I will try Software Engineering. As I've just known they also help with questions about practices. Thank you very much for this recommendation." } ]
[ { "body": "<p>I made some good experience with the following approach. Its more code, but it helped the other developers in the team (and especially the new ones) to get a good grip and a fast start.<br />\nAs always, many roads, choose the one that fits best in your context, they all have drawbacks. :-)</p>\n<p>First i describe the expected data from the Backend</p>\n<pre><code>export interface AddressJSON{\n street: string,\n city: string\n};\n\nexport interface UserJSON{\n id: number,\n name: string,\n address: AddressJSON\n}\n</code></pre>\n<p>That helps to understand what to expect from the backend. Also its easier to track mapping problems (for example a Java LONG that is stored in a JavaScript NUMBER =&gt; Number has a smaller value range)</p>\n<p>Then i create the FE models and if the mapping between backend and FE is easy, then i add converter methods</p>\n<pre><code>class Address {\n public street: string;\n public city: string;\n\n constructor(street: string, city: string){\n this.street = street;\n this.city = city;\n }\n\n public toJSON(): AddressJSON{\n return {\n street: this.street,\n city: this.city\n }\n }\n\n public static fromJSON(address: AddressJSON): Address{\n return new Address(address.street, address.city);\n }\n}\n\n\nclass User {\n public name: string;\n public address: Address;\n private readonly id: number;\n\n constructor(id:number){\n this.id = id;\n }\n\n public toJSON(): UserJSON {\n return {\n id: this.id,\n name: this.name,\n address: this.address.toJSON()\n }\n }\n\n public static fromJSON(user: UserJSON): User{\n const newUser: User = new User(user.id);\n newUser.name = user.name;\n newUser.address = Address.fromJSON(user.address);\n return newUser;\n }\n}\n</code></pre>\n<p>As you can see the entities can be stacked.<br />\nOne reason i choose classes over interfaces for my entities is that i can move functionality directly to the entities.<br />\nAnd, i can FORCE the way this entity has to be used. For example i can disallow the creation of a artificial user without an id.<br />\nIt reduces the risc for later changes. And it enforces a deeper understanding of the business requirements behind those entities.<br />\nOn the over side its much more work at the start.</p>\n<p>Most people who didn´t liked this approach hated the extra work, that you have to invest. The people who liked it, mostly highlighted the better understanding of the business requirements and the possibly to enforce correct usage.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T15:43:18.610", "Id": "498371", "Score": "0", "body": "I see, you use static for fromJSON and do not use it for toJSON? Why is there a difference? Do I understand correctly that every instance of the User class will have toJSON method and will not have fromJSON, because the last one belongs to the class itself. Does it make sense to make both static?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T17:10:46.773", "Id": "498387", "Score": "0", "body": "The \"fromJSON\" is static, because the method will create the instance out of the JSON. The \"toJSON\" is an instance method, because it will take the current instance and create a JSON out of it. You could makte \"toJSON\" static also, but then the method would need a parameter (''toJSON(instance: User):UserJSON''), because only then it could know WHAT should be converted into a JSON. With a instance method you don´t need that parameter because it knows that it should convert itself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T17:48:06.457", "Id": "498393", "Score": "0", "body": "Oh, thanks. I understand the idea. What I actually like is that the mapping methods are close to the model. We can use the advantage of intellisense. We can also decrease the memory footprint using static methods. The footprint itself can be a drawback. For example, mapping service + interface are less memory consumptive. But I actually find your approach good enough in terms of readability." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-30T18:15:38.460", "Id": "498398", "Score": "1", "body": ":-) In my experience the cases were the memory footprint or the CPU usage is more relevant then the readability are a bit rare in modern times. Also, IF there is a performance problem, its much easier to tackle it if the code is understandable. :-) Therefor i first try to make my code nice and shiny, only then i start with a performance analysis and (if really necessary) start to optimize. :-) But as always, three developers, 4 approaches :-)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T10:29:31.603", "Id": "251202", "ParentId": "251182", "Score": "2" } } ]
{ "AcceptedAnswerId": "251202", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T22:28:29.007", "Id": "251182", "Score": "2", "Tags": [ "api", "angular-2+" ], "Title": "How to approach separation of layers mapping response to model in Angular app?" }
251182
<p><a href="https://leetcode.com/problems/number-of-enclaves/" rel="nofollow noreferrer">https://leetcode.com/problems/number-of-enclaves/</a></p> <p>Given a 2D array A, each cell is 0 (representing sea) or 1 (representing land)</p> <p>A move consists of walking from one land square 4-directionally to another land square, or off the boundary of the grid.</p> <p>Return the number of land squares in the grid for which we cannot walk off the boundary of the grid in any number of moves.</p> <p>Example 1:</p> <p>Input: [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]] Output: 3 Explanation: There are three 1s that are enclosed by 0s, and one 1 that isn't enclosed because its on the boundary. Example 2:</p> <p>Input: [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]] Output: 0 Explanation: All 1s are either on the boundary or can reach the boundary.</p> <p>Note:</p> <p>1 &lt;= A.length &lt;= 500 1 &lt;= A[i].length &lt;= 500 0 &lt;= A[i][j] &lt;= 1 All rows have the same size.</p> <p>please review for performance.</p> <p>using Microsoft.VisualStudio.TestTools.UnitTesting;</p> <pre><code>namespace GraphsQuestions { /// &lt;summary&gt; /// https://leetcode.com/problems/number-of-enclaves /// &lt;/summary&gt; [TestClass] public class NumberOfEnclavesTest { [TestMethod] public void FirstTest() { int[][] A = { new[] { 0, 0, 0, 0 }, new[] { 1, 0, 1, 0 }, new[] { 0, 1, 1, 0 }, new[] { 0, 0, 0, 0 } }; int expected = 3; Assert.AreEqual(expected, NumEnclaves(A)); } [TestMethod] public void FailedTest() { int[][] A = { new[] { 0, 1, 1, 0 }, new[] { 0, 0, 1, 0 }, new[] { 0, 0, 1, 0 }, new[] { 0, 0, 0, 0 } }; int expected = 0; Assert.AreEqual(expected,NumEnclaves(A)); } public int NumEnclaves(int[][] A) { int count = 0; for (int row = 1; row &lt; A.Length - 1; row++) { for (int col = 1; col &lt; A[0].Length - 1; col++) { if (A[row][col] != 0) { bool isDone = false; int res = DFS(row, col, A, ref isDone); if (!isDone) { count += res; } } } } return count; } private int DFS(int row, int col, int[][] A, ref bool isDone) { if (row &lt;= 0 || col &lt;= 0 || row &gt;= A.Length-1 || col &gt;= A[0].Length-1 ) { if (A[row][col] == 1) { isDone = true; } return 0; } if (A[row][col] == 0) { return 0; } int count = 1; A[row][col] = 0; count += DFS(row, col - 1, A,ref isDone); count += DFS(row, col + 1, A,ref isDone); count += DFS(row - 1, col, A,ref isDone); count += DFS(row + 1, col, A,ref isDone); if (isDone) { count = 0; } return count; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T22:42:34.410", "Id": "494402", "Score": "0", "body": "This seems pretty extreme for an interview question. " }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T22:56:52.973", "Id": "494404", "Score": "1", "body": "@Emma I suppose it depends on the type of work you'll be doing too though. I think the hardest I've had was to write a method that provided a single point from an nth order Bezier curve based on time, which after landing that position and working there for 4 years, I still think it was overkill. I'm very happy that they let me Google the mathematics for it or I would've never reached the correct answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T06:50:55.947", "Id": "494424", "Score": "2", "body": "@Taco this a medium question. once you practice more and more of those at leetcode.com or any other site. you can see the patterns." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T11:23:26.030", "Id": "494442", "Score": "0", "body": "I wouldn't doubt it to be honest. I've been in the industry for a decade now, and have been on both sides of the interview process many times at this point, just seemed pretty overkill-ish to me lol" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T11:24:28.733", "Id": "494443", "Score": "1", "body": "@Taco this is google/amazon/microsoft type of questions" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-26T22:30:46.620", "Id": "251183", "Score": "2", "Tags": [ "c#", "interview-questions", "graph", "depth-first-search" ], "Title": "LeetCode: Number of enclaves C#" }
251183
<p>This is an exercise to implement a waiting room for an hospital with the following requirements:</p> <ul> <li>Add (and remove) a patient to the queue of the waiting room</li> <li>Move a patient up and down the queue</li> <li>Show all patients in the queue</li> <li>The queue needs to be persisted</li> </ul> <p>The <code>WaitingRoom</code> interface:</p> <pre><code>public interface WaitingRoom { Patient addPatient(Patient patient); Optional&lt;Patient&gt; removePatient(); // Move a patient by delta positions in the queue. // E.g. if p1 is second in the queue, the operation // move(p1,1) moves p1 to the first position. // Delta can be negative. void move(Patient patient, int delta); List&lt;Patient&gt; peekPatients(); int size(); void clear(); } </code></pre> <p>The <code>Patient</code> class:</p> <pre><code>@Getter @Setter @NoArgsConstructor @Entity @ToString public class Patient { @Id @GeneratedValue private Long id; private String name; public Patient(String name) { this.name = name; } } </code></pre> <p>This is the <code>WaitingRoomService</code>:</p> <pre><code>@Service public class WaitingRoomService implements WaitingRoom { private EditableQueue&lt;Patient&gt; queue; public WaitingRoomService(PersistentQueue&lt;Patient&gt; queue) { this.queue = queue; } @Override public List&lt;Patient&gt; getAllPatients() { return queue.getAll(); } @Override public Patient addPatient(Patient patient) { return queue.enqueue(patient); } @Override public Optional&lt;Patient&gt; removePatient() { return queue.dequeue(); } @Override public void move(Patient patient, int delta) { queue.move(patient, delta); } @Override public int size() { return queue.size(); } @Override public void clear() { queue.clear(); } } </code></pre> <p><code>EditableQueue</code> is an interface implemented by <code>PersistentQueue</code>:</p> <pre><code>@Component public class PersistentQueue&lt;T&gt; implements EditableQueue&lt;T&gt; { private NodeRepository&lt;T&gt; nodeRepo; public PersistentQueue(NodeRepository&lt;T&gt; nodeRepo) { this.nodeRepo = nodeRepo; } @Override public List&lt;T&gt; getAll() { return nodeRepo.findByOrderByPosition() .stream() .map(node -&gt; node.getValue()) .collect(Collectors.toList()); } @Override @Transactional public T enqueue(T element) { Node&lt;T&gt; node = new Node&lt;&gt;(element); Optional&lt;Node&lt;T&gt;&gt; lastNode = nodeRepo.findByLastTrue(); int newPosition = 0; if (lastNode.isPresent()) { newPosition = lastNode.get().getPosition() + 1; lastNode.get().setLast(false); } else { node.setFirst(true); } node.setPosition(newPosition); node.setLast(true); return nodeRepo.save(node).getValue(); } @Override @Transactional public Optional&lt;T&gt; dequeue() { if (size() == 0) { return Optional.empty(); } Optional&lt;Node&lt;T&gt;&gt; first = nodeRepo.findByFirstTrue(); Optional&lt;Node&lt;T&gt;&gt; second = nodeRepo.findByPosition(first.get().getPosition() + 1); if (second.isPresent()) { second.get().setFirst(true); } nodeRepo.deleteById(first.get().getId()); return Optional.of(first.get().getValue()); } @Override @Transactional public void move(T element, int delta) { Node&lt;T&gt; toMove = nodeRepo.findByValue(element).get(); int newPosition = toMove.getPosition() - delta; int next = delta &gt; 0 ? toMove.getPosition() - 1 : toMove.getPosition() + 1; int start, end = 0; if (delta &gt; 0) { start = newPosition; end = next; } else { start = next; end = newPosition; } for (Node&lt;T&gt; n : nodeRepo.findAllByPositionBetween(start, end)) { if (delta &gt; 0) { // swap head with node to move if (n.isFirst()) { n.setFirst(false); toMove.setFirst(true); } // swap tail with node to move if (toMove.isLast() &amp;&amp; n.getPosition() == next) { toMove.setLast(false); n.setLast(true); } } else { if (n.isLast()) { n.setLast(false); toMove.setLast(true); } if (toMove.isFirst() &amp;&amp; n.getPosition() == next) { toMove.setFirst(false); n.setFirst(true); } } n.setPosition(delta &gt; 0 ? n.getPosition() + 1 : n.getPosition() - 1); } toMove.setPosition(newPosition); } @Override public int size() { return (int) nodeRepo.count(); } @Override public void clear() { nodeRepo.deleteAll(); } } </code></pre> <p><code>NodeRepository</code>:</p> <pre><code>interface NodeRepository&lt;T&gt; extends JpaRepository&lt;Node&lt;T&gt;, Long&gt; { List&lt;Node&lt;T&gt;&gt; findByOrderByPosition(); Optional&lt;Node&lt;T&gt;&gt; findByPosition(int position); Optional&lt;Node&lt;T&gt;&gt; findByValue(T value); Optional&lt;Node&lt;T&gt;&gt; findByFirstTrue(); Optional&lt;Node&lt;T&gt;&gt; findByLastTrue(); List&lt;Node&lt;T&gt;&gt; findAllByPositionBetween(int start, int end); } </code></pre> <p>A <code>Node</code> is an element of <code>EditableQueue</code> and a wrapper for <code>Patient</code>:</p> <pre><code>@Getter @Setter @NoArgsConstructor @Entity @ToString public class Node&lt;T&gt; { @Id @GeneratedValue private Long id; @OneToOne(cascade = CascadeType.PERSIST, targetEntity = Patient.class) private T value; private int position; private boolean first; private boolean last; public Node(T value) { this.value = value; this.position = -1; } } </code></pre> <p>Finally, the tests:</p> <pre><code>@SpringBootTest public class WaitingRoomServiceTest { @Autowired private WaitingRoom waitingRoom; @BeforeEach public void clearRoom() { waitingRoom.clear(); } @Test public void enqueueDequeueTest() { waitingRoom.addPatient(new Patient(&quot;Marc&quot;)); waitingRoom.addPatient(new Patient(&quot;Anna&quot;)); assertTrue(waitingRoom.size() == 2); assertEquals(&quot;Marc&quot;, waitingRoom.removePatient().get().getName()); assertTrue(waitingRoom.size() == 1); assertEquals(&quot;Anna&quot;, waitingRoom.removePatient().get().getName()); assertTrue(waitingRoom.size() == 0); } @Test public void moveTest() { waitingRoom.addPatient(new Patient(&quot;p1&quot;)); waitingRoom.addPatient(new Patient(&quot;p2&quot;)); Patient p3 = waitingRoom.addPatient(new Patient(&quot;p3&quot;)); waitingRoom.addPatient(new Patient(&quot;p4&quot;)); // Move p3 up by 1 position waitingRoom.move(p3, 1); assertEquals(&quot;p1&quot;, waitingRoom.removePatient().get().getName()); assertEquals(&quot;p3&quot;, waitingRoom.removePatient().get().getName()); assertEquals(&quot;p2&quot;, waitingRoom.removePatient().get().getName()); assertEquals(&quot;p4&quot;, waitingRoom.removePatient().get().getName()); assertTrue(waitingRoom.size() == 0); } @Test public void moveTest2() { waitingRoom.addPatient(new Patient(&quot;p1&quot;)); waitingRoom.addPatient(new Patient(&quot;p2&quot;)); Patient p3 = waitingRoom.addPatient(new Patient(&quot;p3&quot;)); Patient p4 = waitingRoom.addPatient(new Patient(&quot;p4&quot;)); waitingRoom.addPatient(new Patient(&quot;p5&quot;)); // Move p3 up by 2 position waitingRoom.move(p3, 2); // Move p4 down by 1 position waitingRoom.move(p4, -1); assertEquals(&quot;p3&quot;, waitingRoom.removePatient().get().getName()); assertEquals(&quot;p1&quot;, waitingRoom.removePatient().get().getName()); assertEquals(&quot;p2&quot;, waitingRoom.removePatient().get().getName()); assertEquals(&quot;p5&quot;, waitingRoom.removePatient().get().getName()); assertEquals(&quot;p4&quot;, waitingRoom.removePatient().get().getName()); assertTrue(waitingRoom.size() == 0); } @Test public void moveTest3() { waitingRoom.addPatient(new Patient(&quot;p1&quot;)); Patient p2 = waitingRoom.addPatient(new Patient(&quot;p2&quot;)); waitingRoom.move(p2, 1); waitingRoom.move(p2, -1); assertEquals(&quot;p1&quot;, waitingRoom.removePatient().get().getName()); assertEquals(&quot;p2&quot;, waitingRoom.removePatient().get().getName()); assertTrue(waitingRoom.size() == 0); } @Test public void moveTest4() { waitingRoom.addPatient(new Patient(&quot;p1&quot;)); Patient p2 = waitingRoom.addPatient(new Patient(&quot;p2&quot;)); waitingRoom.addPatient(new Patient(&quot;p3&quot;)); waitingRoom.addPatient(new Patient(&quot;p4&quot;)); waitingRoom.removePatient(); waitingRoom.move(p2, -1); assertEquals(&quot;p3&quot;, waitingRoom.removePatient().get().getName()); assertEquals(&quot;p2&quot;, waitingRoom.removePatient().get().getName()); assertEquals(&quot;p4&quot;, waitingRoom.removePatient().get().getName()); assertTrue(waitingRoom.size() == 0); } @Test public void stressTest() { int n = 1000; long startTime = System.nanoTime(); for (long i = 1; i &lt; n; i++) { waitingRoom.addPatient(new Patient(&quot;p&quot; + i)); } long endTime = System.nanoTime(); System.out.format(&quot;Enqueue %d time: %d ms%n&quot;, n, (endTime - startTime) / 1000000); startTime = System.nanoTime(); for (long i = 1; i &lt; n; i++) { waitingRoom.removePatient(); } endTime = System.nanoTime(); System.out.format(&quot;Dequeue %d time: %d ms%n&quot;, n, (endTime - startTime) / 1000000); assertTrue(waitingRoom.size() == 0); } @Test public void getAllPatientsTest() { waitingRoom.addPatient(new Patient(&quot;p1&quot;)); waitingRoom.addPatient(new Patient(&quot;p2&quot;)); waitingRoom.addPatient(new Patient(&quot;p3&quot;)); List&lt;Patient&gt; patients = waitingRoom.getAllPatients(); assertEquals(&quot;p1&quot;, patients.get(0).getName()); assertEquals(&quot;p2&quot;, patients.get(1).getName()); assertEquals(&quot;p3&quot;, patients.get(2).getName()); } } </code></pre> <p>The GitHub repo is <a href="https://github.com/marcello-dev/waitingroom" rel="nofollow noreferrer">here</a> for further details.</p> <p>This is how the method <code>move</code> works. Every node in the queue has a position:</p> <ul> <li><code>n1=0</code>: head</li> <li><code>n2=1</code></li> <li><code>n3=2</code></li> <li><code>n4=3</code></li> <li><code>n5=4</code>: tail</li> </ul> <p>Calling the method <code>move(n4,2)</code> means moving the node <code>n4</code> up by 2 positions. It does it in two actions:</p> <ol> <li>Increment by 1 the nodes <code>n3</code> and <code>n2</code>: <code>n1=0</code>, <code>n2=2</code>, <code>n3=3</code>, <code>n4=3</code>, <code>n5=4</code></li> <li>Set the position of <code>n4</code> to <code>n4.position - delta</code> (that is <code>3-2=1</code>): <code>n1=0</code>, <code>n2=2</code>, <code>n3=3</code>, <code>n4=1</code>, <code>n5=4</code></li> </ol> <p>Sorting by position, the nodes are now: <code>n1</code>, <code>n4</code>, <code>n2</code>, <code>n3</code>, <code>n5</code>.</p> <p>Every time the method <code>move</code> needs to update the positions of the nodes in the database, can it be improved? Or can <code>EditableQueue</code> be implemented more efficiently?</p> <p>Any feedbacks, improvements or alternative solutions are welcome. Thanks.</p>
[]
[ { "body": "<p>You didn't include <code>NodeRepo</code> so I'm assuming you're working with JPQL.</p>\n<p><strong>Reduce redundancy</strong></p>\n<p>One of the first things I was taught in database design was to avoid redundant data. Packing the first/last status to each node is entirely redundant and can easily lead to situations where your queue has more than one head or tail. You would also need an index on both columns as that status is a main search criteria in your queries. I assume the need for those columns came from not having a dedicated entity for the <code>Queue</code>. It would be okay to have a <code>Queue</code> entity just for holding the first/last references. It would also allow you to have more than one queue in your database, but that would make the data structure a bit more complicated so let's leave that for future.</p>\n<p><strong>Remove unnecessary data</strong></p>\n<p>But regardless of the Queue entity the first/last information is however completely unnecessary, since you also have the ordinal number on each node. Because that column also needs an index, you can do the first/last query efficiently with <code>order by</code> and <code>limit</code>.</p>\n<pre><code>SELECT * FROM Node\nORDER BY position\nLIMIT 1\n</code></pre>\n<p>The database will optimize this to an O(1) operation. Once you have that, you don't need to juggle the first/last status of each node when manipulating the queue.</p>\n<p><strong>Reduce unnecesary writes</strong></p>\n<p>I'm not sure if you even need the ordinal numbers to be a continuous set. When moving a node, you can query an ordered list of nodes where ordinal number is less than or greater than the node being moved, limited by &quot;absolute value of delta plus one&quot;. If the returned list is smaller than the limit, then you know you're moving to first/last and don't have to touch the values of nodes in between (unless you hit over/underflow of course :)).</p>\n<p><strong>Optimize data structure</strong></p>\n<p>If moves are frequent, you can then optimize the solution to your particular use case by using increments greater than one and use the gaps so that you can move a node between two others without having to always touch the values in the surrounding nodes. For example, if ordinal values are 10, 20 and 30, moving 30 one forward only requires it's ordinal value to be set to 15. (This is, BTW, how we moved code in C64 Basic when we did refactoring).</p>\n<p><strong>Ensure consistency</strong></p>\n<p>Removing the first/last column however adds complexity to concurrency management. Since you're not getting a write lock to the current last node, you run the risk of getting two nodes with the same ordinal number when adding to the end of the queue. You can do optimistic locking by configuring the ordinal number column to be <code>unique</code> (well it should be unique anyway) and simply retrying a write operation if one fails due to a constraint violation. Whether his is more efficient than pessimistic locking depends on your normal use case.</p>\n<p><strong>Minimize data needing to be read</strong></p>\n<p>You've made the correct choice of separating the <code>Node</code> and <code>Patient</code> data from each other so you don't need to load all patient info when manipulating the queue. However you missed a bit: default loading type for <code>OneToOne</code> relation is <code>eager</code> so you will still be loading the patient info every time you load a node. You should change the loading type between <code>Node</code> and <code>Patient</code> to lazy.</p>\n<p>BTW, having a parameterized Node type seems a bit unnecessary since the relation annotation binds it to Patient.class. The type parameter at least should reflect the fact that the entity must be a Patient.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T08:51:46.833", "Id": "494428", "Score": "0", "body": "Thank you for the great review. Getting the head/tail using ORDER BY\nand LIMIT was actually my first implementation, but then I had the (wrong) idea of removing the sorting operation.. Good idea about the Queue as entity and the other optimizations! FYI I added `NodeRepository`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T09:23:55.230", "Id": "494432", "Score": "1", "body": "@Marc Note: I added a paragraph about lazy vs eager loading." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T12:31:56.320", "Id": "494451", "Score": "0", "body": "Good point about lazy loading. The `Patient` class as target entity is my failed tentative to make `Node` completely generic. I'll investigate more on how to do it." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T07:16:57.390", "Id": "251198", "ParentId": "251184", "Score": "3" } } ]
{ "AcceptedAnswerId": "251198", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T00:46:55.537", "Id": "251184", "Score": "6", "Tags": [ "java", "spring" ], "Title": "Persistent waiting room" }
251184
<p>I wrote this code and I just can't stomach it. The idea is that there is a schema, and the goal is to find the entry with <code>autoIncrement</code> set to true. If it's not found, the result should be <code>idProperty</code>.</p> <pre><code>const idProperty = 'id' const schema = { id: { type: 'number' }, code: { type: 'number', autoIncrement: true }, email: { type: 'string', trim: 512 } } // Find the auto increment field let autoIncrementSchemaFieldName = null for (const name in schema) { const entry = schema[name] if (entry.autoIncrement) { autoIncrementSchemaFieldName = name break } } autoIncrementSchemaFieldName = autoIncrementSchemaFieldName || idProperty console.log('RESULT:', autoIncrementSchemaFieldName) </code></pre> <p>Is this really the best way to do it?</p> <p>(To test whether the <code>idProperty</code> fallback works, just rename <code>autoIncrement</code> into <code>autoIncrement2</code> and run it again)</p>
[]
[ { "body": "<p>When you want to find a particular matching value in a data structure, using <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find\" rel=\"nofollow noreferrer\"><code>Array.prototype.find</code></a> is usually the right way to go. It's complicated by the fact that the condition involves the <em>value</em> of the object, but you want the <em>key</em> of the object to be found, so to iterate over the keys and values at once, use <code>Object.entries</code>. It'll give you an array of <code>[key, value]</code> subarrays, and you can return the first item in the resulting subarray to get the key, if anything is found:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const idProperty = 'id';\nconst schema = {\n id: { type: 'number' },\n code: { type: 'number', autoIncrement: true },\n email: { type: 'string', trim: 512 }\n};\n\nconst autoIncrementSchemaFieldName = Object.entries(schema)\n .find(([, value]) =&gt; value.autoIncrement)\n ?.[0] // Extract the key from the found entry\n ?? idProperty; // Otherwise, if no entry was found, use idProperty\n\nconsole.log('RESULT:', autoIncrementSchemaFieldName)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>That's what I'd prefer, but there are a few compatibility caveats:</p>\n<ul>\n<li><code>Object.entries</code> was introduced in 2017. It's not <em>new</em>, but it's not old either</li>\n<li>I'm using optional chaining and the nullish coalescing operator for conciseness, which is only supported in environments built in 2020 and later</li>\n</ul>\n<p>As always, the usual professional solution to compatibility problems is to use <a href=\"https://babeljs.io/\" rel=\"nofollow noreferrer\">Babel</a> to transpile syntax down to ES5 or ES6, and use <a href=\"https://www.npmjs.com/package/es7-object-polyfill\" rel=\"nofollow noreferrer\">polyfills</a> to add new built-in objects and methods.</p>\n<p>Without ES2020, it'd look like:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const idProperty = 'id';\nconst schema = {\n id: { type: 'number' },\n code: { type: 'number', autoIncrement: true },\n email: { type: 'string', trim: 512 }\n};\n\nconst entry = Object.entries(schema)\n .find(([, value]) =&gt; value.autoIncrement);\nconst autoIncrementSchemaFieldName = entry\n ? entry[0]\n : idProperty;\n\nconsole.log('RESULT:', autoIncrementSchemaFieldName)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T01:18:52.303", "Id": "494408", "Score": "1", "body": "OMG is this even Javascript? :D (I am talking out of my own ignorance!) Nice pearls here, having a play -- and thank you" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T01:35:50.810", "Id": "494409", "Score": "0", "body": "What does this do? `?.[0]` -- I get the question mark, marking the chaining optional, but then that `.[0]`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T01:38:49.470", "Id": "494411", "Score": "0", "body": "That's what optional chaining looks like with bracket notation. Dot notation: `obj?.propName`. Bracket notation: `obj?.[propName]` https://stackoverflow.com/q/59623674 The extra dot is needed to distinguish from the conditional operator when the token is first encountered, I think." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T01:13:28.717", "Id": "251186", "ParentId": "251185", "Score": "1" } }, { "body": "<h2>Functions</h2>\n<p>Always write functions. Even if its just an experiment or example code, writing the code as a function provides you with a better representation of the problem at hand.</p>\n<p>As a function the code is easier to read and understand defining the code as a verb, can often provide a simpler solution, keeps the namespace (scope) clean, and is portable</p>\n<h2><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\">for...of</a> rather than <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in\" rel=\"nofollow noreferrer\">for...in</a></h2>\n<p>Do not use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in\" rel=\"nofollow noreferrer\">for...in</a> as it requires guard functionality to ensure you are not traversing outside the objects prototype and own properties.</p>\n<p>The guard typically used with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in\" rel=\"nofollow noreferrer\">for...in</a> is</p>\n<pre><code> for (const name in object) {\n if (object.hasOwnProperty(name)) {\n</code></pre>\n<p>Rather use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\">for...of</a>. With objects you can access keys, properties or both with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys\" rel=\"nofollow noreferrer\">Object.keys(</a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values\" rel=\"nofollow noreferrer\">Object.values(</a> or <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries\" rel=\"nofollow noreferrer\">Object.entries(</a></p>\n<h2>Noise</h2>\n<p>Noise is code that does nothing but interfere with our ability to read and understand the code. There are many forms of code noise, in your code there are three types of noise.</p>\n<p><strong>Redundant and superfluous noise</strong></p>\n<p>You have <code>let autoIncrementSchemaFieldName = null</code> When a variable is declared it is automatically set to <code>undefined</code> there is no need to set the value to <code>null</code></p>\n<p><strong>Comments</strong></p>\n<p>Comments have there place but comments are almost always because the code is not clear.</p>\n<p>You have the comment <code>// Find the auto increment field</code> a clear indication that the code should be a function. If one assumes we know what the code should do then the comment is only noise.</p>\n<p><strong>Naming noise</strong></p>\n<p>Variable names must be easy to identify. Making names too long does not make code more readable, the reverse is true in a variety of ways.</p>\n<p>The following code has a nasty bug that in standard context will not throw an error</p>\n<pre><code> let autoIncrementSchemaFieldName;\n // ... code may assign name a value ...\n autoIncrementSchemaFie1dName = name ?? idProperty;\n</code></pre>\n<p>Due to how we read names typos can be lost in the noise. There is a direct relationship between the length of a name, the chance of introducing an error, and our inability to spot the error.</p>\n<p>General rules of thumb for variable name lengths.</p>\n<ul>\n<li>No more than 20 characters</li>\n<li>Use common abbreviation. Do not use ad-hoc or made up abbreviations.</li>\n<li>Infer via context (scope). The smaller the scope the shorter a name can safely be.</li>\n</ul>\n<h2>Semicolons <code>;</code></h2>\n<p>Yes JavaScript does not require the source code to have semicolons, however to parse JavaScript they are required and are thus inserted automatically before parsing.</p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion\" rel=\"nofollow noreferrer\">Automatic semicolon insertion</a> can be complicated and unless you can, off the top of your head, name all situations that can result in a semicolon not being inserted at the end of a line you should always use semicolons when there is a possibility of a ambiguous end of line.</p>\n<h2>Strict mode</h2>\n<p>If your code is not a module you should ALWAYS start the code with the directive <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode\" rel=\"nofollow noreferrer\">&quot;use strict&quot;;</a></p>\n<p>Reasons to use Strict mode.</p>\n<ul>\n<li><p>Strict mode will throw errors that are ignored in sloppy mode. Sloppy mode bugs can remain dormant until well after release.</p>\n</li>\n<li><p>Strict mode code always executes quicker (The optimizer has more optimization options)</p>\n</li>\n</ul>\n<h2>Bullet proof</h2>\n<p>Bullet proof code is code that never exhibits undefined behavior.</p>\n<p>Your code is not bullet proof as it does not come with a list of expected behaviors for unexpected data</p>\n<p>A list of reasons your code is not bullet proof.</p>\n<ol>\n<li>What if <code>schema</code> does not contain an <code>autoIncrement</code> nor a property <code>id</code>?</li>\n<li>What if <code>autoIncrement</code> is not a boolean?</li>\n<li>What if <code>schema</code> contains non objects?</li>\n<li>What if <code>schema</code> is not an object?</li>\n</ol>\n<p>And maybe outside the functions responsibility, but one would expect it to be.</p>\n<ol start=\"5\">\n<li>What if the object with <code>autoIncrement</code> is not of type <code>&quot;number&quot;</code>?</li>\n<li>What if the default object is not <code>type</code> <code>&quot;number&quot;</code> and there is no <code>autoIncrement</code> object?</li>\n</ol>\n<h2>Rewrite A</h2>\n<p>The following is a rewrite that matches the behavior of your code.</p>\n<p>Note that the code has been moved into a function</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>\"use strict\";\n\nfunction findIncName(schema, defaultName) { \n for (const [name, entry] of Object.entries(schema)) {\n if (entry.autoIncrement) { return name }\n }\n return defaultName;\n}\n\nconsole.log(findIncName({id: {}, code: {autoIncrement: true}}, \"id\"));\nconsole.log(findIncName({id: {}, code: {autoIncrement: false}}, \"id\"));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>Rewrite B</h2>\n<p>The following addresses some of the problems with the code.</p>\n<p>Returns <code>undefined</code> when a name can not be defined according to the rules...</p>\n<ul>\n<li>Name must be of an existing property of schema,</li>\n<li>Be of type <code>&quot;number&quot;</code></li>\n<li>Have a boolean property <code>autoIncrement</code> or be the default name</li>\n</ul>\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\";\n\nfunction findIncName(schema, defaultName) { \n if (schema &amp;&amp; typeof schema === \"object\") {\n for (const [name, entry] of Object.entries(schema)) {\n if (entry?.autoIncrement === true &amp;&amp; entry.type === \"number\") { return name }\n }\n return schema[defaultName]?.type === \"number\" ? defaultName : undefined;\n }\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T16:54:22.840", "Id": "251261", "ParentId": "251185", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T01:03:01.247", "Id": "251185", "Score": "4", "Tags": [ "javascript", "hash" ], "Title": "Find entry in hash depending on hash's data" }
251185
<p>Hello I have writtern this Prolog code to solve a scrambled 2x2 rubiks cube. Also known as a a pocket cube.</p> <pre><code>%the cube is represented as a fact with 24 arguments, %where each argument represents the color of the sticker at that position. %The Positions are according to cube_diagram.png %Test scrambles: %G_scramble := cube(y,y,y,y,r,r,b,b,w,w,w,w,o,o,g,g,b,b,o,o,g,g,r,r). %G_scramble := cube(y,y,y,y,o,o,o,o,w,w,w,w,r,r,r,r,g,g,g,g,b,b,b,b). %G_scramble := cube(b,y,g,o,r,b,o,o,w,y,o,r,r,w,w,b,r,y,w,g,y,b,g,g). %G_scramble := cube(y,y,y,y,r,g,r,r,w,w,w,w,g,o,o,o,b,b,b,b,o,r,g,g). ?- %The scramble to solve G_scramble := cube(b,y,g,w,w,b,r,b,y,y,g,b,o,r,w,o,y,r,w,g,o,g,o,r), write(&quot;the solution to the scramble is:&quot;),nl, solve_layer_one(Solution,G_scramble, C), layer_one_solved(C), write(Solution),nl, orient_top(Solution2, C, X), top_oriented(X), write(Solution2),nl, permute_top(Solution3, X, Z), solved(Z), write(Solution3),nl. side(up). side(up_prim). side(right). side(right_prim). side(front). side(front_prim). t_perm_or_up(t_perm). t_perm_or_up(up). sune_or_up(up). sune_or_up(sune). solved( cube(C1,C1,C1,C1,C2,C2,C2,C2,C3,C3,C3,C3,C4,C4,C4,C4,C5,C5,C5,C5,C6,C6,C6,C6)). layer_one_solved( cube(C1,C2,C3,C4,C5,C6,C7,C7,C8,C8,C8,C8,C9,C10,C11,C11,C12,C13,C14,C14,C15,C16,C17,C17)). top_oriented( cube(C1,C1,C1,C1,C2,C3,C4,C4,C5,C5,C5,C5,C7,C8,C9,C9,C10,C11,C12,C12,C13,C14,C15,C15)). %recursive predicate which finds the moves from scrambled cube to solved layer one. solve_layer_one([], Cube, Cube). solve_layer_one([NextRotation | Rotation], Cube, EndState) :- solve_layer_one(Rotation, CurrentState, EndState), rotateside(NextRotation, Cube, CurrentState), side(NextRotation). %recursive predicate which finds the moves from cube with one layer solved to cube with one layer solve and top oriented. orient_top([], Cube, Cube). orient_top([NextRotation | Rotation], Cube, EndState) :- orient_top(Rotation, CurrentState, EndState), rotateside(NextRotation, Cube, CurrentState), sune_or_up(NextRotation). %recursive predicate which finds the moves from cube with one layer solved and top oriented to solved cube. permute_top([], Cube, Cube). permute_top([NextRotation | Rotation], Cube, EndState) :- permute_top(Rotation, CurrentState, EndState), rotateside(NextRotation, Cube, CurrentState), t_perm_or_up(NextRotation). %permutation of cube after rotating up side clockwise rotateside(up, cube(C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15, C16, C17, C18, C19, C20, C21, C22, C23, C24), cube(C3, C1, C4, C2, C21, C22, C7, C8, C9, C10, C11, C12, C17, C18, C15, C16, C5, C6, C19, C20, C13, C14, C23, C24)). %permutation of cube after rotating up side anti-clockwise rotateside(up_prim, cube(C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15, C16, C17, C18, C19, C20, C21, C22, C23, C24), cube(C2, C4, C1, C3, C17, C18, C7, C8, C9, C10, C11, C12, C21, C22, C15, C16, C13, C14, C19, C20, C5, C6, C23, C24)). %permutation of cube after rotating right side clockwise rotateside(right, cube(C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15, C16, C17, C18, C19, C20, C21, C22, C23, C24), cube(C1, C6, C3, C8, C5, C10, C7, C12, C9, C15, C11, C13, C4, C14, C2, C16, C17, C18, C19, C20, C23, C21, C24, C22)). %permutation of cube after rotating right side anti-clockwise rotateside(right_prim, cube(C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15, C16, C17, C18, C19, C20, C21, C22, C23, C24), cube(C1, C15, C3, C13, C5, C2, C7, C4, C9, C6, C11, C8, C12, C14, C10, C16, C17, C18, C19, C20, C22, C24, C21, C23)). %permutation of cube after rotating front side clockwise rotateside(front, cube(C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15, C16, C17, C18, C19, C20, C21, C22, C23, C24), cube(C1, C2, C20, C18, C7, C5, C8, C6, C23, C21, C11, C12, C13, C14, C15, C16, C17, C9, C19, C10, C3, C22, C4, C24)). %permutation of cube after rotating front side anti-clockwise rotateside(front_prim, cube(C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15, C16, C17, C18, C19, C20, C21, C22, C23, C24), cube(C1, C2, C21, C23, C6, C8, C5, C7, C18, C20, C11, C12, C13, C14, C15, C16, C17, C4, C19, C3, C10, C22, C9, C24)). %permutation of cube after doing the sune algorithm rotateside(sune, cube(C1 , C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15, C16, C17, C18, C19, C20, C21, C22, C23, C24), cube(C6 , C3, C22, C14, C2, C17, C7, C8, C9, C10, C11, C12, C5, C21, C15, C16, C4, C13, C19, C20, C1, C18, C23, C24)). %permutation of cube after doing the t_perm algorithm rotateside(t_perm, cube(C1 , C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15, C16, C17, C18, C19, C20, C21, C22, C23, C24), cube(C1 , C2, C3, C4, C5, C22, C7, C8, C9, C10, C11, C12, C21, C14, C15, C16, C17, C18, C19, C20, C13, C6, C23, C24)). <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T01:59:20.893", "Id": "251188", "Score": "1", "Tags": [ "algorithm", "recursion", "prolog" ], "Title": "Pocket cube solver in Prolog" }
251188
<p>I have code for a 64-bit timer register which can take in a 32-bit slice and depending on the inputs, place the slice in the high side or the low side, or increment the counter.</p> <pre><code>library IEEE; use IEEE.STD_LOGIC_1164.ALL; use IEEE.NUMERIC_STD.ALL; entity CSR_TIMER is Port ( clk : in STD_LOGIC; reset: in STD_LOGIC := '0'; DATA_IN : in STD_LOGIC_VECTOR (31 downto 0); EN_WRITE_LOW : in STD_LOGIC; EN_WRITE_HIGH : in STD_LOGIC; DATA_LOW_OUT : out STD_LOGIC_VECTOR (31 downto 0); DATA_HIGH_OUT : out STD_LOGIC_VECTOR (31 downto 0)); end CSR_TIMER; architecture Behavioral of CSR_TIMER is signal clock,clock_next : unsigned(63 downto 0) := x&quot;0000000000000000&quot;; begin clock_next &lt;= x&quot;0000000000000000&quot; when (reset = '1') else clock(63 downto 32) &amp; unsigned(DATA_IN) when (EN_WRITE_LOW = '1') else unsigned(DATA_IN) &amp; clock(31 downto 0) when (EN_WRITE_HIGH = '1') else clock+1; DATA_LOW_OUT &lt;= std_logic_vector(clock(31 downto 0)); DATA_HIGH_OUT &lt;= std_logic_vector(clock(63 downto 32)); process(clk) begin if(rising_edge(clk)) then clock&lt;=clock_next; end if; end process; end Behavioral; </code></pre> <p>The trouble that I'm having is that the timer takes up too many physical resources, and I'm looking to shrink it down. This is for a RISC-V Processor where the ISA specifies that a proper processor has 32 of these timers, which is 2kb of on-board memory, and is not friendly to any FPGA. The Data_Low_out and data_high_out are connected to a mux, where they are treated as separate registers at different addresses.</p> <p>How can I optimize this timer ( or a group of 32 timers ) to reduce the physical resource usage? This is synthesized using Vivado 2020.1.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T06:03:07.577", "Id": "494421", "Score": "1", "body": "Hi, please [edit] the title of this question so that it **only states the purpose of your code**, anything else belongs to the body" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T02:22:37.133", "Id": "251189", "Score": "2", "Tags": [ "memory-optimization", "vhdl" ], "Title": "this VHDL code for a 64-bit timer?" }
251189
<p><a href="https://www.hackerrank.com/challenges/queens-attack-2/problem" rel="nofollow noreferrer">https://www.hackerrank.com/challenges/queens-attack-2/problem</a></p> <p>A queen is standing on an nxn chessboard. The chessboard's rows are numbered from 1 to n, going from bottom to top; its columns are numbered from 1 to n, going from left to right. Each square on the board is denoted by a tuple, (r,c), describing the row, r, and column, c, where the square is located.</p> <p>The queen is standing at position (rq,cq) and, in a single move, she can attack any square in any of the eight directions (left, right, up, down, or the four diagonals). In the diagram below, the green circles denote all the cells the queen can attack from (4,4):</p> <p><a href="https://i.stack.imgur.com/3Sa2u.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3Sa2u.png" alt="enter image description here" /></a></p> <p>There are <span class="math-container">\$k\$</span> obstacles on the chessboard preventing the queen from attacking any square that has an obstacle blocking the the queen's path to it. For example, an obstacle at location <span class="math-container">\$(3,5)\$</span> in the diagram above would prevent the queen from attacking cells <span class="math-container">\$(3,5)\$</span>, <span class="math-container">\$(2,6)\$</span>, and <span class="math-container">\$(1,7)\$</span>:</p> <p><a href="https://i.stack.imgur.com/dXa45.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dXa45.png" alt="enter image description here" /></a></p> <p>Given the queen's position and the locations of all the obstacles, find and print the number of squares the queen can attack from her position at <span class="math-container">\$(r_q,c_q)\$</span>.</p> <p><strong>Input Format</strong></p> <p>The first line contains two space-separated integers describing the respective values of <span class="math-container">\$n\$</span> (the side length of the board) and <span class="math-container">\$k\$</span> (the number of obstacles).</p> <p>The next line contains two space-separated integers describing the respective values of <span class="math-container">\$r_q\$</span> and <span class="math-container">\$c_q\$</span>, denoting the position of the queen.</p> <p>Each line <span class="math-container">\$i\$</span> of the <span class="math-container">\$k\$</span> subsequent lines contains two space-separated integers describing the respective values <span class="math-container">\$r_i\$</span> of <span class="math-container">\$c_i\$</span> and , denoting the position of obstacle <span class="math-container">\$i\$</span>.</p> <p><strong>Constraints</strong></p> <p><span class="math-container">\$ 0 \leq n \leq 100000\$</span></p> <p><span class="math-container">\$ 0 \leq k \leq 100000\$</span></p> <p>A single cell may contain more than one obstacle; however, it is guaranteed that there will never be an obstacle at position <span class="math-container">\$(r_q,c_q)\$</span> where the queen is located.</p> <p><strong>Output Format</strong></p> <p>Print the number of squares that the queen can attack from position .</p> <p><strong>Sample Input 0</strong></p> <p><span class="math-container">\$4\$</span> <span class="math-container">\$0\$</span></p> <p><span class="math-container">\$4\$</span> <span class="math-container">\$4\$</span></p> <p><strong>Sample Output 0</strong></p> <p><span class="math-container">\$9\$</span></p> <p><strong>Explanation 0</strong></p> <p>The queen is standing at position <span class="math-container">\$(4,4)\$</span> on a <span class="math-container">\$4\$</span>x<span class="math-container">\$4\$</span> chessboard with no obstacles:</p> <p><a href="https://i.stack.imgur.com/ShVlV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ShVlV.png" alt="enter image description here" /></a></p> <p>We then print the number of squares she can attack from that position, which is <span class="math-container">\$9\$</span>.</p> <p><strong>My approach:</strong></p> <p>Instead of iterating through every single point in the queens path as that will be resource intensive when n is very high, I went with separating the paths into 8 different directions (up left, up, up right, right, etc).</p> <pre><code>int u, d, l, r, ul, ur, dl, dr; u = d = l = r = ul = ur = dl = dr = 0; bool modified[8] = { false }; </code></pre> <p>Than I checked if there is an obstacle in the path by checking if the queens x = obstacles x or queens y = obstacles y and if its on the vertical/horizontal path of the queens I would find the distance by calculating the delta - 1 and to find the diagonal points I know since the points either have to have a 1 or -1 slope to be in the queens path so I checked if |queen's y - obstacle's y| = |queen's x - obstacle's x| and if it is true than I find the delta between either the x or y as either work and if there is no obstacles I would just use the edge to find the distance. I only checks to see if obstacle was in path then calculate the possible points than mark the direction as solved so if it is unmarked than it means there is no obstacles in the path so I find the distance from edge using:</p> <pre><code>if (!modified[0]) u = n - qy; if (!modified[1]) d = qy - 1; if (!modified[2]) l = qx - 1; if (!modified[3]) r = n - qx; if (!modified[4] &amp;&amp; qy != n &amp;&amp; qx != 1) ul = (qx - 1 &lt; n - qy) ? qx - 1 : n - qy; if (!modified[5] &amp;&amp; qy != n &amp;&amp; qx != n) ur = (n - qx &lt; n - qy) ? n - qx : n - qy; if (!modified[6] &amp;&amp; qy != 1 &amp;&amp; qx != 1) dl = (qx - 1 &lt; qy - 1) ? qx - 1 : qy - 1; if (!modified[7] &amp;&amp; qy != 1 &amp;&amp; qx != n) dr = (n - qx &lt; qy - 1) ? n - qx : qy - 1; </code></pre> <p>Sorry for messy style, this is my first time on stackoverflow/stackexchange.</p> <p>Full code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; #include &lt;cmath&gt; using namespace std; int queensAttack(const int &amp;n, const int &amp;k, const int &amp; qy, const int &amp; qx, const vector&lt;vector&lt;int&gt;&gt; &amp;obstacles) { int u, d, l, r, ul, ur, dl, dr; //up, down, left, right, up-left, up-right, down-left, down-right u = d = l = r = ul = ur = dl = dr = 0; bool modified[8] = { false }; //if modified is still false after looping through obstacles check that means no obstacle at path for (int i = 0; i &lt; obstacles.size(); i++) { //loop through all obstacles, if it is in path get distance to queen int temp{}; if (obstacles[i][1] == qx) { //if obstacle x = queen x than they are on same column if (obstacles[i][0] &gt; qy) { //check if its above or below queen temp = obstacles[i][0] - qy - 1; if (modified[0] &amp;&amp; u &gt; temp || !modified[0]) { //only assign distance if it was never assigned before or less than it u = temp; } modified[0] = true; } else { temp = qy - obstacles[i][0] - 1; if (modified[1] &amp;&amp; d &gt; temp || !modified[1]) { d = temp; } modified[1] = true; } } if (obstacles[i][0] == qy) { if (obstacles[i][1] &lt; qx) { temp = qx - obstacles[i][1] - 1; if (modified[2] &amp;&amp; l &gt; temp || !modified[2]) { l = temp; } modified[2] = true; } else { temp = obstacles[i][1] - qx - 1; if (modified[3] &amp;&amp; r &gt; temp || !modified[3]) { r = temp; } modified[3] = true; } } if (abs(qy - obstacles[i][0]) == abs(qx - obstacles[i][1])) { //diagonals, checking if it is on the diagonal path of the queen if (obstacles[i][0] &gt; qy &amp;&amp; obstacles[i][1] &lt; qx) { //check if it is top left diagonal temp = qx - obstacles[i][1] - 1; if (modified[4] &amp;&amp; ul &gt; temp || !modified[4]) { ul = temp; } modified[4] = true; } if (obstacles[i][0] &gt; qy &amp;&amp; obstacles[i][1] &gt; qx) { //check if it is top right diagonal temp = obstacles[i][1] - qx - 1; if (modified[5] &amp;&amp; ur &gt; temp || !modified[5]) { ur = temp; } modified[5] = true; } if (obstacles[i][0] &lt; qy &amp;&amp; obstacles[i][1] &lt; qx) { //check if it is bottom left diagonal temp = qx - obstacles[i][1] - 1; if (modified[6] &amp;&amp; dl &gt; temp || !modified[6]) { dl = temp; } modified[6] = true; } if (obstacles[i][0] &lt; qy &amp;&amp; obstacles[i][1] &gt; qx) { //check if it is bottom right diagonal temp = obstacles[i][1] - qx - 1; if (modified[7] &amp;&amp; dr &gt; temp || !modified[7]) { dr = temp; } modified[7] = true; } } } if (!modified[0]) u = n - qy; //if they never been modified means no obstacles in path so use calculate distance from edge to queen (probably better way to do this) if (!modified[1]) d = qy - 1; if (!modified[2]) l = qx - 1; if (!modified[3]) r = n - qx; if (!modified[4] &amp;&amp; qy != n &amp;&amp; qx != 1) ul = (qx - 1 &lt; n - qy) ? qx - 1 : n - qy; if (!modified[5] &amp;&amp; qy != n &amp;&amp; qx != n) ur = (n - qx &lt; n - qy) ? n - qx : n - qy; if (!modified[6] &amp;&amp; qy != 1 &amp;&amp; qx != 1) dl = (qx - 1 &lt; qy - 1) ? qx - 1 : qy - 1; if (!modified[7] &amp;&amp; qy != 1 &amp;&amp; qx != n) dr = (n - qx &lt; qy - 1) ? n - qx : qy - 1; return u + d + l + r + ul + ur + dl + dr; } int main() { int n, k, qx, qy; cin &gt;&gt; n &gt;&gt; k &gt;&gt; qy &gt;&gt; qx; const int c = k; vector&lt;vector&lt;int&gt;&gt; ob(k); for (int i = 0; i &lt; k; i++) { ob[i].resize(2); cin &gt;&gt; ob[i][0] &gt;&gt; ob[i][1]; } cout &lt;&lt; queensAttack(n,k,qy,qx,ob); return 0; } </code></pre> <p>Forgot to mention I loop through the obstacles and only replaces the current distance if the new one is smaller as the obstacles in the array aren't in order from closest to farthest.</p> <p>Can I get some feedback or suggestions for improvement? Thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T03:36:01.337", "Id": "494413", "Score": "0", "body": "Also, do you want a review of your answer strictly or do you want to see alternate approaches too?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T05:30:09.357", "Id": "494418", "Score": "1", "body": "Please post a program which is also able to be executed. Please create an `int main()` and call your function with some example-values. Please use meaningful variable names. Please don't do things like this -> `u = d = l = r = ul = ur = dl = dr = 0;` PS some `/* comments */` would help for better understanding your program" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T11:07:42.030", "Id": "494438", "Score": "0", "body": "It is absolutely pointless to have constant reference to primitive types. The whole idea of reference is to not pass whole object, but only a much smaller pointer. In the case of primitive types, they are already small, and you wouldn't gain anything by passing const int's as const int refs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T11:37:56.347", "Id": "494447", "Score": "0", "body": "@paladin This is the part of the code that the program challenge left to be programmed, the rest of the program is provided by Hacker Rank. This is very common with questions from code challenge sites. In other words the Original Poster posted all the code they wrote." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T12:02:24.917", "Id": "494449", "Score": "1", "body": "@pacmaninbw I know about this, but OP should anyway implement his own testing environment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T14:41:46.887", "Id": "494457", "Score": "0", "body": "@paladin I did make my own environment but I didn’t post it as it would be made the code a lot longer and messy and the variable names are just u = up, d = down, ul = up left etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T14:44:00.000", "Id": "494458", "Score": "0", "body": "@Ilkhd I did const references because I was told that was good practice so I don’t modify those by accident and I did const to save memory as there was a limit most people ran into when iterating through whole grid." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T15:33:13.780", "Id": "494461", "Score": "0", "body": "@Bork It's a simple rule, just don't pass the built-in types by a constant reference, like `int, float , char` but something like `std::string` or `std::vector` is large, there you should use a constant reference or a pointer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T18:59:02.130", "Id": "494489", "Score": "0", "body": "@AryanParekh ok thank you!" } ]
[ { "body": "<h2>General Observations</h2>\n<p>It was good that you included the necessary headers rather than using the catchall header provided by Hacker Rank. You did include headers that were unnecessary, the code compiles without <code>cmath</code> or <code>algorithm</code>. Only include what is necessary to make the code compile. Using unnecessary headers can increase build times because C++ actually creates a temporary file and copies the headers into that temporary file.</p>\n<p>As a professional software developer one needs to be concerned with maintenance of the code (adding features, fixing bugs). You may write code but not be the person that maintains it because you could be on vacation, you may have gotten a better job at another company, you may have suddenly become rich.</p>\n<p>This code will be very difficult to maintain. Some of it is very easy to read and some of it is almost unreadable. Some examples of almost unreadable code are:</p>\n<pre><code> int u, d, l, r, ul, ur, dl, dr; //up, down, left, right, up-left, up-right, down-left, down-right\n u = d = l = r = ul = ur = dl = dr = 0;\n</code></pre>\n<p>and</p>\n<pre><code> if (!modified[0]) u = n - qy; //if they never been modified means no obstacles in path so use calculate distance from edge to queen (probably better way to do this)\n if (!modified[1]) d = qy - 1;\n if (!modified[2]) l = qx - 1;\n if (!modified[3]) r = n - qx;\n if (!modified[4] &amp;&amp; qy != n &amp;&amp; qx != 1) ul = (qx - 1 &lt; n - qy) ? qx - 1 : n - qy;\n if (!modified[5] &amp;&amp; qy != n &amp;&amp; qx != n) ur = (n - qx &lt; n - qy) ? n - qx : n - qy;\n if (!modified[6] &amp;&amp; qy != 1 &amp;&amp; qx != 1) dl = (qx - 1 &lt; qy - 1) ? qx - 1 : qy - 1;\n if (!modified[7] &amp;&amp; qy != 1 &amp;&amp; qx != n) dr = (n - qx &lt; qy - 1) ? n - qx : qy - 1;\n</code></pre>\n<p>The function <code>queensAttack()</code> is 88 lines and a single function that size is very difficult to write, read, debug or maintain.</p>\n<h2>Avoid <code>using namespace std;</code></h2>\n<p>If you are coding professionally you probably should get out of the habit of using the <code>using namespace std;</code> statement. The code will more clearly define where <code>cout</code> and other identifiers are coming from (<code>std::cin</code>, <code>std::cout</code>). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The identifier<code>cout</code> you may override within your own classes, and you may override the operator <code>&lt;&lt;</code> in your own classes as well. This <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">stack overflow question</a> discusses this in more detail.</p>\n<h2>Complexity</h2>\n<p>The function <code>queensAttack()</code> is too complex (does too much). It should be broken up into functions, I see at least 3 possible functions and probably more. A good design technique is to keep breaking a problem into separate smaller problems until each problem is very easy to solve. This also make the code more maintainable.</p>\n<p>There is also a programming principle called the Single Responsibility Principle that applies here. The <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> states:</p>\n<blockquote>\n<p>that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.</p>\n</blockquote>\n<h2>Magic Numbers</h2>\n<p>There are Magic Numbers in the <code>queensAttack()</code> function (0 through 7), it might be better to create symbolic constants for them to make the code more readable and easier to maintain, in this case an enum could also be used. These numbers may be used in many places and being able to change them by editing only one line makes maintenance easier.</p>\n<p>Numeric constants in code are sometimes referred to as <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">Magic Numbers</a>, because there is no obvious meaning for them. There is a discussion of this on <a href=\"https://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad\">stackoverflow</a>.</p>\n<h2>Prefer <code>unsigned</code> Types to Integer for Index Variables</h2>\n<p>When indexing into arrays or other container types it is better to use unsigned types such as <code>size_t</code> rather than integers. Unsigned types cannot become negative and using a negative index can lead to undefined behavior. The <code>size()</code> function of all container types returns <code>size_t</code> and the code is generating a type mismatch warning in the for loop:</p>\n<pre><code> for (int i = 0; i &lt; obstacles.size(); i++) { //loop through all obstacles, if it is in path get distance to queen\n</code></pre>\n<h2>Variable Declarations</h2>\n<p>Declare and initialize variables one per line. While the following results in a lot of added vertical space it is easier to read and maintain:</p>\n<pre><code> int u = 0;\n int d = 0;\n int l = 0;\n int r = 0;\n int ul = 0;\n int ur = 0;\n int dl = 0;\n int dr = 0;\n bool modified[8] = { false };\n</code></pre>\n<p>If some needs to add or delete a variable it is much easier to add a line or delete a line than to modify the current code. In this case it might also be possible to have an array of directions that matches the array of modifications that already exists, especially if the enum mentioned above is used to index both arrays.</p>\n<h2>Variable Names</h2>\n<p>It is generally better to use descriptive variable names to make the code more readable. Comments are okay, but they need to be maintained as well, self documenting code is better than using comments when that can be done.</p>\n<h2>DRY Code</h2>\n<p>There is a programming principle called the <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">Don't Repeat Yourself Principle</a> sometimes referred to as DRY code. If you find yourself repeating the same code multiple times it is better to encapsulate it in a function. If it is possible to loop through the code that can reduce repetition as well.</p>\n<p>This is very repetitious code:</p>\n<pre><code> if (abs(qy - obstacles[i][0]) == abs(qx - obstacles[i][1])) { //diagonals, checking if it is on the diagonal path of the queen\n if (obstacles[i][0] &gt; qy &amp;&amp; obstacles[i][1] &lt; qx) { //check if it is top left diagonal\n temp = qx - obstacles[i][1] - 1;\n if (modified[4] &amp;&amp; ul &gt; temp || !modified[4]) {\n ul = temp;\n }\n modified[4] = true;\n }\n if (obstacles[i][0] &gt; qy &amp;&amp; obstacles[i][1] &gt; qx) { //check if it is top right diagonal\n temp = obstacles[i][1] - qx - 1;\n if (modified[5] &amp;&amp; ur &gt; temp || !modified[5]) {\n ur = temp;\n }\n modified[5] = true;\n }\n if (obstacles[i][0] &lt; qy &amp;&amp; obstacles[i][1] &lt; qx) { //check if it is bottom left diagonal\n temp = qx - obstacles[i][1] - 1;\n if (modified[6] &amp;&amp; dl &gt; temp || !modified[6]) {\n dl = temp;\n }\n modified[6] = true;\n }\n if (obstacles[i][0] &lt; qy &amp;&amp; obstacles[i][1] &gt; qx) { //check if it is bottom right diagonal\n temp = obstacles[i][1] - qx - 1;\n if (modified[7] &amp;&amp; dr &gt; temp || !modified[7]) {\n dr = temp;\n }\n modified[7] = true;\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T02:34:00.557", "Id": "494505", "Score": "0", "body": "Thank you so much! " }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T17:40:14.537", "Id": "494568", "Score": "0", "body": "The function `queensAttack()` should not be broken up. Instead, the algorithm should be reworked." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T17:53:39.773", "Id": "494569", "Score": "0", "body": "Amazing answer. I tried to edit and correct the formatting by changing \"##Complexity\" to \"## Complexity\", but Stack doesn't allow such a tiny change." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T18:02:53.663", "Id": "494571", "Score": "0", "body": "@JSmart523 thank you for the heads up, I fixed the formatting." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T18:26:08.920", "Id": "494577", "Score": "0", "body": "@Deduplicator I agree the algorithm should be reworked, the goal of my review was to improve some programming habits, and it may provide the OP with an understanding of why another algorithm would be better." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T00:19:20.840", "Id": "251237", "ParentId": "251190", "Score": "4" } }, { "body": "<h3>Your Code:</h3>\n<ol>\n<li><p>Good on you to only include the headers you think you need. You don't use anything from <code>&lt;cmath&gt;</code> or <code>&lt;algorithm&gt;</code> though.</p>\n</li>\n<li><p><code>using namespace std;</code> is plain evil. That namespace is not designed for inclusion, thus there is no comprehensive, fixed and reliable list of its contents.<br />\nSee &quot;<a href=\"//stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Why is “using namespace std;” considered bad practice?</a>&quot; for details.</p>\n</li>\n<li><p>Small trivial types are better passed by copy than by value. Less indirection means more efficient access, and no need to beware of anyone else mucking about with the value, which improves reasoning about the code and generally enables better optimisation.<br />\nSee &quot;<em><a href=\"//softwareengineering.stackexchange.com/a/356200/155513\">In C++, why shouldn't all function parameters be references?</a></em>&quot;.</p>\n</li>\n<li><p>Take a look at <a href=\"https://en.cppreference.com/w/cpp/container/span\" rel=\"nofollow noreferrer\"><code>std::span</code></a> for passing a view of contiguous objects.<br />\nSee also &quot;<em><a href=\"//stackoverflow.com/questions/45723819/what-is-a-span-and-when-should-i-use-one\">What is a “span” and when should I use one?</a></em>&quot;.</p>\n</li>\n<li><p>C++ has for-range loops since C++11. Much less error-prone than manually fiddling with indices or iterators.</p>\n</li>\n<li><p>Using flags to check whether a ray encountered an obstacle and otherwise returning the maximum is distinctly sub-optimal. Just initialize with the maximum and update that as needed.</p>\n</li>\n<li><p>A <code>std::vector</code> of length two is a <em>very</em> poor data-structure to store a point's coordinates. It is very inefficient, inconvenient and error-prone. At least use a <code>std::pair</code>, <code>std::array</code>, or <code>std::tuple</code>, if you decline to invest a single line for a trivial custom type.</p>\n</li>\n<li><p>Your code never tests the user-input is well-formed. Actually, that can be justified for a challenge like this, so let's keep it.</p>\n</li>\n<li><p><code>return 0;</code> is implicit for <code>main()</code> in C++ and C99+.</p>\n</li>\n</ol>\n<h3>Your approach can be optimized and simplified further:</h3>\n<ol>\n<li><p>Use a queen-centric coordinate-system. All the checks are about the queen, and now much simpler.</p>\n</li>\n<li><p>If you store the reach of each arm of the queen's attack considering the obstacles you know (initialise with the border), you can immediately drop each obstacle after processing.</p>\n</li>\n</ol>\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;iostream&gt;\n\nint main() {\n int x, y, k, qx, qy;\n std::cin &gt;&gt; x &gt;&gt; k &gt;&gt; qx &gt;&gt; qy;\n\n int d = qy,\n l = qx,\n u = x + 1 - qy,\n r = x + 1 - qx;\n int dl = std::min(d, l),\n dr = std::min(d, r),\n ul = std::min(u, l),\n ur = std::min(u, r);\n auto update = [](int a, int&amp; b, int&amp; c){\n if (a &lt; 0)\n b = std::min(b, -a);\n else\n c = std::min(c, a);\n };\n\n while (k--) {\n std::cin &gt;&gt; x &gt;&gt; y;\n x -= qx;\n y -= qy;\n if (!x)\n update(y, d, u);\n else if (!y)\n update(x, l, r);\n else if (x == y)\n update(x, dl, ur);\n else if (x == -y)\n update(x, ul, dr);\n }\n\n std::cout &lt;&lt; (d + u + l + r + dl + dr + ul + ur - 8);\n}\n</code></pre>\n<p>Beware: The above code was only proven right, never run.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T17:35:16.953", "Id": "251262", "ParentId": "251190", "Score": "2" } } ]
{ "AcceptedAnswerId": "251237", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T02:47:26.493", "Id": "251190", "Score": "6", "Tags": [ "c++", "programming-challenge", "chess" ], "Title": "Hackerrank's Queen's Attack II" }
251190
<p>I am writing a script to read rows (records) from an excel file with <strong>xlrd</strong> package and then create a dictionary for each row. In next step, I append each dictionary to a list. After I finished reading rows from excel file and prepared the list of dictionaries; I use <code>odoorpc</code> to connect to the interface of an Odoo application and create records in an Odoo model (database table). But before writing the records to the Odoo model I need to make sure to not insert duplicate rows (dictionaries) to the Odoo model. I wrote bellow script, now I want to know where in my script I should check for duplicate rows? Should I do it when I read rows from excel file or check it in the list of dictionaries I have created from rows or even do one select query to the database and check for existent of rows in database? I am asking this because I need to improve performance and also understand how to check for duplicate dictionary as items in a list of dictionaries.</p> <pre><code># -*- coding: utf-8 -*- import psycopg2 import psycopg2.extras import sys import odoorpc import xlrd import base64 class Product(): #Database connection def connet_to_database(self): self.apps_params = { &quot;database&quot;:&quot;test_db&quot;, &quot;user&quot;:&quot;postures&quot;, &quot;password&quot;:&quot;testpassword&quot;, &quot;host&quot;: &quot;testipaddress&quot;, &quot;port&quot; : &quot;5432&quot; } try: self.db_connection = psycopg2.connect(**self.apps_params) self.db_cursor = self.db_connection.cursor(cursor_factory=psycopg2.extras.RealDictCursor) psycopg2.extensions.register_type(psycopg2.extensions.UNICODE) psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY) print ('\033[1;32m Successfully Connected to Database \033[1;m') except: print ('Could not Connected to Database', sys.exc_info()[1]) return # Interface connection to add product itmes. def connect_to_interface(self): try: odoo = odoorpc.ODOO('127.0.0.1', port=8000) odoo.login('setara_erp','admin', 'admin') user = odoo.env.user print('\033[1;32m Successfully Connected to Interface \033[1;m') return odoo, user except Exception as e: print('Could not Connected to Interface', sys.exc_info()[1], e) return def add_product_item(self): connection = self.connect_to_interface() user = connection[1] xmlrpc_object = connection[0] counter = 0 product_items = [] product_item_values = {} file_location = 'product_items.xlsx' workbook = xlrd.open_workbook(file_location) sheet = workbook.sheet_by_index(0) for i in range(sheet.nrows): print('Adding item values to list: ', i) commodity_group_name = sheet.row_values(i)[3] commodity_group_id = None self.db_cursor.execute(&quot;&quot;&quot; SELECT id FROM commodity_group WHERE name =%s&quot;&quot;&quot;, (commodity_group_name,) ) commodity_group = self.db_cursor.fetchone() if commodity_group: commodity_group_id = commodity_group['id'] encoded_string = '' try: with open('photos/'+sheet.row_values(i)[4], &quot;rb&quot;) as image_file: encoded_string = base64.b64encode(image_file.read()).decode(&quot;utf-8&quot;) except Exception as e: print('File not found for this product item.', sheet.row_values(i)[4]) product_item_values = { 'active': True, 'type': 'product', 'default_code': sheet.row_values(i)[0], 'name': sheet.row_values(i)[1], 'image_1920': encoded_string, 'part_number': sheet.row_values(i)[2], 'commodity_group_id': commodity_group_id, } product_items.append(product_item_values) try: for item in product_items: xmlrpc_object.execute('product.template', 'create', item) print (str(counter)+' Items added') counter +=1 except Exception as e: print ('Could not add product. ', e) apps = Product() apps.connet_to_database() apps.connect_to_interface() apps.add_product_item() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T14:41:24.950", "Id": "494456", "Score": "0", "body": "What is the criteria for detecting duplicates?" } ]
[ { "body": "<h2>Passwords</h2>\n<p>I sincerely hope that <code>testpassword</code> and <code>admin</code> will be replaced with more secure passwords. Also, they should not be hard-coded in this script; externalize them to a configuration file, wallet, environmental variables or the like, following good security practices.</p>\n<h2>Grammar</h2>\n<p><code>Could not Connected to Interface</code> -&gt; <code>Could not Connect to Interface</code></p>\n<h2>Magic indexes</h2>\n<pre><code>sheet.row_values(i)[3]\nsheet.row_values(i)[4]\n</code></pre>\n<p>are mysterious. I understand that you're getting them out of a spreadsheet so options for structure are limited, but XLSX (and <code>xlrd</code>) support named ranges. You should use these and avoid magic indexes to improve legibility and maintainability. This assumes that you have control over the format of the spreadsheet.</p>\n<p>If you do not control the spreadsheet, consider doing this in your loop:</p>\n<pre><code>default_code, name, part_number, commodity_group_name, photo = sheet.row_values(i)[:5]\n</code></pre>\n<p>which will be a little more clear.</p>\n<h2>Encoding</h2>\n<p>It appears that you're doing your own base-64 encoding and putting that into a string col. Do not do this. Use an actual blob; psycopg2 supports this natively.</p>\n<h2>Interactive vs. non-interactive</h2>\n<p>These:</p>\n<pre><code>\\033[1;32m\n</code></pre>\n<p>will harm your logs, if you ever need to run this in non-interactive mode. Consider deleting them altogether, or (if you have a burning desire for fancy text) wrap this in a function that conditionally shows ANSI escape codes. Read <a href=\"https://stackoverflow.com/questions/7445658/how-to-detect-if-the-console-does-support-ansi-escape-codes-in-python\">this</a> and similar.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T15:56:40.947", "Id": "494464", "Score": "0", "body": "There is also double call to `connect_to_interface`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T05:04:49.490", "Id": "494507", "Score": "0", "body": "Thank you for the nice comments, I will improve the script considering these points. But my main question was about where should I check for duplicate rows (records) in the script? Also, for the list I have created, how should I check if one dictionary exist in that list of not?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T15:43:20.937", "Id": "251215", "ParentId": "251197", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T07:10:17.130", "Id": "251197", "Score": "3", "Tags": [ "python", "performance", "python-3.x", "odoo" ], "Title": "Find if duplicate items exists in a list of dictionaries" }
251197
<pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;math.h&gt; #include &lt;omp.h&gt; #define MAXN 10*1000*1000 int fillarray(unsigned maxn, int *p, int psize) { int i, top = 1; int n; p[0] = 3; printf(&quot; 2\n 3\n&quot;); for (n = 5;; n += 2) for (i = 0; n % p[i] != 0; i++) if (p[i] * p[i] &gt; n) { printf(&quot;%6d\n&quot;, n); p[top] = n; if (n * n &gt; maxn) return top; if (++top == psize) { printf(&quot;Array too short\n&quot;); return -1; } break; } } int main() { unsigned n, maxn = MAXN; int sum; /* Prime Number Theorem formula (x/logx) to find approx. size of array p[]. Needs some safety margin. */ int psize = 10 + 1.2 * sqrt(maxn) / log(sqrt(maxn)); int p[psize], *pp; int lastp = fillarray(maxn, p, psize); if (lastp &lt; 0) return 1; /* &quot;3&quot; is p[0], plus the &quot;2&quot; */ sum = lastp + 2; #pragma omp parallel for private(pp) schedule(guided) reduction(+:sum) for (n = p[lastp] + 2; n &lt;= maxn; n += 2) for (pp = p; n % *pp &gt; 0; pp++) if (*pp * *pp &gt; n) { printf(&quot;%d\n&quot;, n); sum++; break; } printf(&quot;SUM %d (%.2f%%)\n&quot;, sum, (double) 100*sum / maxn) ; double lnx = maxn / log(maxn); printf(&quot;LnX %.2f (%f)\n&quot;, lnx, sum / lnx); printf(&quot;psize %d\n&quot;, psize); printf(&quot;p[0] p[1]...p[%d] %d %d...%d\n&quot;, lastp, p[0], p[1], p[lastp]); return 0; } </code></pre> <p>Compile with -fopenmp. And -lm for clang. But it works also without openmp.</p> <p>Output:</p> <pre><code># time ./a.out |tail 9999971 9999901 9999931 9999973 9999991 9999937 SUM 664579 (6.65%) LnX 620420.69 (1.071175) psize 480 p[0] p[1]...p[445] 3 5...3163 real 0m0.274s user 0m1.497s sys 0m0.402s </code></pre> <p>It takes 445 primes to reach 3163, whose square is &gt; 10 million. The array size is 480. The output is not sorted, the threads print them directly.</p> <p>The first (single-threaded) phase i.e. fillarray() takes no time compared to second, multi-threaded phase.</p> <p>In main() the prime test is inlined, and written with pointers.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T10:33:40.103", "Id": "494437", "Score": "2", "body": "_\"The first (single-threaded) phase i.e. fillarray() takes no time compared to second, multi-threaded phase.\"_ So your question is to have an explanation why? Or do you ask for generally potential improvements of your code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T09:27:27.143", "Id": "494519", "Score": "1", "body": "Indeed, what is the question? You show some code; very good. It can be compiled; even better. But you haven't asked us anything..." } ]
[ { "body": "<p>A couple of minor things.</p>\n<p>For <code>int psize</code>, consider using <code>size_t</code>.</p>\n<p><code>log(sqrt(maxn))</code> should simply be <code>log(maxn)/2</code>, which is equivalent.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T16:41:56.447", "Id": "494471", "Score": "1", "body": "@AryanParekh I'm not really sure what you're asking, but 1. I learned both C and C++, the latter first; and 2. much (but not all) of the C language and its best practices can be understood \"automatically\" by someone who is already familiar with C++." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T16:44:48.193", "Id": "494474", "Score": "1", "body": "@AryanParekh C++ is backwards compatible with C for a reason, C++ originally started out as C with classes. Another thing you need to keep in mind when programming in C is not to use C++ keywords so that the program can be ported to C++ at a later time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T17:18:19.240", "Id": "494480", "Score": "1", "body": "@AryanParekh Let's move this discussion to https://chat.stackexchange.com/rooms/115582/re-c-c-compatibility - it's not particularly on-topic for the current answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T15:37:38.190", "Id": "494549", "Score": "0", "body": "Thanks, both makes sense. I was not aware of the equivalence. Don't even know if it should be, but yes, it really could be `log(maxn)/2`. I would add a third comment line - for unmathematical people like myself!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T15:19:26.280", "Id": "251213", "ParentId": "251200", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T09:09:02.380", "Id": "251200", "Score": "2", "Tags": [ "c", "primes", "openmp" ], "Title": "Prime numbers with array and OpenMP in C" }
251200
<p>I'm creating a ticket reservation system in Java, I want to use a Two-dimensional String array for managing the seats. I have enums that hold the plane model and the amount of seats available so the array pulls the rows and columns from there. I just want to see efficient my code is and how can I improve it.</p> <pre><code> public String[][] createSeatArray() { String[] alphabet = {&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;,&quot;e&quot;,&quot;f&quot;,&quot;g&quot;,&quot;h&quot;,&quot;i&quot;,&quot;j&quot;,&quot;k&quot;,&quot;l&quot;,&quot;m&quot;,&quot;n&quot;,&quot;o&quot;,&quot;p&quot;,&quot;q&quot;,&quot;r&quot; ,&quot;s&quot;,&quot;t&quot;,&quot;u&quot;,&quot;v&quot;,&quot;w&quot;,&quot;x&quot;,&quot;y&quot;,&quot;z&quot;,&quot;aa&quot;,&quot;bb&quot;,&quot;cc&quot;,&quot;dd&quot;,&quot;ee&quot;,&quot;ff&quot;,&quot;gg&quot;,&quot;hh&quot;,&quot;ii&quot;,&quot;jj&quot;,&quot;kk&quot;,&quot;ll&quot;,&quot;mm&quot;,&quot;nn&quot;,&quot;oo&quot;,&quot;pp&quot;}; String[][] seatArray = new String[this.getNumOfRows()][this.getNumOfColumns()]; int alphabetPos = 0; for(int i = 0; i &lt; this.getNumOfRows(); i++) { for (int j = 1; j &lt;= this.getNumOfColumns(); j++){ String columnToString = String.valueOf(j); seatArray[i][j-1] = alphabet[alphabetPos] + columnToString; if (this.getNumOfColumns() == 4) { if (j == 2) { System.out.print(seatArray[i][j-1] + &quot; &quot;); } else { System.out.print(seatArray[i][j-1] + &quot; &quot;); } } else { if (j == 3) { System.out.print(seatArray[i][j-1] + &quot; &quot;); } else { System.out.print(seatArray[i][j-1] + &quot; &quot;); } } } System.out.println(&quot;\n&quot;); alphabetPos++; } return seatArray; } </code></pre> <p>Thank you for any feedback! also keep in mind that if the indentation is off it may be due to bringing it over to stack overflow, on intellij it's perfect.</p>
[]
[ { "body": "<p>Here are a few optimization suggestions:</p>\n<ol>\n<li><p>You can get rid of <code>alphabetPos</code> because it is always equals to <code>i</code>.<br />\nIn fact, while you are at it, your code will be more readable if you rename <code>i</code> to <code>row</code> and <code>j</code> to <code>col</code> or <code>column</code>.</p>\n</li>\n<li><p>You can also get rid of <code>columnToString</code> and just rely on Java's string concatenation overloads.</p>\n</li>\n</ol>\n <pre>seatArray[i][j-1] = alphabet[alphabetPos] + j;</pre>\n<ol start=\"3\">\n<li><p>Note that you use <code>j</code> multiple times as index, subtracting one, and only once as string.<br />\nIt would make your code more readable if you used zero based index, and only added 1 for the string composition.</p>\n</li>\n<li><p>You may want to use string formatting.</p>\n</li>\n</ol>\n<br/>\n<pre><code>for (int col = 0; col &lt; this.getNumOfColumns(); col++) {\n seatArray[row][col] = String.format(&quot;%s%d&quot;, alphabet[row], col + 1);\n\n if (this.getNumOfColumns() == 4) {\n if (col == 1) {\n System.out.print(seatArray[row][col] + &quot; &quot;);\n } else {\n System.out.print(seatArray[row][col] + &quot; &quot;);\n }\n } else {\n if (col == 2) {\n System.out.print(seatArray[row][col] + &quot; &quot;);\n } else {\n System.out.print(seatArray[row][col] + &quot; &quot;);\n }\n }\n}\n</code></pre>\n<ol start=\"5\">\n<li>You can simplify your array printing by splitting it in to two parts: printing the seat number and printing the spacer.<br />\nThe first part is always the same, so no need to repeat it 4 times.\nThe second part changes only when <code>col</code> and <code>row</code> have certain values, so one condition is enough.</li>\n</ol>\n<br/>\n<pre><code>System.out.print(seatArray[row][col] + &quot; &quot;); //this part is always printed the same\n\n//just add a few more spaces if this is an isle seat\nif ((getNumOfColumns() == 4 &amp;&amp; col == 1) || (getNumOfColumns() != 4 &amp;&amp; col == 2)) {\n System.out.print(&quot; &quot;);\n}\n</code></pre>\n<ol start=\"6\">\n<li>Finally, to save memory, you can get rid of the <code>alphabet</code> array all together, since the seat letters are sequential and rows 26 and above just have the same letter twice:</li>\n</ol>\n<br/>\n<pre><code>String rowStr = String.format(&quot;%c&quot;, 'a' + (row % 26));\nif (row &gt; 25) rowStr += rowStr;\nseatArray[row][col] = String.format(&quot;%s%d&quot;, rowStr, col + 1);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T15:32:56.293", "Id": "494547", "Score": "0", "body": "@mdfst13 good catch, thanks! I was also missing a parenthesis on that line, fixed now." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T14:00:07.743", "Id": "251207", "ParentId": "251201", "Score": "5" } }, { "body": "<p>Printing/displaying the plan and building the plan are two separate concerns, so they really belong in different places. A large part of the build method complexity seems to be around the printing off the aisles between seats, which feels wrong.</p>\n<p>You've also said that your system supports different row/column combinations based on plane model. I've certainly been on planes with two aisles between seats. Is this something your print logic will eventually need to handle?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T14:50:41.297", "Id": "251211", "ParentId": "251201", "Score": "3" } }, { "body": "<blockquote>\n<pre><code> if (this.getNumOfColumns() == 4) {\n if (j == 2) {\n System.out.print(seatArray[i][j-1] + &quot; &quot;);\n } else {\n System.out.print(seatArray[i][j-1] + &quot; &quot;);\n }\n } else {\n if (j == 3) {\n System.out.print(seatArray[i][j-1] + &quot; &quot;);\n } else {\n System.out.print(seatArray[i][j-1] + &quot; &quot;);\n }\n }\n</code></pre>\n</blockquote>\n<p>You can simplify this by declarations outside your loops.</p>\n<pre><code> final int AISLE = (this.getNumOfColumns() == 4) ? 2 : 3;\n final StringBuilder builder = new StringBuilder();\n</code></pre>\n<p>And then replace the previous code with just</p>\n<pre><code> builder.append(seatArray[i][j-1]).append(&quot; &quot;);\n if (j == AISLE) {\n builder.append(&quot; &quot;);\n }\n</code></pre>\n<p>And where your <code>println</code> is now, change to</p>\n<pre><code> builder.append(&quot;\\n&quot;);\n System.out.println(builder.toString());\n builder.setLength(0);\n</code></pre>\n<p>Or even</p>\n<pre><code> builder.append(&quot;\\n\\n&quot;);\n</code></pre>\n<p>And after the loops, add</p>\n<pre><code> System.out.print(builder.toString());\n</code></pre>\n<p>The latter version is fine so long as the plane isn't huge. If you could have a truly large number of rows, then you might be better off printing each row separately (or in groups of rows) so as not to run out of memory. But in this case, you know that you only have 42 rows at most (a to pp). Unless you are on some tiny embedded system, that should not be a problem.</p>\n<p><code>StringBuilder.append</code> is more efficient than <code>System.out.print</code>. So moving all the string operations into the <code>builder</code> and doing just one <code>System.out.print</code> will make the code more efficient.</p>\n<p>By setting the <code>AISLE</code> constant, you save a method call on every iteration of the inner loop. And you get rid of the duplicate code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T07:32:13.033", "Id": "251242", "ParentId": "251201", "Score": "1" } } ]
{ "AcceptedAnswerId": "251207", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T10:09:28.653", "Id": "251201", "Score": "8", "Tags": [ "java", "strings", "array" ], "Title": "Creating Two-Dimensional String Array for Plane Seats" }
251201
<p>I am new to rust and I wrote a little program that takes a part CSS selector and returns the name of the element and two vectors containing its attributes (classes, ids)</p> <p>Example</p> <blockquote> <p>div#menu.big.pink =&gt; &quot;div&quot;, [&quot;menu'], [&quot;big&quot;, &quot;pink&quot;]</p> </blockquote> <p>Because I am new to rust I am looking for improvement to make this code better - more idiomatic faster, etc.</p> <p>Thanks in advance for any suggestions, have a nice day :)</p> <pre class="lang-rust prettyprint-override"><code>const LOOK_UP: [char; 2] = ['#', '.']; fn find(string: &amp;str) -&gt; Option&lt;(usize, usize)&gt; { for (index, char) in string.chars().enumerate() { match LOOK_UP.iter().position(|&amp;r| r == char) { Some(lookup_index) =&gt; return Some((index, lookup_index)), _ =&gt; continue, }; }; return None; } fn get_attributes(node_as_string: &amp;str) -&gt; (&amp;str, [Vec&lt;&amp;str&gt;; 2]) { match find(&amp;node_as_string) { Some(first) =&gt; { let mut attributes: [Vec&lt;&amp;str&gt;; 2] = [Vec::new(), Vec::new()]; let mut current_index = first.0; let mut last_type = first.1; loop { match find(&amp;node_as_string[current_index + 1..]) { Some(next) =&gt; { attributes[last_type].push(&amp;node_as_string[current_index + 1..current_index + next.0 + 1]); current_index += next.0 + 1; last_type = next.1; continue; } None =&gt; { attributes[last_type].push(&amp;node_as_string[current_index + 1..]); break; } } } return (&amp;node_as_string[..first.0], attributes); } None =&gt; panic!(&quot;&quot;) } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T13:30:18.837", "Id": "251206", "Score": "3", "Tags": [ "parsing", "css", "rust" ], "Title": "Simple single css node parser written in rust" }
251206
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/251132/231235">A recursive_transform for std::vector with various return type</a> and <a href="https://codereview.stackexchange.com/q/251171/231235">A recursive_transform for std::array with various return type</a>. Based on these discussion about the recursive things, the another idea comes up in my mind that trying to implement a print function for arbitrary nested iterable things. Normally, the multiple <code>for</code> loops may be used for printing nested iterables. Maybe like this one.</p> <pre><code>std::vector&lt;double&gt; testVector1; testVector1.push_back(1); testVector1.push_back(20); testVector1.push_back(-100); decltype(testVector1) testVector2; testVector2.push_back(10); testVector2.push_back(90); testVector2.push_back(-30); std::vector&lt;decltype(testVector1)&gt; testVector3; testVector3.push_back(testVector1); testVector3.push_back(testVector2); for (auto&amp; outer_element : testVector3) { for (auto&amp; inner_element : outer_element) { std::cout &lt;&lt; inner_element &lt;&lt; std::endl; } } </code></pre> <p>However, the multiple nested <code>for</code> loop shows up when it comes to the case like <code>std::vector&lt;std::vector&lt;std::vector&lt;std::vector&lt;...&gt;&gt;&gt;&gt;</code>.</p> <p>If the structure similar to <code>recursive_transform</code> is used in this task, that's the <code>recursive_print</code> function here.</p> <pre><code>template&lt;typename T&gt; concept is_iterable = requires(T x) { *std::begin(x); std::end(x); }; template&lt;typename T&gt; concept is_elements_iterable = requires(T x) { std::begin(x)-&gt;begin(); std::end(x)-&gt;end(); }; template&lt;class T&gt; requires is_iterable&lt;T&gt; T recursive_print(const T&amp; input, const int level = 0) { T output = input; std::cout &lt;&lt; std::string(level, ' ') &lt;&lt; &quot;Level &quot; &lt;&lt; level &lt;&lt; &quot;:&quot; &lt;&lt; std::endl; std::transform(input.cbegin(), input.cend(), output.begin(), [level](auto&amp; x) { std::cout &lt;&lt; std::string(level, ' ') &lt;&lt; x &lt;&lt; std::endl; return x; } ); return output; } template&lt;class T&gt; requires is_iterable&lt;T&gt; &amp;&amp; is_elements_iterable&lt;T&gt; T recursive_print(const T&amp; input, const int level = 0) { T output = input; std::cout &lt;&lt; std::string(level, ' ') &lt;&lt; &quot;Level &quot; &lt;&lt; level &lt;&lt; &quot;:&quot; &lt;&lt; std::endl; std::transform(input.cbegin(), input.cend(), output.begin(), [level](auto&amp; element) { return recursive_print(element, level + 1); } ); return output; } </code></pre> <p><a href="https://godbolt.org/z/G4ds3v" rel="nofollow noreferrer">Here's a Godbolt link.</a> The output of the example is as below. The nested level is also displaying with this <code>recursive_print</code> function.</p> <pre><code>Level 0: Level 1: Level 2: 1 20 -100 Level 2: 10 90 -30 Level 1: Level 2: 1 20 -100 Level 2: 10 90 -30 </code></pre> <p>All suggestions are welcome.</p> <ul> <li><p>Which question it is a follow-up to?</p> <p><a href="https://codereview.stackexchange.com/q/251132/231235">A recursive_transform for std::vector with various return type</a> and</p> <p><a href="https://codereview.stackexchange.com/q/251171/231235">A recursive_transform for std::array with various return type</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <p>The previous questions focus on the input/output content and type, but the print out operation is the main idea here.</p> </li> <li><p>Why a new review is being asked for?</p> <p>If there is any possible improvement about this code, please let me know.</p> </li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T14:21:35.387", "Id": "251208", "Score": "1", "Tags": [ "c++", "recursion", "c++20" ], "Title": "A recursive_print Function For Various Type Arbitrary Nested Iterable Implementation in C++" }
251208
<p>I'm writing a spigot plugin where I give the user the possibility to send a message to the admins of the server. One of the requirements is that the coordinates of the player are stored, when the message is sent, and that it is stored in a sql table, so that admins on multiple spigot servers can access them independently of where the message was sent originally.</p> <p>I have got a simple sql table, which stores the message, the player's uuid, etc in a table, but I really dislike the idea that I have to store all three values of the <code>Vec3</code> in separate columns. I googled for a possibility to simply store a Vec3 via SQL, but had no luck.</p> <p>Here's an overview of my current table:</p> <p><a href="https://i.stack.imgur.com/8YQ7S.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8YQ7S.png" alt="enter image description here" /></a></p> <p>I just have this one table with the data in it, which I create like this:</p> <pre class="lang-sql prettyprint-override"><code>CREATE TABLE IF NOT EXISTS Meldung ( id INT AUTO_INCREMENT NOT NULL, UUID VARCHAR(64), NAME VARCHAR(64), MESSAGE TEXT, XCOORD INT, YCOORD INT, ZCOORD INT, ISREAD TINYINT(1), primary key(id)); </code></pre> <p>I'd like to know how I can improve in this matter, or the general way how my data is stored. I'm particularly interested in alternative methods to store these coordinates, I don't know why, I find my current way very unsatisfying.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T15:18:07.177", "Id": "494459", "Score": "0", "body": "Is there a reason why your table name is German, but your column names aren't?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T15:21:16.143", "Id": "494460", "Score": "0", "body": "Yes, the name of the plugin was given as a requirement, and so was the name of the main table. However I dislike naming stuff in other languages than English when related to coding, and decided to keep the rest in English." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T15:50:26.787", "Id": "494463", "Score": "0", "body": "Is x,y,z sufficient, or do you need something like world id as well? One option would be too have a reporter location table which you join to from the main report table. You are also using int for your x,y,z. Is this correct/sufficient resolution, the definitions I've seen suggest it's usually a floating point number. You could also look at blobs if you really don't like 3columns, but they can be harder to work with." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T13:26:55.983", "Id": "494535", "Score": "0", "body": "No, I use the \"block\"-Values, for some other reasons, and the block-coord's are always int's" } ]
[ { "body": "<blockquote>\n<p>One of the requirements is that the coordinates of the player are stored, when the message is sent, and that it is stored in a sql table, so that admins on multiple spigot servers can access them independently of where the message was sent originally.</p>\n</blockquote>\n<p>Which raises questions about transactions and concurrent access.</p>\n<hr />\n<pre class=\"lang-sql prettyprint-override\"><code>CREATE TABLE IF NOT EXISTS Meldung (\n id INT AUTO_INCREMENT NOT NULL,\n UUID VARCHAR(64),\n NAME VARCHAR(64),\n MESSAGE TEXT,\n XCOORD INT,\n YCOORD INT,\n ZCOORD INT,\n ISREAD TINYINT(1),\n primary key(id));\n</code></pre>\n<p>Your table structure raises many questions. Let's start with the obvious that MySQL table names might or might not be case-sensitive, depending on whether it runs on a filesystem that is case-sensitive or not.</p>\n<p>The second is, do you need all columns to be <code>nullable</code>?</p>\n<p>Third, I believe that at least <code>UUID</code> and <code>ISREAD</code> should have an index assigned, but that depends on the use-case mostly.</p>\n<pre><code> id INT AUTO_INCREMENT NOT NULL,\n</code></pre>\n<p>Why is the casing different to everything else?</p>\n<pre><code> UUID VARCHAR(64),\n</code></pre>\n<p>That's a bad column name, what UUID? Of what? <code>PLAYER_UUID</code> oder rather <code>PLAYER_ID</code> would be a better choice.</p>\n<pre><code> NAME VARCHAR(64),\n</code></pre>\n<p>Same here, name of what?</p>\n<pre><code> XCOORD INT,\n YCOORD INT,\n ZCOORD INT,\n</code></pre>\n<p>Unless the database provides a fitting datatype, storing the single values of a vector is the best thing you can do. Do not give into the idea &quot;I will store this as string and parse it later&quot;, that's going to bite you or someone else down the road.</p>\n<hr />\n<p>What I'm missing in this table is a <code>CREATED_AT</code> and <code>READ_AT</code> datetime field. The later could even double as flag whether it was read or not, by having it <code>nullable</code>.</p>\n<p>What I'd also rather do is have a separate <code>Player</code> table, which allows to not store the name multiple times:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>CREATE TABLE Player (\n -- Note that I've skipped a column-name prefix here,\n -- as it is clear what is meant because of the table.\n UUID VARCHAR(64) PRIMARY KEY,\n NAME TEXT NOT NULL\n)\n\nCREATE TABLE Meldung (\n -- Primary Keys are not nullable by default.\n ID INT AUTO_INCREMENT PRIMARY KEY,\n PLAYER_UUID VARCHAR(64) FOREIGN KEY REFERENCES Player(UUID),\n MESSAGE TEXT NOT NULL,\n PLAYER_LOCATION_X INT NOT NULL,\n PLAYER_LOCATION_Y INT NOT NULL,\n PLAYER_LOCATION_Z INT NOT NULL,\n -- Could also be SENT_AT.\n CREATED_AT DATETIME NOT NULL DEFAULT NOW(),\n READ_AT DATETIME\n)\n</code></pre>\n<hr />\n<p>On another note, I like to use lowercase SQL with all columns and table names uppercase, like this:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>create table PLAYER (\n -- Note that I've skipped a column-name prefix here,\n -- as it is clear what is meant because of the table.\n UUID varchar(64) primary key,\n NAME text not null\n)\n\ncreate table MELDUNG (\n -- Primary Keys are not nullable by default.\n ID int auto_increment primary key,\n PLAYER_UUID varchar(64) foreign key references PLAYER(UUID),\n MESSAGE text not null,\n PLAYER_LOCATION_X int not null,\n PLAYER_LOCATION_Y int not null,\n PLAYER_LOCATION_Z int not null,\n CREATED_AT datetime not null default NOW(),\n READ_AT datetime\n)\n</code></pre>\n<p>As it is quite easier to type, and anything that is upper-case can be easily identified as table or column. It also removes any of the ambiguity regarding case-sensitivity in MySQL.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T11:12:20.140", "Id": "494531", "Score": "0", "body": "Lots of useful information here. You actually encouraged me to at last write a custom api for player data storage, so I wrote another plugin just to handle the player data, so multiple plugins can use this PLAYER-Table. Also implemented most of your other suggestions :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T20:13:55.150", "Id": "251231", "ParentId": "251212", "Score": "3" } } ]
{ "AcceptedAnswerId": "251231", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T15:03:53.513", "Id": "251212", "Score": "6", "Tags": [ "sql" ], "Title": "SQL structure to save coordinates for spigot plugin" }
251212
<p>I recently came across a problem scheduling Coronavirus testing at a hospital; the testing capacity needed to be allocated to:</p> <ul> <li>High risk wards (combining many factors).</li> <li>Ones which hadn't been tested recently.</li> </ul> <p>This presents a really tricky problem when scheduling, because as well as complexity in combining many properties of the ward to understand its risk factor, there is a knock-on effect where the position of a ward in the schedule dictates its probability of coming up again soon.</p> <p>Coming back into the programming realm, I wanted to do some kind of weighted average of different factors to compare wards for &quot;priority&quot;, and overload <code>__gt__</code> to allow for comparison using the native comparison operators. The problem is, I can't directly compare priority of two wards to sort the list and create a schedule; ward A and ward B may have exactly the same properties - size, risk factor etc. but if ward B was tested more recently then it has a lower priority.</p> <p>What I understood was that I can't compare wards, but I can compare different schedules. That is, I can compare timelines to see which is more optimal, and then try and sort a random list in a way that guides it towards a more optimal sorting. That's what I mean by &quot;sorting with a heuristic approach&quot; - I use a cost function evaluated over the whole list and optimise this. I hope that's reasonably clear.</p> <p>How can I sort a list using a cost function? I have this base class:</p> <pre><code>from __future__ import annotations import numpy as np from typing import Sequence, Callable, Tuple, Optional import pprint import string </code></pre> <pre><code>class SequenceItemBase: &quot;&quot;&quot;Class that wraps a value and the list that contains it and overrides normal value comparison with a heuristic for guiding swaps in the list &quot;&quot;&quot; def __init__( self, parent: Sequence[SequenceItemBase], heuristic: Callable[[Sequence[SequenceItemBase], Tuple[int, int]]], ): self.parent = parent self._heuristic = heuristic def __gt__(self, other): &quot;An item should be placed higher in the list if doing so would increase the value of the heuristic&quot; # store a copy of the current list state so we can &quot;imagine&quot; what effect # swapping self and other would have on the heuristic after_change = self.parent.copy() self_index = self.parent.index(self) other_index = self.parent.index(other) swap_indecies = sorted((self_index, other_index)) after_change[self_index], after_change[other_index] = after_change[other_index], after_change[self_index] # whether the swap improved our heuristic positive_delta_h = self._heuristic( after_change, swap_indecies ) &gt; self._heuristic(self.parent, swap_indecies) # if self greater than other, then 1 of 2 things happens: # when self is earlier in the list, the swap will happen because we are going ascending # vice-versa when self is later in the list # so, if the swap is encouraged by our heuristic, then we must mark self as greater than other # only when it is earlier in the list # and when it is later in the list, then only when our heuristic discourages swapping places return (self_index &lt; other_index and positive_delta_h) or ( self_index &gt; other_index and not positive_delta_h ) </code></pre> <p>I've added a few explanatory comments, but essentially what it does is to override the comparison operator which is called at every step of the sorting process, and replace it with one that looks at the current state of the list, <em>imagines</em> swapping the items being compared to see what effect that would have on the list, and if swapping would be good, then make <code>__gt__</code> return whatever it has to say &quot;the later thing should be earlier in the schedule&quot;.</p> <p>So, when asked &quot;Is A greater than B&quot;, instead of something like:</p> <blockquote> <p>Is the value of A &gt; the value of B</p> </blockquote> <p>it says:</p> <blockquote> <p>If I swapped A and B around, would that make the list have a better sorting? If so, then yes, A is greater/less than B :)</p> </blockquote> <p>Bit of special casing because we don't know if self or other will be earlier in the list.</p> <hr /> <p>This base class can be inherited from to define a sortable class that provides any data the cost function might need. For example, this one just wraps a value that the heuristic function can access.</p> <pre><code>class ValueItem(SequenceItemBase): def __init__(self, value, parent=None, heuristic=None): self.value = value super().__init__(parent, heuristic) def __repr__(self): return str(self.value) def prefer_sequences_in_ascending_order_heuristic( intermediate_state: Sequence[ValueItem], swap_indecies: Optional[Tuple[int, int]] = None, ): &quot;This heuristic will return a larger number when the list is sorted in ascending order&quot; return sum(index * item.value for index, item in enumerate(intermediate_state)) </code></pre> <p>Here the heuristic is equivalent to just doing ascending order. You can see this here:</p> <pre class="lang-py prettyprint-override"><code>random_list_of_nums = [] source_nums = np.random.randint(1, 100, 100) heuristic = prefer_sequences_in_ascending_order_heuristic # wrap the random numbers in classes that all hold a reference to the containing list # so that they can be sorted using the heuristic for i in source_nums: random_list_of_nums.append(ValueItem(i, random_list_of_nums, heuristic)) before = random_list_of_nums.copy() perfect = [ValueItem(value, None) for value in sorted(source_nums)] print(f&quot;{heuristic(before)/heuristic(perfect):0.0%}&quot;, before) selection_sort(random_list_of_nums) after = random_list_of_nums print(f&quot;{heuristic(after)/heuristic(perfect):0.0%}&quot;, after) </code></pre> <p>The list is sorted perfectly by value and the heuristic is maximised.</p> <hr /> <p>For a more applicable problem, there is a method in scheduling called &quot;minimize average tardiness&quot; meaning; &quot;for some tasks each with a duration and due-date, what ordering minimises the average lateness/tardiness&quot;:</p> <pre><code>class TardinessItem(SequenceItemBase): def __init__(self, duration, due_date, parent=None, heuristic=None): self.duration = duration self._due_date = due_date super().__init__(parent, heuristic) def tardiness(self, start_date): return max(0, start_date + self.duration - self._due_date) def __repr__(self): return f&quot;{self.name}: duration {self.duration} day{'s' if self.duration &gt; 1 else ''} - due in {self._due_date}&quot; def tardiness_values(sequence: Sequence[TardinessItem]): running_date_total = 0 for item in sequence: yield item.tardiness(running_date_total) running_date_total += item.duration def minimising_average_tardiness_heuristic( intermediate_state: Sequence[TardinessItem], swap_indecies: Optional[Tuple[int, int]] = None, ): #negative so that maximising this heuristic will minimise total tardiness return sum(-tardiness for tardiness in tardiness_values(intermediate_state)) </code></pre> <p>Example:</p> <pre class="lang-py prettyprint-override"><code>timeline = [] # source_nums = list(zip(np.random.randint(1,10,10),np.random.randint(20,40,10))) source_nums = zip([2, 7, 3, 8, 4, 4, 6, 8, 5], [5, 10, 15, 22, 23, 24, 25, 30, 33]) heuristic = minimising_average_tardiness_heuristic for i, (duration, date) in enumerate(source_nums): timeline.append( TardinessItem(duration, date, timeline, minimising_average_tardiness_heuristic) ) timeline[-1].name = string.ascii_uppercase[i] pprint.pprint(timeline) print( f&quot;Average Tardiness: {np.average(list(tardiness_values(timeline)))}, Heuristic: {heuristic(timeline)}&quot; ) for _ in range(10): selection_sort(timeline) after = timeline pprint.pprint(after) print( f&quot;Average Tardiness: {np.average(list(tardiness_values(timeline)))}, Heuristic: {heuristic(timeline)}&quot; ) </code></pre> <p>prints</p> <pre class="lang-none prettyprint-override"><code>[A: duration 2 days - due in 5, B: duration 7 days - due in 10, C: duration 3 days - due in 15, D: duration 8 days - due in 22, E: duration 4 days - due in 23, F: duration 4 days - due in 24, G: duration 6 days - due in 25, H: duration 8 days - due in 30, I: duration 5 days - due in 33] Average Tardiness: 4.444444444444445, Heuristic: -40 [A: duration 2 days - due in 5, B: duration 7 days - due in 10, C: duration 3 days - due in 15, D: duration 8 days - due in 22, E: duration 4 days - due in 23, F: duration 4 days - due in 24, I: duration 5 days - due in 33, G: duration 6 days - due in 25, H: duration 8 days - due in 30] Average Tardiness: 4.0, Heuristic: -36 </code></pre> <p>which is the same output as <a href="https://en.wikipedia.org/wiki/Modified_due-date_scheduling_heuristic" rel="nofollow noreferrer">MDD</a> gives (another heuristic way to approach minimum tardiness scheduling).</p> <hr /> <h3>Example sort algorithm</h3> <p>This approach is designed to be used with an <em>in-place</em> sort because <code>parent</code> effectively holds a live view of the intermediate steps when sorting, and at the moment <code>selection_sort</code> is used because it reflects the idea of swapping elements as a measure of progress, but I'm open to suggestions...</p> <pre><code>def selection_sort(nums): # This value of i corresponds to how many values were sorted for i in range(len(nums)): # We assume that the first item of the unsorted segment is the smallest lowest_value_index = i # This loop iterates over the unsorted items for j in range(i + 1, len(nums)): if nums[j] &lt; nums[lowest_value_index]: lowest_value_index = j # Swap values of the lowest unsorted element with the first unsorted # element nums[i], nums[lowest_value_index] = nums[lowest_value_index], nums[i] </code></pre> <p>I originally planned to use python's built-in <code>list.sort</code> based on quicksort, which is why I overloaded the native operator, however that method doesn't update the list in place at every step, so the cost function wasn't changing value.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-17T06:06:43.547", "Id": "496849", "Score": "2", "body": "Rather than being called a \"heuristic\", this is called a \"metric\", \"reward function\", or \"cost\". There is a standard body of literature about how to minimize/maximize a cost, once you can evaluate it. Using the standard language this will help you find relevant stuff and other people find it for you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-07T15:44:05.123", "Id": "525047", "Score": "0", "body": "@ZacharyVance would it be valid to say this was a \"heuristic approach/algorithm\" as it does not guarantee a perfect answer? I agree it's not a heuristic function but optimisation of a reward function or something like that..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-07T23:55:41.370", "Id": "525080", "Score": "0", "body": "I'm referring to specific phrases you've used in your question such as \"and the heuristic is maximised\"." } ]
[ { "body": "<p><code>swap_indecies</code> -&gt; <code>swap_indices</code></p>\n<p>Also, you have inconsistent type hinting on your methods: this one is complete -</p>\n<pre><code>def __init__(\n self,\n parent: Sequence[SequenceItemBase],\n heuristic: Callable[[Sequence[SequenceItemBase], Tuple[int, int]]],\n):\n</code></pre>\n<p>but these are not:</p>\n<pre><code>def __gt__(self, other):\n\ndef __init__(self, value, parent=None, heuristic=None):\n\ndef __init__(self, duration, due_date, parent=None, heuristic=None):\n</code></pre>\n<p>The latter suggests that your original hints are incorrect and should be wrapped in <code>Optional</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T16:01:08.257", "Id": "251217", "ParentId": "251214", "Score": "8" } }, { "body": "<p>So, if I understand correctly, you've designed a class <code>SequenceItemBase</code> such that if there are two instances of <code>SequenceItemBase</code>, <code>a</code> and <code>b</code>, <code>a &lt; b</code> might evaluate to <code>True</code> in the context of one list of <code>SequenceItemBase</code> instances, but the same expression might evaluate to <code>False</code> in the context of a different list of <code>SequenceItemBase</code> instances, despite none of the attributes of either <code>a</code> or <code>b</code> having changed in between the two tests.</p>\n<p>My advice would be not to do that. Defining custom comparison dunder methods in python is common, and can often make object-oriented code much more readable, but I think outcomes like this would be very unexpected to other people reading your code. I think it would be a reasonable expectation for other readers of your code to think that if <code>a &lt; b</code> evaluates as <code>True</code> in one context, then <code>a &lt; b</code> will always evaluate as <code>True</code> unless the attributes of either <code>a</code> or <code>b</code> had changed. Rather than having any <code>__lt__</code> or <code>__gt__</code> methods at all, I would instead use a <code>classmethod</code> for sorting these sequences.</p>\n<p>I also find the way you're combining an object-oriented approach with elements of functional programming quite confusing. You define custom <code>TardinessItem</code> and <code>ValueItem</code> classes, which is an object-oriented approach. But despite the fact that you're essentially developing a custom method of sorting instances of these classes, the main sort function is a function in the global namespace, not the class namespace. The way you're passing in functions to objects for them to use in their comparison dunder methods also confuses me, given that the functions seem to be specific to a certain class. If a function is specific to a certain class, it should probably be defined in the class namespace.</p>\n<p>Here's a significant refactoring of your code which makes it more object-oriented and (in my opinion) easier to understand. Rather than have external functions passed into class instances, I've instead taken the approach of defining <code>SequenceItemBase</code> as an Abstract Base Class with one <code>abstractmethod</code>, <code>get_sequence_score</code>, fulfilling a similar purpose to your <code>heuristic</code> function. Subclasses of <code>SequenceItemBase</code> will fail to be instantiated at runtime if they don't provide a concrete implementation of this abstractmethod. This strategy of isolating the specific parts of the algorithm that need to be modified by subclasses for more specific use-cases is known as the <a href=\"https://en.wikipedia.org/wiki/Template_method_pattern?wprov=sfti1\" rel=\"nofollow noreferrer\">&quot;template method pattern&quot;</a>.</p>\n<p>Another major change I've made (along with lots of smaller changes) is to define your <code>TardinessItem</code> class as a <code>dataclass</code>. This makes sense, I think, given that the class is essentially a wrapper around structured data, and it saves us having to write an <code>__init__</code> function that would be solely boilerplate code.</p>\n<pre><code>from __future__ import annotations\n\nfrom abc import ABCMeta, abstractmethod\nfrom typing import TypeVar, Type, List, Any, Protocol, Sequence\nfrom dataclasses import dataclass\nfrom pprint import pprint\n\n\nS = TypeVar('S', bound='SequenceItem')\n\n\nclass SupportsComparisons(Protocol):\n &quot;&quot;&quot;Return type for `SequenceItem.get_sequence_score`.\n Not used at runtime; solely for helping out static type checkers.\n &quot;&quot;&quot;\n\n def __lt__(self, other: Any) -&gt; bool: ...\n def __gt__(self, other: Any) -&gt; bool: ...\n def __eq__(self, other: Any) -&gt; bool: ...\n\n\nclass SequenceItem(metaclass=ABCMeta):\n __slots__ = ()\n \n @classmethod\n @abstractmethod\n def get_sequence_score(cls: Type[S], cls_sequence: Sequence[S]) -&gt; SupportsComparisons:\n &quot;&quot;&quot;Return a &quot;sequence score&quot; for a given sequence of `SequenceItem`s.\n\n If the swapping of two elements in the sequence results in a higher &quot;sequence score&quot;,\n the two elements will be swapped when the sequence is sorted.\n\n This is an abstract method that must be defined in any concrete subclass of `SequenceItem`.\n &quot;&quot;&quot;\n \n @classmethod\n def swapping_improves_order(\n cls: Type[S],\n list_before_change: List[S],\n item_a: S,\n item_a_index: int,\n item_b: S,\n item_b_index: int\n ) -&gt; bool:\n &quot;&quot;&quot;Determine whether swapping two items in a list would improve the order according to a given metric.&quot;&quot;&quot;\n \n # store a copy of the current list state so we can &quot;imagine&quot; what effect...\n # ...swapping the two items would have on the &quot;sequence score&quot;\n list_after_change = list_before_change.copy()\n list_after_change[item_a_index], list_after_change[item_b_index] = item_b, item_a\n\n # whether the swap improved our &quot;sequence score&quot;\n positive_delta_h = cls.get_sequence_score(list_after_change) &gt; cls.get_sequence_score(list_before_change)\n\n return (item_a_index &lt; item_b_index) != positive_delta_h\n \n @classmethod\n def sort_sequence_in_place(cls: Type[S], cls_list: List[S]) -&gt; None:\n &quot;&quot;&quot;Sort a list of class instances in-place.\n\n The items in the list are sorted in such a way\n so as to maximise the list's &quot;score&quot; according to a given metric.\n\n The sorting algorithm used is the &quot;selection_sort&quot; algorithm.\n &quot;&quot;&quot; \n \n for i, item_i in enumerate(cls_list):\n # We assume that the first item of the unsorted segment is the smallest\n lowest_value_index = i\n next_index = i + 1\n \n # This loop iterates over the unsorted items\n for j, item_j in enumerate(cls_list[next_index:], start=next_index):\n if cls.swapping_improves_order(cls_list, item_j, j, cls_list[lowest_value_index], lowest_value_index):\n lowest_value_index = j\n \n # Swap values of the lowest unsorted element with the first unsorted element\n cls_list[i], cls_list[lowest_value_index] = cls_list[lowest_value_index], item_i\n\n\nT = TypeVar('T', bound='TardinessItem')\n\n\n@dataclass\nclass TardinessItem(SequenceItem):\n __slots__ = 'name', 'duration', '_due_date'\n \n name: str\n duration: int\n _due_date: int\n\n def format_duration(self) -&gt; str:\n &quot;&quot;&quot;Helper method for __repr__&quot;&quot;&quot;\n \n duration = self.duration\n return f'duration {duration} day{&quot;s&quot; if duration &gt; 1 else &quot;&quot;}'\n\n def __repr__(self) -&gt; str:\n return f'{self.name}: {self.format_duration()} - due in {self._due_date}'\n\n def tardiness(self, start_date: int) -&gt; int:\n &quot;&quot;&quot;Determine how tardy this scheduled event would be if it started on a given date.&quot;&quot;&quot;\n return max(0, start_date + self.duration - self._due_date)\n\n @classmethod\n def total_tardiness_of_sequence(cls: Type[T], cls_sequence: Sequence[T]) -&gt; int:\n &quot;&quot;&quot;Determine the total tardiness of a given sequence of `TardinessItem`s.&quot;&quot;&quot;\n \n total_tardiness, running_date_total = 0, 0\n\n for item in cls_sequence:\n total_tardiness += item.tardiness(running_date_total)\n running_date_total += item.duration\n\n return total_tardiness\n\n @classmethod\n def get_sequence_score(cls: Type[T], cls_sequence: Sequence[T]) -&gt; int:\n &quot;&quot;&quot;Determine the &quot;sequence score&quot; of a given sequence of `TardinessItem`s.\n\n The greater the total tardiness of a sequence, the lower its sequence score.\n &quot;&quot;&quot;\n \n return ( - cls.total_tardiness_of_sequence(cls_sequence))\n \n\ndef run_example(\n name_inputs: Sequence[str],\n duration_inputs: Sequence[int],\n date_inputs: Sequence[int]\n) -&gt; None:\n \n timeline = [\n TardinessItem(name, duration, date)\n for name, duration, date in zip(name_inputs, duration_inputs, date_inputs)\n ]\n\n initial_total_tardiness = TardinessItem.total_tardiness_of_sequence(timeline)\n initial_average_tardiness = initial_total_tardiness / len(timeline)\n initial_sequence_score = ( - initial_total_tardiness)\n print('### RESULTS PRIOR TO SORTING ###\\n')\n pprint(timeline)\n print(f&quot;\\nAverage Tardiness: {initial_average_tardiness}, Heuristic: {initial_sequence_score}&quot;)\n\n print()\n TardinessItem.sort_sequence_in_place(timeline)\n\n total_tardiness_after = TardinessItem.total_tardiness_of_sequence(timeline)\n average_tardiness_after = total_tardiness_after / len(timeline)\n sequence_score_after = ( - total_tardiness_after)\n print('### RESULTS AFTER SORTING ###\\n')\n pprint(timeline)\n print(f&quot;\\nAverage Tardiness: {average_tardiness_after}, Heuristic: {sequence_score_after}&quot;)\n\n\nif __name__ == '__main__':\n from string import ascii_uppercase\n duration_inputs = [2, 7, 3, 8, 4, 4, 6, 8, 5]\n date_inputs = [5, 10, 15, 22, 23, 24, 25, 30, 33]\n run_example(ascii_uppercase, duration_inputs, date_inputs)\n</code></pre>\n<p>Output:</p>\n<pre><code>### RESULTS PRIOR TO SORTING ###\n\n[A: duration 2 days - due in 5,\n B: duration 7 days - due in 10,\n C: duration 3 days - due in 15,\n D: duration 8 days - due in 22,\n E: duration 4 days - due in 23,\n F: duration 4 days - due in 24,\n G: duration 6 days - due in 25,\n H: duration 8 days - due in 30,\n I: duration 5 days - due in 33]\n\nAverage Tardiness: 4.444444444444445, Heuristic: -40\n\n### RESULTS AFTER SORTING ###\n\n[A: duration 2 days - due in 5,\n B: duration 7 days - due in 10,\n C: duration 3 days - due in 15,\n D: duration 8 days - due in 22,\n E: duration 4 days - due in 23,\n F: duration 4 days - due in 24,\n I: duration 5 days - due in 33,\n G: duration 6 days - due in 25,\n H: duration 8 days - due in 30]\n\nAverage Tardiness: 4.0, Heuristic: -36\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-11T21:35:17.410", "Id": "265973", "ParentId": "251214", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T15:33:21.723", "Id": "251214", "Score": "9", "Tags": [ "python", "python-3.x", "sorting", "covid-19", "heuristic" ], "Title": "Fuzzy list sorting with a heuristic approach to generate a schedule for COVID-19 tests in a hospital" }
251214
<p><a href="https://en.wikipedia.org/wiki/Reversi" rel="nofollow noreferrer">Reversi Game:</a> The image from the Reversi game:</p> <p><a href="https://i.stack.imgur.com/6ie1W.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6ie1W.png" alt="enter image description here" /></a></p> <p>I have my algorithm to find all legal moves in Reversi game.</p> <p>Here's the code with comments:</p> <pre><code>&quot;&quot;&quot; -1 =&gt; no disc 0/1 =&gt; player's disc &quot;&quot;&quot; for row_idx, row in enumerate(board): for column_idx, column in enumerate(board): if board[row_idx][column_idx] == -1: &quot;&quot;&quot; Loop through square with chosen `-1` in middle 5 5 5 5 -1 5 5 5 5 &quot;&quot;&quot; for i in range(-1, 2, 1): for j in range(-1, 2, 1): &quot;&quot;&quot; Check if loop is not beyond borders &quot;&quot;&quot; if row_idx + i &lt; 0 or row_idx + 1 &gt; (len(board) - 1) or column_idx + j &lt; 0 or column_idx + j &gt; (len(board) - 1): continue &quot;&quot;&quot; If there is a opponent disc, go straight in this direction (that way) &quot;&quot;&quot; if board[row_idx + i][column_idx + j] == self.opponent_color: i2, j2 = i, j for _ in range(8): &quot;&quot;&quot; Check if loop is not beyond borders &quot;&quot;&quot; if row_idx + i + i2 &lt; 0 or row_idx + i + i2 &gt; (len(board) - 1) or column_idx + j + j2 &lt; 0 or column_idx + j + j2 &gt; (len(board) - 1): continue &quot;&quot;&quot; Break if the `no disc` is on `that way` &quot;&quot;&quot; if board[row_idx + i + i2][column_idx + j + j2] == -1: break &quot;&quot;&quot; The legal move has been found, then break. &quot;&quot;&quot; if board[row_idx + i + i2][column_idx + j + j2] == self.my_color: legal_moves.append((row_idx, column_idx)) break i2 += i j2 += j </code></pre> <p>Is there any better way to do it? I am not sure about those nested for loops.</p> <p>Thanks for any help or any hint!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T16:23:40.850", "Id": "494465", "Score": "0", "body": "Are you sure this algorithm works? Why is there a random 7 in the border check? Why is `column_idx + j` always expected to be 0 on every iteration and how do you get around the code crashing with `i2` and `j2` not being defined if opponent stone is not found on the first iteration?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T16:30:05.250", "Id": "494466", "Score": "0", "body": "(1) There is 8x8 board, the last one is 7th index in array. (2)(3) I am sorry, bad indentation in the code, not mine on local, but here on CodeReview. I'll fix it, give me one minute." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T16:31:53.773", "Id": "494467", "Score": "0", "body": "@LevM. I have fixed indentation in my code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T16:36:20.697", "Id": "494468", "Score": "0", "body": "It makes more sense now, but there is still this condition in the outer loop: `column_idx + j < 0 or column_idx + j > 0` I am guessing it needs 7 in the end instead of 0, just like the rows condition. I would recommend that instead of using hardcoded board size you use `len()` function on your actual board this will make the code clearer and more versatile. You already enumerate based on board size anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T16:41:44.113", "Id": "494470", "Score": "2", "body": "I really think you should thoroughly describe what your program does since not everyone knows reversi" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T16:43:40.233", "Id": "494472", "Score": "0", "body": "@LevM. Thanks, I have edited my code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T16:43:47.297", "Id": "494473", "Score": "0", "body": "@AryanParekh [Reversi link](https://en.wikipedia.org/wiki/Reversi) I have added the image from the game as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T18:30:10.067", "Id": "494482", "Score": "0", "body": "Without having `board`, how are we supposed to try your code or our suggestions? Should have an input+output example." } ]
[ { "body": "<h2>Iteration</h2>\n<p>This:</p>\n<pre><code>for row_idx, row in enumerate(board):\n for column_idx, column in enumerate(board):\n if board[row_idx][column_idx] == -1:\n</code></pre>\n<p>is effectively incorrect. Is your board in row-major or column-major order? Whichever is true, you cannot iterate over the outer index of the board and get <em>both</em> a row and a column. What you likely meant instead is:</p>\n<pre><code>for row_idx, row in enumerate(board):\n for column_idx, cell in enumerate(row):\n if cell == -1:\n</code></pre>\n<p>Another problematic iteration is this:</p>\n<pre><code>i2, j2 = i, j\nfor _ in range(8):\n # ...\n i2 += i\n j2 += j\n</code></pre>\n<p>should simply be</p>\n<pre><code>for delta in range(1, 8):\n # ... use i*delta instead of i2\n # ... use j*delta instead of j2\n</code></pre>\n<h2>Combined range checking</h2>\n<pre><code>if row_idx + i &lt; 0 or row_idx + 1 &gt; (len(board) - 1) or column_idx + j &lt; 0 or column_idx + j &gt; (len(board) - 1):\n \n</code></pre>\n<p>should be</p>\n<pre><code>if not (0 &lt;= row_idx + i &lt; len(board)) or not (0 &lt;= column_idx &lt; len(board)):\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T17:45:31.557", "Id": "494481", "Score": "0", "body": "(1) Oh, my fault, thanks. (3) Interesting, thanks for it. (2) I think this is not what I mean. I need to go in direction the opponent disc is. The point is, the direction could be <-1; 1>." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T19:24:07.403", "Id": "494490", "Score": "0", "body": "@JohnDoe I had that wrong on the first pass; you're incrementing by `i` and `j` respectively so you can just multiply by delta instead. The alternative is to `zip` two ranges, which is a little uglier." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T16:37:31.420", "Id": "494555", "Score": "0", "body": "You are right, I get it know, thanks a lot!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T16:54:30.843", "Id": "251221", "ParentId": "251216", "Score": "2" } }, { "body": "<p>Some suggestions:</p>\n<p>Avoid magic numbers like -1,0,1. Instead, define constants for the values in the squares:</p>\n<pre><code>EMPTY = -1\nWHITE = 0\nBLACK = 1\n</code></pre>\n<p>One technique for implementing a grid or board like this is to add an extra row on the right and an extra column on the bottom filled with an &quot;out of bounds&quot; marker. For example, your code uses -1 for empty spaces and 0/1 for the pieces. You could use -2 for the out-of-bounds squares. An initial reversi board might look like this.</p>\n<pre><code>board = [\n # 1 2 3 4 5 6 7 8 OoB\n [ -1, -1, -1, -1, -1, -1, -1, -1, -2 ], # 1\n [ -1, -1, -1, -1, -1, -1, -1, -1, -2 ], # 2\n [ -1, -1, -1, -1, -1, -1, -1, -1, -2 ], # 3\n [ -1, -1, -1, -1, -1, -1, -1, -1, -2 ], # 4\n [ -1, -1, -1, -1, -1, -1, -1, -1, -2 ], # 5\n [ -1, -1, -1, -1, -1, -1, -1, -1, -2 ], # 6\n [ -1, -1, -1, -1, -1, -1, -1, -1, -2 ], # 7\n [ -1, -1, -1, -1, -1, -1, -1, -1, -2 ], # 8\n [ -2, -2, -2, -2, -2, -2, -2, -2, -2 ] # OoB\n ]\n</code></pre>\n<p>Doing this simplifies testing adjacent indexes to see if they are in bounds:</p>\n<pre><code>if row_idx + i &lt; 0 or row_idx + 1 &gt; (len(board) - 1) or column_idx + j &lt; 0 or column_idx + j &gt; (len(board) - 1):\n continue\n</code></pre>\n<p>becomes:</p>\n<pre><code>OUT_OF_BOUNDS = -2\n\nif board[row_idx + i][col_idx + j] == OUT_OF_BOUNDS:\n continue\n</code></pre>\n<p>or, just skip that test because the square won't pass the next test anyway (if the square has opponent's color).</p>\n<p>Also, you can reduce the depth of nesting by changing the loops. Instead of:\nSIZE = 8</p>\n<pre><code>for row_idx range(HEIGHT):\n for column_idx in range(WIDTH):\n ...\n</code></pre>\n<p>use:</p>\n<pre><code>from itertools import product\n\nfor row_idx, col_idx in product(range(HEIGHT), range(WIDTH)):\n ...\n</code></pre>\n<p>And instead of:</p>\n<pre><code>for i in range(-1, 2, 1):\n for j in range(-1, 2, 1):\n ...\n</code></pre>\n<p>use:</p>\n<pre><code>for i,j in ((-1,-1), (-1,0), (-1, 1),\n ( 0,-1), ( 0, 1),\n ( 1,-1), ( 1,0), ( 1, 1)):\n ...\n</code></pre>\n<p>Which also skips the case of i = j = 0.</p>\n<p>Also, i, j, i2, and j2 are not very descriptive. It would be easy to miss a mistake like <code>board[row_idx + j]</code>. Use something like <code>row_step</code> or <code>dr</code> (delta_row).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T05:52:26.900", "Id": "251287", "ParentId": "251216", "Score": "1" } } ]
{ "AcceptedAnswerId": "251221", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T15:55:52.540", "Id": "251216", "Score": "3", "Tags": [ "python", "algorithm" ], "Title": "Algorithm to find all legal moves in Reversi game" }
251216
<p>The code should do the following in order:</p> <ol> <li>It should download/clone the public Github repository locally.</li> <li>It should remove all the git history (and branches)</li> <li>Use the Github API to create a new Github repository initialized with the input github repository content that you downloaded locally. The new repository should be named using name supplied. I am able to do steps 1 and 3 but <strong>asks for log-in 2 times</strong>. I am not able to initialize the new remote repo with local repo. <strong>local_repo = repo1</strong> how? And <strong>removing git history?</strong> where can I find git history in the cloned repo.</li> </ol> <pre><code>import git,os,tempfile,os,fnmatch,sys from github import Github username = sys.argv[1] password = sys.argv[2] input_repo_url = sys.argv[3] output_repo_name = sys.argv[4] tempdir=tempfile.mkdtemp(prefix=&quot;&quot;,suffix=&quot;&quot;) predictable_filename = &quot;myfile&quot; saved_umask = os.umask(77) path = os.path.join(tempdir,predictable_filename) print(&quot;Cloning the repository at &quot;+path) local_repo = git.Repo.clone_from(input_repo_url,path, branch=&quot;master&quot;) print(&quot;Clone successful!&quot;) g = Github(username,password) user = g.get_user() repo1 = user.create_repo(output_repo_name) print(&quot;New repository created at &quot;+username+&quot; account &quot;) print(repo1) target_url = &quot;https://github.com/&quot;+username+&quot;/&quot;+output_repo_name+&quot;.git&quot; print(target_url) print(&quot;Pushing cloned repo to target repo&quot;) local_repo.create_remote(&quot;new&quot;,url=target_url) local_repo.git.push(&quot;new&quot;) print(&quot;Success!!&quot;) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T17:00:35.220", "Id": "494477", "Score": "0", "body": "I'll happily provide feedback about the script itself, but the larger question is - why? Why would you want to delete all of the history behind a repository when forking a new repo, and why shouldn't a new repo be just that -- a fork?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T17:08:45.787", "Id": "494478", "Score": "0", "body": "Thanks for your reply! . Its a part of an assignment which is supposed to help me understand git and python. So I have to clone a public repo locally, remove history and then push it as a new repository to a remote user's account. How can I use the same git object that i used to create a new remote repo and initialize it with local repo? Because of the 2 objects, 2 log ins are being called." } ]
[ { "body": "<h2>Octal permission fields</h2>\n<pre><code>77\n</code></pre>\n<p>is likely incorrect. What you've written is 77 in <em>decimal</em>, but this would work out to <code>115</code> in octal. If you wanted <code>077</code> in octal, you would actually need to write <code>0o077</code>.</p>\n<h2>Pathlib</h2>\n<p>Consider replacing <code>os.path</code> with use of <code>pathlib</code>.</p>\n<h2>Argument parsing</h2>\n<p>The <code>argv</code> parsing that you've done is fragile - it will fail with an invalid-index exception if the user provides insufficient parameters. Consider using <code>argparse</code> instead.</p>\n<p>Also: do <em>not</em> ask for a password as part of a command line, since it will be stored in the user's shell history. Accept it from an environmental variable, a secure wallet, or from stdin via <code>getpass</code> (not <code>input</code>).</p>\n<h2>String interpolation</h2>\n<pre><code>&quot;https://github.com/&quot;+username+&quot;/&quot;+output_repo_name+&quot;.git&quot;\n</code></pre>\n<p>is more easily written as</p>\n<pre><code>f'https://github.com/{username}/{output_repo_name}.git'\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T10:17:30.230", "Id": "494524", "Score": "0", "body": "Thanks for your suggestion, I will change them. And what about pushing a local repo to remote repo?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T22:02:47.407", "Id": "251234", "ParentId": "251219", "Score": "1" } }, { "body": "<h1>Comment your code</h1>\n<p>This is a more general tip, but it is <strong>very</strong> good practice to put comments in your code to make it more readable and understandable</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T11:44:53.490", "Id": "251249", "ParentId": "251219", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T16:44:08.477", "Id": "251219", "Score": "5", "Tags": [ "python", "homework", "git" ], "Title": "Pushing local repository to remote repository using python Github" }
251219
<p>I'm learning MVP for Android and am wondering if that piece of code that I wrote is correct in terms of this pattern or maybe is completely messed up.</p> <p>I'm wondering if there can be return type other than void in contract interface like I have in Model interface, secondly context shouldn't be passed in constructor of presenter, then how should the model instance be created in presenter's constructor other way? This is my code:</p> <pre><code>public interface CredentialsContract { interface Model { interface OnFinishedLoginListener { void onFinishedLogin(String body); void onFailureLogin(Throwable t); } void saveSomeCredentials(String nameLogin, String passLogin); void saveEmptyCredentials(); String getNameCredential(); String getPassCredential(); boolean getCbCredential(); void checkLogin(OnFinishedLoginListener onFinishedListener, String login, String pass); } interface View { void showBigProgressDialog(); void hideBigProgressDialog(); void setPropertiesWhenLoginIsTrue(); void setPropertiesWhenLoginIsFalse(); void setLoginTextViewText(String response); void setNameCredential(String name); void setPassCredential(String pass); void setCbCredential(boolean cbState); } interface Presenter { void saveSomeCredentials(String nameLogin, String passLogin); void saveEmptyCredentials(); void checkLoginPresenter(String login, String pass); void setNameCredential(); void setPassCredential(); void setCbCredential(); } } </code></pre> <hr /> <pre><code>public class RestData implements CredentialsContract.Model { private Context context; private SharedPreferences pref; private SharedPreferences.Editor editor; public RestData(Context context) { this.context = context; pref = context.getSharedPreferences(&quot;Preferences&quot;, 0); editor = pref.edit(); } @Override public void saveSomeCredentials(String nameLogin, String passLogin) { editor.putString(&quot;userLogin&quot;, nameLogin); // Storing string editor.putString(&quot;userPassword&quot;, passLogin); // Storing string editor.putBoolean(&quot;cbSaveCredentials&quot;, true); editor.apply(); } @Override public void saveEmptyCredentials() { editor.putString(&quot;userLogin&quot;, &quot;&quot;); // Storing string editor.putString(&quot;userPassword&quot;, &quot;&quot;); // Storing string editor.putBoolean(&quot;cbSaveCredentials&quot;, false); editor.apply(); } @Override public void checkLogin(final OnFinishedLoginListener onFinishedListener, String login, String passWhenLogin) { Call&lt;String&gt; result = Api.getClient().checkLogin(login, passWhenLogin); result.enqueue(new Callback&lt;String&gt;() { @Override public void onResponse(Call&lt;String&gt; call, Response&lt;String&gt; response) { onFinishedListener.onFinished(response.body()); } @Override public void onFailure(Call&lt;String&gt; call, Throwable t) { Log.e(&quot;tag&quot;, t.toString()); onFinishedListener.onFailure(t); } }); } @Override public String getNameCredential() { return pref.getString(&quot;userLogin&quot;, &quot;&quot;); } @Override public String getPassCredential() { return pref.getString(&quot;userPassword&quot;, &quot;&quot;); } @Override public boolean getCbCredential() { return pref.getBoolean(&quot;cbSaveCredentials&quot;, false); } } </code></pre> <hr /> <pre><code>public class Credentials extends AppCompatActivity implements CredentialsContract.View { private EditText etNameLogin, etPassLogin; private CheckBox cbSaveCredentials, cbTerms; private TextView tvLoginStatus, tvRegistrationStatus; private ProgressBar pbBig; private CredentialsPresenter credentialsPresenter; private Button bOk; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.credentials_layout); credentialsPresenter = new CredentialsPresenter(this, this); initUIFields(pref); credentialsPresenter.setNameCredential(); credentialsPresenter.setPassCredential(); credentialsPresenter.setCbCredential(); findViewById(R.id.tvTerms).setOnClickListener(v -&gt; initRegulationsDialog()); bOk = findViewById(R.id.bOk); bOk.setOnClickListener(v -&gt; { if (cbSaveCredentials.isChecked()) credentialsPresenter.saveSomeCredentials(etNameLogin.getText().toString(), etPassLogin.getText().toString()); else credentialsPresenter.saveEmptyCredentials(); Intent i = new Intent(getApplicationContext(), Gra.class); i.putExtra(&quot;userLogin&quot;, etNameLogin.getText().toString()); i.putExtra(&quot;onlineGame&quot;, true); startActivity(i); }); findViewById(R.id.bLogin).setOnClickListener(v -&gt; credentialsPresenter.checkLoginPresenter(etNameLogin.getText().toString(), etPassLogin.getText().toString())); } public void initUIFields(SharedPreferences pref) { etNameLogin = findViewById(R.id.etNameLogin); etPassLogin = findViewById(R.id.etPassLogin); cbSaveCredentials = findViewById(R.id.cbSaveCredentials); etNameRegistration = findViewById(R.id.etName); etEmailRegistration = findViewById(R.id.etEmailRegistration); etPassRegistration = findViewById(R.id.etPassRegistration); etPassConfirmationRegistration = findViewById(R.id.etPassConfirmationRegistration); cbTerms = findViewById(R.id.cbTerms); tvLoginStatus = findViewById(R.id.tvLoginStatus); tvRegistrationStatus = findViewById(R.id.tvRegistrationStatus); pbBig = findViewById(R.id.bigProgressBar); } public void initRegulationsDialog() { AlertDialog.Builder dialogRegulations = new AlertDialog.Builder(Credentials.this); dialogRegulations.setTitle(&quot;Terms and conditions&quot;); dialogRegulations.setMessage(&quot;Content&quot;); dialogRegulations.setCancelable(false); dialogRegulations.setNeutralButton(&quot;OK&quot;, (dialog1, which) -&gt; dialog1.dismiss()); dialogRegulations.show(); } @Override public void showBigProgressDialog() { pbBig.setVisibility(View.VISIBLE); } @Override public void hideBigProgressDialog() { pbBig.setVisibility(View.INVISIBLE); } @Override public void setPropertiesWhenLoginIsTrue() { bOk.setEnabled(true); tvLoginStatus.setTextColor(ContextCompat.getColor(this, R.color.green)); } @Override public void setPropertiesWhenLoginIsFalse() { bOk.setEnabled(false); tvLoginStatus.setTextColor(ContextCompat.getColor(this, R.color.red)); } @Override public void setLoginTextViewText(String response) { tvLoginStatus.setText(response); } @Override public void setNameCredential(String name) { etNameLogin.setText(name); } @Override public void setPassCredential(String pass) { etPassLogin.setText(pass); } @Override public void setCbCredential(boolean cbState) { cbSaveCredentials.setChecked(cbState); } } </code></pre> <hr /> <pre><code>public class CredentialsPresenter implements CredentialsContract.Presenter, CredentialsContract.Model.OnFinishedLoginListener { CredentialsContract.Model model; CredentialsContract.View view; SharedPreferences sharedPreferences; SharedPreferences.Editor editor; public CredentialsPresenter(Context context, CredentialsContract.View view) { model = new RestData(context); this.view = view; this.sharedPreferences = sharedPreferences; editor = sharedPreferences.edit(); } @Override public void saveSomeCredentials(String nameLogin, String passLogin) { editor.putString(&quot;userLogin&quot;, nameLogin); editor.putString(&quot;userPassword&quot;, passLogin); editor.putBoolean(&quot;cbSaveCredentials&quot;, true); editor.apply(); } @Override public void saveEmptyCredentials() { editor.putString(&quot;userLogin&quot;, &quot;&quot;); editor.putString(&quot;userPassword&quot;, &quot;&quot;); editor.putBoolean(&quot;cbSaveCredentials&quot;, false); editor.apply(); } @Override public void checkLoginPresenter(String login, String passWhenLogin) { view.showBigProgressDialog(); model.checkLogin(this, login, passWhenLogin); } @Override public void onFinishedLogin(String body) { view.setLoginTextViewText(body); if(body.contains(&quot;true&quot;)) view.setPropertiesWhenLoginIsTrue(); if(body.contains(&quot;false&quot;)) view.setPropertiesWhenLoginIsFalse(); view.hideBigProgressDialog(); } @Override public void onFailureLogin(Throwable t) { view.hideBigProgressDialog(); } @Override public void setNameCredential() { view.setNameCredential(model.getNameCredential()); } @Override public void setPassCredential() { view.setPassCredential(model.getPassCredential()); } @Override public void setCbCredential() { view.setCbCredential(model.getCbCredential()); } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T16:47:01.180", "Id": "251220", "Score": "4", "Tags": [ "java", "android", "mvp" ], "Title": "Fragment of code with Android MVP that checks login credentials via REST API" }
251220
<p>My game engine uses the following broadphase collision detection algorithm:</p> <pre><code>internal void SweepAndPrune() { // First: order all objects from left to right on the x-axis: IOrderedEnumerable&lt;GameObject&gt; axisList = _gameObjects.OrderBy(x =&gt; x.LeftRightMost.X); // loop through all objects: for(int i = 0; i &lt; axisList.Count(); i++) { // For each object, iterate over all the subsequent objects in the list // and find out if there are overlaps on the x-axis: for(int j = i+1; j &lt; axisList.Count(); j++) { GameObject a = axisList.ElementAt(i); GameObject b = axisList.ElementAt(j); if(b.Left &gt; a.Right) { // if their is no overlap, then the rest will not overlap as well. // might as well stop the inner loop here: break; } // if there is an overlap, add A to B's list // and B to A's list of potential collisions. // [every object's list of collision candidates is // cleared before the next frame] a._collisionCandidates.Add(b); b._collisionCandidates.Add(a); } } } </code></pre> <p>The problem is, this algorithm slows down the performance by a lot if there are &gt; 50 objects on screen. Also, the list of GameObject instances (_gameObjects) needs to get sorted another time per frame because I need to order the objects by their distances from the camera (background objects need to get rendered first because of transparency!).</p> <p>Is there anything I can do to speed things up?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T18:35:27.467", "Id": "494483", "Score": "0", "body": "for starter, you could convert `axisList` to list or array, and use `.Count` or `.Length` instead of `Count()` , then replace `ELementAt` with regular index `axisList[i]`. This would give you some performance boost, the rest would be outside the loop scope I guess." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T18:39:52.943", "Id": "494484", "Score": "0", "body": "Alright, I will give it a try. Thanks!" } ]
[ { "body": "<p>An <code>IEnumerable</code> (and <code>IOrderedEnumerable</code>) represents a <em>question</em>, not an answer. <code>axisList</code> is not really a list -- it is a <em>question</em> asking &quot;What is the sequence of elements from <code>_gameObjects</code> ordered by X value?&quot;. So every time you do this:</p>\n<pre class=\"lang-csharp prettyprint-override\"><code> GameObject a = axisList.ElementAt(i);\n GameObject b = axisList.ElementAt(j);\n</code></pre>\n<p>You are <em>answering</em> the question &quot;What is the <code>i</code>th element in that ordering&quot;. Which means it needs to re-order the sequence on every iteration! Your outer loop ends up being hugely expensive (O(n^3 log(n)) if my math checks out); you certainly don't need to do that.</p>\n<p>You should cache the result of the ordering and re-use it in your loop. Change this</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>IOrderedEnumerable&lt;GameObject&gt; axisList = _gameObjects.OrderBy(x =&gt; x.LeftRightMost.X);\n</code></pre>\n<p>to this:</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>var orderedByX = _gameObjects.OrderBy(x =&gt; x.LeftRightMost.X).ToList();\n</code></pre>\n<p><code>.ToList()</code> will evaluate the <code>OrderBy</code> query and return a flattened &quot;answer&quot; that you can keep reusing, and as a bonus it has O(1) lookup so <code>ElementAt</code> is fast -- you could even change <code>ElementAt(i)</code> to <code>[i]</code> to make that more clear.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T18:52:37.620", "Id": "494486", "Score": "0", "body": "Holy moly! My game loop just went from 16.4ms to 1.9ms with 100 objects on screen. In debug mode! This is the biggest performance increase I have ever seen. I feel so stupid! Thank you both Jeff and iSR5 for helping me. Special thanks to Jeff for elaborating. Wow! I am stunned!!!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T18:54:28.847", "Id": "494487", "Score": "1", "body": "And if `_gameObjects` doesn't change often relative to how often your algorithm runs, you could even just re-sort it every time it changes rather than every time you run your algorithm. Or use a `SortedList` for `_gameObjects` which does that for you automatically." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T18:58:32.440", "Id": "494488", "Score": "0", "body": "I am very grateful for your enthusiasm! I will try that as well. Hell, I wish there was something that I could help YOU with - but you seem to be a lot more experienced than I am :-(" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T18:39:31.747", "Id": "251226", "ParentId": "251223", "Score": "4" } } ]
{ "AcceptedAnswerId": "251226", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T17:56:48.500", "Id": "251223", "Score": "4", "Tags": [ "c#", "game", "opengl" ], "Title": "Sweep & prune broadphase algorithm" }
251223
<p>This is meant to be a performance-centric question as this type of conversion is obviously very common. I'm wondering about the possibilities for making this process faster.</p> <p>I have a program that creates several thousand QR codes from a list, embeds them in an MS Word <code>docx</code> template, and then converts the <code>docx</code> files to <code>pdf</code>. Problem is, what I've designed is very slow. When creating several thousand <code>pdf</code> files, it takes hours on a local machine.</p> <p>What can I do to speed this program up? Is there a way to multithread it? (Total newb to that topic). Or, what about my program design is inherently flawed?</p> <p>Repeatable program below, meant to be run in local Windows 10 directory:</p> <pre><code>import pyqrcode import pandas as pd from docx import Document from docx.enum.text import WD_ALIGN_PARAGRAPH import glob import os from docx2pdf import convert def make_folder(): os.mkdir(&quot;codes&quot;) os.mkdir(&quot;docs&quot;) def create_qr_code(): for index, values in df.iterrows(): data = barcode = values[&quot;barcode&quot;] image = pyqrcode.create(data) image.png(&quot;codes\\&quot;+f&quot;{barcode}.png&quot;, scale=3) def embed_qr_code(): qr_images = glob.glob(&quot;codes\\&quot;+&quot;*.png&quot;) for image in qr_images: image_name = os.path.basename(image) doc = Document() doc.add_picture(image) last_paragraph = doc.paragraphs[-1] last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER doc.save(&quot;docs\\&quot;+f&quot;{image_name}.docx&quot;) convert(&quot;docs\\&quot;+f&quot;{image_name}.docx&quot;) def clean_file_names(): paths = (os.path.join(root, filename) for root, _, filenames in os.walk(&quot;docs\\&quot;) for filename in filenames) for path in paths: newname = path.replace(&quot;.png&quot;, &quot;&quot;) if newname != path: os.rename(path, newname) data = {'barcode': ['teconec', 'tegovec', 'teconvec', 'wettrot', 'wetocen']} df = pd.DataFrame(data) make_folder() create_qr_code() embed_qr_code() clean_file_names() </code></pre> <p>Thank you!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T21:52:40.163", "Id": "494499", "Score": "2", "body": "Why the `docx` step - why not go directly to PDF - using something like `reportlab`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T09:01:56.157", "Id": "494518", "Score": "2", "body": "Since your Python code is small and straightforward (if not particularly maintainable), I assume the library functions you use are slow. You already have it split into three distinct steps (first, create QR codes; second, embed QR codes in DOCX; third, convert DOCX to PDF), so it should be straightforward to insert some code to measure how long each step takes, to get an idea which part slows you down. Finally, while Python is great for scripting because you get results fast, it is slow in general, and for more performance, you may need to step away from Python, and use something else." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T15:30:35.453", "Id": "494546", "Score": "0", "body": "@dumetrulo Thank you, that is very helpful, what feedback would you have as far as improving maintainability?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T18:14:48.630", "Id": "494572", "Score": "2", "body": "Did you profile your code? I have no experience with docx2pdf but it seems to be the bottleneck. You can [save your image directly into pdf using PIL](https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#pdf), thus replacing this time consuming process. You also can, perhaps, use LaTeX for that purpose as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T20:28:43.313", "Id": "494589", "Score": "0", "body": "@dumetrulo Given the code shown Python is very unlikely to be the bottleneck, and libraries are instead. So my question about direct-to-PDF stands." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-04T03:08:55.550", "Id": "495312", "Score": "0", "body": "Which step is the slow one? Measure." } ]
[ { "body": "<p>I <a href=\"https://chriskiehl.com/article/parallelism-in-one-line\" rel=\"nofollow noreferrer\">recently learned</a> how easy it is to incorporate multiprocessing and multithreading into a Python program, and would like to share it with you.</p>\n<p>Python's built-in <a href=\"https://docs.python.org/3/library/multiprocessing.html\" rel=\"nofollow noreferrer\"><code>multiprocessing</code> module</a> offers a simple way to add multiprocessing to a program. However, since your program performs a lot of writes, I think it may be better to use the <code>multiprocessing.dummy</code> module instead. This module offers the same API as the <code>multiprocessing</code> module, but is used for multithreading instead of multiprocessing, and thus is better suited to programs that are IO intensive.</p>\n<p>First, import the <code>Pool</code> class from the <code>multiprocessing.dummy</code> module:</p>\n<p><code>import Pool from multiprocessing.dummy as ThreadPool</code></p>\n<p>I aliased it as <code>ThreadPool</code> just for added clarity that we are using multithreading and not multiprocessing. Next, take a look at all the for loops in your code. To add multithreading, we will have to change those for loops to call a function on each iteration instead of performing a series of steps:</p>\n<pre><code>def create_qr_code(values):\n data = barcode = values[&quot;barcode&quot;]\n image = pyqrcode.create(data)\n image.png(&quot;codes\\\\&quot;+f&quot;{barcode}.png&quot;, scale=3)\n\ndef create_qr_codes():\n for index, values in df.iterrows():\n create_qr_code(values)\n\ndef embed_qr_code(image):\n image_name = os.path.basename(image)\n doc = Document()\n doc.add_picture(image)\n last_paragraph = doc.paragraphs[-1] \n last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER\n doc.save(&quot;docs\\\\&quot;+f&quot;{image_name}.docx&quot;)\n convert(&quot;docs\\\\&quot;+f&quot;{image_name}.docx&quot;)\n\ndef embed_qr_codes():\n qr_images = glob.glob(&quot;codes\\\\&quot;+&quot;*.png&quot;)\n for image in qr_images:\n embed_qr_code(image)\n\ndef clean_file_name(path):\n newname = path.replace(&quot;.png&quot;, &quot;&quot;)\n if newname != path:\n os.rename(path, newname)\n\ndef clean_file_names():\n paths = (os.path.join(root, filename)\n for root, _, filenames in os.walk(&quot;docs\\\\&quot;)\n for filename in filenames)\n for path in paths:\n clean_file_name(path)\n</code></pre>\n<p>Now for the fun part. In each of the functions that use for loops, we will replace the for loops with usages of <code>ThreadPool</code>s as context managers. We can then call each <code>ThreadPool</code>'s <code>map</code> method to perform the actions using multithreading:</p>\n<pre><code>def create_qr_codes():\n rows = (values for _, values in df.iterrows())\n with ThreadPool() as pool:\n pool.map(create_qr_code, rows)\n\ndef embed_qr_codes():\n qr_images = glob.glob(&quot;codes\\\\&quot;+&quot;*.png&quot;)\n with ThreadPool() as pool:\n pool.map(embed_qr_code, qr_images)\n\ndef clean_file_names():\n paths = (os.path.join(root, filename)\n for root, _, filenames in os.walk(&quot;docs\\\\&quot;)\n for filename in filenames)\n with ThreadPool() as pool:\n pool.map(clean_file_name, paths)\n</code></pre>\n<p>Note that when instantiating a Pool, you can pass a value to it to specify the number of processes (or in our case, threads) to use. According to the <a href=\"https://docs.python.org/3/library/multiprocessing.html#module-multiprocessing.pool\" rel=\"nofollow noreferrer\">Python docs</a>:</p>\n<blockquote>\n<p>If processes is None then the number returned by os.cpu_count() is used.</p>\n</blockquote>\n<p>Also, don't forget to change these two function calls...</p>\n<pre><code>create_qr_code()\nembed_qr_code()\n</code></pre>\n<p>...to these:</p>\n<pre><code>create_qr_codes()\nembed_qr_codes()\n</code></pre>\n<p>This should speed up your program significantly. If not, try using the <code>multiprocessing</code> module instead of <code>multiprocessing.dummy</code>.</p>\n<p>Finally, one extra tip. You may want to refactor this function:</p>\n<pre><code>def make_folder():\n os.mkdir(&quot;codes&quot;)\n os.mkdir(&quot;docs&quot;)\n</code></pre>\n<p>To use the <a href=\"https://docs.python.org/3/library/os.html#os.makedirs\" rel=\"nofollow noreferrer\"><code>os.makedirs</code></a> function instead to avoid raising an error if the directories already exist:</p>\n<pre><code>def make_folder():\n os.makedirs(&quot;codes&quot;, exist_ok=True)\n os.makedirs(&quot;docs&quot;, exist_ok=True)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-14T01:15:02.317", "Id": "257128", "ParentId": "251228", "Score": "3" } } ]
{ "AcceptedAnswerId": "257128", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T19:19:46.547", "Id": "251228", "Score": "7", "Tags": [ "python", "performance", "multithreading", "pdf", "ms-word" ], "Title": "Speeding up Python program that converts DOCX to PDF in Windows" }
251228
<p>The excercise is to print n nested squares. The nested squares are given as input by the user.</p> <p>Example output for n = 4:</p> <pre><code>┌────────────────────────────────┐ │ ┌────────────────────────┐ │ │ │ ┌────────────────┐ │ │ │ │ │ ┌────────┐ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ └────────┘ │ │ │ │ │ └────────────────┘ │ │ │ └────────────────────────┘ │ └────────────────────────────────┘ </code></pre> <p>My solution:</p> <pre><code>import Data.List line :: Int -&gt; String -&gt; String -&gt; String -&gt; String line n start middle end = start ++ m ++ end where m = foldl1 (++) (replicate n middle) topLine :: Int -&gt; String topLine n = line n &quot;┌&quot; &quot;────&quot; &quot;┐&quot; middleLine :: Int -&gt; String middleLine n = line n &quot;│&quot; &quot; &quot; &quot;│&quot; bottomLine :: Int -&gt; String bottomLine n = line n &quot;└&quot; &quot;────&quot; &quot;┘&quot; square :: Int -&gt; [String] square n = topLine n : middle ++ [bottomLine n] where middle = take n (repeat (middleLine n)) concentricSquares :: Int -&gt; String concentricSquares n = intercalate &quot;\n&quot; merged where size = n * 2 squares = map square [2, 4 .. size] merged = foldl1 mergeSquares squares mergeSquares :: [String] -&gt; [String] -&gt; [String] mergeSquares x (y:ys) = y : zipWith mergeLines x ys ++ [last ys] mergeLines :: String -&gt; String -&gt; String mergeLines x y = [head y] ++ &quot; &quot; ++ x ++ &quot; &quot; ++ [last y] main :: IO () main = putStrLn &quot;Enter square number:&quot; &gt;&gt; getLine &gt;&gt;= \num -&gt; putStrLn (concentricSquares (read num)) </code></pre>
[]
[ { "body": "<p>This looks fine. Every top-level binding has a type signature, and all functions are nice and short. However, the <code>mergeLines</code> and <code>mergeSquares</code> functions could use a little bit more documentation. There is also (probably) an algorithm that doesn't introduce that many lines just to throw them away in <code>mergeLines</code>.</p>\n<p>Other than that, there are three possible improvements:</p>\n<ul>\n<li><p><code>foldl1 (++)</code> is <code>concat</code>.</p>\n</li>\n<li><p><code>take n . repeat</code> is <code>replicate n</code> (in <code>square</code>)</p>\n</li>\n<li><p><code>getLine &gt;&gt;= \\num -&gt; f (g (read num))</code> is <code>readLn &gt;&gt;= \\num -&gt; f (g num)</code></p>\n<p>We can therefore write <code>readLn &gt;&gt;= putStrLn . concentricSquares</code> in <code>main</code>.</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T20:51:33.090", "Id": "251268", "ParentId": "251230", "Score": "5" } } ]
{ "AcceptedAnswerId": "251268", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T20:09:10.063", "Id": "251230", "Score": "6", "Tags": [ "haskell" ], "Title": "N Nested squares" }
251230
<p>I would like your opinion on my <code>Remove-Files</code> PowerShell function. It is used in my <a href="https://github.com/Zoran-Jankov/File-Removal-PowerShell-Script" rel="nofollow noreferrer"><em>File-Removal-PowerShell-Script</em></a>. It is designed to be very flexible so a script user can have configure it to remove files in multiple and various way as it often the chase.</p> <h3>Remove-Files function</h3> <pre><code>function Remove-Files { [CmdletBinding(SupportsShouldProcess = $true)] [OutputType([PSCustomObject])] param ( [Parameter(Position = 0, Mandatory, ValueFromPipelineByPropertyName)] [string] $FolderPath, [Parameter(Position = 1, Mandatory, ValueFromPipelineByPropertyName)] [string] $FileName, [Parameter(Position = 2, ValueFromPipelineByPropertyName)] [int] $OlderThen = 0, [Parameter(Position = 3, ValueFromPipelineByPropertyName)] [string] $Recurse = &quot;false&quot;, [Parameter(Position = 4, ValueFromPipelineByPropertyName)] [string] $Force = &quot;false&quot; ) begin { $DateToDelete = (Get-Date).AddDays(- $OlderThen) } process { $FolderSpaceFreed = 0 $FilesRemoved = 0 $FailedRemovals = 0 if (-not (Test-Path -Path $FolderPath)) { Write-Log -Message &quot;ERROR: $FolderPath folder does not exist&quot; return } $FullPath = Join-Path -Path $FolderPath -ChildPath $FileName if ($Recurse -eq &quot;true&quot;) { $FileList = Get-ChildItem -Path $FullPath -Recurse } else { $FileList = Get-ChildItem -Path $FullPath } $FileList = $FileList | Where-Object {$_.LastWriteTime -lt $DateToDelete} foreach ($File in $FileList) { $FileSize = (Get-Item -Path $File.FullName).Length $SpaceFreed = Get-FormattedFileSize -Size $FileSize if ($Force -eq &quot;true&quot;) { Get-Item -Path $File.FullName | Remove-Item -Force } else { Get-Item -Path $File.FullName | Remove-Item } if (-not (Test-Path -Path $File.FullName)) { $Message = &quot;Successfully deleted &quot; + $File.Name + &quot; file - removed $SpaceFreed&quot; $FolderSpaceFreed += $FileSize $FilesRemoved ++ } else { $Message = &quot;Failed to delete &quot; + $File.Name + &quot; file&quot; $FailedRemovals ++ } Write-Log -Message $Message } $SpaceFreed = Get-FormattedFileSize -Size $FolderSpaceFreed if ($FilesRemoved -gt 0) { Write-Log -Message &quot;Successfully deleted $FilesRemoved files in $FolderPath folder, and $SpaceFreed of space was freed&quot; } if ($FailedRemovals -gt 0) { Write-Log -Message &quot;Failed to delete $FailedRemovals files in $FolderPath folder&quot; } if ($FilesRemoved -eq 0 -and $FailedRemovals -eq 0) { Write-Log -Message &quot;No files for delition were found in $FolderPath folder&quot; } New-Object -TypeName psobject -Property @{ FolderSpaceFreed = $FolderSpaceFreed FilesRemoved = $FilesRemoved FailedRemovals = $FailedRemovals } } } </code></pre> <p>Before someone says anything about it, I have to tell you why I did not use a <code>switch</code> type for <code>-Recurse</code> and <code>-Force</code> parameters, and it is because the function is feed from <code>.csv</code> file with data, and I did not find a elegant way to pass string value to a <code>switch</code> parameter.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T21:45:59.027", "Id": "494498", "Score": "1", "body": "`… -Force:$($Force -eq \"true\")` is a possible way to pass a `[string]$Force` value to the `-Force` switch parameter…" } ]
[ { "body": "<p>I have found a way to use pass string values to switch parameters to <code>Remove-Files</code> function so I have refactored the function ho have two switch parameters.</p>\n<h2>The new version</h2>\n<pre><code>function Remove-Files {\n [CmdletBinding(SupportsShouldProcess = $true)]\n [OutputType([PSCustomObject])]\n param (\n [Parameter(Mandatory = $true,\n Position = 0,\n ParameterSetName = &quot;FolderPath&quot;,\n ValueFromPipeline = $false,\n ValueFromPipelineByPropertyName = $true,\n HelpMessage = &quot;Full folder path in which file/files are to be deleted&quot;)]\n [string]\n $FolderPath,\n\n [Parameter(Mandatory = $true,\n Position = 1,\n ParameterSetName = &quot;FileName&quot;,\n ValueFromPipeline = $false,\n ValueFromPipelineByPropertyName = $true,\n HelpMessage = &quot;File name that can include wildcard character&quot;)]\n [SupportsWildcards()]\n [string]\n $FileName,\n\n [Parameter(Mandatory = $false,\n Position = 2,\n ParameterSetName = &quot;OlderThen&quot;,\n ValueFromPipeline = $false,\n ValueFromPipelineByPropertyName = $true,\n HelpMessage = &quot;Number of days to delete files older than that&quot;)]\n [int]\n $OlderThen = 0,\n\n [Parameter(Mandatory = $false,\n Position = 3,\n ParameterSetName = &quot;Recurse&quot;,\n ValueFromPipeline = $false,\n ValueFromPipelineByPropertyName = $true,\n HelpMessage = &quot;Switch on to file remove files in subfolders&quot;)]\n [switch]\n $Recurse = $false,\n\n [Parameter(Mandatory = $false,\n Position = 4,\n ParameterSetName = &quot;Force&quot;,\n ValueFromPipeline = $false,\n ValueFromPipelineByPropertyName = $true,\n HelpMessage = &quot;Switch on to force remove files&quot;)]\n [switch]\n $Force = $false\n )\n\n process {\n $FolderSpaceFreed = 0\n $FilesRemoved = 0\n $FailedRemovals = 0\n\n if (-not (Test-Path -Path $FolderPath)) {\n Write-Log -Message &quot;ERROR: $FolderPath folder does not exist&quot;\n return\n }\n\n $FullPath = Join-Path -Path $FolderPath -ChildPath $FileName\n\n if ($Recurse) {\n $FileList = Get-ChildItem -Path $FullPath -Recurse\n }\n else {\n $FileList = Get-ChildItem -Path $FullPath \n }\n\n $DateToDelete = (Get-Date).AddDays(- $OlderThen)\n\n $FileList = $FileList | Where-Object {$_.CreationTime -lt $DateToDelete}\n\n foreach ($File in $FileList) {\n $FileSize = (Get-Item -Path $File.FullName).Length\n $SpaceFreed = Get-FormattedFileSize -Size $FileSize\n\n if ($Force) {\n Get-Item -Path $File.FullName | Remove-Item -Force\n }\n else {\n Get-Item -Path $File.FullName | Remove-Item\n }\n\n if (-not (Test-Path -Path $File.FullName)) {\n $Message = &quot;Successfully deleted &quot; + $File.Name + &quot; file - removed $SpaceFreed&quot;\n $FolderSpaceFreed += $FileSize\n $FilesRemoved ++\n }\n else {\n $Message = &quot;Failed to delete &quot; + $File.Name + &quot; file&quot;\n $FailedRemovals ++\n }\n Write-Log -Message $Message\n }\n\n $SpaceFreed = Get-FormattedFileSize -Size $FolderSpaceFreed\n\n if ($FilesRemoved -gt 0) {\n Write-Log -Message &quot;Successfully deleted $FilesRemoved files in $FolderPath folder, and $SpaceFreed of space was freed&quot;\n }\n if ($FailedRemovals -gt 0) {\n Write-Log -Message &quot;Failed to delete $FailedRemovals files in $FolderPath folder&quot;\n }\n if ($FilesRemoved -eq 0 -and $FailedRemovals -eq 0) {\n Write-Log -Message &quot;No files for delition were found in $FolderPath folder&quot;\n }\n New-Object -TypeName psobject -Property @{\n FolderSpaceFreed = $FolderSpaceFreed\n FilesRemoved = $FilesRemoved\n FailedRemovals = $FailedRemovals\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-30T07:18:28.777", "Id": "251324", "ParentId": "251232", "Score": "0" } } ]
{ "AcceptedAnswerId": "251324", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-27T20:30:26.537", "Id": "251232", "Score": "1", "Tags": [ "powershell" ], "Title": "Fully parameterized PowerShell function for file removal" }
251232
<p>I have recently finished my first real C++ program. It is text based, but hey, what d'ya expect out of a student? So, I would like person(s) to review the code I have written. It ain't short, but I wouldn't call it a &quot;long&quot; program either.</p> <p>I couldn't figure if I could attach a file or not, so I provide a link, and if you'd rather just copy and paste it, then here it is below...</p> <p>Link - <a href="https://www.dropbox.com/sh/ihvmdhl9t22hqrj/AACq_3HxMaMn8lpop2kATtega?dl=0" rel="noreferrer">https://www.dropbox.com/sh/ihvmdhl9t22hqrj/AACq_3HxMaMn8lpop2kATtega?dl=0</a></p> <p>Also, would love feedback. Again, I'm new, and yes it is very clunky and inefficient, but hey, I'm proud! Though, I would love some criticism. I honestly have hardly a clue what I'm doing, and just threw this thing together.</p> <p>Without further adieu, enjoy!</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;time.h&gt; #include &lt;bits/stdc++.h&gt; using namespace std; int number, overall; string team, nextgame; int opponentoverall; int score, score2, random, random2, random3, random4, random5, randoml; float finalscore, finalscore2; string choice; int week = 1; int i = 3; int u = 0; int randl; int champ1, champ2; int onet = 0; int twot = 0; int threet = 0; int fourt = 0; int fivet = 0; int sixt = 0; int sevent = 0; int eightt = 0; int ninet = 0; int tent = 0; int onev = 0; int twov = 0; int threev = 0; int fourv = 0; int fivev = 0; int sixv = 0; int sevenv = 0; int eightv = 0; int ninev = 0; int tenv = 0; string champname, champname2; string prospect1 = &quot;Jonas Hill - QB&quot;; string prospect2 = &quot;Kyle Matthew - DB&quot;; string prospect3 = &quot;Julius Brown - RB&quot;; string prospect4 = &quot;Reece David - C&quot;; string prospect5 = &quot;Cole Anderson - FS&quot;; string prospect6 = &quot;Andy Tyler - WR&quot;; string prospect7 = &quot;Macus Reed - FB&quot;; string prospect8 = &quot;Elijah Moore - LB&quot;; string prospect9 = &quot;Larry Steel - RB&quot;; string prospect10 = &quot;Nicholas Dean - LB&quot;; int oner = 0; int twor = 0; int threer = 0; int fourr = 0; int fiver = 0; int sixr = 0; int sevenr = 0; int eightr = 0; int niner = 0; int tenr = 0; int ones = 0; int twos = 0; int threes = 0; int fours = 0; int fives = 0; int sixs = 0; int sevens = 0; int eights = 0; int nines = 0; int tens = 0; string one = &quot; &quot;; string two = &quot; &quot;; string three = &quot; &quot;; string four = &quot; &quot;; string five = &quot; &quot;; string six = &quot; &quot;; string seven = &quot; &quot;; string eight = &quot; &quot;; string nine = &quot; &quot;; string ten = &quot; &quot;; int minutes = 120; class Team { public: string name; int overall, game; int win, loss; string week1, week2, week3, week4, week5, week6, week7, week8, next; }; void start() { cout &lt;&lt; string( 100, '\n' ); cout &lt;&lt; &quot;Choose a School to Coach!&quot; &lt;&lt; endl; cout &lt;&lt; &quot;1- Tennessee&quot; &lt;&lt; endl; enum Schools{ tennessee = 1,auburn,pennst }; cin &gt;&gt; number; if(number == tennessee){ team = &quot;Tennessee&quot;; overall = 75; } } void mainmenu() { cout &lt;&lt; string( 100, '\n' ); cout &lt;&lt; &quot;FOR THE PLAYER EXPERIENCE, PLEASE PLAY IN FULL SCREEN&quot; &lt;&lt; endl; cout &lt;&lt; &quot;Be the Coach | College Football Manager&quot; &lt;&lt; endl; cout &lt;&lt; &quot;1 - Manage&quot; &lt;&lt; endl &lt;&lt; &quot;2 - Manual&quot; &lt;&lt; endl &lt;&lt; &quot;3 - Abort&quot; &lt;&lt; endl; enum Choices{ manage = 1,manual,abort }; cin &gt;&gt; number; if(number == manage){ start(); } } int main() { srand (time(NULL)); int tut = 0; int rands; int onel = rand() % 30 + 1; int two1 = rand() % 30 + 1; int three1 = rand() % 30 + 1; int four1 = rand() % 30 + 1; int five1 = rand() % 30 + 1; int six1 = rand() % 30 + 1; int seven1 = rand() % 30 + 1; int eight1 = rand() % 30 + 1; int nine1 = rand() % 30 + 1; int ten1 = rand() % 30 + 1; int onec = rand() % 10 + 1; int twoc = rand() % 10 + 1; int threec = rand() % 10 + 1; int fourc = rand() % 10 + 1; int fivec = rand() % 10 + 1; int sixc = rand() % 10 + 1; int sevenc = rand() % 10 + 1; int eightc = rand() % 10 + 1; int ninec = rand() % 10 + 1; int tenc = rand() % 10 + 1; int addrat = 0; int Year = 1; Team Clemson; Clemson.name = &quot;Clemson&quot;; Clemson.overall = 88; Clemson.win = 0; Clemson.loss = 0; Team Alabama; Alabama.name = &quot;Alabama&quot;; Alabama.overall = 86; Alabama.win = 0; Alabama.loss = 0; Team Georgia; Georgia.name = &quot;Georgia&quot;; Georgia.overall = 85; Georgia.win = 0; Georgia.loss = 0; Team Florida; Florida.name = &quot;Florida&quot;; Florida.overall = 83; Florida.win = 0; Florida.loss = 0; Team NotreDame; NotreDame.name = &quot;Notre Dame&quot;; NotreDame.overall = 80; NotreDame.win = 0; NotreDame.loss = 0; Team OhioState; OhioState.name = &quot;Ohio State&quot;; OhioState.overall = 79; OhioState.win = 0; OhioState.loss = 0; Team MiamiFL; MiamiFL.name = &quot;Miami FL&quot;; MiamiFL.overall = 77; MiamiFL.win = 0; MiamiFL.loss = 0; Team UNC; UNC.name = &quot;UNC&quot;; UNC.overall = 75; UNC.win = 0; UNC.loss = 0; Team PennSt; PennSt.name = &quot;Penn State&quot;; PennSt.overall = 72; PennSt.win = 0; PennSt.loss = 0; Team OklahomaSt; OklahomaSt.name = &quot;Oklahoma State&quot;; OklahomaSt.overall = 70; OklahomaSt.win = 0; OklahomaSt.loss = 0; Team Auburn; Auburn.name = &quot;Auburn&quot;; Auburn.overall = 68; Auburn.win = 0; Auburn.loss = 0; Team Tennessee; Tennessee.name = &quot;Tennessee&quot;; Tennessee.overall = 65; Tennessee.win = 0; Tennessee.loss = 0; Tennessee.week1 = &quot;Georgia&quot;; Tennessee.week2 = &quot;Alabama&quot;; Tennessee.week3 = &quot;OklahomaSt&quot;; Tennessee.week4 = &quot;PennSt&quot;; Tennessee.week5 = &quot;Auburn&quot;; Tennessee.week6 = &quot;UNC&quot;; Tennessee.week7 = &quot;MiamiFL&quot;; Tennessee.week8 = &quot;OhioState&quot;; Tennessee.next = Tennessee.week1; mainmenu(); home: if(Alabama.overall &gt; 100){ Alabama.overall = 100; } if(Clemson.overall &gt; 100){ Clemson.overall = 100; } if(OhioState.overall &gt; 100){ OhioState.overall = 100; } if(NotreDame.overall &gt; 100){ NotreDame.overall = 100; } if(OklahomaSt.overall &gt; 100){ OklahomaSt.overall = 100; } if(MiamiFL.overall &gt; 100){ MiamiFL.overall = 100; } if(Auburn.overall &gt; 100){ Auburn.overall = 100; } if(UNC.overall &gt; 100){ UNC.overall = 100; } if(Florida.overall &gt; 100){ Florida.overall = 100; } if(PennSt.overall &gt; 100){ PennSt.overall = 100; } if(Georgia.overall &gt; 100){ Georgia.overall = 100; } if(Tennessee.overall &gt; 100){ Tennessee.overall = 100; } if(Tennessee.next == &quot;Georgia&quot;){ opponentoverall = Georgia.overall; }else if(Tennessee.next == &quot;Alabama&quot;){ opponentoverall = Alabama.overall; }else if(Tennessee.next == &quot;OklahomaSt&quot;){ opponentoverall = OklahomaSt.overall; }else if(Tennessee.next == &quot;PennSt&quot;){ opponentoverall = PennSt.overall; }else if(Tennessee.next == &quot;Auburn&quot;){ opponentoverall = Auburn.overall; }else if(Tennessee.next == &quot;UNC&quot;){ opponentoverall = UNC.overall; }else if(Tennessee.next == &quot;MiamiFL&quot;){ opponentoverall = MiamiFL.overall; }else if(Tennessee.next == &quot;OhioState&quot;){ opponentoverall = OhioState.overall; } cout &lt;&lt; string( 100, '\n' ); cout &lt;&lt; &quot;Year &quot; &lt;&lt; Year &lt;&lt; endl; cout &lt;&lt; &quot;WEEK &quot; &lt;&lt; week &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; &quot;Team - &quot; &lt;&lt; Tennessee.name &lt;&lt; endl; cout &lt;&lt; &quot;Team Overall - &quot; &lt;&lt; Tennessee.overall &lt;&lt; endl; cout &lt;&lt; &quot;Record - &quot; &lt;&lt; &quot;(&quot; &lt;&lt; Tennessee.win &lt;&lt; &quot;-&quot; &lt;&lt; Tennessee.loss &lt;&lt; &quot;)&quot; &lt;&lt; endl; cout &lt;&lt; &quot;Talent joining your team next year - &quot; &lt;&lt; addrat &lt;&lt; endl; cout &lt;&lt; &quot;Next Game is &quot; &lt;&lt; Tennessee.next &lt;&lt; endl; cout &lt;&lt; &quot;Opponent Overall - &quot; &lt;&lt; opponentoverall; cout &lt;&lt; endl &lt;&lt; &quot;1- Play Next Game&quot; &lt;&lt; endl &lt;&lt; &quot;2- Teamboard&quot; &lt;&lt; endl &lt;&lt; &quot;3- Schedule&quot; &lt;&lt; endl &lt;&lt; &quot;4- Recruiting&quot; &lt;&lt; endl &lt;&lt; &quot;5- Customize&quot; &lt;&lt; endl; enum Choices{playgame = 1,teamboard, schedule, recruiting, customize}; cin &gt;&gt; number; if(number == teamboard){ goto TeamBoard; }else if(number == playgame){ if(week &lt; 9){ goto week1; }else{ goto Championship; } }else if(number == schedule){ goto schedule; }else if(number == recruiting){ if(tut == 0){ cout &lt;&lt; string( 100, '\n' ); cout &lt;&lt; &quot;Do you want a recruiting tutorial?&quot; &lt;&lt; endl; cout &lt;&lt; &quot;1 - Yes&quot; &lt;&lt; endl &lt;&lt; &quot;2 - No&quot; &lt;&lt; endl; cin &gt;&gt; number; if(number == 2){ tut = 1; goto recruiting; }else{ tut = 1; goto rechelp; } }else{ goto recruiting; } }else if(number == customize){ goto customize; } rechelp: cout &lt;&lt; string( 100, '\n' ); cout &lt;&lt; &quot;Recruiting is simple! Scout players to find out how good they are, and call and offer visits to them to make them like your program more!&quot; &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; &quot;It is recommended to start off by scouting!&quot; &lt;&lt; endl &lt;&lt; &quot;You can scout by typing in the corresponding number to that option, keep in mind this uses minutes, and you only have so much time in a day!&quot; &lt;&lt; endl; cout &lt;&lt; &quot;Now you will see a list of players! Type in one of their numbers to start scouting them.&quot; &lt;&lt; endl &lt;&lt; &quot;At first, it will give you a basic range of their raiting, but the more you scout them, the more percise the raiting will become!&quot; &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; &quot;You ready to call? Ok then, get to calling!&quot; &lt;&lt; endl &lt;&lt; &quot;Like before, type in the corresponding number to that option. Now you have the list of players again, all awaiting your call!&quot; &lt;&lt; endl; cout &lt;&lt; &quot;Pick one by typing in their number. Once you have done this, it will display how the call went, and how it effected their liking of your program!&quot; &lt;&lt; endl &lt;&lt; &quot;Sometime the call can go bad, and sometimes it can go great!&quot; &lt;&lt; endl; cout &lt;&lt; &quot;The more you call, the more their liking off your program goes higher!&quot; &lt;&lt; endl &lt;&lt; &quot;But keep in mind, this waists time, and you need to leave some time for the other players!&quot; &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; &quot;Now, if you want, to boost their liking of your school, offer them to visit!&quot; &lt;&lt; endl &lt;&lt; &quot;If you win your football game the weekend they visit, then their liking goes up! Loose, and well, you get the point...&quot; &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; &quot;Time to offer them that scholarship(As long as their liking is decently high!)! Depending on their liking of your program, they may or may not accept!&quot; &lt;&lt; endl &lt;&lt; &quot;If they accept, at the end of the year, their raiting will be added to your overall!&quot; &lt;&lt; endl; cin &gt;&gt; number; goto home; customize: cout &lt;&lt; &quot;What is the new name for your team?&quot; &lt;&lt; endl; cin &gt;&gt; choice; Tennessee.name = choice; goto home; schedule: cout &lt;&lt; string( 100, '\n' ); cout &lt;&lt; &quot;Week 1 - &quot; &lt;&lt; Tennessee.week1 &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; &quot;Week 2 - &quot; &lt;&lt; Tennessee.week2 &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; &quot;Week 3 - &quot; &lt;&lt; Tennessee.week3 &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; &quot;Week 4 - &quot; &lt;&lt; Tennessee.week4 &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; &quot;Week 5 - &quot; &lt;&lt; Tennessee.week5 &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; &quot;Week 6 - &quot; &lt;&lt; Tennessee.week6 &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; &quot;Week 7 - &quot; &lt;&lt; Tennessee.week7 &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; &quot;Week 8 - &quot; &lt;&lt; Tennessee.week8 &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; endl &lt;&lt; &quot;Type 1 and press Enter to continue.&quot; &lt;&lt; endl; cin &gt;&gt; number; goto home; recruiting: cout &lt;&lt; string( 100, '\n' ); cout &lt;&lt; &quot;How will you spend your minutes?&quot; &lt;&lt; endl; cout &lt;&lt; &quot;1 - Scout | 20 Minutes &quot; &lt;&lt; endl &lt;&lt; &quot;2- Call | 30 Minutes&quot; &lt;&lt; endl &lt;&lt; &quot;3- Offer Visit | 10 Minutes&quot; &lt;&lt; endl &lt;&lt; &quot;4- Offer Scholarship | 10 Minutes&quot; &lt;&lt; endl &lt;&lt; &quot;5- View Prospect Board&quot; &lt;&lt; endl &lt;&lt; &quot;6 - Back&quot; &lt;&lt; endl; cout &lt;&lt; &quot;Minutes remaining - &quot; &lt;&lt; minutes &lt;&lt; endl; enum Choice{scout = 1, call, visit, scholarship, prospect, back}; cin &gt;&gt; number; cout &lt;&lt; &quot;Prospect List shown below &quot; &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; &quot;If Prospect Rating is 0, that means it is unknown. Prospect rating is out of ten...&quot; &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; &quot;1 - &quot; &lt;&lt; prospect1 &lt;&lt; &quot; | &quot; &lt;&lt; oner &lt;&lt; &quot; | &quot; &lt;&lt; one &lt;&lt; &quot; | He likes your school - &quot; &lt;&lt; onel &lt;&lt; &quot;%&quot; &lt;&lt; endl; cout &lt;&lt; &quot;2 - &quot; &lt;&lt; prospect2 &lt;&lt; &quot; | &quot; &lt;&lt; twor &lt;&lt; &quot; | &quot; &lt;&lt; two &lt;&lt; &quot; | He likes your school - &quot; &lt;&lt; two1 &lt;&lt; &quot;%&quot; &lt;&lt; endl; cout &lt;&lt; &quot;3 - &quot; &lt;&lt; prospect3 &lt;&lt; &quot; | &quot; &lt;&lt; threer &lt;&lt; &quot; | &quot; &lt;&lt; three &lt;&lt; &quot; | He likes your school - &quot; &lt;&lt; three1 &lt;&lt; &quot;%&quot; &lt;&lt; endl; cout &lt;&lt; &quot;4 - &quot; &lt;&lt; prospect4 &lt;&lt; &quot; | &quot; &lt;&lt; fourr &lt;&lt; &quot; | &quot; &lt;&lt; four &lt;&lt; &quot; | He likes your school - &quot; &lt;&lt; four1 &lt;&lt; &quot;%&quot; &lt;&lt; endl; cout &lt;&lt; &quot;5 - &quot; &lt;&lt; prospect5 &lt;&lt; &quot; | &quot; &lt;&lt; fiver &lt;&lt; &quot; | &quot; &lt;&lt; five &lt;&lt; &quot; | He likes your school - &quot; &lt;&lt; five1 &lt;&lt; &quot;%&quot; &lt;&lt; endl; cout &lt;&lt; &quot;6 - &quot; &lt;&lt; prospect6 &lt;&lt; &quot; | &quot; &lt;&lt; sixr &lt;&lt; &quot; | &quot; &lt;&lt; six &lt;&lt; &quot; | He likes your school - &quot; &lt;&lt; six1 &lt;&lt; &quot;%&quot; &lt;&lt; endl; cout &lt;&lt; &quot;7 - &quot; &lt;&lt; prospect7 &lt;&lt; &quot; | &quot; &lt;&lt; sevenr &lt;&lt; &quot; | &quot; &lt;&lt; seven &lt;&lt; &quot; | He likes your school - &quot; &lt;&lt; seven1 &lt;&lt; &quot;%&quot; &lt;&lt; endl; cout &lt;&lt; &quot;8 - &quot; &lt;&lt; prospect8 &lt;&lt; &quot; | &quot; &lt;&lt; eightr &lt;&lt; &quot; | &quot; &lt;&lt; eight &lt;&lt; &quot; | He likes your school - &quot; &lt;&lt; eight1 &lt;&lt; &quot;%&quot; &lt;&lt; endl; cout &lt;&lt; &quot;9 - &quot; &lt;&lt; prospect9 &lt;&lt; &quot; | &quot; &lt;&lt; niner &lt;&lt; &quot; | &quot; &lt;&lt; nine &lt;&lt; &quot; | He likes your school - &quot; &lt;&lt; nine1 &lt;&lt; &quot;%&quot; &lt;&lt; endl; cout &lt;&lt; &quot;10 - &quot; &lt;&lt; prospect10 &lt;&lt; &quot; | &quot; &lt;&lt; tenr &lt;&lt; &quot; | &quot; &lt;&lt; ten &lt;&lt; &quot; | He likes your school - &quot; &lt;&lt; ten1 &lt;&lt; &quot;%&quot; &lt;&lt; endl; if(number == 1){ if(minutes &gt; 19){ cout &lt;&lt; &quot;Scout players to see their attributes, the more you scout, the more you know. Once you have scouted a player three times you have everything you need to know about him.&quot; &lt;&lt; endl; cout &lt;&lt; &quot;Who would you like to scout today?&quot; &lt;&lt; endl; cin &gt;&gt; number; if(number == 1){ if(one == &quot; &quot;){ if(onec &gt; 5){ one = &quot;Raiting is higher than five.&quot;; cout &lt;&lt; &quot;Raiting is higher than five.&quot; &lt;&lt; endl; }else{ one = &quot;Raiting is five or lower.&quot;; cout &lt;&lt; &quot;Raiting is five or lower.&quot; &lt;&lt; endl; } }else if(onet == 0){ cout &lt;&lt; &quot;You almost know this player's exact raiting.&quot; &lt;&lt; endl; onet = 1; }else{ oner = onec; cout &lt;&lt; &quot;This player's raiting is &quot; &lt;&lt; oner &lt;&lt; endl; } }else if(number == 2){ if(two == &quot; &quot;){ if(twoc &gt; 5){ two = &quot;Raiting is higher than five.&quot;; cout &lt;&lt; &quot;Raiting is higher than five.&quot; &lt;&lt; endl; }else{ two = &quot;Raiting is five or lower.&quot;; cout &lt;&lt; &quot;Raiting is five or lower.&quot; &lt;&lt; endl; } }else if(twot == 0){ cout &lt;&lt; &quot;You almost know this player's exact raiting.&quot; &lt;&lt; endl; twot = 1; }else if(twot == 1){ twor = twoc; cout &lt;&lt; &quot;This player's raiting is &quot; &lt;&lt; twor &lt;&lt; endl; } }else if(number == 3){ if(three == &quot; &quot;){ if(threec &gt; 5){ three = &quot;Raiting is higher than five.&quot;; cout &lt;&lt; &quot;Raiting is higher than five.&quot; &lt;&lt; endl; }else{ three = &quot;Raiting is five or lower.&quot;; cout &lt;&lt; &quot;Raiting is five or lower.&quot; &lt;&lt; endl; } }else if(threet == 0){ cout &lt;&lt; &quot;You almost know this player's exact raiting.&quot; &lt;&lt; endl; threet = 1; }else if(threet == 1){ threer = threec; cout &lt;&lt; &quot;This player's raiting is &quot; &lt;&lt; threer &lt;&lt; endl; } }else if(number == 4){ if(four == &quot; &quot;){ if(fourc &gt; 5){ four = &quot;Raiting is higher than five.&quot;; cout &lt;&lt; &quot;Raiting is higher than five.&quot; &lt;&lt; endl; }else{ four = &quot;Raiting is five or lower.&quot;; cout &lt;&lt; &quot;Raiting is five or lower.&quot; &lt;&lt; endl; } }else if(fourt == 0){ cout &lt;&lt; &quot;You almost know this player's exact raiting.&quot; &lt;&lt; endl; fourt = 1; }else if(fourt == 1){ fourr = fourc; cout &lt;&lt; &quot;This player's raiting is &quot; &lt;&lt; fourr &lt;&lt; endl; } }else if(number == 5){ if(five == &quot; &quot;){ if(fivec &gt; 5){ five = &quot;Raiting is higher than five.&quot;; cout &lt;&lt; &quot;Raiting is higher than five.&quot; &lt;&lt; endl; }else{ five = &quot;Raiting is five or lower.&quot;; cout &lt;&lt; &quot;Raiting is five or lower.&quot; &lt;&lt; endl; } }else if(fivet == 0){ cout &lt;&lt; &quot;You almost know this player's exact raiting.&quot; &lt;&lt; endl; fivet = 1; }else if(fivet == 1){ fiver = fivec; cout &lt;&lt; &quot;This player's raiting is &quot; &lt;&lt; fiver &lt;&lt; endl; } }else if(number == 6){ if(six == &quot; &quot;){ if(sixc &gt; 5){ six = &quot;Raiting is higher than five.&quot;; cout &lt;&lt; &quot;Raiting is higher than five.&quot; &lt;&lt; endl; }else{ six = &quot;Raiting is five or lower.&quot;; cout &lt;&lt; &quot;Raiting is five or lower.&quot; &lt;&lt; endl; } }else if(sixt == 0){ cout &lt;&lt; &quot;You almost know this player's exact raiting.&quot; &lt;&lt; endl; sixt = 1; }else if(sixt == 1){ sixr = sixc; cout &lt;&lt; &quot;This player's raiting is &quot; &lt;&lt; sixr &lt;&lt; endl; } }else if(number == 7){ if(seven == &quot; &quot;){ if(sevenc &gt; 5){ seven = &quot;Raiting is higher than five.&quot;; cout &lt;&lt; &quot;Raiting is higher than five.&quot; &lt;&lt; endl; }else{ seven = &quot;Raiting is five or lower.&quot;; cout &lt;&lt; &quot;Raiting is five or lower.&quot; &lt;&lt; endl; } }else if(sevent == 0){ cout &lt;&lt; &quot;You almost know this player's exact raiting.&quot; &lt;&lt; endl; sevent = 1; }else if(sevent == 1){ sevenr = sevenc; cout &lt;&lt; &quot;This player's raiting is &quot; &lt;&lt; sevenr &lt;&lt; endl; } }else if(number == 8){ if(eight == &quot; &quot;){ if(eightc &gt; 5){ eight = &quot;Raiting is higher than five.&quot;; cout &lt;&lt; &quot;Raiting is higher than five.&quot; &lt;&lt; endl; }else{ eight = &quot;Raiting is five or lower.&quot;; cout &lt;&lt; &quot;Raiting is five or lower.&quot; &lt;&lt; endl; } }else if(eightt == 0){ cout &lt;&lt; &quot;You almost know this player's exact raiting.&quot; &lt;&lt; endl; eightt = 1; }else if(eightt == 1){ eightr = eightc; cout &lt;&lt; &quot;This player's raiting is &quot; &lt;&lt; eightr &lt;&lt; endl; } }else if(number == 9){ if(nine == &quot; &quot;){ if(ninec &gt; 5){ nine = &quot;Raiting is higher than five.&quot;; cout &lt;&lt; &quot;Raiting is higher than five.&quot; &lt;&lt; endl; }else{ nine = &quot;Raiting is five or lower.&quot;; cout &lt;&lt; &quot;Raiting is five or lower.&quot; &lt;&lt; endl; } }else if(ninet == 0){ cout &lt;&lt; &quot;You almost know this player's exact raiting.&quot; &lt;&lt; endl; ninet = 1; }else if(ninet == 1){ niner = ninec; cout &lt;&lt; &quot;This player's raiting is &quot; &lt;&lt; niner &lt;&lt; endl; } }else if(number == 10){ if(ten == &quot; &quot;){ if(tenc &gt; 5){ ten = &quot;Raiting is higher than five.&quot;; cout &lt;&lt; &quot;Raiting is higher than five.&quot; &lt;&lt; endl; }else{ ten = &quot;Raiting is five or lower.&quot;; cout &lt;&lt; &quot;Raiting is five or lower.&quot; &lt;&lt; endl; } }else if(tent == 0){ cout &lt;&lt; &quot;You almost know this player's exact raiting.&quot; &lt;&lt; endl; tent = 1; }else if(tent == 1){ tenr = tenc; cout &lt;&lt; &quot;This player's raiting is &quot; &lt;&lt; tenr &lt;&lt; endl; } } minutes = minutes - 20; }else{ cout &lt;&lt; &quot;You don't have enough minutes to do that action!&quot; &lt;&lt; endl; } }else if(number == call){ if(minutes &gt; 29){ cout &lt;&lt; &quot;Who would you like to call today?&quot; &lt;&lt; endl; cin &gt;&gt; number; if(number == 1){ random = 0; random = rand() % 15 + 1; if(random &gt; 7){ cout &lt;&lt; &quot;The call went great! This player likes you &quot; &lt;&lt; random &lt;&lt; &quot;% more!&quot; &lt;&lt; endl; }else{ cout &lt;&lt; &quot;The player did not seem intrested in talking to you. The player only likes you &quot; &lt;&lt; random &lt;&lt; &quot;% more...&quot; &lt;&lt; endl; } onel = onel + random; }else if(number == 2){ random = 0; random = rand() % 15 + 1; if(random &gt; 7){ cout &lt;&lt; &quot;The call went great! This player likes you &quot; &lt;&lt; random &lt;&lt; &quot;% more!&quot; &lt;&lt; endl; }else{ cout &lt;&lt; &quot;The player did not seem intrested in talking to you. The player only likes you &quot; &lt;&lt; random &lt;&lt; &quot;% more...&quot; &lt;&lt; endl; } two1 = two1 + random; }else if(number == 3){ random = 0; random = rand() % 15 + 1; if(random &gt; 7){ cout &lt;&lt; &quot;The call went great! This player likes you &quot; &lt;&lt; random &lt;&lt; &quot;% more!&quot; &lt;&lt; endl; }else{ cout &lt;&lt; &quot;The player did not seem intrested in talking to you. The player only likes you &quot; &lt;&lt; random &lt;&lt; &quot;% more...&quot; &lt;&lt; endl; } three1 = three1 + random; }else if(number == 4){ random = 0; random = rand() % 15 + 1; if(random &gt; 7){ cout &lt;&lt; &quot;The call went great! This player likes you &quot; &lt;&lt; random &lt;&lt; &quot;% more!&quot; &lt;&lt; endl; }else{ cout &lt;&lt; &quot;The player did not seem intrested in talking to you. The player only likes you &quot; &lt;&lt; random &lt;&lt; &quot;% more...&quot; &lt;&lt; endl; } four1 = four1 + random; }else if(number == 5){ random = 0; random = rand() % 15 + 1; if(random &gt; 7){ cout &lt;&lt; &quot;The call went great! This player likes you &quot; &lt;&lt; random &lt;&lt; &quot;% more!&quot; &lt;&lt; endl; }else{ cout &lt;&lt; &quot;The player did not seem intrested in talking to you. The player only likes you &quot; &lt;&lt; random &lt;&lt; &quot;% more...&quot; &lt;&lt; endl; } five1 = five1 + random; }else if(number == 6){ random = 0; random = rand() % 15 + 1; if(random &gt; 7){ cout &lt;&lt; &quot;The call went great! This player likes you &quot; &lt;&lt; random &lt;&lt; &quot;% more!&quot; &lt;&lt; endl; }else{ cout &lt;&lt; &quot;The player did not seem intrested in talking to you. The player only likes you &quot; &lt;&lt; random &lt;&lt; &quot;% more...&quot; &lt;&lt; endl; } six1 = six1 + random; }else if(number == 7){ random = 0; random = rand() % 15 + 1; if(random &gt; 7){ cout &lt;&lt; &quot;The call went great! This player likes you &quot; &lt;&lt; random &lt;&lt; &quot;% more!&quot; &lt;&lt; endl; }else{ cout &lt;&lt; &quot;The player did not seem intrested in talking to you. The player only likes you &quot; &lt;&lt; random &lt;&lt; &quot;% more...&quot; &lt;&lt; endl; } seven1 = seven1 + random; }else if(number == 8){ random = 0; random = rand() % 15 + 1; if(random &gt; 7){ cout &lt;&lt; &quot;The call went great! This player likes you &quot; &lt;&lt; random &lt;&lt; &quot;% more!&quot; &lt;&lt; endl; }else{ cout &lt;&lt; &quot;The player did not seem intrested in talking to you. The player only likes you &quot; &lt;&lt; random &lt;&lt; &quot;% more...&quot; &lt;&lt; endl; } eight1 = eight1 + random; }else if(number == 9){ random = 0; random = rand() % 15 + 1; if(random &gt; 7){ cout &lt;&lt; &quot;The call went great! This player likes you &quot; &lt;&lt; random &lt;&lt; &quot;% more!&quot; &lt;&lt; endl; }else{ cout &lt;&lt; &quot;The player did not seem intrested in talking to you. The player only likes you &quot; &lt;&lt; random &lt;&lt; &quot;% more...&quot; &lt;&lt; endl; } nine1 = nine1 + random; }else if(number == 10){ random = 0; random = rand() % 15 + 1; if(random &gt; 7){ cout &lt;&lt; &quot;The call went great! This player likes you &quot; &lt;&lt; random &lt;&lt; &quot;% more!&quot; &lt;&lt; endl; }else{ cout &lt;&lt; &quot;The player did not seem intrested in talking to you. The player only likes you &quot; &lt;&lt; random &lt;&lt; &quot;% more...&quot; &lt;&lt; endl; } ten1 = ten1 + random; } minutes = minutes - 30; }else{ cout &lt;&lt; &quot;You don't have enough minutes to complete this action!&quot; &lt;&lt; endl; } }else if(number == visit){ if(minutes &gt; 9){ minutes = minutes - 10; cout &lt;&lt; &quot;Who would you liked to offer a visit coach?&quot; &lt;&lt; endl; cin &gt;&gt; number; if(number == 1){ random = 0; random = rand() % 50 + 1; if(onel &gt; random){ cout &lt;&lt; &quot;I'd be delighted to visit!&quot;; onev = 1; }else if(onel &lt;= random){ cout &lt;&lt; &quot;I haven't really considered your program, coach.&quot; &lt;&lt; endl; } }else if(number == 2){ random = 0; random = rand() % 50 + 1; if(two1 &gt; random){ cout &lt;&lt; &quot;I'd be delighted to visit!&quot;; twov = 1; }else if(two1 &lt;= random){ cout &lt;&lt; &quot;I haven't really considered your program, coach.&quot; &lt;&lt; endl; } }else if(number == 3){ random = 0; random = rand() % 50 + 1; if(three1 &gt; random){ cout &lt;&lt; &quot;I'd be delighted to visit!&quot;; threev = 1; }else if(three1 &lt;= random){ cout &lt;&lt; &quot;I haven't really considered your program, coach.&quot; &lt;&lt; endl; } }else if(number == 4){ random = 0; random = rand() % 50 + 1; if(four1 &gt; random){ cout &lt;&lt; &quot;I'd be delighted to visit!&quot;; fourv = 1; }else if(four1 &lt;= random){ cout &lt;&lt; &quot;I haven't really considered your program, coach.&quot; &lt;&lt; endl; } }else if(number == 5){ random = 0; random = rand() % 50 + 1; if(five1 &gt; random){ cout &lt;&lt; &quot;I'd be delighted to visit!&quot;; fivev = 1; }else if(five1 &lt;= random){ cout &lt;&lt; &quot;I haven't really considered your program, coach.&quot; &lt;&lt; endl; } }else if(number == 6){ random = 0; random = rand() % 50 + 1; if(six1 &gt; random){ cout &lt;&lt; &quot;I'd be delighted to visit!&quot;; sixv = 1; }else if(six1 &lt;= random){ cout &lt;&lt; &quot;I haven't really considered your program, coach.&quot; &lt;&lt; endl; } }else if(number == 7){ random = 0; random = rand() % 50 + 1; if(seven1 &gt; random){ cout &lt;&lt; &quot;I'd be delighted to visit!&quot;; sevenv = 1; }else if(seven1 &lt;= random){ cout &lt;&lt; &quot;I haven't really considered your program, coach.&quot; &lt;&lt; endl; } }else if(number == 8){ random = 0; random = rand() % 50 + 1; if(eight1 &gt; random){ cout &lt;&lt; &quot;I'd be delighted to visit!&quot;; eightv = 1; }else if(eight1 &lt;= random){ cout &lt;&lt; &quot;I haven't really considered your program, coach.&quot; &lt;&lt; endl; } }else if(number == 9){ random = 0; random = rand() % 50 + 1; if(nine1 &gt; random){ cout &lt;&lt; &quot;I'd be delighted to visit!&quot;; ninev = 1; }else if(nine1 &lt;= random){ cout &lt;&lt; &quot;I haven't really considered your program, coach.&quot; &lt;&lt; endl; } }else if(number == 10){ random = 0; random = rand() % 50 + 1; if(ten1 &gt; random){ cout &lt;&lt; &quot;I'd be delighted to visit!&quot;; tenv = 1; }else if(ten1 &lt;= random){ cout &lt;&lt; &quot;I haven't really considered your program, coach.&quot; &lt;&lt; endl; } } }else{ cout &lt;&lt; &quot;You don't have enough minutes to complete this action...&quot; &lt;&lt; endl; } }else if(number == scholarship){ if(minutes &gt; 9){ minutes = minutes - 10; cout &lt;&lt; &quot;Who will you offer a scholarship coach?&quot; &lt;&lt; endl; cin &gt;&gt; number; if(number == 1){ if(ones == 0){ ones = 1; rands = 0; rands = rand() % 150 + 1; if(onel &gt; rands){ cout &lt;&lt; &quot;I'd be glad to join your program!&quot; &lt;&lt; endl; addrat = addrat + twoc; }else{ cout &lt;&lt; &quot;Sorry coach, but I don't think your school would fit my playstyle&quot; &lt;&lt; endl; } }else{ cout &lt;&lt; &quot;You've already offered him a scholarship!&quot; &lt;&lt; endl; } }else if(number == 2){ if(twos == 0){ twos = 1; rands = 0; rands = rand() % 150 + 1; if(two1 &gt; rands){ cout &lt;&lt; &quot;I'd be glad to join your program!&quot; &lt;&lt; endl; addrat = addrat + onec; }else{ cout &lt;&lt; &quot;Sorry coach, but I don't think your school would fit my playstyle&quot; &lt;&lt; endl; } }else{ cout &lt;&lt; &quot;You've already offered him a scholarship!&quot; &lt;&lt; endl; } }else if(number == 3){ if(threes == 0){ threes = 1; rands = 0; rands = rand() % 150 + 1; if(three1 &gt; rands){ cout &lt;&lt; &quot;I'd be glad to join your program!&quot; &lt;&lt; endl; addrat = addrat + threec; }else{ cout &lt;&lt; &quot;Sorry coach, but I don't think your school would fit my playstyle&quot; &lt;&lt; endl; } }else{ cout &lt;&lt; &quot;You've already offered him a scholarship!&quot; &lt;&lt; endl; } }else if(number == 4){ if(fours == 0){ fours = 1; rands = 0; rands = rand() % 150 + 1; if(four1 &gt; rands){ cout &lt;&lt; &quot;I'd be glad to join your program!&quot; &lt;&lt; endl; addrat = addrat + fourc; }else{ cout &lt;&lt; &quot;Sorry coach, but I don't think your school would fit my playstyle&quot; &lt;&lt; endl; } }else{ cout &lt;&lt; &quot;You've already offered him a scholarship!&quot; &lt;&lt; endl; } }else if(number == 5){ if(fives == 0){ fives = 1; rands = 0; rands = rand() % 150 + 1; if(five1 &gt; rands){ cout &lt;&lt; &quot;I'd be glad to join your program!&quot; &lt;&lt; endl; addrat = addrat + fivec; }else{ cout &lt;&lt; &quot;Sorry coach, but I don't think your school would fit my playstyle&quot; &lt;&lt; endl; } }else{ cout &lt;&lt; &quot;You've already offered him a scholarship!&quot; &lt;&lt; endl; } }else if(number == 6){ if(sixs == 0){ sixs = 1; rands = 0; rands = rand() % 150 + 1; if(six1 &gt; rands){ cout &lt;&lt; &quot;I'd be glad to join your program!&quot; &lt;&lt; endl; addrat = addrat + sixc; }else{ cout &lt;&lt; &quot;Sorry coach, but I don't think your school would fit my playstyle&quot; &lt;&lt; endl; } }else{ cout &lt;&lt; &quot;You've already offered him a scholarship!&quot; &lt;&lt; endl; } }else if(number == 7){ if(sevens == 0){ sevens = 1; rands = 0; rands = rand() % 150 + 1; if(seven1 &gt; rands){ cout &lt;&lt; &quot;I'd be glad to join your program!&quot; &lt;&lt; endl; addrat = addrat + sevenc; }else{ cout &lt;&lt; &quot;Sorry coach, but I don't think your school would fit my playstyle&quot; &lt;&lt; endl; } }else{ cout &lt;&lt; &quot;You've already offered him a scholarship!&quot; &lt;&lt; endl; } }else if(number == 8){ if(eights == 0){ eights = 1; rands = 0; rands = rand() % 150 + 1; if(eight1 &gt; rands){ cout &lt;&lt; &quot;I'd be glad to join your program!&quot; &lt;&lt; endl; addrat = addrat + eightc; }else{ cout &lt;&lt; &quot;Sorry coach, but I don't think your school would fit my playstyle&quot; &lt;&lt; endl; } }else{ cout &lt;&lt; &quot;You've already offered him a scholarship!&quot; &lt;&lt; endl; } }else if(number == 9){ if(nines == 0){ nines = 1; rands = 0; rands = rand() % 150 + 1; if(nine1 &gt; rands){ cout &lt;&lt; &quot;I'd be glad to join your program!&quot; &lt;&lt; endl; addrat = addrat + ninec; }else{ cout &lt;&lt; &quot;Sorry coach, but I don't think your school would fit my playstyle&quot; &lt;&lt; endl; } }else{ cout &lt;&lt; &quot;You've already offered him a scholarship!&quot; &lt;&lt; endl; } }else if(number == 10){ if(tens == 0){ tens = 1; rands = 0; rands = rand() % 150 + 1; if(ten1 &gt; rands){ cout &lt;&lt; &quot;I'd be glad to join your program!&quot; &lt;&lt; endl; addrat = addrat + tenc; }else{ cout &lt;&lt; &quot;Sorry coach, but I don't think your school would fit my playstyle&quot; &lt;&lt; endl; } }else{ cout &lt;&lt; &quot;You've already offered him a scholarship!&quot; &lt;&lt; endl; } } }else{ cout &lt;&lt; &quot;You don't have enough minutes to do this action!&quot; &lt;&lt; endl; } }else if(number == prospect){ cout &lt;&lt; &quot;Here are the prospects!&quot; &lt;&lt; endl; }else if(number == back){ goto home; } cin &gt;&gt; number; goto home; week1: if(week &lt; 9){ if(Georgia.name != Tennessee.next){ random5 = rand() % 100 + 1; if(Georgia.overall &gt; random5){ Georgia.win = Georgia.win + 1; Georgia.overall = Georgia.overall + 1; }else { Georgia.loss = Georgia.loss + 1; Georgia.overall = Georgia.overall - 1; } } random5 = 0; if(Alabama.name != Tennessee.next){ random5 = rand() % 100 + 1; if(Alabama.overall &gt; random5){ Alabama.win = Alabama.win + 1; Alabama.overall = Alabama.overall + 1; }else { Alabama.loss = Alabama.loss + 1; Alabama.overall = Alabama.overall - 1; } } random5 = 0; if(Clemson.name != Tennessee.next){ random5 = rand() % 100 + 1; if(Clemson.overall &gt; random5){ Clemson.win = Clemson.win + 1; Clemson.overall = Clemson.overall + 1; }else { Clemson.loss = Clemson.loss + 1; Clemson.overall = Clemson.overall - 1; } } random5 = 0; if(MiamiFL.name != Tennessee.next){ random5 = rand() % 100 + 1; if(MiamiFL.overall &gt; random5){ MiamiFL.win = MiamiFL.win + 1; MiamiFL.overall = MiamiFL.overall + 1; }else { MiamiFL.loss = MiamiFL.loss + 1; MiamiFL.overall = MiamiFL.overall - 1; } } random5 = 0; if(Auburn.name != Tennessee.next){ random5 = rand() % 100 + 1; if(Auburn.overall &gt; random5){ Auburn.win = Auburn.win + 1; Auburn.overall = Auburn.overall + 1; }else { Auburn.loss = Auburn.loss + 1; Auburn.overall = Auburn.overall - 1; } } random5 = 0; if(OhioState.name != Tennessee.next){ random5 = rand() % 100 + 1; if(OhioState.overall &gt; random5){ OhioState.win = OhioState.win + 1; OhioState.overall = OhioState.overall + 1; }else { OhioState.loss = OhioState.loss + 1; OhioState.overall = OhioState.overall - 1; } } random5 = 0; if(OklahomaSt.name != Tennessee.next){ random5 = rand() % 100 + 1; if(OklahomaSt.overall &gt; random5){ OklahomaSt.win = OklahomaSt.win + 1; OklahomaSt.overall = OklahomaSt.overall + 1; }else { OklahomaSt.loss = OklahomaSt.loss + 1; OklahomaSt.overall = OklahomaSt.overall - 1; } } random5 = 0; if(Tennessee.next == &quot;Championship&quot;){ goto Championship; } if(NotreDame.name != Tennessee.next){ random5 = rand() % 100 + 1; if(NotreDame.overall &gt; random5){ NotreDame.win = NotreDame.win + 1; NotreDame.overall = NotreDame.overall + 1; }else { NotreDame.loss = NotreDame.loss + 1; NotreDame.overall = NotreDame.overall - 1; } } random5 = 0; if(UNC.name != Tennessee.next){ random5 = rand() % 100 + 1; if(UNC.overall &gt; random5){ UNC.win = UNC.win + 1; UNC.overall = UNC.overall + 1; }else { UNC.loss = UNC.loss + 1; UNC.overall = UNC.overall - 1; } } random5 = 0; if(PennSt.name != Tennessee.next){ random5 = rand() % 100 + 1; if(PennSt.overall &gt; random5){ PennSt.win = PennSt.win + 1; PennSt.overall = PennSt.overall + 1; }else { PennSt.loss = PennSt.loss + 1; PennSt.overall = PennSt.overall - 1; } } random5 = 0; if(Florida.name != Tennessee.next){ random5 = rand() % 100 + 1; if(Florida.overall &gt; random5){ Florida.win = Florida.win + 1; Florida.overall = Florida.overall + 1; }else { Florida.loss = Florida.loss + 1; Florida.overall = Florida.overall - 1; } } random5 = 0; } cout &lt;&lt; string( 100, '\n' );; score = opponentoverall * 0.35; random = rand() % 15 + -5; random2 = rand() % 15 + -5; random = random - random2; score = score + random; score2 = Tennessee.overall * 0.35; random3 = rand() % 15 + -5; random4 = rand() % 15 + -5; random3 = random4 - random3; score2 = score2 + random3; if(score &lt; 2){ score = 0; } if(score2 &lt; 2){ score2 = 0; } cout &lt;&lt; Tennessee.name &lt;&lt; &quot; scored &quot; &lt;&lt; score2 &lt;&lt; &quot; | &quot; &lt;&lt; Tennessee.next &lt;&lt; &quot; scored &quot; &lt;&lt; score &lt;&lt; endl; if(score2 &gt; score){ cout &lt;&lt; &quot;You won! Your overall has increased three points!&quot; &lt;&lt; endl; Tennessee.win = Tennessee.win + 1; Tennessee.overall = Tennessee.overall + 3; randoml = 0; if(onev == 1){ randoml = 0; randoml = rand() % 20 + 1; onel = onel + randoml; cout &lt;&lt; &quot;You had a recruit visiting and you won! The recruit's liking of your school has increased by &quot; &lt;&lt; randoml &lt;&lt; endl; onev = 0; } if(twov == 1){ randoml = 0; randoml = rand() % 20 + 1; two1 = two1 + randoml; cout &lt;&lt; &quot;You had a recruit visiting and you won! The recruit's liking of your school has increased by &quot; &lt;&lt; randoml &lt;&lt; endl; twov = 0; } if(threev == 1){ randoml = 0; randoml = rand() % 20 + 1; three1 = three1 + randoml; cout &lt;&lt; &quot;You had a recruit visiting and you won! The recruit's liking of your school has increased by &quot; &lt;&lt; randoml &lt;&lt; endl; threev = 0; } if(fourv == 1){ randoml = 0; randoml = rand() % 20 + 1; four1 = four1 + randoml; cout &lt;&lt; &quot;You had a recruit visiting and you won! The recruit's liking of your school has increased by &quot; &lt;&lt; randoml &lt;&lt; endl; fourv = 0; } if(fivev == 1){ randoml = 0; randoml = rand() % 20 + 1; five1 = five1 + randoml; cout &lt;&lt; &quot;You had a recruit visiting and you won! The recruit's liking of your school has increased by &quot; &lt;&lt; randoml &lt;&lt; endl; fivev = 0; } if(sixv == 1){ randoml = 0; randoml = rand() % 20 + 1; six1 = six1 + randoml; cout &lt;&lt; &quot;You had a recruit visiting and you won! The recruit's liking of your school has increased by &quot; &lt;&lt; randoml &lt;&lt; endl; sixv = 0; } if(sevenv == 1){ randoml = 0; randoml = rand() % 20 + 1; seven1 = seven1 + randoml; cout &lt;&lt; &quot;You had a recruit visiting and you won! The recruit's liking of your school has increased by &quot; &lt;&lt; randoml &lt;&lt; endl; sevenv = 0; } if(eightv == 1){ randoml = 0; randoml = rand() % 20 + 1; eight1 = eight1 + randoml; cout &lt;&lt; &quot;You had a recruit visiting and you won! The recruit's liking of your school has increased by &quot; &lt;&lt; randoml &lt;&lt; endl; eightv = 0; } if(ninev == 1){ randoml = 0; randoml = rand() % 20 + 1; nine1 = nine1 + randoml; cout &lt;&lt; &quot;You had a recruit visiting and you won! The recruit's liking of your school has increased by &quot; &lt;&lt; randoml &lt;&lt; endl; ninev = 0; } if(tenv == 1){ randoml = 0; randoml = rand() % 20 + 1; ten1 = ten1 + randoml; cout &lt;&lt; &quot;You had a recruit visiting and you won! The recruit's liking of your school has increased by &quot; &lt;&lt; randoml &lt;&lt; endl; tenv = 0; } if(Tennessee.next == &quot;Georgia&quot;){ Georgia.loss = Georgia.loss + 1; Georgia.overall = Georgia.overall - 1; }else if(Tennessee.next == &quot;Alabama&quot;){ Alabama.loss = Alabama.loss + 1; Alabama.overall = Alabama.overall - 1; }else if(Tennessee.next == &quot;Oklahoma State&quot;){ OklahomaSt.loss = OklahomaSt.loss + 1; OklahomaSt.overall = OklahomaSt.overall - 1; }else if(Tennessee.next == &quot;Penn State&quot;){ PennSt.loss = PennSt.loss + 1; PennSt.overall = PennSt.overall - 1; }else if(Tennessee.next == &quot;Auburn&quot;){ Auburn.loss = Auburn.loss + 1; Auburn.overall = Auburn.overall - 1; }else if(Tennessee.next == &quot;UNC&quot;){ UNC.loss = UNC.loss + 1; UNC.overall = UNC.overall - 1; }else if(Tennessee.next == &quot;Miami FL&quot;){ MiamiFL.loss = MiamiFL.loss + 1; MiamiFL.overall = MiamiFL.overall - 1; }else if(Tennessee.next == &quot;Ohio State&quot;){ OhioState.loss = OhioState.loss + 1; OhioState.overall = OhioState.overall - 1; } }else if(score &gt; score2){ cout &lt;&lt; &quot;You lost... Your overall has decreased three points...&quot; &lt;&lt; endl; Tennessee.loss = Tennessee.loss + 1; Tennessee.overall = Tennessee.overall - 3; if(onev == 1){ randoml = rand() % 15 + 1; onel = onel - randoml; cout &lt;&lt; &quot;You had a recruit visiting and you lost... The recruit's liking of your school has decreased by &quot; &lt;&lt; randoml &lt;&lt; endl; } if(twov == 1){ randoml = 0; randoml = rand() % 15 + 1; two1 = two1 - randoml; cout &lt;&lt; &quot;You had a recruit visiting and you lost... The recruit's liking of your school has decreased by &quot; &lt;&lt; randoml &lt;&lt; endl; twov = 0; } if(threev == 1){ randoml = 0; randoml = rand() % 15 + 1; three1 = three1 - randoml; cout &lt;&lt; &quot;You had a recruit visiting and you lost... The recruit's liking of your school has decreased by &quot; &lt;&lt; randoml &lt;&lt; endl; threev = 0; } if(fourv == 1){ randoml = 0; randoml = rand() % 15 + 1; four1 = four1 - randoml; cout &lt;&lt; &quot;You had a recruit visiting and you lost... The recruit's liking of your school has decreased by &quot; &lt;&lt; randoml &lt;&lt; endl; fourv = 0; } if(fivev == 1){ randoml = 0; randoml = rand() % 15 + 1; five1 = five1 - randoml; cout &lt;&lt; &quot;You had a recruit visiting and you lost... The recruit's liking of your school has decreased by &quot; &lt;&lt; randoml &lt;&lt; endl; fivev = 0; } if(sixv == 1){ randoml = 0; randoml = rand() % 15 + 1; six1 = six1 - randoml; cout &lt;&lt; &quot;You had a recruit visiting and you lost... The recruit's liking of your school has decreased by &quot; &lt;&lt; randoml &lt;&lt; endl; sixv = 0; } if(sevenv == 1){ randoml = 0; randoml = rand() % 15 + 1; seven1 = seven1 - randoml; cout &lt;&lt; &quot;You had a recruit visiting and you lost... The recruit's liking of your school has decreased by &quot; &lt;&lt; randoml &lt;&lt; endl; sevenv = 0; } if(eightv == 1){ randoml = 0; randoml = rand() % 15 + 1; eight1 = eight1 - randoml; cout &lt;&lt; &quot;You had a recruit visiting and you lost... The recruit's liking of your school has decreased by &quot; &lt;&lt; randoml &lt;&lt; endl; eightv = 0; } if(ninev == 1){ randoml = 0; randoml = rand() % 15 + 1; nine1 = nine1 - randoml; cout &lt;&lt; &quot;You had a recruit visiting and you lost... The recruit's liking of your school has decreased by &quot; &lt;&lt; randoml &lt;&lt; endl; ninev = 0; } if(tenv == 1){ randoml = 0; randoml = rand() % 15 + 1; ten1 = ten1 - randoml; cout &lt;&lt; &quot;You had a recruit visiting and you lost... The recruit's liking of your school has decreased by &quot; &lt;&lt; randoml &lt;&lt; endl; tenv = 0; } if(Tennessee.next == &quot;Georgia&quot;){ Georgia.win = Georgia.win + 1; Georgia.overall = Georgia.overall + 1; }else if(Tennessee.next == &quot;Alabama&quot;){ Alabama.win = Alabama.win + 1; Alabama.overall = Alabama.overall + 1; }else if(Tennessee.next == &quot;Oklahoma State&quot;){ OklahomaSt.win = OklahomaSt.win + 1; OklahomaSt.overall = OklahomaSt.overall + 1; }else if(Tennessee.next == &quot;Penn State&quot;){ PennSt.win = PennSt.win + 1; PennSt.overall = PennSt.overall + 1; }else if(Tennessee.next == &quot;Auburn&quot;){ Auburn.win = Auburn.win + 1; Auburn.overall = Auburn.overall + 1; }else if(Tennessee.next == &quot;UNC&quot;){ UNC.win = UNC.win + 1; UNC.overall = UNC.overall + 1; }else if(Tennessee.next == &quot;Miami FL&quot;){ MiamiFL.win = MiamiFL.win + 1; MiamiFL.overall = MiamiFL.overall + 1; }else if(Tennessee.next == &quot;Ohio State&quot;){ OhioState.win = OhioState.win + 1; OhioState.overall = OhioState.overall + 1; }else if(Tennessee.next == &quot;Championship&quot;){ goto Championship; minutes = 60; } }else{ goto week1; } if(week == 1){ week = 2; minutes = 120; Tennessee.next = Tennessee.week2; }else if(week == 2){ week = 3; minutes = 120; Tennessee.next = Tennessee.week3; }else if(week == 3){ week = 4; minutes = 120; Tennessee.next = Tennessee.week4; }else if(week == 4){ week = 5; minutes = 120; Tennessee.next = Tennessee.week5; }else if(week == 5){ week = 6; minutes = 120; Tennessee.next = Tennessee.week6; }else if(week == 6){ week = 7; minutes = 120; Tennessee.next = Tennessee.week7; }else if(week == 7){ week = 8; minutes = 120; Tennessee.next = Tennessee.week8; }else if(week == 8){ week = 9; minutes = 0; Tennessee.next = &quot;Championship&quot;; } cout &lt;&lt; endl &lt;&lt; &quot;Type 1 and press Enter to continue...&quot; &lt;&lt; endl; cin &gt;&gt; number; goto home; Championship: cout &lt;&lt; string( 100, '\n' ); cout &lt;&lt; OhioState.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; OhioState.overall &lt;&lt; &quot; ( &quot; &lt;&lt; OhioState.win &lt;&lt; &quot; - &quot; &lt;&lt; OhioState.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; Alabama.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; Alabama.overall &lt;&lt; &quot; ( &quot; &lt;&lt; Alabama.win &lt;&lt; &quot; - &quot; &lt;&lt; Alabama.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; MiamiFL.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; MiamiFL.overall &lt;&lt; &quot; ( &quot; &lt;&lt; MiamiFL.win &lt;&lt; &quot; - &quot; &lt;&lt; MiamiFL.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; OklahomaSt.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; OklahomaSt.overall &lt;&lt; &quot; ( &quot; &lt;&lt; OklahomaSt.win &lt;&lt; &quot; - &quot; &lt;&lt; OklahomaSt.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; Auburn.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; Auburn.overall &lt;&lt; &quot; ( &quot; &lt;&lt; Auburn.win &lt;&lt; &quot; - &quot; &lt;&lt; Auburn.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; Tennessee.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; Tennessee.overall &lt;&lt; &quot; ( &quot; &lt;&lt; Tennessee.win &lt;&lt; &quot; - &quot; &lt;&lt; Tennessee.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; PennSt.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; PennSt.overall &lt;&lt; &quot; ( &quot; &lt;&lt; PennSt.win &lt;&lt; &quot; - &quot; &lt;&lt; PennSt.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; Florida.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; Florida.overall &lt;&lt; &quot; ( &quot; &lt;&lt; Florida.win &lt;&lt; &quot; - &quot; &lt;&lt; Florida.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; Georgia.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; Georgia.overall &lt;&lt; &quot; ( &quot; &lt;&lt; Georgia.win &lt;&lt; &quot; - &quot; &lt;&lt; Georgia.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; UNC.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; UNC.overall &lt;&lt; &quot; ( &quot; &lt;&lt; UNC.win &lt;&lt; &quot; - &quot; &lt;&lt; UNC.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; NotreDame.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; NotreDame.overall &lt;&lt; &quot; ( &quot; &lt;&lt; NotreDame.win &lt;&lt; &quot; - &quot; &lt;&lt; NotreDame.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; Clemson.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; Clemson.overall &lt;&lt; &quot; ( &quot; &lt;&lt; Clemson.win &lt;&lt; &quot; - &quot; &lt;&lt; Clemson.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; &quot;Welcome to the Championship! Answer this : Did your team do the best this year? Tie goes to highest overall!&quot; &lt;&lt; endl; cout &lt;&lt; &quot;1 - Yes&quot; &lt;&lt; endl &lt;&lt; &quot;2- No&quot; &lt;&lt; endl; cin &gt;&gt; number; if(number == 1) { champ1 = Tennessee.overall; champname = &quot;Tennessee&quot;; }else{ cout &lt;&lt; &quot;Ok the, who did the best?&quot; &lt;&lt; endl; cout &lt;&lt; &quot;1 - Clemson&quot; &lt;&lt; endl &lt;&lt; &quot;2 - Alabama &quot; &lt;&lt; endl &lt;&lt; &quot;3 - Florida&quot; &lt;&lt; endl &lt;&lt; &quot;4 - Georgia&quot; &lt;&lt; endl &lt;&lt; &quot;5 - MiamiFL&quot; &lt;&lt; endl &lt;&lt; &quot;6 - Oklahoma State&quot; &lt;&lt; endl; cout &lt;&lt; &quot;7 - Auburn&quot; &lt;&lt; endl &lt;&lt; &quot;8 - UNC&quot; &lt;&lt; endl &lt;&lt; &quot;9 - Notre Dame&quot; &lt;&lt; endl &lt;&lt; &quot;10 - Penn State&quot; &lt;&lt; endl &lt;&lt; &quot;11 - Ohio State?&quot; &lt;&lt; endl; cin &gt;&gt; number; if(number == 1){ champ1 = Clemson.overall; champname = &quot;Clemson&quot;; Clemson.overall = Clemson.overall + 6; }else if(number == 2){ champ1 = Alabama.overall; champname = &quot;Alabama&quot;; Alabama.overall = Alabama.overall + 6; }else if(number == 3){ champ1 = Florida.overall; champname = &quot;Florida&quot;; Florida.overall = Florida.overall + 6; }else if(number == 4){ champ1 = Georgia.overall; champname = &quot;Georgia&quot;; Georgia.overall = Georgia.overall + 6; }else if(number == 5){ champ1 = MiamiFL.overall; champname = &quot;Miami FL&quot;; MiamiFL.overall = MiamiFL.overall + 6; }else if(number == 6){ champ1 = OklahomaSt.overall; champname = &quot;OklahomaST&quot;; OklahomaSt.overall = OklahomaSt.overall + 6; }else if(number == 7){ champ1 = Auburn.overall; champname = &quot;Auburn&quot;; Auburn.overall = Auburn.overall + 6; }else if(number == 8){ champ1 = UNC.overall; champname = &quot;UNC&quot;; UNC.overall = UNC.overall + 6; }else if(number == 9){ champ1 = NotreDame.overall; champname = &quot;Notre Dame&quot;; NotreDame.overall = NotreDame.overall + 6; }else if(number == 10){ champ1 = PennSt.overall; champname = &quot;Penn State&quot;; PennSt.overall = PennSt.overall + 6; }else if(number == 11){ champ1 = OhioState.overall; champname = &quot;Ohio State&quot;; OhioState.overall = OhioState.overall + 6; } } cout &lt;&lt; &quot;Did your team do the second best this year?&quot; &lt;&lt; endl; cout &lt;&lt; &quot;1 - Yes&quot; &lt;&lt; endl &lt;&lt; &quot;2- No&quot; &lt;&lt; endl; cin &gt;&gt; number; if(number == 1){ champ2 = Tennessee.overall; champname = &quot;Tennessee&quot;; }else{ cout &lt;&lt; &quot;Which of these teams did the second best?&quot; &lt;&lt; endl; cout &lt;&lt; &quot;1 - Clemson&quot; &lt;&lt; endl &lt;&lt; &quot;2 - Alabama &quot; &lt;&lt; endl &lt;&lt; &quot;3 - Florida&quot; &lt;&lt; endl &lt;&lt; &quot;4 - Georgia&quot; &lt;&lt; endl &lt;&lt; &quot;5 - MiamiFL&quot; &lt;&lt; endl &lt;&lt; &quot;6 - Oklahoma State&quot; &lt;&lt; endl; cout &lt;&lt; &quot;7 - Auburn&quot; &lt;&lt; endl &lt;&lt; &quot;8 - UNC&quot; &lt;&lt; endl &lt;&lt; &quot;9 - Notre Dame&quot; &lt;&lt; endl &lt;&lt; &quot;10 - Penn State&quot; &lt;&lt; endl &lt;&lt; &quot;11 - Ohio State?&quot; &lt;&lt; endl; cin &gt;&gt; number; if(number == 1){ champ2 = Clemson.overall; champname2 = &quot;Clemson&quot;; Clemson.overall = Clemson.overall + 3; }else if(number == 2){ champ2 = Alabama.overall; champname2 = &quot;Alabama&quot;; Alabama.overall = Alabama.overall + 3; }else if(number == 3){ champ2 = Florida.overall; champname2 = &quot;Florida&quot;; Florida.overall = Florida.overall + 3; }else if(number == 4){ champ2 = Georgia.overall; champname2 = &quot;Georgia&quot;; Georgia.overall = Georgia.overall + 3; }else if(number == 5){ champ2 = MiamiFL.overall; champname2 = &quot;Miami FL&quot;; MiamiFL.overall = MiamiFL.overall + 3; }else if(number == 6){ champ2 = OklahomaSt.overall; champname2 = &quot;OklahomaST&quot;; OklahomaSt.overall = OklahomaSt.overall + 3; }else if(number == 7){ champ2 = Auburn.overall; champname2 = &quot;Auburn&quot;; Auburn.overall = Auburn.overall + 3; }else if(number == 8){ champ2 = UNC.overall; champname2 = &quot;UNC&quot;; UNC.overall = UNC.overall + 3; }else if(number == 9){ champ2 = NotreDame.overall; champname2 = &quot;Notre Dame&quot;; NotreDame.overall = NotreDame.overall + 3; }else if(number == 10){ champ2 = PennSt.overall; champname2 = &quot;Penn State&quot;; PennSt.overall = PennSt.overall + 3; }else if(number == 11){ champ2 = OhioState.overall; champname2 = &quot;Ohio State&quot;; OhioState.overall = OhioState.overall + 3; } calc: score = champ1 * 0.5; random = rand() % 5 + -20; random2 = rand() % 20 + -5; random = random + random2; score = score + random; score2 = champ2 * 0.5;; random3 = rand() % 5 + -20; random4 = rand() % 20 + -5; random3 = random3 + random4; score2 = score2 + random3; if(score &lt; 2){ score = 0; } if(score2 &lt; 2){ score2 = 0; } if(score == score2){ goto calc; } cout &lt;&lt; champname2 &lt;&lt; &quot; scored &quot; &lt;&lt; score2 &lt;&lt; &quot; | &quot; &lt;&lt; champname &lt;&lt; &quot; scored &quot; &lt;&lt; score &lt;&lt; endl; cin &gt;&gt; number; week = 1; random3 = 0; random3 = rand() % 5 + -10; random4 = rand() % 10 + -5; random3 = random3 + random4; Alabama.overall = Alabama.overall + random3; random3 = 0; random3 = rand() % 5 + -10; random4 = rand() % 10 + -5; random3 = random3 + random4; Clemson.overall = Clemson.overall + random3; random3 = 0; random3 = rand() % 5 + -10; random4 = rand() % 10 + -5; random3 = random3 + random4; UNC.overall = UNC.overall + random3; random3 = 0; random3 = rand() % 5 + -10; random4 = rand() % 10 + -5; random3 = random3 + random4; OklahomaSt.overall = OklahomaSt.overall + random3; random3 = 0; random3 = rand() % 5 + -10; random4 = rand() % 10 + -5; random3 = random3 + random4; PennSt.overall = PennSt.overall + random3; random3 = 0; random3 = rand() % 5 + -10; random4 = rand() % 10 + -5; random3 = random3 + random4; OhioState.overall = OhioState.overall + random3; random3 = 0; random3 = rand() % 5 + -10; random4 = rand() % 10 + -5; random3 = random3 + random4; Auburn.overall = Auburn.overall + random3; random3 = 0; random3 = rand() % 5 + -10; random4 = rand() % 10 + -5; random3 = random3 + random4; Georgia.overall = Georgia.overall + random3; random3 = 0; random3 = rand() % 5 + -10; random4 = rand() % 10 + -5; random3 = random3 + random4; Florida.overall = Florida.overall + random3; random3 = 0; random3 = rand() % 5 + -10; random4 = rand() % 10 + -5; random3 = random3 + random4; MiamiFL.overall = MiamiFL.overall + random3; random3 = 0; random3 = rand() % 5 + -10; random4 = rand() % 10 + -5; random3 = random3 + random4; NotreDame.overall = NotreDame.overall + random3; random3 = 0; Tennessee.next = Tennessee.week1; Year = Year + 1; NotreDame.win = 0; NotreDame.loss = 0; UNC.win = 0; UNC.loss = 0; Florida.win = 0; Florida.loss = 0; PennSt.win = 0; PennSt.loss = 0; OklahomaSt.win = 0; OklahomaSt.loss = 0; OhioState.win = 0; OhioState.loss = 0; Auburn.win = 0; Auburn.loss = 0; MiamiFL.win = 0; MiamiFL.loss = 0; Clemson.win = 0; Clemson.loss = 0; Alabama.win = 0; Alabama.loss = 0; MiamiFL.win = 0; MiamiFL.loss = 0; Tennessee.win = 0; Tennessee.loss = 0; one = &quot; &quot;; two = &quot; &quot;; three = &quot; &quot;; four = &quot; &quot;; five = &quot; &quot;; six = &quot; &quot;; seven = &quot; &quot;; eight = &quot; &quot;; nine = &quot; &quot;; ten = &quot; &quot;; oner = 0; twor = 0; threer = 0; fourr = 0; fiver = 0; sixr = 0; sevenr = 0; eightr = 0; niner = 0; tenr = 0; ones = 0; twos = 0; threes = 0; fours = 0; fives = 0; sixs = 0; sevens = 0; eights = 0; nines = 0; tens = 0; onet = 0; twot = 0; threet = 0; fourt = 0; fivet = 0; sixt = 0; sevent = 0; eightt = 0; ninet = 0; tent = 0; minutes = 120; Tennessee.overall = Tennessee.overall + addrat; onel = rand() % 30 + 1; two1 = rand() % 30 + 1; three1 = rand() % 30 + 1; four1 = rand() % 30 + 1; five1 = rand() % 30 + 1; six1 = rand() % 30 + 1; seven1 = rand() % 30 + 1; eight1 = rand() % 30 + 1; nine1 = rand() % 30 + 1; ten1 = rand() % 30 + 1; onec = rand() % 10 + 1; twoc = rand() % 10 + 1; threec = rand() % 10 + 1; fourc = rand() % 10 + 1; fivec = rand() % 10 + 1; sixc = rand() % 10 + 1; sevenc = rand() % 10 + 1; eightc = rand() % 10 + 1; ninec = rand() % 10 + 1; tenc = rand() % 10 + 1; addrat = 0; goto home; } TeamBoard: cout &lt;&lt; string( 100, '\n' ); cout &lt;&lt; &quot;Team Board - All Teams and their Stats - Teams are not sorted&quot; &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; OhioState.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; OhioState.overall &lt;&lt; &quot; ( &quot; &lt;&lt; OhioState.win &lt;&lt; &quot; - &quot; &lt;&lt; OhioState.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; Alabama.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; Alabama.overall &lt;&lt; &quot; ( &quot; &lt;&lt; Alabama.win &lt;&lt; &quot; - &quot; &lt;&lt; Alabama.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; MiamiFL.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; MiamiFL.overall &lt;&lt; &quot; ( &quot; &lt;&lt; MiamiFL.win &lt;&lt; &quot; - &quot; &lt;&lt; MiamiFL.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; OklahomaSt.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; OklahomaSt.overall &lt;&lt; &quot; ( &quot; &lt;&lt; OklahomaSt.win &lt;&lt; &quot; - &quot; &lt;&lt; OklahomaSt.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; Auburn.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; Auburn.overall &lt;&lt; &quot; ( &quot; &lt;&lt; Auburn.win &lt;&lt; &quot; - &quot; &lt;&lt; Auburn.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; Tennessee.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; Tennessee.overall &lt;&lt; &quot; ( &quot; &lt;&lt; Tennessee.win &lt;&lt; &quot; - &quot; &lt;&lt; Tennessee.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; PennSt.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; PennSt.overall &lt;&lt; &quot; ( &quot; &lt;&lt; PennSt.win &lt;&lt; &quot; - &quot; &lt;&lt; PennSt.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; Florida.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; Florida.overall &lt;&lt; &quot; ( &quot; &lt;&lt; Florida.win &lt;&lt; &quot; - &quot; &lt;&lt; Florida.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; Georgia.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; Georgia.overall &lt;&lt; &quot; ( &quot; &lt;&lt; Georgia.win &lt;&lt; &quot; - &quot; &lt;&lt; Georgia.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; UNC.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; UNC.overall &lt;&lt; &quot; ( &quot; &lt;&lt; UNC.win &lt;&lt; &quot; - &quot; &lt;&lt; UNC.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; NotreDame.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; NotreDame.overall &lt;&lt; &quot; ( &quot; &lt;&lt; NotreDame.win &lt;&lt; &quot; - &quot; &lt;&lt; NotreDame.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; Clemson.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; Clemson.overall &lt;&lt; &quot; ( &quot; &lt;&lt; Clemson.win &lt;&lt; &quot; - &quot; &lt;&lt; Clemson.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; endl &lt;&lt; &quot;Type 1 and press Enter to continue.&quot; &lt;&lt; endl; cin &gt;&gt; number; goto home; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T03:47:23.097", "Id": "494506", "Score": "1", "body": "linked: https://codereview.stackexchange.com/questions/250382/football-management-game-in-c/250386#250386" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T14:49:28.160", "Id": "494539", "Score": "0", "body": "I found a bug - renaming your team sends the game into a fit!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T21:59:40.200", "Id": "494596", "Score": "0", "body": "I think it is a problem with strings not allowing spaces..." } ]
[ { "body": "<h1><strike><code>#include &lt;bits/stdc++.h&gt;</code></strike></h1>\n<p>it is a cheap hack, you're basically avoiding including the separate header file - <code>string</code>, <code>vector</code>, <code>iostream</code>. This doesn't even work on my compiler in visual studio ( msvc ).</p>\n<p><a href=\"https://stackoverflow.com/Questions/31816095/Why-Should-I-Not-Include-Bits-Stdc-H.#:%7E:text=By%20using%20this%20header%20file,they%27ll%20be%20less%20productive.\">why should I not #include &lt;bits/stdc++.h&gt;</a></p>\n<h1><strike><code>using namespace std</code></strike></h1>\n<p>This one is worse, it's making your program a lot more confusing. When there are so many people advising <em>against</em> it, why use it? From what I remember you were given the same advice on <a href=\"https://codereview.stackexchange.com/questions/250382/football-management-game-in-c/250386#250386\">this</a> question.</p>\n<p>If you really really need to not write <code>std::</code>, just do it for some functions, preferably in a smaller scope where you can just do <code>using std::cout</code>, I still advise <strong>against it</strong>,</p>\n<p><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\"><strong>Read this</strong>!</a></p>\n<hr />\n<h1>Why so many globals?</h1>\n<pre class=\"lang-cpp prettyprint-override\"><code>int number, overall;\nstring team, nextgame;\nint opponentoverall;\nint score, score2, random, random2, random3, random4, random5, randoml;\nfloat finalscore, finalscore2;\nstring choice;\nint week = 1;\nint i = 3;\nint u = 0;\nint randl;\nint champ1, champ2;\n\nint onet = 0;\nint twot = 0;\nint threet = 0;\nint fourt = 0;\nint fivet = 0;\nint sixt = 0;\nint sevent = 0;\nint eightt = 0;\nint ninet = 0;\nint tent = 0;\nint onev = 0;\nint twov = 0;\nint threev = 0;\nint fourv = 0;\nint fivev = 0;\nint sixv = 0;\nint sevenv = 0;\nint eightv = 0;\nint ninev = 0;\nint tenv = 0;\nstring champname, champname2;\nstring prospect1 = &quot;Jonas Hill - QB&quot;;\nstring prospect2 = &quot;Kyle Matthew - DB&quot;;\nstring prospect3 = &quot;Julius Brown - RB&quot;;\nstring prospect4 = &quot;Reece David - C&quot;;\nstring prospect5 = &quot;Cole Anderson - FS&quot;;\nstring prospect6 = &quot;Andy Tyler - WR&quot;;\nstring prospect7 = &quot;Macus Reed - FB&quot;;\nstring prospect8 = &quot;Elijah Moore - LB&quot;;\nstring prospect9 = &quot;Larry Steel - RB&quot;;\nstring prospect10 = &quot;Nicholas Dean - LB&quot;;\nint oner = 0;\nint twor = 0;\nint threer = 0;\nint fourr = 0;\nint fiver = 0;\nint sixr = 0;\nint sevenr = 0;\nint eightr = 0;\nint niner = 0;\nint tenr = 0;\nint ones = 0;\nint twos = 0;\nint threes = 0;\nint fours = 0;\nint fives = 0;\nint sixs = 0;\nint sevens = 0;\nint eights = 0;\nint nines = 0;\nint tens = 0;\n\nstring one = &quot; &quot;;\nstring two = &quot; &quot;;\nstring three = &quot; &quot;;\nstring four = &quot; &quot;;\nstring five = &quot; &quot;;\nstring six = &quot; &quot;;\nstring seven = &quot; &quot;;\nstring eight = &quot; &quot;;\nstring nine = &quot; &quot;;\nstring ten = &quot; &quot;;\nint minutes = 120;\n</code></pre>\n<p>There is no need to have so many globals, you can declare them only in the scope where you need them, and in cases where a function might need them, pass it as an argument</p>\n<h1>Use an array</h1>\n<pre class=\"lang-cpp prettyprint-override\"><code>int onet = 0;\nint twot = 0;\nint threet = 0;\nint fourt = 0;\nint fivet = 0;\nint sixt = 0;\nint sevent = 0;\nint eightt = 0;\nint ninet = 0;\nint tent = 0;\nint onev = 0;\nint twov = 0;\nint threev = 0;\nint fourv = 0;\nint fivev = 0;\nint sixv = 0;\nint sevenv = 0;\nint eightv = 0;\nint ninev = 0;\nint tenv = 0;\nstring one = &quot; &quot;;\nstring two = &quot; &quot;;\nstring three = &quot; &quot;;\nstring four = &quot; &quot;;\nstring five = &quot; &quot;;\nstring six = &quot; &quot;;\nstring seven = &quot; &quot;;\nstring eight = &quot; &quot;;\nstring nine = &quot; &quot;;\nstring ten = &quot; &quot;;\nint oner = 0;\nint twor = 0;\nint threer = 0;\nint fourr = 0;\nint fiver = 0;\nint sixr = 0;\nint sevenr = 0;\nint eightr = 0;\nint niner = 0;\nint tenr = 0;\nint ones = 0;\nint twos = 0;\nint threes = 0;\nint fours = 0;\nint fives = 0;\nint sixs = 0;\nint sevens = 0;\nint eights = 0;\nint nines = 0;\nint tens = 0;\nstring prospect1 = &quot;Jonas Hill - QB&quot;;\nstring prospect2 = &quot;Kyle Matthew - DB&quot;;\nstring prospect3 = &quot;Julius Brown - RB&quot;;\nstring prospect4 = &quot;Reece David - C&quot;;\nstring prospect5 = &quot;Cole Anderson - FS&quot;;\nstring prospect6 = &quot;Andy Tyler - WR&quot;;\nstring prospect7 = &quot;Macus Reed - FB&quot;;\nstring prospect8 = &quot;Elijah Moore - LB&quot;;\nstring prospect9 = &quot;Larry Steel - RB&quot;;\nstring prospect10 = &quot;Nicholas Dean - LB&quot;;\n</code></pre>\n<p>You can simplify all of this by simply using an <a href=\"http://www.cplusplus.com/doc/tutorial/arrays/#:%7E:text=An%20array%20is%20a%20series,index%20to%20a%20unique%20identifier.&amp;text=Like%20a%20regular%20variable%2C%20an,type%20name%20%5Belements%5D%3B\" rel=\"noreferrer\">array</a> of size <code>x</code>. This way when you need a specific team, you just need to slice from it, since you have used names like <code>oner</code>, <code>ones</code>, <code>prospect1</code>, and <code>onet</code>, I have no idea what they really do, since all of them are initialized to <code>0</code> and the names don't help too much.</p>\n<p>Here is what an array used in this would look like</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>constexpr int number_of_prospects = 10;\nstd::string prospects[ number_of_prospects ];\n\nprospects[ 0 ] = &quot; Prospect 1 &quot;;\nstd::cout &lt;&lt; prospects[0];\n</code></pre>\n<blockquote>\n<p>Prospect 1</p>\n</blockquote>\n<p>This is an example of readable code, when someone sees <code>std::string prospects[ number_of_prospects]</code>, he knows exactly what it is. Does a person know exactly what your program is doing at some points the second he reads it?</p>\n<p>The same array can be applied for all the threads of globals you have, just a simple array of size <code>10</code> can work. Even in your class <code>Team</code></p>\n<pre class=\"lang-cpp prettyprint-override\"><code>string week1, week2, week3, week4, week5, week6, week7, week8, next;\n</code></pre>\n<p>Simply do</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>std::string weeks[ number_of_weeks ];\n</code></pre>\n<p>where <code>number_of_weeks</code> would be, guess what- The number of weeks! It would be clear to anyone</p>\n<h1>from <code>void start()</code></h1>\n<pre class=\"lang-cpp prettyprint-override\"><code>void start() {\n cout &lt;&lt; string( 100, '\\n' );\n cout &lt;&lt; &quot;Choose a School to Coach!&quot; &lt;&lt; endl;\n cout &lt;&lt; &quot;1- Tennessee&quot; &lt;&lt; endl;\nenum Schools{ tennessee = 1,auburn,pennst };\n cin &gt;&gt; number;\n if(number == tennessee){\n team = &quot;Tennessee&quot;;\n overall = 75;\n }\n\n\n\n}\n</code></pre>\n<p>The formatting is hurting my eyes</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>void start() \n{\n cout &lt;&lt; string(100, '\\n');\n cout &lt;&lt; &quot;Choose a School to Coach!&quot; &lt;&lt; endl;\n cout &lt;&lt; &quot;1- Tennessee&quot; &lt;&lt; endl;\n\n enum Schools \n {\n tennessee = 1, auburn, pennst\n };\n\n cin &gt;&gt; number;\n if (number == Tennessee) \n {\n team = &quot;Tennessee&quot;;\n overall = 75;\n }\n}\n</code></pre>\n<ul>\n<li><p>Since you only used <code>tennesse</code>, what is the use of <code>auburn, pennst</code>?</p>\n</li>\n<li><p><code>overall = 75</code> what does <code>75</code> imply here? Avoid <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"noreferrer\">magic numbers</a></p>\n</li>\n</ul>\n<h2>handle inavlid input</h2>\n<p>Here, if the user enter's anything else other than an <code>int</code>, <code>std::cin</code> will fail. This will cause very strange behaviour in your program. It's always good to catch invalid input, you can simply do</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>if (!std::cin &gt;&gt; number) \n{\n std::cout &lt;&lt; &quot;Invalid input! \\n&quot;; \n}\n</code></pre>\n<hr />\n<h1>from <code>void mainmenu()</code></h1>\n<pre class=\"lang-cpp prettyprint-override\"><code>void mainmenu() {\n \n cout &lt;&lt; string( 100, '\\n' );\n cout &lt;&lt; &quot;FOR THE PLAYER EXPERIENCE, PLEASE PLAY IN FULL SCREEN&quot; &lt;&lt; endl;\n cout &lt;&lt; &quot;Be the Coach | College Football Manager&quot; &lt;&lt; endl;\n cout &lt;&lt; &quot;1 - Manage&quot; &lt;&lt; endl &lt;&lt; &quot;2 - Manual&quot; &lt;&lt; endl &lt;&lt; &quot;3 - Abort&quot; &lt;&lt; endl; \nenum Choices{ manage = 1,manual,abort };\n cin &gt;&gt; number;\n if(number == manage){\n start();\n }\n \n}\n</code></pre>\n<p>I have the same three problems here</p>\n<ul>\n<li>Inconsistent, unreadble formatting</li>\n<li><code>enum Choices { ... }; </code> has three enumerators when you are using only one</li>\n<li>no handling of bad input</li>\n</ul>\n<hr />\n<h1><code>std::uniform_int_distribution</code></h1>\n<p>C++ has <a href=\"https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution\" rel=\"noreferrer\">std::uniform_int_distribution</a> which is better than C<code>s </code>rand()`</p>\n<hr />\n<h1>Naming our variables</h1>\n<pre class=\"lang-cpp prettyprint-override\"><code>int rands;\nint onel = rand() % 30 + 1;\nint two1 = rand() % 30 + 1;\nint three1 = rand() % 30 + 1;\nint four1 = rand() % 30 + 1;\nint five1 = rand() % 30 + 1;\nint six1 = rand() % 30 + 1;\nint seven1 = rand() % 30 + 1;\nint eight1 = rand() % 30 + 1;\nint nine1 = rand() % 30 + 1;\nint ten1 = rand() % 30 + 1;\nint onec = rand() % 10 + 1;\nint twoc = rand() % 10 + 1;\nint threec = rand() % 10 + 1;\nint fourc = rand() % 10 + 1;\nint fivec = rand() % 10 + 1;\nint sixc = rand() % 10 + 1;\nint sevenc = rand() % 10 + 1;\nint eightc = rand() % 10 + 1;\nint ninec = rand() % 10 + 1;\nint tenc = rand() % 10 + 1;\n</code></pre>\n<p>Now I see <code>one</code>, <code>onet</code>, onec` which is making me confused more than ever, always use <a href=\"https://medium.com/coding-skills/clean-code-101-meaningful-names-and-functions-bf450456d90c\" rel=\"noreferrer\">meaningful names for functions and variables</a>. An array can be used here too.</p>\n<hr />\n<h1>Factor repetition into functions</h1>\n<pre class=\"lang-cpp prettyprint-override\"><code>cout &lt;&lt; string( 100, '\\n' );\n cout &lt;&lt; OhioState.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; OhioState.overall &lt;&lt; &quot; ( &quot; &lt;&lt; OhioState.win &lt;&lt; &quot; - &quot; &lt;&lt; OhioState.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl;\n cout &lt;&lt; Alabama.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; Alabama.overall &lt;&lt; &quot; ( &quot; &lt;&lt; Alabama.win &lt;&lt; &quot; - &quot; &lt;&lt; Alabama.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl;\n cout &lt;&lt; MiamiFL.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; MiamiFL.overall &lt;&lt; &quot; ( &quot; &lt;&lt; MiamiFL.win &lt;&lt; &quot; - &quot; &lt;&lt; MiamiFL.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl;\n cout &lt;&lt; OklahomaSt.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; OklahomaSt.overall &lt;&lt; &quot; ( &quot; &lt;&lt; OklahomaSt.win &lt;&lt; &quot; - &quot; &lt;&lt; OklahomaSt.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl;\n cout &lt;&lt; Auburn.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; Auburn.overall &lt;&lt; &quot; ( &quot; &lt;&lt; Auburn.win &lt;&lt; &quot; - &quot; &lt;&lt; Auburn.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl;\n cout &lt;&lt; Tennessee.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; Tennessee.overall &lt;&lt; &quot; ( &quot; &lt;&lt; Tennessee.win &lt;&lt; &quot; - &quot; &lt;&lt; Tennessee.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl;\n cout &lt;&lt; PennSt.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; PennSt.overall &lt;&lt; &quot; ( &quot; &lt;&lt; PennSt.win &lt;&lt; &quot; - &quot; &lt;&lt; PennSt.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl;\n cout &lt;&lt; Florida.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; Florida.overall &lt;&lt; &quot; ( &quot; &lt;&lt; Florida.win &lt;&lt; &quot; - &quot; &lt;&lt; Florida.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl;\n cout &lt;&lt; Georgia.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; Georgia.overall &lt;&lt; &quot; ( &quot; &lt;&lt; Georgia.win &lt;&lt; &quot; - &quot; &lt;&lt; Georgia.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl;\n cout &lt;&lt; UNC.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; UNC.overall &lt;&lt; &quot; ( &quot; &lt;&lt; UNC.win &lt;&lt; &quot; - &quot; &lt;&lt; UNC.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl;\n cout &lt;&lt; NotreDame.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; NotreDame.overall &lt;&lt; &quot; ( &quot; &lt;&lt; NotreDame.win &lt;&lt; &quot; - &quot; &lt;&lt; NotreDame.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl;\n cout &lt;&lt; Clemson.name &lt;&lt; &quot; | Overall - &quot; &lt;&lt; Clemson.overall &lt;&lt; &quot; ( &quot; &lt;&lt; Clemson.win &lt;&lt; &quot; - &quot; &lt;&lt; Clemson.loss &lt;&lt; &quot; ) &quot; &lt;&lt; endl &lt;&lt; endl;\n</code></pre>\n<p>There are two reasons a function should do this</p>\n<ul>\n<li>You have used the same chunk of code more than once</li>\n<li>avoids unnecessarily convoluted code</li>\n</ul>\n<p>Just place this in a function with a meaningful name so all you have in your <code>main()</code> function is <code>print_records()</code></p>\n<hr />\n<h1>Don't <code>goto</code>!</h1>\n<p><code>goto</code> is absolutely not required here, especially something like</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>home:\n\n...\n...\n...\n...\n...\n...\n...\n\ngoto home;\n</code></pre>\n<p>stinks a lot, you really only need a <code>while</code> loop</p>\n<p>Other than this, there are still many uses of <code>goto</code> in your program, seriously re-consider, and replace <code>goto</code> with functions.</p>\n<hr />\n<h1>Simplify program</h1>\n<pre class=\"lang-cpp prettyprint-override\"><code>if(Alabama.overall &gt; 100){\n Alabama.overall = 100;\n }\n if(Clemson.overall &gt; 100){\n Clemson.overall = 100;\n }\n if(OhioState.overall &gt; 100){\n OhioState.overall = 100;\n }\n if(NotreDame.overall &gt; 100){\n NotreDame.overall = 100;\n }\n if(OklahomaSt.overall &gt; 100){\n OklahomaSt.overall = 100;\n }\n if(MiamiFL.overall &gt; 100){\n MiamiFL.overall = 100;\n }\n if(Auburn.overall &gt; 100){\n Auburn.overall = 100;\n }\n if(UNC.overall &gt; 100){\n UNC.overall = 100;\n }\n if(Florida.overall &gt; 100){\n Florida.overall = 100;\n }\n if(PennSt.overall &gt; 100){\n PennSt.overall = 100;\n }\n if(Georgia.overall &gt; 100){\n Georgia.overall = 100;\n }\n if(Tennessee.overall &gt; 100){\n Tennessee.overall = 100;\n }\n</code></pre>\n<p>Here is how I would like to see it</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>for( auto&amp; team : Teams)\n{\n team.overall = std::min(team.overall, max_overall);\n}\n</code></pre>\n<p>How can we achieve this.</p>\n<p>Firstly, you'll need to <code>#include &lt;algorithm&gt;</code> and <code>#include &lt;vector&gt;</code></p>\n<p>Now, you can clearly see that if we had a better structure earlier, we would be able to do stuff like this much more efficiently. <br>\nWhat you have to do now is</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>std::vector &lt; Team &gt; teams;\n\nTeam x;\nx.overall = ..\n...\n... // initialise Team x\n\nteams.push_back( x )\n</code></pre>\n<p>With the above changes, your huge thread of <code>if</code> statements can be minimised to</p>\n<pre><code>for( auto&amp; team : Teams)\n{\n team.overall = std::min(team.overall, max_overall);\n}\n</code></pre>\n<ul>\n<li><p>The loop is called a <a href=\"https://en.cppreference.com/w/cpp/language/range-for\" rel=\"noreferrer\">range-based for loop</a> which you can use to iterate through containers like <code>std::vector</code>.</p>\n</li>\n<li><p>You can replace <code>auto</code> with <code>Team</code>, since the type of data in <code>teams</code> is <code>Team</code>. Using <code>auto</code> just makes the compiler do that for us.</p>\n</li>\n<li><p><code>std::min</code> will simply return the <em>smaller</em> of the two</p>\n</li>\n<li><p>Notice how I replaced <code>100</code> with <code>max_overall</code>. This is because again, <code>100</code> doesn't imply anything, <code>max_overall</code> is clear</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T04:59:54.580", "Id": "251241", "ParentId": "251238", "Score": "17" } } ]
{ "AcceptedAnswerId": "251241", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T02:40:28.850", "Id": "251238", "Score": "6", "Tags": [ "c++", "beginner", "object-oriented", "game" ], "Title": "Football Management Program (AMERICAN) C++" }
251238
<h1>Background</h1> <p>I've been looking into a few different way to implement error reporting for an embedded system in C and there a couple things that I'd like to incorporate:</p> <ul> <li>A generic and extensible error type.</li> <li>Backward compatibility with OK and ERROR returns (i.e. can effectively return 0 or 1).</li> <li>Well defined error codes on a per layer/module basis (i.e. a typedef'd enum).</li> <li>Multiplexed error codes.</li> <li>Ideally posix compliant.</li> </ul> <p>I also like using <a href="https://blog.burntsushi.net/rust-error-handling/" rel="nofollow noreferrer">rust's result type</a> as it provides a well defined method for handling returned values. I managed to come up with a header-only implementation in C similar to <a href="https://codereview.stackexchange.com/questions/140231/rust-like-result-in-c-nicer-error-handling?newreg=584c8d8066144009bcb175f891c7bc38">that found here</a>. But I don't want to focus on that here. I only mentioned as context for how I plan to isolate the complexity.</p> <h1>Error Type</h1> <p>I tend to support &quot;multiplexed error codes&quot; via bit masking intergers. This tends to be implemented like so:</p> <pre><code>#include &lt;stdint.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; typedef enum { NO_ERROR = 0, ERROR_OVERTEMP = 0x0001, ERROR_NO_READ = 0x0002, } error_e; float readVal(void) { return 0.0; } uint32_t getSensorVal(float *returnVal) { uint32_t errorRet = 0; float ret = readVal(); if (ret == 0) { errorRet |= ERROR_NO_READ; } return errorRet; } int main() { float val; int ret = getSensorVal(&amp;val); if (!ret) { printf(&quot;Sensor Val: %f \n&quot;, val); } else { printf(&quot;Oh no we have an error \n&quot;); } return 0; } </code></pre> <p>This works well enough but is somewhat limiting in that the number of error codes for a given enumeration set can only be as many as 32 (64 on 64 bit systems). This can be problematic when errors are passed throughout a vast system. This led me to come up with the following typedef:</p> <pre><code>typedef struct errorList_s { unsigned const type; uint32_t value; struct errorList_s *next; } errorList_t; </code></pre> <p>This allows developers to build on interfaces with error codes that are extremely extensible. Its use might look something like the following:</p> <pre><code>typedef enum { NO_ERROR = 0, ERROR_OVERTEMP = 0x0001, ERROR_NO_READ = 0x0002, } error_e; uint32_t getSensorVal(float *returnVal) { uin32_t errorRet = 0; float ret = readVal() if (ret == 0) { errorRet |= ERROR_NO_READ; } } int main() { float val; int ret = getSensorVal(&amp;val); if (!ret) { printf(&quot;Sensor Val: %f \n&quot;, val); } else { printf(&quot;Oh no we have an error \n&quot;); } return 0; } </code></pre> <p>This works well enough but is somewhat limiting in that the number of error codes for a given enumeration set can only be as many as 32 (64 on 64 bit systems). This can be problematic when errors are passed throughout a vast system. This led me to come up with the following typedef:</p> <pre><code>typedef struct errorList_s { unsigned const type; uint32_t value; struct errorList_s *next; } errorList_t; </code></pre> <p>This allows developers to build on interfaces with error codes that are extremely extensible. Its use might look something like the following:</p> <pre><code>#include &lt;stdint.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; typedef struct errorList_s { unsigned type; uint32_t value; struct errorList_s *next; } errorList_t; typedef enum { SENSOR_ERROR = 0, DEVICE_ERROR = 1, } errorTypes_e; typedef enum { OVER_TEMP = 0x001, OVER_CURRENT = 0x002, } sensorErrors_e; typedef enum { DEVICE_UNRESPONSIVE = 0x001, BAD_DEVICE_ID = 0x002, } deviceErrors_e; /* Dummy impl */ float readVal(void) { return 0.0f; } errorList_t *getDevice_MotorPos(float *pos) { errorList_t *devError = NULL; errorList_t *sensorError = NULL; float ret; /* Some logic says that a read of zero from some hw device means overtemp*/ ret = readVal(); if (ret == 0.0f) { sensorError = (errorList_t *) calloc(1, sizeof(errorList_t)); sensorError-&gt;type = SENSOR_ERROR; sensorError-&gt;value |= OVER_TEMP; devError = (errorList_t *) calloc(1, sizeof(errorList_t)); devError-&gt;type = DEVICE_ERROR; devError-&gt;value |= DEVICE_UNRESPONSIVE; devError-&gt;next = sensorError; } else { *pos = ret; } return devError; } void sensorErrorHandler(errorList_t *const err); void deviceErrorHandler(errorList_t *const err); void selectErrorType(errorList_t *const err){ switch (err-&gt;type) { case SENSOR_ERROR: sensorErrorHandler(err); break; case DEVICE_ERROR: deviceErrorHandler(err); break; default: printf(&quot;Unkown error type %d \n&quot;, err-&gt;type); } } void sensorErrorHandler(errorList_t *const err) { if (err-&gt;value &amp; OVER_TEMP) { printf(&quot;Sensor read over temp \n&quot;); } if (err-&gt;value &amp; OVER_CURRENT) { printf(&quot;Sensor read over current \n&quot;); } if (err-&gt;next) { selectErrorType(err-&gt;next); } } void deviceErrorHandler(errorList_t *const err) { if (err-&gt;value &amp; BAD_DEVICE_ID) { printf(&quot;Invalid device ID used to contact device \n&quot;); } if (err-&gt;value &amp; DEVICE_UNRESPONSIVE) { printf(&quot;Device unresponsive \n&quot;); } if (err-&gt;next) { selectErrorType(err-&gt;next); } } int main() { float val; errorList_t *const ret = getDevice_MotorPos(&amp;val); if (!ret-&gt;value) { printf(&quot;Sensor Val: %f \n&quot;, val); } else { selectErrorType(ret); } return 0; } </code></pre> <p>Other than the inherent complexity I'm introducing by requiring &quot;unwrapping&quot; of errors (which will be handled by helper macros)</p> <p>Is there something about this that seems wrong? Is there something here to be improved upon? I'd like to implement this in such a way that is posix compliant although it doesn't seem immediately obvious how to do that.</p> <p>All feedback is much appreciated.</p> <p>EDIT:</p> <p>If we consider the example as being in some file errorTest.c this can be compiled and run with:</p> <pre><code>gcc errorTest.c -o errorTest ./errorTest </code></pre> <p>If implemented formally I would likely create an error handler interface typedef and do more complicated things than just printing errors. After writing this out it also strikes me that this could be used for more in depth status reporting than just error reporting.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T10:12:34.643", "Id": "494522", "Score": "3", "body": "It would help to show how the return type is to be used. In your example, nothing is actually calling `getDevice_MotorPos()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T14:45:29.023", "Id": "494538", "Score": "0", "body": "@G.Sliepen Just extended my example. In real life the idea is that we would do more than just print errors and I'm realizing this could be used to actually promote more in depth status than just errors.\nAlso i think in a formal implementation I'd clean this up by using an interface." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T14:59:31.650", "Id": "494540", "Score": "0", "body": "Your code is syntactically incorrect - it's missing some semicolons and return values. Code Review policy is that we review complete code, not example, theoretical or stub code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T15:16:18.863", "Id": "494542", "Score": "0", "body": "@Reinderien I must have missed that note about the code review policy but the example is fixed now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T15:35:06.670", "Id": "494548", "Score": "0", "body": "Are you sure? `getSensorVal` wouldn't compile." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T15:48:14.647", "Id": "494550", "Score": "0", "body": "@Reinderien now it should. I hadn't looked at the first example as I thought its behaviour was self evident" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T15:50:07.467", "Id": "494551", "Score": "1", "body": "@Reinderien: that's in code that is not part of the review. But it's a bit confusing. Reginald: it would help if you remove the code that is not under review, and only show your implementation that you want reviewed, plus the code that shows how the latter is actually used. Furthermore, if you think you are going to use an interface, why not spend some time writing an interface and including it in the review?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T17:20:43.510", "Id": "494566", "Score": "1", "body": "Using `calloc` in an embedded system is strongly unadvisable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T07:12:00.890", "Id": "494617", "Score": "0", "body": "What system is this for? Looks like a PC program, not an embedded system. It's generally quite pointless to review embedded systems code without a rough idea about which target MCU(s) the code is intended for." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T07:14:22.663", "Id": "494618", "Score": "0", "body": "\"the number of error codes for a given enumeration set can only be as many as 32 (64 on 64 bit systems)\" This is unlikely - the number of enum values in C will never likely exceed 2^31 since enumeration constants have type `int`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T07:18:07.413", "Id": "494619", "Score": "0", "body": "Also, the highest number of error codes I ever encountered in real-world systems is something around 1000, in big industrial automation field bus systems in factories. Normally you'd separate errors into code, sender + additional information." } ]
[ { "body": "<h1>What is the goal?</h1>\n<blockquote>\n<p>This works well enough but is somewhat limiting in that the number of error codes for a given enumeration set can only be as many as 32 (64 on 64 bit systems).</p>\n</blockquote>\n<p>So 4294967296 possible error codes (or 18446744073709551616 on 64-bit systems) isn't extensible enough? You don't need to use bitmasks you know; in the example you gave you would never have both <code>ERROR_OVERTEMP</code> and <code>ERROR_NO_READ</code> set at the same time. Anyway, there are two parts to your <code>errorList_t</code>:</p>\n<ol>\n<li>You have a <em>structured</em> error that is split into a category (<code>type</code>) and an error code within that category (<code>value</code>).</li>\n<li>You have a way to return multiple error codes in one go.</li>\n</ol>\n<p>The question is though: who is this for, and what can they do with this information? Is it for the end user, or are these codes supposed to be handled by the application?\nIf this list of errors is meant to be read by the end user, then they are not interested in codes. They just want to see error messages. Instead of storing <code>type</code> and <code>value</code>, why not just store a pointer to a string?</p>\n<pre><code>typedef struct errorList_s {\n const char *message;\n struct errorList_s *next;\n} errorList_t;\n</code></pre>\n<p>And then use it like so:</p>\n<pre><code>errorList_t *error = ...;\nerror-&gt;message = &quot;Device unresponsive&quot;;\nreturn error;\n</code></pre>\n<p>However, instead of waiting with printing the error message until a whole linked list is returned, why not immediately print the error message, and just return an error code? Then again, if this is for an embedded system, would the user ever get to see an error message?</p>\n<p>If it's meant for the application, then consider whether it is useful at all to have a list of errors. And what does it mean to get multiple errors returned? Are they all independent errors, for example if a function tried to read from 10 different sensors, and 3 of the sensors returned an error? Or is it more like a stack, where each error goes into more detail?</p>\n<p>Consider that most error handling is rather simplistic, and looks like:</p>\n<pre><code>error = someFunction(...);\n\nif (error) {\n cleanUp();\n return error;\n}\n</code></pre>\n<p>There is almost never any parsing being done. The few exceptions I know of are when writing networking code, where you might want to distinguish between a real failure and something like <code>EINTR</code> being returned, or when creating a file and you want to distinguish between really not being able to create one, or perhaps the file already existing. In either case, the application almost always only needs a few bits of information about the cause of the error, and certainly not a linked list of error codes.</p>\n<blockquote>\n<p>After writing this out it also strikes me that this could be used for more in depth status reporting than just error reporting.</p>\n</blockquote>\n<p>It might be good to come up with some practical use cases for this before spending too much time on creating an error reporting framework.</p>\n<h1>Add functions to manipulate error lists</h1>\n<p>You spend a lot of lines of code creating a linked list:</p>\n<pre><code>errorList_t *devError = NULL;\nerrorList_t *sensorError = NULL;\n\nif (ret == 0.0f) {\n sensorError = (errorList_t *) calloc(1, sizeof(errorList_t));\n sensorError-&gt;type = SENSOR_ERROR;\n sensorError-&gt;value |= OVER_TEMP;\n devError = (errorList_t *) calloc(1, sizeof(errorList_t));\n devError-&gt;type = DEVICE_ERROR;\n devError-&gt;value |= DEVICE_UNRESPONSIVE;\n devError-&gt;next = sensorError;\n}\n\nreturn devError;\n</code></pre>\n<p>Ideally you want to create some functions that do all this work for you. For example, the above could be rewritten as:</p>\n<pre><code>errorList_t *errors;\n\nif (ret == 0.0f) {\n errors = createError(SENSOR_ERROR, OVER_TEMP);\n errors = appendError(errors, DEVICE_ERROR, DEVICE_UNRESPONSIVE);\n}\n\nreturn errors;\n</code></pre>\n<h1>Avoid memory leaks</h1>\n<p>You should also clean up an <code>errorList_t</code> after you've used it. Again, writing a function that frees all the elements in a given list would be best.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T22:54:49.663", "Id": "251277", "ParentId": "251239", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T03:14:37.100", "Id": "251239", "Score": "6", "Tags": [ "c", "error-handling", "embedded" ], "Title": "Using a linked list as an error type" }
251239
<p>I put together some functions that allows a PHP script to send the SQL data obtained from user inputs on a website via an email attachment as a CSV file. It works perfectly and I have no issues with the code. Alternatively with the right SQL query it would run every X amount of days with a cron job and only produce the data within a specific criteria such as every month.</p> <p>The idea behind the code is for users that cannot extract their data from SQL and have limited experience running their businesses online. I would like some input from what I have put together from scripts and endless amounts of testing to see if the code is up to standard.</p> <p>Firstly I create the fileName:</p> <pre><code> function fileName() { $path = &quot;csv/&quot;; $filename = &quot;Subscribers&quot; . date('Ymd') . &quot;.csv&quot;; $filepath = $path . $filename; return $filepath; } </code></pre> <p>After which I create the CSV file:</p> <pre><code>function createCSV() { include_once &quot;conn.php&quot;; global $conn; $filepath = fileName(); $output = fopen($filepath, &quot;w&quot;); fputcsv($output, array( 'Name', 'Email', 'Date Joined' )); $query = &quot;SELECT name, email, dateTime FROM tableData&quot;; $result = mysqli_query($conn, $query); while ($row = mysqli_fetch_assoc($result)) { fputcsv($output, $row); } return $output; fclose($output); } </code></pre> <p>Followed by the code I cut and edited from a thread online for attaching the CSV using the built in mail function:</p> <pre class="lang-php prettyprint-override"><code> function sendCSV() { // Recipient $to = 'recipient@email.com'; // Sender $from = 'sender@example.com'; $fromName = 'Test'; // Email subject $subject = 'PHP Email with Attachment'; // Attachment file $file = fileName(); $files = glob('csv/*.csv'); unlink($files); createCSV(); // Email body content $htmlContent = ' &lt;h3&gt;PHP Email with Attachment&lt;/h3&gt; &lt;p&gt;This email is sent from the PHP script with attachment.&lt;/p&gt; '; // Header for sender info $headers = &quot;From: $fromName&quot; . &quot; &lt;&quot; . $from . &quot;&gt;&quot;; // Boundary $semi_rand = md5(time()); $mime_boundary = &quot;==Multipart_Boundary_x{$semi_rand}x&quot;; // Headers for attachment $headers .= &quot;\nMIME-Version: 1.0\n&quot; . &quot;Content-Type: multipart/mixed;\n&quot; . &quot; boundary=\&quot;{$mime_boundary}\&quot;&quot;; // Multipart boundary $message = &quot;--{$mime_boundary}\n&quot; . &quot;Content-Type: text/html; charset=\&quot;UTF-8\&quot;\n&quot; . &quot;Content-Transfer-Encoding: 7bit\n\n&quot; . $htmlContent . &quot;\n\n&quot;; // Preparing attachment if (!empty($file) &gt; 0) { if (is_file($file)) { $message .= &quot;--{$mime_boundary}\n&quot;; $fp = @fopen($file, &quot;rb&quot;); $data = @fread($fp, filesize($file)); @fclose($fp); $data = chunk_split(base64_encode($data)); $message .= &quot;Content-Type: application/octet-stream; name=\&quot;&quot; . basename($file) . &quot;\&quot;\n&quot; . &quot;Content-Description: &quot; . basename($file) . &quot;\n&quot; . &quot;Content-Disposition: attachment;\n&quot; . &quot; filename=\&quot;&quot; . basename($file) . &quot;\&quot;; size=&quot; . filesize($file) . &quot;;\n&quot; . &quot;Content-Transfer-Encoding: base64\n\n&quot; . $data . &quot;\n\n&quot;; } } $message .= &quot;--{$mime_boundary}--&quot;; $returnpath = &quot;-f&quot; . $from; // Send email $mail = @mail($to, $subject, $message, $headers, $returnpath); // Email sending status echo $mail ? &quot;&lt;h1&gt;Email Sent Successfully!&lt;/h1&gt;&quot; : &quot;&lt;h1&gt;Email sending failed.&lt;/h1&gt;&quot;; } </code></pre> <p>I am quite new to PHP but managed to put something together that actually works. If you can point out my mistakes (which I do know there would be), or guide me to more simple techniques, I would really appreciate it and it will help me progress in my PHP learning path.</p>
[]
[ { "body": "<h2>Global variable</h2>\n<p>It appears the connection string is used as a global variable:</p>\n<blockquote>\n<pre><code>global $conn;\n</code></pre>\n</blockquote>\n<p><a href=\"https://softwareengineering.stackexchange.com/q/148108/244085\">Global variables have more negative aspects than positives</a>. The <em>conn.php</em> file could define a function that would return the connection represented by <code>$conn</code> And the function could be called where needed - e.g. in <code>createCSV()</code>. Then there would be no need to globally reference that variable and the function could be stubbed/mocked for unit testing.</p>\n<h2>Limit Data</h2>\n<p>It looks like this query is executed to get all data:</p>\n<blockquote>\n<pre><code>$query = &quot;SELECT name, email, dateTime FROM tableData&quot;;\n</code></pre>\n</blockquote>\n<p>There is no indication of how muc. Then there would be no\ndata exists but you should consider limiting data in some manner- either by adding <code>WHERE</code> conditions and/or a <code>LIMIT</code> clause. Otherwise selecting all rows has the potential to take a large amount of time.</p>\n<h2>String interpolation</h2>\n<p>The line to add the <em>from</em> header:</p>\n<blockquote>\n<pre><code>$headers = &quot;From: $fromName&quot; . &quot; &lt;&quot; . $from . &quot;&gt;&quot;;\n</code></pre>\n</blockquote>\n<p>Uses string interpolation. That could be simplified to:</p>\n<pre><code>$headers = &quot;From: $fromName &lt;$from&gt;&quot;;\n</code></pre>\n<h2>conditionals</h2>\n<p>I see this:</p>\n<blockquote>\n<pre><code>if (!empty($file) &gt; 0) {\n if (is_file($file)) {\n</code></pre>\n</blockquote>\n<p><a href=\"https://www.php.net/empty\" rel=\"nofollow noreferrer\"><code>empty()</code></a> returns a <code>bool</code>, so to compare a negated <code>bool</code> “greater than zero” seems like a convoluted comparison but would function. It would be simpler to just see if it is <code>true</code> so the type does not need to be converted:</p>\n<pre><code>if (!empty($file) === true) {\n</code></pre>\n<p>Though with PHP this can be written simply as:</p>\n<pre><code>if (!empty($file)) {\n</code></pre>\n<p>Then the next conditional can be combined using logical AND - i.e. <code>&amp;&amp;</code></p>\n<pre><code>if (!empty($file) &amp;&amp; is_file($file)) {\n</code></pre>\n<p>This will keep indentation levels minimized.</p>\n<p>After inspecting the return value of <code>fileName()</code> and how <code>$file</code> is not modified from the original value returned from that function, the first conditional expression seems pointless. It would make sense to have it if the value could change.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T18:15:45.680", "Id": "494573", "Score": "0", "body": "This is great information. Thanks for taking time to evaluate and point out parts that can be improved. The idea behind the data limitation would be a SQL query that would take the date the script runs (Managed by a cron job) and subtract X amount of days to only reveal the data from a specific time, using the dateTime field in the SQL table (which is captured automatically as users publish their data). I hope this script can help others looking for the same functionality." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T18:17:09.653", "Id": "494574", "Score": "0", "body": "You're welcome. Please consider voting on it. [\"_The first thing you should do after reading someone's answer to your question is vote on the answer, like any user with sufficient reputation does. Vote up answers that are helpful, and vote down answers that give poor advice._\"](https://codereview.stackexchange.com/help/someone-answers)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T12:16:58.100", "Id": "251250", "ParentId": "251240", "Score": "2" } } ]
{ "AcceptedAnswerId": "251250", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T04:55:25.403", "Id": "251240", "Score": "4", "Tags": [ "beginner", "php", "mysql", "csv", "email" ], "Title": "Create a CSV from SQL Data and email as attachment using PHP" }
251240
<h1>Description</h1> <p>This is a simple &quot;demo&quot; app designed to help gain familiarity with interacting with an Sqlite database from C#, particularly storing images as blobs. The database has a single table, <code>Contacts</code>, represented by the following table creation SQL:</p> <pre><code>CREATE TABLE &quot;Contacts&quot; ( &quot;id&quot; INTEGER NOT NULL, &quot;name&quot; TEXT NOT NULL, &quot;email&quot; TEXT NOT NULL, &quot;address&quot; TEXT NOT NULL, &quot;phoneNumber&quot; INTEGER NOT NULL, &quot;image&quot; BLOB PRIMARY KEY(&quot;id&quot;) </code></pre> <p>For context, a screenshot of this application is shown below. There may be some UX issues around this design, but that is not so important here as it is only a &quot;prototype&quot; or &quot;demo&quot; app, and the idea is to implement the database interaction code.</p> <p><a href="https://i.stack.imgur.com/yQzRx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yQzRx.png" alt="enter image description here" /></a></p> <h1>Code</h1> <p>The code uses the repository and data access object patterns.</p> <h2>Contact.cs</h2> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Drawing; namespace SqliteImageTest { public class Contact { public int id { get; set; } public string name { get; set; } public string email { get; set; } public string address { get; set; } public long phoneNumber { get; set; } public Image photo { get; set; } } } </code></pre> <h2>DataAccessObject.cs</h2> <p>Implements CRUD operations.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.Sql; using System.Drawing; using System.IO; using Microsoft.Data.Sqlite; namespace SqliteImageTest { public interface IDataAccessObject { void create(Contact newContact); IEnumerable&lt;Contact&gt; read(); void update(Contact contact); void delete(int id); } public class DataAccessObject : IDataAccessObject { private readonly string _connString; /// &lt;summary&gt; /// Constructor with connection string. /// &lt;/summary&gt; /// &lt;param name=&quot;connectionString&quot;&gt;&lt;/param&gt; public DataAccessObject(string connectionString) { this._connString = connectionString; } /// &lt;summary&gt; /// Create a new contact record in the database. /// &lt;/summary&gt; /// &lt;param name=&quot;newContact&quot;&gt;Contact object.&lt;/param&gt; public void create(Contact newContact) { // build the query StringBuilder queryBuilder = new StringBuilder(); queryBuilder.AppendLine(&quot;INSERT INTO Contacts (name, email, address, phoneNumber, image)&quot;); queryBuilder.AppendLine(&quot;VALUES ($name, $email, $address, $phoneNumber, $image)&quot;); string query = queryBuilder.ToString(); // execute it using (var conn = new SqliteConnection(this._connString)) { conn.Open(); var cmd = conn.CreateCommand(); cmd.CommandText = query; cmd.Parameters.AddWithValue(&quot;$name&quot;, newContact.name); cmd.Parameters.AddWithValue(&quot;$address&quot;, newContact.address); cmd.Parameters.AddWithValue(&quot;$email&quot;, newContact.email); cmd.Parameters.AddWithValue(&quot;$phoneNumber&quot;, newContact.phoneNumber); if (newContact.photo == null) { cmd.Parameters.AddWithValue(&quot;$image&quot;, DBNull.Value); } else { cmd.Parameters.AddWithValue(&quot;$image&quot;, writeImage(newContact.photo, System.Drawing.Imaging.ImageFormat.Jpeg)); } cmd.ExecuteNonQuery(); } } /// &lt;summary&gt; /// Delete a contact record by its unique ID. /// &lt;/summary&gt; /// &lt;param name=&quot;id&quot;&gt;&lt;/param&gt; public void delete(int id) { // build the query StringBuilder queryBuilder = new StringBuilder(); queryBuilder.AppendLine(&quot;DELETE FROM Contacts&quot;); queryBuilder.AppendLine(&quot;WHERE Contacts.id = $id;&quot;); string query = queryBuilder.ToString(); // execute it using (var conn = new SqliteConnection(this._connString)) { conn.Open(); var cmd = conn.CreateCommand(); cmd.CommandText = query; cmd.Parameters.AddWithValue(&quot;$id&quot;, id); cmd.ExecuteNonQuery(); } } private Image readImage(byte[] imageBytes) { MemoryStream stream = new MemoryStream(imageBytes, 0, imageBytes.Length); stream.Write(imageBytes, 0, imageBytes.Length); Image image = new Bitmap(stream); return image; } private byte[] writeImage(Image image, System.Drawing.Imaging.ImageFormat format) { using (MemoryStream stream = new MemoryStream()) { image.Save(stream, format); byte[] imageBytes = stream.ToArray(); return imageBytes; } } /// &lt;summary&gt; /// Retrieve all contact records from the database. /// &lt;/summary&gt; /// &lt;returns&gt;IEnumerable of Contact objects.&lt;/returns&gt; public IEnumerable&lt;Contact&gt; read() { // build the query string query = &quot;SELECT * FROM Contacts&quot;; // execute it using (var conn = new SqliteConnection(this._connString)) { conn.Open(); var cmd = conn.CreateCommand(); cmd.CommandText = query; SqliteDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { yield return new Contact { id = reader.GetInt32(0), name = reader.GetString(1), email = reader.GetString(2), address = reader.GetString(3), phoneNumber = reader.GetInt64(4), photo = reader.IsDBNull(5) ? null : readImage((byte[])reader[5]) // check if there is an image with this record first }; } } } /// &lt;summary&gt; /// Update a contact record, by its id. /// &lt;/summary&gt; /// &lt;param name=&quot;contact&quot;&gt;Contact object.&lt;/param&gt; public void update(Contact contact) { // build the query StringBuilder queryBuilder = new StringBuilder(); queryBuilder.AppendLine(&quot;UDPATE Contacts&quot;); queryBuilder.AppendLine(&quot;SET name = $name,&quot;); queryBuilder.AppendLine(&quot;email = $email,&quot;); queryBuilder.AppendLine(&quot;address = $address,&quot;); queryBuilder.AppendLine(&quot;phoneNumber = $phoneNumber,&quot;); queryBuilder.AppendLine(&quot;image = $image&quot;); queryBuilder.AppendLine(&quot;WHERE id = $id&quot;); string query = queryBuilder.ToString(); // execute it using (var conn = new SqliteConnection(this._connString)) { conn.Open(); var cmd = conn.CreateCommand(); cmd.CommandText = query; cmd.Parameters.AddWithValue(&quot;$id&quot;, contact.id); cmd.Parameters.AddWithValue(&quot;$name&quot;, contact.name); cmd.Parameters.AddWithValue(&quot;$email&quot;, contact.email); cmd.Parameters.AddWithValue(&quot;$address&quot;, contact.address); cmd.Parameters.AddWithValue(&quot;$phoneNumber&quot;, contact.phoneNumber); if (contact.photo == null) { cmd.Parameters.AddWithValue(&quot;$image&quot;, DBNull.Value); } else { cmd.Parameters.AddWithValue(&quot;$image&quot;, writeImage(contact.photo, System.Drawing.Imaging.ImageFormat.Jpeg)); } cmd.ExecuteNonQuery(); } } } } </code></pre> <h2>Repository.cs</h2> <p>This class might be unit-tested. It has two constructors, one used to instantiate it in the &quot;production&quot; code, and the other for unit-testing which will get a mock or fake of the data access object. However, no unit tests were written yet, as they would be rather trivial for its current set of methods. In the future, methods with more complex logic interacting with the data access layer might be written.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SqliteImageTest { public interface IRepository { IEnumerable&lt;Contact&gt; getAll(); Contact getById(int id); void insert(Contact newContact); void update(Contact contact); void deleteById(int id); } public class Repository : IRepository { private readonly IDataAccessObject _dataAccessObject; /// &lt;summary&gt; /// Production constructor. /// &lt;/summary&gt; /// &lt;param name=&quot;connectionString&quot;&gt;&lt;/param&gt; public Repository(string connectionString) { this._dataAccessObject = new DataAccessObject(connectionString); } /// &lt;summary&gt; /// Test constructor. /// &lt;/summary&gt; /// &lt;param name=&quot;dataAccessObject&quot;&gt;Intended to be a mock or fake.&lt;/param&gt; public Repository(IDataAccessObject dataAccessObject) { this._dataAccessObject = dataAccessObject; } /// &lt;summary&gt; /// Ask the data access object to delete the record with this id. /// &lt;/summary&gt; /// &lt;param name=&quot;id&quot;&gt;&lt;/param&gt; public void deleteById(int id) { this._dataAccessObject.delete(id); } /// &lt;summary&gt; /// Ask the data access object for all records. /// &lt;/summary&gt; /// &lt;returns&gt;IEnumerable of Contact objects.&lt;/returns&gt; public IEnumerable&lt;Contact&gt; getAll() { return this._dataAccessObject.read(); } /// &lt;summary&gt; /// Retrieve one contact record, by its unique id. /// &lt;/summary&gt; /// &lt;param name=&quot;id&quot;&gt;Unique id as stored in the database.&lt;/param&gt; /// &lt;returns&gt;Contact object.&lt;/returns&gt; public Contact getById(int id) { return (this._dataAccessObject.read()).Where(c =&gt; c.id == id).FirstOrDefault(); // note there should only be one record with a particular ID } /// &lt;summary&gt; /// Create a new contact record. /// &lt;/summary&gt; /// &lt;param name=&quot;newContact&quot;&gt;Contact object.&lt;/param&gt; public void insert(Contact newContact) { this._dataAccessObject.create(newContact); } /// &lt;summary&gt; /// Update a contact record, by its id. /// &lt;/summary&gt; /// &lt;param name=&quot;contact&quot;&gt;Contact object.&lt;/param&gt; public void update(Contact contact) { this._dataAccessObject.update(contact); } } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T13:39:39.577", "Id": "494536", "Score": "0", "body": "What's the Target Framework(s)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T19:55:46.317", "Id": "494582", "Score": "0", "body": "@Johnbot .NET Framework 4.6.1" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T20:04:05.017", "Id": "494584", "Score": "0", "body": "Why don't you use https://github.com/StackExchange/Dapper ? Why do `string query = queryBuilder.ToString();`? Methods should be PascalCased, ditto public properties." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T20:15:33.707", "Id": "494588", "Score": "0", "body": "@BCdotWEB I guess the point of this exercise was to do it using \"first principles\". Regarding the casing of the members, I guess it is convention, but personally I prefer to differentiate between class names and members." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T10:56:28.687", "Id": "251247", "Score": "2", "Tags": [ "c#", "object-oriented", ".net", "sqlite", "repository" ], "Title": "Simple Sqlite-driven WinForms app in C# 7.0 - database interaction code" }
251247
<p>I am trying to do multiple queries in one call, so I organized my code as below:</p> <pre><code>try{ $query = $this-&gt;conn-&gt;begin_transaction(); $query = $this-&gt;conn-&gt;prepare(&quot;INSERT INTO table1(xx, xxx, xxxx, xxxxx, xxxxxx, xxxxxxx, xxxxxxxx, xxxxxxxxx, xxxxxxxxxx, xxxxxxxxxxx, xxxxxxxxxxx) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)&quot;); $query-&gt;bind_param(&quot;sssssssssss&quot;, $var1, $var2, $var3, $var4, $var5, $var6, $var7, $var8, $var8, $var9, $var10); $result1 = $query-&gt;execute(); $var1= $xxx- $xxxx; $query = $this-&gt;conn-&gt;prepare(&quot;UPDATE table2 set xxx = ? WHERE xxxx = ?&quot;); $query-&gt;bind_param(&quot;ss&quot;, $var1, $var2); $result2 = $query-&gt;execute(); $query = $this-&gt;conn-&gt;prepare(&quot;INSERT INTO table3 (xx, xxx, xxxx, xxxxx, xxxxxx, xxxxxxx) VALUES (?, ?, ?, ?, ?, ?) &quot;); $query-&gt;bind_param(&quot;ssssss&quot;, $var1, $var2, $var3, $var4, $var5, $var6); $result3 = $query-&gt;execute(); $query = $this-&gt;conn-&gt;commit(); if($result1 == true AND $result2 == true AND $result3 == TRUE){ return &quot;Success&quot;; } exit(); }catch (Exception $e){ $this-&gt;conn-&gt;rollback(); throw $e; } </code></pre> <p>Not sure if this is the correct way of doing it, but I don't want to insert/update records in the database if all queries are not true. It would help me a lot if someone can go through the code and tell me his thoughts, this works fine but I am not sure if this is a good approach.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T19:29:00.713", "Id": "494580", "Score": "2", "body": "This seems correct to me, in theory." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T20:05:50.890", "Id": "494585", "Score": "0", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T20:06:45.553", "Id": "494586", "Score": "1", "body": "Code Review requires concrete code from a project, with sufficient context for reviewers to understand how that code is used. Obfuscated code and generic best practices are outside the scope of this site. Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T11:35:59.087", "Id": "251248", "Score": "2", "Tags": [ "php", "transactions" ], "Title": "Correct way of doing transactional queries" }
251248
<p>I'm willing to check an an object's values in typescript, based on another object's keys. The mental model is &quot;the key exists, it's not an object, is the value in obj set, otherwise, it's an object, iterate again&quot;.</p> <p>What would be your recommandations about this simple snippet :</p> <pre class="lang-js prettyprint-override"><code>/** * Returns an array. If the array is empty, the checked obj is fine. * Otherwise it's not. * * @remarks * areValuesSet(obj, rules).length === 0 is the test to make. * * @param obj {object} - object to verify * @param rules {object} - object containing the keys to check against * @returns {string[]} - array of incorrect keys */ const areValuesSet = ( obj: { [propKey: string]: any }, rules: { [propKey: string]: any } ): string[] =&gt; Object.keys(rules).reduce((prev, key) =&gt; { if (typeof rules[key] === &quot;object&quot; &amp;&amp; typeof obj[key] === &quot;object&quot;) { return areValuesSet(obj[key], rules[key]); } return !obj || !obj[key] || (isEmpty(obj[key]) &amp;&amp; typeof obj[key] !== 'boolean') ? [...prev, key] : [...prev]; }, []); </code></pre> <p>I would enhance this with a &quot;validator&quot; function which would call <code>areValuesSet</code> like so :</p> <pre class="lang-js prettyprint-override"><code>/** * Call `rulesParser` and checks the returned value length equals 0 * * @param obj {object} - object to verify * @param rulesObj {object} - object containing the keys to check against * @returns {boolean} */ export const validateRules = ( obj: { [propKey: string]: any }, rulesObj: { [propKey: string]: any } ): boolean =&gt; rulesParser(obj, rulesObj).length === 0; </code></pre> <p>Thank you</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T18:24:26.550", "Id": "494576", "Score": "0", "body": "To validate, are you hoping that all primitive values in the input (possibly nested inside objects) are *numbers*? Is that the logic you wish to perform?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T08:33:27.750", "Id": "494625", "Score": "0", "body": "No I want to have primitives with no empty value." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T10:49:31.530", "Id": "494632", "Score": "0", "body": "I updated with lodash.isempty" } ]
[ { "body": "<p><strong>Function and parameter names</strong> The function name <code>areValuesSet</code> could be more precise. It returns an array of incorrect property names, not a boolean of if values are set. Maybe call it <code>getIncorrectProperties</code>? Also, the argument named <code>obj</code> is uninformative. You want to indicate that it's the target value being checked. Maybe call it <code>validateTarget</code> or something similar.</p>\n<p><strong>Avoid <code>any</code></strong> <code>any</code> is type-unsafe. Unless you have a really good reason for it, better to type something you don't know about as <code>unknown</code> instead. <code>unknown</code> is similar to <code>any</code>, but requires you to do type-narrowing first. In this case, using <code>unknown</code> will point out a bug in your current logic:</p>\n<p><strong>typeof null gives object</strong> You have:</p>\n<pre><code>if (typeof rules[key] === &quot;object&quot; &amp;&amp; typeof obj[key] === &quot;object&quot;) {\n return areValuesSet(obj[key], rules[key]);\n}\n</code></pre>\n<p>This will result in the recursive call throwing if one of the values happens to be <code>null</code>, since <code>null</code> is an object. Add in and call:</p>\n<pre><code>const isObject = (arg: unknown) =&gt; typeof arg === 'object' &amp;&amp; arg !== null;\n</code></pre>\n<p><strong><code>!obj[key]</code> excludes <code>false</code></strong> Your current logic permits values of <code>true</code> but forbids values of <code>false</code> due to this check:</p>\n<pre><code>!obj[key] || (isEmpty(obj[key]) &amp;&amp; typeof obj[key] !== 'boolean')\n</code></pre>\n<p>Is that deliberate? It's OK if it is, but it may well be a logic bug. If <code>false</code> should indeed be excluded, then <code>typeof obj[key] !== 'boolean'</code> simplifies to <code>obj[key] !== true</code>.</p>\n<p><strong>Nested property bugs</strong></p>\n<p>(1) The recursive call is only entered if <em>both</em> the rules and target are objects. If the rule is an object, and the target is a non-empty non-object, the target will pass, when it probably shouldn't. Eg:</p>\n<pre><code>// rules:\n{\n prop: { val: 'val' }\n}\n\n// target:\n{\n prop: 'foo'\n}\n</code></pre>\n<p>should probably fail, but won't. If the rule is an object and the target value is not an object, you probably want to push the property to the array of errors.</p>\n<p>(2) When a sub-object is found as a value, your <code>reduce</code> callback does:</p>\n<pre><code>return areValuesSet(obj[key], rules[key]);\n</code></pre>\n<p>Whatever may have been put into the accumulator array on prior iterations will be lost, since it's not being factored into the return value. For example, if you had a data structure for which the first 5 properties were wrong, but the 6th property is nested and correct, the function would return an empty array.</p>\n<p>But <code>reduce</code> arguably <a href=\"https://www.youtube.com/watch?v=qaGjS7-qWzg\" rel=\"nofollow noreferrer\">isn't very appropriate</a> in these sorts of situations anyway - see that link for a video by Chrome developers on the subject. It introduces an annoying amount of boilerplate code, especially in TS, and even well-formulated <code>reduce</code>s like these often aren't entirely trivial to understand at a glance.</p>\n<p>Consider creating an array outside the function and pushing to it instead - or use a recursive function which creates the array to return as a default argument when not passed. Including all the other suggestions as well:</p>\n<pre><code>type GenericObj = { [propKey: string]: unknown };\nconst isObject = (arg: unknown): arg is GenericObj =&gt; typeof arg === 'object' &amp;&amp; arg !== null;\n\nconst getIncorrectProperties = (\n validateTarget: GenericObj,\n rules: GenericObj,\n incorrectProperties: string[] = [],\n) =&gt; {\n for (const [key, ruleValue] of Object.entries(rules)) {\n const targetValue = validateTarget[key];\n if (isObject(ruleValue)) {\n if (!isObject(targetValue)) {\n incorrectProperties.push(key);\n } else {\n getIncorrectProperties(targetValue, ruleValue, incorrectProperties);\n }\n } else if (!targetValue || (isEmpty(targetValue) &amp;&amp; targetValue !== true)) {\n incorrectProperties.push(key);\n }\n }\n return incorrectProperties;\n};\n</code></pre>\n<p>Live snippet of compiled code including example validation, to show that it's working:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>\"use strict\";\nconst isObject = (arg) =&gt; typeof arg === 'object' &amp;&amp; arg !== null;\nconst getIncorrectProperties = (validateTarget, rules, incorrectProperties = []) =&gt; {\n for (const [key, ruleValue] of Object.entries(rules)) {\n const targetValue = validateTarget[key];\n if (isObject(ruleValue)) {\n if (!isObject(targetValue)) {\n incorrectProperties.push(key);\n }\n else {\n getIncorrectProperties(targetValue, ruleValue, incorrectProperties);\n }\n }\n else if (!targetValue || (_.isEmpty(targetValue) &amp;&amp; targetValue !== true)) {\n incorrectProperties.push(key);\n }\n }\n return incorrectProperties;\n};\nconsole.log(getIncorrectProperties({\n prop2: {\n nested: 'val',\n }\n}, {\n prop1: true,\n prop2: {\n nested: true,\n nested2: {\n deeplyNested: true\n }\n },\n prop3: true\n}));</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js\"&gt;&lt;/script&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>The only issue I have with the above code is the <code>incorrectProperties</code> argument. Although the approach works to create an array on initial call and return it at the end, having it as a parameter might be confusing, since the initial call should not take 3 arguments, only 2. If you think that's not acceptable, you could create an array in the function body on every call and return it at the end, and spread the result of the recursive call into that array.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-30T05:20:18.747", "Id": "494701", "Score": "0", "body": "Thank you, clear solution. I'm being more aware that I'm over using reduce method. Btw, I opt for a function scoped declaration of `incorrectProperties `. Thank you again" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T15:28:57.653", "Id": "251305", "ParentId": "251251", "Score": "3" } } ]
{ "AcceptedAnswerId": "251305", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T14:17:19.217", "Id": "251251", "Score": "3", "Tags": [ "validation", "typescript" ], "Title": "Checking Object keys set with value against another Object keys" }
251251
<p>I have recently started learning Java and decided to make a basic MDAS calculator in Swing. I am not completely new to programming but I may be making some common mistakes, or not writing the most efficient code.</p> <p>I wanted to make a calculator that can take multiple numbers and operations before finding the answer using MDAS, instead of just returning the answer after every operation and using it for the next.</p> <p><em>e.g.</em> <code>2 * 3 + 4 - 5 / 5 =</code> <strong>9</strong> instead of <strong>1</strong></p> <p>My code consists of a single class. There isn't much code so I didn't know if there was a good reason to split it into multiple classes, however I have never written something like this so please feel free to correct me.</p> <p><a href="https://github.com/RazerMoon/Basic-MDAS-Java-Calculator" rel="nofollow noreferrer">Repo with example gif and runnable jar</a></p> <hr /> <pre><code>package calculator; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.util.ArrayList; import javax.swing.AbstractAction; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class GUI extends JFrame { private static final long serialVersionUID = 1L; private String title = &quot;Basic MDAS Calculator&quot;; private int currentNumber; private JLabel displayLabel = new JLabel(String.valueOf(currentNumber), JLabel.RIGHT); private JPanel panel = new JPanel(); private boolean isClear = true; final String[] ops = new String[] {&quot;+&quot;, &quot;-&quot;, &quot;x&quot;, &quot;/&quot;}; private ArrayList&lt;Integer&gt; numHistory = new ArrayList&lt;Integer&gt;(); private ArrayList&lt;String&gt; opHistory = new ArrayList&lt;String&gt;(); public GUI() { setPanel(); setFrame(); } private void setFrame() { this.setTitle(title); this.add(panel, BorderLayout.CENTER); this.setBounds(10,10,300,700); this.setResizable(false); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } private void setPanel() { panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); panel.setLayout(new GridLayout(0, 1)); displayLabel.setFont(new Font(&quot;Verdana&quot;, Font.PLAIN, 42)); panel.add(displayLabel); panel.add(Box.createRigidArea(new Dimension(0, 0))); createButtons(); } private void createButtons() { // 0-9 for (int i = 0; i &lt; 10; i++) { final int num = i; JButton button = new JButton( new AbstractAction(String.valueOf(i)) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { // If somebody presses &quot;=&quot; and then types a number, start a new equation instead // of adding that number to the end like usual if (!isClear) { currentNumber = 0; isClear = true; } if (currentNumber == 0) { currentNumber = num; } else { currentNumber = currentNumber * 10 + num; } displayLabel.setText(String.valueOf(currentNumber)); } }); panel.add(button); } // +, -, x, / for (String op : ops) { JButton button = new JButton( new AbstractAction(op) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { numHistory.add(currentNumber); currentNumber = 0; opHistory.add(op); displayLabel.setText(op); } }); panel.add(button); } // = JButton button = new JButton( new AbstractAction(&quot;=&quot;) { private static final long serialVersionUID = 1L; private int i; @Override public void actionPerformed(ActionEvent e) { // Display result numHistory.add(currentNumber); while (opHistory.size() &gt; 0) { if (opHistory.contains(&quot;x&quot;)) { i = opHistory.indexOf(&quot;x&quot;); numHistory.set(i, numHistory.get(i) * numHistory.get(i+1)); } else if (opHistory.contains(&quot;/&quot;)) { i = opHistory.indexOf(&quot;/&quot;); numHistory.set(i, numHistory.get(i) / numHistory.get(i+1)); } else if (opHistory.contains(&quot;+&quot;)) { i = opHistory.indexOf(&quot;+&quot;); numHistory.set(i, numHistory.get(i) + numHistory.get(i+1)); } else if (opHistory.contains(&quot;-&quot;)) { i = opHistory.indexOf(&quot;-&quot;); numHistory.set(i, numHistory.get(i) - numHistory.get(i+1)); } opHistory.remove(i); numHistory.remove(i+1); } displayLabel.setText(String.valueOf(numHistory.get(0))); currentNumber = numHistory.get(0); numHistory.clear(); if (isClear) { isClear = false; } } }); panel.add(button); } public static void main(String[] args) { new GUI(); } } </code></pre> <p>I would appreciate any tips.</p> <p><a href="https://i.stack.imgur.com/pn27W.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pn27W.gif" alt="Example calculation" /></a></p>
[]
[ { "body": "<pre class=\"lang-java prettyprint-override\"><code>package calculator;\n</code></pre>\n<p>Package names should associate the software with the author, like <code>com.github.razemoon.basicmdasjavacaluclator</code>.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>public class GUI extends JFrame {\n</code></pre>\n<p>For Java nming conventions, you'd normally use UpperCamelCase, and use lowercase even for acronyms, like &quot;Gui&quot;, &quot;HtmlWidgetToolkit&quot; or &quot;HtmlCssParser&quot;.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>private static final long serialVersionUID = 1L;\n</code></pre>\n<p>You only need this field if it is highly likely that the class will be serialized...in this case, most likely not.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>final String[] ops = new String[] {&quot;+&quot;, &quot;-&quot;, &quot;x&quot;, &quot;/&quot;};\n</code></pre>\n<p>Why is this <code>package-private</code>?</p>\n<p>Also, <code>final</code> arrays are not as <code>final</code> as you'd think, the individual values can still be changed. You most likely want an Enum....actually, you want an interface, but in this example, an Enum would most likely do fine enough.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> private ArrayList&lt;Integer&gt; numHistory = new ArrayList&lt;Integer&gt;();\n private ArrayList&lt;String&gt; opHistory = new ArrayList&lt;String&gt;();\n</code></pre>\n<p>Always try to use the lowest common interface for declarations, in this case <code>List</code>.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> private void setFrame() {\n this.setTitle(title);\n this.add(panel, BorderLayout.CENTER);\n this.setBounds(10,10,300,700); \n this.setResizable(false);\n this.setVisible(true);\n this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n }\n</code></pre>\n<p>Why are you using <code>this</code> here but nowhere else?</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> this.setResizable(false);\n</code></pre>\n<p>Why? Your frame is perfectly resizable as far as I can see. By setting it not-resizable you only make sure that your application becomes unusable under different LaFs and font-sizes.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>for (int i = 0; i &lt; 10; i++) {\n</code></pre>\n<p>I'm a very persistent advocate for that you're only allowed to use single-letter variable names if your dealing with dimensions.</p>\n<pre class=\"lang-java prettyprint-override\"><code>for (int number = 0; number &lt;= 9; number++) {\n// Or\nfor (int digit = 0; digit &lt;= 9; digit++) {\n</code></pre>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>final int num = i;\n</code></pre>\n<p>Don't shorten variable names just because you can, the decreased amount of typing is not worth the decreased readability.</p>\n<hr />\n<p>Regarding the creation of buttons, I like to create helper methods and classes which make the code easier to read, in this case I'd go for lambdas, like this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>private JButton createButton(String text, Runnable action) {\n return new JButton(new AbstractButton(text) {\n @Override\n public void actionPerformed(ActionEvent e) {\n action.run();\n }\n })\n}\n\n// In createButtons:\n\npanel.add(createButton(Integer.toString(number), () -&gt; {\n // Code for the number button goes here.\n}));\n</code></pre>\n<p>Another alternative would be to create a <code>private class NumberAction</code> which accepts a number in its constructor and performs the associated action. That would also allow you to get rid of the final-redeclaration.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>private int i;\n</code></pre>\n<p>That;s a very bad variable name.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> public GUI() {\n setPanel();\n setFrame();\n }\n \n private void setFrame() {\n this.setTitle(title);\n this.add(panel, BorderLayout.CENTER);\n this.setBounds(10,10,300,700); \n this.setResizable(false);\n this.setVisible(true);\n this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n }\n\n// ...\n\n public static void main(String[] args) {\n new GUI();\n }\n</code></pre>\n<p>It would be better to split the responsibilities here. The frame itself is only responsible with getting its own layout going, while the main method should be responsible for getting the frame displayed.</p>\n<pre class=\"lang-java prettyprint-override\"><code> public GUI() {\n setPanel();\n setFrame();\n }\n \n private void setFrame() {\n this.setTitle(title);\n this.add(panel, BorderLayout.CENTER);\n this.setBounds(10,10,300,700); \n this.setResizable(false);\n }\n\n// ...\n\n public static void main(String[] args) {\n GUI gui = new GUI();\n gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n gui.setVisible(true);\n }\n</code></pre>\n<hr />\n<p>Your logic does not seem to contain any sort of error handling, I believe pressing an operator button twice in succession should yield an error.</p>\n<hr />\n<p>Maybe a better approach would be to print the whole expression to the screen as entered, and then apply the <a href=\"https://en.wikipedia.org/wiki/Shunting-yard_algorithm\" rel=\"noreferrer\">Shunting Yard Algorithm</a> to process that expression.</p>\n<hr />\n<p>Your logic doesn't do decimals, neither does it gracefully handle overflows. By changing your logic yo use <code>BigDecimal</code>s you could handle both easily. Note that you must create <code>BigDecimal</code>s with an appropriate <code>MathContext</code> to have proper accuracy and behavior.</p>\n<hr />\n<p>If you want read an already existing implementation, I can recommend <a href=\"https://github.com/fasseg/exp4j\" rel=\"noreferrer\">exp4j</a> for a math-expression library using floats, <a href=\"https://github.com/uklimaschewski/EvalEx\" rel=\"noreferrer\">EvalEx</a> for one using <code>BigDecimal</code>, and my own project <a href=\"https://gitlab.com/RobertZenz/jMathPaper/\" rel=\"noreferrer\">jMathPaper</a> for a calculator which sport different GUIs (regarding abstraction).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T17:28:03.013", "Id": "494567", "Score": "0", "body": "Thank you very much for all the feedback! Especially the lambdas approach. I will make sure to check out the implementations you have sent too.\n\nPressing an operator button twice in succession didn't cause an exception in my simple testing, so I didn't bother to implement an error message (lazy) and thought the user would notice their mistake when they would get a result of 0. However, I did recently notice the fact that dividing twice will return a \"/ by zero\" exception (oversight) so I should have implemented it anyway. Again, thank you very much." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T16:41:13.377", "Id": "251259", "ParentId": "251252", "Score": "5" } }, { "body": "<h2>You can use the array declaration.</h2>\n<p>When you want an array with pre-defined values that can be constant, you can declare the array anonymously.</p>\n<pre class=\"lang-java prettyprint-override\"><code> final String[] ops = {&quot;+&quot;, &quot;-&quot;, &quot;x&quot;, &quot;/&quot;};\n</code></pre>\n<h2>Use Enums for the operations.</h2>\n<p>Instead of having an array of operation, I suggest that you create an Enum instead.</p>\n<pre class=\"lang-java prettyprint-override\"><code>public enum Operators {\n PLUS(&quot;+&quot;), MINUS(&quot;-&quot;), MUL(&quot;x&quot;), DIV(&quot;/&quot;);\n private final String operator;\n Operators(String operator) {\n this.operator = operator;\n }\n public String getOperator() {\n return operator;\n }\n}\n</code></pre>\n<p>This will give you more advantage than the array, since you will be able to remove the duplication.</p>\n<pre class=\"lang-java prettyprint-override\"><code>//[...]\nfor (Operators op : Operators.values()) {\n JButton button = new JButton( new AbstractAction(op.getOperator()) {\n private static final long serialVersionUID = 1L;\n\n @Override\n public void actionPerformed(ActionEvent e) {\n numHistory.add(currentNumber);\n currentNumber = 0;\n\n opHistory.add(op);\n displayLabel.setText(String.valueOf(op.getOperator()));\n }\n });\n panel.add(button);\n}\n//[...]\n</code></pre>\n<pre class=\"lang-java prettyprint-override\"><code>//[...]\nif (opHistory.contains(Operators.MUL)) {\n i = opHistory.indexOf(Operators.MUL);\n numHistory.set(i, numHistory.get(i) * numHistory.get(i + 1));\n} else if (opHistory.contains(Operators.DIV)) {\n i = opHistory.indexOf(Operators.DIV);\n numHistory.set(i, numHistory.get(i) / numHistory.get(i + 1));\n} else if (opHistory.contains(Operators.PLUS)) {\n i = opHistory.indexOf(Operators.PLUS);\n numHistory.set(i, numHistory.get(i) + numHistory.get(i + 1));\n} else if (opHistory.contains(Operators.MINUS)) {\n i = opHistory.indexOf(Operators.MINUS);\n numHistory.set(i, numHistory.get(i) - numHistory.get(i + 1));\n}\n//[...]\n</code></pre>\n<p>Also, in my opinion, this will make the code easier to work with and refactor.</p>\n<h2>When dividing, always check the <code>divisor</code> before doing the division.</h2>\n<p>When dividing by zero, there an <code>java.lang.ArithmeticException</code> throw by java; I suggest that you add a check :)</p>\n<h2>Use the <code>Queue</code> instead of the <code>List</code> to keep the history.</h2>\n<p>By using the <code>List</code> you have to use an index, the <code>Queue</code> to remove the first item (<a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Queue.html#poll()\" rel=\"nofollow noreferrer\"><code>java.util.Queue#poll</code></a>); the only drawback, you will need to refactor the actual code to remove the <code>indexOf</code>.</p>\n<pre class=\"lang-java prettyprint-override\"><code>private Queue&lt;String&gt; opHistory = new ArrayDeque&lt;&gt;();\n</code></pre>\n<p>By doing so, you will make the code shorter.</p>\n<pre class=\"lang-java prettyprint-override\"><code>while (opHistory.size() &gt; 0) {\n Operators currentOperator = opHistory.poll();\n\n switch (currentOperator) { //Java 14+ Switch, you can use if or the older version of the switch.\n case MUL -&gt; numHistory.set(i, numHistory.get(i) * numHistory.get(i+1));\n case DIV -&gt; numHistory.set(i, numHistory.get(i) / numHistory.get(i+1));\n case PLUS -&gt; numHistory.set(i, numHistory.get(i) + numHistory.get(i+1));\n case MINUS -&gt; numHistory.set(i, numHistory.get(i) - numHistory.get(i+1));\n }\n\n numHistory.remove(i + 1);\n}\n</code></pre>\n<h2>Extract the expression to variables when used multiple times.</h2>\n<p>In your code, you can extract the similar expressions into variables; this will make the code shorter and easier to read.</p>\n<pre class=\"lang-java prettyprint-override\"><code>final Integer first = numHistory.get(i);\nfinal Integer second = numHistory.get(i + 1);\nswitch (currentOperator) {\n case MUL -&gt; numHistory.set(i, first * second);\n case DIV -&gt; numHistory.set(i, first / second);\n case PLUS -&gt; numHistory.set(i, first + second);\n case MINUS -&gt; numHistory.set(i, first - second);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T21:33:17.780", "Id": "251272", "ParentId": "251252", "Score": "4" } } ]
{ "AcceptedAnswerId": "251259", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T14:35:11.010", "Id": "251252", "Score": "7", "Tags": [ "java", "calculator", "swing" ], "Title": "Basic MDAS Java Swing Calculator" }
251252
<p>The prompt is as follows: This script will use a text menu to give the user options. The options will include the ability to add grades of different types as well as an option to print the current grades and average. Types of grades are tests, quizzes, and assignments. For the final average, the tests and assignments count 40% each and the quizzes make up the remaining 20%. The lowest quiz grade should be dropped. The menu will have numbers by each option and users enter a number to select that option. Note: grades are the numbers obtained (i.e. 0 to 100)</p> <p>I have written the following code:</p> <pre><code> import io.StdIn._ //global var for grades, implemented as Lists so that updating is easier and efficient var testList: List[Int] = Nil var assignmentList:List[Int] = Nil var quizList: List[Int] = Nil //boolean variable to run program in a loop var is_over: Boolean = false while (!is_over) { //display menu to let the user choose from the options println(&quot;Choose an option from below\n1. Add grades\n2. Get grades and average\n3. Exit program &quot;) val chosenOption: Int = readInt() //match to call the functions according to user selection chosenOption match { case 1 =&gt; println(&quot;\nWhich type of grade do you want to enter?\n1. Test\n2. Quiz\n3. Assignment&quot;) returnGrades(readInt()) //pass the option for the type of grade to add case 2 =&gt; outputGrades() case 3 =&gt; is_over = true //option 3 will exit the program case _ =&gt; println(&quot;Invalid option&quot;) } } def returnGrades(option$:Int):Unit = { //tell the user that while building the list, they enter -1 to exit building the list println(&quot;\nEnter grades, \&quot;-1\&quot; to exit\n &quot;) //match to add grades of a specific type option$ match { case 1 =&gt; testList = buildList() case 2 =&gt; quizList = buildList() case 3 =&gt; assignmentList = buildList() case _ =&gt; println(&quot;Error in value entered&quot;) } println(&quot;-&quot;*40) } //recursive function to build a list def buildList():List[Int] = { val x: Int = readInt() if (x &lt; -1 || x&gt;100) { print(&quot;Invalid entry. Re-enter: &quot;) buildList() } else if (x == -1) { Nil } else x::buildList() } def outputGrades():Unit= { //output current grades with .mkString println(&quot;Grades for tests are : &quot; + testList.mkString(&quot;\t&quot;)) println(&quot;Grades for quizzes are : &quot; + newQuizList().mkString(&quot;\t&quot;)) println(&quot;Grades for assignments are: &quot; + assignmentList.mkString(&quot;\t&quot;)) val x:Double = 0.4 * calculateAverage(testList) + 0.4 * calculateAverage(assignmentList) + 0.2 * calculateAverage(quizList) println(&quot;Average is: &quot; + x ) println(&quot;-&quot;*40) } //function for quizList so that the program does not returns an error if you use .min method on an empty list. def newQuizList():List[Int] = {if (quizList.nonEmpty) quizList diff List(quizList.min) else Nil} def calculateAverage(lst:List[Int]):Double = {if (lst.isEmpty) 0 else lst.sum/lst.length} </code></pre> <p>Are there perhaps more efficient ways to achieve the same goal?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T14:46:17.977", "Id": "251253", "Score": "2", "Tags": [ "linked-list", "scala" ], "Title": "Grading script in SCALA" }
251253
<p>As I asked a question <a href="https://cs.stackexchange.com/questions/131632/serving-k-customers-with-bounded-time-window">here</a>, I want to write a python code for the following problem:</p> <p>A person provides a service and he/she can serve <span class="math-container">\$k\$</span> clients each minute. Now, client number <span class="math-container">\$i\$</span> comes at the beginning of minute <span class="math-container">\$ a_{i} \$</span> and waits <span class="math-container">\$w_{i}\$</span> minutes to receive the service and if they don't receive the service in the interval <span class="math-container">\$[a_{i}, a_{i} + w_{i}]\$</span>, they leave. If we have <span class="math-container">\$n\$</span> clients, can the person serve all them or not?</p> <p>Now, by the answer stated there, I wrote the following code.</p> <pre><code>intervals = [] # Some intervals like [[1, 2], [1, 100], [1, 1], [5, 20]] intervals = sorted(intervals) start = intervals[0][0] end = intervals[-1][1] i = start while i &lt; end: if not intervals: break else: for j in range(k): try: if intervals[0][0] &lt;= i &lt;= intervals[0][1]: del intervals[0] else: break except: pass i += 1 if not intervals: print('YES') else: print('NO') </code></pre> <p><strong>My question</strong>: Is my code right? Can it become more efficient?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T16:52:50.000", "Id": "494558", "Score": "0", "body": "I'll let one of the python guru's answer the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T16:58:54.563", "Id": "494559", "Score": "0", "body": "Thank you for your help..." } ]
[ { "body": "<ul>\n<li><p><strong>Time complexity</strong> is unnecessarily large.</p>\n<p>First, it is linear in the timespan of the arrivals. A list <code>[[1,2], [100,101]]</code> would require 100 iterations; a list <code>[1,2], [1000,1001]]</code> would require 1000 iterations, etc. Don't bruteforce every minute.</p>\n<p>Second, <code>del intervals[0]</code> has a linear time complexity in number of intervals, which results in an overall quadratic time complexity. A cheap way out is to sort in a descending order, and work right to left. This way you would remove intervals from the tail of the list, which is <code>O(1)</code>.</p>\n</li>\n<li><p><strong>DRY</strong>. A presence of two semantically identical <code>break</code>s (the loop is broken when it runs out of the intervals) suggests refactoring. Do not test for <code>if not intervals</code> explicitly. Consider</p>\n<pre><code> try:\n while i &lt; end:\n for j in range(k):\n if intervals[0][0] &lt;=i &lt;= intervals[0][1]:\n del intervals[0]\n i += 1\n except:\n pass\n</code></pre>\n<p>Of course, never <code>except</code> blindly. Catch only exceptions you expect and know how to handle, in this case <code>except IndexError:</code>.</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T18:22:12.323", "Id": "251264", "ParentId": "251254", "Score": "3" } }, { "body": "<p>By the above instructions, I changed my code as following and it passed all the tests (even time limits exceeded are handled).</p>\n<pre><code>import sys\n\nn, k = [int(i) for i in input().split()]\n\nintervals = ([int(i) for i in input().split()] for i in range(n))\n\nif k &gt;= n:\n print('YES')\n sys.exit()\n\nintervals = sorted(intervals)\nstart = intervals[0][0]\nend = intervals[-1][1]\n\ni = start\n\nwhile i &lt; end:\n\n if intervals[0][1] &lt; i:\n print('NO')\n sys.exit()\n\n elif len(intervals) &lt;= k * (end - i + 1):\n print('YES')\n sys.exit()\n else:\n for j in range(k):\n if intervals[0][0] &lt;= i &lt;= intervals[0][1]:\n del intervals[0]\n else:\n break\n i += 1\n\nif not intervals:\n print('YES')\nelse:\n print('NO')\n</code></pre>\n<p>Thank you all.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-11T09:53:43.173", "Id": "251937", "ParentId": "251254", "Score": "0" } } ]
{ "AcceptedAnswerId": "251264", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T15:15:28.413", "Id": "251254", "Score": "3", "Tags": [ "algorithm", "python-3.x" ], "Title": "Python code for serving k customers with bounded time window" }
251254
<p>I decided to implement a <code>DisjointSet&lt;T&gt;</code> data structure myself in Rust, with no dependencies except for <code>std</code>, for the challenge and to get better at Rust. I wanted to have as few requirements for <code>T</code> as possible, especially not <code>T: Copy</code>. I also wanted to be able to iterate over subsets easily.</p> <pre><code>use std::{ cell::RefCell, collections::HashSet, iter::ExactSizeIterator, mem, }; /// Represents a disjoint set of various subsets, /// with fast operations to join sets together. /// /// # Example /// ``` /// let mut ds = DisjointSet::new(); /// /// let a = ds.make_set(1).unwrap(); /// let b = ds.make_set(2).unwrap(); /// /// assert!(ds.contains(&amp;1) &amp;&amp; ds.contains(&amp;2)); /// assert_eq!(ds.same_set(a, b), Some(false)); /// assert_eq!(ds.num_sets(), 2); /// /// assert_eq!(ds.union(a, b), Some(true)); /// /// assert_eq!(ds.same_set(a, b), Some(true)); /// assert_eq!(ds.num_sets(), 1); /// ``` // Details about the algorithm used here can be found // at the Wikipedia page for &quot;Disjoint-set data structure&quot;. #[derive(Clone)] pub struct DisjointSet&lt;T: Eq&gt; { roots: HashSet&lt;usize&gt;, nodes: Vec&lt;RefCell&lt;Node&lt;T&gt;&gt;&gt;, } #[derive(Default, Clone)] struct Node&lt;T&gt; { elem: T, parent_idx: usize, rank: usize, // We use this to be able to iterate // on each of our subsets. next: usize, } impl&lt;T: Eq&gt; DisjointSet&lt;T&gt; { /// Creates an empty `DisjointSet`. pub fn new() -&gt; Self { Self { nodes: vec![], roots: HashSet::new(), } } /// Creates a new `DisjointSet` with the given capacity. pub fn with_capacity(capacity: usize) -&gt; Self { Self { nodes: Vec::with_capacity(capacity), roots: HashSet::new(), } } /// Returns the number of subsets. pub fn num_sets(&amp;self) -&gt; usize { self.roots.len() } /// Returns the number of total elements in all subsets. pub fn num_elements(&amp;self) -&gt; usize { self.nodes.len() } /// Returns true if the given element is present in the `DisjointSet`. pub fn contains(&amp;self, elem: &amp;T) -&gt; bool { self.position(elem).is_some() } /// Returns the index of the given element if it exists, or None otherwise. pub fn position(&amp;self, elem: &amp;T) -&gt; Option&lt;usize&gt; { self.nodes.iter().position(|e| &amp;e.borrow().elem == elem) } /// Adds a new set with a single, given element to /// the `DisjointSet`. Returns an Err with the elem /// if it was already present in any set, otherwise /// returns a Ok(usize) with the index of the element. pub fn make_set(&amp;mut self, elem: T) -&gt; Result&lt;usize, T&gt; { if !self.contains(&amp;elem) { // This is the index where the node will be inserted, // thanks to the magic of zero-indexing. let insertion_idx = self.nodes.len(); self.nodes.push(RefCell::new(Node { elem, parent_idx: insertion_idx, rank: 0, next: insertion_idx, })); self.roots.insert(insertion_idx); Ok(insertion_idx) } else { Err(elem) } } /// If present, returns an immutable reference to the element at `elem_idx`. pub fn get(&amp;self, elem_idx: usize) -&gt; Option&lt;&amp;T&gt; { // Nothing in our code actually mutates node.elem: T using &amp;self. // Even find_root_idx uses interior mutability only // to modify node.parent. And the caller can't // call get_mut or iter_mut_set while the &amp;T here is // still in scope. So it all works out! Some(unsafe { &amp;*self.get_raw(elem_idx)? }) } /// If present, returns a mutable reference to the element at `elem_idx`. pub fn get_mut(&amp;mut self, elem_idx: usize) -&gt; Option&lt;&amp;mut T&gt; { // RefCall::get_mut is used rarely, but here it's appropriate: // As long as the &amp;mut T from this is still in scope, // the caller won't be able to use any other methods, // so interior mutability isn't a concern. Some(&amp;mut self.nodes.get_mut(elem_idx)?.get_mut().elem) } /// If present, returns a raw pointer to the element at `elem_idx`. fn get_raw(&amp;self, elem_idx: usize) -&gt; Option&lt;*mut T&gt; { unsafe { Some(&amp;mut (*self.nodes.get(elem_idx)?.as_ptr()).elem as *mut _) } } /// Returns an `&amp;T` iterator over all elements in the set /// elem_idx belongs to, if it exists. // We use both applicable Iterator types here to give the caller // the maximum possible flexbility when using the returned value. pub fn iter_set( &amp;self, elem_idx: usize, ) -&gt; Option&lt;impl ExactSizeIterator&lt;Item = &amp;T&gt; + DoubleEndedIterator&gt; { Some( self.get_set_idxs(elem_idx)? .into_iter() .map(move |i| self.get(i).unwrap()), ) } /// Returns an `&amp;mut T` iterator over all elements in the set /// elem_idx belongs to, if it exists. pub fn iter_mut_set( &amp;mut self, elem_idx: usize, ) -&gt; Option&lt;impl ExactSizeIterator&lt;Item = &amp;mut T&gt; + DoubleEndedIterator&gt; { let set_idxs = self.get_set_idxs(elem_idx)?; Some(set_idxs.into_iter().map(move |i| { // In reality this is safe because there'll // be no duplicate indexes. But Rust doesn't // have any way of knowing that. unsafe { &amp;mut *(self.get_mut(i).unwrap() as *mut _) } })) } pub fn iter_all_sets( &amp;self, ) -&gt; impl ExactSizeIterator&lt;Item = impl ExactSizeIterator&lt;Item = &amp;T&gt; + DoubleEndedIterator&gt; + DoubleEndedIterator { // Put roots into a Vec to satisfy DoubleEndedIterator let roots = self.roots.iter().collect::&lt;Vec&lt;_&gt;&gt;(); roots.into_iter().map(move |&amp;r| self.iter_set(r).unwrap()) } pub fn iter_mut_all_sets( &amp;mut self, ) -&gt; impl ExactSizeIterator&lt;Item = impl ExactSizeIterator&lt;Item = &amp;mut T&gt; + DoubleEndedIterator&gt; + DoubleEndedIterator { // This function can't be as simple as iter_all_sets, // because Rust won't like it if we just straight up take // &amp;mut self several times over. self.roots .iter() .map(|&amp;root| { self.get_set_idxs(root) .unwrap() .into_iter() .map(|i| { // No duplicate indexes means that using this // pointer as a &amp;mut T is safe. We can't // use get_mut here because that takes &amp;mut self. unsafe { &amp;mut *self.get_raw(i).unwrap() } }) .collect::&lt;Vec&lt;_&gt;&gt;() }) // In order to avoid the closures that borrow // self outliving the function itself, we collect // their results and then turn them back into iterators. .collect::&lt;Vec&lt;_&gt;&gt;() .into_iter() .map(|v| v.into_iter()) } /// Returns Some(true) if the elements at both the given indexes /// are in the same set, or None of either of them aren't present altogether. pub fn same_set(&amp;self, elem1_idx: usize, elem2_idx: usize) -&gt; Option&lt;bool&gt; { // The ? ensures this'll short-circuit and return None if either of the indexes are None, // meaning we don't end up returning Some(true) if both elements don't exist. Some(self.find_root_idx(elem1_idx)? == self.find_root_idx(elem2_idx)?) } /// Performs a union for the two sets containing the given elements. /// Returns Some(true) if the operation was performed, Some(false) if not, /// and None if either element doesn't exist. /// /// # Example /// ``` /// let mut ds = DisjointSet::new(); /// /// // Ommitted: adding 5 seperate elements to the set a..e /// # let a = ds.make_set(1).unwrap(); /// # let b = ds.make_set(2).unwrap(); /// # let c = ds.make_set(3).unwrap(); /// # let d = ds.make_set(4).unwrap(); /// # let e = ds.make_set(5).unwrap(); /// /// assert_eq!(ds.union(a, b), Some(true)); /// /// assert_eq!(ds.same_set(a, b), Some(true)); /// assert_eq!(ds.num_sets(), 4); /// /// assert_eq!(ds.union(a, b), Some(false)); /// assert_eq!(ds.union(c, d), Some(true)); /// assert_eq!(ds.union(e, c), Some(true)); /// /// // Now we have {a, b} and {c, d, e} /// /// assert_eq!(ds.num_sets(), 2); /// assert_eq!(ds.same_set(a, c), Some(false)); /// assert_eq!(ds.same_set(d, e), Some(true)); /// /// assert_eq!(ds.union(a, e), Some(true)); /// /// assert_eq!(ds.num_sets(), 1); /// ``` pub fn union(&amp;mut self, elem_x_idx: usize, elem_y_idx: usize) -&gt; Option&lt;bool&gt; { let (mut x_root_idx, mut y_root_idx) = ( self.find_root_idx(elem_x_idx)?, self.find_root_idx(elem_y_idx)?, ); // We don't have to do anything if this is the case. // Also, if we didn't check this, we'd panic below because // we'd attempt two mutable borrowings of the same RefCell. if x_root_idx == y_root_idx { return Some(false); } let (mut x_root, mut y_root) = ( self.nodes[x_root_idx].borrow_mut(), self.nodes[y_root_idx].borrow_mut(), ); if x_root.rank &lt; y_root.rank { // Must use mem::swap here. If we shadowed, // it'd go out of scope when the if block ended. mem::swap(&amp;mut x_root_idx, &amp;mut y_root_idx); mem::swap(&amp;mut x_root, &amp;mut y_root); } // Now x_root.rank &gt;= y_root.rank no matter what. // Therefore, make X the parent of Y. y_root.parent_idx = x_root_idx; self.roots.remove(&amp;y_root_idx); if x_root.rank == y_root.rank { x_root.rank += 1; } // Drop the RefMuts so we can check self.last, // which needs to immutably borrow, without conflicts. drop(x_root); drop(y_root); let x_last_idx = self.last(x_root_idx).unwrap(); let mut x_last = self.nodes[x_last_idx].borrow_mut(); x_last.next = y_root_idx; Some(true) } /// Returns the index of the root of the subset /// `elem_idx` belongs to, if it exists. pub fn find_root_idx(&amp;self, elem_idx: usize) -&gt; Option&lt;usize&gt; { if self.roots.contains(&amp;elem_idx) { return Some(elem_idx); } let mut curr_idx = elem_idx; let mut curr = self.nodes.get(curr_idx)?.borrow_mut(); while curr.parent_idx != curr_idx { let parent_idx = curr.parent_idx; let parent = self.nodes[parent_idx].borrow_mut(); // Set the current node's parent to its grandparent. // This is called *path splitting*: (see the Wikipedia // page for details) a simpler to implement, one-pass // version of path compression that also, apparently, // turns out to be more efficient in practice. curr.parent_idx = parent.parent_idx; // Move up a level for the next iteration curr_idx = parent_idx; curr = parent; } Some(curr_idx) } /// Returns the last element of the subset with /// `elem_idx` in it, if it exists. fn last(&amp;self, elem_idx: usize) -&gt; Option&lt;usize&gt; { self.get_set_idxs(elem_idx)?.pop() } /// Returns the indexes of all the items in the subset /// `elem_idx` belongs to in arbitrary order, if it exists. fn get_set_idxs(&amp;self, elem_idx: usize) -&gt; Option&lt;Vec&lt;usize&gt;&gt; { let mut curr_idx = self.find_root_idx(elem_idx)?; let mut curr = self.nodes[curr_idx].borrow(); let mut set_idxs = Vec::with_capacity(self.num_elements()); // We can't check the condition up here // using while because that would make // it so the last node is never pushed. loop { set_idxs.push(curr_idx); // This is the last node if curr_idx == curr.next { break; } curr_idx = curr.next; curr = self.nodes[curr.next].borrow(); } set_idxs.shrink_to_fit(); Some(set_idxs) } } </code></pre> <p>I think I succeeded for the most part, having only needed <code>T: Eq</code> and using interior mutability with <code>RefCell</code> to make a mostly sensible public API - mainly for the sake of <code>find_root_idx</code>, which pretends to be an immutable operation by taking <code>&amp;self</code> but actually needs to mutate in order to maintain the performance of union-find. I did have to add a <code>next</code> field to the normal union-find node in order to be able to iterate on subsets.</p> <p>I'm mainly looking for feedback on the &quot;Rustiness&quot; (idiomacity) of this code and how I could make some of the more hacky bits better, such as the <code>get</code> and <code>iter_set</code> family of functions with its unsafe code to get around lifetime issues (especially <code>iter_mut_all_sets</code> - the two <code>collect</code>s needed feel <em>reall</em> dirty) and <code>union</code> with its need to manually use <code>mem::drop</code> for two <code>RefMut&lt;Node&lt;T&gt;&gt;</code>s.</p> <p>Additionally, in general the soundness of this code is hard to guarantee - I'm <em>reasonably</em> sure that there shouldn't be any <code>RefCell</code> panics or memory unsafety no matter what the caller does (given that they only use safe code), but the code has spiraled out such that I don't know 100%.</p> <p>Extensibility is also somewhat of a concern - if I wanted to add a &quot;delete&quot; operation to the set as its currently set up, it would be quite the refactor job. If I wanted to make it thread-safe with <code>RwLock</code> or something similar, that'd be an even bigger problem thanks to the aforementioned unsafe code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-26T11:54:27.067", "Id": "506340", "Score": "0", "body": "Are you sure you want to tag this as [beginner]? I'd say those `unsafe` blocks are beyond what neophytes can navigate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-27T01:07:39.160", "Id": "506420", "Score": "0", "body": "@L.F. Well, I tagged it that because I was a beginner to the language. But fair enough, removed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-02T16:18:46.650", "Id": "506691", "Score": "0", "body": "For thread safety (Sync) I would look into lock-free index manipulation (e.g. with `crossbeam::atomic::AtomicCell`) if you are feeling particularly adventurous. For a \"delete\" operation, it's hard to foresee how large a refactor job would be needed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-13T09:08:56.890", "Id": "507725", "Score": "0", "body": "@naiveai Your struggle with iterators is due to an attempt to write iterators with `impl Trait` results. I recommend defining iterators with structs and good old impls." } ]
[ { "body": "<p>Since you never delete nodes, and if you do not intend to implement element deletion, you may fare better with alternatives for storing nodes, such as <a href=\"https://github.com/Manishearth/elsa/blob/master/src/vec.rs\" rel=\"nofollow noreferrer\"><code>elsa::FrozenVec&lt;Box&lt;Node&lt;T&gt;&gt;</code></a>, or some arena crate such as <code>bumpaloo</code> (edit: cannot index into nodes within an arena, though).</p>\n<p>Your choice of <code>RefCell</code> is slightly suspect. No wonder if you are a beginner in Rust -- for good design of code that uses <em>interior mutability</em> you need familiarity with all kinds of Cells and practice in working with interior mutability. It's one of the parts of Rust from the intermediate bordering on the hard.</p>\n<p>This comment:</p>\n<pre><code>// Nothing in our code actually mutates node.elem: T using &amp;self.\n// Even find_root_idx uses interior mutability only\n// to modify node.parent. ...\n</code></pre>\n<p>immediately points to <code>Cell</code> as a potential solution for mutating small, copyable datum. The changed code is attached at the end of this post, in accordance with the following simple change:</p>\n<pre><code>@@ -27,17 +28,17 @@ use std::{\n // Details about the algorithm used here can be found\n // at the Wikipedia page for &quot;Disjoint-set data structure&quot;.\n #[derive(Clone)]\n pub struct DisjointSet&lt;T: Eq&gt; {\n roots: HashSet&lt;usize&gt;,\n- nodes: Vec&lt;RefCell&lt;Node&lt;T&gt;&gt;&gt;,\n+ nodes: Vec&lt;Node&lt;T&gt;&gt;,\n }\n \n #[derive(Default, Clone)]\n struct Node&lt;T&gt; {\n elem: T,\n- parent_idx: usize,\n+ parent_idx: Cell&lt;usize&gt;,\n rank: usize,\n // We use this to be able to iterate\n // on each of our subsets.\n next: usize,\n }\n</code></pre>\n<p>Safety looks good to me, but I didn't go deep into it.</p>\n<p>Your struggle with iterators is due to an attempt to write iterators with <code>impl Trait</code> results. I recommend defining iterators with structs and good old impls.</p>\n<p>Tests are important and necessary here. Even more so due to the presence of unsafety.</p>\n<hr />\n<p>Nitpick: one of your <code>unsafe</code>s is not explained.</p>\n<p>Nitpick: Your <code>fn position</code> function is suspect. The signature is inconsistent with standard <code>Iterator::position</code>, which takes a predicate, not an element.</p>\n<p>Nitpick: Your return value in <code>fn make_set(&amp;mut self, elem: T) -&gt; Result&lt;usize, T&gt;</code> that can be <code>Err(t)</code> is suspect. It's better to go all the way and implement an <code>Entry</code>-like API for this.</p>\n<p>Nitpick: the following code can be removed, the rest of the function should cover this special case even more efficiently:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>pub fn find_root_idx(&amp;self, elem_idx: usize) -&gt; Option&lt;usize&gt; {\n // remove:\n if self.roots.contains(&amp;elem_idx) {\n return Some(elem_idx);\n }\n</code></pre>\n<hr />\n<pre><code>use std::{\n cell::Cell,\n collections::HashSet,\n iter::ExactSizeIterator,\n mem,\n cmp,\n};\n\n/// Represents a disjoint set of various subsets,\n/// with fast operations to join sets together.\n///\n/// # Example\n/// ```\n/// let mut ds = DisjointSet::new();\n///\n/// let a = ds.make_set(1).unwrap();\n/// let b = ds.make_set(2).unwrap();\n///\n/// assert!(ds.contains(&amp;1) &amp;&amp; ds.contains(&amp;2));\n/// assert_eq!(ds.same_set(a, b), Some(false));\n/// assert_eq!(ds.num_sets(), 2);\n///\n/// assert_eq!(ds.union(a, b), Some(true));\n///\n/// assert_eq!(ds.same_set(a, b), Some(true));\n/// assert_eq!(ds.num_sets(), 1);\n/// ```\n// Details about the algorithm used here can be found\n// at the Wikipedia page for &quot;Disjoint-set data structure&quot;.\n#[derive(Clone)]\npub struct DisjointSet&lt;T: Eq&gt; {\n roots: HashSet&lt;usize&gt;,\n nodes: Vec&lt;Node&lt;T&gt;&gt;,\n}\n\n#[derive(Default, Clone)]\nstruct Node&lt;T&gt; {\n elem: T,\n parent_idx: Cell&lt;usize&gt;,\n rank: usize,\n // We use this to be able to iterate\n // on each of our subsets.\n next: usize,\n}\n\nimpl&lt;T: Eq&gt; DisjointSet&lt;T&gt; {\n /// Creates an empty `DisjointSet`.\n pub fn new() -&gt; Self {\n Self {\n nodes: vec![],\n roots: HashSet::new(),\n }\n }\n\n /// Creates a new `DisjointSet` with the given capacity.\n pub fn with_capacity(capacity: usize) -&gt; Self {\n Self {\n nodes: Vec::with_capacity(capacity),\n roots: HashSet::new(),\n }\n }\n\n /// Returns the number of subsets.\n pub fn num_sets(&amp;self) -&gt; usize {\n self.roots.len()\n }\n\n /// Returns the number of total elements in all subsets.\n pub fn num_elements(&amp;self) -&gt; usize {\n self.nodes.len()\n }\n\n /// Returns true if the given element is present in the `DisjointSet`.\n pub fn contains(&amp;self, elem: &amp;T) -&gt; bool {\n self.position(elem).is_some()\n }\n\n /// Returns the index of the given element if it exists, or None otherwise.\n pub fn position(&amp;self, elem: &amp;T) -&gt; Option&lt;usize&gt; {\n self.nodes.iter().position(|e| &amp;e.elem == elem)\n }\n\n /// Adds a new set with a single, given element to\n /// the `DisjointSet`. Returns an Err with the elem\n /// if it was already present in any set, otherwise\n /// returns a Ok(usize) with the index of the element.\n pub fn make_set(&amp;mut self, elem: T) -&gt; Result&lt;usize, T&gt; {\n if !self.contains(&amp;elem) {\n // This is the index where the node will be inserted,\n // thanks to the magic of zero-indexing.\n let insertion_idx = self.nodes.len();\n\n self.nodes.push(Node {\n elem,\n parent_idx: Cell::new(insertion_idx),\n rank: 0,\n next: insertion_idx,\n });\n\n self.roots.insert(insertion_idx);\n\n Ok(insertion_idx)\n } else {\n Err(elem)\n }\n }\n\n /// If present, returns an immutable reference to the element at `elem_idx`.\n pub fn get(&amp;self, elem_idx: usize) -&gt; Option&lt;&amp;T&gt; {\n // Nothing in our code actually mutates node.elem: T using &amp;self.\n // Even find_root_idx uses interior mutability only\n // to modify node.parent. And the caller can't\n // call get_mut or iter_mut_set while the &amp;T here is\n // still in scope. So it all works out!\n self.nodes.get(elem_idx).map(|node| &amp;node.elem)\n }\n\n /// If present, returns a mutable reference to the element at `elem_idx`.\n pub fn get_mut(&amp;mut self, elem_idx: usize) -&gt; Option&lt;&amp;mut T&gt; {\n // RefCall::get_mut is used rarely, but here it's appropriate:\n // As long as the &amp;mut T from this is still in scope,\n // the caller won't be able to use any other methods,\n // so interior mutability isn't a concern.\n Some(&amp;mut self.nodes.get_mut(elem_idx)?.elem)\n }\n\n /// If present, returns a raw pointer to the element at `elem_idx`.\n fn get_raw(&amp;self, elem_idx: usize) -&gt; Option&lt;*mut T&gt; {\n self.get(elem_idx).map(|elem_ref| elem_ref as *const _ as *mut _)\n }\n\n /// Returns an `&amp;T` iterator over all elements in the set\n /// elem_idx belongs to, if it exists.\n // We use both applicable Iterator types here to give the caller\n // the maximum possible flexbility when using the returned value.\n pub fn iter_set(\n &amp;self,\n elem_idx: usize,\n ) -&gt; Option&lt;impl ExactSizeIterator&lt;Item = &amp;T&gt; + DoubleEndedIterator&gt; {\n Some(\n self.get_set_idxs(elem_idx)?\n .into_iter()\n .map(move |i| self.get(i).unwrap()),\n )\n }\n\n /// Returns an `&amp;mut T` iterator over all elements in the set\n /// elem_idx belongs to, if it exists.\n pub fn iter_mut_set(\n &amp;mut self,\n elem_idx: usize,\n ) -&gt; Option&lt;impl ExactSizeIterator&lt;Item = &amp;mut T&gt; + DoubleEndedIterator&gt; {\n let set_idxs = self.get_set_idxs(elem_idx)?;\n\n Some(set_idxs.into_iter().map(move |i| {\n // In reality this is safe because there'll\n // be no duplicate indexes. But Rust doesn't\n // have any way of knowing that.\n unsafe { &amp;mut *(self.get_mut(i).unwrap() as *mut _) }\n }))\n }\n\n pub fn iter_all_sets(\n &amp;self,\n ) -&gt; impl ExactSizeIterator&lt;Item = impl ExactSizeIterator&lt;Item = &amp;T&gt; + DoubleEndedIterator&gt;\n + DoubleEndedIterator {\n // Put roots into a Vec to satisfy DoubleEndedIterator\n let roots = self.roots.iter().collect::&lt;Vec&lt;_&gt;&gt;();\n\n roots.into_iter().map(move |&amp;r| self.iter_set(r).unwrap())\n }\n\n pub fn iter_mut_all_sets(\n &amp;mut self,\n ) -&gt; impl ExactSizeIterator&lt;Item = impl ExactSizeIterator&lt;Item = &amp;mut T&gt; + DoubleEndedIterator&gt;\n + DoubleEndedIterator {\n // This function can't be as simple as iter_all_sets,\n // because Rust won't like it if we just straight up take\n // &amp;mut self several times over.\n self.roots\n .iter()\n .map(|&amp;root| {\n self.get_set_idxs(root)\n .unwrap()\n .into_iter()\n .map(|i| {\n // No duplicate indexes means that using this\n // pointer as a &amp;mut T is safe. We can't\n // use get_mut here because that takes &amp;mut self.\n unsafe { &amp;mut *self.get_raw(i).unwrap() }\n })\n .collect::&lt;Vec&lt;_&gt;&gt;()\n })\n // In order to avoid the closures that borrow\n // self outliving the function itself, we collect\n // their results and then turn them back into iterators.\n .collect::&lt;Vec&lt;_&gt;&gt;()\n .into_iter()\n .map(|v| v.into_iter())\n }\n\n /// Returns Some(true) if the elements at both the given indexes\n /// are in the same set, or None of either of them aren't present altogether.\n pub fn same_set(&amp;self, elem1_idx: usize, elem2_idx: usize) -&gt; Option&lt;bool&gt; {\n // The ? ensures this'll short-circuit and return None if either of the indexes are None,\n // meaning we don't end up returning Some(true) if both elements don't exist.\n Some(self.find_root_idx(elem1_idx)? == self.find_root_idx(elem2_idx)?)\n }\n\n /// Performs a union for the two sets containing the given elements.\n /// Returns Some(true) if the operation was performed, Some(false) if not,\n /// and None if either element doesn't exist.\n ///\n /// # Example\n /// ```\n /// let mut ds = DisjointSet::new();\n ///\n /// // Ommitted: adding 5 seperate elements to the set a..e\n /// # let a = ds.make_set(1).unwrap();\n /// # let b = ds.make_set(2).unwrap();\n /// # let c = ds.make_set(3).unwrap();\n /// # let d = ds.make_set(4).unwrap();\n /// # let e = ds.make_set(5).unwrap();\n ///\n /// assert_eq!(ds.union(a, b), Some(true));\n ///\n /// assert_eq!(ds.same_set(a, b), Some(true));\n /// assert_eq!(ds.num_sets(), 4);\n ///\n /// assert_eq!(ds.union(a, b), Some(false));\n /// assert_eq!(ds.union(c, d), Some(true));\n /// assert_eq!(ds.union(e, c), Some(true));\n ///\n /// // Now we have {a, b} and {c, d, e}\n ///\n /// assert_eq!(ds.num_sets(), 2);\n /// assert_eq!(ds.same_set(a, c), Some(false));\n /// assert_eq!(ds.same_set(d, e), Some(true));\n ///\n /// assert_eq!(ds.union(a, e), Some(true));\n ///\n /// assert_eq!(ds.num_sets(), 1);\n /// ```\n pub fn union(&amp;mut self, elem_x_idx: usize, elem_y_idx: usize) -&gt; Option&lt;bool&gt; {\n let (mut x_root_idx, mut y_root_idx) = (\n self.find_root_idx(elem_x_idx)?,\n self.find_root_idx(elem_y_idx)?,\n );\n\n // We don't have to do anything if this is the case.\n // Also, if we didn't check this, we'd panic below because\n // we'd attempt two mutable borrowings of the same RefCell.\n if x_root_idx == y_root_idx {\n return Some(false);\n }\n\n if self.nodes[x_root_idx].rank &lt; self.nodes[y_root_idx].rank {\n // Must use mem::swap here. If we shadowed,\n // it'd go out of scope when the if block ended.\n mem::swap(&amp;mut x_root_idx, &amp;mut y_root_idx);\n }\n\n let max_root_idx = cmp::max(x_root_idx, y_root_idx);\n let min_root_idx = cmp::min(x_root_idx, y_root_idx);\n let (nodes_a, nodes_b) = self.nodes.split_at_mut(max_root_idx);\n\n let (mut x_root, mut y_root) = (\n &amp;mut nodes_a[min_root_idx],\n &amp;mut nodes_b[0],\n );\n\n if y_root_idx == min_root_idx {\n mem::swap(&amp;mut x_root, &amp;mut y_root);\n }\n\n // Now x_root.rank &gt;= y_root.rank no matter what.\n // Therefore, make X the parent of Y.\n y_root.parent_idx = Cell::new(x_root_idx);\n self.roots.remove(&amp;y_root_idx);\n if x_root.rank == y_root.rank {\n x_root.rank += 1;\n }\n\n let x_last_idx = self.last(x_root_idx).unwrap();\n self.nodes[x_last_idx].next = y_root_idx;\n\n Some(true)\n }\n\n /// Returns the index of the root of the subset\n /// `elem_idx` belongs to, if it exists.\n pub fn find_root_idx(&amp;self, elem_idx: usize) -&gt; Option&lt;usize&gt; {\n if self.roots.contains(&amp;elem_idx) {\n return Some(elem_idx);\n }\n\n let mut curr_idx = elem_idx;\n let mut curr = self.nodes.get(curr_idx)?;\n\n while curr.parent_idx.get() != curr_idx {\n let parent_idx = curr.parent_idx.get();\n let parent = &amp;self.nodes[parent_idx];\n\n // Set the current node's parent to its grandparent.\n // This is called *path splitting*: (see the Wikipedia\n // page for details) a simpler to implement, one-pass\n // version of path compression that also, apparently,\n // turns out to be more efficient in practice.\n curr.parent_idx.set(parent.parent_idx.get());\n\n // Move up a level for the next iteration\n curr_idx = parent_idx;\n curr = parent;\n }\n\n Some(curr_idx)\n }\n\n /// Returns the last element of the subset with\n /// `elem_idx` in it, if it exists.\n fn last(&amp;self, elem_idx: usize) -&gt; Option&lt;usize&gt; {\n self.get_set_idxs(elem_idx)?.pop()\n }\n\n /// Returns the indexes of all the items in the subset\n /// `elem_idx` belongs to in arbitrary order, if it exists.\n fn get_set_idxs(&amp;self, elem_idx: usize) -&gt; Option&lt;Vec&lt;usize&gt;&gt; {\n let mut curr_idx = self.find_root_idx(elem_idx)?;\n let mut curr = &amp;self.nodes[curr_idx];\n\n let mut set_idxs = Vec::with_capacity(self.num_elements());\n\n // We can't check the condition up here\n // using while because that would make\n // it so the last node is never pushed.\n loop {\n set_idxs.push(curr_idx);\n\n // This is the last node\n if curr_idx == curr.next {\n break;\n }\n\n curr_idx = curr.next;\n curr = &amp;self.nodes[curr.next];\n }\n\n set_idxs.shrink_to_fit();\n\n Some(set_idxs)\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-02T14:23:55.467", "Id": "256620", "ParentId": "251255", "Score": "4" } } ]
{ "AcceptedAnswerId": "256620", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T15:40:19.623", "Id": "251255", "Score": "12", "Tags": [ "rust", "union-find" ], "Title": "How Rusty is my generic union-find implementation?" }
251255
<p>I have the algorithm which splits DateTime range into multiple ranges based on night time range.</p> <p>For example:</p> <p><strong>Night start:</strong> 22:00, <strong>Night end:</strong> 06:00</p> <p><strong>Start time:</strong> 2020-10-26 21:00:00 <strong>End time:</strong> 2020-10-27 07:00:00</p> <p><strong>Expected output:</strong></p> <ul> <li>2020-10-26 21:00:00 - 2020-10-26 22:00:00</li> <li>2020-10-26 22:00:00 - 2020-10-27 06:00:00</li> <li>2020-10-27 06:00:00 - 2020-10-27 07:00:00</li> </ul> <p>It basically splits DateTime range by day and night/to day/night batches.</p> <p>I wonder if there's something I could do to make the code shorter and possibly better performance-wise.</p> <p><strong>Code:</strong></p> <pre><code>internal class Helper { public static readonly TimeSpan NightStartTime = new TimeSpan(22, 0, 0); public static readonly TimeSpan NightEndTime = new TimeSpan(6, 0, 0); public static bool IsNightTime(TimeSpan time) =&gt; time &gt;= NightStartTime || time &lt; NightEndTime; public static bool IsDayTime(TimeSpan time) =&gt; !IsNightTime(time); } internal class Program { private static void Main(string[] args) { var startTime = DateTime.Parse(&quot;2020-10-26 21:00:00&quot;); var endTime = DateTime.Parse(&quot;2020-10-27 07:00:00&quot;); DateTime? currentStartTime = startTime; DateTime? currentEndTime = null; var currentTimeIsDayTime = Helper.IsDayTime(startTime.TimeOfDay); for (var currentTime = startTime; currentTime &lt;= endTime; currentTime = currentTime.AddMinutes(1)) { var isDayTime = Helper.IsDayTime(currentTime.TimeOfDay); if (currentTimeIsDayTime != isDayTime) { currentEndTime = currentTime; currentTimeIsDayTime = isDayTime; } if (currentTime == endTime) { currentEndTime = endTime; } if (currentStartTime != null &amp;&amp; currentEndTime != null) { Console.WriteLine($&quot;{currentStartTime} - {currentEndTime}&quot;); currentStartTime = currentEndTime; currentEndTime = null; } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T20:11:26.440", "Id": "494587", "Score": "0", "body": "Wait, are you going through the entire range of time between two DateTimes minute by minute (`currentTime = currentTime.AddMinutes(1)`)? Why? You can access `NightStartTime` and `NightEndTime`, so why not compare `startTime` and `endTime` to those two and work from there?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T20:51:36.610", "Id": "494591", "Score": "0", "body": "@BCdotWEB yeah, couldn't think of a better algorithm so far. I don't like that minute by minute thing. I still wonder how could I make it shorter" } ]
[ { "body": "<p>You can make it shorter by tackling the problem smarter, as in shift or work segments in relation to a DateTime or TimeofDay. Trying brute force checks of minute-by-minute is a horrifically bad solution. My answer may <strong>point you in the right direction</strong> but it is <strong>NOT TOTALLY CORRECT FOR ALL POSSIBLE INPUTS</strong>.</p>\n<p>I would separate the logic into its own class.</p>\n<pre><code>public enum Shift { Day, Night }\n\n// CAUTION: this class does not perform validation to make sure end times are after start time, or that\n// start and end times are of the same DateTimeKind. \n// This does not work for Kind = Local, specifically on fall back or spring forward transition days.\n// It does work for Kind = Utc or Unspecified, since they do not observe DST.\npublic class WorkShift\n{\n\n // A WorkShift may not be complete shift, but rather segments.\n public Shift Shift { get; }\n public DateTime StartTime { get; }\n public DateTime EndTime { get; }\n\n public WorkShift(Shift shift, DateTime startTime, DateTime endTime)\n {\n this.Shift = shift;\n this.StartTime = startTime;\n this.EndTime = endTime;\n }\n\n public static readonly TimeSpan NightShiftStart = new TimeSpan(22, 0, 0);\n public static readonly TimeSpan NightShiftEnd = new TimeSpan(6, 0, 0);\n\n // Shifts have an inclusive start time but an exclusive end time.\n public static bool IsNightShift(TimeSpan timeOfDay) =&gt; timeOfDay &gt;= NightShiftStart || timeOfDay &lt; NightShiftEnd;\n public static bool IsDayShift(TimeSpan timeofDay) =&gt; !IsNightShift(timeofDay);\n\n public static bool IsNightShift(DateTime time) =&gt; IsNightShift(time.TimeOfDay);\n public static bool IsDayShift(DateTime time) =&gt; IsDayShift(time.TimeOfDay);\n\n public static IEnumerable&lt;WorkShift&gt; GetShiftSegments(DateTime startTime, DateTime endTime)\n {\n var segmentEnd = startTime;\n while (segmentEnd &lt; endTime)\n {\n var segmentStart = segmentEnd;\n var shift = IsNightShift(segmentStart) ? Shift.Night : Shift.Day;\n segmentEnd = GetShiftEndTime(shift, segmentStart);\n if (segmentEnd &gt; endTime)\n {\n segmentEnd = endTime;\n }\n yield return new WorkShift(shift, segmentStart, segmentEnd);\n }\n }\n\n private static DateTime GetShiftEndTime(Shift shift, DateTime segmentStart)\n {\n // Nice thing about Day is it occurs on the same date, but Night may crossover midnight into the next date.\n if (shift == Shift.Day)\n {\n return DateTime.SpecifyKind(segmentStart.Date + NightShiftStart, segmentStart.Kind);\n }\n\n if (segmentStart.TimeOfDay &gt;= NightShiftStart)\n {\n // ending shift would be tomorrow.\n return DateTime.SpecifyKind(segmentStart.Date.AddDays(1) + NightShiftEnd, segmentStart.Kind);\n }\n\n return DateTime.SpecifyKind(segmentStart.Date + NightShiftEnd, segmentStart.Kind);\n }\n}\n</code></pre>\n<p>Now the Main test can become:</p>\n<pre><code>static void Main(string[] args)\n{\n var startTime = DateTime.Parse(&quot;2020-10-26 21:00:00&quot;);\n var endTime = DateTime.Parse(&quot;2020-10-27 07:00:00&quot;);\n Console.WriteLine($&quot;Time Range From {startTime} To {endTime}&quot;);\n\n var workSegments = WorkShift.GetShiftSegments(startTime, endTime).ToList();\n\n for (var i = 0; i &lt; workSegments.Count; i++)\n {\n Console.WriteLine($&quot; [{i}] = {workSegments[i].Shift}, Start:{workSegments[i].StartTime}, End:{workSegments[i].EndTime}&quot;);\n }\n\n Console.WriteLine(&quot;\\nPress ENTER to close&quot;);\n Console.ReadLine();\n}\n</code></pre>\n<p>Sample console output is:</p>\n<pre><code>Time Range From 10/26/2020 9:00:00 PM To 10/27/2020 7:00:00 AM\n [0] = Day, Start:10/26/2020 9:00:00 PM, End:10/26/2020 10:00:00 PM\n [1] = Night, Start:10/26/2020 10:00:00 PM, End:10/27/2020 6:00:00 AM\n [2] = Day, Start:10/27/2020 6:00:00 AM, End:10/27/2020 7:00:00 AM\n\nPress ENTER to close\n</code></pre>\n<p><strong>CAUTIONS AND WARNINGS</strong></p>\n<p>A <code>WorkShift</code> instance may or may not represent a complete Day or Night work shift, but instead a segment depending upon the starting or ending time.</p>\n<p>As the code comments say, there are no validation checks to ensure that the ending time occurs after the starting time. Nor are there any checks to ensure that both the starting and ending times have the same <code>DateTimeKind</code>.</p>\n<p><em><strong>I did not check to see if the code works correctly for Local Kind.</strong></em> My intuition tells me to be suspicious or very leery about it. However, it should work when Kind is Utc or Unspecified, where neither observe DST and therefore neither will have a 23-hour Spring Forward Day or a 25-hour Fall Back Day.</p>\n<p>It is important that both start and ending times belong the the same <code>DateTimeKind</code> when subtracting start from end. If they belong to different kinds, the time range span may be incorrect.</p>\n<p>Even if you are super careful about the Kind, keep in mind that certain operations may return a invalid date and time. For instance, <code>DateTime.Date</code> returns a value at midnight with the same Kind as the input DateTime. But if your local time is Brazil (or Brasil), then the Spring Forward transition day does not have a midnight.</p>\n<p>There are so many gotcha's with dates, times, and local time zones, that I would urge you to read up on <a href=\"https://nodatime.org/\" rel=\"nofollow noreferrer\">https://nodatime.org/</a>,</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T14:35:48.917", "Id": "494649", "Score": "0", "body": "That's much better thanks a lot Rick. I must check NodaTime out if you say it solves time problems of different countries better than the standard API." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T14:10:33.920", "Id": "251299", "ParentId": "251256", "Score": "1" } } ]
{ "AcceptedAnswerId": "251299", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T15:46:46.910", "Id": "251256", "Score": "2", "Tags": [ "c#", "performance", "algorithm", "programming-challenge", "datetime" ], "Title": "DateTime range splitting algorithm" }
251256
<p>I am to preview where a new element will be added on button click. I thought about just creating the element and showing that in the preview, but I have several buttons and some of the elements they create require input (via window.prompt) so I decided to just make a placeholder div and use that instead</p> <p>Javascript:</p> <pre><code>var addTempDiv = function (e) { ... } buttons.on('mouseenter', addTempDiv).on('mouseleave', function() {$(&quot;#NewElemPlaceholder&quot;).remove();}); </code></pre> <p>CSS:</p> <pre><code>#NewElemPlaceholder { background: blue; opacity: 50%; height: 3em; } body.editMode-dontlist #editDiv { display: block !important; position: sticky; } </code></pre> <ul> <li>The buttons are in #editDiv, div above the main content with position: sticky (as shown)</li> <li>The placeholder is removed on mouseleave on the button, or on button click.</li> <li>Internally, I am storing the placeholder div in a global variable so that it can be reused.</li> <li>I haven't included the code in addTempDiv, as it's rather convoluted. But it does add the tempDiv in the right place.</li> </ul> <p>-- Edit --</p> <p>What makes addTempDiv convoluted is that I maintain a &quot;lastFocused&quot; element in the main content, and new content elements are added relative to the lastFocused element. It is also complicated because of html hierarchy: With some elements (like P's and H1's) the new element is appended <em>after</em> the element. With others (like TD) the new element should be added as a child of the TD.</p> <p>The whole reason for adding the &quot;preview&quot; feature is that if someone is editing an ol/ul list, and then they hit &quot;P&quot;, it will create a new paragraph under the list item (if that is the lastFocused element). But if the last focused element is an ol/ul, then the new paragraph is added after the list (in the editDiv there is a toolbar to set lastFocused to parent elements in the DOM hierarchy)</p> <p>I created this technology, and even I get tripped up with exactly the case above (adding a paragraph after a list). So my idea was to add this preview/temp div so that I (and hopefully others going forward) could see where the new element would be placed before adding it.</p> <p>Maybe this information should have be right at the start of my question, but then I have to get into the sticky issues of lastFocused and addTempDiv right away which I worry could confuse people looking at my question. Anyway, I've put it here.</p> <p>-- End Edit --</p> <p>This is currently working with all bugs fixed.</p> <p>Is there a better way to preview / indicate where a new element will appear on button click? Has anyone else done this differently and can tell me about how they designed such a feature? Is this implementation going to come back and bite me?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T14:16:29.997", "Id": "494648", "Score": "1", "body": "I have an idea, but I can't be sure about it without seeing more code. Can you show the HTML structure of the `buttons` and the possible associated `NewElemPlaceholder` in relation to the buttons?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T14:57:57.797", "Id": "494653", "Score": "0", "body": "@CertainPerformance I have updated my question. Hopefully my updates answer your question" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T16:38:32.470", "Id": "251258", "Score": "1", "Tags": [ "javascript", "css", "html5" ], "Title": "Is there a better way to preview the addition of a new element?" }
251258
<p>I'm working on a spigot plugin, that deals with messages to from players on a server to the admin's. It's the same plugin this question relates to: <a href="https://codereview.stackexchange.com/questions/251212/sql-structure-to-save-coordinates-for-spigot-plugin">SQL structure to save coordinates for spigot plugin</a> . I've got a command, which allowes access to the inbox, and does all kinds of operations on the data. One of these operations is deleting an entry by it's ID.</p> <p>I've got a simple SQL query to delete it, and want to display a message, depending on if the message could be deleted or not. Therefore I wrote this method in my Command-Class:</p> <pre class="lang-java prettyprint-override"><code>private void deleteMessage(CommandSender sender, int messageId) { int deleted = DatabaseMethods.deleteMessage(messageId); if (deleted == 0) { sender.sendMessage(MessageManager.couldNotBeFound(messageId)); } else { sender.sendMessage(MessageManager.deletedMessage(messageId)); } } </code></pre> <p>and this is the method that accesses the database:</p> <pre><code>public static int deleteMessage(int messageId) { try (final PreparedStatement ps = BasePluginAPI.getDatabaseConnection() .prepareStatement(&quot;delete from MELDUNG where ID = ?&quot;)) { ps.setInt(1, messageId); return ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); return 0; } } </code></pre> <p>I don't know if this is the best way to approach it. I have two main questions:</p> <ol> <li>Is an early return better for the first method? Or is it just a question of personal taste?</li> <li>Can the SQL-handling be improved? Should maybe the method return a <code>boolean</code> instead of an <code>int</code>?</li> </ol> <p>Besides these specific questions, of course general feedback is very welcome as well! :)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T17:06:38.453", "Id": "494561", "Score": "0", "body": "What do you mean with an earlier return? You can't return earlier there as far as I can see." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T17:07:48.060", "Id": "494562", "Score": "0", "body": "Can the delete affect multiple messages? If yes, int, if not, boolean." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T17:08:03.217", "Id": "494563", "Score": "0", "body": "Instead of using an `else` clause, just insert a `return;` after sending the `couldNotBeFound`-Message, and putting the second message after the `if`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T17:09:05.313", "Id": "494564", "Score": "0", "body": "@Bobby No it cannot. `ID`, or `messageId` is the primary key of my database table" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T17:10:00.210", "Id": "494565", "Score": "1", "body": "Personal taste, I'm afraid. I like if/else constructs for these situations, as they provide immediate meaning how the two statements depend on then condition. Performance-wise it doesn't matter at all." } ]
[ { "body": "<p>Regarding your questions:</p>\n<blockquote>\n<ol>\n<li>Is an early return better for the first method? Or is it just a question of personal taste?</li>\n</ol>\n</blockquote>\n<p>The alternative you suggest would be:</p>\n<pre><code>private void deleteMessage(CommandSender sender, int messageId) {\n int deleted = DatabaseMethods.deleteMessage(messageId);\n if (deleted == 0) {\n sender.sendMessage(MessageManager.couldNotBeFound(messageId));\n return;\n } \n sender.sendMessage(MessageManager.deletedMessage(messageId));\n}\n</code></pre>\n<p>I generally don't recommend it. A developer might delete the empty return thinking it's unnecessary causing a bug. The <code>if-else</code> is more readable in my opinion.</p>\n<blockquote>\n<ol start=\"2\">\n<li>Can the SQL-handling be improved? Should maybe the method return a boolean instead of an int?</li>\n</ol>\n</blockquote>\n<p>If the delete operation can return only <code>0</code> or <code>1</code>, then it should be a <code>boolean</code>. However, <strong>there are more than two outcomes</strong>: the database is down, the database call times out, etc. &quot;Message not found&quot; is just one of the reasons for <code>deleteMessage</code> to return <code>0</code>. So instead of <code>MessageManager.couldNotBeFound(messageId))</code>, would be more appropriate to say &quot;message cannot be deleted&quot;.</p>\n<p>To tell the user &quot;message not found&quot;, you can let the second method throw the exception and catch it in the first method.</p>\n<p>One more thing, from the method signature is not clear why <code>deleteMessage(CommandSender sender, int messageId)</code> needs a <code>CommandSender</code>, a better name can be <code>deleteMessageAndNotify</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T07:36:05.737", "Id": "251290", "ParentId": "251260", "Score": "3" } } ]
{ "AcceptedAnswerId": "251290", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T16:49:21.663", "Id": "251260", "Score": "6", "Tags": [ "java", "sql" ], "Title": "Delete Entry from SQL-Table and confirm the deletion to a CommandSender in a spigot plugin" }
251260
<p>Seeing as a concurrent collection does not exist in .net that allows specific items to be removed, I have put together the following class.</p> <p>It's important to note that it is only threadsafe until the <code>LockTimeout</code> on a given operation expires.</p> <p>The main goal was to to guard against cheeky 'InvalidOperationException: Collection Was Modified' exceptions, which occur if I'm enumerating in one thread, and adding / removing in another.</p> <p>I've defaulted the <code>LockTimeout</code> to 10 seconds, but in reality, 1 second would still be plenty (in my user case at least).</p> <p>Lastly, this specific implementation also incorporates <code>INotifyCollectionChanged</code> and <code>INotifyPropertyChanged</code>.</p> <pre><code>public class ThreadsafeObservableCollection&lt;T&gt; : IList&lt;T&gt;, INotifyCollectionChanged, INotifyPropertyChanged { public event NotifyCollectionChangedEventHandler CollectionChanged; public event PropertyChangedEventHandler PropertyChanged; private readonly ConcurrentQueue&lt;PropertyChangedEventArgs&gt; _propertyChangedEvents = new ConcurrentQueue&lt;PropertyChangedEventArgs&gt;(); private readonly ConcurrentQueue&lt;NotifyCollectionChangedEventArgs&gt; _collectionChangedEvents = new ConcurrentQueue&lt;NotifyCollectionChangedEventArgs&gt;(); private readonly ObservableCollection&lt;T&gt; _collection; private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1); private static TimeSpan LOCK_TIMEOUT = TimeSpan.FromSeconds(10); public ThreadsafeObservableCollection() { _collection = new ObservableCollection&lt;T&gt;(); _collection.CollectionChanged += _collection_CollectionChanged; (_collection as INotifyPropertyChanged).PropertyChanged += _collection_PropertyChanged; } private void Wait() { while (!_semaphore.Wait(LOCK_TIMEOUT)) _semaphore.Release(); } public void Add(T item) { Wait(); try { _collection.Add(item); } finally { _semaphore.Release(); } FireOutstandingEvents(); } public void Clear() { Wait(); try { _collection.Clear(); } finally { _semaphore.Release(); } FireOutstandingEvents(); } public bool Contains(T item) { Wait(); bool result; try { result = _collection.Contains(item); } finally { _semaphore.Release(); } FireOutstandingEvents(); return result; } public int Count { get { Wait(); int count; try { count = _collection.Count; } finally { _semaphore.Release(); } FireOutstandingEvents(); return count; } } public bool IsReadOnly =&gt; false; public T this[int index] { get { Wait(); T item; try { item = _collection[index]; } finally { _semaphore.Release(); } FireOutstandingEvents(); return item; } set { Wait(); try { _collection[index] = value; } finally { _semaphore.Release(); } FireOutstandingEvents(); } } public void CopyTo(T[] array, int arrayIndex) { Wait(); try { _collection.CopyTo(array, arrayIndex); } finally { _semaphore.Release(); } FireOutstandingEvents(); } public int IndexOf(T item) { Wait(); int index; try { index = _collection.IndexOf(item); } finally { _semaphore.Release(); } FireOutstandingEvents(); return index; } public void Insert(int index, T item) { Wait(); try { _collection.Insert(index, item); } finally { _semaphore.Release(); } FireOutstandingEvents(); } public bool Remove(T item) { Wait(); bool result; try { result = _collection.Remove(item); } finally { _semaphore.Release(); } FireOutstandingEvents(); return result; } public void RemoveAt(int index) { Wait(); try { _collection.RemoveAt(index); } finally { _semaphore.Release(); } FireOutstandingEvents(); } private void FireOutstandingEvents() { while (_propertyChangedEvents.TryDequeue(out PropertyChangedEventArgs arg)) PropertyChanged?.Invoke(this, arg); while (_collectionChangedEvents.TryDequeue(out NotifyCollectionChangedEventArgs arg)) CollectionChanged?.Invoke(this, arg); } private void _collection_PropertyChanged(object sender, PropertyChangedEventArgs e) { _propertyChangedEvents.Enqueue(e); } private void _collection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { _collectionChangedEvents.Enqueue(e); } public IEnumerator&lt;T&gt; GetEnumerator() { Wait(); try { return ((IEnumerable&lt;T&gt;)_collection.ToArray()).GetEnumerator(); } finally { _semaphore.Release(); } } IEnumerator IEnumerable.GetEnumerator() { Wait(); try { return _collection.ToArray().GetEnumerator(); } finally { _semaphore.Release(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-01T20:01:25.023", "Id": "494987", "Score": "0", "body": "I like [this](https://gist.github.com/thomaslevesque/10023516) one. The Thread-safety here achieved by pushing each modification call to UI Thread. The only restriction here: you must construct the instance in the UI Thread. It's easy as it could be. I checked, it's totally thread-safe. I'm using it in almost all of my WPF projects." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-01T20:09:31.113", "Id": "494988", "Score": "0", "body": "Also your implementation contains a problem. To interact with UI Controls properly you must fire the events in the UI Thread. Otherwise you may probably break the state of the Items Control by Race Condition at `CollectionChanged` calls e.g. new fire before previous was handled by UI." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-01T20:25:39.053", "Id": "494989", "Score": "0", "body": "Thus the solution in review is ok to eleminate `Collection was modified` but not ready to use with UI Data Bindings. The solution in the first comment doesn't fix this exception but fix another one `Operation not supported` when modification call performed from some pooled thread. One more question: why `SemaphoreSlim` instead of `lock`?" } ]
[ { "body": "<p>The <code>Wait</code> method is not correct.\nIf the timeout expires the semaphore is released without being taken.\nThis may allow code to run immediately afterwards because there's a slot available (not really as it was already taken but erroneously released) but in the future when <code>Release</code> is called it will fail because the semaphore has already reached its maximum size.</p>\n<pre><code>private void Wait()\n{\n while (!_semaphore.Wait(LOCK_TIMEOUT))\n _semaphore.Release();\n}\n</code></pre>\n<p>Every <em>successful</em> call to <code>Wait</code> <strong>must</strong> be paired with a call to <code>Release</code>.\nA <code>Wait</code> returning false is not successful.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T14:20:12.483", "Id": "251300", "ParentId": "251263", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T17:45:46.757", "Id": "251263", "Score": "3", "Tags": [ "c#", "thread-safety" ], "Title": "A 'ThreadSafe' Observable Collection - C#" }
251263
<p>I have written Python code which uses multiple <code>if</code> conditions and a <code>for</code> loop. The main objective of the code is to produce a traffic light system based on certain conditions.</p> <pre><code>Red = -1 Yellow = 0 Green = 1 </code></pre> <p>It takes 4 months (<code>m0</code>, <code>m1</code>, <code>m2</code>, <code>m3</code>) and <code>dataframe</code> as an input, runs the condition through each row, and returns -1, 0 or 1.</p> <p><a href="https://i.stack.imgur.com/VN3CM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VN3CM.png" alt="scenarios" /></a></p> <p>The code compares Month 1 with Month 0, Month 2 with Month 1 and Month 3 with Month 2.</p> <p>For input:</p> <pre><code>if month+1 &lt; Month for any value, then red else green. </code></pre> <p>For example, if the revenue of July 2020 is less than June 2020 then the input is red, otherwise green. Based on three comparisons the outcome is calculated. The outcome could be either 1-, 0, or 1.</p> <p>The code I have written works well but is not optimised in any way. Is there a better way to do this?</p> <p>This would be an O(n) operation but, at least there should be a way to write it concisely in Python. Or if code can be improved operationally as well.</p> <pre><code>def getTrafficLightData(df, dimension, m1, m2, m3, m4): ''' Inputs - Dataframe dimension = on which we want to calculate traffic light system m1, m2, m3, m4 - Could be any for months but we have taken consecutive months for Traffic Light System. Example Call - getTrafficLightData(report6_TLS_data, &quot;Revenue_&quot;,&quot;2020-6&quot;,&quot;2020-7&quot;,&quot;2020-8&quot;,&quot;2020-9&quot;) ''' TFS_df = pd.DataFrame(columns=[dimension + &quot;_TLS&quot;]) if dimension == &quot;Overstrike_&quot;: suffix = &quot;%&quot; for i in range(len(df)): if ( ( df[dimension + m1 + suffix].iloc[i] &gt; df[dimension + m2 + suffix].iloc[i] ) and ( df[dimension + m2 + suffix].iloc[i] &gt; df[dimension + m3 + suffix].iloc[i] ) and ( df[dimension + m3 + suffix].iloc[i] &gt; df[dimension + m4 + suffix].iloc[i] ) ): TFS_df.loc[i] = [1] elif ( ( df[dimension + m1 + suffix].iloc[i] &lt; df[dimension + m2 + suffix].iloc[i] ) and ( df[dimension + m2 + suffix].iloc[i] &lt; df[dimension + m3 + suffix].iloc[i] ) and ( df[dimension + m3 + suffix].iloc[i] &lt; df[dimension + m4 + suffix].iloc[i] ) ): TFS_df.loc[i] = [-1] elif ( ( df[dimension + m1 + suffix].iloc[i] &lt; df[dimension + m2 + suffix].iloc[i] ) and ( df[dimension + m2 + suffix].iloc[i] &gt; df[dimension + m3 + suffix].iloc[i] ) and ( df[dimension + m3 + suffix].iloc[i] &lt; df[dimension + m4 + suffix].iloc[i] ) ): TFS_df.loc[i] = [-1] elif ( ( df[dimension + m2 + suffix].iloc[i] &gt; df[dimension + m2 + suffix].iloc[i] ) and ( df[dimension + m2 + suffix].iloc[i] &lt; df[dimension + m3 + suffix].iloc[i] ) and ( df[dimension + m3 + suffix].iloc[i] &lt; df[dimension + m4 + suffix].iloc[i] ) ): TFS_df.loc[i] = [-1] elif ( ( df[dimension + m1 + suffix].iloc[i] &gt; df[dimension + m2 + suffix].iloc[i] ) and ( df[dimension + m2 + suffix].iloc[i] &gt; df[dimension + m3 + suffix].iloc[i] ) and ( df[dimension + m3 + suffix].iloc[i] &lt; df[dimension + m4 + suffix].iloc[i] ) ): TFS_df.loc[i] = [0] elif ( ( df[dimension + m1 + suffix].iloc[i] &gt; df[dimension + m2 + suffix].iloc[i] ) and ( df[dimension + m2 + suffix].iloc[i] &lt; df[dimension + m3 + suffix].iloc[i] ) and ( df[dimension + m3 + suffix].iloc[i] &gt; df[dimension + m4 + suffix].iloc[i] ) ): TFS_df.loc[i] = [1] elif ( ( df[dimension + m1 + suffix].iloc[i] &lt; df[dimension + m2 + suffix].iloc[i] ) and ( df[dimension + m2 + suffix].iloc[i] &gt; df[dimension + m3 + suffix].iloc[i] ) and ( df[dimension + m3 + suffix].iloc[i] &gt; df[dimension + m4 + suffix].iloc[i] ) ): TFS_df.loc[i] = [1] elif ( ( df[dimension + m1 + suffix].iloc[i] &lt; df[dimension + m2 + suffix].iloc[i] ) and ( # df[dimension + m2 + suffix].iloc[i] &lt; df[dimension + m3 + suffix].iloc[i] ) and ( # df[dimension + m3 + suffix].iloc[i] &gt; df[dimension + m4 + suffix].iloc[i] ) ): TFS_df.loc[i] = [0] else: TFS_df.loc[i] = [0] return TFS_df else: if dimension == &quot;Margin_&quot;: suffix = &quot;%&quot; else: suffix = &quot;&quot; for i in range(len(df)): if ( ( df[dimension + m1 + suffix].iloc[i] &gt; df[dimension + m2 + suffix].iloc[i] ) and ( df[dimension + m2 + suffix].iloc[i] &gt; df[dimension + m3 + suffix].iloc[i] ) and ( df[dimension + m3 + suffix].iloc[i] &gt; df[dimension + m4 + suffix].iloc[i] ) ): TFS_df.loc[i] = [-1] elif ( ( df[dimension + m1 + suffix].iloc[i] &lt; df[dimension + m2 + suffix].iloc[i] ) and ( df[dimension + m2 + suffix].iloc[i] &lt; df[dimension + m3 + suffix].iloc[i] ) and ( df[dimension + m3 + suffix].iloc[i] &lt; df[dimension + m4 + suffix].iloc[i] ) ): TFS_df.loc[i] = [1] elif ( ( df[dimension + m1 + suffix].iloc[i] &lt; df[dimension + m2 + suffix].iloc[i] ) and ( df[dimension + m2 + suffix].iloc[i] &gt; df[dimension + m3 + suffix].iloc[i] ) and ( df[dimension + m3 + suffix].iloc[i] &lt; df[dimension + m4 + suffix].iloc[i] ) ): TFS_df.loc[i] = [1] elif ( ( df[dimension + m1 + suffix].iloc[i] &gt; df[dimension + m2 + suffix].iloc[i] ) and ( df[dimension + m2 + suffix].iloc[i] &lt; df[dimension + m3 + suffix].iloc[i] ) and ( df[dimension + m3 + suffix].iloc[i] &lt; df[dimension + m4 + suffix].iloc[i] ) ): TFS_df.loc[i] = [1] elif ( ( df[dimension + m1 + suffix].iloc[i] &gt; df[dimension + m2 + suffix].iloc[i] ) and ( df[dimension + m2 + suffix].iloc[i] &gt; df[dimension + m3 + suffix].iloc[i] ) and ( df[dimension + m3 + suffix].iloc[i] &lt; df[dimension + m4 + suffix].iloc[i] ) ): TFS_df.loc[i] = [0] elif ( ( df[dimension + m1 + suffix].iloc[i] &gt; df[dimension + m2 + suffix].iloc[i] ) and ( df[dimension + m2 + suffix].iloc[i] &lt; df[dimension + m3 + suffix].iloc[i] ) and ( df[dimension + m3 + suffix].iloc[i] &gt; df[dimension + m4 + suffix].iloc[i] ) ): TFS_df.loc[i] = [-1] elif ( ( df[dimension + m1 + suffix].iloc[i] &lt; df[dimension + m2 + suffix].iloc[i] ) and ( df[dimension + m2 + suffix].iloc[i] &gt; df[dimension + m3 + suffix].iloc[i] ) and ( df[dimension + m3 + suffix].iloc[i] &gt; df[dimension + m4 + suffix].iloc[i] ) ): TFS_df.loc[i] = [-1] elif ( ( df[dimension + m1 + suffix].iloc[i] &lt; df[dimension + m2 + suffix].iloc[i] ) and ( df[dimension + m2 + suffix].iloc[i] &lt; df[dimension + m3 + suffix].iloc[i] ) and ( df[dimension + m3 + suffix].iloc[i] &gt; df[dimension + m4 + suffix].iloc[i] ) ): TFS_df.loc[i] = [0] else: TFS_df.loc[i] = [0] return TFS_df </code></pre> <p>The function is called in below way -</p> <pre><code>report6_TLS_data['Revenue_TLS']=getTrafficLightData(report6_TLS_data, &quot;Revenue_&quot;,&quot;2020-6&quot;,&quot;2020-7&quot;,&quot;2020-8&quot;,&quot;2020-9&quot;) report6_TLS_data[&quot;Margin_TLS&quot;]=getTrafficLightData(report6_TLS_data, &quot;Margin_&quot;,&quot;2020-6&quot;,&quot;2020-7&quot;,&quot;2020-8&quot;,&quot;2020-9&quot;) report6_TLS_data[&quot;Overstrike_TLS&quot;]=getTrafficLightData(report6_TLS_data, &quot;Overstrike_&quot;,&quot;2020-6&quot;,&quot;2020-7&quot;,&quot;2020-8&quot;,&quot;2020-9&quot;) </code></pre> <p>Any pointers would be helpful.</p> <p>The input data is of form -</p> <pre><code>ym PART NUMBER BranchCode Revenue_2019-1 Revenue_2019-10 Revenue_2019-11 Revenue_2019-12 Revenue_2019-2 Revenue_2019-3 Revenue_2019-4 Revenue_2019-5 Revenue_2019-6 Revenue_2019-7 Revenue_2019-8 Revenue_2019-9 Revenue_2020-1 Revenue_2020-2 Revenue_2020-3 Revenue_2020-4 Revenue_2020-5 Revenue_2020-6 Revenue_2020-7 Revenue_2020-8 Revenue_2020-9 Margin_2019-1 Margin_2019-10 Margin_2019-11 Margin_2019-12 Margin_2019-2 Margin_2019-3 Margin_2019-4 Margin_2019-5 Margin_2019-6 Margin_2019-7 Margin_2019-8 Margin_2019-9 Margin_2020-1 Margin_2020-2 Margin_2020-3 Margin_2020-4 Margin_2020-5 Margin_2020-6 Margin_2020-7 Margin_2020-8 Margin_2020-9 Overstrike_2019-1 Overstrike_2019-10 Overstrike_2019-11 Overstrike_2019-12 Overstrike_2019-2 Overstrike_2019-3 Overstrike_2019-4 Overstrike_2019-5 Overstrike_2019-6 Overstrike_2019-7 Overstrike_2019-8 Overstrike_2019-9 Overstrike_2020-1 Overstrike_2020-2 Overstrike_2020-3 Overstrike_2020-4 Overstrike_2020-5 Overstrike_2020-6 Overstrike_2020-7 Overstrike_2020-8 Overstrike_2020-9 Transactions_2019-1 Transactions_2019-10 Transactions_2019-11 Transactions_2019-12 Transactions_2019-2 Transactions_2019-3 Transactions_2019-4 Transactions_2019-5 Transactions_2019-6 Transactions_2019-7 Transactions_2019-8 Transactions_2019-9 Transactions_2020-1 Transactions_2020-2 Transactions_2020-3 Transactions_2020-4 Transactions_2020-5 Transactions_2020-6 Transactions_2020-7 Transactions_2020-8 Transactions_2020-9 Margin_2019-1% Margin_2019-10% Margin_2019-11% Margin_2019-12% Margin_2019-2% Margin_2019-3% Margin_2019-4% Margin_2019-5% Margin_2019-6% Margin_2019-7% Margin_2019-8% Margin_2019-9% Margin_2020-1% Margin_2020-2% Margin_2020-3% Margin_2020-4% Margin_2020-5% Margin_2020-6% Margin_2020-7% Margin_2020-8% Margin_2020-9% Overstrike_2019-1% Overstrike_2019-10% Overstrike_2019-11% Overstrike_2019-12% Overstrike_2019-2% Overstrike_2019-3% Overstrike_2019-4% Overstrike_2019-5% Overstrike_2019-6% Overstrike_2019-7% Overstrike_2019-8% Overstrike_2019-9% Overstrike_2020-1% Overstrike_2020-2% Overstrike_2020-3% Overstrike_2020-4% Overstrike_2020-5% Overstrike_2020-6% Overstrike_2020-7% Overstrike_2020-8% Overstrike_2020-9% 0 BAGG001 BC 71.75 90.00 20.25 43.50 42.50 30.00 70.00 44.25 45.00 46.75 129.50 58.00 81.00 36.00 33.25 0.75 15.00 24.75 0.00 0.00 2.50 32.97 39.15 8.95 14.31 18.95 7.86 30.68 19.27 19.74 18.12 59.38 22.30 34.95 17.59 14.10 0.32 6.35 5.30 0.00 0.00 1.06 0.00 0.00 0.00 1.00 0.00 1.00 0.00 0.00 3.00 3.00 1.00 1.00 2.00 0.00 0.00 0.00 0.00 2.00 0.00 0.00 0.00 8 16 5 9 5 6 12 7 10 7 13 10 13 5 11 1 2 4 0 0 1 1.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00 0.00 0.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00 1.00 0.00 0.00 1.00 1 BAGG001 PK 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 25.50 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 9.90 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 1.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T21:01:56.420", "Id": "494592", "Score": "2", "body": "Your syntax is incorrect. Please fix your indentation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T22:34:47.040", "Id": "494598", "Score": "1", "body": "Looks like a copy paste error...`df[dimension + m2 + suffix].iloc[i] > df[dimension + m2 + suffix].iloc[i]`" } ]
[ { "body": "<p>It's important to understand that Pandas is a wrapper around Numpy, and both are geared toward vectorization. Avoid loops and repetition as much as possible, and this method can really be boiled down. It's worth saying that</p>\n<blockquote>\n<p>if month+1 &lt; Month for any value, then red else green.</p>\n</blockquote>\n<p>is absolutely <em>not</em> what's going on. For now I've made a proposed solution that deals with a fixed number of months using a lookup table. You can adapt it as necessary. It's based on the table that you showed, interpreting comparisons as bits in a field.</p>\n<p>Otherwise: don't bake an underscore into your <code>dimension</code> string; don't produce a double-underscore in the output dataframe; add type hints; and accept the months as a variadic argument or tuple.</p>\n<pre><code>import numpy as np\nimport pandas as pd\n\n\nlookup = np.array((-1, 0, -1, 1, -1, 1, 0, 1))\n\nto_binary = np.array((4, 2, 1)).T\n\n\ndef get_traffic_light_data_new(\n df: pd.DataFrame,\n dimension: str,\n *months: str,\n) -&gt; np.array:\n assert len(months) == 4\n by_month = df[[f'{dimension}_{month}' for month in months]].to_numpy()\n signs = by_month[:, 1:] - by_month[:, :-1] &gt; 0\n index = np.matmul(signs, to_binary)\n return lookup[index]\n\n\ndef test():\n scenarios = pd.DataFrame(\n [\n [3, 2, 1, 0],\n [1, 2, 3, 4],\n [1, 2, 1.5, 1.7],\n [2, 1, 3, 4],\n [3, 2, 1, 4],\n [3, 2, 2.5, 2.4],\n [5, 6, 1, 0],\n [3, 4, 5, 4],\n\n ],\n columns=(\n 'Revenue_2020-6',\n 'Revenue_2020-7',\n 'Revenue_2020-8',\n 'Revenue_2020-9',\n ),\n )\n args = (\n scenarios,\n 'Revenue',\n '2020-6',\n '2020-7',\n '2020-8',\n '2020-9',\n )\n new_result = get_traffic_light_data_new(*args)\n print(new_result)\n\n\nif __name__ == '__main__':\n test()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T08:14:57.110", "Id": "494624", "Score": "0", "body": "the condition I have stated is for input. what i mean here is the colurs on the inputs are based on above side. for example, if there are 4 months ( June july, Aug and September), and if you see first row on the input side, it means july revenue was less than june, august revenue was less than july and sep revenue was less than august, so all three are red. If all three are red, output should be red. and similarly for other conditions. The input data contains values for revenue for 4 months, then based on which condition it satisfies on the input side, output should be accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T13:37:40.770", "Id": "494645", "Score": "0", "body": "Your description violates scenario 3. There is a decrease, yet the output is green. Both your old implementation and my proposed implementation match the coloured table and not the description." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T20:24:29.867", "Id": "494686", "Score": "0", "body": "I guess I have not been clear in my comment. Apologies. What I am saying is if my data satisfies input condition for all 3 columns of the left side, my code should give me right hand (output) color. Thank you." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T23:10:46.217", "Id": "251279", "ParentId": "251266", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T19:07:25.077", "Id": "251266", "Score": "2", "Tags": [ "python", "performance" ], "Title": "Conditional traffic light system" }
251266
<p>I've been thinking about it for a while and, after asking <a href="https://vi.stackexchange.com/q/27704/6498">a question on vi.stackexchange</a>, I decided to write a small plugin myself and <a href="https://github.com/Aster89/WinZoZ" rel="nofollow noreferrer">put it on GitHub</a>; basically it offers a mapping to activate a kind of &quot;window movement&quot; mode where Vim waits for inputs that it appends to <kbd>Ctrl+w</kbd>, so that one does not have to press this combination before every window-related movement or action; hitting <kbd>Esc</kbd> exits this mode.</p> <p>It's mostly just one main function and one mapping, so I will copy them below.</p> <ul> <li>The mapping plus some things I copied from <a href="https://github.com/mtth/scratch.vim" rel="nofollow noreferrer">scratch.vim</a> which seemed reasonable:</li> </ul> <pre class="lang-none prettyprint-override"><code>&quot; plugin/winzoz.vim if (exists('g:winzoz_disable') &amp;&amp; g:winzoz_disable) || &amp;compatible finish endif nnoremap &lt;silent&gt; &lt;Plug&gt;(go-zoz-navigation) :call winzoz#goZoZ()&lt;cr&gt; if !exists('g:winzoz_no_mappings') nmap &lt;silent&gt; &lt;leader&gt;w &lt;Plug&gt;(go-zoz-navigation) endif </code></pre> <ul> <li>The function with the logic (plus a helper function for coloring the command line while the functionality is active)</li> </ul> <pre class="lang-none prettyprint-override"><code>&quot; autoload/winzoz.vim function! winzoz#goZoZ() redrawstatus! echohl Search echo s:make_status_line() echohl None let l:key = '' while l:key !=? &quot;\&lt;Esc&gt;&quot; let l:key = nr2char(getchar()) execute &quot;normal! \&lt;c-w&gt;&quot; . l:key redrawstatus! endw echo '' redrawstatus! endfunction &quot; drawing function function! s:make_status_line() let l:text = 'Go WinZoZ' let l:text .= repeat(' ', (&amp;columns - len(l:text))/2) return repeat(' ', &amp;columns - len(l:text) - 1) . l:text endfunction </code></pre> <p>I'd like some feedback in general, but also on the following points.</p> <ul> <li>As regards the logic, I'm not checking that the input is correct (with a <code>:try</code>-<code>:catch</code>-<code>:finally</code>), because I'm not inventing any functionality, but only forwarding the keys to the already existing functionality of <kbd>Ctrl+w</kbd>+<kbd>whatever</kbd>.</li> <li>I'm using <code>echohl Search</code> + <code>echo</code> to print a colored command line to make apparent when the mode is active; is this a good way of doing it? <ul> <li>Regarding this part, I had to make a trick (the <code>- 1</code> in the second to last line of code above) in order to have one character left for the blinking cursor. I really don't like this, but I don't know what else I could do...</li> </ul> </li> <li>There are some <kbd>Ctrl+w</kbd>-commands that take <em>two</em> key strokes, but my plugin cannot deal with them :( ... I'll fix when I have time.</li> <li>Do you like it?</li> <li>Do you think it could be useful?</li> </ul> <p>(I also plan to add some documentation to it, fwiw :/ )</p>
[]
[ { "body": "<p>As requested on vi.SE, here is my little view.</p>\n<p>First, I see a great quality in most patterns you have used: autoload plugin, plug-mappings, and so on. Good work!</p>\n<p>If I really had to nit-pick, it would be that:</p>\n<ul>\n<li>I find <code>l:</code> prefix to be cumbersome and useless in many situations</li>\n<li>I like to annotate my functions with <code>abort</code> in order to simplify error messages in case I'd introduce errors in future versions. <code>abort</code> should have been the default, but unfortunately, this is not the case.</li>\n<li><code>&quot;\\&lt;Esc&gt;&quot;</code> and <code>&quot;\\&lt;ESC&gt;&quot;</code> and <code>&quot;\\&lt;eSc&gt;&quot;</code> are the same character, using a case-insensitive comparator doesn't really make any sense. <code>!=#</code> would make more sense. I have an old habit, personally I simply use <code>!=</code> ^^'</li>\n</ul>\n<p>Regarding your question regarding <code>finally</code>, it could make sense to make sure to reset the highlighting used with <code>:echo</code> in case <code>make_status_line()</code> could fail. I don't see any other place where it could make sense.</p>\n<p>Regarding <code>catch</code> around <code>&lt;c-w&gt; + {key}</code>, it would depend on the user experience you want to provide. Use your plugin for some time, make some mistakes, and see how you'd like to see your plugin react.</p>\n<p>Regarding the highlight color, in my plugin I use <code>StatusLineNC</code> as it's similar to what <code>:substitute/pat/txt/c</code> seems to use. In <a href=\"https://github.com/LucHermitte/lh-vim-lib/blob/master/autoload/lh/ui.vim\" rel=\"nofollow noreferrer\">another plugin</a>, I use <code>Question</code>.</p>\n<blockquote>\n<p>Do you think it could be useful?</p>\n</blockquote>\n<p>Well. I know I could do without it. And yet a few times, I've been bothered by the number of times I had to hit <code>&lt;c-w&gt;&lt;down&gt;</code>. In the end I use the mouse. So... Why not. I'd have to make sure though that I never use <code>&lt;c-w&gt;</code> in a non-nore mapping.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T08:04:40.857", "Id": "494623", "Score": "0", "body": "As regards `finally` you are suggesting that the lines around there be `try`, `echo s:make_status_line()`, `finally`, `echohl None`, `endtry`. Is it so?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T10:47:46.697", "Id": "494630", "Score": "1", "body": "Indeed, the temporary highlight is the only resource you acquire and that you must be sure to release; this is the only place where `finally` could make sense. So. In case `s:make_status_line()` could fail (I don't think this is possible -- unless you introduce a bug), this is what should be done. As only a bug, and not an unexpected but plausible situation, could trigger an error here, IMO there is no need for `finally` here." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T23:03:47.127", "Id": "251278", "ParentId": "251269", "Score": "3" } } ]
{ "AcceptedAnswerId": "251278", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T21:21:20.700", "Id": "251269", "Score": "1", "Tags": [ "plugin", "vimscript", "vim" ], "Title": "Vim plugin for easy window navigation" }
251269
<p>I tried to implement a singly linked list myself, sorry it is not commented but I think it should be pretty self-explanatory, if not feel free to comment. I know that using namespace std; is not optimal, but I figured it would be okay for this little example. Same goes for defining the class right in the main.cpp file (and in the declaration). I have two questions:</p> <ol> <li>Is this even a correct implementation or did I miss something important? The methods worked as expected for me.</li> <li>Would it make any sense to use smart pointers here? If yes, why? And what would I have to change for it to work?</li> </ol> <p>Thank you for your time, I would appreciate any answers! :)</p> <pre><code>#include &lt;iostream&gt; using namespace std; struct Node { int32_t data; Node* next; }; class linked_list { public: linked_list() : last{ NULL }, tmp{ NULL }, begin{ NULL } {}; ~linked_list() { clear(); } void push_back(int32_t data) { if (begin) { tmp = new Node; tmp-&gt;data = data; tmp-&gt;next = NULL; last-&gt;next = tmp; last = tmp; tmp = NULL; } else { begin = new Node; begin-&gt;data = data; begin-&gt;next = NULL; last = begin; } } void display_all() { if (begin) { tmp = begin; while (tmp) { cout &lt;&lt; tmp-&gt;data &lt;&lt; endl; tmp = tmp-&gt;next; } tmp = NULL; } else { cout &lt;&lt; &quot;List is empty.&quot; &lt;&lt; endl; } } void clear() { while (tmp != last) { tmp = begin-&gt;next; delete begin; begin = tmp; } delete last; begin = NULL; tmp = NULL; last = NULL; } private: Node* last; Node* begin; Node* tmp; }; </code></pre> <p>PS:</p> <p>(Someone told me this would fit better on this site than on Stack Overflow so I am reposting.)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T21:59:23.260", "Id": "494595", "Score": "4", "body": "Welcome to Code Review! We only review working code here - after reading the body of your post it sounds like it does work, but your title makes it sound like you aren't sure. Can you [edit](https://codereview.stackexchange.com/posts/251273/edit) your question to make the title & body explicit that this works to the best of your knowledge?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-30T07:10:14.593", "Id": "494707", "Score": "0", "body": "`display_all`: Instead of hard-coding it as output to `cout`, allow output to an arbitrary ostream. Better yet, rewrite this to override `operator <<`" } ]
[ { "body": "<ul>\n<li><p><code>struct Node</code> would benefit from its own constructor. As a side note, if you don't want to expose <code>struct Node</code> to the client (and trust me, you don't), better make it private to <code>class LinkedList</code>.</p>\n</li>\n<li><p><code>tmp</code> doesn't deserve to be a class member. It is strictly local to each method.</p>\n</li>\n<li><p><strong>DRY</strong>. <code>push_back</code> could and should be streamlined:</p>\n<pre><code> struct Node * tmp = new Node(data);\n if (begin) {\n last-&gt;next = tmp;\n } else {\n begin = tmp;\n }\n last = tmp;\n</code></pre>\n</li>\n<li><p><code>display_all</code> should not print anything on the empty list. The caller might be greatly confused.</p>\n</li>\n<li><p><code>clear</code> could and should be streamlined. Run the loop till <code>nullptr</code>:</p>\n<pre><code> while (begin) {\n struct Node * tmp = begin-&gt;next;\n delete begin;\n begin = tmp;\n }\n last = nullptr;\n</code></pre>\n<p>As a side note, prefer <code>nullptr</code> to <code>NULL</code>.</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T23:18:10.077", "Id": "494602", "Score": "0", "body": "Thanks. Can you please explain further what you mean by \"streamlining\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T23:54:35.540", "Id": "494603", "Score": "0", "body": "@TomGebel See [here](https://www.lexico.com/en/definition/streamline), especially the second meaning; the emphasis on _simpler_. A very important concept in software engineering." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T00:08:03.583", "Id": "494604", "Score": "0", "body": "Oh, haha thanks. I thought it might be a technical term, english is not my mother tongue." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T10:48:12.230", "Id": "494631", "Score": "0", "body": "Actually, making `Node` a simple `struct` simplifies implementation of `linked_list`, and is thus the way to go." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-30T07:12:01.907", "Id": "494708", "Score": "0", "body": "For `clear`, this is not just streamlining - in the OP version it is not clear to me why `tmp != last` upon entry when the list is not empty (though this is *possibly* true somehow)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T22:28:33.647", "Id": "251274", "ParentId": "251273", "Score": "7" } }, { "body": "<h2>General Observations</h2>\n<p>Welcome to Code Review. It is helpful when you provide the code that tested the class as well as the class so that we can do a better code review.</p>\n<p>As noted by VNP modern C++ uses nullptr rather than NULL, this helps differentiate it from the C programming language.</p>\n<p>Obvious additional possible methods are <code>addNode()</code>, and <code>deleteNode()</code> although the push back method does basically implement the <code>addNode()</code> method. A method to search through the linked list might also be helpful.</p>\n<p>As VNP also noted it would be better if the class linked_list contained the class Node.</p>\n<p>If you follow VNP's advice about <code>display_all()</code> then that method becomes much simpler because the while loop won't be entered at all if <code>begin</code> is equal to nullptr.</p>\n<h2>Avoid <code>using namespace std;</code></h2>\n<p>If you are coding professionally you probably should get out of the habit of using the <code>using namespace std;</code> statement. The code will more clearly define where <code>cout</code> and other identifiers are coming from (<code>std::cin</code>, <code>std::cout</code>). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The identifier<code>cout</code> you may override within your own classes, and you may override the operator <code>&lt;&lt;</code> in your own classes as well. This <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">stack overflow question</a> discusses this in more detail.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T22:46:50.120", "Id": "251275", "ParentId": "251273", "Score": "6" } }, { "body": "<p>There's an implementation trick for linked lists which simplifies a lot of the logic. If your per-node data isn't too large that this is wasteful, consider</p>\n<pre><code>class linked_list\n{\n struct Node\n {\n int32_t data;\n Node* next;\n };\n\n Node sentinel {0, nullptr};\n Node *last {&amp;sentinel};\n\n // ...\n};\n</code></pre>\n<p>Now: you don't need a special case for an empty list, because <code>last</code> is always non-NULL. Just replace references to <code>begin</code> with <code>sentinel.next</code>.</p>\n<p>See how vnp's streamlined <code>push_back</code> becomes simpler still:</p>\n<pre><code>void push_back(int32_t data)\n{\n struct Node *tmp = new Node{data};\n last-&gt;next = tmp;\n last = tmp;\n}\n</code></pre>\n<hr />\n<p>Potential improvements:</p>\n<ul>\n<li><p>if the per-node data <em>is</em> too large, you can split the Node type into two parts:</p>\n<pre><code> struct NodeLink { NodeLink *next; };\n struct Node : public NodeLink { LargeObject data; };\n\n NodeLink sentinel {nullptr};\n NodeLink *last {&amp;sentinel};\n</code></pre>\n<p>This will add some casts when you're returning data, but doesn't otherwise complicate things too much.</p>\n</li>\n<li><p>if sentinel <em>does</em> contain data, and if your data type has a well-known &quot;invalid&quot; value, you should probably store that in <code>sentinel</code>. You should never be reading that field, so it's sensible to make it easy to detect.</p>\n</li>\n<li><p>consider documenting your class invariants, even when you don't comment every individual method. These invariants often give you clear conditions you can assert on, or write unit tests for, if things aren't behaving as you expect. For example:</p>\n<ol>\n<li><code>last</code> must <strong>never</strong> be <code>nullptr</code></li>\n<li><code>last-&gt;next</code> must <strong>always</strong> be <code>nullptr</code></li>\n<li><code>sentinel.next</code> must never point to <code>sentinel</code> (there are uses for circular lists, but that isn't what you've chosen to write)</li>\n<li><code>sentinel.data</code> (assuming the original Node structure) must never be read or written</li>\n<li>there must be no cycles in the list</li>\n</ol>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T23:25:46.463", "Id": "494695", "Score": "0", "body": "That can be done without storing a full Node in the linked_list class: Separate out the links, store them first, and store one set in the linked_list. Only convert from pointer to links to pointer to full Node when and if the Node must be destroyed or its data accessed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-30T10:04:13.320", "Id": "494722", "Score": "1", "body": "True, although I wanted to keep it simple for the _my first linked list_ implementation. I'm always surprised at how many tutorials miss out good practice even on the simplest structures." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-30T13:34:22.587", "Id": "494742", "Score": "0", "body": "True enough. I wonder why nobody mentioned the rule-of-three though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-30T14:20:00.950", "Id": "494748", "Score": "1", "body": "I really thought this answer was long enough covering only the core (more-or-less language agnostic) data structure. Actually coding the whole thing to what I'd consider a good standard seems ... probably worthwhile, but more effort than I have to spare." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T13:22:25.027", "Id": "251298", "ParentId": "251273", "Score": "6" } } ]
{ "AcceptedAnswerId": "251274", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T21:50:47.187", "Id": "251273", "Score": "6", "Tags": [ "c++", "beginner", "algorithm", "linked-list", "reinventing-the-wheel" ], "Title": "Implementation of Singly Linked List (C++)" }
251273
<p>I am trying to improved my coding skills. I mainly work in web development. I had a &quot;system&quot; that I use in all my projects to fetch data from my DB to the browser. I tried an implementation of OOP, it works fine, but I dont think I did it correctly.</p> <p>How can I optimized this code to make full use of an OOP design?</p> <pre><code>&lt;?php class DBX{ //---------------USER----------------------------- static function GetUserByEmail($email){ $link = openlink(); $query = &quot;SELECT * FROM users WHERE email = ? LIMIT 1&quot;; $stmt = mysqli_stmt_init($link); if (!mysqli_stmt_prepare($stmt, $query)) { //return false if there was an error return false; }else { mysqli_stmt_bind_param($stmt, &quot;s&quot;, $email); if (mysqli_stmt_execute($stmt)) { $result = $stmt-&gt;get_result(); // get the mysqli result $resultArray = $result-&gt;fetch_assoc(); $finalTest = $resultArray; } else { $finalTest = false; } } closeLink($stmt, $link); return $finalTest; } static function GetUserByID($id){ $link = openlink(); $query = &quot;SELECT * FROM users WHERE user_id = ? LIMIT 1&quot;; $stmt = mysqli_stmt_init($link); if (!mysqli_stmt_prepare($stmt, $query)) { //return false if there was an error return false; }else { mysqli_stmt_bind_param($stmt, &quot;i&quot;, $id); if (mysqli_stmt_execute($stmt)) { $result = $stmt-&gt;get_result(); // get the mysqli result $resultArray = $result-&gt;fetch_assoc(); $finalTest = $resultArray; } else { $finalTest = false; } } closeLink($stmt, $link); return $finalTest; } static function GetUsers(){ $link = openlink(); $query = &quot;SELECT * FROM users&quot;; $stmt = mysqli_stmt_init($link); if (!mysqli_stmt_prepare($stmt, $query)) { //return false if there was an error return false; }else { if (mysqli_stmt_execute($stmt)) { $result = $stmt-&gt;get_result(); // get the mysqli result $resultArray = $result-&gt;fetch_all(); $finalTest = $resultArray; } else { $finalTest = false; } } closeLink($stmt, $link); return $finalTest; } static function GetClients(){ $link = openlink(); $l = 4; $query = &quot;SELECT * FROM users WHERE access_level_id = ?&quot;; $stmt = mysqli_stmt_init($link); if (!mysqli_stmt_prepare($stmt, $query)) { //return false if there was an error return false; }else { mysqli_stmt_bind_param($stmt, &quot;i&quot;, $l); if (mysqli_stmt_execute($stmt)) { $result = $stmt-&gt;get_result(); // get the mysqli result $resultArray = $result-&gt;fetch_all(); $finalTest = $resultArray; } else { $finalTest = false; } } closeLink($stmt, $link); return $finalTest; } static function AddUser( $f_name, $l_name, $ll_name, $email, $access_level, $status, $phone, $joinDate, $clientNum, $hashedPW ){ $link = openlink(); $query = &quot;INSERT INTO users ( name, l_name, ll_name, phone, email, status, access_level_id, join_date, contract_id, password ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)&quot;; $stmt = mysqli_stmt_init($link); if (!mysqli_stmt_prepare($stmt, $query)) { //return false if there was an error return false; }else { mysqli_stmt_bind_param( $stmt, &quot;sssssiisss&quot;, $f_name, $l_name, $ll_name, $phone, $email, $status, $access_level, $joinDate, $clientNum, $hashedPW ); if (mysqli_stmt_execute($stmt)) { $result = $stmt-&gt;get_result(); // get the mysqli result $finalTest = true; } else { $finalTest = false; } } closeLink($stmt, $link); return $finalTest; } static function UpdateUser($id, $userInfo){ $link = openlink(); $query = &quot;UPDATE users SET name = ?, l_name = ?, ll_name = ?, email = ?, access_level_id = ?, phone = ?, status = ?, join_date = ?, contract_id = ?, password = ? WHERE user_id = ? LIMIT 1&quot;; $stmt = mysqli_stmt_init($link); if (!mysqli_stmt_prepare($stmt, $query)) { //return false if there was an error return false; }else { mysqli_stmt_bind_param( $stmt, &quot;ssssisisssi&quot;, $userInfo['name'], $userInfo['l_name'], $userInfo['ll_name'], $userInfo['email'], $userInfo['access_level_id'], $userInfo['phone'], $userInfo['status'], $userInfo['join_date'], $userInfo['contract_id'], $userInfo['password'], $id ); if (mysqli_stmt_execute($stmt)) { $result = $stmt-&gt;get_result(); // get the mysqli result $finalTest = true; } else { $finalTest = &quot;false5&quot;; } } closeLink($stmt, $link); return $finalTest; } static function UpdateUserPasswordByID($password, $id){ $link = openlink(); $query = &quot;UPDATE users SET password = ? where user_id = ? LIMIT 1&quot;; $stmt = mysqli_stmt_init($link); if (!mysqli_stmt_prepare($stmt, $query)) { //return false if there was an error return false; } else { mysqli_stmt_bind_param( $stmt, &quot;si&quot;, $password, $id ); if (mysqli_stmt_execute($stmt)) { $result = $stmt-&gt;get_result(); // get the mysqli result $finalTest = true; } else { $finalTest = false; } } closeLink($stmt, $link); return $finalTest; } //---------------ACCESS LEVELS----------------------------- static function GetAccessLevels(){ $link = openlink(); $query = &quot;SELECT * FROM access_levels&quot;; $stmt = mysqli_stmt_init($link); if (!mysqli_stmt_prepare($stmt, $query)) { //return false if there was an error return false; }else { if (mysqli_stmt_execute($stmt)) { $result = $stmt-&gt;get_result(); // get the mysqli result $resultArray = $result-&gt;fetch_all(); $finalTest = $resultArray; } else { $finalTest = false; } } closeLink($stmt, $link); return $finalTest; } //---------------Follow Ups----------------------------- static function GetFUByUserID($id){ $link = openlink(); $query = &quot;SELECT * FROM follow_up WHERE user_id = ? ORDER BY created_at DESC&quot;; $stmt = mysqli_stmt_init($link); if (!mysqli_stmt_prepare($stmt, $query)) { //return false if there was an error return false; }else { mysqli_stmt_bind_param($stmt, &quot;i&quot;, $id); if (mysqli_stmt_execute($stmt)) { $result = $stmt-&gt;get_result(); // get the mysqli result $resultArray = $result-&gt;fetch_all(); $finalTest = $resultArray; } else { $finalTest = false; } } closeLink($stmt, $link); return $finalTest; } static function AddFu($targetID, $senderID, $type, $message){ $link = openlink(); $date = date(&quot;Y-m-d H:i:s&quot;); $query = &quot;INSERT INTO follow_up (user_id, created_by, created_at, type, message) VALUES (?, ?, ?, ?, ?)&quot;; $stmt = mysqli_stmt_init($link); if (!mysqli_stmt_prepare($stmt, $query)) { //return false if there was an error return false; }else { mysqli_stmt_bind_param($stmt, &quot;iisis&quot;, $targetID, $senderID, $date, $type, $message); if (mysqli_stmt_execute($stmt)) { $result = $stmt-&gt;get_result(); // get the mysqli result $finalTest = true; } else { $finalTest = false; } } closeLink($stmt, $link); return $finalTest; } //-------REPURPUSING Pool //---------------USER----------------------------- static function QuickAddUser($email, $f_name, $l_name, $ll_names, $hashedPW){ $link = openlink(); $status = 1; $accessLevel = 8; $query = &quot;INSERT INTO users (email, f_name, l_name, ll_name, password, status, access_level_id) VALUES (?, ?, ?, ?, ?, ?, ?)&quot;; $stmt = mysqli_stmt_init($link); if (!mysqli_stmt_prepare($stmt, $query)) { //return false if there was an error return false; }else { mysqli_stmt_bind_param( $stmt, &quot;sssssii&quot;, $email, $f_name, $l_name, $ll_names, $hashedPW, $status, $accessLevel ); if (mysqli_stmt_execute($stmt)) { $result = $stmt-&gt;get_result(); // get the mysqli result $finalTest = true; } else { $finalTest = false; } } closeLink($stmt, $link); return $finalTest; } static function GetUserByUsername($username){ $link = openlink(); $query = &quot;SELECT * FROM users WHERE username = ? LIMIT 1&quot;; $stmt = mysqli_stmt_init($link); if (!mysqli_stmt_prepare($stmt, $query)) { //return false if there was an error return false; }else { mysqli_stmt_bind_param($stmt, &quot;s&quot;, $username); if (mysqli_stmt_execute($stmt)) { $result = $stmt-&gt;get_result(); // get the mysqli result $resultArray = $result-&gt;fetch_assoc(); $finalTest = $resultArray; } else { $finalTest = false; } } closeLink($stmt, $link); return $finalTest; } static function GetUsersByNames($string){ $link = openlink(); $string = &quot;%&quot;.$string.&quot;%&quot;; $query = &quot;SELECT * FROM users WHERE f_name LIKE ? OR l_name LIKE ? OR ll_name LIKE ?&quot;; $stmt = mysqli_stmt_init($link); if (!mysqli_stmt_prepare($stmt, $query)) { //return false if there was an error return false; }else { mysqli_stmt_bind_param($stmt, &quot;sss&quot;, $string, $string, $string); if (mysqli_stmt_execute($stmt)) { $result = $stmt-&gt;get_result(); // get the mysqli result $resultArray = $result-&gt;fetch_all(); $finalTest = $resultArray; } else { $finalTest = false; } } closeLink($stmt, $link); return $finalTest; } static function GetStudentsByGroupID($groupID){ $link = openlink(); $query = &quot;SELECT * FROM users WHERE group_id = ? ORDER BY l_name DESC&quot;; $stmt = mysqli_stmt_init($link); if (!mysqli_stmt_prepare($stmt, $query)) { //return false if there was an error return false; }else { mysqli_stmt_bind_param($stmt, &quot;i&quot;, $groupID); if (mysqli_stmt_execute($stmt)) { $result = $stmt-&gt;get_result(); // get the mysqli result $resultArray = $result-&gt;fetch_all(); $finalTest = $resultArray; } else { $finalTest = false; } } closeLink($stmt, $link); return $finalTest; } static function GetStudentsBySchoolYearID($yearID){ $link = openlink(); $query = &quot;SELECT * FROM users WHERE grado_id = ? ORDER BY l_name DESC&quot;; $stmt = mysqli_stmt_init($link); if (!mysqli_stmt_prepare($stmt, $query)) { //return false if there was an error return false; }else { mysqli_stmt_bind_param($stmt, &quot;i&quot;, $yearID); if (mysqli_stmt_execute($stmt)) { $result = $stmt-&gt;get_result(); // get the mysqli result $resultArray = $result-&gt;fetch_all(); $finalTest = $resultArray; } else { $finalTest = false; } } closeLink($stmt, $link); return $finalTest; } static function GetFamilyByChildID($userID){ $link = openlink(); $query = &quot;SELECT * FROM family_student WHERE student_id = ?&quot;; $stmt = mysqli_stmt_init($link); if (!mysqli_stmt_prepare($stmt, $query)) { //return false if there was an error return false; }else { mysqli_stmt_bind_param($stmt, &quot;i&quot;, $userID); if (mysqli_stmt_execute($stmt)) { $result = $stmt-&gt;get_result(); // get the mysqli result $resultArray = $result-&gt;fetch_all(); $finalTest = $resultArray; } else { $finalTest = false; } } closeLink($stmt, $link); return $finalTest; } static function GetChildrenByFamilyID($userID){ $link = openlink(); $query = &quot;SELECT * FROM family_student WHERE family_member_id = ?&quot;; $stmt = mysqli_stmt_init($link); if (!mysqli_stmt_prepare($stmt, $query)) { //return false if there was an error return false; }else { mysqli_stmt_bind_param($stmt, &quot;i&quot;, $userID); if (mysqli_stmt_execute($stmt)) { $result = $stmt-&gt;get_result(); // get the mysqli result $resultArray = $result-&gt;fetch_all(); $finalTest = $resultArray; } else { $finalTest = false; } } closeLink($stmt, $link); return $finalTest; } static function GetUserByIDArray($id){ $link = openlink(); $query = &quot;SELECT * FROM users WHERE user_id = ? LIMIT 1&quot;; $stmt = mysqli_stmt_init($link); if (!mysqli_stmt_prepare($stmt, $query)) { //return false if there was an error return false; }else { mysqli_stmt_bind_param($stmt, &quot;i&quot;, $id); if (mysqli_stmt_execute($stmt)) { $result = $stmt-&gt;get_result(); // get the mysqli result $resultArray = $result-&gt;fetch_all(); $finalTest = $resultArray; } else { $finalTest = false; } } closeLink($stmt, $link); return $finalTest; } static function GetUsersByAccessLevel($accessLevel){ $link = openlink(); $query = &quot;SELECT * FROM users WHERE access_id = ? ORDER BY l_name DESC&quot;; $stmt = mysqli_stmt_init($link); if (!mysqli_stmt_prepare($stmt, $query)) { //return false if there was an error return false; }else { mysqli_stmt_bind_param($stmt, &quot;i&quot;, $accessLevel); if (mysqli_stmt_execute($stmt)) { $result = $stmt-&gt;get_result(); // get the mysqli result $resultArray = $result-&gt;fetch_all(); $finalTest = $resultArray; } else { $finalTest = false; } } closeLink($stmt, $link); return $finalTest; } static function linkToStudentByTargetUserID($id, $studentID){ $link = openlink(); $query = &quot;INSERT INTO family_student (student_id, family_member_id) VALUES (?, ?)&quot;; $stmt = mysqli_stmt_init($link); if (!mysqli_stmt_prepare($stmt, $query)) { //return false if there was an error return false; } else { mysqli_stmt_bind_param( $stmt, &quot;ii&quot;, $studentID, $id ); if (mysqli_stmt_execute($stmt)) { $result = $stmt-&gt;get_result(); // get the mysqli result $finalTest = true; } else { $finalTest = false; } } closeLink($stmt, $link); return $finalTest; } static function UnlinkStudent($id, $studentID){ $link = openlink(); $query = &quot;DELETE FROM family_student WHERE student_id = ? AND family_member_id = ? LIMIT 1&quot;; $stmt = mysqli_stmt_init($link); if (!mysqli_stmt_prepare($stmt, $query)) { //return false if there was an error return false; } else { mysqli_stmt_bind_param( $stmt, &quot;ii&quot;, $studentID, $id ); if (mysqli_stmt_execute($stmt)) { $result = $stmt-&gt;get_result(); // get the mysqli result $finalTest = true; } else { $finalTest = false; } } closeLink($stmt, $link); return $finalTest; } static function AddStudentToGroup($groudID, $studentID){ $link = openlink(); $query = &quot;UPDATE users SET group_id = ? where user_id = ? LIMIT 1&quot;; $stmt = mysqli_stmt_init($link); if (!mysqli_stmt_prepare($stmt, $query)) { //return false if there was an error return false; } else { mysqli_stmt_bind_param( $stmt, &quot;ii&quot;, $groudID, $studentID ); if (mysqli_stmt_execute($stmt)) { $result = $stmt-&gt;get_result(); // get the mysqli result $finalTest = true; } else { $finalTest = false; } } closeLink($stmt, $link); return $finalTest; } static function UpdateUserPhotoByID($photoLoc, $id){ $link = openlink(); $query = &quot;UPDATE users SET profile_photo = ? where user_id = ? LIMIT 1&quot;; $stmt = mysqli_stmt_init($link); if (!mysqli_stmt_prepare($stmt, $query)) { //return false if there was an error return false; } else { mysqli_stmt_bind_param( $stmt, &quot;si&quot;, $photoLoc, $id ); if (mysqli_stmt_execute($stmt)) { $result = $stmt-&gt;get_result(); // get the mysqli result $finalTest = true; } else { $finalTest = false; } } closeLink($stmt, $link); return $finalTest; } static function UpdateUserStatusByID($id, $status){ $link = openlink(); if ($status) { $tempStatus = 1; } else { $tempStatus = 0; } $query = &quot;UPDATE users SET status = ? where user_id = ? LIMIT 1&quot;; $stmt = mysqli_stmt_init($link); if (!mysqli_stmt_prepare($stmt, $query)) { //return false if there was an error return false; } else { mysqli_stmt_bind_param( $stmt, &quot;ii&quot;, $tempStatus, $id ); if (mysqli_stmt_execute($stmt)) { $result = $stmt-&gt;get_result(); // get the mysqli result $finalTest = true; } else { $finalTest = false; } } closeLink($stmt, $link); return $finalTest; } //---------------SCHOOL GRADE YEARS----------------------------- static function AddSchoolYear($yearName){ $link = openlink(); $status = 1; $query = &quot;INSERT INTO grados ( name, status) VALUES (?, ?)&quot;; $stmt = mysqli_stmt_init($link); if (!mysqli_stmt_prepare($stmt, $query)) { //return false if there was an error return false; }else { mysqli_stmt_bind_param($stmt, &quot;si&quot;, $yearName, $status); if (mysqli_stmt_execute($stmt)) { $result = $stmt-&gt;get_result(); // get the mysqli result $finalTest = true; } else { $finalTest = false; } } closeLink($stmt, $link); return $finalTest; } static function GetSchoolYearGrades(){ $link = openlink(); $query = &quot;SELECT * FROM grados&quot;; $stmt = mysqli_stmt_init($link); if (!mysqli_stmt_prepare($stmt, $query)) { //return false if there was an error return false; }else { if (mysqli_stmt_execute($stmt)) { $result = $stmt-&gt;get_result(); // get the mysqli result $resultArray = $result-&gt;fetch_all(); $finalTest = $resultArray; } else { $finalTest = false; } } closeLink($stmt, $link); return $finalTest; } static function GetSchoolYearByID($id){ $link = openlink(); $query = &quot;SELECT * FROM grados WHERE grados_id = ? LIMIT 1&quot;; $stmt = mysqli_stmt_init($link); if (!mysqli_stmt_prepare($stmt, $query)) { //return false if there was an error return false; }else { mysqli_stmt_bind_param($stmt, &quot;i&quot;, $id); if (mysqli_stmt_execute($stmt)) { $result = $stmt-&gt;get_result(); // get the mysqli result $resultArray = $result-&gt;fetch_assoc(); $finalTest = $resultArray; } else { $finalTest = false; } } closeLink($stmt, $link); return $finalTest; } static function UpdateSchoolYear($id, $year){ $link = openlink(); $query = &quot;UPDATE grados SET name = ? WHERE grados_id = ? LIMIT 1&quot;; $stmt = mysqli_stmt_init($link); if (!mysqli_stmt_prepare($stmt, $query)) { //return false if there was an error return false; } else { mysqli_stmt_bind_param( $stmt, &quot;si&quot;, $year['name'], $id ); if (mysqli_stmt_execute($stmt)) { $result = $stmt-&gt;get_result(); // get the mysqli result $finalTest = true; } else { $finalTest = false; } } closeLink($stmt, $link); return $finalTest; } static function UpdateSchoolYearStatusByID($id, $status){ $link = openlink(); if ($status) { $tempStatus = 1; } else { $tempStatus = 0; } $query = &quot;UPDATE grados SET status = ? where grados_id = ? LIMIT 1&quot;; $stmt = mysqli_stmt_init($link); if (!mysqli_stmt_prepare($stmt, $query)) { //return false if there was an error return false; } else { mysqli_stmt_bind_param( $stmt, &quot;ii&quot;, $tempStatus, $id ); if (mysqli_stmt_execute($stmt)) { $result = $stmt-&gt;get_result(); // get the mysqli result $finalTest = true; } else { $finalTest = false; } } closeLink($stmt, $link); return $finalTest; } //---------------ACCESS LEVELS----------------------------- static function AddAccessLevel($yearName){ $link = openlink(); $query = &quot;INSERT INTO acess_levels (name) VALUES (?)&quot;; $stmt = mysqli_stmt_init($link); if (!mysqli_stmt_prepare($stmt, $query)) { //return false if there was an error return false; }else { mysqli_stmt_bind_param($stmt, &quot;s&quot;, $yearName); if (mysqli_stmt_execute($stmt)) { $result = $stmt-&gt;get_result(); // get the mysqli result $finalTest = true; } else { $finalTest = false; } } closeLink($stmt, $link); return $finalTest; } } //open link include 'dbConnect.inc.php'; //closing link function closeLink($stmt, $link){ mysqli_stmt_close($stmt); mysqli_close($link); } //date(&quot;Y-m-d H:i:s&quot;) ?&gt; </code></pre> <p>As you can see I repeat most of the code over and over, I think I could do one method for each CRUD and then somehow just pass the differences... any ideas??</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T22:58:41.123", "Id": "494599", "Score": "0", "body": "Why are you mixing procedural and oop mysqli syntax? I recommend only learning the oop style, because the procedural syntax is more verbose. (Too long to give a proper review right now)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T23:01:05.030", "Id": "494600", "Score": "0", "body": "Frankly, beacause I am not fully undrstanding OOP. That is the reason for this post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T23:09:30.417", "Id": "494601", "Score": "0", "body": "I am not talking about the design theory around OOP. I am only talking about the syntax of the `mysqli` functions/methods. Right now it is inconsistent." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T00:33:22.233", "Id": "494605", "Score": "0", "body": "This is my point. How can I make it more consitent. I frankensteined this code from many different sources, and just modified it to work together. Help me make it more consistent or at least point me to the right direction. Thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T07:22:14.313", "Id": "494621", "Score": "1", "body": "Object-oriented means we work with objects. Your code is just a static class. That is basically FP in OOP disguise... In a very short, there is no OOP without `$this`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T07:27:19.460", "Id": "494622", "Score": "0", "body": "Your code is fine to review I guess, but if all you care for is a rewrite to OOP style, I think that's a bit beyond the scope of Code Review, but you'll see..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T13:19:48.597", "Id": "494643", "Score": "0", "body": "First of all I would divide the code by responsibility and with that I would create more classes (it's too much code for understanding in minutes but, at least, I see functions that handle clients, other that handle users, other students, MySQL connection... that would be a nice start). That would be the S in SOLID (a set of principles that help to make an OOP design). When you get that division, start using the same MySQL class you created from the other classes (instantiate it in the constructor, for example). Then read more about SOLID and start applying and understanding the priciples." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T15:39:46.157", "Id": "494665", "Score": "0", "body": "Thank you very much, I would start reading on those concepts" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-01T12:05:55.287", "Id": "494928", "Score": "0", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." } ]
[ { "body": "<h3>1. This is not OOP</h3>\n<p>Ask yourself one simple question: what would happen if you remove words &quot;class&quot;, &quot;DBX&quot; and &quot;static&quot; from your code?</p>\n<p>Nothing.<br />\nNothing would happen. It would continue to work. Because your code is essentially <em>procedural</em>. There is not a hint of OOP, other than a Halloween costume.</p>\n<p>An object is not a collection of functions. It's a collection of functions and variables <code>working together</code>.</p>\n<p>Moreover, OOP is not about stuffing some functions and variables into a single entity either. OOP is about the <em>object interconnection</em>. Your code becomes OOP only when your objects talk to each other, use each other, pass information from each other.</p>\n<h3>2. At this stage, you can not and should not try to use OOP</h3>\n<ul>\n<li>First, there are other, much more pressing matters.</li>\n<li>Besides, Object Oriented Programming is a helluva complex matter. Nobody can learn it from a post on Stack Overflow. It takes years to grasp. An only after you get some experience with procedural and feel its limitations.</li>\n<li>After all, your goal is a more organized code which you confused with OOP. I can assure you, this code could be made 10 times more organized without any OOP.</li>\n</ul>\n<h3>3. Learn the object syntax first</h3>\n<p>You have to realize that OOP stands for <em>writing</em> classes only. Whereas using existing classes in your procedural code is just about a slightly different syntax. An incomparably simpler matter that you can grasp in 5 minutes. An mysqli is a perfect example that can demonstrate the difference. Instead of writing too werbose and uselessly elaborate code like this</p>\n<pre><code>mysqli_stmt_bind_param($stmt, &quot;s&quot;, $email);\n</code></pre>\n<p>you are just taking the <code>$stmt</code> part, then add an arrow, <code>-&gt;</code> and then add a meaningful function name without repeating words stmt and mysqli over and over again.</p>\n<pre><code>$stmt-&gt;bind_param(&quot;s&quot;, $email);\n</code></pre>\n<p>see, almost 2 times shorter!</p>\n<p>all you need to know that each object can contain a variable (called a property), a function (called a method) and a constant (called a class constant). And you call them as follows</p>\n<pre><code>$obj-&gt;property; // similar to a variable, no braces\n$obj-&gt;method($param); // similar to a function, with or without parameters\nCLASS::CONSTANT; // similar to regular constant but prefixed with class name and ::\n</code></pre>\n<h3>4. Start organizing your code without OOP</h3>\n<p>There are many techniques, let's see what we can do. Fist of all, having functions like yours is the right move. For the moment just have them as functions, not static methods. but they can be improved.</p>\n<h3>5. Fight the repetitions</h3>\n<p>As you correctly noticed, your current code repeats itself over an over. When you see a repetition, it's time to introduce a function. Definitely, all the code required to run a single mysql query is asking to be encapsulated in a function. Luckily, I already have one already made, exactly for the purpose:</p>\n<pre><code>function prepared_query($mysqli, $sql, $params, $types = &quot;&quot;)\n{\n $types = $types ?: str_repeat(&quot;s&quot;, count($params));\n $stmt = $mysqli-&gt;prepare($sql);\n $stmt-&gt;bind_param($types, ...$params);\n $stmt-&gt;execute();\n return $stmt;\n}\n</code></pre>\n<p>You may read the detailed description in my article, <a href=\"https://phpdelusions.net/mysqli/simple\" rel=\"nofollow noreferrer\">Mysqli helper function</a>.</p>\n<p>Just compare the two methods</p>\n<pre><code>static function GetUserByEmail($email){\n $link = openlink();\n $query = &quot;SELECT * FROM users WHERE email = ? LIMIT 1&quot;;\n $stmt = mysqli_stmt_init($link);\n if (!mysqli_stmt_prepare($stmt, $query)) {\n //return false if there was an error\n return false;\n }else {\n mysqli_stmt_bind_param($stmt, &quot;s&quot;, $email);\n if (mysqli_stmt_execute($stmt)) {\n $result = $stmt-&gt;get_result(); // get the mysqli result\n $resultArray = $result-&gt;fetch_assoc();\n $finalTest = $resultArray;\n } else {\n $finalTest = false;\n }\n }\n closeLink($stmt, $link);\n return $finalTest;\n}\n</code></pre>\n<p>vs</p>\n<pre><code>function GetUserByEmail($link, $email){\n $link = openlink();\n $query = &quot;SELECT * FROM users WHERE email = ? LIMIT 1&quot;;\n $stmt = prepared_query($link, $query, $email);\n $result = $stmt-&gt;get_result();\n return $result-&gt;fetch_assoc();\n}\n</code></pre>\n<p>Whoops! <strong>Three times</strong> less code!</p>\n<h3>6. Learn very important basic concepts</h3>\n<ul>\n<li>A database connection should be made only once. Create a db link at the beginning and then pass to your functions as a parameter</li>\n<li>Learn the proper <a href=\"https://phpdelusions.net/articles/error_reporting\" rel=\"nofollow noreferrer\">error reporting</a>. Simply returning false in case of error is absolutely not the way to go. An error must be reported to you, so you'll be able to fix it. the link is to my article that will give you an idea.</li>\n<li><code>static</code> methods must be used with caution. For the time being avoid them completely</li>\n<li>Consider formatting your code according to a <a href=\"https://www.php-fig.org/psr/psr-12/\" rel=\"nofollow noreferrer\">standard</a></li>\n</ul>\n<h3>7. Eventually, you could begin to learn OOP</h3>\n<ul>\n<li>First, you can group methods that belong to a single table, into distinct classes.</li>\n<li>When you notice that some methods in these classes have identical code, but only differ by the table name and the set of fields, then you can create a prototype (abstract) class with such methods that use <em>class variables</em> that hold the table and field names, and then <em>extend</em> your classes from it.</li>\n</ul>\n<p>Here is <a href=\"https://stackoverflow.com/a/58221204/285587\">an example of such a basic OOP</a> I am talking about. Using this approach, you will have a <code>User</code> class with <code>add()</code> and <code>get()</code> methods <em>without the need of writing <code>AddUser()</code> and <code>GetUser()</code> at all!</em> That will be OOP.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-01T10:50:12.663", "Id": "251414", "ParentId": "251276", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-28T22:53:57.757", "Id": "251276", "Score": "3", "Tags": [ "php", "object-oriented", "mysqli" ], "Title": "OOP: The correct use of classes and optimizing code" }
251276
<pre class="lang-py prettyprint-override"><code>answer = input(&quot;what's the word&quot;) answer_list = list(answer) #list version of the original word presentation = [] for i in range(len(answer_list)): presentation.append(&quot;_&quot;) #makes a list that shows the progress of the player during the game incorrect = 0 #number of allowed guesses completion = False # condition for end game while completion == False: attempt = input('guess') ind = 0 #index of the guess that appears in answer_list count = 0 #number of occurences of the guess in answer_list for x in answer_list: #searches for all occurences of the guess in answer_list and change presentation accordingly if x == attempt: num = answer_list.index(attempt) presentation[num] = attempt answer_list[num] = 0 #if there is an occurence, replace that occurence with 0 in answer_list count += 1 if count&gt;0: print (&quot;Your guess is correct, there was/were {} matches in the word&quot;.format(count)) print(presentation) elif count == 0: incorrect += 1 if incorrect == 5: print(&quot;You lost&quot;) break if any(answer_list) == False: #since all 0 have a negative truthy value, we can use any() to check if any element has a truthy value print(&quot;Congrats, you got everything correct&quot;) completion = True break </code></pre> <p>I want to make clean up this hangman game and format it as 1 or 2 functions. How do I make it work? For example, initializing lists could be initialize() and from the declaration of incorrect to the end of the code can be play_hangman(). I am still very new to python.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T01:21:00.497", "Id": "494606", "Score": "1", "body": "Welcome to the Code Review site where we review your working code and provide suggestions on how that working code can be improved. I agree that should should create functions, but we can't tell you how to do that. If you want a review of the current code we can do that. Please read our [guidelines on what makes a good question](https://codereview.stackexchange.com/help/asking) and what we can can can't help you with." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T12:29:35.467", "Id": "494642", "Score": "1", "body": "This code doesn't work. I run it, it asks me for the word, and fails immediately afterwards." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T16:27:27.790", "Id": "494671", "Score": "0", "body": "@C.Harley Is there an error when it fails? If so, what is the error? I tried [running it on onlinegdb.com](https://onlinegdb.com/S1EVpP_uD) and saw no failure as you described" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T17:18:11.800", "Id": "494681", "Score": "0", "body": "For anyone voting refactor requests as off-topic: please see answers to [this relevant meta](https://codereview.meta.stackexchange.com/q/9277/120114)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-30T12:02:13.267", "Id": "494730", "Score": "0", "body": "The error was \"NameError: name 'dog' is not defined\" when I used the word dog. This is in both python 2.7.16 and 3.6.1 - I added 3.8.5 this morning, the code worked in that version." } ]
[ { "body": "<p>Welcome to Code Review!</p>\n<h2>PEP-8</h2>\n<p>Since you're still new to python, it's a good idea to keep a window/tab open <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">with PEP-8 loaded</a> into it. It is mostly suggestions for coding style. Few things that can be picked up from the same:</p>\n<ul>\n<li>Comparisons to singletons like <code>None</code> should always be done with <code>is</code> or <code>is not</code>, never the equality operators.</li>\n<li>Comments should be complete sentences. The first word should be capitalized, unless it is an identifier that begins with a lower case letter (never alter the case of identifiers!).</li>\n<li><a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"noreferrer\">PEP 257</a> describes good docstring conventions. Note that most importantly, the <code>&quot;&quot;&quot;</code> that ends a multiline docstring should be on a line by itself:</li>\n</ul>\n<h2>Functions</h2>\n<p>As you've already raised this point, splitting the code into individual functions is always a good practice.</p>\n<h2><code>if __name__</code> block</h2>\n<p>Put the execution logic of your script inside the <code>if __name__ == &quot;__main__&quot;</code> block. Read more about the details on <a href=\"https://stackoverflow.com/a/419185/1190388\">why on stack overflow</a>.</p>\n<h2>f-string</h2>\n<p>Python 3.x also introduced literal string interpolation, or more commonly used term: <strong>f-string</strong>. Read more <a href=\"https://www.python.org/dev/peps/pep-0498/\" rel=\"noreferrer\">about it here (PEP-498)</a>.</p>\n<h2>Type hinting</h2>\n<p>When writing functions, you can also make use of type hinting to provide a more readable flow of your code to anyone. This helps removing the manual labour of having to backtrack variable types etc. More details can be found <a href=\"https://www.python.org/dev/peps/pep-0484/\" rel=\"noreferrer\">in PEP-484</a>.</p>\n<h2>Game logic</h2>\n<p>The initialisation of <code>presentation</code> array can be simplified to:</p>\n<pre><code>presentation = [&quot;_&quot;] * len(answer)\n</code></pre>\n<p>For every guessed character from the user, you keep looping over the <code>answer_list</code>, irrespective of validating whether the guess is correct or not.</p>\n<p>Before the loop over each character of the correct word, you have setup <code>ind = 0</code> which is never really used.</p>\n<p>Your global while loop relies on the condition <code>completion == False</code> (which should ideally be <code>completion is False</code>) but you <code>break</code> out before the loop/condition really has a chance to do so for you, making the variable useless.</p>\n<hr />\n<h2>Rewrite</h2>\n<pre><code>from typing import List\n\nMAX_ATTEMPTS: int = 5\n\n\ndef get_answer() -&gt; str:\n return input(&quot;What's the word? &quot;)\n\n\ndef correct_guess(char_count: int, guessed_word: List[str]):\n print(f&quot;Your guess is correct, there was/were {char_count} matches in the word.&quot;)\n print(&quot; &quot;.join(guessed_word))\n\n\ndef game_win(guessed_word: List[str]) -&gt; bool:\n return &quot;_&quot; in guessed_word\n\n\ndef game():\n answer = get_answer()\n correct_letters = set(answer)\n guessed_word = [&quot;_&quot;] * len(answer)\n incorrect = 0\n while True:\n if incorrect &gt;= MAX_ATTEMPTS:\n print(&quot;You lost!&quot;)\n break\n attempt = input(&quot;Guess: &quot;)\n if attempt not in correct_letters:\n incorrect += 1\n continue\n char_count = 0\n for index, char in enumerate(answer):\n if char == attempt:\n guessed_word[index] = char\n char_count += 1\n correct_guess(char_count, guessed_word)\n if game_win(guessed_word):\n print(&quot;Congrats, you got everything correct&quot;)\n break\n\n\nif __name__ == &quot;__main__&quot;:\n game()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-30T12:30:08.607", "Id": "494736", "Score": "0", "body": "We aren't supposed to provide a code writing service." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-30T12:42:57.723", "Id": "494738", "Score": "2", "body": "@pacmaninbw I was just bored at work...." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-30T07:25:56.633", "Id": "251326", "ParentId": "251281", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T00:43:32.303", "Id": "251281", "Score": "4", "Tags": [ "python", "python-3.x", "game", "hangman" ], "Title": "Hangman Game in Python-3" }
251281
<p>I have a working program that reads user input keys and echoes them back to the screen using the producer/consumer paradigm (the project requires you to use threads).</p> <p>While this program does work, it is unfortunately very inefficient. When I run the 'top' command, the CPU usage is over 200. Any suggestions to modify this code so it's not using up a significant percentage of the CPU? This is my first program using threads so I'm not sure if I am doing something wrong if this is normal haha. Thanks in advance.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;pthread.h&gt; #define NITEMS 10 // number of items in shared buffer // shared variables char shared_buffer[NITEMS]; // echo buffer int shared_count; // item count pthread_mutex_t mutex; // pthread mutex unsigned int prod_index = 0; // producer index into shared buffer unsigned int cons_index = 0; // consumer index into shard buffer // function prototypes void * producer(void *arg); void * consumer(void *arg); int main() { pthread_t prod_tid, cons_tid1, cons_tid2; // initialize pthread variables pthread_mutex_init(&amp;mutex, NULL); // start producer thread pthread_create(&amp;prod_tid, NULL, producer, NULL); // start consumer threads pthread_create(&amp;cons_tid1, NULL, consumer, NULL); pthread_create(&amp;cons_tid2, NULL, consumer, NULL); // wait for threads to finish pthread_join(prod_tid, NULL); pthread_join(cons_tid1, NULL); pthread_join(cons_tid2, NULL); // clean up pthread_mutex_destroy(&amp;mutex); return 0; } // producer thread executes this function void * producer(void *arg) { char key; printf(&quot;Enter text for producer to read and consumer to print, use Ctrl-C to exit.\n\n&quot;); // this loop has the producer read in from stdin and place on the shared buffer while (1) { // read input key scanf(&quot;%c&quot;, &amp;key); // this loop is used to poll the shared buffer to see if it is full: // -- if full, unlock and loop again to keep polling // -- if not full, keep locked and proceed to place character on shared buffer while (1) { // acquire mutex lock pthread_mutex_lock(&amp;mutex); // if buffer is full, release mutex lock and check again if (shared_count == NITEMS) pthread_mutex_unlock(&amp;mutex); else break; } // store key in shared buffer shared_buffer[prod_index] = key; // update shared count variable shared_count++; // update producer index if (prod_index == NITEMS - 1) prod_index = 0; else prod_index++; // release mutex lock pthread_mutex_unlock(&amp;mutex); } return NULL; } // consumer thread executes this function void * consumer(void *arg) { char key; long unsigned int id = (long unsigned int)pthread_self(); // this loop has the consumer gets from the shared buffer and prints to stdout while (1) { // this loop is used to poll the shared buffer to see if it is empty: // -- if empty, unlock and loop again to keep polling // -- if not empty, keep locked and proceed to get character from shared buffer while (1) { // acquire mutex lock pthread_mutex_lock(&amp;mutex); // if buffer is empty, release mutex lock and check again if (shared_count == 0) pthread_mutex_unlock(&amp;mutex); else break; } // read key from shared buffer key = shared_buffer[cons_index]; // echo key printf(&quot;consumer %lu: %c\n&quot;, (long unsigned int) id, key); // update shared count variable shared_count--; // update consumer index if (cons_index == NITEMS - 1) cons_index = 0; else cons_index++; // release mutex lock pthread_mutex_unlock(&amp;mutex); } return NULL; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T07:21:50.190", "Id": "494620", "Score": "0", "body": "Over 200 what? Threads? Percent? Common sense dictates that it isn't possible to use more than 100% of a CPU." } ]
[ { "body": "<h2>Pay attention when things explode</h2>\n<p>Let's <a href=\"https://pubs.opengroup.org/onlinepubs/007908799/xsh/pthread_mutex_init.html\" rel=\"nofollow noreferrer\">do some reading</a>.</p>\n<blockquote>\n<p>If successful, the <code>pthread_mutex_init()</code> and <code>pthread_mutex_destroy()</code> functions return zero. Otherwise, an error number is returned to indicate the error. The <code>[EBUSY]</code> and <code>[EINVAL]</code> error checks, if implemented, act as if they were performed immediately at the beginning of processing for the function and cause an error return prior to modifying the state of the mutex specified by <code>mutex</code>.</p>\n</blockquote>\n<p>This matters. For all we know, every single one of your pthread calls could be failing and you wouldn't know it. C doesn't hold your hand through this sort of thing - no exceptions are thrown; it's your responsibility to read the documentation for every function you call and check every return value for failure.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T01:48:02.900", "Id": "494607", "Score": "0", "body": "would that effect the cpu at all?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T02:06:51.167", "Id": "494608", "Score": "0", "body": "Yep. If a function inside a loop is failing and returning immediately, and the loop spins forever... how much CPU would that eat up?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T02:09:46.997", "Id": "494609", "Score": "0", "body": "ah okay I see, I was reading about conditional variables. I haven't used them before, would that be useful in this case?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T17:08:35.470", "Id": "494679", "Score": "1", "body": "@user232489 Yes, condition variables would help. But also search on CodeReview for posts from other people who submitted C++ implementations of multi-threaded producer/consumer queues, and study their code and the answers given there." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T01:29:58.040", "Id": "251284", "ParentId": "251282", "Score": "1" } }, { "body": "<p>Input is <em>s l o w</em>. Most of the time the buffer is empty, and the producer patiently waits for <code>scanf</code> to return. So the consumer loop</p>\n<pre><code> while (1)\n {\n // acquire mutex lock\n pthread_mutex_lock(&amp;mutex);\n\n // if buffer is empty, release mutex lock and check again\n if (shared_count == 0)\n pthread_mutex_unlock(&amp;mutex);\n else\n break;\n }\n</code></pre>\n<p>breaks <em>very rarely</em>. Most of the time it just busy waits. That explains the high CPU usage.</p>\n<p>Producer-consumer scenario requires not one, but two blocking points, one to block the producer, another to block the consumer. An easiest way out is to have two counting semaphores, <code>free_space</code> (initialized to <code>NITEMS</code>), and <code>data_space</code> (initialized to <code>0</code>). Producer shall wait on <code>free_space</code> and signal <code>data_space</code>, and consumer shall do vice versa.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T16:26:03.767", "Id": "251309", "ParentId": "251282", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T01:10:30.210", "Id": "251282", "Score": "4", "Tags": [ "performance", "c", "multithreading", "pthreads" ], "Title": "Thread Synchronization - CPU Usage exceeds 200 - C program" }
251282
<p>I am writing code that runs a simulation in an interactive way. The building blocks are:</p> <pre><code>runStep :: I -&gt; State S O runWorld :: World m -&gt; O -&gt; StateT W m I </code></pre> <p>Note that the world has some state <code>W</code> but is also allowed to have effects of type <code>m</code>. My question is about the function that feeds <code>runStep</code> and <code>runWorld</code> into each other. My current implementation is quite heavy on the <code>Control.Lens</code> noise:</p> <pre><code>sim :: (Monad m) =&gt; World m -&gt; StateT (I, S, O) m Result sim w = do inp &lt;- use _1 out &lt;- zoom _2 $ state . runState $ runStep inp inp' &lt;- zoom _3 $ runWorld w out _1 .= inp' return $ resultComputedPurelyFrom out </code></pre> <p>What I'd like to improve on this code is two things:</p> <ul> <li><p>Reduce the lens piping. I could, of course, get rid of <code>_1</code>, <code>_2</code> and <code>_3</code> by using a bespoke record type, but then that introduces its own noise -- <code>sim</code> is the only function that uses this particular combination of <code>I</code>, <code>S</code> and <code>O</code>.</p> </li> <li><p>The write-back to <code>inp'</code> could easily be accidentally omitted, resulting in not-obviously-wrong-looking, well-typed code that wouldn't work correctly.</p> </li> </ul> <p><strong>ETA</strong>: An alternative formulation is to forego the lens stuff completely, at the cost of making even the updating of the <code>S</code> component something that can be accidentally omitted:</p> <pre><code>sim :: (Monad m) =&gt; World m -&gt; StateT (I, S) (StateT O m) Result sim w = do (inp, s) &lt;- get let (out, s') = runState (runStep inp) s inp' &lt;- lift $ runWorld w out put (inp', s') return $ resultComputedPurelyFrom out </code></pre>
[]
[ { "body": "<blockquote>\n<p>What I'd like to improve on this code is two things:</p>\n<ul>\n<li>Reduce the lens piping. I could, of course, get rid of <code>_1</code>, <code>_2</code> and <code>_3</code> by using a bespoke record type, but then that introduces its own noise -- <code>sim</code> is the only function that uses this particular combination of <code>I</code>, <code>S</code> and <code>O</code>.</li>\n</ul>\n</blockquote>\n<p>Is this really a problem? I don't understand what could be improved about that part.</p>\n<blockquote>\n<ul>\n<li>The write-back to <code>inp'</code> could easily be accidentally omitted, resulting in not-obviously-wrong-looking, well-typed code that\nwouldn't work correctly.</li>\n</ul>\n</blockquote>\n<p>You can move the state-passing of <code>I</code> into a separate function for which that's the only job:</p>\n<pre><code>withInput :: ALens' s i -&gt; (i -&gt; StateT s i) -&gt; StateT s ()\nwithInput l go = do\n i &lt;- use (cloneLens l)\n i' &lt;- go i\n cloneLens l := i'\n\n...\nsim = do\n withInput _1 $ \\inp -&gt;\n inp' &lt;- ...\n pure inp'\n ...\n</code></pre>\n<p>The result type <code>()</code> of <code>withInput</code> makes it difficult to forget to update the state: the function would fail to typecheck if you forget the last clause.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-30T06:57:30.747", "Id": "494706", "Score": "0", "body": "The lens noise is a problem for my use case because this is for a book I'm writing, and the less lens experience required, the easier it will be for some of my readers." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T18:47:03.953", "Id": "251312", "ParentId": "251289", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T06:53:33.527", "Id": "251289", "Score": "4", "Tags": [ "haskell", "functional-programming" ], "Title": "Feeding stateful and stateful-effectful computations into each other" }
251289
<p>Questions about Parse, an application stack with storage, authentication and notifications.</p> <p><a href="https://parseplatform.org/" rel="nofollow noreferrer">Official website</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T09:28:44.060", "Id": "251292", "Score": "0", "Tags": null, "Title": null }
251292
Questions about Parse, including UI, cloud, server, platform, etc.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T09:28:44.060", "Id": "251293", "Score": "0", "Tags": null, "Title": null }
251293
<p>Consider this code, that uses EF Core wrapped inside the <code>unitOfWork</code> to manage the database:</p> <pre><code>public class UnitOfWork { private readonly Context DbContext; public async Task SaveChangesAsync(CancellationToken cancellationToken) =&gt; await DbContext.SaveChangesAsync(cancellationToken); public UnitOfWork(Context context) { this.DbContext = context ?? throw new ArgumentNullException(context.GetType().Name); } public async Task&lt;AggregateRoot&gt; GetAggregateRootByIdAsync(int id, CancellationToken cancellationToken) =&gt; await DbContext.AggregateRoots.FirstOrDefaultAsync(i =&gt; i.Id == id, cancellationToken); } </code></pre> <pre><code>public class Controller { private UnitOfWork unitOfWork; public Controller(UnitOfWork unitOfWork) { this.unitOfWork = unitOfWork; } [HttpDelete] [Route(&quot;{aggregateRootId}/child/{childId}&quot;)] public async Task&lt;IActionResult&gt; Delete([FromRoute] int aggregateRootId, [FromRoute]int childId, CancellationToken cancellationToken) { var aggregateRoot = await unitOfWork.GetAggregateRootByIdAsync(aggregateRootId, cancellationToken); if(aggregateRoot is null) return BadRequest(&quot;Not Found&quot;); if (!aggregateRoot.RemoveChildById(childId)) return BadRequest(&quot;Not found&quot;); await unitOfWork.SaveChangesAsync(cancellationToken); return Ok(); } } </code></pre> <p>Here, <code>AggregateRoot</code> contains the method to delete its child, due to the principle of</p> <blockquote> <p>All changes to the data must be done through the aggregate roots</p> </blockquote> <p>so as you can see, there will be a redundant select of the aggregate root along with all the children that seems to be useless.</p> <p>What do you think about this code and the mentioned problem above? Is there any way to improve it?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T11:58:56.693", "Id": "494638", "Score": "1", "body": "You have added what I asked for. I removed my down vote and close vote." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T20:48:57.367", "Id": "494687", "Score": "0", "body": "I would suggest avoiding using `GetAggregateRootByIdAsync` under `UnitOfWork`. Instead, implement a method inside the target `child` repository that would solve it like `Delete` or `GetAggregateRootIdAsync`. This would enforce aggregation along with maintainable API." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T09:45:32.447", "Id": "251294", "Score": "1", "Tags": [ "c#", "ddd" ], "Title": "Deleting a child of aggregate root in DDD" }
251294
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/250743/231235">A Summation Function For Arbitrary Nested Vector Implementation In C++</a> and <a href="https://codereview.stackexchange.com/q/250790/231235">A Summation Function For Various Type Arbitrary Nested Iterable Implementation in C++</a>. I am trying to implement a <code>recursive_sum</code> function for <a href="https://www.boost.org/doc/libs/1_63_0/libs/multi_array/doc/user.html" rel="nofollow noreferrer">the Boost Multidimensional Array Library</a>. The purpose of this <code>recursive_sum</code> function is to sum up each element in a input <code>boost::multi_array</code> data. The recursive structure here is similar to the previous implementation for <code>std::vector</code> and the other type nested iterable. Furthermore, I found that there are several types including <code>boost::multi_array</code>, <code>boost::detail::multi_array::sub_array</code> and <code>boost::detail::multi_array::const_sub_array</code> in Boost.MultiArray library. I am trying to handle these types with multiple overload function as below.</p> <pre><code>template&lt;class T&gt; requires is_summable&lt;T&gt; auto recursive_sum(const T&amp; input) { return input; } // Deal with the boost::multi_array case template&lt;class T, std::size_t Dims&gt; requires is_summable&lt;T&gt; auto recursive_sum(const boost::detail::multi_array::const_sub_array&lt;T, Dims&gt;&amp; input) { T sum_output{}; for (typename boost::multi_array&lt;T, Dims&gt;::index i = 0; i &lt; input.shape()[0]; i++) { sum_output += recursive_sum(input[i]); } return sum_output; } // Deal with the boost::multi_array case template&lt;class T, std::size_t Dims&gt; requires is_summable&lt;T&gt; auto recursive_sum(const boost::detail::multi_array::sub_array&lt;T, Dims&gt;&amp; input) { T sum_output{}; for (typename boost::multi_array&lt;T, Dims&gt;::index i = 0; i &lt; input.shape()[0]; i++) { sum_output += recursive_sum(input[i]); } return sum_output; } // Deal with the boost::multi_array case template&lt;class T, std::size_t Dims&gt; requires is_summable&lt;T&gt; auto recursive_sum(boost::multi_array&lt;T, Dims&gt;&amp; input) { T sum_output{}; for (typename boost::multi_array&lt;T, Dims&gt;::index i = 0; i &lt; input.shape()[0]; i++) { sum_output += recursive_sum(input[i]); } return sum_output; } </code></pre> <p>The used <code>is_summable</code> concept:</p> <pre><code>template&lt;typename T&gt; concept is_summable = requires(T x) { x + x; }; </code></pre> <p>The test for this <code>recursive_sum</code> function:</p> <pre><code>int main() { // Create a 3D array that is 3 x 4 x 2 typedef boost::multi_array&lt;double, 3&gt; array_type; typedef array_type::index index; array_type A(boost::extents[3][4][2]); // Assign values to the elements int values = 0; for (index i = 0; i != 3; ++i) for (index j = 0; j != 4; ++j) for (index k = 0; k != 2; ++k) A[i][j][k] = values++; auto recursive_sum_output = recursive_sum(A); std::cout &lt;&lt; &quot;recursive_sum_output: &quot; &lt;&lt; recursive_sum_output; return 0; } </code></pre> <p>All suggestions are welcome.</p> <ul> <li><p>Which question it is a follow-up to?</p> <p><a href="https://codereview.stackexchange.com/q/250743/231235">A Summation Function For Arbitrary Nested Vector Implementation In C++</a> and</p> <p><a href="https://codereview.stackexchange.com/q/250790/231235">A Summation Function For Various Type Arbitrary Nested Iterable Implementation in C++</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <p>The previous question is focused on the common containers in C++ STL, such as <code>std::vector</code>. The main idea in this question is trying to implement another type summation function which can deal with <code>boost::multi_array</code>.</p> </li> <li><p>Why a new review is being asked for?</p> <p>I found that there are three types of array structure in Boost.MultiArray library which are <code>boost::multi_array</code>, <code>boost::detail::multi_array::sub_array</code> and <code>boost::detail::multi_array::const_sub_array</code>. In order to handle these different type classes, there are three overload functions <code>recursive_sum</code> for dealing with each type separately. I am not sure is there any better way to simplify these overload functions. Moreover, if there is any possible improvement for this code, please let me know.</p> </li> </ul>
[]
[ { "body": "<h1>Implement a recursive <code>std::reduce()</code></h1>\n<p>You shouldn't need to special-case <code>boost::multi_array</code> and related types, as those types already act like STL containers (they provide <code>begin()</code> and <code>end()</code> for example). The main problem however is how to deduce the return type of <code>recursive_sum()</code>. Your functions seem to work because they deduce <code>T</code> from a <code>boost::multi_array&lt;T, Dims&gt;</code>, but do they really? Your <code>recursive_sum()</code> recurses over the <em>dimensions</em> of a <code>multi_array</code>, but it doesn't actually handle nested <code>multi_array</code>s, like for example:</p>\n<pre><code>boost::multi_array&lt;boost::multi_array&lt;double, 2&gt;, 3&gt; array;\n</code></pre>\n<p>The reason is that in the above case, calling <code>recursive_sum(array)</code> will deduce <code>T</code> to be a <code>boost::multi_array&lt;double, 2&gt;</code> instead of a <code>double</code>.</p>\n<p>To solve this issue, I would do what <a href=\"https://en.cppreference.com/w/cpp/algorithm/reduce\" rel=\"nofollow noreferrer\"><code>std::reduce()</code></a> does, and sidestep the issue by requiring an initial value for the sum. The type of this initial value will also be the return type. For example:</p>\n<pre><code>template&lt;class T, class ValueType, class Function = std::plus&lt;ValueType&gt;&gt;\nauto recursive_reduce(const T&amp; input, ValueType init, const Function&amp; f)\n{\n return f(init, input);\n}\n\ntemplate&lt;class Container, class ValueType, class Function = std::plus&lt;ValueType&gt;&gt;\nrequires is_iterable&lt;Container&gt;\nauto recursive_reduce(const Container&amp; input, ValueType init, const Function&amp; f = std::plus&lt;ValueType&gt;())\n{\n for (const auto &amp;element: input) {\n auto result = recursive_reduce(element, ValueType{}, f);\n init = f(init, result);\n }\n\n return init;\n}\n</code></pre>\n<p>Then you can call it like so:</p>\n<pre><code>boost::multi_array&lt;...&gt; array(...);\nstd::cout &lt;&lt; recursive_reduce(array, 0.0) &lt;&lt; &quot;\\n&quot;;\n</code></pre>\n<p>You could perhaps write some template to find the inner-most value type, so that you can use that as a default for the template parameter <code>ValueType</code> in <code>recursive_reduce()</code>, and then you can use <code>{}</code> as the default value for <code>init</code>, and be able to write:</p>\n<pre><code>std::cout &lt;&lt; recursive_reduce(array) &lt;&lt; &quot;\\n&quot;;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T16:59:15.780", "Id": "251310", "ParentId": "251295", "Score": "2" } } ]
{ "AcceptedAnswerId": "251310", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T10:03:16.363", "Id": "251295", "Score": "4", "Tags": [ "c++", "recursion", "boost" ], "Title": "A Summation Function For Boost.MultiArray in C++" }
251295
<p>Here is method to calculate age given the birth date in the format YYYYMMDD.</p> <pre><code>function getAge(dateString) { var today = new Date(); var birthDate = new Date(dateString); var age = today.getFullYear() - birthDate.getFullYear(); var m = today.getMonth() - birthDate.getMonth(); if (m &lt; 0 || (m === 0 &amp;&amp; today.getDate() &lt; birthDate.getDate())) { age--; } return age; } </code></pre> <p>Is it possible to make it more readable and easy to understand? I don't want moment.js</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T14:42:33.250", "Id": "494650", "Score": "2", "body": "Looks quite reasonable to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T15:16:47.517", "Id": "494661", "Score": "0", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T15:17:40.977", "Id": "494662", "Score": "0", "body": "https://stackoverflow.com/a/21984136/648075" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T15:32:20.813", "Id": "494664", "Score": "0", "body": "The shorter, accepted answer in the linked question has precision problems, as described. This is probably the best alternative, or near to it, though I'm not enthusiastic about the `age--`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T19:58:41.793", "Id": "494685", "Score": "0", "body": "This solution does not consider two special cases I can think of. 1. Some people were born under the Julian calendar, so the date must be converted to Gregorian first. 2. Under common law, a person is considered to reach a given age one day sooner than you would expect. A person born 10 Jan. 1999 became 21 under common law at the beginning of the day 9 Jan. 2020. Look it up: https://www.lexology.com/library/detail.aspx?g=9a48d1d7-d0d4-47de-a1f9-ad7b265ec416" } ]
[ { "body": "<p>I've removed the use of <code>m</code> and added comments for clarity:</p>\n<pre><code>function getAge(dateString) {\n var today = new Date();\n var birthDate = new Date(dateString);\n \n /* year difference */\n var age = today.getFullYear() - birthDate.getFullYear();\n \n /* check today: */\n if(\n /* is before birth month */\n (today.getMonth() &lt; birthDate.getMonth())\n \n /* or */\n ||\n (\n /* is birth month */\n (today.getMonth() == birthDate.getMonth())\n \n /* AND */\n &amp;&amp;\n /* is before birth day of month */\n (today.getDate() &lt; birthDate.getDate()) \n ) \n ) {\n /* =&gt; no birthday yet this year */\n /* so, one year less */\n age--;\n }\n return age;\n}\n</code></pre>\n<p>Hope this clarify what's going on in the original function.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-30T19:20:20.377", "Id": "251351", "ParentId": "251301", "Score": "0" } }, { "body": "<h2>Non standard date string YYYYMMDD</h2>\n<p>As pointed out in the comments <em>&quot;Looks quite reasonable...&quot;</em> and as such there is not too much to review...</p>\n<p>Well apart from the fact that <code>new Date(&quot;19671031&quot;)</code> is not a valid date The date string as parsed by Date must be a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#Date_Time_String_Format\" rel=\"nofollow noreferrer\">valid date strings</a>. (I did not spot this until halfway through the review)</p>\n<p>Ignoring the fact your code does not work as a simple oversight and continuing on as initially started...</p>\n<p>...I will therefor nit pick, and I do stress the point this is just nit picking for sake of a review.</p>\n<h2>Constants</h2>\n<p>Constants as <code>const</code> The named vars <code>today</code>, <code>birthDate</code>, <code>m</code> can all be const. In fact the whole thing can be rewritten to only use constants.</p>\n<h2>Names</h2>\n<p>Names are too verbose. The general rule is to use the scope to infer meaning, for names to preference 1 word over 2, 2 words over 3, etc... Short words rather than long. Common abbreviations instead of full words.</p>\n<ul>\n<li><code>birthDate</code> can be <code>birth</code> as date is inferred</li>\n<li><code>dateString</code> can be <code>dateStr</code> using the common abbreviation for string</li>\n<li><code>today</code> could be <code>now</code>. In context <code>today</code> is the most accurate however nothing is lost if <code>now</code> is used.</li>\n<li><code>m</code> does not work as <code>month</code>. The value represents a quantitative query (How many months?) and as such <code>months</code> or better yet the abbreviated <code>mths</code>... eww ... drop the <code>s</code> for <code>mth</code></li>\n</ul>\n<h2>Rewrite A</h2>\n<p>And then I realize it does not work</p>\n<pre><code>function getAge(dateStr) {\n const birth = new Date(dateStr);\n const now = new Date();\n const mth = now.getMonth() - birth.getMonth();\n const adjust = mth &lt; 0 || (mth === 0 &amp;&amp; now.getDate() &lt; birth.getDate()) ? 1 : 0;\n return now.getFullYear() - birth.getFullYear() - adjust;\n}\n</code></pre>\n<h2>Responsibility</h2>\n<p>A general rule for functions is that they should only do one thing. Your function has two tasks, parse the date string and calculate the age.</p>\n<p>As the date string is likely an un-trusted source (eg user input) and as such requires vetting which is outside the functions responsibility (inferred by the name <code>getAge</code>) the function should accept a Date rather than a string to parse.</p>\n<p>This solves the problem of incorrectly formatted date string.</p>\n<h2>Rewrite B</h2>\n<p>As the birth date is now an argument the simple name <code>birth</code> does not hold enough meaning to be clear so it is changed back to <code>birthDate</code></p>\n<pre><code>function getAge(birthDate) {\n const now = new Date();\n const mth = now.getMonth() - birthDate.getMonth();\n const adjust = mth &lt; 0 || (mth === 0 &amp;&amp; now.getDate() &lt; birthDate.getDate()) ? 1 : 0;\n return now.getFullYear() - birthDate.getFullYear() - adjust;\n}\n</code></pre>\n<h2>Parsing and vetting</h2>\n<p>The task of vetting and parsing the date string can now be handed to a more appropriate function.</p>\n<p>The function assumes that the format is YYYYMMDD and returns a date only if the Date accepts the year, month, and day extracted from the string, that the date is earlier than now. It will return an age that fits within the Date object range (age of historical births)</p>\n<p>If the date is invalid it can be said to be undefined and as such the function returns a <code>Date</code> or <code>undefined</code>.</p>\n<pre><code>function parseBirthDate(dateStr) {\n const birth = new Date(dateStr.slice(0,4), dateStr.slice(4,6), dateStr.slice(6,8)););\n const since = Date.now() - birth.getTime();\n return isNaN(since) || since &lt; 0 ? undefined : birth;\n}\n</code></pre>\n<p>Using the two functions to get an age.</p>\n<pre><code>const birth = parseBirthDate(&quot;19671031&quot;);\nconst age = birth ? getAge(birth) : undefined;\n</code></pre>\n<h2>Testing</h2>\n<p>A simple manual test snippet accepts a string input</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function getAge(birthDate) {\n const now = new Date();\n const mth = now.getMonth() - birthDate.getMonth();\n const adjust = mth &lt; 0 || (mth === 0 &amp;&amp; now.getDate() &lt; birthDate.getDate()) ? 1 : 0;\n return now.getFullYear() - birthDate.getFullYear() - adjust;\n}\nfunction parseBirthDate(dateStr) {\n const birth = new Date(dateStr.slice(0,4), dateStr.slice(4,6), dateStr.slice(6,8));\n const since = Date.now() - birth.getTime();\n return isNaN(since) || since &lt; 0 ? undefined : birth;\n}\nbirthDate.addEventListener(\"change\", () =&gt; {\n const birth = parseBirthDate(birthDate.value);\n const age = birth ? getAge(birth) : undefined;\n ageDisplay.textContent = age !== undefined ? \n \"Age: \" + age + \" years old\" : \n \"Invalid birth date!\";\n})\n </code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;label for=\"birthDate\"&gt;Enter birth date:&lt;/label&gt;\n&lt;input type=\"text\" id=\"birthDate\" maxlength=\"8\" placeholder = \"YYYYMMDD\" size=\"8\"&gt;\n&lt;div id=\"ageDisplay\"&gt;&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-31T14:36:09.203", "Id": "251378", "ParentId": "251301", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T14:39:14.133", "Id": "251301", "Score": "3", "Tags": [ "javascript", "datetime" ], "Title": "Calculate age given the birth date in the format YYYYMMDD" }
251301
<p>I have created a script where I add a timestamp to each value that has been found with a code that I have written:</p> <pre><code>import random from datetime import datetime, timedelta from typing import Dict, List import time class RequestFilter: &quot;&quot;&quot;Tracks requests and filters them to prevent hammering.&quot;&quot;&quot; def __init__(self, cooldown: timedelta): self._cooldown = cooldown self._requests: Dict[str, datetime] = {} def filter(self, requests: List[str], time: datetime) -&gt; List[str]: &quot;&quot;&quot;Filter requests to only those that haven't been made previously within our defined cooldown period.&quot;&quot;&quot; # Get filtered set of requests. filtered = [ r for r in list(set(requests)) if ( r not in self._requests or time - self._requests[r] &gt;= self._cooldown ) ] # Refresh timestamps for requests we're actually making. for r in filtered: self._requests[r] = time print(self._requests) return filtered if __name__ == '__main__': from time import sleep request_filter = RequestFilter(timedelta(minutes=5)) firstReq = [] for _ in range(random.randint(1,5)): firstReq.append(f&quot;US {random.randint(1, 10)}&quot;) for _ in range(100): newReq = [] for _ in range(random.randint(2, 8)): newReq.append(f&quot;US {random.randint(1, 10)}&quot;) if len(newReq) &gt; len(firstReq): print(request_filter.filter(newReq, datetime.now()), datetime.now()) sleep(1) firstReq = newReq else: print(&quot;Length is not bigger, testing again in 3 sec...&quot;) time.sleep(3) firstReq = newReq </code></pre> <p>As you can see at the very bottom i'm checking if the list size from previous request is less than newest request (at this momentit just random function but it would be reading from a HTML later on) and if it is, that means that something has been added to a webpage and we want to see what value has been added. If the value has already a timestamp then we check &quot;filter&quot; and see if it has been over 5 minutes difference in the timestamp and if its true then we should say &quot;New value has been found!&quot;</p> <p>However my improvements in general here is that I am not quite happy with the way that I check for length of firstReq vs newReq. and reason if that could be etc if I request a page and it has US 3 and then the newReq has value US 6 but it still will have 1 &gt; 1 which is false but still different value which will not print due to the 1 &gt; 1. My question is, how can I improve the code that I could skip the &lt; function and check maybe the sizes directly?</p>
[]
[ { "body": "<h2>Global code</h2>\n<p>Move the code after your <code>__main__</code> check into a function, since it's still in global scope.</p>\n<h2>PEP8</h2>\n<p><code>firstReq</code> should be <code>first_req</code>, and the same for <code>new_req</code>.</p>\n<h2>Dict comprehension</h2>\n<p>I would rearrange your <code>filtered</code> comprehension to be only a dict, and to use <code>dict.update</code>. In other words,</p>\n<pre><code>filtered = {r: self._requests.get(r) for r in requests}\n\nself._requests.update({\n r: time\n for r, orig_time in filtered.items()\n if orig_time is None or time - orig_time &gt;= self._cooldown\n})\n</code></pre>\n<h2>List comprehension</h2>\n<pre><code> firstReq = []\n for _ in range(random.randint(1, 5)):\n firstReq.append(f&quot;US {random.randint(1, 10)}&quot;)\n</code></pre>\n<p>can be</p>\n<pre><code>first_req = [\n f&quot;US {random.randint(1, 10)}&quot;\n for _ in range(random.randint(1, 5))\n]\n</code></pre>\n<h2>Diagnostic printing</h2>\n<pre><code> print(self._requests)\n</code></pre>\n<p>is out-of-place. Remove it, and if you still want this to happen, issue an equivalent statement from <code>main()</code>, perhaps printing the entire <code>RequestFilter</code> and overriding <code>__str__</code> to return <code>pprint.pformat(self._requests)</code>.</p>\n<h2>Change detection</h2>\n<p>Apparently what you actually want is to return a boolean that is true if <code>self._requests</code> has changed. This can be done like:</p>\n<pre><code>filtered = {r: self._requests.get(r) for r in requests}\n\nold_requests = dict(self._requests)\n\nself._requests.update({\n r: time\n for r, orig_time in filtered.items()\n if orig_time is None or time - orig_time &gt;= self._cooldown\n})\n\nreturn old_requests == self._requests\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T15:58:25.543", "Id": "494666", "Score": "0", "body": "Hello! I appreciate the advice and I will be right on it! About the pep8 I do agree. I was used to use the camelCase but will be changed to underscore instead :) About the `Dict comprehension` I tried to run the code you provided and it does give me an error `self._requests.update({ TypeError: cannot unpack non-iterable NoneType object` Im not sure what could be a cause of it at this moment. But also what should we return in that case if we in our case remove the filtered?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T15:58:27.727", "Id": "494667", "Score": "0", "body": "The `List comprehension` would it be really needed to have a list of different values if we check timestamp for each value that has been found anyways? In that case I wouldn't need `if len(newReq) > len(firstReq):` at all and incase I could just do the timestamp comprehension ? :D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T16:00:11.680", "Id": "494668", "Score": "1", "body": "Re. the `TypeError` - my mistake; I needed to use `.items()`. Please try again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T16:17:09.963", "Id": "494670", "Score": "0", "body": "Im having abit trouble to understand your `Dict comprehension` compare to what I have done. as I understood, im checking the currently request and compare it to the `self._requests` and if there is new value added then it will be added to the filtered list - which we can then return and assume its true (Meaning that there has been something being added from the filter function) else if there is no value added then it will return empty filtered list which will be False. Im not sure if you do the same?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T16:51:07.577", "Id": "494674", "Score": "0", "body": "If you're looking to return an indicator that `self._requests` has changed, there's a better way to do it. I'll update." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T16:53:25.930", "Id": "494675", "Score": "0", "body": "I would say I just want to know if there has been an update for a value or not, if it has been a update then return True or False if there havent been an update basically :) I think that would be enough for me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T17:00:24.783", "Id": "494676", "Score": "0", "body": "I would need more testing but I think it might look better! I did get an error saying: Expected type 'List[str]', got 'bool' instead for `def filter(self, requests: List[str], time: datetime) -> List[str]:` instead of List[str] it should be bool, would the change be a problem?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T17:04:23.030", "Id": "494677", "Score": "0", "body": "You'd need to update your return type hint, of course. And if you want to compare one dict to another, yes, you need `old_requests` to be a dict." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T17:12:37.487", "Id": "494680", "Score": "0", "body": "I will give it a try, its looking lots promising compare to what I had before actually :) Thank you very much for the review! - If I might ask, im just curious, what is the difference between what I had before vs. what you did? Is it better performens to have it the way you showed? Or faster, please let me know :D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T17:26:43.640", "Id": "494682", "Score": "0", "body": "Also after testing, it seems to return False even though it has added a new value into the dict or changed the timestamp. Are you sure that it is working as expected? I assume it should be != instead of == if we want to see if we have added a new value?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T17:36:15.907", "Id": "494683", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/115658/discussion-between-reinderien-and-protractornewbie)." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T15:50:02.037", "Id": "251307", "ParentId": "251302", "Score": "2" } } ]
{ "AcceptedAnswerId": "251307", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T14:40:24.890", "Id": "251302", "Score": "3", "Tags": [ "python" ], "Title": "Check if we find new value from a request" }
251302
<p>I'm making a game. There is a turtle and lots of platforms it can walk on. It walks on its own and you can change the direction it is walking. I implemented a working logic, but I think it can be improved.</p> <p>I made 2 classes (one for the turtle and one for the platforms).</p> <pre><code>class Turtle { public Rect HitBox; public bool IsMoving; public bool IsDirectionForward; public double DistanceWalked; public double MetersFalled; } class Ground { public Rect HitBox; } </code></pre> <p>Then I created a virtual Rect that would simulate the right width and height of the ground and the turtle only after using <strong>Inflate</strong> function.</p> <pre><code>public MainWindow() { InitializeComponent(); ground1 = new Ground(); ground1.HitBox = new Rect(groundImg1.Margin.Left, groundImg1.Margin.Top, groundImg1.Width, groundImg1.Height); ground1.HitBox.Inflate(0, -35); zelvicka = new Turtle(); zelvicka.IsMoving = true; zelvicka.IsDirectionForward = true; timer = new DispatcherTimer(); timer.Interval = TimeSpan.FromMilliseconds(20); timer.Tick += Update; timer.Start(); } </code></pre> <p>I've done the same with the turtle, whose virtual Rect is updating every time it moves in Update function generated by DispatcherTimer so the virtual Rect is always up to date.</p> <pre><code> private void Update(object sender, EventArgs e) { zelvicka.HitBox = new Rect(turtleImg.Margin.Left, turtleImg.Margin.Top, turtleImg.Width, turtleImg.Height); zelvicka.HitBox.Inflate(-110, -30); // ZELVICKA IS GOING FORWARD AND IS TOUCHING THE GROUND // ZELVICKA IS GOING BACKWARDS AND IS TOUCHING THE GROUND if (zelvicka.IsMoving &amp;&amp; zelvicka.IsDirectionForward &amp;&amp; zelvicka.HitBox.IntersectsWith(ground1.HitBox)) { turtleImg.Margin = new Thickness(zelvicka.DistanceWalked += 3, zelvicka.MetersFalled, 0, 0); } else if (zelvicka.IsMoving &amp;&amp; !zelvicka.IsDirectionForward &amp;&amp; zelvicka.HitBox.IntersectsWith(ground1.HitBox)) { turtleImg.Margin = new Thickness(zelvicka.DistanceWalked -= 3, zelvicka.MetersFalled, 0, 0); } } </code></pre> <p>Rate this code, please, and suggest improvements, if any.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T14:55:21.633", "Id": "494652", "Score": "0", "body": "It works properly, but I have to manually set new height and new width with Inflate function, which I found very ineffective and time-consuming, hence I'm looking for a better way as I don't think my code is good enough and it needs some more improvements!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T15:12:24.077", "Id": "494659", "Score": "0", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T14:45:22.397", "Id": "251303", "Score": "5", "Tags": [ "c#", "wpf" ], "Title": "Finding collision between two Images using virtual Rect" }
251303
<p>I'm trying to make some methods more reusable and have now three classes that work together: AbstractDao (the superclass), MemberDao (extends AbstractDao) and ProjectTaskDao (extendsAbstractDao). The method insert is very similar in both subclasses with some minor differences:</p> <p>insert method in MemberDao:</p> <pre><code>public void insert(Member member) throws SQLException { try (Connection connection = dataSource.getConnection()){ try(PreparedStatement statement = connection.prepareStatement( &quot;INSERT INTO members (member_name, email) values (?, ?)&quot;, Statement.RETURN_GENERATED_KEYS )){ statement.setString(1, member.getName()); statement.setString(2, member.getEmail()); statement.executeUpdate(); try (ResultSet generatedKeys = statement.getGeneratedKeys()) { generatedKeys.next(); member.setId(generatedKeys.getLong(&quot;id&quot;)); } } } </code></pre> <p>}</p> <p>insert method in ProjectTaskDao:</p> <pre><code>public void insert(ProjectTask task) throws SQLException { try (Connection connection = dataSource.getConnection()){ try(PreparedStatement statement = connection.prepareStatement( &quot;INSERT INTO project_tasks (task_name) values (?)&quot;, Statement.RETURN_GENERATED_KEYS )){ statement.setString(1, task.getName()); statement.executeUpdate(); try (ResultSet generatedKeys = statement.getGeneratedKeys()) { generatedKeys.next(); task.setId(generatedKeys.getLong(&quot;id&quot;)); } } } </code></pre> <p>}</p> <p>Thesee methods do the same with some minor differences with the &quot;statement.setSomething()&quot;. I`m not that advanced in Java yet so I'm kind of stuck on this. I would also like to pull these methods in as well:</p> <p>list method in MemberDao:</p> <pre><code>public List&lt;Member&gt; list() throws SQLException { List&lt;Member&gt; members = new ArrayList&lt;&gt;(); try (Connection connection = dataSource.getConnection()) { try (PreparedStatement statement = connection.prepareStatement(&quot;SELECT * FROM members&quot;)) { try (ResultSet rs = statement.executeQuery()) { while (rs.next()) { Member member = new Member(); member.setName(rs.getString(&quot;member_name&quot;)); members.add(mapRow(rs)); } } } } return members; </code></pre> <p>}</p> <p>list method in ProjectTaskDao:</p> <pre><code>public List&lt;ProjectTask&gt; list() throws SQLException { List&lt;ProjectTask&gt; tasks = new ArrayList&lt;&gt;(); try (Connection connection = dataSource.getConnection()) { try (PreparedStatement statement = connection.prepareStatement(&quot;SELECT * FROM project_tasks&quot;)) { try (ResultSet rs = statement.executeQuery()) { while (rs.next()) { //ProjectTask projectTask = new ProjectTask(); //projectTask.setName(rs.getString(&quot;&quot;)); tasks.add(mapRow(rs)); } } } } return tasks; </code></pre> <p>}</p> <p>And here is the whole superclass as it stands currently:</p> <pre><code>public abstract class AbstractDao&lt;T&gt; { protected final DataSource dataSource; public AbstractDao(DataSource dataSource) { this.dataSource = dataSource; } protected T retrieve(Long id, String sql) throws SQLException { try (Connection connection = dataSource.getConnection()) { try (PreparedStatement statement = connection.prepareStatement(sql)) { statement.setLong(1, id); try (ResultSet rs = statement.executeQuery()) { if (rs.next()) { return mapRow(rs); } else { return null; } } } } } protected abstract T mapRow(ResultSet rs) throws SQLException; </code></pre> <p>}</p> <p>Let me know if you need more information to help! Thanks :D</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T15:03:20.063", "Id": "494654", "Score": "0", "body": "Is your code working as you expect it to?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T15:04:15.450", "Id": "494655", "Score": "0", "body": "Yeah it works now, but wondering if it is possible to make it so i dont have to type the same method in every new classDao.java i make in the future." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T15:05:14.260", "Id": "494656", "Score": "1", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T15:09:25.920", "Id": "494657", "Score": "0", "body": "@PetterHaugland Sorry about my downvote then (removed it now), I earlier got the impression that you have asked for a review of code that wasn't working." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T15:10:16.123", "Id": "494658", "Score": "0", "body": "First time posting here so im dont really know everything here yet ':)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T15:15:24.730", "Id": "494660", "Score": "0", "body": "@PetterHaugland It's alright, this community is typically very welcoming and you will find nice people here, I suggest you read [ask] for good questions!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T15:23:24.490", "Id": "494663", "Score": "0", "body": "Yeah thats good to hear! I will read up on it :)" } ]
[ { "body": "<ol>\n<li><p>The first advise is to not over-architect the classes.</p>\n</li>\n<li><p>Keep alternatives in mind - <strong>JPA</strong> for instance <strong>eclipseLink</strong>. A bit of not reinventing the wheel as the database field has a long history of &quot;clever&quot; code.</p>\n<p>This is an <strong>O/R mapping</strong> translating data base Relations into java Objects and vice versa. For a beginner I would first refrain from such magic, and continue as you did. (Your <code>mapRow</code>.)</p>\n<p>The entity classes like <code>Member</code> in general are kept small without logic.\nAnd for every entity class there is a repository class with data access (retrieve and such). They rely on a persistence manager singleton instance that takes care of the connection per transaction session (time doing some task).</p>\n</li>\n<li><p>A long ID and using generated keys is used often.</p>\n<p>For the ID inheritance can be used. Too much inheritance can be painful however.</p>\n</li>\n</ol>\n<p>So keep <code>id</code> in its own base class, and do</p>\n<pre><code>public class Member extends IdEntity { ... }\n\npublic void insert(Member member) throws SQLException {\n try (Connection connection = dataSource.getConnection()) {\n try (PreparedStatement statement = connection.prepareStatement(\n &quot;INSERT INTO members (member_name, email) values (?, ?)&quot;,\n Statement.RETURN_GENERATED_KEYS)) {\n statement.setString(1, member.getName());\n statement.setString(2, member.getEmail());\n statement.executeUpdate();\n\n SQLUtils.fillGeneratedKeys(member, statement);\n }\n }\n}\n\npublic abstract class SQLUtils {\n\n public static void fillGeneratedKeys(IdEntity entity, PreparedStatement statement) throws SQLException {\n try (ResultSet generatedKeys = statement.getGeneratedKeys()) {\n generatedKeys.next();\n entity.setId(generatedKeys.getLong(&quot;id&quot;));\n }\n }\n</code></pre>\n<p>3a. Similar is the initialisation of a time stamp field. If you disregard the database server's clock and use java's clock, think of a locale independent time.</p>\n<ol start=\"4\">\n<li><p>Consider a &quot;transaction&quot; level; grouping of data base access.</p>\n<p>Several database operations, say some INSERTs and UPDATEs best function under the same connection. Possible as transaction, an error raising a rollback and otherwise the data is committed at the end. This cleans up the repetition of <code>try (Connection ...</code>.</p>\n</li>\n</ol>\n<p>In every case consider a <em>connection pool</em> or at least getting the connection by your own utility function.</p>\n<ol start=\"5\">\n<li>For query methods do not use null results but <code>Optional</code> or exceptions. It not only prevents NullPointerExceptions, but allows chaining:</li>\n</ol>\n<p>Several usage like:</p>\n<pre><code>A.retrieve().map(A::getChildren()).map(List::size).orElse(0);\n\nprotected Optional&lt;T&gt; retrieve(long id, String sql) throws SQLException {\n try (Connection connection = dataSource.getConnection()) {\n try (PreparedStatement statement = connection.prepareStatement(sql)) {\n statement.setLong(1, id);\n try (ResultSet rs = statement.executeQuery()) {\n if (rs.next()) {\n return Optional.of(mapRow(rs)=;\n }\n return Optional.empty();\n }\n }\n }\n}\n</code></pre>\n<p>Here <code>Long</code> can be <code>long</code> (It is a <code>long id</code> field too). For retrieve-by-id an exception would probably be better.</p>\n<p>Here it could be a painful use of inheritance as the child class provides logic; but it is okay.</p>\n<pre><code>protected abstract String retrieveByIdSQL();\n\npublic final T retrieveById(long id) throws SQLException {\n String sql = retrieveByIdSQL();\n try (Connection connection = dataSource.getConnection()) {\n try (PreparedStatement statement = connection.prepareStatement(sql)) {\n statement.setLong(1, id);\n try (ResultSet rs = statement.executeQuery()) {\n if (rs.next()) {\n return mapRow(rs);\n }\n throw new SQLException(...);\n }\n }\n }\n</code></pre>\n<ol start=\"6\">\n<li>Consider translating an SQLException to your own child of a RuntimeException, by rethrowing catched exceptions. Checked exceptions like SQLException <em>must</em> be catched,\nwhich nowadays with Stream usage can be cumbersome. But you could postpone this for the fare future.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-30T02:16:21.123", "Id": "494698", "Score": "0", "body": "Wow thanks for your time there! Ill try it out and mark it as answered " }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-30T16:58:05.143", "Id": "494765", "Score": "0", "body": "Thanks alot for the help! I have now figured it out and it works perfectly! :D" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T17:49:26.360", "Id": "251311", "ParentId": "251304", "Score": "3" } } ]
{ "AcceptedAnswerId": "251311", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T15:01:39.167", "Id": "251304", "Score": "5", "Tags": [ "java" ], "Title": "Code that lists and inserts data to database: Make methods more reusable in superclass" }
251304
<p>I have some piece of code that I already optimized, however I found that there is an edge case that I should handle and I am unable to make it elegant.</p> <pre><code>char* data = get_data_from_queue(data); Album album; get_album(data, &amp;album); if (get_album_vals(album) &lt;= 0) { printf(&quot;Album doesn't exist, will try to create it&quot;); return should_create_album(album); } do_stuff_with_data(&amp;data); </code></pre> <p>Now, when I don't find album vals, under certain conditions (&lt; 0.01%), it may be a golden album. If it is a golden album, under certain conditions (&lt;0.01%), it may need a second chance.</p> <p>This is the modified code that should keep same behavior, apart from the second chance for golden album:</p> <pre><code>char* data = get_data_from_queue(data); Album album; get_album(data, &amp;album); if (get_album_vals(album) &lt;= 0) { int is_golden_album = 0; ret = should_create_album(album); if (!ret &amp;&amp; album_might_be_golden(album)) { GoldenAlbum golden_album; if (get_golden_album(data, &amp;golden_album) { ret = should_create_album(golden_album); } else { is_golden_album = 1; } } if (is_golden_album &gt; 0) { return ret; } } do_stuff_with_data(&amp;data); </code></pre> <p>However the new code is awful and I am not sure how to make it more elegant and optimized and I have spent way too much time on this.</p> <p>Anyone have a suggestion?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-30T07:58:03.533", "Id": "494712", "Score": "2", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-30T12:02:26.097", "Id": "494731", "Score": "3", "body": "Welcome to the Code Review Site where we review actual working code from your project and provide suggestions on how to improve that code. There are 2 problems with the question that could make it off-topic for this site. Unlike stack overflow we need more code to be able to analyze how the code can be improved. Functions names like `do_stuff_with_data()` seem to indicate this is -topic.not the real code. If that is the real name of the function than we need to see the entire `do_stuff_with_data()` function. The code you have posted is not a complete function and that makes it off" } ]
[ { "body": "<p>The inelegance lies in the way you're storing your data. You haven't normalized it, so you have to check multiple places for what should be the same information.</p>\n<p>Why are golden albums in a different list? The fact that you need to check <em>that</em> list too, should be an indication that those two lists should be the same. Just like the artists, producers, and other information about the album, whether or not it's golden (and indeed, how many times, if I understand golden album status correctly) is an attribute of the data.</p>\n<p>You don't spend much time justifying why <code>GoldenAlbum</code> and <code>Album</code> are different types. Without knowing much about the data you're modeling, it's hard to be sure exactly what your data attempts to describe. So maybe I'm misunderstanding what 'golden' means for an 'album'. But if you have only one <code>Album</code> object and it has a <code>is_golden</code> attribute, you can avoid continuing to implement checks for both types of album in any code that interacts with the data by album name.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-31T21:01:06.347", "Id": "251389", "ParentId": "251313", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T20:02:43.543", "Id": "251313", "Score": "3", "Tags": [ "c" ], "Title": "Making code elegant, clean and optimized" }
251313
<p>I have rows in a database table with a <code>hierarchypath</code> column. The values in the column are hierarchy paths with up to four levels:</p> <pre><code>HIERARCHYPATH --------------------------------------------------- FACILITIES \ FIREHALL \ PLUMBING FACILITIES \ PARK ROADS \ GRASS/TURF BLVD MAINTENANCE ROADS \ SIDEWALKS \ REPLACEMENT FACILITIES \ PARKING - MAIN ST RECREATION \ BANDSHELL \ PROPERTY \ BUILDING-GENERAL FACILITIES </code></pre> <p>I've written a Jython 2.7 <a href="https://www.ibm.com/support/knowledgecenter/SSMAMS/com.ibm.mbs.doc/autoscript/c_automation_scripts.html" rel="nofollow noreferrer">automation script</a> that parses the levels at the <code>\</code> delimiter and inserts the values into individual level columns:</p> <ul> <li>CLASSL1</li> <li>CLASSL2</li> <li>CLASSL3</li> <li>CLASSL4</li> </ul> <pre><code>#Example: s = &quot;FACILITIES \ FIREHALL \ PLUMBING&quot; col_prefix = &quot;CLASSL&quot; #Note: The term &quot;mbo&quot; is an IBM Maximo concept. #It can be thought of as the currently selected record in the application. for i in range(0, 4): try: mbo.setValue(col_prefix + str(i+1), s.split(' \\ ')[i]) except: #Null-out any existing values that were not overriden mbo.setValueNull(col_prefix + str(i+1)) HIERARCHYPATH CLASSL1 CLASSL2 CLASSL3 CLASSL4 -------------------------------- ---------- ---------- ---------- ----------- FACILITIES \ FIREHALL \ PLUMBING FACILITIES FIREHALL PLUMBING null </code></pre> <hr /> <p>I'm relatively new to coding. How can the script be improved?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T23:27:04.273", "Id": "494696", "Score": "2", "body": "Why Jython? It's pretty old and unsupported." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T23:34:01.813", "Id": "494697", "Score": "0", "body": "@Reinderien Unfortunately, I don't have a choice. Jython is the standard scripting language for IBM Maximo. It's the only viable way to interact with the Java classes." } ]
[ { "body": "<h2>Normalization</h2>\n<p>A fully-normalized schema would not have four path component columns in a table; it would have one table with a string column for the path component, and a foreign key to its parent (and/or child), conceptually similar to a linked list. Advantages to this approach would be support for an arbitrarily long path. Disadvantage is likely decreased performance, though the scale of your problem is not clear.</p>\n<p>Otherwise, I find it odd that you're parsing a path, and storing the result of the parse back into the database alongside the original data. This is a fast-enough operation that surely any advantage to caching parse results is outweighed by the disadvantage of increased storage and fetch time.</p>\n<p>The only solid justification I can think of for such a thing is when (1) you know that certain interesting strings exist in fixed locations in the path, and (2) you need very fast, indexed querying on them, and (3) such querying is too slow when doing the usual pattern-matching approach on the original path.</p>\n<h2>Iteration</h2>\n<p>Don't use <code>range</code> for your loop; use <code>enumerate</code>. Also use a raw string due to your backslash.</p>\n<pre><code>for i, part in enumerate(s.split(r' \\ '), 1):\n</code></pre>\n<h2>Bare <code>except</code></h2>\n<p>Generally this is a bad idea. At the least, catch <code>Exception</code> instead, or more preferably the actual exception type you expect to see. If it's only an index error because you're trying to index into a split that has fewer than four components, just avoid that situation altogether:</p>\n<pre><code>parts = s.split(r' \\ ')\nfor i, part in enumerate(parts, 1):\n mbo.setValue(col_prefix + str(i), part)\nfor i in range(len(parts)+1, 5):\n mbo.setValueNull(col_prefix + str(i))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-30T16:11:51.523", "Id": "251346", "ParentId": "251314", "Score": "2" } } ]
{ "AcceptedAnswerId": "251346", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-29T21:14:38.770", "Id": "251314", "Score": "3", "Tags": [ "python", "python-2.x", "jython" ], "Title": "Parse backslash-delimited hierarchy path into separate columns" }
251314
<p>I've made a simple winhttp client in C++ and here is kind've the skeleton of the header file. I was thinking of initializing the session once and then using it throughout the rest of my http client structure. I don't know if this is super stupid but this was my thinking. This is just a skeleton of what I would like it to be and wanted to get a feel if this skeleton of a http client could be improved. Another question I have is: &quot;If I create multiple connections using WinHTTPConnect is that a bad idea and could their be issues, if so should I do something similar to how I have my session?&quot;</p> <pre class="lang-cpp prettyprint-override"><code>#ifndef HTTPLITE_H #define HTTPLITE_H #include &lt;Windows.h&gt; #include &lt;Winhttp.h&gt; //everything required in terms of imports and libraries #pragma comment(lib, &quot;winhttp.lib&quot;) class httplite { private: //creates our local session within our class HINTERNET sess = WinHttpOpen(NULL, WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, NULL ); public: httplite(); ~httplite(); LPCWSTR get( LPWSTR host, LPWSTR path=NULL, LPWSTR headers=NULL, boolean https=false ); LPCSTR post( LPWSTR host, LPWSTR path=NULL, LPCSTR content= NULL, LPWSTR headers= NULL, boolean https=false ); }; #endif HTTPLITE_H </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-30T05:22:44.703", "Id": "494702", "Score": "1", "body": "url consists of a few more fields: `schema/user/password/host/port/path/query/fragment` you should be able to handle all this in your `get` and `post` commands. user/password are rare. schema defines default port. host can by IP/domainName. query can support multiple of the same value." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-30T06:15:58.590", "Id": "494704", "Score": "0", "body": "@MartinYork thats a good point, I'll implement that. Otherwise does my class structure look fine? Do you think that I could run maybe 50-100 threads and not have issues?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-30T12:12:31.040", "Id": "494733", "Score": "1", "body": "Welcome to the Code Review site where we review actual working code from your project and provide suggestions on how to improve that code. The question indicates that this is not the actual code of the project and that makes the question off-topic for this site. If you want a good answer rather than a short answer in a comment please post the actual header file and possibly the .cpp file that implements the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-30T16:05:21.980", "Id": "494761", "Score": "1", "body": "@WindowsGoBRRRRRR Not really much to review here. HTTP and REST also allow for a couple of other commands. `PUT` and `DELETE` are relatively common. But you can find a full list here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-30T16:07:23.043", "Id": "494762", "Score": "2", "body": "@WindowsGoBRRRRRR I think adding `https` in this interface is the wrong thing to do. That is the next layer up. I would have `httplite` interface (that takes a URL) then have an `httpslite` interface that accepts an `httplite` as a member for the constructor and then wraps all the read/write calls so the correct encryption can be done before passing to the `httplite` interface for actual transport." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-30T02:12:56.043", "Id": "251319", "Score": "2", "Tags": [ "c++", "object-oriented", "http" ], "Title": "HTTP Client Skeleton" }
251319
<p>For one of my labs I need to write a complete java program which will simulate a &quot;very simple&quot; dice betting game. The specifications are as follows: simulate the throw of 3 dice. If you throw three sixes then you win $20; if you throw three of any other value then you win $10; if you throw two dice which are the same value then you win $5. If none of the conditions above are met, then you would lose $1.</p> <p><strong>Example Runs: Dice Throw</strong></p> <pre><code>Dice 1 : 2 Dice 2 : 1 Dice 3 : 2 Congratulations : You threw TWO - 2s You win $5 Dice 1 : 2 Dice 2 : 2 Dice 3 : 2 Congratulations : You threw THREE - 2s You win $10 Dice 1 : 4 Dice 2 : 6 Dice 3 : 3 Unfortunately : You did not throw anything of value You lose $1 </code></pre> <p>The resulting code that I wrote to solve this problem is as follows:</p> <pre><code>/** * SRN: 507-147-9 */ public class Lab6_part3 { public static void main(String[] args) { // define vars int round = 1; int dice1, dice2, dice3; while (round &lt;= 3) { dice1 = 1 + (int)(Math.random() * 6); dice2 = 1 + (int)(Math.random() * 6); dice3 = 1 + (int)(Math.random() * 6); System.out.println(); System.out.println(&quot;Dice 1 : &quot; + dice1 + &quot; Dice 2 : &quot; + dice2 + &quot; Dice 3 : &quot; + dice3); // Three of a kind if ((dice1 == dice2) &amp;&amp; (dice1 == dice3)) { // 3-of-a-kind (D1) // Rolls three sixes if (dice1 == 6) { System.out.println(&quot;Congratulations : You threw THREE - 6s&quot;); System.out.println(&quot;You win $20&quot;); } else { // Rolls three of anything else System.out.println(&quot;Congratulations : You threw THREE - &quot; + dice1 + &quot;s&quot;); System.out.println(&quot;You win $10&quot;); } } // Two of a kind (PRINT &quot;dice1&quot;) else if (dice1 == dice2 || dice1 == dice3) { System.out.println(&quot;Congratulations : You threw TWO - &quot; + dice1 + &quot;s&quot;); System.out.println(&quot;You win $5&quot;); } // Two of a kind (PRINT &quot;dice2&quot;) else if (dice2 == dice1 || dice2 == dice3) { System.out.println(&quot;Congratulations : You threw TWO - &quot; + dice2 + &quot;s&quot;); System.out.println(&quot;You win $5&quot;); } // Two of a kind (PRINT &quot;dice3&quot;) else if (dice3 == dice1 || dice3 == dice2) { System.out.println(&quot;Congratulations : You threw TWO - &quot; + dice3 + &quot;s&quot;); System.out.println(&quot;You win $5&quot;); } // Did not throw anything of value else { System.out.println(&quot;Unfortunately : You did not throw anything of value&quot;); System.out.println(&quot;You lose $1&quot;); } round++; } } } </code></pre> <p>The problem that I'm running into with this approach is that although the code functions as it's supposed to, I would like to have a simpler way to write the two-of-a-kind instead of having three &quot;if&quot; statements. My goal in this, is to create a three-way &quot;or&quot; statement instead of comparing dice1 with dice 2 and 3, and dice 2 with dice 1 and 3, etc...</p> <pre><code>else if (dice1 == dice2 || dice1 == dice3 || dice2 == dice3) { System.out.println(&quot;Congratulations : You threw TWO - &quot; + somethings?? + &quot;s&quot;); System.out.println(&quot;You win $5&quot;); </code></pre> <p>If I were to do that, how would I then be able to print out the value of the pair which I've identified?</p>
[]
[ { "body": "<p>Welcome to CodeReview. Regarding your issue, a quick solution is:</p>\n<pre><code>else if (dice1 == dice2 || dice1 == dice3 || dice2 == dice3) { \n int doubleNum = dice1 == dice2 ? dice1 : dice1 == dice3 ? dice1 : dice3;\n System.out.println(&quot;Congratulations : You threw TWO - &quot; + doubleNum + &quot;s&quot;);\n System.out.println(&quot;You win $5&quot;); \n}\n</code></pre>\n<p>The ternary operator makes the code more compact, but in this case I think it's a bit less readable than a chain of <code>if-else</code>.</p>\n<p>Few other suggestions:</p>\n<ul>\n<li>The while-loop can be replaced by a more convenient for-loop. From:\n<pre><code>int round = 1;\nwhile(round&lt;=3){\n //...\n round++;\n}\n</code></pre>\nTo:\n<pre><code>for(int round = 1; round &lt;= 3; round++) {\n //...\n}\n</code></pre>\n</li>\n<li>Declaring multiple variables in one line <code>int dice1, dice2, dice3;</code> is not considered <a href=\"https://google.github.io/styleguide/javaguide.html#s4.8.2-variable-declarations\" rel=\"noreferrer\">good practice</a> in Java.</li>\n<li>Instead of generating a random <code>float</code> and then casting it to an <code>int</code>, generate directly an <code>int</code> with <code>ThreadLocalRandom.current().nextInt(6)</code>. <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/ThreadLocalRandom.html#nextInt(int)\" rel=\"noreferrer\">Docs</a>.</li>\n<li>You can print the first line with <code>System.out.format</code>. From:\n<pre><code>System.out.println();\nSystem.out.println(&quot;Dice 1 : &quot; + dice1 + &quot; Dice 2 : &quot; + dice2 + &quot; Dice 3 : &quot; + dice3);\n</code></pre>\nTo:\n<pre><code>System.out.format(&quot;%nDice 1 : %d Dice 2 : %d Dice 3 : %n&quot;, dice1, dice2, dice3)\n</code></pre>\n</li>\n<li>Class names <a href=\"https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html\" rel=\"noreferrer\">should be PascalCase</a>. Instead of <code>Lab6_part3</code> you can name it <code>Lab6Part3</code>.</li>\n<li>Declare a constant for the number of rounds, to make it easier to change. For example:\n<pre><code>public class Lab6Part3 {\n\n private static final int ROUNDS = 3;\n\n public static void main(String[] args) {\n for(int round = 1; round &lt;= ROUNDS; round++) {\n //...\n }\n}\n</code></pre>\n</li>\n</ul>\n<p>Another approach is to generate three numbers with <code>Random#ints</code> and calculate the frequencies:</p>\n<pre><code>Random r = new Random();\n// Generate three random numbers from 1 to 6\nIntStream diceRolls = r.ints(3, 1, 7);\n\n// Generate map of frequencies\nMap&lt;Integer, Long&gt; freq = diceRolls.boxed()\n .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));\n\nboolean winner = false;\nfor (Entry&lt;Integer, Long&gt; entry : freq.entrySet()) {\n int number = entry.getKey();\n long times = entry.getValue();\n if (times == 3) {\n // Three of a kind ...\n winner = true;\n } else if (times == 2) {\n // Two of a kind...\n System.out.println(&quot;Congratulations : You threw TWO - &quot; + number + &quot;s&quot;);\n System.out.println(&quot;You win $5&quot;);\n winner = true;\n }\n}\nif(!winner) {\n // Did not throw anything of value\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-30T13:33:49.053", "Id": "494741", "Score": "1", "body": "Oooh good call using `ints`. I confess that would not have occurred to me -- though if this is OP's class assignment I'm not sure streams would be covered yet (or at all)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-30T18:59:55.850", "Id": "494771", "Score": "0", "body": "You can statically import `Collections.groupingBy`, `Collectors.counting`, and `Function.identity`, to slim down that call-site to just `.collect(groupingBy(identity(), counting()));`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-30T07:37:59.517", "Id": "251327", "ParentId": "251321", "Score": "7" } }, { "body": "<p>You don't need to have 3 else_if statements. There are 3 scenarios where you are in a &quot;two-fo-a-kind&quot; case. dice1==dice2, dice1==dice3, dice2==dice3. Your first if block catches 2 of these scenarios. The only other option is if dice2==dice3.</p>\n<p>If you think about it, your third else_If block would always create a true evaluation in one of the first two blocks, so your code will never reach it.</p>\n<pre><code>// Two of a kind (PRINT &quot;dice1&quot;)\nelse if (dice1 == dice2 || dice1 == dice3) {\n System.out.println(&quot;Congratulations : You threw TWO - &quot; + dice1 + &quot;s&quot;);\n System.out.println(&quot;You win $5&quot;);\n} \n \n// Two of a kind (PRINT &quot;dice2&quot;)\nelse if (dice2 == dice3) { \n System.out.println(&quot;Congratulations : You threw TWO - &quot; + dice2 + &quot;s&quot;);\n System.out.println(&quot;You win $5&quot;);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-30T14:40:55.337", "Id": "251342", "ParentId": "251321", "Score": "2" } }, { "body": "<blockquote>\n<pre><code> }\n \n // Two of a kind (PRINT &quot;dice1&quot;)\n else if (dice1 == dice2 || dice1 == dice3) {\n</code></pre>\n</blockquote>\n<p>Please don't do this. If you want to use the half-cuddled <code>else</code>, please write it always on two consecutive lines.</p>\n<pre><code> }\n else if (dice1 == dice2 || dice1 == dice3) {\n // Two of a kind (PRINT &quot;dice1&quot;)\n</code></pre>\n<p>There are two reasons.</p>\n<ol>\n<li>If I want to know that the structure is finished, this way I can see just by looking one line past the <code>}</code>. With your original, I would have to look an arbitrary number of lines to the next statement. This gets especially bad as the comment blocks get longer. It is entirely possible to write a comment that is taller than a single screen. Meaning that instead of simply scrolling a little farther, I would need to page down past the comment to see that there is an <code>else</code> block.</li>\n<li>If someone uses something that reformats the code to put the <code>else</code> on the same line as the <code>}</code>, it will have to move the comment anyway. Then even if they format it back, the comment will move. This causes confusion in source control. So just put it the way that the reformatter would from the beginning.</li>\n</ol>\n<p>C-style languages in general have confusing block handling. Because they use <code>}</code> both to end the structure and just to end the block in a continuing structure. I.e. they have no way to say that the <code>if</code> structure is ending versus continuing with an <code>else</code> of some sort. To compensate, we have to use coding conventions. And one of the simplest conventions, which transcends style, is to never put a curly-brace (<code>}</code> or <code>{</code>) more than one line away from the associated keyword if there is one.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-31T11:20:22.953", "Id": "251373", "ParentId": "251321", "Score": "2" } } ]
{ "AcceptedAnswerId": "251327", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-10-30T04:31:40.600", "Id": "251321", "Score": "7", "Tags": [ "java", "beginner", "dice" ], "Title": "Dice throwing simulation in Java" }
251321