body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>In call of Duty warzone, there is a Duos mode (Teams of two). As the game progresses and people are eliminated some teams might have just one player left and some still with two. The game tells you the number of players left and the number of teams. For example, 5 players left, 3 teams left. In this case we can know that this will be two teams of 2, and one team of 1.</p> <p>Anyway I worked out a formula for calculating the number of teams with 1 or 2 players. below is a short code and some test cases I would appreciate any review / feedback on.</p> <p><strong>source code</strong></p> <pre><code>from typing import Tuple def team_counts(players: int, teams: int) -&gt; Tuple[int, int]: if players &lt;= 0 or teams &lt;= 0: raise ValueError(f&quot;{players=}, {teams=} - Players and teams must be a positive value&quot;) if teams &gt; players or teams &lt; players / 2: raise ValueError(f&quot;{players=}, {teams=} - Teams must be less than players and greater than or equal to half of players&quot;) twos = players - teams ones = teams - twos return ones, twos </code></pre> <p><strong>Test code</strong></p> <pre><code>from teams_of_two import team_counts import pytest def test_players_teams_positive(): assert team_counts(players=1, teams=1) == (1, 0) def test_players_negative_teams_positive(): with pytest.raises(ValueError): team_counts(players=-1, teams=1) def test_players_positive_teams_negative(): with pytest.raises(ValueError): team_counts(players=1, teams=-1) def test_players_zero_teams_positive(): with pytest.raises(ValueError): team_counts(players=0, teams=1) def test_players_positive_teams_zero(): with pytest.raises(ValueError): team_counts(players=1, teams=0) def test_to_many_teams(): with pytest.raises(ValueError): team_counts(players=1, teams=2) </code></pre>
[]
[ { "body": "<p>Good job overall. You're developing good habits: you're testing your code, you've used the type annotations, you're using f-strings.</p>\n<p>If I were to be nit-picky, here's what I'd still suggest:</p>\n<ul>\n<li>some of your lines are too long and I have to horizontally scroll to see everything. try to shorten them as specified in <a href=\"https://www.python.org/dev/peps/pep-0008/#maximum-line-length\" rel=\"nofollow noreferrer\">PEP8</a></li>\n<li>add a docstrings to your function</li>\n<li>function names are usually describing an action so you should be calling yours something like: <code>def count_teams()</code> - I'm really bad at naming things but you got my point</li>\n</ul>\n<p>The final code would look like this:</p>\n<pre><code>from typing import Tuple\n\n\ndef count_teams(players: int, teams: int) -&gt; Tuple[int, int]:\n &quot;&quot;&quot;\n Calculate the number of teams with 1 or 2 players\n in call of Duty WarZone (Duos mode)\n &quot;&quot;&quot;\n\n if players &lt;= 0 or teams &lt;= 0:\n raise ValueError(f&quot;{players=}, {teams=} - Players and &quot;\n f&quot;teams must be a positive value&quot;)\n\n if teams &gt; players or teams &lt; players / 2: \n raise ValueError(f&quot;{players=}, {teams=} - Teams must be &quot;\n f&quot;less than players and greater than or&quot;\n f&quot; equal to half of players&quot;)\n\n twos = players - teams\n ones = teams - twos\n\n return ones, twos\n</code></pre>\n<p>As far as your tests go, the only thing you could improve is to parametrize the tests that are the same but use different values. You have on the <code>pytest</code>'s official docs <a href=\"https://docs.pytest.org/en/stable/example/parametrize.html#paramexamples\" rel=\"nofollow noreferrer\">some examples</a>.</p>\n<p>And another small nit-pick would be to first import the 3rd party libraries and then the local ones, with a blank line between each group:</p>\n<pre><code>import pytest\n\nfrom teams_of_two import team_counts\n\n\n# tests ...\n</code></pre>\n<p>LE: edited the chain comparison advice which wasn’t applicable in this case.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-26T23:56:03.733", "Id": "500811", "Score": "0", "body": "Thanks for an excellent and well presented answer. I will have a look at the parmeterising. If have just started with TDD so trying to write a test case then write the code and so on to build up my tests." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T10:50:18.700", "Id": "500821", "Score": "0", "body": "@KellyBundy I’m not sure what you’re trying to say. Feel free to add another answer if you still have improvements for OP’s code ^^" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T13:22:54.477", "Id": "500829", "Score": "0", "body": "They are saying it should be `players / 2 < teams < players`, unless teams is negative, which has already been ruled out." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T16:28:01.187", "Id": "500839", "Score": "0", "body": "Chain comparisons have an implied \"and,\" while OP's code has \"or.\" They're really cool and useful to know about, but not (I think) applicable in this case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T16:29:28.043", "Id": "500840", "Score": "0", "body": "Thinking about it a bit more, if you invert the condition and use De Morgan you can use a chain comparison: `if not (players/2 <= teams <= players): ... `. Although the text of OP's error there implies the `<= players` should maybe really be `< players`" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-26T23:12:35.620", "Id": "253942", "ParentId": "253940", "Score": "3" } } ]
{ "AcceptedAnswerId": "253942", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-26T22:40:13.010", "Id": "253940", "Score": "2", "Tags": [ "python" ], "Title": "calculate team sizes - Warzone - duos" }
253940
<p>I wanted a menu that is always a hamburger, regardless of screen size. Plus it has to be activated by click, not hover.</p> <p>Any comments / review will be appreciated.</p> <p>Pls let me know if this is not worded properly / off topic etc.</p> <p>Please see <a href="https://codepen.io/ganrang/pen/YzGEdyE" rel="nofollow noreferrer">Codepen</a></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset=&quot;utf-8&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt; &lt;title&gt;Sample website&lt;/title&gt; &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;css/test.css&quot;&gt; &lt;/head&gt; &lt;body&gt; &lt;div id=&quot;menuBar&quot;&gt; &lt;div class = &quot;menuHamburger&quot; onclick = &quot;hideAllButFirstChild('menuBar')&quot;&gt; &amp;#9776; &lt;/div&gt; &lt;ul id='menu1'&gt; &lt;li onclick=&quot;hideAllButFirstChild('menu1')&quot;&gt;Menu 1&lt;/li&gt; &lt;li&gt;Menu 1-1&lt;/li&gt; &lt;li&gt;Menu 1-2&lt;/li&gt; &lt;li&gt;Menu 1-3&lt;/li&gt; &lt;li&gt;Menu 1-4&lt;/li&gt; &lt;/ul&gt; &lt;ul id='menu2'&gt; &lt;li onclick=&quot;hideAllButFirstChild('menu2')&quot;&gt;Menu 2&lt;/li&gt; &lt;li&gt;Menu 2-1&lt;/li&gt; &lt;li&gt;Menu 2-2&lt;/li&gt; &lt;li&gt;Menu 2-3&lt;/li&gt; &lt;li&gt;Menu 2-4&lt;/li&gt; &lt;/ul&gt; &lt;ul id='menu3'&gt; &lt;li onclick=&quot;hideAllButFirstChild('menu3')&quot;&gt;Menu 3&lt;/li&gt; &lt;li&gt;Menu 3-1&lt;/li&gt; &lt;li&gt;Menu 3-2&lt;/li&gt; &lt;li&gt;Menu 3-3&lt;/li&gt; &lt;li&gt;Menu 3-4&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;script src=&quot;js/test.js&quot;&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; #menuBar &gt; ul { display: none; } ul { list-style-type: none; margin: 0; padding: 0; width: 10em; } li { list-style-type:none; margin: 1px; padding: 1px; } li:first-child { background: grey; color: #fff; } li:not(:first-child) { display: none; } .menuHamburger { font-size: 2em; } function hideAllButFirstChild(parentId) { var children = document.getElementById(parentId).children; for (var i=0; i &lt; children.length; i++) { if (children[i].style.display=='' || children[i].style.display=='none') { children[i].style.display=&quot;block&quot;; // but set its children to none? } else { // block all except first if (i != 0) { children[i].style.display=&quot;none&quot;; } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T19:42:02.900", "Id": "501206", "Score": "1", "body": "I've flagged this question for closure, because the code does not appear to work as intended. This is required to get a code review. To get help with non-working code, ask an on-topic question on Stackoverflow instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T22:06:31.727", "Id": "501222", "Score": "1", "body": "@Sumurai8 What's wrong with it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T22:24:47.910", "Id": "501224", "Score": "0", "body": "The site looks empty. Are you sure it's ready for review? Is this part of an actually working site?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T10:58:39.230", "Id": "501252", "Score": "0", "body": "The `hideAllButFirstChild` function does not seem to do what the function name claims it should do. It seems at most to be a toggle of sorts, but the \"hide all\" functionality seems to be missing or just doesn't work. The function also contains a question in a comment. Besides that the menu seems to be a prototype of sorts, missing critical things like... links... for example. And while that does seem like a minor gripe, links being clickable by nature cause all kinds of issues that are not even touched yet." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T04:19:04.950", "Id": "501315", "Score": "1", "body": "Hi, it's not a complete site just a menu and I wanted comments on its implementation. If you see the code pen, the menu expands and collapses on click. That's the part I would like reviewed for better approach or general advise etc." } ]
[ { "body": "<h1>HTML</h1>\n<ul>\n<li>The formating could be a bit cleaner (<code>&lt;/head&gt;</code> on its own line, superfluous spaces around <code>=</code>, content of <code>&lt;div id=&quot;menuBar&quot;&gt;</code> not indented).</li>\n<li><code>on...</code> attributes shouldn't be used. Event handlers should be assigned in the script.</li>\n<li>I don't believe <code>&amp;#9776;</code> (&quot;Trigram For Heaven&quot;) is a suitable character to use for a menu icon.</li>\n<li>The submenus aren't structured properly in my opinion:\n<ul>\n<li>The clickable header entries shouldn't be list items themselves, but separate elements before the <code>ul</code>.</li>\n<li>Also they should be an interactive elements such as <code>&lt;button&gt;</code> or <code>&lt;a&gt;</code>.</li>\n<li>If you would also wrap all the submenus in a separate item with the hamburger button before it, then you could simplify the JavaScript so that it simply toggles that single element, which spares you the loop and the exception of the first element.</li>\n<li>Alternatively you could even consider using the <a href=\"https://developer.mozilla.org/de/docs/Web/HTML/Element/details\" rel=\"nofollow noreferrer\"><code>&lt;details&gt;</code></a> element, which has the toggling built in, requiring no JavaScript at all.</li>\n</ul>\n</li>\n</ul>\n<h1>JavaScript</h1>\n<ul>\n<li>Instead of passing the ID of the parent element into the function you could get the clicked element (and thus its parent) from the event object. Example:</li>\n</ul>\n<pre><code>// Assign event handler in JavaScript instead of using the HTML attribute\ndocument.querySelector(&quot;.menuHamburger&quot;).addEventListener(&quot;click&quot;, hideAllButFirstChild);\n\nfunction hideAllButFirstChild(event) {\n // TODO Add null checks.\n const children = event.target.parent.children;\n\n // ...\n}\n</code></pre>\n<ul>\n<li>And as seen above use <code>const</code> or <code>let</code> instead of <code>var</code> for variables.</li>\n<li>Start the loop at <code>i = 1</code> to skip the first element instead of checking inside the loop.</li>\n<li>Instead of manipulating <code>style</code> in JavaScript set/remove a class (or, better, in this case the <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/hidden\" rel=\"nofollow noreferrer\"><code>hidden</code> attribute</a>)</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-02-03T03:49:47.177", "Id": "504204", "Score": "0", "body": "Thanks very much.. I'll amend accordingly. Sorry was busy with other stuff only saw today." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-15T15:57:42.673", "Id": "254752", "ParentId": "253945", "Score": "1" } } ]
{ "AcceptedAnswerId": "254752", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T04:12:55.237", "Id": "253945", "Score": "0", "Tags": [ "javascript", "html5" ], "Title": "Hamburger menu with Javascript - clearing state" }
253945
<p><br />I'm new to programming and python,this one of my biggest codes in python yet...<br /> I just wanted to know if you can simplify it further...<br /> English is not my first language, so corrections in the language are also welcomed!<br /> <em>Thank You In advance</em>!</p> <pre><code>x = int(input('Enter an integer who\'s root value you need: ')) e = int(input('Enter an +ve integer for root value: ')) #Removing the possiblities of zero in eihter of the variables if x==0: print('Zero power anything is zero!') elif e==0: print('Anything power zero is one!') else: while e &lt; 0: print('I SAID +VE INTEGER FOR ROOT!') x = int(input('Enter an integer who\'s root value you need: ')) e = int(input('Enter an +ve integer for root value: ')) while e %2 == 0 and x &lt; 0: print('-ve nos. can\'t have root value for even roots!') x = int(input('Enter an integer who\'s root value you need: ')) e = int(input('Enter an +ve integer for root value: ')) epsilon = 0.0000001 numGuesses = 0 if x&gt;0: low = -x elif x&lt;0: low = x if x&gt;0: high = max(1.0,x) elif x&lt;0: high = max(1.0,-x) ans = (high + low)/2.0 while abs(ans**e - x) &gt;= epsilon: print('low =', low, 'high =', high, 'ans =', ans) numGuesses += 1 if ans**e &lt; x: low = ans else: high = ans ans = (high + low)/2.0 print('numGuesses =', numGuesses) print(ans, 'is close to the value of', e, 'root', x) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T16:16:02.453", "Id": "500837", "Score": "1", "body": "Note that the size of python integers is limited only by the available memory, whereas python floats have a maximum/minimum size. What size constraints did you want to place on the inputs? Note that with python's `decimal` and `fractions` modules you have a lot of flexibility to work with arbitrarily large values and manage performance, accuracy, and code complexity tradeoffs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T22:52:58.903", "Id": "500861", "Score": "1", "body": "There is repetition of code for input of x,e - would be nice to move it to separate function(x, e = user_input()). It is easier to see value of epsilon in scientific notation(epsilon = 1e-7). Extra comment would be nice. Camelcase -> underscores." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T13:05:15.490", "Id": "500906", "Score": "0", "body": "Thank you @President James K. Polk\nI will use floats to make the code more flexibile when desired" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T13:08:59.600", "Id": "500907", "Score": "0", "body": "@Vashu thank you fro your your comment ,I will definetly do so!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T17:21:13.810", "Id": "500936", "Score": "2", "body": "The assumption in your first `if` statement is false, since [0°=1](https://en.wikipedia.org/wiki/Zero_to_the_power_of_zero). I.e. your `if` check and the following `elif` check should be switched." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T19:09:15.270", "Id": "500942", "Score": "0", "body": "@RichardNeumann Thank you for that comment! I never knew that 0^0 = 1,\nThank you for it again. I'll edit the code!" } ]
[ { "body": "<p>Ignoring points already made in comments...</p>\n<h1>Escapes</h1>\n<p><code>x = int(input('Enter an integer who\\'s root value you need: '))</code></p>\n<p>I find reading this line of code jarring. There is an escape <code>\\'</code> in the middle of the string. Python gives many different types of literal strings with allow you to embed special characters in strings without using escapes. At the simplest end of the spectrum, a double-quoted string will allow you to embed a single quote without an escape.</p>\n<p><code>x = int(input(&quot;Enter an integer who's root value you need: &quot;))</code></p>\n<p>There are also triple-quoted strings <code>&quot;&quot;&quot;...&quot;&quot;&quot;</code> or <code>'''...'''</code> both of which will allow you to embed unescaped single and double quotes, as well as new lines. You don't need this here, but it is good to be aware of.</p>\n<h1>Input Validation</h1>\n<p>Your validation has holes.</p>\n<p>At the first pair of prompts, enter &quot;1&quot; and &quot;-1&quot;. This causes you to enter the <code>while e &lt; 0:</code> loop, where you can enter another pair, like &quot;-1&quot; and &quot;2&quot;. This will cause you to enter the <code>while e %2 == 0 and x &lt; 0:</code> loop, where you can enter &quot;0&quot; and &quot;0&quot;.</p>\n<p>At this point, <code>x</code> is neither greater than or less than zero, so neither <code>low</code> nor <code>high</code> are assigned a value, causing an exception at <code>ans = (high + low)/2.0</code></p>\n<p>You want the earlier tests to be repeated for the new inputs. This is easiest achieved with a single while loop around the input.</p>\n<pre class=\"lang-py prettyprint-override\"><code>while True:\n x = int(input(&quot;Enter an integer who's root value you need: &quot;))\n e = int(input(&quot;Enter an +ve integer for root value: &quot;))\n\n if e &lt; 0:\n print(&quot;I SAID +VE INTEGER FOR ROOT!&quot;)\n elif e % 2 == 0 and x &lt; 0:\n print(&quot;-ve nos. can't have root value for even roots!&quot;)\n else:\n # The input is now good, exit the while-loop.\n break\n\nif x==0:\n print(&quot;Zero power anything is zero!&quot;)\nelif e==0:\n print(&quot;Anything power zero is one!&quot;)\nelse:\n epsilon = 0.0000001\n numGuesses = 0\n ...\n</code></pre>\n<p>Now, the input is requested. If it fails either test, the <code>while</code> loop repeats, and all the validation checks are repeated with the new input.</p>\n<h1>Exceptions</h1>\n<p>If the user enters a non-integer value, <code>int(...)</code> will raise an <code>ValueError</code> exception. You could be kind and capture that as well.</p>\n<pre class=\"lang-py prettyprint-override\"><code>while True:\n try:\n x = int(input(&quot;Enter an integer who's root value you need: &quot;))\n e = int(input(&quot;Enter an +ve integer for root value: &quot;))\n\n if e &lt; 0:\n print(&quot;I SAID +VE INTEGER FOR ROOT!&quot;)\n elif e % 2 == 0 and x &lt; 0:\n print(&quot;-ve nos. can't have root value for even roots!&quot;)\n else:\n # The input is now good, exit the while-loop.\n break\n except ValueError:\n print(&quot;Only integer values are permitted.&quot;)\n\nif x == 0:\n ...\n...\n</code></pre>\n<h1>Unnecessary conditionals</h1>\n<pre class=\"lang-py prettyprint-override\"><code> if x&gt;0:\n low = -x\n elif x&lt;0:\n low = x\n if x&gt;0:\n high = max(1.0,x)\n elif x&lt;0:\n high = max(1.0,-x)\n</code></pre>\n<p>You are testing <code>x&gt;0</code>, <code>x&lt;0</code>, <code>x&gt;0</code>, and <code>x&lt;0</code>. We can remove half of these, by combining the two if-elif statements:</p>\n<pre class=\"lang-py prettyprint-override\"><code> if x&gt;0:\n low = -x\n high = max(1.0,x)\n elif x&lt;0:\n low = x\n high = max(1.0,-x)\n</code></pre>\n<p>This is arguably clearer. But the second test, <code>x&lt;0</code> is unnecessary. We've already checked for <code>x == 0</code> earlier, and now have just tested <code>x&gt;0</code>. The only other possibility is <code>x &lt; 0</code>, so we can get away with just an <code>else:</code></p>\n<pre class=\"lang-py prettyprint-override\"><code> if x&gt;0:\n low = -x\n high = max(1.0,x)\n else:\n low = x\n high = max(1.0,-x)\n</code></pre>\n<h1>PEP 8</h1>\n<p>The <a href=\"https://pep8.org\" rel=\"noreferrer\">Style Guide for Python Code</a> lists many conventions which Python programs should follow, for maximum readability by other Python programmers.</p>\n<ul>\n<li>Binary operators should be surrounded by one space. For instance, you should write <code>x == 0</code>, <code>e % 2 == 0</code>, <code>x &gt; 0</code> and <code>(...) / 2.0</code> instead of <code>x==0</code>, <code>e %2 == 0</code>, <code>x&gt;0</code> and <code>(...)/2.0</code>.</li>\n<li><code>snake_case</code> should be used for function names and variables. For example, <code>num_guesses</code> instead of <code>numGuesses</code>.</li>\n<li>constants should be in <code>UPPER_CASE</code>. For example, <code>EPSILON = 0.000_000_1</code> instead of <code>epsilon = 0.0000001</code> if the value never changes.</li>\n<li>Use <code>_</code> in long numerical constants to group digits for easier readability, as in above example.</li>\n<li>Commas should be followed by a space. For instances, <code>max(1.0, x)</code> instead of <code>max(1.0,x)</code>.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T15:31:04.797", "Id": "501110", "Score": "0", "body": "OMG! \nI never thought I can do this much simplifications to this small piece of code\nTY @AJNeufeld" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T20:35:23.283", "Id": "254008", "ParentId": "253946", "Score": "5" } } ]
{ "AcceptedAnswerId": "254008", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T07:35:42.980", "Id": "253946", "Score": "5", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Python code to guess the roots of any integer" }
253946
<p>So I got kind of a weird format returned from the api I'm calling it's the following:</p> <pre><code>[ [ 1609065000000, &quot;22739.71000000&quot;, &quot;22795.73000000&quot;, &quot;22700.39000000&quot;, &quot;22779.08000000&quot;, &quot;38.81782800&quot;, 1609065899999, &quot;883167.94526884&quot;, 2261, &quot;18.58965200&quot;, &quot;423036.58181400&quot;, &quot;0&quot; ] ] </code></pre> <pre><code> public static class StringExtensions { public static IEnumerable&lt;Candlestick&gt; ToCandleStickList(this string jsonObject) { var candleStickList = new List&lt;Candlestick&gt;(); var list = JsonConvert.DeserializeObject&lt;List&lt;object[]&gt;&gt;(jsonObject); foreach (var obj in list) { candleStickList.Add(new Candlestick { OpenTime = (long)obj[0], Open = double.Parse((string)obj[1]), High = double.Parse((string)obj[2]), Low = double.Parse((string)obj[3]), Close = double.Parse((string)obj[4]), Volume = double.Parse((string)obj[5]), CloseTime = (long)obj[6], QuoteAssetVolume = double.Parse((string)obj[7]), NumberOfTrades = (long)obj[8], TakerBuyBaseAssetVolume = double.Parse((string)obj[9]), TakerBuyQuoteAssetVolume = double.Parse((string)obj[10]) }); } return candleStickList; } } </code></pre> <pre><code> public class Candlestick { public long OpenTime { get; set; } public double Open { get; set; } public double High { get; set; } public double Low { get; set; } public double Close { get; set; } public double Volume { get; set; } public long CloseTime { get; set; } public double QuoteAssetVolume { get; set; } public long NumberOfTrades { get; set; } public double TakerBuyBaseAssetVolume { get; set; } public double TakerBuyQuoteAssetVolume { get; set; } } </code></pre> <p>I use the static method as follows</p> <pre><code>public async Task&lt;IEnumerable&lt;Candlestick&gt;&gt; GetCandleSticks(string symbol, string interval) { var endpoint = $&quot;api/v3/klines?symbol={symbol}&amp;interval={interval}&quot;; var response = await _httpClient.GetAsync(endpoint); if (response.IsSuccessStatusCode) { var result = (await response.Content.ReadAsStringAsync()).ToCandleStickList(); return result; } throw new Exception($&quot;&quot;); } </code></pre> <p>Does anyone got any suggestions for better code? Thanks in advance!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T12:20:51.567", "Id": "500824", "Score": "0", "body": "Does your code work as expected. We only review working code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T12:40:54.443", "Id": "500826", "Score": "0", "body": "My code works as expected yeah." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T13:15:43.173", "Id": "500828", "Score": "0", "body": "@pacmaninbw I was looking for a better way to cast the string to an object. Or overall code smells that would get noticed. I think I clarified that in the last sentece of my question?" } ]
[ { "body": "<p>A few quick observations:</p>\n<p>String extensions is generally a bad idea because <code>string</code> is such a common type.</p>\n<p>Conversion code can be written more defensively. Use <code>TryParse</code> instead of <code>Parse</code> and if <code>TryParse</code> fails then handle that by throwing an Exception, or some other error handling.</p>\n<p>Throwing a generic exception with no message is not great.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T19:20:42.157", "Id": "500844", "Score": "0", "body": "Thank you very much for the quick observations, I'll try and use TryParse instead of Parse. Do you have a recommendation what to use instead of using a string extensions?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T19:23:32.643", "Id": "500845", "Score": "0", "body": "@MounirMehjoub a local method inside ```GetCandleSticks``` could be an idea." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T14:55:52.170", "Id": "253958", "ParentId": "253949", "Score": "1" } }, { "body": "<p><code>Json.NET</code> has a very useful <code>JsonConverter</code> which you can use to add a custom JsonConverter. Which what you actually need.</p>\n<p>So, you can do something like this :</p>\n<pre><code>public class CandlestickConverter : JsonConverter\n{\n public override bool CanConvert(Type objectType)\n {\n return objectType == typeof(Candlestick);\n }\n\n public override object ReadJson(JsonReader reader , Type objectType , object existingValue , JsonSerializer serializer)\n {\n if(reader.TokenType == JsonToken.Null)\n {\n return null;\n }\n\n var candle = ( existingValue as Candlestick ?? new Candlestick() );\n\n var array = JArray.Load(reader);\n\n candle.OpenTime = array.ElementAtOrDefault(0)?.ToObject&lt;long&gt;(serializer) ?? 0;\n candle.Open = array.ElementAtOrDefault(1)?.ToObject&lt;double&gt;(serializer) ?? 0;\n candle.High = array.ElementAtOrDefault(2)?.ToObject&lt;double&gt;(serializer) ?? 0;\n candle.Low = array.ElementAtOrDefault(3)?.ToObject&lt;double&gt;(serializer) ?? 0;\n candle.Close = array.ElementAtOrDefault(4)?.ToObject&lt;double&gt;(serializer) ?? 0;\n candle.Volume = array.ElementAtOrDefault(5)?.ToObject&lt;double&gt;(serializer) ?? 0;\n candle.CloseTime = array.ElementAtOrDefault(6)?.ToObject&lt;long&gt;(serializer) ?? 0;\n candle.QuoteAssetVolume = array.ElementAtOrDefault(7)?.ToObject&lt;double&gt;(serializer) ?? 0;\n candle.NumberOfTrades = array.ElementAtOrDefault(8)?.ToObject&lt;long&gt;(serializer) ?? 0;\n candle.TakerBuyBaseAssetVolume = array.ElementAtOrDefault(9)?.ToObject&lt;double&gt;(serializer) ?? 0;\n candle.TakerBuyQuoteAssetVolume = array.ElementAtOrDefault(10)?.ToObject&lt;double&gt;(serializer) ?? 0;\n\n return candle;\n }\n\n public override void WriteJson(JsonWriter writer , object value , JsonSerializer serializer)\n {\n var candle = (Candlestick) value;\n serializer.Serialize(writer ,\n new[]\n {\n candle.OpenTime,\n candle.Open,\n candle.High,\n candle.Low,\n candle.Close,\n candle.Volume,\n candle.CloseTime,\n candle.QuoteAssetVolume,\n candle.NumberOfTrades,\n candle.TakerBuyBaseAssetVolume,\n candle.TakerBuyQuoteAssetVolume\n });\n }\n}\n</code></pre>\n<p>Now, using this custom converter you can use the <code>JsonConverter</code> attribute on the class like this :</p>\n<pre><code>[JsonConverter(typeof(CandlestickConverter))]\npublic class Candlestick\n{\n ...\n}\n</code></pre>\n<p>Now you can do this directly :</p>\n<pre><code>var candles = JsonConvert.DeserializeObject&lt;List&lt;Candlestick&gt;&gt;(jsonObject);\n</code></pre>\n<p>So, you don't need to use extensions, you only need to do a custom converter which is the proper way to handle Json serialization when using <code>Json.NET</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T21:05:21.187", "Id": "500849", "Score": "0", "body": "Thanks I'll give this a try and keep the post updated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T12:37:42.227", "Id": "500900", "Score": "0", "body": "I gave it a try and ran in following error ```Cannot deserialize the current JSON array (e.g. [1,2,3]) into type Candlestick because the type requires a JSON object (e.g. {\"name\":\"\nvalue\"}) to deserialize correctly.```. I'll post my question about stackoverflow about this question. But to clarify the refactoring didn't exactly work as expected." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T12:54:03.617", "Id": "500904", "Score": "0", "body": "https://stackoverflow.com/questions/65477922/deserializing-json-response-to-c-sharp-object-error" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T13:20:29.653", "Id": "500911", "Score": "0", "body": "Resolved and the code is a lot cleaner now thanks for the code review." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T20:35:00.217", "Id": "253968", "ParentId": "253949", "Score": "3" } } ]
{ "AcceptedAnswerId": "253968", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T10:43:43.267", "Id": "253949", "Score": "2", "Tags": [ "c#", "json" ], "Title": "API response json to C# object" }
253949
<p>The longest example program in my <a href="https://flatassembler.github.io/PicoBlaze/PicoBlaze.html" rel="nofollow noreferrer">PicoBlaze Simulator in JavaScript</a> is this decimal-to-binary converter:</p> <pre><code>;This is an example program that uses ;UART, the interface that PicoBlaze uses ;for connecting to terminals (a DOS-like ;user interface, with a keyboard and a ;screen capable of displaying text). ;It loads base-10 integer numbers from ;the terminal, converts them into binary, ;and then prints the binary ;representations back onto the terminal. ;Example input would be: ;1 ;2 ;4 ;8 ;15 ;127 ;255 ; ;And the expected output is: ;1_(10)=1_(2) ;2_(10)=10_(2) ;4_(10)=100_(2) ;8_(10)=1000_(2) ;15_(10)=1111_(2) ;127_(10)=1111111_(2) ;255_(10)=11111111_(2) ; ;Note that you need to click the ;&quot;Enable UART&quot; button in order to use it. ;Also, the trailing empty line in the ;input is necessary for the result to be ;printed. ;Now follows some boilerplate code ;we use in our Computer Architecture ;classes... CONSTANT LED_PORT,00 CONSTANT HEX1_PORT,01 CONSTANT HEX2_PORT,02 CONSTANT UART_TX_PORT,03 CONSTANT UART_RESET_PORT,04 CONSTANT SW_PORT,00 CONSTANT BTN_PORT,01 CONSTANT UART_STATUS_PORT,02 CONSTANT UART_RX_PORT,03 ; Tx data_present CONSTANT U_TX_D, 00000001'b ; Tx FIFO half_full CONSTANT U_TX_H, 00000010'b ; TxFIFO full CONSTANT U_TX_F, 00000100'b ; Rxdata_present CONSTANT U_RX_D, 00001000'b ; RxFIFO half_full CONSTANT U_RX_H, 00010000'b ; RxFIFO full CONSTANT U_RX_F, 00100000'b ADDRESS 000 START: ;At the beginning, the number is 0. load s0,0 ;And we are storing its string ;representation at the beginning ;of RAM. namereg s3,pointer load pointer,0 ;Now follows a loop to load ;the digits of the number. loading_the_number: ;Load a character from the UART ;terminal. call UART_RX ;Check whether the character is a digit. compare s9,&quot;0&quot; ;If it is not a digit, jump to the ;part of the program for printing ;the number you have got. jump c,print_the_number load s1,&quot;9&quot; compare s1,s9 jump c,print_the_number ;If it is a digit, store it into RAM. store s9,(pointer) add pointer,1 ;Multiply the number you have got by 10. load sf,s0 call multiply_by_10 load s0,se ;Then, convert the digit from ASCII ;into binary. sub s9,&quot;0&quot; ;And then add it to the number you ;have got. add s0,s9 call c,abort ;In case of overflow. jump loading_the_number ;Repeat until a ;non-digit is ;loaded. print_the_number: ;If there are no digits to be printed, ;do not print anything. sub pointer,0 jump z,START print_the_decimal: load s4,pointer load pointer,0 printing_the_decimal_loop: compare pointer,s4 jump nc, end_of_printing_the_decimal fetch s9,(pointer) ;Do some basic sanity check: Is the ;character you are printing indeed ;a decimal digit? compare s9,&quot;0&quot; call c,abort load s1,&quot;9&quot; compare s1,s9 call c,abort ;If it is indeed a decimal digit, ;print it. call UART_TX add pointer,1 jump printing_the_decimal_loop end_of_printing_the_decimal: ;After you have repeated the decimal ;number, print the string &quot;_(10)=&quot;. load s9,&quot;_&quot; call UART_TX load s9,&quot;(&quot; call UART_TX load s9,&quot;1&quot; call UART_TX load s9,&quot;0&quot; call UART_TX load s9,&quot;)&quot; call UART_TX load s9,&quot;=&quot; call UART_TX ;If the number to be printed is ;equal to zero, print 0. sub s0,0 jump nz,print_the_binary load s9,&quot;0&quot; call UART_TX jump end_of_printing_loop print_the_binary: ;Make the pointer point to the ;beginning of RAM. load pointer,0 ;Now goes a loop which stores the binary ;representation of the number we have ;got into RAM, but reversed. beginning_of_converting_to_binary: sub s0,0 jump z,end_of_converting_to_binary load s9,&quot;0&quot; sr0 s0 jump nc,store_digit_to_memory add s9,1 store_digit_to_memory: store s9,(pointer) add pointer,1 jump beginning_of_converting_to_binary end_of_converting_to_binary: ;Do some basic sanity check, such as that ;the pointer does not point to zero. compare pointer,0 call z,abort ;Something went wrong ;so end the program. ;Check whether there are more than 8 bits. compare pointer,9 call nc,abort ;Now goes a loop which will print ;the binary number in RAM, with digits ;in the correct order. The pointer now ;points at a memory location right after ;the binary number (not at the last digit, ;but after it). beginning_of_printing_loop: sub pointer,1 jump c,end_of_printing_loop fetch s9,(pointer) ;Do some basic sanity check: ;Is the character the pointer points to ;indeed a binary digit? compare s9,&quot;0&quot; jump z,memory_is_fine compare s9,&quot;1&quot; jump z,memory_is_fine call abort ;Something went wrong, ;so end the program. memory_is_fine: ;If everything is fine, print that ;digit. call UART_TX ;Repeat until you have printed all ;digits of the binary number ;stored in RAM. jump beginning_of_printing_loop end_of_printing_loop: ;After you have printed that binary ;number, print the string &quot;_(2)&quot; and ;a new-line. load s9,&quot;_&quot; call UART_TX load s9,&quot;(&quot; call UART_TX load s9,&quot;2&quot; call UART_TX load s9,&quot;)&quot; call UART_TX load s9,a ;newline character, 0xa=='\n'. call UART_TX ;The program runs in an infinite loop... JUMP START multiply_by_10: load se,sf add se,se call c,abort add se,se call c,abort add se,sf call c,abort add se,se call c,abort return abort: load s9,&quot;E&quot; call UART_TX load s9,&quot;R&quot; call UART_TX load s9,&quot;R&quot; call UART_TX load s9,&quot;O&quot; call UART_TX load s9,&quot;R&quot; call UART_TX load s9,&quot;!&quot; call UART_TX load s9,a ;newline call UART_TX infinite_loop: jump infinite_loop return ;Now follows some boilerplate code ;we use in our Computer Architecture ;classes... UART_RX: INPUT sA, UART_STATUS_PORT TEST sA, U_RX_D JUMP Z, UART_RX INPUT s9, UART_RX_PORT RETURN UART_TX: INPUT sA, UART_STATUS_PORT TEST sA, U_TX_F JUMP NZ, UART_TX OUTPUT s9, UART_TX_PORT RETURN </code></pre> <p>So, what do you think about it? Do you have some suggestions about how to make it better?</p>
[]
[ { "body": "<h2>Readability is poor</h2>\n<p>You should insert more empty lines in order to cleanly separate the logical code blocks.</p>\n<p>Your use of indentation is not all that consistent. It will improve readability a lot if you get this right.</p>\n<p>Also, seeing that you can use some alias (<code>namereg s3,pointer</code>), I think you could use this more often to improve readability.</p>\n<p>I feel your 'basic sanity checks' are more of 'insanity' checks. You should not doubt that much. The extra code also increases the risk of errors.</p>\n<p>When something is wrong, you go to the <em>abort</em> part of the program never to return. It's confusing to see that most of the time you use a <code>call</code> to do this and not the much clearer <code>jump</code>.</p>\n<hr />\n<h2>Optimizations</h2>\n<p>If you're using the ASCII character set, then the colon character (&quot;:&quot;) follows the character &quot;9&quot;. You can simplify the verification of a valid digit (no longer needing that temporary register <code>s1</code>) like:</p>\n<pre><code>compare s9,&quot;0&quot;\njump c,print_the_number\ncompare s9,&quot;:&quot;\njump nc,print_the_number\n</code></pre>\n<p>Minimizing the number of instructions, and certainly control transferring instructions, is important. I have moved the more likely <em>jumping back</em> above the unlikely <em>jumping to abort</em>.</p>\n<pre><code>jump nc,loading_the_number ;Repeat until a non-digit is loaded.\njump abort\n</code></pre>\n<blockquote>\n<pre><code>;If the number to be printed is\n;equal to zero, print 0.\nsub s0,0\njump nz,print_the_binary\nload s9,&quot;0&quot;\ncall UART_TX\njump end_of_printing_loop\n</code></pre>\n</blockquote>\n<p>You don't need to special-case if the number happens to be zero. It will shave off numerous instructions.</p>\n<p>Most of your loops are WHILE-WEND loops that have a condition on top and an unconditional jump that goes back to the top. Using REPEAT-UNTIL loops will be faster and require but one conditional jump instruction.</p>\n<p>The new code:</p>\n<pre><code>START:\n load s0,0\n namereg s3,pointer\n load pointer,0\n\nloading_the_number:\n call UART_RX\n compare s9,&quot;0&quot;\n jump c,print_the_number\n compare s9,&quot;:&quot;\n jump nc,print_the_number\n store s9,(pointer)\n add pointer,1\n load sf,s0\n call multiply_by_10\n load s0,se\n sub s9,&quot;0&quot;\n add s0,s9\n jump nc,loading_the_number ;Repeat until a non-digit is loaded.\n jump abort\n\nprint_the_number:\n sub pointer,0 ;If there are no digits to be printed, do not print anything.\n jump z,START\n\n load s4,pointer\n load pointer,0\nprinting_the_decimal_loop:\n fetch s9,(pointer)\n call UART_TX\n add pointer,1\n compare pointer,s4\n jump c,printing_the_decimal_loop\n\n ... some fixed text gets outputted here\n\n\n load pointer,0 ; Works even if s0 == 0\nbeginning_of_converting_to_binary: ; This stores in reverse order!\n load s9,&quot;0&quot;\n sr0 s0\n jump nc,store_digit_to_memory\n load s9,&quot;1&quot;\nstore_digit_to_memory:\n store s9,(pointer)\n add pointer,1\n sub s0,0\n jump nz,beginning_of_converting_to_binary\n\n ; pointer is certainly not zero\n sub pointer,1\nbeginning_of_printing_loop:\n fetch s9,(pointer)\n call UART_TX\n sub pointer,1\n jump nc,beginning_of_printing_loop\n\n ... some fixed text gets outputted here\n\n JUMP START\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T23:50:53.123", "Id": "253978", "ParentId": "253951", "Score": "1" } } ]
{ "AcceptedAnswerId": "253978", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T11:28:10.467", "Id": "253951", "Score": "1", "Tags": [ "assembly", "binary" ], "Title": "Converting decimal to binary in Assembly" }
253951
<p>I've made component that based on values submitted by user allows to update the list of records in the list. Code is working really nice, but I've been thinking if there is any room for improvement. Especially I'm concerned about <code>nextId</code> value which is hardcoded, but I think it'll be better to have it increment based on existing last id (assuming ids are sorted in ascending order).</p> <pre><code>import { useState } from &quot;react&quot;; import GuestsList from &quot;./GuestsList&quot;; import GuestsForm from &quot;./GuestsForm&quot;; const initialValues = [ { id: 1, firstName: &quot;John&quot;, lastName: &quot;Snow&quot;, email: &quot;john@snow.com&quot; }, { id: 2, firstName: &quot;Jack&quot;, lastName: &quot;Frost&quot;, email: &quot;jack@frost.com&quot; }, ]; var nextId = 3; function GuestsManagementForm() { const [data, setData] = useState(initialValues); function parentSubmit(value) { console.log(&quot;Form submitted from parent&quot;); const newRecord = { id: nextId++, firstName: value.firstName, lastName: value.lastName, email: value.email, }; setData([...data, newRecord]); } function resetForm() { console.log(&quot;Form restarted from parent&quot;); } return ( &lt;div&gt; &lt;GuestsForm onSubmit={parentSubmit} onReset={resetForm} /&gt; &lt;br&gt;&lt;/br&gt; &lt;GuestsList listings={data} /&gt; &lt;/div&gt; ); } export default GuestsManagementForm; </code></pre> <p>and the form itself can be found here:</p> <pre><code>import { Formik, Field, Form, ErrorMessage } from &quot;formik&quot;; import * as Yup from &quot;yup&quot;; function GuestsForm(props) { const handleReset = () =&gt; { props.onReset(); }; return ( &lt;Formik initialValues={{ firstName: &quot;&quot;, lastName: &quot;&quot;, email: &quot;&quot; }} validationSchema={Yup.object({ firstName: Yup.string() .max(15, &quot;Must be max 15 characters&quot;) .min(2, &quot;Must be at least 2 characters&quot;) .required(&quot;Required&quot;), lastName: Yup.string() .max(20, &quot;Must be max 20 characters&quot;) .min(2, &quot;Must be at least 2 characters&quot;) .required(&quot;Required&quot;), email: Yup.string().email(&quot;Invalid email address&quot;).required(&quot;Required&quot;), })} onSubmit={(values, actions) =&gt; { props.onSubmit(values); actions.setSubmitting(false); actions.resetForm(); }} &gt; &lt;Form&gt; &lt;label htmlFor=&quot;firstName&quot;&gt;First Name&lt;/label&gt; &lt;Field name=&quot;firstName&quot; type=&quot;text&quot; /&gt; &lt;ErrorMessage name=&quot;firstName&quot; /&gt; &lt;br&gt;&lt;/br&gt; &lt;label htmlFor=&quot;lastName&quot;&gt;Last Name&lt;/label&gt; &lt;Field name=&quot;lastName&quot; type=&quot;text&quot; /&gt; &lt;ErrorMessage name=&quot;lastName&quot; /&gt; &lt;br&gt;&lt;/br&gt; &lt;label htmlFor=&quot;email&quot;&gt;Email Address&lt;/label&gt; &lt;Field name=&quot;email&quot; type=&quot;email&quot; /&gt; &lt;ErrorMessage name=&quot;email&quot; /&gt; &lt;br&gt;&lt;/br&gt; &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt; &lt;button type=&quot;reset&quot; onClick={handleReset}&gt;Reset&lt;/button&gt; &lt;/Form&gt; &lt;/Formik&gt; ); } export default GuestsForm; </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T12:50:24.857", "Id": "253953", "Score": "0", "Tags": [ "javascript", "react.js" ], "Title": "ReactJS Formik form with list update" }
253953
<p>This question came from a real use case. I had a data frame with different columns each one containing data from a data source and I wanted to design a hypothesis test to prove or not if the data had the same mean. So I had to compute the Kolmogorov-Smirnov test for each couple of columns.</p> <p><strong>Now the problem can be generalized to any combinatory task.</strong></p> <p>It follows that I had to implement a Binomial Coefficient like</p> <p><span class="math-container">$$ \binom{n}{k} $$</span></p> <p>Where <strong>n</strong> is the number of columns</p> <p>and <strong>k</strong> is = 2</p> <p><strong>My question is</strong>: if exists a more efficient way to apply a function on permutated samples taken from a list? And how to do this permutation eg. Given a <code>func</code> and a list <code>[a,b,c,d]</code></p> <pre><code>func(a,b) func(a,c) func(a,d) func(b,c) func(b,d) func(c,d) </code></pre> <p>I created an algorithm to solve this issue, but I am wondering if there is a better way to do that <strong>in Python</strong>.</p> <p>In my algorithm, I simply multiply each <code>n</code> element in an explanatory array with another element <code>i</code> of the same array, with <code>n!=i</code>, instead of computing the statistical test.</p> <pre><code>to_do=[1,2,3,4,5] #done will store information on the elements already combined done=[] #j will store information on the results of the combination j=[] #iterating over the to_do array for n in to_do: #checking if we already computed the n element if n not in done: print(n) #taking another i element from the array #where n!=i for i in to_do: print(i) #if the condition is satisfied if i!=n: #combine the two elements m=n*i #append the result on the &quot;j&quot; array j.append(m) #updating the array with the &quot;done&quot; elements done.append(n) print(len(done)) print(len(j)) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T21:17:18.677", "Id": "500851", "Score": "1", "body": "Unclear. What exactly is the input, what exactly is the output? Do you just want `itertools.permutations(to_do, 2)`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T09:42:52.673", "Id": "500886", "Score": "0", "body": "The input is the array ´to_do´ and then each element of the array is multiplied with another one and this operation should be done for each element." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T10:01:24.090", "Id": "500888", "Score": "0", "body": "I read the documentation, how can I avoid to repeat an operation when I have to permutate like in the [documentation](https://docs.python.org/3/library/itertools.html#itertools.permutations) a list of 4 elements `[ABCD]` and I need only `AB` and not `BA` (or viceversa). I tried to fix this issue with the `done` array in my code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T15:37:03.473", "Id": "500928", "Score": "0", "body": "Well your own code does both AB and BA. Are you saying your code isn't correct and thus your question is off-topic?" } ]
[ { "body": "<p>If you just want the length of the list, your code can be reduced to one line:</p>\n<pre><code>result = len(to_do) * (len(to_do) - 1)\n</code></pre>\n<p>Also, you're comments are, at the very least, <em>excessive</em>. You should really only use comments to explain a design choice or a complicated equation/algorithm. Comments like <code>#if the condition is satisfied</code> just clutters your code.</p>\n<p>As explained <a href=\"https://codereview.stackexchange.com/questions/253954/python-combinatory-algorithm-a-binomial-coefficient-application-with-n-mutable/253972?noredirect=1#comment500887_253972\">in a comment</a>, actual computations need to be made. This can be done using <code>itertools.permutations</code>.</p>\n<pre><code>import itertools\nfrom typing import List\n\ndef func(nums: List[int]) -&gt; List[int]:\n\n return list(set(\n x * y for x, y in itertools.permutations(nums, 2)\n ))\n</code></pre>\n<p>While this doesn't avoid the extra computations, it's a short and sweet solution. And below is how you would use it:</p>\n<pre><code>to_do = [1, 2, 3, 4, 5]\nfunc(to_do)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T09:45:07.023", "Id": "500887", "Score": "0", "body": "Thank you the point about the comment is very useful, the output as I commented above is to multiply each element of the list with another one and this should be done for all the elements, except for the multiplication of the element ´i´ with itself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T12:51:53.660", "Id": "500902", "Score": "0", "body": "@AndreaCiufo Please see my edited answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T18:12:06.980", "Id": "501362", "Score": "0", "body": "what does it mean `-> List[int]` it's the first time that I see it in the function signature?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T20:01:33.520", "Id": "501379", "Score": "0", "body": "@AndreaCiufo It means that the function returns a list of integers. Take a look at the [python docs regarding type hints](https://docs.python.org/3/library/typing.html)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T21:46:18.467", "Id": "253972", "ParentId": "253954", "Score": "1" } }, { "body": "<blockquote>\n<p><strong>My question is:</strong> if exists a more efficient way to apply a function on\npermutated samples taken from a list? And how to do this permutation\neg. Given a func and a list [a,b,c,d]</p>\n<p>func(a,b)</p>\n<p>func(a,c)</p>\n<p>func(a,d)</p>\n<p>func(b,c)</p>\n<p>func(b,d)</p>\n<p>func(c,d)</p>\n</blockquote>\n<p>It seems that you are looking for combinations rather than permutations. In that case, use <a href=\"https://docs.python.org/3/library/itertools.html#itertools.combinations\" rel=\"nofollow noreferrer\">itertools.combinations</a>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from itertools import combinations\n\nfor x, y in combinations(['a', 'b', 'c', 'd'], 2):\n print(x, y)\n</code></pre>\n<p>It prints:</p>\n<pre><code>a b\na c\na d\nb c\nb d\nc d\n</code></pre>\n<p>Using <code>itertools.combinations</code> in your example:</p>\n<pre><code>from itertools import combinations\n\ntodo = [1, 2, 3, 4, 5]\nj = [x * y for x, y in combinations(todo, 2)]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T14:20:20.527", "Id": "253997", "ParentId": "253954", "Score": "1" } } ]
{ "AcceptedAnswerId": "253972", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T13:23:39.697", "Id": "253954", "Score": "0", "Tags": [ "python", "algorithm" ], "Title": "Python Combinatory Algorithm - A Binomial Coefficient application with n mutable and k fixed to 2" }
253954
<p>Looking for input on how to clean up my code. I am writing a file converter that can read different but related file types (relatable like a wav and mp3 encode audio or how a jpg and tiff encode image data) and convert them to a desired file type. I got it to a decent stopping point where I can handle one file type to output to CSV and want to take this time to refactor.</p> <p>Please let me know if my program can benefit from any design principles or if I should break down objects/classes further or I'm doing anything just plain wrong. I am trying my best to improve on my own. Ultimate goal is add a GUI and a plotter function for the data to look at before converting.</p> <p><strong>Main.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &quot;file_interface.h&quot; #include &quot;simple_parser.h&quot; int main(int argc, char** argv) { InputParser input(argc, argv); const std::string&amp; filepath = input.getCmdOption(&quot;-f&quot;); if (!filepath.empty()) { max_temp_data values; try { FileInterface file_interface; values = file_interface.extract_from(filepath); } catch (const std::runtime_error &amp; e) { std::cout &lt;&lt; e.what(); } std::string output_path = &quot;C:\\Documents\\example.csv&quot;; FileInterface file_interface; file_interface.output_new(output_path, values); } return 0; } </code></pre> <p><strong>file_interface.h</strong></p> <pre><code>#include &lt;fstream&gt; #include &lt;vector&gt; #include &lt;memory&gt; #include &quot;base_definition.h&quot; struct max_temp_data { int total_points = 0; double start_time = 0.0; double end_time = 0.0; std::vector&lt;float&gt; T_values = {0}; }; // // File interface loads the file to be converted and assigns the proper encoder/decoder // class FileInterface { public: FileInterface(); ~FileInterface(); void initialize_from(const std::string&amp; filepath); max_temp_data extract_from(const std::string&amp; filepath); void output_new(const std::string&amp; extension, max_temp_data&amp; values); friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const max_temp_data&amp; mhd); private: void load_definition(const std::string&amp; extension); // // Current loaded file std::ifstream input_file_; std::unique_ptr&lt;BaseDefinition&gt; definition_; }; inline std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const max_temp_data&amp; mhd) { os &lt;&lt; mhd.total_points &lt;&lt; '/' &lt;&lt; mhd.start_time &lt;&lt; '/' &lt;&lt; mhd.end_time; return os; } </code></pre> <p><strong>file_interface.cpp</strong></p> <pre><code>#include &lt;fstream&gt; #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;filesystem&gt; #include &quot;file_interface.h&quot; #include &quot;peak_definition.h&quot; #include &quot;csv_definition.h&quot; FileInterface::FileInterface() { } FileInterface::~FileInterface() { if (input_file_.is_open()) { input_file_.close(); } } void FileInterface::load_definition(const std::string&amp; extension) { if (extension == std::string(&quot;.peak&quot;)) { std::cout &lt;&lt; &quot;PEAK Definition&quot; &lt;&lt; &quot;\n&quot;; definition_ = std::make_unique&lt;PeakDefinition&gt;(); } if (extension == std::string(&quot;.csv&quot;)) { std::cout &lt;&lt; &quot;CSV Definition&quot; &lt;&lt; &quot;\n&quot;; definition_ = std::make_unique&lt;CsvDefinition&gt;(); } } void FileInterface::initialize_from(const std::string&amp; filepath) { auto extension = std::filesystem::path(filepath).extension().string(); load_definition(extension); if (!definition_) { //Throw invalid file type throw std::runtime_error(extension + &quot;: is not a valid extension&quot;); } } max_temp_data FileInterface::extract_from(const std::string&amp; filepath) { input_file_.open(filepath, std::ios::binary); if (!input_file_) { //Throw file open error throw std::runtime_error(filepath + &quot;: could not be opened &quot;); } initialize_from(filepath); max_temp_data values = { 0 }; // Extract Header definition_-&gt;extract_header(input_file_); if (input_file_.fail()) { throw std::runtime_error(&quot;Failed to read header&quot;); } if (!definition_-&gt;validate_descriptor()) { throw std::runtime_error(&quot;File bytes do not match expected bytes.&quot;); } values.total_points = definition_-&gt;extract_total_points(); values.start_time = definition_-&gt;extract_start_freq(); values.end_time = definition_-&gt;extract_end_freq(); // Extract Data input_file_.seekg(0, std::ios::end); auto length = input_file_.tellg(); if(length &lt; definition_-&gt;get_start_pos()) { throw std::runtime_error(&quot;Start position of file exceeds length of file: &quot; + (int)length); } input_file_.seekg(definition_-&gt;get_start_pos(), std::ios_base::beg); for (int i = 0; i &lt; values.total_points; ++i) { auto val = definition_-&gt;extract_data_point(input_file_); values.T_values.push_back(val); if (input_file_.fail()) { throw std::runtime_error(&quot;Failed to read data at position: &quot; + i); } } input_file_.close(); return values; } void FileInterface::output_new(const std::string&amp; output_path, max_temp_data &amp;values) { initialize_from(output_path); std::ofstream output_file(output_path); definition_-&gt;write_header(output_file, values.total_points, values.start_time, values.end_time); for (auto&amp; val : values.T_values) { definition_-&gt;write_data(output_file, val); } output_file.close(); } </code></pre> <p><strong>base_definition.h</strong></p> <pre><code>class BaseDefinition { public: //Virtual Extractor methods virtual void extract_header(std::istream&amp; file) = 0; virtual float extract_data_point(std::istream&amp; file) = 0; virtual bool validate_descriptor() = 0; virtual uint32_t extract_total_points() = 0; virtual double extract_start_time() = 0; virtual double extract_end_time() = 0; //Virtual Encoder methods virtual void write_header(std::ostream&amp; file, int &amp;total_data_points, double &amp;data_start, double &amp;data_end) = 0; virtual void write_data(std::ostream&amp; file, float &amp;t_value) = 0; //Basic methods virtual uint8_t get_start_pos() = 0; }; </code></pre> <p><strong>peak_definition.h</strong></p> <pre><code>#include &lt;array&gt; #include &lt;cstdint&gt; #include &quot;base_definition.h&quot; namespace peak { #pragma pack(push, 1) struct HeaderChunk { std::array&lt;uint8_t, 24&gt; Descriptor; // Magic bytes std::array&lt;uint8_t, 36&gt; unused1; // Not used currently std::array&lt;uint8_t, 4&gt; display1; // Not used currently std::array&lt;uint8_t, 4&gt; display2; // Not used currently std::array&lt;uint8_t, 4&gt; display3; // Not used currently std::array&lt;uint8_t, 4&gt; display4; // Not used currently std::array&lt;uint8_t, 4&gt; start; // Used to compute Start std::array&lt;uint8_t, 4&gt; end; // Used to compute End std::array&lt;uint8_t, 4&gt; unused2; // Not used currently std::array&lt;uint8_t, 4&gt; totalP; // Actual data points present std::array&lt;uint8_t, 4&gt; offset; // Subtract this by total to get where data actually starts std::array&lt;uint8_t, 2&gt; trail; // End header 01 00 std::array&lt;uint8_t, 126&gt; pad; // Pad of 00 }; #pragma pack(pop) #pragma pack(push, 1) struct DataChunk { uint8_t chunk; }; #pragma pack(pop) } //namespace peak class PeakDefinition : public BaseDefinition { public: PeakDefinition(); void extract_header(std::istream&amp; file) override; float extract_data_point(std::istream&amp; file) override; bool validate_descriptor() override; uint32_t extract_total_points() override; double extract_start_time() override; double extract_end_time() override; uint8_t get_start_pos() override { return data_start; } ; void write_header(std::ostream&amp; file, int&amp; total_data_points, double&amp; data_start, double&amp; data_end) override {}; void write_data(std::ostream&amp; file, float&amp; t_value) override {}; private: const int sample_rate = 100; const uint8_t data_start = 0xEC; //start of data peak::HeaderChunk header_buffer = {0}; std::array&lt;uint8_t, 24&gt; magic_bytes = { 0x00, 0x01, 0x02, 0x03, 0x4, 0x00, 0x50, 0x00, 0x40, 0x00, 0x40, 0x00, 0x50, 0x00, 0x20, 0x00, 0x40, 0x00, 0x60, 0x00, 0x70, 0x00, 0x60, 0x00 }; }; </code></pre> <p><strong>peak_definition.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &quot;peak_definition.h&quot; #include &quot;byte_operations.h&quot; PeakDefinition::PeakDefinition() { } void PeakDefinition::extract_header(std::istream&amp; file) { file.read((char*)(&amp;header_buffer), sizeof(header_buffer)); } bool PeakDefinition::validate_descriptor() { return header_buffer.Descriptor == magic_bytes; } uint32_t PeakDefinition::extract_total_points() { return convertArray2int(header_buffer.totalP) - convertArray2int(header_buffer.offset); } double PeakDefinition::extract_start_time() { double first = (int)header_buffer.start[0] * (double)sample_rate; //3,112,785 max double second = (int)header_buffer.start[1] * (double)sample_rate * 255; //793,760,175 max double third = (int)header_buffer.start[2] * (double)sample_rate * 255 * 255; //202,408,844,625 max return first + second + third; } double PeakDefinition::extract_end_time() { return extract_start_time() + (convertArray2int(header_buffer.totalP) - convertArray2int(header_buffer.offset))* (double)sample_rate; } float PeakDefinition::extract_data_point(std::istream&amp; file) { peak::DataChunk buffer = { 0 }; file.read((char*)(&amp;buffer), sizeof(buffer)); return (float)1.8 * buffer.chunk + 32; } </code></pre> <p><strong>csv_definition.h</strong></p> <pre><code>#pragma once #include &lt;cstdint&gt; #include &lt;string&gt; #include &quot;base_definition.h&quot; namespace csv { struct Row{ std::string colA = &quot;&quot;; std::string colB = &quot;&quot;; }; } //namespace csv class CsvDefinition : public BaseDefinition { public: CsvDefinition(); void extract_header(std::istream&amp; input) override; float extract_data_point(std::istream&amp; file) override; bool validate_descriptor() override; uint32_t extract_total_points() override; double extract_start_freq() override; double extract_end_freq() override; uint8_t get_start_pos() override { return 0; }; void write_header(std::ostream&amp; file, int&amp; total_data_points, double&amp; data_start, double&amp; data_end) override; void write_data(std::ostream&amp; file, float&amp; db_value) override ; private: void read_row(std::istream&amp; file, csv::Row&amp; row); csv::Row first_row_; float sample_rate_ = 0; const std::string separator = &quot;,&quot;; }; </code></pre> <p><strong>csv_definition.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;string&gt; #include &lt;sstream&gt; #include &quot;csv_definition.h&quot; #include &quot;byte_operations.h&quot; CsvDefinition::CsvDefinition() { } void CsvDefinition::extract_header(std::istream&amp; file) { } bool CsvDefinition::validate_descriptor() { int int_total = 0; double sample_rate = 0.0; bool assert = validate_csv_value(first_row_.colA, int_total) + validate_csv_value(first_row_.colB, sample_rate); if (assert) { return true; } return false; } uint32_t CsvDefinition::extract_total_points() { return std::stoi(first_row_.colA); } double CsvDefinition::extract_start_time() { //TODO: Implement return 0.0; } double CsvDefinition::extract_end_time() { //TODO: Implement return 0.0; } float CsvDefinition::extract_data_point(std::istream &amp; file) { //TODO: Implement return 0.0; } void CsvDefinition::read_row(std::istream&amp; file, csv::Row &amp;row) { std::getline(file, row.colA, ','); std::getline(file, row.colB, ','); } void CsvDefinition::write_header(std::ostream&amp; file, int&amp; total_data_points, double&amp; data_start, double&amp; data_end) { sample_rate_ = (data_start + data_end) / total_data_points; file &lt;&lt; std::to_string(total_data_points) &lt;&lt; separator &lt;&lt; std::to_string(sample_rate_) &lt;&lt; separator &lt;&lt; &quot;\n&quot;; file &lt;&lt; std::to_string(data_start) &lt;&lt; separator &lt;&lt; std::to_string(data_end) &lt;&lt; separator &lt;&lt; &quot;\n&quot;; } void CsvDefinition::write_data(std::ostream&amp; file, float&amp; db_value) { file &lt;&lt; &quot; &quot; &lt;&lt; separator &lt;&lt; std::to_string(db_value) &lt;&lt; separator &lt;&lt; &quot;\n&quot;; } </code></pre> <p><strong>byte_operations.h</strong></p> <pre><code>#pragma once #include &lt;array&gt; #include &lt;cstdint&gt; #include &lt;sstream&gt; inline uint32_t convertArray2int(std::array&lt;uint8_t, 4&gt;&amp; arr) { return(arr[0] | (arr[1] &lt;&lt; 8) | (arr[2] &lt;&lt; 16) | (arr[3] &lt;&lt; 24)); } template&lt;typename T&gt; inline bool validate_csv_value(std::string&amp; str, T &amp;compare) { std::stringstream convertor; convertor &lt;&lt; str; convertor &gt;&gt; compare; if (convertor.fail()) { return false; } return true; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T20:17:30.037", "Id": "500846", "Score": "4", "body": "You haven't included \"csv_definition.h\". [Edit] the question to include it (or remove the csv_definition.cpp part). What is \"byte_operations.h\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T21:29:50.677", "Id": "500854", "Score": "0", "body": "Consider publishing your software as open source on e.g. http://github.com/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T07:18:43.560", "Id": "500875", "Score": "0", "body": "@1201ProgramAlarm added the h file for defintion and the helper library byte_operations.h , supposed to be generic operations any of the file formats can use." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T14:43:43.863", "Id": "500917", "Score": "2", "body": "Please do not update the code in your question after receiving answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. It's important that all reviewers see the same version of your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T14:51:57.560", "Id": "500921", "Score": "0", "body": "The answer is that the code has bugs and that he reviewed a feature that was not meant to be reviewed. It compiles well on my machine and the \"bugs\" are present because there is a typo. The answer was more suited as a comment much like @1201ProgramAlarm gave me to request more info." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T15:23:33.517", "Id": "500924", "Score": "4", "body": "Welcome to Code Review! Rather than editing the question (and invalidating any reviews), the practice here is to leave the question as it was and post a follow-up question if desired. See https://codereview.stackexchange.com/help/how-to-ask" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T21:36:15.270", "Id": "501034", "Score": "1", "body": "I've rolled back your latest revision. As explained before, please see [what you may and may not do after receiving answers](https://codereview.meta.stackexchange.com/questions/1763/for-an-iterative-review-is-it-okay-to-edit-my-own-question-to-include-revised-c/1765#1765)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T22:00:33.697", "Id": "501036", "Score": "0", "body": "As was mentioned by other users, please don't update the code. Protip: as recommended by [the post already linked](https://codereview.meta.stackexchange.com/a/1765/120114) as well as the [help center](https://codereview.stackexchange.com/help/someone-answers) post a new question with the updated code and you may earn more reputation points, which may bring more privileges." } ]
[ { "body": "<p>Here are some things that may help you improve your code.</p>\n<h2>Understand <code>override</code></h2>\n<p>Using the <code>override</code> keyword after a member function declaration in C++ means that the function is intending to override a virtual member function in a base class. It's generally good practice to specify it when you are actually intending to override a function because it helps the compiler identify mismatches. However, it should <em>not</em> be used for functions that do not override virtual member functions. In this code, these two functions in <code>csv_definition.h</code> should NOT be overrides, because there is no corresponding virtual function in the base class:</p>\n<pre><code>double extract_start_freq() override;\ndouble extract_end_freq() override;\n</code></pre>\n<h2>Fix the many bugs</h2>\n<p>The <code>get_start_pos()</code> function in <code>csv_definition.h</code> can't compile because it returns <code>data_start_</code> which is undefined. Similarly, <code>extract_header</code> does not do what it claims (it does nothing) and <code>validate_csv_value()</code> does not exist. The <code>CsvDefinition::extract_start_time()</code> and <code>CsvDefinition::extract_end_time()</code> override function declarations are missing from <code>csv_definition.h</code>. There is a long list. Turn on all available compiler warnings to get that list. This code does not seem really to be ready for a code review.</p>\n<h2>Use include guards</h2>\n<p>There should be an include guard in each <code>.h</code> file. That is, start the file with:</p>\n<pre><code>#ifndef PEAK_DEFINITION_H\n#define PEAK_DEFINITION_H\n// file contents go here\n#endif // PEAK_DEFINITION_H\n</code></pre>\n<p>The use of <code>#pragma once</code> is a common extension, but it's not in the standard and thus represents at least a potential portability problem. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#sf8-use-include-guards-for-all-h-files\" rel=\"nofollow noreferrer\">SF.8</a></p>\n<h2>Understand data initialization</h2>\n<p>The code includes this line:</p>\n<pre><code>peak::HeaderChunk header_buffer = {0};\n</code></pre>\n<p>I am guessing that this is intended to zero out the entire <code>header_buffer</code> but that is not what it does at all. In fact, it assigns the value 0 to <code>HeaderChuck::Descriptor</code> and leaves all of the other fields uninitialized.</p>\n<h2>Put your own <code>#include</code>s first</h2>\n<p>It is good practice to put your program's own <code>#include</code> files first. This allows you (and the compiler) to see if you have missed anything. For instance, the <code>peak_definition.h</code> file refers to <code>std::ifstream</code> but fails to <code>#include &lt;fstream&gt;</code>.</p>\n<h2>Provide complete code to reviewers</h2>\n<p>This is not so much a change to the code as a change in how you present it to other people. Without the full context of the code and an example of how to use it, it takes more effort for other people to understand your code. This affects not only code reviews, but also maintenance of the code in the future, by you or by others. One good way to address that is by the use of comments. Another good technique is to include test code showing how your code is intended to be used.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T15:25:30.557", "Id": "500926", "Score": "0", "body": "Accepting and will repost with the changes." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T13:55:12.983", "Id": "253996", "ParentId": "253956", "Score": "1" } } ]
{ "AcceptedAnswerId": "253996", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T13:59:09.803", "Id": "253956", "Score": "6", "Tags": [ "c++", "file", "converting" ], "Title": "C++ File Converter Program" }
253956
<p>I'm using the Hilbert transform function from the FFTW source. Because I am going to use it in my DAQ with data streaming mode. The function is working fine but the calculation speed is slow which will cause the FIFO overflow. I've heard that move the <code>fftw_plan()</code> outside from the <code>hilbert()</code> for reuse the <code>plan</code> might be useful, however, it's an error once I did that, saying <code>Exception thrown at 0x0000000070769240 (libfftw3-3.dll) in CppFFTW.exe: 0xC0000005: Access violation reading location 0x0000000000000000. at the fftw_destroy_plan(plan);</code>. Does anyone has similar experiences or even better solution to boost up the <code>hilbert()</code> calculation?</p> <p>Here is what I've tried (2020 12/30 edited):</p> <pre><code>#include &lt;iostream&gt; #include &lt;fftw3.h&gt; #include &lt;time.h&gt; using namespace std; //macros for real and imaginary parts #define REAL 0 #define IMAG 1 //length of complex array #define N 8 void hilbert(const double* in, fftw_complex* out, fftw_plan plan_forward, fftw_plan plan_backward) { // copy the data to the complex array for (int i = 0; i &lt; N; ++i) { out[i][REAL] = in[i]; out[i][IMAG] = 0; } // creat a DFT plan and execute it //fftw_plan plan = fftw_plan_dft_1d(N, out, out, FFTW_FORWARD, FFTW_ESTIMATE); fftw_execute(plan_forward); // destroy a plan to prevent memory leak fftw_destroy_plan(plan_forward); int hN = N &gt;&gt; 1; // half of the length (N/2) int numRem = hN; // the number of remaining elements // multiply the appropriate value by 2 //(those should multiplied by 1 are left intact because they wouldn't change) for (int i = 1; i &lt; hN; ++i) { out[i][REAL] *= 2; out[i][IMAG] *= 2; } // if the length is even, the number of the remaining elements decrease by 1 if (N % 2 == 0) numRem--; else if (N &gt; 1) { out[hN][REAL] *= 2; out[hN][IMAG] *= 2; } // set the remaining value to 0 // (multiplying by 0 gives 0, so we don't care about the multiplicands) memset(&amp;out[hN + 1][REAL], 0, numRem * sizeof(fftw_complex)); // creat a IDFT plan and execute it //plan = fftw_plan_dft_1d(N, out, out, FFTW_BACKWARD, FFTW_ESTIMATE); fftw_execute(plan_backward); // do some cleaning fftw_destroy_plan(plan_backward); //fftw_cleanup(); // scale the IDFT output for (int i = 0; i &lt; N; ++i) { out[i][REAL] /= N; out[i][IMAG] /= N; } } /* Displays complex numbers in the form a +/- bi. */ void displayComplex(fftw_complex* y) { for (int i = 0; i &lt; N; i++) { if (y[i][IMAG] &lt; 0) cout &lt;&lt; y[i][REAL] &lt;&lt; &quot;-&quot; &lt;&lt; abs(y[i][IMAG]) &lt;&lt; &quot;i&quot; &lt;&lt; endl; else cout &lt;&lt; y[i][REAL] &lt;&lt; &quot;+&quot; &lt;&lt; y[i][IMAG] &lt;&lt; &quot;i&quot; &lt;&lt; endl; } } /* Test */ int main() { // input array double x[N]; // output array fftw_complex y[N]; fftw_plan plan_forward = fftw_plan_dft_1d(N, y, y, FFTW_FORWARD, FFTW_ESTIMATE); fftw_plan plan_backward = fftw_plan_dft_1d(N, y, y, FFTW_BACKWARD, FFTW_ESTIMATE); // fill the first of some numbers for (int i = 0; i &lt; N; ++i) { x[i] = i + 1; // i.e.{1 2 3 4 5 6 7 8} } // compute the FFT of x and store the result in y. hilbert(x, y, plan_forward, plan_backward); // display the result cout &lt;&lt; &quot;Hilbert =&quot; &lt;&lt; endl; displayComplex(y); } </code></pre> <p>The exact output value</p> <pre><code>Hilbert = 1+3.82843i 2-1i 3-1i 4-1.82843i 5-1.82843i 6-1i 7-1i 8+3.82843i </code></pre> <p>Here is the original code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;fftw3.h&gt; using namespace std; //macros for real and imaginary parts #define REAL 0 #define IMAG 1 //length of complex array #define N 8 void hilbert(const double* in, fftw_complex* out) { // copy the data to the complex array for (int i = 0; i &lt; N; ++i) { out[i][REAL] = in[i]; out[i][IMAG] = 0; } // creat a DFT plan and execute it fftw_plan plan = fftw_plan_dft_1d(N, out, out, FFTW_FORWARD, FFTW_ESTIMATE); fftw_execute(plan); // destroy a plan to prevent memory leak fftw_destroy_plan(plan); int hN = N &gt;&gt; 1; // half of the length (N/2) int numRem = hN; // the number of remaining elements // multiply the appropriate value by 2 //(those should multiplied by 1 are left intact because they wouldn't change) for (int i = 1; i &lt; hN; ++i) { out[i][REAL] *= 2; out[i][IMAG] *= 2; } // if the length is even, the number of the remaining elements decrease by 1 if (N % 2 == 0) numRem--; else if (N &gt; 1) { out[hN][REAL] *= 2; out[hN][IMAG] *= 2; } // set the remaining value to 0 // (multiplying by 0 gives 0, so we don't care about the multiplicands) memset(&amp;out[hN + 1][REAL], 0, numRem * sizeof(fftw_complex)); // creat a IDFT plan and execute it plan = fftw_plan_dft_1d(N, out, out, FFTW_BACKWARD, FFTW_ESTIMATE); fftw_execute(plan); // do some cleaning fftw_destroy_plan(plan); fftw_cleanup(); // scale the IDFT output for (int i = 0; i &lt; N; ++i) { out[i][REAL] /= N; out[i][IMAG] /= N; } } /* Displays complex numbers in the form a +/- bi. */ void displayComplex(fftw_complex* y) { for (int i = 0; i &lt; N; i++) { if (y[i][IMAG] &lt; 0) cout &lt;&lt; y[i][REAL] &lt;&lt; &quot;-&quot; &lt;&lt; abs(y[i][IMAG]) &lt;&lt; &quot;i&quot; &lt;&lt; endl; else cout &lt;&lt; y[i][REAL] &lt;&lt; &quot;+&quot; &lt;&lt; y[i][IMAG] &lt;&lt; &quot;i&quot; &lt;&lt; endl; } } /* Test */ int main() { // input array double x[N]; // output array fftw_complex y[N]; // fill the first of some numbers for (int i = 0; i &lt; N; ++i) { x[i] = i + 1; // i.e.{1 2 3 4 5 6 7 8} } // compute the FFT of x and store the result in y. hilbert(x, y); // display the result cout &lt;&lt; &quot;Hilbert =&quot; &lt;&lt; endl; displayComplex(y); } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T13:33:33.063", "Id": "500912", "Score": "1", "body": "Post only the working code, remove any mention of throwing exceptions. Change the `C` tag to C++ because @chux-ReinstateMonica is correct, this is C++ code." } ]
[ { "body": "<h2>Updated Code Review for 2020-12-30 Code</h2>\n<p>Some of the original code review items have been addressed. Good work! Here are some remaining ideas:</p>\n<ul>\n<li>I assume your purpose here is to make the <code>hilbert</code> function faster, because you will call it multiple times. You've moved the FFT plan creation outside of <code>hilbert</code>, which is probably a huge speed increase. However, you still call <code>fftw_destroy_plan</code> within <code>hilbert</code>. This is a problem if you call <code>hilbert</code> more than once. You should move <code>fftw_destroy_plan</code> outside of <code>hilbert</code>, so it would be called from <code>main</code> instead.</li>\n<li>You have three different <code>for</code> loops inside <code>hilbert</code>. One copies data from input vector to output vector. One scales half the output vector by a factor of 2. One scales the output vector by 1/N. These loops can all be combined into a single loop at the beginning of <code>hilbert</code>. This works because an FFT is linear, so scaling the input by a constant factor is the same as scaling the output by a constant factor. This new loop would look something like:\n<pre><code> auto scale = 2.0 / N;\n for (int i = 0; i &lt; N; ++i)\n {\n out[i][REAL] = in[i] * scale;\n out[i][IMAG] = 0.0;\n }\n</code></pre>\nThen you would get rid of the other <code>for</code> loops. You would also get rid of the code which multiplies out[hN] by 2 (but keep the call to <code>memset</code> which zeros the second half of the output). Finally, you need to fix out[0], which is now too large by a factor of two:\n<pre><code> out[0][REAL] /= 2.0;\n out[0][IMAG] /= 2.0;\n</code></pre>\nHowever, the speed increase from combining these loops is probably small compared to the FFT time.</li>\n<li>It may take a little more work, but you could change the forward FFT so that it takes its input directly from the real-valued input vector. This is probably close to twice as fast as the complex FFT you are currently doing (but this is just for the forward FFT, so your overall speed increase might be up to 25%). Still, I think it is likely that your complex FFT is already fast enough now that you've removed the creation/destruction of the plan outside of <code>hilbert</code>.</li>\n</ul>\n<h2>Original Code Review for Original 2020-12-26 Code</h2>\n<ul>\n<li><p>In general, using global variables is a bad idea (see below for my reasoning for this statement). You declare a global variable <code>out</code>. It is never used, because your <code>hilbert</code> function takes a parameter named <code>out</code>. So just delete the global <code>out</code> variable.</p>\n</li>\n<li><p>You also declare the FFT plan as a global variable. This <code>plan</code> is what gets used by the <code>hilbert</code> function. But when you initialize the plan in <code>main</code>, you declare a local <code>plan</code> variable. The local <code>plan</code> variable gets initialized by <code>fft_plan_dft_1d</code>, but that doesn't initialize the global variable. The local <code>plan</code> variable is never used. Better would be to get rid of the global <code>plan</code> variable, and use only the one declared in <code>main</code>. Pass it as a parameter into the <code>hilbert</code> function. (This may be one cause of your exception, since you're currently using an uninitialized plan variable inside <code>hilbert</code>.)</p>\n</li>\n<li><p>You only have one <code>plan</code> variable, but it looks like you're trying to make it hold two plans. That won't work. It will remember only the last call to <code>fft_plan_dft_1d</code>, so both times you call <code>fft_execute</code>, you are getting an inverse FFT. And when you call <code>fft_destroy_plan</code> twice, the second one may cause an exception.</p>\n<p>To fix this, you'd want two different <code>plan</code> variables, maybe call them <code>plan_forward</code> and <code>plan_inverse</code> or something like that. Pass them both as parameters into the <code>hilbert</code> function.</p>\n</li>\n<li><p>Having <code>using namespace std;</code> is generally not a good idea. Instead, when you want to use something from that namespace, put <code>std::</code> in front of the name. For example, use <code>std::cout</code> instead of <code>cout</code>.</p>\n</li>\n<li><p>You have <code>int hN = N &gt;&gt; 1;</code>. I personally would prefer <code>int hN = N / 2</code>, as it seems clearer.</p>\n</li>\n<li><p>You copy the input array into the output array and then do an in-place FFT. I think it should be possible to have fftw do a non-in-place FFT where the input vector is real-valued and the output is complex. This should be slightly more efficient. But I'm too lazy to look up the details of how to do it.</p>\n</li>\n</ul>\n<h2>Thoughts on Global Variables</h2>\n<p>My original review just said &quot;In general, using global variables is a bad idea&quot;, without any explanation or context. Some of the comments on this answer either disagreed or wanted more explanation, so here's my reasoning.</p>\n<p>As with most things related to coding style, reasonable people may have differing opinions. Furthermore, nothing is absolute, so I certainly acknowledge that there are cases where global variables are useful or even necessary. Perhaps I should have said &quot;use global variables only when really necessary&quot;.</p>\n<ul>\n<li><p>What do commonly-used coding guidelines say?</p>\n<p>There are lots of coding guidelines on the internet. Many of them in some way discourage the use of global variables. Some examples:</p>\n<ul>\n<li>The <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Ri-global\" rel=\"nofollow noreferrer\">C++ Core Guidelines</a>, maintained by Bjarne Stroustrup and Herb Sutter, say to avoid non-const global variables.</li>\n<li>The <a href=\"https://google.github.io/styleguide/cppguide.html#Static_and_Global_Variables\" rel=\"nofollow noreferrer\">Google C++ Style Guide</a> forbids objects with static storage duration unless they are trivially destructable, and also discourages static storage duration if the object uses dynamic initialization. (Note: global variables have static storage duration.)</li>\n<li>In <a href=\"http://www.stroustrup.com/JSF-AV-rules.pdf\" rel=\"nofollow noreferrer\">Joint Strike Fighter C++ Coding Standards</a>, based on the MISRA C++ coding standards, AV Rule 98 says &quot;Every nonlocal name, except main(), should be placed in some namespace.&quot; (This doesn't prohibit global variables, but does help avoid <em>some</em> of the problems caused by global variables.)</li>\n<li>In <a href=\"http://www.umich.edu/%7Eeecs381/handouts/C++_Coding_Standards.pdf\" rel=\"nofollow noreferrer\">University of Michigan C++ Coding Standards</a>, global variables are acceptable only in certain limited circumstances.</li>\n<li><a href=\"https://www.freecodecamp.org/news/how-to-write-clean-code-in-c/\" rel=\"nofollow noreferrer\">Some random code guideline found on the internet</a> discourages use of global variables, suggesting that you instead use variables declared in functions.</li>\n</ul>\n</li>\n<li><p>What can go wrong when you use global variables</p>\n<ul>\n<li>Initialization issues. If global variables are declared in two different files, there is no specification of the order in which they are initialized. If the initialization of one of them depends on the value of the other, you have undefined behavior. It may appear to work sometimes, but it can't be relied upon.</li>\n<li>Multi-thread issues. If multiple threads simultaneously try to use or modify a global variable, you can get unexpected or undefined behavior. Making this work correctly can be tricky, sometimes requiring the use of mutexes or similar constructs. Often, these constructs slow down the code substantially.</li>\n<li>Name conflicts within a file. You can have a function-local variable and a global variable with the same name. They are different variables, and this can lead to confusion. Maybe you meant the local variable to access the global variable, but accidentally declared it locally. Or maybe you meant for the local variable to be different than the global variable, but a subsequent maintainer may not realize that and think they are the same variable. These kind of issues can lead to bugs.</li>\n<li>Name conflicts with external libraries. If you have an external global variable, it can conflict with other external global variables with the same name. These kind of conflicts can make it difficult to integrate separate software libraries.</li>\n</ul>\n</li>\n</ul>\n<p>In many cases, global variables offer no benefit in exchange for the above potential problems (the original post is one example of that). Therefore, I think it is best to avoid global variables unless they are really necessary.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T01:53:34.887", "Id": "500866", "Score": "1", "body": "\"In general, using global variables is a bad idea.\" is too sweeping a statement - global data is fine - it is an application dependent issue. IAC unless that memory location affects performance, little reason to comment on it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T06:14:20.763", "Id": "500871", "Score": "0", "body": "I still think that *in general* global variables are a bad idea, though I will admit there are times when they are useful/necessary." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T13:19:07.740", "Id": "500909", "Score": "1", "body": "Explain why in your experience global variables are bad. I happen to agree with you but in my answers I explain why." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T14:11:31.153", "Id": "500914", "Score": "2", "body": "The C++ Guidelines is a good reference for many things, including why one should [avoid non-const global variables](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Ri-global)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T15:24:52.470", "Id": "500925", "Score": "0", "body": "I tried to follow your guide, but still several problems happened:\n1. The VS is keep showing that `out` is an undefined variables, since I moved `fftw_plan plan_forward = fftw_plan_dft_1d(N, out, out, FFTW_FORWARD, FFTW_ESTIMATE);` out the `hilbert()`, so I still preserved `fftw_complex* out;` at global declaration, any better thoughts?\n2. Similar to the `out` variable problem, as I moved `fftw_plan plan_forward = fftw_plan_dft_1d(N, out, out, FFTW_FORWARD, FFTW_ESTIMATE);` out `hilbert()`, the variable `plan` inside the `hilbert` became needs to be defined again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T15:28:25.767", "Id": "500927", "Score": "0", "body": "In order to prevent the `plan` variables need to be defined, I moved both `fftw_execute` to the `main`. However, the code still didn't work since the similar `Exception thrown at 0x00000000707E4D38 (libfftw3-3.dll) in CppFFTW.exe: 0xC0000005: Access violation reading location 0x0000000000000000.` happened. Please take a look to the code I updated today at the question content." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T17:11:02.163", "Id": "500934", "Score": "0", "body": "A classic example where global data is good and allocated data is bad is with life critical applications (air traffic control, medical devices) where out-of-memory is simple not an option. IAC, I see scant performance change (OP's review goals) due to its use or not." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T20:12:13.267", "Id": "500955", "Score": "0", "body": "@pacmaninbw OK, I've tried to add some explanation of why I think global variables are not generally a good idea." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T20:14:10.510", "Id": "500957", "Score": "0", "body": "@chux-ReinstateMonica Yes, it is true that the global variables in the original post are not affecting performance, though they *were* contributing to a defect that prevents the code from working. Yes, embedded critical systems may be a place where allocated data is bad. However, even if the original post's hilbert transform was meant for that environment, I would still be arguing that the FFT plan variables should be passed into `hilbert` rather than be global." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T20:22:44.080", "Id": "500959", "Score": "0", "body": "\"should be passed into hilbert\" is an agreeable view and is more true with C++ than C (now that the tag has changed) Yet \"using global variables is a bad idea\" remains an overstatement and takes always from OP's efficiency focus." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T23:00:25.483", "Id": "500967", "Score": "0", "body": "Better. Since the question is now closed you may not get a lot of up votes, but good job." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T10:35:40.837", "Id": "500989", "Score": "0", "body": "@Eric Backus I tried almost followed your instruction to rewrite the code, at least it can run normally now, but the output value was not right. Please take a look in the question content which I updated. Any thoughts?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T18:06:12.103", "Id": "501128", "Score": "0", "body": "@Kevin I think you've got some fundamental misunderstanding of C++ there. That's OK, we've all had to learn it at some point, and C++ is a complicated language. Anyway, you have no calls to FFT at all in your `hilbert` function, so all it is doing is multiplying the first half of the input data by 1/N (for the first point) or 2/N (for the remainder of the first half), and setting the second half of the points to zero. You need to put back the calls to `fft_execute` in `hilbert`, but leave the `plan_forward` and `plan_backward` in `main`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T18:08:59.017", "Id": "501129", "Score": "0", "body": "Then pass `plan_forward` and `plan_backward` as parameters into `hilbert`, and use them in the calls to `fft_execute`. Your initialization of `plan_forward` and `plan_backward` should use `y`, not `out`, since `y` is what you pass to `hilbert`. Hope this helps... :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T18:24:27.710", "Id": "501135", "Score": "0", "body": "@Eric Backus Thanks for the reply, I will try and realize what you mentioned above. In fact, I just be thrown to use C/C++ recently because our data stream DAQ card only support in C, since I only know how to write Matlab... So, I'm just trying to write and let it run but with less knowledge." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T18:39:32.963", "Id": "501140", "Score": "0", "body": "@EricBackus If I move `fft_execute(plan_forward)` (also the backward) back to the `hilbert()`, the VS will show the red saying `the variable is undefined` so where is the place better to declare these two variables?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T21:37:41.307", "Id": "501155", "Score": "0", "body": "@Kevin Leave the plan variables declared in `main`. But add them to the parameters passed to `hilbert`. So the hilbert function declaration would look like `void hilbert(const double* in, fftw_complex* out, fftw_plan plan_forward, fftw_plan plan_backward)`. Then when you call the hilbert function from main, use `hilbert(x, y, plan_forward, plan_backward);`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T21:57:50.437", "Id": "501157", "Score": "0", "body": "@EricBackus Super cool! I got the same output answer! I think this could be my late Christmas gift, thanks! One last check, please take a look to the code that I updated to see if there are anything can be more optimized." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-03T01:48:55.780", "Id": "501413", "Score": "0", "body": "@Kevin See my updated answer..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-03T16:41:50.470", "Id": "501448", "Score": "0", "body": "@EricBackus Thanks for your advice! However, I tried to move the `fftw_destroy_plan(plan_forward);` out to the `hilbert()` and put them on the end of the `main()`(below the `displayComplex(y);`), there is a `break point` occurred, saying `CppFFTW.exe has triggered a breakpoint.` Maybe I put them on the wrong place of `main()`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-03T17:46:30.700", "Id": "501452", "Score": "0", "body": "Sounds like you did the right thing, so I don't know what's causing the break point. I'm no FFTW expert though. Perhaps call fftw_cleanup() after you destroy the plans?" } ], "meta_data": { "CommentCount": "21", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T17:55:52.290", "Id": "253964", "ParentId": "253959", "Score": "6" } } ]
{ "AcceptedAnswerId": "253964", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T14:56:42.187", "Id": "253959", "Score": "0", "Tags": [ "c++", "performance", "signal-processing" ], "Title": "How could I make FFTW Hilbert transform calculate faster?" }
253959
<p>I'm currently creating a text based game where the user navigates through the game via buttons and i'm trying to improve on my code because i'm pretty sure it could be alot better, the following is some code which i wrote to give the user some options (via html buttons) and then check what their selection is in order to execute the correct function.</p> <pre><code>class Room { constructor(description, options) { this.description = description; this.options = options; } } var f1hallway = new Room(&quot;You see two rooms&quot;, [&quot;Room 1&quot;, &quot;Room 2&quot;]); var f1room1 = new Room(&quot;You find a letter on a table&quot;, [&quot;Read it&quot;, &quot;Exit&quot;]); var f1room2 = new Room(&quot;Nothing of interest here&quot;, [&quot;Exit&quot;]); whichArea = function(areaSelected) { selectedArea = areaSelected; areaSelected(); } function presentChoices(options) { choices.innerHTML = &quot;&quot;; for (var x = 0; x &lt; options.length; x++) { choiceButton = document.createElement(&quot;button&quot;); choiceButton.setAttribute(&quot;class&quot;, &quot;choice-button&quot;); choices.appendChild(choiceButton); choiceButton.innerHTML = options[x]; selectedChoiceIndex = x; choiceButton.setAttribute(&quot;id&quot;, x); choiceButton.onclick = function() { selectedChoice = this.innerHTML; chosenOptionId = this.id; whichArea(selectedArea); } } } function f1hallwayFunc() { mainText.innerHTML = f1hallway.description; choices.innerHTML = &quot;&quot;; presentChoices(f1hallway.options); if (chosenOptionId == 0) { chosenOptionId = null; whichArea(f1roomOneFunc); } else if (chosenOptionId == 1) { chosenOptionId = null; whichArea(f1roomTwoFunc); } function f1roomOneFunc() { mainText.innerHTML = f1room1.description; presentChoices(f1room1.options); if (chosenOptionId == 0) { chosenOptionId = null; mainTextWrap.innerHTML = &quot;You start reading the letter&quot;; } else if (chosenOptionId == 1) { chosenOptionId = null; whichArea(f1hallwayFunc); mainText.innerHTML = &quot;You exit the room and return to the hallway&quot;; } } function f1roomTwoFunc() { mainText.innerHTML = f1room2.description; presentChoices(f1room2.options); if (chosenOptionId == 0) { chosenOptionId = null; whichArea(f1hallwayFunc); mainText.innerHTML = &quot;You exit the room and return to the hallway&quot;; } } </code></pre> <p>The code works fine but seems like a mess at the same time, each area that the user ends up in goes through this same process, can someone please tell me how this could be written better and any best practices i'm missing? I'm still quite new to programming and would appreciate any help, thanks!</p>
[]
[ { "body": "<p>I think a good way to approach this would be to integrate all the data (descriptions, options, and additional room choices) into an object indexed by room number or step name (since multiple things can be done in a single room). Starting at the first room, parse the data for that room to display the description and choices appropriately, and continue recursively whenever a new choice is made. Doing it this way means that, to set up the rooms, you only need to change around the object room numbers and strings instead of writing convoluted JavaScript logic.</p>\n<p>For example, for the hallway and 2 rooms, you could have:</p>\n<pre><code>const steps = {\n hallway: {\n desc: 'You see two rooms',\n choices: ['Room 1', 'Room 2']\n },\n 'Room 2': {\n desc: 'Nothing of interest here',\n // when the choice description and JS step name are not the same,\n // separate them\n choices: [{ desc: 'Exit', target: 'hallway' }]\n },\n 'Room 1': {\n desc: 'You find a letter on the table',\n choices: [\n { desc: 'Read it', target: 'readLetter' },\n { desc: 'Exit', target: 'hallway', onChoiceDesc: 'You exit the room and return to the hallway' }\n ]\n },\n readLetter: {\n // ...\n },\n}; \n</code></pre>\n<p>Whenever a new step runs, if the choice that was just chosen had a <code>onChoiceDesc</code> property, display that. Otherwise, display the <code>desc</code> of the new step onto the page. Iterate through each choice to add a button, a button description, and a click handler.</p>\n<p>To conditionally display a choice depending on program state, add a function to the choice object. Eg, if, after reading the letter, something becomes available in the hallway, you could add the following:</p>\n<pre><code>choices: ['Room 1', 'Room 2', { desc: 'Room 3', target: 'Room 3', showIf: () =&gt; hasReadLetter }]\n</code></pre>\n<pre><code>readLetter: {\n desc: 'You start reading the letter. The letter informs you that Room 3 exists',\n choices: [\n { desc: 'Exit', target: 'hallway', onChoiceFn: () =&gt; hasReadLetter = true }\n ]\n}\n</code></pre>\n<p>where <code>onChoice</code> gets invoked when the button is clicked (in addition to the default behavior of re-rendering the hallway step). (Make sure to have declared a <code>hasReadLetter</code> variable outside.)</p>\n<p>That's the general idea - leave the manipulation of the DOM to the other code that parses through the <code>steps</code> object, while writing the meat of the game inside the <code>steps</code> object.</p>\n<hr />\n<p>Although you'll probably be ditching most of it, some suggestions regarding your current code:</p>\n<p><strong>Classes are good for tying together data with methods related to the data.</strong> If all you have is plain data, a class doesn't help you. In your case, unless you were planning on adding methods later, using a plain object would make more sense for the <code>Room</code>s.</p>\n<p><strong>Use consistent indentation</strong> so that you (and other readers of the code) can pick up on the <code>{</code> <code>}</code> blocks at a glance. Ideally, use an IDE that indents code properly and automatically. For example, this:</p>\n<pre><code>}\n var f1hallway = new Room(&quot;You see two rooms&quot;, [&quot;Room 1&quot;, &quot;Room 2&quot;]);\n whichArea = function(areaSelected) {\n selectedArea = areaSelected;\n</code></pre>\n<p>should be</p>\n<pre><code>}\nvar f1hallway = new Room(&quot;You see two rooms&quot;, [&quot;Room 1&quot;, &quot;Room 2&quot;]);\nwhichArea = function(areaSelected) {\n selectedArea = areaSelected;\n</code></pre>\n<p><strong>Declare variables before using them</strong> - if you don't, you'll either be implicitly assigning to the global object (which is inelegant), or an error will be thrown if running in strict mode (and strict mode is recommended). Not declaring a variable before using it is a not-uncommon source of bugs when one finds that the variable isn't scoped as one expected it to be. The <code>whichArea =</code> should be <code>let whichArea =</code>.</p>\n<p><strong>Use modern syntax</strong> If you're going to write in ES6+ (which you are with the <code>class</code>, and as you should), never use <code>var</code>, it has too many gotchas to be worth using nowadays - use <code>const</code> instead when declaring variables, or use <code>let</code> when you have to reassign the variable.</p>\n<p><strong>Prefer IDL properties over <code>setAttribute</code></strong> when feasible - IDL properties are usually more concise and easier to read and write. These two:</p>\n<pre><code>choiceButton.setAttribute(&quot;class&quot;, &quot;choice-button&quot;);\nchoiceButton.setAttribute(&quot;id&quot;, x);\n</code></pre>\n<p>can be</p>\n<pre><code>choiceButton.className = &quot;choice-button&quot;;\nchoiceButton.id = x;\n</code></pre>\n<p>(though, neither of those should be necessary at all: to target the button with CSS, you should be able to do <code>.choices &gt; button</code>, by giving the parent a class name instead. Dynamic IDs are quite a code smell too - to get the index inside a click handler, either check the child's index in an array of all siblings, or use a data attribute, or a Map - but not an ID. Or, even better, in this case, just use the closure in the click handler over the index being iterated over.)</p>\n<p><strong>Prefer <code>.textContent</code> over <code>.innerHTML</code></strong> unless you're deliberately setting text content; <code>.textContent</code> is faster, safer, and more semantically appropriate.</p>\n<p><strong>Prefer strict equality</strong> - loose equality with <code>==</code> and <code>!=</code> has a whole bunch of weird coercion rules that neither you nor others who happen to read the code should have to have memorized to understand what's going on. Use <code>===</code> and <code>!==</code> instead.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T19:28:41.377", "Id": "253966", "ParentId": "253963", "Score": "0" } }, { "body": "<h2>Programming rules of thumb.</h2>\n<ul>\n<li><p>If you find yourself prefixing many names with the same prefix it is a sign that you should be creating an object to hold these variables.</p>\n</li>\n<li><p>Many functions doing similar things is a sign that one function with arguments defining things can do the same.</p>\n</li>\n<li><p>Always separate data from code. You should not need to change code when you change the data and you should design the data so that changes to the code does not effect unrelated data.</p>\n<p>Creating games is a very creative and iterative process. Having to change code each time you change some aspect of the game impedes the creative process, the end result is a so so game. Separating data from code make it much easier to create a great game.</p>\n</li>\n</ul>\n<h2>Encapsulate</h2>\n<p>A program is created to manage abstractions. For example your game has the abstract entities Rooms, Room, Option, etc..</p>\n<p>You should encapsulate abstract concepts withing Objects so that it becomes much easier to manage and work with these abstract objects rather than a long list of loosely related functions.</p>\n<h2>Use maps</h2>\n<p>When performance is not critical use named references via maps, rather than indexes to locate data. We humans are much better at associating names to items, than numbers.</p>\n<p>A map can be an object with named properties. Eg</p>\n<pre><code>rooms = {};\nrooms[&quot;room1&quot;] = new Room(...);\nrooms[&quot;room2&quot;] = new Room(...);\n</code></pre>\n<h2>Code noise</h2>\n<p>Code noise is anything that is not absolutely needed to achieve some task. Always strive to reduce code noise.</p>\n<h3>Repeated verbose code</h3>\n<p>The DOM interface is a rather verbose and ugly thing. You can greatly reduce the amount of noise in your code by creating functions to do these often repeated calls.</p>\n<p>The example creates functions to work with the DOM <code>tag</code>, <code>append</code>, <code>listener</code>. Then some higher level functions to help with the game <code>clearOptions</code>, <code>createOptionBtn</code>, <code>showActionText</code> that use the DOM functions to do their thing.</p>\n<p>Then when you want to add a choice you can call <code>createOptionBtn</code> rather than a long list of obscure DOM calls.</p>\n<h2>Rewrite</h2>\n<p>The rewrite is as an example only, there is no right or wrong way to write this type of code. If you are new to coding it may be too complex, if so take what you can from it. It is better to write code you are comfortable with than struggle with code you don't understand.</p>\n<p>The rewrite is from the ground up.</p>\n<p>It completely separates the game logic from the game data.</p>\n<p>It encapsulates</p>\n<ul>\n<li><code>Room</code> A room has a description, and may contain named options.</li>\n<li><code>Option</code> An option, has a name and actions. Actions define what the options will do. In the example I did not formalize the actions within an abstract Object as I did not plan out what the game should do.</li>\n<li><code>rooms</code> Holds all the rooms by name <code>rooms.list</code> it has a function to add a room, and handles the actions available to an option.</li>\n</ul>\n<p>With the code in place the game is created by defining rooms and options.</p>\n<p>For example to add a room with two options.</p>\n<pre><code>rooms.add(&quot;hallway&quot;, &quot;You see two rooms&quot;,\n Option(&quot;Enter Room 1&quot;, {goto: &quot;room1&quot;}),\n Option(&quot;Enter Room 2&quot;, {goto: &quot;room2&quot;})\n);\n</code></pre>\n<p>The first room has the letter. The option to read the letter has actions to replace the read letter option with a new option.</p>\n<pre><code>rooms.add(&quot;room1&quot;, &quot;You find a letter on a table&quot;,\n Option(&quot;Read it&quot;, {\n do: &quot;You start reading the letter. 'Something evil lurks in the other room'&quot;,\n addOption: {\n room: &quot;room1&quot;,\n option: Option(&quot;Read it&quot;, {do: &quot;You read the letter again&quot;}),\n },\n update: {room: &quot;room1&quot;},\n }),\n Option(&quot;Exit&quot;, {goto: &quot;hallway&quot;, desc: &quot;You exit the room and return to the hallway&quot;}),\n);\n</code></pre>\n<p>Though only partly thought out you should be able to see how the game content is independent of the game logic. You could create a huge adventure without needing to add any more code.</p>\n<p>If you find that the existing code does not cover all aspects of the game, you should be able to add extra features to the code logic without having to change any unrelated data.</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>;(()=&gt;{\n\"use strict\";\n// General utils\nconst tag = (tag, props = {}) =&gt; Object.assign(document.createElement(tag), props);\nconst append = (par, ...sibs) =&gt; sibs.reduce((p, sib) =&gt; (p.appendChild(sib), p), par);\nconst listener = (el, type, call, opts = {}) =&gt; (el.addEventListener(type, call, opts), el);\n\n// Game utils\nconst clearOptions = () =&gt; optionsContainer.innerHTML = \"\";\nconst createOptionBtn = option =&gt; listener(\n tag(\"button\", {className: \"choiceButton\", textContent: option.name}),\n \"click\", option.clickEvent, {once: true}\n);\nconst showActionText = text =&gt; {\n append(textContainer, tag(\"div\", {textContent: text}));\n textContainer.scrollTo(0, 2000000);\n};\n\n// game object\nfunction Option(name, actions) {\n return {\n get name() { return name } ,\n get actions() { return actions } ,\n };\n}\nfunction Room(description, ...options) {\n const optionSelectClick = option =&gt; event =&gt; {\n for (const action of Object.keys(option.actions)) {\n rooms.actions[action] &amp;&amp; rooms.actions[action](option);\n }\n };\n\n const optionMap = {};\n const addOption = option =&gt; {\n optionMap[option.name] = option;\n option.clickEvent = optionSelectClick(option);\n };\n options.forEach(addOption);\n return {\n enter() {\n showActionText(description);\n clearOptions();\n append(optionsContainer, ...Object.values(optionMap).map(createOptionBtn));\n },\n addOption,\n removeOption(name) { delete optionMap[name] },\n update(desc = description) {\n description = desc,\n clearOptions();\n append(optionsContainer, ...Object.values(optionMap).map(createOptionBtn));\n },\n };\n}\nconst rooms = {\n list: {},\n add(name, desc, ...options) { rooms.list[name] = Room(desc, ...options) },\n actions: {\n goto(option) {\n option.actions.desc &amp;&amp; showActionText(option.actions.desc);\n rooms.list[option.actions.goto].enter();\n },\n do (option) { showActionText(option.actions.do) },\n addOption(option) {\n const add = option.actions.addOption;\n rooms.list[add.room].addOption(add.option);\n },\n removeOption(option) {\n const remove = option.actions.removeOption;\n rooms.list[remove.room].removeOption(remove.name);\n },\n update(option) { \n const update = option.actions.update ;\n rooms.list[update.room].update(update.desc) \n },\n }\n};\n\n\n// Game data\nrooms.add(\"hallway\", \"You see two rooms\",\n Option(\"Room 1\", {goto: \"room1\", desc: \"You enter the first room.\"}),\n Option(\"Room 2\", {goto: \"room2\", desc: \"You enter the second room.\" })\n);\n\nrooms.add(\"room1\", \"You find a letter on a table\",\n Option(\"Read it\", {\n do: \"You start reading the letter. 'Something evil lurks in the other room'\",\n addOption: {\n room: \"room1\",\n option: Option(\"Read it\", {\n do: \"Reading the letter again you notice a drawing of what looks like bug spray\",\n addOption: {\n room: \"room2\",\n option: Option(\"Get bug spray\", {\n do: \"You pickup the can of bug spray\",\n removeOption: {room: \"room2\", name: \"Get bug spray\"},\n addOption: {\n room: \"room2\",\n option: Option(\"Spray bug\", {\n do: \"You spray the bug. It reacts with a hiss and disapares down a rather large hole in the floor boards\",\n removeOption: {room: \"room2\", name: \"Spray bug\"},\n addOption: {\n room: \"room2\",\n option: Option(\"Inspect bug\", {\n do: \"The bug is gone\",\n removeOption: {room: \"room2\", name: \"Inspect bug\"},\n update: {room: \"room2\"}\n })\n },\n update: {room: \"room2\", desc: \"You enter an empty room\"}\n }),\n },\n update: {room: \"room2\"},\n })\n },\n removeOption: {\n room: \"room1\",\n name: \"Read it\",\n },\n update: {room: \"room1\"} \n }),\n },\n update: {room: \"room1\"},\n }),\n Option(\"Exit\", {goto: \"hallway\", desc: \"You exit the room and return to the hallway\"}),\n);\n\nrooms.add(\"room2\", \"You find a huge bug\",\n Option(\"Inspect bug\", {\n do: \"The bug is as big as you and looks hungry\",\n addOption: {\n room: \"room2\",\n option: Option(\"Inspect bug\", {\n goto: \"endGame\", desc:\"The gigantic bug looms over and devours you\" }),\n },\n update: {room: \"room2\"},\n }),\n Option(\"Exit\", {goto: \"hallway\", desc: \"You exit the room and return to the hallway\"})\n);\n\nrooms.add(\"endGame\", \"Game over you die\");\n\n\n// game start\nrooms.actions.goto({actions:{goto:\"hallway\", desc: \"You are in a hallway, you hear a noise somewhere down the hallway.\"}});\n\n\n})();</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.choiceButton {\n}\n\n#textContainer {\n height: 140px;\n max-height: 140px;\n overflow-y: scroll;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div id=\"textContainer\"&gt; \n&lt;/div&gt;\n&lt;div id=\"optionsContainer\"&gt; \n&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-12-29T16:39:47.430", "Id": "254043", "ParentId": "253963", "Score": "0" } } ]
{ "AcceptedAnswerId": "254043", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T17:51:53.440", "Id": "253963", "Score": "1", "Tags": [ "javascript" ], "Title": "Presenting user with options and executing a function based on user choice in Javascript" }
253963
<p>I have implemented my own version of algorithm to multiply two matrices together and I need someone who know what they are doing to see if there is anything that can be done in a more optimal way. I am also keen on understanding how I can make it robust such that it doesn't crash when non-rectangular matrices are passed as argument i.e. matrix that has uneven number of elements in different <code>Vd</code>s it holds.</p> <p>I am particularly interested in function <code>matrixDot</code> in the code bellow, everything else is only to show how I am using it in my project).</p> <pre><code>#include &quot;iostream&quot; #include &lt;vector&gt; #define LOG(m) std::cout &lt;&lt; m &lt;&lt; std::endl struct Vd { std::vector&lt;double&gt; v; }; struct Md { std::vector&lt;Vd&gt; m; //fill matrix with num void fill(unsigned const int rows, unsigned const int cols, const double num) { m.clear(); for (unsigned int i = 0; i &lt; rows; i++) { Vd tempVec; for (unsigned int j = 0; j &lt; cols; j++) { tempVec.v.push_back(num); } m.push_back(tempVec); } } friend std::ostream&amp; operator &lt;&lt; (std::ostream&amp; out, const Md&amp; mat) { out &lt;&lt; &quot;[&quot; &lt;&lt; std::endl &lt;&lt; std::endl; for (unsigned int i = 0; i &lt; mat.m.size(); i++) { out &lt;&lt; &quot;[&quot;; for (unsigned int j = 0; j &lt; mat.m[i].v.size(); j++) { if (j % mat.m[i].v.size() == mat.m[i].v.size() - 1) out &lt;&lt; mat.m[i].v[j] &lt;&lt; &quot;]&quot; &lt;&lt; std::endl &lt;&lt; std::endl; else out &lt;&lt; mat.m[i].v[j] &lt;&lt; &quot;, &quot;; } } out &lt;&lt; &quot;]&quot; &lt;&lt; std::endl; return out; } }; inline void matrixDot(const Md&amp; m1, const Md&amp; m2, Md&amp; outm) { if (m1.m[0].v.size() &amp;&amp; m2.m.size()) if (m1.m[0].v.size() != m2.m.size()) { LOG(&quot;Shape mismatch: &quot; &lt;&lt; &quot;matrix1 columns: &quot; &lt;&lt; m1.m[0].v.size() &lt;&lt; &quot;, &quot; &lt;&lt; &quot;matrix2 rows: &quot; &lt;&lt; m2.m.size()); throw std::exception(); } unsigned int m1x = 0; unsigned int m1y = 0; unsigned int m2y = 0; //m2x = m1y while (outm.m.size() &lt; m1.m.size()) { Vd tempv; while (tempv.v.size() &lt; m2.m[0].v.size()) { double total = 0.0; while (m1x &lt; m1.m[0].v.size()) { total += m1.m[m1y].v[m1x] * m2.m[m1x].v[m2y]; m1x++; } tempv.v.push_back(total); m1x = 0; m2y &lt; m2.m[0].v.size() - 1 ? m2y++ : m2y = 0; } m1y &lt; m1.m.size() - 1 ? m1y++ : m1y = 0; outm.m.push_back(tempv); } } int main() { Md mat1; mat1.fill(5, 2, 1.0); Md mat2; mat2.fill(2, 6, 2.0); Md mat3; matrixDot(mat1, mat2, mat3); std::cout &lt;&lt; mat3; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T03:24:27.673", "Id": "500868", "Score": "2", "body": "I heard that some of the hard core matrix libraries don't actually do any arithmetic until the values are needed. That way if there are operations you can combine (addition/subtraction) or operations that can be removed (multiply by identity) these can be done before the hard work is done. Or if the value is never used the arithmatic is never actually done." } ]
[ { "body": "<p>I have to admit I'm a bit confused, you did the hard parts and have a question on the easy parts? I might be misunderstanding your question.</p>\n<blockquote>\n<p>I am also keen on understanding how I can make it robust such that it doesn't crash when non-rectangular matrices are passed as argument i.e. matrix that has uneven number of elements in different Vds it holds.</p>\n</blockquote>\n<p>You could validate that you have a well formed matrix by</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>inline bool isValid(const Md&amp; mat)\n{\n if (mat.m.size())\n {\n int size = mat.m[0].v.size();\n for (int i = 1; i &lt; mat.m.size(); i++) {\n if (size != mat.m[i].v.size())\n {\n return false;\n }\n } \n }\n \n return true;\n}\n\n</code></pre>\n<p>and incorporating it into the <code>matrixDot</code> function for validation similar to the shape validation you have right now</p>\n<pre><code> if (m1.m[0].v.size() &amp;&amp; m2.m.size())\n if (m1.m[0].v.size() != m2.m.size())\n {\n LOG(&quot;Shape mismatch: &quot; &lt;&lt; &quot;matrix1 columns: &quot; &lt;&lt; m1.m[0].v.size() &lt;&lt; &quot;, &quot; &lt;&lt; &quot;matrix2 rows: &quot; &lt;&lt; m2.m.size());\n throw std::exception();\n }\n \n if (!isValid(m1))\n {\n LOG(&quot;Invalid matrix :: &quot; &lt;&lt; std::endl);\n std::cout &lt;&lt; m1;\n throw std::exception();\n }\n \n if (!isValid(m2))\n {\n LOG(&quot;Invalid matrix :: &quot; &lt;&lt; std::endl);\n std::cout &lt;&lt; m2;\n throw std::exception();\n }\n</code></pre>\n<p>Any optimizations I can think of are around utilizing <code>std::array</code> instead of <code>std::vector</code> as you are aware of row and column lengths at time of creation.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T02:24:55.333", "Id": "500867", "Score": "0", "body": "I did think of loops but then I left like it would be not be worth it to sacrifice performance just to check if data is valid when I most likely would be passing the right data anyway. I was think more of a trick or something to validate without a loop." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T02:20:46.043", "Id": "253981", "ParentId": "253970", "Score": "3" } }, { "body": "<p>Personally I'd extend the Md struct (class) so that it encapsulates the matrix fully. It would have:</p>\n<p>--&gt; Member variables for:</p>\n<pre><code> The number of rows and columns. \n Vector to hold the data. (Consider one dimensional array here).\n</code></pre>\n<p>--&gt; Constructor that would allow a matrix of the right size to be created (rows,cols).</p>\n<pre><code> This would allow you to use vector resize and reserve which will give you \n a more performant implementation, especially if the matrices are re-used.\n So avoid using push_back and instead set values directly.\n</code></pre>\n<p>--&gt; Get functions to get number of rows/columns</p>\n<p>--&gt; Get/Set functions to get/set matrix data values.</p>\n<pre><code> Get/Set functions implement bounds checking.\n</code></pre>\n<p>I'd then derive a mathMatrix class which would add the matrix multiplication functionality. This would necessitate replacing most of the direct access to size functions/data items etc with calls from the above which would make it easier to read and hence maintain.</p>\n<p>Then as the earlier poster suggested adding isValid or canMultiply functions would help with making the solution more robust.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T09:57:04.910", "Id": "254023", "ParentId": "253970", "Score": "3" } }, { "body": "<p>I see some things that you might want to use to improve your code.</p>\n<h2>Use <code>using</code> where appropriate</h2>\n<p>The code currently contains this:</p>\n<pre><code>struct Vd\n{\n std::vector&lt;double&gt; v;\n};\n</code></pre>\n<p>This is probably better expressed like this instead:</p>\n<pre><code>using Vd = std::vector&lt;double&gt;;\n</code></pre>\n<p>So now, instead of writing this:</p>\n<pre><code>out &lt;&lt; mat.m[i].v[j] &lt;&lt; &quot;, &quot;;\n</code></pre>\n<p>We can use this cleaner syntax:</p>\n<pre><code>out &lt;&lt; mat.m[i][j] &lt;&lt; &quot;, &quot;;\n</code></pre>\n<h2>Understand header include paths</h2>\n<p>There is a subtle difference between <code>#include &quot;iostream&quot;</code> and <code>#include &lt;iostream&gt;</code>. Although it's implementation defined, most compiler implementations is that the quotation mark form searches locally first (e.g. the current directory) and then searches system include directories if that fails. The angle bracket form usually searches in system include directories. See <a href=\"https://stackoverflow.com/questions/21593/what-is-the-difference-between-include-filename-and-include-filename\">this question</a> for more. For that reason, this code should probably use <code>#include &lt;iostream&gt;</code>.</p>\n<h2>Don't use <code>std::endl</code> if you don't really need it</h2>\n<p>The difference betweeen <code>std::endl</code> and <code>'\\n'</code> is that <code>'\\n'</code> just emits a newline character, while <code>std::endl</code> actually flushes the stream. This can be time-consuming in a program with a lot of I/O and is rarely actually needed. It's best to <em>only</em> use <code>std::endl</code> when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one. Avoiding the habit of using <code>std::endl</code> when <code>'\\n'</code> will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized.</p>\n<h2>Use standard functions where appropriate</h2>\n<p>Rather than writing the <code>ostream&amp; operator&lt;&lt;</code> as you have, a neat alternative would be to use <code>std::copy</code> and <a href=\"https://en.cppreference.com/w/cpp/experimental/ostream_joiner\" rel=\"nofollow noreferrer\"><code>std::experimental::ostream_joiner</code></a> like this:</p>\n<pre><code>friend std::ostream&amp; operator &lt;&lt; (std::ostream&amp; out, const Md&amp; mat)\n{\n out &lt;&lt; &quot;[\\n&quot;;\n for (const auto&amp; row : mat.m) {\n out &lt;&lt; &quot;\\t[&quot;;\n std::copy(row.begin(), row.end(), std::experimental::make_ostream_joiner(out, &quot;, &quot;));\n out &lt;&lt; &quot;]\\n&quot;;\n }\n return out &lt;&lt; &quot;]\\n&quot;;\n}\n</code></pre>\n<h2>Prefer return values to output parameters</h2>\n<p>It seems much more logical to have <code>matrixDot</code> return a new matrix, rather than using the third parameter as an output parameter. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rf-out\" rel=\"nofollow noreferrer\">F.20</a> for more details.</p>\n<h2>Consider an alternative representation</h2>\n<p>This code is somewhat fragile in that both the <code>Md</code> and <code>Vd</code> are implemented as <code>struct</code>, with all members public. Worse, is that we could have a jagged array in which each row does not have the same number of items. This is probably not going to result in anything nice. For both of those reasons, I'd suggest using a <code>class</code> and using a single <code>vector</code> to hold all items. See <a href=\"https://codereview.stackexchange.com/questions/142815/generic-matrix-type-in-c\">this question</a> for some ideas and advice on how to do that. You might also look at <a href=\"https://en.cppreference.com/w/cpp/numeric/valarray\" rel=\"nofollow noreferrer\"><code>std::valarray</code></a> as an underlying type.</p>\n<h2>Provide a full class implementation</h2>\n<p>In addition to a constructor taking <code>std::initializer_list</code> arguments, I'd also suggest some of the other operators such as <code>operator==</code> for this class.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T22:39:54.553", "Id": "501040", "Score": "0", "body": "\"Rather than writing the `ostream& operator<<`\" was that a typo and you meant \"Rather than writing the ` out <<`\" ? or am I missing something here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T23:22:13.537", "Id": "501047", "Score": "1", "body": "No, I meant the function itself, the full name of which is `std::ostream& operator<<(std::ostream& out, const Md& mat)`. I was just trying to use a slightly shorter version of that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T21:55:25.250", "Id": "254062", "ParentId": "253970", "Score": "1" } } ]
{ "AcceptedAnswerId": "254062", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T21:06:43.007", "Id": "253970", "Score": "3", "Tags": [ "c++", "matrix" ], "Title": "Optimizing matrix multiplication algorithm" }
253970
<p>I've wrote a FixedArray to fit seamlessly (function-wise) with the default C++ containers, including working with algorithms/etc. It is a dynamically allocated, but fixed size array.</p> <h2>Code</h2> <br/> <pre><code>#pragma once #include &lt;cstddef&gt; #include &lt;initializer_list&gt; #include &lt;algorithm&gt; #include &lt;limits&gt; #include &lt;concepts&gt; #include &lt;iterator&gt; #include &lt;stdexcept&gt; namespace Util { template&lt;typename C, typename T=typename C::value_type&gt; concept Container = std::input_iterator&lt;typename C::iterator&gt; &amp;&amp; std::is_same_v&lt;typename C::value_type,T&gt; &amp;&amp; requires(C c,const C cc,size_t i) { { c.begin() } -&gt; std::same_as&lt;typename C::iterator&gt;; { c.end() } -&gt; std::same_as&lt;typename C::iterator&gt;; { cc.begin() } -&gt; std::same_as&lt;typename C::const_iterator&gt;; { cc.end() } -&gt; std::same_as&lt;typename C::const_iterator&gt;; { c.size() } -&gt; std::same_as&lt;typename C::size_type&gt;; }; template&lt;typename T, bool _reassignable=false, typename Alloc=std::allocator&lt;T&gt;&gt; class FixedArray { public: using value_type=T; using allocator_type=Alloc; using size_type=size_t; using difference_type=std::ptrdiff_t; using reference=T&amp;; using pointer=T*; using iterator=T*; using reverse_iterator=std::reverse_iterator&lt;T*&gt;; using const_reference=const T&amp;; using const_pointer=const T*; using const_iterator=const T*; using const_reverse_iterator=std::reverse_iterator&lt;const T*&gt;; private: value_type * _data; size_type _size; [[no_unique_address]] Alloc allocator; void _cleanup() { // destroy all objects, deallocate all memory, leaves container in a valid empty state if(_data) { for(size_t i=0;i&lt;_size;i++) { _data[i].~value_type(); } allocator.deallocate(_data,_size); _data=nullptr; } _size=0; } template&lt;typename C&gt; void _container_assign(const C &amp;container) { // allocate memory and copy contents from generic container of type C if(container.size()==0) { _size=0; _data=nullptr; } else { _size=container.size(); _data=allocator.allocate(_size); typename C::const_iterator it=container.begin(); for(size_t i=0;i&lt;_size;i++,it++){ new(_data+i) value_type(*it); } } } public: FixedArray() : _data(nullptr), _size(0) { } FixedArray(std::nullptr_t) : _data(nullptr), _size(0) { } FixedArray(std::initializer_list&lt;T&gt; data) requires std::is_copy_constructible_v&lt;value_type&gt; { _container_assign(data); } template&lt;typename U&gt; FixedArray(std::initializer_list&lt;U&gt; data) requires (!std::is_same_v&lt;T,U&gt;) &amp;&amp; requires (U x){ T(x); } { _container_assign(data); } FixedArray(const FixedArray &amp; other) requires std::is_copy_constructible_v&lt;value_type&gt; { _container_assign(other); } FixedArray(FixedArray &amp;&amp; other) : _data(other._data), _size(other._size) { other._data=nullptr; other._size=0; } template&lt;typename C&gt; FixedArray(const C&amp; container) requires Container&lt;C,value_type&gt; &amp;&amp; std::is_copy_constructible_v&lt;value_type&gt; { _container_assign(container); } template&lt;typename C&gt; FixedArray(const C&amp; container) requires Container&lt;C&gt; &amp;&amp; (!std::is_same_v&lt;T,typename C::value_type&gt;) &amp;&amp; requires (typename C::value_type v) { T(v); } { _container_assign(container); } FixedArray(size_t n) requires std::is_default_constructible_v&lt;value_type&gt; : _data(nullptr), _size(n) { if(_size&gt;0){ _data=allocator.allocate(_size); for(size_t i=0;i&lt;_size;i++){ new(_data+i) value_type(); } } } ~FixedArray() { _cleanup(); } // --- optional reassignment methods --- void operator=(std::nullptr_t) requires _reassignable { _cleanup(); } void clear() requires _reassignable { _cleanup(); } FixedArray &amp; operator=(std::initializer_list&lt;T&gt; data) requires _reassignable { _cleanup(); _container_assign(data); return *this; } template&lt;typename U&gt; FixedArray &amp; operator=(std::initializer_list&lt;U&gt; data) requires _reassignable &amp;&amp; requires (U x){ T(x); } { _cleanup(); _container_assign(data); return *this; } FixedArray &amp; operator=(const FixedArray &amp; other) requires _reassignable { _cleanup(); _container_assign(other); return *this; } FixedArray &amp; operator=(FixedArray &amp;&amp; other) requires _reassignable { _cleanup(); _data=other._data; _size=other._size; other._data=nullptr; other._size=0; return *this; } template&lt;typename C&gt; FixedArray &amp; operator=(const C&amp; container) requires _reassignable &amp;&amp; Container&lt;C,value_type&gt; { _cleanup(); _container_assign(container); return *this; } template&lt;typename C&gt; FixedArray &amp; operator=(const C&amp; container) requires _reassignable &amp;&amp; Container&lt;C&gt; &amp;&amp; (!std::is_same_v&lt;T,typename C::value_type&gt;) &amp;&amp; requires (typename C::value_type v) { T(v); } { _cleanup(); _container_assign(container); return *this; } void swap(FixedArray &amp; other) requires _reassignable { value_type * temp_data=_data; size_t temp_size=_size; _data=other._data; _size=other._size; other._data=temp_data; other._size=temp_size; } static void swap(FixedArray &amp; lhs,FixedArray &amp; rhs) requires _reassignable { lhs.swap(rhs); } // --- container boilerplate after this --- template&lt;typename C&gt; bool operator==(const C&amp; container) const { return _size==container.size()&amp;&amp;std::equal(container.begin(),container.end(),begin(),end()); } template&lt;typename C&gt; bool operator!=(const C&amp; container) const { return _size!=container.size()||!std::equal(container.begin(),container.end(),begin(),end()); } size_type size() const noexcept { return _size; } static size_type max_size() noexcept { return (std::numeric_limits&lt;size_type&gt;::max()/sizeof(value_type))-1; } size_type empty() const noexcept { return _size==0; } iterator begin() noexcept { return _data; } iterator end() noexcept { return _data+_size; } const_iterator begin() const noexcept { return _data; } const_iterator end() const noexcept { return _data+_size; } const_iterator cbegin() const noexcept { return _data; } const_iterator cend() const noexcept { return _data+_size; } reverse_iterator rbegin() noexcept { return std::make_reverse_iterator(end()); } reverse_iterator rend() noexcept { return std::make_reverse_iterator(begin()); } const_reverse_iterator rbegin() const noexcept { return std::make_reverse_iterator(end()); } const_reverse_iterator rend() const noexcept { return std::make_reverse_iterator(begin()); } const_reverse_iterator crbegin() const noexcept { return std::make_reverse_iterator(end()); } const_reverse_iterator crend() const noexcept { return std::make_reverse_iterator(begin()); } pointer data() noexcept { return _data; } const_pointer data() const noexcept { return _data; } reference front() noexcept { return _data[0]; } const_reference front() const noexcept { return _data[0]; } reference back() noexcept { return _data[_size-1]; } const_reference back() const noexcept { return _data[_size-1]; } reference operator[](size_t i) noexcept { return _data[i]; } const_reference operator[](size_t i) const noexcept { return _data[i]; } reference at(size_t i) { if(i&gt;=_size) throw std::out_of_range(&quot;Index &quot;+std::to_string(i)+&quot; is out of range for FixedArray of size &quot;+std::to_string(_size)); return _data[i]; } const_reference at(size_t i) const { if(i&gt;=_size) throw std::out_of_range(&quot;Index &quot;+std::to_string(i)+&quot; is out of range for FixedArray of size &quot;+std::to_string(_size)); return _data[i]; } }; } </code></pre> <p>After testing it, it <em>seems</em> to work without any problems, but a second pair of eyes could help find anything i might have overlooked.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T21:23:21.617", "Id": "500852", "Score": "1", "body": "Can you outline any important differences between this and [`std::Array`](https://en.cppreference.com/w/cpp/container/array)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T21:26:18.103", "Id": "500853", "Score": "0", "body": "@Edward you can construct this from any Container-like object (vector/etc), and since it is dynamically allocated, the size doesn't need to be known at compile-time" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T21:35:05.370", "Id": "500855", "Score": "1", "body": "It looks like a lot of work for what is basically a `std::vector` that you just never resize. Why would someone want to use this class over `std::vector`? The latter also allows construction from any other container-like object, given two iterators." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T21:42:29.950", "Id": "500856", "Score": "0", "body": "@G.Sliepen Why is there a need to critize OP doing this project? This website is meant for people to receive constructive criticism on working code, which this is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T21:43:55.477", "Id": "500857", "Score": "0", "body": "@G.Sliepen I've written it more of as a `std::array` than a `std::vector`, it is useful in places where you know that the size won't change (or where it _must_ not change), but at the same time the size isn't known at compile time, it also has slightly less memory overhead due to needing to store less data, but that's negligible (8 bytes on GCC)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T21:59:59.867", "Id": "500858", "Score": "1", "body": "@TomGebel I'm asking this because it is important to understand what the code is intended for. Is it for the OP to excercise building a C++ container? Or is it meant for actual production code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T22:02:51.323", "Id": "500859", "Score": "0", "body": "@G.Sliepen While not meant for 'production' per-se, it is intended to be used, although in a hobby project" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T01:23:32.950", "Id": "500863", "Score": "1", "body": "Nice: The one thing I would note is that arrays/std::vector/std::array etc destroy the objects in reverse order of creation. I would change your clean up to call destructors from `(n --> 0]` to mimik this behavior." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T01:24:49.560", "Id": "500864", "Score": "1", "body": "Some more optimizations that I implemented for vector that may help here: https://lokiastari.com/blog/2016/03/19/vector-simple-optimizations/index.html" } ]
[ { "body": "<h1>Consider not using this class</h1>\n<p>Your class basically reimplements almost all of <code>std::vector</code>, except the functions that resized the container. The only feature I can see that it has over regular <code>std::vector</code> is that you can easily assign another container to it without using a pair of iterators. In this case, I would recommend considering not using this class, but just a regular <code>std::vector</code>, so that you don't have to maintain this code.</p>\n<p>Alternatively, you could perhaps consider deriving your class from <code>std::vector</code>, but delete all the functions that resize. For example:</p>\n<pre><code>template&lt;typename T, typename Alloc = std::allocator&lt;T&gt;&gt;\nclass FixedArray: public std::vector&lt;T, Alloc&gt; {\npublic:\n // Delete functions you don't want:\n void resize(size_t) = delete;\n ...\n\n // Pull in the constructors of the parent class:\n using std::vector&lt;T, Alloc&gt;::vector;\n\n // Add more constructors/functions if needed:\n template&lt;typename C&gt;\n FixedArray(const C&amp; container) : std::vector&lt;T, Alloc&gt;(std::begin(container), std::end(container)) {}\n ...\n};\n</code></pre>\n<p>Inheriting from a container class this way has its own drawbacks, so I wouldn't recommend this either, but I do think this approach will require much less code to be written.</p>\n<p>For the rest of the review I'm assuming you do want to use your own class as it is.</p>\n<h1>Make better use of existing concepts</h1>\n<p>Instead of defining your own <code>concept Container</code>, make use of the concepts from the Ranges library, like <a href=\"https://en.cppreference.com/w/cpp/ranges/range\" rel=\"nofollow noreferrer\"><code>std::ranges::range</code></a>, or even better the more specific ones like <a href=\"https://en.cppreference.com/w/cpp/ranges/input_range\" rel=\"nofollow noreferrer\"><code>std::ranges::input_range</code></a>.</p>\n<p>Also, instead of writing <code>requires (typename C::value_type v) { T(v); }</code>, consider using <a href=\"https://en.cppreference.com/w/cpp/types/is_constructible\" rel=\"nofollow noreferrer\"><code>requires std::is_constructible_v&lt;T, C::value_type&gt;</code></a>.</p>\n<h1>Use concepts directly inside a <code>template</code> parameter list</h1>\n<p>A nice thing about concepts is that you can use them instead of <code>typename</code> in a <code>template</code> parameter list. This avoids some typing, and makes the code a little easier to read. For example, instead of:</p>\n<pre><code>template&lt;typename C&gt;\nFixedArray(const C&amp; container) requires Container&lt;C&gt; &amp;&amp; (!std::is_same_v&lt;T,typename C::value_type&gt;) &amp;&amp; requires (typename C::value_type v) { T(v); }\n{\n _container_assign(container);\n}\n</code></pre>\n<p>You can write:</p>\n<pre><code>template&lt;std::ranges::input_range C&gt;\nFixedArray(const C&amp; container) requires (!std::is_same_v&lt;T,typename C::value_type&gt; &amp;&amp; std::is_constructible_v(T, C::value_type))\n{\n _container_assign(container);\n}\n</code></pre>\n<h1>Use default member value initialization</h1>\n<p>You can avoid some typing by using member value initialization:</p>\n<pre><code>pointer _data{};\nsize_type _size{};\n</code></pre>\n<p>This avoids repeating the default initialization in several of the constructors. In fact, this way the default constructor can really be made <code>default</code>:</p>\n<pre><code>FixedArray() = default;\n</code></pre>\n<h1>Avoid code duplication</h1>\n<p>There are several ways you can reduce the amount of code you have written:</p>\n<h2>Reuse your own functions</h2>\n<p>You can make use of your own member functions and iterators. For example, you can use range-<code>for</code> to loop over the elements of <code>_data</code>:</p>\n<pre><code>void _cleanup() { // destroy all objects, deallocate all memory, leaves container in a valid empty state\n if(_data) {\n for(auto &amp;el: *this) {\n el.~value_type();\n }\n allocator.deallocate(_data, _size);\n _data = nullptr;\n }\n _size = 0;\n}\n</code></pre>\n<p>Also, when moving data from another container, make use of your own <code>swap()</code> function. Combined with the default member initialization, this removes a lot of lines, for example the move constructor becomes:</p>\n<pre><code>FixedArray(FixedArray &amp;&amp; other) {\n swap(other);\n}\n</code></pre>\n<h2>Merge (template) overloads where possible</h2>\n<p>There are several places where you have multiple overloads for dealing with other containers of the same <code>value_type</code> or of another, when they can be merged into one. For example, the constructors taking initializer lists can be merged into this single one:</p>\n<pre><code>template&lt;typename U&gt;\nFixedArray(std::initializer_list&lt;U&gt; data) requires std::is_constructible_v&lt;value_type, U&gt;\n{\n _container_assign(data);\n}\n</code></pre>\n<p>Since this will also handle the case of a <code>std::initializer_list&lt;value_type&gt;</code> just fine. The same goes for the other cases where you used <code>!std::is_same_v&lt;&gt;</code>.</p>\n<h2>Define <code>operator!=</code> in terms of <code>operator==</code></h2>\n<p>It's always best to define one of those operators in terms of the other, so you cannot have a small mistake give subtly different behaviour. So:</p>\n<pre><code>template&lt;std::ranges::input_range C&gt;\nbool operator!=(const C&amp; container) const {\n return !operator==(container);\n}\n</code></pre>\n<h1>Be consistent using <code>std::size()</code>, <code>std::begin()</code> and <code>std::end()</code></h1>\n<p>To ensure your class works with all possible containers, don't use member functions <code>.size()</code>, <code>.begin()</code> and <code>.end()</code> directly, but use the free-standing <code>std::size()</code> and related functions. For example:</p>\n<pre><code>template&lt;std::ranges::input_range C&gt;\nbool operator==(const C&amp; container) const {\n return std::equal(std::begin(container), std::end(container), begin(), end());\n}\n</code></pre>\n<p>Note that you also don't need to use <code>std::size()</code> in this example, <code>std::equal()</code> will already check whether the sizes match.</p>\n<h1>Use your own type aliases consistently</h1>\n<p>If you define an alias, you should use it yourself as well. This ensures that if you need to change a type, you only need to do it on one line. So replace <code>size_t</code> with <code>size_type</code> everywhere, use <code>value_type</code> instead of <code>T</code> in a few places, and so on.</p>\n<h1>Use consistent code formatting</h1>\n<p>Your code does not use consistent formatting, in some places there are spaces around operators, in other places there are none. I recommend using a code formatting tool to do this for you, for example <a href=\"http://astyle.sourceforge.net/\" rel=\"nofollow noreferrer\">Artistic Style</a> or <a href=\"https://clang.llvm.org/docs/ClangFormat.html\" rel=\"nofollow noreferrer\">ClangFormat</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T15:06:32.127", "Id": "500922", "Score": "0", "body": "I'd argue that it's better to use a `std::vector` as a member, or to inherit from it *privately*, than to use public inheritance like that (where one could find it used as the base class, and therefore resized unexpectedly)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T15:41:05.190", "Id": "500929", "Score": "0", "body": "@TobySpeight Indeed, that's one of the issues that inheritance has. But either private inheritance or making it a member value would mean writing a lot of wrapper functions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T16:30:27.863", "Id": "500930", "Score": "0", "body": "I think private inheritance would just need lots of `using` base-class functions rather than wrappers. Still lots of them, of course (but only one for each identifier, not for each override)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T00:31:24.310", "Id": "253980", "ParentId": "253971", "Score": "4" } } ]
{ "AcceptedAnswerId": "253980", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T21:18:47.563", "Id": "253971", "Score": "3", "Tags": [ "c++", "array", "collections", "c++20" ], "Title": "C++20 \"FixedArray\" Container (dynamically allocated fixed-size array)" }
253971
<p>I built a shop system for a Python text RPG I'm making. It repeats itself more than I would like. I was thinking I could use dictionaries to make it better but I'm not sure how. Anyways, how is it?<br /> There are 5 shop levels, each having different things to buy. So based on the shop level I set what you can buy, as well as how much it is.</p> <pre><code>def shop(shopLvl, playerGp, playerInventory): print(&quot;What would you like to buy?\n&quot;) if shopLvl == 1: shopWeapon = &quot;1. Longsword&quot; weaponCost = 20 shopArmor = &quot;2. Leather Armor&quot; armorCost = 30 shopPotion = &quot;3. Potion&quot; potionCost = 5 shopElixer = &quot;4. Elixer&quot; elixerCost = 5 if shopLvl == 2: shopWeapon = &quot;1. Greatsword&quot; weaponCost = 30 shopArmor = &quot;2. Chainmail Armor&quot; armorCost = 45 shopPotion = &quot;3. Potion&quot; potionCost = 5 shopElixer = &quot;4. Elixer&quot; elixerCost = 5 if shopLvl == 3: shopWeapon = &quot;1. Crested Blade&quot; weaponCost = 45 shopArmor = &quot;2. Plate Armor&quot; armorCost = 60 shopPotion = &quot;3. Super Potion&quot; potionCost = 10 shopElixer = &quot;4. Super Elixer&quot; elixerCost = 10 if shopLvl == 4: shopWeapon = &quot;1. Diamond Sword&quot; weaponCost = 75 shopArmor = &quot;2. Diamond Armor&quot; armorCost = 125 shopPotion = &quot;3. Super Potion&quot; potionCost = 10 shopElixer = &quot;4. Super Elixer&quot; elixerCost = 10 if shopLvl == 5: shopWeapon = &quot;1. Enchanted Sword&quot; weaponCost = 150 shopArmor = &quot;2. Angelic Armor&quot; armorCost = 225 shopPotion = &quot;3. Mega Potion&quot; potionCost = 20 shopElixer = &quot;4. Mega Elixer&quot; elixerCost = 20 shopItems = { shopWeapon : weaponCost, shopArmor : armorCost, shopPotion : potionCost, shopElixer : elixerCost } print(shopItems,&quot;\nYour gp:&quot;, playerGp) shopChoice = input(&quot;1/2/3/4&quot;) if shopChoice == '1': if weaponCost &lt; playerGp: print(&quot;You bought a&quot;, shopWeapon, &quot;for&quot;, weaponCost, &quot;gp!\n&quot;) time.sleep(0.8) playerGp = playerGp - weaponCost print(&quot;You now have&quot;, playerGp, &quot;gp left\n&quot;) time.sleep(0.8) playerWeapon = shopWeapon elif weaponCost &gt; playerGp: print(&quot;Not enough gold\n&quot;) else: print(&quot;Error\n&quot;) if shopChoice == '2': if armorCost &lt; playerGp: print(&quot;You bought a&quot;, shopArmor, &quot;for&quot;, armorCost, &quot;gp!\n&quot;) time.sleep(0.8) playerGp = playerGp - armorCost print(&quot;You now have&quot;, playerGp, &quot;gp left\n&quot;) time.sleep(0.8) playerArmor = shopArmor elif armorCost &gt; playerGp: print(&quot;Not enough gold\n&quot;) else: print('Error\n') if shopChoice == '3' : if potionCost &lt; playerGp: print(&quot;You bought a&quot;, shopPotion, &quot;for&quot;, potionCost, &quot;gp!\n&quot;) time.sleep(0.8) playerGp = playerGp - potionCost print(&quot;You now have&quot;, playerGp, &quot;gp left\n&quot;) time.sleep(0.8) if shopPotion == &quot;3. Potion&quot;: playerInventory[&quot;1.Potion&quot;] = playerInventory[&quot;1.Potion&quot;] + 1 if shopPotion == &quot;3. Super Potion&quot;: playerInventory[&quot;3.Super Potion&quot;] = playerInventory[&quot;3.Super potion&quot;] + 1 if shopPotion == &quot;3. Mega Potion&quot;: playerInventory[&quot;3.Mega Potion&quot;] = playerInventory[&quot;3.Mega Potion&quot;] + 1 elif potionCost &lt; playerGp: print(&quot;Not enough gold\n&quot;) if shopChoice == '4' : if elixerCost &lt; playerGp: print(&quot;You bought a&quot;, shopElixer, &quot;for&quot;, elixerCost, &quot;gp!\n&quot;) time.sleep(0.8) playerGp = playerGp - elixerCost print(&quot;You now have&quot;, playerGp, &quot;gp left\n&quot;) time.sleep(0.8) if shopElixer == &quot;4. Elixer&quot;: playerInventory[&quot;2.Elixer&quot;] = playerInventory[&quot;2.Elixer&quot;] + 1 if shopElixer == &quot;3. Super Elixer&quot;: playerInventory[&quot;4.Super Elixer&quot;] = playerInventory[&quot;4.Super Elixer&quot;] + 1 if shopElixer == &quot;3. Mega Elixer&quot;: playerInventory[&quot;6.Mega Elixer&quot;] = playerInventory[&quot;6.Mega Elixer&quot;] + 1 elif elixerCost &lt; playerGp: print(&quot;Not enough gold!\n&quot;) <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T15:15:28.137", "Id": "500923", "Score": "1", "body": "Micro review - I think you've misspelt \"Elixir\" throughout." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T20:00:49.793", "Id": "500951", "Score": "0", "body": "Be aware that your ```if shopChoice == '1'```, ```if shopChoice == '2'```, etc. if-blocks aren't exclusive as written; if somehow in the body of one of those blocks you accidentally modify the value of ```shopChoice```, or if you modify any of your conditions to make them more complex and add a bug, you could wind up having more than one of those blocks executed, which I'm guessing isn't what you want, and which could be a confusing bug to encounter. I think instead you want those to be an ```if-elif-else``` chain. That way it is guaranteed to only ever execute one block." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T20:02:48.840", "Id": "500952", "Score": "0", "body": "The same goes anywhere else that pattern is used in your code." } ]
[ { "body": "<p>Lets consider the design here:</p>\n<p>The item type (weapon / armor / potion) is not relevant to the shop functionality.<br />\nAll we really care about is item name, cost, and level.</p>\n<p>You can use a <a href=\"https://docs.python.org/3/library/collections.html#collections.namedtuple\" rel=\"noreferrer\"><code>namedtuple</code></a> to easily create an &quot;item&quot; data class.</p>\n<p>So, start by creating a list of all the items, like this:</p>\n<pre><code>from collections import namedtuple\n\nItem = namedtuple('Item', ['name', 'cost', 'levels'])\n\ngameItems = [ Item('Longsword', 20, [1]),\n Item('Greatsword', 30, [2]),\n Item('Potion', 5, [1, 2]),\n ...\n Item('Mega Elixer', 20, [5])]\n</code></pre>\n<p>Notice, that <code>levels</code> is a list, to allow the same item to appear in multiple store levels without creating it twice.</p>\n<p>Now we can prepare the shop using a simple list comprehension filtering items by player level:</p>\n<pre><code>def get_shop_items(playerLevel):\n return [ item for item in gameItems if playerLevel in item.levels ]\n</code></pre>\n<p>You will have to do a bit more work to print available items, but not much:</p>\n<pre><code>def print_shop_items(shopItems):\n for index, item in enumerate(shopItems, 1):\n print(f'{index}. {item.name}: {item.cost} gp')\n</code></pre>\n<p>From here, you should be able to see how you can also eliminate the <code>if</code> statements for player choice, and simply pick the item from the list by index.</p>\n<p>Then, make the player inventory a dictionary where item name is the key, and item count is the value.</p>\n<p>A successful purchase would look something like this:</p>\n<pre><code>playerInventory['gp'] -= item.cost\nplayerInventory[item.name] += 1\n</code></pre>\n<p>This way, you can even store player currency in the inventory, instead of having a separate variable.</p>\n<p>You may want to use <a href=\"https://docs.python.org/3/library/collections.html#collections.Counter\" rel=\"noreferrer\"><code>Counter</code></a> for this instead of a regular dictionary to avoid having extra code to handle items not yet in player inventory.</p>\n<p>If you do care about item type at some point, like in a 'use' function, you can simply add a field called 'type' to the <code>Item</code> tuple, and check it in the parts of the code you care about.</p>\n<p>You can also add a 'limit' field, if you want the player to be able to only carry certain amount of certain item, say only one sword, or up to 10 potions.</p>\n<p>You can then check this field before adding item to the inventory and print an appropriate message if there is no room.</p>\n<p><strong>EDIT:</strong> I incorporated some important comments in to the answer, but I am keeping the naming convention to align with OP's code.</p>\n<p>My thanks to everyone who helped improve this answer!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T06:42:18.030", "Id": "500874", "Score": "2", "body": "on of the notable things in python is PEP-8 for naming conventions, preferring `snake_case` over `camelCase` variables." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T08:46:17.270", "Id": "500880", "Score": "1", "body": "To add to the above comment, `namedtuple` is a class factory - a function that creates and returns a class. What you get back is a class, so should be named in CamelCase like any other class" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T12:56:31.647", "Id": "500905", "Score": "2", "body": "`namedtuple` already existed in Python 2. And `enumerate` takes an optional second argument, which is the start value, so you don't need to do `index + 1` if you use `enumerate(items, 1)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T13:20:11.863", "Id": "500910", "Score": "1", "body": "A set may be semantically more appropriate than a list for the levels (the added performance is a side benefit)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T23:38:36.427", "Id": "253977", "ParentId": "253973", "Score": "23" } }, { "body": "<h1>Bug</h1>\n<p>If a player has 100 gold, and an item costs 100 gold, you generate an <code>Error</code>!</p>\n<pre><code> if weaponCost &lt; playerGp:\n print(&quot;You bought a&quot;, shopWeapon, &quot;for&quot;, weaponCost, &quot;gp!\\n&quot;)\n ...\n elif weaponCost &gt; playerGp:\n print(&quot;Not enough gold\\n&quot;)\n else: print(&quot;Error\\n&quot;)\n</code></pre>\n<p>While spending every last one of the coins in your pocket may be ill-advised, the player should be allowed to do so!</p>\n<p>You don't need an <code>if ... elif ... else</code> construct. If the player has sufficient gold, allow the purchase. If they don't, say not enough gold. There is no third case to worry about.</p>\n<pre><code> if playerGp &gt;= weaponCost:\n print(&quot;You bought a&quot;, shopWeapon, &quot;for&quot;, weaponCost, &quot;gp!\\n&quot;)\n ... \n else:\n print(&quot;Not enough gold\\n&quot;)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T06:58:05.230", "Id": "253988", "ParentId": "253973", "Score": "12" } }, { "body": "<p>This function is quite complicated. You should consider writing tests for it. For example:</p>\n<p>If the code you gave is in a file named <code>shop.py</code>. Put the below code in a file called <code>test_shop.py</code>:</p>\n<pre><code>from shop import shop\nfrom unittest import TestCase\nfrom mock import patch\n\n\nclass TestBuyingThings(TestCase):\n @patch('shop.input', return_value='3')\n def test_buy_a_potion_when_inventory_empty_and_just_enough_gold(self, *args):\n playerInventory = {}\n playerGp = 20\n shop(1, playerGp, playerInventory)\n self.assertEqual(playerInventory, {'1.Potion': 1})\n\n @patch('shop.input', return_value='3')\n def test_buy_a_potion_when_not_enough_gold(self, *args):\n playerInventory = {}\n playerGp = 0\n with patch('shop.print') as mocked_print:\n shop(1, playerGp, playerInventory)\n mocked_print.assert_any_call(&quot;Not enough gold!\\n&quot;)\n self.assertEqual(playerInventory, {'1.Potion': 1})\n</code></pre>\n<p>make sure you have mock installed <code>pip install mock</code>, then run the tests with\n<code>python -m unittest test_shop</code>. When I run the tests I get this output:</p>\n<pre><code>[staging] ~/game $ python -m unittest test_shop\nWhat would you like to buy?\n\n{'1. Longsword': 20, '2. Leather Armor': 30, '3. Potion': 5, '4. Elixer': 5}\nYour gp: 20\nYou bought a 3. Potion for 5 gp!\n\nYou now have 15 gp left\n\nEF\n======================================================================\nERROR: test_buy_a_potion_when_inventory_empty_and_just_enough_gold (test_shop.TestBuyingThings)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File &quot;/usr/local/lib/python3.8/site-packages/mock/mock.py&quot;, line 1346, in patched\n return func(*newargs, **newkeywargs)\n File &quot;/Users/lukebryant/game/test_shop.py&quot;, line 11, in test_buy_a_potion_when_inventory_empty_and_just_enough_gold\n shop(1, playerGp, playerInventory)\n File &quot;/Users/lukebryant/game/shop.py&quot;, line 96, in shop\n playerInventory[&quot;1.Potion&quot;] = playerInventory[&quot;1.Potion&quot;] + 1\nKeyError: '1.Potion'\n\n======================================================================\nFAIL: test_buy_a_potion_when_not_enough_gold (test_shop.TestBuyingThings)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File &quot;/usr/local/lib/python3.8/site-packages/mock/mock.py&quot;, line 1346, in patched\n return func(*newargs, **newkeywargs)\n File &quot;/Users/lukebryant/game/test_shop.py&quot;, line 20, in test_buy_a_potion_when_not_enough_gold\n mocked_print.assert_any_call(&quot;Not enough gold!\\n&quot;)\n File &quot;/usr/local/lib/python3.8/site-packages/mock/mock.py&quot;, line 985, in assert_any_call\n raise AssertionError(\nAssertionError: print('Not enough gold!\\n') call not found\n\n----------------------------------------------------------------------\nRan 2 tests in 1.606s\n</code></pre>\n<p>Both tests fail! Can you see why?</p>\n<p>Testing like this is a very good habit to get into. Once you have a suite of tests like this you can code freely with the knowledge that if you break any existing functionality, your tests will tell you. It's worth doing purely for the sake of your own sanity, but if you wanted to apply for a job in the industry, then a tested project would also look great in your portfolio.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T13:01:53.133", "Id": "254036", "ParentId": "253973", "Score": "4" } }, { "body": "<p>This answer is meant to be for beginners from a beginner. I try to incorporate best practices as explained by Lev M. while not changing the original structure of the code too much. I guess the most important take away is to follow the <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY principle</a> as much as possible.</p>\n<p>I changed the structure of the shop items to lists for easier access. The shop level then is simply an item's position in the list. The main motivation is to have a single piece of code to handle the transaction later on instead of repeating the code for each <code>shopChoice</code>. To keep with the initial system of shop level from 1 upwards I simply use <code>shopLvl-1</code> later on.</p>\n<pre><code>def shop(shopLvl, playerGp, playerInventory):\n print(&quot;What would you like to buy?\\n&quot;)\n shopWeapon = [[&quot;1. Longsword&quot;, 20],\n [&quot;1. Greatsword&quot;, 30],\n [&quot;1. Crested Blade&quot;, 45],\n [&quot;1. Diamond Sword&quot;, 75],\n [&quot;1. Enchanted Sword&quot;, 150]]\n shopArmor = [[&quot;2. Leather Armor&quot;, 30],\n [&quot;2. Chainmail Armor&quot;, 45],\n [&quot;2. Plate Armor&quot;, 60],\n [&quot;2. Diamond Armor&quot;, 125],\n [&quot;2. Angelic Armor&quot;, 225]]\n shopPotion = [[&quot;3. Potion&quot;, 5],\n [&quot;3. Potion&quot;, 5],\n [&quot;3. Super Potion&quot;, 10],\n [&quot;3. Super Potion&quot;, 10],\n [&quot;3. Mega Potion&quot;, 20]]\n shopElixer = [[&quot;4. Elixer&quot;, 5],\n [&quot;4. Elixer&quot;, 5],\n [&quot;4. Super Elixer&quot;, 10],\n [&quot;4. Super Elixer&quot;, 10],\n [&quot;4. Mega Elixer&quot;, 20]]\n</code></pre>\n<p>I keep the the <code>shopItems</code> object but turn it into a list as well. This allows for the extraction of item name and cost independent of which type of item it is. I turn <code>shopChoice</code> into an integer for easier use. Illegal inputs would need to be handled here.</p>\n<pre><code> shopItems = [\n shopWeapon[shopLvl-1],\n shopArmor[shopLvl-1],\n shopPotion[shopLvl-1],\n shopElixer[shopLvl-1]\n ]\n\n print(shopItems, &quot;\\nYour gp:&quot;, playerGp)\n shopChoice = int(input(&quot;1/2/3/4&quot;)) # TODO handle illegal inputs\n\n item, cost = shopItems[shopChoice-1]\n</code></pre>\n<p>I replace all the <code>shopWeapon, etc</code> variables and their costs with <code>item</code> and <code>cost</code>.</p>\n<pre><code> if cost &lt;= playerGp:\n print(&quot;You bought a&quot;, item, &quot;for&quot;, cost, &quot;gp!\\n&quot;)\n time.sleep(0.8)\n playerGp -= cost\n print(&quot;You now have&quot;, playerGp, &quot;gp left\\n&quot;)\n time.sleep(0.8)\n</code></pre>\n<p>Here I keep with your initial design of <code>playerWeapon</code> and <code>playerArmor</code> variables but implement a dictionary update or create logic for potions and elixirs.</p>\n<pre><code> if shopChoice == 1:\n playerWeapon = item\n elif shopChoice == 2:\n playerArmor = item\n elif shopChoice in [3, 4]:\n if item not in playerInventory:\n playerInventory[item] = 1\n else:\n playerInventory[item] += 1\n print(playerInventory)\n\n else:\n print(&quot;Not enough gold\\n&quot;)\n</code></pre>\n<p>I also implemented AJNeufeld's bug fix regarding zero gold after purchase.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-04T23:10:13.140", "Id": "254330", "ParentId": "253973", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T22:16:30.293", "Id": "253973", "Score": "12", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Shop system for an RPG in Python" }
253973
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/253793/231235">Nested std::deque and std::vector Type Test Cases for recursive_transform Template Function in C++</a>, <a href="https://codereview.stackexchange.com/q/253556/231235">A recursive_transform Template Function Implementation with <code>std::invocable</code> concept in C++</a>, <a href="https://codereview.stackexchange.com/q/251823/231235">A recursive_transform Template Function with Execution Policy</a> and <a href="https://codereview.stackexchange.com/q/253665/231235">A recursive_transform Template Function Implementation with std::invocable Concept and Execution Policy in C++</a>. Thanks to <a href="https://codereview.stackexchange.com/a/253916/231235">indi's detailed and clear answer</a> and <a href="https://codereview.stackexchange.com/a/253910/231235">G. Sliepen's answer</a>. Considering the process of the return type determination in <code>recursive_transform()</code> function is complicated and indi mentioned <em>You don’t need to use just <code>int</code>s and <code>double</code>s. In fact you could replace any of those with basically any other type. It might even be smart to mix it up, and throw in some char, some custom types, or whatever.</em> I am trying to perform the part of various type test cases for <code>recursive_transform()</code> as below.</p> <p><strong>The experimental implementation</strong></p> <ul> <li><p>The part of non-range return type test</p> <p>The tested types here include <code>char</code>, <code>int</code>, <code>float</code>, <code>double</code> and <code>long double</code>, <code>std::string</code>, <code>std::complex&lt;char&gt;</code>, <code>std::complex&lt;int&gt;</code>, <code>std::complex&lt;float&gt;</code>, <code>std::complex&lt;double&gt;</code> and <code>std::complex&lt;long double&gt;</code>.</p> <pre><code>template &lt;typename Container, typename Function, typename Expected&gt; using return_type_test_type = std::tuple&lt; Container, Function, Expected, decltype(recursive_transform(std::execution::par, std::declval&lt;Container&gt;(), std::declval&lt;Function&gt;())) &gt;; using return_type_test_types = std::tuple&lt; // Container Function Result // Non-range. return_type_test_type&lt;char, char (*)(char), char&gt;, return_type_test_type&lt;char, char (*)(char const&amp;), char&gt;, return_type_test_type&lt;char const, char (*)(char const&amp;), char&gt;, return_type_test_type&lt;char&amp;, char (*)(char const&amp;), char&gt;, return_type_test_type&lt;char const&amp;, char (*)(char const&amp;), char&gt;, return_type_test_type&lt;char&amp;&amp;, char (*)(char const&amp;), char&gt;, return_type_test_type&lt;int, char (*)(int), char&gt;, return_type_test_type&lt;int, char (*)(int const&amp;), char&gt;, return_type_test_type&lt;int const, char (*)(int const&amp;), char&gt;, return_type_test_type&lt;int&amp;, char (*)(int const&amp;), char&gt;, return_type_test_type&lt;int const&amp;, char (*)(int const&amp;), char&gt;, return_type_test_type&lt;int&amp;&amp;, char (*)(int const&amp;), char&gt;, return_type_test_type&lt;float, char (*)(float), char&gt;, return_type_test_type&lt;float, char (*)(float const&amp;), char&gt;, return_type_test_type&lt;float const, char (*)(float const&amp;), char&gt;, return_type_test_type&lt;float&amp;, char (*)(float const&amp;), char&gt;, return_type_test_type&lt;float const&amp;, char (*)(float const&amp;), char&gt;, return_type_test_type&lt;float&amp;&amp;, char (*)(float const&amp;), char&gt;, return_type_test_type&lt;double, char (*)(double), char&gt;, return_type_test_type&lt;double, char (*)(double const&amp;), char&gt;, return_type_test_type&lt;double const, char (*)(double const&amp;), char&gt;, return_type_test_type&lt;double&amp;, char (*)(double const&amp;), char&gt;, return_type_test_type&lt;double const&amp;, char (*)(double const&amp;), char&gt;, return_type_test_type&lt;double&amp;&amp;, char (*)(double const&amp;), char&gt;, return_type_test_type&lt;long double, char (*)(long double), char&gt;, return_type_test_type&lt;long double, char (*)(long double const&amp;), char&gt;, return_type_test_type&lt;long double const, char (*)(long double const&amp;), char&gt;, return_type_test_type&lt;long double&amp;, char (*)(long double const&amp;), char&gt;, return_type_test_type&lt;long double const&amp;, char (*)(long double const&amp;), char&gt;, return_type_test_type&lt;long double&amp;&amp;, char (*)(long double const&amp;), char&gt;, return_type_test_type&lt;std::string, char (*)(std::string), char&gt;, return_type_test_type&lt;std::string, char (*)(std::string const&amp;), char&gt;, return_type_test_type&lt;std::string const, char (*)(std::string const&amp;), char&gt;, return_type_test_type&lt;std::string&amp;, char (*)(std::string const&amp;), char&gt;, return_type_test_type&lt;std::string const&amp;, char (*)(std::string const&amp;), char&gt;, return_type_test_type&lt;std::string&amp;&amp;, char (*)(std::string const&amp;), char&gt;, return_type_test_type&lt;std::complex&lt;char&gt;, char (*)(std::complex&lt;char&gt;), char&gt;, return_type_test_type&lt;std::complex&lt;char&gt;, char (*)(std::complex&lt;char&gt; const&amp;), char&gt;, return_type_test_type&lt;std::complex&lt;char&gt; const, char (*)(std::complex&lt;char&gt; const&amp;), char&gt;, return_type_test_type&lt;std::complex&lt;char&gt;&amp;, char (*)(std::complex&lt;char&gt; const&amp;), char&gt;, return_type_test_type&lt;std::complex&lt;char&gt; const&amp;, char (*)(std::complex&lt;char&gt; const&amp;), char&gt;, return_type_test_type&lt;std::complex&lt;char&gt;&amp;&amp;, char (*)(std::complex&lt;char&gt; const&amp;), char&gt;, return_type_test_type&lt;std::complex&lt;int&gt;, char (*)(std::complex&lt;int&gt;), char&gt;, return_type_test_type&lt;std::complex&lt;int&gt;, char (*)(std::complex&lt;int&gt; const&amp;), char&gt;, return_type_test_type&lt;std::complex&lt;int&gt; const, char (*)(std::complex&lt;int&gt; const&amp;), char&gt;, return_type_test_type&lt;std::complex&lt;int&gt;&amp;, char (*)(std::complex&lt;int&gt; const&amp;), char&gt;, return_type_test_type&lt;std::complex&lt;int&gt; const&amp;, char (*)(std::complex&lt;int&gt; const&amp;), char&gt;, return_type_test_type&lt;std::complex&lt;int&gt;&amp;&amp;, char (*)(std::complex&lt;int&gt; const&amp;), char&gt;, return_type_test_type&lt;std::complex&lt;float&gt;, char (*)(std::complex&lt;float&gt;), char&gt;, return_type_test_type&lt;std::complex&lt;float&gt;, char (*)(std::complex&lt;float&gt; const&amp;), char&gt;, return_type_test_type&lt;std::complex&lt;float&gt; const, char (*)(std::complex&lt;float&gt; const&amp;), char&gt;, return_type_test_type&lt;std::complex&lt;float&gt;&amp;, char (*)(std::complex&lt;float&gt; const&amp;), char&gt;, return_type_test_type&lt;std::complex&lt;float&gt; const&amp;, char (*)(std::complex&lt;float&gt; const&amp;), char&gt;, return_type_test_type&lt;std::complex&lt;float&gt;&amp;&amp;, char (*)(std::complex&lt;float&gt; const&amp;), char&gt;, return_type_test_type&lt;std::complex&lt;double&gt;, char (*)(std::complex&lt;double&gt;), char&gt;, return_type_test_type&lt;std::complex&lt;double&gt;, char (*)(std::complex&lt;double&gt; const&amp;), char&gt;, return_type_test_type&lt;std::complex&lt;double&gt; const, char (*)(std::complex&lt;double&gt; const&amp;), char&gt;, return_type_test_type&lt;std::complex&lt;double&gt;&amp;, char (*)(std::complex&lt;double&gt; const&amp;), char&gt;, return_type_test_type&lt;std::complex&lt;double&gt; const&amp;, char (*)(std::complex&lt;double&gt; const&amp;), char&gt;, return_type_test_type&lt;std::complex&lt;double&gt;&amp;&amp;, char (*)(std::complex&lt;double&gt; const&amp;), char&gt;, return_type_test_type&lt;std::complex&lt;long double&gt;, char (*)(std::complex&lt;long double&gt;), char&gt;, return_type_test_type&lt;std::complex&lt;long double&gt;, char (*)(std::complex&lt;long double&gt; const&amp;), char&gt;, return_type_test_type&lt;std::complex&lt;long double&gt; const, char (*)(std::complex&lt;long double&gt; const&amp;), char&gt;, return_type_test_type&lt;std::complex&lt;long double&gt;&amp;, char (*)(std::complex&lt;long double&gt; const&amp;), char&gt;, return_type_test_type&lt;std::complex&lt;long double&gt; const&amp;, char (*)(std::complex&lt;long double&gt; const&amp;), char&gt;, return_type_test_type&lt;std::complex&lt;long double&gt;&amp;&amp;, char (*)(std::complex&lt;long double&gt; const&amp;), char&gt;, return_type_test_type&lt;char, int (*)(char), int&gt;, return_type_test_type&lt;char, int (*)(char const&amp;), int&gt;, return_type_test_type&lt;char const, int (*)(char const&amp;), int&gt;, return_type_test_type&lt;char&amp;, int (*)(char const&amp;), int&gt;, return_type_test_type&lt;char const&amp;, int (*)(char const&amp;), int&gt;, return_type_test_type&lt;char&amp;&amp;, int (*)(char const&amp;), int&gt;, return_type_test_type&lt;int, int (*)(int), int&gt;, return_type_test_type&lt;int, int (*)(int const&amp;), int&gt;, return_type_test_type&lt;int const, int (*)(int const&amp;), int&gt;, return_type_test_type&lt;int&amp;, int (*)(int const&amp;), int&gt;, return_type_test_type&lt;int const&amp;, int (*)(int const&amp;), int&gt;, return_type_test_type&lt;int&amp;&amp;, int (*)(int const&amp;), int&gt;, return_type_test_type&lt;float, int (*)(float), int&gt;, return_type_test_type&lt;float, int (*)(float const&amp;), int&gt;, return_type_test_type&lt;float const, int (*)(float const&amp;), int&gt;, return_type_test_type&lt;float&amp;, int (*)(float const&amp;), int&gt;, return_type_test_type&lt;float const&amp;, int (*)(float const&amp;), int&gt;, return_type_test_type&lt;float&amp;&amp;, int (*)(float const&amp;), int&gt;, return_type_test_type&lt;double, int (*)(double), int&gt;, return_type_test_type&lt;double, int (*)(double const&amp;), int&gt;, return_type_test_type&lt;double const, int (*)(double const&amp;), int&gt;, return_type_test_type&lt;double&amp;, int (*)(double const&amp;), int&gt;, return_type_test_type&lt;double const&amp;, int (*)(double const&amp;), int&gt;, return_type_test_type&lt;double&amp;&amp;, int (*)(double const&amp;), int&gt;, return_type_test_type&lt;long double, int (*)(long double), int&gt;, return_type_test_type&lt;long double, int (*)(long double const&amp;), int&gt;, return_type_test_type&lt;long double const, int (*)(long double const&amp;), int&gt;, return_type_test_type&lt;long double&amp;, int (*)(long double const&amp;), int&gt;, return_type_test_type&lt;long double const&amp;, int (*)(long double const&amp;), int&gt;, return_type_test_type&lt;long double&amp;&amp;, int (*)(long double const&amp;), int&gt;, return_type_test_type&lt;std::string, int (*)(std::string), int&gt;, return_type_test_type&lt;std::string, int (*)(std::string const&amp;), int&gt;, return_type_test_type&lt;std::string const, int (*)(std::string const&amp;), int&gt;, return_type_test_type&lt;std::string&amp;, int (*)(std::string const&amp;), int&gt;, return_type_test_type&lt;std::string const&amp;, int (*)(std::string const&amp;), int&gt;, return_type_test_type&lt;std::string&amp;&amp;, int (*)(std::string const&amp;), int&gt;, return_type_test_type&lt;std::complex&lt;char&gt;, int (*)(std::complex&lt;char&gt;), int&gt;, return_type_test_type&lt;std::complex&lt;char&gt;, int (*)(std::complex&lt;char&gt; const&amp;), int&gt;, return_type_test_type&lt;std::complex&lt;char&gt; const, int (*)(std::complex&lt;char&gt; const&amp;), int&gt;, return_type_test_type&lt;std::complex&lt;char&gt;&amp;, int (*)(std::complex&lt;char&gt; const&amp;), int&gt;, return_type_test_type&lt;std::complex&lt;char&gt; const&amp;, int (*)(std::complex&lt;char&gt; const&amp;), int&gt;, return_type_test_type&lt;std::complex&lt;char&gt;&amp;&amp;, int (*)(std::complex&lt;char&gt; const&amp;), int&gt;, return_type_test_type&lt;std::complex&lt;int&gt;, int (*)(std::complex&lt;int&gt;), int&gt;, return_type_test_type&lt;std::complex&lt;int&gt;, int (*)(std::complex&lt;int&gt; const&amp;), int&gt;, return_type_test_type&lt;std::complex&lt;int&gt; const, int (*)(std::complex&lt;int&gt; const&amp;), int&gt;, return_type_test_type&lt;std::complex&lt;int&gt;&amp;, int (*)(std::complex&lt;int&gt; const&amp;), int&gt;, return_type_test_type&lt;std::complex&lt;int&gt; const&amp;, int (*)(std::complex&lt;int&gt; const&amp;), int&gt;, return_type_test_type&lt;std::complex&lt;int&gt;&amp;&amp;, int (*)(std::complex&lt;int&gt; const&amp;), int&gt;, return_type_test_type&lt;std::complex&lt;float&gt;, int (*)(std::complex&lt;float&gt;), int&gt;, return_type_test_type&lt;std::complex&lt;float&gt;, int (*)(std::complex&lt;float&gt; const&amp;), int&gt;, return_type_test_type&lt;std::complex&lt;float&gt; const, int (*)(std::complex&lt;float&gt; const&amp;), int&gt;, return_type_test_type&lt;std::complex&lt;float&gt;&amp;, int (*)(std::complex&lt;float&gt; const&amp;), int&gt;, return_type_test_type&lt;std::complex&lt;float&gt; const&amp;, int (*)(std::complex&lt;float&gt; const&amp;), int&gt;, return_type_test_type&lt;std::complex&lt;float&gt;&amp;&amp;, int (*)(std::complex&lt;float&gt; const&amp;), int&gt;, return_type_test_type&lt;std::complex&lt;double&gt;, int (*)(std::complex&lt;double&gt;), int&gt;, return_type_test_type&lt;std::complex&lt;double&gt;, int (*)(std::complex&lt;double&gt; const&amp;), int&gt;, return_type_test_type&lt;std::complex&lt;double&gt; const, int (*)(std::complex&lt;double&gt; const&amp;), int&gt;, return_type_test_type&lt;std::complex&lt;double&gt;&amp;, int (*)(std::complex&lt;double&gt; const&amp;), int&gt;, return_type_test_type&lt;std::complex&lt;double&gt; const&amp;, int (*)(std::complex&lt;double&gt; const&amp;), int&gt;, return_type_test_type&lt;std::complex&lt;double&gt;&amp;&amp;, int (*)(std::complex&lt;double&gt; const&amp;), int&gt;, return_type_test_type&lt;std::complex&lt;long double&gt;, int (*)(std::complex&lt;long double&gt;), int&gt;, return_type_test_type&lt;std::complex&lt;long double&gt;, int (*)(std::complex&lt;long double&gt; const&amp;), int&gt;, return_type_test_type&lt;std::complex&lt;long double&gt; const, int (*)(std::complex&lt;long double&gt; const&amp;), int&gt;, return_type_test_type&lt;std::complex&lt;long double&gt;&amp;, int (*)(std::complex&lt;long double&gt; const&amp;), int&gt;, return_type_test_type&lt;std::complex&lt;long double&gt; const&amp;, int (*)(std::complex&lt;long double&gt; const&amp;), int&gt;, return_type_test_type&lt;std::complex&lt;long double&gt;&amp;&amp;, int (*)(std::complex&lt;long double&gt; const&amp;), int&gt;, return_type_test_type&lt;char, float (*)(char), float&gt;, return_type_test_type&lt;char, float (*)(char const&amp;), float&gt;, return_type_test_type&lt;char const, float (*)(char const&amp;), float&gt;, return_type_test_type&lt;char&amp;, float (*)(char const&amp;), float&gt;, return_type_test_type&lt;char const&amp;, float (*)(char const&amp;), float&gt;, return_type_test_type&lt;char&amp;&amp;, float (*)(char const&amp;), float&gt;, return_type_test_type&lt;int, float (*)(int), float&gt;, return_type_test_type&lt;int, float (*)(int const&amp;), float&gt;, return_type_test_type&lt;int const, float (*)(int const&amp;), float&gt;, return_type_test_type&lt;int&amp;, float (*)(int const&amp;), float&gt;, return_type_test_type&lt;int const&amp;, float (*)(int const&amp;), float&gt;, return_type_test_type&lt;int&amp;&amp;, float (*)(int const&amp;), float&gt;, return_type_test_type&lt;float, float (*)(float), float&gt;, return_type_test_type&lt;float, float (*)(float const&amp;), float&gt;, return_type_test_type&lt;float const, float (*)(float const&amp;), float&gt;, return_type_test_type&lt;float&amp;, float (*)(float const&amp;), float&gt;, return_type_test_type&lt;float const&amp;, float (*)(float const&amp;), float&gt;, return_type_test_type&lt;float&amp;&amp;, float (*)(float const&amp;), float&gt;, return_type_test_type&lt;double, float (*)(double), float&gt;, return_type_test_type&lt;double, float (*)(double const&amp;), float&gt;, return_type_test_type&lt;double const, float (*)(double const&amp;), float&gt;, return_type_test_type&lt;double&amp;, float (*)(double const&amp;), float&gt;, return_type_test_type&lt;double const&amp;, float (*)(double const&amp;), float&gt;, return_type_test_type&lt;double&amp;&amp;, float (*)(double const&amp;), float&gt;, return_type_test_type&lt;long double, float (*)(long double), float&gt;, return_type_test_type&lt;long double, float (*)(long double const&amp;), float&gt;, return_type_test_type&lt;long double const, float (*)(long double const&amp;), float&gt;, return_type_test_type&lt;long double&amp;, float (*)(long double const&amp;), float&gt;, return_type_test_type&lt;long double const&amp;, float (*)(long double const&amp;), float&gt;, return_type_test_type&lt;long double&amp;&amp;, float (*)(long double const&amp;), float&gt;, return_type_test_type&lt;std::string, float (*)(std::string), float&gt;, return_type_test_type&lt;std::string, float (*)(std::string const&amp;), float&gt;, return_type_test_type&lt;std::string const, float (*)(std::string const&amp;), float&gt;, return_type_test_type&lt;std::string&amp;, float (*)(std::string const&amp;), float&gt;, return_type_test_type&lt;std::string const&amp;, float (*)(std::string const&amp;), float&gt;, return_type_test_type&lt;std::string&amp;&amp;, float (*)(std::string const&amp;), float&gt;, return_type_test_type&lt;std::complex&lt;char&gt;, float (*)(std::complex&lt;char&gt;), float&gt;, return_type_test_type&lt;std::complex&lt;char&gt;, float (*)(std::complex&lt;char&gt; const&amp;), float&gt;, return_type_test_type&lt;std::complex&lt;char&gt; const, float (*)(std::complex&lt;char&gt; const&amp;), float&gt;, return_type_test_type&lt;std::complex&lt;char&gt;&amp;, float (*)(std::complex&lt;char&gt; const&amp;), float&gt;, return_type_test_type&lt;std::complex&lt;char&gt; const&amp;, float (*)(std::complex&lt;char&gt; const&amp;), float&gt;, return_type_test_type&lt;std::complex&lt;char&gt;&amp;&amp;, float (*)(std::complex&lt;char&gt; const&amp;), float&gt;, return_type_test_type&lt;std::complex&lt;int&gt;, float (*)(std::complex&lt;int&gt;), float&gt;, return_type_test_type&lt;std::complex&lt;int&gt;, float (*)(std::complex&lt;int&gt; const&amp;), float&gt;, return_type_test_type&lt;std::complex&lt;int&gt; const, float (*)(std::complex&lt;int&gt; const&amp;), float&gt;, return_type_test_type&lt;std::complex&lt;int&gt;&amp;, float (*)(std::complex&lt;int&gt; const&amp;), float&gt;, return_type_test_type&lt;std::complex&lt;int&gt; const&amp;, float (*)(std::complex&lt;int&gt; const&amp;), float&gt;, return_type_test_type&lt;std::complex&lt;int&gt;&amp;&amp;, float (*)(std::complex&lt;int&gt; const&amp;), float&gt;, return_type_test_type&lt;std::complex&lt;float&gt;, float (*)(std::complex&lt;float&gt;), float&gt;, return_type_test_type&lt;std::complex&lt;float&gt;, float (*)(std::complex&lt;float&gt; const&amp;), float&gt;, return_type_test_type&lt;std::complex&lt;float&gt; const, float (*)(std::complex&lt;float&gt; const&amp;), float&gt;, return_type_test_type&lt;std::complex&lt;float&gt;&amp;, float (*)(std::complex&lt;float&gt; const&amp;), float&gt;, return_type_test_type&lt;std::complex&lt;float&gt; const&amp;, float (*)(std::complex&lt;float&gt; const&amp;), float&gt;, return_type_test_type&lt;std::complex&lt;float&gt;&amp;&amp;, float (*)(std::complex&lt;float&gt; const&amp;), float&gt;, return_type_test_type&lt;std::complex&lt;double&gt;, float (*)(std::complex&lt;double&gt;), float&gt;, return_type_test_type&lt;std::complex&lt;double&gt;, float (*)(std::complex&lt;double&gt; const&amp;), float&gt;, return_type_test_type&lt;std::complex&lt;double&gt; const, float (*)(std::complex&lt;double&gt; const&amp;), float&gt;, return_type_test_type&lt;std::complex&lt;double&gt;&amp;, float (*)(std::complex&lt;double&gt; const&amp;), float&gt;, return_type_test_type&lt;std::complex&lt;double&gt; const&amp;, float (*)(std::complex&lt;double&gt; const&amp;), float&gt;, return_type_test_type&lt;std::complex&lt;double&gt;&amp;&amp;, float (*)(std::complex&lt;double&gt; const&amp;), float&gt;, return_type_test_type&lt;std::complex&lt;long double&gt;, float (*)(std::complex&lt;long double&gt;), float&gt;, return_type_test_type&lt;std::complex&lt;long double&gt;, float (*)(std::complex&lt;long double&gt; const&amp;), float&gt;, return_type_test_type&lt;std::complex&lt;long double&gt; const, float (*)(std::complex&lt;long double&gt; const&amp;), float&gt;, return_type_test_type&lt;std::complex&lt;long double&gt;&amp;, float (*)(std::complex&lt;long double&gt; const&amp;), float&gt;, return_type_test_type&lt;std::complex&lt;long double&gt; const&amp;, float (*)(std::complex&lt;long double&gt; const&amp;), float&gt;, return_type_test_type&lt;std::complex&lt;long double&gt;&amp;&amp;, float (*)(std::complex&lt;long double&gt; const&amp;), float&gt;, return_type_test_type&lt;char, double (*)(char), double&gt;, return_type_test_type&lt;char, double (*)(char const&amp;), double&gt;, return_type_test_type&lt;char const, double (*)(char const&amp;), double&gt;, return_type_test_type&lt;char&amp;, double (*)(char const&amp;), double&gt;, return_type_test_type&lt;char const&amp;, double (*)(char const&amp;), double&gt;, return_type_test_type&lt;char&amp;&amp;, double (*)(char const&amp;), double&gt;, return_type_test_type&lt;int, double (*)(int), double&gt;, return_type_test_type&lt;int, double (*)(int const&amp;), double&gt;, return_type_test_type&lt;int const, double (*)(int const&amp;), double&gt;, return_type_test_type&lt;int&amp;, double (*)(int const&amp;), double&gt;, return_type_test_type&lt;int const&amp;, double (*)(int const&amp;), double&gt;, return_type_test_type&lt;int&amp;&amp;, double (*)(int const&amp;), double&gt;, return_type_test_type&lt;float, double (*)(float), double&gt;, return_type_test_type&lt;float, double (*)(float const&amp;), double&gt;, return_type_test_type&lt;float const, double (*)(float const&amp;), double&gt;, return_type_test_type&lt;float&amp;, double (*)(float const&amp;), double&gt;, return_type_test_type&lt;float const&amp;, double (*)(float const&amp;), double&gt;, return_type_test_type&lt;float&amp;&amp;, double (*)(float const&amp;), double&gt;, return_type_test_type&lt;double, double (*)(double), double&gt;, return_type_test_type&lt;double, double (*)(double const&amp;), double&gt;, return_type_test_type&lt;double const, double (*)(double const&amp;), double&gt;, return_type_test_type&lt;double&amp;, double (*)(double const&amp;), double&gt;, return_type_test_type&lt;double const&amp;, double (*)(double const&amp;), double&gt;, return_type_test_type&lt;double&amp;&amp;, double (*)(double const&amp;), double&gt;, return_type_test_type&lt;long double, double (*)(long double), double&gt;, return_type_test_type&lt;long double, double (*)(long double const&amp;), double&gt;, return_type_test_type&lt;long double const, double (*)(long double const&amp;), double&gt;, return_type_test_type&lt;long double&amp;, double (*)(long double const&amp;), double&gt;, return_type_test_type&lt;long double const&amp;, double (*)(long double const&amp;), double&gt;, return_type_test_type&lt;long double&amp;&amp;, double (*)(long double const&amp;), double&gt;, return_type_test_type&lt;std::string, double (*)(std::string), double&gt;, return_type_test_type&lt;std::string, double (*)(std::string const&amp;), double&gt;, return_type_test_type&lt;std::string const, double (*)(std::string const&amp;), double&gt;, return_type_test_type&lt;std::string&amp;, double (*)(std::string const&amp;), double&gt;, return_type_test_type&lt;std::string const&amp;, double (*)(std::string const&amp;), double&gt;, return_type_test_type&lt;std::string&amp;&amp;, double (*)(std::string const&amp;), double&gt;, return_type_test_type&lt;std::complex&lt;char&gt;, double (*)(std::complex&lt;char&gt;), double&gt;, return_type_test_type&lt;std::complex&lt;char&gt;, double (*)(std::complex&lt;char&gt; const&amp;), double&gt;, return_type_test_type&lt;std::complex&lt;char&gt; const, double (*)(std::complex&lt;char&gt; const&amp;), double&gt;, return_type_test_type&lt;std::complex&lt;char&gt;&amp;, double (*)(std::complex&lt;char&gt; const&amp;), double&gt;, return_type_test_type&lt;std::complex&lt;char&gt; const&amp;, double (*)(std::complex&lt;char&gt; const&amp;), double&gt;, return_type_test_type&lt;std::complex&lt;char&gt;&amp;&amp;, double (*)(std::complex&lt;char&gt; const&amp;), double&gt;, return_type_test_type&lt;std::complex&lt;int&gt;, double (*)(std::complex&lt;int&gt;), double&gt;, return_type_test_type&lt;std::complex&lt;int&gt;, double (*)(std::complex&lt;int&gt; const&amp;), double&gt;, return_type_test_type&lt;std::complex&lt;int&gt; const, double (*)(std::complex&lt;int&gt; const&amp;), double&gt;, return_type_test_type&lt;std::complex&lt;int&gt;&amp;, double (*)(std::complex&lt;int&gt; const&amp;), double&gt;, return_type_test_type&lt;std::complex&lt;int&gt; const&amp;, double (*)(std::complex&lt;int&gt; const&amp;), double&gt;, return_type_test_type&lt;std::complex&lt;int&gt;&amp;&amp;, double (*)(std::complex&lt;int&gt; const&amp;), double&gt;, return_type_test_type&lt;std::complex&lt;float&gt;, double (*)(std::complex&lt;float&gt;), double&gt;, return_type_test_type&lt;std::complex&lt;float&gt;, double (*)(std::complex&lt;float&gt; const&amp;), double&gt;, return_type_test_type&lt;std::complex&lt;float&gt; const, double (*)(std::complex&lt;float&gt; const&amp;), double&gt;, return_type_test_type&lt;std::complex&lt;float&gt;&amp;, double (*)(std::complex&lt;float&gt; const&amp;), double&gt;, return_type_test_type&lt;std::complex&lt;float&gt; const&amp;, double (*)(std::complex&lt;float&gt; const&amp;), double&gt;, return_type_test_type&lt;std::complex&lt;float&gt;&amp;&amp;, double (*)(std::complex&lt;float&gt; const&amp;), double&gt;, return_type_test_type&lt;std::complex&lt;double&gt;, double (*)(std::complex&lt;double&gt;), double&gt;, return_type_test_type&lt;std::complex&lt;double&gt;, double (*)(std::complex&lt;double&gt; const&amp;), double&gt;, return_type_test_type&lt;std::complex&lt;double&gt; const, double (*)(std::complex&lt;double&gt; const&amp;), double&gt;, return_type_test_type&lt;std::complex&lt;double&gt;&amp;, double (*)(std::complex&lt;double&gt; const&amp;), double&gt;, return_type_test_type&lt;std::complex&lt;double&gt; const&amp;, double (*)(std::complex&lt;double&gt; const&amp;), double&gt;, return_type_test_type&lt;std::complex&lt;double&gt;&amp;&amp;, double (*)(std::complex&lt;double&gt; const&amp;), double&gt;, return_type_test_type&lt;std::complex&lt;long double&gt;, double (*)(std::complex&lt;long double&gt;), double&gt;, return_type_test_type&lt;std::complex&lt;long double&gt;, double (*)(std::complex&lt;long double&gt; const&amp;), double&gt;, return_type_test_type&lt;std::complex&lt;long double&gt; const, double (*)(std::complex&lt;long double&gt; const&amp;), double&gt;, return_type_test_type&lt;std::complex&lt;long double&gt;&amp;, double (*)(std::complex&lt;long double&gt; const&amp;), double&gt;, return_type_test_type&lt;std::complex&lt;long double&gt; const&amp;, double (*)(std::complex&lt;long double&gt; const&amp;), double&gt;, return_type_test_type&lt;std::complex&lt;long double&gt;&amp;&amp;, double (*)(std::complex&lt;long double&gt; const&amp;), double&gt;, return_type_test_type&lt;char, long double (*)(char), long double&gt;, return_type_test_type&lt;char, long double (*)(char const&amp;), long double&gt;, return_type_test_type&lt;char const, long double (*)(char const&amp;), long double&gt;, return_type_test_type&lt;char&amp;, long double (*)(char const&amp;), long double&gt;, return_type_test_type&lt;char const&amp;, long double (*)(char const&amp;), long double&gt;, return_type_test_type&lt;char&amp;&amp;, long double (*)(char const&amp;), long double&gt;, return_type_test_type&lt;int, long double (*)(int), long double&gt;, return_type_test_type&lt;int, long double (*)(int const&amp;), long double&gt;, return_type_test_type&lt;int const, long double (*)(int const&amp;), long double&gt;, return_type_test_type&lt;int&amp;, long double (*)(int const&amp;), long double&gt;, return_type_test_type&lt;int const&amp;, long double (*)(int const&amp;), long double&gt;, return_type_test_type&lt;int&amp;&amp;, long double (*)(int const&amp;), long double&gt;, return_type_test_type&lt;float, long double (*)(float), long double&gt;, return_type_test_type&lt;float, long double (*)(float const&amp;), long double&gt;, return_type_test_type&lt;float const, long double (*)(float const&amp;), long double&gt;, return_type_test_type&lt;float&amp;, long double (*)(float const&amp;), long double&gt;, return_type_test_type&lt;float const&amp;, long double (*)(float const&amp;), long double&gt;, return_type_test_type&lt;float&amp;&amp;, long double (*)(float const&amp;), long double&gt;, return_type_test_type&lt;double, long double (*)(double), long double&gt;, return_type_test_type&lt;double, long double (*)(double const&amp;), long double&gt;, return_type_test_type&lt;double const, long double (*)(double const&amp;), long double&gt;, return_type_test_type&lt;double&amp;, long double (*)(double const&amp;), long double&gt;, return_type_test_type&lt;double const&amp;, long double (*)(double const&amp;), long double&gt;, return_type_test_type&lt;double&amp;&amp;, long double (*)(double const&amp;), long double&gt;, return_type_test_type&lt;long double, long double (*)(long double), long double&gt;, return_type_test_type&lt;long double, long double (*)(long double const&amp;), long double&gt;, return_type_test_type&lt;long double const, long double (*)(long double const&amp;), long double&gt;, return_type_test_type&lt;long double&amp;, long double (*)(long double const&amp;), long double&gt;, return_type_test_type&lt;long double const&amp;, long double (*)(long double const&amp;), long double&gt;, return_type_test_type&lt;long double&amp;&amp;, long double (*)(long double const&amp;), long double&gt;, return_type_test_type&lt;std::string, long double (*)(std::string), long double&gt;, return_type_test_type&lt;std::string, long double (*)(std::string const&amp;), long double&gt;, return_type_test_type&lt;std::string const, long double (*)(std::string const&amp;), long double&gt;, return_type_test_type&lt;std::string&amp;, long double (*)(std::string const&amp;), long double&gt;, return_type_test_type&lt;std::string const&amp;, long double (*)(std::string const&amp;), long double&gt;, return_type_test_type&lt;std::string&amp;&amp;, long double (*)(std::string const&amp;), long double&gt;, return_type_test_type&lt;std::complex&lt;char&gt;, long double (*)(std::complex&lt;char&gt;), long double&gt;, return_type_test_type&lt;std::complex&lt;char&gt;, long double (*)(std::complex&lt;char&gt; const&amp;), long double&gt;, return_type_test_type&lt;std::complex&lt;char&gt; const, long double (*)(std::complex&lt;char&gt; const&amp;), long double&gt;, return_type_test_type&lt;std::complex&lt;char&gt;&amp;, long double (*)(std::complex&lt;char&gt; const&amp;), long double&gt;, return_type_test_type&lt;std::complex&lt;char&gt; const&amp;, long double (*)(std::complex&lt;char&gt; const&amp;), long double&gt;, return_type_test_type&lt;std::complex&lt;char&gt;&amp;&amp;, long double (*)(std::complex&lt;char&gt; const&amp;), long double&gt;, return_type_test_type&lt;std::complex&lt;int&gt;, long double (*)(std::complex&lt;int&gt;), long double&gt;, return_type_test_type&lt;std::complex&lt;int&gt;, long double (*)(std::complex&lt;int&gt; const&amp;), long double&gt;, return_type_test_type&lt;std::complex&lt;int&gt; const, long double (*)(std::complex&lt;int&gt; const&amp;), long double&gt;, return_type_test_type&lt;std::complex&lt;int&gt;&amp;, long double (*)(std::complex&lt;int&gt; const&amp;), long double&gt;, return_type_test_type&lt;std::complex&lt;int&gt; const&amp;, long double (*)(std::complex&lt;int&gt; const&amp;), long double&gt;, return_type_test_type&lt;std::complex&lt;int&gt;&amp;&amp;, long double (*)(std::complex&lt;int&gt; const&amp;), long double&gt;, return_type_test_type&lt;std::complex&lt;float&gt;, long double (*)(std::complex&lt;float&gt;), long double&gt;, return_type_test_type&lt;std::complex&lt;float&gt;, long double (*)(std::complex&lt;float&gt; const&amp;), long double&gt;, return_type_test_type&lt;std::complex&lt;float&gt; const, long double (*)(std::complex&lt;float&gt; const&amp;), long double&gt;, return_type_test_type&lt;std::complex&lt;float&gt;&amp;, long double (*)(std::complex&lt;float&gt; const&amp;), long double&gt;, return_type_test_type&lt;std::complex&lt;float&gt; const&amp;, long double (*)(std::complex&lt;float&gt; const&amp;), long double&gt;, return_type_test_type&lt;std::complex&lt;float&gt;&amp;&amp;, long double (*)(std::complex&lt;float&gt; const&amp;), long double&gt;, return_type_test_type&lt;std::complex&lt;double&gt;, long double (*)(std::complex&lt;double&gt;), long double&gt;, return_type_test_type&lt;std::complex&lt;double&gt;, long double (*)(std::complex&lt;double&gt; const&amp;), long double&gt;, return_type_test_type&lt;std::complex&lt;double&gt; const, long double (*)(std::complex&lt;double&gt; const&amp;), long double&gt;, return_type_test_type&lt;std::complex&lt;double&gt;&amp;, long double (*)(std::complex&lt;double&gt; const&amp;), long double&gt;, return_type_test_type&lt;std::complex&lt;double&gt; const&amp;, long double (*)(std::complex&lt;double&gt; const&amp;), long double&gt;, return_type_test_type&lt;std::complex&lt;double&gt;&amp;&amp;, long double (*)(std::complex&lt;double&gt; const&amp;), long double&gt;, return_type_test_type&lt;std::complex&lt;long double&gt;, long double (*)(std::complex&lt;long double&gt;), long double&gt;, return_type_test_type&lt;std::complex&lt;long double&gt;, long double (*)(std::complex&lt;long double&gt; const&amp;), long double&gt;, return_type_test_type&lt;std::complex&lt;long double&gt; const, long double (*)(std::complex&lt;long double&gt; const&amp;), long double&gt;, return_type_test_type&lt;std::complex&lt;long double&gt;&amp;, long double (*)(std::complex&lt;long double&gt; const&amp;), long double&gt;, return_type_test_type&lt;std::complex&lt;long double&gt; const&amp;, long double (*)(std::complex&lt;long double&gt; const&amp;), long double&gt;, return_type_test_type&lt;std::complex&lt;long double&gt;&amp;&amp;, long double (*)(std::complex&lt;long double&gt; const&amp;), long double&gt;, return_type_test_type&lt;char, std::string (*)(char), std::string&gt;, return_type_test_type&lt;char, std::string (*)(char const&amp;), std::string&gt;, return_type_test_type&lt;char const, std::string (*)(char const&amp;), std::string&gt;, return_type_test_type&lt;char&amp;, std::string (*)(char const&amp;), std::string&gt;, return_type_test_type&lt;char const&amp;, std::string (*)(char const&amp;), std::string&gt;, return_type_test_type&lt;char&amp;&amp;, std::string (*)(char const&amp;), std::string&gt;, return_type_test_type&lt;int, std::string (*)(int), std::string&gt;, return_type_test_type&lt;int, std::string (*)(int const&amp;), std::string&gt;, return_type_test_type&lt;int const, std::string (*)(int const&amp;), std::string&gt;, return_type_test_type&lt;int&amp;, std::string (*)(int const&amp;), std::string&gt;, return_type_test_type&lt;int const&amp;, std::string (*)(int const&amp;), std::string&gt;, return_type_test_type&lt;int&amp;&amp;, std::string (*)(int const&amp;), std::string&gt; &gt;; BOOST_AUTO_TEST_CASE_TEMPLATE(return_type, Types, return_type_test_types) { //using Container = std::tuple_element_t&lt;0, Types&gt;; //using Function = std::tuple_element_t&lt;1, Types&gt;; using Expected = std::tuple_element_t&lt;2, Types&gt;; using Result = std::tuple_element_t&lt;3, Types&gt;; BOOST_TEST((std::is_same_v&lt;Expected, Result&gt;)); } </code></pre> </li> <li><p>The part of the input type with non-recursive <code>std::optional</code></p> <pre><code>return_type_test_type&lt;std::optional&lt;char&gt;, char (*)(std::optional&lt;char&gt;), char&gt;, return_type_test_type&lt;std::optional&lt;int&gt;, char (*)(std::optional&lt;int&gt;), char&gt;, return_type_test_type&lt;std::optional&lt;short&gt;, char (*)(std::optional&lt;short&gt;), char&gt;, return_type_test_type&lt;std::optional&lt;long&gt;, char (*)(std::optional&lt;long&gt;), char&gt;, return_type_test_type&lt;std::optional&lt;long long int&gt;, char (*)(std::optional&lt;long long int&gt;), char&gt;, return_type_test_type&lt;std::optional&lt;float&gt;, char (*)(std::optional&lt;float&gt;), char&gt;, return_type_test_type&lt;std::optional&lt;double&gt;, char (*)(std::optional&lt;double&gt;), char&gt;, return_type_test_type&lt;std::optional&lt;long double&gt;, char (*)(std::optional&lt;long double&gt;), char&gt;, return_type_test_type&lt;std::optional&lt;char&gt;, int (*)(std::optional&lt;char&gt;), int&gt;, return_type_test_type&lt;std::optional&lt;int&gt;, int (*)(std::optional&lt;int&gt;), int&gt;, return_type_test_type&lt;std::optional&lt;short&gt;, int (*)(std::optional&lt;short&gt;), int&gt;, return_type_test_type&lt;std::optional&lt;long&gt;, int (*)(std::optional&lt;long&gt;), int&gt;, return_type_test_type&lt;std::optional&lt;long long int&gt;, int (*)(std::optional&lt;long long int&gt;), int&gt;, return_type_test_type&lt;std::optional&lt;float&gt;, int (*)(std::optional&lt;float&gt;), int&gt;, return_type_test_type&lt;std::optional&lt;double&gt;, int (*)(std::optional&lt;double&gt;), int&gt;, return_type_test_type&lt;std::optional&lt;long double&gt;, int (*)(std::optional&lt;long double&gt;), int&gt;, return_type_test_type&lt;std::optional&lt;char&gt;, short (*)(std::optional&lt;char&gt;), short&gt;, return_type_test_type&lt;std::optional&lt;int&gt;, short (*)(std::optional&lt;int&gt;), short&gt;, return_type_test_type&lt;std::optional&lt;short&gt;, short (*)(std::optional&lt;short&gt;), short&gt;, return_type_test_type&lt;std::optional&lt;long&gt;, short (*)(std::optional&lt;long&gt;), short&gt;, return_type_test_type&lt;std::optional&lt;long long int&gt;, short (*)(std::optional&lt;long long int&gt;), short&gt;, return_type_test_type&lt;std::optional&lt;float&gt;, short (*)(std::optional&lt;float&gt;), short&gt;, return_type_test_type&lt;std::optional&lt;double&gt;, short (*)(std::optional&lt;double&gt;), short&gt;, return_type_test_type&lt;std::optional&lt;long double&gt;, short (*)(std::optional&lt;long double&gt;), short&gt;, return_type_test_type&lt;std::optional&lt;char&gt;, long (*)(std::optional&lt;char&gt;), long&gt;, return_type_test_type&lt;std::optional&lt;int&gt;, long (*)(std::optional&lt;int&gt;), long&gt;, return_type_test_type&lt;std::optional&lt;short&gt;, long (*)(std::optional&lt;short&gt;), long&gt;, return_type_test_type&lt;std::optional&lt;long&gt;, long (*)(std::optional&lt;long&gt;), long&gt;, return_type_test_type&lt;std::optional&lt;long long int&gt;, long (*)(std::optional&lt;long long int&gt;), long&gt;, return_type_test_type&lt;std::optional&lt;float&gt;, long (*)(std::optional&lt;float&gt;), long&gt;, return_type_test_type&lt;std::optional&lt;double&gt;, long (*)(std::optional&lt;double&gt;), long&gt;, return_type_test_type&lt;std::optional&lt;long double&gt;, long (*)(std::optional&lt;long double&gt;), long&gt;, return_type_test_type&lt;std::optional&lt;char&gt;, long long int (*)(std::optional&lt;char&gt;), long long int&gt;, return_type_test_type&lt;std::optional&lt;int&gt;, long long int (*)(std::optional&lt;int&gt;), long long int&gt;, return_type_test_type&lt;std::optional&lt;short&gt;, long long int (*)(std::optional&lt;short&gt;), long long int&gt;, return_type_test_type&lt;std::optional&lt;long&gt;, long long int (*)(std::optional&lt;long&gt;), long long int&gt;, return_type_test_type&lt;std::optional&lt;long long int&gt;, long long int (*)(std::optional&lt;long long int&gt;), long long int&gt;, return_type_test_type&lt;std::optional&lt;float&gt;, long long int (*)(std::optional&lt;float&gt;), long long int&gt;, return_type_test_type&lt;std::optional&lt;double&gt;, long long int (*)(std::optional&lt;double&gt;), long long int&gt;, return_type_test_type&lt;std::optional&lt;long double&gt;, long long int (*)(std::optional&lt;long double&gt;), long long int&gt;, return_type_test_type&lt;std::optional&lt;char&gt;, float (*)(std::optional&lt;char&gt;), float&gt;, return_type_test_type&lt;std::optional&lt;int&gt;, float (*)(std::optional&lt;int&gt;), float&gt;, return_type_test_type&lt;std::optional&lt;short&gt;, float (*)(std::optional&lt;short&gt;), float&gt;, return_type_test_type&lt;std::optional&lt;long&gt;, float (*)(std::optional&lt;long&gt;), float&gt;, return_type_test_type&lt;std::optional&lt;long long int&gt;, float (*)(std::optional&lt;long long int&gt;), float&gt;, return_type_test_type&lt;std::optional&lt;float&gt;, float (*)(std::optional&lt;float&gt;), float&gt;, return_type_test_type&lt;std::optional&lt;double&gt;, float (*)(std::optional&lt;double&gt;), float&gt;, return_type_test_type&lt;std::optional&lt;long double&gt;, float (*)(std::optional&lt;long double&gt;), float&gt;, return_type_test_type&lt;std::optional&lt;char&gt;, double (*)(std::optional&lt;char&gt;), double&gt;, return_type_test_type&lt;std::optional&lt;int&gt;, double (*)(std::optional&lt;int&gt;), double&gt;, return_type_test_type&lt;std::optional&lt;short&gt;, double (*)(std::optional&lt;short&gt;), double&gt;, return_type_test_type&lt;std::optional&lt;long&gt;, double (*)(std::optional&lt;long&gt;), double&gt;, return_type_test_type&lt;std::optional&lt;long long int&gt;, double (*)(std::optional&lt;long long int&gt;), double&gt;, return_type_test_type&lt;std::optional&lt;float&gt;, double (*)(std::optional&lt;float&gt;), double&gt;, return_type_test_type&lt;std::optional&lt;double&gt;, double (*)(std::optional&lt;double&gt;), double&gt;, return_type_test_type&lt;std::optional&lt;long double&gt;, double (*)(std::optional&lt;long double&gt;), double&gt;, return_type_test_type&lt;std::optional&lt;char&gt;, long double (*)(std::optional&lt;char&gt;), long double&gt;, return_type_test_type&lt;std::optional&lt;int&gt;, long double (*)(std::optional&lt;int&gt;), long double&gt;, return_type_test_type&lt;std::optional&lt;short&gt;, long double (*)(std::optional&lt;short&gt;), long double&gt;, return_type_test_type&lt;std::optional&lt;long&gt;, long double (*)(std::optional&lt;long&gt;), long double&gt;, return_type_test_type&lt;std::optional&lt;long long int&gt;, long double (*)(std::optional&lt;long long int&gt;), long double&gt;, return_type_test_type&lt;std::optional&lt;float&gt;, long double (*)(std::optional&lt;float&gt;), long double&gt;, return_type_test_type&lt;std::optional&lt;double&gt;, long double (*)(std::optional&lt;double&gt;), long double&gt;, return_type_test_type&lt;std::optional&lt;long double&gt;, long double (*)(std::optional&lt;long double&gt;), long double&gt;, </code></pre> </li> <li><p>The part of non-recursive <code>std::optional</code> input and non-recursive <code>std::optional</code> output</p> <pre><code>return_type_test_type&lt;std::optional&lt;char&gt;, std::optional&lt;char&gt; (*)(std::optional&lt;char&gt;), std::optional&lt;char&gt;&gt;, return_type_test_type&lt;std::optional&lt;int&gt;, std::optional&lt;char&gt; (*)(std::optional&lt;int&gt;), std::optional&lt;char&gt;&gt;, return_type_test_type&lt;std::optional&lt;short&gt;, std::optional&lt;char&gt; (*)(std::optional&lt;short&gt;), std::optional&lt;char&gt;&gt;, return_type_test_type&lt;std::optional&lt;long&gt;, std::optional&lt;char&gt; (*)(std::optional&lt;long&gt;), std::optional&lt;char&gt;&gt;, return_type_test_type&lt;std::optional&lt;long long int&gt;, std::optional&lt;char&gt; (*)(std::optional&lt;long long int&gt;), std::optional&lt;char&gt;&gt;, return_type_test_type&lt;std::optional&lt;unsigned char&gt;, std::optional&lt;char&gt; (*)(std::optional&lt;unsigned char&gt;), std::optional&lt;char&gt;&gt;, return_type_test_type&lt;std::optional&lt;float&gt;, std::optional&lt;char&gt; (*)(std::optional&lt;float&gt;), std::optional&lt;char&gt;&gt;, return_type_test_type&lt;std::optional&lt;double&gt;, std::optional&lt;char&gt; (*)(std::optional&lt;double&gt;), std::optional&lt;char&gt;&gt;, return_type_test_type&lt;std::optional&lt;long double&gt;, std::optional&lt;char&gt; (*)(std::optional&lt;long double&gt;), std::optional&lt;char&gt;&gt;, return_type_test_type&lt;std::optional&lt;char&gt;, std::optional&lt;int&gt; (*)(std::optional&lt;char&gt;), std::optional&lt;int&gt;&gt;, return_type_test_type&lt;std::optional&lt;int&gt;, std::optional&lt;int&gt; (*)(std::optional&lt;int&gt;), std::optional&lt;int&gt;&gt;, return_type_test_type&lt;std::optional&lt;short&gt;, std::optional&lt;int&gt; (*)(std::optional&lt;short&gt;), std::optional&lt;int&gt;&gt;, return_type_test_type&lt;std::optional&lt;long&gt;, std::optional&lt;int&gt; (*)(std::optional&lt;long&gt;), std::optional&lt;int&gt;&gt;, return_type_test_type&lt;std::optional&lt;long long int&gt;, std::optional&lt;int&gt; (*)(std::optional&lt;long long int&gt;), std::optional&lt;int&gt;&gt;, return_type_test_type&lt;std::optional&lt;unsigned char&gt;, std::optional&lt;int&gt; (*)(std::optional&lt;unsigned char&gt;), std::optional&lt;int&gt;&gt;, return_type_test_type&lt;std::optional&lt;float&gt;, std::optional&lt;int&gt; (*)(std::optional&lt;float&gt;), std::optional&lt;int&gt;&gt;, return_type_test_type&lt;std::optional&lt;double&gt;, std::optional&lt;int&gt; (*)(std::optional&lt;double&gt;), std::optional&lt;int&gt;&gt;, return_type_test_type&lt;std::optional&lt;long double&gt;, std::optional&lt;int&gt; (*)(std::optional&lt;long double&gt;), std::optional&lt;int&gt;&gt;, return_type_test_type&lt;std::optional&lt;char&gt;, std::optional&lt;short&gt; (*)(std::optional&lt;char&gt;), std::optional&lt;short&gt;&gt;, return_type_test_type&lt;std::optional&lt;int&gt;, std::optional&lt;short&gt; (*)(std::optional&lt;int&gt;), std::optional&lt;short&gt;&gt;, return_type_test_type&lt;std::optional&lt;short&gt;, std::optional&lt;short&gt; (*)(std::optional&lt;short&gt;), std::optional&lt;short&gt;&gt;, return_type_test_type&lt;std::optional&lt;long&gt;, std::optional&lt;short&gt; (*)(std::optional&lt;long&gt;), std::optional&lt;short&gt;&gt;, return_type_test_type&lt;std::optional&lt;long long int&gt;, std::optional&lt;short&gt; (*)(std::optional&lt;long long int&gt;), std::optional&lt;short&gt;&gt;, return_type_test_type&lt;std::optional&lt;unsigned char&gt;, std::optional&lt;short&gt; (*)(std::optional&lt;unsigned char&gt;), std::optional&lt;short&gt;&gt;, return_type_test_type&lt;std::optional&lt;float&gt;, std::optional&lt;short&gt; (*)(std::optional&lt;float&gt;), std::optional&lt;short&gt;&gt;, return_type_test_type&lt;std::optional&lt;double&gt;, std::optional&lt;short&gt; (*)(std::optional&lt;double&gt;), std::optional&lt;short&gt;&gt;, return_type_test_type&lt;std::optional&lt;long double&gt;, std::optional&lt;short&gt; (*)(std::optional&lt;long double&gt;), std::optional&lt;short&gt;&gt;, return_type_test_type&lt;std::optional&lt;char&gt;, std::optional&lt;long&gt; (*)(std::optional&lt;char&gt;), std::optional&lt;long&gt;&gt;, return_type_test_type&lt;std::optional&lt;int&gt;, std::optional&lt;long&gt; (*)(std::optional&lt;int&gt;), std::optional&lt;long&gt;&gt;, return_type_test_type&lt;std::optional&lt;short&gt;, std::optional&lt;long&gt; (*)(std::optional&lt;short&gt;), std::optional&lt;long&gt;&gt;, return_type_test_type&lt;std::optional&lt;long&gt;, std::optional&lt;long&gt; (*)(std::optional&lt;long&gt;), std::optional&lt;long&gt;&gt;, return_type_test_type&lt;std::optional&lt;long long int&gt;, std::optional&lt;long&gt; (*)(std::optional&lt;long long int&gt;), std::optional&lt;long&gt;&gt;, return_type_test_type&lt;std::optional&lt;unsigned char&gt;, std::optional&lt;long&gt; (*)(std::optional&lt;unsigned char&gt;), std::optional&lt;long&gt;&gt;, return_type_test_type&lt;std::optional&lt;float&gt;, std::optional&lt;long&gt; (*)(std::optional&lt;float&gt;), std::optional&lt;long&gt;&gt;, return_type_test_type&lt;std::optional&lt;double&gt;, std::optional&lt;long&gt; (*)(std::optional&lt;double&gt;), std::optional&lt;long&gt;&gt;, return_type_test_type&lt;std::optional&lt;long double&gt;, std::optional&lt;long&gt; (*)(std::optional&lt;long double&gt;), std::optional&lt;long&gt;&gt;, return_type_test_type&lt;std::optional&lt;char&gt;, std::optional&lt;long long int&gt; (*)(std::optional&lt;char&gt;), std::optional&lt;long long int&gt;&gt;, return_type_test_type&lt;std::optional&lt;int&gt;, std::optional&lt;long long int&gt; (*)(std::optional&lt;int&gt;), std::optional&lt;long long int&gt;&gt;, return_type_test_type&lt;std::optional&lt;short&gt;, std::optional&lt;long long int&gt; (*)(std::optional&lt;short&gt;), std::optional&lt;long long int&gt;&gt;, return_type_test_type&lt;std::optional&lt;long&gt;, std::optional&lt;long long int&gt; (*)(std::optional&lt;long&gt;), std::optional&lt;long long int&gt;&gt;, return_type_test_type&lt;std::optional&lt;long long int&gt;, std::optional&lt;long long int&gt; (*)(std::optional&lt;long long int&gt;), std::optional&lt;long long int&gt;&gt;, return_type_test_type&lt;std::optional&lt;unsigned char&gt;, std::optional&lt;long long int&gt; (*)(std::optional&lt;unsigned char&gt;), std::optional&lt;long long int&gt;&gt;, return_type_test_type&lt;std::optional&lt;float&gt;, std::optional&lt;long long int&gt; (*)(std::optional&lt;float&gt;), std::optional&lt;long long int&gt;&gt;, return_type_test_type&lt;std::optional&lt;double&gt;, std::optional&lt;long long int&gt; (*)(std::optional&lt;double&gt;), std::optional&lt;long long int&gt;&gt;, return_type_test_type&lt;std::optional&lt;long double&gt;, std::optional&lt;long long int&gt; (*)(std::optional&lt;long double&gt;), std::optional&lt;long long int&gt;&gt;, return_type_test_type&lt;std::optional&lt;char&gt;, std::optional&lt;unsigned char&gt; (*)(std::optional&lt;char&gt;), std::optional&lt;unsigned char&gt;&gt;, return_type_test_type&lt;std::optional&lt;int&gt;, std::optional&lt;unsigned char&gt; (*)(std::optional&lt;int&gt;), std::optional&lt;unsigned char&gt;&gt;, return_type_test_type&lt;std::optional&lt;short&gt;, std::optional&lt;unsigned char&gt; (*)(std::optional&lt;short&gt;), std::optional&lt;unsigned char&gt;&gt;, return_type_test_type&lt;std::optional&lt;long&gt;, std::optional&lt;unsigned char&gt; (*)(std::optional&lt;long&gt;), std::optional&lt;unsigned char&gt;&gt;, return_type_test_type&lt;std::optional&lt;long long int&gt;, std::optional&lt;unsigned char&gt; (*)(std::optional&lt;long long int&gt;), std::optional&lt;unsigned char&gt;&gt;, return_type_test_type&lt;std::optional&lt;unsigned char&gt;, std::optional&lt;unsigned char&gt; (*)(std::optional&lt;unsigned char&gt;), std::optional&lt;unsigned char&gt;&gt;, return_type_test_type&lt;std::optional&lt;float&gt;, std::optional&lt;unsigned char&gt; (*)(std::optional&lt;float&gt;), std::optional&lt;unsigned char&gt;&gt;, return_type_test_type&lt;std::optional&lt;double&gt;, std::optional&lt;unsigned char&gt; (*)(std::optional&lt;double&gt;), std::optional&lt;unsigned char&gt;&gt;, return_type_test_type&lt;std::optional&lt;long double&gt;, std::optional&lt;unsigned char&gt; (*)(std::optional&lt;long double&gt;), std::optional&lt;unsigned char&gt;&gt;, return_type_test_type&lt;std::optional&lt;char&gt;, std::optional&lt;float&gt; (*)(std::optional&lt;char&gt;), std::optional&lt;float&gt;&gt;, return_type_test_type&lt;std::optional&lt;int&gt;, std::optional&lt;float&gt; (*)(std::optional&lt;int&gt;), std::optional&lt;float&gt;&gt;, return_type_test_type&lt;std::optional&lt;short&gt;, std::optional&lt;float&gt; (*)(std::optional&lt;short&gt;), std::optional&lt;float&gt;&gt;, return_type_test_type&lt;std::optional&lt;long&gt;, std::optional&lt;float&gt; (*)(std::optional&lt;long&gt;), std::optional&lt;float&gt;&gt;, return_type_test_type&lt;std::optional&lt;long long int&gt;, std::optional&lt;float&gt; (*)(std::optional&lt;long long int&gt;), std::optional&lt;float&gt;&gt;, return_type_test_type&lt;std::optional&lt;unsigned char&gt;, std::optional&lt;float&gt; (*)(std::optional&lt;unsigned char&gt;), std::optional&lt;float&gt;&gt;, return_type_test_type&lt;std::optional&lt;float&gt;, std::optional&lt;float&gt; (*)(std::optional&lt;float&gt;), std::optional&lt;float&gt;&gt;, return_type_test_type&lt;std::optional&lt;double&gt;, std::optional&lt;float&gt; (*)(std::optional&lt;double&gt;), std::optional&lt;float&gt;&gt;, return_type_test_type&lt;std::optional&lt;long double&gt;, std::optional&lt;float&gt; (*)(std::optional&lt;long double&gt;), std::optional&lt;float&gt;&gt;, return_type_test_type&lt;std::optional&lt;char&gt;, std::optional&lt;double&gt; (*)(std::optional&lt;char&gt;), std::optional&lt;double&gt;&gt;, return_type_test_type&lt;std::optional&lt;int&gt;, std::optional&lt;double&gt; (*)(std::optional&lt;int&gt;), std::optional&lt;double&gt;&gt;, return_type_test_type&lt;std::optional&lt;short&gt;, std::optional&lt;double&gt; (*)(std::optional&lt;short&gt;), std::optional&lt;double&gt;&gt;, return_type_test_type&lt;std::optional&lt;long&gt;, std::optional&lt;double&gt; (*)(std::optional&lt;long&gt;), std::optional&lt;double&gt;&gt;, return_type_test_type&lt;std::optional&lt;long long int&gt;, std::optional&lt;double&gt; (*)(std::optional&lt;long long int&gt;), std::optional&lt;double&gt;&gt;, return_type_test_type&lt;std::optional&lt;unsigned char&gt;, std::optional&lt;double&gt; (*)(std::optional&lt;unsigned char&gt;), std::optional&lt;double&gt;&gt;, return_type_test_type&lt;std::optional&lt;float&gt;, std::optional&lt;double&gt; (*)(std::optional&lt;float&gt;), std::optional&lt;double&gt;&gt;, return_type_test_type&lt;std::optional&lt;double&gt;, std::optional&lt;double&gt; (*)(std::optional&lt;double&gt;), std::optional&lt;double&gt;&gt;, return_type_test_type&lt;std::optional&lt;long double&gt;, std::optional&lt;double&gt; (*)(std::optional&lt;long double&gt;), std::optional&lt;double&gt;&gt;, return_type_test_type&lt;std::optional&lt;char&gt;, std::optional&lt;long double&gt; (*)(std::optional&lt;char&gt;), std::optional&lt;long double&gt;&gt;, return_type_test_type&lt;std::optional&lt;int&gt;, std::optional&lt;long double&gt; (*)(std::optional&lt;int&gt;), std::optional&lt;long double&gt;&gt;, return_type_test_type&lt;std::optional&lt;short&gt;, std::optional&lt;long double&gt; (*)(std::optional&lt;short&gt;), std::optional&lt;long double&gt;&gt;, return_type_test_type&lt;std::optional&lt;long&gt;, std::optional&lt;long double&gt; (*)(std::optional&lt;long&gt;), std::optional&lt;long double&gt;&gt;, return_type_test_type&lt;std::optional&lt;long long int&gt;, std::optional&lt;long double&gt; (*)(std::optional&lt;long long int&gt;), std::optional&lt;long double&gt;&gt;, return_type_test_type&lt;std::optional&lt;unsigned char&gt;, std::optional&lt;long double&gt; (*)(std::optional&lt;unsigned char&gt;), std::optional&lt;long double&gt;&gt;, return_type_test_type&lt;std::optional&lt;float&gt;, std::optional&lt;long double&gt; (*)(std::optional&lt;float&gt;), std::optional&lt;long double&gt;&gt;, return_type_test_type&lt;std::optional&lt;double&gt;, std::optional&lt;long double&gt; (*)(std::optional&lt;double&gt;), std::optional&lt;long double&gt;&gt;, return_type_test_type&lt;std::optional&lt;long double&gt;, std::optional&lt;long double&gt; (*)(std::optional&lt;long double&gt;), std::optional&lt;long double&gt;&gt;, </code></pre> </li> <li><p>The part of non-recursive <code>std::array</code> return type test</p> <pre><code>// Non-recursive array. return_type_test_type&lt;std::array&lt;char, 5&gt;, char (*)(char), std::array&lt;char, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;int, 5&gt;, char (*)(int), std::array&lt;char, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;short, 5&gt;, char (*)(short), std::array&lt;char, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;long, 5&gt;, char (*)(long), std::array&lt;char, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;long long int, 5&gt;, char (*)(long long int), std::array&lt;char, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;float, 5&gt;, char (*)(float), std::array&lt;char, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;double, 5&gt;, char (*)(double), std::array&lt;char, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;long double, 5&gt;, char (*)(long double), std::array&lt;char, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;char, 5&gt;, int (*)(char), std::array&lt;int, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;int, 5&gt;, int (*)(int), std::array&lt;int, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;short, 5&gt;, int (*)(short), std::array&lt;int, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;long, 5&gt;, int (*)(long), std::array&lt;int, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;long long int, 5&gt;, int (*)(long long int), std::array&lt;int, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;float, 5&gt;, int (*)(float), std::array&lt;int, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;double, 5&gt;, int (*)(double), std::array&lt;int, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;long double, 5&gt;, int (*)(long double), std::array&lt;int, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;char, 5&gt;, short (*)(char), std::array&lt;short, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;int, 5&gt;, short (*)(int), std::array&lt;short, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;short, 5&gt;, short (*)(short), std::array&lt;short, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;long, 5&gt;, short (*)(long), std::array&lt;short, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;long long int, 5&gt;, short (*)(long long int), std::array&lt;short, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;float, 5&gt;, short (*)(float), std::array&lt;short, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;double, 5&gt;, short (*)(double), std::array&lt;short, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;long double, 5&gt;, short (*)(long double), std::array&lt;short, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;char, 5&gt;, long (*)(char), std::array&lt;long, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;int, 5&gt;, long (*)(int), std::array&lt;long, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;short, 5&gt;, long (*)(short), std::array&lt;long, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;long, 5&gt;, long (*)(long), std::array&lt;long, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;long long int, 5&gt;, long (*)(long long int), std::array&lt;long, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;float, 5&gt;, long (*)(float), std::array&lt;long, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;double, 5&gt;, long (*)(double), std::array&lt;long, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;long double, 5&gt;, long (*)(long double), std::array&lt;long, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;char, 5&gt;, long long int (*)(char), std::array&lt;long long int, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;int, 5&gt;, long long int (*)(int), std::array&lt;long long int, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;short, 5&gt;, long long int (*)(short), std::array&lt;long long int, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;long, 5&gt;, long long int (*)(long), std::array&lt;long long int, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;long long int, 5&gt;, long long int (*)(long long int), std::array&lt;long long int, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;float, 5&gt;, long long int (*)(float), std::array&lt;long long int, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;double, 5&gt;, long long int (*)(double), std::array&lt;long long int, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;long double, 5&gt;, long long int (*)(long double), std::array&lt;long long int, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;char, 5&gt;, float (*)(char), std::array&lt;float, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;int, 5&gt;, float (*)(int), std::array&lt;float, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;short, 5&gt;, float (*)(short), std::array&lt;float, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;long, 5&gt;, float (*)(long), std::array&lt;float, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;long long int, 5&gt;, float (*)(long long int), std::array&lt;float, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;float, 5&gt;, float (*)(float), std::array&lt;float, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;double, 5&gt;, float (*)(double), std::array&lt;float, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;long double, 5&gt;, float (*)(long double), std::array&lt;float, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;char, 5&gt;, double (*)(char), std::array&lt;double, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;int, 5&gt;, double (*)(int), std::array&lt;double, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;short, 5&gt;, double (*)(short), std::array&lt;double, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;long, 5&gt;, double (*)(long), std::array&lt;double, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;long long int, 5&gt;, double (*)(long long int), std::array&lt;double, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;float, 5&gt;, double (*)(float), std::array&lt;double, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;double, 5&gt;, double (*)(double), std::array&lt;double, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;long double, 5&gt;, double (*)(long double), std::array&lt;double, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;char, 5&gt;, long double (*)(char), std::array&lt;long double, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;int, 5&gt;, long double (*)(int), std::array&lt;long double, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;short, 5&gt;, long double (*)(short), std::array&lt;long double, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;long, 5&gt;, long double (*)(long), std::array&lt;long double, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;long long int, 5&gt;, long double (*)(long long int), std::array&lt;long double, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;float, 5&gt;, long double (*)(float), std::array&lt;long double, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;double, 5&gt;, long double (*)(double), std::array&lt;long double, 5&gt;&gt;, return_type_test_type&lt;std::array&lt;long double, 5&gt;, long double (*)(long double), std::array&lt;long double, 5&gt;&gt;, </code></pre> </li> </ul> <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/253793/231235">Nested std::deque and std::vector Type Test Cases for recursive_transform Template Function in C++</a>,</p> <p><a href="https://codereview.stackexchange.com/q/253556/231235">A recursive_transform Template Function Implementation with <code>std::invocable</code> concept in C++</a>,</p> <p><a href="https://codereview.stackexchange.com/q/251823/231235">A recursive_transform Template Function with Execution Policy</a> and</p> <p><a href="https://codereview.stackexchange.com/q/253665/231235">A recursive_transform Template Function Implementation with std::invocable Concept and Execution Policy in C++</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <p>Based on indi's answer in the previous question, the testing structure is updated. Moreover, the main idea here is the part of various type test cases in order to make sure that the return types deducing in <code>recursive_transform()</code> is correct.</p> </li> <li><p>Why a new review is being asked for?</p> <p>If there is any possible improvement, please let me know.</p> </li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-27T22:56:00.123", "Id": "253974", "Score": "0", "Tags": [ "c++", "unit-testing", "lambda", "boost", "c++20" ], "Title": "Various Type Test Cases for recursive_transform Template Function in C++" }
253974
<p>This is my implementation of the Pig Latin recommended exercise in The Rust Programming Language book. I am using the <a href="https://crates.io/crates/unicode-segmentation" rel="nofollow noreferrer">unicode segmentation crate</a> to split the string into words while also keeping the delimiters. Any pointers on making this code more idiomatic or run more optimal?</p> <pre><code>use unicode_segmentation::UnicodeSegmentation; #[allow(overlapping_patterns)] fn translate_word(s: &amp;str) -&gt; String { let mut it = s.chars(); let first = it.next().unwrap(); match first.to_ascii_lowercase() { 'a' | 'e' | 'i' | 'o' | 'u' =&gt; format!(&quot;{}-hay&quot;, s), 'a'..='z' =&gt; format!(&quot;{}-{}ay&quot;, it.collect::&lt;String&gt;(), first), _ =&gt; s.to_string(), } } pub fn translate(s: &amp;str) -&gt; String { s.split_word_bounds() .map(translate_word) .collect::&lt;Vec&lt;_&gt;&gt;() .join(&quot;&quot;) } </code></pre> <p>The code is inside a module named <code>pig_latin</code>.</p>
[]
[ { "body": "<h2>Be aware that Rust typically uses 4 spaces</h2>\n<p>It's fine if you consistently use 2 spaces (especially if you override it in rustfmt.toml), but just be aware that the standard is different.</p>\n<h2>Collect directly to a <code>String</code></h2>\n<p>Instead of collecting to a <code>Vec</code> and then copying that over to a new <code>Vec</code> (within <code>String</code>), collect to a <code>String</code> directly:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>pub fn translate(s: &amp;str) -&gt; String {\n s.split_word_bounds().map(translate_word).collect()\n}\n</code></pre>\n<h2>Use <code>Chars::as_str</code></h2>\n<p>When you use <code>str::chars</code>, the specific iterator that it returns is called <a href=\"https://doc.rust-lang.org/std/str/struct.Chars.html\" rel=\"nofollow noreferrer\"><code>Chars</code></a>. It has a <a href=\"https://doc.rust-lang.org/std/str/struct.Chars.html#method.as_str\" rel=\"nofollow noreferrer\">handy function</a> to get the remaining part, so you don't need to allocate a new string:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>'a'..='z' =&gt; format!(&quot;{}-{}ay&quot;, it.as_str(), first),\n</code></pre>\n<h2>Use <a href=\"https://doc.rust-lang.org/std/borrow/enum.Cow.html\" rel=\"nofollow noreferrer\"><code>Cow</code></a></h2>\n<p>This is a bit of an advanced optimization that you don't need to do—the Book doesn't even mention it once.</p>\n<p>Currently, you allocate a new <code>String</code> even when the output is identical to the input. Instead, return <code>Cow&lt;str&gt;</code>: if the first character isn't a letter, you can return <code>Cow::Borrowed(s)</code>, which points to the existing <code>&amp;str</code>. If it does start with a letter, return <code>Cow::Owned(format!(...))</code>, which has the same overhead as it did before. Here, I'm using <code>.into()</code> instead of writing <code>Cow::Owned</code> and <code>Cow::Borrowed</code> explicitly. You can do either.</p>\n<pre class=\"lang-rust prettyprint-override\"><code>fn translate_word(s: &amp;str) -&gt; Cow&lt;str&gt; {\n let mut it = s.chars();\n let first = it.next().unwrap();\n match first.to_ascii_lowercase() {\n 'a' | 'e' | 'i' | 'o' | 'u' =&gt; format!(&quot;{}-hay&quot;, s).into(),\n 'a'..='z' =&gt; format!(&quot;{}-{}ay&quot;, it.as_str(), first).into(),\n _ =&gt; s.into(),\n }\n}\n</code></pre>\n<h1>Final code</h1>\n<p><a href=\"https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=78daca7b7adab4587436cacf35bca90e\" rel=\"nofollow noreferrer\">https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=78daca7b7adab4587436cacf35bca90e</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T03:51:05.150", "Id": "253983", "ParentId": "253979", "Score": "2" } } ]
{ "AcceptedAnswerId": "253983", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T00:21:46.310", "Id": "253979", "Score": "1", "Tags": [ "rust" ], "Title": "The Rust Programming Language Pig Latin Exercise" }
253979
<p><strong>Background</strong></p> <p>I've written an algorithm to solve the three-dimensional Time Difference of Arrival (TDoA) multi-lateration problem. That is, given the coordinates of <code>n</code> nodes, the velocity <code>v</code> of some signal, and the time of signal arrival at each node, we want to determine the coordinates of the signal source. In my case, the problem was further complicated by the fact that only four nodes are available.</p> <p>I tried numerous approaches, and found the most success implementing <a href="https://gssc.esa.int/navipedia/index.php/Bancroft_Method#:%7E:text=The%20Bancroft%20method%20allows%20obtaining,knowledge%20for%20the%20receiver%20location." rel="nofollow noreferrer">Bancroft's method</a>. With it, I'm able to obtain remarkable accuracy and precision, as well as excellent efficiency. I leave mathematical commentary to the linked page, however I'll try to step through my code as clearly as possible.</p> <hr /> <p><code>def find():</code></p> <p>The <code>find()</code> method of the <code>Vertexer</code> class does the actual leg-work. When a <code>Vertexer</code> object is constructed, the coordinates of the nodes to be used are passed as a <code>NumPy</code> array to the constructor. That array looks like:</p> <pre><code>[[x_1, y_1, z_1], [x_2, y_2, z_2], [x_3, y_3, z_3], [x_4, y_4, z_4]] </code></pre> <p>The times of arrival are passed as a <code>NumPy</code> array to the <code>find()</code> method. That array looks like:</p> <pre><code>[[t_1], [t_2], [t_3], [t_4]] </code></pre> <p>The math (as per above) is performed, then we iterate through (typically two) possible solutions, and append each solution to a list, <code>solution</code>.</p> <pre><code> # Iterate for Lambda in np.roots([ lorentzInner(oneA, oneA), (lorentzInner(oneA, invA) - 1) * 2, lorentzInner(invA, invA), ]): # Obtain solution X, Y, Z, T = M @ np.linalg.solve(A, Lambda * np.ones(4) + b) # Append solution as NumPy array to `solution` solution.append(np.array([X,Y,Z])) </code></pre> <p>The final solution is obtained by taking the <code>min</code> from <code>solution</code>, with the <code>key</code> being an error function which gives the sum of squared residuals (RSS error) of the time of arrival of the predicted point at each node, minus the given time of arrival.</p> <hr /> <p><code>def __post_init__():</code></p> <p>In my application, it could be that times inputted are &quot;invalid&quot; (don't correspond to an actual localization, even though the code will try to find one). I compute the minimum possible time of arrival difference, and the maximum possible time of arrival difference.</p> <p>The minimum possible time of arrival difference is given by a source at the centroid of the nodes. I calculate the centroid with <code>centroid = np.average(self.nodes, axis = 0)</code>. Then, I find the time of arrival at each node and take the minimum.</p> <p>The maximum possible time of arrival difference is given by the two furthest nodes in the network. I find this using a simple <code>O(n^2)</code> brute-force &quot;algorithm&quot;. As of now, the code doesn't do much with this, except print the bounds.</p> <p><strong>Goals</strong></p> <ol> <li><p>Readability/Brevity: Of utmost importance is the readability/brevity of my code. Please, feel free to offer criticism of even the most minor grievances with regards to readability.</p> </li> <li><p>Efficiency</p> </li> </ol> <p><strong>Code</strong></p> <pre><code>from dataclasses import dataclass import numpy as np from random import randrange import math M = np.diag([1, 1, 1, -1]) @dataclass class Vertexer: nodes: np.ndarray # Defaults v = 299792 def __post_init__(self): # Calculate valid input range max = 0 min = 1E+10 centroid = np.average(self.nodes, axis = 0) for n in self.nodes: dist = np.linalg.norm(n - centroid) if dist &lt; min: min = dist for p in self.nodes: dist = np.linalg.norm(n - p) if dist &gt; max: max = dist max /= self.v min /= self.v print(min, max) def errFunc(self, point, times): # Return RSS error error = 0 for n, t in zip(self.nodes, times): error += ((np.linalg.norm(n - point) / self.v) - t)**2 return error def find(self, times): def lorentzInner(v, w): # Return Lorentzian Inner-Product return np.sum(v * (w @ M), axis = -1) A = np.append(self.nodes, times * self.v, axis = 1) b = 0.5 * lorentzInner(A, A) oneA = np.linalg.solve(A, np.ones(4)) invA = np.linalg.solve(A, b) solution = [] for Lambda in np.roots([ lorentzInner(oneA, oneA), (lorentzInner(oneA, invA) - 1) * 2, lorentzInner(invA, invA), ]): X, Y, Z, T = M @ np.linalg.solve(A, Lambda * np.ones(4) + b) solution.append(np.array([X,Y,Z])) return min(solution, key = lambda err: self.errFunc(err, times)) </code></pre> <p><strong>Sample Input/Output</strong></p> <p>This (quite crude) code, which you can append directly to the code above, will &quot;simulate&quot; a source/node network, print the actual source coordinates, and pass the times of arrival/node coordinates to the algorithm. We work with light signals, and in kilometers.</p> <p>Note that I'm aware this bit could be done much better. I'm interested only in improving the algorithm above, this code is just to demonstrate the algorithm's efficacy.</p> <pre><code># Simulate sources to test code # # Pick nodes to be at random locations x_1 = randrange(10); y_1 = randrange(10); z_1 = randrange(10) x_2 = randrange(10); y_2 = randrange(10); z_2 = randrange(10) x_3 = randrange(10); y_3 = randrange(10); z_3 = randrange(10) x_4 = randrange(10); y_4 = randrange(10); z_4 = randrange(10) # Pick source to be at random location x = randrange(1000); y = randrange(1000); z = randrange(1000) # Set velocity c = 299792 # km/ns # Generate simulated source t_1 = math.sqrt( (x - x_1)**2 + (y - y_1)**2 + (z - z_1)**2 ) / c t_2 = math.sqrt( (x - x_2)**2 + (y - y_2)**2 + (z - z_2)**2 ) / c t_3 = math.sqrt( (x - x_3)**2 + (y - y_3)**2 + (z - z_3)**2 ) / c t_4 = math.sqrt( (x - x_4)**2 + (y - y_4)**2 + (z - z_4)**2 ) / c print('Actual:', x, y, z) myVertexer = Vertexer(np.array([[x_1, y_1, z_1],[x_2, y_2, z_2],[x_3, y_3, z_3],[x_4, y_4, z_4]])) print(myVertexer.find(np.array([[t_1], [t_2], [t_3], [t_4]]))) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T22:44:33.190", "Id": "500966", "Score": "0", "body": "Have you looked at `numba`? It limits the numpy functions you can use (I don't know off the top of my head if the ones you use would work as-is or not) but it provides Just-in-time compilation to C code that can execute significantly faster than native python code. Also your `x_1...x_4` and `t_1...t_4` generation could be done in one line each if you vectorize it. I didn't look in depth but guessing your `for` loops could be be vectorised as well if you're applying the same function to each node" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T23:21:04.390", "Id": "500968", "Score": "1", "body": "@Coupcoup Thanks for the suggestions! `numba` looks interesting, I'll have to look into it further." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T00:11:41.460", "Id": "500976", "Score": "0", "body": "As a heads up if numba works for you I wouldn't worry about vectorizing the inner for loops (still do the `x_n` though), numba runs basically as fast with for loops as with vectorized functions because it's converting everything to vectorized c code already" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T10:08:46.927", "Id": "529739", "Score": "0", "body": "Your value for the speed of light is a billion times too fast. The unit for that value is km/sec." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-02T12:09:51.847", "Id": "529751", "Score": "0", "body": "Try using [`distance_matrix`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance_matrix.html) in your `__post_init__`." } ]
[ { "body": "<h2>Dataclass types</h2>\n<p><code>nodes</code> has a type but <code>v</code> doesn't - it should probably be <code>: int</code>.</p>\n<h2>Vectorization</h2>\n<p>First of all, you should probably do dimension (shape) checking on <code>self.nodes</code>. You probably have assumptions about the shape of this array that we can't see.</p>\n<p>Also, this:</p>\n<pre><code> for n in self.nodes:\n dist = np.linalg.norm(n - centroid)\n if dist &lt; min:\n min = dist\n\n for p in self.nodes:\n dist = np.linalg.norm(n - p)\n\n if dist &gt; max:\n max = dist\n</code></pre>\n<p>really smells as if it can be further vectorized. Reading the <a href=\"https://numpy.org/devdocs/reference/generated/numpy.linalg.norm.html\" rel=\"nofollow noreferrer\">documentation for norm</a>, it does accept an <code>axis</code>, so at the very least you should be able to make a <code>dist</code> array in one step without the need to put it in a loop. <code>min</code> can similarly be applied over a specific axis on an entire <code>ndarray</code>.</p>\n<p>You should be able to eliminate the inner loop using broadcasting. However, I can't be more specific than that as I don't know the shape of <code>self.nodes</code>.</p>\n<h2>Forced output</h2>\n<p>Don't do this -</p>\n<pre><code> print(min, max)\n</code></pre>\n<p>in your post-constructor. It's not useful for headless or unsupervised execution. Instead, move all of your <code>min</code>/<code>max</code> code to a method that calculates and returns these values, so that the caller can decide what to do with them. Among other reasons, this will make unit testing nicer.</p>\n<h2>Names</h2>\n<p><code>errFunc</code> should be <code>err_func</code> by PEP8; <code>lorentz_inner</code> and so on.</p>\n<h2>Tests</h2>\n<p>You're so close to having a useful unit test. The only thing missing is <code>assert</code>. For this to work, you may have to give up calling <code>randrange</code> and instead choose known, easily-verifiable values.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-04T17:10:15.827", "Id": "254315", "ParentId": "253982", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T02:50:13.450", "Id": "253982", "Score": "3", "Tags": [ "python", "performance", "algorithm", "numpy", "mathematics" ], "Title": "Bancroft's method implementation" }
253982
<p>This is not a question related to a bug.I've just created a very tiny <code>node.js/express API</code> for education purposes. I've created a very little <code>API</code> and what i would like is to have your point of view about the design and projet architecture and what you would recommand be as advice in term of what i can improve in this code.</p> <p>As it's open sources you're also welcome for <code>pull requests</code>.</p> <p>Notice : I've not considered aspects like <code>logging</code>,<code>ORM's</code> or specific packages for <code>validation</code> or these kind of things.</p> <p>Here is the github repo where i explain cleary how to run the project in the local computer.</p> <p><a href="https://github.com/jochri3/tiny-express-api" rel="nofollow noreferrer">https://github.com/jochri3/tiny-express-api</a></p> <p>My code organization is in a MVC pattern:</p> <pre><code>|controllers -posts.js |middlewares -bodyValidation.js -postExists.js |models -post.js |startups -db.js -routes.js app.js router.js </code></pre> <p>Here is the codes content:</p> <p><strong>controllers/posts.js</strong></p> <pre><code>const Post=require('../models/post'); const index=async(req,res)=&gt;{ const posts=await Post.getAll(); res.send({data:posts}) } // const show=(req,res)=&gt;{ // } const create=async({body},res)=&gt;{ await Post.create(body); res.status(201).send({message:'post created successfully'}); } const update=async({body,params:{id}},res)=&gt;{ await Post.update(id,body) res.status(201).send({message:'posts updated successfully'}); } const destroy=async({params:{id}},res)=&gt;{ await Post.delete(id); res.status(202).send({message:'post deleted successfully'}) } module.exports={ index, // show, create, update, destroy } </code></pre> <p><strong>middlewares/bodyValidate</strong></p> <pre><code>module.exports=async({body},res,next)=&gt;{ const bodyValues=Object.values(body); if(bodyValues.some(value=&gt;!value)){ return res.status(422).send({message:'Veuillez remplir tous les champs correctement'}) } next(); } </code></pre> <p><strong>middlewares/postExists.js</strong></p> <pre><code>const connection=require(&quot;../startups/db&quot;) module.exports=async(req,res,next)=&gt;{ const {params:{id}}=req; if(!id){ return res.status(404).send({message:'not found'}) } const post=await connection.select().from('posts').where('id',id); if(!post.length){ return res.status(404).send({message:'not found'}) } req.post=post; next(); } </code></pre> <p><strong>models/post.js</strong></p> <pre><code>const connection=require(&quot;../startups/db&quot;); class Post{ static getAll(){ return connection.select().from(&quot;posts&quot;); } static update(id,data){ return connection('posts').where('id',id).update(data); } // static getOne(id){ // } static delete(id){ return connection('posts').where('id', id).del(); } static create(data){ return connection('posts').insert(data); } } module.exports=Post; </code></pre> <p><strong>startups/db.js</strong></p> <pre><code>const knex=require(&quot;knex&quot;); module.exports=knex({ client: 'sqlite3', connection: { filename: &quot;./db.sqlite&quot; } }) </code></pre> <p><strong>startups/routes.js</strong></p> <pre><code>const express=require('express'); const {postsRouter}=require('../router') module.exports=(app)=&gt;{ app.use(express.json()) app.use('/api/posts',postsRouter) } </code></pre> <p><strong>app.js</strong></p> <pre><code>const express=require(&quot;express&quot;); const connection=require(&quot;./startups/db&quot;); const app=express(); require('./startups/routes')(app,connection) require('express-async-errors'); const port=8000 app.listen(port,()=&gt;{ console.info(`Server in listening on port ${port}`) }) </code></pre> <p><strong>router.js</strong></p> <pre><code>const express=require('express'); //custom middlewares const idExists=require(&quot;./middlewares/postsExists&quot;); const bodyValidates=require(&quot;./middlewares/bodyValidate&quot;); const PostsController=require(&quot;./controllers/posts&quot;) const postsRouter=express.Router(); postsRouter.get('/',PostsController.index); postsRouter.get('/:id',[idExists],async(req,res)=&gt;{ res.send({data:req.post[0]}); }); postsRouter.post('/',[bodyValidates],PostsController.create) postsRouter.put('/:id',[idExists,bodyValidates],PostsController.update) postsRouter.delete('/:id',[idExists],PostsController.destroy) module.exports={ postsRouter } </code></pre> <p>You can view the project in codesandbox : <a href="https://codesandbox.io/s/angry-montalcini-vsbfb" rel="nofollow noreferrer">https://codesandbox.io/s/angry-montalcini-vsbfb</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T07:32:01.077", "Id": "253990", "Score": "2", "Tags": [ "node.js", "api", "express.js" ], "Title": "Tiny REST API for making CRUD operations on list of posts" }
253990
<p>I am using Django Rest Framework and below is the code of one of the API Endpoints. The code creates generates the PUBLIC and SECRET Values based on Stellar SDK.</p> <pre><code>def create(self, request): try: if 'app_id' not in request.data: response = {'status': 'FAIL', 'data': 'App ID field not found'} return Response(response, status=status.HTTP_400_BAD_REQUEST) if 'customer_id' not in request.data: response = {'status': 'FAIL', 'data': 'Customer ID field not found'} return Response(response, status=status.HTTP_400_BAD_REQUEST) customer_id = request.data['customer_id'] app_id = request.data['app_id'] app = App.objects.get(id=app_id) # Creating Stellar Account addr, secret = create_account() if addr is None and secret is None: response = {'status': 'FAIL', 'data': 'Could not generate customer Wallet'} return Response(response, status=status.HTTP_200_OK) # Make sure we do not add duplicate customers wallet_count = Wallet.objects.filter(customer_id=customer_id).count() if wallet_count &gt; 0: response = {'status': 'FAIL', 'data': 'The customer ID already exist'} return Response(response, status=status.HTTP_200_OK) # The customer does not exist, hence create his wallet. wallet = Wallet(customer_id=customer_id, app=app, address=addr, secret=secret) wallet.save() if wallet.pk is None and wallet.pk &gt; 0: response = {'status': 'OK', 'data': 'success'} else: response = {'status': 'FAIL', 'data': 'Messed up'} except App.DoesNotExist: response = {'status': 'FAIL', 'data': 'The App ID not found'} return Response(response, status=status.HTTP_404_NOT_FOUND) return Response({'status': 'OK', 'data': 'success'}, status=status.HTTP_200_OK) </code></pre> <p>As you can see there is repetition of codeblock like below:</p> <pre><code>response = {'status': 'FAIL', 'data': 'The customer ID already exist'} return Response(response, status=status.HTTP_200_OK) </code></pre> <p>It'd be nice if I can reduce all this code either by passing to a function or someway once and let it handle based on <code>request</code> dict.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T11:18:48.070", "Id": "500893", "Score": "2", "body": "Welcome to Code Review. I have rolled back your edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." } ]
[ { "body": "<h1>Exception handling</h1>\n<p>You may want to consider reducing the try block to where the expected exception actually is raised.</p>\n<pre><code>try:\n app = App.objects.get(id=app_id)\nexcept App.DoesNotExist:\n …\n</code></pre>\n<h1>Possible bugs</h1>\n<p>This test does not consider the case, that <em>only one</em> of <code>addr</code> and <code>secret</code> is <code>None</code>. Is that permitted?</p>\n<pre><code>if addr is None and secret is None:\n …\n</code></pre>\n<p>These response dicts are never used:</p>\n<pre><code>if wallet.pk is None and wallet.pk &gt; 0:\n response = {'status': 'OK', 'data': 'success'}\nelse:\n response = {'status': 'FAIL', 'data': 'Messed up'}\n</code></pre>\n<h1>Deduplication</h1>\n<p>Regarding your concern of duplicated dicts: I see none.\nSure, they are <em>similar</em>, but there are no duplicates, since the error messages differ. Of course, you can outsource the generation to a function like</p>\n<pre><code>def make_response(data: str, success: bool) -&gt; dict:\n &quot;&quot;&quot;Returns a response dict.&quot;&quot;&quot;\n return {'status': 'OK' if success else 'FAIL', 'data': data}\n</code></pre>\n<p>but it's up to you to decide if that's worth an extra function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T11:14:50.663", "Id": "500892", "Score": "0", "body": "Thanks, Richard, your first two recommendations implemented/fixed however did not get the dedup one. Could you check the updated question?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T20:23:51.037", "Id": "500960", "Score": "0", "body": "You could drop the response variable, and just return - it simplifies this a bit, e.g. : return Response({'status': 'FAIL', 'data': 'Customer ID field not found'}, status=status.HTTP_400_BAD_REQUEST)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T01:53:48.400", "Id": "500977", "Score": "0", "body": "I thought of writing a function to use like `return fail_with('Customer ID field not found', status.HTTP_404_BAD_REQUEST)`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T10:33:20.670", "Id": "253993", "ParentId": "253991", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T07:48:41.140", "Id": "253991", "Score": "3", "Tags": [ "python", "django" ], "Title": "How can I refactor the validation code to minimize it?" }
253991
<p>I've implemented the first experiment from the <a href="https://paperswithcode.com/paper/reward-design-via-online-gradient-ascent" rel="nofollow noreferrer">Reward Design via Online Gradient Ascent paper</a>. I don't have any specific concerns, but it's my first time using multiprocessing or doing reinforcement learning, and I want to add this work to my portfolio. So I want to know if there is anything wrong with this code or if it can be improved in any way. The number of trials is 13 instead of 130 like in the paper because I don't have that much compute.</p> <p>Main file:</p> <pre><code>import numpy as np from agent import Agent from environment import BirdEnv from pgrd import PGRD from gym.utils.seeding import np_random from multiprocessing import Pool import os # 5 actions: move right, left, down, up, eat the worm NUM_ACTIONS = 5 #the agent observes the full state given by 9*agent_location + worm_location NUM_STATES = 81 TAU = 100 GAMMA = 0.95 NUM_TRIALS = 13 TOTAL_TIMESTEPS = 5000 if __name__ == &quot;__main__&quot;: rng_env, _ = np_random() env = BirdEnv(rng_env) for depth in range(7): print(depth) for alpha in [0, 2e-6, 5e-6, 2e-5, 5e-5, 2e-4, 5e-4, 2e-3, 5e-3, 1e-2]: print(alpha) for beta in [0, 0.4, 0.7, 0.9, 0.95, 0.99]: def run_trial(num_trial): env.reset() rng_agent, _ = np_random() agent = Agent(depth, TAU, GAMMA, rng_agent, NUM_ACTIONS, NUM_STATES) model = PGRD(agent, env, alpha, beta) return model.learn(total_timesteps=TOTAL_TIMESTEPS, visualize=False) pool = Pool(os.cpu_count()) try: returns = pool.map(run_trial, np.arange(num_trials)) returns = np.sum(np.array(returns), axis=0) / num_trials finally: pool.close() pool.join() np.save(&quot;results/Result_depth_{}_alpha_{}_beta_{}.npy&quot;.format(depth, alpha, beta), returns) </code></pre> <p>agent.py:</p> <pre><code>import numpy as np from collections import defaultdict from functools import lru_cache def softmax(action_values, tau): &quot;&quot;&quot; Arguments: action_values - 1-dimensional array tau - temperature &quot;&quot;&quot; preferences = action_values * tau max_preference = np.max(preferences) exp_prefs = np.exp(preferences - max_preference) return exp_prefs / np.sum(exp_prefs) class Agent: def __init__(self, depth, tau, gamma, rng, nA, nS): self.nA = nA self.nS = nS self.depth = depth #depth of planning self.tau = tau #policy temperature self.gamma = gamma #discount rate #agent's model of the environment #N[s][a] = {total: total_visits, 'counts': {s': x, ...}} #N[s][a][s'] - number of visits to s' after taking action s in state a #N[s][a][s`] / N[s][a][total] = Pr(s`|s, a) self.N = defaultdict(lambda: defaultdict(lambda: {'total':0, 'counts': defaultdict(lambda:0)})) self.rand_generator = rng def update(self, state, action, newstate): self.N[state][action]['total'] += 1 self.N[state][action]['counts'][newstate] += 1 def plan(self, state, theta): &quot;&quot;&quot; Compute d-step Q-value function and its theta-gradient at state&quot;&quot;&quot; @lru_cache(maxsize=None) def _plan(self, state, d): &quot;&quot;&quot; Recursive memoized function&quot;&quot;&quot; reward_grad = np.zeros((self.nA, self.nS, self.nA)) for a in range(self.nA): reward_grad[a,state,a] = 1 if d == 0: action_values = theta[state] value_grad = reward_grad else: inc = np.zeros(self.nA) grad_inc = np.zeros((self.nA, self.nS, self.nA)) for action in self.N[state].keys(): for state_next, count in self.N[state][action]['counts'].items(): values_next, grad_next = _plan(self, state_next, d-1) action_next = np.argmax(values_next) p = count / self.N[state][action]['total'] inc[action] += values_next[action_next] * p grad_inc[action, state_next, action_next] += np.argmax(values_next) * p action_values = theta[state] + self.gamma * inc value_grad = reward_grad + self.gamma * grad_inc return action_values, value_grad return _plan(self, state, self.depth) def logpolicy_grad(self, value_grad, probas, action): &quot;&quot;&quot; Arguments: value_grad: nA x nS x nA probas: nA action: int Returns: grad: nS x nA &quot;&quot;&quot; grad = self.tau * (value_grad[action] - np.tensordot(probas, value_grad, axes=1)) return grad def policy(self, action_values): probas = softmax(action_values, self.tau) return probas def step(self, state, theta): action_values, value_grad = self.plan(state, theta) # compute the Boltzman stochastic policy parametrized by action_values probas = self.policy(action_values) #shape: nA # select action according to policy action = self.rand_generator.choice(np.arange(self.nA), p=probas) grad = self.logpolicy_grad(value_grad, probas, action) return action, grad </code></pre> <p>environment.py</p> <pre><code>import sys import numpy as np from collections import defaultdict MAP = [&quot;CCC&quot;, &quot; ==&quot;, &quot;CCC&quot;, &quot; ==&quot;, &quot;CCC&quot;] class BirdEnv: &quot;&quot;&quot;Bird looks for a worm&quot;&quot;&quot; metadata = {'render.modes': ['human']} def __init__(self, rng): self.nA = 5 #number of actions: right, left, down, up, eat the worm self.nC = 9 #number of cells in 3x3 grid self.nS = self.nC**2 # state = (position of bird, position of worm) self.ncol = 3 #number of columns in 3x3 grid self.rand_generator = rng #transitions[c][a] == [(probability, nextcell),..] self.transitions = {c : {} for c in range(self.nC)} def move(i, j, inc): cell_i = max(min(i + inc[0], 4), 0) cell_j = max(min(j + inc[1], 2), 0) #move according to action, if you can if MAP[cell_i][cell_j] == &quot;=&quot;: cell_i = i elif MAP[cell_i][cell_j] == &quot; &quot;: cell_i += inc[0] cell = 3 * (cell_i // 2) + cell_j return cell for i, row in enumerate(MAP): for j, char in enumerate(row): if char == &quot;C&quot;: d = defaultdict(lambda:0) for inc in [(0,1), (0, -1), (1, 0), (-1,0)]: cell = move(i,j,inc) d[cell] += 0.025 for action, inc in enumerate([(0,1), (0, -1), (1, 0), (-1,0)]): cell = move(i,j,inc) trans = d.copy() trans[cell] += 0.9 self.transitions[3*(i//2)+j][action] = [(prob, nextcell) for nextcell, prob in trans.items()] #initial cell distribution (always start in the upper left corner) self.icd = [1, 0, 0, 0, 0, 0, 0, 0, 0] self.cell = self.rand_generator.choice(np.arange(self.nC), p=self.icd) #initial worm distribution: in one of the three right-most locations at the end of each corridor self.iwd = [0, 0, 1./3, 0, 0, 1./3, 0, 0, 1./3] self.worm = self.rand_generator.choice(np.arange(self.nC), p=self.iwd) self.lastaction = 4 def state(self): return self.nC * self.cell + self.worm def step(self, action): &quot;&quot;&quot;Execute one time step within the environment&quot;&quot;&quot; reward = 0 if action == 4: #try eating the worm if self.cell == self.worm: #move worm into one of the empty cells on the right self.worm = self.rand_generator.choice([(self.worm + 3) % self.nC, (self.worm + 6) % self.nC]) reward = 1 else: transitions = self.transitions[self.cell][action] i = self.rand_generator.choice(np.arange(len(transitions)), p=[t[0] for t in transitions]) _, cell = transitions[i] self.cell = cell self.lastaction = action state = self.state() return state, reward def reset(self): # Reset the state of the environment to an initial state self.cell = self.rand_generator.choice(np.arange(self.nC), p=self.icd) self.worm = self.rand_generator.choice(np.arange(self.nC), p=self.iwd) def render(self, mode='human', close=False): # Render the environment to the screen outfile = sys.stdout desc = [[&quot;C&quot;, &quot;C&quot;, &quot;C&quot;], [&quot;C&quot;, &quot;C&quot;, &quot;C&quot;], [&quot;C&quot;, &quot;C&quot;, &quot;C&quot;]] row, col = self.cell // self.ncol, self.cell % self.ncol desc[row][col] = &quot;B&quot; row, col = self.worm // self.ncol, self.worm % self.ncol desc[row][col] = &quot;W&quot; if self.lastaction is not None: outfile.write(&quot; ({})\n&quot;.format( [&quot;Right&quot;, &quot;Left&quot;, &quot;Down&quot;, &quot;Up&quot;, &quot;Eat&quot;][self.lastaction])) else: outfile.write(&quot;\n&quot;) outfile.write(&quot;\n&quot;.join(''.join(line) for line in desc)+&quot;\n&quot;) </code></pre> <p>pgrd.py</p> <pre><code>import numpy as np class PGRD: def __init__(self, agent, env, alpha, beta): self.agent = agent self.env = env self.alpha = alpha #step size self.beta = beta #theta is initialized so that the initial reward function = objective reward function self.theta = np.zeros((env.nS, env.nA)) for cell in [2,5,8]: self.theta[10*cell, 4] = 1 #variable to store theta gradient self.z = np.zeros((env.nS, env.nA)) def learn(self, total_timesteps, visualize=False): state = self.env.state() total_reward = 0 returns = [] for i in range(total_timesteps): if visualize: print(i) self.env.render() action, grad = self.agent.step(state, self.theta) newstate, reward = self.env.step(action) total_reward += reward #update agent's model of the environment: self.agent.update(state, action, newstate) state = newstate #update theta self.z = self.beta * self.z + grad self.theta += self.alpha * reward * self.z #cap parameters at +-1: self.theta = np.maximum(self.theta, -1) self.theta = np.minimum(self.theta, 1) returns.append(total_reward / (i+1)) return np.array(returns) </code></pre> <p>tests.py</p> <pre><code>import numpy as np #print environment transitions: def print_env(env): def pretty(d, indent=0): for key, value in d.items(): print('\t' * indent + str(key)) if isinstance(value, dict): pretty(value, indent+1) else: print('\t' * (indent+1) + str(value)) pretty(env.transitions, indent=1) def test_value_grad(agent): theta = np.random.rand(agent.nS, agent.nA) delta_theta = 1e-2 * np.random.rand(agent.nS, agent.nA) state = 0 values1, grad1 = agent.plan(state, theta) values2, grad2 = agent.plan(state, theta + delta_theta) assert np.allclose(values2 - values1, np.tensordot(grad1, delta_theta, axes=2)) def test_policy_grad(agent): theta = np.random.rand(agent.nS, agent.nA) delta_theta = 1e-3 * np.random.rand(agent.nS, agent.nA) state = 0 for action in range(5): values1, value_grad1 = agent.plan(state, theta) logprobas1 = np.log(agent.policy(values1)) values2, value_grad2 = agent.plan(state, theta + delta_theta) logprobas2 = np.log(agent.policy(values2)) grad = agent.logpolicy_grad(value_grad1, agent.policy(values1), action) assert np.allclose(logprobas2[action] - logprobas1[action], (grad * delta_theta).sum()) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T08:36:39.947", "Id": "253992", "Score": "2", "Tags": [ "python", "machine-learning", "multiprocessing" ], "Title": "Implementation of Policy Gradient Reward Design paper" }
253992
<p>Over the holidays I played around with coroutines and their use as two-in-one getter and setter methods:</p> <pre><code>#! /usr/bin/env python3 # coroproperty.py - Coroutine-based two-in-one properties. # # Copyright (C) 2020 Richard Neumann &lt;mail at richard dash neumann period de&gt; # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see &lt;https://www.gnu.org/licenses/&gt;. &quot;&quot;&quot;Coroutine-based two-in-one decorator.&quot;&quot;&quot; from contextlib import suppress from math import pi, sqrt from typing import Any, Callable def coroproperty(method: Callable) -&gt; property: &quot;&quot;&quot;Single decorator for getter and setter methods.&quot;&quot;&quot; def getter(self) -&gt; Any: &quot;&quot;&quot;Property getter function.&quot;&quot;&quot; coro = method(self) value = next(coro) coro.close() return value def setter(self, value: Any): &quot;&quot;&quot;Property setter function.&quot;&quot;&quot; coro = method(self) next(coro) next(coro) with suppress(StopIteration): coro.send(value) return property(getter, setter) class Circle: &quot;&quot;&quot;Information about a circle.&quot;&quot;&quot; def __init__(self, radius: float): &quot;&quot;&quot;Initializes the circle with its radius.&quot;&quot;&quot; self.radius = radius @coroproperty def diameter(self): &quot;&quot;&quot;Gets and sets the diameter.&quot;&quot;&quot; yield self.radius * 2 self.radius = (yield) / 2 @coroproperty def circumference(self): &quot;&quot;&quot;Gets and sets the circumference.&quot;&quot;&quot; yield self.diameter * pi self.diameter = (yield) / pi @coroproperty def area(self): &quot;&quot;&quot;Gets and sets the area.&quot;&quot;&quot; yield pow(self.radius, 2) * pi self.radius = sqrt((yield) / pi) </code></pre> <p>The downsides I already discovered are, that each <code>set</code> access implies that an unused <code>get</code> is performed before. Furthermore, these decorators are significantly slower than a &quot;classical&quot; property with separate <a href="https://gist.github.com/conqp/48e517dc926b77888d2fd52b9e28103f" rel="nofollow noreferrer">getter and setter methods</a>:</p> <pre><code>Coro get: 0.2394869327545166 Classic get: 0.09408378601074219 Ratio coro / classic: 2.5454644515174247 Coro set: 0.7087152004241943 Classic set: 0.10921454429626465 Ratio coro / classic: 6.489201644257868 </code></pre> <p>What other side-effects could arise when using these kind of properties?</p> <p>Note that this code is not intended for use in productive environments, but is of academic interest only.</p>
[]
[ { "body": "<p>The proper way to prime a generator for accepting values is to send an initial <code>None</code> value.</p>\n<p>Yield will simultaneously return a value to the caller, and accept a value sent from the caller.</p>\n<p>Using those two facts, you could rewrite the code like:</p>\n<pre class=\"lang-py prettyprint-override\"><code>...\n\ndef coroproperty(method: Callable) -&gt; property:\n\n ...\n\n def setter(self, value: Any) -&gt; None:\n coro = method(self)\n coro.send(None)\n with suppress(StopIteration):\n coro.send(value)\n\n ...\n\nclass Circle:\n\n ...\n\n @coroproperty\n def diameter(self):\n self.radius = (yield self.radius * 2) / 2\n\n ...\n</code></pre>\n<h1>Side-effects</h1>\n<p>Wasted time and computation. Setting the diameter, circumference and/or area first involves computing those quantities, which is unnecessary.</p>\n<p>You could circumvent that by accepting a new value before returning the value.</p>\n<pre class=\"lang-py prettyprint-override\"><code> @coroproperty\n def diameter(self):\n diameter = yield None\n if diameter is not None:\n self.radius = diameter / 2\n else:\n yield self.radius * 2\n</code></pre>\n<p>The getter would need to call <code>next(coro)</code> twice, ignoring the first returned value: <code>None</code>.</p>\n<p>If you desired a property which could store <code>None</code>, you'd need to create and use your own sentinel value.</p>\n<hr />\n<p>Assignment to diameter, even if not changing the value, will change the radius. In this example, it is changed from an <code>int</code> to a <code>float</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; c.radius = 100\n&gt;&gt;&gt; c.radius\n100\n&gt;&gt;&gt; c.diameter = c.diameter\n&gt;&gt;&gt; c.radius\n100.0\n</code></pre>\n<p>Add in <code>sqrt</code>, and multiplication &amp; division by π, and accuracy can be lost:</p>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; c.radius = 1_000_000_000_000\n&gt;&gt;&gt; c.area = c.area\n&gt;&gt;&gt; c.radius\n999999999999.9999\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T21:25:39.533", "Id": "254009", "ParentId": "253994", "Score": "3" } } ]
{ "AcceptedAnswerId": "254009", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T11:21:13.700", "Id": "253994", "Score": "3", "Tags": [ "python", "python-3.x", "generator", "properties" ], "Title": "Coroutine-based two-in-one properties" }
253994
<p>I solved the following Kata on Codewars: <a href="https://www.codewars.com/kata/58905bfa1decb981da00009e/train/cpp" rel="nofollow noreferrer">https://www.codewars.com/kata/58905bfa1decb981da00009e/train/cpp</a></p> <p>It was a lot of fun to solve it.</p> <p>Here everything you need to know so no need to use the link.</p> <blockquote> <p>Synopsis A multi-floor building has a Lift in it.</p> <p>People are queued on different floors waiting for the Lift.</p> <p>Some people want to go up. Some people want to go down.</p> <p>The floor they want to go to is represented by a number (i.e. when they enter the Lift this is the button they will press)</p> <pre><code>BEFORE (people waiting in queues) AFTER (people at their destinations) +--+ +--+ /----------------| |----------------\ /----------------| |----------------\ 10| | | 1,4,3,2 | 10| 10 | | | |----------------| |----------------| |----------------| |----------------| 9| | | 1,10,2 | 9| | | | |----------------| |----------------| |----------------| |----------------| 8| | | | 8| | | | |----------------| |----------------| |----------------| |----------------| 7| | | 3,6,4,5,6 | 7| | | | |----------------| |----------------| |----------------| |----------------| 6| | | | 6| 6,6,6 | | | |----------------| |----------------| |----------------| |----------------| 5| | | | 5| 5,5 | | | |----------------| |----------------| |----------------| |----------------| 4| | | 0,0,0 | 4| 4,4,4 | | | |----------------| |----------------| |----------------| |----------------| 3| | | | 3| 3,3 | | | |----------------| |----------------| |----------------| |----------------| 2| | | 4 | 2| 2,2,2 | | | |----------------| |----------------| |----------------| |----------------| 1| | | 6,5,2 | 1| 1,1 | | | |----------------| |----------------| |----------------| |----------------| G| | | | G| 0,0,0 | | | |====================================| |====================================| </code></pre> <p><strong>Rules</strong></p> <p><strong>Lift Rules</strong></p> <ul> <li><p>The Lift only goes up or down!</p> </li> <li><p>Each floor has both UP and DOWN Lift-call buttons (except top and ground floors which have only DOWN and UP respectively)</p> </li> <li><p>The Lift never changes direction until there are no more people wanting to get on/off in the direction it is already travelling</p> </li> <li><p>When empty the Lift tries to be smart. For example,</p> </li> <li><p>If it was going up then it may continue up to collect the highest floor person wanting to go down</p> </li> <li><p>If it was going down then it may continue down to collect the lowest floor person wanting to go up</p> </li> <li><p>The Lift has a maximum capacity of people</p> </li> <li><p>When called, the Lift will stop at a floor even if it is full, although unless somebody gets off nobody else can get on!</p> </li> <li><p>If the lift is empty, and no people are waiting, then it will return to the ground floor</p> </li> </ul> <p><strong>People Rules</strong></p> <ul> <li><p>People are in &quot;queues&quot; that represent their order of arrival to wait for the Lift</p> </li> <li><p>All people can press the UP/DOWN Lift-call buttons</p> </li> <li><p>Only people going the same direction as the Lift may enter it</p> </li> <li><p>Entry is according to the &quot;queue&quot; order, but those unable to enter do not block those behind them that can</p> </li> <li><p>If a person is unable to enter a full Lift, they will press the UP/DOWN Lift-call button again after it has departed without them</p> </li> </ul> <p><strong>Kata Task</strong></p> <ul> <li><p>Get all the people to the floors they want to go to while obeying the Lift rules and the People rules</p> </li> <li><p>Return a list of all floors that the Lift stopped at (in the order visited!)</p> </li> </ul> <p>NOTE: The Lift always starts on the ground floor (and people waiting on the ground floor may enter immediately)</p> <p><strong>I/O</strong></p> <p><strong>Input</strong></p> <ul> <li><p>queues a list of queues of people for all floors of the building.</p> </li> <li><p>The height of the building varies</p> </li> <li><p>0 = the ground floor</p> </li> <li><p>Not all floors have queues</p> </li> <li><p>Queue index [0] is the &quot;head&quot; of the queue</p> </li> <li><p>Numbers indicate which floor the person wants go to</p> </li> <li><p>capacity maximum number of people allowed in the lift</p> </li> <li><p>Parameter validation - All input parameters can be assumed OK. No need to check for things like:</p> <ul> <li>People wanting to go to floors that do not exist</li> <li>People wanting to take the Lift to the floor they are already on</li> <li>Buildings with &lt; 2 floors</li> <li>Basements</li> </ul> </li> </ul> <p>Output</p> <p>A list of all floors that the Lift stopped at (in the order visited!)</p> </blockquote> <p>I solved this with C++. Here is the code with basic tests:</p> <pre><code>#include &lt;algorithm&gt; #include &lt;cassert&gt; #include &lt;vector&gt; #include &lt;optional&gt; #include &lt;set&gt; enum class Direction{ up, down }; using Queues = std::vector&lt;std::vector&lt;int&gt;&gt;; bool queuesEmpty(Queues&amp; queues) { for(const auto&amp; queue : queues) { if(!queue.empty()) { return false; } } return true; } void movePeopleIntoLift(std::multiset&lt;int&gt;&amp; passengers, std::vector&lt;int&gt;&amp; peopleOnFloor, std::vector&lt;int&gt;&amp; newPassengers) { for(const auto&amp; newPassenger : newPassengers) { peopleOnFloor.erase(std::find(peopleOnFloor.begin(), peopleOnFloor.end(), newPassenger)); } for(const auto&amp; newPassenger : newPassengers) { passengers.insert(newPassenger); } } std::optional&lt;int&gt; highestFloorAboveLiftPushedDown(int liftPos, const Queues&amp; queues) { for(std::size_t i = queues.size() -1; i != static_cast&lt;std::size_t&gt;(liftPos); --i) { for(const auto&amp; person : queues[i]) { if(person &lt; i) { // person wants to go down return {i}; } } } return {}; } std::optional&lt;int&gt; nextFloorAboveLiftPushedUp( int liftPos, const Queues&amp; queues) { if(std::size_t(liftPos) &gt;= queues.size() - 2) { return {}; } for(std::size_t i = liftPos + 1; i &lt; queues.size(); ++i) { for(const auto&amp; person : queues[i]) { if(person &gt; i) { return {i}; } } } return {}; } std::optional&lt;int&gt; nextFloorUnderLiftPushedDown( int liftPos, const Queues&amp; queues) { if(liftPos &lt;= 1) { return {}; } for(std::size_t i = liftPos - 1; i!= std::size_t(0) - 1; --i) { for(const auto&amp; person : queues[i]) { if(person &lt; i) { return {i}; } } } return {}; } std::optional&lt;int&gt; lowestFloorUnderLiftPushedUp(int liftPos, const Queues&amp; queues) { for(std::size_t i = 0; i &lt; static_cast&lt;std::size_t&gt;(liftPos); ++i) { for(const auto&amp; person : queues[i]) { if(person &gt; i) { // person wants to go up return {i}; } } } return {}; } std::optional&lt;int&gt; passengerDestinationLowerThanLiftPos(int liftPos, const std::multiset&lt;int&gt;&amp; passengers) { auto it = std::find_if(passengers.crbegin(), passengers.crend(), [curr = liftPos](int passenger){ return passenger &lt; curr; }); if(it != passengers.crend()) { return {*it}; } return {}; } std::optional&lt;int&gt; passengerDestinationHigherThanLiftPos(int liftPos, const std::multiset&lt;int&gt;&amp; passengers) { auto it = std::find_if(passengers.cbegin(), passengers.cend(), [curr = liftPos](int passenger){ return passenger &gt; curr; }); if(it != passengers.cend()) { return {*it}; } return {}; } class Lift{ public: Lift(const Queues&amp; queues, int capacity); void emptyQueues(); std::vector&lt;int&gt; visitedFloors() const; private: void releasePassengersWithCurrentFloorDestination(); void goUp(); void addPeopleWhoWantToGoUp(std::vector&lt;int&gt;&amp; peopleOnFloor); bool goUpWithoutPassengers(); bool goUpToNextFloorPushedUp(); bool goUpToHighestFloorPushedDown(); void goUpWithPassengers(); int getNextFloorUpWithPerson() const; void goDown(); void addPeopleWhoWantToGoDown(std::vector&lt;int&gt;&amp; peopleOnFloor); bool goDownWithoutPassengers(); bool goDownToNextFloorPushedDown(); bool goDownToLowestFloorPushedUp(); void goDownWithPassengers(); int getNextFloorDownWithPerson() const; void arriveToFloor(int floor); int currentFloor() const; void changeDirection(); Direction direction() const; std::multiset&lt;int&gt; mPassangers{}; std::vector&lt;int&gt; mVisitedFloors{}; Direction mDirection = Direction::up; int mCurrentFloor = 0; int mCapacity; Queues mQueues; }; Lift::Lift(const Queues&amp; queues, int capacity) :mQueues{queues}, mCapacity{capacity} { } void Lift::emptyQueues() { arriveToFloor(0); bool goToStartPosition = false; for(;;) { while(mDirection == Direction::up) { goUp(); } while(mDirection == Direction::down) { goDown(); if(queuesEmpty(mQueues) &amp;&amp; mPassangers.empty()) { goToStartPosition = true; break; } } if(goToStartPosition) { break; } } if(mCurrentFloor != 0) { arriveToFloor(0); } } std::vector&lt;int&gt; Lift::visitedFloors() const { return mVisitedFloors; } void Lift::releasePassengersWithCurrentFloorDestination() { mPassangers.erase(mCurrentFloor); } void Lift::goUp() { releasePassengersWithCurrentFloorDestination(); addPeopleWhoWantToGoUp(mQueues[mCurrentFloor]); if(mPassangers.empty()) { if(goUpToNextFloorPushedUp()) { return; } if(goUpToHighestFloorPushedDown()) { changeDirection(); addPeopleWhoWantToGoDown(mQueues[mCurrentFloor]); return; } changeDirection(); } else { goUpWithPassengers(); } } void Lift::addPeopleWhoWantToGoUp(std::vector&lt;int&gt;&amp; peopleOnFloor) { std::vector&lt;int&gt; newPassengers; for(const auto&amp; person : peopleOnFloor) { if(newPassengers.size() + mPassangers.size() &gt;= mCapacity) { break; } if(person &gt; mCurrentFloor) { newPassengers.push_back(person); } } movePeopleIntoLift(mPassangers, peopleOnFloor, newPassengers); } bool Lift::goUpToNextFloorPushedUp() { auto optNextFloorUp = nextFloorAboveLiftPushedUp( mCurrentFloor, mQueues); if(optNextFloorUp) { arriveToFloor(*optNextFloorUp); return true; } return false; } bool Lift::goUpToHighestFloorPushedDown() { auto optHighestFloorDown = highestFloorAboveLiftPushedDown( mCurrentFloor, mQueues); if(optHighestFloorDown) { arriveToFloor(*optHighestFloorDown); return true; } return false; } void Lift::goUpWithPassengers() { auto higherFloor = getNextFloorUpWithPerson(); arriveToFloor(higherFloor); } int Lift::getNextFloorUpWithPerson() const { auto itPosPassengerUp = std::find_if(mPassangers.cbegin(), mPassangers.cend(), [curr = mCurrentFloor](const auto&amp; val) { return val &gt; curr; } ); // there should be always a person who wants to get higher assert(itPosPassengerUp != mPassangers.cend()); auto optPosUp = nextFloorAboveLiftPushedUp( mCurrentFloor, mQueues); if(optPosUp &amp;&amp; *optPosUp &lt; *itPosPassengerUp) { return *optPosUp; } return *itPosPassengerUp; } void Lift::goDown() { releasePassengersWithCurrentFloorDestination(); addPeopleWhoWantToGoDown(mQueues[mCurrentFloor]); if(mPassangers.empty()) { if(goDownToNextFloorPushedDown()) { return; } if(goDownToLowestFloorPushedUp()) { changeDirection(); addPeopleWhoWantToGoUp(mQueues[mCurrentFloor]); return; } if(!queuesEmpty(mQueues)) { changeDirection(); } } else { goDownWithPassengers(); } } void Lift::addPeopleWhoWantToGoDown(std::vector&lt;int&gt;&amp; peopleOnFloor) { std::vector&lt;int&gt; newPassengers; for(const auto&amp; person : peopleOnFloor) { if(newPassengers.size() + mPassangers.size() &gt;= mCapacity) { break; } if(person &lt; mCurrentFloor) { newPassengers.push_back(person); } } movePeopleIntoLift(mPassangers, peopleOnFloor, newPassengers); } bool Lift::goDownToNextFloorPushedDown() { auto optNextFloorDown = nextFloorUnderLiftPushedDown( mCurrentFloor, mQueues); if(optNextFloorDown) { arriveToFloor(*optNextFloorDown); return true; } return false; } bool Lift::goDownToLowestFloorPushedUp() { auto optLowestFloorUp = lowestFloorUnderLiftPushedUp( mCurrentFloor, mQueues); if(optLowestFloorUp) { arriveToFloor(*optLowestFloorUp); return true; } return false; } void Lift::goDownWithPassengers() { auto lowerFloor = getNextFloorDownWithPerson(); arriveToFloor(lowerFloor); } int Lift::getNextFloorDownWithPerson() const { auto itPosPassengerDown = std::find_if(mPassangers.crbegin(), mPassangers.crend(), [curr = mCurrentFloor](const auto&amp; val) { return val &lt; curr; } ); // there should be always a person who wants to get down assert(itPosPassengerDown != mPassangers.crend()); auto optPosDown = nextFloorUnderLiftPushedDown( mCurrentFloor, mQueues); if(optPosDown &amp;&amp; *optPosDown &gt; *itPosPassengerDown) { return *optPosDown; } return *itPosPassengerDown; } void Lift::arriveToFloor(int floor) { mCurrentFloor = floor; mVisitedFloors.push_back(mCurrentFloor); } int Lift::currentFloor() const { return mCurrentFloor; } void Lift::changeDirection() { if(mDirection == Direction::up) { mDirection = Direction::down; } else { mDirection = Direction::up; } } Direction Lift::direction() const { return mDirection; } std::vector&lt;int&gt; the_lift(std::vector&lt;std::vector&lt;int&gt;&gt; queues, int capacity) { Lift lift(queues, capacity); lift.emptyQueues(); return lift.visitedFloors(); } int main() { std::vector&lt;std::vector&lt;int&gt;&gt; queues; std::vector&lt;int&gt; result; // lift exactly full queues = { {}, {}, {5,5,5,5,5}, {}, {}, {}, {} }; result = {0, 2, 5, 0}; assert(the_lift(queues, 5) == result); // up queues = { {}, {}, {5,5,5}, {}, {}, {}, {} }; result = {0, 2, 5, 0}; assert(the_lift(queues, 5) == result); // down queues = { {}, {}, {1,1}, {}, {}, {}, {} }; result = {0, 2, 1, 0}; assert(the_lift(queues, 5) == result); // up and up queues = { {}, {3}, {4}, {}, {5}, {}, {} }; result = {0, 1, 2, 3, 4, 5, 0}; assert(the_lift(queues, 5) == result); // down and down queues = { {}, {0}, {}, {}, {2}, {3}, {} }; result = {0, 5, 4, 3, 2, 1, 0}; assert(the_lift(queues, 5) == result); // yoyo queues = { {}, {}, {4,4,4,4}, {}, {2, 2, 2, 2}, {}, {} }; result = {0, 2, 4, 2, 4, 2, 0}; assert(the_lift(queues, 2) == result); // lift full up queues = { {3, 3, 3, 3, 3, 3}, {}, {}, {}, {}, {}, {} }; result = {0, 3, 0, 3, 0}; assert(the_lift(queues, 5) == result); // lift full down queues = { {}, {}, {}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {}, {}, {} }; result = {0, 3, 1, 3, 1, 3, 1, 0}; assert(the_lift(queues, 5) == result); // lift full up and down queues = { {3, 3, 3, 3, 3, 3}, {}, {}, {}, {}, {4, 4, 4, 4, 4, 4 }, {} }; result = {0, 3, 5, 4, 0, 3, 5, 4, 0}; assert(the_lift(queues, 5) == result); // Tricky_queues queues = { {}, {0, 0, 0, 6}, {}, {}, {}, {6, 6, 0, 0, 0, 6}, {} }; result = {0, 1, 5, 6, 5, 1, 0, 1, 0}; assert(the_lift(queues, 5) == result); // Highlander queues = { {}, {2}, {3, 3, 3}, {1}, {}, {}, {} }; result = {0, 1, 2, 3, 1, 2, 3, 2, 3, 0}; assert(the_lift(queues, 1) == result); // Fire drill queues = { {}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0} }; result = {0, 6, 5, 4, 3, 2, 1, 0, 5, 4, 3, 2, 1, 0, 4, 3, 2, 1, 0, 3, 2, 1, 0, 1, 0}; assert(the_lift(queues, 5) == result); } </code></pre> <p>As a note. Codewars only allows one file per solution. That's why I have not separated the class in files.</p> <p>What do you think can be improved?</p> <p>Is the code easy to read?</p> <p>Could I have used more algorithms from the standard library?</p> <p>I feel like I needed a lot of code to get this working.</p> <p>My approach was like this:</p> <p>First solve the problem without the required capacity.</p> <p>Just for that I rewrote the whole thing like 2 or 3 times because I was missing some requirements.</p> <p>That let me pass the first few tests.</p> <p>I would also like some hints how its best to tackle a complex problem like this better.</p> <p>Then I added the capacity and went through the remaining tests. It was like maybe 2 hours of coding and 5h debugging and fixing to pass the tests.</p>
[]
[ { "body": "<h3>Standard Algorithms</h3>\n<p>You can make more use of standard algorithms. For one example consider your <code>queuesEmpty</code>:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>bool queuesEmpty(Queues&amp; queues)\n{\n for(const auto&amp; queue : queues) {\n if(!queue.empty()) {\n return false;\n }\n }\n return true;\n}\n</code></pre>\n<p>Given a choice, I'd probably write this more like:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>bool queuesEmpty(Queues&amp; queues) {\n return std::all_of(queues.begin(), queues.end(), [](auto const &amp;q) { return q.empty(); });\n}\n</code></pre>\n<p>[I'll probably add more later.]</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T10:37:42.607", "Id": "254026", "ParentId": "254000", "Score": "3" } }, { "body": "<p>Nice code. Your function names are very clear, and it's great to see the unit tests included with the code.</p>\n<p>Some tests I'm surprised not to see:</p>\n<ul>\n<li>see the trivial test, with no passengers waiting. That's the first test I would have written. Writing this test first helps get a good testable interface that can then be used to write the next-simplest test get that passing.</li>\n<li><strike>tests of capacity other than 5. Do we know that other capacities work? In particular, are passengers carried in the correct order of queueing?</strike></li>\n<li>tests with up passengers waiting behind down passengers, and vice versa.</li>\n</ul>\n<p>Here's a couple of extra tests:</p>\n<pre><code>// nothing to do\nqueues = { {} };\nresult = {0};\nassert(the_lift(queues, 1) == result);\n\n// lift full up and down, but don't block passengers\nqueues = { {}, {3,3,3,0,0,0,0,0,3}, {}, {1,1,1}, };\nresult = {0, 1, 3, 1, 0, 1, 3, 1, 0, 1, 0};\nassert(the_lift(queues, 2) == result);\n</code></pre>\n<p>And some that expose fragility in the code:</p>\n<pre><code>// no floors (seg fault)\nqueues = { };\nresult = {0};\nassert(the_lift(queues, 1) == result);\n\n// no capacity (infinite loop)\nqueues = { {1}, {} };\nresult = {0};\nassert(the_lift(queues, 0) == result);\n\n// passenger not changing floor (infinite loop)\nqueues = { {0} };\nresult = {0};\nassert(the_lift(queues, 1) == result);\n</code></pre>\n<p>One thing I would change about the tests is that they currently abort (using <code>assert()</code>) at the first failure. When writing or refactoring code, it's likely to cause multiple tests to fail, and that's useful information to identify the cause. I'd like to see all failures reported to <code>std::cerr</code> and the return value indicate whether all tests succeeded. That's what the usual test frameworks manage, and it's not hard to do.</p>\n<hr />\n<p>I get a few compiler warnings that could easily be fixed:</p>\n<pre class=\"lang-none prettyprint-override\"><code>g++ -std=c++2a -fconcepts -fPIC -g -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Weffc++ 254000.cpp -o 254000\n254000.cpp: In function ‘std::optional&lt;int&gt; highestFloorAboveLiftPushedDown(int, const Queues&amp;)’:\n254000.cpp:43:17: warning: comparison of integer expressions of different signedness: ‘const int’ and ‘std::size_t’ {aka ‘long unsigned int’} [-Wsign-compare]\n if(person &lt; i) { // person wants to go down\n ~~~~~~~^~~\n254000.cpp: In function ‘std::optional&lt;int&gt; nextFloorAboveLiftPushedUp(int, const Queues&amp;)’:\n254000.cpp:59:17: warning: comparison of integer expressions of different signedness: ‘const int’ and ‘std::size_t’ {aka ‘long unsigned int’} [-Wsign-compare]\n if(person &gt; i) {\n ~~~~~~~^~~\n254000.cpp: In function ‘std::optional&lt;int&gt; nextFloorUnderLiftPushedDown(int, const Queues&amp;)’:\n254000.cpp:75:17: warning: comparison of integer expressions of different signedness: ‘const int’ and ‘std::size_t’ {aka ‘long unsigned int’} [-Wsign-compare]\n if(person &lt; i) {\n ~~~~~~~^~~\n254000.cpp: In function ‘std::optional&lt;int&gt; lowestFloorUnderLiftPushedUp(int, const Queues&amp;)’:\n254000.cpp:90:17: warning: comparison of integer expressions of different signedness: ‘const int’ and ‘std::size_t’ {aka ‘long unsigned int’} [-Wsign-compare]\n if(person &gt; i) { // person wants to go up\n ~~~~~~~^~~\n254000.cpp: In constructor ‘Lift::Lift(const Queues&amp;, int)’:\n254000.cpp:172:10: warning: ‘Lift::mQueues’ will be initialized after [-Wreorder]\n Queues mQueues;\n ^~~~~~~\n254000.cpp:170:7: warning: ‘int Lift::mCapacity’ [-Wreorder]\n int mCapacity;\n ^~~~~~~~~\n254000.cpp:175:1: warning: when initialized here [-Wreorder]\n Lift::Lift(const Queues&amp; queues, int capacity)\n ^~~~\n254000.cpp: In member function ‘void Lift::addPeopleWhoWantToGoUp(std::vector&lt;int&gt;&amp;)’:\n254000.cpp:240:50: warning: comparison of integer expressions of different signedness: ‘std::vector&lt;int&gt;::size_type’ {aka ‘long unsigned int’} and ‘int’ [-Wsign-compare]\n if(newPassengers.size() + mPassangers.size() &gt;= mCapacity) {\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~\n254000.cpp: In member function ‘void Lift::addPeopleWhoWantToGoDown(std::vector&lt;int&gt;&amp;)’:\n254000.cpp:326:50: warning: comparison of integer expressions of different signedness: ‘std::vector&lt;int&gt;::size_type’ {aka ‘long unsigned int’} and ‘int’ [-Wsign-compare]\n if(newPassengers.size() + mPassangers.size() &gt;= mCapacity) {\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~\n</code></pre>\n<p>I think we should use an unsigned type for the floor number throughout (probably <code>std::size_t</code>; it might be worth writing a type alias, <code>using Floor = std::size_t;</code>).</p>\n<hr />\n<p>There's quite a bit of duplication between &quot;up&quot; and &quot;down&quot; functions that could be reduced. For example,</p>\n<blockquote>\n<pre><code>int Lift::getNextFloorUpWithPerson() const\n{\n auto itPosPassengerUp = std::find_if(mPassangers.cbegin(), mPassangers.cend(), \n [curr = mCurrentFloor](const auto&amp; val)\n {\n return val &gt; curr;\n }\n );\n\n // there should be always a person who wants to get higher\n assert(itPosPassengerUp != mPassangers.cend());\n \n auto optPosUp = nextFloorAboveLiftPushedUp(\n mCurrentFloor, mQueues);\n if(optPosUp &amp;&amp; *optPosUp &lt; *itPosPassengerUp) {\n return *optPosUp;\n }\n return *itPosPassengerUp;\n}\n\nint Lift::getNextFloorDownWithPerson() const\n{\n auto itPosPassengerDown = std::find_if(mPassangers.crbegin(), mPassangers.crend(), \n [curr = mCurrentFloor](const auto&amp; val)\n {\n return val &lt; curr;\n }\n );\n // there should be always a person who wants to get down\n assert(itPosPassengerDown != mPassangers.crend());\n\n auto optPosDown = nextFloorUnderLiftPushedDown(\n mCurrentFloor, mQueues);\n if(optPosDown &amp;&amp; *optPosDown &gt; *itPosPassengerDown) {\n return *optPosDown;\n }\n return *itPosPassengerDown;\n}\n</code></pre>\n</blockquote>\n<p>These could be combined with a small helper function, especially if we change <code>Direction</code> to be integer-based and define <code>up</code> as 1 and <code>down</code> as -1:</p>\n<pre><code>enum Direction{\n up = 1,\n down = -1,\n};\n\ntemplate&lt;typename Iter&gt;\nint Lift::getNextFloorWithPerson(Iter first, Iter last) const\n{\n auto const next_passenger_iter =\n std::find_if(first, last,\n [this](const auto&amp; val) { return val * mDirection &gt; mCurrentFloor * mDirection; });\n\n // there should be always a person who wants to get higher\n assert(next_passenger_iter != last);\n\n for (int i = mCurrentFloor + mDirection; i != *next_passenger_iter; i += mDirection) {\n // is there a person waiting between, going our direction?\n if (std::any_of(mQueues[i].cbegin(), mQueues[i].cend(),\n [i,this](auto const&amp; person){ return person * mDirection &gt; i * mDirection; })) {\n return i;\n }\n }\n return *next_passenger_iter;\n}\n</code></pre>\n<p>And we can inline the uses in the one place each they are called:</p>\n<pre><code>void Lift::goUpWithPassengers()\n{\n auto higherFloor = getNextFloorWithPerson(mPassangers.cbegin(), mPassangers.cend());\n arriveToFloor(higherFloor);\n}\n\nvoid Lift::goDownWithPassengers()\n{\n auto lowerFloor = getNextFloorWithPerson(mPassangers.crbegin(), mPassangers.crend());\n arriveToFloor(lowerFloor);\n}\n</code></pre>\n<hr />\n<p>There might be value in splitting the queues at each floor into two: one for upward passengers, and one for downward passengers.</p>\n<hr />\n<p>Trivial: spelling <code>mPassangers</code> → <code>mPassengers</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T14:31:11.077", "Id": "501002", "Score": "0", "body": "Thanks for the feedback. I agree its quite basic to use only asserts as tests. In a real project I would use something like gtest framework for the test." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T14:33:33.680", "Id": "501003", "Score": "0", "body": "some test like the no Floor test I did not bother because the description above in I/O explicitly states that the building will be never < 2 floors." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T14:38:42.677", "Id": "501004", "Score": "0", "body": "Sure, we could skip testing the invalid input cases. But I often understand my code better if I check for such cases and deal with them explicitly. It's a personal preference, and I wouldn't reject the code on that basis. TBH, I misread that, but I've edited the question to make the formatting clearer." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T12:09:57.347", "Id": "254034", "ParentId": "254000", "Score": "4" } }, { "body": "<p>To answer the question, &quot;how to go about solving problems like this&quot;, here's a work-through of how I would approach it.</p>\n<p>Start with the simplest test you can think of and ensure that it fails. For me, that's a single queue, which is empty. Most of the work here is in creating the test framework, to print the code location and failing values (which I wouldn't normally have to write, if using an existing test framework). The rest is in creating the interface to the class under test.</p>\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;cstdlib&gt;\n#include &lt;cstddef&gt;\n#include &lt;iostream&gt;\n#include &lt;iterator&gt;\n#include &lt;source_location&gt;\n#include &lt;vector&gt;\n\nusing Floor = std::size_t;\n \n// return zero on success, or non-zero on failure\nstatic int test_lift(std::size_t capacity,\n const std::vector&lt;std::vector&lt;Floor&gt;&gt;&amp; queues,\n const std::vector&lt;Floor&gt;&amp; expect_visited,\n const std::source_location&amp; location = std::source_location::current())\n{\n Lift lift(capacity, queues);\n lift.emptyQueues();\n const auto actual_visited = lift.visitedFloors();\n if (actual_visited == expect_visited) {\n return 0; // success\n }\n std::cerr &lt;&lt; location.file_name() &lt;&lt; ':' &lt;&lt; location.line() &lt;&lt; &quot;: FAIL: expected {&quot;;\n std::copy(expect_visited.begin(), expect_visited.end(),\n std::ostream_iterator&lt;Floor&gt;{std::cerr,&quot;,&quot;});\n std::cerr &lt;&lt; &quot;} but got {&quot;;\n std::copy(actual_visited.begin(), actual_visited.end(),\n std::ostream_iterator&lt;Floor&gt;{std::cerr,&quot;,&quot;});\n std::cerr &lt;&lt; &quot;}\\n&quot;;\n return 1;\n}\n\n\nint main()\n{\n int failures = 0;\n\n failures += test_lift(1, {{}}, {0});\n\n if (!failures) {\n return EXIT_SUCCESS;\n }\n std::cerr &lt;&lt; failures &lt;&lt; &quot; failures reported.\\n&quot;;\n return EXIT_FAILURE;\n}\n</code></pre>\n<p>Now write the minimal <code>Lift</code> class that enables the test to compile:</p>\n<pre><code>class Lift\n{\npublic:\n Lift(std::size_t capacity,\n const std::vector&lt;std::vector&lt;Floor&gt;&gt; queues)\n {}\n\n void emptyQueues()\n {}\n\n std::vector&lt;Floor&gt; visitedFloors() const\n {\n return {};\n }\n};\n</code></pre>\n<p>The test will fail (important - otherwise how do we know the test itself works?), and we can change <code>visitedFloors()</code> to make it pass:</p>\n<pre><code> std::vector&lt;Floor&gt; visitedFloors() const\n {\n return {0};\n }\n</code></pre>\n<p>Now it's time to add our next failing test:</p>\n<pre><code>failures += test_lift(1, {{}}, {0});\nfailures += test_lift(1, {{1}, {}}, {0,1,0});\n</code></pre>\n<p>We need to do more work to make this one pass:</p>\n<pre><code>#include &lt;utility&gt;\n\nclass Lift\n{\n const std::size_t capacity;\n std::vector&lt;std::vector&lt;Floor&gt;&gt; queues;\n std::vector&lt;Floor&gt; visited= { 0 };\n Floor current = 0;\n\npublic:\n Lift(std::size_t capacity,\n const std::vector&lt;std::vector&lt;Floor&gt;&gt; queues)\n : capacity{capacity},\n queues{std::move(queues)}\n {}\n\n void emptyQueues()\n {\n // go up and down once\n while (current &lt; queues.size() - 1) {\n ++current;\n visited.push_back(current);\n }\n while (current &gt; 0) {\n --current;\n visited.push_back(current);\n }\n }\n\n const std::vector&lt;Floor&gt;&amp; visitedFloors() const\n {\n return visited;\n }\n};\n</code></pre>\n<p>Although we have made this test pass, we know it's not correct. We're stopping on every floor, not just the requested ones. Let's add a test that we don't stop everywhere:</p>\n<pre><code>failures += test_lift(1, {{2}, {}, {}}, {0,2,0});\n</code></pre>\n<p>And make it pass, then fix the tests we broke:</p>\n<pre><code>#include &lt;set&gt;\n\n\nclass Lift\n{\n // ...\n std::multiset&lt;Floor&gt; passengers = {};\n\n // ...\n void emptyQueues()\n {\n // get ground-floor passengers\n passengers.insert(queues[0].begin(), queues[0].end());\n while (!passengers.empty()) {\n // go up and down once\n while (current &lt; queues.size() - 1) {\n ++current;\n if (passengers.count(current) &gt; 0) {\n visited.push_back(current);\n passengers.erase(current);\n }\n }\n while (current &gt; 0) {\n --current;\n if (passengers.count(current) &gt; 0) {\n visited.push_back(current);\n }\n }\n }\n // return to ground floor\n if (visited.back() != 0) {\n visited.push_back(0);\n }\n }\n</code></pre>\n<p>Now, let's add tests that exceed the lift capacity:</p>\n<pre><code>failures += test_lift(1, {{1,1}, {}}, {0,1,0,1,0});\nfailures += test_lift(1, {{1,2}, {}, {}}, {0,1,0,2,0});\nfailures += test_lift(1, {{2,1}, {}, {}}, {0,2,0,1,0});\n</code></pre>\n<p>The last two of these ensure that we pick up passengers in the correct order.</p>\n<p>I'm going to add a private function to transfer passengers from the queue to the lift, as we'll need this in a few places:</p>\n<pre><code>void add_passengers(std::vector&lt;Floor&gt;&amp; queue)\n{\n auto const add_one =\n [this](Floor requested) {\n if (passengers.size() &gt;= capacity) {\n return false;\n }\n passengers.insert(requested);\n return true;\n };\n queue.erase(std::remove_if(queue.begin(), queue.end(), add_one), queue.end());\n}\n</code></pre>\n<p>And use it in <code>emptyQueues</code>:</p>\n<pre><code>void emptyQueues()\n{\n // get ground-floor passengers\n add_passengers(queues[0]);\n while (!passengers.empty()) {\n // go up and down once\n while (current &lt; queues.size() - 1) {\n ++current;\n if (passengers.count(current) &gt; 0 || !queues[current].empty()) {\n visited.push_back(current);\n passengers.erase(current);\n add_passengers(queues[current]);\n }\n }\n while (current &gt; 0) {\n --current;\n if (passengers.count(current) &gt; 0 || !queues[current].empty()) {\n visited.push_back(current);\n passengers.erase(current);\n add_passengers(queues[current]);\n }\n }\n }\n // return to ground floor\n if (visited.back() != 0) {\n visited.push_back(0);\n }\n}\n</code></pre>\n<p>Now we're picking up passengers at all floors, but we need to be selective about their direction of travel. Again, write some tests:</p>\n<pre><code>failures += test_lift(1, {{}, {0,2}, {}}, {0,1,2,1,0});\n</code></pre>\n<p>This one failed right away because we're still only moving if we have passengers. So change the condition to also move if there are any queues waiting:</p>\n<pre><code> while (!passengers.empty() || any_waiting()) {\n</code></pre>\n<p>And implement the function:</p>\n<pre><code>private:\n bool any_waiting() const\n {\n return std::any_of(queues.begin(), queues.end(),\n [](auto&amp; q){ return !q.empty() });\n }\n</code></pre>\n<p>I think I've shown enough now how to solve smaller problems and build up to the full solution a test at a time.</p>\n<hr />\n<p>After implementing the rest of the code, and a couple of rounds of refactoring, I ended up with:</p>\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;cstddef&gt;\n#include &lt;iterator&gt;\n#include &lt;set&gt;\n#include &lt;vector&gt;\n\nusing Floor = std::size_t;\n\nclass Lift\n{\n const std::size_t capacity;\n std::vector&lt;std::vector&lt;Floor&gt;&gt; up_queue = {};\n std::vector&lt;std::vector&lt;Floor&gt;&gt; down_queue = {};\n std::vector&lt;Floor&gt; visited= { 0 };\n std::multiset&lt;Floor&gt; passengers = {};\n\n bool any_waiting() const\n {\n return std::any_of(up_queue.begin(), up_queue.end(),\n [](auto&amp; q){ return !q.empty(); })\n || std::any_of(down_queue.begin(), down_queue.end(),\n [](auto&amp; q){ return !q.empty(); });\n }\n\n void visit_floor(Floor floor, std::vector&lt;Floor&gt;&amp; queue)\n {\n // if there's waiting passengers, we have to stop, even if no-one can get on\n bool have_visited = passengers.erase(floor) &gt; 0 || !queue.empty();\n if (have_visited &amp;&amp; visited.back() != floor) {\n // yes, we stopped here\n visited.push_back(floor);\n }\n // now move passengers from queue\n auto const add_one =\n [this](Floor requested) {\n if (passengers.size() &gt;= capacity) { return false; }\n passengers.insert(requested);\n return true;\n };\n queue.erase(std::remove_if(queue.begin(), queue.end(), add_one), queue.end());\n }\n\npublic:\n Lift(std::size_t capacity,\n const std::vector&lt;std::vector&lt;Floor&gt;&gt; queues)\n : capacity{capacity}\n {\n // split the input into up traffic and down traffic\n auto floors = queues.size();\n up_queue.resize(floors);\n down_queue.resize(floors);\n for (std::size_t actual = 0; actual &lt; floors; ++actual) {\n std::vector&lt;Floor&gt;&amp; up = up_queue[actual];\n std::vector&lt;Floor&gt;&amp; down = down_queue[actual];\n for (auto wanted: queues[actual]) {\n if (wanted &lt; actual) {\n down.push_back(wanted);\n } else if (actual &lt; wanted &amp;&amp; wanted &lt; floors) {\n up.push_back(wanted);\n }\n }\n }\n }\n\n void emptyQueues()\n {\n Floor current = 0;\n while (!passengers.empty() || any_waiting()) {\n // go up and down once\n while (current &lt; up_queue.size() - 1) {\n visit_floor(current, up_queue[current]);\n ++current;\n }\n while (current &gt; 0) {\n visit_floor(current, down_queue[current]);\n --current;\n }\n }\n // return to ground floor\n if (visited.back() != 0) {\n visited.push_back(0);\n }\n }\n\n const std::vector&lt;Floor&gt;&amp; visitedFloors() const\n {\n return visited;\n }\n};\n</code></pre>\n<p>And the tests (slightly modified, to compile with C++17)</p>\n<pre><code>#include &lt;cstdlib&gt;\n#include &lt;iostream&gt;\n\n// return zero on success, or non-zero on failure\nstatic int test_lift(std::size_t capacity,\n const std::vector&lt;std::vector&lt;Floor&gt;&gt;&amp; queues,\n const std::vector&lt;Floor&gt;&amp; expect_visited)\n{\n Lift lift(capacity, queues);\n lift.emptyQueues();\n const auto actual_visited = lift.visitedFloors();\n if (actual_visited == expect_visited) {\n return 0; // success\n }\n std::cerr &lt;&lt; &quot;FAIL: expected {&quot;;\n std::copy(expect_visited.begin(), expect_visited.end(),\n std::ostream_iterator&lt;Floor&gt;{std::cerr,&quot;,&quot;});\n std::cerr &lt;&lt; &quot;} but got {&quot;;\n std::copy(actual_visited.begin(), actual_visited.end(),\n std::ostream_iterator&lt;Floor&gt;{std::cerr,&quot;,&quot;});\n std::cerr &lt;&lt; &quot;}\\n&quot;;\n return 1;\n}\n\n\nint main()\n{\n int failures = 0;\n failures += test_lift(1, {{}}, {0});\n failures += test_lift(1, {{1}, {}}, {0,1,0});\n failures += failures += test_lift(1, {{2}, {}, {}}, {0,2,0});\n failures += test_lift(1, {{1}, {}, {}}, {0,1,0});\n failures += test_lift(1, {{}, {}, {1}}, {0,2,1,0});\n failures += test_lift(1, {{}, {}, {1, 1}}, {0,2,1,2,1,0});\n failures += test_lift(1, {{1,1}, {}}, {0,1,0,1,0});\n failures += test_lift(1, {{}, {0,0}}, {0,1,0,1,0});\n failures += test_lift(1, {{1,2}, {}, {}}, {0,1,0,2,0});\n failures += test_lift(1, {{2,1}, {}, {}}, {0,2,0,1,0});\n failures += test_lift(1, {{}, {0,2}, {}}, {0,1,2,1,0});\n // lift full up and down\n failures += test_lift(2, {{3,3,3}, {}, {}, {}, {}, {4,4,4}, {}},\n {0,3,5,4,0,3,5,4,0});\n // Highlander\n failures += test_lift(1, {{}, {2}, {3,3,3}, {1}, {}, {}, {}},\n {0,1,2,3,1,2,3,2,3,0});\n // queuing order\n failures += test_lift(2, {{}, {}, {4,1,4,3,1}, {}, {}},\n {0,2,4,2,1,2,3,0});\n // Fire drill\n failures += test_lift(5, {{}, {0,0,0,0}, {0,0,0,0}, {0,0,0,0}, {0,0,0,0}, {0,0,0,0}, {0,0,0,0}},\n {0,6,5,4,3,2,1,0,5,4,3,2,1,0,4,3,2,1,0,3,2,1,0,1,0});\n\n if (!failures) {\n return EXIT_SUCCESS;\n }\n std::cerr &lt;&lt; failures &lt;&lt; &quot; failures reported.\\n&quot;;\n return EXIT_FAILURE;\n}\n</code></pre>\n<p>Notes on this implementation:</p>\n<ul>\n<li>The most obvious thing is splitting the queues into &quot;up&quot; and &quot;down&quot; queues. I didn't do that straight away, but it soon made sense to filter the directions when we construct the <code>Lift</code> object.</li>\n<li>Instead of searching for the next floor to visit, we look at every floor on the way, and decide when we reach it whether or not to record a visit.</li>\n<li>I've tested for some of the invalid input cases that the challenge told us not to bother with. Although deemed unnecessary, some of these (asking for a non-existent floor, or for the passenger's current floor) were so easy to add in whilst splitting the queues, it seemed better to just clean the data as we went.</li>\n<li>There's still more that can be improved. For example, we consider every waiting passenger when we stop, even if we already know there's no more room. Perhaps when we split the queues, we could use <code>std::queue</code> for storage rather than <code>std::vector</code>, and replace the erase-remove with a simple <code>pop()</code> loop that finishes when no more passengers can be moved (because either the car is full or the queue is empty).</li>\n<li>We might refactor <code>if (visited.back() != floor) { visited.push_back(floor); }</code> into a small <code>record_visit()</code> function.</li>\n</ul>\n<hr />\n<p>Notes on the process:</p>\n<ul>\n<li>I've described how I would solve this, using a <a href=\"https://en.wikipedia.org/wiki/Test-driven_development\" rel=\"nofollow noreferrer\">Test-Driven Development</a> (TDD) approach. This is well suited to any problem which can be specified in terms of inputs and outputs.</li>\n<li>The mantra of TDD is &quot;Red - Green - REFACTOR&quot; and it's that <em>refactor</em> step (also called &quot;reduce complexity&quot; or &quot;remove duplications&quot;) that helps you get your code small and simple. It's worth spending more time on refactoring as you go; don't wait until you have all your tests in place, but do a little refactoring every iteration.</li>\n<li>The design is <em>emergent</em>, rather than planned. We don't start off knowing what structures we'll need to support the functionality until we get there. That helps keep the code simple, as we don't implement anything that we think we'll need later - just the things we actually do need.</li>\n<li>When we refactor, we only need to worry about keeping the existing tests passing, and not any future ones we haven't written yet. So we can make large changes to the interface early on, but that becomes more difficult once we've written a large body of tests. It makes sense to write tests that help define the interface at the beginning, and later to concentrate on those that nail down the implementation. That's why I like to start with tests of invalid inputs, where appropriate, rather than leaving the error reporting until last (I know this particular problem doesn't have any error reporting, but the princple still stands).</li>\n<li>It's not unusual to throw away the initial structure - that's what happens as you gain more insight into the problem space. So don't be dispirited when you do so - the work isn't wasted, despite how it looks (from outside of your head).</li>\n<li>We can make the steps larger, writing several tests at a time when we're confident we can make them pass in one go. But when the code gets difficult, we can always fall back to testing the smallest possible increment in each step, and that helps us to make perceptible progress even when we're struggling.</li>\n<li>On longer-term projects, I find it helpful to end the day with a <em>failing</em> test. That sounds counter-intuitive if you're used to tidying up when you finish, but the advantage is that you then start the next session with a clear place to start working; I find that helps me get back into the rhythm, without having to think what to implement next. Even on a one-afternoon program, it's a good state to leave things when you stop for a tea break!</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T15:33:20.380", "Id": "501005", "Score": "0", "body": "I kinda did it like that. I just started on an more complicated test and build up with that. I had like the first 3 test pass and realized then on the 4 test that my design was crap and reworked it because i could not pass the next test like it was. I also had a up and down queue before but I couldn't get it to work and throw it away. +Points for `source_location` I didn't knew about that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T18:48:10.517", "Id": "501015", "Score": "0", "body": "The XP mantra is \"Red - Green - REFACTOR\" and it's that *refactor* step (also called \"reduce complexity\" or \"remove duplications\") that helps you get your code small and simple. Perhaps spend more time on refactoring as you go; don't wait until you have all your tests in place, but do a little refactoring every iteration. With test-driven development like this, it's not unusual to throw away the initial structure - that's how you gain the most insight into the problem space. So don't be dispirited when you do so - the work isn't wasted, despite how it looks (from outside of your head)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T22:00:37.473", "Id": "501037", "Score": "1", "body": "This review is a good synopsis of [TDD](https://en.wikipedia.org/wiki/Test-driven_development)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T09:30:37.247", "Id": "501073", "Score": "0", "body": "Thanks @Edward; that's exactly what I wanted to convey. I've incorporated that link (and my long comment about TDD refactoring) into the answer now." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T15:17:18.297", "Id": "254040", "ParentId": "254000", "Score": "1" } } ]
{ "AcceptedAnswerId": "254034", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T18:14:06.397", "Id": "254000", "Score": "1", "Tags": [ "c++", "algorithm" ], "Title": "Implementing a Lift (Kata on Codewars)" }
254000
<p>I tried following the official solution of LC975 (<a href="https://leetcode.com/problems/odd-even-jump/" rel="nofollow noreferrer">https://leetcode.com/problems/odd-even-jump/</a>), using a monotonic stack - i.e., I reimplemented their solution (Approach 1) from python in C++.</p> <p>TLDR Problem statement: Given an array of ints A, &quot;good index&quot; is an index from which the last element of A can be reached, through a series of consecutive &quot;odd&quot; and &quot;even&quot; jumps. Odd jump (1st, 3rd, 5th jump) from index &quot;i&quot; is defined as jump to the smallest element to the right, greater or equal to the current element (A[i]); Even jump (2nd, 4th,...) -&gt; is defined as jump from index &quot;i&quot; to the largest element to the right, smaller or equal to the current element, A[i]. In case of equality, the element with the lowest index is chosen. Return the number of &quot;good&quot; indices.</p> <p>[Update]: Fixed a bug, passing A by reference instead of value, in the sort lambda -- which fixes the Time Limit Exceeded.</p> <pre><code>int oddEvenJumps(vector&lt;int&gt;&amp; A) { int N = static_cast&lt;int&gt;(A.size()); // Compute odd and even jump indices, i.e. where we can jump from here std::vector&lt;int&gt; odd_next(N, 0); std::vector&lt;int&gt; even_next(N, 0); // First, sort indices in A, by value. for (int ii = 0; ii &lt; N; ++ii) { odd_next[ii] = ii; even_next[ii] = ii; } // Sort indices in increasing order by value. std::sort(odd_next.begin(), odd_next.end(), [&amp;A](int a, int b) { if (A[a] == A[b]) { return a &lt; b;} else { return A[a] &lt; A[b]; } }); // Sort indices in decreasing order, for even jumps. //Update: previously -- [A](int a, int b) -- passed A by value -- which was slow. std::sort(even_next.begin(), even_next.end(), [&amp;A](int a, int b){ if (A[a] == A[b]) { return a &lt; b; } else { return A[a] &gt; A[b]; } }); // Convert the sorted indices into next jump index, // using a monotonic stack. odd_next = make_vec(odd_next); even_next = make_vec(even_next); // Store a flag if from the current index, through an odd jump or // even jump respectively, we can reach the last element. vector&lt;int&gt; odd(N, 0); vector&lt;int&gt; even(N, 0); odd[N - 1] = 1; even[N - 1] = 1; // Go backwards, and mark reachable elements. for (int ii = N - 2; ii &gt;= 0; --ii) { if (odd_next[ii] != -1) { odd[ii] = even[odd_next[ii]]; } if (even_next[ii] != -1) { even[ii] = odd[even_next[ii]]; } } int res = 0; for (int jj = 0; jj &lt; N; ++jj){ res += odd[jj]; } return res; } // Use monotonic stack to find the element to jump to, i.e. // the closest larger or closest smaller element. inline std::vector&lt;int&gt; make_vec(const std::vector&lt;int&gt;&amp; v){ std::vector&lt;int&gt; result(v.size(), -1); stack&lt;int&gt; st; for (int x: v){ while (!st.empty() &amp;&amp; x &gt; st.top()) { result[st.top()] = x; st.pop(); } st.push(x); } return result; } </code></pre> <p>However, this implementation doesn't pass few tests, resulting in time limit exceeded. The complexity of the algorithm should be O(N log N), dominated by the two sort loops.</p> <p><code>make_vec</code> according to my understanding, is O(N), because each element in the vector gets on the stack only once.</p> <p>How could I improve this code, in particular performance?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T18:30:46.097", "Id": "254001", "Score": "1", "Tags": [ "c++", "algorithm", "complexity", "stack" ], "Title": "Monotonic stack - complexity analysis" }
254001
<p>My website has multiple pages that use the Google Maps api. Each page uses a different part of the api (e.g. autocomplete, displaying markers etc). However, every page needs to call the initMap() function for the api to be initialized. The logic that calls initMap() is controlled by google and it cannot take parameters.</p> <p>maps.js</p> <pre><code>function initMap() { const mapOptions = { center: {lat: 0, lng: 0}, zoom: 7 }; window.map = new google.maps.Map(document.getElementById(&quot;map&quot;), mapOptions); if (typeof callback !== 'undefined') { callback(); // defined above html link to maps.js } } </code></pre> <p>Instead of writing out a different initMap() function for every page, I opted to have it in one .js file which is linked to every page. After initializing the map, the function executes a callback function which is defined in each page's corresponding .js file.</p> <p>index.js</p> <pre><code>function autocomplete() { var input = document.getElementById('address'); new google.maps.places.Autocomplete(input); } </code></pre> <p>As initMap() cannot take parameters, I had to define the callback function's name using a cross-script global variable before maps.js is linked. This variable is different on every page depending what function needs to be run in initMap() after the map is initialized.</p> <pre><code>&lt;script type=&quot;text/javascript&quot; src=&quot;js/index.js&quot;&gt;&lt;/script&gt; &lt;script&gt; var callback = autocomplete &lt;/script&gt; &lt;!-- global variable, defines the callback function (in index.js) to initMap()(in maps.js) --&gt; &lt;script type=&quot;text/javascript&quot; src=&quot;js/maps.js&quot;&gt;&lt;/script&gt; </code></pre> <p>Is there a cleaner way to accomplish this?</p>
[]
[ { "body": "<p>You can avoid the global by creating a closure around the function to be called by the maps api code. To do this define another function that returns a function. You can pass in the callback here.</p>\n<p>The below code is runnable in single file but you will need to split it across pages in your real code.</p>\n<pre><code>function createInitMap(callback){\n return () =&gt; {\n const mapOptions = {\n center: {lat: 0, lng: 0},\n zoom: 7\n };\n window.map = new google.maps.Map(document.getElementById(&quot;map&quot;), mapOptions);\n \n if (typeof callback !== 'undefined') {\n callback();\n } \n }\n}\n\n/*\n In first page\n*/\n//&lt;script type=&quot;text/javascript&quot; src=&quot;js/index.js&quot;&gt;&lt;/script&gt;\nlet initMap = createInitMap(() =&gt; console.log('first callback'));\n//&lt;script type=&quot;text/javascript&quot; src=&quot;js/maps.js&quot;&gt;&lt;/script&gt;\n\ninitMap(); // simulate google maps calling your function\n\n/*\n In second page\n*/\n//&lt;script type=&quot;text/javascript&quot; src=&quot;js/index.js&quot;&gt;&lt;/script&gt;\ninitMap = createInitMap(() =&gt; console.log('second callback'));\n//&lt;script type=&quot;text/javascript&quot; src=&quot;js/maps.js&quot;&gt;&lt;/script&gt;\n\ninitMap(); // simulate google maps calling your function\n</code></pre>\n<p>Ensure the return value of the function is assigned to the global name <code>initMap</code> (It might need to be <code>window.initMap</code>).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T23:40:59.470", "Id": "254012", "ParentId": "254003", "Score": "1" } } ]
{ "AcceptedAnswerId": "254012", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T18:55:07.107", "Id": "254003", "Score": "2", "Tags": [ "javascript", "html", "google-maps" ], "Title": "Avoid global variable for callback function called by function with no arguments" }
254003
<p><a href="https://groups.google.com/g/comp.lang.c/c/kYOAuWbYND0/m/munZ47p0AwAJ" rel="nofollow noreferrer">Challenge posted 5 Dec 2020 to comp.lang.c</a> This program is essentially the same as my Version 8 posted to that thread, but with some further cosmetic improvements.</p> <p>This program reads from stdin (or a named file) and writes its result to stdout, removing C comments from the text. It has to <em>see through</em> any sequences of <em>BACKSLASH NEWLINE</em> when detecting comments, but reproduce all such line continuation sequences that were not part of a comment. Additionally, the challenge was to use no <code>goto</code>s and reasonably short functions.</p> <p>The code was originally inspired by a Haskell program and it implements a simple Lisp-ish data structure including a simple garbage collector. I don't want to explain much more because I want the code to speak for itself.</p> <p><a href="https://github.com/luser-dr00g/strpcom/blob/622ce574bb11b3ecde8034b25bcdb1a0e23ba072/strpcom-v5.c" rel="nofollow noreferrer">strpcom-v5.c</a></p> <pre><code>//strpcom-v5.c: //$ make strpcom-v5 CFLAGS='-std=c99 -Wall -pedantic -Wextra -Wno-switch' #ifndef DEBUG_LEVEL #define DEBUG_LEVEL 0 #endif static const int debug_level = DEBUG_LEVEL; static const int handle_roots = 1; #include &lt;stddef.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; typedef union uobject *object; typedef object list; typedef enum tag { INVALID, INTEGER, LIST } tag; #define OBJECT(...) new_( (union uobject[]){{ __VA_ARGS__ }} ) union uobject { tag t; struct { tag t; int i, continues; } Int; struct { tag t; object a, b; } List; }; typedef struct record { int mark; struct record *prev; object *handle; union uobject o; } record; static void init_patterns(); static void cleanup(); static list chars_from_file( FILE *f ); static list logical_lines( list o ); static list trim_continue( list o, list tail ); static list restore_continues( list o ); static list strip_comments( list o ); static list single_remainder( list tail ); static list multi_remainder( list tail ); static int starts_literal( object a ); static list literal_val( object a, list o ); static list skip_quote( object q, list o ); static list nested_comment( list o ); static void print( list o, FILE *f ); static object Int( int i ); static list cons( object a, object b ); static list one( object a ); static object car( list o ); static object cdr( list o ); static int eq( object a, object b ); static int eqint( object a, int i ); static int match( object pat, object it, object *matched, object *tail ); static object add_global_root( object o, object *op ); static int collect( object local_roots ); static void mark( object ob ); static int sweep( record **ptr ); static record * alloc(); static object new_( object a ); static int error( char *msg ); record *allocation_list; object global_roots; list slnl; // patterns list single, multi; list starsl; int main( int argc, char **argv ){ init_patterns(); list input = chars_from_file( argc &gt; 1 ? fopen( argv[1], &quot;r&quot; ) : stdin ); if( debug_level &gt;= 2 ) fprintf( stderr, &quot;input:\n&quot;), print( input, stderr ); list logical = logical_lines( input ); if( debug_level &gt;= 2 ) fprintf( stderr, &quot;logical:\n&quot;), print( logical, stderr ); list stripped = strip_comments( logical ); if( debug_level &gt;= 2 ) fprintf( stderr, &quot;stripped:\n&quot;), print( stripped, stderr ); list restored = restore_continues( stripped ); if( debug_level &gt;= 2 ) fprintf( stderr, &quot;restored:\n&quot;); print( restored, stdout ), fflush( stdout ); cleanup( restored ), input = logical = stripped = restored = NULL; } void init_patterns(){ slnl = add_global_root( cons( Int( '\\' ), one( Int( '\n' ) ) ), &amp;slnl ); single = add_global_root( cons( Int( '/' ), one( Int( '/' ) ) ), &amp;single ); multi = add_global_root( cons( Int( '/' ), one( Int( '*' ) ) ), &amp;multi ); starsl = add_global_root( cons( Int( '*' ), one( Int( '/' ) ) ), &amp;starsl ); } void cleanup( object restored ){ if( debug_level ){ if( debug_level &gt;= 2 ) fprintf( stderr, &quot;@%d\n&quot;, collect( restored ) ); if( handle_roots ){ global_roots = NULL; } fprintf( stderr, &quot;@%d\n&quot;, collect( NULL ) ); } } list chars_from_file( FILE *f ){ int c = fgetc( f ); return c != EOF ? cons( Int( c ), chars_from_file( f ) ) : one( Int( c ) ); } list logical_lines( list o ){ if( !o ) return NULL; if( debug_level &gt;= 2 &amp;&amp; car(o)-&gt;Int.i != EOF ) fprintf( stderr, &quot;[%c%c]&quot;, car(o)-&gt;Int.i, car(cdr(o))-&gt;Int.i ); object matched, tail; return match( slnl, o, &amp;matched, &amp;tail ) ? trim_continue( o, tail ) : cons( car( o ), logical_lines( cdr( o ) ) ); } list trim_continue( list o, list tail ){ if( debug_level &gt;= 2 ) fprintf( stderr, &quot;@&quot; ); return car( tail )-&gt;Int.continues = car( o )-&gt;Int.continues + 1, logical_lines( tail ); } list restore_continues( list o ){ return !o ? NULL : car( o )-&gt;Int.continues--&gt;0 ? cons( Int( '\\' ), cons( Int( '\n' ), restore_continues( o ) ) ) : cons( car( o ), restore_continues( cdr( o ) ) ); } list strip_comments( list o ){ if( !o ) return NULL; if( debug_level &gt;= 2 &amp;&amp; car(o)-&gt;Int.i != EOF ) fprintf( stderr, &quot;&lt;%c%c&gt;&quot;, car(o)-&gt;Int.i, car(cdr(o))-&gt;Int.i ); object matched, tail; object a; return match( single, o, &amp;matched, &amp;tail ) ? single_remainder( tail ) : match( multi, o, &amp;matched, &amp;tail ) ? multi_remainder( tail ) : starts_literal( a = car( o ) ) ? literal_val( a, cdr( o ) ) : cons( a, strip_comments( cdr( o ) ) ); } list single_remainder( list tail ){ if( debug_level &gt;= 2 ) fprintf( stderr, &quot;@/&quot; ); object c; for( c = car( tail ); tail &amp;&amp; ! (eqint( c, '\n' ) || eqint( c, EOF )); c = car( tail = cdr( tail ) ) ) ; return eqint( c, '\n' ) ? cons( Int( '\n' ), strip_comments( cdr( tail ) ) ) : tail; } list multi_remainder( list tail ){ if( debug_level &gt;= 2 ) fprintf( stderr, &quot;@*&quot; ); return cons( Int( ' ' ), strip_comments( nested_comment( tail ) ) ); } int starts_literal( object a ){ return eqint( a, '\'' ) || eqint( a, '&quot;' ); } list literal_val( object a, list o ){ return cons( a, skip_quote( a, o ) ); } list nested_comment( list o ){ if( !o ) error( &quot;Unterminated comment\n&quot; ); if( debug_level &gt;= 2 ) fprintf( stderr, &quot;(%c%c)&quot;, car( o )-&gt;Int.i, car( cdr( o ) )-&gt;Int.i ); object matched, tail; return match( starsl, o, &amp;matched, &amp;tail ) ? tail : eqint( car( o ), EOF ) ? error( &quot;Unterminated comment\n&quot; ),NULL : nested_comment( cdr( o ) ); } list skip_quote( object q, list o ){ if( !o ) error( &quot;Unterminated literal\n&quot; ); object a = car( o ); return eqint( a, '\\' ) ? cons( a, cons( car( cdr( o ) ), skip_quote( q, cdr( cdr( o ) ) ) ) ) : eq( a, q ) ? cons( a, strip_comments( cdr( o ) ) ) : eqint( a, '\n' ) || eqint( a, EOF ) ? error( &quot;Unterminated literal\n&quot; ),NULL : cons( a, skip_quote( q, cdr( o ) ) ); } void print( list o, FILE *f ){ switch( o ? o-&gt;t : 0 ){ case INTEGER: if( o-&gt;Int.i != EOF ) fputc( o-&gt;Int.i, f ); break; case LIST: print( car( o ), f ); print( cdr( o ), f ); break; } } object Int( int i ){ return OBJECT( .Int = { INTEGER, i } ); } list cons( object a, object b ){ return OBJECT( .List = { LIST, a, b } ); } list one( object a ){ return cons( a, NULL ); } object car( list o ){ return o &amp;&amp; o-&gt;t == LIST ? o-&gt;List.a : NULL; } object cdr( list o ){ return o &amp;&amp; o-&gt;t == LIST ? o-&gt;List.b : NULL; } int eq( object a, object b ){ return !a &amp;&amp; !b ? 1 : !a || !b ? 0 : a-&gt;t != b-&gt;t ? 0 : a-&gt;t == INTEGER ? a-&gt;Int.i == b-&gt;Int.i : !memcmp( a, b, sizeof *a ); } int eqint( object a, int i ){ union uobject b = { .Int = { INTEGER, i } }; return eq( a, &amp;b ); } int match( object pat, object it, object *matched, object *tail ){ if( !pat ) return *tail = it, 1; if( pat-&gt;t != (it ? it-&gt;t : 0) ) return 0; switch( pat-&gt;t ){ case LIST: { object sink; if( match( car( pat ), car( it ), &amp; sink, tail ) ) return *matched = it, match( cdr( pat ), cdr( it ), &amp; sink, tail ); } break; case INTEGER: if( eq( pat, it ) ) return *matched = it, 1; } return 0; } object add_global_root( object o, object *op ){ if( handle_roots ){ global_roots = cons( o, global_roots ); record *r = ((void*)( (char*)o - offsetof( record, o ) ) ); r-&gt;handle = op; } return o; } void mark( object ob ){ if( !ob ) return; record *r = ((void*)( (char*)ob - offsetof( record, o ) ) ); if( r-&gt;mark ) return; r-&gt;mark = 1; switch( ob ? ob-&gt;t : 0 ){ case LIST: mark( ob-&gt;List.a ); mark( ob-&gt;List.b ); break; } } int sweep( record **ptr ){ int count = 0; while( *ptr ){ if( (*ptr)-&gt;mark ){ (*ptr)-&gt;mark = 0; ptr = &amp;(*ptr)-&gt;prev; } else { record *z = *ptr; if( z-&gt;handle ) *z-&gt;handle = NULL; *ptr = (*ptr)-&gt;prev; free( z ); ++count; } } return count; } int collect( object local_roots ){ mark( local_roots ); mark( global_roots ); return sweep( &amp;allocation_list ); } record * alloc(){ return calloc( 1, sizeof(record) ); } object new_( object a ){ record *r = alloc(); object p = NULL; if( r ){ r-&gt;prev = allocation_list; allocation_list = r; p = (void*)( ((char*)r) + offsetof( record, o ) ); *p = *a; } return p; } int error( char *msg ){ fprintf( stderr, &quot;%s&quot;, msg ); exit( EXIT_FAILURE ); return 0777; } </code></pre> <p><a href="https://github.com/luser-dr00g/strpcom/tree/622ce574bb11b3ecde8034b25bcdb1a0e23ba072" rel="nofollow noreferrer">The repository</a> includes a testing script, but due to some bash quirks it reports some false negatives so I don't wish to display the results here. Compiling with DEBUG_LEVEL defined to 1 or higher will run a garbage collection at the end. Running under valgrind including the GC reports zero memory leaks.</p> <p>Questions: Is is easy to discern the top-level structure? Are the individual functions readable/maintainable? Is it overkill to include a GC that doesn't even run under normal compilation? Are there any functions where it's possible to rewrite in a tail-recursive form to potentially reduce the function call depth?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T20:02:51.083", "Id": "500953", "Score": "0", "body": "Why not implement with `flex` and ten lines of code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T20:08:08.317", "Id": "500954", "Score": "3", "body": "Well, the challenge was to write it in C and to use no `goto`s and reasonably short functions. I then got a little sidetracked trying to add a tiny garbage collector." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T04:15:08.623", "Id": "500980", "Score": "1", "body": "Just a side note for a real-world production quality solution, comment chars in string literals (`\"/*\"`) and replacing comments with whitespace (`a/**/b` to `a b`) and conserving line numbers by line feeds in that whitespace." } ]
[ { "body": "<p>I think the code does a lot more to reflect its genealogy than it does to represent the actual task. Despite being written in C, it seems to do its best to embody the old line about every sufficiently complex program including a half-broken implementation of half of LISP.</p>\n<p>Simply put, even though it's acceptable to a C compiler, it's not really written even close to how I'd normally expect most people to write C to do a job like this.</p>\n<p>It's been years since I did write C much, but as it happens back when I did, I wrote some code to tokenize C source code (I'm not sure, but I think this is from around 1995 or so).</p>\n<p>Now make no mistake: I'm not going to claim this is even close to ideal (I'd certainly do it differently if I were going to do the same job today), but I think it's at least quite a bit closer to how I'd typically expect C code to be written.</p>\n<p>The big difference I see is that it looks like your code tries to read in the entire source file, decompose it into a giant data structure, then produce its output by regurgitating data from that structure. I think most C programmers (certainly at that time, but I think still largely true today) would prefer to write a filter as being as close to an actual filter as possible--that is, reading in a little data, processing the data, and writing out the processed data as it goes, so even if you had a source file many times larger than your available RAM, it could still process it quite easily. Admittedly, that's not nearly as a serious a problem today as it was 30 years ago when I still wrote quite a bit of C, but I think a lot of C programmers would still be somewhat bothered by the idea of it, unless they gained a significant benefit from storing everything in memory first.</p>\n<pre class=\"lang-c prettyprint-override\"><code>/* get_src.c */\n#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n#include &lt;ctype.h&gt;\n#include &lt;stdlib.h&gt;\n\n#define GET_SOURCE\n#include &quot;get_src.h&quot;\n\nstatic size_t current = 0;\n\nchar last_token[MAX_TOKEN_SIZE];\n\nPFILE *parse_fopen(char const *name) {\n\n PFILE *temp = malloc(sizeof(PFILE));\n\n if ( NULL != temp ) {\n temp-&gt;file = fopen(name, &quot;r&quot;);\n memset(temp-&gt;peeks, 0, sizeof(temp-&gt;peeks));\n temp-&gt;last_peek = 0;\n }\n return temp;\n}\n\nPFILE *parse_fdopen(FILE *file) {\n\n PFILE *temp = malloc(sizeof(PFILE));\n\n if ( NULL != temp) {\n temp-&gt;file = file;\n memset(temp-&gt;peeks, 0, sizeof(temp-&gt;peeks));\n temp-&gt;last_peek = 0;\n }\n return temp;\n}\n\nint parse_fclose(PFILE *stream) {\n\n int retval = fclose(stream-&gt;file);\n\n free(stream);\n return retval;\n}\n\nstatic void addchar(int ch) {\n/* adds the passed character to the end of `last_token' */\n\n if ( current &lt; sizeof(last_token) -1 )\n last_token[current++] = (char)ch;\n\n if ( current == sizeof(last_token)-1 )\n last_token[current] = '\\0';\n}\n\nstatic void clear(void) {\n/* clears the previous token and starts building a new one. */\n current = 0;\n}\n\nstatic int read_char(PFILE *stream) {\n if ( stream-&gt;last_peek &gt; 0 )\n return stream-&gt;peeks[--stream-&gt;last_peek];\n return fgetc(stream-&gt;file);\n}\n\nvoid unget_character(int ch, PFILE * stream) {\n if ( stream-&gt;last_peek &lt; sizeof(stream-&gt;peeks) )\n stream-&gt;peeks[stream-&gt;last_peek++] = ch;\n}\n\nstatic int check_trigraph(PFILE *stream) {\n/* Checks for trigraphs and returns the equivalant character if there\n * is one. Expects that the leading '?' of the trigraph has already\n * been read before this is called.\n */\n\n int ch;\n\n if ( '?' != (ch=read_char(stream))) {\n unget_character(ch, stream);\n return '?';\n }\n\n ch = read_char(stream);\n\n switch( ch ) {\n case '(': return '[';\n case ')': return ']';\n case '/': return '\\\\';\n case '\\'': return '^';\n case '&lt;': return '{';\n case '&gt;': return '}';\n case '!': return '|';\n case '-': return '~';\n case '=': return '#';\n default:\n unget_character('?', stream);\n unget_character(ch, stream);\n return '?';\n }\n}\n\n#ifdef DIGRAPH\nstatic int check_digraph(PFILE *stream, int first) {\n/* Checks for a digraph. The first character of the digraph is\n * transmitted as the second parameter, as there are several possible\n * first characters of a digraph.\n */\n\n int ch = read_char(stream);\n\n switch(first) {\n case '&lt;':\n if ( '%' == ch )\n return '{';\n if ( ':' == ch )\n return '[';\n break;\n case ':':\n if ( '&gt;' == ch )\n return ']';\n break;\n case '%':\n if ( '&gt;' == ch )\n return '}';\n if ( ':' == ch )\n return '#';\n break;\n }\n\n/* If it's not one of the specific combos above, return the characters\n * separately and unchanged by putting the second one back into the\n * stream, and returning the first one as-is.\n */\n unget_character(ch, stream);\n return first;\n}\n#endif\n\n\nstatic int get_char(PFILE *stream) {\n/* Gets a single character from the stream with any trigraphs or digraphs converted \n * to the single character represented. Note that handling digraphs this early in\n * translation isn't really correct (and shouldn't happen in C at all).\n */\n int ch = read_char(stream);\n\n if ( ch == '?' )\n return check_trigraph(stream);\n\n#ifdef DIGRAPH\n if (( ch == '&lt;' || ch == ':' || ch == '%' ))\n return check_digraph(stream, ch);\n#endif\n\n return ch;\n}\n\nint get_character(PFILE *stream) {\n/* gets a character from `stream'. Any amount of any kind of whitespace\n * is returned as a single space. Escaped new-lines are &quot;eaten&quot; here as well.\n */\n int ch;\n\n if ( !isspace(ch=get_char(stream)) &amp;&amp; ch != '\\\\')\n return ch;\n\n // handle line-slicing\n if (ch == '\\\\') {\n ch = get_char(stream);\n if (ch == '\\n') \n ch = get_char(stream);\n else {\n unget_character(ch, stream);\n return ch;\n }\n }\n\n /* If it's a space, skip over consecutive white-space */\n while (isspace(ch) &amp;&amp; ('\\n' != ch))\n ch = get_char(stream);\n\n if ('\\n' == ch)\n return ch;\n\n /* Then put the non-ws character back */\n unget_character(ch, stream);\n\n /* and return a single space character... */\n return ' ';\n}\n\nstatic int read_char_lit(PFILE *stream) {\n/* This is used internally by `get_source' (below) - it expects the\n * opening quote of a character literal to have already been read and\n * returns CHAR_LIT or ERROR if there's a newline before a close\n * quote is found, or if the character literal contains more than two\n * characters after escapes are taken into account.\n */\n\n int ch;\n int i;\n\n\n clear();\n addchar('\\'');\n\n for (i=0; i&lt;2 &amp;&amp; ('\\'' != ( ch = read_char(stream))); i++) {\n\n addchar(ch);\n\n if ( ch == '\\n' )\n return ERROR;\n\n if (ch == '\\\\' ) {\n ch = get_char(stream);\n addchar(ch);\n }\n }\n addchar('\\'');\n addchar('\\0');\n\n if ( i &gt; 2 )\n return ERROR;\n\n return CHAR_LIT;\n}\n\nstatic int read_str_lit(PFILE *stream) {\n/* Used internally by get_source. Expects the opening quote of a string\n * literal to have already been read. Returns STR_LIT, or ERROR if a\n * un-escaped newline is found before the close quote.\n */\n\n int ch;\n\n clear();\n addchar('&quot;');\n\n while ( '&quot;' != ( ch = get_char(stream))) {\n\n if ( '\\n' == ch || EOF == ch )\n return ERROR;\n\n addchar(ch);\n\n if( ch == '\\\\' ) {\n ch = read_char(stream);\n addchar(ch);\n }\n\n }\n\n addchar('&quot;');\n addchar('\\0');\n\n return STR_LIT;\n}\n\nstatic int read_comment(PFILE *stream) {\n/* Skips over a comment in stream. Assumes the leading '/' has already\n * been read and skips over the body. If we're reading C++ source, skips\n * C++ single line comments as well as normal C comments.\n */\n int ch;\n\n clear();\n\n ch = get_char(stream);\n\n /* Handle a single line comment.\n */\n if ('/' == ch) {\n addchar('/');\n addchar('/');\n\n while ( '\\n' != ( ch = get_char(stream))) \n addchar(ch); \n\n addchar('\\0');\n return COMMENT;\n }\n\n if ('*' != ch ) {\n unget_character(ch, stream);\n return '/';\n }\n\n addchar('/');\n\n do {\n addchar(ch);\n while ('*' !=(ch = get_char(stream)))\n if (EOF == ch)\n return ERROR;\n else\n addchar(ch);\n addchar(ch);\n } while ( '/' != (ch=get_char(stream)));\n\n addchar('/');\n addchar('\\0');\n\n return COMMENT;\n}\n\nint get_source(PFILE *stream) {\n/* reads and returns a single &quot;item&quot; from the stream. An &quot;item&quot; is a\n * comment, a literal or a single character after trigraph and possible\n * digraph substitution has taken place.\n */\n\n int ch = get_character(stream);\n\n switch(ch) {\n case '\\'':\n return read_char_lit(stream);\n case '&quot;':\n return read_str_lit(stream);\n case '/':\n return read_comment(stream);\n default:\n return ch;\n }\n}\n\n#ifdef TEST\n\nint main(int argc, char **argv) {\n PFILE *f;\n int ch;\n\n if (argc != 2) {\n fprintf(stderr, &quot;Usage: get_src &lt;filename&gt;\\n&quot;);\n return EXIT_FAILURE;\n }\n\n if (NULL==(f= parse_fopen(argv[1]))) {\n fprintf(stderr, &quot;Unable to open: %s\\n&quot;, argv[1]);\n return EXIT_FAILURE;\n }\n\n while (EOF!=(ch=get_source(f))) \n if (ch &lt; 0) \n printf(&quot;\\n%s\\n&quot;, last_token);\n else\n printf(&quot;%c&quot;, ch);\n parse_fclose(f);\n return 0; \n}\n\n#endif\n</code></pre>\n<p>Now make no mistake--I'm certainly not trying to hold this up as a paragon of virtue. Its use of a global variable is particularly bothersome (at least to me). It also supports a few things (like trigraphs) the challenge specifically excluded. Its support for digraphs is somewhat broken as well (it's translating them earlier in the translation process than it really should). But I think it's still rather closer to the basic style I think most C programmers would find acceptable. In particular, although it has a lot of other &quot;stuff&quot; (that you'd normally ignore--most of it in the form of <code>static</code> functions, so the rest of the world should never see them) the interface to <code>get_source</code> is simple enough that it's pretty trivial to use the tokenizer for a fairly wide variety of tasks (e.g., writing a simple <code>indent</code> program). I'll admit, I'm a bit uncertain about it, but at first glance, it seems like that's rather less true of your code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T04:15:45.723", "Id": "533469", "Score": "0", "body": "Is there a portability issue with <stdio.h>:`ungetc()`? Or is there some other advantage to the PFILE:peeks?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T06:53:58.207", "Id": "533476", "Score": "1", "body": "@luserdroog: There are circumstances under which this needs to unget more than one character, and the normal ungetc only guarantees the ability to unget one character." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T05:32:42.590", "Id": "254016", "ParentId": "254005", "Score": "5" } }, { "body": "<h3>Initial comments</h3>\n<ol>\n<li><p><code>static void cleanup();</code> is a function declaration, but it is not a prototype. It does not give you the protection that a prototype does. For the <code>cleanup()</code> function, it should be <code>static void cleanup(object restored);</code> — for the other functions without a prototype, the argument list should be explicitly written as <code>function(void)</code> to show that no arguments are expected. You should compile with <code>-Wstrict-prototypes</code> so that such function declarations are rejected.</p>\n</li>\n<li><p>Personally, I always include <code>static</code> in the function definition as well as the function declaration; I prefer the consistency. Since this is a single source file, I'd make all the file scope (global) variables into static variables too. If it were a multi-file program, then there'd be headers to declare the variables and functions (and any other supporting information needed across files — types, macros, enumerations).</p>\n</li>\n<li><p>I would include a <code>default:</code> clause or an explicit <code>case INVALID:</code> in the <code>switch</code> so that I did not need to specify <code>-Wno-switch</code>.</p>\n</li>\n<li><p>Your code does not detect <code>*/</code> appearing outside a <code>/*</code> comment. This isn't a major flaw (a compiler will reject the code). It also doesn't detect <code>/*</code> appearing inside a <code>/*</code> comment. Again, this isn't a major flaw.</p>\n</li>\n<li><p>Your code doesn't preserve line numbers. It can be a good idea to preserve newlines found in comments. It probably wasn't a design goal, so it isn't a major criticism.</p>\n</li>\n<li><p>It's possible to avoid trailing white space on output lines, but considerably harder. Again, this probably wasn't a design goal, so it isn't a major criticism.</p>\n</li>\n<li><p>You don't handle trigraphs. The only one that matters for comment removal is <code>??/</code> which is equivalent to a backslash. Since C++ has removed support for trigraphs, and GCC requires the <code>-trigraphs</code> option to enable them, it isn't a major issue, but the fact that they aren't handled should perhaps be documented. There is no need to handle digraphs; digraphs do not affect the interpretation of comments.</p>\n</li>\n<li><p>You don't detect multiple command-line arguments. IMO, it is not a good idea to ignore extra arguments — either process them or reject them.</p>\n</li>\n<li><p>You don't error check memory allocations. There's only one function that calls <code>calloc()</code> — no calls to <code>malloc()</code> or <code>realloc()</code> — so it would be easy to add an error check that reports 'out of memory' and stops the program on allocation failure. That's preferable to a crash. (In <code>new_()</code>, you detect if the allocation failed, but simply pass back a null pointer without reporting that the allocation failed.)</p>\n</li>\n<li><p>You don't error check that the file was opened successfully; that's close to criminal — users give wrong file names or unreadable file names and your program should not crash because they do so.</p>\n</li>\n</ol>\n<p>Yes, I do have a program SCC — Strip C Comments. You can find the code on GitHub under <a href=\"https://github.com/jleffler/scc-snapshots\" rel=\"nofollow noreferrer\">https://github.com/jleffler/scc-snapshots</a>. I ran your code on some of its test cases. SCC also handles C++, including more recent versions, which causes conniptions at times. Raw string literals and punctuation in numeric constants (and binary constants) cause major problems — for example, <code>0b1101'0011</code> is a valid C++ binary literal, but looks to a naïve C parser like an incomplete character constant. Sticking with just C is much easier. SCC does not handle digraphs (because it isn't necessary to do so) or trigraphs. If I need to map either digraphs or trigraphs, I have separate programs that can add or remove them (called, with stunning originality, <code>digraphs</code> and <code>trigraphs</code>). They're primarily obfuscatory features these days, though trigraphs addressed a real problem in the days when C90 was defined, and digraphs were added in C99 as preferable to trigraphs. (Hmmm…I need to update the <code>scc-snapshots</code> repository. I've created releases 7.00, 7.10, 7.20, 7.30, 7.40 and 7.50 since I last updated it, though most of the revisions (except for removing trailing blanks) are minor. Oops!) There is some fairly gruesome code in SCC; it wouldn't all necessarily stand up to detailed scrutiny either.</p>\n<h3>Code style</h3>\n<blockquote>\n<ul>\n<li>Is it easy to discern the top-level structure?</li>\n</ul>\n</blockquote>\n<p>Not particularly easy.</p>\n<ul>\n<li>You are over-fond of the comma operator.</li>\n<li>You use <code>typedef union uobject *object;</code> to hide the pointer — see Stack Overflow on <a href=\"https://stackoverflow.com/questions/750178/is-it-a-good-idea-to-typedef-pointers\">Is it a good idea to typedef pointers?</a>.</li>\n<li>You slurp the entire file into a list that contains one element for each character in the file. Slurping is a good idea (I've debated doing that for SCC), but I'm not convinced that a list of single characters to represent the whole file is a good idea.</li>\n<li>You use the LISP-like functions <code>cons</code>, <code>car</code>, <code>cdr</code> — that isn't a common idiom in C.</li>\n</ul>\n<blockquote>\n<ul>\n<li>Are the individual functions readable/maintainable?</li>\n</ul>\n</blockquote>\n<p>Some of the functions have odd parts. For example, in function <code>void mark(object ob)</code> you have <code>if (!ob) return;</code> and then later <code>switch (ob ? ob-&gt;t : 0)</code>. You previously determined that <code>ob</code> is not null, so there's no need to retest it. And a <code>switch</code> with one case and no <code>default:</code> is probably better written as an <code>if</code> statement:</p>\n<pre><code>if (ob-&gt;t == LIST) {\n mark(ob-&gt;List.a);\n mark(ob-&gt;List.b);\n}\n</code></pre>\n<p>The <code>logical_lines()</code> function is not easily understood.</p>\n<p>The <code>trim_continue()</code> function is not easily understood. I think it is written unnecessarily opaquely. It is:</p>\n<pre class=\"lang-c prettyprint-override\"><code>list\ntrim_continue( list o, list tail )\n{\n if (debug_level &gt;= 2)\n fprintf( stderr, &quot;@&quot; );\n return car( tail )-&gt;Int.continues = car( o )-&gt;Int.continues + 1,\n logical_lines( tail );\n}\n</code></pre>\n<p>It would probably be clearer if written as:</p>\n<pre class=\"lang-c prettyprint-override\"><code>list\ntrim_continue(list o, list tail)\n{\n if (debug_level &gt;= 2)\n fprintf(stderr, &quot;@&quot;);\n car(tail)-&gt;Int.continues = car(o)-&gt;Int.continues + 1;\n return logical_lines(tail);\n}\n</code></pre>\n<p>It's still opaque, but the comma operator doesn't make anything clearer. It has its uses; this isn't a good one.</p>\n<p>Many of the other functions are also hard to understand.</p>\n<blockquote>\n<ul>\n<li>Is it overkill to include a GC that doesn't even run under normal compilation?</li>\n</ul>\n</blockquote>\n<p>Yes.</p>\n<blockquote>\n<ul>\n<li>Are there any functions where it's possible to rewrite in tail-recursive form to potentially reduce the function call depth?</li>\n</ul>\n</blockquote>\n<p>Probably most of them. I think using lists less extensively would reduce the overhead. I'd expect to read lines into buffers, and then manipulate lines, both a single line at a time and consecutive lines at times. I think that would reduce the overhead.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T06:24:18.243", "Id": "254017", "ParentId": "254005", "Score": "4" } } ]
{ "AcceptedAnswerId": "254017", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T19:36:46.557", "Id": "254005", "Score": "5", "Tags": [ "c", "linked-list" ], "Title": "Removing C comments from Source" }
254005
<p>I am trying to find an optimal way to get the min and max limits from a list of lists provided a multiplier. I've tried two methods and I'm wondering if there is a more optimal solution that scales better in terms of performance when executed multiple times.</p> <pre><code>import timeit def get_lower_upper_limits(inps): ranges, multipliers = inps min_l = 0 max_l = 0 for idx, multiplier in enumerate(multipliers): min_l += multiplier * (min(ranges[idx]) if multiplier &gt; 0 else max(ranges[idx])) max_l += multiplier * (max(ranges[idx]) if multiplier &gt; 0 else min(ranges[idx])) return min_l, max_l def wrapper(func, *args, **kwargs): def wrapped(): return func(*args, **kwargs) return wrapped ranges = [[1000, 1400, 1800], [2200, 2400, 2600], [3000, 3100, 3200]] multiplier = [-1, 2, 3] assert len(ranges) == len(multiplier) wrapped = wrapper(get_lower_upper_limits, (ranges, multiplier)) print('get_lower_upper_limits: {}'.format(timeit.timeit(wrapped, number=5000000))) </code></pre> <p>get_lower_upper_limits: 9.775336363000001</p> <p>Example:</p> <p>range = [[1000, 1500, 2000], [2000, 2500, 3000]]</p> <p>multiplier = [1, 2]</p> <p>range_after_multiplication = [[1000, 1500, 2000], [4000, 5000, 6000]]</p> <p>The min/max limit (or number) that can be produced from the sum of each of the elements in the list is:</p> <p>min_l = 1000 + 4000 = 5000</p> <p>max_l = 2000 + 6000 = 8000</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T00:02:26.237", "Id": "500974", "Score": "0", "body": "@superbrain added an example, I hope it's clearer now" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T00:08:31.080", "Id": "500975", "Score": "3", "body": "Seems inefficient to search for min and max in the ranges. They're all sorted, so just take the first and last element." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T22:16:06.130", "Id": "501223", "Score": "0", "body": "this combined with the changes in the answer below help. Thanks" } ]
[ { "body": "<h1>Function Arguments</h1>\n<pre class=\"lang-py prettyprint-override\"><code>def get_lower_upper_limits(inps):\n ranges, multipliers = inps\n ...\n</code></pre>\n<p>This is a curious choice for declaring arguments to the function. You must package two arguments together as a tuple for the <code>inps</code> argument, without any clear indication to the caller of the requirement.</p>\n<p>Why not declare the function as:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def get_lower_upper_limits(ranges, multipliers):\n ...\n</code></pre>\n<p>The caller then has a clue that the function takes two arguments, a <code>ranges</code> and a <code>multipliers</code>.</p>\n<p>A <code>&quot;&quot;&quot;docstring&quot;&quot;&quot;</code> could go a long way towards helping the caller understand the requirements for calling the function. Type-hints would go even further. I recommend researching both subjects.</p>\n<h1>Wrapper</h1>\n<p>With the above change to the function arguments, your <code>wrapped</code> function will need a new definition:</p>\n<pre class=\"lang-py prettyprint-override\"><code>wrapped = wrapper(get_lower_upper_limits, (ranges, multiplier))\n</code></pre>\n<p>This presently provides 1 argument (the <code>tuple</code> created with <code>(ranges, multiplier)</code>) to be passed to the function being wrapped. With the above change, the function now needs the <code>ranges</code> and <code>multiplier</code> passed as individual arguments:</p>\n<pre class=\"lang-py prettyprint-override\"><code>wrapped = wrapper(get_lower_upper_limits, ranges, multiplier)\n</code></pre>\n<h1>Wrapper-free packaging</h1>\n<p>The <code>wrapper</code> function is not needed.</p>\n<p>First, the <code>partial</code> function from <code>functools</code> will perform the wrapping for you (and provides additional capabilities, which are not needed here). Remove the <code>wrapper</code> function, and replace it with an import:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from functools import partial\n\nwrapped = partial(get_lower_upper_limits, ranges, multiplier)\n</code></pre>\n<p>This may be faster than your hand-written <code>wrapper</code> function, as built-ins can be implemented directly in C.</p>\n<p>Again, as this is not using the full capabilities of <code>partial</code>, a simpler alternative exists:</p>\n<pre class=\"lang-py prettyprint-override\"><code>wrapped = lambda: get_lower_upper_limits(ranges, multiplier)\n</code></pre>\n<h1>Don't index</h1>\n<p>In Python, indexing is relatively slow. If you do not need <code>idx</code>, except for use in <code>variable[idx]</code>, it is best to loop over <code>variable</code> directly.</p>\n<p>Since in this case, you need to loop over two lists <code>ranges</code> and <code>multipliers</code> simultaneously, you'll need to <code>zip</code> them together first (zip as in zipper, not as in compression).</p>\n<pre class=\"lang-py prettyprint-override\"><code> for values, multiplier in zip(ranges, multipliers):\n min_l += multiplier * (min(values) if multiplier &gt; 0 else max(values))\n ...\n</code></pre>\n<h1>Improved code</h1>\n<pre class=\"lang-py prettyprint-override\"><code>import timeit\n\ndef get_lower_upper_limits(ranges, multipliers):\n min_l = 0\n max_l = 0\n for values, multiplier in zip(ranges, multipliers):\n min_l += multiplier * (min(values) if multiplier &gt; 0 else max(values))\n max_l += multiplier * (max(values) if multiplier &gt; 0 else min(values))\n return min_l, max_l\n\nranges = [[1000, 1400, 1800], [2200, 2400, 2600], [3000, 3100, 3200]]\nmultiplier = [-1, 2, 3]\nassert len(ranges) == len(multiplier)\nfunc = lambda: get_lower_upper_limits(ranges, multiplier)\n\nprint('get_lower_upper_limits: {}'.format(timeit.timeit(func, number=500000)))\n</code></pre>\n<p>Approximately 5% faster</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T20:09:49.443", "Id": "254054", "ParentId": "254011", "Score": "1" } } ]
{ "AcceptedAnswerId": "254054", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-28T23:37:15.070", "Id": "254011", "Score": "1", "Tags": [ "python", "performance", "python-3.x" ], "Title": "Extracting lower and upper limit of a range of values based on a multiplier" }
254011
<p>I've created a Christmas tree using only HTML and CSS. It's pretty sure that the code can be written in a more efficient way. Also, the lights are turning on and off at the same time, is there a way to make them work independently?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { background-color: #9fd8ee; } .tree { display: flex; flex-direction: column; align-items: center; } .triangle-one { width: 0; height: 0; border-left: 60px solid transparent; border-right: 60px solid transparent; border-bottom: 100px solid rgb(20, 97, 27); margin-top: -69px; } .triangle-two { width: 0; height: 0; border-left: 90px solid transparent; border-right: 90px solid transparent; border-bottom: 150px solid rgb(20, 97, 27); margin-top: -40px; } .triangle-three { width: 0; height: 0; border-left: 120px solid transparent; border-right: 120px solid transparent; border-bottom: 200px solid rgb(20, 97, 27); margin-top: -80px; } .triangle-four { width: 0; height: 0; border-left: 150px solid transparent; border-right: 150px solid transparent; border-bottom: 250px solid rgb(20, 97, 27); margin-top: -120px; } .rectangle { height: 50px; width: 60px; background-color: maroon; } .globe { border-radius: 50%; width: 25px; height: 25px; position: absolute; } .glpos-1 { background: red; top: 175px; left: 630px; } .glpos-2 { background: blue; top: 225px; left: 655px; } .glpos-3 { background: yellow; top: 315px; left: 610px; } .glpos-4 { background: orange; top: 375px; left: 680px; } .glpos-5 { background: cyan; top: 425px; left: 640px; } .glpos-6 { background: red; top: 535px; left: 700px; } .glpos-7 { background: blue; top: 510px; left: 590px; } .light { border-radius: 50%; width: 10px; height: 10px; background: yellow; animation: example 1s infinite; position: absolute; } .lipos-1 { top: 260px; left: 620px; } .lipos-2 { top: 300px; left: 710px; } .lipos-3 { top: 410px; left: 590px; } .lipos-4 { top: 510px; left: 730px; } .lipos-5 { top: 160px; left: 666px; } .lipos-6 { top: 417px; left: 700px; } .lipos-7 { top: 480px; left: 610px; } @keyframes example { 50% { box-shadow: 1px 1px 10px #ccc, -2px 1px 10px #ccc, 0 -1px 10px #ccc; } } .star { margin: 50px 0; position: relative; display: block; color: yellow; width: 0px; height: 0px; border-right: 100px solid transparent; border-bottom: 70px solid yellow; border-left: 100px solid transparent; transform: rotate(35deg) scale(0.75); } .star:before { border-bottom: 80px solid yellow; border-left: 30px solid transparent; border-right: 30px solid transparent; position: absolute; height: 0; width: 0; top: -45px; left: -65px; display: block; content: ''; transform: rotate(-35deg); } .star:after { position: absolute; display: block; color: yellow; top: 3px; left: -105px; width: 0px; height: 0px; border-right: 100px solid transparent; border-bottom: 70px solid yellow; border-left: 100px solid transparent; transform: rotate(-70deg); content: ''; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Christmas tree&lt;/title&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1" /&gt; &lt;link rel="stylesheet" type="text/css" href="style.css" /&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="tree"&gt; &lt;div class="star"&gt;&lt;/div&gt; &lt;div class="triangle-one"&gt;&lt;/div&gt; &lt;div class="triangle-two"&gt;&lt;/div&gt; &lt;div class="triangle-three"&gt;&lt;/div&gt; &lt;div class="triangle-four"&gt;&lt;/div&gt; &lt;div class="rectangle"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="globe glpos-1"&gt;&lt;/div&gt; &lt;div class="globe glpos-2"&gt;&lt;/div&gt; &lt;div class="globe glpos-3"&gt;&lt;/div&gt; &lt;div class="globe glpos-4"&gt;&lt;/div&gt; &lt;div class="globe glpos-5"&gt;&lt;/div&gt; &lt;div class="globe glpos-6"&gt;&lt;/div&gt; &lt;div class="globe glpos-7"&gt;&lt;/div&gt; &lt;div class="light lipos-1"&gt;&lt;/div&gt; &lt;div class="light lipos-2"&gt;&lt;/div&gt; &lt;div class="light lipos-3"&gt;&lt;/div&gt; &lt;div class="light lipos-4"&gt;&lt;/div&gt; &lt;div class="light lipos-5"&gt;&lt;/div&gt; &lt;div class="light lipos-6"&gt;&lt;/div&gt; &lt;div class="light lipos-7"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p><strong>PS</strong>: it seems that in this code snippet the globes and lights are not positioned on the tree. I don't know why, I copied the code from my project where it looks right.</p>
[]
[ { "body": "<p>You could make a few adjustments to your code:</p>\n<ul>\n<li><p><a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/position\" rel=\"nofollow noreferrer\">Positioning</a> looks inconsistent here. Make sure to set your parent element's position to relative. An absolutely positioned element is positioned relative to its parent. If there is no such parent, it is positioned relative to the window, just like in your example.</p>\n</li>\n<li><p>Add <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/z-index\" rel=\"nofollow noreferrer\">z-index</a> to make ornaments and lights appear in front of the tree.</p>\n</li>\n<li><p><a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/clip-path\" rel=\"nofollow noreferrer\">clip-path</a> is quite handy when it comes to creating shapes (Check for browser compatibility <a href=\"https://caniuse.com/?search=clip-path\" rel=\"nofollow noreferrer\">here</a>).</p>\n</li>\n</ul>\n<p>Hope this helps!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-05T11:30:23.693", "Id": "254339", "ParentId": "254014", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T00:44:54.830", "Id": "254014", "Score": "0", "Tags": [ "html", "css", "html5", "animation", "sass" ], "Title": "Christmas tree made up only with HTML and CSS" }
254014
<p>I am using a code similar to the following example to create a table with <code>tkinter</code> using <code>Python 3</code>:</p> <ul> <li><p>Each cell is individually created as a <code>ttk.Label</code> and displayed using <code>.grid(row, column)</code></p> </li> <li><p>Some of my values get updated while the program is running with <code>tk.StringVar().set()</code></p> </li> <li><p>Each value is unique and has it's own variable name <code>count1</code> <code>count2</code></p> </li> </ul> <p>This example seems short, but in my program I have a few more rows being displayed and each row has 2 <code>StringVar()</code> that I need to keep updated. Overall, it's a very large <code>for</code> loop because it has to check if it's in the correct row &amp; column combination (<code>row 1</code> <code>column 0</code> or <code>row 2</code> <code>column 0</code>) before creating a <code>StringVar()</code>.</p> <ul> <li>Any suggestions on how to reduce the size of my <code>for</code> loop?</li> <li>Are there better ways of creating tables that need a few values consistently updated?</li> </ul> <p>Thank you for your time and Happy Holidays!</p> <pre><code>import time import tkinter as tk import tkinter.ttk as ttk from threading import Thread gui = tk.Tk() gui.geometry('360x270') gui.configure(bg='white') style = ttk.Style() style.theme_create('custom', settings={ 'header.TLabel': {'configure': { 'background': 'white', 'foreground': 'dark green', 'font': 'Times 16 bold', 'padding': (10, 0)}}, 'TLabel': {'configure': {'background': 'white', 'font': 'Times 12'}}, 'TFrame': {'configure': {'background': 'white'}}}) style.theme_use('custom') table_frame = ttk.Frame(gui) table_frame.pack(pady=(36, 0)) values = [('Count', 'Date', 'Time', 'Phrase'), ('5', '12/12/10', '03:15', 'blue car'), ('13', '09/09/98', '16:20', 'red door')] total_rows = len(values) total_columns = len(values[0]) for i in range(total_rows): for j in range(total_columns): if i == 0: label = ttk.Label(table_frame, text=values[i][j], style='header.TLabel') label.grid(row=i, column=j) elif i == 1: if j == 0: count1 = tk.StringVar() count1.set(values[i][j]) label = ttk.Label(table_frame, textvariable=count1) label.grid(row=i, column=j) else: label = ttk.Label(table_frame, text=values[i][j]) label.grid(row=i, column=j) elif i == 2: if j == 0: count2 = tk.StringVar() count2.set(values[i][j]) label = ttk.Label(table_frame, textvariable=count2) label.grid(row=i, column=j) else: label = ttk.Label(table_frame, text=values[i][j]) label.grid(row=i, column=j) def increment_count(): increment_count.status = 'run' while increment_count.status == 'run': new_minute1 = int(count1.get()) + 1 count1.set(str(new_minute1)) new_minute2 = int(count2.get()) - 1 count2.set(str(new_minute2)) time.sleep(1) Thread(target=increment_count).start() gui.mainloop() increment_count.status = 'exit' </code></pre>
[]
[ { "body": "<p>As I suspected, there's already a thing for this - a TreeView. Strongly prefer built-in widgets that get the job done, leaving the construction of individual elements as a last resort if the built-in widget doesn't at all meet your needs.</p>\n<p>There's plenty of <a href=\"https://stackoverflow.com/a/50651988/313768\">examples on how to use this as a table</a>, but if I were you I'd start with the <a href=\"https://docs.python.org/3/library/tkinter.ttk.html#tkinter.ttk.Treeview\" rel=\"nofollow noreferrer\">reference documentation</a>.</p>\n<p>Remove the first row of your <code>values</code> and use it as a dedicated heading, instead. Break your <code>i</code>/<code>j</code> loop into two halves - a heading half, and a body half.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-04T17:19:01.220", "Id": "501532", "Score": "1", "body": "Thanks a lot! I didn't even know you could use TreeView like that, I thought it was just for dropdown menus." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-04T16:53:22.543", "Id": "254313", "ParentId": "254018", "Score": "1" } } ]
{ "AcceptedAnswerId": "254313", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T07:49:36.537", "Id": "254018", "Score": "1", "Tags": [ "python", "tkinter" ], "Title": "Creating a Table with Tkinter" }
254018
<p>I am pretty sure my code does not follow <a href="https://www.python.org/dev/peps/pep-0008/" rel="nofollow noreferrer">PEP 8</a> and would definitely want someone to point out my errors specifically. I am open any form of criticism or suggestions.</p> <pre><code>import chess import chess.engine import time import stockfish engine = chess.engine.SimpleEngine.popen_uci(&quot;stockfish&quot;) board = chess.Board() def pact(): # Player's Action print('----------------\n' + 'The legal moves are: \n' + str(board.legal_moves) + '\n' + str(board)) Action = input('Declare your moves: ') try: board.push_san(Action) except ValueError: # output: &quot;integer division or modulo by zero&quot; print('Invalid move, try again') def cact(): # Computer's Action result = engine.play(board, chess.engine.Limit(time=2.0)) board.push(result.move) print(board) print(board) for index in range(3, 0, -1): print('The game starts in ' + str(index) + 'seconds') time.sleep(1) while(board.is_checkmate() == False): pact() cact() # print(engine.play.move(board, limit) </code></pre> <p>Ideally I would like to incorporate sound recognition and making it a hands-free chess playing with Stockfish or other player. For now, I just want to get the basics right to avoid any future bugs and improve overall tidiness so I can have a good habit in my future coding progress.</p>
[]
[ { "body": "<ul>\n<li><p>The game logic is broken in many respects.</p>\n<p>First, the game may reach an &quot;insufficient material&quot; condition, in which checkmate is impossible. Infinite loop right away.</p>\n<p>Second, the game may get into a stalemate. There is no legal moves in a stalemate, so <code>pact</code> would reject anything the user tries to enter. Yet another infinite loop.</p>\n<p>Finally, the end of game condition shall be tested after each <em>half-move</em>. BTW, <code>chess</code> module conveniently offers a <code>board.is_game_over()</code> method, which encompasses everything above, plus three-fold repetition, plus 50 moves rule.</p>\n</li>\n<li><p>Board is printed only after a computer move. This is strange.</p>\n</li>\n<li><p>Listing the legal moves unconditionally is annoying. It should only be printed when the player enters an illegal one.</p>\n</li>\n<li><p>When you feel compelled to put a comment like</p>\n<pre><code> def pact(): # Player's Action\n</code></pre>\n<p>it means that you fail to express yourself clearly in the code. Giving the function a meaningful name, like</p>\n<pre><code> def player_action():\n</code></pre>\n<p>eliminates the need to comment it.</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T18:41:16.623", "Id": "254047", "ParentId": "254020", "Score": "3" } } ]
{ "AcceptedAnswerId": "254047", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T08:15:14.690", "Id": "254020", "Score": "1", "Tags": [ "python", "pygame", "chess" ], "Title": "Little chess game with python" }
254020
<p>The previous day, I helped someone build a really simple console &quot;Lucky Number&quot; game. It's really simple, the user has to choose a number, the program will also choose one, and if there's a match between the two, the user wins.</p> <p>To made the game a bit more visual, the numbers are initially blue and displayed in a nice way.</p> <p>I'm looking for the following things in a review, but any advice is welcome:</p> <ul> <li>is the code structured ok?</li> <li>did I use the correct data structures along the program? (e.g.: is it okay for <code>Colors</code> to be an <code>Enum</code>, should <code>numbers</code> be a <code>number</code>: <code>color</code> map and so on)</li> <li>are type annotations used correctly?</li> <li>are the function / variable names suggestive enough?</li> <li>is there anything in terms of performance that can be improved?</li> </ul> <p>Here's the code:</p> <pre><code>import random import sys import time from enum import Enum from typing import Dict LINE_WIDTH = 5 EXTRA_PADDING = 6 # seconds to wait until the next number # is picked up SECONDS_TO_WAIT = 5 MIN_NUMBER = 1 MAX_NUMBER = 30 class Colors(Enum): red = '\033[91m' green = '\033[92m' blue = '\033[94m' end = '\033[0m' def assign_color_to_number(number: int, default_color: str) -&gt; str: &quot;&quot;&quot; Show ANSI colors in terminal for nicer UX. Arguments: number (int): A number between `MIN_NUMBER` and `MAX_NUMBER` default_color (str): The color of a number Returns: str: Each number with it's own color &quot;&quot;&quot; for color in Colors: if color.name == default_color: return f'{color.value}{number}{Colors.end.value}' else: return f'{number}' def print_table(numbers_color_map: Dict[int, str]) -&gt; None: &quot;&quot;&quot; Print a nice table with colorful numbers wrapped after `LINE_WIDTH` numbers. Arguments: numbers_color_map (dict): A map between numbers and their color. &quot;&quot;&quot; print('\n') padding = max([int(len(color.name)) for color in Colors]) + len(str(MAX_NUMBER)) + EXTRA_PADDING for number, default_color in numbers_color_map.items(): colored_number = assign_color_to_number(number, default_color).ljust(padding) print(colored_number, end=' ') if number % LINE_WIDTH != 0 else print(colored_number) print('\n') def countdown(seconds: int) -&gt; None: &quot;&quot;&quot; Let user know how much until the next game. Arguments: seconds (int): How many seconds until next game. &quot;&quot;&quot; for second in range(seconds, -1, -1): sys.stdout.write(f&quot;\r{second} seconds remaining until next &quot; f&quot;number will be picked.&quot;) time.sleep(1) sys.stdout.flush() print('\n') def get_user_number() -&gt; int: &quot;&quot;&quot; Sanitize user's input. Returns: int: User's chosen number. &quot;&quot;&quot; while True: try: value = int(input(f'Please chose a number between ' f'{MIN_NUMBER} and {MAX_NUMBER}: ')) if MAX_NUMBER &lt; value &lt; MIN_NUMBER: print(f&quot;Please insert a number between {MIN_NUMBER} and &quot; f&quot;{MAX_NUMBER}!\n&quot;) continue return value except ValueError: print(f&quot;Please insert a number between {MIN_NUMBER} and &quot; f&quot;{MAX_NUMBER}!\n&quot;) continue def play(): numbers_color_map = { number: 'blue' for number in range(MIN_NUMBER, MAX_NUMBER + 1) } print_table(numbers_color_map) user_number = get_user_number() print(f&quot;You chose {user_number}. GOOD LUCK!\n\n&quot;) countdown(SECONDS_TO_WAIT) random_number = random.randint(MIN_NUMBER, MAX_NUMBER) if user_number != random_number: numbers_color_map.update({ random_number: 'green', user_number: 'red' }) print_table(numbers_color_map) print(f' Your number: {user_number}\n' f'Computer number: {random_number}\n\n' f'You did not win. GOOD LUCK NEXT TIME!') else: print('You guessed it! Congrats! Please fill in the information ' 'below in order to receive your prize.\n\n') # reset our numbers to their initial color numbers_color_map.update({ random_number: 'blue', user_number: 'blue' }) def main(): while True: os.system('cls' if os.name == 'nt' else 'clear') print('\nWELCOME TO THE LUCKY NUMBER!') play() answer = input('\nPlay again? [Y]es/[N]o: ') if answer.lower() == 'n': break print('\nTHANKS FOR PLAYING!') if __name__ == '__main__': main() </code></pre> <p>You can either c/p the code and run it locally or <a href="https://repl.it/@alexu/LotteryGameRST-1#main.py" rel="nofollow noreferrer">play it here</a>.</p>
[]
[ { "body": "<p>Nice implementation, the code is well structured and easy to understand. My suggestions:</p>\n<ul>\n<li><strong>Printing the table</strong>: there are two variables to configure how to display the numbers:\n<pre><code>LINE_WIDTH = 5\nEXTRA_PADDING = 6\n</code></pre>\n<code>LINE_WIDTH</code> seems to be how many numbers can be displayed for each line, so a better name could be <code>NUMBERS_PER_LINE</code>. The variable <code>EXTRA_PADDING</code> is ok but I would document it in the <code>print_table</code> function.</li>\n<li><strong>Bug</strong>: this condition doesn't catch the wrong input:\n<pre class=\"lang-py prettyprint-override\"><code>if MAX_NUMBER &lt; value &lt; MIN_NUMBER:\n print(f&quot;Please insert a number between {MIN_NUMBER} and {MAX_NUMBER}!\\n&quot;)\n</code></pre>\nAssuming that <code>MIN_NUMBER</code> and <code>MAX_NUMBER</code> are valid options, you can change it to:\n<pre><code>if value &lt; MIN_NUMBER or value &gt; MAX_NUMBER:\n print(f&quot;Please insert a number between {MIN_NUMBER} and {MAX_NUMBER}!\\n&quot;)\n</code></pre>\n</li>\n<li><strong>Colors</strong>:\n<pre><code>class Colors(Enum):\nred = '\\033[91m'\ngreen = '\\033[92m'\nblue = '\\033[94m'\nend = '\\033[0m'\n</code></pre>\nThe color <code>end</code> is a bit confusing for an enum called <code>Colors</code>. Consider <code>ANSIColorCode</code> as a name, from <a href=\"https://en.wikipedia.org/wiki/ANSI_escape_code\" rel=\"nofollow noreferrer\">here</a>.</li>\n<li><strong>Design</strong>: the logic to display the numbers is interesting but not very easy to reuse. Suppose I want to reuse it, I need to copy the functions <code>assign_color_to_number</code>, <code>print_table</code>, <code>Colors</code>, and the two constants to configure how to display the numbers. Plus understanding how to create and use the map <code>numbers_color_map</code>. Consider creating a class for it, like <code>TablePrinter</code> or <code>RangePrinter</code>, to make it easier to reuse and test. For example:\n<pre><code>class RangePrinter:\n NUMBERS_PER_LINE = 5\n EXTRA_PADDING = 6\n\n def __init__(self, start, end, default_color='blue'):\n # Initialize the map setting all numbers to default_color\n def print(self):\n # Print numbers to console\n def set_number_to_color(self, number, color):\n # Set color for a single number\n def set_all_numbers_to_color(self, color):\n # Set color for all numbers\n</code></pre>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T10:13:08.603", "Id": "254025", "ParentId": "254021", "Score": "2" } }, { "body": "<p>Firstly, I really enjoyed reviewing this code, it is very readable and understandable. The code looks nice. I would just highlight few things that might be improve</p>\n<h2>Reduce the use of Globals</h2>\n<p>You want to always reduce your use of global variables. In your program, you have a lot of global variables, you can eliminate all of them by encapsulating them in a <code>datatclass</code>. I would not expect <code>MIN_NUMBER</code> and <code>MAX_NUMBER</code> to be constant as they might change.</p>\n<p>Here I created a data class named <code>LuckyGameConfig</code> and hide some configuration data in it</p>\n<pre><code>from dataclasses import dataclass\n\n@dataclass \nclass LuckyGameConfig:\n &quot;&quot;&quot;Lucky number guessing game configurations&quot;&quot;&quot; \n\n line_width: int = 5\n padding: int = 6\n seconds_to_wait: int = 5\n min_number: int = 1\n max_number: int = 30 \n</code></pre>\n<p>This looks better now, we know where to look when we need to modify how we want our game to look.</p>\n<h2>Prefer <code>colorama</code> Module to ANSI Color</h2>\n<p>I see you created a nice <code>Enum</code> class to hold your colors, <code>colorama</code> module shines here, it makes what you are doing really easy.</p>\n<pre><code>from colorama import init, Fore \n</code></pre>\n<p>We can simply create a green color</p>\n<pre><code>green_color = Fore.GREEN\nFore.RESET # reset our color\n</code></pre>\n<p>The module also have styles like <code>BOLD</code>, <code>ITALIC</code>, you might want to check the module out.</p>\n<h2>Reduce <code>print_table</code> Complexity</h2>\n<p>A lot of stuff are going on in <code>print_table</code>. The name is also misleading, what table are we printing here. It would not take much to get confused on what is really going on in the function.</p>\n<p>Why smashed this into one line?</p>\n<pre><code> print(colored_number, end=' ') if number % LINE_WIDTH != 0 else print(colored_number)\n</code></pre>\n<p>This looks smart but confuses the reader, he/she would need to pause a little to understand this piece of code.</p>\n<p>This following can also be improved.</p>\n<pre><code>padding = max([int(len(color.name)) for color in Colors]) + len(str(MAX_NUMBER)) + EXTRA_PADDING\n</code></pre>\n<p>Let's call our function <code>display_numbers</code></p>\n<pre><code>def display_numbers(numbers: dict) -&gt; None:\n &quot;&quot;&quot;Display a nice table with colorful numbers wrapped.\n\n Arguments:\n numbers (dict): A dict of numbers that maps to its color\n &quot;&quot;&quot;\n for number, color in numbers.items():\n if number % LuckyGameConfig.line_width != 0:\n format = f'{number:&lt;{LuckyGameConfig.padding}}'\n print(color, format, end=' ')\n else:\n print(color, number)\n print(Fore.RESET)\n</code></pre>\n<p>This looks more readable.</p>\n<h2>Fix the Bug</h2>\n<p>The little bug in your program. Choosing a number greater than <code>MAX_NUMBER</code> or less than <code>MIN_NUMBER</code> seems to work. On inspecting the code, I found that you wrote this test</p>\n<pre><code> if MAX_NUMBER &lt; value &lt; MIN_NUMBER:\n</code></pre>\n<p>Let's see a simple example, say the user chooses 90, the condition evaluates to <code>30 &lt; 90 &lt; 1</code> which is <code>False</code>, the condition statement never evaluates and the error passes silently and <code>value</code> is initialized.</p>\n<p>The bug can be fixed like this</p>\n<pre><code>if value &lt; MIN_NUMBER or value &gt; MAX_NUMBER:\n</code></pre>\n<p>The full code becomes</p>\n<pre><code>&quot;&quot;&quot;A random lucky number game&quot;&quot;&quot;\n\nimport sys\nimport time\nimport os\nfrom dataclasses import dataclass\nfrom enum import Enum\nfrom colorama import init, Fore \nfrom random import randint\nfrom typing import Dict \n\n\n@dataclass \nclass LuckyGameConfig:\n &quot;&quot;&quot;Lucky number guessing game configurations&quot;&quot;&quot; \n\n line_width: int = 5\n padding: int = 6\n seconds_to_wait: int = 5\n min_number: int = 1\n max_number: int = 30 \n\n\ndef display_numbers(numbers: dict) -&gt; None:\n &quot;&quot;&quot;Display a nice table with colorful numbers wrapped.\n\n Arguments:\n numbers (dict): A dict of numbers that maps to its color\n &quot;&quot;&quot;\n for number, color in numbers.items():\n if number % LuckyGameConfig.line_width != 0:\n format = f'{number:&lt;{LuckyGameConfig.padding}}'\n print(color, format, end=' ')\n else:\n print(color, number)\n print(Fore.RESET)\n\ndef get_user_number() -&gt; int:\n &quot;&quot;&quot;\n Sanitize user's input.\n\n Returns:\n int: User's chosen number.\n &quot;&quot;&quot;\n\n while True:\n try:\n value = int(input(f'Please chose a number between '\n f'{LuckyGameConfig.min_number} and {LuckyGameConfig.max_number}: '))\n\n if value &lt; LuckyGameConfig.min_number or value &gt; LuckyGameConfig.max_number:\n print(f&quot;Please insert a number between {LuckyGameConfig.min_number} and &quot;\n f&quot;{LuckyGameConfig.max_number}!\\n&quot;)\n continue\n\n return value\n except ValueError:\n print(f&quot;Please insert integer values!\\n&quot;)\n continue\n\ndef countdown(seconds: int) -&gt; None:\n &quot;&quot;&quot;\n Let user know how much until the next game.\n\n Arguments:\n seconds (int): How many seconds until next game.\n &quot;&quot;&quot;\n\n for second in range(seconds, -1, -1):\n sys.stdout.write(f&quot;\\r{second} seconds remaining until next &quot;\n f&quot;number will be picked.&quot;)\n time.sleep(1)\n sys.stdout.flush()\n\n print('\\n')\n\ndef play():\n &quot;&quot;&quot;Play a lucky number guessing game&quot;&quot;&quot; \n\n init() # initialize colorama to get our basic colors\n numbers = {number: Fore.BLUE for number in range(LuckyGameConfig.min_number, LuckyGameConfig.max_number + 1)}\n display_numbers(numbers)\n user_number = get_user_number()\n print(f&quot;You chose {user_number}. GOOD LUCK!\\n\\n&quot;)\n\n countdown(LuckyGameConfig.seconds_to_wait)\n random_number = randint(LuckyGameConfig.min_number, LuckyGameConfig.max_number)\n\n if user_number != random_number:\n numbers.update({\n random_number: Fore.GREEN,\n user_number: Fore.RED\n })\n display_numbers(numbers)\n\n print(f' Your number: {user_number}\\n'\n f'Computer number: {random_number}\\n\\n'\n f'You did not win. GOOD LUCK NEXT TIME!')\n else:\n print('You guessed it! Congrats! Please fill in the information '\n 'below in order to receive your prize.\\n\\n')\n\n # we do not need to reset the colors, the while loop in main does the job\n\ndef main():\n\n while True:\n os.system('cls' if os.name == 'nt' else 'clear')\n print('\\nWELCOME TO THE LUCKY NUMBER!')\n play()\n answer = input('\\nPlay again? [Y]es/[N]o: ')\n if answer.lower() == 'n':\n break\n\n print('\\nTHANKS FOR PLAYING!')\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T11:32:32.623", "Id": "500992", "Score": "1", "body": "Nice review. Regarding **Fix the Bug** I find `if not MIN_NUMBER <= value <= MAX_NUMBER:` nice to read." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T11:05:26.163", "Id": "254030", "ParentId": "254021", "Score": "2" } } ]
{ "AcceptedAnswerId": "254030", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T08:27:49.327", "Id": "254021", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "Let's win at Python Lucky Number" }
254021
<p>I am recently learning OOP concepts and thought that implementing a simple workflow simulating a vending machine would help me put what I've learnt into practice. I am open to criticisms and feedback, and am mainly trying to get some comments regarding:</p> <ul> <li>Best practices for OOP</li> <li>File structure</li> <li>Data encapsulation</li> <li>Unit testing practices</li> <li>General architecture advice for OOP</li> </ul> <p>The project simulates a vending machine dispensing drinks for customers for X hours (user input), given that arrival times follow a Poisson(K) distribution and an initial stock list (user input). The project also produces a sales report for the given simulation.</p> <p>The link to my the entire github repository is here: <a href="https://github.com/jtsw1990/oop_vending_machine" rel="nofollow noreferrer">https://github.com/jtsw1990/oop_vending_machine</a></p> <p>Below is a snippet of vending_machine.py, which is the class to simulate the behavior of a typical vending machine. Any help is appreciated not just for this snippet, but the other classes in the repo as well like the customer class.</p> <pre><code>import csv import numpy as np class DataReader: ''' Object to read in initial drinks data set to be used as input in VendingMachine class ''' def __init__(self, filepath): self.df = [] with open(filepath, &quot;r&quot;) as file: my_reader = csv.reader(file, delimiter=&quot;,&quot;) next(my_reader) for row in my_reader: self.df.append(row) class VendingMachine: ''' Insert doc string here ''' def __init__(self, max_capacity): print(&quot;__init__ is being called here&quot;) self.max_capacity = max_capacity self.current_earnings = 0 self.current_stock = 0 self.stock_list = None self.drinks_displayed = None def __repr__(self): print(&quot;__repr__ was being called here&quot;) return &quot;VendingMachine({!r})&quot;.format(self.max_capacity) @property def max_capacity(self): print(&quot;max_cap property being called here&quot;) return self.__max_capacity @max_capacity.setter def max_capacity(self, max_capacity): print(&quot;max_cap setter called here&quot;) if not isinstance(max_capacity, (int, float)): raise TypeError(&quot;Please enter an integer value&quot;) elif max_capacity &lt; 0: raise ValueError(&quot;Capacity cannot be negative&quot;) elif max_capacity % 1 != 0: raise TypeError(&quot;Please enter an integer value&quot;) else: self.__max_capacity = max_capacity def load_drinks(self, filepath): self.drink_list = DataReader(filepath).df if self.stock_list is None: self.stock_list = { row[0]: [float(row[1]), int(row[2])] for row in self.drink_list } current_stock = sum([value[-1] for key, value in self.stock_list.items()]) if current_stock &gt; self.max_capacity: raise ValueError(&quot;Loaded drinks past capacity&quot;) else: self.current_stock = current_stock def display_stock(self): self.drinks_displayed = [ x[0] for x in list(self.stock_list.items()) if x[-1][-1] &gt; 0 ] return self.drinks_displayed def dispense_drink(self, drink_name): ''' Method to simulate a vending machine object dispensing a drink. Returns drink_name as a string if available. Returns None if out of stock. ''' try: if self.stock_list[drink_name][-1] &gt; 0: self.stock_list[drink_name][-1] -= 1 self.current_earnings = np.round( self.current_earnings + self.stock_list[drink_name][0], 2) self.current_stock = sum( [value[-1] for key, value in self.stock_list.items()]) return drink_name else: return None except KeyError: print(&quot;Machine out of stock&quot;) return None if __name__ == &quot;__main__&quot;: test = VendingMachine(200) test.load_drinks(&quot;drinks_list.csv&quot;) test.display_stock() for i in range(150): test.dispense_drink(&quot;coke&quot;) test.dispense_drink(&quot;ice_lemon_tea&quot;) test.dispense_drink(&quot;fanta_orange&quot;) test.dispense_drink(&quot;fanta_grape&quot;) test.dispense_drink(&quot;sprite&quot;) test.dispense_drink(&quot;pepsi&quot;) test.dispense_drink(&quot;mountain_dew&quot;) print(test.stock_list) print(test.display_stock()) </code></pre>
[]
[ { "body": "<p>The biggest change needed here is to delete your <code>DataReader</code> class, replace direct use of Numpy with Pandas (which wraps Numpy), and use named columns in your dataframe instead of numeric indices.</p>\n<p>Pandas has excellent built-in support for CSV operations and structured tabular data where column names can be used to make the code more legible and robust. For instance, you can permute the order of columns in your CSV file and none of your code would need to change.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-06T02:46:28.347", "Id": "501647", "Score": "1", "body": "Ahh that's a really good point, and my bad. I was initially writing this on the iPad using the Pythonista app where Pandas was not supported. Should've switched it out when changing back to PC thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T17:25:52.073", "Id": "254182", "ParentId": "254022", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T08:31:15.357", "Id": "254022", "Score": "2", "Tags": [ "python-3.x", "object-oriented", "classes" ], "Title": "Python code for simple Vending Machine simulation implementing OOP principles" }
254022
<p>In this method, I was tasked to take in a list of <code>TemplateMap</code> and attach dynamic parameters and in a certain case, add further templates to the returned list. This functionality exists within a report rendering service and at this stage, I am constructing the templates to send into the rendering function.</p> <p><code>ParameterName</code> in these <code>templateMaps</code> can have the following formats:</p> <ol> <li>&quot;XML|MPAN={}|IsCopy={}&quot;</li> <li>&quot;XML|MPRN={}|IsCopy={}&quot;</li> <li>&quot;XML&quot;</li> <li>&quot;XML|IsCopy={}&quot;</li> </ol> <p>FYI the ParameterName is a string and the above is how I retrieve them from the database</p> <pre><code>private static IEnumerable&lt;TemplateMap&gt; TransformTemplateMaps(IEnumerable&lt;TemplateMap&gt; templateMaps, XmlDocument xml, bool isCopy = false) { var transformedTemplates = new List&lt;TemplateMap&gt;(); var bindingOrder = 1; foreach (var template in templateMaps) { var parameters = template.ParameterName.Split('|'); var skipCurrentTemplate = false; foreach (var param in parameters) { var paramName = param.Split(&quot;=&quot;).First(); switch (paramName.ToUpper()) { case &quot;MPRN&quot;: case &quot;MPAN&quot;: // Returns a list of strings var meters = GetMetersInXml(xml, paramName); if ((meters ?? throw new InvalidOperationException()).Count == 1) { template.ParameterName = template.ParameterName.Replace($&quot;{paramName}={{}}&quot;, $&quot;{paramName}={meters.SingleOrDefault()}&quot;); } else { // Multiple meters per site requires one template each with different meter variables foreach (var meter in meters) { // Initialise clone of template instance with different parameter values var additionalTemplate = (TemplateMap) template.Clone(); additionalTemplate.ParameterName = additionalTemplate.ParameterName.Replace($&quot;{paramName}={{}}&quot;, $&quot;{paramName}={meter}&quot;); additionalTemplate.ParameterName = additionalTemplate.ParameterName.Replace($&quot;IsCopy={{}}&quot;, $&quot;IsCopy={isCopy}&quot;); additionalTemplate.BindingOrder = bindingOrder; bindingOrder++; transformedTemplates.Add(additionalTemplate); } // Skips current template so that it doesn't add a duplicate template below skipCurrentTemplate = true; } break; case &quot;ISCOPY&quot;: template.ParameterName = template.ParameterName.Replace($&quot;{paramName}={{}}&quot;, $&quot;{paramName}={isCopy}&quot;); break; // add variables that require dynamic values here } } if (skipCurrentTemplate) continue; template.BindingOrder = bindingOrder; bindingOrder++; transformedTemplates.Add(template); } return transformedTemplates; } </code></pre> <p>In my code you can see that I have multiple nested foreach loops which I know to be bad design. I have found answers online that mention flattening out the nested loops into methods for better readability.</p> <p>In my case however, I have certain properties i.e. <code>bindingOrder</code> and <code>skipCurrentTemplate</code> that need to be accessed from the inner loops so I'm not sure how to go about extracting these inner loops into methods as I'd have to return these other properties as well.</p> <p>What way would you suggest I improve this code?</p> <p>EDIT</p> <p>Adding the TemplateMap object definition</p> <pre><code>public class TemplateMap : ICloneable { public string ReportPath { get; set; } public string ParameterName { get; set; } public int BindingOrder { get; set; } public bool? IncludedInInvoice { get; set; } public object Clone() { return new TemplateMap { ReportPath = this.ReportPath, BindingOrder = this.BindingOrder, ParameterName = this.ParameterName, IncludedInInvoice = this.IncludedInInvoice }; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T10:57:25.097", "Id": "500991", "Score": "0", "body": "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-12-29T13:24:17.347", "Id": "500996", "Score": "0", "body": "Are you sure the code works? There seems to be a mismatch between the return type and what is actually returned. What is the relationship between Template and TemplateDTO?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T13:32:04.270", "Id": "500997", "Score": "0", "body": "@MrBalanikas Yep the code works as intended. Apologies, forgot to change that part. It is supposed to be TemplateMap not DTO. Will edit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T12:07:44.787", "Id": "501089", "Score": "0", "body": "`XML|MPAN={}|IsCopy={}` what is `XML` ? is it a valid `XmlDocument`? and what would `{}` means ? array ? could you give us a working sample of the `ParameterName` I need to know the full data structure that is being processed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T16:10:10.720", "Id": "501116", "Score": "0", "body": "@iSR5 Parameter name is a string that is retrieved as part of the template found in the database. `XML|MPAN={}|IsCopy={}` is how the string will come from the database. `XML` means that the parameter requires the standard xml for each template. If the parameter has `={}` it means that it requires a dynamic value which I insert in my method." } ]
[ { "body": "<p>Some quick remarks:</p>\n<ul>\n<li><p>You should move the &quot;convert <code>template.ParameterName</code> to values to iterate through&quot; logic to a separate class and return a meaningful object. Now you twice have this code where you split a string and this adds noise. Especially since all you are interested in is the collection of <code>paramName</code>s.</p>\n</li>\n<li><p>Considering that this is one <code>private</code> method which seems to call another <code>private</code> method, I'd argue that <code>TransformTemplateMaps</code> shouldn't be a method, but a class of its own. Then <code>IEnumerable&lt;TemplateMap&gt; templateMaps, XmlDocument xml, bool isCopy = false</code> could be class-level private fields, and you could easily split this method into smaller methods. This class could contain <code>GetMetersInXml</code> (or that could be a class of its own, if that method is long as well or if it needs to be used by other methods).</p>\n</li>\n<li><p>Comments like <code>// Returns a list of strings</code> are pointless. Comments should explain why the code is the way it is (if necessary), not what the code does (this should be clear from the code itself).</p>\n</li>\n<li><p>I realize naming is hard, but <code>xml</code> is way too vague. <code>template</code> doesn't seem to be the correct name, shouldn't it be <code>templateMap</code>?</p>\n</li>\n<li><p>There is no reason to do <code>meters.SingleOrDefault()</code>. The <code>if</code> already checked that there is one entry in the collection, so <code>.Single()</code> is enough.</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T13:16:26.910", "Id": "500995", "Score": "0", "body": "Thanks, in this case I only added that comment for this question as I didn't include the `GetMetersInXml` method." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T11:21:08.243", "Id": "254031", "ParentId": "254024", "Score": "1" } }, { "body": "<p>One common approach is to split the main problem into smaller subproblems. We can start from the innermost loop and move up nesting levels as we go. First subproblem is mainly about cloning the template, and that is subproblem1. Moving up to higher level, and the code seems to be about converting a template to a template DTO, and that is subproblem2.</p>\n<p>Eventually the structure of the main problem will be something like:</p>\n<pre><code>main problem\n subproblem3\n subproblem2\n subproblem1\n</code></pre>\n<p>If you follow this, you will find out that there are lots of variables, state changes and parameters passed around, so you can also consider introducing a 'context' type, that groups the changeable state into a single data structure. That should make the code easier to understand.</p>\n<p>Next thing to try is to make methods as pure as possible. Changing state within a method often makes code more difficult to grasp.</p>\n<p>Finally, if you try to break down your code into multiple types and/or methods, then go for it wherever it makes sense, but only up to a certain point. After that point it is possible that you code becomes even more complicated than what it is now.</p>\n<p>Those are just some of my hints. Try to experiment with different approaches until you reach something that makes sense, i.e. you should be able to quickly come back and understand the code even after you have been away for a year.\nHopefully there already exists some unit tests to support you in the code refactoring.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T13:34:17.473", "Id": "500998", "Score": "0", "body": "Apologies, there isn't any need to convert to a DTO object. The TemplateMap object is the only object needed." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T13:21:20.543", "Id": "254037", "ParentId": "254024", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T09:59:58.443", "Id": "254024", "Score": "0", "Tags": [ "c#" ], "Title": "Nested foreach loop returning modified list" }
254024
<h1>Update</h1> <p>The implementation did not consider multiple occurrences of a same word, and self word occurrences.</p> <p>For instance when stride=2 and the word at the position is <code>W</code>, co-occurrence of X needs +2, self-co-occurrence of W needs +1.</p> <pre><code>X|Y|W|X|W </code></pre> <h1>Question</h1> <p>Please advise how to vectorize the co occurrence matrix generation without using a loop. The current issue is also posted as <a href="https://stackoverflow.com/questions/65490619/numpy-how-to-combine-multiple-indices-replace-multiple-one-by-one-matrix-acce">numpy - how to combine multiple indices (replace multiple one-by-one matrix access with one access)</a> and posting here as well to get and suggestions.</p> <p>Please also provide reviews for any issues, performance improvement opportunities, coding standards, related resource to look into.</p> <h2>Challenge</h2> <p>To update the <code>m * m</code> matrix (<a href="https://stackoverflow.com/questions/24073030/what-are-co-occurance-matrixes-and-how-are-they-used-in-nlp">co_occurance_matrix</a>), currently accessing row by row with a loop. The entire code is at the bottom.</p> <p>How can I remove the loop and update the multiple rows all at once? I believe there should be a way to combine each index into one matrix that replaces the loop with one vectorized update.</p> <h2>Current implementation</h2> <pre><code>for position in range(0, n): co_ccurrence_matrix[ sequence[position], # position to the word sequence[max(0, position-stride) : min((position+stride),n-1) +1] # positions to co-occurrence words ] += 1 </code></pre> <ol> <li>Loop over an array of word indices <code>sequence</code> (word index is an integer code for each word).</li> <li>For each word at the <code>position</code> in the loop, check the co-occurring words on both sides within a <code>stride</code> distance. <br>This is a N-gram <code>context</code> window as in the <strong>purple box in the diagram</strong>. <code>N = context_size = stride*2 + 1</code>.</li> <li>Increment the count of each co-occurrence word in the <code>co_occurrence_matrix</code> as per <strong>blue lines in the diagram</strong>.</li> </ol> <p><a href="https://i.stack.imgur.com/GbKo7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GbKo7.png" alt="enter image description here" /></a></p> <h2>Code</h2> <pre><code>import numpy as np def preprocess(text): &quot;&quot;&quot; Args: text: A string including sentences to process. corpus Returns: sequence: A numpy array of word indices to every word in the original text as they appear in the text. The objective of corpus is to preserve the original text but as numerical indices. word_to_id: A dictionary to map a word to a word index id_to_word: A dictionary to map a word index to a word &quot;&quot;&quot; text = text.lower() text = text.replace('.', ' .') words = text.split(' ') word_to_id = {} id_to_word = {} for word in words: if word not in word_to_id: new_id = len(word_to_id) word_to_id[word] = new_id id_to_word[new_id] = word sequence= np.array([word_to_id[w] for w in words]) return sequence, word_to_id, id_to_word def create_cooccurrence_matrix(sequence, vocabrary_size, context_size=3): &quot;&quot;&quot; Args: sequence: word index sequence of the original corpus text vocabrary_size: number of words in the vocabrary (same with co-occurrence vector size) context_size: context (N-gram size N) within which to check co-occurrences. &quot;&quot;&quot; n = sequence_size = len(sequence) co_ccurrence_matrix = np.zeros((vocabrary_size, vocabrary_size), dtype=np.int32) stride = int((context_size - 1)/2 ) assert(n &gt; stride), &quot;sequence_size {} is less than/equal to stride {}&quot;.format( n, stride ) for position in range(0, n): co_ccurrence_matrix[ sequence[position], # position to the word sequence[max(0, position-stride) : min((position+stride),n-1) +1] # positions to co-occurrence words ] += 1 np.fill_diagonal(co_ccurrence_matrix, 0) return co_ccurrence_matrix corpus= &quot;To be, or not to be, that is the question&quot; sequence, word_to_id, id_to_word = preprocess(corpus) vocabrary_size = max(word_to_id.values()) + 1 create_cooccurrence_matrix(sequence, vocabrary_size , 3) --- [[0 2 0 1 0 0 0 0] [2 0 1 0 1 0 0 0] [0 1 0 1 0 0 0 0] [1 0 1 0 0 0 0 0] [0 1 0 0 0 1 0 0] [0 0 0 0 1 0 1 0] [0 0 0 0 0 1 0 1] [0 0 0 0 0 0 1 0]] </code></pre> <h2>Profiling</h2> <p>Using <a href="https://www.researchgate.net/publication/2873803_The_Penn_Treebank_An_overview" rel="nofollow noreferrer">Penn Treebank</a> <a href="https://github.com/tomsercu/lstm/tree/master/data" rel="nofollow noreferrer">data from the site of Tom Sercu</a>.</p> <pre><code>%lprun -T create_cooccurrence_matrix.log -f create_cooccurrence_matrix create_cooccurrence_matrix(corpus, vocab_size, 3) print(open('create_cooccurrence_matrix.log', 'r').read()) --- Timer unit: 1e-06 s Total time: 23.0015 s File: &lt;ipython-input-8-27f5e530d4ff&gt; Function: create_cooccurrence_matrix at line 1 Line # Hits Time Per Hit % Time Line Contents ============================================================== 1 def create_cooccurrence_matrix(sequence, vocabrary_size, context_size=3): 2 &quot;&quot;&quot; 3 Args: 4 sequence: word index sequence of the original corpus text 5 vocabrary_size: number of words in the vocabrary (same with co-occurrence vector size) 6 context_size: context (N-gram size N) within to check co-occurrences. 7 Returns: 8 co_occurrence matrix 9 &quot;&quot;&quot; 10 1 4.0 4.0 0.0 n = sequence_size = len(sequence) 11 1 98.0 98.0 0.0 co_occurrence_matrix = np.zeros((vocabrary_size, vocabrary_size), dtype=np.int32) 12 13 1 5.0 5.0 0.0 stride = int((context_size - 1)/2 ) 14 1 1.0 1.0 0.0 assert(n &gt; stride), &quot;sequence_size {} is less than/equal to stride {}&quot;.format( 15 n, stride 16 ) 17 18 &quot;&quot;&quot; 19 # Handle position=slice(0 : (stride-1) +1), co-occurrences=slice(max(0, position-stride): min((position+stride),n-1) +1) 20 # Handle position=slice((n-1-stride) : (n-1) +1), co-occurrences=slice(max(0, position-stride): min((position+stride),n-1) +1) 21 indices = [*range(0, (stride-1) +1), *range((n-1)-stride +1, (n-1) +1)] 22 #print(indices) 23 24 for position in indices: 25 debug(sequence, position, stride, False) 26 co_occurrence_matrix[ 27 sequence[position], # position to the word 28 sequence[max(0, position-stride) : min((position+stride),n-1) +1] # indices to co-occurance words 29 ] += 1 30 31 32 # Handle position=slice(stride, ((sequence_size-1) - stride) +1) 33 for position in range(stride, (sequence_size-1) - stride + 1): 34 co_occurrence_matrix[ 35 sequence[position], # position to the word 36 sequence[(position-stride) : (position + stride + 1)] # indices to co-occurance words 37 ] += 1 38 &quot;&quot;&quot; 39 40 929590 1175326.0 1.3 5.1 for position in range(0, n): 41 2788767 15304643.0 5.5 66.5 co_occurrence_matrix[ 42 1859178 2176964.0 1.2 9.5 sequence[position], # position to the word 43 929589 3280181.0 3.5 14.3 sequence[max(0, position-stride) : min((position+stride),n-1) +1] # positions to co-occurance words 44 929589 1062613.0 1.1 4.6 ] += 1 45 46 1 1698.0 1698.0 0.0 np.fill_diagonal(co_occurrence_matrix, 0) 47 48 1 2.0 2.0 0.0 return co_occurrence_matrix </code></pre> <h1>Related</h1> <ul> <li><a href="https://codereview.stackexchange.com/questions/235633/generating-a-co-occurrence-matrix">Generating a co-occurrence matrix</a> - Using looping to get the matrix</li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T11:22:00.887", "Id": "254032", "Score": "0", "Tags": [ "numpy", "matrix", "vectorization" ], "Title": "Vectorized numpy co-occurrence matrix generation" }
254032
<p>I am attempting to write a Python code to simulate many particles in a confined box. These particles behave in such a way that they move in the box in straight lines with a slight angular noise (small changes in the direction of the particle path). They should interact by acknowledging the other particle and 'shuffle/squeeze' past each other and continue on their intended path, much like humans on a busy street. Eventually, the particles should cluster together when the density of particles (or packing fraction) reaches a certain value.</p> <p>However, I have a feeling there are parts of the code that are inefficient or which could be either sped up or written more conveniently.</p> <p>If anyone has any improvements for the code speed or ideas which may help with the interactions and/or angular noise that would be much appreciated. I will also leave an example of an animation which is my aim: <a href="https://warwick.ac.uk/fac/sci/physics/staff/research/cwhitfield/abpsimulations" rel="nofollow noreferrer">https://warwick.ac.uk/fac/sci/physics/staff/research/cwhitfield/abpsimulations</a></p> <p>The above link shows the animation I am looking for, although I don't need the sliders, just the box, and moving particles. The whole code is shown below:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation def set_initial_coordinates(): x_co = [np.random.uniform(0, 2) for i in range(n_particles)] y_co = [np.random.uniform(0, 2) for i in range(n_particles)] return x_co, y_co def set_initial_velocities(): x_vel = np.array([np.random.uniform(-1, 1) for i in range(n_particles)]) y_vel = np.array([np.random.uniform(-1, 1) for i in range(n_particles)]) return x_vel, y_vel def init(): ax.set_xlim(-0.05, 2.05) ax.set_ylim(-0.07, 2.07) return ln, def update(dt): xdata = initialx + vx * dt ydata = initialy + vy * dt fx = np.abs((xdata + 2) % 4 - 2) fy = np.abs((ydata + 2) % 4 - 2) for i in range(n_particles): for j in range(n_particles): if i == j: continue dx = fx[j] - fx[i] # distance in x direction dy = fy[j] - fy[i] # distance in y direction dr = np.sqrt((dx ** 2) + (dy ** 2)) # distance between x if dr &lt;= r: force = k * ((2 * r) - dr) # size of the force if distance is less than or equal to radius # Imagine a unit vector going from i to j x_comp = dx / dr # x component of force y_comp = dy / dr # y component of force fx[i] += -x_comp * force # x force fy[i] += -y_comp * force # y force ln.set_data(fx, fy) return ln, # theta = np.random.uniform(0, 2) for i in range(n_particles) n_particles = 10 initialx, initialy = set_initial_coordinates() vx, vy = set_initial_velocities() fig, ax = plt.subplots() x_co, y_co = [], [] ln, = plt.plot([], [], 'bo', markersize=15) # radius 0.05 plt.xlim(0, 2) plt.ylim(0, 2) k = 1 r = 0.1 t = np.linspace(0, 10, 1000) ani = FuncAnimation(fig, update, t, init_func=init, blit=True, repeat=False) plt.show() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T18:29:36.377", "Id": "501013", "Score": "2", "body": "@SᴀᴍOnᴇᴌᴀ Hi, the code supplied does work for the functions I have mentioned above and I would like to improve the lines above. In the other post, I am asking questions about lines that I have attempted but not completed. I would like to both improve this code and add new features but my question here is only asking for review/improvement, hopefully, this can keep it on topic?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T18:50:50.390", "Id": "501016", "Score": "1", "body": "Okay - thanks for explaining that. I have retracted my close vote. I hope you receive valuable feedback." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T19:38:35.647", "Id": "501024", "Score": "1", "body": "@SᴀᴍOnᴇᴌᴀ No worries, apologies for the confusion" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-16T20:20:24.613", "Id": "502545", "Score": "0", "body": "Has it to be matplotlib? The OO structure there has a huge penalty in time complexity, these lags are noticeable in animations. I did once a similar simulation in an answer to a question using pygame with a much smoother feeling: https://stackoverflow.com/questions/29374247/lennard-jones-potential-simulation" } ]
[ { "body": "<h2>Coordinates as a matrix</h2>\n<p>This:</p>\n<pre><code>x_co = [np.random.uniform(0, 2) for i in range(n_particles)]\ny_co = [np.random.uniform(0, 2) for i in range(n_particles)]\nreturn x_co, y_co\n</code></pre>\n<p>is a little baffling. You call into Numpy to generate uniformly distributed numbers (good) but then put it in a list comprehension (not good) and separate <code>x</code> and <code>y</code> into separate lists (not good).</p>\n<p>Consider instead</p>\n<pre><code>return np.random.uniform(low=0, high=2, size=(2, n_particles))\n</code></pre>\n<p>and similarly for <code>set_initial_velocities</code>:</p>\n<pre><code>return np.random.uniform(low=-1, high=1, size=(2, n_particles))\n</code></pre>\n<p>All of the rest of your code, such as the calculations for <code>xdata</code>/<code>ydata</code> should similarly vectorize over the new length-2 dimension eliminating distinct code for <code>x</code> and <code>y</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T10:49:25.493", "Id": "501250", "Score": "0", "body": "Hi @Reinderien, thanks for your advice. Quick question about vectorising; should I keep my x_co and y_co lines below the 'def...' line and replace my current return line with your return line like this\n\n\"def set_initial_coordinates():\n x_co = [np.random.uniform(0, 2) for i in range(n_particles)]\n y_co = [np.random.uniform(0, 2) for i in range(n_particles)]\n return np.random.uniform(low=0, high=2, size=(2, n_particles))\"\n\nor do this\n\n\"def set_initial_coordinates():\n return np.random.uniform(low=0, high=2, size=(2, n_particles))\"\n\nor are both of those not what you meant?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T15:25:12.827", "Id": "501276", "Score": "0", "body": "The second one is what I meant." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T20:29:48.830", "Id": "501298", "Score": "0", "body": "Awesome, thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-16T17:33:34.700", "Id": "502533", "Score": "0", "body": "@LutzLehmann You're entirely right. The premise of that entire section was wrong so I just deleted it." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T15:20:03.710", "Id": "254137", "ParentId": "254033", "Score": "2" } }, { "body": "<h3>On the implementation of the dynamic</h3>\n<p>The (first) value that <code>animate</code> passes to the <code>update</code> function as argument is the frame number, if you use that as <code>dt</code> you can expect some strangely accelerating particles. As your dynamic does not depend on time, the frame number should not enter the computation. The time step is a global constant related to the frame rate.</p>\n<p>On second glance,</p>\n<pre><code>xdata = initialx + vx * dt\n</code></pre>\n<p>is completely wrong. That is to say, yes, you can use it, but the resulting dynamic is rather unnatural. What you intend to do is to implement the (symplectic) Euler method for</p>\n<pre><code>dx/dt = vx, dy/dt = vy\ndvx/dt = force_x(x), dvy/dt = force_y(x)\n</code></pre>\n<p>so you should increase the particle positions incrementally as you do with the velocities.</p>\n<p>As dynamic on the torus, <code>dx</code> and <code>dy</code> should also be reduced by the torus period <code>4</code> using the same centering formula, <code>dx = (dx+2)%4-2</code> etc. Else you miss interactions that cross the wrap-around lines.</p>\n<p>Just as you have the time step in the position update, you should also have it in the velocity update</p>\n<pre><code>fx[i] += -x_comp * force * dt # x force\n</code></pre>\n<p>Otherwise you get a substantially different dynamic if you change <code>dt</code>.</p>\n<hr />\n<p>Overall, I got following code implementing the corrected dynamic and some numpy tricks</p>\n<pre><code>from matplotlib.animation import FuncAnimation\n\ndef dynamic_gen(n_particles, r_particles, elasticity, dt):\n x,y = np.random.uniform(low=0, high=2, size=(2, n_particles))\n vx,vy = np.random.uniform(low=-1, high=1, size=(2, n_particles))\n yield x,y\n r = r_particles\n k = elasticity\n while True:\n x += vx*dt; x = (x+2)%4-2\n y += vy*dt; y = (y+2)%4-2\n # dx[i,j] = x[i]-x[j]\n dx = x[:,None]-x[None,:]; dx = (dx+2)%4-2\n dy = y[:,None]-y[None,:]; dy = (dy+2)%4-2\n\n dr = np.hypot(dx,dy)\n dr = np.ma.masked_where( ~((0&lt;dr)&amp;(dr&lt;r)), dr )\n \n force = k*(2*r-dr)\n vx += np.ma.sum(force*dx/dr,axis=1)*dt\n vy += np.ma.sum(force*dy/dr,axis=1)*dt\n yield x,y\n \ndef update(t,dynamic,scatter):\n x,y = next(dynamic)\n scatter.set_data([x,y])\n return scatter,\n\nn_particles = 400\nk = 20\nr = 0.2\nt = np.linspace(0, 4, 1000)\ndynamic = dynamic_gen(n_particles,r,k,t[1]-t[0])\nx,y = next(dynamic)\n\nfig, ax = plt.subplots(1,1,figsize=(8,8))\nscatter, = ax.plot(x,y,'ob',ms=5)\nax.set_xlim(-2,2); ax.set_ylim(-2,2)\n\nani = FuncAnimation(fig, update, frames=t, fargs=(dynamic,scatter), blit=True, repeat=False)\nplt.show()\n</code></pre>\n<p>Guiding ideas:</p>\n<ul>\n<li><p>separate computation and plotting code by providing a stepper for the dynamic progress in the form of a generator function, so that in the update function the only steps are &quot;get new model data&quot; and &quot;modify plot scene data&quot;</p>\n</li>\n<li><p>In the physics simulation, avoid explicit python loops, shift everything to implicit numpy loops behind the scenes. This is at the cost of creating some large objects in memory, but should be significantly faster.</p>\n</li>\n<li><p>Use the broadcasting trick <code>dx = x[:,None]-x[None,:]</code>, so that `dx[i,j]=x[i]-x[j]</p>\n</li>\n<li><p>Use a masked arrays from <code>numpy.ma</code> to select the pairs of particles with non-zero forces and restrict the computation of the forces to them.</p>\n</li>\n<li><p>Use the appropriate sum function, sum over <code>axis=1</code>, that is, over the <code>j</code> index.</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-16T08:30:03.763", "Id": "254786", "ParentId": "254033", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T11:23:33.423", "Id": "254033", "Score": "3", "Tags": [ "python", "numpy", "animation" ], "Title": "Active Brownian Motion" }
254033
<p>This is my project(beta) after studying for 3 weeks. It took me more or less 30 hours of writing and researching. I would appreciate a review based on my beginner level. I'm very proud of it, it was hard work for me.</p> <p>Learned... Files management, control <code>if</code> <code>for</code> <code>while</code> loops, integers and strings, lists dictionaries and tuples.</p> <p>Code:</p> <pre><code>#C:\restaurant software with open('names.txt', 'r') as r : f_n = r.read().splitlines() print(&quot;Welcome to NAME.app&quot;) ############## # USER LOGIN # ############## while True: name = input(&quot;&quot;&quot; \n - Insert name to logg in \n - ADD to save new user \n - LIST to see saved users \n - REMOVE to delete a user \n - EXIT to finish \n - ...&quot;&quot;&quot;) lname = name.lower() if lname == &quot;add&quot;: n_input = input(&quot;Name:&quot;) with open('names.txt', 'a') as f: f.write(n_input + '\n') elif lname == &quot;list&quot;: with open('names.txt') as f: print(f.read().splitlines()) f.close() elif name in f_n: print(&quot;Logged as&quot;, name.upper()) user = name input('Welcome, press enter to continue \n') break elif lname == 'remove': rem = input(&quot;Insert user name to remove \n ...&quot;) with open('names.txt', 'r+') as f: l = f.readlines() l = [z for z in l if rem not in z] with open('names.txt', 'w') as f: f.writelines(l) elif lname == &quot;exit&quot;: exit() #################### # TABLE MANAGEMENT # #################### #C:\restaurant software while True: action = input (''' - NEW table \n - ADD table \n - BILL \n - CLOSING \n - EXIT \n - ... ''') d = {'(1) chburger': 19,'(2) bncburger': 23,'(3) plpasta': 6} if action == 'new' : tn = input('Insert table number \n - ...') name = 'T' + tn t = open(name + '.txt', 'w+') print('Done') elif action.lower() == 'add': # Select table table = input ('Select desired table number: \n - ...') fulltab = 'T' + table with open(fulltab + '.txt', 'w+') as f : # Order list and add Order while True: for k, v in d.items() : print(k, v) addprod = input('Insert order. \n - ...') for k, v in d.items() : if addprod == k[1] : f.write(str(v) + '\n') #Option to continue. q = input('Add more? y/n \n -...') if q.lower() == 'y' : continue if q.lower() == 'n' : break #File as F elif action.lower() == 'bill' : p_b = input('Please insert number of table. \n -... ') with open (('T' + p_b)+ '.txt', 'r+') as p : tobill = 0 for line in p : tobill = int(tobill) + int(line) xtra = input('Group table (+10 ppl)? y/n: \n') if xtra == 'y' : tobill = tobill + (tobill/100)*10 print('SERVICE CHARGE ADDED.') elif xtra == 'n' : print ('Processing bill...') print('Total to pay:', tobill) print('Serviced by', user) #### Closing added part to bill. with open('closing.txt', 'a+') as f : f.write(str(tobill) + '\n') # Closing days balance. elif action.lower() == 'closing' : date = input('Please enter DATE. ') with open('closing.txt', 'r+') as f : result = 0 for line in f : result = int(result) + int(line) print('Closing is...') print(result) print('Today tips', (result / 100 * 10)) current_closing = 'C:restaurant software\\closing.txt' old_closing = 'C:restaurant software\\' + date + '.txt' import os os.rename(current_closing, old_closing) print('Day closed, find the closing balance in the specific dated document.') # Exit command. elif action.lower() == 'exit' : exit() </code></pre> <p>I know I have to improve the log in system with the possible names that someone could enter and a lot more of things.</p> <p>Before starting this project the largest that I write was 30 lines.</p>
[]
[ { "body": "<h1>Functions</h1>\n<p>Study functions. Your code would greatly benefit from breaking up into functions.</p>\n<h1>Bugs</h1>\n<h2>User Management</h2>\n<ul>\n<li>If you add the name &quot;Anne&quot;, you cannot login with the name &quot;Anne&quot; until you quit and restart the program.</li>\n<li>If you remove the name &quot;Anne&quot;, you can still login with the name &quot;Anne&quot; until you quit and restart the program.</li>\n<li>If you remove the name &quot;Anne&quot;, it will also remove the name &quot;Mary-Anne&quot;.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T00:10:49.420", "Id": "254068", "ParentId": "254038", "Score": "4" } }, { "body": "<h2>File storage</h2>\n<p>Text files are not convenient for lookups. So your next logical step should be to learn about databases and SQL. With Python you can use SQLite to build a small, self-contained database file.</p>\n<h2>Security</h2>\n<p>Entering a user name is not enough, there should be a password too. I am assuming this is for a family business or a small circle of very trusting people. Speaking of accountability, I would advise that you get familiar with the Python logging module. I would <strong>log</strong> all meaningful events to a file. For example, when booking a table, it is interesting to know who carried out the action and when. Then a single line like this would result in a timestamped entry into the log file:</p>\n<pre><code>logger.info(f&quot;Table #{table_number} booked by user {username}&quot;)\n</code></pre>\n<p>Same when cashing in money, this type of event should be recorded (who-what-when), preferably not in a place that can easily be tampered with, even if I understand you are not a bank.</p>\n<h2>Don't repeat yourself (DRY)</h2>\n<p>There is a lot of <strong>repetition</strong> eg <code>with open('names.txt', 'r+') as f:</code>. The file name (and path) should be declared once as a 'constant' variable at the top of the script. Then break up your code in small <strong>functions</strong>. For example a function to check if a user name is valid - it has to return True or False. Each menu entry should call a function, to better separate tasks and to keep the code as small and lean as possible.</p>\n<p>The files are surely very small, but to optimize things, you could load the lists once, when starting up your program. Reload them only if changes occur.</p>\n<h2>User input</h2>\n<p><strong>Validation of user input</strong> is very important or your program will crash or behave predictably. That may involve regular expressions depending on the patterns you need to validate.</p>\n<h2>Coding style</h2>\n<p>Imports like <code>import os</code> should be at the top of the script, not declared just before using some function. Get familiar with PEP8 coding rules. This: <code>with open('closing.txt', 'a+') as f :</code> should be written: <code>with open('closing.txt', 'a+') as f:</code>. You are doing it right in some parts of the code but not everywhere. Consistency is important and PEP8 is considered the Bible of Python programmers.</p>\n<p>I suggest to use an editor with a linter that will help enforce those rules and highlight problematic lines.</p>\n<p>It is good that you are using <strong>context managers</strong> with files, but then you don't need to explicitly close the file here:</p>\n<pre><code>elif lname == &quot;list&quot;:\n with open('names.txt') as f:\n print(f.read().splitlines())\n f.close()\n</code></pre>\n<p>...as long as you stick with this approach, which is the recommended way and not just for files.</p>\n<p>Give more thoughts about <strong>variable naming</strong>. For example in this code the name <code>f_n</code> is not intuitive:</p>\n<pre><code>elif name in f_n:\n print(&quot;Logged as&quot;, name.upper())\n user = name\n input('Welcome, press enter to continue \\n')\n break\n</code></pre>\n<p>It should be user_names, valid_users or something like that. Then you can write:</p>\n<pre><code>if user in valid_users:\n # ...\n</code></pre>\n<p>Which makes the code semantically more clear, more intuitive and easier to read.</p>\n<p>Another selected snippet:</p>\n<pre><code>p_b = input('Please insert number of table. \\n -... ')\nwith open (('T' + p_b)+ '.txt', 'r+') as p :\n</code></pre>\n<p>what does <code>p_b</code> mean ? Pay the bill I suppose... Fortunately the variable is defined just above and I don't have to scroll 500 lines of code to find out what it means. Seems to me that <code>p_b</code> should be named <code>table_number</code> simply. There is no penalty for using longer and more meaningful variable names. Only benefits.</p>\n<p>For loop should be formatted like this:</p>\n<pre><code>for line in p:\n tobill = int(tobill) + int(line)\n</code></pre>\n<p>instead of:</p>\n<pre><code>for line in p : tobill = int(tobill) + int(line)\n</code></pre>\n<p>Another more cryptic line:</p>\n<pre><code>l = [z for z in l if rem not in z]\n</code></pre>\n<p>Without analyzing your code it's not immediately <strong>obvious</strong> what this line is doing. Even if it's clear to you now, it won't be when you revisit your code after a few months.</p>\n<p>To further comment on the offending code:</p>\n<pre><code>elif lname == 'remove':\n rem = input(&quot;Insert user name to remove \\n ...&quot;)\n with open('names.txt', 'r+') as f:\n l = f.readlines()\n l = [z for z in l if rem not in z]\n with open('names.txt', 'w') as f:\n f.writelines(l)\n</code></pre>\n<p>First of all, you are rebuilding the list of users every time. The performance hit is negligible until you work with large files. Clearly, using files has its limits for what you are doing. But the approach is <strong>unsafe</strong>, you could destroy the file if an exception occurs in this code section. And exceptions related to file I/O are pretty common, between permissions issues, lack of disk space or path errors. One more reason for using a database (with <em>transactions</em>).</p>\n<p>Imagine that you make a mistake in the file name when reading it, and accidentally read from another file that happens to exist. What do you think the ultimate result would be when you write to names.txt ? That's one more reason for not repeating yourself. Define file names and paths as constants once for all. At some point you may have to change the file name or path, and it's better to change it at one place only, rather than review all the code manually, at the risk of missing out one line, or do a search and replace that may be incomplete.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T10:04:37.373", "Id": "501179", "Score": "1", "body": "Wow! I suppose this will take me a good few days to fix. And I'm going straight to learn about SQL. Thank you very much for the time you spent writing this, it really helps me." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T23:27:24.007", "Id": "254113", "ParentId": "254038", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T13:26:43.463", "Id": "254038", "Score": "4", "Tags": [ "python", "beginner", "python-3.x" ], "Title": "Python beginner - Restaurant software project" }
254038
<p>I have a simple class, called website which is able to get the html of a website (if the website html is not provided), the urls inside the website, the contents of the title, and description tag. As well as providing an array populated with the words, and objects representing the website image. My main concern is whether I should use existing libraries like cheerio or not, because I only want these 5 functions (where cheerio has many more) so it may be overkill. Also, cheerio cannot return an array populated with words and images (like in my content function), so I am still wondering if the advantages of cheerio outweigh the benefits. Also are there any alternatives to using regex to parse html as html is irregular?</p> <p>Here is the class</p> <pre><code>function Query(haystack) { this.haystack = haystack; this.find = function(needle) { let position = 0; let positions = []; let i = -1; while (position !== -1) { position = this.haystack.indexOf(needle, i + 1); positions.push(position); i = position; }; positions.pop(); return positions; }; this.count = function(needle) { let position = 0; let count = -1; let i = -1; while (position !== -1) { position = this.haystack.indexOf(needle, i + 1); count += 1; i = position; }; return count; }; this.individualize = function () { const seen = {}; for (item of this.haystack) { seen[item] = true; }; return Object.keys(seen); }; }; function Website(url, html) { this.url = url; this.html = html; this.request = function () { return new Promise(async (resolve) =&gt; { try { const response = await fetch(this.url); const htmlCode = await response.text(); resolve({ url, htmlCode }); } catch { resolve(&quot;Error&quot;); }; }); }; this.urls = function () { const query = new Query(this.html); const urlStarts = query.find(&quot;&lt;a&quot;); return urlStarts.map((index) =&gt; { const start = this.html.indexOf('href=&quot;', index) + 6; const end = this.html.indexOf('&quot;', start); return this.html.substring(start, end); }).filter((urlItem) =&gt; { return urlItem[0] !== &quot;#&quot; &amp;&amp; urlItem.substring(0, 11) !== &quot;:javascript&quot; }) .map(urlItem =&gt; new URL(urlItem, this.url).href); }; this.title = function () { const titlePosition = this.html.indexOf(&quot;&lt;title&quot;); const start = this.html.indexOf(&quot;&gt;&quot;, titlePosition) + 1; const end = this.html.indexOf(&quot;&lt;&quot;, start); return this.html.substring(start, end); }; this.description = function () { const descriptionMeta = this.html.indexOf('name=&quot;description&quot;'); if (descriptionMeta !== -1) { const query = new Query(this.html); const metaStarts = query.find(&quot;&lt;meta&quot;); for (metaStart of metaStarts) { const metaEnd = this.html.indexOf(&quot;&gt;&quot;, metaStart); if (descriptionMeta &lt; metaEnd) { const contentStart = this.html.indexOf('content=&quot;', metaStart) + 9; const contentEnd = this.html.indexOf('&quot;', contentStart); return this.html.substring(contentStart, contentEnd); }; }; }; return &quot;undefined&quot;; }; this.content = function () { const parsedHtml = this.html.split(/(?!&lt;img.+?&gt;)&lt;.+?&gt;/g).join(&quot; &quot;) .split(/(\n|\r|\t)/g).join(&quot; &quot;); let contentList = []; for (i = 0; i &lt; parsedHtml.length; i++) { const previousToken = i === 0 ? &quot; &quot; : parsedHtml[i - 1]; const currentToken = parsedHtml[i]; if (parsedHtml.substring(i, i + 4) === &quot;&lt;img&quot;) { const end = parsedHtml.indexOf(&quot;&gt;&quot;, i) + 1; const srcStart = parsedHtml.indexOf('src=&quot;', i) + 5 const srcEnd = parsedHtml.indexOf('&quot;', srcStart); const srcRelative = parsedHtml.substring(srcStart, srcEnd); const src = new URL(srcRelative, this.url).href; const altStart = parsedHtml.indexOf('alt=&quot;', i) + 5; const altEnd = parsedHtml.indexOf('&quot;', altStart); let alt = parsedHtml.substring(altStart, altEnd); if (alt === &quot;&quot;) alt = &quot;undefined&quot;; contentList.push({ alt, src, parent: this.url }); i = end; } else if (currentToken !== &quot; &quot; &amp;&amp; previousToken === &quot; &quot;) { let end = parsedHtml.indexOf(&quot; &quot;, i) ; if (end === -1) end = parsedHtml.length; const words = parsedHtml.substring(i, end); contentList = contentList.concat( words.split(/[!&quot;#$%&amp;'()*+, -./:;&lt;=&gt;?@[\]^_`{|}~]/g) .map(word =&gt; stemmer(word.toLowerCase())) ); i = end; }; }; return contentList; }; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-04T23:28:04.383", "Id": "501549", "Score": "0", "body": "1) Is there a reason you aren't using `class` syntax? 2) Include example use case(s) please" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T15:22:06.890", "Id": "254041", "Score": "0", "Tags": [ "javascript", "node.js", "web-scraping" ], "Title": "Node.js html parser class" }
254041
<p>A part of my day job is load-testing of our infrastructure. I wanted a tool to quickly write a load scenario for some application (DB, HTTP, ...). I have tried to write something in Haskell (a fairly new language for me). Would someone help me improve by reviewing the code?</p> <p>This is the main module:</p> <pre><code>module Load.Core ( runLoadN, Config (..), ) where import Control.Concurrent (ThreadId, forkIO) import Control.Concurrent.STM (STM, atomically, newEmptyTMVar, putTMVar, readTMVar) import Control.Concurrent.STM.TBMQueue (TBMQueue, closeTBMQueue, newTBMQueue, readTBMQueue, writeTBMQueue) import Control.Concurrent.STM.TSem (TSem, newTSem, signalTSem, waitTSem) import Control.Concurrent.TokenBucket (newTokenBucket, tokenBucketWait) import Control.Exception.Lifted (finally) import Control.Monad (replicateM_, void) import Control.Monad.Base (MonadBase, liftBase) import Control.Monad.Trans.Control (MonadBaseControl, liftBaseWith) import Data.Default (Default, def) import Data.Word import Numeric.Natural data Config m a b c = Config { supplier :: m a, performer :: a -&gt; IO b, collector :: b -&gt; c -&gt; c, workers :: Natural, queue :: Natural, rate :: Double, burst :: Integer } runLoadN :: (MonadBase IO m, MonadBaseControl IO m, Default c) =&gt; Natural -&gt; Config m a b c -&gt; m c runLoadN nat cfg = do let n = toInt nat let w = toInt $ workers cfg let q = toInt $ queue cfg let b = fromIntegral $ burst cfg let r = toInvRate $ rate cfg let perf = performer cfg let coll = collector cfg let supp = supplier cfg jobq &lt;- atomically' $ newTBMQueue q resq &lt;- atomically' $ newTBMQueue q mvar &lt;- atomically' newEmptyTMVar sema &lt;- atomically' $ newTSem 0 tobu &lt;- liftBase newTokenBucket startWorkers w perf jobq resq sema tobu r b _ &lt;- forkIO' $ closing resq $ \_ -&gt; waitForWorkers w sema _ &lt;- forkIO' $ closing jobq $ supplyRequests n supp _ &lt;- forkIO' $ collectResults coll def resq mvar atomically' . readTMVar $ mvar where collectResults f z resq mv = do mbNxt &lt;- atomically' $ readTBMQueue resq case mbNxt of Nothing -&gt; atomically' $ putTMVar mv z Just nxt -&gt; let z' = f nxt z in seq z' $ collectResults f z' resq mv supplyRequests n supp q = replicateM_ n (supp &gt;&gt;= \req -&gt; atomically' $ writeTBMQueue q req) waitForWorkers w sema = atomically' (replicateM_ w (waitTSem sema)) startWorkers w perf jobq resq sema tobu r b = do replicateM_ w $ forkIO' $ signaling sema $ performRequests perf jobq resq tobu r b -- todo: what about exceptions? performRequests perf jobq resq tobu r b = run where run = do mbreq &lt;- atomically' (readTBMQueue jobq) case mbreq of Nothing -&gt; return () Just req -&gt; do res &lt;- liftBase $ tokenBucketWait tobu b r &gt;&gt; perf req atomically' $ writeTBMQueue resq res run -- performs f on the queue and closes it afterwards -- -- use for sending requests, closing when done closing :: (MonadBaseControl IO m) =&gt; TBMQueue a -&gt; (TBMQueue a -&gt; m ()) -&gt; m () closing q f = f q `finally` atomically' (closeTBMQueue q) -- performs f and signals the the semaphore afterwards -- -- use for worker threads, signaling that they are done signaling :: (MonadBaseControl IO m) =&gt; TSem -&gt; m () -&gt; m () signaling sem f = f `finally` atomically' (signalTSem sem) -- some convenience methods -- -- forkIO' :: MonadBaseControl IO m =&gt; m () -&gt; m ThreadId forkIO' m = liftBaseWith $ \runInBase -&gt; forkIO (void $ runInBase m) atomically' :: (MonadBaseControl IO m) =&gt; STM a -&gt; m a atomically' stm = liftBase $ atomically stm toInt :: Natural -&gt; Int toInt = fromIntegral . toInteger toInvRate :: Double -&gt; Word64 toInvRate r = round (1e6 / r) </code></pre> <p>Repository can be found here: <a href="https://gitlab.com/michoffmann/load" rel="nofollow noreferrer">https://gitlab.com/michoffmann/load</a></p>
[]
[ { "body": "<p>From a quick glance, I would say you're on the right track. It might be worthwhile to bust up the work being done by Config into two components:</p>\n<ul>\n<li><code>Config</code>: the pure configuration elements; workers, queue, rate, burst; and</li>\n<li><code>Env</code>: the (effectful) environment state; supplier, performer, collector.</li>\n</ul>\n<p>And then think about creating a few boiler-plate functions (not including the polymorphic Env bits):</p>\n<pre><code>new :: Config -&gt; IO Env\nclose :: Env -&gt; IO ()\ncheck :: Env -&gt; IO Text\n\nwithConfig :: Config -&gt; (Config -&gt; Env -&gt; IO ()) -&gt; IO ()\nwithConfig c cont = bracket (new c) close (cont c)\n</code></pre>\n<p>Once you have this, you can create a new environment, play around with it, and properly close it in a robust way. As it stands, and given my workflow preferences, I would think that <code>runLoadN</code> is too monolithic for easy maintenance and extension.</p>\n<p>General descriptions of these refactors include the <a href=\"https://jaspervdj.be/posts/2018-03-08-handle-pattern.html\" rel=\"nofollow noreferrer\">handle pattern</a> and the <a href=\"https://www.schoolofhaskell.com/user/meiersi/the-service-pattern\" rel=\"nofollow noreferrer\">service pattern</a>. The <a href=\"https://www.parsonsmatt.org/2018/03/22/three_layer_haskell_cake.html\" rel=\"nofollow noreferrer\">three layer cake</a> is classic also though I suspect you don't need the extra complexity.</p>\n<p>With runLoadN freed of environment setup and teardown you'll be able to see more clearly the key components of the process.</p>\n<p>A few vague guesses about other aspect of the code:</p>\n<ul>\n<li><p>I would work towards refactoring away the convenience functions. Do you really need the extra monadic complexity? Can it all be IO?</p>\n</li>\n<li><p>the collector looks like a WriterT or logger, and might be simplified by using those patterns.</p>\n</li>\n<li><p>There are a lot of polymorphic types being thrown around. Both m and IO, in particular, exists in Config, which might suggest some refactoring needed. I reckon you could aim for just an <code>Env</code> without any polymorphism.</p>\n</li>\n<li><p>If you're always altering pure Config types (with toInt), then it's better to change the Config types instead.</p>\n</li>\n<li><p>I would suggest that best practice is to define a <code>defaultConfig :: Config</code> explicitly, rather than run through Data.Default and use the anonymising <code>def</code> pattern</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-09T23:55:42.357", "Id": "254507", "ParentId": "254042", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T16:14:13.107", "Id": "254042", "Score": "1", "Tags": [ "haskell" ], "Title": "generic load testing tool" }
254042
<p><strong>I would very much appreciate it if someone could review the php script below for any security risks.</strong></p> <p>I have a live website using shared hosting. There's a page that accepts text submissions from users. The message is sent to a phpmyadmin database table; nothing is printed immediately to HTML. The messages are stored in the table for my review, and I manually put the text onto the page if I choose to.</p> <p>I spent several months monitoring a user who would submit <code>&lt;script&gt;alert('xssvuln');&lt;/script&gt;</code> every Monday morning around 6AM. The JavaScript alert has never shown up on the page itself, but it is instead stored in the table as a regular string. While I'm confident that there are no xss attack vulnerabilities in my scripts, I have disabled the input form for the time being. I assume the user ip is spoofed and it is automatically making these submissions. What purpose does this repetition serve if the alert is not injected to the html? Is there anything I'm missing?</p> <h2>About the PHP Script...</h2> <p>Along with the message, I also store the user's IPv4 address and the date-time that the submission was made. This is for archival purposes. I prefer the yyyymmdd-hhmm format, which is why I have it done automatically in the script. I'm aware that <code>htmlspecialchars()</code> is only effective for when you are printing directly to HTML. The same can be said for the trimming of whitespace. The <code>filter_var()</code> string sanitization is included just to be safe. While mutating the script like this is not preferred, I would like to for cosmetic reasons. I'm primarily concerned about whether including these things in the script opens it up for any type of attack.</p> <p><strong>Table Variables:</strong></p> <ul> <li>id, int(11), AI</li> <li>IPv4, varbinary(34)</li> <li>datetime, varchar(18)</li> <li>message, text</li> </ul> <h2>HTML</h2> <pre><code>&lt;form action=&quot;script.php&quot; method=&quot;POST&quot; autocomplete=&quot;off&quot;&gt; &lt;textarea placeholder=&quot;*Type here&quot; type=&quot;text&quot; maxlength=&quot;20000&quot; required wrap=&quot;soft&quot; name=&quot;message&quot; autocomplete=&quot;off&quot;&gt;&lt;/textarea&gt;&lt;br/&gt; &lt;br/&gt; &lt;div&gt; &lt;button id=&quot;button02&quot; type=&quot;submit&quot; value=&quot;Send&quot; style=&quot;cursor: pointer;&quot;&gt;Send&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <h2>PHP</h2> <pre><code>&lt;?php //1---DATABASE CONNECTION--- $bHost = &quot;localhost&quot;; $bName = &quot;x&quot;; $bUser = &quot;x&quot;; $bPassword = &quot;x&quot;; $bport = &quot;x&quot;; $bcharset = &quot;x&quot;; $boptions = [ \PDO::ATTR_ERRMODE =&gt; \PDO::ERRMODE_EXCEPTION, \PDO::ATTR_DEFAULT_FETCH_MODE =&gt; \PDO::FETCH_ASSOC, \PDO::ATTR_EMULATE_PREPARES =&gt; false, ]; $bdsn = &quot;mysql:host=$dbHost;dbname=$bName;charset=$bcharset;port=$bport&quot;; try { $bpdo = new \PDO($bdsn, $bUser, $bPassword, $boptions); } catch (\PDOException $b) { throw new \PDOException($b-&gt;getMessage(), (int)$b-&gt;getCode()); } //1---END--- //2---ADD INPUT TO DATABASE--- date_default_timezone_set('America/Los_Angeles'); //set timezone $datetime = date('Ymd-Hi', strtotime('NOW')); //date and time variable $userIP4 = $_SERVER['REMOTE_ADDR']; //ipv4 address variable if($_SERVER['REQUEST_METHOD'] == 'POST') { $Tmessage = trim(preg_replace(['/^\s+|\s+$/u', '/\s{2,}/u'], ['', ' '], htmlspecialchars($_POST[&quot;message&quot;]))); //trim whitespace from message $sanitizedMessage = filter_var($Tmessage, FILTER_SANITIZE_STRING); //prepare info and submit into table $statmnt = $bpdo-&gt;prepare(&quot;INSERT INTO table (IP4, datetime, message) VALUES (:IP4, :datetime, :message)&quot;); $statmnt-&gt;execute(['IP4' =&gt; $userIP4, 'datetime' =&gt; $datetime, 'message' =&gt; $sanitizedMessage]); header(&quot;Location: success.html&quot;); exit (0); } header(&quot;Location: failure.html&quot;); exit (0); //2---END--- ?&gt; </code></pre> <p><em>Please let me know in the comments if there is any further information I can provide.</em></p> <p><em>Edit: Please see the comments below before submitting an answer. While I've made <a href="https://codereview.stackexchange.com/questions/250132/sanitizing-user-form-input-in-php">posts</a> about this subject before, the answers that I received on them derailed from the original inquiry. I understand that this is not the way to do things, but I would prefer to unless this opens up a security risk. If this is the case, please let me know. Otherwise, I would appreciate an answer regarding the <code>&lt;script&gt;alert('xssvuln');&lt;/script&gt;</code> submissions that I was receiving.</em></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T20:26:41.223", "Id": "501026", "Score": "0", "body": "I've always leaned to the idea of letting the raw data be raw data, and to ensure that the presentation filters according to the medium used (therefore, applying `htmlspecialchars()` when getting the data to present as html). This requires a CRUD object that handles all things going in and out of the database, so you have a single place to apply `htmlspecialchars()`. But, perhaps it's better to prevent junk from getting into the database. Hoping to see some others weigh in on this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T21:28:52.093", "Id": "501032", "Score": "0", "body": "wait...[they already have weighed in](https://codereview.stackexchange.com/a/250137/146968), hence your comment about htmlentities and trim. *What purpose does this repetition serve...?* It’s probably a bot, probing for unfiltered response, just patiently waiting for you to stop paying attention. It’s also probably waiting in vain... especially if you’re not confirming submitted data by repeating it back." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T10:37:58.397", "Id": "501079", "Score": "0", "body": "@Cod why are you calling `trim()` after the multibyte trim pattern is already executed?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T16:28:41.490", "Id": "501118", "Score": "0", "body": "@TimMorton I promise Im a not a bot. When I manually add the user messages to the HTML, I prefer to simply copy and paste it from the table. With this in mind, I prefer to have certain characters mutated into their character codes. Using htmlspecialchars() is the best way to do this. What I would like to know is does this open up any security risks?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T16:31:13.240", "Id": "501119", "Score": "0", "body": "@mickmackusa I call trim after the multibyte because the multibyte does not remove a single space from the end of the string, trim() does. The multibyte is there to mutate multiple spaces into a single space. Trim() does this on the end of the string, but not anywhere else (in the middle). Including both covers all bases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T16:49:28.270", "Id": "501122", "Score": "0", "body": "You disabled the user input *because it doesn't* have an XSS vulnerability...?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T17:15:38.883", "Id": "501125", "Score": "0", "body": "@user253751 It doesn't have a vulnerability as far as I'm aware, but it's possible I'm overlooking something that someone else could point out." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T18:16:22.783", "Id": "501130", "Score": "2", "body": "The fact that someone is *trying* a vulnerability doesn't mean there is one. Of course, there might be one. But you shouldn't assume there is one just because someone is trying to exploit it. Literally every server on the internet gets these \"attacks\" - hackers have automatic programs that try to exploit everything they can think of." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T19:22:54.027", "Id": "501145", "Score": "1", "body": "@CodeLoveGuy I was saying the “attack” is probably coming from a bot. It’s going to keep probing, but you passed the test, and it learned nothing. In addition, you’re manually screening submissions. Are you paranoid enough? Yeah, I think so!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T21:13:00.153", "Id": "501154", "Score": "1", "body": "@Cod please revisit my review on your earlier question (mentioned by Tim in the secons comment here). You will notice that the `/^\\s+|\\s+$/u` pattern that I recommended ONLY removes multibyte whitespace characters from the start and end of the string. I think you misunderstood what it does. This is why I did not use `trim()` in my suggested snippet. `^` means the start of the string and `$` means the end of the string." } ]
[ { "body": "<p>It is commendable to be concerned about security. But don’t let the fear of the unknown cripple you.</p>\n<h3>The attack</h3>\n<p>First, hackers typically go for the low-hanging fruit. They will use known exploits and search for code that is vulnerable. They’re looking for careless mistakes.</p>\n<p>This particular one is probing to see if they can inject javascript and have it executed. For example, this code would be vulnerable:</p>\n<pre><code>if($_POST['message']) {\n $message = $_POST['message'];\n $db-&gt;query(&quot;insert into table (message) values('$message')&quot;);\n echo &quot;You have submitted: $message&quot;;\n}\n</code></pre>\n<p>While this code actually has several vulnerabilities (a <em>notice</em> might be generated for missing key, not using prepared statement, and unsanitized echo), the only one being targeted (at this point) is the unsanitized echo.</p>\n<p>The probe would be considered successful if an alert popped up in the echoed message. The payload is negligible, except that it serves as a signal that more devious things are possible.</p>\n<h3>Danger to your code from this probe</h3>\n<p>Practically none. You are using prepared statements, and don’t even appear to be echoing the message back to the user. Furthermore, you’re even applying htmlentities <em>before</em> saving to the database, and htmlentities is probably sufficient to stop it in its tracks. <em><strong>And if that weren’t enough, you’re approving each one and manually pasting what is shown.</strong></em></p>\n<h3>Validation vs Sanitation</h3>\n<p>As you’ve been told before, you should validate input and sanitize output. There is absolutely no danger to your database by applying <code>htmlentities</code> before you save the data. The database doesn’t care; it’s just a string.</p>\n<p>So what’s the issue? Why does everyone object to it?</p>\n<ul>\n<li>Your data is not being stored accurately. This would completely mess up binary and xml data.</li>\n<li>This discourages using htmlentities when showing content. (The browser would show the htmlentity code, not the actual entity). So in practice, it discourages best practice.</li>\n<li>Back in the php3 era, before prepared statements were available, you had to <code>addslash</code> data before saving it, then <code>stripslash</code> it before presenting it. Sometimes it would accidentally get addslashed twice (magic quotes) and then you had a real mess on your hands. The validate/sanitize advice comes from a long history of learning from hard knocks.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T21:48:04.890", "Id": "254107", "ParentId": "254045", "Score": "1" } } ]
{ "AcceptedAnswerId": "254107", "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T17:04:57.840", "Id": "254045", "Score": "0", "Tags": [ "javascript", "php", "html", "security", "sql-injection" ], "Title": "Recieving an XSS Injection: <script>alert('xssvuln');</script>" }
254045
<p>I'm currently learning C# in hopes of making games on my own using Unity. I'm using the Udemy class by Denis Panjuta and followed 8 sections before making my first app by myself.</p> <p>The 8 sections include Datatypes and Variables, Functions and Methods, Making decisions, Loops, OOP, Arrays and List, and Debugging. I know how important it is to maintain best practices in code, but being new this gets... overwhelming pretty fast.</p> <p>I'm looking for good practices considering what I know, as I will be able to go further once I acquire more knowledge, of course.</p> <p>In this game, you play a character who has to work on a school project and need to chose what to do everyday in order to increase specific stats. He has 50 days to finish his project and must defeat 4 bosses, one of which has 3 phases.</p> <p>I'm using 5 classes; the first is <code>BattleSystem</code> which handles battles:</p> <pre><code>using System; namespace My_first_game { // This class handles battles. class BattleSystem { private static bool isOver = false; // The battle handles everything needed to have an encounter. public static void Battle(Character player) { bool playerTurn = true; // needs to be true in order for first turn to be the players string playerInput; // will hold what the player types in bool correctInput; // will check if the input is correct int healAmount; int damageAmount; int phase; Enemy boss = GetEnemy(Story.chapter); bool alreadyDone = false; int numberOfHeals = player.insight / 3; string bossLine = &quot;&quot;; while (!isOver) // while the battle is not over { phase = DeterminePhase(boss.bossHp, boss.bossTotalHp); if (playerTurn) // should start here and then alternate { Console.WriteLine(&quot;\n&quot; + boss.lines[phase][0]); bossLine = AlternateDialogue(phase, boss); // To avoid the boss saying a line that doesn't match with the phase starter. Console.WriteLine(&quot;Do you want to (W)ork or take a (B)reak?&quot;); do // here we read the line as long as the player does an incorrect input { playerInput = Console.ReadLine(); if (playerInput == &quot;W&quot; || playerInput == &quot;w&quot;) // to deal damage { damageAmount = Character.DealDamage(player); boss.bossHp -= damageAmount; Console.WriteLine(&quot;The boss has {0} hp remaining&quot;, boss.bossHp); if (boss.bossHp &lt;= 0) isOver = true; correctInput = true; } else if (playerInput == &quot;B&quot; || playerInput == &quot;b&quot;) // to heal { if (numberOfHeals &gt; 0) { healAmount = Program.DiceRoll() * (player.knowledge / 2); Character.Heal(healAmount, player); numberOfHeals--; Console.WriteLine(&quot;You have {0} heals left.&quot;, numberOfHeals); correctInput = true; } else { Console.WriteLine(&quot;You don't have any heals left&quot;); correctInput = false; } } else // if input is anything but w, W, b or B { Console.WriteLine(&quot;Please enter (w) to heal or (b) to attack.&quot;); correctInput = false; } } while (!correctInput); if (((float)boss.bossHp / (float)boss.bossTotalHp * 100) &lt;= boss.insightTrigger &amp;&amp; !alreadyDone) alreadyDone = Enemy.InsightCheck(Story.chapter, player, boss); playerTurn = false; } else // if it's not the players turn, do the enemy turn { Console.WriteLine(bossLine); Character.TakeDamage(boss.attackDamage, player); playerTurn = true; } } Console.WriteLine(&quot;You won the battle! Press enter to continue!&quot;); Console.ReadLine(); } // This section will alternate what the boss will say. private static string AlternateDialogue(int phase, Enemy boss) { int rng = new Random().Next(1, 5); string line = boss.lines[phase][rng]; return line; } // Determines which phase the boss is at by fourths of hp left public static int DeterminePhase(int currentHp, int totalHp) { int phase = 0; float lifePercent = ((float)currentHp / (float)totalHp) * 100; if (lifePercent &gt; 75f) phase = 0; else if (lifePercent &gt; 50f) phase = 1; else if (lifePercent &gt; 25f) phase = 2; else phase = 3; return phase; } // This takes in the chapter the player is at and figures out which boss to output. public static Enemy GetEnemy(int chapter) { Enemy enemie = new Enemy(); switch (chapter) { case 1: enemie = Enemy.Boss1(); break; case 2: enemie = Enemy.Boss2(); break; case 3: enemie = Enemy.Boss31(); break; case 4: enemie = Enemy.Boss32(); break; case 5: enemie = Enemy.Boss33(); break; case 6: enemie = Enemy.Boss4(); break; } return enemie; } } } </code></pre> <p>The second one is <code>Enemy</code> for my boss designs:</p> <pre><code>using System; namespace My_first_game { // This class handles the boss creation process class Enemy { public int bossHp; public int bossTotalHp; public int attackDamage; // the first line of every subarray is the step the character is at, the rest is dialogue public string[][] lines; // For insight boosts public float insightTrigger; // At what point in the boss health does the effect triggers public int insightThreshold; // how much insight the player needs // constructor public Enemy(int hp, int ad, string[][] text, float itr, int ith) { bossTotalHp = hp; bossHp = bossTotalHp; attackDamage = ad; lines = text; insightTrigger = itr; insightThreshold = ith; } // temp constructor empty public Enemy() { } // The bosses should all increase in difficulty the further you go down // The patern is variables for balance, insight stuff, Strings for phases 1 to 4, then creating the array, then creating it with the arrays // Boss 1 is choosing the subject public static Enemy Boss1() { int hp = 300; int ad = new Random().Next(1, 5); float itr = 0f; int ith = 10; string t1 = &quot;The first step is finding something original.&quot;; string t11 = &quot;Trying to find something original?&quot;; string t12 = &quot;Everything has already been done.&quot;; string t13 = &quot;Do you really think nobody thought of that?&quot;; string t14 = &quot;Wow, I'm sure noooobody ever worked on that subject...&quot;; string t2 = &quot;Now, you need to find the subject interesting yourself.&quot;; string t21 = &quot;That subject looks booooooring.&quot;; string t22 = &quot;Do you really find this interesting?&quot;; string t23 = &quot;Imagine just talking about this to your friends... See their long faces?&quot;; string t24 = &quot;You will never finish if you chose this subject.&quot;; string t3 = &quot;Your subject needs to find the perfect balance between vagueness and preciseness.&quot;; string t31 = &quot;That subject is too vague...&quot;; string t32 = &quot;That's way too precise, you won't have enough data.&quot;; string t33 = &quot;Are you planing on doing 500 pages?&quot;; string t34 = &quot;You know you need at least 80 pages worth of content, right?&quot;; string t4 = &quot;Finally, make sure your subject is doable.&quot;; string t41 = &quot;You won't be able to find any data on this subject.&quot;; string t42 = &quot;You really think you're going to find people to interview over there? Keep dreaming.&quot;; string t43 = &quot;There's just not enough scientific sources around to chose that subject.&quot;; string t44 = &quot;Where are you going to find the funds to make that project?&quot;; string[][] lines = new string[][] { new string[] { t1, t11, t12, t13, t14 }, new string[] { t2, t21, t22, t23, t24 }, new string[] { t3, t31, t32, t33, t34 }, new string[] { t4, t41, t42, t43, t44 } }; Enemy boss1 = new Enemy(hp, ad, lines, itr, ith); return boss1; } // Boss 2 is the directed reading seminary. public static Enemy Boss2() { int hp = 425; int ad = new Random().Next(1, 6); float itr = 50f; int ith = 12; string t1 = &quot;You need to make time to read.&quot;; string t11 = &quot;You don't have the time to work on that.&quot;; string t12 = &quot;You've got bills to pay, just work instead of reading.&quot;; string t13 = &quot;Your appartment is a mess... Maybe you should clean it up?&quot;; string t14 = &quot;When's the last time you took time off?&quot;; string t2 = &quot;Make sure you are motivated!&quot;; string t21 = &quot;You'd rather be playing video games right now...&quot;; string t22 = &quot;You know who you haven't seen in a while? Remember that highschool friend?&quot;; string t23 = &quot;Finish up quickly here, there's a party at 8.&quot;; string t24 = &quot;Why are these texts so uninteresting? Hey, author, can you spice things up a little?&quot;; string t3 = &quot;Taking good notes while you read is crucial! It will help down the line.&quot;; string t31 = &quot;Reading with a pen in hand is so much slower.&quot;; string t32 = &quot;It really feels like your not making any progress with all these scribbles.&quot;; string t33 = &quot;Are these notes even worthwhile?&quot;; string t34 = &quot;You are never going to read these.&quot;; string t4 = &quot;Guess what, you have a paper to produce on your readings...&quot;; string t41 = &quot;Oh no... a blank page appears!&quot;; string t42 = &quot;You're only repeating what those authors said. YOU're not saying anything original here.&quot;; string t43 = &quot;Are you seriously going to write that?&quot;; string t44 = &quot;You thought this would be over in an hour didn't you?&quot;; string[][] lines = new string[][] { new string[] { t1, t11, t12, t13, t14 }, new string[] { t2, t21, t22, t23, t24 }, new string[] { t3, t31, t32, t33, t34 }, new string[] { t4, t41, t42, t43, t44 } }; Enemy boss2 = new Enemy(hp, ad, lines, itr, ith); return boss2; } // Boss 3 is subdivised in 3 sub bosses which follow the difficulty curve as if they were 3 seperate bosses. // Boss 3-1 is argument 1 public static Enemy Boss31() { int hp = 525; int ad = new Random().Next(2, 7); float itr = 100f; int ith = 14; string t1 = &quot;Let's start right away with your first argument. You'll do the intro later.&quot;; string t11 = &quot;The first page of project, what are you going to write?&quot;; string t12 = &quot;How do you even start an argument?&quot;; string t13 = &quot;You've done this all your bachelors degree, and now, you just can't...&quot;; string t14 = &quot;You've read on this a ton, don't you have anything to say?&quot;; string t2 = &quot;Still on this first argument, but now you've got it going.&quot;; string t21 = &quot;Look at you typing now! Are you sure this is all good?&quot;; string t22 = &quot;Oh, I wouldn't phrase it like this...&quot;; string t23 = &quot;Have you eaten? ooh, grab a bite!&quot;; string t24 = &quot;That's a load of bullshit you're writing there. You should start this part again.&quot;; string t3 = &quot;All is said and done. You should do a mini-conclusion here.&quot;; string t31 = &quot;It's just a single paragraph... What, are you too tired?&quot;; string t32 = &quot;Is this really what you said?&quot;; string t33 = &quot;It feels like you could've read a bit more before writing.&quot;; string t34 = &quot;Time to fact check this info real quick, just in case...&quot;; string t4 = &quot;Time to finish up. Correct these typos.&quot;; string t41 = &quot;You're, your, yuor...&quot;; string t42 = &quot;That sentence... really makes no sense.&quot;; string t43 = &quot;Are you even a masters degree student? What's with this language?&quot;; string t44 = &quot;[insert corrector app] has crashed! Send an error report?&quot;; string[][] lines = new string[][] { new string[] { t1, t11, t12, t13, t14 }, new string[] { t2, t21, t22, t23, t24 }, new string[] { t3, t31, t32, t33, t34 }, new string[] { t4, t41, t42, t43, t44 } }; Enemy boss31 = new Enemy(hp, ad, lines, itr, ith); return boss31; } // Boss 3-2 is argument 2 public static Enemy Boss32() { int hp = 650; int ad = new Random().Next(2, 8); float itr = 100f; int ith = 16; string t1 = &quot;Chapter 2 now! This should be your last argument.&quot;; string t11 = &quot;Your worst enemy once again appears: the blank page!&quot;; string t12 = &quot;Maybe you should just write something and come back to it later.&quot;; string t13 = &quot;Why must you go though this all the time?&quot;; string t14 = &quot;You'd think you'd be better at writing words as time goes by...&quot;; string t2 = &quot;Now you're all setup. The rest *should* be a breeze!&quot;; string t21 = &quot;Shouldn't this go in the first argument? It feels like it should...&quot;; string t22 = &quot;That whole section needs more precision. It feels like you havn't read enough.&quot;; string t23 = &quot;Something feels off... Start over?&quot;; string t24 = &quot;You feel like you really shouldn't have gone for a masters degree...&quot;; string t3 = &quot;Time to conclude the second part.&quot;; string t31 = &quot;Get your thoughts together, this should be easy.&quot;; string t32 = &quot;Is this section really different than the first one?&quot;; string t33 = &quot;It feels like this whole section is pointless.&quot;; string t34 = &quot;Maybe take a break? I don't know.&quot;; string t4 = &quot;Revision, revision, revision...&quot;; string t41 = &quot;Look how many mistakes you've made.&quot;; string t42 = &quot;This should be something you should've mastered in fifth grade.&quot;; string t43 = &quot;Corrector shows 30 errors... in 6 pages...&quot;; string t44 = &quot;This sentence is missing words, again!&quot;; string[][] lines = new string[][] { new string[] { t1, t11, t12, t13, t14 }, new string[] { t2, t21, t22, t23, t24 }, new string[] { t3, t31, t32, t33, t34 }, new string[] { t4, t41, t42, t43, t44 } }; Enemy boss32 = new Enemy(hp, ad, lines, itr, ith); return boss32; } // Boss 3-3 is intro, conclu and finishing up public static Enemy Boss33() { int hp = 750; int ad = new Random().Next(2, 9); float itr = 100f; int ith = 18; string t1 = &quot;On to the introduction of your project!&quot;; string t11 = &quot;How do you back to the introduction now?&quot;; string t12 = &quot;It feels like I should've started here.&quot;; string t13 = &quot;That thesis is all wrong.&quot;; string t14 = &quot;What even is a problem statement...&quot;; string t2 = &quot;Now for the conclusion. The end is near.&quot;; string t21 = &quot;This should be the easiest part. Just type it.&quot;; string t22 = &quot;I almost don't want this to be done.&quot;; string t23 = &quot;What am I really bringing to the table here?&quot;; string t24 = &quot;I should just rush this part... No one will notice.&quot;; string t3 = &quot;Spell checking. Let's check the whole document, just to make sure everything is in order.&quot;; string t31 = &quot;Spell checking again...&quot;; string t32 = &quot;Mistakes in the sections I've already corrected? How do new ones keep poping up?&quot;; string t33 = &quot;All these sentences are starting to blend in together.&quot;; string t34 = &quot;You've used the same words how many time in the past 4 lines? 5?&quot;; string t4 = &quot;Time to put the layout in place.&quot;; string t41 = &quot;Just going to change the font aaaand... everything is out of place.&quot;; string t42 = &quot;Why did you type in 3 different font sizes?&quot;; string t43 = &quot;Those footnotes are horrible. One is completely missing.&quot;; string t44 = &quot;What name are you going to give to this paper? It should be obvious but...&quot;; string[][] lines = new string[][] { new string[] { t1, t11, t12, t13, t14 }, new string[] { t2, t21, t22, t23, t24 }, new string[] { t3, t31, t32, t33, t34 }, new string[] { t4, t41, t42, t43, t44 } }; Enemy boss33 = new Enemy(hp, ad, lines, itr, ith); return boss33; } // Boss 4 is the defense of project public static Enemy Boss4() { int hp = 900; int ad = new Random().Next(4, 9); float itr = 100f; int ith = 20; string t1 = &quot;This is really the last stretch. You've got this!&quot;; string t11 = &quot;How do you even prepare for this?&quot;; string t12 = &quot;Should you dress in something... I don't know... official?&quot;; string t13 = &quot;What are they going to say? This is stressful&quot;; string t14 = &quot;So they can have you start over again? You really don't want to go through this again.&quot;; string t2 = &quot;This is far from perfect, but what did you expect? Everything right the first try? You'll get it right in the actual thesis!&quot;; string t21 = &quot;Lot's and lot's of criticism. Did they even like it?&quot;; string t22 = &quot;You're going to fail aren't you?&quot;; string t23 = &quot;This is going horribly.&quot;; string t24 = &quot;They can't even agree on their criticism.&quot;; string t3 = &quot;You won't be able to reuse this unless you work on it a bit more.&quot;; string t31 = &quot;How many comments are on this paper? Did they really hate it that much?&quot;; string t32 = &quot;Will you be able to reuse any of this?&quot;; string t33 = &quot;I am not starting this over again.&quot;; string t34 = &quot;This comment doesn't feel fair at all... Is the professor projecting or something?&quot;; string t4 = &quot;You've put something out in the world. Criticism is part of the experience.&quot;; string t41 = &quot;They say you defend it, but you're really just sitting there, taking the criticism in.&quot;; string t42 = &quot;Can't they just tell if they liked it or not? Why keep the suspense going?&quot;; string t43 = &quot;Almost... there...&quot;; string t44 = &quot;It feels like they want you to do their thing.&quot;; string[][] lines = new string[][] { new string[] { t1, t11, t12, t13, t14 }, new string[] { t2, t21, t22, t23, t24 }, new string[] { t3, t31, t32, t33, t34 }, new string[] { t4, t41, t42, t43, t44 } }; Enemy boss4 = new Enemy(hp, ad, lines, itr, ith); return boss4; } public static void InsightEffect(int chap, Character c, Enemy e) { switch (chap) { case 1: // Increases insight by 50% Console.WriteLine(&quot;With your subject in mind, your insight has increased&quot;); c.insight += (c.insight / 2); break; case 2: // Restores WP by 20% Console.WriteLine(&quot;Now that you made time and are motivated, you gain a boost in will&quot;); c.currentWP += (c.totalWP / 5); if (c.currentWP &gt; c.totalWP) c.currentWP = c.totalWP; break; case 3: // Skip first phase of the boss fight (25% health damage at the start of battle) Console.WriteLine(&quot;You are insightful enough to start writing right away&quot;); e.bossHp -= (e.bossTotalHp / 4); break; case 4: // Skip first phase of the boss fight (25% health damage at the start of battle) Console.WriteLine(&quot;You are insightful enough to start writing right away&quot;); e.bossHp -= (e.bossTotalHp / 4); break; case 5: // Skip first phase of the boss fight (25% health damage at the start of battle) Console.WriteLine(&quot;You are insightful enough to start writing right away&quot;); e.bossHp -= (e.bossTotalHp / 4); break; case 6: // Increases knowledge by 20% Console.WriteLine(&quot;Your insight garantees you'll have all the right answers. Your knowledge is increased.&quot;); c.knowledge += (c.knowledge / 5); break; } } public static bool InsightCheck(int chap, Character c, Enemy e) { bool success = false; if (c.insight &gt;= e.insightThreshold) { InsightEffect(chap, c, e); success = true; } return success; } } } </code></pre> <p>Then I have <code>Story</code> for my story elements:</p> <pre><code>using System; namespace My_first_game { // This class contains all the story bits class Story { public static int chapter = 1; // the first thing you see, not a part of the actual game public static void Intro() { Console.WriteLine(&quot;Welcome to this game.&quot;); Console.WriteLine(&quot;You will play a character trying to complete his thesis draft.&quot;); Console.WriteLine(&quot;Let's start by creating your character.&quot;); Console.WriteLine(Program.line + &quot;\n&quot;); } // reminds the player what story beats he needs to do public static void Reminder() { switch (chapter) { case 1: Console.WriteLine(&quot;You still need to chose your subject before anything else. Maybe get on that?&quot;); break; case 2: Console.WriteLine(&quot;Between 2 500 and 3 000 pages to read? Better be ready for it!&quot;); break; case 3: Console.WriteLine(&quot;This is it! You know your stuff, you just need to write it down.&quot;); break; case 4: Console.WriteLine(&quot;You've written a lot, but there is still more to go.&quot;); break; case 5: Console.WriteLine(&quot;Almost finished. This is the last stretch!&quot;); break; case 6: Console.WriteLine(&quot;WHAT? You need to defend this thing? Okay, better be prepared.&quot;); break; } } public static void NoShow(Character p, int willHit) { Console.WriteLine(&quot;You decided not to go, but you regret it.&quot;); Console.WriteLine(&quot;The hit on your will was pretty big.&quot;); Character.TakeDamage((willHit), p); Program.StartNewDay(); } public static void Work(Character p) { int willHit = 10; int insIncrease = 1; Console.WriteLine(&quot;It is wednesday my dudes.&quot;); Console.WriteLine(&quot;Time to go to work.&quot;); Console.WriteLine(&quot;Once you come back, you are too exhausted to get back to your project.&quot;); Console.WriteLine(&quot;At least, you've made enough money to survive another week.&quot;); Console.WriteLine(&quot;(Who said this game was realistic?)&quot;); Console.WriteLine(&quot;Your will has taken a hit, but your determination has increased&quot;); Character.TakeDamage(willHit, p); p.insight += insIncrease; } public static void PartyInvite(Character p) { bool isValid; int detIncrease = 3; int willHit = 5; Console.WriteLine(&quot;Today, your friends invited you over for a party.&quot;); Console.WriteLine(&quot;This might be a great way to unwind.&quot;); do // as long as the player doesn't input a valid string { Console.WriteLine(&quot;Would you like to go? (Y)es or (N)o?&quot;); string choice = Console.ReadLine(); if (choice == &quot;Y&quot; || choice == &quot;y&quot;) { Console.WriteLine(&quot;You had a great time in the party!&quot;); Console.WriteLine(&quot;Unfortunately, you weren't able to put in meaningful work.&quot;); Console.WriteLine(&quot;Your determination has increased!&quot;); Console.WriteLine(&quot;... but your will has taken a hit&quot;); p.determination += detIncrease; Character.TakeDamage(willHit, p); Console.WriteLine(&quot;Press enter to continue.&quot;); Console.ReadLine(); isValid = true; } else if (choice == &quot;N&quot; || choice == &quot;n&quot;) { NoShow(p, (willHit * 2)); isValid = true; } else { Console.WriteLine(&quot;Your answer did not register.&quot;); isValid = false; } } while (!isValid); } public static void DineAtParents(Character p) { bool isValid; int detDecrease = 1; int insIncrease = 1; int knowIncrease = 1; int willHit = 5; Console.WriteLine(&quot;Your parents invited you to your weekly diner.&quot;); Console.WriteLine(&quot;They'll want to know how you're progressing.&quot;); do // as long as the player doesn't input a valid string { Console.WriteLine(&quot;Would you like to go? (Y)es or (N)o?&quot;); string choice = Console.ReadLine(); if (choice == &quot;Y&quot; || choice == &quot;y&quot;) { Console.WriteLine(&quot;The food was good (and free) but the questions were hard.&quot;); Console.WriteLine(&quot;It feels like you haven't made discernable progress in your project.&quot;); Console.WriteLine(&quot;Maybe you don't have anything to report...&quot;); Console.WriteLine(&quot;Your will was replenished, your insight increased, as did your knowledge. But your determination has decreased.&quot;); p.determination -= detDecrease; p.totalWP = Character.CalculateTotalWP(p.determination); p.currentWP = p.totalWP; p.insight += insIncrease; p.knowledge += knowIncrease; Console.WriteLine(&quot;Press enter to continue.&quot;); Console.ReadLine(); isValid = true; } else if (choice == &quot;N&quot; || choice == &quot;n&quot;) { NoShow(p, (willHit * 2)); isValid = true; } else { Console.WriteLine(&quot;Your answer did not register.&quot;); isValid = false; } } while (!isValid); } public static int Trip(Character p) { bool isValid; int daysLost = 3; int detIncrease = 2; int insIncrease = 2; int knowIncrease = 2; int willHit = 15; Console.WriteLine(&quot;Your friends invite you over for a road trip, lasting {0} days.&quot;, daysLost); Console.WriteLine(&quot;You really could use those days off...&quot;); do // as long as the player doesn't input a valid string { Console.WriteLine(&quot;Would you like to go? (Y)es or (N)o?&quot;); string choice = Console.ReadLine(); if (choice == &quot;Y&quot; || choice == &quot;y&quot;) { Console.WriteLine(&quot;You had a great time with your friends!&quot;); Console.WriteLine(&quot;You had time to discuss about various subjects, some of wich might pertain to your project.&quot;); Console.WriteLine(&quot;Not only did you learn a lot in your trip, but you feel refreshed&quot;); p.determination += detIncrease; p.insight += insIncrease; p.knowledge += knowIncrease; p.currentWP = Character.CalculateTotalWP(p.determination); Console.WriteLine(&quot;Press enter to continue.&quot;); Console.ReadLine(); isValid = true; } else if (choice == &quot;N&quot; || choice == &quot;n&quot;) { NoShow(p, willHit); Console.WriteLine(&quot;Seriously, you should've gone.&quot;); daysLost = 1; isValid = true; } else { Console.WriteLine(&quot;Your answer did not register.&quot;); isValid = false; } } while (!isValid); return daysLost; } // lose state, will exit the game. // Considering not ending the game and putting back player in day to day with 1 WP. It would be more modern game design public static void GameOver(Character c) { Console.WriteLine(&quot;\n\n{0} has lost his will to complete his draft. Try again!&quot;, c.name); Console.WriteLine(&quot;Press enter to close the game!&quot;); Console.ReadKey(); Environment.Exit(0); } // win state will exit the game public static void Win(Character c) { Console.WriteLine(&quot;{0} has officialy finished his project!&quot;, c.name); Console.WriteLine(&quot;Congratulations on finishing this simple game. I hope you enjoyed it.&quot;); Console.WriteLine(&quot;A sequel should be coming quote-unquote soon!&quot;); Console.WriteLine(&quot;Press enter to close the game!&quot;); Console.ReadKey(); Environment.Exit(0); } } } </code></pre> <p>Next comes <code>Character</code> for handling the player character:</p> <pre><code>using System; namespace My_first_game { // This class handles creating and managing the character. class Character { public string name; public int determination; // same as vitality public int knowledge; // same as strength public int insight; // same as intelligence public int currentWP; // WP is like HP public int totalWP; private static int baseStats = 5; // For balancing stats applies to all of them // constructor public Character(string nam, int det, int know, int ins) { name = nam; determination = det; knowledge = know; insight = ins; totalWP = CalculateTotalWP(determination); currentWP = totalWP; } // puts the user in charge of creating the character using dicerolls public static Character GenerateCharacter() { Console.WriteLine(&quot;To create a character, enter a name:&quot;); string name = Console.ReadLine(); Console.WriteLine(&quot;\nNow, let's take care of the stats.\n&quot;); Console.WriteLine(&quot;The first stat we need to check is determination.&quot;); Console.WriteLine(&quot;This will determine how much will {0} has (think of it like HP).&quot;, name); Console.WriteLine(&quot;Roll the dice 2 times:&quot;); int det = Program.DiceRoll() + Program.DiceRoll() + baseStats; // between 7 and 17 Console.WriteLine(&quot;{0}s determination is {1}\n&quot;, name, det); Console.WriteLine(&quot;Next, let's see how knowledgeable your character is.&quot;); Console.WriteLine(&quot;{0}s knowledge will determine how hard the problems will be tackled.&quot;, name); Console.WriteLine(&quot;Roll the dice once&quot;); int know = Program.DiceRoll() + baseStats; // between 6 and 11 Console.WriteLine(&quot;{0}s knowledge is {1}\n&quot;, name, know); Console.WriteLine(&quot;Finally, we need to determine how insightful your character is.&quot;); Console.WriteLine(&quot;{0}s insight will give bonuses during fights and determine the number of times you can heal in a fight.&quot;, name); Console.WriteLine(&quot;Roll the dice once:&quot;); int ins = Program.DiceRoll() + baseStats; // between 6 and 11 Console.WriteLine(&quot;{0}s insight is {1}\n&quot;, name, ins); Character player = new Character(name, det, know, ins); ShowStats(player); Console.WriteLine(&quot;\nPress enter to continue&quot;); Console.ReadLine(); return player; } // Handles the calculations to dertermine the total WP, needs to be updatable public static int CalculateTotalWP(int det) { int minimumWP = 10; int result = minimumWP + (det*2); // so initial total wp is from 24 to 44 return result; } // Handles the balance for the number of heals the player gets public static int CalculateNumberOfHeals(int ins) { int numHeals = ins / 3; return numHeals; } // Is in charge of showing the players stats public static void ShowStats(Character c) { c.totalWP = CalculateTotalWP(c.determination); Console.WriteLine(&quot; &quot;.PadRight(Console.BufferWidth - 2) + &quot;\n&quot; + Program.line); Console.WriteLine(&quot;Name: {0}&quot;, c.name); Console.WriteLine(&quot;Determination: {0}&quot;, c.determination); Console.WriteLine(&quot;Knowledge: {0}&quot;, c.knowledge); Console.WriteLine(&quot;Insight: {0}&quot;, c.insight); Console.WriteLine(&quot;WP: {0}/{1}&quot;, c.currentWP, c.totalWP); Console.WriteLine(Program.line); } // Handles when the character is hurt, either by boss or story beats public static void TakeDamage(int amount, Character c) { if (amount &gt;= c.currentWP) // check to see if he dies { Console.WriteLine(&quot;\n{0} took {1} damage to will.&quot;, c.name, amount); c.currentWP = 0; Story.GameOver(c); } else { c.currentWP -= amount; Console.WriteLine(&quot;\n{0} took {1} damage to will.&quot;, c.name, amount); Console.WriteLine(&quot;{0} has {1} will point remaining&quot;, c.name, c.currentWP); } } // The amount that is healed in battle is calculated in BattleSystem public static void Heal(int amount, Character c) { if (amount &gt;= (c.totalWP - c.currentWP)) { Console.WriteLine(&quot;{0} healed by {1}.&quot;, c.name, (c.totalWP - c.currentWP)); c.currentWP = c.totalWP; } else { c.currentWP += amount; Console.WriteLine(&quot;{0} healed by {1}.&quot;, c.name, amount); } Console.WriteLine(&quot;{0} currently has {1} out of {2} will points&quot;, c.name, c.currentWP, c.totalWP); } //When the character attacks public static int DealDamage(Character c) { int roll = Program.DiceRoll(); float damageModifier = 1.5f; int damage = Convert.ToInt32((c.knowledge + roll) * damageModifier); Console.WriteLine(&quot;{0} hit for {1}&quot;, c.name, damage); return damage; } // The next methods handle the day to day activities. They help boost the characters stats public static void HangoutFriends(Character c) { Console.WriteLine(&quot; &quot;.PadRight(Console.BufferWidth - 2) + &quot;\n{0} chose to hangout with some friends.&quot;, c.name); Console.WriteLine(&quot;{0} is having a wonderful time.&quot;, c.name); Console.WriteLine(&quot;{0} even picked up on something while discussing the subject with them.&quot;, c.name); Console.WriteLine(&quot;{0}s insight has improved, things might get a bit easier.&quot;, c.name); Console.WriteLine(&quot;{0} is reminded that although you wish it could always be that simple, life isn't like this.&quot;, c.name); c.insight += 1; TakeDamage(5, c); Console.WriteLine(&quot;\nPress enter to continue&quot;); Console.ReadLine(); } public static void Study(Character c) { Console.WriteLine(&quot; &quot;.PadRight(Console.BufferWidth - 2) + &quot;\n{0} chose to stay in and study.&quot;.PadRight(Console.BufferWidth - 2), c.name); Console.WriteLine(&quot;{0} reads interesting material on the subject.&quot;, c.name); Console.WriteLine(&quot;{0}s knowledge has improved, {0} will fare better in the coming steps.&quot;, c.name); c.knowledge += 1; Console.WriteLine(&quot;\nPress enter to continue&quot;); Console.ReadLine(); } public static void PlayGames(Character c) { Console.WriteLine(&quot; &quot;.PadRight(Console.BufferWidth - 2) + &quot;\n{0} spent the day playing video games.&quot;.PadRight(Console.BufferWidth - 2), c.name); Console.WriteLine(&quot;{0} feels pretty bad about it, but it did make for some relaxing time.&quot;, c.name); Console.WriteLine(&quot;{0} feels revitalised, {0}s will was restored&quot;, c.name); c.currentWP = c.totalWP; Console.WriteLine(&quot;\nPress enter to continue&quot;); Console.ReadLine(); } } } </code></pre> <p>And finally, my Program:</p> <pre><code>using System; namespace My_first_game { class Program { static Character playerChar; public static string line = &quot;---------------------------&quot;; static void Main(string[] args) { Story.Intro(); playerChar = Character.GenerateCharacter(); int i = 1; do { switch (i) // isn't sexy, but it helps in case I want to add story beats to specific days { case 1: DawnOfDay(playerChar, 0, i); StartNewDay(); i++; break; case 2: DawnOfDay(playerChar, 0, i); StartNewDay(); i++; break; case 3: DawnOfDay(playerChar, 0, i); Story.Work(playerChar); i++; break; case 4: DawnOfDay(playerChar, 0, i); Story.PartyInvite(playerChar); i++; break; case 5: DawnOfDay(playerChar, 0, i); StartNewDay(); i++; break; case 6: DawnOfDay(playerChar, 0, i); StartNewDay(); i++; break; case 7: DawnOfDay(playerChar, 0, i); Story.DineAtParents(playerChar); i++; break; case 8: DawnOfDay(playerChar, 0, i); StartNewDay(); i++; break; case 9: DawnOfDay(playerChar, 1, i); Story.PartyInvite(playerChar); i++; break; case 10: DawnOfDay(playerChar, 1, i); Story.Work(playerChar); i++; break; case 11: DawnOfDay(playerChar, 1, i); StartNewDay(); i++; break; case 12: DawnOfDay(playerChar, 1, i); StartNewDay(); i++; break; case 13: DawnOfDay(playerChar, 1, i); Story.PartyInvite(playerChar); i++; break; case 14: DawnOfDay(playerChar, 1, i); Story.DineAtParents(playerChar); i++; break; case 15: DawnOfDay(playerChar, 1, i); StartNewDay(); i++; break; case 16: DawnOfDay(playerChar, 1, i); StartNewDay(); i++; break; case 17: DawnOfDay(playerChar, 2, i); Story.Work(playerChar); i++; break; case 18: DawnOfDay(playerChar, 2, i); StartNewDay(); i++; break; case 19: DawnOfDay(playerChar, 2, i); StartNewDay(); i++; break; case 20: DawnOfDay(playerChar, 2, i); StartNewDay(); i++; break; case 21: DawnOfDay(playerChar, 2, i); Story.DineAtParents(playerChar); i++; break; case 22: DawnOfDay(playerChar, 2, i); StartNewDay(); i++; break; case 23: DawnOfDay(playerChar, 2, i); StartNewDay(); i++; break; case 24: DawnOfDay(playerChar, 2, i); Story.Work(playerChar); i++; break; case 25: DawnOfDay(playerChar, 3, i); i += Story.Trip(playerChar); break; case 26: DawnOfDay(playerChar, 3, i); Story.PartyInvite(playerChar); i++; break; case 27: DawnOfDay(playerChar, 3, i); StartNewDay(); i++; break; case 28: DawnOfDay(playerChar, 3, i); Story.DineAtParents(playerChar); i++; break; case 29: DawnOfDay(playerChar, 3, i); StartNewDay(); i++; break; case 30: DawnOfDay(playerChar, 3, i); StartNewDay(); i++; break; case 31: DawnOfDay(playerChar, 3, i); Story.Work(playerChar); i++; break; case 32: DawnOfDay(playerChar, 3, i); StartNewDay(); i++; break; case 33: DawnOfDay(playerChar, 4, i); StartNewDay(); i++; break; case 34: DawnOfDay(playerChar, 4, i); StartNewDay(); i++; break; case 35: DawnOfDay(playerChar, 4, i); Story.DineAtParents(playerChar); i++; break; case 36: DawnOfDay(playerChar, 4, i); Story.PartyInvite(playerChar); i++; break; case 37: DawnOfDay(playerChar, 4, i); StartNewDay(); i++; break; case 38: DawnOfDay(playerChar, 4, i); Story.Work(playerChar); i++; break; case 39: DawnOfDay(playerChar, 4, i); StartNewDay(); i++; break; case 40: DawnOfDay(playerChar, 4, i); StartNewDay(); i++; break; case 41: DawnOfDay(playerChar, 5, i); Story.PartyInvite(playerChar); i++; break; case 42: DawnOfDay(playerChar, 5, i); Story.DineAtParents(playerChar); i++; break; case 43: DawnOfDay(playerChar, 5, i); StartNewDay(); i++; break; case 44: DawnOfDay(playerChar, 5, i); StartNewDay(); i++; break; case 45: DawnOfDay(playerChar, 5, i); Story.Work(playerChar); i++; break; case 46: DawnOfDay(playerChar, 5, i); Story.PartyInvite(playerChar); i++; break; case 47: DawnOfDay(playerChar, 5, i); StartNewDay(); i++; break; case 48: DawnOfDay(playerChar, 5, i); StartNewDay(); i++; break; case 49: DawnOfDay(playerChar, 5, i); Story.DineAtParents(playerChar); i++; break; case 50: DawnOfDay(playerChar, 5, i); StartNewDay(); i++; break; } } while (i &lt; 51); // To stop the app from closing Console.ReadKey(); } // decides a number for RNG public static int DiceRoll() { Console.WriteLine(&quot;Press enter to roll the dice&quot;); Console.ReadLine(); int result = new Random().Next(1, 7); Console.SetCursorPosition(0, Console.CursorTop - 1); Console.WriteLine(&quot;You rolled a {0}&quot;, result); return result; } public static void DawnOfDay(Character p, int expectedChapter, int day) { Console.Clear(); Console.WriteLine(&quot;{0}\nDawn of a new day.&quot;, line); Console.WriteLine(&quot;You are at day {0} out of 50.&quot;, day); ProgressionCheck(p, expectedChapter); } // Default day public static void StartNewDay() { bool isValid; int choice; Story.Reminder(); Console.WriteLine(&quot;Chose your next move carefully&quot;); Console.WriteLine(&quot;You have four choices:&quot;); Console.WriteLine(&quot;1. Hangout with friends (improves insight but lowers will)&quot;); Console.WriteLine(&quot;2. Study, study, study... (improves knowledge)&quot;); Console.WriteLine(&quot;3. Play video games (restores will)&quot;); Console.WriteLine(&quot;4. Work on your project (advances the story and improves determination)&quot;); do // as long as the player doesn't input a valid string { Console.WriteLine(&quot;Enter the corresponding number and press enter (or press s to see your stats)&quot;); string input = Console.ReadLine(); bool isInt = int.TryParse(input, out choice); Console.SetCursorPosition(0, (Console.CursorTop - 1)); if (input == &quot;s&quot;) { Character.ShowStats(playerChar); isValid = false; } else if (!isInt || choice &lt; 1 || choice &gt; 4) { isValid = false; Console.WriteLine(&quot;Your input is incorrect, try again.&quot;); Console.SetCursorPosition(0, (Console.CursorTop - 2)); } else { isValid = true; } } while (!isValid); switch (choice) { case 1: Character.HangoutFriends(playerChar); break; case 2: Character.Study(playerChar); break; case 3: Character.PlayGames(playerChar); break; case 4: Console.WriteLine(&quot;Let's see if you're ready!&quot;); playerChar.determination += 1; playerChar.totalWP = Character.CalculateTotalWP(playerChar.determination); Console.WriteLine(&quot;\nPress enter to continue&quot;); Console.ReadLine(); BattleSystem.Battle(playerChar); break; } } public static void ProgressionCheck (Character p, int expectedChapter) { int willHit = 2; if (Story.chapter &lt; expectedChapter) { Console.WriteLine(&quot;You feel like you've not made significant progress in a while.&quot;); Console.WriteLine(&quot;Your will is slowly waning.&quot;); p.currentWP -= willHit; } } } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T20:35:10.383", "Id": "501027", "Score": "0", "body": "Tip: `public static readonly string line = new string('-', 27);`" } ]
[ { "body": "<p>Hey here a few little things I saw. I hope this helps a bit.</p>\n<ol>\n<li>Overall comments</li>\n</ol>\n<p>A good coding practice is to use Access modfiers\n<code>class BattleSystem</code> should maybe become <code>public class BattleSystem</code> depends on how you layer your projects what access modifier to use <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers</a>.</p>\n<p>A code convention is to start your property with a capital letter if it's public in your <code> class enemy</code> for example you have <code>public int bossHp;</code> this should be <code>public int BossHp;</code></p>\n<ol start=\"2\">\n<li>class Program</li>\n</ol>\n<p>in your main method you do <code>i++</code> in every switch case, you would be able to put this i++ behind your switch because only one case at a time can be accessed and you want to increment <code>i</code> everytime it seems like.</p>\n<ol start=\"3\">\n<li>enemy class</li>\n</ol>\n<pre><code> case 3: // Skip first phase of the boss fight (25% health damage at the start of battle)\n Console.WriteLine(&quot;You are insightful enough to start writing right away&quot;);\n e.bossHp -= (e.bossTotalHp / 4);\n break;\n\n case 4: // Skip first phase of the boss fight (25% health damage at the start of battle)\n Console.WriteLine(&quot;You are insightful enough to start writing right away&quot;);\n e.bossHp -= (e.bossTotalHp / 4);\n break;\n\n case 5: // Skip first phase of the boss fight (25% health damage at the start of battle)\n Console.WriteLine(&quot;You are insightful enough to start writing right away&quot;);\n e.bossHp -= (e.bossTotalHp / 4);\n break;\n</code></pre>\n<p>A quick tip when writing code and you see yourself writing 2 times the same exact thing there is probably a better way to write it.</p>\n<p>The only thing different above here is the case statements, so you'll have to look for something you can reuse for example you save what you copied pasted in Console.WriteLine() in a string variable above the switch case statment, or you make a method where you print that line and return the boss hp/4. (Just an idea)</p>\n<p>I love this site I still use it to this day and I think it will surely help you to write better code:\n<a href=\"https://refactoring.guru/refactoring\" rel=\"nofollow noreferrer\">https://refactoring.guru/refactoring</a></p>\n<p><em>EDIT</em></p>\n<p>Typo I wrote BoosHP should have been BossHP</p>\n<p>Styling after 2. the whole text was pasted behind it but there should have been an enter</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T21:16:29.793", "Id": "254059", "ParentId": "254046", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T17:27:05.587", "Id": "254046", "Score": "1", "Tags": [ "c#", "beginner", "object-oriented", "game", "console" ], "Title": "Text-based console game" }
254046
<p>I had a task to create a simple hangman game using O.O.P. with Javascript. It had to render the puzzle and remaining guesses to the DOM but didn't require any C.S.S.</p> <p>This is what I created.</p> <p>This is my index.html</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang=&quot;en&quot;&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;title&gt;Document&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h2 id=&quot;render-puzzle&quot;&gt;&lt;/h2&gt; &lt;h2 id=&quot;guesses&quot;&gt;&lt;/h2&gt; &lt;script src=&quot;hangman.js&quot;&gt;&lt;/script&gt; &lt;script src=&quot;app.js&quot;&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>This is my hangman.js which is used to create a hangman object</p> <pre><code>&quot;strict&quot;; const Hangman = function (word, remainingGuesses) { this.word = word.toLowerCase().split(&quot;&quot;); this.remainingGuesses = remainingGuesses; this.guessedWords = new Set(); this.status = &quot;Playing&quot;; }; Hangman.prototype.getPuzzle = function () { let puzzle = []; this.word.forEach((char) =&gt; { this.guessedWords.has(char) || char === &quot; &quot; ? puzzle.push(char) : puzzle.push(&quot;*&quot;); }); return puzzle.join(&quot;&quot;); }; Hangman.prototype.makeGuess = function (guess) { guess = guess.toLowerCase(); const isUnique = !this.guessedWords.has(guess); const isBadGuess = !this.word.includes(guess); if (isUnique) { this.guessedWords.add(guess); } if (isUnique &amp;&amp; isBadGuess &amp;&amp; this.status === &quot;Playing&quot;) { this.remainingGuesses--; } this.calculateStatus(); }; Hangman.prototype.calculateStatus = function () { const finsished = this.word.every((letter) =&gt; this.guessedWords.has(letter)); if (this.remainingGuesses === 0) { this.status = &quot;Failed&quot;; } else if (finsished) { this.status = &quot;Finished&quot;; } else { this.status = &quot;Playing&quot;; } }; Hangman.prototype.getStatus = function(){ let message = &quot;&quot;; if (this.status === &quot;Playing&quot;) { message = `Remaining Guesses: ${this.remainingGuesses}` } else if(this.status === &quot;Failed&quot;) { message = `Nice try! The word was ${this.word.join(&quot;&quot;)}`; } else { message = `Great Work! You guessed the word!!!` } return message; } </code></pre> <p>and this is the app.js where I create an instance of the hangman game</p> <pre><code>&quot;strict&quot;; const puzzle = document.querySelector(&quot;#render-puzzle&quot;); const guesses = document.querySelector(&quot;#guesses&quot;); const hangman = new Hangman(&quot;Cat&quot;, 2); generatePuzzleDom(); window.addEventListener(&quot;keypress&quot;, (e) =&gt; { hangman.makeGuess(e.key); generatePuzzleDom(); console.log(hangman.status); }); function generatePuzzleDom() { puzzle.innerHTML = hangman.getPuzzle(); guesses.innerHTML = hangman.getStatus(); } </code></pre>
[]
[ { "body": "<h1>Good things</h1>\n<ul>\n<li>The code appears to function properly.</li>\n<li>The code makes good use of strict equality operators and functional techniques like using <code>.every()</code>.</li>\n<li><code>const</code> is used for most variables.</li>\n<li>Prototypes are used properly.</li>\n</ul>\n<h1>Suggested changes</h1>\n<h2>Strict mode flaw</h2>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode\" rel=\"nofollow noreferrer\">Strict mode</a> is enabled with the string literal:</p>\n<pre><code>&quot;use strict&quot;;\n</code></pre>\n<p>Yet the first line of the two JS files is</p>\n<blockquote>\n<pre><code>&quot;strict&quot;;\n</code></pre>\n</blockquote>\n<h2>Variable declarations</h2>\n<p>Some variables declared with <code>let</code> could be declared with <code>const</code> since they are not re-assigned - e.g. <code>puzzle</code> since it is never re-assigned. Using <code>const</code> instead of <code>let</code> helps avoid <a href=\"https://softwareengineering.stackexchange.com/a/278653/244085\">accidental re-assignment and other bugs</a>.</p>\n<h2>status values</h2>\n<p>The values for <code>status</code> could be stored in constants - e.g.</p>\n<pre><code>const STATUS_FAILED = 'Failed';\nconst STATUS_PLAYING = 'Playing';\n// ... etc...\n</code></pre>\n<p>Then those can be used in the code- e.g. instead of</p>\n<blockquote>\n<pre><code>this.status = &quot;Playing&quot;;\n</code></pre>\n</blockquote>\n<p>it can use the constant:</p>\n<pre><code>this.status = STATUS_PLAYING;\n</code></pre>\n<p>Those could also be stored in &quot;an enum&quot;</p>\n<pre><code>const STATUS_VALUES = Object.freeze({ FAILED: 0, PLAYING: 1, FINISHED: 2});\n</code></pre>\n<p>With this approach, there is no risk of mistyping the values throughout the code, and if a value needs to be updated, it can be done in one place.</p>\n<h2>Selecting elements</h2>\n<p>It isn't wrong to use <code>querySelector</code> to get elements by <em>id</em> but using <code>getElementById()</code> &quot;<em>is definitely faster</em>&quot; <sup><a href=\"https://www.sitepoint.com/community/t/getelementbyid-vs-queryselector/280663/2\" rel=\"nofollow noreferrer\">1</a></sup> (see <a href=\"https://web.archive.org/web/20170210062404/http://jsperf.com:80/getelementbyid-vs-queryselector\" rel=\"nofollow noreferrer\">this jsPerf test for comparison</a>).</p>\n<h2>ES-6 class syntax</h2>\n<p>The code could be converted to the newer ES6 <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes\" rel=\"nofollow noreferrer\">class syntax</a> - bear in mind that it is &quot;<em>primarily syntactical sugar over JavaScript's existing prototype-based inheritance</em>&quot;. If there were many subclasses then it would help simplify setting up the prototypal inheritance.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T09:06:46.947", "Id": "501067", "Score": "0", "body": "thank you for the feedback, it was very helpful and insightful" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T19:10:42.123", "Id": "254050", "ParentId": "254048", "Score": "2" } }, { "body": "<p>JavaScript is a powerful and unique OO language that dropped a lot of the formality used in languages like Java and C# in favor of expressive coding (creative for want of a better term)</p>\n<p>Many people confuse syntax with OO, and will consider code OO if the traditional syntax is involved. Using <code>this</code>, <code>new</code> does not make it Good OO. Syntax has little to do with OO, it is the structure of the code that is important.</p>\n<p>In JavaScript good OO focuses on Encapsulation, and uses Polymorphism to replace Inheritance.</p>\n<p>Your code does not use Inheritance so not much to review on that part.</p>\n<p>Your code however does not use any from of safe encapsulation, leaving the object state at the mercy of bad code. Safe encapsulation is the most important part of OO design letting you trust the state of the code and know it will always work no matter the environment.</p>\n<h2>Reduce code noise</h2>\n<ul>\n<li>Function blocks do not need to be terminated with <code>};</code></li>\n<li>There is no need to split the string into an array. String have array like properties in JavaScript.</li>\n<li>The keyword <code>this</code> is both a danger (can be replaced by code outside the Object) and noisy as it turns up all over the place. In Good OO JavaScript you seldom need to use <code>this</code>. The example does not use <code>this</code></li>\n<li><code>window</code> is the default this. Avoid using it randomly.</li>\n<li>Learn to use the ternary operator <code>?</code> as it can remove a lot of noise from the code.</li>\n<li>Unique to JavaScript is the fact that expressions and statements are evaluated in a known order. This introduces the ability to use the shortcircuit style to replace the messy and rather old fashioned <code>if () { } else if () { }</code> See example there is only one if statement in the whole thing.</li>\n<li>The prototype can be assigned with an object literal eg</li>\n</ul>\n<p>eg</p>\n<pre><code>Hangman.prototype = {\n getPuzzle() { }, \n makeGuess() { },\n ... etc ...\n}\n</code></pre>\n<h2>OO coding</h2>\n<ul>\n<li>Use getters and setters</li>\n<li>Hangman is a only ever used as a single instance. I will not work if you create a second instance. Because of this you should not define it as function but rather as a object literal. To protect the state use a IIF to assign the object literal and encapsulate its state.</li>\n<li>Good OO code always protects the object state and does not expose anything that is not needed to use the Object. In javascript we use closure to hold an Objects state and define an object as an interface to that state.</li>\n</ul>\n<h2>Conflicting needs.</h2>\n<p>Modern web pages have 3 Main components. HTML, CSS, JavaScript. Unfortunately each was defined by a separate set of designers, each of whom created their own standards for naming.</p>\n<p>The result is a complete mess, where HTML, and CSS naming conventions are in direct conflict with JavaScript names. For example &quot;render-puzzle&quot; is not a valid name in JavaScript.</p>\n<p>You do not have to follow the naming conventions of CSS and HTML. You can use the JavaScript naming convention and thus reduce the needless overhead of querying the DOM of elements defined by <code>id</code>. Element ids are automatically created when needed in javascript providing a far simpler method of interfacing with the DOM</p>\n<h2>Rewrite</h2>\n<p>The rewrite create hangman as a static instance. Rather than creating a new instance to play a game you call <code>Hangman.newGame(word, guesses)</code>;</p>\n<p>The interface to Hangman then uses getters and setters to provide the functionality needed to play the game.</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\";\nconst Hangman = (() =&gt; {\n const STATUS = {\n playing: 1,\n finished: 2, \n failed: 3,\n };\n const statusStrs = {\n [STATUS.playing]() { return \"Remaining Guesses: \" + guesses },\n [STATUS.finished]() { return \"Great Work! You guessed the word!!!\" }, \n [STATUS.failed]() { return \"Nice try! The word was \" + word },\n };\n\n var word, guesses, status, used;\n function calculateStatus() {\n const finsished = [...word].every(char =&gt; used.has(char));\n status = !guesses ? STATUS.failed : finsished ? STATUS.finished : STATUS.playing;\n }\n return {\n get puzzle() {\n return word.replace(/./g, chr =&gt; used.has(chr) || chr === \" \" ? chr : \"*\");\n },\n set guess(char) {\n char = char.toLowerCase();\n if (!used.has(char)) { \n used.add(char); \n !word.includes(char) &amp;&amp; status === STATUS.playing &amp;&amp; (guesses--);\n calculateStatus(); \n }\n },\n get usedLetters() { return [...used.values()].join(\"\") },\n get status() { return statusStrs[status]() },\n newGame(newWord, numGuesses) {\n word = newWord.toLowerCase();\n guesses = numGuesses;\n status = STATUS.playing;\n used = new Set();\n },\n };\n})();\n\n;(()=&gt;{\n Hangman.newGame(\"Testing\", 5);\n renderPuzzle();\n\n addEventListener(\"keypress\", e =&gt; {\n Hangman.guess = e.key;\n renderPuzzle();\n });\n function renderPuzzle() {\n puzzleWords.textContent = Hangman.puzzle;\n usedLetters.textContent = Hangman.usedLetters;\n guesses.textContent = Hangman.status;\n }\n})();</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;h2 id=\"puzzleWords\"&gt;&lt;/h2&gt;\n&lt;h2 id=\"usedLetters\"&gt;&lt;/h2&gt;\n&lt;h2 id=\"guesses\"&gt;&lt;/h2&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T09:09:19.903", "Id": "501068", "Score": "0", "body": "amazing feedback and detailed explaination. I think what was new to me was that I didn't know you could chain ternary operators like the following, `status = !guesses ? STATUS.failed : finsished ? STATUS.finished : STATUS.playing;`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T09:10:39.057", "Id": "501069", "Score": "0", "body": "also what is the reason for using `var` instead of `let` and `const` to define `word, guesses, status, used`;?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T09:15:58.467", "Id": "501071", "Score": "0", "body": "@user6248190 I did not use `const` as they all are variables. I used `var` because they exist in the function's scope, thus using `let` would not clearly indicate my intent." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T18:17:05.073", "Id": "501131", "Score": "1", "body": "Some argue [\"_In ES6, there's no reason to use `var` - use `const` instead (or `let` when you must reassign)_\"](https://codereview.stackexchange.com/a/250206/120114) and [\"_(If you're writing in ES2015, never use `var`. Linting rule)_\"](https://codereview.stackexchange.com/a/248824/120114) - citing [linting rule _no-var_](https://eslint.org/docs/rules/no-var)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T18:19:06.380", "Id": "501133", "Score": "0", "body": "There are many good points here, and a lot to learn from this post. But I'll respectfully disagree on a few: * Don't use auto-generated globals from element ids, they're \"magical\", hard to know where they come from, and browsers want to deprecate them. See https://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables * I agree with @SᴀᴍOnᴇᴌᴀ and would still prefer `let` over `var`, even when they act the same because they're defined in a function scope - there's no advantage to self-documenting this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T20:08:36.613", "Id": "501148", "Score": "0", "body": "@ScottyJamison I disagree. It is my opinion that... Clear and unambiguous intent is not self documenting, it just good code. There are many arguments against `let` (noisy, encourages long functions, increased memory use, to name a few) `let` is based on a flawed premise, dogmatically promoted on un-instantiated evidence (block scope makes code better!!?) . Id mapped to global scope came from IE 4 (or earlier, recalling my way back machine) Was then adopted by other browsers until formalized in HTML5. It is not magical, enforces uniqueness across page, scripts, and reduces code noise." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T20:25:13.963", "Id": "501149", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ Because a linter has an option we all must follow? Linters are products, products compete via features, features help gain popularity, popularity breads unquestionable dogma. Linters add warnings to a language without, that is all, they do not dictate what is good code and what is bad." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T20:30:52.507", "Id": "501151", "Score": "1", "body": "@Blindman67 Thanks for your opinions - while I'll continue to disagree, I always like hearing opposing viewpoints to better understand why people code different ways - there's usually something to learn from them :)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T21:59:31.757", "Id": "501158", "Score": "1", "body": "@ScottyJamison Yes I totally agree, if there were no opposing view points then change would be very slow. Not a good thing for the forward edge of technology driven work IMHO. :)" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T01:08:57.493", "Id": "254070", "ParentId": "254048", "Score": "2" } } ]
{ "AcceptedAnswerId": "254070", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T18:49:50.753", "Id": "254048", "Score": "1", "Tags": [ "javascript", "object-oriented", "ecmascript-6", "hangman" ], "Title": "Create a simple hangman game using OOP and Javascript" }
254048
<p>I want to find the largest element in a sorted array, where the differences between the consecutive elements of the array are increasing, that is smaller than x.</p> <p>For example:</p> <ul> <li><code>[1, 3, 10, 17, 50, 1000]</code> is a valid input , because the consecutive differences <code>(2,7,7,33,950)</code> are in increasing order.</li> <li><code>[1, 3, 4, 10, 18]</code> is not a valid input, as the consecutive differences <code>(2, 1, 6, 8)</code> are not in increasing order.</li> </ul> <p>The optimum solution is O(log(log <em>max_value</em>)), so I am looking for better solutions than upperbound/ binary search. Actually ,I am looking to optimize binary search from O(log <em>N</em>) to O(log(log <em>max_value</em>).</p> <pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; const int n=50000001; int arr[n]; int binarysearch_lowerbound(int begin, int end, int x){ int ans=end; while(begin&lt;end){ int mid=(begin+end)/2; if(arr[mid] &gt;= x){ ans = mid; end = mid; } else { begin = mid + 1; } }return ans; } int main() { int N; cin&gt;&gt;N; for (int i=0; i&lt;N; i++){ cin&gt;&gt; arr[i]; } int q; cin&gt;&gt;q; for (int i=0; i&lt;q; i++){ int x; cin&gt;&gt;x; int k; int begin = x/(arr[N-1]-arr[N-2]); int end = x/(arr[1]-arr[0]); if(end&gt;N-1){ end=N; } k=binarysearch_lowerbound(begin,end,x); cout&lt;&lt;arr[k-1]&lt;&lt;endl; } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T18:55:44.773", "Id": "501018", "Score": "1", "body": "Also. you say that you're looking for better than _O(log n)_ scaling, but you don't say whether you have achieved that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T19:15:34.697", "Id": "501023", "Score": "0", "body": "You guessed right, I am texting with my mobile phone, had problem inserting the code.... I wrote a lowerbound function which gives me the right answer but in O(logn) , I tried to change the begin and end of the lowerbound function by dividing x with the first (smallest)and last ( largest) difference, but that’s also O( logN)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T19:50:23.343", "Id": "501025", "Score": "2", "body": "You never use the fact that _the differences between the consecutive elements of the array are increasing_, and it is vital. Think [Newton-Raphson](https://en.wikipedia.org/wiki/Newton's_method)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T11:44:11.290", "Id": "501087", "Score": "0", "body": "@vnp Yes, that’s actually what it all comes down to: how to use that fact, so that in each iteration of the binarysearch, the bounds are restricted by that fact..!!!" } ]
[ { "body": "<blockquote>\n<pre><code>#include &lt;bits/stdc++.h&gt;\n</code></pre>\n</blockquote>\n<p>Not a good start. This is not a standard C++ header; it's an artefact of your compiler's implementation, so <em>non-portable</em>, and <em>subject to change without notice</em>. Use the Standard-specified headers to define the library identifiers you need (any good reference tells you which to include).</p>\n<blockquote>\n<pre><code>using namespace std;\n</code></pre>\n</blockquote>\n<p>Please don't bring all of the Standard Library identifiers into the global namespace. It makes it much harder to reason about your code, and in extreme cases, can cause future versions of C++ to silently change the meaning of the program (when a new library function becomes a better match than one you define, for example).</p>\n<blockquote>\n<pre><code>const int n=50000001;\n</code></pre>\n</blockquote>\n<p>Where does this magic constant come from? What does it mean? <code>n</code> is not very descriptive for a global constant.</p>\n<blockquote>\n<pre><code>int arr[n];\n</code></pre>\n</blockquote>\n<p>Another global variable with an unhelpful name. What's it for? Why does it need to be global? Why are we using C-style arrays rather than <code>std::array</code> or <code>std::vector</code>?</p>\n<blockquote>\n<pre><code>int binarysearch_lowerbound(int begin, int end, int x){\n</code></pre>\n</blockquote>\n<p>This function isn't very reusable, as it depends on the global <code>arr</code>. If we passed pointers instead of integers for <code>begin</code> and <code>end</code>, then we would be able to find a value in <em>any</em> array we like. And why are we passing <em>signed</em> integers? Why would a negative value ever be useful?</p>\n<blockquote>\n<pre><code> int ans=end;\n</code></pre>\n</blockquote>\n<p>We don't need this variable, since at the end of the loop <code>ans==begin==end</code>. So just return <code>end</code> when we get there.</p>\n<blockquote>\n<pre><code> while(begin&lt;end){\n</code></pre>\n</blockquote>\n<p>Nothing wrong with this line (although I would like the operators to have more &quot;room to breathe&quot;).</p>\n<blockquote>\n<pre><code> int mid=(begin+end)/2;\n</code></pre>\n</blockquote>\n<p>There's a problem here that's frequently found in binary search algorithms. The sum could overflow (which in signed integers, is Undefined Behaviour). A better way, given that we know <code>begin</code> is less than <code>end</code>, is</p>\n<pre><code> int mid = begin + (end - begin) / 2;\n</code></pre>\n<p>This also has an advantage of being legal when we replace the indices with pointers.</p>\n<p>That said, what we have here is plain binary search. We haven't used the information about the distribution (namely that the curve is concave, so all values are no higher than the straight line joining <code>begin</code> and <code>end</code>). We're only going to scale as <em>O(log n)</em>.</p>\n<blockquote>\n<pre><code>int main() {\n int N;\n cin&gt;&gt;N;\n</code></pre>\n</blockquote>\n<p>Again, an utterly unhelpful variable name. I had to read the rest of <code>main()</code> to determine that this is supposed to be the array size to read.</p>\n<p>After reading from a stream, we must confirm that the stream is not in error before using the value we read (e.g. <code>if (!std::cin) { return EXIT_FAILURE; }</code>).</p>\n<blockquote>\n<pre><code> for (int i=0; i&lt;N; i++){\n cin&gt;&gt; arr[i];\n }\n</code></pre>\n</blockquote>\n<p>If we'd used a <code>std::vector</code> for this, we could replace that loop with a simple standard copy:</p>\n<pre><code>std::copy_n(std::istream_iterator&lt;int&gt;(std::cin), N, std::back_inserter(arr));\n</code></pre>\n<p>Again, we need to check the error state after reading.</p>\n<blockquote>\n<pre><code> int q;\n cin&gt;&gt;q;\n</code></pre>\n</blockquote>\n<p>What's <code>q</code>? I'm guessing a query into the array we have read.</p>\n<blockquote>\n<pre><code> for (int i=0; i&lt;q; i++){\n int x;\n cin&gt;&gt;x;\n</code></pre>\n</blockquote>\n<p>No, <code>q</code> must be the number of queries, and <code>x</code> is the actual query. These unhelpful names are really making the code harder to follow!</p>\n<blockquote>\n<pre><code> int k;\n</code></pre>\n</blockquote>\n<p>Why declare <code>k</code> here? It's best to declare and initialise variables together, to reduce the risk of using it before it's initialised (though any decent compiler will warn if you do that).</p>\n<blockquote>\n<pre><code> int begin = x/(arr[N-1]-arr[N-2]);\n int end = x/(arr[1]-arr[0]);\n</code></pre>\n</blockquote>\n<p>Here, we're using gradient to estimate the bounds for our search, but I'm not convinced the calculation is correct (shouldn't <code>begin</code> be subtracted from <code>N</code>?). When it has been corrected, I think we should be doing this inside <code>binarysearch_lowerbound()</code> <em>at every iteration</em>, since each subarray obeys the constraint on its shape.</p>\n<blockquote>\n<pre><code> if(end&gt;N-1){\n end=N;\n }\n k=binarysearch_lowerbound(begin,end,x);\n cout&lt;&lt;arr[k-1]&lt;&lt;endl;\n</code></pre>\n</blockquote>\n<p>There's no need to flush output using <code>std::endl</code>. Just output an ordinary return <code>&quot;\\n&quot;</code> and let the stream do its buffering.</p>\n<blockquote>\n<pre><code> }\n return 0;\n</code></pre>\n</blockquote>\n<p>In C++, we're allowed to omit <code>return 0;</code> from the end of <code>main()</code> (but only <code>main()</code>, not any other function). Success is assumed if we run off the end of the main function.</p>\n<hr />\n<h1>Modified code</h1>\n<p>Fixing the faults (other than the algorithm to reduce the search space, which is your own responsibility), I get:</p>\n<pre><code>/* Constraints (TODO: express using C++20 Concepts):\n * * Iter must be a random-access iterator\n * * Its value type must be an arithmetic type\n */\ntemplate&lt;typename Iter, typename T&gt;\nIter binarysearch_lowerbound(Iter begin, Iter end, const T x)\n{\n --end; // make an inclusive range\n while (begin &lt; end) {\n // TODO: improve algorithm to use curve constraint\n auto mid = begin + (end - begin + 1) / 2;\n if (x &lt;= *mid) {\n end = mid - 1;\n } else {\n begin = mid;\n }\n }\n return begin;\n}\n</code></pre>\n\n<pre><code>#ifdef TEST\n\n#include &lt;array&gt;\n#include &lt;cassert&gt;\n#include &lt;iterator&gt;\n\nint main() {\n auto check = [](auto collection, auto value)\n { using std::begin; using std::end; // for argument-dependent lookup\n return *binarysearch_lowerbound(begin(collection), end(collection), value) ; };\n assert(check(std::array{ 0, 1, 1, 5, 10 }, 11) == 10);\n assert(check(std::array{ 0, 1, 1, 5, 10 }, 8) == 5);\n assert(check(std::array{ 0, 1, 1, 5, 10 }, 5) == 1);\n assert(check(std::array{ 0, 1, 1, 5, 10 }, -1) == 0);\n}\n</code></pre>\n\n<pre><code>#else // not test\n\n#include &lt;algorithm&gt;\n#include &lt;iostream&gt;\n#include &lt;iterator&gt;\n#include &lt;vector&gt;\n\nint main()\n{\n using value_type = int; // would work for doubles, rationals, etc\n\n std::size_t array_size;\n if (!(std::cin &gt;&gt; array_size)) {\n return EXIT_FAILURE;\n }\n std::vector&lt;value_type&gt; values;\n values.reserve(array_size);\n std::copy_n(std::istream_iterator&lt;int&gt;(std::cin), array_size,\n std::back_inserter(values));\n if (!std::cin) {\n return EXIT_FAILURE;\n }\n\n std::size_t query_count;\n if (!(std::cin &gt;&gt; query_count)) {\n return EXIT_FAILURE;\n }\n\n while (query_count--&gt;0) {\n value_type query;\n if (!(std::cin &gt;&gt; query)) {\n return EXIT_FAILURE;\n }\n std::cout &lt;&lt; *binarysearch_lowerbound(values.begin(), values.end(), query);\n }\n}\n\n#endif\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T11:34:15.953", "Id": "501086", "Score": "0", "body": "@ Toby Speight wow! thank you for thoroughly inspecting my code. Obviously, I am a new student of c++, thank you for making some points clear ( about bits, using namespace std, etc) My problem now, actually, comes down to using the fact about the differences ( the concave curve, as you say) and implementing that into my algorithm, so I restrict , in every iteration, the bounds of the function binarysearch _lowerbound. Again, thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T11:12:16.770", "Id": "254088", "ParentId": "254049", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T18:50:47.500", "Id": "254049", "Score": "0", "Tags": [ "c++", "algorithm" ], "Title": "Find the largest element in a sorted array with increasing consecutive differences, smaller than x, in O( log(logmax_value)" }
254049
<p>I've recently started working on my own game engine and I have been thinking about creating my own <strong>model format</strong>. Since text usually takes a long time to load and process I decided to make a binary file. After a little work, I already had the basic concept:</p> <h2>The concept</h2> <ul> <li><strong>The header</strong>:<br /> The header of the file contains the magic number and the current major and minor version of the file. The magic number I chose is <code>706D6600</code>. An example header would like this: <code>706D6600 0100 0000</code></li> <li><strong>The body</strong><br /> I thought for a long time how I could make the body. In the end, I decided on the following: Models consist of <strong>vertices</strong>, <strong>texture coordinates</strong>, <strong>normals</strong>, and <strong>faces</strong>. Each type has a unique identifier and always the same size. This fixed size makes it easier for the file reader to read the file. Here is a list of all ID's: <ul> <li><strong>EOF</strong> - <code>0000FFF1</code></li> <li><strong>Vertex</strong> - <code>0000FFF2</code> 3x Float(12 bytes)</li> <li><strong>Texture Coordinate</strong> <code>0000FFF3</code> 2x Float(8 bytes)</li> <li><strong>Normal</strong> <code>0000FFF4</code> 3x Float(12 bytes)</li> <li><strong>Face</strong> <code>0000FFF5</code> 9x Integer(36 bytes) (Sorry for not choosing <code>FACE</code>)</li> </ul> </li> </ul> <hr /> <p>A cube would look like this: <a href="https://i.stack.imgur.com/Z0igi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Z0igi.png" alt="file" /></a></p> <h2>The Reader</h2> <p>To test the file out, I wrote a simple reader which would print the file like a <strong>Wavefront Obj Model</strong>.</p> <p>While writing, I didn't pay attention to performance: it was just to make the function of the file clearer. Here is the code:</p> <strong><code>pmf_types.h</code></strong> <pre><code>#define PMF_TYPES_H #include &lt;stdint.h&gt; const unsigned char pmf_magicnumber[4] = {0x70, 0x6D, 0x66, 0x00}; const uint32_t pmf_min_major = 1; const uint32_t pmf_min_minor = 0; const uint32_t pmf_max_major = 1; const uint32_t pmf_max_minor = 0; const unsigned char pmf_eof_id[4] = {0x00, 0x00, 0xFF, 0xF1}; const unsigned char pmf_vertex_id[4] = {0x00, 0x00, 0xFF, 0xF2}; const unsigned char pmf_texture_coordinate_id[4] = {0x00, 0x00, 0xFF, 0xF3}; const unsigned char pmf_normal_id[4] = {0x00, 0x00, 0xFF, 0xF4}; const unsigned char pmf_face_id[4] = {0x00, 0x00, 0xFF, 0xF5}; #endif </code></pre> <strong><code>main.c</code></strong> <pre><code> #include &quot;pmf_types.h&quot; int main() { FILE *file = fopen(&quot;example.pmf&quot;, &quot;rb&quot;); fseek(file, 0, SEEK_END); size_t fileSize = ftell(file); fseek(file, 0, SEEK_SET); unsigned char magicnumber[4]; fread(magicnumber, sizeof(magicnumber), 1, file); if(memcmp(magicnumber, pmf_magicnumber, sizeof(magicnumber)) != 0) { printf(&quot;Invalid Magic Number. (Perhaps wrong format)\n&quot;); return -1; } unsigned char version[4]; fseek(file, 4, SEEK_SET); fread(version, sizeof(version), 1, file); uint32_t major, minor; memcpy(&amp;major, (unsigned char[2]){version[0], version[1]}, 2); memcpy(&amp;minor, (unsigned char[2]){version[2], version[3]}, 2); if(major &lt; pmf_min_major || (major == pmf_min_major &amp;&amp; minor &lt; pmf_max_minor)) { printf(&quot;The file is outdated.\nSupported maximum version: %d.%d\n&quot;, pmf_max_major, pmf_max_minor); return -1; } if(major &gt; pmf_max_major || (major == pmf_max_major &amp;&amp; minor &gt; pmf_max_minor)) { printf(&quot;The reader is outdated.\nSupported maximum version: %d.%d\n&quot;, pmf_max_major, pmf_max_minor); return -1; } int offset = 8; while(1) { if(offset&gt;fileSize) { printf(&quot;Unexpected end of file.\n&quot;); break; } unsigned char identifier[4]; fseek(file, offset, SEEK_SET); fread(&amp;identifier, sizeof(identifier), 1, file); offset+=4; if(memcmp(identifier, pmf_vertex_id, sizeof(identifier)) == 0) { if(offset+12&gt;fileSize) { printf(&quot;Marked as vertex but not enough values supplied.\n&quot;); break; } float x, y, z; fseek(file, offset, SEEK_SET); fread((void*)(&amp;x), sizeof(x), 1, file); offset += 4; fseek(file, offset, SEEK_SET); fread((void*)(&amp;y), sizeof(y), 1, file); offset += 4; fseek(file, offset, SEEK_SET); fread((void*)(&amp;z), sizeof(z), 1, file); offset += 4; printf(&quot;Vertex %f %f %f\n&quot;, x, y, z); } else if(memcmp(identifier, pmf_texture_coordinate_id, sizeof(identifier)) == 0) { if(offset+8&gt;fileSize) { printf(&quot;Marked as texture coordinate but not enough values supplied.\n&quot;); break; } float x, y; fseek(file, offset, SEEK_SET); fread((void*)(&amp;x), sizeof(x), 1, file); offset+=4; fseek(file, offset, SEEK_SET); fread((void*)(&amp;y), 4, 1, file); offset+=4; printf(&quot;Texture coordinate %f %f\n&quot;, x, y); } else if(memcmp(identifier, pmf_normal_id, sizeof(identifier)) == 0) { if(offset+12&gt;fileSize) { printf(&quot;Marked as normal but not enough values supplied.\n&quot;); break; } float x=0, y=0, z=0; fseek(file, offset, SEEK_SET); fread(&amp;x, 4, 1, file); offset+=4; fseek(file, offset, SEEK_SET); fread(&amp;y, 4, 1, file); offset+=4; fseek(file, offset, SEEK_SET); fread(&amp;z, 4, 1, file); offset+=4; printf(&quot;Normal %f %f %f\n&quot;, x, y, z); } else if(memcmp(identifier, pmf_face_id, sizeof(identifier)) == 0) { if(offset+36&gt;fileSize) { printf(&quot;Marked as face but not enough values supplied.\n&quot;); break; } uint32_t vx, vy, vz, vtx, vty, vtz, vnx, vny, vnz; fseek(file, offset, SEEK_SET); fread(&amp;vx, 4, 1, file); offset+=4; fseek(file, offset, SEEK_SET); fread(&amp;vy, 4, 1, file); offset+=4; fseek(file, offset, SEEK_SET); fread(&amp;vz, 4, 1, file); offset+=4; fseek(file, offset, SEEK_SET); fread(&amp;vtx, 4, 1, file); offset+=4; fseek(file, offset, SEEK_SET); fread(&amp;vty, 4, 1, file); offset+=4; fseek(file, offset, SEEK_SET); fread(&amp;vtz, 4, 1, file); offset+=4; fseek(file, offset, SEEK_SET); fread(&amp;vnx, 4, 1, file); offset+=4; fseek(file, offset, SEEK_SET); fread(&amp;vny, 4, 1, file); offset+=4; fseek(file, offset, SEEK_SET); fread(&amp;vnz, 4, 1, file); offset+=4; printf(&quot;Face %d/%d/%d %d/%d/%d %d/%d/%d\n&quot;, vx, vtx, vnx, vy, vty, vny, vz, vtz, vnz); } else if(memcmp(identifier, pmf_eof_id, sizeof(identifier)) == 0) { //End of File break; } else { printf(&quot;Unknown identifier!\n&quot;); break; } } } </code></pre> <h2>What I want</h2> <p>I'm not sure if it's a good idea to use such identifiers or if floats and integers can be stored in a better way.</p> <p>Anyway, I want to get <strong>tips</strong> and <strong>criticism</strong> (Especially about my format).</p> <h2>Miscellaneous</h2> <p>Here is a link to the cube file: <a href="https://hastebin.com/tuqayebila.apache" rel="noreferrer">https://hastebin.com/tuqayebila.apache</a></p> <p>The file extension of my file is <code>pmf</code> which stands for <code>Plutonium File Format</code>. (Plutonium is the name of my engine)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T20:35:50.443", "Id": "501028", "Score": "1", "body": "Hello, thank you very much for your answers. I get the points, but I'm actually kind of looking for improvements to my file format. If my current approach is good enough, please let me know in a comment. (I will of course accept an answer then) :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T14:05:17.537", "Id": "501100", "Score": "0", "body": "My criticism is that you even made your own file format. That means no 3d design tool will support it. Which makes development of games more of a pain. Most of the time spent developing games can be 3d graphic design by artists, sometimes you like to let them use what they want. Additionally it seems there is a finite amount of things to a 3d model, and so ounce an optimal file format is found, there's not too much more to do. I personally use .obj, I find no issue with text because I'm not loading on the fly or in real time. I admit binary is more optimal in some ways." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T14:07:16.627", "Id": "501101", "Score": "0", "body": "Yeah I just hate seeing many proprietary spins on things which are very simple. Like apples head phone jacks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T14:27:19.837", "Id": "501104", "Score": "0", "body": "Also I can conceive, in some large world, you may need to store 3d objects i suppose on the hard drive if sizes are too large for program memory, then as well as hard drive speed, file format speed is important. But you may have to consider that you are pushing the boundaries of what is possible. This though is a different question for another site. So I would take the stance that outside of this situation, you aren't loading on the fly from files, and so no gain is really made from binary encodings that I can conceive. Perhaps ultra complicated engineering cads, with whole system assemblies?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T14:28:22.710", "Id": "501105", "Score": "0", "body": "I can really conceive of no real preference for binary, other then the simple fact is it is more direct, but no gains can be realized compared to text in most conceivable cases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T15:39:32.130", "Id": "501111", "Score": "2", "body": "I somehow don't understand that many people have problems with 3D design tools and proprietary formats. Blender, for example, has an API that lets you write exporters and importers for your own file formats (I'm working on that right now). And to make things even less painful, my engine has an asset browser where you can drag and drop files. I'd like to add a feature that, for example, immediately converts .obj files to my format." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T15:53:14.683", "Id": "501113", "Score": "2", "body": "@marshalcraft As long as you use a standard format to create your model and then export it to your format, that's fine. Custom model formats are not at all uncommon in the games industry, because every game [engine] has slightly different requirements, and the overhead from parsing a totally generic format is significant. (OBJ is the lowest common denominator, though)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T18:36:54.157", "Id": "501138", "Score": "0", "body": "@marshalcraft There are two types of games: ones that load instantly, and ones that don't load fast enough. Unless it's already instant, any reduction in the amount of work the game has to do to load is good!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T03:08:44.857", "Id": "501167", "Score": "0", "body": "Quick note : I did the same for my engine; here a few things I did on top of that :\n[1] I needed to import / export other types, so I went with a visitor pattern anyway, and it works great for 3d models too [2] that custom format is only a \"live\" format; during dev I stick to .fbx/.dae and usse Assimp to load them, then once I'm happy with the content I can pack everything and convert (through that visitor pattern) to the formats I want. I do the same for every other formats (Font for instance)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T04:17:32.303", "Id": "501243", "Score": "0", "body": "Seeks are costly; design the file format so that it is consumed in-order. Have you considered FOURCC instead of non-human-readable 4-byte codes? Have you considered a standard wrapper around structures and collections, such as RIFF64?" } ]
[ { "body": "<blockquote>\n<p>I'm not sure if it's a good idea to use such identifiers or if floats and integers can be stored in a better way.<br />\nAnyway, I want to get tips and criticism.</p>\n</blockquote>\n<p><strong>Declare, not define</strong></p>\n<p><code>pmf_types.h</code> declares and defines various objects. It should only <em>declare</em> them.</p>\n<pre><code>// const uint32_t pmf_min_major = 1;\nextern const uint32_t pmf_min_major;\n</code></pre>\n<p>and <em>define</em> them in one .c file</p>\n<p>e.g. <code>pmf_types.c</code></p>\n<pre><code>#include &quot;pmf_types.h&quot;\nconst uint32_t pmf_min_major = 1;\n</code></pre>\n<p><strong>Use include guards</strong></p>\n<p><code>pmf_types.h</code> missing include guards.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T19:37:01.360", "Id": "254052", "ParentId": "254051", "Score": "6" } }, { "body": "<p><code>fread</code> advances the file pointer. You may safely discard all those</p>\n<pre><code> offset+=4;\n fseek(file, offset, SEEK_SET);\n</code></pre>\n<p>When you <em>really</em> need an offset, call <code>ftell</code>.</p>\n<hr />\n<p>Always test what <code>fread</code> returns. BTW, it would eliminate a need in maintaining <code>offset</code> and comparing it with <code>fileSize</code>.</p>\n<hr />\n<pre><code> float x, y, z;\n\n fread((void*)(&amp;x), sizeof(x), 1, file);\n fread((void*)(&amp;y), sizeof(y), 1, file);\n fread((void*)(&amp;z), sizeof(z), 1, file);\n</code></pre>\n<p>is a long way to say</p>\n<pre><code> float vertex[3];\n fread (vertex, sizeof(vertex[0]), 3, file);\n \n</code></pre>\n<hr />\n<p>Beware the endianness.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T20:22:38.867", "Id": "254055", "ParentId": "254051", "Score": "8" } }, { "body": "<h2>Code</h2>\n<p>I would remove the explicit <code>if(offset+val&gt;fileSize) {</code> checks, as well as even getting <code>fileSize</code> in the first place. Instead, replace it with actual error handling, which you completely skip. This properly handles errors such as a disk issue while reading, and allows for flexibility in cases such as streaming a file over the network when you don't know its size before hand.</p>\n<h2>File format</h2>\n<p>It looks fine to me, but I would consider if &quot;This fixed size makes it easier for the file reader to read the file&quot; is really true compared to 1-byte identifiers. I would also remove the explicit EOF marker, and just look for the EOF errno instead.</p>\n<p>For final use, I would also compress it. <a href=\"https://lz4.github.io/lz4/\" rel=\"noreferrer\">LZ4</a> is <em>extremely</em> fast at decompression, and can generally decompress 1 byte per clock cycle: e.g. a 4GHz CPU could decompress 4GB of data per second. Unless you're on a PCI-e gen 4 NVMe drive, the disk will be slower than that, but if you are, you can easily just use more threads for loading other assets in parallel on different cores. As an example, Nintendo Switch games are compressed with LZ4.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T04:30:34.560", "Id": "254075", "ParentId": "254051", "Score": "5" } }, { "body": "<p>(This didn't fit in the comment field, not really an answer, more like advice)</p>\n<p>I get the allure of rolling your own format and writing the code, you wanna do it right, you wanna squeeze every last ounce of performance out of the CPU, you wanna create something awesome, maybe even learn something along the way, but here's some advice from a professional software engineer:</p>\n<p><strong>Use pre-existing, well known formats and libraries for these things.</strong></p>\n<p>The reason being simply that if you start rolling your own model formats, vector classes, UI Frameworks etc you'll spend all your time and energy writing those instead of the thing you actually wanted to create. You'll feel like you're not getting where you wanted to go and you'll lose motivation and then abandon the project and start another one. In addition, whatever you create will likely not be as performant and well thought out as the industry standard libraries etc because they have many times more hours of development and research in them then you on your lonesome can ever commit to on a hobby project. Not to mention that if you create your own formats, you're also committing to writing your own tools for working with these formats which makes it more tedious to get assets into your game engine, adding additional friction to getting a working product, increasing the chance that the project is going to fail.</p>\n<p>I have the best intentions here, I've been down the path you're setting your foot on here, and I can tell you: you're much more likely to compete the project if you focus on making the thing you want instead of getting bogged down with creating all the things around it.</p>\n<p>So my review, I guess, is: this code is not what you actually want, you should replace it with a common format, loaded by some library.</p>\n<p>Sorry for sounding bitter, it's not my intent. I really wish that op success in their project which is why I'm giving this advice.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T14:19:05.610", "Id": "501103", "Score": "2", "body": "Just one note, I slightly disagree with using an existing library to load some standard formats. This is because often the formats are simple enough (vertex coordinates, normal, textures) that simply parsing it yourself is easier, more versatile, then learning to use someone else's library. Just my opinion. And of course might not always be the case, but then if we could come to agreement on a specific library which is very sensible, then that good too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T18:39:30.523", "Id": "501139", "Score": "0", "body": "Industry standard libraries are just as often full of bells and whistles that you don't need which make them slower!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T01:43:54.330", "Id": "501165", "Score": "2", "body": "@user253751 that's s fallacy. They often contain highly optimized and per CPU model tuning. Having bells and whistles doesn't make them slower, it makes them powerful. See for example MKL, BLAS, Eigen, Armadillo you'll spend years researching and writing something that gets even close to their performance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T01:49:38.440", "Id": "501166", "Score": "0", "body": "@marshal craft yeah until you realize that you need to add an IK structure and per bone vertex weights and blend functions to add animations, then you need to figure out key frame animations because you realized that static models are boring, then special markers to designate where bullets should appear etc. Without the proper experience you won't know what you'll need later on in the project and you're building yourself a burden. And you'll end up making mistakes and oversights that have already been addressed by the libraries... I respectfully disagree with your assessment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T17:03:53.880", "Id": "501193", "Score": "0", "body": "I'm merely talking about the file codec, not the format. I'm not saying to make existing format. I'm saying that for simple 3d models, there not that much to parsing the format, into an array or structure for use. Now I have ran into issues with minor differences in way different cads, format a single format, which led to difficult bugs. But, sometimes the library you use might not support some specific cads, .obj format, and it won't open the file. So, it seem 50/50. Now I've also worked with say video codecs. With video, audio, it is much more complex a format." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T17:05:13.873", "Id": "501194", "Score": "0", "body": "And so I think if then, a known very standard codec is available, it could save a lot of time, because the nature of that file format simply requires more work to get the same thing if done self." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T17:14:08.390", "Id": "501195", "Score": "0", "body": "Also while I'm not as experienced with dynamic models in animations, I can say I'm not familiar with intricate file formats storing additional information about animation with the model. It is interesting that modular animated models, could be moved around various graphics engines etc, a file format could surely reduce redundant work. But I'm not aware of any useful cooperation on such things. Additionally it could be that such things are too variable, that any attempt to standardize would constrain what is then possible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T19:07:06.750", "Id": "501203", "Score": "0", "body": "Can't upvote this enough - don't roll your own if this is \"production\" code for something you actually want to finish and be polished. That said, writing your own file formats is a great learning experience and I'd encourage folks to try it. It makes you think about optimizing for space AND performance, fixed-length fields vs variable blocks with headers, bit packing & manipulation, lots of things that are really useful to be familiar with. Writing your own ray-tracer is similar: FANTASTIC learning experience, but in production you wanna use a 3rd party lib. [XKCD](https://xkcd.com/927/)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T20:19:27.160", "Id": "501209", "Score": "0", "body": "@EmilyL. I said \"just as often\" i.e. they are equally likely to be well-optimized, or to be full of inefficient bells and whistles. You should find out which one is true for your particular library." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T20:20:58.597", "Id": "501210", "Score": "0", "body": "@marshalcraft That is the situation in game engines - the tradeoffs and resulting limitations taken by each game engine are too different from each other. Any universal format will be full of features that your game engine can't do." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T12:07:27.113", "Id": "501256", "Score": "0", "body": "Well that was what I saying, assuming you are constructing a game engine. My views are this. Due to the simple nature of 3d models, they are vertuces, normal, and texture. The normal are redundant information. Assuming the engine does not load 3d models from file in real time, there is likely an optimal file format in existence. Likewise, writing the codec for the said file format in this case, is simple enough in theory that is what I recommend." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T12:12:33.513", "Id": "501257", "Score": "0", "body": "And for again ray tracing, you could use a proprietary library in your engine, or more often you could not. The only rule is value, not, use library always or never. What value do you get from gluing various graphics components together, in the field of graphic engine dev? Best if these values can be quantified, but not always possible. Nobody can validate a phrase \"don't do ray tracing\" for general case of graphic engine dev. However you can validate a phrase, \"use .obj but write your own codec\" for all cases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T12:17:12.860", "Id": "501258", "Score": "0", "body": "I think you will see the industry does this to some extent at less then optimal rate. For say windows audio format conversion for different driver and hardware, like say microphone recording, while there are libraries, manumy do it themselves, cause it is per code length short and easy, compared to adding a fixed interface requirement of a outside library to your code base. Other areas like video, well look around the web, everyone uses YouTube flash essentially, so it must be more of a cost." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T12:24:24.593", "Id": "501259", "Score": "0", "body": "Ultimately id like to say, graphics is intensive, we rely on fixed hardware which constrain capability. Fixing further is not necessarily good in todays climate. But forn3d model, it is simple enough, verticies, normal, and texture coordinate. Sense there are so few variables this lends to a concrete single optimal solutions. We are lucky for this natural topology, so I use a standard format rather then create yet more. However as for decoding and encoding these files l, I tend to like to do them my self. As there is often some variation with in the format, that certain cad vendors can fail" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T12:27:53.767", "Id": "501260", "Score": "0", "body": "To open. Ultimately the yet variable aspect is scaring and precision. Depending on things, you can deal with wide variety of scales, but other things can lead to lack of precision. This could be similar analously to how floating point attempts to handle such things. This is not an answer to that problem just making sure aware of it. A lot of glitches and graphic artifacts such as aliasing can be caused by the manner continuous things, infinitely precise are discretized." } ], "meta_data": { "CommentCount": "15", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T05:11:38.133", "Id": "254076", "ParentId": "254051", "Score": "15" } }, { "body": "<blockquote>\n<p>Anyway, I want to get tips and criticism (Especially about my format).</p>\n</blockquote>\n<p>I think the fixed-size 4-byte things are great, much better than text. They're easy to use both for humans and computers, the identifiers are easy to identify in a hex view, and nothing misaligns the data stream so it stays in nice columns in hex view as well. However, I don't think it's good that the identifiers pepper the format so much. I'm not that worried about the size, though that is an aspect as well. One result of having so many identifers everywhere was that code like <code>memcmp(identifier, pmf_vertex_id, sizeof(identifier)) == 0</code> is executed several times <em>per element</em>, which conflicts with a general rule of thumb I would use for file formats:</p>\n<p>Ideally, design a file format to be read and written in <em>chunks of significant size</em>.</p>\n<p>IO (even buffered IO) tends to like significant chunks. It doesn't have to be megabytes at once, but if you can fire off a read or write of several KB at once, that's good. Working in bigger chunks becomes even more important if you add compression. Generally that means arrays of things, with their length stored somewhere before them, such as in the header (enabling reading all lengths at once which is nice) or length-prefixed (which is suitable for more dynamic formats). Array-with-length also has an advantage compared to using an end-of-file marker, related to an other rule of thumb:</p>\n<p>Ideally, design a file format to be readable in one pass without reallocation.</p>\n<p>The issue didn't show itself in the example reader here, because the data is printed instead of kept around. More commonly though, it would be loaded into arrays. With the current file format, if you wanted to load a file into arrays, their length would not be known until the the end-of-file marker is found. We could do two passes, with a first pass to find the size and the second pass to actually load the data, but that's a waste. Seeking to the end is an option, but the file format does not actually promise that there is nothing after the first occurrence of the end-of-file marker (and if it did promise that, what would be the point of the marker?). Anyway, having the lengths up-front also solves that issue.</p>\n<p>Arrays with known length have an other advantage, which I don't know whether it's important to you, but it might become interesting someday: they enable a reader to skip data they're not interested in.</p>\n<hr />\n<p>By the way, I don't think it's bad that you're making custom formats like this. Having custom converters as part of your asset pipeline is not strange at all, and compatibility of the game files with common editors is not that useful: editing them directly is often banned anyway (or it should be), it bypasses the asset pipeline risking incorrect or improper results (out-of-sync lightmaps, unoptimized meshes, meta-data with dangling references etc). The formats of the development versions of assets are an other matter entirely, of course <em>there</em> you would want them to be editable by their respective editors, but even then it may be useful to write a small plugin.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T08:01:36.627", "Id": "254080", "ParentId": "254051", "Score": "11" } }, { "body": "<blockquote>\n<pre><code> float x;\n fread((void*)(&amp;x), sizeof(x), 1, file);\n</code></pre>\n</blockquote>\n<p>All pointers are convertible to <code>void*</code>, so there's no need for the explicit cast:</p>\n<pre><code> fread(&amp;x, sizeof x, 1, file);\n</code></pre>\n<p>However, there's a bigger issue lurking here. In-memory representation of <code>float</code> can vary between platforms. Even if we limit ourselves to platforms using single-width IEEE-754 format for their <code>float</code>, then interpretation is often affected by byte order issues This seems a shame, given the care to use order-independent constants in the header; it means that your saved files can't safely be transported between hosts without some translation.</p>\n<p>That's a good argument to use an existing serialisation library, and/or to support a text-based format for interchange (and debugging, incidentally).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T12:40:37.710", "Id": "254090", "ParentId": "254051", "Score": "3" } }, { "body": "<p>In this answer I'm skipping over most of the implementation and only talking about the file format itself.</p>\n<p><strong>How does your game consume this file? Your format should be designed for efficient reading.</strong></p>\n<p>I bet your game doesn't use the data in this format. I bet your game engine parses this format and creates a single array with interleaved vertices, normals and texture coordinates - because that's the format OpenGL wants - and then passes it to OpenGL. In this regard, your format is no better than a text-based OBJ. In fact your format looks exactly like a binary-ified version of OBJ.</p>\n<p>If your model data is just getting passed to OpenGL, your format should be convertible to OpenGL with minimal work. In this case, that means: you read the size, you allocate the buffer, you read that much data from the file and pass it to OpenGL. No conversion. The script that creates your model files should already write it in this format. If you use index buffers, then you'll have two buffers - do the same thing twice.</p>\n<p>Why? Because you shouldn't do work if you don't need to. Programs that achieve the same result with less work are better. Pointless extra work is pointless.</p>\n<p>If you have some bits of information that don't go in the buffer - like the type of shape (GL_QUADS/GL_TRIANGLES/GL_TRIANGLE_STRIP) - then of course you don't read those into the buffer. Those can be part of the header, next to the buffer size.</p>\n<p>There's no reason to make all fields are the same size if you are parsing them anyway. There <em>is</em> a reason to <em>align</em> the fields for efficiency if you are processing the data on the CPU (e.g. 4-byte fields should start at multiples of 4 bytes). You're right about fixed-size fields, but it doesn't mean all fields have to be the same size as other fields, just that all fields have to be the same size as themselves. E.g. a float is always 4 bytes.</p>\n<p>The version number is useful, but there's no reason to have a major and minor version. It just adds confusion because every time you update the format you have to decide whether it's a major or minor update. Just use a single number. The advantage of having a version number is that whenever you change the format, you don't have to re-convert all your models. The game knows to load the old models the old way and the new models the new way. Of course, when you release the game, then you can re-convert all the models and delete the code for loading old versions.</p>\n<p><strong>About the code, though</strong></p>\n<ul>\n<li><p>Why do you use this pattern?</p>\n<pre><code> fseek(file, offset, SEEK_SET);\n fread(&amp;vx, 4, 1, file);\n offset+=4;\n</code></pre>\n<p>The file already knows which offset it's at. You can just do:</p>\n<pre><code> fread(&amp;vx, 4, 1, file);\n</code></pre>\n<p>and it reads 4 bytes from the current offset, and adds 4 bytes to the current offset. There's no need to keep track of the offset yourself and there's no need to keep calling fseek.</p>\n</li>\n<li><p>You can also read an entire <code>struct</code> at once:</p>\n<pre><code>struct face {\n int vx, vy, vz;\n int vtx, vty, vtz;\n int vnx, vny, vnz;\n} f;\n\nfread(&amp;f, sizeof f, 1, file);\n</code></pre>\n<p>For more complicated structures, beware of compilers inserting padding - but that's good, the compiler does it so the CPU can access the data more efficiently, you just have to make sure it's consistent and account for it in the file format.</p>\n</li>\n<li><p>Why do you call the vertices in a face X, Y and Z? I think this is confusing, because the coordinates in a vertex are also called X, Y and Z. I would name them <code>v1</code>, <code>v2</code>, <code>v3</code> or <code>a</code>, <code>b</code>, <code>c</code>.</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T16:02:01.143", "Id": "254094", "ParentId": "254051", "Score": "6" } } ]
{ "AcceptedAnswerId": "254080", "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T19:29:14.550", "Id": "254051", "Score": "12", "Tags": [ "c", "game", "binary" ], "Title": "A binary 3D model format for a game" }
254051
<p>I’m learning python and have built a very simple program that just renames files. It makes all letters lowercase and replaces spaces and <code>%20</code>-instances with underscores and then copies them into a ‘Finished’ folder. I’m looking for better methods and approaches of writing and structuring my code.</p> <p>Can anybody find any obvious imperfections or methods of improvement? If anyone has any advice then that would be great.</p> <p>My code can be found below:</p> <pre class="lang-py prettyprint-override"><code> import os from shutil import copyfile files_to_improve_dir = 'Files to Improve' finished_files_dir = 'Finished' print('isdir', os.path.isdir(files_to_improve_dir)) # 1 - copy files into 'finished' folder for f in os.listdir(files_to_improve_dir): copyfile(os.path.join(files_to_improve_dir, f), os.path.join(finished_files_dir, f)) for f in os.listdir(finished_files_dir): new_filename = f.replace(' ', '_').replace('%20', '_').lower() print('f', f, 'new_filename', new_filename) if (f != new_filename): os.rename(os.path.join(finished_files_dir, f), os.path.join(finished_files_dir, new_filename)) </code></pre>
[]
[ { "body": "<ol>\n<li>Try using <code>pathlib</code> over <code>os</code> when you're dealing with file/glob operations. It has a lot cleaner interface, and is part of standard library in python 3.</li>\n<li>Name constants in your code with the <code>CAPITAL_SNAKE_CASE</code>. It is recommended guideline from <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">the PEP-8</a>.</li>\n<li>Split your code into individual functions doing a single task each.</li>\n<li>Put the execution flow for your code inside <a href=\"https://stackoverflow.com/q/419163/1190388\">an <code>if __name__ == &quot;__main__&quot;</code> block</a>.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T16:43:48.593", "Id": "501120", "Score": "0", "body": "very useful advice, thank you" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T20:51:12.807", "Id": "254057", "ParentId": "254053", "Score": "2" } } ]
{ "AcceptedAnswerId": "254057", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T20:04:49.530", "Id": "254053", "Score": "3", "Tags": [ "python", "python-3.x", "file", "file-system" ], "Title": "Simple file-renaming program in python" }
254053
<h1>Overview</h1> <p>A &quot;from scratch&quot; generic quicksort implemented in C, which allows predicate (returning <code>bool</code>, like C++ rather than <code>int</code> like C), and any type via <code>void*</code>.</p> <p>Using <code>memcpy</code> for the <code>swap()</code> implementation was the general solution. But this was about twice as slow as declared types for small types (int, float, double etc). So I added a simple &quot;type-size-switch&quot;, which worked to restore performance to pre-generic levels.</p> <p>More types/sizes can be easily added. Including <code>char*</code> to sort strings by swapping their pointers - demo included, it uses the <code>long</code> case in the type switch on my machine because <code>long</code> and <code>ptr</code> are both 8 bytes. I know the <code>memcpy</code> solution won't handle very large types - would have to use <code>malloc</code> or &quot;byte-by-byte swap&quot; it with our own loop.</p> <p>Uses &quot;C++ iterator&quot; style params <code>start</code> and <code>end</code> (which is one past the end) rather than C-style <code>start</code> and <code>count</code>.</p> <h2>Questions</h2> <ol> <li>Type-size switch. Is this a reasonable techique hint to the compiler to use registers for optimisation rather than slow generic <code>memcpy</code> for small types.</li> <li>Does the above violate the standard? What about using <code>long</code> to <code>swap</code> a <code>double</code> if they happen to be the same size, which is very common?</li> <li>How about the use of <code>/dev/urandom</code> use for <code>srand()</code> (I know it's not cross-platform).</li> <li>Any other comments?</li> </ol> <pre class="lang-c prettyprint-override"><code>#include &lt;stdbool.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;time.h&gt; #include &lt;stdio.h&gt; typedef bool (*cmp)(const void*, const void*); bool less_ints(const void* a, const void* b) { return *(const int*)a &lt; *(const int*)b; } bool greater_ints(const void* a, const void* b) { return *(const int*)a &gt; *(const int*)b; } bool less_strs(const void* a, const void* b) { return strcmp(*((const char**)a), *((const char**)b)) &lt; 0; } void swap(void* x, void* y, size_t size) { switch (size) { case sizeof(int): { int t = *((int*)x); *((int*)x) = *((int*)y); *((int*)y) = t; break; } case sizeof(long): { // used by char** long t = *((long*)x); *((long*)x) = *((long*)y); *((long*)y) = t; break; } default: { char t[size]; memcpy(t, x, size); memcpy(x, y, size); memcpy(y, t, size); } } } void* partition(void* start, void* end, size_t size, cmp predicate) { if (start == NULL || end == NULL || start == end) return start; char* storage = (char*)start; char* last = (char*)end - size; // used as pivot for (char* current = start; current != last; current += size) { if (predicate(current, last)) { swap(current, storage, size); storage += size; } } swap(storage, last, size); return storage; // returns position of pivot } void quicksort(void* start, void* end, size_t size, cmp predicate) { if (start == end) return; void* middle = partition(start, end, size, predicate); quicksort(start, middle, size, predicate); quicksort((char*)middle + size, end, size, predicate); } bool sortcheck(const int* start, int size) { for (int i = 0; i &lt; size - 1; ++i) { if (start[i] &gt; start[i + 1]) return false; } return true; } void print(const int* start, int size) { for (int i = 0; i &lt; size; ++i) printf(&quot;%3d&quot;, start[i]); printf(&quot;\n&quot;); } bool rand_seed() { int seed = 0; FILE* fp = fopen(&quot;/dev/urandom&quot;, &quot;re&quot;); if (!fp) { fprintf(stderr, &quot;Error: couldn't open source of randomness&quot;); return false; } if (fread(&amp;seed, sizeof(int), 1, fp) &lt; 1) { fprintf(stderr, &quot;Error: couldn't read random seed&quot;); fclose(fp); return false; } fclose(fp); srand(seed); // nice seed for rand() return true; } int rand_range(int start, int end) { return start + rand() / (RAND_MAX / (end - start + 1) + 1); } int main() { #define size 10000000 int* data = malloc(size * sizeof(int)); if (!data) { fprintf(stderr, &quot;couldn't allocate memory&quot;); exit(EXIT_FAILURE); } if (!rand_seed()) { fprintf(stderr, &quot;couldn't seed random number generator&quot;); free(data); exit(EXIT_FAILURE); } for (int i = 0; i &lt; size; ++i) data[i] = rand_range(1, size / 2); // print(data, size); quicksort(data, data + size, sizeof(int), &amp;less_ints); // partition(data, data + size, sizeof(int), &amp;less_ints); // if (!sortcheck(data, size)) { // fprintf(stderr, &quot;ERROR: data is not sorted!\n&quot;); // exit(EXIT_FAILURE); // } // print(data, size); free(data); // string demo #define str_count 12 const char* strings[str_count] = { &quot;material&quot;, &quot;rare&quot;, &quot;fade&quot;, &quot;aloof&quot;, &quot;way&quot;, &quot;torpid&quot;, &quot;men&quot;, &quot;purring&quot;, &quot;abhorrent&quot;, &quot;unpack&quot;, &quot;zinc&quot;, &quot;unsightly&quot;, }; quicksort(strings, strings + str_count, sizeof(char*), &amp;less_strs); for (int i = 0; i &lt; str_count; ++i) printf(&quot;%s\n&quot;, strings[i]); return EXIT_SUCCESS; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T21:00:22.343", "Id": "501030", "Score": "1", "body": "If your `rand` only returns 15 or 16 bits (which is common) your random ranges won't cover the full range." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T23:02:43.543", "Id": "501042", "Score": "0", "body": "@1201ProgramAlarm Thanks, valid point. It's (2^31)-1, ie ~ 2Billion on my machine, and I wasn't really focused on uniform distribution etc. But fair point." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T12:45:21.917", "Id": "501095", "Score": "1", "body": "There shouldn't be anything random in here anyway - sorting should be completely deterministic, and tests need to be reproducible (nothing worse than tests that sometimes pass and sometimes fail - how do you debug that?) At least print the seed used, and allow that to be passed in to reproduce the test." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T12:46:35.523", "Id": "501096", "Score": "0", "body": "Yes, that's true, and I did fix the seed while debugging. But I opened it to generate any possible unforseen edge cases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T12:48:01.317", "Id": "501097", "Score": "0", "body": "How many platforms' implementations of `memcpy()` did you profile to determine that it always performs weakly with small count? You're probably reimplementing something that the better compilers are already doing for you (remember that `memcpy()` may be inlined by the compiler, so it likely depends on the optimisation level you ask for, too)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T12:50:39.013", "Id": "501098", "Score": "0", "body": "I used gcc-9 and clang-10 on ubuntu 20.04 with `-O3`. I suspect they used the same underlying `libc` implementation of `memcpy()`." } ]
[ { "body": "<blockquote>\n<p>Type-size switch. Is this a reasonable techique hint to the compiler to use registers for optimisation rather than slow generic memcpy for small types.</p>\n</blockquote>\n<p>Why do you think that <code>memcpy()</code> has not already implemented this optimization itself? Do you have timing data to suggest this optimization works and improves performance?</p>\n<blockquote>\n<p>Does the above violate the standard? What about using long to swap a double if they happen to be the same size, which is very common?</p>\n</blockquote>\n<p>On a lot of systems <code>long</code> and <code>int</code> are the same size. In that case your <code>switch()</code> will fail to compile (I think).</p>\n<blockquote>\n<p>How about the use of /dev/urandom use for srand() (I know it's not cross-platform).</p>\n</blockquote>\n<p>If it does not exist then why not fall back on the classic <code>time(NULL)</code> rather than generating an error.</p>\n<blockquote>\n<p>Any other comments?</p>\n</blockquote>\n<p>Let the compiler do the work of calculating array sizes:</p>\n<pre><code>const char* strings[] = {\n // ^^ Notice empty braces forces the compiler to \n // calculate the correct size based on the initialization values.\n &quot;material&quot;, &quot;rare&quot;, &quot;fade&quot;, &quot;aloof&quot;, &quot;way&quot;, &quot;torpid&quot;,\n &quot;men&quot;, &quot;purring&quot;, &quot;abhorrent&quot;, &quot;unpack&quot;, &quot;zinc&quot;, &quot;unsightly&quot;,\n};\n\nconst int str_count = sizeof(strings) / sizeof(strings[0]);\n // This trick works even if the array has size 0\n // because the sizeof is done at compile time\n // and thus strings[0] is never actually accessed\n // just type information is retrieved.\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T22:58:44.097", "Id": "501041", "Score": "0", "body": "Sure thanks. Aware of that technique and use it often." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T23:08:12.777", "Id": "501043", "Score": "0", "body": "Yes I did time it. Without the `sizeof()` switch just using `memcpy` for small types it is twice as slow. As soon as I made `swap()` type aware the performance improved by 2x." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T23:11:03.163", "Id": "501044", "Score": "0", "body": "I like the idea of `time(NULL)` as a fallback. I guess if I really cared enough about quality randomness, I probably shouldn't be using `rand()` anyway?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T23:12:18.723", "Id": "501045", "Score": "0", "body": "I am compiling with clang-10 on ubuntu 20.04 btw. `clang -O3 -Wall -Wextra -Werror`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T23:17:58.417", "Id": "501046", "Score": "0", "body": "Interesting point on the duplicate sizes. You're right. If I add a case for `double` (which is same size as `long` on my machine) then it fails to compile. Might be safer as an `if / else if / else`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T23:26:37.457", "Id": "501048", "Score": "0", "body": "I timed it with `if / else if / else` and it's marginally faster than with `switch`, so that's definitely the way to go." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T23:32:20.937", "Id": "501049", "Score": "0", "body": "If you use `if/else if/else` you will loose performance. You could add `#if sizeof(long) != sizeof(int)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T23:32:27.183", "Id": "501050", "Score": "0", "body": "Both `gcc-9.3` and `clang-10` exhibit the significant perf improvement from the `size` `switch/if`. `gcc` is faster overall, but has a > 2x difference. `clang` is slightly slower but has a ~ 1.75x difference." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T23:33:16.943", "Id": "501051", "Score": "0", "body": "Yeah, not so on my machine with above compilers. `if/else` is marginally faster than switch, don't ask me why." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T23:34:51.640", "Id": "501052", "Score": "2", "body": "`marginally faster` => branch prediction. The trouble is for times when the predication fails. `switch` will be faster in most situations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T23:37:05.963", "Id": "501053", "Score": "0", "body": "That could well be, yes. Either way, I am super surprised that this \"hack\" (which is what it feels like) gets me 1.75 -> 2.2x performance improvements for small primitive types..`switch` or `if/else`, because the type will be same for entire sort, so the branch predictor is doing good work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T00:46:46.607", "Id": "501056", "Score": "0", "body": "Perhaps there is some compiler optimisation magic/inlining which is possible when the type is known in the local source file, but not possible when linking against a shared object file (memcpy) from libc?" } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T22:57:00.327", "Id": "254065", "ParentId": "254056", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T20:33:12.483", "Id": "254056", "Score": "1", "Tags": [ "c", "quick-sort" ], "Title": "Generic QuickSort with Performance Optimised Swap for small types" }
254056
<p>I'm trying to implement a function (a template-helper function) which provides a simple merge-like functionality for both arrays and objects. The two functions are basically looks identical:</p> <pre class="lang-javascript prettyprint-override"><code>const mergeArrays = (first, ...rest) =&gt; rest.reduce((acc, curr) =&gt; ([ ...acc, ...curr]), first); const mergeObjects = (first, ...rest) =&gt; rest.reduce((acc, curr) =&gt; ({ ...acc, ...curr }), first); </code></pre> <p>One could do a <strong>type check and a local variable</strong> to write a single function like this:</p> <pre class="lang-javascript prettyprint-override"><code>const mergeArraysOrObjects1 = (first, ...rest) =&gt; { let reducer = null; if ('object' === typeof first &amp;&amp; null !== first) { reducer = (acc, curr) =&gt; ({ ...acc, ...curr }); } if (Array.isArray(first)) { reducer = (acc, curr) =&gt; [...acc, ...curr]; } if (!reducer) { throw new Error('The &quot;merge&quot; filter only works with arrays and hashes.'); } return rest.reduce(reducer, first); } </code></pre> <p>... but it seems so ugly to me. Another possibility is a <strong>type check and inline conditional</strong>:</p> <pre class="lang-javascript prettyprint-override"><code>const mergeArraysOrObjects2 = (first, ...rest) =&gt; { if ('object' !== typeof first || null === first) { throw new Error('The &quot;merge&quot; filter only works with arrays and hashes.'); } return rest.reduce( (acc, curr) =&gt; Array.isArray(acc) ? [...acc, ...curr] : {...acc, ...curr}, first ); } </code></pre> <p>I'm still learning JavaScript so I'm guessing if there is a more elegant and concise way to treat the return value the same way.</p>
[]
[ { "body": "<h2><code>Object.assign</code> &amp;&amp; <code>Array.flat</code></h2>\n<p>By the first example which does not have any type checking makes the throwing of errors in the second two examples look superfluous, a little over kill.</p>\n<p>As the function <code>Array.isArray</code> is the more concise statement over the always ugly object test <code>typeof obj === &quot;Object &amp;&amp; obj !== null</code> you can use a simple ternary to call the correct function</p>\n<p>You can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign\" rel=\"nofollow noreferrer\">Object.assign</a> rather than the long and slow object by object reduce method to merge objects.</p>\n<p>And for the array <code>Array.push</code>, then <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat\" rel=\"nofollow noreferrer\">Array.flat(1)</a> depth of 1 for the arrays. To ensure you do not effect the input array <code>first</code> you would also need to copy it to a new array</p>\n<h3>Examples.</h3>\n<pre><code>const merge = (first, ...rest) =&gt; {\n const arrays = (arr) =&gt; (arr.push(...rest), arr.flat(1));\n const objects = () =&gt; Object.assign({}, first, ...rest); \n return Array.isArray(first) ? arrays([[...first]]) : objects();\n}\n</code></pre>\n<p>Or a shortened form</p>\n<pre><code>const merge = (first, ...rest) =&gt; {\n return Array.isArray(first) ? \n (first = [[...first]], first.push(...rest), first.flat(1)) : \n Object.assign({}, first, ...rest);\n}\n</code></pre>\n<h2>Update</h2>\n<p>Fixed bug as pointed out in comments.</p>\n<p>From the same comment by <em>ScottyJamison</em> in which is presented an even better solution, using the rest operator on all the arguments resulting in...</p>\n<pre><code>const merge = (...items) =&gt; Array.isArray(items[0]) ? \n items.flat(1) : \n Object.assign({}, ...items);\n</code></pre>\n<p>or</p>\n<pre><code>const merge = (...items) =&gt; Array.isArray(items[0]) ? items.flat(1) : Object.assign({}, ...items);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T18:23:58.367", "Id": "501200", "Score": "0", "body": "Your example is broken - if the first array has subarrays, they would get flattened, which is different from the O.P.'s implementation. Why not just do to this? `const merge = (...items) => Array.isArray(items[0]) ? items.flat(1) : Object.assign({}, ...items);`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T18:53:37.590", "Id": "501202", "Score": "0", "body": "@ScottyJamison Yes thank you very much for pointing that out. Will fix it. :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T09:48:47.320", "Id": "254085", "ParentId": "254063", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T22:06:35.760", "Id": "254063", "Score": "0", "Tags": [ "javascript", "array", "ecmascript-6" ], "Title": "Avoid the object/array check and treat the return value the same way with JavaScript spread operator?" }
254063
<p>This code works, and I'm pretty sure it's mathematically/algorithmically correct:</p> <pre><code>model = tf.keras.applications.MobileNet(include_top=False,input_shape=INPUT_SHAPE) model.trainable = False model = tf.keras.Sequential([ model, tf.keras.layers.Flatten(), tf.keras.layers.Dense( 1, &quot;sigmoid&quot; ), ]) try: model.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=False), optimizer=tf.keras.optimizers.RMSprop(), metrics=['accuracy', tf.keras.metrics.AUC(curve=&quot;PR&quot;)]) model.fit(train_dataset, epochs=2, validation_data=validation_dataset) finally: for directory in tempdirs: rmtree(directory) </code></pre> <p>For completion, here is my dataset setup and imports, I'm being very verbose and not using <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset#from_tensor_slices" rel="nofollow noreferrer"><code>tf.data.Dataset.from_tensor_slices</code></a> and/or builtin random dataset utility functions, to keep things like my real workflow:</p> <pre><code>from tempfile import mkdtemp from os import path, mkdir from shutil import rmtree import tensorflow as tf import numpy as np from PIL import Image NUM_CLASSES = 2 INPUT_SHAPE = 256, 256, 3 def create_random_ds(tempdir): for class_num in range(NUM_CLASSES): directory = path.join(tempdir, 'class{}'.format(class_num)) mkdir(directory) for i in range(20): Image \ .fromarray((np.random.rand(*INPUT_SHAPE) * 255).astype('uint8')) \ .convert('RGBA') \ .save(path.join(directory, 'image{}.png'.format(i))) return tf.keras.preprocessing.image_dataset_from_directory( tempdir, labels='inferred', label_mode='int', ) tempdirs = mkdtemp(), mkdtemp() train_dataset = create_random_ds(tempdirs[0]) validation_dataset = create_random_ds(tempdirs[1]) </code></pre> <hr /> <p>What do you think, is it correct, and how can it be improved?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-29T23:37:16.723", "Id": "254066", "Score": "3", "Tags": [ "python", "machine-learning", "tensorflow" ], "Title": "Transfer learning CNNs for image classification in TensorFlow" }
254066
<p>This is a (more or less) continuation of a previous post I made: <a href="https://codereview.stackexchange.com/questions/253409/generic-implementation-of-a-hashtable-with-double-linked-list">Generic implementation of a hashtable with double-linked list</a>. I got lots of valuable feedback, so I decided to rewrite the entire module from scratch to improve readability, performance and also to add new features.</p> <p><strong>Specifications:</strong></p> <ul> <li>The hashmap implementation is able to store any data (generic)</li> <li>The hashmap provides collision handling using a single linked list.</li> <li>The hashmap dynamically resizes, to allow for good performance <ul> <li>With many collisions (e.g. because of a small bucket count), access-time per element on average is not O(1)</li> <li>Therefore, when a certain threshold is exceeded (150%), the hashmap is resized, to allow for a better distribution of entries, and hence for faster access times.</li> </ul> </li> </ul> <p><strong>Review Request:</strong></p> <p>I'd like to get feedback for the following things:</p> <ul> <li>Is the API of the hashmap intuitive/easy to use? Is it consistent (Parameters passed, values returned, Naming conventions etc) <ul> <li>I plan on re-using this module in future projects</li> </ul> </li> <li>Is there room for performance improvements? (E.g. are there any checks or loops that could be avoided?) <ul> <li>I am especially thinking about the functions that directly manipulate the buckets, such as <code>hm_get</code>, <code>hm_set</code>, <code>hm_delete</code> and <code>hm_resize</code>.</li> </ul> </li> <li>The test functions in <code>main.c</code> don't need to be reviewed, as they will be replaced with proper unit tests in the future.</li> <li>Are there any bad practices I didn't catch? (e.g Redundant code etc)</li> </ul> <p><strong>hashmap.h</strong></p> <pre><code>#ifndef HASHTABLE_H #define HASHTABLE_H #include &lt;stddef.h&gt; #include &lt;stdbool.h&gt; typedef struct entry { void *key; const void *value; struct entry *next; } entry; typedef struct hashmap { size_t buckets_count; size_t entries_count; struct entry **buckets; } hashmap; size_t hm_compute_hash(size_t key, size_t bucket_count); /** * Initializes a new hashmap instance with the default size * @return The hashmap instance */ hashmap *hm_new(); /** * Returns a pointer to the value from the entry in the hashmap given the key, or NULL, if entry doesn't exist. * @param hm The hashmap instance * @param key The entry key * @return The pointer to the value of the matching entry, or NULL, if key is not valid. */ const void *hm_get(hashmap *hm, void *key); /** * Adds a new entry to the hashmap * @param phm Pointer to the hashmap instance * @param key The entry key * @param value The value associated with the key * @return Returns 0 if element was added successfully, otherwise a negative value is returned. */ int hm_set(hashmap **phm, void *key, const void *value); /** * Deletes an entry from the hashmap * @param hm The hashmap instance * @param key The key to the entry to delete */ void hm_delete(hashmap **phm, void *key); /** * Prints the hashtable in a human readable format to stdout * @param hm The hashmap instance */ void hm_print(hashmap *hm); /** * Searches an entry by key in a bucket * @param hm The hashmap instance * @param key The entry key * @return Pointer to the entry if found, otherwise NULL */ struct entry *hm_entry_search(struct hashmap *hm, void *key); /** * Creates a new entry that is accepted by that hashmap * @param key The entry key * @param value The value of the entry * @return Returns a pointer to the created entry, or NULL, if an error occurred. */ struct entry *entry_create(void *key, const void *value); /** * Checks if the hashmap should be expanded to remain efficient * @param hm The hashmap instance * @return Returns the new bucket size, if expanding is recommended, otherwise 0 */ int hm_should_grow(struct hashmap *hm); /** * Checks if the hashmap should be shrinked to remain efficient * @param hm The hashmap instance * @return Returns the new bucket size, if shrinking is recommended, otherwise 0 */ int hm_should_shrink(struct hashmap *hm); /** * Creates a new larger or smaller hashtable with the given size. * All entries get relinked, and the old hashtable instance gets replaced with the new one. * @param hm_old The hashmap instance that should be expanded * @param new_size The amount of buckets that the new hashmap instance should have * @return The new (expanded) hashmap instance */ hashmap *hm_resize(struct hashmap *hm_old, size_t new_size); /** * Frees all memory allocated by the hashmap */ void hm_free(struct hashmap *hm); #endif </code></pre> <p><strong>hashmap.c</strong></p> <pre><code>#include &quot;hashmap.h&quot; #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; // Sources used as reference/learning material: // http://pokristensson.com/code/strmap/strmap.c // https://github.com/Encrylize/hashmap/blob/master/hashmap.c // https://github.com/goldsborough/hashtable/blob/master/hashtable.c hashmap *hm_new() { const size_t DEFAULT_HASHMAP_SIZE = 3; // Allocate a new hashmap hashmap *hm = malloc(sizeof(hashmap)); if (hm == NULL) return NULL; // Allocate buckets hm-&gt;buckets = malloc(sizeof(entry) * DEFAULT_HASHMAP_SIZE); if (hm-&gt;buckets == NULL) { free(hm); return NULL; } // Set initial bucket count, preferably to a prime number hm-&gt;buckets_count = DEFAULT_HASHMAP_SIZE; hm-&gt;entries_count = 0; // Initialize the buckets, might be obsolete if calloc is used for (size_t i = 0; i &lt; hm-&gt;buckets_count; ++i) { hm-&gt;buckets[i] = NULL; } return hm; } struct entry *hm_entry_search(struct hashmap *hm, void *key) { // Compute index from key size_t index = hm_compute_hash((size_t) key, hm-&gt;buckets_count); // Get bucket start entry *e_curr = hm-&gt;buckets[index]; // Iterate bucket until entry is found, or bucket end was reached while (e_curr != NULL) { if (e_curr-&gt;key == key) { break; } e_curr = e_curr-&gt;next; } return e_curr; } const void *hm_get(hashmap *hm, void *key) { // Make sure the key is not null if (key == NULL) return NULL; // Find entry first entry *entry_ptr = hm_entry_search(hm, key); // Return value of entry, or NULL, if not present return entry_ptr == NULL ? NULL : entry_ptr-&gt;value; } int hm_set(hashmap **phm, void *key, const void *value) { struct hashmap *hm = *phm; // Make sure the key is not null if (key == NULL) return -1; /* Search for entry in bucket*/ entry *entry_ptr = hm_entry_search(hm, key); // If entry is already present, overwrite old value with new one if (entry_ptr != NULL) { entry_ptr-&gt;value = value; return 0; } // If entry is not present, create a new one struct entry *new_entry_ptr = entry_create(key, value); if (new_entry_ptr == NULL) return -2; // Add newly created entry to the head of the bucket, and update next pointer, if necessary size_t index = hm_compute_hash((size_t) key, hm-&gt;buckets_count); struct entry *current_entry_ptr = hm-&gt;buckets[index]; new_entry_ptr-&gt;key = key; new_entry_ptr-&gt;value = value; new_entry_ptr-&gt;next = current_entry_ptr != NULL ? current_entry_ptr : NULL; hm-&gt;buckets[index] = new_entry_ptr; hm-&gt;entries_count++; // Check if the hashmap should be resized int hm_size = hm_should_grow(hm); if (hm_size != 0) { *phm = hm_resize(hm, hm_size); } return 0; } void hm_delete(hashmap **phm, void *key) { struct hashmap *hm = *phm; // Make sure the key is not null if (key == NULL) return; // Compute index from key size_t index = hm_compute_hash((size_t) key, hm-&gt;buckets_count); // Iterate through bucket. When entry is found, remove it, and update neighbor entries entry *e_prev = NULL; entry *e_curr = hm-&gt;buckets[index]; while (e_curr != NULL) { if (e_curr-&gt;key == key) { if (e_prev == NULL) { hm-&gt;buckets[index] = e_curr-&gt;next; } else { e_prev-&gt;next = e_curr-&gt;next; } hm-&gt;entries_count--; free(e_curr); break; } e_prev = e_curr; e_curr = e_curr-&gt;next; } int hm_size = hm_should_shrink(hm); if (hm_size != 0) { *phm = hm_resize(hm, hm_size); } return; } entry *entry_create(void *key, const void *value) { entry *e_new = malloc(sizeof(entry)); // Check if malloc failed if (e_new == NULL) { return NULL; } // Set fields for newly created entry e_new-&gt;key = key; e_new-&gt;value = value; e_new-&gt;next = NULL; return e_new; } int hm_should_grow(struct hashmap *hm) { if (hm-&gt;entries_count &gt;= 1.5 * hm-&gt;buckets_count) { // Double the table size return 2 * hm-&gt;buckets_count; } return 0; } int hm_should_shrink(struct hashmap *hm) { if (hm-&gt;entries_count &lt;= 0.5 * hm-&gt;buckets_count) { // Half the table size return hm-&gt;buckets_count / 2; } return 0; } hashmap *hm_resize(struct hashmap *hm_old, size_t new_size) { // First, create a new hashtable which is bigger in size hashmap *hm = malloc(sizeof(hashmap)); if (hm == NULL) return NULL; // Allocate new amount of buckets hm-&gt;buckets = malloc(sizeof(entry) * new_size); if (hm-&gt;buckets == NULL) { free(hm); return NULL; } // Set new bucket count and reset entries count to 0 hm-&gt;buckets_count = new_size; hm-&gt;entries_count = 0; // Initialize the buckets, might be obsolete if calloc is used for (size_t i = 0; i &lt; hm-&gt;buckets_count; ++i) { hm-&gt;buckets[i] = NULL; } // Traverse old and relink entries to new hashmap. This requires re-hashing for (size_t i = 0; i &lt; hm_old-&gt;buckets_count; ++i) { struct entry *e_curr = hm_old-&gt;buckets[i]; while (e_curr != NULL) { hm_set(&amp;hm, e_curr-&gt;key, e_curr-&gt;value); e_curr = e_curr-&gt;next; } } hm_free(hm_old); return hm; } size_t hm_compute_hash(size_t key, size_t bucket_count) { key = ((key &gt;&gt; 16) ^ key) * 0x45d9f3b; key = ((key &gt;&gt; 16) ^ key) * 0x45d9f3b; key = (key &gt;&gt; 16) ^ key; return key % bucket_count; } void hm_print(hashmap *hm) { for (size_t i = 0; i &lt; hm-&gt;buckets_count; ++i) { printf(&quot;[%zu] &quot;, i); struct entry *e_curr = hm-&gt;buckets[i]; for (; e_curr != NULL; e_curr = e_curr-&gt;next) { printf(&quot;%zu -&gt; &quot;, (size_t)(e_curr-&gt;key)); } printf(&quot;NULL\n&quot;); } } void hm_free(struct hashmap *hm) { // Free all buckets for (size_t i = 0; i &lt; hm-&gt;buckets_count; ++i) { entry *e_curr = hm-&gt;buckets[i]; entry *e_prev = NULL; while (e_curr != NULL) { e_prev = e_curr; e_curr = e_curr-&gt;next; free(e_prev); } } // Free hashmap struct free(hm-&gt;buckets); free(hm); } </code></pre> <p><strong>main.c</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &quot;hashmap.h&quot; #include &lt;assert.h&gt; void test_hm_set_entry() { hashmap *hm = hm_new(3); hm_set(&amp;hm, (void *) 1, (void *) 100); assert(hm_get(hm, (void *) 1) == (void *) 100); hm_free(hm); } void test_hm_get_entry() { hashmap *hm = hm_new(3); hm_set(&amp;hm, (void *) 1, (void *) 100); hm_set(&amp;hm, (void *) 2, (void *) 200); hm_set(&amp;hm, (void *) 3, (void *) 300); hm_set(&amp;hm, (void *) 4, (void *) 400); hm_set(&amp;hm, (void *) 5, (void *) 500); hm_set(&amp;hm, (void *) 6, (void *) 600); hm_set(&amp;hm, (void *) 7, (void *) 700); assert(hm_get(hm, (void *) 1) == (void *) 100); assert(hm_get(hm, (void *) 2) == (void *) 200); assert(hm_get(hm, (void *) 3) == (void *) 300); assert(hm_get(hm, (void *) 4) == (void *) 400); assert(hm_get(hm, (void *) 5) == (void *) 500); assert(hm_get(hm, (void *) 6) == (void *) 600); assert(hm_get(hm, (void *) 7) == (void *) 700); hm_free(hm); } void test_hm_delete_entry() { hashmap *hm = hm_new(3); hm_set(&amp;hm, (void *) 1, (void *) 100); hm_set(&amp;hm, (void *) 2, (void *) 200); hm_set(&amp;hm, (void *) 3, (void *) 300); hm_delete(&amp;hm, (void *) 2); assert(hm_get(hm, (void *) 2) == NULL); hm_free(hm); } void test_hm_resize() { // Allocate new hashmap (3 buckets by default) hashmap *hm = hm_new(); // Make sure 3 buckets are present assert(hm-&gt;buckets_count == 3); /* Add 5 items to trigger resize */ hm_set(&amp;hm, (void *) 1, (void *) 100); hm_set(&amp;hm, (void *) 2, (void *) 200); hm_set(&amp;hm, (void *) 3, (void *) 300); hm_set(&amp;hm, (void *) 4, (void *) 400); hm_set(&amp;hm, (void *) 5, (void *) 500); // Check if buckets size was doubled assert(hm-&gt;buckets_count == 6); // Check if elements can still be obtained correctly assert(hm_get(hm, (void *) 1) == (void *) 100); assert(hm_get(hm, (void *) 2) == (void *) 200); assert(hm_get(hm, (void *) 3) == (void *) 300); assert(hm_get(hm, (void *) 4) == (void *) 400); assert(hm_get(hm, (void *) 5) == (void *) 500); // Delete some entries hm_delete(&amp;hm, (void *) 1); hm_delete(&amp;hm, (void *) 2); // Check if table size shrinked again assert(hm-&gt;buckets_count == 3); // Fee hashmap hm_free(hm); } int main() { test_hm_get_entry(); test_hm_set_entry(); test_hm_delete_entry(); test_hm_resize(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T12:42:33.567", "Id": "501094", "Score": "1", "body": "It's a shame that you say \"the test functions shouldn't be reviewed\" - the interface usability is likely revealed by whether those test functions are simple or unwieldy." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T12:59:05.757", "Id": "501099", "Score": "1", "body": "@TobySpeight Fair point. I probably worded that poorly. I just meant to say they shouldn't be the main focus of the review." } ]
[ { "body": "<h1>Interface</h1>\n<p>We're not consistent in using <code>struct hashmap</code> or the typedef <code>hashmap</code> in the interface. Choose one and use it consistently.</p>\n<blockquote>\n<pre><code>hashmap *hm_new();\n</code></pre>\n</blockquote>\n<p>Make this a prototype (<code>hashmap *hm_new(void)</code>).</p>\n<blockquote>\n<pre><code>const void *hm_get(hashmap *hm, void *key);\nvoid hm_print(hashmap *hm);\nint hm_should_grow(struct hashmap *hm);\nint hm_should_shrink(struct hashmap *hm);\n</code></pre>\n</blockquote>\n<p>I think these should accept a <code>const hashmap*</code>.</p>\n<blockquote>\n<pre><code>void hm_print(hashmap *hm);\n</code></pre>\n</blockquote>\n<p>It seems limiting to support only <code>stdout</code> as destination. And we probably need to be able to pass functions that know how to print keys and values, or we'll only be able to write the pointer values, meaningless to most users.</p>\n<blockquote>\n<pre><code>typedef struct entry {\n void *key;\n // ...\n} entry;\n</code></pre>\n</blockquote>\n<p>We don't need to be able to modify <code>*key</code>, so this should be a <code>const void*</code>. Otherwise, we can't use (e.g.) string literals as keys, and users will be left wondering how the hashmap might modify the objects they pass in as keys.</p>\n<blockquote>\n<pre><code>struct entry *hm_entry_search(struct hashmap *hm, void *key);\nstruct entry *entry_create(void *key, const void *value);\nint hm_should_grow(struct hashmap *hm);\nint hm_should_shrink(struct hashmap *hm);\nhashmap *hm_resize(struct hashmap *hm_old, size_t new_size);\n</code></pre>\n</blockquote>\n<p>Should these (and <code>struct entry</code>) be exposed as the <em>public</em> interface? I think they would be better off inside the implementation, with <code>static</code> linkage. If you want to expose them for unit testing but not to normal user code, then consider using the preprocessor:</p>\n<pre><code>#ifndef HASHTABLE_H\n#define HASHTABLE_H\n\n/* public interface ... */\n\n#ifdef HASHTABLE_IMPLEMENTATION\n\ntypedef struct entry {\n void *key;\n const void *value;\n struct entry *next;\n} entry;\n\n/* and the rest of the private interface ... */\n\n#endif\n\n#endif\n</code></pre>\n<p>In the implementation and the tests, you'll need</p>\n<pre><code>#define HASHTABLE_IMPLEMENTATION\n#include &quot;hashmap.h&quot;\n</code></pre>\n<hr />\n<h1>Implementation</h1>\n<p><code>hm_should_grow()</code> and <code>hm_should_shrink()</code> return <code>int</code>, but then the result is used as input to <code>hm_resize()</code> which takes a <code>size_t</code>. I think these functions should both return <code>size_t</code> to avoid problems when <code>int</code> is too small (remember that <code>bucket_count</code> is a <code>size_t</code>).</p>\n<p>The remaining conversion problems are in the implementation of these functions, where <code>size_t</code> is converted to <code>double</code>, with possible loss of precision:</p>\n<pre><code>if (hm-&gt;entries_count &gt;= 1.5 * hm-&gt;buckets_count) {\n</code></pre>\n\n<pre><code>if (hm-&gt;entries_count &lt;= 0.5 * hm-&gt;buckets_count) {\n</code></pre>\n<p>We could simply use <code>long double</code> constants instead (<code>1.5L</code> and <code>0.5L</code>), but I would favour converting to integer arithmetic (and checking we don't overflow the arithmetic - include <code>&lt;stdint.h&gt;</code>):</p>\n<pre><code>if (hm-&gt;buckets_count &lt; SIZE_MAX / 2\n &amp;&amp; hm-&gt;entries_count &gt;= hm-&gt;buckets_count + hm-&gt;buckets_count / 2) {\n</code></pre>\n<p>As these functions are only used once each, consider inlining them into their call sites:</p>\n<pre><code>// Check if the hashmap should be resized\nif (hm-&gt;buckets_count &lt; SIZE_MAX / 2 &amp;&amp; hm-&gt;entries_count &gt;= hm-&gt;buckets_count * 3 / 2) {\n // Double the table size\n *phm = hm_resize(hm, 2 * hm-&gt;buckets_count);\n}\n</code></pre>\n<p>Observe that we have the <code>realloc()</code> problem here. If we failed to resize, we got a null pointer back, and didn't free the memory we lost. Both of these are bad, but we can change <code>hm_resize()</code> to return the old pointer rather than a null pointer when it fails. We'll have an inefficient size of map, but that's better than losing data and leaking memory.</p>\n<blockquote>\n<pre><code>// Allocate a new hashmap\nhashmap *hm = malloc(sizeof(hashmap));\nif (hm == NULL)\n return NULL;\n</code></pre>\n</blockquote>\n<p>It's good that we take account of allocations here, and clean up correctly. I'd make a couple of small changes:</p>\n<pre><code>hashmap *hm = malloc(sizeof *hm);\nif (!hm) {\n return hm;\n}\n</code></pre>\n<p>It's always good to allocate the size of the dereferenced pointer, rather than writing its type again (it's more important when we're not also declaring the variable, but assigning to one whose definition is distant, and so harder to confirm it's consistent). Explicitly testing <code>==NULL</code> is redundant; all non-null pointers evaluate true (I find that these explicit tests clutter C code and make it look like Java!). And always using the braces can avoid some errors during maintenance.</p>\n<blockquote>\n<pre><code>// Compute index from key\nsize_t index = hm_compute_hash((size_t) key, hm-&gt;buckets_count);\n</code></pre>\n</blockquote>\n<p>I don't think this is a good way to compute a hash. Firstly, <code>size_t</code> might not be big enough for a pointer (we should be using <code>uintptr_t</code>, I think). Secondly, it works on object <em>identity</em>, not <em>equality</em> - see below. We need a hash function and an equality function that are tailored for the actual types the user is storing. I think that we should keep two function pointers as part of <code>struct hashmap</code>, and ask the user to pass these in when constructing.</p>\n<blockquote>\n<pre><code>new_entry_ptr-&gt;next = current_entry_ptr != NULL ? current_entry_ptr : NULL;\n</code></pre>\n</blockquote>\n<p>It's equivalent, and much simpler, to write</p>\n<pre><code>new_entry_ptr-&gt;next = current_entry_ptr;\n</code></pre>\n<blockquote>\n<pre><code> struct entry *e_curr = hm_old-&gt;buckets[i];\n\n while (e_curr) {\n hm_set(&amp;hm, e_curr-&gt;key, e_curr-&gt;value);\n e_curr = e_curr-&gt;next;\n }\n</code></pre>\n</blockquote>\n<p>This matches a <code>for</code> loop much better:</p>\n<pre><code> for (struct entry *e_curr = hm_old-&gt;buckets[i]; e_curr; e_curr = e_curr-&gt;next) {\n hm_set(&amp;hm, e_curr-&gt;key, e_curr-&gt;value);\n }\n</code></pre>\n<p>I note that if <code>hm_set()</code> fails here, we carry on and give back an incomplete copy of the original, with no warning. Users aren't going to like that any more than the leak.</p>\n<p>We really need to revisit <code>hm_resize()</code> and make it a lot more robust. Consider every action in it that might fail, and what we should do about that failure. The first two <code>malloc()</code> tests are a good start, once they are changed to return the old map instead of a null pointer. Actually, I think it's fairly simple to fix the call to <code>hm_set()</code>, too:</p>\n<pre><code> for (struct entry *e_curr = hm_old-&gt;buckets[i]; e_curr; e_curr = e_curr-&gt;next) {\n if (hm_set(&amp;hm, e_curr-&gt;key, e_curr-&gt;value)) {\n /* abandon the resize */\n hm_free(hm);\n return hm_old;\n }\n }\n</code></pre>\n<h1>Identity vs Equality</h1>\n<p>As mentioned above, our implementation considers keys to be equal only if they are the same object (i.e. their pointers compare equal). This is a problem for users because it's generally more useful to be able to compare keys by value. Consider this use-case:</p>\n<pre><code>int main(void)\n{\n hashmap *hm = hm_new();\n if (!hm) { return EXIT_FAILURE; }\n hm_set(&amp;hm, &quot;one&quot;, &quot;aon&quot;);\n hm_set(&amp;hm, &quot;two&quot;, &quot;dà&quot;);\n hm_set(&amp;hm, &quot;three&quot;, &quot;tri&quot;);\n hm_set(&amp;hm, &quot;four&quot;, &quot;ceithir&quot;);\n\n char buf[20];\n if (scanf(&quot;%19s&quot;, buf) == 1) {\n const char *translation = hm_get(hm, buf);\n if (translation) {\n printf(&quot;%s → %s\\n&quot;, buf, translation);\n } else {\n printf(&quot;No translation found for %s.\\n&quot;, buf);\n }\n }\n\n hm_free(hm);\n}\n</code></pre>\n<p>This program never finds the translation, regardless of the input. How are we supposed to retrieve values if we need to obtain the original pointer used to add the item?</p>\n<p>We could use variables to retain the keys, but then it's equivalent and simpler to just replace those with variables pointing to the values!</p>\n<h1>Object ownership and lifetime</h1>\n<p>The pointers passed in to the map (both keys and values) are not <em>owned</em> by the map (the interface comments don't make this clear, which may leave users wondering). This means that it's the user's responsibility to remove the pointers from the map when destroying the pointed-to objects (either by <code>free()</code> for heap objecs or by the end of scope for local objects).</p>\n<p>Users might prefer an interface that copies at least the keys into the map's ownership; perhaps also the values (but then they might have to do more work to store pointers to shared objects, and would benefit from separate functions for value types and reference types).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T17:03:06.307", "Id": "501123", "Score": "0", "body": "Thanks for the review - very valuable! I agree with almost everything suggested. As for the `value == NULL` vs `!value` comment, I am a bit undecided. I did it for all malloc checks now. Do you suggest using this convention everytime, apart from malloc checking?\nAnd yea, I'd love to get some more input on the resize function especially - I feel like there is still plenty of room for improvement. As for the hash-function comment, can you ellaborate on that a bit, I didn't quiet get that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T17:04:46.537", "Id": "501124", "Score": "0", "body": "Regarding cleaning up the interface, - I see why it makes sense to remove these functions from the header. Are you saying I should just add them as static prototypes in the .c file instead? I'd love to comment them, but it feels a bit odd when half of the documented functions are in the header and the other half of them is in the implementation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T19:42:56.453", "Id": "501146", "Score": "1", "body": "`value == NULL` vs `!value` is a personal preference; some prefer the Java style and some prefer the C style. You're consistent, and that's good. For the non-public functions, I would probably make the definitions be static declarations (no separate prototype) and comment them there - users of the functions don't need to know they even exist, and the implementer (you!) knows exactly where to find them. For the hash function, I'll edit (probably tomorrow: it's getting late here) to see if I can make that clearer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T11:01:46.500", "Id": "501183", "Score": "0", "body": "Thanks for the additional feedback. I see the problem with the hashfunction/comparison now, and I'll try to work out a better solution for that. What else do you think can be improved in `hm_resize()`, since you said \"We really need to revisit `hm_resize()` and make it a lot more robust.\" ?\n\nAlso, I think it might be worth changing how parameters are passed to some of the public functions. For example, right now `hm_set` and `hm_delete` take a `hashmap**`, where as `hm_get` and `hm_print` take a `hashmap*` - maybe not the most intuitive API design ..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T11:20:31.077", "Id": "501184", "Score": "0", "body": "Actually, it's just `hm_set()` that wasn't being checked; I've edited that section with a version that abandons the resize if that fails. There's a high likelihood of failing again next time it's called of course; I'm not sure of the best way to deal with that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T11:22:40.673", "Id": "501185", "Score": "0", "body": "Yes, `hm_set()` and `hm_delete()` could easily be changed to take a plain pointer. We just need to copy the new structure into the old before we return." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T14:31:32.687", "Id": "254092", "ParentId": "254069", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T00:17:16.147", "Id": "254069", "Score": "2", "Tags": [ "c", "collections", "hash-map" ], "Title": "Generic hashmap with dynamic resizing and collision handling" }
254069
<p>System76 sells laptops that come preloaded with their Ubuntu spinoff Pop_OS. The laptop keyboards have backlights that can change color and brightness, but so far <strong>I haven't found any way to keep the setting when I restart the machine; it goes back to bright white</strong>.</p> <p><a href="https://www.reddit.com/r/System76/comments/gj5mss/5th_gen_oryx_pro_keyboard_backlight/" rel="nofollow noreferrer">Here's someone else struggling with the same problem somewhat recently</a>. The comments link to a useful python script, but it doesn't seem to be finished to the point where it would do what's wanted. (It's primary goal seems to be a GUI, with persistence on the wishlist.)</p> <p>I finally got sick of it and implemented the behavior I wanted using systemd, which I'm using to call a Python script.</p> <p>Since other people have asked the same questions as me in the past, I figured I'd share my solution, but the first step is to ask for feedback.</p> <p><strong>Is this a good solution to the problem? Are there mistakes or other reasons people shouldn't use it?</strong></p> <pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python3 import argparse as ag import os.path as path import re print(&quot;Attempting to set system76 keyboard backlight color and brightness.&quot;) &quot;&quot;&quot; Partially cribbed from https://github.com/ahoneybun/keyboard-color-chooser/blob/master/keyboard-color-switcher.py Called by /etc/systemd/system/system76-kb-backlight.service as decribed here: https://www.howtogeek.com/687970/how-to-run-a-linux-program-at-startup-with-systemd/ Example file /etc/systemd/system/system76-kb-backlight.service `` [Unit] Description=Set color and brightness of system-76 laptop keyboard backlight [Service] Type=simple ExecStart=systemd-cat /path_to_this_executable/set_system76_kb_backlight -g 55 -r FF -B 150 [Install] WantedBy=multi-user.target `` (Don't forget to enable the service.) &quot;&quot;&quot; def color_fragment(string): if re.fullmatch(r'^[0-9A-F]{2}$', string): return string else: raise ag.ArgumentTypeError(f'&quot;{string}&quot; is not a two-digit hex value.') def brightness_fragment(string): if re.fullmatch(r'^[0-9]{1,3}$', string) and 0 &lt;= int(string) and 255 &gt;= int(string): return string else: raise ag.ArgumentTypeError(f'&quot;{string}&quot; is not an integer 0-255.') arg_parse = ag.ArgumentParser(description=&quot;Set the color and brightness of the system76 keyboard backlight.&quot;) arg_parse.add_argument('-r', help=&quot;The red RGB value (00 to FF).&quot;, default=&quot;00&quot;, type=color_fragment) arg_parse.add_argument('-g', help=&quot;The green RGB value (00 to FF).&quot;, default=&quot;00&quot;, type=color_fragment) arg_parse.add_argument('-b', help=&quot;The blue RGB value (00 to FF).&quot;, default=&quot;00&quot;, type=color_fragment) arg_parse.add_argument('-B', help=&quot;The brightness (0 to 255).&quot;, default=&quot;48&quot;, type=brightness_fragment) args = arg_parse.parse_args() red = args.r green = args.g blue = args.b brightness = args.B color = f'{red}{green}{blue}' ledPath = &quot;/&quot; + path.join('sys', 'class', 'leds', 'system76_acpi::kbd_backlight') + '/' if not path.exists(ledPath): ledPath = &quot;/&quot; + path.join('sys', 'class', 'leds', 'system76::kbd_backlight') + '/' regions = ['left', 'center', 'right', 'extra'] region_paths = [ledPath + f'color_{r}' for r in regions] brightness_path = ledPath + 'brightness' settings = {brightness_path: brightness, **{rp: color for rp in region_paths}} for (p,s) in settings.items(): with open(p, 'w') as f: f.write(s) print(&quot;Successfully set system76 keyboard backlight brightness.&quot;) arg_parse.exit(0) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T03:07:04.673", "Id": "501058", "Score": "1", "body": "Not enough for an answer, but another option could be a `-c` flag, where the user just enters colors like `00FF00`, instead of a separate flags for each color." } ]
[ { "body": "<h1>Namespaces...</h1>\n<p>... are not for creating taxonomies. They are there to avoid name collisions. Also the chosen module alias for <code>argparse</code> seems strange. It's name is derived from <em>argument parser</em> so, if any, the obvious abbreviation should be <code>ap</code>. However, it might be better to just import the needed names, instead of creating taxonomies, since there are no name collisions in your code base.</p>\n<pre><code>from argparse import ArgumentTypeError, ArgumentParser\nfrom os.path import exists, join\nfrom re import fullmatch\n</code></pre>\n<h1>Don't run business logic on module load</h1>\n<p>Currently, your script parses the command line arguments and writes to files, as soon as the module is laoded. This can be avoided by using an <code>if __name__ == '__main__':</code> guard and / or a <code>main()</code> function.</p>\n<pre><code>def main():\n &quot;&quot;&quot;Runs the script.&quot;&quot;&quot;\n\n arg_parse = ag.ArgumentParser(description=&quot;Set the color and brightness of the system76 keyboard backlight.&quot;)\n arg_parse.add_argument('-r', help=&quot;The red RGB value (00 to FF).&quot;, default=&quot;00&quot;, type=color_fragment)\n arg_parse.add_argument('-g', help=&quot;The green RGB value (00 to FF).&quot;, default=&quot;00&quot;, type=color_fragment)\n arg_parse.add_argument('-b', help=&quot;The blue RGB value (00 to FF).&quot;, default=&quot;00&quot;, type=color_fragment)\n arg_parse.add_argument('-B', help=&quot;The brightness (0 to 255).&quot;, default=&quot;48&quot;, type=brightness_fragment)\n\n args = arg_parse.parse_args()\n …\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>It might be even better to outsource the argument parsing into an own function.</p>\n<pre><code>def get_args():\n &quot;&quot;&quot;Parses the command line arguments.&quot;&quot;&quot;\n\n arg_parse = ag.ArgumentParser(description=&quot;Set the color and brightness of the system76 keyboard backlight.&quot;)\n arg_parse.add_argument('-r', help=&quot;The red RGB value (00 to FF).&quot;, default=&quot;00&quot;, type=color_fragment)\n arg_parse.add_argument('-g', help=&quot;The green RGB value (00 to FF).&quot;, default=&quot;00&quot;, type=color_fragment)\n arg_parse.add_argument('-b', help=&quot;The blue RGB value (00 to FF).&quot;, default=&quot;00&quot;, type=color_fragment)\n arg_parse.add_argument('-B', help=&quot;The brightness (0 to 255).&quot;, default=&quot;48&quot;, type=brightness_fragment)\n return arg_parse.parse_args()\n\n\ndef main():\n &quot;&quot;&quot;Runs the script.&quot;&quot;&quot;\n\n args = get_args()\n …\n</code></pre>\n<h1>Input validation</h1>\n<p>Your input validation seems complicated. In both cases, for the RGB values and the brightness, an integer within a certain range is expected.</p>\n<pre><code>def parse_rgb(text):\n &quot;&quot;&quot;Parses an RGB value from a string.&quot;&quot;&quot;\n \n rgb = int(text)\n \n if not 0 &lt;= rgb &lt;= 0xff:\n raise ValueError('RGB value out of bounds.')\n\n return rgb\n\n\ndef parse_brightness(text):\n &quot;&quot;&quot;Parses a value for the brightness from a string.&quot;&quot;&quot;\n \n brightness = int(text)\n \n if not 0 &lt;= brightness &lt;= 255:\n raise ValueError('Brightness out of bounds.')\n\n return brightness\n</code></pre>\n<p>Note that argparse will automatically display an error message if a parser specified at <code>type=</code> raises a <code>ValueError</code>. So you can also get rid of one import and work with a built-in exception instead.</p>\n<p>The downside of the integer parsing is, that you'll have to convert the <code>int</code>s back to strings then:</p>\n<pre><code>red = hex(args.r)[2:].upper().zfill(2)\ngreen = hex(args.g)[2:].upper().zfill(2)\nblue = hex(args.b)[2:].upper().zfill(2)\nbrightness = str(args.B)\n…\n</code></pre>\n<p>You may also subclass an <code>int</code> for this use case:</p>\n<pre><code>class RGB(int):\n def __init__(self, value):\n if not 0 &lt;= value &lt;= 0xff:\n raise ValueError('RGB value out of bounds.')\n\n def __str__(self):\n return hex(self)[2:].upper().zfill(2)\n\n …\n\narg_parse.add_argument('-r', help=&quot;The red RGB value (0x00 to 0xff).&quot;, default=RGB(0), type=RGB)\n…\nred = str(args.r)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T21:02:48.660", "Id": "501153", "Score": "0", "body": "This is all good advice, thanks! My current version is frankly bloated more than I'd like; whatever. One detail: using a `ValueError` instead of a `ArgumentTypeError` in the `type` callable causes argeparse to ignore/shadow the provided error message." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T09:20:33.013", "Id": "254083", "ParentId": "254071", "Score": "2" } }, { "body": "<p>I think this is a strange use of the path library:</p>\n<blockquote>\n<pre><code>&quot;/&quot; + path.join('sys', 'class', 'leds', 'system76_acpi::kbd_backlight') + '/'\n</code></pre>\n</blockquote>\n<p>It would be clearer as a single string, given that we don't need portability to non-Linux hosts:</p>\n<pre><code>'/sys/class/leds/system76_acpi::kbd_backlight/'\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-13T16:27:28.203", "Id": "502226", "Score": "0", "body": "Thanks. I think that, while `path.join` is maybe _overkill_ here, it's a normal way of working with paths. On the other hand, the mixing of string-concat and `path.join` is weird. Reading the docs again, I guess `path.join('/', 'sys', 'class', 'leds', 'system76_acpi::kbd_backlight', '')` would be proper?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-13T17:08:11.837", "Id": "502234", "Score": "0", "body": "It still seems somewhat odd, in that we're using `path.join()` which abstracts away the separator char, but then mixing literal `/` back in. Just an opinion, anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-13T21:20:39.220", "Id": "502275", "Score": "1", "body": "Agreed; it's odd that `os.path` doesn't give a way of _building_ absolute paths. On the other hand, the script at hand wouldn't be relevant outside of the one particular system, so portability is less of a concern :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-13T21:28:11.373", "Id": "502277", "Score": "0", "body": "Yes, I meant to mention that we weren't using the portability that `path.join()` was created for. I've updated now." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-11T13:55:43.233", "Id": "254556", "ParentId": "254071", "Score": "1" } } ]
{ "AcceptedAnswerId": "254083", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T02:44:03.630", "Id": "254071", "Score": "1", "Tags": [ "python", "python-3.x", "linux" ], "Title": "Persist keyboard backlight color on Linux laptop" }
254071
<p>Just finished my canvas game that is more or less replica of the old school arcade game &quot;Space Invaders&quot;.</p> <p>The code below chooses two random enemies every second (approximately) from the enemies array to shoot projectiles. If there are two or more enemies left in the array I want two random enemies to shoot every second and if there is only one enemy left only that enemy will shoot every second.</p> <p>I have two solutions for this problem. Both of them work. However the first one seems quite unnecessary repetitive and the second solution although short and elegant is probably unnecessary more &quot;expensive&quot;. Keep in mind I am beginner and I might be wrong here with my assumptions and conclusions.</p> <p>First solution:</p> <pre><code>let req; let timer = 0 function animate() { req = requestAnimationFrame(animate); ctx.clearRect(0, 0, canvas.width, canvas.height); // other game logic // two random enemies shoot every second if (timer % 60 === 0 &amp;&amp; timer !== 0) { let enemiesLength = enemies.length; if (enemiesLength &gt; 2) { let rndIndex_1; let rndIndex_2; rndIndex_1 = Math.floor(Math.random() * enemiesLength); do { rndIndex_2 = Math.floor(Math.random() * enemiesLength) } while (rndIndex_1 == rndIndex_2); enemies[rndIndex_1].shootProjectile(); enemies[rndIndex_2].shootProjectile(); } else if (enemiesLength === 2) { enemies[0].shootProjectile(); enemies[1].shootProjectile(); } else if (enemiesLength === 1) { enemies[0].shootProjectile(); } } // other game logic timer++ } animate(); </code></pre> <p>Second solution:</p> <pre><code>let req; let timer = 0 function animate() { req = requestAnimationFrame(animate); ctx.clearRect(0, 0, canvas.width, canvas.height); // other game logic // two random enemies shoot every second if (timer % 60 === 0 &amp;&amp; timer !== 0) { enemies.sort(() =&gt; 0.5 - Math.random()).slice(0, 2).forEach(e =&gt; { e.shootProjectile(); }); } // other game logic timer++ } animate(); </code></pre> <p>Any other solutions and help is much appreciated.</p> <p>EDIT:</p> <p>In response to CertainPerformance answer. I changed the answer to this so it would work:</p> <pre><code> if (timer % 60 === 0 &amp;&amp; timer !== 0) { const enemiesCopy = [...enemies]; const enemiesToShoot = []; while (enemiesToShoot.length &lt; 2 &amp;&amp; enemiesCopy.length) { const [enemy] = enemiesCopy.splice(Math.floor(Math.random() * enemiesCopy.length), 1); enemiesToShoot.push(enemy); } for (const enemy of enemiesToShoot) { enemy.shootProjectile(); } } </code></pre> <p>It works fine like this. Is this how it should be? Some clarification please.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T11:19:35.670", "Id": "501083", "Score": "1", "body": "Warning: do not make any more edits to your question. It is important that reviewers all see the same version of your code and your question will become a mess for future readers if you change it further. The edit you made after CertainPerformance's answer would ordinarily be rolled back, but we can't since Blindman67 posted an answer in the meantime. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T12:36:34.820", "Id": "501091", "Score": "0", "body": "No problem and thanks for the warning. I won't edit anything anymore, but I can remove the edit after CertainPerformance's answer if it is needed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T12:39:10.947", "Id": "501092", "Score": "0", "body": "Well, no. As I said, that edit is part of what Blindman saw when he reviewed it. So that's how it will have to stay." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T12:41:31.037", "Id": "501093", "Score": "0", "body": "All right and thanks for the understanding." } ]
[ { "body": "<p>Your second code looks better on the surface, but it has a couple problems:</p>\n<p><strong>Random sort bias</strong> <code>.sort(() =&gt; 0.5 - Math.random())</code> is biased - elements that occur earlier in the array will be chosen at a different frequency than elements that appear later (in most JS implementations, at least). For an extended description of this problem, see <a href=\"https://www.robweir.com/blog/2010/02/microsoft-random-browser-ballot.html\" rel=\"nofollow noreferrer\">this page</a>. If you want to shuffle an array, you'll probably want to use the <a href=\"https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array\">fischer-yates shuffle</a>.</p>\n<p><strong>Sorting is expensive</strong> - given an array of size N, sorting it will take on the order of <code>N(log N)</code> operations. If there are a large number of items in the array, this could be a problem. I bet there won't be enough in your situation for the performance impact to be noticeable, but it's still somewhat inelegant to sort when sorting isn't needed. Choosing two indicies that aren't the same - what you're doing in the first code - is the better approach.</p>\n<p>So, to clean up your first code:</p>\n<p><strong>Abstract away distinct parts of the logic into functions</strong> to keep code readable and avoid long functions. That is, it'd be good if your first code could be refactored to something somewhat resembling the following:</p>\n<pre><code>let req;\nlet timer = 0\nfunction animate() {\n req = requestAnimationFrame(animate);\n ctx.clearRect(0, 0, canvas.width, canvas.height); // maybe put this into the function below\n initialGameLogic();\n haveEnemiesShoot();\n otherGameLogic();\n timer++\n}\n\nanimate();\n</code></pre>\n<p><strong>Do you really need to save the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame#Return_value\" rel=\"nofollow noreferrer\">callback ID</a> from <code>requestAnimationFrame</code>?</strong> Are you using <code>cancelAnimationFrame</code> somewhere? If so, it's needed - if you aren't, you can remove the <code>req</code> variable.</p>\n<p><strong><code>timer</code> name</strong> isn't very precise - it's not completely obvious what it refers to until you read how it's used. Consider calling it something like <code>frameNumber</code> instead.</p>\n<p><strong>Selecting random indicies</strong> This is the big one. A reasonably clean way to approach this that I'd prefer would be to copy the array, then select random indicies and <code>splice</code> them out until the number of projectiles is reached or the array is empty:</p>\n<pre><code>const enemiesCopy = [...enemies];\nconst enemiesToShoot = [];\nwhile (enemiesToShoot.length &lt; 2 &amp;&amp; enemiesCopy.length) {\n const [enemy] = enemiesCopy(Math.floor(Math.random() * enemiesCopy.length), 1);\n enemiesToShoot.push(enemy);\n}\nfor (const enemy of enemiesToShoot) {\n enemy.shootProjectile();\n}\n</code></pre>\n<p>This is easily adaptable to any number of projectiles - just change the <code>2</code> to a variable that gets altered as needed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T04:06:37.233", "Id": "501059", "Score": "0", "body": "Thanks a lot for the help. However I could not make it work. Did I not implement it right? Any suggestions?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T04:36:42.727", "Id": "501060", "Score": "0", "body": "Thanks for the quick edit and response but I still can't make it work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T04:41:26.297", "Id": "501061", "Score": "0", "body": "Typo, I forgot the `.length`, but the general approach should be \n clear regardless, right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T04:56:12.620", "Id": "501062", "Score": "0", "body": "The general approach is clear. Also I changed enemiesLength to enemiesCopy.length. Is this how it should be? It works now but some clarification would be nice." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T03:39:52.087", "Id": "254074", "ParentId": "254072", "Score": "4" } }, { "body": "<h2>Games</h2>\n<h3>Performance</h3>\n<p>Writing games using JavaScript presents some unique problems.</p>\n<ul>\n<li><p>Jank and slowdown due to memory management. Though there have been vast improvements to what was the norm just a few years back, memory management remains a major point of performance degradation.</p>\n<p>Games must always be aware of the issues of memory management. Many common pattern used in JavaScript are not suitable for games.</p>\n</li>\n<li><p>Platform variance. JavaScript games will run a vast range of platforms, from low end hand held devices, to power hungry overclocked water cooled desktop towers. The average consumer's device is generally of lower spec than the average developer's device.</p>\n<p>The success of a browser based game is highly dependent on social networking, a game that does not have a strong focus on performance will not be as successful. Even minor performance problems can make the game unplayable on many more devices than would be expected on a linear curve as the majority of devices are to the lower end of capability.</p>\n<p>Bad reviews are worse than good in a market dominated by word of mouth (social networking) Poor performance is a major driver of bad reviews.</p>\n</li>\n</ul>\n<p>To get the best performance you must get a good understanding of what is slow and what is fast. This is true right down to the most trivial operations need to consider performance.</p>\n<h2>A look at performance.</h2>\n<h3>Arrays are slow.</h3>\n<p>Creating and populating arrays are slow due to many factors.</p>\n<ul>\n<li>Allocation on heap</li>\n<li>Iteration to fill</li>\n<li>De-allocation at end of execution (is scoped to execution content) or as a GC deferred slowdown if part of scope that is not released at execution idle.</li>\n</ul>\n<p>The following snippet shows 3 examples, two from your question and a 3rd I created,</p>\n<p>To ensure that the optimizer does not remove code that has no side effects the enemy shoot function returns a random value that is added to a global <code>soak</code>. All 3 methods use the same <code>enemy</code>, <code>enemies</code> and <code>soak</code>.</p>\n<p>This test concentrates only on the shooting ignoring the time test.</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> const enemyCount = 60;\n const enemy = { shootProjectile(){ return Math.random() } }\n const enemies = $setOf(enemyCount,() =&gt; ({...enemy}));\n \n\n var soak = 0;\n function testA() {\n enemies.sort(() =&gt; 0.5 - Math.random()).slice(0, 2).forEach(e =&gt; {\n soak += e.shootProjectile();\n }\n\n function testB() {\n const enemiesCopy = [...enemies];\n const enemiesToShoot = [];\n \n while (enemiesToShoot.length &lt; 2 &amp;&amp; enemiesCopy.length) {\n const [enemy] = enemiesCopy.splice(Math.floor(Math.random() * enemiesCopy.length), 1);\n enemiesToShoot.push(enemy);\n }\n for (const enemy of enemiesToShoot) {\n soak += enemy.shootProjectile();\n }\n }\n\n function testC() {\n const shooterIdx = Math.random() * enemies.length | 0;\n var shooterIdx1 = Math.random() * enemies.length | 0;\n if (shooterIdx1 === shooterIdx) { shooterIdx1 = (shooterIdx1 + 1) % enemies.length }\n soak += enemies[shooterIdx].shootProjectile();\n soak += enemies[shooterIdx1].shootProjectile();\n }</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><strong>Shooters: 60. Shots per call: 2</strong></p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Test Function</th>\n<th style=\"text-align: right;\">Mean time</th>\n<th style=\"text-align: right;\">Max diff</th>\n<th style=\"text-align: right;\">OPS*</th>\n<th style=\"text-align: right;\">Relative Performance *1</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>TestA</td>\n<td style=\"text-align: right;\">31.929µs</td>\n<td style=\"text-align: right;\">±17.298µs</td>\n<td style=\"text-align: right;\">31,319</td>\n<td style=\"text-align: right;\">1%</td>\n</tr>\n<tr>\n<td>TestB</td>\n<td style=\"text-align: right;\">0.609µs</td>\n<td style=\"text-align: right;\">±0.604µs</td>\n<td style=\"text-align: right;\">1,642,819</td>\n<td style=\"text-align: right;\">27%</td>\n</tr>\n<tr>\n<td>TestC</td>\n<td style=\"text-align: right;\">0.166µs</td>\n<td style=\"text-align: right;\">±0.226µs</td>\n<td style=\"text-align: right;\">6,025,389</td>\n<td style=\"text-align: right;\">100%</td>\n</tr>\n</tbody>\n</table>\n</div>\n<ul>\n<li>µs millisecond. 1 millionth of second.</li>\n<li>(*) OPS is calculated operations per second, where the function call is considered the operation</li>\n<li>(*1) Percentage of best</li>\n</ul>\n<p>As higher enemy counts will negatively effect the outcome of <code>testA</code> and <code>testB</code> and lower enemy counts will negatively effect the outcome of <code>testC</code> the following table is with an enemy count of 6</p>\n<p><strong>Shooters: 6. Shots per call: 2</strong></p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Test Function</th>\n<th style=\"text-align: right;\">Mean time</th>\n<th style=\"text-align: right;\">Max diff</th>\n<th style=\"text-align: right;\">OPS</th>\n<th style=\"text-align: right;\">Relative Performance</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>TestA</td>\n<td style=\"text-align: right;\">1.208µs</td>\n<td style=\"text-align: right;\">±0.284µs</td>\n<td style=\"text-align: right;\">828,136</td>\n<td style=\"text-align: right;\">14%</td>\n</tr>\n<tr>\n<td>TestB</td>\n<td style=\"text-align: right;\">0.490µs</td>\n<td style=\"text-align: right;\">±0.123µs</td>\n<td style=\"text-align: right;\">2,039,537</td>\n<td style=\"text-align: right;\">34%</td>\n</tr>\n<tr>\n<td>TestC</td>\n<td style=\"text-align: right;\">0.168µs</td>\n<td style=\"text-align: right;\">±0.266µs</td>\n<td style=\"text-align: right;\">5,959,047</td>\n<td style=\"text-align: right;\">100%</td>\n</tr>\n</tbody>\n</table>\n</div><h3>Game compromises</h3>\n<p>I have been in the games industry for a long time and one thing I have learnt is that pushing for ideal implementations will hurt performance, while compromising in favor of performance goes completely unnoticed.</p>\n<p><strong>Selecting many from many</strong></p>\n<p>There is another factor that effects the performance of the code and that is the number of shooters. As function <code>textC</code> can only handle 2 shooters at a time we must rewrite it to work with any number of shooters.</p>\n<p>At this point we make a sacrifice. Finding shooters randomly means that we need to test against shooter firing at the same time. This overhead should be ignored, rather we flag shooters that get to shoot so that we do not shoot twice.</p>\n<p><strong>The compromise</strong></p>\n<p>The function TestC will shoot about 7% less than the others giving it a slight advantage, but that advantage pales when compared to the 3* faster than <code>testB</code> and a huge 30* faster than <code>testA</code></p>\n<p>The updated code</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>const enemyCount = 60;\nconst enemyShoot = 10;\nconst enemy = {\n shoot: 0,\n shootProjectile(){ return Math.random() }\n}\nconst enemies = $setOf(enemyCount,() =&gt; ({...enemy}));\n\nvar soak = 0;\nvar time = 0;\nfunction testA() {\n enemies.sort(() =&gt; 0.5 - Math.random()).slice(0, enemyShoot).forEach(e =&gt; {\n soak += e.shootProjectile();\n });\n time ++;\n}\n\nfunction testB() {\n const enemiesCopy = [...enemies];\n const enemiesToShoot = [];\n while (enemiesToShoot.length &lt; enemyShoot &amp;&amp; enemiesCopy.length) {\n const [enemy] = enemiesCopy.splice(Math.floor(Math.random() * enemiesCopy.length), 1);\n enemiesToShoot.push(enemy);\n }\n for (const enemy of enemiesToShoot) {\n soak += enemy.shootProjectile();\n }\n time ++;\n}\n\n\nfunction testC() {\n var count = enemyShoot + 1;\n while (count--) {\n const shooter = enemies[Math.random() * enemies.length | 0];\n soak += shooter.shoot !== time ? (shooter.shoot = time, shooter.shootProjectile()) : 0;\n }\n time ++;\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p><strong>Shooters: 60. Shots per call: 10</strong></p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Test Function</th>\n<th style=\"text-align: right;\">Mean time</th>\n<th style=\"text-align: right;\">Max diff</th>\n<th style=\"text-align: right;\">OPS</th>\n<th style=\"text-align: right;\">Relative Performance</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>TestA</td>\n<td style=\"text-align: right;\">26.669µs</td>\n<td style=\"text-align: right;\">±8.919µs</td>\n<td style=\"text-align: right;\">37,497</td>\n<td style=\"text-align: right;\">3%</td>\n</tr>\n<tr>\n<td>TestB</td>\n<td style=\"text-align: right;\">2.293µs</td>\n<td style=\"text-align: right;\">±1.023µs</td>\n<td style=\"text-align: right;\">436,149</td>\n<td style=\"text-align: right;\">33%</td>\n</tr>\n<tr>\n<td>TestC</td>\n<td style=\"text-align: right;\">0.762µs</td>\n<td style=\"text-align: right;\">±0.834µs</td>\n<td style=\"text-align: right;\">1,313,125</td>\n<td style=\"text-align: right;\">100%</td>\n</tr>\n</tbody>\n</table>\n</div><h3>Arrays the outcome</h3>\n<p>As you can see the results show that using arrays in this case to select items to perform and action is much slower than avoiding the need to hold shooters.</p>\n<p>With that said arrays are not bad if used correctly.</p>\n<p>Part of the performance penalty of arrays is the allocation and de allocation process.</p>\n<p>As memory is currently very cheap compared to CPU cycles you can leave arrays populated and keep a separate counter to track how many active items it holds. This eliminates the need to allocate and de-allocate arrays each frame.</p>\n<h3>The overhead of iteration</h3>\n<p>Each time you iterate an array you add the overhead of the loop logic. A general rule is iterate twice only, once for update, once for display. Actions that you would normally do in a separate loop should be done in the update loop.</p>\n<p>In this case as you would already be iterating each enemy to move them, this is where the logic to select a shooter should be.</p>\n<p>I would not try for 2 shooters every 1 seconds, I would give all shooters odds to shoot that are equivalent. So if there are 60 enemy at 2 shoots total every 1 second the odds for any shooter shooting per frame is 2 / (60 * 60) = 5.556e-4</p>\n<p>Thus in the main enemy loop you add <code>Math.random() &lt; 5.556e-4 &amp;&amp; enemy.shootProjectile();</code> complete eliminating the extra code finding shooters, and in my view creating a far more realistic AI.</p>\n<p><sub> All tests on Chrome 87. 64Bit i9 windows laptop, cooling set to active.</sub></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T09:37:36.943", "Id": "501074", "Score": "0", "body": "Hey thanks a lot for the detailed answer. I really appreciate it. I edited my question so if u can see if I understood you correctly would be nice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T09:55:16.230", "Id": "501075", "Score": "4", "body": "@HappyCoconut That is about correct but the odds need to be calculated `shotsPerSecond / (enemy.length * framesPerSecond)` which would be recalculated only when needed (eg enemies count changes) and outside the loop. Also the firing test should be done is the same loop as the enemies are normally updated in. BTW not that I mind, but the general rule here at CR is you should avoid changes to the question after you have accepted an answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T09:58:43.430", "Id": "501076", "Score": "0", "body": "Thanks a lot for the explanation. I will avoid changing the question in the future. Final question: should I erase the edits now?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T10:01:27.373", "Id": "501077", "Score": "1", "body": "@HappyCoconut I dont think anyone will take issue with it, just something to keep in mind next time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T11:21:52.047", "Id": "501084", "Score": "1", "body": "Oh, there are plenty of issues with edits like that. I'm glad the damage was limited, but it's a step beyond what we'd like already." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T12:07:20.533", "Id": "501088", "Score": "1", "body": "@HappyCoconut An Old school space invaders example on codepen using odds to fire invader bombs https://codepen.io/Blindman67/pen/WYxQam" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T12:28:27.757", "Id": "501090", "Score": "0", "body": "Hey thanks a lot for this!" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T08:52:10.757", "Id": "254081", "ParentId": "254072", "Score": "7" } } ]
{ "AcceptedAnswerId": "254081", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T03:12:42.333", "Id": "254072", "Score": "5", "Tags": [ "javascript", "canvas" ], "Title": "Make two random enemies shoot projectiles every second" }
254072
<p>I am trying to create an optimized 16-bit division algorithm for the AVR ATMEGA1284. The goal is to reduce the number of clock cycles as much as possible.</p> <p>AVR INSTRUCTION SET MANUAL: <a href="https://ww1.microchip.com/downloads/en/devicedoc/atmel-0856-avr-instruction-set-manual.pdf" rel="nofollow noreferrer">https://ww1.microchip.com/downloads/en/devicedoc/atmel-0856-avr-instruction-set-manual.pdf</a></p> <p>AVR200: Multiply and Divide Routines: <a href="https://ww1.microchip.com/downloads/en/AppNotes/doc0936.pdf" rel="nofollow noreferrer">https://ww1.microchip.com/downloads/en/AppNotes/doc0936.pdf</a></p> <p>A standard shift and subtract type division algorithm suggested by Atmel/Microchip takes between 173 clock cycles and 243 clock cycles, depending on if you unroll the loop or not.</p> <p>What I have so far takes a maximum of 68 clock cycles. I ran an exhaustive test 16-hour test proving that the algorithm returns the correct result for all 2^32 combinations of inputs and outputs. So I am not looking for any validation that the algorithm returns the correct results. I am looking for ways to reduce either the code size, lookup table size, or number of clock cycles.</p> <p>The constraints are as follows.</p> <ul> <li>The dividend is an unsigned 16-bit number passed into the algorithm in a pair of 8-bit registers.</li> <li>The divisor is an unsigned 16-bit number passed into the algorithm in a pair of 8-bit registers.</li> <li>The algorithm returns the quotient in a pair of 8-bit registers.</li> <li>The algorithm also returns the remainder in a pair of 8-bit registers.</li> <li>The algorithm code (plus any lookup tables) must consume less than 5K bytes of flash memory.</li> <li>The algorithm may return any values for division by 0.</li> </ul> <p>Here is what I have so far.</p> <pre><code>.align 256 ;Recipricol table #1, high byte. ;R1H_TBL[x] = min( high(2^16/x) / 256 , 255) R1H_TBL: .db 0xFF, 0xFF, 0x80, 0x55, 0x40, 0x33, 0x2A, 0x24, 0x20, 0x1C, 0x19, 0x17, 0x15, 0x13, 0x12, 0x11 .db 0x10, 0x0F, 0x0E, 0x0D, 0x0C, 0x0C, 0x0B, 0x0B, 0x0A, 0x0A, 0x09, 0x09, 0x09, 0x08, 0x08, 0x08 .db 0x08, 0x07, 0x07, 0x07, 0x07, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x05, 0x05, 0x05, 0x05, 0x05 .db 0x05, 0x05, 0x05, 0x05, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04 .db 0x04, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03 .db 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02 .db 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02 .db 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02 .db 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 .db 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 .db 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 .db 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 .db 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 .db 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 .db 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 .db 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 ;Recipricol table #1, low byte. ;R1L_TBL[x] = min( low(2^16/x) mod 256 , 255) R1L_TBL: .db 0xFF, 0xFF, 0x00, 0x55, 0x00, 0x33, 0xAA, 0x92, 0x00, 0x71, 0x99, 0x45, 0x55, 0xB1, 0x49, 0x11 .db 0x00, 0x0F, 0x38, 0x79, 0xCC, 0x30, 0xA2, 0x21, 0xAA, 0x3D, 0xD8, 0x7B, 0x24, 0xD3, 0x88, 0x42 .db 0x00, 0xC1, 0x87, 0x50, 0x1C, 0xEB, 0xBC, 0x90, 0x66, 0x3E, 0x18, 0xF4, 0xD1, 0xB0, 0x90, 0x72 .db 0x55, 0x39, 0x1E, 0x05, 0xEC, 0xD4, 0xBD, 0xA7, 0x92, 0x7D, 0x69, 0x56, 0x44, 0x32, 0x21, 0x10 .db 0x00, 0xF0, 0xE0, 0xD2, 0xC3, 0xB5, 0xA8, 0x9B, 0x8E, 0x81, 0x75, 0x69, 0x5E, 0x53, 0x48, 0x3D .db 0x33, 0x29, 0x1F, 0x15, 0x0C, 0x03, 0xFA, 0xF1, 0xE8, 0xE0, 0xD8, 0xD0, 0xC8, 0xC0, 0xB9, 0xB1 .db 0xAA, 0xA3, 0x9C, 0x95, 0x8F, 0x88, 0x82, 0x7C, 0x76, 0x70, 0x6A, 0x64, 0x5E, 0x59, 0x53, 0x4E .db 0x49, 0x43, 0x3E, 0x39, 0x34, 0x30, 0x2B, 0x26, 0x22, 0x1D, 0x19, 0x14, 0x10, 0x0C, 0x08, 0x04 .db 0x00, 0xFC, 0xF8, 0xF4, 0xF0, 0xEC, 0xE9, 0xE5, 0xE1, 0xDE, 0xDA, 0xD7, 0xD4, 0xD0, 0xCD, 0xCA .db 0xC7, 0xC3, 0xC0, 0xBD, 0xBA, 0xB7, 0xB4, 0xB2, 0xAF, 0xAC, 0xA9, 0xA6, 0xA4, 0xA1, 0x9E, 0x9C .db 0x99, 0x97, 0x94, 0x92, 0x8F, 0x8D, 0x8A, 0x88, 0x86, 0x83, 0x81, 0x7F, 0x7D, 0x7A, 0x78, 0x76 .db 0x74, 0x72, 0x70, 0x6E, 0x6C, 0x6A, 0x68, 0x66, 0x64, 0x62, 0x60, 0x5E, 0x5C, 0x5A, 0x58, 0x57 .db 0x55, 0x53, 0x51, 0x50, 0x4E, 0x4C, 0x4A, 0x49, 0x47, 0x46, 0x44, 0x42, 0x41, 0x3F, 0x3E, 0x3C .db 0x3B, 0x39, 0x38, 0x36, 0x35, 0x33, 0x32, 0x30, 0x2F, 0x2E, 0x2C, 0x2B, 0x29, 0x28, 0x27, 0x25 .db 0x24, 0x23, 0x21, 0x20, 0x1F, 0x1E, 0x1C, 0x1B, 0x1A, 0x19, 0x18, 0x16, 0x15, 0x14, 0x13, 0x12 .db 0x11, 0x0F, 0x0E, 0x0D, 0x0C, 0x0B, 0x0A, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01 ;Recipricol table #2 ;R2_TBL[x] = min( 2^16/(x+256), 255) R2_TBL: .db 0xFF, 0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8, 0xF7, 0xF6, 0xF5, 0xF4, 0xF3, 0xF2, 0xF1 .db 0xF0, 0xF0, 0xEF, 0xEE, 0xED, 0xEC, 0xEB, 0xEA, 0xEA, 0xE9, 0xE8, 0xE7, 0xE6, 0xE5, 0xE5, 0xE4 .db 0xE3, 0xE2, 0xE1, 0xE1, 0xE0, 0xDF, 0xDE, 0xDE, 0xDD, 0xDC, 0xDB, 0xDB, 0xDA, 0xD9, 0xD9, 0xD8 .db 0xD7, 0xD6, 0xD6, 0xD5, 0xD4, 0xD4, 0xD3, 0xD2, 0xD2, 0xD1, 0xD0, 0xD0, 0xCF, 0xCE, 0xCE, 0xCD .db 0xCC, 0xCC, 0xCB, 0xCA, 0xCA, 0xC9, 0xC9, 0xC8, 0xC7, 0xC7, 0xC6, 0xC5, 0xC5, 0xC4, 0xC4, 0xC3 .db 0xC3, 0xC2, 0xC1, 0xC1, 0xC0, 0xC0, 0xBF, 0xBF, 0xBE, 0xBD, 0xBD, 0xBC, 0xBC, 0xBB, 0xBB, 0xBA .db 0xBA, 0xB9, 0xB9, 0xB8, 0xB8, 0xB7, 0xB7, 0xB6, 0xB6, 0xB5, 0xB5, 0xB4, 0xB4, 0xB3, 0xB3, 0xB2 .db 0xB2, 0xB1, 0xB1, 0xB0, 0xB0, 0xAF, 0xAF, 0xAE, 0xAE, 0xAD, 0xAD, 0xAC, 0xAC, 0xAC, 0xAB, 0xAB .db 0xAA, 0xAA, 0xA9, 0xA9, 0xA8, 0xA8, 0xA8, 0xA7, 0xA7, 0xA6, 0xA6, 0xA5, 0xA5, 0xA5, 0xA4, 0xA4 .db 0xA3, 0xA3, 0xA3, 0xA2, 0xA2, 0xA1, 0xA1, 0xA1, 0xA0, 0xA0, 0x9F, 0x9F, 0x9F, 0x9E, 0x9E, 0x9D .db 0x9D, 0x9D, 0x9C, 0x9C, 0x9C, 0x9B, 0x9B, 0x9A, 0x9A, 0x9A, 0x99, 0x99, 0x99, 0x98, 0x98, 0x98 .db 0x97, 0x97, 0x97, 0x96, 0x96, 0x95, 0x95, 0x95, 0x94, 0x94, 0x94, 0x93, 0x93, 0x93, 0x92, 0x92 .db 0x92, 0x91, 0x91, 0x91, 0x90, 0x90, 0x90, 0x90, 0x8F, 0x8F, 0x8F, 0x8E, 0x8E, 0x8E, 0x8D, 0x8D .db 0x8D, 0x8C, 0x8C, 0x8C, 0x8C, 0x8B, 0x8B, 0x8B, 0x8A, 0x8A, 0x8A, 0x89, 0x89, 0x89, 0x89, 0x88 .db 0x88, 0x88, 0x87, 0x87, 0x87, 0x87, 0x86, 0x86, 0x86, 0x86, 0x85, 0x85, 0x85, 0x84, 0x84, 0x84 .db 0x84, 0x83, 0x83, 0x83, 0x83, 0x82, 0x82, 0x82, 0x82, 0x81, 0x81, 0x81, 0x81, 0x80, 0x80, 0x80 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;ARGUMENTS: r16, r17, r18, r19 ; r16:r17 = N (numerator) ; r18:r19 = D (divisor) ;RETURNS: r20, r21 ; r20:r21 (quotient) ; r22:r23 (remainder) ; ;DESCRIPTION: divides an unsigned 16 bit number N by unsigned 16 bit divisor D ; Typical run time is 57 to 68 clock cycles. ; ;ALGORITHM OVERVIEW ; ;RZERO = 0; ;if(D &lt; 256){ ; N2 = (N * ((R1H_TBL[D] &lt;&lt; 8) + R1L_TBL[D])) &gt;&gt; 16; ; P = N2 * D ;}else{ ; D1 = (R1H_TBL[D] * D) &gt;&gt; 8 ; N1 = (R1H_TBL[D] * N) &gt;&gt; 8 ; if(D1 &lt; 256){ ; N2 = N1 &gt;&gt; 8; ; }else{ ; N2 = N1 * R2_TBL[D1 &amp; 0xFF]; ; } ; P = N2 * D; ; if(P &gt; 65535){ ; N2 = N2 - 1 ;//Decrement quotient ; N1 = N2 - P + D;//Calculate remainder ; return;//return quotient in N2, remainder in N1 ; } ;} ;N1 = N - P; ;if(P &gt; N){ ; N2 = N2 - 1;//decrease quotient ; N1 = N1 + D;//increase reamainder ; return;//return quotient in N2, remainder in N1 ;} ;if(N1 &gt; D){ ; N2 = N2 + 1; ; N1 = N1 - D; ; return;//return quotient in N2, remainder in N1 ;} ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; .def NH = r16 .def NL = r17 .def DH = r18 .def DL = r19 .def N2H = r20 .def N2L = r21 .def N1H = r22 .def N1L = r23 .def PRODL = r0 .def PRODH = r1 .def PH = r2 .def PL = r3 .def D1H = r4 .def D1L = r5 .def RZERO = r6 .def Rx = r7 idivu_16x16: clr RZERO ;1 ;Check that DH is not zero tst DH ;1 brne idivu_16x16_dhne ;2 ;code for D &lt; 256 idivu_16x8: ;lookup low byte of recipricol into P. ;where P = min(2^16 / D,2^16-1) mov zl, DL ;1 ldi zh, high(R1L_TBL*2) ;1 lpm PL, Z ;3 ldi zh, high(R1H_TBL*2) ;1 lpm PH, Z ;3 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;calculate N2 = (P * N) &gt;&gt; 16 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; NH:NL ; X RH:RL ;------------------------------------------ ; N2H | N2L | N1H | dropped ;----------+----------+----------+--------- ; | | H(PL*NL) | L(PL*NL) ; | H(PL*NH) | L(PL*NH) | ; | H(PH*NL) | L(PH*NL) | ; H(PH*NH) | L(PH*NH) | | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; mul NL , PL ;2 PL*NL mov N1H, PRODH ;1 N1H &lt;= H(PL*NL) mul NH , PH ;2 PH*NH mov N2H, PRODH ;1 N2H &lt;= H(PH*NH) mov N2L, PRODL ;1 N2L &lt;= L(PH*NH) mul NH , PL ;2 PL*NH add N1H, PRODL ;1 N1H &lt;= H(PL*NL) + L(PL*NH) adc N2L, PRODH ;1 N2L &lt;= L(PH*NH) + H(PL*NH) adc N2H, RZERO ;1 propagate carry to N2H mul NL , PH ;2 PH*NL add N1H, PRODL ;1 N1H &lt;= H(PL*NL) + L(PL*NH) + L(PH*NL) adc N2L, PRODH ;1 N2L &lt;= H(PH*NL) + L(PH*NH) + H(PL*NH) adc N2H, RZERO ;1 propagate carry to N2H ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;calculate P = N2 * DL ,note DH=0 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; mul N2L, DL ;2 mov PL, PRODL ;1 mov PH, PRODH ;1 mul N2H, DL ;2 add PH, PRODL ;1 rjmp idivu_16x16_adj_n ;2 ;code for D &gt;= 256 idivu_16x16_dhne: ;Lookup Rx = min(256 / DH, 255) mov zl, DH ;1 ldi zh, high(R1H_TBL*2) ;1 lpm Rx, Z ;3 ;D1 = (D * Rx) &gt;&gt; 8 mul Rx , DH ;2 mov D1L, PRODL ;1 mov D1H, PRODH ;1 mul Rx , DL ;2 add D1L, PRODH ;1 adc D1H, RZERO ;1 ;N1 = (D * Rx) &gt;&gt; 8 mul Rx , NH ;2 mov N1L, PRODL ;1 mov N1H, PRODH ;1 mul Rx , NL ;2 add N1L, PRODH ;1 adc N1H, RZERO ;1 ;if D1H = 0 then use Rx = 256, otherwise use table tst D1H ;1 brne idivu_16x16_dxhne ;2 mov N2L, N1H ;1 clr N2H ;1 rjmp idivu_16x16_checkn;2 idivu_16x16_dxhne: ;Lookup Rx = (2 ^ 16) \ (256 + D1H) mov zl, D1L ;1 ldi zh, high(R2_TBL*2) ;1 lpm Rx, Z ;3 ;N2 = (N1 * R2) &gt;&gt; 16 mul Rx , N1H ;2 mov PL , PRODL ;1 mov N2L , PRODH ;1 mul Rx , N1L ;2 add PL , PRODH ;1 adc N2L, RZERO ;1 clr N2H ;1 idivu_16x16_checkn: ;Check result (it may be off by +/- 1) ;P = N2 * D ;NOTE: N2 &lt;=255 so NxH = 0, also P &lt; 2^16 so we can discard upper byte of DH * NxL mul DL , N2L ;2 mov PL, PRODL ;1 mov PH, PRODH ;1 mul DH , N2L ;2 add PH , PRODL ;1 brcc idivu_16x16_adj_n ;2 ;if multiply overflowed then... ;decrement quotient ;calculate remainder as N - P + D subi N2L, 0x01 ;1 sbci N2H, 0x00 ;1 mov N1L, NL ;1 mov N1H, NH ;1 sub N1L, PL ;1 sbc N1H, PH ;1 add N1L, DL ;1 adc N1H, DH ;1 rjmp idivu_16x16_end ;2 ;Adjust result up or down by 1 if needed. idivu_16x16_adj_n: ;Add -P to N, with result in P mov N1L, NL ;1 mov N1H, NH ;1 sub N1L, PL ;1 sbc N1H, PH ;1 brsh idivu_16x16_pltn ;2 idivu_16x16_decn2: ;if P &gt; N then decrement quotient, add to remainder subi N2L, 0x01 ;1 sbci N2H, 0x00 ;1 add N1L, DL ;1 adc N1H, DH ;1 rjmp idivu_16x16_end ;2 idivu_16x16_pltn: ;test remainder to D cp N1L, DL ;1 cpc N1H, DH ;1 ;if remainder &lt; D then goto end brlo idivu_16x16_end ;2 ;if remainder &gt;= D then increment quotient, reduce remainder subi N2L, 0xFF ;1 sbci N2H, 0xFF ;1 sub N1L, DL ;1 sbc N1H, DH ;1 idivu_16x16_end: ret .undef NH .undef NL .undef DH .undef DL .undef N2H .undef N2L .undef N1H .undef N1L .undef PRODL .undef PRODH .undef PH .undef PL .undef D1H .undef D1L .undef RZERO .undef Rx </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T15:51:29.637", "Id": "501112", "Score": "0", "body": "What is the specific assembler you're using?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T16:05:52.723", "Id": "501114", "Score": "0", "body": "Also, why is the division being performed on this device?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T16:09:53.250", "Id": "501115", "Score": "0", "body": "Finally, can you give some domain information on the variables being divided? Often, this information can help optimize algebraic operations or even avoid them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T03:21:53.020", "Id": "501234", "Score": "0", "body": "@Reinderien The division is being used to determine the intersection points of lines in a 2D space. This is used as part of some 2D graphics rendering routines. Specifically I have some data points from an external source and am scaling the data points in both X & Y for visual display. A 2D line is drawn between adjacent data-points to create a line graph. It may happen that one or both points are totally outside the bounds of the screen once scaled. In that case I need to determine the intersections of the lines with the display area before drawing them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T03:23:27.830", "Id": "501236", "Score": "0", "body": "@Reinderien I am using AVR Assembler in Atmel Studio 7." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T06:31:34.393", "Id": "501245", "Score": "0", "body": "Will you be using Bresenham's line algorithm?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T19:39:42.547", "Id": "501294", "Score": "0", "body": "@Reinderien Its an algorithm that I developed myself, but it solves the same problem in the same way, so it wound up being similar to Bresenham's line algorithm." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-13T18:21:21.180", "Id": "502257", "Score": "0", "body": "@greybeard Fixed typo in code comment. Its now N2 = N1 * …" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-13T21:50:58.967", "Id": "502279", "Score": "0", "body": "(Fired up my venerable Atmel Studio. Found no obvious performance blunder in the implementation, in contrast to most every \"more-than-8-bits-implementation\" in avr200b.asm. Guesstimate a competent non-restoring implementation is around 130 cycles. If those digits following the `;` are to be cycle counts, 2 for `mul` may be closer to reality than 1.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-13T23:10:02.530", "Id": "502283", "Score": "0", "body": "@greybeard The digits in my comments are cycle counts. You are correct, the ATMEGA1284 multiply takes 2 clock cycles. I will correct that. In any case I verified the run time using the simulator in Atmel Studio to be 68 clock cycles worst case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-14T07:44:00.060", "Id": "502302", "Score": "0", "body": "(A pity \"the `mul`s\" leave the result in a byte order different from the one used for parameter and result passing above (and by GCC) - 1 cycle for each pair of `mov`s from the `mul` result registers instead of a single `movw`.)" } ]
[ { "body": "<p>For assessibility and tinkering, I tried to transliterate into Python:</p>\n<pre class=\"lang-py prettyprint-override\"><code>''' all-16-bit numerator / divisor = (quotient, remainder) ALGORITHM OVERVIEW '''\nreciprocals_h = R1H_TBL = [ 255 ] + [ min(((1 &lt;&lt; 16) // x) &gt;&gt; 8, 255) for x in range(1, 256) ]\nreciprocals_l = R1L_TBL = [ 255 ] + [ min(((1 &lt;&lt; 16) // x)&amp;0xFF, 255) for x in range(1, 256) ]\nR2_TBL = [min((1 &lt;&lt; 16) // (x + 256), 255) for x in range(0, 256)]\ndivisor, numerator = D, N = 5, 42\n\nif divisor &lt; 256:\n quotient = N2 = (numerator * ((reciprocals_h[divisor] &lt;&lt; 8)\n + reciprocals_l[divisor])) &gt;&gt; 16\n product = P1 = quotient * divisor\nelse:\n D1 = (reciprocals_h[divisor] * divisor) &gt;&gt; 8\n remainder = N1 = (reciprocals_h[divisor] * numerator) &gt;&gt; 8\n quotient = (remainder &gt;&gt; 8 if D1 &lt; 256\n else remainder * R2_TBL[D1 &amp; 0xFF])\n product = quotient * divisor\n if product &gt; 65535:\n quotient = quotient - 1 # Decrement quotient\n remainder = quotient - product + divisor # Calculate remainder\n return (quotient, remainder)\n\nremainder = numerator - product\nif product &gt; numerator:\n quotient = quotient - 1 # decrement quotient\n remainder = remainder + divisor # increase remainder\n return (quotient, remainder)\nif remainder &gt; divisor:\n quotient = quotient + 1\n remainder = remainder - divisor\n return (quotient, remainder)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-14T16:00:31.350", "Id": "502349", "Score": "0", "body": "Is this really an answer though?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-14T17:02:16.923", "Id": "502358", "Score": "1", "body": "@Mast definitely *not an answer*: one of those *extended comments* SE doesn't provide for. Room for user4574 to improve on the readability of the embedded *ALGORITHM OVERVIEW*, starting with variable naming, before this gets deleted or rated down into oblivion. A *code review* from me would be an instance of *Don't do as I do: Do as I **say***." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-13T12:37:43.650", "Id": "254649", "ParentId": "254077", "Score": "0" } }, { "body": "<p><strong>Have mercy on the maintenance programmer</strong> -\nIt <em>may</em> be your older self.</p>\n<p>Separate documentation tends to become</p>\n<ul>\n<li>separated, as in <em>not always readily accessible</em><br />\n  (Murphy: when direly needed)</li>\n<li>out of sync - well, that's a problem even with in-line comments<br />\n  → document, in the code (for every part created for a separate reason)\n<ul>\n<li>what it is good for</li>\n<li>where it got inspired (there may be easily accessible explanations enlightening to someone unfamiliar with the problem at hand or the approach used: even name dropping may help find such)</li>\n<li>what has been the incentive to write it</li>\n</ul>\n</li>\n</ul>\n<p>Adopting good practices running counter to adverse customs isn't easy and fast.<br />\nMuch material about <em>assembly programming</em> is pre-1980s, when there was some reason to have short mnemonics for instructions and operands. (No matter pointing pen or finger at a (printed…if you were lucky) program listing: no pop-up. So better keep things all in one line…).</p>\n<p>Please <strong>use telling names</strong>. Coding in assembly is no licence not to.<br />\nIn a division implementation, I'd not imagine problems with <code>R</code> for <em>remainder</em> or <code>Q</code> for <em>quotient</em>. Resist any impulse to outsmart everyone with the likes of <code>DVsor</code>. <code>N</code> for numerator wouldn't be bad if talking about fractions, but if\n<code>N2</code> and <code>N1</code> in addition - all three in H and L flavours - weren't bad enough, along comes</p>\n<blockquote>\n<pre><code>;NOTE: N2 &lt;=255 so NxH = 0, also P &lt; 2^16 so we can discard upper byte of DH * NxL\n</code></pre>\n</blockquote>\n<p><code>P</code> <em>is</em> mentioned in the <em>ALGORITHM OVERVIEW</em>.</p>\n<p>In one comment, you switched from</p>\n<blockquote>\n<pre><code>sum = sum + term2\nsum = sum + term2 + term3\n</code></pre>\n</blockquote>\n<p>to</p>\n<blockquote>\n<pre><code>sum = sum + term2\nsum = term3 + sum + term2\n</code></pre>\n</blockquote>\n<p>Even then, I'd prefer</p>\n<pre><code>sum += term2 \nsum += term3\n</code></pre>\n<hr />\n<blockquote>\n<p>I am looking for ways to reduce either</p>\n<ul>\n<li>the code size,</li>\n<li>lookup table size,</li>\n<li>or number of clock cycles</li>\n</ul>\n</blockquote>\n<p>One source of inspiration on <em>how to code integer arithmetic</em> is <a href=\"https://github.com/gcc-mirror/gcc/blob/master/libgcc/config/avr/lib1funcs.S\" rel=\"nofollow noreferrer\">libgcc</a>:<br />\nA &quot;non-performing&quot; division would be slightly faster than a non-restoring one, but hardly faster than about 120 cycles.</p>\n<p>Rather than trying to understand the algorithm you sketch in <em>OVERVIEW</em> and thinking up shortcuts myself, I scrutinised the code presented. Did you write it from scratch, or did you take some compiler output for inspiration?</p>\n<p>Catching my eye:</p>\n<ul>\n<li>&quot;register order&quot; differs from the one implied by <code>mul</code> or the <a href=\"https://gcc.gnu.org/wiki/avr-gcc#Calling_Convention\" rel=\"nofollow noreferrer\">GCC calling convention</a>, preventing the 1 cycle&amp;word advantage each <code>movw</code> offers. As this is not included in <code>The constraints</code>, change either one.</li>\n<li>The critical (&quot;normal&quot;?) path turns out to be <em>taken branches</em> mostly. With AVR, non-taken branches are faster.<br />\nAs it turns out, table access is on the critical path. While it would seem possible to save at least 127 bytes of <code>R1H_TBL</code>, it would cost speed.</li>\n</ul>\n<hr />\n<p>With an eye on recognisability rather than mnemonic naming:</p>\n<pre><code>; not sure about the correct &quot;movw syntax with defs&quot;, anyway)\n\nidivu_16x8: ; 8 cycles less than idivu_16x16?\n; stab at catching all the micro efficiencies:\n; - AVR taken branches take longer: keep the critical path straight\n; - &quot;movw&quot; takes one cycle where two &quot;mov&quot;s take two\n; - where possible, arrange order of computation to render &quot;tst&quot; redundant\n; to leverage movw, low and high registers are exchanged with respect to\n; &lt;https://codereview.stackexchange.com/revisions/254077/4&gt;\n; digits starting an aligned in-line comment are cycle counts:\n; per instruction, cumulative in basic block,\n; and worst case cumulative from idivu_16x16\n\n;code for D &lt; 256 \n clr RZERO ;1 3\n;lookup low and high byte of reciprocal into P.\n;where P = min(2^16 / D, 2^16-1)\n mov zl, DL ;1 4\n ldi zh, high(R1L_TBL*2) ;1 1\n lpm PL, Z ;3 2\n ldi zh, high(R1H_TBL*2) ;1 5\n lpm PH, Z ;3 6 10\n ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n ;calculate N2 = (P * N) &gt;&gt; 16\n ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n ; NH:NL\n ; X RH:RL\n ;------------------------------------------\n ; N2H | N2L | N1H | dropped\n ;----------+----------+----------+---------\n ; H(PH*NH) | L(PH*NH) | H(PL*NL) | L(PL*NL)\n ; | H(PL*NH) | L(PL*NH) |\n ; | H(PH*NL) | L(PH*NL) |\n ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n mul NL , PL ;2 13 PL*NL\n mov N1H, PRODH ;1 2 N1H &lt;= H(PL*NL)\n mul NH , PH ;2 3 PH*NH\n movw N2H,PRODH ;1 5 N2H &lt;= H(PH*NH)\n ;mov N2L,PRODL ;1 6 N2L &lt;= L(PH*NH)\n mul NH , PL ;2 6 PL*NH\n add N1H, PRODL ;1 8 N1H &lt;= H(PL*NL) + L(PL*NH) \n adc N2L, PRODH ;1 9 N2L &lt;= L(PH*NH) + H(PL*NH)\n adc N2H, RZERO ;1 10 propagate carry to N2H \n mul NL , PH ;2 11 PH*NL\n add N1H, PRODL ;1 13 N1H &lt;= H(PL*NL) + L(PL*NH) + L(PH*NL)\n adc N2L, PRODH ;1 14 N2L &lt;= L(PH*NH) + H(PL*NH) + H(PH*NL)\n adc N2H, RZERO ;1 15 propagate carry to N2H \n ;calculate P = N2 * DL, note DH=0\n mul N2L, DL ;2 16\n movw P, PROD ;1 18\n ;mov PH, PRODH ;1 19\n mul N2H, DL ;2 20\n add PH, PRODL ;1 22\n rjmp idivu_16x16_adj_n ;2 23 36\n\nd1Heq:\n mov N2L, N1H ;1 25\n clr N2H ;1 1\n rjmp idivu_16x16_checkn ;2 2 27\n\nidivu_16x16:\n ;Check that DH is not zero\n tst DH ;1 0 0\n breq idivu_16x8 ;2 1\n\n;code for D &gt;= 256\n;idivu_16x16_dhne:\n clr RZERO ;1 2 *\n;Lookup Rx = min(256 / DH, 255)\n mov zl, DH ;1 3 *\n ldi zh, high(R1H_TBL*2) ;1 1\n lpm Rx, Z ;3 2\n\n ;N1 = (N? * Rx) &gt;&gt; 8\n mul Rx , NH ;2 5\n movw N1L,PRODL ;1 7\n ;mov N1H,PRODH ;1 8\n mul Rx , NL ;2 8\n add N1L, PRODH ;1 10\n adc N1H, RZERO ;1 11\n\n ;D1 = (D * Rx) &gt;&gt; 8\n mul Rx , DH ;2 12\n movw D1L,PRODL ;1 14\n ;mov D1H,PRODH ;1 15\n mul Rx , DL ;2 15\n add D1L, PRODH ;1 17\n adc D1H, RZERO ;1 18\n\n ;if D1H = 0 then use Rx = 256, otherwise use table\n ;tst D1H ;1 19\n brne d1Heq ;2 19 22\n\nidivu_16x16_dxhne:\n ;Lookup Rx = (2 ^ 16) \\ (256 + D1H)\n mov zl, D1L ;1 23 *\n ldi zh, high(R2_TBL*2) ;1 1\n lpm Rx, Z ;3 2\n ;N2 = (N1 * R2) &gt;&gt; 16\n mul Rx , N1H ;2 5\n mov PL , PRODL ;1 7\n mov N2L, PRODH ;1 8\n mul Rx , N1L ;2 9\n add PL , PRODH ;1 11\n adc N2L, RZERO ;1 12\n clr N2H ;1 13 36\n\nidivu_16x16_checkn:\n ;Check result (it may be off by +/- 1)\n ;P = N2 * D\n ;NOTE: N2 &lt;=255 so NxH = 0,\n ; also P &lt; 2^16 so we can discard upper byte of DH * NxL\n mul DL, N2L ;2 37 *\n movw PL, PRODL ;1 2\n ;mov PH, PRODH ;1 3\n mul DH, N2L ;2 3\n add PH, PRODL ;1 5\n ;brcc idivu_16x16_adj_n ;2 6 43\n brcs idivu_16x16_mofl ;2 6 43\n\n;Adjust result up or down by 1 if needed.\nidivu_16x16_adj_n:\n ;Add -P to N, with result in P\n ;mov N1L, NL ;1 44 *\n movw N1H, NH ;1\n sub N1L, PL ;1 1\n sbc N1H, PH ;1 2\n ;brsh idivu_16x16_pltn ;2 3 47\n brlo idivu_16x16_decn2 ;2 3 47\n\nidivu_16x16_pltn:\n ;test remainder to D \n cp N1L, DL ;1 49 *\n cpc N1H, DH ;1 1\n ;if remainder &lt; D then goto end\n brlo idivu_16x16_end ;2 2 51\n\n ;if remainder &gt;= D then increment quotient, reduce remainder\n subi N2L, 0xFF ;1 3\n sbci N2H, 0xFF ;1 4\n sub N1L, DL ;1 5\n sbc N1H, DH ;1 6 55\nidivu_16x16_end:\n ret ; 56 **\n\nidivu_16x16_decn2:\n ;if P &gt; N then decrement quotient, add to remainder\n subi N2L, 1 ;1 49\n sbci N2H, 0 ;1 1\n add N1L, DL ;1 2\n adc N1H, DH ;1 3\n ret ; 4 53\n\n\nidivu_16x16_mofl:\n ;if multiply overflowed then...\n ;decrement quotient\n ;calculate remainder as N - P + D\n subi N2L, 0x01 ;1 45\n sbci N2H, 0x00 ;1 1\n mov N1L, NL ;1 2\n mov N1H, NH ;1 3\n sub N1L, PL ;1 4\n sbc N1H, PH ;1 5\n add N1L, DL ;1 6\n adc N1H, DH ;1 7\n ret ;1 8 53\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-17T21:29:25.823", "Id": "502675", "Score": "0", "body": "Putting off a stab at decent naming in hopes of fully understanding the algorithm - don't hold your breath." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-18T07:25:48.380", "Id": "502701", "Score": "0", "body": "With the byte/register order changed, all 2-instruction *adjust quotient* sequences could be replaced by the respective word instruction, saving one word each, but no cycle." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-18T16:38:30.060", "Id": "502769", "Score": "0", "body": "I can adjust the naming a bit, but the issue is that I don't want to use more registers than necessary, so the same registers get used for different things at different parts of the algorithm." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-18T16:47:06.067", "Id": "502774", "Score": "0", "body": "The best way to understand the algorithm is to look at the \"ALGORITHM OVERVIEW\" part of the comments. Basically for a divisor that is 8 bits or less, look up the16-bit reciprocal from the table and multiply by that (pretty standard). For a divisor that is more than 8 bits we look up a pair of values R1*R2 whose product makes the correct reciprocal. This allows me to use two tables of 256 entries rather than one table of 65536 entries. R1 is based only on a lookup of the upper byte. R2 is based only on a lookup of the lower byte (after multiplying by R1)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-18T16:48:40.640", "Id": "502775", "Score": "0", "body": "The first value R1 is normalizes the divisor to a form that looks like 0b1_xxxx_xxxx. The second value R2 completes the division. The other parts of the code are just to correct for errors where the result can be off by +/- 1 count. The algorithm is my own original work, but is similar in concept to **Goldschmidt division**. It is not at all inspired by what GCC does, because GCCs division algorithm on this part is pretty slow (over 200 cycles)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-18T17:21:38.567", "Id": "502778", "Score": "0", "body": "(@user4574 didn't actually analyse \"the original `__udivmodhi4`\" until right now: getting 202 cycles +call/return overhead, worst case. Had done a variant computing result high bytes in one loop and low bytes in another - 176 cycles, about twice as long.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-19T13:28:37.243", "Id": "502881", "Score": "0", "body": "(`brne d1Heq` most likely needs to be `breq d1Heq` - with next edit.)" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-17T19:14:58.227", "Id": "254860", "ParentId": "254077", "Score": "3" } }, { "body": "<p>Here are the updates after adding RAM based tables and using MOVW where appropriate. The RAM based tables save a few clock cycles compared to reading flash based tables.</p>\n<p>The high/low positions of any multi-register arguments were swapped to facilitate use of MOVW, which saves a clock cycle each time its used compared to using two separate byte moves.</p>\n<p>The max run time is now 62 clock cycles.</p>\n<p>A preprocessor symbol (RAM_DIVIDE_TABLE) was added to select use of tables in RAM or in ROM.</p>\n<p>There is an init_math routine that gets called once at startup to copy the tables to RAM.</p>\n<p>I re-ran my exhaustive 16-hour test (on the actual chip) to make sure every one of the 2^32 combinations of inputs yielded the correct output when compared to a standard shift and subtract type divide routine. There were no failures.</p>\n<p>The tables now look like this...</p>\n<pre><code>#define RAM_DIVIDE_TABLE\n#ifdef RAM_DIVIDE_TABLE\n .dseg\n .align 256\n R1H_TBL: .byte 256\n R1L_TBL: .byte 256\n R2_TBL: .byte 256\n .cseg\ninit_math:\n;Copy ROM divide tables to RAM\n clr r1;counter\n ldi zl, low(R1H_TBL_ROM*2) ;1 \n ldi zh, high(R1H_TBL_ROM*2) ;1\n ldi yh, low(R1H_TBL)\n ldi yh, high(R1H_TBL)\ninit_math_loop_1:\n lpm r0, Z+ ;3\n st Y+, r0 ;2\n inc r1 ;1\n brne init_math_loop_1 ;2\ninit_math_loop_2:\n lpm r0, Z+ ;3\n st Y+, r0 ;2\n inc r1 ;1\n brne init_math_loop_2 ;2\ninit_math_loop_3:\n lpm r0, Z+ ;3\n st Y+, r0 ;2\n inc r1 ;1\n brne init_math_loop_3 ;2\n ret\n#else \n .cseg\n .align 256\n#endif\n;Recipricol table #1, high byte.\n;R1H_TBL[x] = min( high(2^16/x) / 256 , 255)\nR1H_TBL_ROM:\n.db 0xFF, 0xFF, 0x80, 0x55, 0x40, 0x33, 0x2A, 0x24, 0x20, 0x1C, 0x19, 0x17, 0x15, 0x13, 0x12, 0x11\n.db 0x10, 0x0F, 0x0E, 0x0D, 0x0C, 0x0C, 0x0B, 0x0B, 0x0A, 0x0A, 0x09, 0x09, 0x09, 0x08, 0x08, 0x08\n.db 0x08, 0x07, 0x07, 0x07, 0x07, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x05, 0x05, 0x05, 0x05, 0x05\n.db 0x05, 0x05, 0x05, 0x05, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04\n.db 0x04, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03\n.db 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02\n.db 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02\n.db 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02\n.db 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01\n.db 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01\n.db 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01\n.db 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01\n.db 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01\n.db 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01\n.db 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01\n.db 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01\n;Recipricol table #1, low byte.\n;R1L_TBL[x] = min( low(2^16/x) mod 256 , 255)\nR1L_TBL_ROM:\n.db 0xFF, 0xFF, 0x00, 0x55, 0x00, 0x33, 0xAA, 0x92, 0x00, 0x71, 0x99, 0x45, 0x55, 0xB1, 0x49, 0x11\n.db 0x00, 0x0F, 0x38, 0x79, 0xCC, 0x30, 0xA2, 0x21, 0xAA, 0x3D, 0xD8, 0x7B, 0x24, 0xD3, 0x88, 0x42\n.db 0x00, 0xC1, 0x87, 0x50, 0x1C, 0xEB, 0xBC, 0x90, 0x66, 0x3E, 0x18, 0xF4, 0xD1, 0xB0, 0x90, 0x72\n.db 0x55, 0x39, 0x1E, 0x05, 0xEC, 0xD4, 0xBD, 0xA7, 0x92, 0x7D, 0x69, 0x56, 0x44, 0x32, 0x21, 0x10\n.db 0x00, 0xF0, 0xE0, 0xD2, 0xC3, 0xB5, 0xA8, 0x9B, 0x8E, 0x81, 0x75, 0x69, 0x5E, 0x53, 0x48, 0x3D\n.db 0x33, 0x29, 0x1F, 0x15, 0x0C, 0x03, 0xFA, 0xF1, 0xE8, 0xE0, 0xD8, 0xD0, 0xC8, 0xC0, 0xB9, 0xB1\n.db 0xAA, 0xA3, 0x9C, 0x95, 0x8F, 0x88, 0x82, 0x7C, 0x76, 0x70, 0x6A, 0x64, 0x5E, 0x59, 0x53, 0x4E\n.db 0x49, 0x43, 0x3E, 0x39, 0x34, 0x30, 0x2B, 0x26, 0x22, 0x1D, 0x19, 0x14, 0x10, 0x0C, 0x08, 0x04\n.db 0x00, 0xFC, 0xF8, 0xF4, 0xF0, 0xEC, 0xE9, 0xE5, 0xE1, 0xDE, 0xDA, 0xD7, 0xD4, 0xD0, 0xCD, 0xCA\n.db 0xC7, 0xC3, 0xC0, 0xBD, 0xBA, 0xB7, 0xB4, 0xB2, 0xAF, 0xAC, 0xA9, 0xA6, 0xA4, 0xA1, 0x9E, 0x9C\n.db 0x99, 0x97, 0x94, 0x92, 0x8F, 0x8D, 0x8A, 0x88, 0x86, 0x83, 0x81, 0x7F, 0x7D, 0x7A, 0x78, 0x76\n.db 0x74, 0x72, 0x70, 0x6E, 0x6C, 0x6A, 0x68, 0x66, 0x64, 0x62, 0x60, 0x5E, 0x5C, 0x5A, 0x58, 0x57\n.db 0x55, 0x53, 0x51, 0x50, 0x4E, 0x4C, 0x4A, 0x49, 0x47, 0x46, 0x44, 0x42, 0x41, 0x3F, 0x3E, 0x3C\n.db 0x3B, 0x39, 0x38, 0x36, 0x35, 0x33, 0x32, 0x30, 0x2F, 0x2E, 0x2C, 0x2B, 0x29, 0x28, 0x27, 0x25\n.db 0x24, 0x23, 0x21, 0x20, 0x1F, 0x1E, 0x1C, 0x1B, 0x1A, 0x19, 0x18, 0x16, 0x15, 0x14, 0x13, 0x12\n.db 0x11, 0x0F, 0x0E, 0x0D, 0x0C, 0x0B, 0x0A, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01\n;Recipricol table #2\n;R2_TBL[x] = min( 2^16/(x+256), 255)\nR2_TBL_ROM:\n.db 0xFF, 0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8, 0xF7, 0xF6, 0xF5, 0xF4, 0xF3, 0xF2, 0xF1\n.db 0xF0, 0xF0, 0xEF, 0xEE, 0xED, 0xEC, 0xEB, 0xEA, 0xEA, 0xE9, 0xE8, 0xE7, 0xE6, 0xE5, 0xE5, 0xE4\n.db 0xE3, 0xE2, 0xE1, 0xE1, 0xE0, 0xDF, 0xDE, 0xDE, 0xDD, 0xDC, 0xDB, 0xDB, 0xDA, 0xD9, 0xD9, 0xD8\n.db 0xD7, 0xD6, 0xD6, 0xD5, 0xD4, 0xD4, 0xD3, 0xD2, 0xD2, 0xD1, 0xD0, 0xD0, 0xCF, 0xCE, 0xCE, 0xCD\n.db 0xCC, 0xCC, 0xCB, 0xCA, 0xCA, 0xC9, 0xC9, 0xC8, 0xC7, 0xC7, 0xC6, 0xC5, 0xC5, 0xC4, 0xC4, 0xC3\n.db 0xC3, 0xC2, 0xC1, 0xC1, 0xC0, 0xC0, 0xBF, 0xBF, 0xBE, 0xBD, 0xBD, 0xBC, 0xBC, 0xBB, 0xBB, 0xBA\n.db 0xBA, 0xB9, 0xB9, 0xB8, 0xB8, 0xB7, 0xB7, 0xB6, 0xB6, 0xB5, 0xB5, 0xB4, 0xB4, 0xB3, 0xB3, 0xB2\n.db 0xB2, 0xB1, 0xB1, 0xB0, 0xB0, 0xAF, 0xAF, 0xAE, 0xAE, 0xAD, 0xAD, 0xAC, 0xAC, 0xAC, 0xAB, 0xAB\n.db 0xAA, 0xAA, 0xA9, 0xA9, 0xA8, 0xA8, 0xA8, 0xA7, 0xA7, 0xA6, 0xA6, 0xA5, 0xA5, 0xA5, 0xA4, 0xA4\n.db 0xA3, 0xA3, 0xA3, 0xA2, 0xA2, 0xA1, 0xA1, 0xA1, 0xA0, 0xA0, 0x9F, 0x9F, 0x9F, 0x9E, 0x9E, 0x9D\n.db 0x9D, 0x9D, 0x9C, 0x9C, 0x9C, 0x9B, 0x9B, 0x9A, 0x9A, 0x9A, 0x99, 0x99, 0x99, 0x98, 0x98, 0x98\n.db 0x97, 0x97, 0x97, 0x96, 0x96, 0x95, 0x95, 0x95, 0x94, 0x94, 0x94, 0x93, 0x93, 0x93, 0x92, 0x92\n.db 0x92, 0x91, 0x91, 0x91, 0x90, 0x90, 0x90, 0x90, 0x8F, 0x8F, 0x8F, 0x8E, 0x8E, 0x8E, 0x8D, 0x8D\n.db 0x8D, 0x8C, 0x8C, 0x8C, 0x8C, 0x8B, 0x8B, 0x8B, 0x8A, 0x8A, 0x8A, 0x89, 0x89, 0x89, 0x89, 0x88\n.db 0x88, 0x88, 0x87, 0x87, 0x87, 0x87, 0x86, 0x86, 0x86, 0x86, 0x85, 0x85, 0x85, 0x84, 0x84, 0x84\n.db 0x84, 0x83, 0x83, 0x83, 0x83, 0x82, 0x82, 0x82, 0x82, 0x81, 0x81, 0x81, 0x81, 0x80, 0x80, 0x80\n</code></pre>\n<p>The divide routine looks like this...</p>\n<pre><code>;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n;ARGUMENTS: r16, r17, r18, r19\n; r17:r16 = N (numerator)\n; r19:r18 = D (divisor)\n;RETURNS: r20, r21\n; r21:r20 (quotient)\n; r23:r22 (remainder)\n;\n;DESCRIPTION: divides an unsigned 16 bit number N by unsigned 16 bit divisor D\n; Max run time is 62 clock cycles.\n;\n;ALGORITHM OVERVIEW\n;\n;RZERO = 0;\n;if(D &lt; 256){\n; N2 = (N * ((R1H_TBL[D] &lt;&lt; 8) + R1L_TBL[D])) &gt;&gt; 16;\n; P = N2 * D\n;}else{\n; D1 = (R1H_TBL[D] * D) &gt;&gt; 8\n; N1 = (R1H_TBL[D] * N) &gt;&gt; 8\n; if(D1 &lt; 256){\n; N2 = N1 &gt;&gt; 8;\n; }else{\n; N2 = N2 * R2_TBL[D1 &amp; 0xFF];\n; }\n; P = N2 * D;\n; if(P &gt; 65535){\n; N2 = N2 - 1 ;//Decrement quotient\n; N1 = N2 - P + D;//Calculate remainder\n; return;//return quotient in N2, remainder in N1\n; }\n;}\n;N1 = N - P;\n;if(P &gt; N){\n; N2 = N2 - 1;//decrease quotient\n; N1 = N1 + D;//increase reamainder\n; return;//return quotient in N2, remainder in N1\n;}\n;if(N1 &gt; D){\n; N2 = N2 + 1;\n; N1 = N1 - D;\n; return;//return quotient in N2, remainder in N1\n;}\n;\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n.def NL = r16 .def NH = r17 ;numerator\n.def DL = r18 .def DH = r19 ;divisor\n.def N2L = r20 .def N2H = r21 ;temp variables, becomes quotient.\n.def N1L = r22 .def N1H = r23 ;temp variables, becomes remainder.\n.def PRODL = r0 .def PRODH = r1 ;hardware multiply product\n.def PL = r2 .def PH = r3 ;product\n.def D1L = r4 .def D1H = r5\n.def RZERO = r6 ;zero value\n.def Rx = r7 \n\nidivu_16x16:\n clr RZERO ;1\n ;Check that DH is not zero\n tst DH ;1\n brne idivu_16x16_dhne ;2\n ;code for D &lt; 256 \nidivu_16x8:\n ;lookup low byte of recipricol into P.\n ;where P = min(2^16 / D,2^16-1)\n mov zl, DL ;1\n #ifdef RAM_DIVIDE_TABLE\n ldi zh, high(R1L_TBL) ;1 \n ld PL, Z ;2\n ldi zh, high(R1H_TBL) ;1\n ld PH, Z ;2\n #else\n ldi zh, high(R1L_TBL*2) ;1\n lpm PL, Z ;3\n ldi zh, high(R1H_TBL*2) ;1\n lpm PH, Z ;3\n #endif \n ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n ;calculate N2 = (P * N) &gt;&gt; 16\n ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n ; NH:NL\n ; X RH:RL\n ;------------------------------------------\n ; N2H | N2L | N1H | dropped\n ;----------+----------+----------+---------\n ; | | H(PL*NL) | L(PL*NL)\n ; | H(PL*NH) | L(PL*NH) |\n ; | H(PH*NL) | L(PH*NL) |\n ; H(PH*NH) | L(PH*NH) | |\n ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; \n \n mul NL , PL ;1 PL*NL\n mov N1H, PRODH ;1 N1H &lt;= H(PL*NL)\n mul NH , PH ;1 PH*NH\n movw N2L, PRODL\n mul NH , PL ;1 PL*NH\n add N1H, PRODL ;1 N1H &lt;= H(PL*NL) + L(PL*NH) \n adc N2L, PRODH ;1 N2L &lt;= L(PH*NH) + H(PL*NH)\n adc N2H, RZERO ;1 propagate carry to N2H \n mul NL , PH ;1 PH*NL\n add N1H, PRODL ;1 N1H &lt;= H(PL*NL) + L(PL*NH) + L(PH*NL)\n adc N2L, PRODH ;1 N2L &lt;= H(PH*NL) + L(PH*NH) + H(PL*NH)\n adc N2H, RZERO ;1 propagate carry to N2H \n ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n ;calculate P = N2 * DL ,note DH=0\n ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; \n mul N2L, DL ;1\n movw PL, PRODL ;1\n mul N2H, DL ;1\n add PH, PRODL ;1\n rjmp idivu_16x16_adj_n ;2\n ;code for D &gt;= 256\nidivu_16x16_dhne: \n ;Lookup Rx = min(256 / DH, 255) \n mov zl, DH ;1\n #ifdef RAM_DIVIDE_TABLE\n ldi zh, high(R1H_TBL) ;1\n ld Rx, Z ;2\n #else\n ldi zh, high(R1H_TBL*2) ;1\n lpm Rx, Z ;3\n #endif\n ;D1 = (D * Rx) &gt;&gt; 8 \n mul Rx , DH ;1\n movw D1L, PRODL ;1\n mul Rx , DL ;1\n add D1L, PRODH ;1\n adc D1H, RZERO ;1\n ;N1 = (D * Rx) &gt;&gt; 8 \n mul Rx , NH ;1\n movw N1L, PRODL ;1\n mul Rx , NL ;1\n add N1L, PRODH ;1\n adc N1H, RZERO ;1\n ;if D1H = 0 then use Rx = 256, otherwise use table \n tst D1H ;1\n brne idivu_16x16_dxhne ;2\n \n mov N2L, N1H ;1\n clr N2H ;1\n rjmp idivu_16x16_checkn;2\n\n idivu_16x16_dxhne:\n ;Lookup Rx = (2 ^ 16) \\ (256 + D1H)\n mov zl, D1L ;1\n #ifdef RAM_DIVIDE_TABLE\n ldi zh, high(R2_TBL) ;1\n ld Rx, Z ;2\n #else\n ldi zh, high(R2_TBL*2) ;1\n lpm Rx, Z ;3\n #endif\n ;N2 = (N1 * R2) &gt;&gt; 16\n mul Rx , N1H ;1\n mov PL , PRODL ;1\n mov N2L , PRODH ;1\n mul Rx , N1L ;1\n add PL , PRODH ;1\n adc N2L, RZERO ;1\n clr N2H ;1\n\n idivu_16x16_checkn:\n ;Check result (it may be off by +/- 1)\n ;P = N2 * D\n ;NOTE: N2 &lt;=255 so NxH = 0, also P &lt; 2^16 so we can discard upper byte of DH * NxL\n mul DL , N2L ;1\n movw PL, PRODL ;1\n mul DH , N2L ;1\n add PH , PRODL ;1 \n brcc idivu_16x16_adj_n ;2\n\n ;if multiply overflowed then...\n ;decrement quotient\n ;calculate remainder as N - P + D\n subi N2L, 0x01 ;1\n sbci N2H, 0x00 ;1\n movw N1L, NL ;1\n sub N1L, PL ;1\n sbc N1H, PH ;1\n add N1L, DL ;1\n adc N1H, DH ;1\n rjmp idivu_16x16_end ;2\n\n ;Adjust result up or down by 1 if needed.\n idivu_16x16_adj_n:\n ;Add -P to N, with result in P\n movw N1L, NL ;1\n sub N1L, PL ;1\n sbc N1H, PH ;1\n brsh idivu_16x16_pltn ;2\n\n idivu_16x16_decn2:\n ;if P &gt; N then decrement quotient, add to remainder\n subi N2L, 0x01 ;1\n sbci N2H, 0x00 ;1\n add N1L, DL ;1\n adc N1H, DH ;1\n rjmp idivu_16x16_end ;2\n\n idivu_16x16_pltn:\n ;test remainder to D \n cp N1L, DL ;1\n cpc N1H, DH ;1\n ;if remainder &lt; D then goto end\n brlo idivu_16x16_end ;2\n\n ;if remainder &gt;= D then increment quotient, reduce remainder\n subi N2L, 0xFF ;1\n sbci N2H, 0xFF ;1\n sub N1L, DL ;1\n sbc N1H, DH ;1\n idivu_16x16_end:\n ret\n .undef NH .undef NL \n .undef DH .undef DL \n .undef N2H .undef N2L \n .undef N1H .undef N1L \n .undef PRODL .undef PRODH\n .undef PH .undef PL \n .undef D1H .undef D1L \n .undef RZERO \n .undef Rx \n</code></pre>\n<p>One optimization that could have a big impact on the code run time would be to see if I can eliminate overflow error checking by rounding the table values up or down by one count. Right now some combinations of table values and inputs can result in overflow, and I need to check for that. I might try running a variant of this algorithm on a PC and find those cases and see if rounding the table value up or down by one count fixes the problem without breaking anything else.</p>\n<p>In any case I am not aware of any other 16-bit x 16-bit divide algorithms that will run on this processor in less than 62 cycles, so we did good so far.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-06-17T05:12:36.890", "Id": "263131", "ParentId": "254077", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T05:23:35.987", "Id": "254077", "Score": "6", "Tags": [ "performance", "integer", "assembly" ], "Title": "Fastest (in clock cycles) 16-bit x 16-bit unsigned integer division algorithm for ATMEGA1284?" }
254077
<p>I'm trying to build a wish list for my website. So I created a view that will</p> <ol> <li>render out the wish list and to</li> <li>add items to the wish list - using ajax</li> </ol> <p>Those two tasks are carried out by the same view. Here's how I did it,</p> <p>views.py</p> <pre><code>@login_required(login_url='/login') def wishlist(request): wishes = Wishlist.objects.filter(customer=request.user.customer).prefetch_related( Prefetch('product', queryset=Product.objects.prefetch_related( Prefetch( 'productimage_set', ProductImage.objects.filter(place='Main Product Image'), to_attr='main_image' ), ), to_attr='wished_dish' ), ) # delete wished dish if request.method == 'POST': dish_to_delete = request.POST.getlist('delete_items') print(dish_to_delete) Wishlist.objects.filter(pk__in=dish_to_delete).delete() # question is related to below statements if request.method == 'GET': try: dish_id = request.GET['dish_id'] dish = Product.objects.get(id=dish_id) wish, created = Wishlist.objects.get_or_create( customer=request.user.customer, product=dish ) if created: return HttpResponse('Dish &lt;b&gt;{}&lt;/b&gt; Added to wish list!'.format(dish.name)) else: return HttpResponse('Dish &lt;b&gt;{}&lt;/b&gt; is already in your wish list!'.format(dish.name)) except: pass context = { 'wishes': wishes, } return render(request, 'store/wishlist.html', context) </code></pre> <p>As you can see I've used a <code>try:... except: pass</code> block for <code>GET requests</code> to separate the <strong>adding</strong> functionality and <strong>viewing</strong> functionality.</p> <p>It works fine but is this the optimal way to achieve the intended goal?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-03T20:10:01.973", "Id": "501475", "Score": "0", "body": "Why don't you create two separate views? One to handle the `GET` requests and another one to handle the `POST` request? There's `require_http_methods ` in which you can specify what method you want your view to accept. Or even better, just use [CBVs](https://docs.djangoproject.com/en/3.1/topics/class-based-views/intro/)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-04T05:34:00.020", "Id": "501503", "Score": "0", "body": "@GrajdeanuAlex here I have one `POST` method and **two `GET` ** methods... the question is with two `GET` methods" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-04T07:10:50.050", "Id": "501505", "Score": "0", "body": "Well, each view can have its own url so that shouldn’t be a problem either :) You’d just have to point each url from `urls.py` to its corresponding view" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T09:12:29.637", "Id": "254082", "Score": "0", "Tags": [ "django" ], "Title": "How to configure view to carryout two operations from GET request Django" }
254082
<p>This is my first project I am attempting in Python, and my first time on Stack Exchange, so please be kind.</p> <p>The game uses a text file with lots of words. I was wondering how to improve the game by having different difficultly levels. E.g. easy for 1-4 letters, medium for 5-8 letters, hard for 9+ letters in the word. All the code in <code>print_graphics()</code> was pre-made, so I have to figure out a way to incorporate it into the code I was writing.</p> <p>I was also thinking it might look neater if it didn't keep printing new iterations of the hangman after each body part is added, but I'm not sure how I could do that without massively changing the text.</p> <p>I couldn't figure out how to attach <a href="https://colab.research.google.com/drive/1qDg_c-uiADs3aq6SZQ47ciDIwIZFJuvQ?usp=sharing" rel="nofollow noreferrer">the input file</a> so I've linked it instead.</p> <pre><code>import random from IPython.display import clear_output from termcolor import colored def print_graphics(wrong_guesses): # list of possible body parts body_parts = [' O |', ' | |',' /| |', ' /|\ |', ' / |', ' / \ |'] # how many lines to print lines = 4 if wrong_guesses != 0 else 5 # check number provided is usable if 0 &lt;= wrong_guesses &lt;= 6: print(' +-----+') # print top of frame print(' | |') # print the correct body parts for current state if wrong_guesses &gt; 0: if wrong_guesses &gt; 1: print(body_parts[0]) lines -= 1 if wrong_guesses &gt; 4: print(body_parts[3]) lines -= 1 print(body_parts[wrong_guesses-1]) for i in range(lines): print(' |') # print the lines print('==========') # print the floor with open(&quot;wordlist.txt&quot;) as file: words = file.read().split() word = random.choice(words) guessed_word = [] guessed_letters = [] max_guesses = 5 length_word = len(word) alphabet = &quot;abcdefghijklmnopqrstuvwxyz&quot; letter_storage = [] body_parts = [' O |', ' | |',' /| |', ' /|\ |', ' / |', ' / \ |'] def start(): print(&quot;\033[1;34m&quot;+&quot;Welcome to hangman! You have 6 tries to guess the correct word, enter a letter to get started&quot;, &quot;\033[0;30m&quot;) start() def intro(): for character in word: guessed_word.append(&quot;_&quot;) print(&quot;The word you are guessing has&quot;, length_word, &quot;characters&quot;) print_graphics(0) intro() def play(word): wrong_guesses = 0 while wrong_guesses &lt;6: guess = input(&quot;Guess a letter or word: &quot;) if guess in guessed_letters: print(&quot;\033[1;31m&quot;+&quot;Whoops! You have already guessed this letter. Don't worry, you still have&quot;, 6-wrong_guesses, &quot;guesses remaining&quot; &quot;\033[0;30m&quot;) if guess not in alphabet: print(&quot;\033[1;31m&quot;+&quot;Character invalid. Please enter a letter&quot;, &quot;\033[0;30m&quot;) elif guess in alphabet and guess not in guessed_letters: if guess in word: print(&quot;\033[1;3;32m&quot;+&quot;Well done&quot;, guess.upper(), &quot;is correct!&quot;, &quot;\033[0;30m&quot;) guessed_letters.append(guess) for i in range(0, length_word): if word[i] == guess: guessed_word[i] = guess print(guessed_word) if not &quot;_&quot; in guessed_word: print(&quot;\033[1;3;32m&quot;+&quot;Congratulations, you beat the Hangman!&quot;, &quot;\033[0;30m&quot;) break elif guess not in word: wrong_guesses += 1 print(print_graphics(wrong_guesses)) print(guessed_word) print(&quot;\033[1;31m&quot;+guess.upper(), &quot;is not correct. You have&quot;, 6-wrong_guesses, &quot;guesses left&quot;, &quot;\033[0;30m&quot;) guessed_letters.append(guess) if wrong_guesses == 6: print(&quot;\033[1;31m&quot;+&quot;Bad luck! You have been beaten by the Hangman. The word you were trying to guess was&quot;, word, &quot;\033[0;30m&quot;) play(word) print(&quot;\033[1;3;35m&quot;+&quot;Game over, thank you for playing :)&quot;) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T11:19:25.837", "Id": "501082", "Score": "4", "body": "On Code Review, we can offer advice on improving the existing code. Changes to the functionality (adding difficulty levels) are off-topic, so don't expect reviewers to add that for you!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T14:35:22.440", "Id": "501106", "Score": "1", "body": "I wasn't looking for anyone to do the code for me as I am trying to learn! I was simply hoping someone could review the code and suggest how to read the number of characters in the words in the file. so far I have: `def difficulty(word):\n print(\"Easy = word has 2-4 characters\\nMedium = word has 5-8 characters\\nHard = word has 9+ characters\")\n diff = input(\"Do you want easy, medium or hard?\")\n\n if diff is easy:\n len(word) >= 2 and <= 4\n if diff is medium:\n len(word) >= 5 and <= 8\n if diff is hard: \n len(word) >9\ndifficulty(word)` but there is nothing about the file" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T18:46:36.600", "Id": "501142", "Score": "1", "body": "Code review is not a site to ask for new features, we only review existing features and provide insight on how it might be improved." } ]
[ { "body": "<p>You write</p>\n<blockquote>\n<pre><code>from termcolor import colored\n</code></pre>\n</blockquote>\n<p>but then ignore that and write non-portable escape sequences directly in the strings:</p>\n<blockquote>\n<pre><code> print(&quot;\\033[1;34m&quot;+&quot;....&quot;, &quot;\\033[0;30m&quot;)\n</code></pre>\n</blockquote>\n<p>Doesn't that defeat the point of <code>termcolor</code>, which is supposed to adapt to the connected terminal?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T14:16:15.503", "Id": "501102", "Score": "0", "body": "Thanks for pointing that out, I tried to it that way originally but it wasn't working and I forgot to remove that module" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T11:22:56.377", "Id": "254089", "ParentId": "254087", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T11:05:06.110", "Id": "254087", "Score": "2", "Tags": [ "python", "beginner", "hangman" ], "Title": "Simple hangman game from beginner" }
254087
<p>The idea of a <em>prime sieve</em> is fascinating - but it has to be segmented to increase the locality of the code if you want it to be fast.</p> <p><strong>Walish's segmented_sieve.cpp</strong> (see below)showed me that it works - fast. It took me some time to understand how the segments are managed. Once my version was working, it was 5% faster than the .cpp. I was a bit disappointed - Walish's cpp seemed more elegant than super-fast.</p> <p>After switching from <code>int</code> to <code>unsigned</code> and <code>(r-1)/2</code> to <code>r/2</code>, my code is now almost <strong>twice as fast</strong>. This is my first Q: <strong>is this a special case?</strong> All the <code>r</code>'s are odd, but the compiler probably can't know. Anyway, I changed <em>all</em> to unsigned (except main() and argc.</p> <p>I need this index-to-value translation (<code>2*i+1</code>) (or viceversa) all over the place. I think the compactness of my segments shows here, in the inner loop, where the candidates are deleted:</p> <pre><code>segment[r/2] = 0; THIS VERSION sieve[j] = false; WALISH'S </code></pre> <p>This is my second guess: since memory usage is crucial here, I gain speed by leaving out (not just skipping) even numbers.</p> <p>Plus: My segments start without 2-13 multiples.</p> <p>Here my commented code:</p> <pre><code>/* Segmented Prime Sieve with pre-sieved pattern Segmentation tricks based on Kim Walish's segmented_sieve.cpp, and wikipedia */ /* Counts primes under 1G in 0.4s (2.3GHz i5) (above .cpp: 0.7s) */ #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;math.h&gt; #include &lt;string.h&gt; #include &lt;limits.h&gt; /* This &quot;inflates&quot; a preprime pattern like &quot;101&quot; to &quot;10.101101101.01&quot; (dot = new zero) */ unsigned grow_pat_by(unsigned p, char *pattern, unsigned patsize) { unsigned i; /* Multiply by p */ for (i = 1; i &lt; p; i++) memcpy(pattern + i*patsize, pattern, patsize); /* Sieve out every p */ for (i = p/2; i &lt; p*patsize; i += p) pattern[i] = 0; return p * patsize; } /* Classic/simple self sieve (odds only), with lower limit for pre-sieved sieves */ void sieve_above(char *sieve, unsigned start, unsigned max) { unsigned p, pp; for (p = start; p &lt;= sqrt(max); p += 2) if (sieve[p/2]) for (pp = p*p; pp &lt;= max; pp += 2*p) sieve[pp/2] = 0; } /* Translates an index in preprimes[] into number in primes[]. Return value could be used to know size/number */ unsigned * gather_primes(char *preprimes, unsigned min, unsigned max, unsigned *primes) { unsigned i; for (i = min/2; i &lt;= max/2; i++) if (preprimes[i]) *primes++ = 2*i+1; return primes; } /* A new segment activates higher primes[] into new runners[] * In a segment[], the numbers are indexed: num=2*i+1 and i=(num-1)/2, but the &quot;-1&quot; does not matter (odd integers) * Unsigned makes it about 20% faster */ void do_segment(unsigned segm_start, unsigned segm_end, unsigned char *segment, unsigned *primes, unsigned *runners, unsigned *irun) { /* Do new prime squares fit in this segment? */ unsigned p; while((p = primes[*irun]) &gt; 0 &amp;&amp; p*p &lt;= segm_end) runners[(*irun)++] = p*p - segm_start; /* Run each runner[i] through and past the end of this segment */ unsigned segm_size = segm_end - segm_start; unsigned i, r; for(i = 0; (r = runners[i]) &gt; 0; i++) { while (r &lt; segm_size) { segment[r/2] = 0; r += 2*primes[i]; } /* Reset for next segment: same pattern, different offsets */ runners[i] = r - segm_size; } } /* Initialize pattern[], preprimes[], primes[] and allocate runners[]. Prepare segment[] and call do_segment() */ void segmented_sieve(const unsigned MAX) { const unsigned SQR = sqrt(MAX); unsigned i; /* pattern[] is used for preprimes[] and segment[] * &quot;101&quot; is &quot;1-(3)-5&quot; i.e. &quot;3&quot; is sieved out. Even numbers are left out. Relation: number value is 2*index + 1 */ static char pattern[3*5*7*11*13 * 2] = {1, 0, 1}; unsigned patsize = 3; /* grow (multiply and sieve) until patsize reaches magical ~30KB*/ patsize = grow_pat_by( 5, pattern, patsize); patsize = grow_pat_by( 7, pattern, patsize); patsize = grow_pat_by(11, pattern, patsize); patsize = grow_pat_by(13, pattern, patsize); /* preprimes[] shall deliver primes up to ~65K = sqrt(4G) = 32KB phys. (no odds) */ /* So copy pattern twice (phys. patsize: 15015)*/ char *preprimes = malloc(256*256/2); memcpy(preprimes, pattern, patsize); memcpy(preprimes+patsize, pattern, patsize); /* Primes 2-13 can be skipped */ const unsigned FIRST = 17; sieve_above(preprimes, FIRST, SQR); /* Fill primes[] up to SQR, followed by zeroes. 7000 is enough to hold primes up to 65500 */ unsigned *primes = calloc(7000, sizeof*primes); gather_primes(preprimes, FIRST, SQR, primes); free(preprimes); /* Optimize: stretch pattern[] by 2 (without sieving) to make segments a bit bigger (30KB) */ memcpy(pattern + patsize, pattern, patsize); patsize *= 2; /* The segment is a working copy of pattern[] that should fit into lowest cache * 30030 is a primorial, but the &quot;x2&quot; only slips back in because of &quot;stretching&quot; of the odds-only 15015-pattern * Without stretching, or with a second one, speed goes down (locality/cache) */ static unsigned char segment[3*5*7*11*13 * 2]; /* runners[i] has primes[i]'s current offset for do_segment() */ unsigned *runners = calloc(7000, sizeof*runners); /* Segments advance in numbers by 2xpatsize (no odds in pattern) * First one has &quot;1&quot; set, but lacks &quot;2,3,5,7,11,13&quot;, thus &quot;count&quot; starts at 5. Last segment is simply truncated to MAX */ unsigned count = 5; unsigned irun = 0; unsigned segm_start, segm_end; for (segm_start = 0; segm_start &lt; MAX; segm_start += 2*patsize) { /* Fresh pattern for segment */ memcpy(segment, pattern, patsize); segm_end = segm_start + 2*patsize; if (segm_end &gt; MAX) segm_end = MAX; do_segment(segm_start, segm_end, segment, primes, runners, &amp;irun); /* Count (and possibly print by numbers) the sieved segment */ for(i=0; 2*i+1 &lt; segm_end - segm_start; i++) { count += segment[i]; //if (segment[i]) //printf(&quot;%d\n&quot;, segm_start + 2*i+1); } } printf(&quot;PI of %d (prime count): %d\n&quot;, MAX, count); return ; } int main(int argc, char** argv) { if (argc &lt; 2) { printf(&quot;No limit given\n&quot;); return 1; } unsigned MAX = atoi(argv[1]); if (MAX &lt; 100) printf(&quot;Choose a number above 100, and below 4G. Not: %d\n&quot;, MAX); segmented_sieve(MAX); return 0; } </code></pre> <p>Here Walish's c++ version; check out his <code>for(;...&lt;limit; ...++)</code> loops:</p> <blockquote> <pre><code>&lt;kim.walisch@gmail.com&gt; /// @brief This is a simple implementation of the segmented sieve of /// Eratosthenes with a few optimizations. It generates the /// primes below 10^9 in 0.8 seconds (single-threaded) on an /// Intel Core i7-6700 3.4 GHz CPU. /// @license Public domain. #include &lt;iostream&gt; #include &lt;algorithm&gt; #include &lt;cmath&gt; #include &lt;vector&gt; #include &lt;cstdlib&gt; #include &lt;stdint.h&gt; /// Set your CPU's L1 data cache size (in bytes) here const int64_t L1D_CACHE_SIZE = 32768; /// Generate primes using the segmented sieve of Eratosthenes. /// This algorithm uses O(n log log n) operations and O(sqrt(n)) space. /// @param limit Sieve primes &lt;= limit. /// void segmented_sieve(int64_t limit) { int64_t sqrt = (int64_t) std::sqrt(limit); int64_t segment_size = std::max(sqrt, L1D_CACHE_SIZE); int64_t count = (limit &lt; 2) ? 0 : 1; // we sieve primes &gt;= 3 int64_t i = 3; int64_t n = 3; int64_t s = 3; std::vector&lt;char&gt; sieve(segment_size); std::vector&lt;char&gt; is_prime(sqrt + 1, true); std::vector&lt;int64_t&gt; primes; std::vector&lt;int64_t&gt; multiples; for (int64_t low = 0; low &lt;= limit; low += segment_size) { std::fill(sieve.begin(), sieve.end(), true); // current segment = [low, high] int64_t high = low + segment_size - 1; high = std::min(high, limit); // generate sieving primes using simple sieve of Eratosthenes for (; i * i &lt;= high; i += 2) if (is_prime[i]) for (int64_t j = i * i; j &lt;= sqrt; j += i) is_prime[j] = false; // initialize sieving primes for segmented sieve for (; s * s &lt;= high; s += 2) { if (is_prime[s]) { primes.push_back(s); multiples.push_back(s * s - low); } } // sieve the current segment for (std::size_t i = 0; i &lt; primes.size(); i++) { int64_t j = multiples[i]; for (int64_t k = primes[i] * 2; j &lt; segment_size; j += k) sieve[j] = false; multiples[i] = j - segment_size; } for (; n &lt;= high; n += 2) if (sieve[n - low]) // n is a prime count++; } std::cout &lt;&lt; count &lt;&lt; &quot; primes found.&quot; &lt;&lt; std::endl; } /// Usage: ./segmented_sieve n /// @param n Sieve the primes up to n. /// int main(int argc, char** argv) { if (argc &gt;= 2) segmented_sieve(std::atoll(argv[1])); else segmented_sieve(1000000000); return 0; } </code></pre> </blockquote> <p>I can confirm his 0.8s on a i5-8xxx, with <code>-O2</code>. My version needs <code>-O3</code> (and <code>-lm</code>).</p> <p>Can I further improve speed and/or design?</p> <p>If it gets even faster, I will have to change from <code>unsigned</code> to <code>long</code> for <code>MAX</code>. Highest MAX I tested was 3 billion.</p> <p>So many mathematical stuff to consider - and then the compiler needs help to turn 17 into 8: <code>10001</code> -&gt; <code>1000</code></p> <p><em>(oh, so it is just a right shift)</em></p> <hr /> <p>Update: the variables can stay <code>int</code> with <code>segment[r&gt;&gt;1] = 0</code> (430ms) instead of <code>[r/2]</code> (500ms) or even <code>[(r-1)/2]</code> (550ms).</p> <p>With <code>unsigned r</code>, both<code>r&gt;&gt;1</code>and <code>r/2</code> are 410ms. Good enough.</p> <p>The version above (everybody unsigned, [r/2]) is still fastest: 400-405ms. (I saw 0.400 several times, but never 0.399 (for 1 billion))</p> <p>Normally these kind of optimizations are frowned upon - but this inner loop over a compact odds-only-segment is not &quot;normal&quot;.</p> <hr /> <p><code>unsigned *primes</code> makes the difference: 402ms. So 90% of above <code>unsigned</code>s are not necessary.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T14:42:03.303", "Id": "501107", "Score": "1", "body": "A *high* possibility of what is going on here is just that you aren't actually sorting it - The C compiler discards any variables you aren't using, so all you're going to end up doing is incrementing `count` that many times. If you want to actually see how long it takes to sort lists like that, you need to put it on `-O0`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T14:54:20.020", "Id": "501108", "Score": "1", "body": "You either need to do that, or in some way force the compiler to not optimize specific variables/operations away." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T18:23:55.853", "Id": "501134", "Score": "1", "body": "What's the point of your updates?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T18:24:30.483", "Id": "501136", "Score": "0", "body": "\"...you aren't actually sorting it\" --- true, these prime numbers come already sorted. Haven't checked it, though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T18:26:40.373", "Id": "501137", "Score": "0", "body": "@Mast To help you answer my questions. What is the point of your comment?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T18:53:43.187", "Id": "501144", "Score": "1", "body": "Just keeping an eye out. Please keep in mind not to change too much after receiving answers. It's explained [here](//codereview.meta.stackexchange.com/a/1765)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T19:47:08.827", "Id": "501147", "Score": "0", "body": "I did not change the code. It's still full of `unsigned` with no `r>>1`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T07:51:52.643", "Id": "501173", "Score": "0", "body": "I know, but you asked the point of the comment. Had the edit be a problem we'd have rolled it back already." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T00:49:40.737", "Id": "501306", "Score": "0", "body": "Sivix - What I mean by \"you aren't actually sorting it\" is that you aren't even processing anything. Most likely, you're just incrementing a variable X amount of times, and printing a constant for the number of primes found." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-09T06:54:58.317", "Id": "507284", "Score": "0", "body": "Kim's code is meant to illustrate the idea, and IMO does that, is simple, easy to read, and surprisingly fast. However it is just an illustration, missing a lot of optimizations. See the slightly out of date [SoE benchmarks](http://ntheory.org/sieves/benchmarks.html) for some timing and code for lots of others. It looks like the code you're starting with is the \"Walisch byte segment\" version, which is the slowest listed (again because it is wonderfully illustrating the concept, rather than using convoluted optimizations)." } ]
[ { "body": "<p>Argument checking - we test for missing argument; we should also fail if there are extra arguments, rather than just ignoring them. <code>atoi()</code> is a poor function to convert strings to integers - in particular, it accepts negative values, it produces a signed value, and it doesn't reject out-of-range values or trailing garbage. Consider <code>strtoul()</code> or <code>strtoull()</code> instead.</p>\n<p>And after checking, we should both print an error message (to <code>stderr</code>, not <code>stdout</code>) and exit with a failure status.</p>\n<p>Handling of signed and unsigned is poor; my first test gave strange output:</p>\n<pre><code>./254091 3000000000\nPI of -1294967296 (prime count): 144449537\n</code></pre>\n<p>That's so easily avoided, it looks like you've taken no care over correctness.</p>\n<p>As you've hinted in the description, you might need to change the type used for arithmetic. But it's scattered all over the code, giving you many places to change. A better start would be to add a typedef which can be easily changed to work with wider types.</p>\n<hr />\n<p>Here's a better <code>main()</code>:</p>\n<pre><code>int main(int argc, char** argv)\n{\n if (argc != 2) {\n fprintf(stderr, &quot;Usage: %s LIMIT\\n&quot;, argv[0]);\n return EXIT_FAILURE;\n }\n char *end;\n unsigned long max = strtoul(argv[1], &amp;end, 0);\n if (*end || max &lt; 100 || max &gt; UINT_MAX) {\n fprintf(stderr, &quot;Choose a number above 100, and below %u. Not: %s\\n&quot;,\n UINT_MAX, argv[1]);\n return EXIT_FAILURE;\n }\n segmented_sieve((unsigned int)max);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T15:07:17.100", "Id": "501109", "Score": "0", "body": "You should probably mention the fact that they were using optimization and that optimization probably prevented half of the code from actually getting used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T16:46:47.330", "Id": "501121", "Score": "0", "body": "Yes, there was a `%d` in `printf()`. Should be: `%u` . This arg test is a last minute feature, mostly to avoid a result of 6 for an input of 10 without a warning. Thank you for the better main()!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T15:00:51.420", "Id": "254093", "ParentId": "254091", "Score": "1" } }, { "body": "<p>Some concerns about preforming the function right, not just fast.</p>\n<p><strong>Slow and ...</strong></p>\n<p><code>sqrt(max)</code>, potentially, is evaluated for each loop. This give the classic approach an unfair performance assessment.</p>\n<pre><code>for (p = start; p &lt;= sqrt(max); p += 2)\n</code></pre>\n<p>Some compilers will &quot;know&quot; <code>sqrt(max)</code> returns the same result each time and so only call <code>sqrt(max)</code> once. This is not something that should be relied on to happen.</p>\n<pre><code>// Alternative\nunsigned end = sqrt(max);\nfor (p = start; p &lt;= end; p += 2)\n</code></pre>\n<p><strong>... and maybe wrong</strong></p>\n<p><code>sqrt()</code> is not specified to return the <em>exact</em> square root for a perfect square. With a quality implementation, this issue is rare. Still, better to round up than integer truncate.</p>\n<pre><code>unsigned end = ceil(sqrt(max));\n</code></pre>\n<p>What can be a problem is when conversion of <code>max</code> (perhaps it is a 64-bit integer type) incurs rounding converting to <code>double</code>, imprecision within the <code>sqrt()</code> calculation and truncation when converting the result from <code>double</code> to the integer type.</p>\n<p>Code could use your own <code>isqrt()</code> to avoid that - or use <code>for (p = start; p &lt;= max/p; p += 2)</code>. See next.</p>\n<p><strong>Code risks overflow</strong></p>\n<p><code>i * i &lt;= high</code> risks overflow when <code>high</code> is near the max value of the type. Consider <code>i*i &lt;= high</code> can be true, but <code>(i+2)*(i+2)</code> on the next iteration overflows.</p>\n<p>An alterative that does not overflow when <code>i &gt; 0</code>:</p>\n<pre><code>for (; i &lt;= high/i; i += 2)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T23:30:48.523", "Id": "254160", "ParentId": "254091", "Score": "0" } }, { "body": "<p>Here the main difference is visible, when the left over sieve-indices are counted:</p>\n<p><strong>n += 2</strong></p>\n<pre><code> for (; n &lt;= high; n += 2)\n if (sieve[n - low]) // n is a prime\n count++;\n</code></pre>\n<p><strong>i++</strong></p>\n<pre><code> for(i=0; 2*i+1 &lt; segm_end - segm_start; i++) {\n count += segment[i];\n</code></pre>\n<p>My segments are double-density, because they are odds-only. Yes, <code>+= 2</code> skips evens easily, but wastes cache space.</p>\n<p>The <code>2*i+1</code> is not complicated enough to loose that advantage. a problem. Making this <code>i</code> unsigned does not help.</p>\n<p>Here a version with only the necessary <code>unsigned</code> and a comment on that <code>[r&gt;&gt;1]</code>.</p>\n<pre><code>void do_segment(int segm_start, int segm_end, // real numbers\n char *segment, unsigned *primes, int *runners, // arrays\n int *irun) { // activated primes/runners\n\n unsigned p;\n while((p = primes[*irun]) &gt; 0 &amp;&amp; p*p &lt;= segm_end)\n runners[(*irun)++] = p*p - segm_start;\n\n unsigned segm_size = segm_end - segm_start;\n unsigned i, r;\n for(i = 0; (r = runners[i]) &gt; 0; i++) {\n while (r &lt; segm_size) {\n segment[r&gt;&gt;1] = 0; // or [r/2] but not [(r-1)/2] (1% slower) \n r += 2 * primes[i];\n }\n runners[i] = r - segm_size;\n }\n}\n\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T23:43:21.310", "Id": "254161", "ParentId": "254091", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T14:15:30.273", "Id": "254091", "Score": "2", "Tags": [ "c", "primes" ], "Title": "Why is this Segmented Prime Sieve so fast?" }
254091
<p>The program takes 2 decimals as input and an operator (+, -, *, /, ^) so far. Any suggestions to make this code cleaner or shorter?</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Calculator { class Program { static void Main(string[] args) { Console.Write(&quot;Enter a number: &quot;); Decimal n1 = Convert.ToDecimal(Console.ReadLine()); Console.Write(&quot;Enter an operator: &quot;); string op = Console.ReadLine(); Console.Write(&quot;Enter a number: &quot;); Decimal n2 = Convert.ToDecimal(Console.ReadLine()); if (op == &quot;+&quot;) { Console.WriteLine(Sum(n1, n2)); Console.ReadLine(); } else if (op == &quot;-&quot;) { Console.WriteLine(Dif(n1, n2)); Console.ReadLine(); } else if (op == &quot;*&quot;) { Console.WriteLine(Prod(n1, n2)); Console.ReadLine(); } else if (op == &quot;/&quot;) { Console.WriteLine(Div(n1, n2)); Console.ReadLine(); } else if (op == &quot;^&quot;) { Console.WriteLine(Pow(n1, n2)); Console.ReadLine(); } else { Console.WriteLine(&quot;Invalid Operator! Only '+', '-', '*', '/', or '^' allowed.&quot;); Console.ReadLine(); } } static Decimal Sum(Decimal n1, Decimal n2) { Decimal sum; sum = n1 + n2; return sum; } static Decimal Dif(Decimal n1, Decimal n2) { Decimal dif; dif = n1 - n2; return dif; } static Decimal Prod(Decimal n1, Decimal n2) { Decimal prod; prod = n1 * n2; return prod; } static Decimal Div(Decimal n1, Decimal n2) { Decimal div; div = n1 / n2; return div; } static Decimal Pow(Decimal n1, Decimal n2) { Decimal pow; pow = (decimal)Math.Pow((double)n1, (double)n2); return pow; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T17:57:29.803", "Id": "501127", "Score": "4", "body": "Welcome to Code Review! I rolled back your last edit. After getting an answer you are not allowed to change your code anymore. This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). See the section _What should I not do?_ on [_What should I do when someone answers my question?_](https://codereview.stackexchange.com/help/someone-answers) for more information" } ]
[ { "body": "<p><strong>Remove the useless functions</strong></p>\n<p>There's already a sum function. It's called <code>+</code></p>\n<p>Instead of</p>\n<pre><code>Console.WriteLine(Sum(n1, n2));\n</code></pre>\n<p>and</p>\n<pre><code>static Decimal Sum(Decimal n1, Decimal n2)\n{\n Decimal sum;\n sum = n1 + n2;\n return sum;\n}\n</code></pre>\n<p>just write</p>\n<pre><code>Console.WriteLine(n1 + n2);\n</code></pre>\n<p>... and the exact same thing applies to all the other calculation functions you wrote.</p>\n<p><strong>The same thing in every branch of an <code>if</code></strong></p>\n<p>No matter what <code>op</code> is, you do <code>Console.ReadLine();</code>. So delete it from each <code>if</code>/<code>else if</code>/<code>else</code> and just add it after the end of the <code>if</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T16:46:28.230", "Id": "254097", "ParentId": "254095", "Score": "3" } }, { "body": "<p>In addition to what the accepted answer states:</p>\n<p>You can convert all if statements to a single switch statement.\nI would also parse the input more defensively, i.e. use <code>decimal.TryParse()</code> and break execution early if the input is invalid.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T13:27:11.730", "Id": "254173", "ParentId": "254095", "Score": "0" } } ]
{ "AcceptedAnswerId": "254097", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T16:20:42.010", "Id": "254095", "Score": "5", "Tags": [ "c#", "calculator" ], "Title": "Simple 5 operator calculator in C#" }
254095
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/253556/231235">A recursive_transform Template Function Implementation with std::invocable concept in C++</a>, <a href="https://codereview.stackexchange.com/q/253665/231235">A recursive_transform Template Function Implementation with std::invocable Concept and Execution Policy in C++</a>, <a href="https://codereview.stackexchange.com/q/251132/231235">A recursive_transform for std::vector with various return type</a> and <a href="https://stackoverflow.com/q/65503495/6667035">A recursive_invoke_result_t template structure</a>. Thanks to <a href="https://codereview.stackexchange.com/a/253634/231235">indi's answer</a>. After checked the mentioned &quot;completely different way&quot;, I am trying to implement another version <code>recursive_transform</code> function here. A recursive version <a href="https://en.cppreference.com/w/cpp/types/result_of" rel="nofollow noreferrer"><code>std::invoke_result_t</code></a> is used instead of <a href="https://en.cppreference.com/w/cpp/iterator/indirect_result_t" rel="nofollow noreferrer"><code>std::indirect_result_t</code></a> to determine the type of output structure. Therefore, the structure</p> <pre><code>using TransformedValueType = decltype(recursive_transform(*input.begin(), f)); Container&lt;TransformedValueType&gt; output; </code></pre> <p>turns into <code>recursive_invoke_result_t&lt;F, Range&gt; output{};</code>.</p> <p>The implementation of <code>recursive_invoke_result_t</code> template structure is from <a href="https://stackoverflow.com/a/65504127/6667035">HTNW's answer</a>.</p> <p><strong>The experimental implementation</strong></p> <p>The experimental implementation is as below.</p> <pre><code>// recursive_invoke_result_t implementation // from https://stackoverflow.com/a/65504127/6667035 template&lt;typename, typename&gt; struct recursive_invoke_result { }; template&lt;typename T, std::invocable&lt;T&gt; F&gt; struct recursive_invoke_result&lt;F, T&gt; { using type = std::invoke_result_t&lt;F, T&gt;; }; template&lt;typename F, template&lt;typename...&gt; typename Container, typename... Ts&gt; requires ( !std::invocable&lt;F, Container&lt;Ts...&gt;&gt; &amp;&amp; std::ranges::input_range&lt;Container&lt;Ts...&gt;&gt; &amp;&amp; requires { typename recursive_invoke_result&lt;F, std::ranges::range_value_t&lt;Container&lt;Ts...&gt;&gt;&gt;::type; }) struct recursive_invoke_result&lt;F, Container&lt;Ts...&gt;&gt; { using type = Container&lt;typename recursive_invoke_result&lt;F, std::ranges::range_value_t&lt;Container&lt;Ts...&gt;&gt;&gt;::type&gt;; }; template&lt;typename F, typename T&gt; using recursive_invoke_result_t = typename recursive_invoke_result&lt;F, T&gt;::type; template &lt;std::ranges::range Range&gt; constexpr auto get_output_iterator(Range&amp; output) { return std::inserter(output, std::ranges::end(output)); } template &lt;class T, std::invocable&lt;T&gt; F&gt; constexpr auto recursive_transform(const T&amp; input, const F&amp; f) { return f(input); } template &lt; std::ranges::input_range Range, class F&gt; requires (!std::invocable&lt;F, Range&gt;) constexpr auto recursive_transform(const Range&amp; input, const F&amp; f) { recursive_invoke_result_t&lt;F, Range&gt; output{}; auto out = get_output_iterator(output); std::ranges::transform( input.cbegin(), input.cend(), out, [&amp;f](auto&amp;&amp; element) { return recursive_transform(element, f); } ); return output; } </code></pre> <p><strong>Test cases</strong></p> <p>Considering <a href="https://codereview.stackexchange.com/a/253853/231235">G. Sliepen's answer</a>, the <code>std::vector&lt;std::string&gt;</code> test cases is added.</p> <pre><code>// non-nested input test, lambda function applied on input directly int test_number = 3; std::cout &lt;&lt; recursive_transform(test_number, [](int element) { return element + 1; }) &lt;&lt; std::endl; // nested input test, lambda function applied on input directly std::vector&lt;int&gt; test_vector = { 1, 2, 3 }; std::cout &lt;&lt; recursive_transform(test_vector, [](std::vector&lt;int&gt; element) { auto output = element; output.push_back(4); return output; }).size() &lt;&lt; std::endl; // std::vector&lt;int&gt; -&gt; std::vector&lt;std::string&gt; 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;std::vector&lt;int&gt; -&gt; std::vector&lt;std::string&gt;: &quot; + recursive_transform_result.at(0) &lt;&lt; std::endl; // recursive_transform_result.at(0) is a std::string // std::vector&lt;string&gt; -&gt; std::vector&lt;int&gt; std::cout &lt;&lt; &quot;std::vector&lt;string&gt; -&gt; std::vector&lt;int&gt;: &quot; &lt;&lt; recursive_transform( recursive_transform_result, [](std::string x) { return std::atoi(x.c_str()); }).at(0) + 1 &lt;&lt; std::endl; // std::string element to int // std::vector&lt;std::vector&lt;int&gt;&gt; -&gt; std::vector&lt;std::vector&lt;std::string&gt;&gt; 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 // std::deque&lt;int&gt; -&gt; std::deque&lt;std::string&gt; std::deque&lt;int&gt; test_deque; test_deque.push_back(1); test_deque.push_back(1); test_deque.push_back(1); auto recursive_transform_result3 = recursive_transform( test_deque, [](int x)-&gt;std::string { return std::to_string(x); }); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result3.at(0) &lt;&lt; std::endl; // std::deque&lt;std::deque&lt;int&gt;&gt; -&gt; std::deque&lt;std::deque&lt;std::string&gt;&gt; std::deque&lt;decltype(test_deque)&gt; test_deque2; test_deque2.push_back(test_deque); test_deque2.push_back(test_deque); test_deque2.push_back(test_deque); auto recursive_transform_result4 = recursive_transform( test_deque2, [](int x)-&gt;std::string { return std::to_string(x); }); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result4.at(0).at(0) &lt;&lt; std::endl; // std::list&lt;int&gt; -&gt; std::list&lt;std::string&gt; std::list&lt;int&gt; test_list = { 1, 2, 3, 4 }; auto recursive_transform_result7 = recursive_transform( test_list, [](int x)-&gt;std::string { return std::to_string(x); }); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result7.front() &lt;&lt; std::endl; // std::list&lt;std::list&lt;int&gt;&gt; -&gt; std::list&lt;std::list&lt;std::string&gt;&gt; std::list&lt;std::list&lt;int&gt;&gt; test_list2 = { test_list, test_list, test_list, test_list }; auto recursive_transform_result8 = recursive_transform( test_list2, [](int x)-&gt;std::string { return std::to_string(x); }); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result8.front().front() &lt;&lt; std::endl; </code></pre> <p><a href="https://godbolt.org/z/xanzxs" rel="nofollow noreferrer">A Godbolt link is here.</a></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/253556/231235">A recursive_transform Template Function Implementation with std::invocable concept in C++</a>,</p> <p><a href="https://codereview.stackexchange.com/q/253665/231235">A recursive_transform Template Function Implementation with std::invocable Concept and Execution Policy in C++</a>,</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://stackoverflow.com/q/65503495/6667035">A recursive_invoke_result_t template structure</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <p>I am trying to implement another version <code>recursive_transform</code> function with <code>recursive_invoke_result_t</code> and <code>std::ranges::transform</code> here.</p> </li> <li><p>Why a new review is being asked for?</p> <p>A recursive version <a href="https://en.cppreference.com/w/cpp/types/result_of" rel="nofollow noreferrer"><code>std::invoke_result_t</code></a> is used instead of something like <code>something_something_recursively_indirect_result_t</code> because I am not sure how to use <a href="https://en.cppreference.com/w/cpp/iterator/indirect_result_t" rel="nofollow noreferrer"><code>std::indirect_result_t</code></a> correctly. If the idea of using <code>std::indirect_result_t</code> is still better, please let me know. On the other hand, if there is any good example of <code>std::indirect_result_t</code> usage available, please also tell me.</p> </li> </ul>
[]
[ { "body": "<p>Just some minor things:</p>\n<h1>Use <code>std::ranges::begin()</code>, <code>end()</code> and <code>size()</code></h1>\n<p>Make sure you consistently use the free-standing functions, instead of using member functions <code>.begin()</code>, <code>.end()</code>, their <code>const</code> counterparts, and <code>.size()</code>.</p>\n<h1>Remove <code>get_output_iterator()</code></h1>\n<p>This looks like a utility function, but it is used only once, and it kind of hides what it is actually calling. Instead of using this function, I would call <code>std::inserter()</code> directly where needed:</p>\n<pre><code>... recursive_transform(const Range&amp; input, const F&amp; f)\n{\n recursive_invoke_result_t&lt;F, Range&gt; output{};\n std::ranges::transform(\n std::ranges::begin(input),\n std::ranges::end(input),\n std::inserter(output, std::ranges::end(output)),\n [&amp;f](auto&amp;&amp; element) { return recursive_transform(element, f); }\n );\n return output;\n}\n</code></pre>\n<h1>Make use of automatic type deduction</h1>\n<p>In your test cases, I see several opportunities where you can use automatic type deduction to save yourself some typing. In particular, most STL containers can deduce their type from the constructor, and the lambda's you pass to <code>recursive_transform()</code> also don't need an explicit return type. For example, you could write:</p>\n<pre><code>std::vector test_vector2 = {\n test_vector, test_vector, test_vector\n};\n\nauto recursive_transform_result2 = recursive_transform(\n test_vector2,\n [](int x) { return std::to_string(x); }\n);\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T00:03:45.390", "Id": "254115", "ParentId": "254096", "Score": "2" } } ]
{ "AcceptedAnswerId": "254115", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T16:45:06.293", "Id": "254096", "Score": "1", "Tags": [ "c++", "recursion", "lambda", "c++20" ], "Title": "A recursive_transform Template Function Implementation with recursive_invoke_result_t and std::ranges::transform in C++" }
254096
<p>The question is: To select 2 numbers out of n positive integer inputs (order matters), where the number that is placed anywhere before the second must be greater than the second by a given number m. Count the total number of selections.</p> <p>An example answer would be, given the inputs 5 1 3 2 4 and m is 0, the total number of selections is 5 (51,53,52,54,32)</p> <p>Another example answer would be, given the inputs 6 5 4 3 2 1 and m is 2, the total number of selections is 6 (63,62,61,52,51,41)</p> <p>How do I improve my double for-loop method in terms of time?</p> <pre><code>using namespace std; int main() { int n, m, i, j, m = 0, sum = 0; cin &gt;&gt; n &gt;&gt; m; int *a=new int[n]; for (i = 0; i &lt; n; i++) { scanf(&quot;%d&quot;, &amp;a[i]); } for(i=0;i&lt;n-1;i++) { if (a[i] - m &lt;= 0) continue; int temp=a[i]-m; for(j=i+1;j&lt;n;j++) if(a[j]&lt;temp) sum++; } cout&lt;&lt;sum&lt;&lt;endl; return 0; } <span class="math-container">`</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T17:56:10.900", "Id": "501126", "Score": "0", "body": "Think of counting inversions. The approach is the same, with a slight modification." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T18:25:27.267", "Id": "501201", "Score": "0", "body": "The results of your second example seems to be missing 64, 53, 42 and 31" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T14:44:28.750", "Id": "501346", "Score": "0", "body": "No, it has to be strictly greater than 2." } ]
[ { "body": "<p>Thanks to vnp's comment about counting inversions! This link should be fully sufficient to optimize your code with a modified merge sort scheme:</p>\n<p><a href=\"https://towardsdatascience.com/basic-algorithms-counting-inversions-71aaa579a2c0\" rel=\"nofollow noreferrer\">https://towardsdatascience.com/basic-algorithms-counting-inversions-71aaa579a2c0</a></p>\n<p>As far as I can see, the only thing you'll have to modify is this line</p>\n<pre><code>if array[i] &gt; array[j]\n</code></pre>\n<p>with your desired delta value m.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-16T09:43:16.793", "Id": "254789", "ParentId": "254099", "Score": "0" } }, { "body": "<blockquote>\n<pre><code>using namespace std;\n</code></pre>\n</blockquote>\n<p>Don't do this. We have namespaces for a reason, you know. And we seem to be missing the necessary Standard Library headers <code>&lt;iostream&gt;</code> and <code>&lt;cstdio&gt;</code>.</p>\n<blockquote>\n<pre><code> int n, m, i, j, m = 0, sum = 0;\n</code></pre>\n</blockquote>\n<p>These variable names tell us nothing about what they are used for. Please use more expressive names.</p>\n<blockquote>\n<pre><code> cin &gt;&gt; n &gt;&gt; m;\n</code></pre>\n</blockquote>\n<p>When reading from a stream such as <code>std::cin</code>, it's vital to check that the conversion was successful before using the values. That could be as simple as</p>\n<pre><code>if (!cin) {\n return EXIT_FAILURE;\n}\n</code></pre>\n<blockquote>\n<pre><code> int *a=new int[n];\n</code></pre>\n</blockquote>\n<p>Prefer a standard container (e.g. <code>std::vector</code>).</p>\n<blockquote>\n<pre><code> for (i = 0; i &lt; n; i++) {\n</code></pre>\n</blockquote>\n<p>If we had a <code>std::vector</code>, we could have avoided hand-coding this loop:</p>\n<pre><code>auto a = std::vector{};\na.reserve(n);\nstd::copy_n(std::istream_iterator&lt;int&gt;(std::cin), n, a.begin());\n</code></pre>\n<blockquote>\n<pre><code> scanf(&quot;%d&quot;, &amp;a[i]);\n</code></pre>\n</blockquote>\n<p>Why are we mixing C++ streams and C stdio? It's better to use just one (preferably the streams). Again, we're missing the test whether the conversion was successful.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-16T10:45:41.027", "Id": "254792", "ParentId": "254099", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T17:30:24.257", "Id": "254099", "Score": "2", "Tags": [ "c++", "complexity" ], "Title": "Optimize nested loops for counting the total number of selections" }
254099
<p>My goal was to have a single page display bulk amounts of media without the need to load new pages. I also wanted it to be able to load fast, so the generator uses a JavaScript array to display one item at a time. The user can move through the array backwards and forwards with the use of two buttons.</p> <p>Images, video and audio can be added as strings in the following ways:</p> <ul> <li><code>'&lt;video controls source src=&quot;FILE.mp4&quot; type=&quot;video/mp4&quot;&gt;&lt;/video&gt;',</code></li> <li><code>'&lt;img src=&quot;FILE.png&quot;&gt;',</code></li> <li><code>'&lt;audio controls source src=&quot;FILE.mp3&quot; type=&quot;audio/mpeg&quot;&gt;&lt;/audio&gt;',</code></li> </ul> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const array = [ '', '&lt;p&gt;Text\&lt;br&gt;Hello I am text&lt;/p&gt;', '&lt;video controls source src="FILE.mp4" type="video/mp4"&gt;&lt;/video&gt;', '&lt;img src="FILE.png"&gt;', '&lt;audio controls source src="FILE.mp3" type="audio/mpeg"&gt;&lt;/audio&gt;', ]; //variables const arrayLength = array.length; var For = -1; function backForth(ev) { if(ev.target.className == "buttonS") { const output = document.querySelector('output'); let increment = (ev.target.textContent == "Back" ? -1 : 1); For = (For + increment + arrayLength) % arrayLength; output.innerHTML = array[For]; document.getElementById('counter').innerHTML = For + '&amp;nbsp;/&amp;nbsp;' + (arrayLength - 1); }} document.addEventListener('click', backForth); backForth({target:{className: "buttonS"}});</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;body&gt; &lt;output&gt;&lt;/output&gt; &lt;div&gt; &lt;button class="buttonS"&gt;Back&lt;/button&gt; &lt;b&gt;&lt;span id="counter"&gt;&lt;/span&gt;&lt;/b&gt; &lt;button class="buttonS"&gt;Forth&lt;/button&gt; &lt;/div&gt; &lt;/body&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<p>The overall approach looks fine. Some suggestions:</p>\n<p><strong>Delegated click logic</strong> The current <code>backForth</code> being used both as a click listener and on the initial load feels a bit clunky since you have to pass in <code>{target:{className: &quot;buttonS&quot;}}</code>. Consider making a separate function that you pass an index to increment (either 1 or -1), and call that inside <code>backForth</code>, and call it with <code>(1)</code> initially.</p>\n<p><strong>Don't move buttons</strong> User interfaces are slightly friendlier when buttons stay in the same place - when they don't move based on the content size. Consider either moving the buttons above the output, or giving the output a fixed (or high minimum) height.</p>\n<p><strong><code>For</code> variable name</strong> is really weird - it's very close to <code>for</code>, which is a reserved word, and regardless doesn't really indicate what the variable contains very well. Consider naming it something like <code>displayedMediaIndex</code>.</p>\n<p><strong>Variable initializers</strong> - you use <code>var</code>, <code>let</code>, and <code>const</code>:</p>\n<ul>\n<li>If you're going to write in ES6+ (which you are, and you should), always use <code>const</code> or <code>let</code> to declare variables. <code>var</code> has a few gotchas (such as an unintuitive function scope rather than block scope, and of automatically assigning itself to properties of the global object when on the top level.) See ESLint rule <a href=\"https://eslint.org/docs/rules/no-var\" rel=\"nofollow noreferrer\"><code>no-var</code></a>.</li>\n<li>When deciding between <code>const</code> and <code>let</code>, <a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">use <code>const</code> whenever possible</a>, since it indicates that the variable won't be reassigned, which improves readability when a reader of the code can understand that at a glance.</li>\n</ul>\n<p><strong>Prefer strict equality</strong> over sloppy equality, since sloppy equality operators have some very strange type coercion rules that a reader of the code should not have to have memorized to be entirely confident of the logic your code is implementing.</p>\n<p>This is how I'd do it:</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 medias = [\n '',\n '&lt;p&gt;Text\\&lt;br&gt;Hello I am text&lt;/p&gt;',\n '&lt;video controls source src=\"FILE.mp4\" type=\"video/mp4\"&gt;&lt;/video&gt;',\n '&lt;img src=\"FILE.png\"&gt;',\n '&lt;audio controls source src=\"FILE.mp3\" type=\"audio/mpeg\"&gt;&lt;/audio&gt;',\n];\nconst mediasLength = medias.length;\nlet displayedMediaIndex = -1;\nconst output = document.querySelector('output');\nconst paginator = document.querySelector('.paginator');\nconst changeMedia = (indexChange) =&gt; {\n displayedMediaIndex = (displayedMediaIndex + indexChange + mediasLength) % mediasLength;\n output.innerHTML = medias[displayedMediaIndex];\n paginator.textContent = displayedMediaIndex + ' / ' + (mediasLength - 1);\n};\ndocument.addEventListener('click', (event) =&gt; {\n if (event.target.className == 'buttonS') {\n changeMedia(event.target.textContent === \"Back\" ? -1 : 1);\n }\n});\nchangeMedia(1);</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div&gt;\n &lt;button class=\"buttonS\"&gt;Back&lt;/button&gt;\n &lt;b&gt;&lt;span class=\"paginator\"&gt;&lt;/span&gt;&lt;/b&gt;\n &lt;button class=\"buttonS\"&gt;Forth&lt;/button&gt;\n&lt;/div&gt;\n&lt;output&gt;&lt;/output&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T18:43:14.840", "Id": "501288", "Score": "0", "body": "Your snippet is incomplete, \"ReferenceError: ev is not defined\"" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T20:07:44.403", "Id": "254102", "ParentId": "254100", "Score": "0" } }, { "body": "<h2>Code and style</h2>\n<ul>\n<li><p>Odd name to use as a variable <code>For</code> you have been forced to capitalize it which is not in line with JS naming conventions. ES6 lets you use keywords as property names, but I would not encourage using them even if you use capitals to avoid syntax errors. Maybe <code>next</code> would be more appropriate.</p>\n</li>\n<li><p>I have not seen collapsed closing blocks in a long time. I was once into them as they could save considerable space. However in the long run they make code much harder to read, and worse, modifying code in collapsed closing blocks becomes a guessing game to the point of defining them pure evil.</p>\n</li>\n<li><p>I would normally argue against inserting HTML via markup (setting <code>innerHTML</code>) but in this case to use the DOM would add needless complexity where not needed.</p>\n</li>\n<li><p>For <code>counter.innerHTML</code> use counter.textContent and you don't have to use the ' / '</p>\n</li>\n<li><p>Comments (lack or whim) are what some programming teachers used as an excuses to mark down/up assignments. Comments are generally useless, and at worse dangerous. The comment <code>// variables</code> comes under the heading useless.</p>\n</li>\n<li><p>Query the DOM once rather than many times inside code.</p>\n</li>\n<li><p>Use strict equality <code>===</code>, its faster (not that it matters in this case). Using strict equality is just a good habit when coding JS, a real pain if you are switching between C like languages. In this case there is no ambiguity so this is just to let you know that JS has two types of equality and inequality <code>==</code>, <code>!=</code> and <code>===</code>, <code>!==</code>.</p>\n</li>\n<li><p>Avoid code noise, <code>(ev.target.textContent == &quot;Back&quot; ? -1 : 1);</code> does not need the <code>()</code></p>\n</li>\n<li><p>Spaces after <code>if</code>. eg <code>if(</code> becomes <code>if (</code> same with <code>for</code>, <code>while</code>, <code>else</code>, etc.</p>\n</li>\n<li><p>Adding data to the element's <a href=\"https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes\" rel=\"nofollow noreferrer\">dataset</a> can simplify some of the work of determining an action for a click. See rewrite</p>\n</li>\n<li><p>Break up the function &quot;backForth&quot; into two roles &quot;event listener&quot; and &quot;media navigator&quot; See rewrite.</p>\n</li>\n<li><p>Protect your codes state, wrap it in a function. See rewrite.</p>\n</li>\n</ul>\n<h2>UI</h2>\n<ul>\n<li><p>There is nothing worse than a button that is intended to be clicked repeatedly that moves and needs to be hunted down to click again. Fix its position or move it to some location that does not make it move when the content changes.</p>\n</li>\n<li><p>Consider using the button elements title to provide additional information.</p>\n</li>\n</ul>\n<h2>Rewrite</h2>\n<p>Rewrite addresses most of the points above and adds some. It is as an example only.</p>\n<p>There is no right or wrong when coding, you will develop a style as you learn and gain experience.</p>\n<p>You will likely tend towards the language's conventions or even discover a better style.</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>;(()=&gt;{\n const query = (qStr, el = document) =&gt; el.querySelector(qStr);\n const content = (HTML, title) =&gt; ({HTML, title});\n const options = [\n content('', \"Empty selection\"),\n content('&lt;p&gt;Text\\&lt;br&gt;Hello I am text&lt;/p&gt;', 'Some text'),\n content('&lt;video controls source src=\"FILE.mp4\" type=\"video/mp4\"&gt;&lt;/video&gt;', 'Video FILE.mp4'),\n content('&lt;img src=\"FILE.png\"&gt;', 'Image FILE.png'),\n content('&lt;audio controls source src=\"FILE.mp3\" type=\"audio/mpeg\"&gt;&lt;/audio&gt;', 'Audio file.mp3'),\n ];\n \n document.addEventListener(\"click\", clickEvent);\n\n const output = query(\"output\");\n const counter = query(\"#counter\");\n const back = query(\"#backBtn\");\n const forward = query(\"#forwardBtn\");\n const length = options.length;\n var current = 0;\n backForth(0);\n\n function backForth(step) {\n current = (current + step + length) % length;\n output.innerHTML = options[current].HTML;\n counter.textContent = current + ' / ' + (options.length - 1);\n back.title = \"Prev \" + options[(current + length - 1) % length].title;\n forward.title = \"Next \" + options[(current + 1) % length].title;\n }\n\n function clickEvent(e) {\n if (e.target.className === \"buttonS\") { backForth(Number(e.target.dataset.step)) }\n } \n})();</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;button class=\"buttonS\" id=\"backBtn\" data-step=\"-1\"&gt;Back&lt;/button&gt;\n&lt;b&gt;&lt;span id=\"counter\"&gt;&lt;/span&gt;&lt;/b&gt;\n&lt;button class=\"buttonS\" id=\"forwardBtn\" data-step=\"1\"&gt;Forth&lt;/button&gt;&lt;br&gt;\n&lt;output&gt;&lt;/output&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-12-30T21:49:01.527", "Id": "254108", "ParentId": "254100", "Score": "0" } } ]
{ "AcceptedAnswerId": "254102", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T17:41:33.120", "Id": "254100", "Score": "1", "Tags": [ "javascript", "html", "image", "audio", "video" ], "Title": "A Simple Media Generator with Directional Control" }
254100
<p>I try to use <code>unittest</code> for conference class, but I am not sure that I have considered all condition or more complex tests should be added?</p> <p><strong>conference.py</strong></p> <pre><code>from datetime import timedelta, datetime class Conference: def __init__(self): self.inputs ='input.txt' self.outputs = 'output.txt' self.talks = self.proposals_extract() self.Track = 1 def proposals_extract(self): talks = {} f = open(self.inputs) try: while True: line = f.readline() duration = ''.join(filter(lambda i: i.isdigit(), line)) if duration: talks[line] = duration elif (not duration) and line: print('for proposal {} no duration has been detected'.format(line)) break if not line: break except FileNotFoundError as e: raise f.close() return talks def delete_content(self, pfile): pfile.seek(0) pfile.truncate() def format_time(self, hours): return (datetime.min + hours).strftime('%I:%M %p') def plan(self, start, end, Output): start = timedelta(hours=start) end = timedelta(hours=end) while start &lt; end and self.talks: item = self.talks.popitem() duration = item[1] proposal = item[0] print(self.format_time(start), ' ', proposal) Output.write('{} {} '.format(self.format_time(start), proposal)) start += timedelta(minutes=int(duration)) start = self.format_time(hours=start) return start def print_plan(self): O = open('output.txt', 'a') self.delete_content(O) lunch = self.format_time(timedelta(hours=12)) while (self.talks): print('Track {}\n'.format(self.Track)) O.write('Track {}\n'.format(self.Track)) end_morning_session = self.plan(9, 12, O) print('{} {} '.format(lunch, ' Lunch\n')) O.write('{} {} '.format(lunch, ' Lunch\n')) end_afternoon_session =self.plan(13, 17, O) print('{} {}'.format(end_afternoon_session, 'Networking Event\n')) O.write('{} {}'.format(end_afternoon_session, 'Networking Event\n')) self.Track += 1 O.close() if __name__ == '__main__': P = Conference() P.print_plan() </code></pre> <p><strong>TestConference.py</strong></p> <pre><code>import unittest import conference as c from datetime import timedelta, datetime import io from unittest.mock import mock_open, patch from mock_open.mocks import MockOpen, FileLikeMock import os try: # pylint: disable=no-name-in-module from unittest.mock import patch, call, NonCallableMock, DEFAULT except ImportError: from mock import patch, call, NonCallableMock, DEFAULT class TestConference(unittest.TestCase): @classmethod def setUpClass(cls): print('setupClass') @classmethod def tearDownClass(cls): print('tearDownClass') def setUp(self): print('setUp') f = open('input.txt') self.lines={line.strip('') for line in f} f.close() def test_proposals_extract(self): &quot;&quot;&quot;Check effects of reading from an empty file.&quot;&quot;&quot; myclass_instace = c.Conference() handle = open(myclass_instace.inputs, 'r') self.assertFalse(handle.closed) self.assertEqual('input.txt', handle.name) self.assertEqual('r', handle.mode) self.assertEqual(0, handle.tell()) text = handle.read() self.assertNotEqual(0, handle.tell()) self.assertNotEqual('', text) handle.close() self.assertTrue(handle.closed) talks = myclass_instace.proposals_extract() self.assertEqual(len(self.lines), len(talks)) &quot;&quot;&quot;Check calls made when `open` is used as a context manager.&quot;&quot;&quot; with open(myclass_instace.inputs, 'r') as handle: self.assertFalse(handle.closed) self.assertEqual(myclass_instace.inputs, handle.name) self.assertEqual('r', handle.mode) self.assertEqual(0, handle.tell()) def test_format_time(self): myclass_instace = c.Conference() time = myclass_instace.format_time(timedelta(hours=9)) self.assertEqual(time,'09:00 AM') def test_plan(self): O = open('output.txt', 'a') myclass_instace = c.Conference() end_session = myclass_instace.plan(9, 10, O) self.assertEqual(end_session,'10:00 AM') end_session = myclass_instace.plan(16, 17, O) self.assertEqual(end_session,'05:00 PM') O.close() def test_print_plan(self): myclass_instace = c.Conference() myclass_instace.print_plan() self.assertTrue(os.path.isfile(myclass_instace.outputs)) self.assertFalse(myclass_instace.talks) if __name__ == '__main__': unittest.main() </code></pre>
[]
[ { "body": "<h2>Parametric files</h2>\n<p>It would be trivially easy to have <code>Conference</code> accept filenames as parameters to its constructor, and will make this more usable.</p>\n<h2>Variable names</h2>\n<p><code>Track</code> should be lower-case. <code>O</code> is a poor choice of variable name for a list of reasons:</p>\n<ul>\n<li>It should be lowercase</li>\n<li>It looks the same as a zero</li>\n<li>Generally speaking, single-letter variable names are mystifying, and it's only by luck that I understand it to mean &quot;output&quot;</li>\n</ul>\n<p><code>P</code> should similarly be called <code>plan</code>.</p>\n<h2>Context management</h2>\n<p>Avoid <code>open</code>ing <code>f</code> and <code>O</code> and <code>close</code>ing them separately; put this in a <code>with</code> instead. Delete your <code>FileNotFoundError</code> block; it does nothing useful.</p>\n<h2>Line iteration</h2>\n<p>Replace</p>\n<pre><code> while True:\n line = f.readline()\n if not line:\n break \n</code></pre>\n<p>with</p>\n<pre><code>for line in f:\n</code></pre>\n<h2>Unpacking</h2>\n<p>Try replacing</p>\n<pre><code> duration = item[1]\n proposal = item[0]\n</code></pre>\n<p>with</p>\n<pre><code>proposal, duration = item\n</code></pre>\n<p>assuming that there are only two items in this sequence.</p>\n<h2>Spelling</h2>\n<p><code>instace</code> = <code>instance</code>.</p>\n<h2>Tests</h2>\n<p>This entire block:</p>\n<pre><code> myclass_instace = c.Conference()\n handle = open(myclass_instace.inputs, 'r')\n self.assertFalse(handle.closed)\n self.assertEqual('input.txt', handle.name)\n self.assertEqual('r', handle.mode)\n self.assertEqual(0, handle.tell())\n text = handle.read()\n self.assertNotEqual(0, handle.tell())\n self.assertNotEqual('', text)\n handle.close()\n self.assertTrue(handle.closed)\n\n &quot;&quot;&quot;Check calls made when `open` is used as a context manager.&quot;&quot;&quot;\n with open(myclass_instace.inputs, 'r') as handle:\n self.assertFalse(handle.closed)\n self.assertEqual(myclass_instace.inputs, handle.name)\n self.assertEqual('r', handle.mode)\n self.assertEqual(0, handle.tell())\n</code></pre>\n<p>is not useful and should be deleted. You're basically testing that file IO in Python works, and spoiler alert: it does. The only valuable part of this test is when you call <code>proposals_extract</code> and validate its return value against known-good data.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T22:01:52.333", "Id": "254110", "ParentId": "254101", "Score": "8" } } ]
{ "AcceptedAnswerId": "254110", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T19:21:41.617", "Id": "254101", "Score": "5", "Tags": [ "python", "python-3.x", "unit-testing" ], "Title": "Writing unit testing for conference management class" }
254101
<p>I just finished a small assignment and I would like to get some feedback about the implementation here. Basically, it was all about distributing items (&quot;talks&quot; in this case) throughout the day based on the time constraints (their duration). For instance, a given place have different &quot;tracks&quot; each of which has a <em>morning</em> (9AM - 12PM) and <em>afternoon</em> (1PM - 5PM) session.</p> <blockquote> <p>The input data is a file with this structure: <code>Talk Name XYmin</code> (where <code>XY</code> are positive numbers).</p> </blockquote> <p>This is what I came up with (I know it's a little bit silly but I guess it works for the most part):</p> <pre class="lang-java prettyprint-override"><code>public final class Conference { private static final long MORNING_SPAN = 180; // 09:00 AM - 12:00PM private static final long AFTERNOON_SPAN = 240; // 01:00 PM - 05:00 PM private final List&lt;Talk&gt; talks; private final List&lt;Track&gt; tracks; private final long numberOfTracks; public Conference(final List&lt;Talk&gt; talks) { final var duration = talks.stream().mapToLong(Talk::duration).sum(); final var daySpan = MORNING_SPAN + AFTERNOON_SPAN; this.talks = talks; numberOfTracks = duration / daySpan + (duration % daySpan == 0L ? 0L : 1L); tracks = new LinkedList&lt;&gt;(); } public List&lt;Track&gt; getTracks() { return tracks; } public void displaySchedule() { if (tracks.isEmpty()) { makeSchedule(); } // More System.out.println statements for the required output } private void makeSchedule() { // ...this one is the deal! for (int i = 0; i &lt; numberOfTracks; i++) { final var morning = new LinkedList&lt;Talk&gt;(); final var afternoon = new LinkedList&lt;Talk&gt;(); var morningSpan = MORNING_SPAN; var afternoonSpan = AFTERNOON_SPAN; final var iterator = talks.iterator(); while (iterator.hasNext()) { final var talk = iterator.next(); if (talk.duration() &lt;= morningSpan) { morning.add(talk); morningSpan -= talk.duration(); iterator.remove(); } else if (talk.duration() &lt;= afternoonSpan) { afternoon.add(talk); afternoonSpan -= talk.duration(); iterator.remove(); } } tracks.add(new Track(morning, afternoon)); } } } </code></pre> <pre class="lang-java prettyprint-override"><code>public final class Talk { public final String title; public final String duration; public Talk(final String title, final String duration) { this.title = title; this.duration = duration; } public long duration() { if (&quot;lightning&quot;.equalsIgnoreCase(duration)) { return Constant.LIGHTNING; } // Basically this returns the duration for the talk (as long)...that's it return Long.parseLong(Constant.NON_NUMBERS.matcher(duration).replaceAll(&quot;&quot;)); } } </code></pre> <pre class="lang-java prettyprint-override"><code>public final class Track { private final List&lt;Talk&gt; morning; private final List&lt;Talk&gt; afternoon; public Track(final List&lt;Talk&gt; morning, final List&lt;Talk&gt; afternoon) { this.morning = morning; this.afternoon = afternoon; } // Some more stuff here to display the required output } </code></pre> <p>The real deal here is <code>Conference::makeSchedule</code> — that's where I would like to know if there is a better, more efficient way to approach this solution...probably using different data structures, etc. Thanks in advance!</p>
[]
[ { "body": "<p>Nice implementation, it's well structured and easy to understand. Few general suggestions:</p>\n<ul>\n<li><strong><code>int</code> instead of <code>long</code></strong>: the constants <code>MORNING_SPAN</code> and <code>AFTERNOON_SPAN</code> contain minutes in a day, using an <code>int</code> is enough.</li>\n<li><strong>Input validation</strong>: the talk duration needs to be validated. If the talk duration is greater than <code>MORNING_SPAN</code> or <code>AFTERNOON_SPAN</code> it won't be included in any track. If it's negative it will also lead to issues. In the <code>Conference</code> class ensure that the list <code>talks</code> is not empty.</li>\n<li><strong>Creating the schedule</strong>: I see that the schedule is created (lazily) in the <code>displaySchedule</code> method of <code>Conference</code>. I think that creating the schedule is an important action, it can be the responsibility of another class, like <code>ScheduleMaker</code>. Then, the list of tracks can be added to <code>Conference</code> in the constructor.</li>\n<li><strong><code>Talk</code> interface</strong>: <code>talk.duration</code> returns a string like &quot;30min&quot;, while <code>talk.duration()</code> returns <code>30</code> as a <code>long</code>. I find it a bit confusing. If you need both, consider creating two different variables and two getters. Otherwise, parse the duration in the constructor and use only the <code>long</code> value.</li>\n</ul>\n<h2>Bin packing problem</h2>\n<p>Let's consider this example:</p>\n<pre><code>morning_span = 2m (2 minutes)\nafternoon_span = 1m\ndaily_span = morning_span + afternoon_span = 3m\n\ntalk1 = 2m\ntalk2 = 2m\ntalk3 = 2m\ntotal_talks_duration = 6m\n</code></pre>\n<p>Calling <code>conference.makeSchedule()</code> will result in:</p>\n<pre><code>numberOfTracks = total_talks_duration / daily_span = 6 / 3 = 2\n\nSchedule:\nTrack1 = talk1 (morning)\nTrack2 = talk2 (morning)\ntalk3 ??\n</code></pre>\n<p>As you can see the current <code>makeSchedule</code> will create two tracks, but <code>talk3</code> won't be included.</p>\n<p>This bug can be fixed by running the other loop till all the talks are placed:</p>\n<pre><code>private void makeSchedule() {\n while (talks.size() &gt; 0) {\n // Create a new track\n // Add in the track as many talks as possible\n // Remove talks added to the current track\n }\n}\n</code></pre>\n<p>Now all talks will be placed in the tracks, however, there are cases where the algorithm will create more tracks than needed. This is considered a <a href=\"https://en.wikipedia.org/wiki/Bin_packing_problem#CITEREFMartelloToth1990\" rel=\"nofollow noreferrer\">Bin packing problem</a>. Basically, fit the talks in the minimum number of tracks. Interestingly, my university professor developed an <a href=\"https://en.wikipedia.org/wiki/Bin_packing_problem#Exact_algorithm\" rel=\"nofollow noreferrer\">exact algorithm</a> for this problem (<a href=\"http://www.or.deis.unibo.it/kp/Chapter8.pdf\" rel=\"nofollow noreferrer\">pdf</a>). I'll leave it to you for additional study.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T14:53:31.347", "Id": "501189", "Score": "1", "body": "That's great feedback. I didn't know about the `Bin packing problem`! Let me try to incorporate those suggestions — this time just for myself, but it's always nice to make it better!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T09:48:50.727", "Id": "254124", "ParentId": "254103", "Score": "2" } } ]
{ "AcceptedAnswerId": "254124", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T20:33:15.770", "Id": "254103", "Score": "2", "Tags": [ "java", "performance", "algorithm" ], "Title": "Distribute items based on the time duration" }
254103
<p>Today I am working on refactoring and documenting some ancient Delphi code. In that language, which is derived from Pascal, there are three forms of comments:</p> <pre class="lang-delphi prettyprint-override"><code>(* This is the original Pascal style comment, which is never used in my files *) { this is TurboPascal-style comment which I want to remove } // This is a Delphi-style comment which I want to remove </code></pre> <p>As noted in this small sample, I want to strip out the last two styles of comments. The first kind of comment is never used in the code files I'm using, so there is no special processing done if they are encountered. I decided to do this using a <code>std::streambuf</code>. The code and some sample input is below. I'm interested in any comments for improvement.</p> <h2>commentfilterbuf.h</h2> <pre class="lang-cpp prettyprint-override"><code>#ifndef COMMENTFILTER_H #define COMMENTFILTER_H #include &lt;streambuf&gt; class commentfilterbuf : public std::streambuf { std::streambuf* sbuf; char buffer = EOF; public: commentfilterbuf(std::streambuf* sbuf); int underflow(); }; #endif // COMMENTFILTER_H </code></pre> <h2>commentfilterbuf.cpp</h2> <pre><code>#include &quot;commentfilterbuf.h&quot; commentfilterbuf::commentfilterbuf(std::streambuf* sbuf) : sbuf(sbuf) { } int commentfilterbuf::underflow() { traits_type::int_type i; // skip comments which are delimited with { and } for (i = sbuf-&gt;sbumpc(); i == '{'; i = sbuf-&gt;sbumpc()) { while ((i = sbuf-&gt;sbumpc()) != '}'); } if (traits_type::not_eof(i)) { // check for single line comments like this one if (i == sbuf-&gt;sgetc() &amp;&amp; i == '/') { while ((i = sbuf-&gt;sbumpc()) != '\n'); } buffer = traits_type::to_char_type(i); setg(&amp;buffer, &amp;buffer, &amp;buffer+1); } return i; } </code></pre> <h2>testfilter.cpp</h2> <pre><code>#include &quot;commentfilterbuf.h&quot; #include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;string&gt; int main(int argc, char* argv[]) { if (argc != 2) { std::cerr &lt;&lt; &quot;Usage: testfilter inputfile\n&quot;; return 0; } std::ifstream fin{argv[1]}; if (!fin) { std::cerr &lt;&lt; &quot;Error: could not open &quot; &lt;&lt; argv[1] &lt;&lt; &quot;\n&quot;; return 1; } commentfilterbuf sbuf(fin.rdbuf()); std::istream in(&amp;sbuf); std::string line; for (std::string line; std::getline(in, line); ) { std::cout &lt;&lt; line &lt;&lt; '\n'; } } </code></pre> <h2>sample.in</h2> <pre class="lang-delphi prettyprint-override"><code>program HelloWorld; {$APPTYPE CONSOLE} { This is a comment. } { this is a multiline comment. } { This is a Turbo Pascal comment } // This is a Delphi comment. All is ignored till the end of the line. // let's try to confuse the parser { comment 1 // Comment 2 }begin // comment 1 { comment 2 }foo // Here's a comment WriteLn('Hello World'); { and another } end. </code></pre>
[]
[ { "body": "<p>I only have a few minor comments.</p>\n<p>The first is about your empty while loops, such as:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code> for (i = sbuf-&gt;sbumpc(); i == '{'; i = sbuf-&gt;sbumpc()) {\n while ((i = sbuf-&gt;sbumpc()) != '}');\n }\n</code></pre>\n<p>I generally prefer to at least put the semicolon on a line by itself, to make it fairly obvious that it's intentional that the semicolon wasn't just accidentally entered at the end of a line where it shouldn't have been:</p>\n<pre><code>for (i = sbuf-&gt;sbumpc(); i == '{'; i = sbuf-&gt;sbumpc()) {\n while ((i = sbuf-&gt;sbumpc()) != '}')\n ;\n}\n</code></pre>\n<p>In this case, there's no other statement there before the closing brace that the loop <em>could</em> be controlling so it's probably less serious than usual, but I still prefer consistency (even though: &quot;a foolish consistency is the hobgoblin of small minds&quot;).</p>\n<p>Second, if you're going to do all this, I'd probably add a little <code>commentfilterstream</code> class on this order:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;fstream&gt;\n#include &lt;istream&gt;\n\nclass commentfilterstream : public std::istream {\n std::filebuf buffer;\n commentfilterbuf buf;\n\npublic:\n // or use an `std::filesystem::path` instead of a string.\n commentfilterstream(std::string const&amp; filename)\n : buf(&amp;buffer)\n , std::istream(&amp;buf)\n {\n buffer.open(filename.c_str(), std::ios_base::in);\n }\n\n ~commentfilterstream() { buffer.close(); }\n};\n</code></pre>\n<p>This lets you simplify the client code a bit to become something like this:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>int main(int argc, char* argv[])\n{\n if (argc != 2) {\n std::cerr &lt;&lt; &quot;Usage: testfilter inputfile\\n&quot;;\n return 0;\n }\n\n // Opening stream is now one step, just like usual:\n commentfilterstream in{argv[1]};\n\n if (!fin) {\n std::cerr &lt;&lt; &quot;Error: could not open &quot; &lt;&lt; argv[1] &lt;&lt; &quot;\\n&quot;;\n return 1;\n }\n\n std::string line;\n for (std::string line; std::getline(in, line); ) {\n std::cout &lt;&lt; line &lt;&lt; '\\n';\n }\n}\n</code></pre>\n<p>Finally, I'd probably put the buffer and filter into a namespace (e.g., <code>Delphi</code>) to give a little better indication of their intended purpose (<code>Delphi::commentfilterstream</code>).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T04:59:08.277", "Id": "254118", "ParentId": "254104", "Score": "2" } } ]
{ "AcceptedAnswerId": "254118", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T20:35:13.790", "Id": "254104", "Score": "5", "Tags": [ "c++", "stream", "c++20" ], "Title": "Filter out comments in Delphi source code" }
254104
<p>Here's my very basic String class. This is my first attempt, to try to design and write a basic String class in C++, without using the absolute new features provided by newer C++.</p> <pre><code>class MyString { public: MyString(): pSize{0}, pStr{nullptr} {} MyString(const char* cstr): pSize{compute_length(cstr)}, pStr{nullptr} { pStr = new char[pCapacity]; std::copy(cstr, cstr + pSize, pStr); } MyString(const MyString&amp; rhs): pSize{rhs.size()}, pStr{nullptr} { pStr = new char[pCapacity]; std::copy(rhs.data(), rhs.data() + rhs.size(), pStr); } ~MyString() { if(pStr){ delete[] pStr; } } size_t size() const { return pSize; } size_t capacity() const { return pCapacity; } const char* data() const { return pStr; } MyString&amp; operator=(const MyString&amp; rhs){ if(this == &amp;rhs) return *this; if(pCapacity &lt; rhs.size()){ delete[] pStr; pSize = rhs.pSize; pCapacity = (pCapacity &lt; rhs.capacity()) ? rhs.capacity() : pCapacity; pStr = new char[pCapacity]; std::copy(rhs.data(), rhs.data() + rhs.size(), pStr); return *this; } pSize = rhs.size(); pCapacity = rhs.capacity(); std::copy(rhs.data(), rhs.data() + rhs.size(), pStr); return *this; } private: size_t pSize; char* pStr; size_t pCapacity = 14; inline size_t compute_length(const char* cstr) { if(cstr == &quot;&quot;) return 0; size_t i = 0; while(cstr[++i] != '\0'); return i; } } </code></pre> <p>Any tips, suggestions, and/or feedback!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T22:48:33.327", "Id": "501159", "Score": "3", "body": "Why not using a std::unique_ptr ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T23:09:48.707", "Id": "501161", "Score": "0", "body": "@Pierre-AntoineGuillaume, because I don't want to." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T23:25:16.547", "Id": "501162", "Score": "0", "body": "What are your reasons for prefering raw pointers to unique pointer?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T23:28:33.000", "Id": "501163", "Score": "0", "body": "theProgrammer, the main reason is, that I simply want to do this the hard way, before, I take the simpler approach." } ]
[ { "body": "<h1>There are some bugs</h1>\n<p>There are several bugs in your code. In the constructor that takes a C string, you compute the length of <code>cstr</code> and set <code>pSize</code> accordingly, but you allocate <code>pCapacity</code> bytes. You should allocate at least <code>pSize</code> bytes. I recommend you get rid of <code>pCapacity</code> and try to make the class work with just <code>pSize</code> first.\nYou make the same mistake in <code>operator=()</code>.</p>\n<p>Second, the way you compute the length is wrong. The compiler should have warned you about comparing <code>cstr</code> to <code>&quot;&quot;</code>, if not turn on compiler warnings. The statement:</p>\n<pre><code>if(cstr == &quot;&quot;)\n</code></pre>\n<p>Is comparing the <em>pointers</em>, not the contents of the C strings. The correct way is to write <code>if(cstr[0] == '\\0')</code>, but even that is not necessary; you should just make the loop below work correctly even for the corner case of a zero length string.</p>\n<h1>Store a terminating NUL-byte</h1>\n<p>It is very common to want to access a string object as a regular C string. And the member function <code>data()</code> almost allows you to do that, except that you don't reserve memory for and don't store a NUL byte at the end. I recommend you do that, it makes accessing a <code>MyString</code> as a C string much easier, and will prevent some accidents.</p>\n<h1>No need to check for NULL pointers before calling <code>delete</code></h1>\n<p>Calling <code>delete</code> on a NULL pointer is guaranteed to be safe. So:</p>\n<pre><code>~MyString()\n{\n delete[] pStr;\n}\n</code></pre>\n<p>Or even better, as mentioned in the comments, use <code>std::unique_ptr</code> to handle memory for you. Don't reinvent too many wheels at the same time.</p>\n<h1>Handle out-of-memory conditions correctly</h1>\n<p>Be aware that calling <code>new</code> might fail if the program has ran out of memory. In that case, an exception will be thrown. You can choose to ignore the exception, but you must do it in such a way that your object is left in a valid state. Consider that <code>operator=</code> might fail calling <code>new</code>, then <code>pStr</code> is left pointing to the old data which is already deleted. If the caller handles the exception, then you have a problem, since as soon as the destructor is called it tries to delete the memory again.</p>\n<p>The solution is to try to allocate memory for the copy first before deleting the old memory:</p>\n<pre><code>if(pSize &lt; rhs.size()){\n char *newStr = new char[rhs.size()];\n delete[] pStr;\n pStr = newStr;\n}\n\npSize = rhs.size();\n...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T23:42:51.220", "Id": "501164", "Score": "0", "body": "Hi thx, what bugs are there really? I am using Visual Studio the latest community edition." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T23:29:49.787", "Id": "254114", "ParentId": "254105", "Score": "4" } }, { "body": "<p>Trivial: the declaration is not complete - you're missing the final <code>;</code> after the class definition.</p>\n<p>Missing includes:</p>\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;cstddef&gt;\n\nusing std::size_t; // don't do this in a header!\n</code></pre>\n<p>As noted in the comment, don't put standard library identifiers into the global namespace - just write the type in full throughout the interface.</p>\n<p>Don't use a null pointer for an empty string. That's going to result in a lot of special-case code when you implement the rest of the String interface (e.g. <code>operator==()</code>, <code>operator+=</code>, and more).</p>\n<p>In this constructor:</p>\n<blockquote>\n<pre><code> MyString(const char* cstr): \n pSize{compute_length(cstr)}, pStr{nullptr} \n {\n pStr = new char[pCapacity];\n std::copy(cstr, cstr + pSize, pStr);\n }\n</code></pre>\n</blockquote>\n<p>As well as using an array which may be too small, we're assigning to <code>pStr</code> twice. We could do it just once, if we rearrange the order of the data members:</p>\n<pre><code>private:\n static constexpr std::size_t default_capacity = 14;\n std::size_t pSize;\n std::size_t pCapacity = default_capacity;\n char* pStr;\n</code></pre>\n\n<pre><code>public:\n MyString(const char* cstr)\n : pSize{compute_length(cstr)},\n pCapacity{pSize},\n pStr{new char[pCapacity]}\n {\n std::copy_n(cstr, pSize, pStr);\n }\n</code></pre>\n<p>The same problem exists with the copy constructor, and is as easily fixed:</p>\n<pre><code> MyString(const MyString&amp; rhs):\n pSize{rhs.pSize},\n pCapacity{pSize},\n pStr{new char[pCapacity]}\n {\n std::copy_n(rhs.pStr, pSize, pStr);\n }\n</code></pre>\n<p>Actually, I'd re-write all the constructors both in terms of a new <code>(const char*, std::size_t)</code> constructor:</p>\n<pre><code>public:\n MyString(const char* s, std::size_t len)\n : pSize{len},\n pCapacity{len},\n pStr{new char[len]}\n {\n std::copy_n(s, len, pStr);\n }\n\n MyString()\n : MyString{&quot;&quot;}\n {}\n\n MyString(const char* cstr)\n : MyString{cstr, std::strlen(cstr)}\n {}\n\n MyString(const MyString&amp; rhs)\n : MyString{rhs.pStr, rhs.pSize}\n {}\n</code></pre>\n<p>Well done for remembering the test for self-assignment here:</p>\n<blockquote>\n<pre><code>MyString&amp; operator=(const MyString&amp; rhs){\n if(this == &amp;rhs)\n return *this;\n</code></pre>\n</blockquote>\n<p>I'm not convinced it's a good idea to retain the string's storage when it's already large enough to accommodate <code>rhs</code> - this means that any string that's ever held a very long string will continue to use that space until it's destroyed. That's not what most users expect when they write <code>s = &quot;&quot;</code>! Even worse, we copy that huge capacity to any other string we construct or assign from this:</p>\n<pre><code>MyString s = some_huge_string(); // capacity is now big\ns = &quot;&quot;; // capacity is still big\nMyString s1 = s; // s1's capacity is also big, even though it's an empty string!\nMyString s2{&quot;&quot;}; // s2's capacity is small\ns2 = s; // now it's huge, even though its content is unchanged\n</code></pre>\n<p>Perhaps use a threshold to determine whether the storage should be reduced? I'd go with something like</p>\n<pre><code> if (rhs.pSize &gt; pCapacity\n || rhs.pSize &lt; pCapacity / 2 &amp;&amp; rhs.pSize &lt; default_capacity)\n</code></pre>\n<p>And much of the duplication in this function can be reduced:</p>\n<pre><code>MyString&amp; operator=(const MyString&amp; rhs){\n if (this == &amp;rhs) {\n return *this;\n }\n\n if (rhs.pSize &gt; pCapacity\n || rhs.pSize &lt; pCapacity / 2 &amp;&amp; rhs.pSize &lt; default_capacity)\n {\n char *new_str = new char[rhs.pSize];\n delete[] pStr;\n pStr = new_str;\n pCapacity = rhs.pSize;\n }\n\n pSize = rhs.size();\n std::copy_n(rhs.pStr, pSize, pStr);\n return *this;\n}\n</code></pre>\n<p>You'll need to write a move-constructor and move-assignment soon - I recommend writing a <code>swap()</code> first, and implementing those in terms of <code>swap()</code>.</p>\n<hr />\n<h1>Modified code</h1>\n<p>As there were no tests, I added a simple <code>main()</code> to exercise the class.</p>\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;cstddef&gt;\n#include &lt;cstring&gt;\n\nclass MyString {\npublic:\n MyString(const char* s, std::size_t len)\n : pSize{len},\n pCapacity{len},\n pStr{new char[len]}\n {\n std::copy_n(s, len, pStr);\n }\n\n MyString()\n : MyString{&quot;&quot;}\n {}\n\n MyString(const char* cstr)\n : MyString{cstr, std::strlen(cstr)}\n {}\n\n MyString(const MyString&amp; rhs)\n : MyString{rhs.pStr, rhs.pSize}\n {}\n\n ~MyString()\n {\n delete[] pStr;\n }\n\n std::size_t size() const { return pSize; }\n std::size_t capacity() const { return pCapacity; }\n const char* data() const { return pStr; }\n\n MyString&amp; operator=(const MyString&amp; rhs)\n {\n if (this == &amp;rhs) {\n return *this;\n }\n\n if (rhs.pSize &gt; pCapacity\n || rhs.pSize &lt; pCapacity / 2 &amp;&amp; rhs.pSize &lt; default_capacity)\n {\n char *new_str = new char[rhs.pSize];\n delete[] pStr;\n pStr = new_str;\n pCapacity = rhs.pSize;\n }\n\n pSize = rhs.size();\n std::copy_n(rhs.pStr, pSize, pStr);\n return *this;\n }\n\nprivate:\n static constexpr std::size_t default_capacity = 14;\n std::size_t pSize;\n std::size_t pCapacity = default_capacity;\n char* pStr;\n};\n</code></pre>\n\n<pre><code>#include &lt;iostream&gt;\nint main()\n{\n MyString s0 = &quot;abc&quot;;\n MyString s1 = s0;\n s1 = &quot;&quot;;\n s1 = s0;\n std::cout.write(s1.data(), s1.size());\n std::cout &lt;&lt; '\\n';\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T13:37:24.970", "Id": "501266", "Score": "0", "body": "Doesn't calling self constructor from constructor create overhead and copies?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T14:46:47.807", "Id": "501272", "Score": "1", "body": "No, that's how we write a *delegating constructor*. They both work on the same instance, with no extra copy." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T16:25:49.377", "Id": "501281", "Score": "0", "body": "I am getting CRT memory leak at line: `pStr{new char[pCapacity]}`, **14 bytes long**." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T16:28:45.450", "Id": "501282", "Score": "0", "body": "That's interesting. You should probably fix that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T16:35:36.747", "Id": "501283", "Score": "1", "body": "Valgrind gives a clean report on my test program." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T10:41:58.570", "Id": "254126", "ParentId": "254105", "Score": "4" } } ]
{ "AcceptedAnswerId": "254126", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T20:46:57.743", "Id": "254105", "Score": "2", "Tags": [ "c++", "c++11", "reinventing-the-wheel" ], "Title": "My String Class" }
254105
<p>The following SQL code serves the purpose of assessing basic SQL Server literacy.</p> <p>I am creating database and tables schemas, inserting data from .csv files. Constructing 8 simple queries as answers to assignment tasks.</p> <p>The code works well, but as I am very new to MSSQL Server I need some advice on the following:</p> <ol> <li>Are there any better ways for constructing database and table schemas?</li> <li>Are there any better ways to populate tables from .csv files?</li> <li>Best practices for error-handling. Print on external file or as query output?</li> <li>How the syntax can be improved, but provide somewhat foolproofness if the wrong database is in use. Practical and convenient, or complicated and accurate?</li> </ol> <p>Assessment questions can be found commented-out prior to every query. Comma-separated sample datasets can be found at the bottom.</p> <pre><code>USE master GO --------------------------------------------------------------------------------------- -- Create database IF NOT (EXISTS ( SELECT * FROM SYS.DATABASES WHERE NAME = N'SQLAssessment' ) )BEGIN CREATE DATABASE [SQLAssessment] ON PRIMARY ( NAME = N'[SQLAssessment]', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\DATA\SQLAssessment.mdf', SIZE = 10096KB, FILEGROWTH = 1024KB ) LOG ON ( NAME = N'Products_log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\DATA\SQLAssessment.ldf', SIZE = 1024KB, FILEGROWTH = 10 % ) END --USE [SQLAssessment] --GO --------------------------------------------------------------------------------------- -- Create Customers table IF NOT (EXISTS ( SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE OBJECT_ID(N'[SQLAssessment].[dbo].[Customers]') IS NOT NULL ) )BEGIN CREATE TABLE [SQLAssessment].[dbo].[Customers] ( customerid INT not null, firstname VARCHAR (50) null, lastname VARCHAR (50) null, city VARCHAR (50) null, state VARCHAR (50) null, CONSTRAINT PK_Customers_customerid PRIMARY KEY CLUSTERED (customerid) ) END GO --------------------------------------------------------------------------------------- -- Populate Customers table from .csv BEGIN TRY BULK INSERT [SQLAssessment].[dbo].[Customers] FROM 'C:\Users\tsenk\OneDrive\Работен плот\customers_data.csv' WITH ( -- &lt;--- fit for purpose FIRSTROW = 1, FIELDTERMINATOR = ',', ROWTERMINATOR = '\n', ERRORFILE = 'C:\Users\tsenk\OneDrive\CustomersErrorRows.csv', TABLOCK ) END TRY BEGIN CATCH SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_LINE() AS ErrorLine, ERROR_MESSAGE() AS ErrorMessage; END CATCH GO --------------------------------------------------------------------------------------- -- Create Customer_Purchases table IF NOT EXISTS( SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE OBJECT_ID(N'[SQLAssessment].[dbo].[Customer_Purchases]') IS NOT NULL ) BEGIN CREATE TABLE [SQLAssessment].[dbo].[Customer_Purchases] ( customerid INT NOT NULL, order_date DATE NULL, item VARCHAR (200) NULL, quantity INT NULL, price DECIMAL (20,2) NULL, CONSTRAINT FK_CustomerPurchases_CustomerID FOREIGN KEY (customerid) REFERENCES [SQLAssessment].[dbo].[Customers](customerid) ON DELETE CASCADE ON UPDATE CASCADE ) END GO --------------------------------------------------------------------------------------- -- Populate Customer_Purchases table from .csv BEGIN TRY BULK INSERT [SQLAssessment].[dbo].[Customer_Purchases] FROM 'C:\Users\tsenk\OneDrive\customer_purchases_data.csv' WITH ( -- &lt;--- fit for purpose FIRSTROW = 1, FIELDTERMINATOR = ',', ROWTERMINATOR = '\n', ERRORFILE = 'C:\Users\tsenk\OneDrive\CustomerPurchasesErrorRows.csv', TABLOCK ) END TRY BEGIN CATCH SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_LINE() AS ErrorLine, ERROR_MESSAGE() AS ErrorMessage; END CATCH GO --------------------------------------------------------------------------------------- -- 1. Count clients by state and show in descending order. SELECT [SQLAssessment].[dbo].[Customers].*, COUNT([SQLAssessment].[dbo].[Customers].[customerid]) AS [customercount] FROM [SQLAssessment].[dbo].[Customers] WHERE [SQLAssessment].[dbo].[Customers].[state] IS NOT NULL GROUP BY [SQLAssessment].[dbo].[Customers].[customerid], [SQLAssessment].[dbo].[Customers].[firstname], [SQLAssessment].[dbo].[Customers].[lastname], [SQLAssessment].[dbo].[Customers].[state], [SQLAssessment].[dbo].[Customers].[city] ORDER BY [customercount] DESC --------------------------------------------------------------------------------------- -- 2. Show first and last name of the customers who are presented with their first name more than once. SELECT [SQLAssessment].[dbo].[Customers].[customerid], [SQLAssessment].[dbo].[Customers].[firstname], [SQLAssessment].[dbo].[Customers].[lastname], [SQLAssessment].[dbo].[Customers].[city], [SQLAssessment].[dbo].[Customers].[state] FROM [SQLAssessment].[dbo].[Customers] WHERE [SQLAssessment].[dbo].[Customers].[firstname] IN( SELECT [SQLAssessment].[dbo].[Customers].[firstname] FROM [SQLAssessment].[dbo].[Customers] GROUP BY [SQLAssessment].[dbo].[Customers].[firstname] HAVING COUNT([SQLAssessment].[dbo].[Customers].[firstname]) &gt; 1 ) GROUP BY [SQLAssessment].[dbo].[Customers].[customerid], [SQLAssessment].[dbo].[Customers].[firstname], [SQLAssessment].[dbo].[Customers].[lastname], [SQLAssessment].[dbo].[Customers].[city], [SQLAssessment].[dbo].[Customers].[state] --------------------------------------------------------------------------------------- -- 3. How many flashlights are bought by John Gray? SELECT c.[customerid], c.[firstname], c.[lastname], cp.[item], SUM(cp.[quantity]) AS [quantity_bought] FROM [SQLAssessment].[dbo].[Customers] AS c INNER JOIN [SQLAssessment].[dbo].[Customer_Purchases] AS cp ON c.[customerid] = cp.[customerid] WHERE cp.[item] IN ( SELECT [SQLAssessment].[dbo].[Customer_Purchases].[item] FROM [SQLAssessment].[dbo].[Customer_Purchases] WHERE [SQLAssessment].[dbo].[Customer_Purchases].[item] LIKE 'Flashlight' GROUP BY [SQLAssessment].[dbo].[Customer_Purchases].[item] HAVING count(*) &gt; 1 ) AND c.[customerid] = 10101 GROUP BY c.[customerid], c.[firstname], c.[lastname], cp.[item] --------------------------------------------------------------------------------------- -- 4. Show 5 random customers and purchases (item and quantity). SELECT TOP 5 c.[customerid], c.[firstname], c.[lastname], c.[city], c.[state], cp.[item], cp.[quantity] FROM [SQLAssessment].[dbo].[Customers] AS c INNER JOIN [SQLAssessment].[dbo].[Customer_Purchases] AS cp ON cp.[customerid] = c.[customerid] ORDER BY RAND(CHECKSUM(*) * RAND()) --------------------------------------------------------------------------------------- -- 5. What is the earliest item purchased by Isabela Moore? SELECT TOP 1 c.[customerid], c.[firstname], c.[lastname], cp.[item], cp.[order_date] FROM [SQLAssessment].[dbo].[Customers] AS c LEFT JOIN [SQLAssessment].[dbo].[Customer_Purchases] AS cp ON c.[customerid] = cp.[customerid] WHERE c.[customerid] = 10449 GROUP BY c.[customerid], c.[firstname], c.[lastname], cp.[item], cp.[order_date] ORDER BY cp.[order_date] --------------------------------------------------------------------------------------- -- 6. What did Isabela Moore purchase in the period 01 August to 31 December? SELECT cp.[customerid], c.[firstname], c.[lastname], cp.[item], cp.[order_date] FROM [SQLAssessment].[dbo].[Customers] AS c LEFT JOIN [SQLAssessment].[dbo].[Customer_Purchases] AS cp ON c.[customerid] = cp.[customerid] WHERE c.[customerid] = 10449 AND cp.[order_date] BETWEEN '2009-08-13' AND '2009-12-31' GROUP BY cp.[customerid], c.[firstname], c.[lastname], cp.[item], cp.[order_date] ORDER BY cp.[order_date] --------------------------------------------------------------------------------------- -- 7. Show the total number of items, total amount and weighted average price by state. SELECT c.[state], SUM(cp.[quantity]) AS [total_items], SUM(cp.[price] * cp.[quantity]) AS [total_amount], SUM(cp.[price] * cp.[quantity]) / SUM(cp.[quantity]) AS [weighted_average_price] FROM [SQLAssessment].[dbo].[Customers] AS c INNER JOIN [SQLAssessment].[dbo].[Customer_Purchases] AS cp ON c.[customerid] = cp.[customerid] GROUP BY c.[state] --------------------------------------------------------------------------------------- -- 8. Show in separate columns Isabela Moore`s purchases item and order date. SELECT cp.[item], cp.[order_date] FROM [SQLAssessment].[dbo].[Customers] AS c INNER JOIN [SQLAssessment].[dbo].[Customer_Purchases] AS cp ON c.[customerid] = cp.[customerid] WHERE c.[customerid] = 10449 GROUP BY cp.[item], cp.[order_date] </code></pre> <p><strong>Customers Dataset:</strong></p> <pre><code>10101,John,Gray,Lynden,Washington 10298,Leroy,Brown,Pinetop,Arizona 10299,Elroy,Keller,Snoqualmie,Washington 10315,Lisa,Jones,Oshkosh,Wisconsin 10325,Ginger,Schultz,Pocatello,Idaho 10329,Kelly,Mendoza,Kailua,Hawaii 10330,Shawn,Dalton,Cannon Beach,Oregon 10338,Michael,Howell,Tillamook,Oregon 10339,Anthony,Sanchez,Winslow,Arizona 10408,Elroy,Cleaver,Globe,Arizona 10410,Mary Ann,Howell,Charleston,South Carolina 10413,Donald,Davids,Gila Bend,Arizona 10419,Linda,Sakahara,Nogales,Arizona 10429,Sarah,Graham,Greensboro,North Carolina 10438,Kevin,Smith,Durango,Colorado 10439,Conrad,Giles,Telluride,Colorado 10449,Isabela,Moore,Yuma,Arizona </code></pre> <p><strong>Customer Purchases Dataset:</strong></p> <pre><code>10330,30-Jun-09,Pogo stick,1,28 10101,30-Jun-09,Raft,1,58 10298,01-Jul-09,Skateboard,1,33 10101,01-Jul-09,Life Vest,4,125 10299,06-Jul-09,Parachute,1,1250 10339,27-Jul-09,Umbrella,1,4.5 10449,13-Aug-09,Unicycle,1,180.79 10439,14-Aug-09,Ski Poles,2,25.5 10101,18-Aug-09,Rain Coat,1,18.3 10449,01-Sep-09,Snow Shoes,1,45 10439,18-Sep-09,Tent,1,88 10298,19-Sep-09,Lantern,2,29 10410,28-Oct-09,Sleeping Bag,1,89.22 10438,01-Nov-09,Umbrella,1,6.75 10438,02-Nov-09,Pillow,1,8.5 10298,01-Dec-09,Helmet,1,22 10449,15-Dec-09,Bicycle,1,380.5 10449,22-Dec-09,Canoe,1,280 10101,30-Dec-09,Hoola Hoop,3,14.75 10330,01-Jan-00,Flashlight,4,28 10101,02-Jan-10,Lantern,1,16 10299,18-Jan-10,Inflatable Mattress,1,38 10438,18-Jan-10,Tent,1,79.99 10413,19-Jan-10,Lawnchair,4,32 10410,30-Jan-10,Unicycle,1,192.5 10315,02-Feb-10,Compass,1,8 10449,28-Feb-10,Flashlight,1,4.5 10101,08-Mar-10,Sleeping Bag,2,88.7 10298,18-Mar-10,Pocket Knife,1,22.38 10449,19-Mar-10,Canoe paddle,2,40 10298,01-Apr-10,Ear Muffs,1,12.5 10330,19-Apr-10,Shovel,1,16.75 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T18:56:08.100", "Id": "501290", "Score": "2", "body": "Some quick remarks (from standard ETL practices): load data into a staging area, temp tables will do, and then load (insert) them into the target tables, so you can first apply validations and reject an entire batch when something isn't OK. It also allows you to transform data before loading. For example, you should normalize the customer data: store cities and states in separate tables and have foreign keys from customer to city and city to state." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T19:15:42.943", "Id": "501291", "Score": "0", "body": "@GertArnold much appreciated advice. Will start working on it right away. Will be posting updates." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T01:50:54.847", "Id": "501310", "Score": "0", "body": "Why MSSQL? Is this for work?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T02:55:32.497", "Id": "501311", "Score": "0", "body": "@Reinderien school. Taking it one step further just to obtain the right knowledge." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T15:21:12.293", "Id": "501353", "Score": "0", "body": "Does your course teach Microsoft specifically, or is it just covering SQL in general? If the latter, you should consider switching to open-source." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T15:54:08.017", "Id": "501354", "Score": "1", "body": "@Reinderien, MSSQL Server specifically. The goal of the course is for the student to obtain skills and knowledge enough to build and manage Data Mart, which is the final assignment of the course. What is posted above is an assessment of the first few lessons in general MSSQL Server. The sole goal of the question is educational as well. The aim is to obtain solid foundations in SQL Database Administration by learning best practices." } ]
[ { "body": "<h2>Data location</h2>\n<p>This is probably a weirdness from MSSQL itself and not specifically your setup, but your database location:</p>\n<pre><code>FILENAME = N'C:\\Program Files\\Microsoft SQL Server\\MSSQL15.MSSQLSERVER\\MSSQL\\DATA\\SQLAssessment.mdf',\n \n</code></pre>\n<p>as well as MSSQL's own <a href=\"https://docs.microsoft.com/en-us/sql/sql-server/install/file-locations-for-default-and-named-instances-of-sql-server?view=sql-server-ver15#specifying-file-paths\" rel=\"nofollow noreferrer\">default Database Engine data file location</a>:</p>\n<pre><code>\\Program Files\\Microsoft SQL Server\\MSSQL{nn}.&lt;InstanceID&gt;\\\n</code></pre>\n<p>are surprising to me. <code>Program Files</code> should only contain application binaries and non-user-data resources. A better place for database files would either be <code>ProgramData</code> or the home directory of the service user. Unix-like operating systems enforce this more often than Windows. All of that said, changing this might be an up-hill battle if there are spooky dependencies on the data directory setting.</p>\n<h2>Parametric paths</h2>\n<p><code>C:\\Users\\tsenk\\OneDrive\\Работен плот</code> should not appear in your script, and this kind of thing should not be hard-coded. There are <a href=\"https://social.technet.microsoft.com/wiki/contents/articles/35120.sql-script-passing-parameters-to-sql-script-with-batch-file-and-powershell.aspx\" rel=\"nofollow noreferrer\">reasonable ways</a> to pass parameters into your script instead.</p>\n<h2>Unneeded group-by</h2>\n<p>Are these <code>group</code> clauses from queries 2</p>\n<pre><code>GROUP BY\n [SQLAssessment].[dbo].[Customers].[customerid],\n [SQLAssessment].[dbo].[Customers].[firstname], \n [SQLAssessment].[dbo].[Customers].[lastname],\n [SQLAssessment].[dbo].[Customers].[city],\n [SQLAssessment].[dbo].[Customers].[state]\n</code></pre>\n<p>and 3</p>\n<pre><code>GROUP BY \n c.[customerid],\n c.[firstname], \n c.[lastname],\n cp.[item]\n</code></pre>\n<p>strictly necessary? There's no corresponding aggregate in either <code>select</code>.</p>\n<h2>Don't hard-code IDs</h2>\n<p>Queries 3, 5, 6 and 8 should not hard-code <code>c.[customerid]</code> in a <code>where</code>. Compare the first and last names instead.</p>\n<h2>Data types</h2>\n<p>Consider either <code>smallmoney</code> or <code>money</code> for your <code>price</code> column.</p>\n<h2>Logging</h2>\n<p>You ask:</p>\n<blockquote>\n<p>Best practices for error-handling. Print on external file or as query output?</p>\n</blockquote>\n<p>This is difficult to answer in general, as it will be influenced by context; but thinking to the lowest-barrier-to-entry for all of the common logging aggregators, file-based logs will present less of an integration fight. So keep your</p>\n<pre><code> ) LOG ON (\n NAME = N'Products_log',\n FILENAME = N'C:\\Program Files\\Microsoft SQL Server\\MSSQL15.MSSQLSERVER\\MSSQL\\DATA\\SQLAssessment.ldf',\n SIZE = 1024KB,\n FILEGROWTH = 10 %\n )\n</code></pre>\n<p>but, per &quot;Data Location&quot; above, it doesn't make sense to live in <code>Program Files</code>.</p>\n<h2>Fully-qualified object references</h2>\n<p>When you ask</p>\n<blockquote>\n<p>How the syntax can be improved, but provide somewhat foolproofness if the wrong database is in use. Practical and convenient, or complicated and accurate?</p>\n</blockquote>\n<p>That's a little difficult for me to decode, but I assume you're talking about this reference style:</p>\n<pre><code>[SQLAssessment].[dbo].[Customers]\n</code></pre>\n<p>You're debating whether or not database and schema prefixes should exist in your object references. Generally I would want to omit these, the reason being maintainability. If the database or schema name ever change, a script littered with fully-qualified references will require many changes, but a script that can assume a correctly set current schema will need few or no changes. SQL Server has <a href=\"https://stackoverflow.com/a/4942223/313768\">well-understood mechanisms</a> for setting the current schema.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-05T13:14:58.813", "Id": "501575", "Score": "0", "body": "I am grateful for the time you invested in providing an answer. I have taken note to the corrections that you suggest and applied them. If you can throw in some pointers to error handling best practices and on how a script can be made more secure in terms of referencing databases and tables (points 3 and 4), I will gladly mark your answer as a solution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-08T02:11:32.213", "Id": "501785", "Score": "1", "body": "I've attempted to address those questions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-09T16:57:12.400", "Id": "501927", "Score": "0", "body": "Is there anything else preventing this answer from being accepted? It seems that the bounty has expired." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-24T08:45:48.880", "Id": "503369", "Score": "0", "body": "I have missed your update. Seemed like you have abandoned the question at the time. Started a new bounty and accepted your answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-28T23:34:23.850", "Id": "503796", "Score": "1", "body": "I agree with the data location. On a production environment, you probably also would put the log file on a different (logical and physical) drive than the data files (e.g. `C:\\Data\\SQLAssessment.mdf` and `D:\\Data\\SQLAssessment.ldf`) and an auto-growth value of 1MB would give you terrible fragmentation, use 50 or 100MB instead (in production)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-28T23:53:15.423", "Id": "503798", "Score": "1", "body": "I would only put database names in a query if it spans multiple databases. Reason: Imagine you need to perform some challenging database reengineering and decide to restore a copy of your DB called `SQLAssessmentTryOut` side-by-side by your normal SQLAssessment DB on the test system. You would now have to adjust every single query in the database as well as the application to point to the new database. If you don't database-qualify the objects, you only adjust the connection string of the application and everything works just the same - just on a different database." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-29T00:19:10.793", "Id": "503800", "Score": "0", "body": "Generally speaking are the tables too simple for real life usage. `Customer_Purchases` (why not `Orders`?) would need an order number, quantity would probably need some decimals and a unit id (one can also sell hours, kilos and square-meters etc.). As order date I would also include the time, e.g. as datetimeoffset. The product information would be stored in a different table (e.g. `Products`) and only an item number (e.g. VARCHAR(15) or INT) and copied price, VAT-code etc. would be stored in the order item record, the order would have currency-id and totals incl/excl VAT etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-29T00:20:11.207", "Id": "503801", "Score": "1", "body": "@Christoph Half of these comments seem like they should be in your own answer, not on mine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-29T00:39:43.980", "Id": "503802", "Score": "0", "body": "@Reinderien: Agreed. I was a bit in a flow... ;-)" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T19:23:19.257", "Id": "254232", "ParentId": "254109", "Score": "1" } } ]
{ "AcceptedAnswerId": "254232", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T21:53:24.260", "Id": "254109", "Score": "5", "Tags": [ "sql", "sql-server", "t-sql" ], "Title": "Basic schemas for database and tables creation, bulk import from .csv and basic queries" }
254109
<p>I am practically brand new to coding and this is my first &quot;real&quot; project I've been attempting. It's an attempt at a vanilla JS game with selectable layout and win conditions (partially implemented). ATM it only has a vertical win condition included as I didn't want too much cluttering of the code (horizontal and diagonal would look more so the same).</p> <p><strong>SCRIPT.JS</strong></p> <pre><code>const mainDiv = document.querySelector('[data-screen]') class TicTacToe { constructor(div) { this.board = div.querySelector('[data-board]') } //most of the initial variables here varUpdater = () =&gt; { this.pauseButton = this.board.querySelector('[data-pause-button]') this.pauseButton.addEventListener('click', this.setUp) this.pauseScreen = this.board.querySelector('[data-pause]') this.pauseText = this.board.querySelector('[data-pause-text]') this.playerOne = &quot;x&quot; this.playerTwo = &quot;o&quot; this.currentPlayer = this.playerOne this.winCondition = 3 //adjusts win condition this.rows = 5 // these values adjust layout this.columns = 5 } setUp = () =&gt; { this.pauseMenuSetUp() this.varUpdater() this.cellSetUp() this.start() } pauseMenuSetUp = () =&gt; { this.board.innerHTML = ` &lt;div class=&quot;pause-screen show&quot; data-pause&gt; &lt;div data-pause-text&gt;&lt;/div&gt; &lt;button data-pause-button&gt;Start&lt;/button&gt; &lt;/div&gt; ` } //Sets up cell layout and css style based on given parameters cellSetUp = () =&gt; { this.board.style.cssText = `grid-template-columns: repeat(${this.columns}, auto);` this.colSeperatorDiv = document.createElement('div') this.cellElement = document.createElement('div') this.cellElement.setAttribute('class', 'cell') for (let i = 0; i &lt; this.rows; i++){ this.cellElement.setAttribute('data-cell', i) this.colSeperatorDiv.appendChild(this.cellElement.cloneNode(true)) } for (let i = 0; i &lt; this.columns;i++){ this.colSeperatorDiv.setAttribute('data-seperator', i) this.board.appendChild(this.colSeperatorDiv.cloneNode(true)) } } //Clears cell attributes and adds event listener before removing pause screen start = () =&gt; { this.board.querySelectorAll('[data-cell]').forEach(cell =&gt; { cell.classList.remove('x', 'o') cell.removeEventListener('click', this.clickHandle) cell.addEventListener('click', this.clickHandle, { once: true }) }) this.pauseScreen.classList.remove('show') } //Adds symbol based on cell target clickHandle = (cell) =&gt; { this.cell = cell.target this.cell.classList.add(this.currentPlayer) this.checkBoard() } //Decides if it should select next player or conclude game checkBoard = () =&gt; { this.columnIndex = parseInt(this.cell.getAttribute('data-cell')) this.rowIndex = parseInt(this.cell.parentElement.getAttribute('data-seperator')) if (this.isConcluded() == true) { this.pauseText.innerHTML = `${this.currentPlayer} wins!` this.pauseScreen.classList.add('show') } else if (this.isConcluded() === 'tie') { this.pauseText.innerHTML = `Tie!` this.pauseScreen.classList.add('show') } else { this.playerSelect() } } //Selects next player playerSelect = () =&gt; { this.currentPlayer !== this.playerTwo ? this.currentPlayer = this.playerTwo : this.currentPlayer = this.playerOne; } //Checks for game conclusion. Does NOT check for horizontal and diagonal conditions atm isConcluded = () =&gt; { return this.verticalScore(0, this.columnIndex) &gt;= this.winCondition ? true : Array.from(this.board.querySelectorAll('[data-cell]')).every(c =&gt; c.classList.contains(this.playerOne) || c.classList.contains(this.playerTwo)) ? 'tie' : false } //Goes down the column using recursion to add up score, //Diagonal/horizontal win condition would use the rowIndex as well verticalScore = (score, col) =&gt; { return this.cell.parentElement.querySelector(`[data-cell=&quot;${col}&quot;]`) == null ? score += this.reverseDirectionScore(0, this.columnIndex - 1) : this.cell.parentElement.querySelector(`[data-cell=&quot;${col}&quot;]`).classList.contains(this.currentPlayer) ? score += this.verticalScore(1, col + 1) : score += this.reverseDirectionScore(0, this.columnIndex - 1); } //Goes up column using recursion to return a score reverseDirectionScore = (rScore, rCol) =&gt; { return this.cell.parentElement.querySelector(`[data-cell=&quot;${rCol}&quot;]`) == null ? rScore : this.cell.parentElement.querySelector(`[data-cell=&quot;${rCol}&quot;]`).classList.contains(this.currentPlayer) ? rScore += this.reverseDirectionScore(1, rCol - 1) : rScore } } const newBoard = new TicTacToe(mainDiv) newBoard.setUp() </code></pre> <p>attaches to this HTML page</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Tic-Tac-Toe&lt;/title&gt; &lt;link rel=&quot;stylesheet&quot; href=&quot;styles.css&quot;&gt; &lt;/head&gt; &lt;body&gt; &lt;div data-screen&gt; &lt;div class=&quot;board&quot; data-board&gt; &lt;/div&gt; &lt;/div&gt; &lt;script src=&quot;/script.js&quot; async defer&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Codepen: <a href="https://codepen.io/sarbastu/pen/XWjZgey" rel="noreferrer">https://codepen.io/sarbastu/pen/XWjZgey</a></p> <p>The game is functioning as intended, but I have a bunch of doubt on the way it was written particularly with possible overuse of querySelector/data-attributes. A few particular questions:</p> <ol> <li>Was the choice to make the game a template object pointless/more damaging than otherwise?</li> <li>Does this code at all represent decently implemented OOP style?</li> <li>How is the use of querySelector (mainly the use of it in the last 3 game conclusion check functions)? Should I have attached them to a variable first? Is there anything I could have done better?</li> </ol> <p>Do to my complete lack of experience I have no idea if I am at all approaching OOP or programming in general correctly. Any criticism/feedback is greatly appreciated.</p>
[]
[ { "body": "<p>As you are as you say <em>&quot;brand new&quot;</em> to coding this will be less like a review and more like some pointers and advice..</p>\n<h2>Some pointers</h2>\n<ul>\n<li><p>Rather than define the functions as arrow functions within the class <code>verticalScore = (score, col) =&gt; {</code> Use the shorter syntax <code>verticalScore(score, col) {</code></p>\n<p>There is a technical reason due to the way <code>this</code> is associated with arrow functions differently from standard function (arrow functions close over <code>this</code> while standard function are bound to <code>this</code>)</p>\n</li>\n<li><p>JavaScript actually requires that expressions be terminated with semicolons. If you dont add them the parser will try an guess where they should be. 99% of the time it gets it right, but when it does not your code will not work as expected, or throw an error and it will not be obvious looking at the code what is wrong.</p>\n<p>To be safe always add the semicolon <code>;</code> If you are not sure add it. Its better to have too many than trying to fix the JavaScript's parser bad guess.</p>\n</li>\n<li><p>JavaScript was designed to be easy to learn and use and had many features that in hindsight turned out to make life hard for those new to code. To help fix this problem they added <a href=\"https://developer.mozilla.org/en-US/docs/Glossary/strict_mode\" rel=\"noreferrer\">strict mode</a> that will highlight problematic code with errors.</p>\n<p>As a beginner it is best to always add the directive <code>&quot;use strict&quot;;</code> at the very top (first line) of the JS file. It will save you hours of bug hunting due to problems that a few simple rules will avoid.</p>\n</li>\n<li><p>Go easy on the comments. Things like <code>//Selects next player</code> followed by the line <code>playerSelect = () =&gt; {</code> does not make a good comment and just clutters up the code.</p>\n<p>As a beginner comments help you keep track of your thought patterns as you code. Thus when adding comment think of them a future notes to self, do you really need them. In the long run good code does not need comments, good code explains its self.</p>\n</li>\n</ul>\n<h2>Objects</h2>\n<p>OOP does not mean using objects per say. As a beginner you should focus on objects as abstract entities with roles and responsibilities. OOP is a very advanced subject and the nitty details can often elude even experienced coders.</p>\n<blockquote>\n<p><em>&quot;Does this code at all represent decently implemented OOP style?&quot;</em></p>\n</blockquote>\n<p>You have defined an object with a properties and functions. You have instantiated an instance of that object <code>const newBoard = new TicTacToe(mainDiv)</code> and then called its functions, so you have the basics.</p>\n<p>OOP is not a style, it is in the structure, logic, and organisation of the code.</p>\n<p>For now keep using the basics, and as you get comfortable you will naturally begin to expand you knowledge of OOP</p>\n<h3>Developing your use of objects</h3>\n<p>Objects should be focused to specific parts of the task. You have one Object that does everything. Consider some creating more objects to do specific parts of the job.</p>\n<p>Some object could be...</p>\n<ul>\n<li><p>The game state has a start, play, gameover cycles, show the text Game Over, Player won, that is a task for an object.</p>\n</li>\n<li><p>There are two players that have turns. An object to store the players, whos turn is it, is it a draw, who won, who lost.</p>\n</li>\n<li><p>An object to hold a player, name, what side they are X or O, Track wins and losses.</p>\n</li>\n<li><p>You have cells that make up the board. An object to handle all the cells, with functions like <code>reset</code>, <code>checkWin</code>, <code>isValidMove</code> etc.</p>\n</li>\n<li><p>Each cell can also be an object, it handles the rendering and visual appearance of the cell, providing functions to allow other objects know what the cell is doing (empty, X or O), where the cell is. Etc</p>\n</li>\n</ul>\n<p>All these objects define the various abstract concepts that make up the game. If done well then the higher and more abstract the object, the more you code using these abstractions.</p>\n<p>For example at the top level Object you may call <code>Game</code>, it holds the <code>board</code>, <code>players</code>, and <code>game state</code>. It manages the various lower level objects. It would instruct the <code>board</code> object to reset <code>game.board.reset()</code> or <code>this.board.reset()</code>. Call <code>game.players.nextUp()</code> to get the next player set up to play with the correct pieces (X, O). and so on. Call game state to display a new game is starting <code>game.gameState.start(game.players.currentTurn)</code> passing it the player that has the first turn.</p>\n<p>How you break the task up into abstract concepts and associated objects is up to you, what is best is a skill to learn. One object to do all things is the wrong path to good OOP</p>\n<p>But be warned, breaking a task into to too many parts can make the task of managing them all become larger and more complex that the problem you are solving (namely play a game). Objects should make things easier, not harder.</p>\n<h2>Three questions</h2>\n<blockquote>\n<p><em>&quot;How is the use of querySelector (mainly the use of it in the last 3 game conclusion check functions)?&quot;</em></p>\n</blockquote>\n<ol>\n<li>Your use of <code>querySelector</code> is poor. See answer to next question.</li>\n</ol>\n<blockquote>\n<p><em>&quot;Should I have attached them to a variable first?&quot;</em></p>\n</blockquote>\n<ol start=\"2\">\n<li><p>Yes and no. Looking at your code you have not shown any detailed use of arrays. The cells of the board should be stored in an array and encapsulated by an object. Often in tic-tac-toe people use a 2D array. Detailing how to use arrays is a little outside the scope of CR answers.</p>\n<p>MDN provides many resources and are a good place to get a start in JS. For more on <a href=\"https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Arrays\" rel=\"noreferrer\">arrays</a>. There are also many other resources there to help you get started as a coder</p>\n</li>\n</ol>\n<blockquote>\n<p><em>&quot;Is there anything I could have done better?&quot;</em></p>\n</blockquote>\n<ol start=\"3\">\n<li><p>Again.. Yes and sort of.</p>\n<ul>\n<li><p><strong>The Yes</strong> The first part of this code review highlights some of the more important things to do better. As for the rest there is a long list of things that could be better, many of these points are still hotly debated amongst professional coders. More often than not better is a personal preference. Could you do better, yes, everyone can always do better.</p>\n</li>\n<li><p><strong>The sort of</strong> Does the code work? Have you tried your best to use game in a way that breaks it? Did you encounter bugs and did you fix them? If you answer yes to these questions then you have done very well.</p>\n<p>Coding is hard, some people will never be coders, others take to it like ducks to water. Though your the code is not up to professional standards getting it to work bug free without fear of a user doing the wrong thing at the wrong time is a clear sign that you have what is needed to be a great coder.</p>\n<p>There is a lot to learn, and you must master the basics of problem solving using the features of the language you choose to start with. There is only one way to do that and that is by gaining experience as you code.</p>\n</li>\n</ul>\n</li>\n</ol>\n<h2>Template object?</h2>\n<blockquote>\n<p><em>&quot;Was the choice to make the game a template object pointless/more damaging than otherwise?&quot;</em></p>\n</blockquote>\n<p>I am not that sure what you mean by template object, something I am unfamiliar with apart from its literal meaning.</p>\n<p>If you mean that the defined object <code>TicTacToe</code> is a template for other games then yes pointless, not damaging.</p>\n<h2>Conclusion</h2>\n<p>As a beginner you have done well, and if you enjoy coding then do keep at it, because enjoying something that can also be a career is a priceless asset to have.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T01:35:41.450", "Id": "254116", "ParentId": "254112", "Score": "5" } } ]
{ "AcceptedAnswerId": "254116", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-30T22:10:28.927", "Id": "254112", "Score": "5", "Tags": [ "javascript", "beginner", "html", "css", "tic-tac-toe" ], "Title": "Tic-Tac-Toe Game vanilla JS/CSS" }
254112
<p><code>input: 800(days)</code></p> <pre><code>output: 2 years 2 months 10 days </code></pre> <p>Conditions are required to match: <code>only to facilitate the calculation, consider the whole year with 365 days and 30 days every month. In the cases of test there will never be a situation that allows 12 months and some days, like 360, 363 or 364.</code></p> <p>I have solved this problem in this way:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;math.h&gt; int main(void){ int n; double years; double months; double days; scanf(&quot;%d&quot;,&amp;n); years = n / 365.0; double fractional, integer; //To split the floating value(years) into the integer and decimal fractional = modf (years, &amp;integer); //To get months from here months = 12.1666666667 * fractional; //To take nearest 8 digits after the decimal double d = round (months * 100000000.0)/100000000.0; double fractionalUpdate, integerUpdate; //To split the floating value(months) into the integer and decimal fractionalUpdate = modf (d,&amp;integerUpdate); //To get days from here days = (365 * fractionalUpdate) / 12.1666666667; printf(&quot;%g years\n&quot;,integer); printf(&quot;%g months\n&quot;,integerUpdate); printf(&quot;%g days\n&quot;,days); } </code></pre> <p>My purpose is: Would you propose any simplification from this solution? Would I face any kind of problem for some conditions?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T07:53:24.247", "Id": "501174", "Score": "3", "body": "What are the expected inputs? What should the desired behaviour be when unexpected input is encountered?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T10:50:42.503", "Id": "501182", "Score": "4", "body": "What kind of year always has 365.0 days?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T12:18:12.080", "Id": "501186", "Score": "2", "body": "Mandatory watching: https://www.youtube.com/watch?v=-5wpm-gesOY" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T03:21:50.970", "Id": "501233", "Score": "0", "body": "@TobySpeight, Sorry for the late reply sir, I have updated my question regarding conditions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T03:22:24.427", "Id": "501235", "Score": "0", "body": "@G.Sliepen Ok Sir, I am going to watch it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T03:30:46.980", "Id": "501237", "Score": "0", "body": "@Mast Sorry for the late reply sir. I did not check in this solution when unexpected input is encountered. Would you please explain how can I handle the situation when unexpected input is encountered?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T06:33:53.517", "Id": "501246", "Score": "2", "body": "Is this homework?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T09:53:12.620", "Id": "501249", "Score": "0", "body": "@Reinderien Obviously not." } ]
[ { "body": "<h2>Intractability</h2>\n<p>Think hard about what's happening here - you're asking that the user provide a timedelta or time interval that is divorced from absolute time, e.g. 800 days. However, you do not ask that it be specified as &quot;800 days in 2020&quot; or &quot;800 days in 1974&quot;. So:</p>\n<p>It is impossible to map a number of days to a number of years, months and days unless, in practice, you ask for either a start point or end point of the given period.</p>\n<p>Ignoring daylight savings time, unequal-length months, leap years etc. it's not even exactly possible to map an arbitrary interval to a count of hours, minutes and seconds, because leap seconds are also sometimes introduced, though this effect is minor.</p>\n<p>Long story short, for this program to produce meaningful results, ask for &quot;number of days past a given timestamp&quot;.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T03:35:52.410", "Id": "501238", "Score": "0", "body": "Sorry for the late reply sir. I have updated my question. I hope now everything is going to be clear. Check out the 'Conditions are required to match' section." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T15:07:58.107", "Id": "254136", "ParentId": "254119", "Score": "3" } }, { "body": "<p>I think you just invented the 12x30 + 5 calender: this gives you a fractional month (5 extra days in between the years), and your seasons will drift 1 day every 4 years.</p>\n<pre><code>365\n1 years\n0 months\n0 days\n\n364\n0 years\n12 months\n4 days\n</code></pre>\n<p>12 months, 4 days is quite wrong.</p>\n<p>There is a simpler solution. I think it does make sense to figure out how much 1000 days is in larger units. These &quot;years&quot; and &quot;months&quot; have an average value, based on two facts: earth takes 365.25 days around the sun, and we divide a year into twelve months.</p>\n<pre><code>365\nyears: 0 months: 11 days 30\n366\nyears: 1 months: 0 days 0\n</code></pre>\n<p>Having a non-integer days-per-year also helps conceptually: either you are below or above.</p>\n<p>So for 800 I get 2 days less than your solution:</p>\n<pre><code>800\nyears: 2 months: 2 days 8\n</code></pre>\n<pre><code> #include &lt;stdio.h&gt;\n \n void main(void) {\n double dpy = 365.25; // a bit less, actually\n int mpy = 12;\n double dpm = dpy / mpy;\n \n int n;\n scanf(&quot;%d&quot;, &amp;n);\n \n int years = n / dpy;\n int months = n / dpm - years*mpy;\n int days = n - years*dpy - months*dpm;\n\n printf(&quot;years: %d months: %d days %d\\n&quot;, years, months, days);\n }\n</code></pre>\n<p>An illustration:</p>\n<pre><code> 800-365-365-30-30\n 10\n 800-365.25-365.25-30.5-30.5\n 8.50\n\n</code></pre>\n<p>The numbers are not precise. Still it means you have to say</p>\n<p><code>800 days = 2 years, 2 months, 2 days and 12 hours</code></p>\n<p>which is quite paradoxical on first view. The way I started my program I think I lost these hours forever...</p>\n<hr />\n<p>With <code>dpy = 365.2425</code> I also get 400:0:0 for 146097 days. With the full quarter it was 399:11:27. This 4-100-400-rule can get you far. And <code>.2425</code> is not a funny fraction, but very logical:</p>\n<pre><code>1/4 = 0.25, minus 1/100 is 0.24\n1/400= 0.0025\nAdd:\n 0.24\n+0.0025\n</code></pre>\n<p><strong>HAPPY NEW 365.2425 2021</strong></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T03:56:05.403", "Id": "501240", "Score": "0", "body": "Sorry for the late reply sir. 'I think you just invented the 12x30 + 5 calender:'. Your assumption is hundred percent right. I have updated my question. You can check the 'Conditions are required to match' section." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T12:01:23.993", "Id": "501255", "Score": "0", "body": "The old Egyptians had a 360+5 days year. I assume they handled it more elegant than that. What is your definition of year? Is the title not a bit misleading?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T21:09:05.263", "Id": "254152", "ParentId": "254119", "Score": "2" } }, { "body": "<blockquote>\n<p>Would you propose any simplification from this solution?</p>\n</blockquote>\n<p>C has <code>mktime()</code> to help convert days into year, month, day.</p>\n<p>Consider using standard library functions. OP's approach is fragile.</p>\n<p>I see this goes against the task's &quot;only to facilitate the calculation, consider the whole year with 365 days and 30 days every month&quot;, yet I see that requirement as counter idiomatic. Rather I encourage date manipulation code should consider standard functions first.</p>\n<blockquote>\n<p>Would I face any kind of problem for some conditions?</p>\n</blockquote>\n<p>Usually using integer math is better for an integer problem, rather than having to cope with various subtleties of floating point math. Research <code>%, /</code> and maybe even <code>div()</code>.</p>\n<hr />\n<p>Slight variation occur depending on your reference date.</p>\n<p>For &quot;Age&quot;, I'd use one's birthday as the reference date.</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;time.h&gt;\n\n// Return error flag\nint days_to_ymd(int *year, int *month, int *day, int days) {\n // TBD, extend functionality to handle negative days.\n if (days &lt; 0) {\n return 1;\n }\n\n const struct tm ref_2001Jan1 = {.tm_year = 2001 - 1900, .tm_mon = 1 - 1,\n .tm_mday = 1, // Maye use subject's birthday?\n .tm_hour = 12}; // Use Noon to avoid DST and time zone shift issues\n struct tm ts = ref_2001Jan1;\n\n // Add the days\n ts.tm_mday += days;\n\n // mktime() re-adjusts it members to their primary range. \n if (mktime(&amp;ts) == -1) {\n return 1;\n }\n\n *year = ts.tm_year - ref_2001Jan1.tm_year;\n // More code needed if ref month is not January to handle wrap around.\n *month = ts.tm_mon - ref_2001Jan1.tm_mon;\n // More code needed if ref day is not 1st to handle wrap around.\n *day = ts.tm_mday - ref_2001Jan1.tm_mday;\n return 0;\n}\n</code></pre>\n<p>Test</p>\n<pre><code>void test_days_to_ymd(int days) {\n int year, month, day;\n int err = days_to_ymd(&amp;year, &amp;month, &amp;day, days);\n if (err) {\n printf(&quot;Error: %d days\\n&quot;, days);\n } else {\n printf(&quot;%9d days --&gt; %3d years, %2d months, %2d days\\n&quot;, days, year, month,\n day);\n }\n}\n\nint main(void) {\n test_days_to_ymd(0);\n test_days_to_ymd(31);\n test_days_to_ymd(365);\n test_days_to_ymd(365 * 4 + 1);\n test_days_to_ymd(27375 /* Average lifespan (est) */);\n test_days_to_ymd(100 * (365 * 4 + 1) - 3);\n}\n</code></pre>\n<p>Output</p>\n<pre><code> 0 days --&gt; 0 years, 0 months, 0 days\n 31 days --&gt; 0 years, 1 months, 0 days\n 365 days --&gt; 1 years, 0 months, 0 days\n 1461 days --&gt; 4 years, 0 months, 0 days\n 27375 days --&gt; 74 years, 11 months, 13 days\n 146097 days --&gt; 400 years, 0 months, 0 days\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T21:40:33.123", "Id": "254154", "ParentId": "254119", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T05:58:03.920", "Id": "254119", "Score": "0", "Tags": [ "c" ], "Title": "Age in days in c" }
254119
<pre><code>public sealed class Client { private Simulation _simulation; public Client(ITickProvider tickProvider, ICommandReceiver commandReceiver) { _simulation = new Simulation(); tickProvider.Tick += HandleTick; commandReceiver.CommandReceived += HandleCommandReceived; } private void HandleTick () { //Distribute tick to _simulation } private void HandleCommandReceived(Command command) { //Inject command to _simulation } } </code></pre> <p><code>Client</code> operates a multithreaded Simulation, distributing ticks and external input to the Simulation.</p> <p><code>ITickProvider</code> provides a Tick event that runs every e.g. fixed interval, button click, etc..</p> <p><code>ICommandReceiver</code> receives external input (Commands); i.e. User input, server input, serialized input, etc..</p> <p>Because the interfaces' implementations are usually exclusive, I decided to make Client sealed and inject the functionality with the constructor. This also helps with controlling thread-sensitive access to Simulation.</p> <p>What is the pattern of composing a sealed class with modular interfaces? Is this a well-known pattern and if so, have I implemented it correctly?</p>
[]
[ { "body": "<p>It depends on the actual class requirements along with the overall code factors.\nFor instance,</p>\n<ul>\n<li>Do you think that <code>Client</code> class can be extended in the future? <em>(not by inheritance surely since it's <code>sealed</code>)</em>.</li>\n<li>How often this class is going to be called?</li>\n<li>How simple you need to simplify the initiation of this class? <em>(as a way to automate handling of its dependencies)</em></li>\n<li>Are these interfaces going to be recalled or extended in any other way except this class ?</li>\n<li>Do interfaces have many <code>unneeded</code> members? <em>(say you only need some members and not all of them).</em></li>\n</ul>\n<p>You must investigate that, and decide the best approach that would be feasible to your current project.</p>\n<p>As kick-starter that would give you some ideas after looking at your class, and interfaces, without knowing your actual implementations, I could say the safest way is to create <code>ClientHandler</code> and pass it to the constructor instead. something like this :</p>\n<pre><code>public class ClientHandler : ITickProvider, ICommandReceiver\n{\n private readonly Simulation _simulation;\n public ClientHandler(Simulation simulation)\n {\n if(simulation == null)\n {\n throw new ArgumentNullExecption(nameof(simulation));\n }\n _simulation = simulation;\n }\n \n // ITickProvider implementation\n // Do the handeling here \n public void Tick() { ... }\n\n // ICommandReceiver implementation\n // Do the handeling here \n public void CommandReceived() { ... }\n}\n\npublic sealed class Client\n{\n private readonly ClientHandler _handler; \n \n public Client(ClientHandler clientHandler)\n {\n if(clientHandler == null)\n {\n throw new ArgumentNullExecption(nameof(clientHandler));\n }\n \n _handler = clientHandler; \n }\n}\n</code></pre>\n<p>This is better, because you'll have more room in your code to be able to control the handler and the client side-by-side, with a benefit of extending the handler as per requirement. Also, Implementing interfaces would ease your work, especially if your work includes <code>Reflection</code>. You can also keep the handler as <code>abstract class</code> and inherit it to have more customizable handlers.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-03T20:50:48.023", "Id": "254286", "ParentId": "254120", "Score": "1" } } ]
{ "AcceptedAnswerId": "254286", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T06:26:02.373", "Id": "254120", "Score": "0", "Tags": [ "c#", "object-oriented", "design-patterns", "classes", "interface" ], "Title": "Composing functionality of sealed class with interfaces" }
254120
<p>I am trying to implement a sub-string extractor with &quot;start keyword&quot; and &quot;end keyword&quot; and the extracted result is from (but excluded) the given start keyword to (but excluded) end keyword. For example:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">Input String</th> <th style="text-align: center;">Start Keyword</th> <th style="text-align: center;">End Keyword</th> <th style="text-align: center;">Output</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">&quot;C# was developed around 2000 by Microsoft as part of its .NET initiative&quot;</td> <td style="text-align: center;">&quot;&quot;(empty string)</td> <td style="text-align: center;">&quot;&quot;(empty string)</td> <td style="text-align: center;">&quot;C# was developed around 2000 by Microsoft as part of its .NET initiative&quot;</td> </tr> <tr> <td style="text-align: center;">&quot;C# was developed around 2000 by Microsoft as part of its .NET initiative&quot;</td> <td style="text-align: center;">&quot;&quot;(empty string)</td> <td style="text-align: center;">&quot;.NET&quot;</td> <td style="text-align: center;">&quot;C# was developed around 2000 by Microsoft as part of its&quot;</td> </tr> <tr> <td style="text-align: center;">&quot;C# was developed around 2000 by Microsoft as part of its .NET initiative&quot;</td> <td style="text-align: center;">&quot;C#&quot;</td> <td style="text-align: center;">&quot;&quot;(empty string)</td> <td style="text-align: center;">&quot;was developed around 2000 by Microsoft as part of its .NET initiative&quot;</td> </tr> <tr> <td style="text-align: center;">&quot;C# was developed around 2000 by Microsoft as part of its .NET initiative&quot;</td> <td style="text-align: center;">&quot;C#&quot;</td> <td style="text-align: center;">&quot;.NET&quot;</td> <td style="text-align: center;">&quot;was developed around 2000 by Microsoft as part of its&quot;</td> </tr> <tr> <td style="text-align: center;">&quot;C# was developed around 2000 by Microsoft as part of its .NET initiative&quot;</td> <td style="text-align: center;">&quot;.NET&quot;</td> <td style="text-align: center;">&quot;&quot;(empty string)</td> <td style="text-align: center;">&quot;initiative&quot;</td> </tr> <tr> <td style="text-align: center;">&quot;C# was developed around 2000 by Microsoft as part of its .NET initiative&quot;</td> <td style="text-align: center;">&quot;&quot;(empty string)</td> <td style="text-align: center;">&quot;C#&quot;</td> <td style="text-align: center;">&quot;&quot;(empty string)</td> </tr> <tr> <td style="text-align: center;">&quot;C# was developed around 2000 by Microsoft as part of its .NET initiative&quot;</td> <td style="text-align: center;">&quot;.NET&quot;</td> <td style="text-align: center;">&quot;C#&quot;</td> <td style="text-align: center;">&quot;&quot;(empty string)</td> </tr> </tbody> </table> </div> <p><strong>The experimental implementation</strong></p> <p>The experimental implementation is as below.</p> <pre><code>private static string GetTargetString(string stringInput, string startKeywordInput, string endKeywordInput) { int startIndex; if (String.IsNullOrEmpty(startKeywordInput)) { startIndex = 0; } else { if (stringInput.IndexOf(startKeywordInput) &gt;= 0) { startIndex = stringInput.IndexOf(startKeywordInput) + startKeywordInput.Length; } else { return &quot;&quot;; } } int endIndex; if (String.IsNullOrEmpty(endKeywordInput)) { endIndex = stringInput.Length; } else { if (stringInput.IndexOf(endKeywordInput) &gt; startIndex) { endIndex = stringInput.IndexOf(endKeywordInput); } else { return &quot;&quot;; } } // Check startIndex and endIndex if (startIndex &lt; 0 || endIndex &lt; 0 || startIndex &gt;= endIndex) { return &quot;&quot;; } if (endIndex.Equals(0).Equals(true)) { endIndex = stringInput.Length; } int TargetStringLength = endIndex - startIndex; return stringInput.Substring(startIndex, TargetStringLength).Trim(); } </code></pre> <p><strong>Test cases</strong></p> <pre><code>string test_string1 = &quot;C# was developed around 2000 by Microsoft as part of its .NET initiative&quot;; Console.WriteLine(GetTargetString(test_string1, &quot;&quot;, &quot;&quot;)); Console.WriteLine(GetTargetString(test_string1, &quot;&quot;, &quot;.NET&quot;)); Console.WriteLine(GetTargetString(test_string1, &quot;C#&quot;, &quot;&quot;)); Console.WriteLine(GetTargetString(test_string1, &quot;C#&quot;, &quot;.NET&quot;)); Console.WriteLine(GetTargetString(test_string1, &quot;.NET&quot;, &quot;&quot;)); Console.WriteLine(GetTargetString(test_string1, &quot;&quot;, &quot;C#&quot;)); Console.WriteLine(GetTargetString(test_string1, &quot;.NET&quot;, &quot;C#&quot;)); </code></pre> <p>The output of the above test cases.</p> <pre><code>C# was developed around 2000 by Microsoft as part of its .NET initiative C# was developed around 2000 by Microsoft as part of its was developed around 2000 by Microsoft as part of its .NET initiative was developed around 2000 by Microsoft as part of its initiative </code></pre> <p>If there is any possible improvement, please let me know.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T09:17:56.547", "Id": "501175", "Score": "2", "body": "Why not also provide an optional https://docs.microsoft.com/en-us/dotnet/api/system.stringcomparison parameter?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T21:00:27.220", "Id": "501301", "Score": "1", "body": "It is good practice to specify culture when doing string operations, like ```string.IndexOf```" } ]
[ { "body": "<p>Maybe the last <code>if</code>-statement could be simplified by removing the <code>Equals(true)</code>, for <code>Equals(0)</code> already returns a bool, doesn’t it?</p>\n<p>Edit:<br>\nActually, I think you could skip the whole if block because if <code>endIndex</code> is 0 it couldn’t bypass the <code>if</code>-statement before, could it?</p>\n<p>If <code>startIndex</code> is 0 empty string will be returned <code>startIndex &gt;= endIndex</code> .</p>\n<p>If <code>startIndex</code> is less than 0 then empty string will be returned.</p>\n<p>So how could endIndex be 0 at the last <code>if</code>-statement?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T13:56:45.230", "Id": "254133", "ParentId": "254121", "Score": "1" } }, { "body": "<p>I tend to have the &quot;error handling&quot; code at the beginning of the method, which usually makes the rest of the method more simple.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private static string GetTargetString(string input, string startKeyword, string endKeyword, StringComparison comparer)\n{\n if (!string.IsNullOrEmpty(startKeyword) &amp;&amp; input.IndexOf(startKeyword, comparer) &lt; 0) return &quot;&quot;;\n if (!string.IsNullOrEmpty(endKeyword) &amp;&amp; input.IndexOf(endKeyword, comparer) &lt; 0) return &quot;&quot;;\n\n var startIndex = string.IsNullOrEmpty(startKeyword)\n ? 0\n : input.IndexOf(startKeyword, comparer) + startKeyword.Length;\n\n var endIndex = string.IsNullOrEmpty(endKeyword) \n ? input.Length \n : input.IndexOf(endKeyword, comparer);\n\n if (startIndex &lt; 0 || endIndex &lt; 0 || startIndex &gt;= endIndex) return &quot;&quot;;\n\n return input.Substring(startIndex, endIndex - startIndex).Trim();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T21:17:24.603", "Id": "254191", "ParentId": "254121", "Score": "2" } } ]
{ "AcceptedAnswerId": "254133", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T08:37:17.897", "Id": "254121", "Score": "1", "Tags": [ "c#", "strings" ], "Title": "A Sub-string Extractor with Specific Keywords Parameter Implementation in C#" }
254121
<p>Please find the following scenario, I've dynamic JS date format string from API but I am looking for the best way to convert the format that accepts in PHP date format. For now, I wrote it my own way but I doubt there should be a standard solution.</p> <p>JS time format: YYYY-MM-DD / YYYY/MM/DD <br/> Need PHP format: Y-m-d / Y/m/d</p> <p>I've written the solution this way, please let me know if you find something else in a better way than this.</p> <pre><code>function dateFormatStringConvert(string $format) : string { foreach (['-', '/'] as $operator) { if (strpos($format, $operator) !== false) { return implode($operator, array_map(function ($piece){ return $piece[0]=='M' || $piece[0]=='D' ? strtolower($piece[0]) : $piece[0]; }, explode($operator, $format))); } } return 'm-d-Y'; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T10:01:35.437", "Id": "501178", "Score": "0", "body": "is the js code under your control?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T10:08:55.850", "Id": "501180", "Score": "0", "body": "No. we are using the service of somebody else." } ]
[ { "body": "<p>I don't see the need to do so much dynamic work. I would establish a lookup array to access. This will be clean, direct, and easy to maintain. If the incoming format is not found, just fallback to <code>m-d-Y</code> using the null coalescing operator.</p>\n<pre><code>private $formatLookup = [\n 'YYYY-MM-DD' =&gt; 'Y-m-d',\n 'YYYY/MM/DD' =&gt; 'Y/m/d',\n];\n\npublic function dateFormatStringConvert(string $format) : string\n{\n return $this-&gt;formatLookup[$format] ?? 'm-d-Y';\n}\n</code></pre>\n<p>With this setup, you never need to touch the processing method, you only need to maintain the lookup array.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T06:41:13.050", "Id": "254166", "ParentId": "254123", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T09:40:47.830", "Id": "254123", "Score": "0", "Tags": [ "php", "datetime", "formatting" ], "Title": "JavaScript date format string to php date format string convert" }
254123
<p>Please review my ostream logger, ologger, which attempts to make logging as easy as using cout. The ostream operator&lt;&lt; is leveraged so that anything that can be logged to cout can be logged to this logger. To log custom classes/structs the user would need to overload operator&lt;&lt; in their custom class.</p> <p>Any feedback would be much appreciated.</p> <p>ologger.hpp:</p> <pre><code>/* ologger or ostream logger, a logger as convenient as using std::cout Features: 1. logging as per cout/cerr/clog ie logger.error &lt;&lt; &quot;i=&quot; &lt;&lt; 3 &lt;&lt; std::endl; 2. logging obeys log level set. If you set log level error, then logging to info or debug is a no-op. 3. log rotation - specify a maximum file size in bytes and maximum number of files 4. Configure via path, file name prefix and file name extension. End a line with std::endl Example usage: ologger logger(&quot;.&quot;, &quot;projectz&quot;, &quot;log&quot;, 10000, 5, ologger::log_level::LOG_INFO); // nothing should be logged because we have set logger at ERROR level only logger.debug &lt;&lt; &quot;low level developer data, X level exceeded, x=&quot; &lt;&lt; 9.75 &lt;&lt; std::endl; // nothing should be logged because we have set logger at ERROR level only logger.info &lt;&lt; &quot;informational stuff about sending x protocol data to server, bytes transferred: &quot; &lt;&lt; 1250 &lt;&lt; std::endl; // this should be logged logger.error &lt;&lt; &quot;!!! Invalid Data Received !!!&quot; &lt;&lt; std::endl; */ #ifndef OLOGGER_HPP_ #define OLOGGER_HPP_ #include &lt;string&gt; #include &lt;iostream&gt; #include &lt;fstream&gt; class ologger { public: using endl_type = std::ostream&amp; (std::ostream&amp;); enum class log_level { LOG_NONE, LOG_ERROR, LOG_INFO, LOG_DEBUG }; /* Construct with log files path, file name prefix and suffix, max_file_size in bytes, max_files before rotation and logging level */ ologger(const std::string&amp; path, const std::string&amp; file_prefix, const std::string&amp; file_suffix, size_t max_file_size, size_t max_files, log_level level = log_level::LOG_NONE); // prevent copying object ologger(const ologger&amp;) = delete; ologger(ologger&amp;&amp;) = delete; ologger&amp; operator=(const ologger&amp;) = delete; ologger&amp; operator=(ologger&amp;&amp;) = delete; // debug level logging class Debug { public: Debug(ologger&amp; parent); template&lt;typename T&gt; Debug&amp; operator&lt;&lt; (const T&amp; data) { if (parent_.level_ &gt;= log_level::LOG_DEBUG) { if (start_of_line_) { parent_.prefix_message(); start_of_line_ = false; } parent_.log_stream_ &lt;&lt; data; } return *this; } Debug&amp; operator&lt;&lt;(endl_type endl); private: ologger&amp; parent_; bool start_of_line_; }; // info level logging class Info { public: Info(ologger&amp; parent); template&lt;typename T&gt; Info&amp; operator&lt;&lt; (const T&amp; data) { if (parent_.level_ &gt;= log_level::LOG_INFO) { if (start_of_line_) { parent_.prefix_message(); start_of_line_ = false; } parent_.log_stream_ &lt;&lt; data; } return *this; } Info&amp; operator&lt;&lt;(endl_type endl); private: ologger&amp; parent_; bool start_of_line_; }; // error level logging class Error { public: Error(ologger&amp; parent); template&lt;typename T&gt; Error&amp; operator&lt;&lt; (const T&amp; data) { if (parent_.level_ &gt;= log_level::LOG_ERROR) { if (start_of_line_) { parent_.prefix_message(); start_of_line_ = false; } parent_.log_stream_ &lt;&lt; data; } return *this; } Error&amp; operator&lt;&lt;(endl_type endl); private: ologger&amp; parent_; bool start_of_line_; }; private: size_t changeover_if_required(); const std::string to_string(ologger::log_level level); void prefix_message(); void make_logger(const std::string&amp; path, const std::string&amp; file_prefix, const std::string&amp; file_suffix); const std::string path_; const std::string file_prefix_; const std::string file_suffix_; size_t max_file_size_; size_t max_files_; log_level level_; std::fstream log_stream_; public: Debug debug; Info info; Error error; }; #endif // OLOGGER_HPP_ </code></pre> <p>ologger.cpp:</p> <pre><code>#ifdef _WIN32 #define _CRT_SECURE_NO_WARNINGS #define SEPARATOR ('\\') #else #define SEPARATOR ('/') #endif #include &quot;ologger.hpp&quot; #include &lt;cstring&gt; #include &lt;ctime&gt; #include &lt;chrono&gt; #include &lt;stdexcept&gt; // domain_error for bad path static size_t get_next_file_suffix(const std::string&amp; path) { size_t next { 0 }; std::fstream fstrm(path + SEPARATOR + &quot;next&quot;, std::ofstream::in | std::ofstream::out); if (fstrm) { fstrm &gt;&gt; next; } return next; } // convert blank string to . and remove trailing path separator static const std::string make_path(const std::string&amp; original_path) { std::string massaged_path{ original_path }; if (massaged_path.empty()) { massaged_path = &quot;.&quot;; } if (massaged_path[massaged_path.size() - 1] == SEPARATOR) { massaged_path = massaged_path.substr(0, massaged_path.size() - 1); } return massaged_path; } const std::string ologger::to_string(ologger::log_level level) { switch (level) { case ologger::log_level::LOG_NONE: return &quot;&quot;; case ologger::log_level::LOG_ERROR: return &quot;error&quot;; case ologger::log_level::LOG_INFO: return &quot;info&quot;; case ologger::log_level::LOG_DEBUG: return &quot;debug&quot;; default: return &quot;&quot;; } } void ologger::make_logger(const std::string&amp; path, const std::string&amp; file_prefix, const std::string&amp; file_suffix) { size_t next_id = get_next_file_suffix(path); log_stream_.open(path + SEPARATOR + file_prefix + std::to_string(next_id) + &quot;.&quot; + file_suffix, std::ofstream::out | std::ofstream::app); if (!log_stream_.good()) { throw std::domain_error(&quot;ologger error: unable to open log file: &quot; + path + SEPARATOR + file_prefix + std::to_string(next_id) + &quot;.&quot; + file_suffix); } } ologger::ologger(const std::string&amp; path, const std::string&amp; file_prefix, const std::string&amp; file_suffix, size_t max_file_size, size_t max_files, log_level level) : path_(make_path(path)), file_prefix_(file_prefix), file_suffix_(file_suffix), max_file_size_(max_file_size), max_files_(max_files), level_(level), debug(*this), info(*this), error(*this) { make_logger(path_, file_prefix_, file_suffix); } size_t ologger::changeover_if_required() { size_t next_id{0}; if (log_stream_) { const std::streampos pos = log_stream_.tellp(); if (static_cast&lt;size_t&gt;(pos) &gt; max_file_size_) { next_id = get_next_file_suffix(path_); next_id = (next_id + 1) % max_files_; std::fstream fstrm(path_ + SEPARATOR + &quot;next&quot;, std::ofstream::out | std::ofstream::trunc); if (fstrm) { fstrm &lt;&lt; next_id; } log_stream_.close(); log_stream_.clear(); // if next file exists, delete so we start with empty file const std::string next_file{ path_ + SEPARATOR + file_prefix_ + std::to_string(next_id) + &quot;.&quot; + file_suffix_ }; std::remove(next_file.c_str()); log_stream_.open(next_file, std::ofstream::out | std::ofstream::app); } } return next_id; } std::string get_time_stamp() { const auto now = std::chrono::system_clock::now(); const std::time_t now_time_t = std::chrono::system_clock::to_time_t(now); char timestamp[50]{}; std::strftime(timestamp, sizeof(timestamp), &quot;%Y-%m-%d,%H:%M:%S&quot;, std::localtime(&amp;now_time_t)); const int millis = std::chrono::time_point_cast&lt;std::chrono::milliseconds&gt;(now).time_since_epoch().count() % 100; snprintf(timestamp + strlen(timestamp), sizeof(timestamp) - strlen(timestamp), &quot;.%03d,&quot;, millis); return timestamp; } void ologger::prefix_message() { log_stream_ &lt;&lt; get_time_stamp() &lt;&lt; to_string(level_) &lt;&lt; ','; } //inner logging level classes for ostream overloading ologger::ologger::Debug::Debug(ologger&amp; parent) : parent_(parent), start_of_line_(true) {} ologger::Debug&amp; ologger::Debug::operator&lt;&lt;(endl_type endl) { if (parent_.level_ &gt;= log_level::LOG_INFO) { parent_.log_stream_ &lt;&lt; endl; } parent_.changeover_if_required(); start_of_line_ = true; return *this; } ologger::ologger::Info::Info(ologger&amp; parent) : parent_(parent), start_of_line_(true) {} ologger::Info&amp; ologger::Info::operator&lt;&lt;(endl_type endl) { if (parent_.level_ &gt;= log_level::LOG_INFO) { parent_.log_stream_ &lt;&lt; endl; } parent_.changeover_if_required(); start_of_line_ = true; return *this; } ologger::ologger::Error::Error(ologger&amp; parent) : parent_(parent), start_of_line_(true) {} ologger::Error&amp; ologger::Error::operator&lt;&lt;(endl_type endl) { if (parent_.level_ &gt;= log_level::LOG_ERROR) { parent_.log_stream_ &lt;&lt; endl; } parent_.changeover_if_required(); start_of_line_ = true; return *this; } </code></pre> <p>example main.cpp to exercise:</p> <pre><code>#include &quot;ologger.hpp&quot; int main() { ologger logger(&quot;.&quot;, &quot;projectz&quot;, &quot;log&quot;, 10000, 5, ologger::log_level::LOG_ERROR); // nothing should be logged because we have set logger at ERROR level only logger.debug &lt;&lt; &quot;low level developer data, X level exceeded, x=&quot; &lt;&lt; 9.75 &lt;&lt; std::endl; // nothing should be logged because we have set logger at ERROR level only logger.info &lt;&lt; &quot;informational stuff about sending x protocol data to server, bytes transferred: &quot; &lt;&lt; 1250 &lt;&lt; std::endl; // this should be logged logger.error &lt;&lt; &quot;!!! Invalid Data Received !!!&quot; &lt;&lt; std::endl; for (int i = 0; i &lt; 10000; i++) { logger.error &lt;&lt; &quot;Beware the Ides of March, i=&quot; &lt;&lt; i &lt;&lt; std::endl; } } </code></pre> <p>Makefile:</p> <pre><code>CFLAGS=-ggdb3 -Wall -Werror -pedantic -std=c++11 logger: ologger.cpp main.cpp g++ -o logger $(CFLAGS) main.cpp ologger.cpp </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T15:58:41.850", "Id": "501191", "Score": "1", "body": "Why not a `std::clog`-style logger? ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T20:11:00.017", "Id": "501207", "Score": "0", "body": "I would expect a logger class to send the data to the system log." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T20:16:39.457", "Id": "501208", "Score": "0", "body": "The problem here (that most system logger handle) is if the logging level is not matched then no work is done. Here you are still doing work when logging level is created then simply discarding that output when operator<< is called. So you are still forcing the application to crate the formatted message (which is wasted work)." } ]
[ { "body": "<p>There's very little difference between <code>Debug</code>, <code>Info</code> and <code>Error</code>; to me it looks like those three can be a single class, with only one extra member (to store the logging threshold).</p>\n<p>The whole business of log rotation seems to be duplicating standard utilities such as <code>logrotate</code>. I recommend doing one thing and doing it well, rather than sprawling over several responsibilities like that.</p>\n<p>Talking of which, it would have been nice to include an adapter to <code>syslog()</code>, which instantly gives the ability to log to files (with rotation), to network, or to database, without any extra code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T16:05:18.463", "Id": "254139", "ParentId": "254134", "Score": "5" } }, { "body": "<p>One of the main problems of <code>cout</code> is that it is not suitable for multithreading logging, as characters from different prints might interleave. It can be fixed without syntax change (with some trickery) by making streaming operation return a handle that can be further streamed, and that locks the logger's mutex in constructor and releases in destructor.</p>\n<p>The other problem is that <code>cout</code> is inconvenient for logging, as its formatting is poorly designed to begin with. Check out the <code>fmt</code> open source library for better alternatives. Its primary function, <code>format</code>, is included in C++20.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T16:28:28.997", "Id": "254140", "ParentId": "254134", "Score": "2" } } ]
{ "AcceptedAnswerId": "254139", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T14:39:32.847", "Id": "254134", "Score": "1", "Tags": [ "c++", "logging" ], "Title": "cout style logger in C++" }
254134
<p>I'm writing a multi-threaded program where some external part of the program needs access to a large piece of data that's controlled by my class. I'm trying to return a reference to this data in a thread-safe way.</p> <pre><code>class Chunk { public: Chunk(){ chunkData = std::make_shared&lt;vector&lt;XMFLOAT3&gt;&gt;(); chunkMutex = std::make_shared&lt;std::mutex&gt;(); }; struct LockedData { LockedData(std::vector&lt;float&gt; const&amp; d, std::mutex&amp; mtx) : data(d), lk(mtx) {}; std::vector&lt;XMFLOAT3&gt; const&amp; data; private: std::lock_guard&lt;mutex&gt;lk; }; inline LockedData const&amp;&amp; RequestChunkData()const { return LockedData(*chunkData,chunkMutex); }; private: mutable std::shared_ptr&lt;std::mutex&gt; chunkMutex; std::shared_ptr&lt;vector&lt;float&gt;&gt; chunkData; } </code></pre> <p>Is this over-complicated? will this actually protect my data, and am I using the rvalue references (<code>&amp;&amp;</code>) correctly?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T22:35:29.240", "Id": "501225", "Score": "1", "body": "Welcome to CodeReview@SE. Is this [actual code from a project](https://codereview.stackexchange.com/help/on-topic), yours to put under a Creative Commons licence and change?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T15:26:16.400", "Id": "501277", "Score": "0", "body": "@greybeard thanks for the welcome, this is actual code from a project I am currently writing, it is my code :)" } ]
[ { "body": "<h2>Overview</h2>\n<p>This is not a good solution.</p>\n<p><strike>You are basically setting up a busy wait on the mutex.</strike></p>\n<p>You should be using a condition variable to give the OS the opportunity to reassign the processor to do other work.</p>\n<p>Returning the <code>LockedData</code> is just making this much more complex than it needs to be. Use a get/release set of methods (but make them private) then use RAII to call get/release so that it is done correctly.</p>\n<h2>Code Review</h2>\n<pre><code>class Chunk\n{\n // I put private member variables at the top.\n // When writting the constructor I want to double check that\n // I have correctly set up all members.\n // I put all private methods at the bottom.\n // Not everybody agrees with me on this. But its what I like. :-)\n private: \n mutable std::shared_ptr&lt;std::mutex&gt; chunkMutex;\n std::shared_ptr&lt;vector&lt;float&gt;&gt; chunkData;\n\n public:\n \n // Use the initializer list to set up members\n Chunk(){\n // I don't think these need to be shared dynamically like this.\n // Just make them members of chunk.\n chunkData = std::make_shared&lt;vector&lt;XMFLOAT3&gt;&gt;();\n chunkMutex = std::make_shared&lt;std::mutex&gt;();\n };\n\n\n \n \n // don't use `inline` here (it means nothing).\n // Dont add &amp;&amp; on the return type it does nothing.\n inline LockedData const&amp;&amp; RequestChunkData()const { return LockedData(*chunkData,chunkMutex); };\n \n \n};\n</code></pre>\n<h2>How I would do it:</h2>\n<pre><code>class ChunkAccess;\nclass Chunk\n{\n private:\n \n std::mutex chunkMutex;\n std::condition_variable chunkCondition;\n std::vector&lt;float&gt; chunkData;\n bool inUse; \n\n public:\n Chunk()\n : inUse(false)\n {}\n private:\n friend class ChunkAccess;\n void getUniqueAccesses()\n {\n std::lock_guard&lt;mutex&gt; lock(chunkMutex);\n chunkCondition.wait(lock, [&amp;inUse](){return !inUse;});\n inUse = true;\n }\n void releaseUniqueAccesses()\n {\n std::lock_guard&lt;mutex&gt; lock(chunkMutex);\n inUse = false;\n chunkCondition.notify_one();\n }\n};\nclass ChunkAccess\n{\n private:\n Chunk&amp; chunk;\n public:\n ChunkAccess(Chunk&amp; chunk)\n : chunk(chunk)\n {\n chunk.getUniqueAccesses();\n }\n ~ChunkAccess()\n {\n chunk.releaseUniqueAccesses();\n }\n // Don't want multiple access objects so prevent copy.\n ChunkAccess(ChunkAccess const&amp;) = delete;\n ChunkAccess operator=(ChunkAccess const&amp;) = delete;\n // With a bit of tinkering you can make this moveable.\n\n // Simplify data accesses\n float&amp; operator[](std::size_t index) {return chunk.chunkData[index];}\n float const&amp; operator[](std::size_t index) const {return chunk.chunkData[index];}\n};\n\nint main()\n{\n Chunk data;\n ChunkAccess dataAccess(data);\n\n std::cout &lt;&lt; dataAccess[3] &lt;&lt; &quot;\\n&quot;;\n}\n</code></pre>\n<h2>How I could do (Option 2)</h2>\n<pre><code>class Chunk\n{\n private:\n \n std::mutex chunkMutex;\n std::vector&lt;float&gt; chunkData;\n\n public:\n Chunk()\n : inUse(false)\n {}\n\n void access(std::function&lt;void(std::vector&lt;float&gt;&amp;)&gt; const&amp; action)\n {\n std::lock_guard&lt;mutex&gt; lock(chunkMutex);\n action(chunkData);\n }\n};\n\nint main()\n{\n Chunk data;\n data.access([](std::vector&lt;float&gt;&amp; value){\n std::cout &lt;&lt; value[3] &lt;&lt; &quot;\\n&quot;;\n });\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T21:36:45.180", "Id": "501219", "Score": "0", "body": "There is no busy wait in OP's code. Trying to take a mutex that is already locked will cause the current thread to sleep until the mutex is released. Maybe using a [std::shared_lock](https://en.cppreference.com/w/cpp/thread/shared_lock) would be best here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T23:04:54.747", "Id": "501226", "Score": "0", "body": "@G.Sliepen Removed busy wait statement. There does not seem like a shared lock situation. The OP seems to want exclusive ownership by a thread, which means condition variable is required (unless you want to hold the lock constantly until all your work is done). I suppose we could use an exclusive lock and pass a functor to do the work required." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T23:08:36.003", "Id": "501227", "Score": "0", "body": "There's nothing wrong per se about keeping a lock until all work is done. But I mentioned the shared lock because `RequestChunkData()` is a `const` function, and the resulting `LockedData` points to a `const` vector, so in principle multiple users could have read access simultaneously." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T20:00:57.583", "Id": "254149", "ParentId": "254141", "Score": "1" } }, { "body": "<p><a href=\"/a/254149/170106\">Martin York</a> has done a fine job of reviewing the actual code, so I’ll defer to that, but I want to go a different direction on the design review.</p>\n<h1>Your design concept is unwise</h1>\n<p>Regardless of the details of how it’s actually implemented, the basic concept of your design is not a good one.</p>\n<p>If you have <strong>only a <em>single</em> chunk</strong> in your <strong>entire program</strong>… and there are <strong>no other synchronization objects <em>at all</em> in the entire program</strong>… then you’re fine.</p>\n<p>However….</p>\n<p>The moment you add even a single other synchronization object, you’re playing with fire.</p>\n<p>For example, imagine you have just two chunks in the entire program:</p>\n<pre><code>auto chunk_1 = Chunk{};\nauto chunk_2 = Chunk{};\n\n// thread 1\n{\n auto data_1 = chunk_1.RequestChunkData();\n auto data_2 = chunk_2.RequestChunkData();\n}\n\n// thread 2\n{\n auto data_2 = chunk_2.RequestChunkData();\n auto data_1 = chunk_1.RequestChunkData();\n}\n</code></pre>\n<p>Boom. Deadlock.</p>\n<p>And this could happen with <em>any</em> additional lock in the program, and it won’t always be this obvious:</p>\n<pre><code>auto chunk = Chunk{};\n\n// thread 1: work with data, then print\n{\n auto data = chunk.RequestChunkData();\n\n // do stuff with data\n\n // now print\n auto cout_lock = std::scoped_lock(cout_mutex);\n std::cout &lt;&lt; data;\n}\n\n// thread 2: just printing data\n{\n auto cout_lock = std::scoped_lock(cout_mutex);\n std::cout &lt;&lt; chunk.RequestChunkData();\n}\n</code></pre>\n<p>Boom. Deadlock. (In case it’s not obvious, thread 1 locks the chunk mutex then the cout mutex, while thread 2 locks the cout mutex, then the chunk mutex.)</p>\n<p>The problem is that with your design, it is functionally impossible to write a program that is guaranteed deadlock-free unless you’re really, <em>REALLY</em> careful. Hiding the mutex isn’t doing anyone any favours. If the chunk mutex were available, you could write safe code:</p>\n<pre><code>auto chunk_1 = Chunk{};\nauto chunk_2 = Chunk{};\n\n// thread 1\n{\n auto lock = std::scoped_lock(chunk_1.mutex, chunk_2.mutex);\n\n // safe to work with both chunk 1 and chunk 2\n}\n\n// thread 2\n{\n auto lock = std::scoped_lock(chunk_2.mutex, chunk_1.mutex);\n\n // safe to work with both chunk 1 and chunk 2\n}\n</code></pre>\n<p>I understand the impulse to hide the synchronization stuff so that code <em>looks</em> single-threaded… but I don’t think that’s wise in the general case, for several reasons. One, expanded below, is that I don’t believe that concurrent programming has evolved to the point that there’s a one-size-fits-all solution (and may <em>never</em> get to that point). Another reason is that it takes away power from client code. For example, if you expose the mutex, you can use <code>try_lock()</code> to make an attempt to grab the data, and if it’s not available, do something else instead. (You can also do multi-locking, as illustrated in the code block above.)</p>\n<p>So, if this design concept is wrong, what is the <em>right</em> design?</p>\n<p>Well….</p>\n<h1>There is no one-size-fits-all solution</h1>\n<p>So, your design uses just a mutex. <a href=\"/a/254149/170106\">In his answer, Martin York’s (first) solution adds a condition variable</a>. Question: Is he right? Would the design be better with a condition variable?</p>\n<p>Answer: </p>\n<p>Some areas of computer science are more-or-less “solved”, and we have a single one-size-fits-all solution that we can apply automatically, by-default, in virtually all cases. Like, I remember the bad old days where some programming languages differentiated between “functions” (that return values) and “procedures” (that don’t return values)… now most languages just have functions, and the concept of returning “nothing”, or <code>void</code>. (There are some languages that seem determined to regress toward the primordial ooze, though, like CMake. But don’t get me started on CMake.)</p>\n<p>Concurrent programming is a <em>LOT</em> better than it used to be ~20-25 years ago—it’s no longer the wild west—but it’s still hardly settled science. There is no single, elegant solution that works well in virtually all cases.</p>\n<p>For example: adding a condition variable into the mix would make sense if you expect to be spending long periods waiting on the data to become available. A condition variable sorta… “turns off” a thread completely, making it stop wasting CPU resources until you notify it (or it gets spuriously notified). Sounds great… but that “turning off” isn’t free (nor is the waking up). That’s multiple dives into kernel space. If you expect to be waiting for multiple time slices, then sure, that cost is amortized away.</p>\n<p>But on the other hand, if you <em>don’t</em> expect to be waiting long periods, then a condition variable is overkill. Indeed, a <em>mutex</em> might even be overkill. If you expect very low contention, and wait times that are on the order of a single thread time slice or less, then you could probably get away with just an atomic flag:</p>\n<pre><code>auto _data = std::vector&lt;XMFLOAT3&gt;{};\nauto _flag = std::atomic&lt;bool&gt;{};\n\n// thread 1: the basic idea\n{\n // wait for data to be available...\n auto available = false;\n while (not _flag.compare_exchange_strong(available, true)) // (1)\n // data not available, so just give up our time slice then try again later.\n std::this_thread::yield();\n\n // (1): could also use:\n // _flag.compare_exchange_strong(available, true, std::memory_order_release, std::memory_order_relaxed)\n\n // _data is now safe to use.\n\n // we're done, so:\n _flag = false; // (2)\n\n // (2): could also use:\n // _flag.store(false, std::memory_order_release);\n}\n\n// thread 2: using RAII\nclass chunk_lock\n{\n std::atomic&lt;bool&gt;* _flag = nullptr;\n\npublic:\n chunk_lock(std::atomic&lt;bool&gt;&amp; flag) : _flag{&amp;flag}\n {\n auto available = false;\n while (not _flag-&gt;compare_exchange_strong(available, true, std::memory_order_release, std::memory_order_relaxed))\n std::this_thread::yield();\n }\n\n ~chunk_lock()\n {\n _flag-&gt;store(false, std::memory_order_release);\n }\n\n // no copy/move\n chunk_lock(chunk_lock const&amp;) = delete;\n chunk_lock(chunk_lock&amp;&amp;) = delete;\n\n auto operator=(chunk_lock const&amp;) -&gt; chunk_lock&amp; = delete;\n auto operator=(chunk_lock&amp;&amp;) -&gt; chunk_lock&amp; = delete;\n};\n\n{\n auto lock = chunk_lock(_flag);\n\n // _data is now safe to use.\n\n // auto unlock\n}\n</code></pre>\n<p>In C++20, atomics now have wait/notify semantics, too:</p>\n<pre><code>auto _data = std::vector&lt;XMFLOAT3&gt;{};\nauto _flag = std::atomic&lt;bool&gt;{};\n\n// thread\n{\n _flag.wait(false /*, std::memory_order::acquire */);\n\n // _data is now safe to use.\n\n _flag.store(false /*, std::memory_order::release */);\n _flag.notify_one();\n}\n\n// and of course, you could use an RAII object to do the store and notify\n</code></pre>\n<p>That would probably be the best solution if you expect very little contention for the data, and very short lock times when there is contention.</p>\n<p>But there are still other patterns that might be better still. For example, if you are expecting lots and lots of contention, but <em>most</em> of that will be from threads that just want to <em>read</em> the data, while there will only be a tiny few actually modifying it, then you might consider using a shared mutex:</p>\n<pre><code>auto _data = std::vector&lt;XMFLOAT3&gt;{};\nauto _mutex = std::shared_mutex{};\n\n// read-only thread\n{\n auto lock = std::shared_lock(_mutex);\n\n // this thread now has SHARED access to _data, which it may share with\n // other read-only threads.\n // _data is safe to READ, but not modify.\n\n // auto unlock\n}\n\n// modifying thread\n{\n auto lock = std::scoped_lock(_mutex);\n\n // this thread now has EXCLUSIVE access to _data.\n // _data is safe to read/modify.\n\n // auto unlock\n}\n</code></pre>\n<p>That allows multiple threads to <em>read</em> the data at the same time… but if a thread needs to <em>modify</em> the data, it will get exclusive access. There is no blocking or waiting unless someone actually wants to change the data, which is presumably rare.</p>\n<p>A variant of the <code>shared_mutex</code> <em>without</em> any mutexes is to use an atomic shared pointer to <code>const</code> data. This requires C++20, but it looks like:</p>\n<pre><code>auto p_data = std::atomic&lt;std::shared_ptr&lt;std::vector&lt;XMFLOAT3&gt; const&gt;&gt;{};\n\n// create the chunk data somehow:\np_data = std::make_shared&lt;std::vector&lt;XMFLOAT3&gt;&gt;();\n\n// read-only thread\n{\n auto const p = p_data.load(/* std::memory_order::acquire */); // or maybe even relaxed\n\n // data in *p is now safe to read\n}\n\n// modify thread\n{\n auto new_data = std::shared_ptr&lt;std::vector&lt;XMLFLOAT3&gt; const&gt;{};\n\n if (a_copy_of_the_existing_data_is_needed)\n new_data = p_data.load(/* std::memory_order::acquire */); // or maybe even relaxed\n\n // fill new_data with new data somehow, then\n\n p_data.store(new_data /*, std::memory_order::release */); // or relaxed\n}\n</code></pre>\n<p>(You could do this without <code>atomic&lt;shared_ptr&gt;</code> pre-C++20, but it’ll be harder because you’ll have to manually maintain ref counts.)</p>\n<p>The benefit of doing it this way is that there are (functionally) no locks, no blocking, and no waiting. Every thread will be busy, pretty much 100% of the time. The downside is that some of those threads will be using stale data. Thing is, if you’re allowing the data to be modified at arbitrary points, then that’s more-or-less unavoidable, even if you’re using a <code>shared_mutex</code>. The difference is that with <code>shared_mutex</code>, when the data does need to be modified, everything grinds to a halt until the data is modified, then everything starts up again with the modified data, while with the shared pointer design, nothing ever really stops (so some threads will be working with stale data until the most recent modifications propagate through the system).</p>\n<p>None of the solutions I’ve shown is the “right” solution for all cases. Which one is best for you depends entirely on your situation, which you didn’t describe, so no one can possibly give you the best answer.</p>\n<h1>A better design concept</h1>\n<p>The primary problem with your existing design concept is that it acquires a (hidden) lock, and then lets that lock spill out of its interface. This is why it has deadlock issues; when you do:</p>\n<pre><code>auto chunk = Chunk{};\nauto data = chunk.RequestChunkData();\n\n// !!! THERE IS A LOCK HELD HERE !!!\n\n// other code... that may try to obtain other locks or do other stuff that\n// might lead to a deadlock\n</code></pre>\n<p>One way to “fix” this problem is to say that if the mutex is an implementation detail of the type, so too should be any locking. Locking should not be visible from outside the interface.</p>\n<p>That would mean that any operations you may want to do on a chunk should be class member functions:</p>\n<pre><code>class Chunk\n{\n std::vector&lt;XMFLOAT3&gt; _data;\n std::mutex _mutex;\n\npublic:\n Chunk()\n {\n // initialize somehow\n }\n\n auto transmogrify()\n {\n auto lock = std::scoped_lock(_mutex);\n\n // transmogrify _data here\n }\n\n auto frobnicate()\n {\n auto lock = std::scoped_lock(_mutex);\n\n // frobnicate _data here\n }\n\n auto swizzle()\n {\n auto lock = std::scoped_lock(_mutex);\n\n // swizzle _data here\n }\n\n // for when you actually want to get the raw data itself:\n auto get_data() const\n {\n auto lock = std::scoped_lock(_mutex);\n\n // copy the data, and return it\n auto res = _data;\n return res;\n }\n};\n</code></pre>\n<p>This is safe because you know that within each member function, no other locking or synchronization is being done. There’s no chance of deadlock.</p>\n<p>The downside is that you either have to implement every imaginable algorithm you may conceivably want to use as a member function of the class, <em>OR</em> accept that there will be possibly undesirable locking and unlocking—and the data may potentially change—if you build larger algorithms out of multiple member function calls.</p>\n<p>Martin York suggests a much more flexible solution, roughly:</p>\n<pre><code>class Chunk\n{\n std::vector&lt;XMFLOAT3&gt; _data;\n std::mutex _mutex;\n\npublic:\n Chunk()\n {\n // initialize somehow\n }\n\n template &lt;typename Func&gt;\n auto access(Func&amp;&amp; func)\n {\n auto lock = std::scoped_lock(_mutex);\n\n return func(_data);\n }\n\n template &lt;typename Func&gt;\n auto access(Func&amp;&amp; func) const\n {\n auto lock = std::scoped_lock(_mutex);\n\n return func(_data);\n }\n};\n</code></pre>\n<p>But… eeeeeehhhh… not really keen on this. This is the moral equivalent of using <code>const_cast</code> to cast away <code>const</code>. Sure, it’ll “work” if you’re disciplined and careful. But if you’re allowing arbitrary functions <em><strong>WITHIN YOUR PRIVATE LOCK</strong></em>… you’re just in potential deadlock territory all over again. Frankly, I wouldn’t approve this design in the general case.</p>\n<p>If I <em>were</em> going to do this, I wouldn’t name the function with something as benign as <code>access</code>. I would give it a name with “lock” in there somewhere, to make it clear what kind of dangerous territory you’re in; something like <code>with_data_locked()</code> or <code>lock_data_and_then()</code>.</p>\n<p>There may be a better answer, one that might sound a little crazy:</p>\n<h1>You might not need synchronization at all</h1>\n<p>The only time you need to do any synchronization at all is when you have data that is:</p>\n<ul>\n<li>shared; and</li>\n<li>mutable</li>\n</ul>\n<p>Your data is shared (presumably). However… is it mutable?</p>\n<p>As your code is written, the answer is no. Your <code>LockedData</code> trucks the data around as a <code>const</code> reference. That makes all the difference.</p>\n<p>If the data is <code>const</code>, then it cannot be modified. So there’s no need to synchronize access. That means the entirety of the <code>LockedData</code> structure, the mutex, everything, is all pointless.</p>\n<p>This is not a rare situation at all! In fact, it’s quite common. It’s a very common use pattern to have one thread that loads/generates a big amount of data, then have multiple threads do stuff with it. For example, you’d load an image from disk in a single thread, but then once it’s loaded, you can often break it into subsections and process those subsections independently in multiple threads. In situations like that, you don’t need any synchronization; you just load the data into an immutable object (a <code>const</code> object, or a class that has only <code>const</code> member functions) and then… you’re done. You can safely share that among multiple threads.</p>\n<p>For example:</p>\n<pre><code>auto chunk = std::vector&lt;XMFLOAT3&gt;{};\n\n// initialize chunk with its data here\n\n// now chunk is ready to use, so create some threads to do stuff with the data:\n\nauto func1(std::vector&lt;XMFLOAT3&gt; const&amp;) -&gt; void;\nauto func2(std::vector&lt;XMFLOAT3&gt; const&amp;) -&gt; void;\n\nauto t1 = std::thread{func1, std::cref(chunk)};\nauto t2 = std::thread{func2, std::cref(chunk)};\n\n// and that's that\n\nt1.join();\nt2.join();\n</code></pre>\n<p>That’s it; not a synchronization primitive in sight.</p>\n<p>If for some reason you can’t start the processing threads after the load/generate thread (like, all threads have to be started at the same time for some reason), then you need some sort of synchronization signal so the processing threads know when the data is ready. For example you could wait on an atomic flag (in C++20), or a condition variable, or a shared future. Once a processing thread has the green light, though, no further synchronization is necessary.</p>\n<h1>Summary</h1>\n<p>Given that you haven’t really given any information about your project, how these “chunks” are going to be used, the amount and type contention you expect for the shared data, or even if the data really needs to be shared at all, you’re not going to get any useful, concrete advice from any code review. Reviewers are just going to have to make blind guesses, and maybe one of them will get lucky and guess exactly your situation… but likely not.</p>\n<p>If I base my understanding of how you’re going to use this chunk data based only on the code you’ve given, then I’d say yes, your code is <em>WILDLY</em> over-complicated. <em>ALL</em> of the code you wrote can essentially be replaced with this:</p>\n<pre><code>using Chunk = std::vector&lt;XMFLOAT3&gt; const;\n</code></pre>\n<p>That will make <code>Chunk</code> a thread-safe type that will allow you to share chunk data across multiple threads.</p>\n<p>If, on the other hand, there’s more to your code than you’ve let on, and you need to allow concurrent read <em>AND WRITE</em> access, then maybe the best solution is a <code>shared_mutex</code>. Unless you’re not expecting much contention, in which case you might be able to get away with just an atomic flag.</p>\n<p>One thing you need to be cautious about are designs that allow locks to leach out of an interface, or that allow the execution of arbitrary code while a lock is being held. That is the key problem with your current design: a lock is still being held when the <code>LockedData</code> constructor returns, which you may say, “yeah, duh, that’s the point”… but which I say, yeah, that’s the <em>problem</em>. Anything may happen between that constructor and the destructor (which releases the lock), which is why you have a deadlock problem.</p>\n<p>You may object and say that your <code>LockedData</code> just like <code>std::lock_guard</code>, and if <code>std::lock_guard</code> is fine, why isn’t <code>LockedData</code>. The answer to that is: <code>std::lock_guard</code> <em>isn’t</em> “fine”. It’s “okay” in simple cases. But there’s a reason C++17 added <code>std::scoped_lock</code>, and you shouldn’t use <code>std::lock_guard</code> as of C++17✳, but rather prefer <code>std::scoped_lock</code> instead (unless you need to use <code>std::unique_lock</code> for special use cases, like dealing with condition variables). And <code>LockedData</code> is <em>not</em> like <code>std::scoped_lock</code>. (Though I suppose you <em>could</em> make it more like <code>std::scoped_lock</code>… but that would only be a partial solution, because it would allow locking multiple locks, but still wouldn’t give you the ability to try, adopt, or defer or anything else.) But anyway, even if it were exactly like <code>std::scoped_lock</code>, <code>std::scoped_lock</code> is still <em>dangerous</em>; we just accept the risks because they’re unavoidable, and balance that by being cautious whenever we see any locks being acquired. <em>Hiding</em> locks makes everything more dangerous; at least when it’s openly visible, programmers know to be cautious around <code>std::scoped_lock</code>s.</p>\n<p>✳ (This is a rule of thumb, not a rule. Obviously if <code>std::lock_guard</code> works safely, then fine, leave it… but the default choice as of C++17 should be <code>std::scoped_lock</code>. It works everywhere <code>std::lock_guard</code> does, and in places <code>std::lock_guard</code> cannot work.)</p>\n<p>Now, you may decide to just go ahead with your design anyway, accept the limitations, and rely on programmer discipline to avoid the pitfalls. That’s not a “wrong” solution, and with some tweaks to the interface it might even be practical. At some point, you have to rely on disciplined programmers anyway; compilers just aren’t smart enough to detect poorly written concurrency code, and even sanitizers are’t perfect at detecting data races and deadlocks. So it’s not “wrong” to just say: “Fuck it, I know this design has deadlock risks, so I’ll just make sure all code that uses it does so carefully.” In that case… I guess the best option is the Martin York option 2 design (with a better name than <code>access()</code>, like <code>while_locked()</code> or something, and maybe an overload that allows locking multiple mutexes).</p>\n<p>Concurrency programming is still in its infancy, and we don’t have perfect, generic, one-size-fits-all solutions yet. No one can give you the “right” answer for your situation without knowing it in detail. I hope I’ve given you a comprehensive set of options, with the pros and cons of each. But ultimately, you’ll have to consider your situation, and make the call.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T22:04:53.377", "Id": "254192", "ParentId": "254141", "Score": "1" } } ]
{ "AcceptedAnswerId": "254192", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T16:48:57.380", "Id": "254141", "Score": "0", "Tags": [ "c++", "thread-safety" ], "Title": "Returning data reference with mutex lock guard struct" }
254141
<p>I got tasked with writing a page that will add as many profile entries as the user wants, and web programming is not at all my field. There are multiple input groups but I'm just using the &quot;age&quot; one as an example. Currently I'm using a function to create DOM elements, then I assemble them together and return the completed outer HTML code. Is this the correct way to do this? Here's my code:</p> <pre><code>function addInputGroup(userID, userAge) { let ageCol = document.createElement('div'); ageCol.setAttribute('class', 'col-4'); let ageLabel = document.createElement('label'); ageLabel.setAttribute('class', 'sr-only'); ageLabel.innerHTML = &quot;Age&quot;; let ageInputGroup = document.createElement('div'); ageInputGroup.setAttribute('class', 'input-group'); let ageInputGroupPrepend = document.createElement('div'); ageInputGroupPrepend.setAttribute('class', 'input-group-prepend'); let ageInputGroupText = document.createElement('div'); ageInputGroupText.setAttribute('class', 'input-group-text'); ageInputGroupText.innerHTML = &quot;Age&quot;; let ageInput = document.createElement('input'); ageInput.setAttribute('id', 'fldAge'+userID); ageInput.setAttribute('type', 'text'); ageInput.setAttribute('class', 'form-control'); ageInput.setAttribute('placeholder', userAge); ageInput.setAttribute('value', userAge); //assemble age column ageInputGroupPrepend.appendChild(ageInputGroupText); ageInputGroup.appendChild(ageInputGroupPrepend); ageInputGroup.appendChild(ageInput); ageCol.appendChild(ageLabel); ageCol.appendChild(ageInputGroup); return(ageCol.outerHTML); } </code></pre> <p>Then I call <code>document.write(addInputGroup(&quot;12345&quot;, &quot;18&quot;));</code> when I need to create an &quot;age&quot; input group.</p> <p>Does this look correct?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T18:17:29.060", "Id": "501198", "Score": "0", "body": "Welcome to Code Review! If you're not sure whether your code works correctly, I'm afraid it's not yet ready for review. Code Review is for finished code that you believe to be functionally correct. Please read [What topics can I ask about here?](https://codereview.stackexchange.com/help/on-topic) - note that it states \"_If you are looking for feedback on a specific **working** piece of code...then you are in the right place!_\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T21:30:29.507", "Id": "501217", "Score": "0", "body": "`Does this look correct?` How have you arranged for testing your code? I see two interpretations for the question I quoted: a) Does this look the correct way to achieve the code's goal? b) Does this look as if it actually achieved the code's goal? - the latter is off-topic." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T21:32:53.487", "Id": "501218", "Score": "0", "body": "(16 is unusually large a code indent.)(Would I expect `import`s, say, for *bootstrap*?)" } ]
[ { "body": "<h1>DOM</h1>\n<p>The outer HTML conversion is probably unecessary. You can manipulate DOM nodes directly. The appending could look something like this.</p>\n<pre><code>// note that the HTML representation is irrelevant; we go straight to the DOM\ndocument.getElementById('input-groups').appendChild(ageCol)\n</code></pre>\n<h1>JS</h1>\n<p><code>addInputGroup()</code> seems to be a misleading name, as the function creates a new DOM element; it doesn't do anything with it. <code>createInputGroup()</code> would be more appropriate I think.</p>\n<p>You can use <code>const</code> instead of <code>let</code> here. This provides some nice guarantees about consistency, and makes these guarantees immediately visible to the reader.</p>\n<p><code>return(ageCol.outerHTML);</code> is more commonly written as <code>return ageCol.outerHTML;</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T21:07:29.823", "Id": "501215", "Score": "0", "body": "Thanks for the help. I'll make the changes you're suggesting. Do you mind looking at my other original question linked below? It was rejected for being an opinion based question, but at this point I *need* opinions since I don't know if my approach is close to acceptable or very inefficient: https://stackoverflow.com/questions/65517018/correct-best-way-to-use-javascript-to-write-dynamic-bootstrap-input-groups" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T18:41:30.917", "Id": "254144", "ParentId": "254142", "Score": "3" } }, { "body": "<p>Overall your code is not bad perse, but you can make some improvements to it.</p>\n<h2>Do not use <code>document.write</code></h2>\n<p><code>document.write</code> has several issues and should not be used. Instead, if you need to dynamically add DOM elements, select the parent element and use something like <code>Node.insertBefore()</code>. For more information, please read <a href=\"https://stackoverflow.com/q/802854/2209007\"><em>Why is document.write considered a “bad practice”?</em></a>.</p>\n<h2>Naming functions</h2>\n<p>Your function does not do what it claims it does. It claims to add an input group, but it is limited to &quot;Age&quot;. Make it more generic.</p>\n<h2>a11y</h2>\n<p>Accessibility-wise, your code is messy. Your label is not attached to any input. A label should either surround the input field (<code>&lt;label&gt;Label name &lt;input ...&gt;&lt;/label&gt;</code>) or use the <code>for</code> attribute. This way, screen readers actually know what a field needs to contain, and clicking the label focuses the input field.</p>\n<p>Furthermore, you are currently printing &quot;Age&quot; twice; once in a screenreader only field and once normally. Screenreaders would thus read it twice to the user.</p>\n<p>To fix this, restructure the rendered html.</p>\n<h2>Other improvements</h2>\n<p>All your variables are not changed after declaring them. You can declare them with <code>const</code> instead. <code>return</code> is a statement and not a function. You don't have to call it and can instead write <code>return whateverYouWantToReturn</code>. You can use template strings to clean up strings that are composed of different substrings. Instead of writing <code>'fldAge'+userID</code> you can write</p>\n<pre><code>`fldAge${userId}`\n</code></pre>\n<p>Lastly, consider if you can instead do this on the server-side instead of with javascript. Especially since you use <code>document.write</code>, it does sound like you are not dynamically adding the inputs, and as such you are better off by just returning the html immediatelly instead of doing it in the browser.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T18:57:58.410", "Id": "254146", "ParentId": "254142", "Score": "2" } }, { "body": "<p>I hope you don't have to do too many of these.</p>\n<h2>Quick points</h2>\n<ul>\n<li>You don't need to use <code>setAttribute</code>. you can assign directly to the property defined in the DOM eg <code>ageInput.id = 'fldAge' + userID;</code></li>\n<li>Why add a placeholder that is identical to the input's value. Should it not say something like <code>&quot;Users age&quot;</code></li>\n</ul>\n<h2>Very poor code</h2>\n<p>You code is near impossible to read.</p>\n<p>Names are overwhelmed by repetitive use of verbose DOM calls, I see that you did use names to relate order but in the noise I was too lazy to bother following it.</p>\n<h2>Structure code</h2>\n<p>Code that is predominantly data entry should focus on the data (elements / forms / HTML) and should do its upmost to remove as much of the un-associated clutter as possible.</p>\n<p>It should be methodical in its ordering. It may not be possible to structure the script to match the data, but some method or logical rules can go a long way.</p>\n<h2>Use functions</h2>\n<p>Functions were originally invented to simplify exactly this type of mess. Making life easier for coders</p>\n<p>JavaScript makes it exceedingly easy to create functions, use them, it will make coding much less of the chore your question implies it is...</p>\n<blockquote>\n<p><em>&quot;I got tasked with writing a page...&quot;</em></p>\n</blockquote>\n<h2>Rewrite</h2>\n<p>The rewrite address the two tasks your code does. It does this using two very simple functions</p>\n<p>The two tasks are</p>\n<ol>\n<li>Create an populate elements with properties.</li>\n<li>Append elements to created elements.</li>\n</ol>\n<p>The two function return elements and can thus be nested.</p>\n<p>By nesting the function calls you can structure the code to match the result.</p>\n<p>The two functions...</p>\n<pre><code>const tag = (tag, className, props = {}) =&gt; \n Object.assign(document.createElement(tag), {className, ...props});\nconst append = (par, ...sibs) =&gt; \n sibs.reduce((p, sib) =&gt; (p.appendChild(sib), p), par);\n</code></pre>\n<p>With which you can create code that matches the structure of the HTML and is predominantly data.</p>\n<pre><code>function inputGroup(userID, age) {\n return append(tag(&quot;div&quot;, &quot;col-4&quot;),\n tag(&quot;label&quot;, &quot;sr-only&quot;, {textContent: &quot;Age&quot;}),\n tag(&quot;div&quot;, &quot;input-group&quot;), \n append(tag(&quot;div&quot;, &quot;input-group-prepend&quot;),\n tag(&quot;div&quot;, &quot;input-group-text&quot;, {textContent: &quot;Age&quot;})),\n tag(&quot;input&quot;, &quot;form-control&quot;, {id: &quot;fldAge&quot; + userID, type: &quot;text&quot;, value: age}));\n}\nappend(document.body, inputGroup(userID, userAge));\n</code></pre>\n<p>minus all this unrelated noise.</p>\n<pre><code>document.createElement\ndocument.createElement\ndocument.createElement\ndocument.createElement\ndocument.createElement\ndocument.createElement\n.setAttribute\n.setAttribute\n.setAttribute\n.setAttribute\n.setAttribute\n.setAttribute\n.setAttribute\n.setAttribute\n.setAttribute\n.setAttribute\n.appendChild\n.appendChild\n.appendChild\n.appendChild\n.appendChild\nageCol\nageCol\nageCol\nageCol\nageCol\nageLabel\nageLabel\nageLabel\nageLabel\nageInput\nageInput\nageInput\nageInput\nageInput\nageInput\nageInput\nageInputGroup\nageInputGroup\nageInputGroup\nageInputGroup\nageInputGroup\nageInputGroupText \nageInputGroupText\nageInputGroupText\nageInputGroupText\nageInputGroupPrepend\nageInputGroupPrepend\nageInputGroupPrepend\nageInputGroupPrepend\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T00:09:29.397", "Id": "501229", "Score": "0", "body": "This is what I was hoping to find, an incredibly efficient way that I didn't know was possible. Thank you for this. I wasn't aware of the `...` syntax and found a tutorial on it. If you don't mind 1 more question, I have a button that calls a function to setup the profile which will call functions like the one above to setup name, age, etc. Once the user is done adding entries, there is a save button that will take all entries and write it to a database. Is that an efficient way to achieve dynamic list creation/storage?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T02:02:55.777", "Id": "501231", "Score": "0", "body": "@Jeff2005 If you are referring to the rest syntax `...` then maybe, but I cant comment on unknowns. There are many ways to gather and process data in JS what is best suit will change depending on needs. It is best to become familiar with what the language can do. MDN is a good reference, the link is to the spread operator AKA rest syntax '...' The site has good coverage of JS with examples and more.. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T22:10:42.937", "Id": "501400", "Score": "0", "body": "Thanks. Is there a way to make the tag function work with hyphenated attributes like 'data-parent'? I tried ['data-parent'] also and it didn't work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T22:13:50.707", "Id": "501401", "Score": "0", "body": "@Jeff2005 `data` is a called `dataset` by the DOM and is an object You can assign to the `dataset` if you create a function `const data = (el, data) => (Object.assign(el.dataset, data), el);`. You use it like `data(tag(\"div\", \"myClass\",{textContent:\"Some text\"}),{parent: \"somevalue\"})` Note that dataset names are modified by the DOM. You will need to make sure you understand how it works to use it correctly https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/dataset" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T23:50:20.607", "Id": "501405", "Score": "0", "body": "Thank you again. Wish there was a \"thanks\" or upvote for comment button." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T22:36:29.323", "Id": "254157", "ParentId": "254142", "Score": "0" } } ]
{ "AcceptedAnswerId": "254157", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T17:46:39.503", "Id": "254142", "Score": "0", "Tags": [ "javascript", "ecmascript-6", "bootstrap-4" ], "Title": "function to get input group for user" }
254142
<hr /> <p>Edit: this is a base library for including in larger projects for the overall management of <a href="https://en.wikipedia.org/wiki/JSON_Web_Token" rel="nofollow noreferrer">JSON Web Token</a>s (JWT) that should be compatible with other JWT libraries that share an encryption secret - also remote systems can reach out to the issuing system (with my library or a different JWT library) to verify the token works. The encryption &quot;secret&quot; thing is the crux of the matter: you can't encode, modify, or verify without it, regardless of the library.</p> <hr /> <p>This is my first time posting here. This is &quot;reinventing the wheel&quot;, but somewhat an earnest thing I wanted to try, and a representative sample of where I am at in this skill. I would be grateful for any comments or suggestions that might make me a better developer tomorrow.</p> <p>The code coverage is 100%, mostly as a good start for letting me know if I broke something when I modify the code - one of the things I would like to improve next year (tomorrow... as today is 2020-12-31) is to be able to expect a specific <code>RuntimeException</code> message, telling me that I am triggering the specific predicted runtime exception when I expect that I should get an exception in a particular place in the code.</p> <hr /> <p>There's a <a href="https://github.com/bradchesney79/effortless-hs256-jwt" rel="nofollow noreferrer">GitHub repo</a>, and a 20-minute Youtube video of <a href="https://youtu.be/lx1FYXB6fB4" rel="nofollow noreferrer">stepping through the tests</a>.</p> <p>(you shouldn't need a video to see how it works. ... And you don't. I just included it to be helpful as I believe more people have access to youtube than phpunit.)</p> <p>If you wanted to see any particular chunk in action-- you can click to the area in the video you want to see happening. (Loading and running the code is still an option, but sometimes &quot;I don't wanna&quot; and maybe you don't either.)</p> <hr /> <p>The config file is essentially a php script that returns an array with the &quot;secret&quot; and database connection credentials.</p> <p>I know revocation storage and handling is not part of JWT officially - but, I wanted it, so I baked it in, complete with an SQL table creation script.</p> <p>I really appreciate you spending your time looking at my thing.</p> <hr /> <pre><code>&lt;?php namespace BradChesney79; use DateTime; use DateTimeZone; use Exception; use LogicException; use PDO; use RuntimeException; class EHJWT { /* iss: issuer, the website that issued the token sub: subject, the id of the entity being granted the token aud: audience, the users of the token-- generally a url or string exp: expires, the UTC UNIX epoch time stamp of when the token is no longer valid nbf: not before, the UTC UNIX epoch time stamp of when the token becomes valid iat: issued at, the UTC UNIX epoch time stamp of when the token was issued jti: JSON web token ID, a unique identifier for the JWT that facilitates revocation DB/MySQL limits: int has an unsigned, numeric limit of 4294967295 bigint has an unsigned, numeric limit of 18446744073709551615 unix epoch as of &quot;now&quot; 1544897945 */ /** * Token Claims * * @var array */ private array $tokenClaims = array(); /** * @var string */ private string $token = ''; /** * The config data. * * @var array */ protected $configurations = []; // /** // * Error Object // * // * @var object // */ // public object $error; // methods public function __construct(string $secret = '', string $configFileNameWithPath = '', string $dsn = '', string $dbUser = '', string $dbPassword = '') { try { $this-&gt;setConfigurationsFromEnvVars(); if (mb_strlen($configFileNameWithPath) &gt; 0) { $this-&gt;setConfigurationsFromConfigFile($configFileNameWithPath); } $this-&gt;setConfigurationsFromArguments($secret, $dsn, $dbUser, $dbPassword); } catch (Exception $e) { throw new LogicException('Failure creating EHJWT object: ' . $e-&gt;getMessage(), 0); } return true; } private function setConfigurationsFromEnvVars() { $envVarNames = array( 'EHJWT_JWT_SECRET', 'EHJWT_DSN', 'EHJWT_DB_USER', 'EHJWT_DB_PASS' ); $settingConfigurationName = array( 'jwtSecret', 'dsn', 'dbUser', 'dbPassword' ); for ($i = 0; $i &lt; count($envVarNames); $i++) { $retrievedEnvironmentVariableValue = getenv($envVarNames[$i]); if (mb_strlen($retrievedEnvironmentVariableValue) &gt; 0) { $this-&gt;configurations[$settingConfigurationName[$i]] = $retrievedEnvironmentVariableValue; } } } private function setConfigurationsFromConfigFile(string $configFileWithPath) { if (file_exists($configFileWithPath)) { $configFileSettings = require $configFileWithPath; if (gettype($configFileSettings) !== 'array') { throw new RuntimeException('EHJWT config file does not return an array'); } if (count($configFileSettings) == 0) { trigger_error('No valid configurations received from EHJWT config file', 8); } foreach (array( 'jwtSecret', 'dsn', 'dbUser', 'dbPassword' ) as $settingName) { $retrievedConfigFileVariableValue = $configFileSettings[$settingName]; if (mb_strlen($retrievedConfigFileVariableValue) &gt; 0) { $this-&gt;configurations[$settingName] = $retrievedConfigFileVariableValue; } } } } private function setConfigurationsFromArguments(string $jwtSecret = '', string $dsn = '', string $dbUser = '', string $dbPassword = '') { foreach (array( 'jwtSecret', 'dsn', 'dbUser', 'dbPassword' ) as $settingName) { $argumentValue = $ { &quot;$settingName&quot; }; if (mb_strlen($argumentValue) &gt; 0) { $this-&gt;configurations[$settingName] = $argumentValue; } } } public function addOrUpdateJwtClaim(string $key, $value, $requiredType = 'mixed') { // ToDo: Needs more validation or something ...added utf8 if (gettype($value) == $requiredType || $requiredType === 'mixed') { if (mb_detect_encoding($value, 'UTF-8', true)) { $this-&gt;tokenClaims[$key] = $value; return true; } throw new RuntimeException('Specified JWT claim required encoding mismatch'); } throw new RuntimeException('Specified JWT claim required type mismatch'); } public function clearClaim(string $key) { if (isset($key)) { unset($this-&gt;tokenClaims[$key]); } return true; } private function jsonEncodeClaims() { return json_encode($this-&gt;tokenClaims, JSON_FORCE_OBJECT); } private function createSignature($base64UrlHeader, $base64UrlClaims) { $jsonSignature = $this-&gt;makeHmacHash($base64UrlHeader, $base64UrlClaims); return $this-&gt;base64UrlEncode($jsonSignature); } public function createToken() { // !!! ksort to maintain properties in repeatable order ksort($this-&gt;tokenClaims); $jsonClaims = $this-&gt;jsonEncodeClaims(); // The hash is always the same... don't bother computing it. $base64UrlHeader = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9'; $base64UrlClaims = $this-&gt;base64UrlEncode($jsonClaims); $jsonSignature = $this-&gt;createSignature($base64UrlHeader, $base64UrlClaims); $base64UrlSignature = $this-&gt;base64UrlEncode($jsonSignature); $tokenParts = array( $base64UrlHeader, $base64UrlClaims, $base64UrlSignature ); $this-&gt;token = implode('.', $tokenParts); return true; } public function getUtcTime() { $date = new DateTime('now', new DateTimeZone('UTC')); return $date-&gt;getTimestamp(); } public function loadToken(string $tokenString) { $this-&gt;clearClaims(); $this-&gt;token = $tokenString; if ($this-&gt;validateToken()) { $tokenParts = explode('.', $tokenString); $this-&gt;tokenClaims = $this-&gt;decodeTokenPayload($tokenParts[1]); return true; } return false; } public function validateToken() { $tokenParts = $this-&gt;getTokenParts(); $unpackedTokenPayload = $this-&gt;decodeTokenPayload($tokenParts[1]); $this-&gt;tokenClaims = $unpackedTokenPayload; if ($tokenParts[0] !== 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9') { throw new RuntimeException('Encryption algorithm tampered with', 0); } $utcTimeNow = $this-&gt;getUtcTime(); if (!isset($unpackedTokenPayload['exp'])) { throw new RuntimeException(&quot;Expiration standard claim for JWT missing&quot;, 0); } $expiryTime = $unpackedTokenPayload['exp']; // a good JWT integration uses token expiration, I am forcing your hand if ($utcTimeNow &gt; intval($expiryTime)) { // 'Expired (exp)' throw new RuntimeException('Token is expired', 0); } $notBeforeTime = $unpackedTokenPayload['nbf']; // if nbf is set if (null !== $notBeforeTime) { if (intval($notBeforeTime) &gt; $utcTimeNow) { // 'Too early for not before(nbf) value' throw new RuntimeException('Token issued before nbf header allows', 0); } } if (mb_strlen($this-&gt;configurations['dbUser']) &gt; 0 &amp;&amp; mb_strlen($this-&gt;configurations['dbPassword']) &gt; 0) { if (strpos($this-&gt;configurations['dsn'], ':') === false) { throw new RuntimeException('No valid DSN stored for connection to DB', 0); } try { $dbh = $this-&gt;makeRevocationTableDatabaseConnection(); } catch (Exception $e) { throw new RuntimeException('Cannot connect to the DB to check for revoked tokens and banned users', 0); } $lastCharacterOfJti = substr(strval($this-&gt;tokenClaims['jti']), -1); // clean out revoked token records if the UTC unix time ends in '0' if (0 == (intval($lastCharacterOfJti))) { $this-&gt;revocationTableCleanup($utcTimeNow); } if (!isset($unpackedTokenPayload['sub'])) { throw new RuntimeException(&quot;Subject standard claim not set to check ban status&quot;); } // ToDo: fix bind statement $stmt = $dbh-&gt;prepare(&quot;SELECT * FROM revoked_ehjwt where sub = ?&quot;); $stmt-&gt;bindParam(1, $unpackedTokenPayload['sub']); // get records for this sub if ($stmt-&gt;execute()) { while ($row = $stmt-&gt;fetch()) { if ($row['jti'] == 0 &amp;&amp; $row['exp'] &gt; $utcTimeNow) { // user is under an unexpired ban condition return false; } if ($row['jti'] == $unpackedTokenPayload['jti']) { // token is revoked return false; } // remove records for expired tokens to keep the table small and snappy if ($row['exp'] &lt; $utcTimeNow) { // deleteRevocation record $this-&gt;deleteRecordFromRevocationTable($row['id']); } } } } $this-&gt;createToken(); $recreatedToken = $this-&gt;getToken(); $recreatedTokenParts = explode('.', $recreatedToken); $recreatedTokenSignature = $recreatedTokenParts[2]; if ($recreatedTokenSignature !== $tokenParts['2']) { // 'signature invalid, potential tampering return false; } // the token checks out! return true; } public function revocationTableCleanup(int $utcTimeStamp) { $dbh = $this-&gt;makeRevocationTableDatabaseConnection(); $stmt = $dbh-&gt;prepare(&quot;DELETE FROM revoked_ehjwt WHERE `exp` &lt;= $utcTimeStamp&quot;); $stmt-&gt;execute(); } private function getTokenParts() { $tokenParts = explode('.', $this-&gt;token); if ($this-&gt;verifyThreeMembers($tokenParts)) { return $tokenParts; } throw new RuntimeException('Token does not contain three delimited sections', 0); } private function verifyThreeMembers(array $array) { if (3 !== count($array)) { // 'Incorrect quantity of segments' return false; } return true; } private function makeRevocationTableDatabaseConnection() { return new PDO($this-&gt;configurations['dsn'], $this-&gt;configurations['dbUser'], $this-&gt;configurations['dbPassword'], array( PDO::ATTR_DEFAULT_FETCH_MODE =&gt; PDO::FETCH_NAMED )); } private function deleteRecordFromRevocationTable(string $recordId) { $dbh = $this-&gt;makeRevocationTableDatabaseConnection(); $stmt = $dbh-&gt;prepare(&quot;DELETE FROM revoked_ehjwt WHERE id = ?&quot;); $stmt-&gt;bindParam(1, $recordId); return $stmt-&gt;execute(); } public function reissueToken(string $tokenString, int $newUtcTimestampExpiration) { if ($this-&gt;loadToken($tokenString)) { $this-&gt;addOrUpdateJwtClaim('exp', $newUtcTimestampExpiration); $this-&gt;createToken(); } return; } public function getToken() { return $this-&gt;token; } private function decodeTokenPayload($jwtPayload) { $decodedPayload = json_decode($this-&gt;base64UrlDecode($jwtPayload), true); if (0 !== json_last_error()) { throw new RuntimeException(&quot;JWT payload json_decode() error: &quot; . json_last_error_msg(), 0); } return $decodedPayload; } public function getTokenClaims() { return $this-&gt;tokenClaims; } private function base64UrlEncode(string $unencodedString) { return rtrim(strtr(base64_encode($unencodedString), '+/', '-_'), '='); } private function base64UrlDecode(string $base64UrlEncodedString) { return base64_decode(str_pad(strtr($base64UrlEncodedString, '-_', '+/'), mb_strlen($base64UrlEncodedString) % 4, '=', STR_PAD_RIGHT)); } private function makeHmacHash(string $base64UrlHeader, string $base64UrlClaims) { // sha256 is the only algorithm. sorry, not sorry. return hash_hmac('sha256', $base64UrlHeader . '.' . $base64UrlClaims, $this-&gt;configurations['jwtSecret'], true); } public function clearClaims() { $this-&gt;tokenClaims = []; } public function revokeToken() { // only add if the token is valid-- don't let imposters kill otherwise valid tokens if ($this-&gt;validateToken()) { $revocationExpiration = (int)$this-&gt;tokenClaims['exp'] + 30; $this-&gt;writeRecordToRevocationTable($revocationExpiration); } } public function banUser(string $utcUnixTimestampBanExpiration) { $banExp = (int)$this-&gt;tokenClaims['exp'] + 60; // insert jti of 0, sub... the userId to ban, and UTC Unix epoch of ban end $this-&gt;writeRecordToRevocationTable($utcUnixTimestampBanExpiration, true); } public function permabanUser() { // insert jti of 0, sub... the userId to ban, and UTC Unix epoch of ban end-- Tuesday after never $this-&gt;writeRecordToRevocationTable(4294967295, true); } public function unbanUser() { $this-&gt;deleteRecordsFromRevocationTable(); } private function writeRecordToRevocationTable(int $exp, bool $ban = false) { $userBanJtiPlaceholder = 0; $dbh = $this-&gt;makeRevocationTableDatabaseConnection(); $stmt = $dbh-&gt;prepare(&quot;INSERT INTO revoked_ehjwt (jti, sub, exp) VALUES (?, ?, ?)&quot;); $stmt-&gt;bindParam(1, $this-&gt;tokenClaims['jti']); if ($ban) { $stmt-&gt;bindParam(1, $userBanJtiPlaceholder); } $stmt-&gt;bindParam(2, $this-&gt;tokenClaims['sub']); $stmt-&gt;bindParam(3, $exp); return $stmt-&gt;execute(); } private function deleteRecordsFromRevocationTable() { $dbh = $this-&gt;makeRevocationTableDatabaseConnection(); $stmt = $dbh-&gt;prepare(&quot;DELETE FROM revoked_ehjwt WHERE sub = ? AND jti = 0&quot;); $stmt-&gt;bindParam(1, $this-&gt;tokenClaims['sub']); return $stmt-&gt;execute(); } // ToDo: Provide access to a list of banned users public function retrieveBannedUsers() { $bannedUsers = array(); $dbh = $this-&gt;makeRevocationTableDatabaseConnection(); $stmt = $dbh-&gt;query('SELECT * FROM revoked_ehjwt WHERE `jti` = 0'); if ($stmt-&gt;execute()) { while ($row = $stmt-&gt;fetch()) { $bannedUsers[] = $row; } return $bannedUsers; } }} </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T19:08:25.657", "Id": "501204", "Score": "0", "body": "You haven't said what your library is supposed to *do* (that should be the title). Maybe it's in your video, but not all of us have installed video players, and in any case, the question should be complete in itself, and not dependent on external resources to make sense." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T19:28:13.067", "Id": "501205", "Score": "0", "body": "@TobySpeight, I have edited the title as requested. I included the code and link to the github. The video link is just because I thought it would be helpful for people that didn't feel like installing my cruddy library and configuring phpunit. --I guess I figured more people would have access to youtube than phpunit." } ]
[ { "body": "<ul>\n<li><p>The <code>mb_strlen($configFileNameWithPath) &gt; 0</code> checks don't need the <code>&gt; 0</code> part at the end. <code>mb_strlen()</code> will always return an integer-type value, so you only need to check if it is truthy. As I think about it, I don't see the value in <code>mb_strlen()</code> -- it will be potentially more accurate in non-zero cases, but you only intend to differentiate between zero and non-zero. For this reason, maybe just use <code>strlen()</code>.</p>\n</li>\n<li><p><strong>IMPORTANT</strong>: A constructor returns nothing. You should not be returning <code>true</code>. Please read <a href=\"https://stackoverflow.com/q/11904255/2943403\">Constructor returning value?</a>.</p>\n</li>\n<li><p><code>$envVarNames</code> and <code>$settingConfigurationName</code> are related arrays, but you have not declared them as such. I recommend that you logically construct a lookup array (as a class property so that only processing code is in the method) which is associative. This will set you up to employ a <code>foreach()</code> loop instead of counting the length of an array on every iteration.</p>\n<pre><code>private $envConfigNames = [\n 'EHJWT_JWT_SECRET' =&gt; 'jwtSecret',\n 'EHJWT_DSN' =&gt; 'dsn',\n 'EHJWT_DB_USER' =&gt; 'dbUser',\n 'EHJWT_DB_PASS' =&gt; 'dbPassword',\n];\n\nprivate function setConfigurationsFromEnvVars(): void\n{\n foreach ($this-&gt;$envConfigNames as $envName =&gt; $configName) {\n $value = getenv($envName);\n if (strlen($value)) {\n $this-&gt;configurations[$configName] = $value;\n }\n }\n</code></pre>\n<p>Use this lookup array again in <code>setConfigurationsFromConfigFile()</code> and <code>setConfigurationsFromArguments()</code>.</p>\n</li>\n<li><p>Instead of <code>gettype($configFileSettings) !== 'array'</code>, it is more concise to use <code>!is_array($configFileSettings)</code>.</p>\n</li>\n<li><p>I, generally, do not endorse the use of &quot;<a href=\"https://www.php.net/manual/en/language.variables.variable.php\" rel=\"nofollow noreferrer\">variable variables</a>&quot;, but I don't find your usage to be offensive or pulling your code into a disheveled state. The syntax can be as simple as <code>$value = $$settingName;</code></p>\n</li>\n<li><p>You never need to check if a variable/element <code>isset()</code> before <code>unset()</code>ing it. Remove the condition and just <code>unset()</code> it.</p>\n</li>\n<li><p>I do not endorse the unconditional return of <code>true</code> in methods. It is not informative, it is just useless noise. If there is no chance of returning <code>false</code>, just don't return anything (<code>:void</code>).</p>\n</li>\n<li><p>I prefer to avoid single-use variables (unless there is a clear and valuable benefit in the declarative variable name). <code>createToken()</code> seems like the values should be directly fed into the <code>implode()</code> call.</p>\n</li>\n<li><p>I recommend declaring the return types on all methods (except the constructor). This will help with debugging and enforce strict/predictable types in your application. <code>public function loadToken(string $tokenString): bool</code></p>\n</li>\n<li><p>Consistently use ALL-CAPS when writing sql keywords -- this will improve the readability of your code. (e.g. convert <code>where</code> to <code>WHERE</code>)</p>\n</li>\n<li><p>Even if variables fed to your sql are coming from a safe place, I recommend consistently using prepared statements with bound parameters. When you have a whole application written this way, you will be less likely to have other devs on your team &quot;sneak in&quot; unsafe values when they copy-pasta from your un-parameterized query.</p>\n</li>\n<li><p>I do not like that you are creating a new pdo connection for every query. You should modify <code>makeRevocationTableDatabaseConnection()</code> so that if there is already an established connection, then it is re-used.</p>\n</li>\n<li><p>Return the boolean evaluation for more concise code.</p>\n<pre><code>private function verifyThreeMembers(array $array): bool\n{\n return count($array) === 3;\n}\n</code></pre>\n<p>For methods that return a boolean value, I often start the method name with <code>is</code> or <code>has</code> (or a similar/suitable verb) so that all devs that read the code will infer from its name that it returns a boolean. When sorting my methods in my IDE (phpstorm), this serves to group the boolean-returning methods together.</p>\n</li>\n<li><p>With pdo, I prefer to pass the values directly into the <code>execute()</code> function to avoid the <code>bindParam()</code> calls.</p>\n</li>\n<li><p>Use <code>fetchAll()</code> when returning an entire unaltered result set instead of iteratively fetching the result set.</p>\n<pre><code>return $stmt-&gt;fetchAll(PDO::FETCH_ASSOC);\n</code></pre>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-04T15:33:54.597", "Id": "501526", "Score": "0", "body": "That is a lot of good advice. Thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T09:08:33.100", "Id": "254170", "ParentId": "254145", "Score": "3" } } ]
{ "AcceptedAnswerId": "254170", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T18:54:50.233", "Id": "254145", "Score": "2", "Tags": [ "php", "reinventing-the-wheel", "jwt" ], "Title": "PHP JWT management base library for inclusion in larger projects" }
254145
<p>I found these two videos by Marcel Vos: <a href="https://www.youtube.com/watch?v=KVgoy_a_gWI" rel="nofollow noreferrer">(1)</a> <a href="https://www.youtube.com/watch?v=b-5aX2oLOgU" rel="nofollow noreferrer">(2)</a> that show how you can make hedge mazes that are very hard for the simple <a href="https://en.wikipedia.org/wiki/RollerCoaster_Tycoon_2" rel="nofollow noreferrer">roller coaster tycoon 2</a> park guest AI to solve. Long story short, he eventually makes mazes that cover the entire map and leaves the guest to wander for what we'll just call eternity.</p> <p>Because the mechanics are actually very simple, I decided to try to learn threading by making a multithreaded program that simulate various &quot;mazes&quot; and how much time they take on average (and maybe make a nice scatter plot).</p> <h2>The maze AI and simulation of it</h2> <p>The maze AI that is simulated here is the OpenRCT2 one, which works like this.</p> <pre class="lang-none prettyprint-override"><code>If there is a dead end: Turn around Otherwise: Make a list of all directions (Except the one that you entered from) Randomly pick one from the list and take that one </code></pre> <p>What Marcel simply did was make a maze entirely of blocks like this</p> <pre class="lang-none prettyprint-override"><code> ^ out ## # # # ## # ^ in </code></pre> <p>The AI enters the junction and will have a 50-50 chance of turning into the indent or continuing forward. After turning around in the indent, there is then a further 50-50 chance of continuing forward and turning around. So for each indent there is</p> <ul> <li>A 50% (2/4ths) chance of going forward</li> <li>A 25% (1/4th) chance of wasting time and going forward</li> <li>A 25% (1/4th) chance of wasting time and turning around</li> </ul> <p>This is what <code>simulate</code> does repeatedly until it reaches its goal indent. &quot;wasting time&quot; is simply counted as a extra step taken to solve the maze.</p> <h2>Some intresting results</h2> <p><em>This section is not needed to understand the code, i just thought it would be fun to share stuff that would just go to waste otherwise.</em></p> <p>The simulation is very coarse and has alot of room for improvement. The error when compared to the actual solve times in the video starts to grow linearly (and pretty quickly at that) after 40 indents. Despite this, the results are pretty intresting anyway.</p> <p>The complexity of the AI was predicted to exponential in the video, with complexity <span class="math-container">\$\mathcal{O}(1.052^n)\$</span> for n indents. The simulation instead has the much better <span class="math-container">\$\mathcal{O}(n^2)\$</span>, or <span class="math-container">\$\mathcal{O}(n^3)\$</span> if we (foolishly?) assume that the error factor stays linear. The simulation-predicted time for the full maze (which now is a pretty useless lower bound) is 2½ years.</p> <p>The distribution of times to solve a maze with a certain indent count seems to follow a binomial distribution, which makes sense. I cannot even pretend to understand statistics well enough to approximate parameters, but there it is.</p> <h2>Questions</h2> <p>Hopefully there aren't to general.</p> <ul> <li>Is the threading done safetly here? Is there any big no-nos here?</li> <li>Is the RNG handled properly? I know that java uses a &quot;uniquifier&quot; for each instance of its RNG, but it didn't seem to be needed here.</li> <li>Is the code style general good?</li> </ul> <h2>The code</h2> <p>The main thread syncronizes the simulation threads that each simulate a park guest navigating the maze, counting the number of needed steps. These threads increment a counter that keeps track of the number of trials performed, with the treads waiting on others to finish if enough trials are done. When all threads are waiting the the main tread makes the &quot;maze&quot; bigger and gets the other threads running again. The total step count is used to compute a average for that maze size which is written to a file as CSV.</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; #include &lt;random&gt; #include &lt;chrono&gt; #include &lt;thread&gt; #include &lt;mutex&gt; #include &lt;condition_variable&gt; #include &lt;iostream&gt; #include &lt;fstream&gt; long long simulate(int goal, std::default_random_engine &amp;rng) { int pos = 0; long long stepCount = 0; // Direction to move. abs(facing) == 1 int facing = +1; auto zeroto3 = std::uniform_int_distribution&lt;&gt;(0, 3); while (pos &lt; goal) { stepCount++; // Boundary condition: Always turn around if pos 0 if (pos == 0) { facing = +1; pos = 1; continue; } // There is a 50% chance of entering a indent and 50% chance // to go forward. When exiting a indent there is a 50% chance of // going forward and 50% chance of going backward. // Thus // 2/4 -&gt; forward // 1/4 -&gt; wait, then forward // 1/4 -&gt; wait, then backward int val = zeroto3(rng); if (val &lt;= 1) { //forward pos += facing; } else if (val == 2) { // wait, then forward stepCount++; pos += facing; } else { // wait, then turn around stepCount++; facing = -facing; pos += facing; } } return stepCount; } const int INITIAL_GOAL = 3; const int FINAL_GOAL = 10000; const int THREAD_COUNT = 8; const int SAMPLE_COUNT = 10000; std::mutex testNo_check_mutex; std::mutex output_mutex; std::mutex next_sim_mutex; std::mutex all_waiting_mutex; std::condition_variable next_sim; std::condition_variable all_waiting; void simulate_task(std::atomic&lt;int&gt;* testNo, std::atomic&lt;int&gt;* goal, std::atomic&lt;int&gt;* threadsWaiting, std::atomic&lt;long long&gt;* sum) { int seed = std::chrono::system_clock::now().time_since_epoch().count(); std::default_random_engine rng(seed); while (true) { testNo_check_mutex.lock(); if (testNo-&gt;load() &gt;= SAMPLE_COUNT) { testNo_check_mutex.unlock(); std::unique_lock&lt;std::mutex&gt; cond_lock(next_sim_mutex); threadsWaiting-&gt;fetch_add(1); all_waiting.notify_all(); next_sim.wait(cond_lock); if (goal-&gt;load() &gt; FINAL_GOAL) { return; } } else { testNo-&gt;fetch_add(1); testNo_check_mutex.unlock(); } long long result = simulate(goal-&gt;load(),rng); //output_mutex.lock(); // Keep these mutexes in case more statistics are needed sum-&gt;fetch_add(result); //output_mutex.unlock(); } } int main() { std::atomic&lt;int&gt; testNo = 0; std::atomic&lt;int&gt; goal = INITIAL_GOAL; std::atomic&lt;int&gt; threadsWaiting = 0; std::atomic&lt;long long&gt; sum = 0; std::ofstream resultFile; resultFile.open(&quot;--- Removed for privacy ---&quot;); if (!resultFile.is_open()) { std::cout &lt;&lt; &quot;Failed to open file.&quot; &lt;&lt; std::endl; return -1; } std::thread Threadpool[THREAD_COUNT]; for (int i = 0; i &lt; THREAD_COUNT; i++) { Threadpool[i] = std::thread(simulate_task, &amp;testNo, &amp;goal, &amp;threadsWaiting, &amp;sum); } while (goal.load() &lt;= FINAL_GOAL) { std::unique_lock&lt;std::mutex&gt; cond_lock(next_sim_mutex); // ThreadsWaiting is not global, so it can't be // in the wait condition lambda. while (threadsWaiting.load() &lt; THREAD_COUNT) { all_waiting.wait(cond_lock); } resultFile &lt;&lt; goal.load() &lt;&lt; &quot;;&quot; &lt;&lt; sum.load() / SAMPLE_COUNT &lt;&lt; &quot;\n&quot;; double percentage = ((double)goal.load()*100)/FINAL_GOAL; std::cout &lt;&lt; &quot;\rProgress: &quot; &lt;&lt; goal.load() &lt;&lt; &quot; of &quot; &lt;&lt; FINAL_GOAL &lt;&lt; &quot; (&quot; &lt;&lt; percentage &lt;&lt; &quot;%) &quot;; // Update relevant variables, calculate stats testNo.store(0); goal.fetch_add(1); sum.store(0); threadsWaiting = 0; next_sim.notify_all(); } std::cout &lt;&lt; &quot;done!&quot; &lt;&lt; std::endl; for (int i = 0; i &lt; THREAD_COUNT; i++) { Threadpool[i].join(); } resultFile.close(); std::cout &lt;&lt; &quot;And this was hopefully not a massive waste of time!\n&quot;; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T21:37:44.723", "Id": "501220", "Score": "0", "body": "(When putting a spelling checker to (beneficial) use: mine doesn't flag lower case `i`s even where used as a pronoun.)" } ]
[ { "body": "<h1>Answers to your questions</h1>\n<blockquote>\n<p>Is the threading done safetly here? Is there any big no-nos here?</p>\n</blockquote>\n<p>Avoid manually calling <code>.lock()</code> and <code>.unlock()</code>, and use the version of <code>std::condition_variable::wait()</code> that takes a predicate to wait for. Furthermore, you want to avoid needing locks. Instead of having threads update shared variables, consider having them store their results in per-thread variables, and only merge them when all threads are done.</p>\n<blockquote>\n<p>Is the RNG handled properly? I know that java uses a &quot;uniquifier&quot; for each instance of its RNG, but it didn't seem to be needed here.</p>\n</blockquote>\n<p>Your &quot;uniquifier&quot; is <code>seed</code>. However, instead of taking the time, you should use a proper random number as the seed. You can use <a href=\"https://en.cppreference.com/w/cpp/numeric/random/random_device\" rel=\"nofollow noreferrer\"><code>std::random_device</code></a> for that, like so:</p>\n<pre><code>std::random_device rd;\nstd::default_random_engine rng(rd());\n</code></pre>\n<blockquote>\n<p>Is the code style general good?</p>\n</blockquote>\n<p>The style looks fine to me. The most important thing is that style is applied consistently, which you do.</p>\n<h1>Simplify your thread pool</h1>\n<p>You have four mutexes and two condition variables just to maintain your thread pool. This makes the code quite complex; you've spent roughly as many lines on the thread pool as one the actual simulation. You don't need any mutexes and condition variables, if you don't mind not having a progress counter, and only have the result written out at the end. Here is how it might look:</p>\n<pre><code>void simulate_task(std::atomic&lt;int&gt; &amp;goal_counter, std::vector&lt;long long&gt; &amp;results) {\n std::random_device rd;\n std::default_random_engine rng(rd());\n\n while (true) {\n const int goal = goal_counter++;\n if (goal &gt;= SAMPLE_COUNT)\n break;\n\n long long sum = 0;\n for(int i = 0; i &lt; SAMPLE_COUNT; ++i)\n sum += simulate(goal, rng);\n\n results[goal] = sum / SAMPLE_COUNT;\n }\n}\n\nint main()\n{ \n std::atomic&lt;int&gt; goal_counter = INITIAL_GOAL;\n std::vector&lt;long long&gt; results(FINAL_GOAL);\n\n std::ofstream resultFile(&quot;--- Removed for privacy ---&quot;);\n if (!resultFile.is_open()) {\n std::cout &lt;&lt; &quot;Failed to open file.\\n&quot;;\n return 1;\n }\n\n std::thread Threadpool[THREAD_COUNT];\n\n for (int i = 0; i &lt; THREAD_COUNT; i++)\n Threadpool[i] = std::thread(simulate_task, std::ref(goal_counter), std::ref(results));\n \n for (int i = 0; i &lt; THREAD_COUNT; i++)\n Threadpool[i].join();\n\n for (int i = INITIAL_GOAL; i &lt; FINAL_GOAL; ++i)\n resultFile &lt;&lt; i &lt;&lt; &quot;;&quot; &lt;&lt; results[i] &lt;&lt; &quot;\\n&quot;;\n\n if (resultFile.close(); resultFile.fail()) {\n std::cerr &lt;&lt; &quot;Failed to write file.\\n&quot;;\n return 1;\n }\n}\n</code></pre>\n<h1>Return <code>EXIT_FAILURE</code> on error</h1>\n<p>The proper exit code for a program that encountered an error is <code>EXIT_FAILURE</code> (defined in <code>&lt;cstdlib&gt;</code>, and on most systems it will have the value <code>1</code>), not <code>-1</code>.</p>\n<h1>Write error messages to <code>std::cerr</code></h1>\n<p>Write errors to <code>std::cerr</code> instead of <code>std::cout</code>, so they don't get mixed with regular output. This is especially important if you are redirecting standard output from the program to a file, for example.</p>\n<h1>Check whether all data was written succesfully</h1>\n<p>You checked only if the output file could be opened succesfully, but you didn't check whether all data was written at the end. To do this, you have to call <code>.close()</code> first to ensure all the output buffers are flushed, and then check with <code>.fail()</code> whether any error has happened since you opened the file.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T10:54:38.007", "Id": "501251", "Score": "0", "body": "Ah, dammit! I really should have thought of having a vector like that. (Might get alot of speedup out of it, too) Some exchanges get mad if you accept too early, but i assume that it's fine at code review, right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T11:11:36.247", "Id": "501253", "Score": "0", "body": "You can always change the accepted answer later, so there's no problem accepting something early :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T16:17:06.183", "Id": "501280", "Score": "1", "body": "The exit code for a program that encountered an error is **`EXIT_FAILURE`** (defined in `<cstdlib>`)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T01:37:17.827", "Id": "254163", "ParentId": "254151", "Score": "2" } }, { "body": "<p>Each branch in <code>simulate</code>'s <code>if/else if/else</code> block does <code>pos += facing;</code>. The DRY principle mandates lifting it out. After that the <code>if</code> branch becomes empty:</p>\n<pre><code> int val = zeroto3(rng);\n if (val &lt;= 1) {\n }\n else if (val == 2) {\n stepCount++;\n }\n else {\n stepCount++;\n facing = -facing;\n }\n pos += facing;\n</code></pre>\n<p>This is a strong indication that something is not right. The problem is with a <code>zeroto3</code> function, which violates an SRP (and also has a very suspicious name, BTW). Consider two decision making calls instead:</p>\n<pre><code> if (enter_indent()) {\n stepCount++;\n if (change_direction()) {\n facing = -facing;\n }\n }\n pos += facing;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-03T11:23:33.830", "Id": "501428", "Score": "0", "body": "The first thing i did with this project was to flatten that decision tree. I am not very smart. \n(Also, sorry for the brace style, visual studio keeps murdering my formatting for some reason)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-03T01:28:23.453", "Id": "254257", "ParentId": "254151", "Score": "1" } } ]
{ "AcceptedAnswerId": "254163", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T20:29:53.317", "Id": "254151", "Score": "3", "Tags": [ "c++", "multithreading", "c++17", "simulation" ], "Title": "A simple multithreaded openrct2 maze simulator" }
254151
<p>I am writing an immutable interpreter in C++ for fun. Originally standard vectors and dequeues were used to create a double ended queue data type, but it was very slow, because each operation require a whole new copy of the original container to be created.</p> <p>So it was redone using a custom immutable single linked node lists which only requires a single node to be recreated during each operation on list like data types. And a double ended queue was implemented using two of these single linked lists.</p> <p>While it doesn't require the whole data type and each element to be copied during each operation. It does require a limited recreation of the data type during dequeue operations to rebalance the two lists, which is expensive.</p> <p>Is there a more efficient, and less copy expensive method, that could have been used to implement the double ended queue? Which does not require rebalancing the lists, and the original data still remains immutable during each operation.</p> <p>(Per comments below is the minimum code needed to get it to compile.)</p> <pre class="lang-cpp prettyprint-override"><code>int main() { let l = list(); for (int i = 5; i &lt;= 10; ++i) { l = l.place_last(number(i)); } l = l.place_lead(l); for (int i = 4; i &gt;= 0; --i) { l = l.place_lead(number(i)); } l = l.reverse(); print(&quot;list l = &quot; + str(l)); while (l.is()) { print(&quot;lead element of l = &quot; + str(l.lead())); l = l.shift_lead(); print(&quot;l lead shifted = &quot; + str(l)); } return 0; } </code></pre> <pre class="lang-cpp prettyprint-override"><code>class list { let _lead; let _last; int_t _size; public: list(); list(const list&amp; exp); list(let exp); virtual ~list(); friend str_t __type__(const list&amp; self); friend bool_t __is__(const list&amp; self); friend real_t __comp__(const list&amp; self, const let&amp; other); friend void __str__(stream_t&amp; out, const list&amp; self); friend void __repr__(stream_t&amp; out, const list&amp; self); friend int_t __len__(const list&amp; self); friend let __lead__(const list&amp; self); friend let __last__(const list&amp; self); friend let __place_lead__(const list&amp; self, const let&amp; other); friend let __shift_lead__(const list&amp; self); friend let __place_last__(const list&amp; self, const let&amp; other); friend let __shift_last__(const list&amp; self); friend let __reverse__(const list&amp; self); private: void balance(); }; list::list() : _lead(__node__()), _last(__node__()), _size(0) { } list::list(const list&amp; exp) : _lead(exp._lead), _last(exp._last), _size(exp._size) { } list::list(let exp) : _lead(__node__()), _last(__node__()), _size(0) { _lead = _lead.place_lead(exp); } list::~list() { } std::string __type__(const list&amp; self) { return &quot;list&quot;; } bool_t __is__(const list&amp; self) { if (self._lead.is() || self._last.is()) { return true; } return false; } real_t __comp__(const list&amp; self, const let&amp; other) { const list* e = other.cast&lt;list&gt;(); if (e) { if ((self._lead == e-&gt;_lead) &amp;&amp; (self._last == e-&gt;_last)) { return 0.0; } } return NOT_A_NUMBER; } void __str__(stream_t&amp; out, const list&amp; self) { if (!__is__(self)) { out &lt;&lt; &quot;[]&quot;; return; } out &lt;&lt; &quot;[&quot;; out &lt;&lt; str(self._lead); if (self._last.is()) { if (self._lead.is()) { out &lt;&lt; &quot; &quot;; } out &lt;&lt; str(self._last.reverse()); } out &lt;&lt; &quot;]&quot;; } void __repr__(stream_t&amp; out, const list&amp; self) { if (!__is__(self)) { out &lt;&lt; &quot;[]&quot;; return; } out &lt;&lt; &quot;[&quot;; out &lt;&lt; repr(self._lead); if (self._last.is()) { if (self._lead.is()) { out &lt;&lt; &quot; &quot;; } out &lt;&lt; repr(self._last.reverse()); } out &lt;&lt; &quot;]&quot;; } int_t __len__(const list&amp; self) { return self._size; } let __lead__(const list&amp; self) { if (!self._lead.is()) { return self._last.lead(); } return self._lead.lead(); } let __last__(const list&amp; self) { if (!self._last.is()) { return self._lead.lead(); } return self._last.lead(); } let __place_lead__(const list&amp; self, const let&amp; other) { if (other.is_nothing()) { return self; } list e = self; e._lead = e._lead.place_lead(other); e._size += 1; if (!e._last.is()) { e.balance(); } return e; } let __shift_lead__(const list&amp; self) { if (__len__(self) == 0) { return self; } list e = self; if (!e._lead.is()) { if (e._last.shift_lead().is()) { // Balance if _last has more than one element. e.balance(); } else { e._last = e._last.shift_lead(); return e; } } e._lead = e._lead.shift_lead(); if (!e._lead.is()) { if (e._last.shift_lead().is()) { e.balance(); } } return e; } let __place_last__(const list&amp; self, const let&amp; other) { if (other.is_nothing()) { return self; } list e = self; e._last = e._last.place_lead(other); e._size += 1; if (!e._lead.is()) { e.balance(); } return e; } let __shift_last__(const list&amp; self) { if (__len__(self) == 0) { return self; } list e = self; if (!e._last.is()) { if (e._lead.shift_lead().is()) { // Balance if _last has more than one element. e.balance(); } else { e._lead = e._lead.shift_lead(); return e; } } e._last = e._last.shift_lead(); if (!e._last.is()) { if (e._lead.shift_lead().is()) { e.balance(); } } return e; } let __reverse__(const list&amp; self) { if (__len__(self) &lt; 2) { return self; } list e; e._lead = self._last; e._last = self._lead; e._size = self._size; return e; } void list::balance() { // print(&quot;lead = &quot; + str(_lead) + &quot; : last = &quot; + str(_last)); bool_t flip = _last.is() &amp;&amp; !_lead.is(); if (flip) { std::swap(_lead, _last); } int_t i = _size &lt; 2 ? 1 : _size / 2; _lead = _lead.reverse(); _last = _last.reverse(); while (i-- &gt; 0) { _last = _last.place_lead(_lead.lead()); _lead = _lead.shift_lead(); } _lead = _lead.reverse(); _last = _last.reverse(); if (flip) { std::swap(_lead, _last); } // print(&quot;lead = &quot; + str(_lead) + &quot; : last = &quot; + str(_last)); } </code></pre> <pre class="lang-cpp prettyprint-override"><code>class number { typedef std::complex&lt;real_t&gt; num_t; public: number(); number(const number&amp; obj); number(const int_t&amp; value); virtual ~number(); friend str_t __type__(const number&amp; self); friend bool_t __is__(const number&amp; self); friend real_t __comp__(const number&amp; self, const let&amp; other); friend void __str__(stream_t&amp; out, const number&amp; self); friend void __repr__(stream_t&amp; out, const number&amp; self); private: num_t _value; }; number::number() : _value(0.0, 0.0) { } number::number(const number&amp; obj) : _value(obj._value) { } number::number(const int_t&amp; value) : _value(value, 0.0) { } number::~number() { } str_t __type__(const number&amp; self) { return &quot;number&quot;; } bool_t __is__(const number&amp; self) { if (__nan__(self)) { return false; } return (self._value.real() || self._value.imag() ? true : false); } real_t __comp__(const number&amp; self, const let&amp; other) { const number* n = other.cast&lt;number&gt;(); if (n) { if (__nan__(self) || __nan__(*n) || __complex__(self) || __complex__(*n)) { return NOT_A_NUMBER; } real_t x = self._value.real(); real_t y = n-&gt;_value.real(); if (x &gt; y) { return 1.0; } if (x &lt; y) { return -1.0; } return 0.0; } return NOT_A_NUMBER; } void __str__(stream_t&amp; out, const number&amp; self) { real_t real = self._value.real(); real_t imag = self._value.imag(); if (imag &amp;&amp; !real) { out &lt;&lt; imag &lt;&lt; &quot;j&quot;; return; } if (!imag &amp;&amp; real) { out &lt;&lt; real; return; } if (!real &amp;&amp; !imag) { out &lt;&lt; 0.0; return; } out &lt;&lt; &quot;(&quot; &lt;&lt; real &lt;&lt; &quot;,&quot;; out.setf(std::ios::showpos); out &lt;&lt; imag &lt;&lt; &quot;j)&quot;; out.unsetf(std::ios::showpos); } void __repr__(stream_t&amp; out, const number&amp; self) { out &lt;&lt; &quot;\'&quot;; __str__(out, self); out &lt;&lt; &quot;\'&quot;; } </code></pre> <p>The let class and support classes / functions.</p> <pre class="lang-cpp prettyprint-override"><code> #if _WIN32 || _WIN64 #if _WIN64 using int_t = long int; #else using int_t = int; #endif #endif #if __GNUC__ #if __x86_64__ || __ppc64__ using int_t = long int; #else using int_t = int; #endif #endif typedef bool bool_t; typedef long double real_t; typedef std::string str_t; typedef std::stringstream stream_t; static const real_t NOT_A_NUMBER = std::numeric_limits&lt;real_t&gt;::quiet_NaN(); static const std::hash&lt;str_t&gt; DEFAULT_HASH_FUNCTION; /********************************************************************************************/ // // 'let' Class Definition // // The 'let' class represents an immutable object wrapper. It will accept // any object assigned to by the assignment operator '='. // Example: let a = 42; // // The fundamental structure of the 'let' data type was inspired and extended // from a presentation entitled: // Title: Value Semantics and Concept-based Polymorphism // By - Sean Parent // (http://sean-parent.stlab.cc/papers-and-presentations) // /********************************************************************************************/ class let { public: let(); template &lt;typename T&gt; let(T x); template &lt;typename T&gt; let(T* x); template &lt;typename T&gt; const T* cast() const; // Cast the object as an instance of the specified type. str_t id() const; // Return the typeid of the object. bool_t is_type(const let&amp; other) const; // Compair two objects by typeid. std::size_t hash() const; // Get the hash of an object. str_t type() const; // The class generated type name. bool_t is() const; // Is or is not the object defined. void str(stream_t&amp; out) const; // String representation of the object. void repr(stream_t&amp; out) const; real_t comp(const let&amp; other) const; // Compare two objects. 0 = equality, &gt; 0 = grater than, &lt; 0 = less than. bool_t eq(const let&amp; other) const; // Equal to. bool_t ne(const let&amp; other) const; // Not equal to. bool_t ge(const let&amp; other) const; // Greater than equal to. bool_t le(const let&amp; other) const; // Less than equal to. bool_t gt(const let&amp; other) const; // Greater than. bool_t lt(const let&amp; other) const; // Less than. int_t len() const; // Length of an object. let lead() const; // Lead element of an object. let last() const; // Last element of an object. let place_lead(const let&amp; other) const; // Place an object as the lead element. let shift_lead() const; // Remove the lead element from an object. let place_last(const let&amp; other) const; // Place an object as the last element. let shift_last() const; // Remove the last element from an object. let reverse() const; // Reverse the order of an object's elements. bool_t is_nothing() const; bool_t nan() const; bool_t complex() const; // General object operator overloads. bool_t operator==(const let&amp; other) const; bool_t operator!=(const let&amp; other) const; bool_t operator&gt;=(const let&amp; other) const; bool_t operator&gt; (const let&amp; other) const; bool_t operator&lt;=(const let&amp; other) const; bool_t operator&lt; (const let&amp; other) const; private: struct interface_t { /********************************************************************************************/ // // 'interface_t' Class Definition // // A simple interface description allowing redirection of the 'let' data type. // /********************************************************************************************/ virtual ~interface_t() = default; virtual operator bool() const = 0; virtual void* __as() = 0; virtual str_t __id() const = 0; virtual std::size_t __hash() const = 0; virtual str_t __type() const = 0; virtual bool_t __is() const = 0; virtual void __str(stream_t&amp; out) const = 0; virtual void __repr(stream_t&amp; out) const = 0; virtual real_t __comp(const let&amp; other) const = 0; virtual int_t __len() const = 0; virtual let __lead() const = 0; virtual let __last() const = 0; virtual let __place_lead(const let&amp; other) const = 0; virtual let __shift_lead() const = 0; virtual let __place_last(const let&amp; other) const = 0; virtual let __shift_last() const = 0; virtual let __reverse() const = 0; virtual bool_t __is_nothing() const = 0; virtual bool_t __nan() const = 0; virtual bool_t __complex() const = 0; }; template &lt;typename T&gt; struct data_t : interface_t { /******************************************************************************************/ // // 'data_t' Class Definition // // The int_terface implementation of the 'interface_t' data type. // Defining a shared const point_ter of the data type passed to it. // /******************************************************************************************/ data_t(T val); operator bool() const; void* __as(); str_t __id() const; std::size_t __hash() const; str_t __type() const; bool_t __is() const; void __str(stream_t&amp; out) const; void __repr(stream_t&amp; out) const; real_t __comp(const let&amp; other) const; int_t __len() const; let __lead() const; let __last() const; let __place_lead(const let&amp; other) const; let __shift_lead() const; let __place_last(const let&amp; other) const; let __shift_last() const; let __reverse() const; bool_t __is_nothing() const; bool_t __nan() const; bool_t __complex() const; T _data; }; std::shared_ptr&lt;const interface_t&gt; _self; }; /********************************************************************************************/ // // 'nothing' Class Definition // // A basic class definition of the value of nothing. This is used within // 'let' class implementation to return a result of nothing for results // which have either conflicting types, or in some cases as the default to // return unless overridden. // // This class also demonstrates the basic function methods that should be // over written for proper object behavior. // /********************************************************************************************/ class nothing { public: nothing(); nothing(const nothing&amp; obj); virtual ~nothing(); friend str_t __type__(const nothing&amp; self); friend bool_t __is__(const nothing&amp; self); friend real_t __comp__(const nothing&amp; self, const let&amp; other); friend void __str__(stream_t&amp; out, const nothing&amp; self); friend void __repr__(stream_t&amp; out, const nothing&amp; self); friend bool_t __is_nothing__(const nothing&amp; self); }; /********************************************************************************************/ // // '__node__' Class Definition // // The __node__ class is implimented using Lisp inspired data nodes. It // is used to define the data lists as in Lisp. // /********************************************************************************************/ class __node__ { let _data; let _next; public: __node__(); __node__(const __node__&amp; exp); __node__(let obj); virtual ~__node__(); friend str_t __type__(const __node__&amp; self); friend bool_t __is__(const __node__&amp; self); friend real_t __comp__(const __node__&amp; self, const let&amp; other); friend void __str__(stream_t&amp; out, const __node__&amp; self); friend void __repr__(stream_t&amp; out, const __node__&amp; self); friend int_t __len__(const __node__&amp; self); friend let __lead__(const __node__&amp; self); friend let __last__(const __node__&amp; self); friend let __place_lead__(const __node__&amp; self, const let&amp; other); friend let __shift_lead__(const __node__&amp; self); friend let __reverse__(const __node__&amp; self); }; /********************************************************************************************/ // // Basic Primitive Declarations // // These definitions add a few useful and some necessary support functions. // /********************************************************************************************/ inline void print(); // Simply print a new line. inline void print(const str_t&amp; str); // Accept any single string and print it with a std::endl. inline void print(const let&amp; a); // Accept any single 'let' and print it with a std::endl. str_t str(const let&amp; a); // Convert any 'let' to a str_t. /********************************************************************************************/ // // 'let' Class Function Default Template API. // // The following function templates define the over-ridable functions which // may be used to tailor the behavior of any object held within a 'let'. // // Each function defined here defines the default behavior of each function // which is invoked if a function is not overwritten for a defined class. // /********************************************************************************************/ template&lt;typename T&gt; /**** Hash Value ****/ std::size_t __hash__(const T&amp; self); template&lt;typename T&gt; std::size_t __hash__(const T&amp; self) { return DEFAULT_HASH_FUNCTION(repr(self)); } template&lt;typename T&gt; /**** Type Name ****/ str_t __type__(const T&amp; self); template&lt;typename T&gt; str_t __type__(const T&amp; self) { return typeid(self).name(); } template&lt;typename T&gt; /**** Boolean Conversion ****/ bool_t __is__(const T&amp; self); template&lt;typename T&gt; bool_t __is__(const T&amp; self) { return false; } template&lt;typename T&gt; /**** String Conversion ****/ void __str__(stream_t&amp; out, const T&amp; self); template&lt;typename T&gt; void __str__(stream_t&amp; out, const T&amp; self) { out &lt;&lt; &quot;object&lt;&quot; &lt;&lt; &amp;self &lt;&lt; &quot;,&quot; &lt;&lt; __type__(self) &lt;&lt; &quot;&gt;&quot;; } template&lt;typename T&gt; /**** String Representation ****/ void __repr__(stream_t&amp; out, const T&amp; self); template&lt;typename T&gt; void __repr__(stream_t&amp; out, const T&amp; self) { out &lt;&lt; str(nothing()); } template&lt;typename T&gt; /**** Comparison Between Variables ****/ real_t __comp__(const T&amp; self, const let&amp; other); template&lt;typename T&gt; real_t __comp__(const T&amp; self, const let&amp; other) { return NOT_A_NUMBER; } template&lt;typename T&gt; /**** Length Of ****/ int_t __len__(const T&amp; self); template&lt;typename T&gt; int_t __len__(const T&amp; self) { return 0; } template&lt;typename T&gt; /**** Lead Element Of ****/ let __lead__(const T&amp; self); template&lt;typename T&gt; let __lead__(const T&amp; self) { return nothing(); } template&lt;typename T&gt; /**** Last Element Of ****/ let __last__(const T&amp; self); template&lt;typename T&gt; let __last__(const T&amp; self) { return nothing(); } template&lt;typename T&gt; /**** Perpend Lead Element Of ****/ let __place_lead__(const T&amp; self, const let&amp; other); template&lt;typename T&gt; let __place_lead__(const T&amp; self, const let&amp; other) { return nothing(); } template&lt;typename T&gt; /**** Left Shift Remove ****/ let __shift_lead__(const T&amp; self); template&lt;typename T&gt; let __shift_lead__(const T&amp; self) { return nothing(); } template&lt;typename T&gt; /**** Postpend Last Element Of ****/ let __place_last__(const T&amp; self, const let&amp; other); template&lt;typename T&gt; let __place_last__(const T&amp; self, const let&amp; other) { return nothing(); } template&lt;typename T&gt; /**** Right Shift Remove ****/ let __shift_last__(const T&amp; self); template&lt;typename T&gt; let __shift_last__(const T&amp; self) { return nothing(); } template&lt;typename T&gt; /**** Reverse The Elements Of ****/ let __reverse__(const T&amp; self); template&lt;typename T&gt; let __reverse__(const T&amp; self) { return nothing(); } template&lt;typename T&gt; /**** Is Nothing Type ****/ bool_t __is_nothing__(const T&amp; self); template&lt;typename T&gt; bool_t __is_nothing__(const T&amp; self) { return false; } template&lt;typename T&gt; /**** Is Not A Number ****/ bool_t __nan__(const T&amp; self); template&lt;typename T&gt; bool_t __nan__(const T&amp; self) { return false; } template&lt;typename T&gt; /**** Is A Complex Number ****/ bool_t __complex__(const T&amp; self); template&lt;typename T&gt; bool_t __complex__(const T&amp; self) { return false; } /********************************************************************************************/ // // 'nothing' Class Implimentation // /********************************************************************************************/ nothing::nothing() { } nothing::nothing(const nothing&amp; obj) { } nothing::~nothing() { } str_t __type__(const nothing&amp; self) { return &quot;nothing&quot;; } bool_t __is__(const nothing&amp; self) { return false; } real_t __comp__(const nothing&amp; self, const let&amp; other) { return other.is_nothing() ? 0.0 : NOT_A_NUMBER; } void __str__(stream_t&amp; out, const nothing&amp; self) { out &lt;&lt; &quot;nothing&quot;; } void __repr__(stream_t&amp; out, const nothing&amp; self) { __str__(out, self); } bool_t __is_nothing__(const nothing&amp; self) { return true; } /********************************************************************************************/ // // '__node__' Class Implimentation // /********************************************************************************************/ __node__::__node__() : _data(), _next() { } __node__::__node__(const __node__&amp; exp) : _data(exp._data), _next(exp._next) { } __node__::__node__(let object) : _data(object), _next() { } __node__::~__node__() { } std::string __type__(const __node__&amp; self) { return &quot;__node__&quot;; } bool_t __is__(const __node__&amp; self) { if (self._data.is_nothing()) { return false; } return true; } real_t __comp__(const __node__&amp; self, const let&amp; other) { const __node__* p = other.cast&lt;__node__&gt;(); if (p) { let a = self; let b = *p; while (a.is() &amp;&amp; b.is()) { if (a.lead() != b.lead()) { return NOT_A_NUMBER; } a = a.shift_lead(); b = b.shift_lead(); } if (!a.is() &amp;&amp; !b.is()) { return 0.0; } } return NOT_A_NUMBER; } void __str__(stream_t&amp; out, const __node__&amp; self) { if (!__is__(self)) { return; } let e = self; bool_t next = false; do { out &lt;&lt; str(e.lead()); e = e.shift_lead(); next = e.is(); if (next) { out &lt;&lt; &quot; &quot;; } } while (next); } void __repr__(stream_t&amp; out, const __node__&amp; self) { if (!__is__(self)) { return; } let e = self; bool_t next = false; do { out &lt;&lt; repr(e.lead()); e = e.shift_lead(); next = e.is(); if (next) { out &lt;&lt; &quot; &quot;; } } while (next); } int_t __len__(const __node__&amp; self) { if (!__is__(self)) { return 0; } int_t size = 1; let next = self._next; while (next.is()) { size += 1; next = next.shift_lead(); } return size; } let __lead__(const __node__&amp; self) { return self._data; } let __last__(const __node__&amp; self) { if (self._next.is_nothing()) { return self; } let next = self; while (next.shift_lead().is()) { next = next.shift_lead(); } return next; } let __place_lead__(const __node__&amp; self, const let&amp; other) { if (other.is_nothing()) { return self; } __node__ a(other); if (__is__(self)) { a._next = self; } return a; } let __shift_lead__(const __node__&amp; self) { if (self._next.is_nothing()) { return __node__(); } return self._next; } let __reverse__(const __node__&amp; self) { if (self._next.is_nothing()) { return self; } let a = __node__(); let next = self; while (next.is()) { a = a.place_lead(next.lead()); next = next.shift_lead(); } return a; } /********************************************************************************************/ // // 'let' Class Implementation // /********************************************************************************************/ let::let() : _self(std::make_shared&lt;data_t&lt;Olly::nothing&gt;&gt;(Olly::nothing())) { } template &lt;typename T&gt; let::let(T x) : _self(std::make_shared&lt;data_t&lt;T&gt;&gt;(std::move(x))) { } template &lt;typename T&gt; let::let(T* x) : _self(std::make_shared&lt;data_t&lt;T&gt;&gt;(x)) { } template &lt;typename T&gt; const T* let::cast() const { const T* p = static_cast&lt;T*&gt;(const_cast&lt;interface_t*&gt;(_self.get())-&gt;__as()); if (p) { return p; } return nullptr; } str_t let::id() const { return _self-&gt;__id(); } bool_t let::is_type(const let&amp; other) const { return _self-&gt;__id() == other._self-&gt;__id(); } std::size_t let::hash() const { return _self-&gt;__hash(); } str_t let::type() const { return _self-&gt;__type(); } bool_t let::is() const { return const_cast&lt;interface_t*&gt;(_self.get())-&gt;__is(); } void let::str(stream_t&amp; out) const { _self-&gt;__str(out); } void let::repr(stream_t&amp; out) const { _self-&gt;__repr(out); } real_t let::comp(const let&amp; other) const { return _self-&gt;__comp(other); } bool_t let::eq(const let&amp; other) const { return (comp(other) == 0 ? true : false); } bool_t let::ne(const let&amp; other) const { return (comp(other) != 0 ? true : false); } bool_t let::ge(const let&amp; other) const { return (comp(other) &gt;= 0 ? true : false); } bool_t let::le(const let&amp; other) const { return (comp(other) &lt;= 0 ? true : false); } bool_t let::gt(const let&amp; other) const { return (comp(other) &gt; 0 ? true : false); } bool_t let::lt(const let&amp; other) const { return (comp(other) &lt; 0 ? true : false); } int_t let::len() const { return _self-&gt;__len(); } let let::lead() const { return _self-&gt;__lead(); } let let::last() const { return _self-&gt;__last(); } let let::place_lead(const let&amp; other) const { return _self-&gt;__place_lead(other); } let let::shift_lead() const { return _self-&gt;__shift_lead(); } let let::place_last(const let&amp; other) const { return _self-&gt;__place_last(other); } let let::shift_last() const { return _self-&gt;__shift_last(); } let let::reverse() const { return _self-&gt;__reverse(); } bool_t let::is_nothing() const { return _self-&gt;__is_nothing(); } bool_t let::nan() const { return _self-&gt;__nan(); } bool_t let::complex() const { return _self-&gt;__complex(); } bool_t let::operator==(const let&amp; other) const { return eq(other); } bool_t let::operator!=(const let&amp; other) const { return ne(other); } bool_t let::operator&gt;=(const let&amp; other) const { return ge(other); } bool_t let::operator&gt; (const let&amp; other) const { return gt(other); } bool_t let::operator&lt;=(const let&amp; other) const { return le(other); } bool_t let::operator&lt; (const let&amp; other) const { return lt(other); } /********************************************************************************************/ // // 'data_t' Class Implementation // /********************************************************************************************/ template &lt;typename T&gt; let::data_t&lt;T&gt;::data_t(T val) : _data(std::move(val)) { } template &lt;typename T&gt; let::data_t&lt;T&gt;::operator bool() const { return __is(); } template &lt;typename T&gt; void* let::data_t&lt;T&gt;::__as() { return &amp;_data; } template &lt;typename T&gt; str_t let::data_t&lt;T&gt;::__id() const { return typeid(_data).name(); } template &lt;typename T&gt; std::size_t let::data_t&lt;T&gt;::__hash() const { return __hash__(_data); } template &lt;typename T&gt; str_t let::data_t&lt;T&gt;::__type() const { return __type__(_data); } template &lt;typename T&gt; bool_t let::data_t&lt;T&gt;::__is() const { return __is__(_data); } template &lt;typename T&gt; void let::data_t&lt;T&gt;::__str(stream_t&amp; out) const { __str__(out, _data); } template &lt;typename T&gt; void let::data_t&lt;T&gt;::__repr(stream_t&amp; out) const { __repr__(out, _data); } template &lt;typename T&gt; real_t let::data_t&lt;T&gt;::__comp(const let&amp; other) const { return __comp__(_data, other); } template &lt;typename T&gt; int_t let::data_t&lt;T&gt;::__len() const { return __len__(_data); } template &lt;typename T&gt; let let::data_t&lt;T&gt;::__lead() const { return __lead__(_data); } template &lt;typename T&gt; let let::data_t&lt;T&gt;::__last() const { return __last__(_data); } template &lt;typename T&gt; let let::data_t&lt;T&gt;::__place_lead(const let&amp; other) const { return __place_lead__(_data, other); } template &lt;typename T&gt; let let::data_t&lt;T&gt;::__shift_lead() const { return __shift_lead__(_data); } template &lt;typename T&gt; let let::data_t&lt;T&gt;::__place_last(const let&amp; other) const { return __place_last__(_data, other); } template &lt;typename T&gt; let let::data_t&lt;T&gt;::__shift_last() const { return __shift_last__(_data); } template &lt;typename T&gt; let let::data_t&lt;T&gt;::__reverse() const { return __reverse__(_data); } template &lt;typename T&gt; bool_t let::data_t&lt;T&gt;::__is_nothing() const { return __is_nothing__(_data); } template &lt;typename T&gt; bool_t let::data_t&lt;T&gt;::__nan() const { return __nan__(_data); } template &lt;typename T&gt; bool_t let::data_t&lt;T&gt;::__complex() const { return __complex__(_data); } /********************************************************************************************/ // // Basic Primitive Implementations // /********************************************************************************************/ void print() { std::cout &lt;&lt; std::endl; } void print(const str_t&amp; str) { std::cout &lt;&lt; str &lt;&lt; std::endl; } void print(const let&amp; a) { print(str(a)); } str_t str(const let&amp; a) { /* Convert a 'let' to its string representation. */ stream_t stream; stream &lt;&lt; std::boolalpha; if (a.type() == &quot;format&quot;) { /* The 'format' data type must be printed using its string representation, else it would only impart its formating to the stream instead of being printed to it. */ a.repr(stream); } else { a.str(stream); } return stream.str(); } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T04:02:05.927", "Id": "501241", "Score": "1", "body": "Double underscore in an identifier is a no no - [What are the rules about using an underscore in a C++ identifier?](https://stackoverflow.com/q/228783/14065)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T13:11:58.133", "Id": "501261", "Score": "0", "body": "Thank you for the heads up on the underscore rules! I was not aware of them. I used that pattern to identify visually what level of function overloading I am working on. Since I typically use a single underscore for private variables I choose two underscores to document the overloads. I will come up with another solution for that." } ]
[ { "body": "<h1>Try to write ideomatic C++</h1>\n<p>Your code doesn't really look like the typical C++ you will find in many other projects. For example, the name of every member function that is not a constructor or destructor is surrounded by double underscores. Apart from the <a href=\"https://stackoverflow.com/q/228783/14065\">issues with using underscores</a> already mentioned by Martin York, this is very uncommon. It requires more typing and I am not sure the sheer quantity of underscores in your code is helping with readability.</p>\n<p>Furthermore, you are creating <code>typedef</code>s for all the types you are using, but this is not really helping matters. Some issues for example are:</p>\n<ul>\n<li><code>bool_t</code> is longer to type than <code>bool</code></li>\n<li><code>int_t</code> does not tell you what size the integer is, and apparently it can either be a <code>long int</code> or a regular <code>int</code>, but the sizes of those types are not guaranteed to be what you think either.</li>\n<li>In general, you are hiding the underlying type, and while that is sometimes a good thing, as someone who is not familiar with your code, now I'm constantly having to guess whether <code>str_t</code> is the same as a <code>std::string</code>, if <code>stream_t</code> is a <code>std::stringstream</code> or any other kind of stream, like <code>std::ofstream</code> for example.</li>\n</ul>\n<p>I recommend you don't <code>typedef</code> anything. It doesn't require that much extra typing, especially not if you use more <code>auto</code>.</p>\n<p>Another issue is terminology. It's very uncommon to see the terms &quot;lead&quot; and &quot;last&quot; used, normally it is &quot;head&quot; and &quot;tail&quot; for a list, and the STL uses &quot;front&quot; and &quot;back&quot; for the first and last element of a container.</p>\n<h1>Use of <code>let</code></h1>\n<p>I'm not really sure I like the use of <code>let</code>. It hides the types and introduces a lot of overhead. For example:</p>\n<pre><code>let a = 42;\n</code></pre>\n<p><code>a</code> contains a pointer to an instance of <code>data_t&lt;int&gt;</code>, and the latter inherits from a base class with virtual functions, so it also contains a pointer to a <a href=\"https://en.wikipedia.org/wiki/Virtual_method_table\" rel=\"nofollow noreferrer\">vtable</a>. To do something simple as getting the value of <code>a</code> back, like in:</p>\n<pre><code>int value = *a.cast&lt;int&gt;();\n</code></pre>\n<p>The compiler will first dereference the pointer to <code>data_t&lt;int&gt;</code>, then dereference the pointer to the vtable, then look up the pointer to <code>__as</code> in that table, and then call through that pointer, just to get the address to the actual <code>int</code> value, which the caller then still has to dereference. All that for just an <code>int</code>! Apart from that, you lose type safety because the caller now has to know what the actual type was that was stored in the <code>let</code> object, but the compiler will not warn you if you would write <code>a.cast&lt;double&gt;()</code>.</p>\n<p>So, if you want an immutable <code>int</code>, why not just use <code>const</code>?</p>\n<pre><code>const int a = 42;\n</code></pre>\n<h1>Making an immutable list using the STL</h1>\n<p>So you want to be able to create new lists without creating/copying the nodes. But behind the scenes you are using a <code>std::shared_ptr</code> anyway to ensure you can copy <code>let</code> objects. So what you can do instead, is use the standard library to create a list of shared pointers to <code>const int</code>s:</p>\n<pre><code>std::list&lt;std::shared_ptr&lt;const int&gt;&gt; my_list = {std::make_shared&lt;int&gt;(42)};\nmy_list.push_back(std::make_shared&lt;int&gt;(123));\n</code></pre>\n<p>The <em>contents</em> are immutable, for example the following will not compile:</p>\n<pre><code>*my_list.front() = 0;\n</code></pre>\n<p>I would use this as a basis to create an immutable list class, for example like so:</p>\n<pre><code>template&lt;typename T&gt;\nclass immutable_list {\n std::list&lt;std::shared_ptr&lt;const T&gt;&gt; data;\n\npublic:\n // Constructors\n immutable_list() = default;\n immutable_list(const T &amp;value): data{std::make_shared&lt;T&gt;(value)} {}\n ...\n\n // Member functions returning modified lists\n immutable_list push_front(const T &amp;value) {\n immutable_list result = *this;\n result.data.emplace_front(std::make_shared&lt;T&gt;(value));\n return result;\n }\n ...\n\n // Member functions accessing list contents\n std::size_t size() {\n return data.size();\n }\n\n const T &amp;front() {\n return *data.front();\n }\n ...\n};\n</code></pre>\n<p>And then you can use it like so:</p>\n<pre><code>auto foo = immutable_list(42);\nfoo = foo.push_front(123);\nstd::cout &lt;&lt; foo.front() &lt;&lt; &quot;\\n&quot;;\n</code></pre>\n<p>You probably should write wrappers for all the member functions of <code>std::list</code>, including for the iterators, so you can write something like this:</p>\n<pre><code>for (auto &amp;value: foo) {\n std::cout &lt;&lt; value &lt;&lt; &quot;\\n&quot;;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T18:46:14.190", "Id": "501289", "Score": "0", "body": "Thank you for the answer! A point I think needs to clarified. The class `let` is being used to invoke method overloading on the derived datatypes passed to `let`, using the interface to `data_t` to call the friend function of each data type held by the specific instance of `let`. Including that the list can hold a reference to itself as an element of data. `l = [a b c]`, `l.place_lead(l)` then results in `l = [[a b c] a b c]`. That way the interpreter doesn't need to know what data type it is using the `let` class manages both that and memory management of the data type." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T17:35:04.067", "Id": "254183", "ParentId": "254153", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T21:25:51.587", "Id": "254153", "Score": "2", "Tags": [ "c++", "performance", "immutability" ], "Title": "Immutable interpreter in C++" }
254153
<p><a href="https://getbootstrap.com/" rel="nofollow noreferrer">Bootstrap 4</a> is the fourth major version of the popular front-end component library and open-source toolkit for developing with HTML, CSS, and JS. The Bootstrap framework aids in the creation of responsive, mobile-first websites and web apps. Bootstrap 4 embraces flexbox and SASS technologies. Bootstrap is open-sourced on <a href="https://github.com/twbs/bootstrap" rel="nofollow noreferrer">GitHub</a>.</p> <p>The latest release is <a href="https://getbootstrap.com/docs/4.5/getting-started/introduction/" rel="nofollow noreferrer"><code>4.5.0</code></a>.</p> <h3>Stack Snippet Starter Pack</h3> <pre class="lang-html prettyprint-override"><code>&lt;link rel=&quot;stylesheet&quot; href=&quot;https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css&quot; integrity=&quot;sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk&quot; crossorigin=&quot;anonymous&quot;&gt; &lt;script src=&quot;https://code.jquery.com/jquery-3.5.1.slim.min.js&quot; integrity=&quot;sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt; &lt;script src=&quot;https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js&quot; integrity=&quot;sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt; &lt;script src=&quot;https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js&quot; integrity=&quot;sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt; </code></pre> <h3>Helpful Resources</h3> <p><a href="https://getbootstrap.com/docs/4.5/getting-started/introduction/" rel="nofollow noreferrer">Official Documentation</a><br> <a href="https://getbootstrap.com/docs/4.5/getting-started/introduction/#starter-template" rel="nofollow noreferrer">Official Starter Template</a><br> <a href="https://getbootstrap.com/docs/4.5/layout/grid/" rel="nofollow noreferrer">Layout with the Grid System</a><br> <a href="https://getbootstrap.com/docs/4.5/components/" rel="nofollow noreferrer">Bootstrap 4 Components</a><br> <a href="https://getbootstrap.com/docs/4.5/utilities" rel="nofollow noreferrer">Bootstrap 4 Utility Classes</a><br></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T22:29:49.280", "Id": "254155", "Score": "0", "Tags": null, "Title": null }
254155
Bootstrap 4 is the fourth major version of the popular front-end component library. The Bootstrap framework aids in the creation of responsive, mobile-first websites and web apps.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T22:29:49.280", "Id": "254156", "Score": "0", "Tags": null, "Title": null }
254156
<p>I'm wondering if there is a more efficient way of filtering a dataframe down based on certain unique values in several columns. Once I have it filtered down, I then want to extract keep one the largest value and I do this by dropping all indexes from the original dataframe. However, this process is slow and as the iterations and number of items in the dataframe increase the speed becomes more of an issue.</p> <pre><code>import pandas as pd import numpy as np import timeit data_len = 1000 half = int(data_len/2) fifth = int(data_len/5) ans = ['Cat'] * data_len cols = ['White'] * half + ['Black'] * half age = np.random.randint(1, 10, data_len) breed = ['A'] * fifth + ['B'] * fifth + ['C'] * fifth + ['D'] * fifth + ['E'] * fifth weights = np.random.uniform(1, 100, data_len) heights = np.random.uniform(1, 100, data_len) df = pd.DataFrame(columns=['Animal', 'Color', 'Age', 'Breed', 'Weight', 'Height']) df['Animal'] = ans df['Color'] = cols df['Age'] = age df['Breed'] = breed df['Weight'] = weights df['Height'] = heights def get_largest(df): drop_id = [] sort_cols = ['Weight', 'Height'] for Animal in pd.unique(df['Animal']): animals_df = df.loc[np.in1d(df['Animal'], Animal)] for Color in pd.unique(animals_df['Color']): color_df = animals_df.loc[np.in1d(animals_df['Color'], Color)] for uid in pd.unique(color_df['Age']): age_df = color_df.loc[np.in1d(color_df['Age'], uid)] for vic in pd.unique(age_df['Breed']): breed_df = age_df.loc[np.in1d(age_df['Breed'], vic)] drop_id.extend( breed_df.sort_values(by=sort_cols, ascending=[False] * len(sort_cols)).index[1:].values) df = df.drop(df.index[drop_id]) return df func = lambda: get_largest(df) print(timeit.timeit(func, number=100)) </code></pre>
[]
[ { "body": "<p>I may have misunderstood what your are trying to achieve. However it sounds like you want to filter your dataframe for a unique list animal, color, age and breed. and from that take that largest, weight and height.</p>\n<p>you could achieve this by sorting your data frame by weight then height this will sort from lowest to highest.</p>\n<p>you can then drop duplicates based on the animal, color, age and breed and specify to the drop method to keep the last row(This will be the biggest since the table is ordered from low to high).</p>\n<p>We can write this in a general function that will accept three parameters, a df, a list to sort by and a list to filter by.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def my_df_filter(df: pd.DataFrame, sort_by: List[str], drop_by: List[str]) -&gt; pd.DataFrame:\n sorted_df = df.sort_values(by=sort_by)\n dropped_df = sorted_df.drop_duplicates(subset=drop_by, keep='last')\n return dropped_df\n</code></pre>\n<p>This could actually all be returned in a single line by chaining them together. However I have broken it down for more readability. But you could write as</p>\n<pre class=\"lang-py prettyprint-override\"><code>def my_df_filter1(df: pd.DataFrame, sort_by: List[str], drop_by: List[str]) -&gt; pd.DataFrame:\n return df.sort_values(by=sort_by).drop_duplicates(subset=drop_by, keep='last')\n</code></pre>\n<p>using your original code and a dataset of 100,000 rows. it reduced it from 100k rows to 54 rows and running it 100 times via timeit on my laptop took around 18 seconds.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import pandas as pd\nimport numpy as np\nimport timeit\nfrom typing import List\n\ndef my_df_filter(df: pd.DataFrame, sort_by: List[str], drop_by: List[str]) -&gt; pd.DataFrame:\n return df.sort_values(by=sort_by).drop_duplicates(subset=drop_by, keep='last')\n\n\ndata_len = 100000\nhalf = int(data_len / 2)\nfifth = int(data_len / 5)\ndata = {\n 'Animal': ['Cat'] * data_len,\n 'Color': ['White'] * half + ['Black'] * half,\n 'Age': np.random.randint(1, 10, data_len),\n 'Breed': ['A'] * fifth + ['B'] * fifth + ['C'] * fifth + ['D'] * fifth + ['E'] * fifth,\n 'Weight': np.random.uniform(1, 100, data_len),\n 'Height': np.random.uniform(1, 100, data_len)\n}\ndf = pd.DataFrame(data)\n\nprint(df.shape)\nprint(my_df_filter(df, sort_by=['Weight', 'Height'], drop_by=['Animal', 'Color', 'Age', 'Breed']).shape)\n\nfunc = lambda: my_df_filter(df, sort_by=['Weight', 'Height'], drop_by=['Animal', 'Color', 'Age', 'Breed'])\nprint(timeit.timeit(func, number=100))\n</code></pre>\n<p><strong>OUTPUT</strong></p>\n<pre class=\"lang-none prettyprint-override\"><code>(100000, 6)\n(54, 6)\n18.2784114\n</code></pre>\n<p>Having a general function means that its much easier to increase or reduce the number of columns to filter or sort by without having to change much code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T02:07:51.067", "Id": "254201", "ParentId": "254158", "Score": "1" } } ]
{ "AcceptedAnswerId": "254201", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-12-31T23:12:25.073", "Id": "254158", "Score": "4", "Tags": [ "python", "pandas" ], "Title": "Filter dataframe based on unique values in multiple columns and drop rows based on index" }
254158
<p>I have a short function written in JavaScript using jQuery which takes a message and appends it to a div. It does this one character at a time with a small delay between characters, and then returns the time that it took it will take for the function to finish running.</p> <pre><code>const log = $('#log') function logMessage(message, type) { log.append('&lt;div&gt;&lt;/div&gt;') log.children().last().addClass(type); for (let charIndex = 0; charIndex &lt; message.length; charIndex++) setTimeout(() =&gt; { log.children().last().append(message[charIndex]) }, charIndex * 10) return message.length * 10 } </code></pre> <p>This code feels a little bit unoptimized but I'm not sure what would be a better of going about doing this.</p>
[]
[ { "body": "<p>You're using the right approach with the <code>log</code> - you're saving it in a variable so you don't have to select the element again. Do the same thing with the newly appended <code>&lt;div&gt;</code>.</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>const log = $('#log')\n\nfunction logMessage(message, type) {\n const newDiv = $('&lt;div&gt;&lt;/div&gt;')\n .addClass(type)\n .appendTo(log);\n for (let charIndex = 0; charIndex &lt; message.length; charIndex++) {\n setTimeout(() =&gt; {\n newDiv.append(message[charIndex])\n }, charIndex * 10)\n }\n}\n\nlogMessage('something with lots and lots and lots and lots of characters', 'sometype');</code></pre>\r\n<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;\n&lt;div id=\"log\"&gt;&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>A tiny issue with iterating over the indicies of the string manually is that characters composed of surrogate pairs (like ) will take twice as long to print as others, and if you were to slow down the animation, you'd get a broken character before the second part gets fully rendered:</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>const log = $('#log')\n\nfunction logMessage(message, type) {\n const newDiv = $('&lt;div&gt;&lt;/div&gt;')\n .addClass(type)\n .appendTo(log);\n for (let charIndex = 0; charIndex &lt; message.length; charIndex++) {\n setTimeout(() =&gt; {\n newDiv.append(message[charIndex])\n }, charIndex * 500)\n }\n}\n\nlogMessage('something with lots and lots and lots and lots of characters', 'sometype');</code></pre>\r\n<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;\n&lt;div id=\"log\"&gt;&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>It also might be useful to return a Promise indicating that the message has been fully logged, instead of a number indicating how long to wait before the message is finished.</p>\n<p>To tweak this, and to avoid having to touch the string indicies at all (since you only <em>really</em> care about the characters, not the indicies of characters) would be to invoke the string's iterator and <code>await</code> a Promise inside the loop:</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 log = $('#log');\nconst delay = ms =&gt; new Promise(resolve =&gt; setTimeout(resolve, ms));\n\nasync function logMessage(message, type) {\n const newDiv = $('&lt;div&gt;&lt;/div&gt;')\n .addClass(type)\n .appendTo(log);\n for (const char of message) {\n newDiv.append(char);\n await delay(500);\n }\n}\n\nlogMessage('something', 'sometype')\n .then(() =&gt; {\n console.log('message fully printed');\n });</code></pre>\r\n<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;\n&lt;div id=\"log\"&gt;&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>I'm a bit worried about the <code>log</code> ID - you have both a <a href=\"https://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables\">global identifier <code>log</code></a> which refers to the HTMLElement and exists on the window. Then the code shadows the global identifier and creates a <code>log</code> which refers to the jQuery collection. It's an unlikely source of bugs, but I'd use a class instead of an ID.</p>\n<p>I notice you're not using semicolons. If this is a deliberate style choice and you consider yourself an expert who can avoid the pitfalls of <a href=\"https://stackoverflow.com/questions/2846283/what-are-the-rules-for-javascripts-automatic-semicolon-insertion-asi\">Automatic Semicolon Insertion</a>, that's just fine. Otherwise, you may occasionally run into very confusing bugs due to a statement unexpectedly crossing a linebreak, and I'd recommend using them.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T02:10:05.123", "Id": "254165", "ParentId": "254162", "Score": "2" } }, { "body": "<h2>jQuery?</h2>\n<p>Is there a need for Jquery in this day and age. Interest in jQuery and demand for jQuery experience has been on the decline for years. Apart from the need to load a bulky library before you can even start access to the page via it, most of the functionality it provides is available via the much faster native API's. The main concern with jQuery is that you are not gaining experience using the native DOM API's</p>\n<h2>Avoid functions inside loops.</h2>\n<p>There is so much wrong with the following two expressions it painful to see.</p>\n<pre><code>for (let charIndex = 0; charIndex &lt; message.length; charIndex++)\n setTimeout(() =&gt; {\n log.children().last().append(message[charIndex])\n }, charIndex * 10)\n</code></pre>\n<ul>\n<li><p>Functions in loop are needless power hungry resource drains. Each iteration is creating a new function, closure, event stack entry, memory allocations (cleanable only via deferred GC). This is a lot of RAM and resources for a single character.</p>\n<p>Yes its safe because you used <code>let</code> (part of why <code>let</code> is so bad). Even with <code>let</code> or <code>const</code>, functions inside loops are not good practice in terms of performance.</p>\n</li>\n<li><p>No guarantee that the timers will fire at the times given <code>charIndex * 10</code></p>\n</li>\n<li><p>Would be better if you used the conventional for loop counter name <code>i</code></p>\n</li>\n<li><p>You should end lines with <code>;</code>. Unless you are fully clued in on how <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion\" rel=\"nofollow noreferrer\">ASI</a> works you should use semicolons. Those that learnt how API works seldom adopt a style that does not use <code>;</code></p>\n</li>\n<li><p>Did not delimit the loops code block with <code>{</code> <code>}</code>.</p>\n<p>Yes you can do without them as you can shoot yourself in the foot, but I strongly advice against either.</p>\n</li>\n</ul>\n<h2>Timers</h2>\n<p>Javascript timers are throttled and thus you can not rely on them firing on time.</p>\n<p>The reason timers are throttles is to extend battery life. Tests have shown that throttling timers can <a href=\"https://www.zdnet.com/article/chrome-javascript-timer-throttling-googles-tests-show-it-saves-up-to-2-hours-battery-life/\" rel=\"nofollow noreferrer\">extend battery life up to 2 hours</a></p>\n<p>Your function returns a time. This is only an estimation, when the actual timers have all fired will depend on many factors.</p>\n<p>Much of the throttling is performed when a tab is not focused. However even if you force the browser to respect timers (via browser flags not something you would ask a client to do) JavaScript execution is blocking, your own code will mean that timers will not fire when you want.</p>\n<h3>How to handle timed code</h3>\n<p>The best way (and also best for battery life) is to use only one timer. That timer then uses time to workout what to do.</p>\n<p>You can get a high resolutions time since page load via the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Performance\" rel=\"nofollow noreferrer\">Performance</a> interface. Eg <code>performance.now()</code> will return time in milliseconds with an accuracy of up to 1 microsecond (1/1,000,000 second)</p>\n<h3>Don't Update display &lt; 16.667ms</h3>\n<p>Browser display rates are 60FPS, displaying content at rates higher than this is pointless as anything displayed between frames will not be seen. Though it will still trigger re-flows (if you are sloppy) and force the display buffers to update (re-composite).</p>\n<p><code>setTimeout</code> and <code>setInterval</code> do not know anything about the display timing.</p>\n<p>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame\" rel=\"nofollow noreferrer\">requestAnimationFrame</a> when animating any type of page content, even if the update rates are low.</p>\n<p>Why...</p>\n<ul>\n<li><code>requestAnimationFrame</code> came with power saving in mind</li>\n<li>It cooperates with all the other page processes competing for time and visual content updates</li>\n<li>It is smart and knows when content is visible, and will only update when it matters.</li>\n<li>It is synced to the display so you know all the new content will be ready and visible for the next frame.</li>\n<li>It provides a high res microsecond time to the callback function. Though I prefer to use <code>performance.now</code> due to some ambiguity regarding the time the argument represents.</li>\n</ul>\n<h3>Example timed text via <code>requestAnimationFrame</code></h3>\n<p>The example shows a <code>textLogger</code> similar to yours that will display <code>text</code> at a given <code>rate</code> (in characters per second), updating a selected elements <code>el</code> display text.</p>\n<p><strong>Note</strong> that the center text is 100 chars per second matching your 10ms text.</p>\n<p><strong>Note</strong> When the text is updated as many characters as needed are display, it does not update one character at a time.</p>\n<p>Click to start timed text.</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 textLogger(text, rate, el) { // rate is chars per second\n const start = performance.now(), time = (text.length / rate) * 1000;\n (function tick() {\n const len = Math.round(text.length * (performance.now() - start) / time);\n if (len &lt; text.length) {\n el.textContent = text.slice(0, len + 1);\n requestAnimationFrame(tick); \n } else { \n el.textContent = text;\n }\n })();\n return time;\n}\naddEventListener(\"click\", () =&gt; {\n textLogger(\n \"Testing text logger at rate 60 chars per second. abcdefghijklmnopqrstuvwxyz\",\n 60, logger1);\n textLogger(\n \"Testing text logger at rate 100 chars per second. abcdefghijklmnopqrstuvwxyz\",\n 100, logger2);\n textLogger(\n \"Testing text logger at rate 20 chars per second. abcdefghijklmnopqrstuvwxyz\",\n 20, logger3); \n\n});</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>Click to start text loggers....&lt;br&gt;\n&lt;div id=\"logger1\"&gt;&lt;/div&gt;\n&lt;div id=\"logger2\"&gt;&lt;/div&gt;\n&lt;div id=\"logger3\"&gt;&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Personally good coding means doing all you can to benefit the client. Code that has little regard for the clients power is rude.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T15:00:32.173", "Id": "254176", "ParentId": "254162", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T01:24:30.127", "Id": "254162", "Score": "0", "Tags": [ "javascript", "jquery" ], "Title": "Simple terminal style message logger" }
254162
<p>Currently, I can set the the <code>current_user</code> in the <code>views.py</code> for a form, which requires the <code>user</code> object to validate the post (and its origin).</p> <p>Is there a better way to more eloquently set the user in a form than what I've posted below? Note, this is in <code>views.py</code> and I have no altered <code>forms</code> or <code>models</code> to tackle this aspect.</p> <pre><code>def index(request): article = Article.objects.all() if request.method == 'POST': form = ArticleForm(request.POST) # This segment below is the focal point of my question: if form.is_valid() and request.user.is_authenticated: form_object = form.save(commit=False) form_object.author = request.user form_object.save() return HttpResponseRedirect('to somewhere over the rainbow') else: # stuff </code></pre> <p>The code works. It just seems gimmicky to use a non-committed form, store it in a variable, alter the form object, then ultimately save it.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-03T20:06:44.593", "Id": "501474", "Score": "0", "body": "Well, the _right_ way to deal with this would be the have a `Form` which you can then prepopulate with the data you need" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-05T22:35:33.733", "Id": "501638", "Score": "0", "body": "Ah, understood. I'll edit `ArticleForm` in this example to do that." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T01:53:29.703", "Id": "254164", "Score": "2", "Tags": [ "python", "django" ], "Title": "Set logged-in USER in a Form requiring Current User Credentials" }
254164
<p>Here is an example where I'm trying to understand the concepts of buffered channels&gt; I have three functions and create a buffered channel of length 3. And also passed a waitgroup to nofiy when all the goroutines are done. And finally collecting the values through range.</p> <p>Could you please help me in reviewing this code? And where I could improve?</p> <pre><code>package main import ( &quot;fmt&quot; &quot;sync&quot; ) type f func(int, int, chan int, *sync.WaitGroup) func add(x, y int, r chan int, wg *sync.WaitGroup) { fmt.Println(&quot;Started Adding function....&quot;) r &lt;- (x + y) wg.Done() } func sub(x, y int, r chan int, wg *sync.WaitGroup) { fmt.Println(&quot;Started Difference function&quot;) r &lt;- (x - y) wg.Done() } func prod(x, y int, r chan int, wg *sync.WaitGroup) { fmt.Println(&quot;Started Prod function&quot;) r &lt;- (x * y) wg.Done() } func main() { var operations []f = []f{add, sub, prod} ch := make(chan int, len(operations)) wg := sync.WaitGroup{} x, y := 10, 20 wg.Add(len(operations)) for _, i := range operations { go i(x, y, ch, &amp;wg) } wg.Wait() close(ch) for val := range ch { fmt.Println(val) } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-05T14:27:31.597", "Id": "501581", "Score": "0", "body": "why would you wait to consume values from the channel until _after_ the waitgroup is done? Add 1 `r <- (x/y)` (or any other write to the channel) in any of the routines and the waitgroup will never finish (the channel buffer would be full, and a write would block). We use waitgroups specifically when we have routines do work, and we can't sensibly buffer the channel/output. We consume the channel while the work is being done, and wait for the waitgroup to be done to tidy up (close the channel etc...)" } ]
[ { "body": "<p>The code in the question cannot determine which result corresponds to which operation. Otherwise, the code is correct. Here are two alternatives for improving the code:</p>\n<h3>1. Eliminate the channel</h3>\n<ul>\n<li>Change the operations to simple functions that return an int. This makes it easier to test and reason about the implementation of the operations.</li>\n<li>Collect the results in a slice instead of in a channel. With this change, we know that result of operations[0] is at slice index 0, operations[1] is at slice index 1 and so on.</li>\n<li>Move all the waitgroup and goroutine related code together in main. This makes the concurrency aspect of the program easier to understand.</li>\n</ul>\n<p>Here's the code:</p>\n<pre><code>package main\n\nimport (\n &quot;fmt&quot;\n &quot;sync&quot;\n)\n\ntype f func(int, int) int\n\nfunc add(x, y int) int {\n return (x + y)\n}\n\nfunc sub(x, y int) int {\n return (x - y)\n}\n\nfunc prod(x, y int) int {\n return (x * y)\n}\n\nfunc main() {\n var operations []f = []f{add, sub, prod}\n\n\n x, y := 10, 20\n\n results := make([]int, len(operations))\n\n var wg sync.WaitGroup\n wg.Add(len(operations))\n for i, fn := range operations {\n go func(i int, fn f) {\n defer wg.Done()\n results[i] = fn(x, y)\n }(i, fn)\n }\n wg.Wait()\n\n fmt.Println(results)\n}\n</code></pre>\n<h3>2. Eliminate the waitgroup</h3>\n<p>The application can receive the known number of values sent to the channel instead of receiving until the channel is closed. If the channel is not closed, then there's no need for the waitgroup. What's more, there's no need to buffer the channel.</p>\n<pre><code>package main\n\nimport (\n &quot;fmt&quot;\n)\n\ntype f func(int, int, chan int)\n\nfunc add(x, y int, r chan int) {\n r &lt;- (x + y)\n}\n\nfunc sub(x, y int, r chan int) {\n r &lt;- (x - y)\n}\n\nfunc prod(x, y int, r chan int) {\n r &lt;- (x * y)\n}\n\nfunc main() {\n var operations []f = []f{add, sub, prod}\n ch := make(chan int)\n\n x, y := 10, 20\n\n for _, i := range operations {\n go i(x, y, ch)\n }\n for range operations {\n val := &lt;-ch\n fmt.Println(val)\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T07:32:58.187", "Id": "254168", "ParentId": "254167", "Score": "2" } }, { "body": "<p>I've majorly written the review comments inline with the code. I could've made the code simple as @thwd suggested; but as you're learning and this is not an actual use case, I'm not changing the logic.</p>\n<p>Also, to know about buffered channels better, do <a href=\"https://www.ardanlabs.com/blog/2017/10/the-behavior-of-channels.html\" rel=\"nofollow noreferrer\">read</a> this.</p>\n<pre class=\"lang-golang prettyprint-override\"><code>package main\n\nimport (\n &quot;fmt&quot;\n &quot;sync&quot;\n)\n\n// As goroutine could schedule in any order, it's better if the\n// operation is stored as well, with the result.\ntype result struct {\n op string\n v int\n}\n\n// It's better to use unidirectional channels if bi-directional\n// is not needed. It can also distinguish how a channel should be used\n// in different function/ methods (eg. producer, consumer)\ntype fn func(int, int, chan&lt;- result, *sync.WaitGroup)\n\nfunc add(x, y int, r chan&lt;- result, wg *sync.WaitGroup) {\n fmt.Println(&quot;op: add&quot;)\n r &lt;- result{&quot;add&quot;, x + y}\n wg.Done()\n}\n\nfunc sub(x, y int, r chan&lt;- result, wg *sync.WaitGroup) {\n fmt.Println(&quot;op: sub&quot;)\n r &lt;- result{&quot;sub&quot;, x - y}\n wg.Done()\n}\n\nfunc prod(x, y int, r chan&lt;- result, wg *sync.WaitGroup) {\n fmt.Println(&quot;op: prod&quot;)\n r &lt;- result{&quot;prod&quot;, x * y}\n wg.Done()\n}\n\nfunc main() {\n // In case of multiple declaration, you can group\n // But it's totally dependent on the developer writing it.\n // But the ultimate goal is write clean code.\n var (\n fops = []fn{add, sub, prod}\n ch = make(chan result, len(fops))\n wg sync.WaitGroup\n x, y = 10, 20\n )\n\n wg.Add(len(fops))\n for _, f := range fops {\n go f(x, y, ch, &amp;wg)\n }\n\n wg.Wait()\n close(ch)\n\n // Either use range, or you run a loop from [0, len(fops));\n // that would work as well!\n for v := range ch {\n fmt.Println(v)\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T07:41:32.723", "Id": "254169", "ParentId": "254167", "Score": "3" } } ]
{ "AcceptedAnswerId": "254168", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T07:24:09.820", "Id": "254167", "Score": "2", "Tags": [ "go" ], "Title": "Golang unbuffered channel - Correct Usage" }
254167
<p>Recently on SO there was <a href="https://stackoverflow.com/questions/65521805/get-data-from-each-array-of-array-with-sequence-output/65528916#65528916">this</a> question</p> <blockquote> <p>i am trying to get sequence index of each array of array like I have an element of the array and that 5 arrays have multiple elements and I want to get the first index of each array then the second and so.</p> <p>below is my array data const arrData = [[1,2,4,6],[3,8,7],[12,13],[],[9,10]];</p> <p>and my expected outout [1,3,12,9,2,8,13,10,4,7,6]</p> </blockquote> <p>This is very basic but I found it interesting and tried to solve it.</p> <p>I solved it like this, I thought it is easy to understand and to read but in reasons that I go in every nested array through all elements maybe it is not the best solution.</p> <p>For example if I have one array with length 100 and all the other ones are just have length 1.</p> <p>What do you think about my code?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const arr = [ [1, 2, 4, 6], [3, 8, 7], [12, 13], [], [9, 10] ]; let biggestLength = Number.MIN_VALUE; for (let i = 0; i &lt; arr.length; i++) { if (arr[i].length &gt; biggestLength) { biggestLength = arr[i].length; } } let result = []; for (let l = 0; l &lt; biggestLength; l++) { for (let k = 0; k &lt; arr.length; k++) { if (arr[k][l] !== undefined) { result.push(arr[k][l]) } } } console.log(result)</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T09:29:26.777", "Id": "501331", "Score": "0", "body": "Please do not update the code in your question after receiving answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T09:35:23.217", "Id": "501333", "Score": "0", "body": "well okay I will keep that in mind" } ]
[ { "body": "<p>Overall your code is readable and it seems reasonably clear what it does. As you said, the code is somewhat inefficient if one of the arrays is much larger than the rest, but for your example (and honestly, even if you had a thousand items in one array), the time cost would probably be negligible, unless the number of arrays in <code>arr</code> is very very large.</p>\n<h2><code>Number.MIN_VALUE</code></h2>\n<p><code>Number.MIN_VALUE</code> is not what you think it is. It represents the smallest positive number that can be represented, not the most negative number. As a result, if you use <code>let arr = [];</code> you end up with a biggestLength that is slightly more than 0 and run your second loop... only to figure out that you do not have items. Or arrays, This in itself does not break anything, but you could just initialise <code>biggestLength</code> to 0 and things would work out fine.</p>\n<h2>Optimising</h2>\n<p>As I said earlier, the amount of time it takes to do this operation is negligible, even if you have 100 items in the first array. With 11 items over 4 arrays (16 operations) it takes me 0.010ms, and with 107 items over 4 arrays (400 operations) it takes me 0.025ms.</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>const arr = [\n [1, 2, 4, 6],\n [3, 8, 7],\n [12, 13],\n [],\n [9, 10]\n];\n\nfunction getUnfoldedArray(arr) {\n let biggestLength = Number.MIN_VALUE;\n for (let i = 0; i &lt; arr.length; i++) {\n if (arr[i].length &gt; biggestLength) {\n biggestLength = arr[i].length;\n }\n }\n\n let result = [];\n for (let l = 0; l &lt; biggestLength; l++) {\n for (let k = 0; k &lt; arr.length; k++) {\n if (arr[k][l] !== undefined) {\n result.push(arr[k][l])\n }\n }\n }\n \n return result;\n}\n\nconsole.time('First run is always slower');\ngetUnfoldedArray(arr);\nconsole.timeEnd('First run is always slower');\n\nconsole.time('time1');\nconst result = getUnfoldedArray(arr);\nconsole.timeEnd('time1'); // 0.010ms\n\narr[0] = [];\nfor (let i = 0; i &lt; 100; i++) {\n arr[0].push(i);\n}\n\nconsole.time('time2');\nconst result2 = getUnfoldedArray(arr);\nconsole.timeEnd('time2'); // 0.025ms\n\nconsole.log(result);\nconsole.log(result2);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>If you don't mind destroying the array you are doing stuff on, you can potentially use <code>Array.shift()</code>. You could also splice out any empty arrays then, but keep in mind that loops will mess up when you do that. Overall your code would probably get more complicated for not a lot of gain.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T13:54:14.300", "Id": "501268", "Score": "0", "body": "Thanks a lot for this explanation, I was also thinking about maybe break out of the loop iteration when the first undefined occured.\nBecause I can assume that after the first undefined there will probably follow just undefineds as the array has no gaps" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T10:32:30.233", "Id": "501337", "Score": "0", "body": "That would not do much for you. It is the outer loop that defines the current index in the array, and you cannot break out of that unless you want to ignore everything after the minimum length of the arrays." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T12:46:48.070", "Id": "254172", "ParentId": "254171", "Score": "2" } }, { "body": "<p>For a better way of identifying the <code>biggestLength</code>, consider mapping each array to its length and spreading the result into <code>Math.max</code>.</p>\n<p>Since the <code>arr</code> variable actually contains multiple arrays, I think it'd be a bit more appropriate to call it something like <code>arrs</code> (plural) to avoid possibly mixing it up with one of the single arrays of numbers.</p>\n<p>You can also use <code>const</code> instead of <code>let</code> for <code>result</code> (since it never gets reassigned, <code>const</code> <a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">should be preferred</a>).</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 arrs = [\n [1, 2, 4, 6],\n [3, 8, 7],\n [12, 13],\n [],\n [9, 10]\n];\n\nconst biggestLength = Math.max(...arrs.map(subarr =&gt; subarr.length));\n\nconst result = [];\nfor (let l = 0; l &lt; biggestLength; l++) {\n for (let k = 0; k &lt; arrs.length; k++) {\n if (arrs[k][l] !== undefined) {\n result.push(arrs[k][l])\n }\n }\n}\n\nconsole.log(result);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T14:46:32.507", "Id": "501271", "Score": "0", "body": "Why is it a better way mit Math.max( and arr.map)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T14:47:44.940", "Id": "501273", "Score": "0", "body": "It's what I'd prefer, at least. I find it a lot more readable than iterating over the indicies manually, and it doesn't require reassigning the `biggestLength` variable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T14:52:21.957", "Id": "501274", "Score": "0", "body": "ah true and I can write it as a one liner" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T14:39:41.583", "Id": "254175", "ParentId": "254171", "Score": "2" } }, { "body": "<h2>Bug</h2>\n<p>The second function does not work. The <code>break</code> will exit the inner loop before all arrays have been processed. Having a short arrays does not mean the following arrays will also be short.</p>\n<p>However looks like you copied it from an answer so not really your code (apart from the bug you added).</p>\n<h2>Question</h2>\n<blockquote>\n<p><em>&quot;What do you think about my code?&quot;</em></p>\n</blockquote>\n<p>The first snippet.</p>\n<ul>\n<li>Not too bad.</li>\n<li>Some odd naming.</li>\n<li>A little old school in terms of style.</li>\n<li>A few missing semicolons.</li>\n</ul>\n<h2>Always create functions</h2>\n<p>When ever you write code, even as example or experiment write it as a named function with arguments as input, and return the result. This forces you to name the code and changes the way you conceptualize the problem. It may seem like a trivial thing to do, and may not always be useful, however good habits need repetition to pick up.</p>\n<h3>Number.MIN_VALUE</h3>\n<p>Javascript has some clangers that should never have been let into the language. This is one of them.</p>\n<p>The name suggests MIN as in minimum. One would expect <code>Math.min(Number.MIN_VALUE, anyNumber)</code> to always return <code>Number.MIN_VALUE</code>. But no.</p>\n<p>Rather it is the smallest positive number greater than 0 or 5e-324 and also happens to the largest negative number if you change the sign <code>-Number.MIN_VALUE === -5e-324</code>. I wonder what that would be called if they named that.</p>\n<p><code>Number.MIN_VALUE</code> is as close to useless as you can get. To understand it requires a good working knowledge of Floating point numbers. The minimum practical positive number is <code>Number.EPSILON</code> and defines the maximum precision of JavaScripts number.</p>\n<p>I digress. Your code....</p>\n<blockquote>\n<p>let biggestLength = Number.MIN_VALUE;</p>\n</blockquote>\n<p>Your code works the smallest non empty array has a length of 1. Any number smaller than <code>Number.MIN_VALUE;</code> would also have worked.</p>\n<pre><code>let biggestLength = 0; // would be best for arrays sizes.\n</code></pre>\n<h2>Avoid indexing arrays out of bounds.</h2>\n<p>I can not think of a good reason to do this unless the array has <code>undefined</code> items within the array length.</p>\n<p>You have</p>\n<blockquote>\n<p>if (arr[k][l] !== undefined) {</p>\n</blockquote>\n<p>It works as a test to see if you have gone past the end of the array. But you pay a huge cost. I am not sure why, but indexing outside an arrays bounds is just over 5 times slower than testing against the array size (chrome)</p>\n<p>You may say. <em>&quot;Its just a single test how much of a difference can it make.&quot;</em></p>\n<p>Well if you change the test to what you actually intended</p>\n<pre><code>if (l &lt; arr[k].length) {\n</code></pre>\n<p>Then run the function on 100 arrays of random sizes 1 to 100 the difference is 25%. That means you can process ~125 arrays in the same time as 100.</p>\n<p>JavaScript rule of thumb <code>somearray[i] !== undefined</code> should never replace <code>i &lt; somearray.length</code></p>\n<h2>Iterators</h2>\n<p>You are using <code>for ;;;</code> type loops to iterate the arrays. Meaning accessing the arrays is via an index, array indexing is harder on the eyes than direct referencing.</p>\n<p><strong>Note</strong> replacing <code>biggestLength</code> with <strike> <code>theMostGiganticArraysLength</code> no no sorry, </strike> with <code>max</code></p>\n<p>You have</p>\n<blockquote>\n<pre><code>for (let i = 0; i &lt; arr.length; i++) {\n if (arr[i].length &gt; max) {\n max = arr[i].length;\n }\n}\n</code></pre>\n</blockquote>\n<p>Use <code>for of</code> loops if you do not need the item index, the loop becomes...</p>\n<pre><code>for (const array of arr) {\n if (array.length &gt; max) {\n max = array.length;\n }\n}\n</code></pre>\n<p>As you only want <code>length</code> you could also extract the length via destructuring</p>\n<pre><code>for (const {length} of arr) {\n if (length &gt; max) {\n max = length;\n }\n}\n</code></pre>\n<p><strong>Note</strong> there is a small performance penalty using the <code>for of</code> loop in this case.</p>\n<h2>Finding max length</h2>\n<p>The first loop is redundant as you can do that inside the main nested loop. You only need the max value to know when to stop. At minimum you need to look at each array at least once to check length.</p>\n<p>You set the max to 1 at the start to make sure you look at each array at least once. As you go check the array length for a max length. After the first inner loop you have the first column of values added and the max array length.</p>\n<p>There are many ways you could do this.</p>\n<pre><code>function interlacedFlat(arrays) {\n const result = [];\n var max = 1;\n for (let i = 0; i &lt; max; i++) {\n for (const array of arrays) {\n if (i &lt; array.length) {\n result.push(array[i]);\n if (!i &amp;&amp; max &lt; array.length) { max = array.length }\n }\n }\n }\n return result;\n}\n</code></pre>\n<p>or</p>\n<pre><code>function interlacedFlat(arrays) {\n const result = [];\n var max = 1, i = 0;\n do {\n for (const array of arrays) {\n if (i &lt; array.length) {\n result.push(array[i]);\n max &lt; array.length &amp;&amp; (max = array.length);\n }\n }\n } while (++i &lt; max);\n return result;\n}\n</code></pre>\n<p>or</p>\n<pre><code>function interlacedFlat(arrays) {\n const result = [];\n var max = 1, i = -1;\n while (i++ &lt; max) {\n for (const array of arrays) {\n if (i &lt; array.length) {\n result.push(array[i]);\n max = i + 1;\n }\n }\n } \n return result;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T08:37:24.117", "Id": "501323", "Score": "0", "body": "Thanks a lot for your answer an this detailed answer.\nI have two questions first why do you use for max and I the \"var\" keyword I thought it is not a good practice because it is in the global scope.\nThe second is what does the negotioation of i in this condition? `if (!i && max < array.length) { max = array.length }` is it because zero would evaluate to false?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T08:49:58.653", "Id": "501324", "Score": "0", "body": "@Alex I use the `!i` (Not i) equivalent to `i == 0` so that it only does the test for `max < array.length` on the first pass. In hindsight it is not really needed, I used it as a minor optimization when I originally had `array[k][l].length`. `var` is perfectly safe to use. `var` creates the variable in function scope, it has as much to do with global scope as `let` or `const` which are both block scope." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T08:54:03.487", "Id": "501328", "Score": "0", "body": "This means it doesn't make the second test if i is equal to zero?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T12:12:16.700", "Id": "501341", "Score": "0", "body": "@Alex Yes that is correct" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T05:54:15.520", "Id": "254208", "ParentId": "254171", "Score": "1" } } ]
{ "AcceptedAnswerId": "254208", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T10:37:30.080", "Id": "254171", "Score": "4", "Tags": [ "javascript", "sorting" ], "Title": "Sorting Nested Array" }
254171
<p>I am trying to re-organise my mp3 collection based on its id3 meta data into folders based on the artist. I'm new to nodeJs and more importantly promises. I was hoping I could get some feedback on my script. I can manage the creating of folders and copying of files quite easily, but I'm a little unsure on the async reading and looping part (shown below).</p> <p>It does run, but almost crashes my computer when I run it on the full directory.</p> <p>Thanks in advance for any suggestions or advice.</p> <pre><code>const fs = require('fs'); const NodeID3 = require('node-id3-promise') const util = require(&quot;util&quot;); const testFolder = '/home/james/Music'; const reorderedFolder = '/home/james/Music/reordered'; const existsProm = util.promisify(fs.access); const statsProm = util.promisify(fs.stat); const mkdirProm = util.promisify(fs.mkdir); const copyFileProm = util.promisify(fs.copyFile); const removeFileProm = util.promisify(fs.rm); const readAllFiles = util.promisify(fs.readdir); const isDelete = false; async function getFiles(){ const files = await readAllFiles(testFolder); return Promise.all(files); } (async ()=&gt;{ const files = await getFiles(); files.forEach(file =&gt; { var sourceFilePath = testFolder + &quot;/&quot; + file; Promise.resolve(sourceFilePath) .then(filePath =&gt;{ //Return an array of promises. a) does file exist, b) filePath return Promise.all([existsProm(filePath), Promise.resolve(filePath)]); }) .catch(err =&gt;{ //File wasn't found. Kill it. throw new Error(&quot;File not found&quot;); }) .then(fileExistsAndFilePath =&gt; { //get tags for existing file path. return Promise.all([NodeID3.read(fileExistsAndFilePath[1]), fileExistsAndFilePath[1]]) }) .then(tagAndFilePath =&gt; { //get the id3 tag info and create an object from it. var tagDetails = {}; tagDetails.artist = tagAndFilePath[0].artist; tagDetails.title = tagAndFilePath[0].title; tagDetails.filePath = tagAndFilePath[1]; return tagDetails; }) .then(tagDetails =&gt; { //Create file paths if(tagDetails != null &amp;&amp; tagDetails.artist != null &amp;&amp; tagDetails.title != null){ var fileAndFolder = {}; fileAndFolder.existingFilePath = tagDetails.filePath; fileAndFolder.newFolderPath = reorderedFolder + &quot;/&quot; + tagDetails.artist; fileAndFolder.newFilePath = fileAndFolder.newFolderPath + &quot;/&quot; + tagDetails.title + &quot;.mp3&quot;; return fileAndFolder; }else{ throw new Error(&quot;No artist&quot;); } }) .then(fileAndFolder =&gt; { //Create the directory, if it exists, ignore the error return Promise.all([mkdirProm(fileAndFolder.newFolderPath).catch(err =&gt; {}), fileAndFolder]); }) .then(mdkirAndFileAndFolder =&gt; { //Copy the file to the new location return Promise.all([ copyFileProm(mdkirAndFileAndFolder[1].existingFilePath, mdkirAndFileAndFolder[1].newFilePath).catch(err =&gt; { console.log(err); throw new Error(&quot;Problem copying file&quot;); }), mdkirAndFileAndFolder[1] ]); }) .then(copyFileResultAndFileAndFolder =&gt; { //Remove the old file if(isDelete){ return Promise.all([ removeFileProm(copyFileResultAndFileAndFolder[1].existingFilePath).catch(err =&gt; {console.log(&quot;Problem deleting file &quot; + err);}), copyFileResultAndFileAndFolder[1].existingFilePath ]); }else{ return Promise.all([null, copyFileResultAndFileAndFolder[1].existingFilePath]); } }) .then(rmFileResult =&gt; { //Output success message console.log(rmFileResult[1] + &quot; = successfully moved.&quot;); return true; }) .catch(error =&gt; { if(error.message != &quot;File not found&quot; &amp;&amp; error.message != &quot;No artist&quot;){ console.error(error); } }) }); })() </code></pre>
[]
[ { "body": "<p><strong>Use precise variable names</strong> <code>getFiles</code> resolves not to an array of <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/File\" rel=\"nofollow noreferrer\">File</a>s, but to an array of file name strings. Consider renaming appropriately.</p>\n<p><strong>Processing issues</strong> Very large amounts of parallel file system accesses can make the system seem unresponsive. One solution to this would be to throttle the number of files that can be processed at any one time. The limit will depend on your system, depending on how much resources you consider acceptable to be taken up by the script. To implement this, instead of processing the files immediately with the big outer <code>forEach</code>, construct an array of functions. Each function, when called, processes a file. Then, iterate over up to the limit (say, 15), and call 15 of those functions. Once each file has finished processing, take another function from the array, if it exists, and call it.</p>\n<p>For example, if you put the file processing into a separate function named <code>processFile</code> (to make the flow easier to understand), you could do:</p>\n<pre><code>const LIMIT = 15;\nconst fns = filenames.map(filename =&gt; () =&gt; processFile(filename));\nPromise.all(Array.from(\n { length: LIMIT },\n (_, i) =&gt; fns.pop?.() // use optional chaining if there may be less than 15 items in the folder\n))\n .then(() =&gt; {\n // All done\n });\n</code></pre>\n<p>where <code>processFile</code> has, at the end of it, after the <code>.catch</code>:</p>\n<pre><code>.then(() =&gt; {\n return fns.pop?.();\n});\n</code></pre>\n<p>You could also use an index that gets incremented instead of mutating the array with <code>.pop</code> if you wanted, but it almost certainly won't make a difference.</p>\n<p>Also, your existing code could do with a number of improvements:</p>\n<p><strong>Use <code>fs.promises</code></strong> - unless you're on an obsolete version of Node, the fs module contains native promisified versions of each API. Eg, instead of</p>\n<pre><code>const existsProm = util.promisify(fs.access);\n</code></pre>\n<p>just use <code>fs.promises.access</code>, or do something like:</p>\n<pre><code>const fs = require('fs').promises;\n// ...\n// use fs.access\n</code></pre>\n<p><strong>Only use <code>Promise.all</code> on an array of Promises</strong> Since <code>readdir</code> resolves to an array of strings, just return that array instead of wrapping it in a Promise.</p>\n<p><strong>Only use <code>Promise.resolve</code> when you don't have a Promise to begin with</strong> Here, since the data you're missing at the start of processing is the result of calling <code>fs.access</code>, use <em>that</em> as the intial Promise instead of using <code>Promise.resolve(sourceFilePath)</code>.</p>\n<p><strong>Use <code>await</code> instead of long <code>.then</code> chains</strong> - <code>await</code> makes the code much flatter and easier to make sense of at a glance. It also helps avoid having to pass down arrays of <code>Promise.all</code> when you want to transfer multiple values over the asynchronous chain. It will also help you avoid the following problem:</p>\n<p><strong>Don't return from a <code>.then</code> when carrying out synchronous processing</strong> - <code>.then</code>s allow you to chain together <em>asynchronous</em> operations. If what you're doing isn't asynchronous, don't use <code>.then</code>. For example, this:</p>\n<pre><code>.then(tagAndFilePath =&gt; {\n //get the id3 tag info and create an object from it.\n var tagDetails = {};\n tagDetails.artist = tagAndFilePath[0].artist;\n tagDetails.title = tagAndFilePath[0].title;\n tagDetails.filePath = tagAndFilePath[1];\n\n return tagDetails;\n})\n.then(tagDetails =&gt; {\n // do stuff with tagDetails\n</code></pre>\n<p>should be something more like</p>\n<pre><code>.then(([id3Result, filePath]) =&gt; { // destructuring is nice\n const { artist, title } = id3Result;\n const tagDetails = {\n artist,\n title,\n filePath: \n };\n // do stuff with tagDetails\n</code></pre>\n<p><strong>Don't use <code>var</code></strong> - it's better to declare variables with <code>const</code>, both to indicate that a variable won't be reassigned, and to avoid the unintuitive function-scope of <code>var</code>. (<code>const</code> and <code>let</code> both have block scope instead.) (When you must reassign a variable, use <code>let</code>.)</p>\n<p><strong><code>.catch</code> only once?</strong> It looks a bit odd to me to <code>.catch</code> and immediately re-throw. Is there a reason you don't want to leave it as-is and just examine the error object at the end of the chain instead? That way you can have just a single <code>.catch</code> that encompasses all possible errors that arose.</p>\n<p><strong>Rewrite</strong></p>\n<pre><code>const processFile = async (filename) =&gt; {\n try {\n const existingFilePath = testFolder + &quot;/&quot; + file;\n await fs.exists(existingFilePath);\n const { artist, title } = await NodeID3.read(exists);\n if (!artist || !title) {\n throw new Error('No artist or no title');\n }\n const newFolderPath = reorderedFolder + &quot;/&quot; + artist;\n await fs.makeDir(newFolderPath);\n const newFilePath = newFolderPath + &quot;/&quot; + title + &quot;.mp3&quot;;\n await fs.copyFile(existingFilePath, newFilePath);\n if (isDelete) {\n await fs.rm(existingFilePath);\n }\n console.log(existingFilePath + &quot; = successfully moved.&quot;);\n } catch (error) {\n console.log(error.message);\n // implement custom error handling and logging here if needed\n }\n return fns.pop?.();\n};\n\nconst LIMIT = 15;\nconst filenames = await fs.readdir(testFolder);\nconst fns = filenames.map(filename =&gt; () =&gt; processFile(filename));\nPromise.all(Array.from(\n { length: LIMIT },\n (_, i) =&gt; fns.pop?.()\n))\n .then(() =&gt; { /* All done */ });\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T11:10:49.697", "Id": "501339", "Score": "0", "body": "Note that there are plenty of libraries that could save you the need to implement your own throttling mechanism, such as es6-promise-pool, or Bluebird's Promise.map with a \"concurrency\" parameter." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-11T16:11:59.873", "Id": "502028", "Score": "0", "body": "What an amazingly thorough and well written answer. Thank you." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T02:11:47.910", "Id": "254202", "ParentId": "254174", "Score": "4" } } ]
{ "AcceptedAnswerId": "254202", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T13:47:09.193", "Id": "254174", "Score": "1", "Tags": [ "javascript", "node.js", "promise" ], "Title": "NodeJS promise loop through all files in directory" }
254174
<p>I am writing a python module to interact to the ROD (remedy on demand) BMC ticketing product. So far I have only written the log in and log out methods and tests. Before I crack on with the more complex methods I hope someone can review the current test strategy and happy to hear any suggestions for improvements.</p> <p><strong>rodAPI.py</strong></p> <pre class="lang-py prettyprint-override"><code>import requests class RodApi: def __init__(self, fqdn, username, password, token_type=&quot;AR-JWT&quot;): self.username = username self.password = password self.fqdn = fqdn self.token_type = token_type self.login_url = f&quot;https://{fqdn}/api/jwt/login&quot; self.logout_url = f&quot;https://{fqdn}/api/jwt/logout&quot; self.token = None def login(self) -&gt; bool: data = {&quot;username&quot;: self.username, &quot;password&quot;: self.password} headers = {&quot;content-type&quot;: &quot;application/x-www-form-urlencoded&quot;} response = requests.post(self.login_url, data=data, headers=headers) print(f&quot;connecting to URL: {self.login_url}&quot;) print(f&quot;https status code: {response.status_code}&quot;) self.token = response.text if response.status_code == 200: return True return False def logout(self) -&gt; bool: headers = {&quot;Authorization&quot;: f&quot;{self.token_type} {self.token}&quot;} response = requests.post(self.logout_url, headers=headers) print(f&quot;connecting to URL: {self.logout_url}&quot;) print(f&quot;https status code: {response.status_code}&quot;) if response.status_code == 204: print(f&quot;Logged out with a status of: {response.status_code}&quot;) return True else: print(f&quot;Error logging out: {response.text}&quot;) return False </code></pre> <p><strong>test_rodAPI</strong></p> <pre class="lang-py prettyprint-override"><code>import pytest from rodAPI import RodApi @pytest.fixture() def rod_api_instance(): rod_api = RodApi(&quot;example.com&quot;, &quot;some_user&quot;, &quot;some_password&quot;) return rod_api @pytest.fixture() def rod_api_logged_in_instance(responses, rod_api_instance): responses.add(responses.POST, rod_api_instance.login_url, body=&quot;some_token_string&quot;) rod_api_instance.login() return rod_api_instance def test_login_success(responses, rod_api_instance: RodApi): responses.add(responses.POST, rod_api_instance.login_url, body=&quot;some_token_string&quot;) result = rod_api_instance.login() assert result is True assert rod_api_instance.token == &quot;some_token_string&quot; def test_login_fail(responses, rod_api_instance: RodApi): responses.add(responses.POST, rod_api_instance.login_url, status=404) result = rod_api_instance.login() assert result is False def test_logout_success(responses, rod_api_logged_in_instance: RodApi): responses.add(responses.POST, rod_api_logged_in_instance.logout_url, status=204) result = rod_api_logged_in_instance.logout() assert result is True def test_logout_fail(responses, rod_api_logged_in_instance: RodApi): responses.add(responses.POST, rod_api_logged_in_instance.logout_url, status=404) result = rod_api_logged_in_instance.logout() assert result is False <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<h2>Redundant headers</h2>\n<p>Read\n<a href=\"https://github.com/psf/requests/blob/master/requests/models.py#L514\" rel=\"nofollow noreferrer\">https://github.com/psf/requests/blob/master/requests/models.py#L514</a> - your use of</p>\n<pre><code> headers = {&quot;content-type&quot;: &quot;application/x-www-form-urlencoded&quot;}\n</code></pre>\n<p>should not be needed.</p>\n<h2>Out-of-order progress</h2>\n<p>You print</p>\n<pre><code> print(f&quot;connecting to URL: {self.login_url}&quot;)\n</code></pre>\n<p>when this has already happened. Either say &quot;connected to&quot;, or move this statement before your <code>post</code>.</p>\n<h2>Exception degradation</h2>\n<p>Resist the urge to sabotage the Python exception system. Rather than returning booleans from your methods, call <code>response.raise_for_status</code>, and optionally wrap that in a <code>try/except/raise MyException() from e</code> with your own exception type. <code>raise_for_status</code> will also obviate your status code checks.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T20:59:39.577", "Id": "501300", "Score": "1", "body": "Thanks for the feedback, I wasnt aware of raise for status, I have taken all your feedback and incorporated it into my code and testing strategy." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T15:59:51.787", "Id": "254179", "ParentId": "254177", "Score": "1" } } ]
{ "AcceptedAnswerId": "254179", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T15:29:44.427", "Id": "254177", "Score": "1", "Tags": [ "python", "unit-testing" ], "Title": "Testing Remedy-on-Demand REST API code" }
254177
<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/253556/231235">A recursive_transform Template Function Implementation with std::invocable concept in C++</a>. Besides the recursive version <a href="https://en.cppreference.com/w/cpp/algorithm/ranges/transform" rel="nofollow noreferrer"><code>std::ranges::transform</code></a>, I am trying to implement a recursive version <a href="https://en.cppreference.com/w/cpp/algorithm/ranges/copy" rel="nofollow noreferrer"><code>std::ranges::copy_if</code></a>.</p> <p><strong>The experimental implementation</strong></p> <p>The experimental implementation is as below.</p> <pre><code>// recursive_copy_if function template &lt;std::ranges::input_range Range, std::invocable&lt;std::ranges::range_value_t&lt;Range&gt;&gt; UnaryPredicate&gt; constexpr auto recursive_copy_if(const Range&amp; input, const UnaryPredicate&amp; unary_predicate) { Range output{}; std::ranges::copy_if(std::ranges::cbegin(input), std::ranges::cend(input), std::inserter(output, std::ranges::end(output)), unary_predicate); return output; } template &lt; std::ranges::input_range Range, class UnaryPredicate&gt; requires (!std::invocable&lt;UnaryPredicate, std::ranges::range_value_t&lt;Range&gt;&gt;) constexpr auto recursive_copy_if(const Range&amp; input, const UnaryPredicate&amp; unary_predicate) { Range output{}; std::ranges::transform( std::ranges::cbegin(input), std::ranges::cend(input), std::inserter(output, std::ranges::end(output)), [&amp;unary_predicate](auto&amp;&amp; element) { return recursive_copy_if(element, unary_predicate); } ); return output; } </code></pre> <p><strong>Test cases</strong></p> <pre><code>// std::vector&lt;int&gt; std::vector&lt;int&gt; test_vector = { 1, 2, 3, 4, 5, 6 }; recursive_print(recursive_copy_if(test_vector, [](int x) { return (x % 2) == 0; })); // std::vector&lt;std::vector&lt;int&gt;&gt; std::vector&lt;decltype(test_vector)&gt; test_vector2 = { test_vector, test_vector, test_vector }; recursive_print(recursive_copy_if(test_vector2, [](int x) { return (x % 2) == 0; })); // std::vector&lt;std::string&gt; recursive_print( recursive_copy_if( recursive_transform(test_vector, [](int x) { return std::to_string(x); }), [](std::string x) { return (x == &quot;1&quot;); } ) ); // std::vector&lt;std::vector&lt;std::string&gt;&gt; recursive_print( recursive_copy_if( recursive_transform(test_vector2, [](int x) { return std::to_string(x); }), [](std::string x) { return (x == &quot;1&quot;); } ) ); // std::deque&lt;int&gt; std::deque&lt;int&gt; test_deque; test_deque.push_back(1); test_deque.push_back(2); test_deque.push_back(3); test_deque.push_back(4); test_deque.push_back(5); test_deque.push_back(6); recursive_print(recursive_copy_if(test_deque, [](int x) { return (x % 2) == 0; })); // std::deque&lt;std::deque&lt;int&gt;&gt; std::deque&lt;decltype(test_deque)&gt; test_deque2; test_deque2.push_back(test_deque); test_deque2.push_back(test_deque); test_deque2.push_back(test_deque); recursive_print(recursive_copy_if(test_deque2, [](int x) { return (x % 2) == 0; })); // std::list&lt;int&gt; std::list&lt;int&gt; test_list = { 1, 2, 3, 4, 5, 6 }; recursive_print(recursive_copy_if(test_list, [](int x) { return (x % 2) == 0; })); // std::list&lt;std::list&lt;int&gt;&gt; std::list&lt;std::list&lt;int&gt;&gt; test_list2 = { test_list, test_list, test_list, test_list }; recursive_print(recursive_copy_if(test_list2, [](int x) { return (x % 2) == 0; })); </code></pre> <p></p> Full Testing Code <p> <p>The full testing code:</p> <pre><code>#include &lt;algorithm&gt; #include &lt;array&gt; #include &lt;cassert&gt; #include &lt;chrono&gt; #include &lt;complex&gt; #include &lt;concepts&gt; #include &lt;deque&gt; #include &lt;execution&gt; #include &lt;exception&gt; #include &lt;functional&gt; #include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;list&gt; #include &lt;map&gt; #include &lt;mutex&gt; #include &lt;numeric&gt; #include &lt;optional&gt; #include &lt;ranges&gt; #include &lt;stdexcept&gt; #include &lt;string&gt; #include &lt;tuple&gt; #include &lt;type_traits&gt; #include &lt;utility&gt; #include &lt;variant&gt; #include &lt;vector&gt; // recursive_copy_if function template &lt;std::ranges::input_range Range, std::invocable&lt;std::ranges::range_value_t&lt;Range&gt;&gt; UnaryPredicate&gt; constexpr auto recursive_copy_if(const Range&amp; input, const UnaryPredicate&amp; unary_predicate) { Range output{}; std::ranges::copy_if(std::ranges::cbegin(input), std::ranges::cend(input), std::inserter(output, std::ranges::end(output)), unary_predicate); return output; } template &lt; std::ranges::input_range Range, class UnaryPredicate&gt; requires (!std::invocable&lt;UnaryPredicate, std::ranges::range_value_t&lt;Range&gt;&gt;) constexpr auto recursive_copy_if(const Range&amp; input, const UnaryPredicate&amp; unary_predicate) { Range output{}; std::ranges::transform( std::ranges::cbegin(input), std::ranges::cend(input), std::inserter(output, std::ranges::end(output)), [&amp;unary_predicate](auto&amp;&amp; element) { return recursive_copy_if(element, unary_predicate); } ); return output; } // recursive_print implementation // https://codereview.stackexchange.com/q/251208/231235 template&lt;std::ranges::input_range Range&gt; constexpr auto recursive_print(const Range&amp; input, const int level = 0) { auto 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(std::ranges::cbegin(input), std::ranges::cend(input), std::ranges::begin(output), [level](auto&amp;&amp; x) { std::cout &lt;&lt; std::string(level, ' ') &lt;&lt; x &lt;&lt; std::endl; return x; } ); return output; } template&lt;std::ranges::input_range Range&gt; requires (std::ranges::input_range&lt;std::ranges::range_value_t&lt;Range&gt;&gt;) constexpr auto recursive_print(const Range&amp; input, const int level = 0) { auto 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(std::ranges::cbegin(input), std::ranges::cend(input), std::ranges::begin(output), [level](auto&amp;&amp; element) { return recursive_print(element, level + 1); } ); return output; } // recursive_invoke_result_t implementation template&lt;typename, typename&gt; struct recursive_invoke_result { }; template&lt;typename T, std::invocable&lt;T&gt; F&gt; struct recursive_invoke_result&lt;F, T&gt; { using type = std::invoke_result_t&lt;F, T&gt;; }; template&lt;typename F, template&lt;typename...&gt; typename Container, typename... Ts&gt; requires ( !std::invocable&lt;F, Container&lt;Ts...&gt;&gt; &amp;&amp; std::ranges::input_range&lt;Container&lt;Ts...&gt;&gt; &amp;&amp; requires { typename recursive_invoke_result&lt;F, std::ranges::range_value_t&lt;Container&lt;Ts...&gt;&gt;&gt;::type; }) struct recursive_invoke_result&lt;F, Container&lt;Ts...&gt;&gt; { using type = Container&lt;typename recursive_invoke_result&lt;F, std::ranges::range_value_t&lt;Container&lt;Ts...&gt;&gt;&gt;::type&gt;; }; template&lt;typename F, typename T&gt; using recursive_invoke_result_t = typename recursive_invoke_result&lt;F, T&gt;::type; // recursive_transform implementation template &lt;class T, std::invocable&lt;T&gt; F&gt; constexpr auto recursive_transform(const T&amp; input, const F&amp; f) { return f(input); } template &lt; std::ranges::input_range Range, class F&gt; requires (!std::invocable&lt;F, Range&gt;) constexpr auto recursive_transform(const Range&amp; input, const F&amp; f) { recursive_invoke_result_t&lt;F, Range&gt; output{}; std::ranges::transform( std::ranges::cbegin(input), std::ranges::cend(input), std::inserter(output, std::ranges::end(output)), [&amp;f](auto&amp;&amp; element) { return recursive_transform(element, f); } ); return output; } int main() { // std::vector&lt;int&gt; std::vector&lt;int&gt; test_vector = { 1, 2, 3, 4, 5, 6 }; recursive_print(recursive_copy_if(test_vector, [](int x) { return (x % 2) == 0; })); // std::vector&lt;std::vector&lt;int&gt;&gt; std::vector&lt;decltype(test_vector)&gt; test_vector2 = { test_vector, test_vector, test_vector }; recursive_print(recursive_copy_if(test_vector2, [](int x) { return (x % 2) == 0; })); // std::vector&lt;std::string&gt; recursive_print( recursive_copy_if( recursive_transform(test_vector, [](int x) { return std::to_string(x); }), [](std::string x) { return (x == &quot;1&quot;); } ) ); // std::vector&lt;std::vector&lt;std::string&gt;&gt; recursive_print( recursive_copy_if( recursive_transform(test_vector2, [](int x) { return std::to_string(x); }), [](std::string x) { return (x == &quot;1&quot;); } ) ); // std::deque&lt;int&gt; std::deque&lt;int&gt; test_deque; test_deque.push_back(1); test_deque.push_back(2); test_deque.push_back(3); test_deque.push_back(4); test_deque.push_back(5); test_deque.push_back(6); recursive_print(recursive_copy_if(test_deque, [](int x) { return (x % 2) == 0; })); // std::deque&lt;std::deque&lt;int&gt;&gt; std::deque&lt;decltype(test_deque)&gt; test_deque2; test_deque2.push_back(test_deque); test_deque2.push_back(test_deque); test_deque2.push_back(test_deque); recursive_print(recursive_copy_if(test_deque2, [](int x) { return (x % 2) == 0; })); // std::list&lt;int&gt; std::list&lt;int&gt; test_list = { 1, 2, 3, 4, 5, 6 }; recursive_print(recursive_copy_if(test_list, [](int x) { return (x % 2) == 0; })); // std::list&lt;std::list&lt;int&gt;&gt; std::list&lt;std::list&lt;int&gt;&gt; test_list2 = { test_list, test_list, test_list, test_list }; recursive_print(recursive_copy_if(test_list2, [](int x) { return (x % 2) == 0; })); return 0; } </code></pre> </p> <p><a href="https://godbolt.org/z/zaa47P" rel="nofollow noreferrer">A Godbolt link is here.</a></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> and</p> <p><a href="https://codereview.stackexchange.com/q/253556/231235">A recursive_transform Template Function Implementation with std::invocable concept in C++</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <p>The implementation of <code>recursive_copy_if</code> template function is the main idea in this question.</p> </li> <li><p>Why a new review is being asked for?</p> <p>If there is any possible improvement, please let me know.</p> </li> </ul>
[]
[ { "body": "<p>You don't need this line:</p>\n<pre><code>requires (!std::invocable&lt;UnaryPredicate, std::ranges::range_value_t&lt;Range&gt;&gt;)\n</code></pre>\n<p>And your test cases miss a <code>std::vector&lt;std::string&gt;</code> as input, but your <code>recursive_copy_if()</code> works fine on those as well.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T18:01:23.640", "Id": "254184", "ParentId": "254178", "Score": "0" } } ]
{ "AcceptedAnswerId": "254184", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T15:52:08.910", "Id": "254178", "Score": "2", "Tags": [ "c++", "recursion", "lambda", "c++20" ], "Title": "A recursive_copy_if Template Function Implementation in C++" }
254178
<p>I have done a sorting program, it works but I am new to the coding world and I would love to hear your thoughts.</p> <pre class="lang-java prettyprint-override"><code> public class CorrectPlacement { public void placer(int... numbers) { System.out.println(&quot;Before : &quot; + Arrays.toString(numbers) + &quot; &quot;); for (int i = -1; i &lt;= numbers.length - 2; i++) { int min = numbers[i + 1]; for (int number : numbers) { if (number &lt;= min &amp;&amp; indexofTheRight(number, numbers, i) &gt; i) { min = number; } } numbers[indexofTheRight(min, numbers, i)] = numbers[i + 1]; numbers[i + 1] = min; } System.out.println(&quot;After : &quot; + Arrays.toString(numbers)); } public int indexofTheRight(int element, int[] array, int range) { for (int i = array.length - 1; i &gt; range; i--) { if (array[i] == element) { return i; } } return -1; } } </code></pre>
[]
[ { "body": "<p>A few things.</p>\n<pre><code>for (int i = 0; i &lt; numbers.length-1; i++)\n</code></pre>\n<p>Also, look up quick sort. Worst-case performance O(n^2) with a best-case of O(nlogn). By randomizing the pivot in the quick sort you can enhance the best case scenario.</p>\n<p>Psuedo for recursive Quicksort:</p>\n<pre><code>partition(arr[], low, high)\n pivot = arr[high]\n i = low\n for j:= low to high-1\n if arr[j] &lt;= pivot\n swap arr[i] with arr[j]\n i = i+1\n swap arr[i] with arr[high]\n\nrandom(arr[], low, high)\n r = a random number from low to high\n swap arr[r] and arr[high]\n return partition(arr, low, high)\n\nquickSort(arr[], low, high)\n if low &lt; high\n p = random(arr, low, high)\n quickSort(arr, low , p-1)\n quickSort(arr, p+1, high)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T06:27:10.983", "Id": "501320", "Score": "0", "body": "Thank you for your input sir" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T20:20:20.023", "Id": "254189", "ParentId": "254185", "Score": "1" } }, { "body": "<p>A more detailed explanation on what you're doing here would have been nice.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> public class CorrectPlacement {\n\n public void placer(int... numbers) {\n</code></pre>\n<p>Your names could be better overall. I'd also rather call the class and method <code>ArraySorter.sort</code>, for example.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code>for (int i = -1; i &lt;= numbers.length - 2; i++) {\n</code></pre>\n<p>I'm still an advocate for using <em>real</em> names for loops, like <code>index</code> or <code>counter</code>.</p>\n<hr />\n<p>You're never checking whether you actually received an array, it could be <code>null</code>.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> for (int i = -1; i &lt;= numbers.length - 2; i++) {\n int min = numbers[i + 1];\n</code></pre>\n<p>For easier reading and using, I'd rather go with a <code>index - 0 .. numbers.length - 1</code> loop and do mutations on the index as needed inside the loop.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> for (int number : numbers) {\n\n if (number &lt;= min &amp;&amp; indexofTheRight(number, numbers, i) &gt; i) {\n min = number;\n }\n }\n numbers[indexofTheRight(min, numbers, i)] = numbers[i + 1];\n</code></pre>\n<p>You seem to be doing quite a few unnecessary iterations in your logic. What you could do instead is to have a <code>findLowerThan</code> function which seeks the lowest index, below the current one, and returns it. From there you can get the value easily for swapping. This also allows you to do nothing if not lower value was found. Combine this with a little bit more readable loop variant and you get rather easy to follow logic:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public void sort(int... numbers) {\n // Simple loop which allows to easily see that the whole array is traversed\n // except the last item.\n for (int index = 0; index &lt; numbers.length - 1; index++) {\n // Extract the current value.\n int currentValue = numbers[index];\n // Find the lowest value in the remaining array.\n int lowestValueIndex = findLowerThan(numbers, currentValue, index);\n \n // If none was found, there's nothing to do.\n if (lowestValueIndex &gt;= 0) {\n // Actually swap the values.\n int swapValue = numbers[lowestValueIndex];\n numbers[lowestValueIndex] = currentValue;\n numbers[index] = swapValue;\n }\n }\n}\n\nprivate int findLowerThan(int[] array, int threshold, int stopAtIndex) {\n int lowestValue = threshold;\n int lowestValueIndex = -1;\n \n // Easy to read loop again, which makes it easy to see that we\n // traverse only a part of the array.\n for (int index = array.length - 1; index &gt; stopAtIndex; index--) {\n int currentValue = array[index];\n \n if (currentValue &lt; lowestValue) {\n lowestValue = currentValue;\n lowestValueIndex = index;\n }\n }\n \n // Returning only the index allows us to signal that no element\n // that is lower has been found.\n return lowestValueIndex;\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-04T18:29:18.250", "Id": "254320", "ParentId": "254185", "Score": "0" } } ]
{ "AcceptedAnswerId": "254320", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T18:58:38.273", "Id": "254185", "Score": "2", "Tags": [ "java", "sorting" ], "Title": "Sorting program code" }
254185
<p><em>Purpose of the code</em> : <br /> To assign the corresponding label of the centroids to the points which are close to it. Below is a graphical (2D) example.</p> <p><a href="https://i.stack.imgur.com/VXYKU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VXYKUm.png" alt="enter image description here" /></a></p> <hr /> <blockquote> <p>Variable <strong>X</strong> is a matrix, rows represent the points, columns collectively represent the coordinates</p> <p><strong>idx</strong> is the list of centroids assigned to every example</p> </blockquote> <p>Inefficient MATLAB code to find and assign nearest Centroids</p> <pre><code>sd2=size(X,2); t2=[]; for a=1:K t1=[]; for b=1:sd2 temp=(X(:,b)-centroids(a,b)).^2; t1=[t1 temp]; end dmat=sum(t1,2); t2=[t2 dmat]; end [~,idx]=min(t2,[],2); </code></pre> <p>supposedly faster MATLAB code which worked on a small dataset:</p> <pre><code>[~,idx]=min(sum(((repmat(X,1,1,K)-reshape(centroids,1,n,K)).^2),2),[],3); </code></pre> <p><strong>My Question:</strong> <br /> Is my second implementation correct? If yes, why doesn't it work on a <strong>300 x 2</strong> matrix <strong>X</strong> , in the sense that the final array <strong>idx</strong> produced is not correct. If no, where is the problem (because I tested it with a small sample code just to be sure that I am finding (x-x<sub>1</sub>)<sup>2</sup>+ (y-y<sub>1</sub>)<sup>2</sup> correctly).</p> <p><em><strong>speculation:</strong></em> <br /> MATLAB is erroneous because of a multidimensional matrix.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T19:18:30.210", "Id": "501292", "Score": "1", "body": "Could you share the data in a `MAT` or `CSV` file? I will give a reference code for it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T19:27:40.533", "Id": "501293", "Score": "0", "body": "@Royi https://gofile.io/d/NM9A9q ignore the .txt I tried to add. I was opening in it my computer on notepad" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T23:33:36.980", "Id": "501303", "Score": "1", "body": "Posted the solution. Enjoy..." } ]
[ { "body": "<h2>You Distance Matrix Calculation</h2>\n<p>You wrote the code (I summarize it for the Distance Matrix):</p>\n<pre><code>K = 3;\nn = size(mX, 1);\nd = size(mX, 2); %&lt;! Number of dimensions per sample\nmC = mX(randperm(n, K), :);\n\n% mD = repmat(mX, 1, 1, K) - reshape(mC, 1, n, K); %&lt;! Your code, Will fail because of reshape\nmD = sum((reshape(mX, n, 1, d) - reshape(mC.', 1, K, d)) .^ 2, 3); %&lt;! Correctly with no `repmat()`\n\n</code></pre>\n<p>The reason it won't work is the reshaping you're doing.<br />\nThe number of elements in <code>mC</code> is <code>K x d</code> while your <code>reshape()</code> should keep the number of elements.</p>\n<p>In the following I gave you a code snippet how to calculate the matrix <code>mD</code> efficiently.</p>\n<h2>K-Means</h2>\n<p>To calculate the distance you shouldn't use <code>repmat()</code> which will allocate new memory.\nTo calculate the <em>Distance Matrix</em> with the 3rd dimension and broadcasting you should do something like:</p>\n<pre><code>mD = sum((reshape(mA, numVarA, 1, varDim) - reshape(mB.', 1, numVarB, varDim)) .^ 2, 3);\n</code></pre>\n<p>But a faster way would be:</p>\n<pre><code>mD = sum(mA .^ 2).' - (2 * mA.' * mB) + sum(mB .^ 2);\n</code></pre>\n<p>Which utilizes the fast the Matrix Multiplication is probably the most optimized algorithm and that:</p>\n<p><span class=\"math-container\">$$ {\\left\\| \\boldsymbol{x} - \\boldsymbol{y} \\right\\|}_{2}^{2} = \\boldsymbol{x}^{T} \\boldsymbol{x} - 2 \\boldsymbol{x}^{T} \\boldsymbol{y} + \\boldsymbol{y}^{T} \\boldsymbol{y} $$</span></p>\n<p>For you to have a reference of K-Means algorithm with support for any Distance Function I created a function and ran it on your data:</p>\n<p><a href=\"https://i.stack.imgur.com/i0oTt.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/i0oTt.png\" alt=\"enter image description here\" /></a></p>\n<p>It will converge very fast for that data:</p>\n<p><a href=\"https://i.stack.imgur.com/IiGLf.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IiGLf.png\" alt=\"enter image description here\" /></a></p>\n<p>I also created a small benchmark for various algorithm to compute the Euclidean Squared Distance Matrix.<br />\nThe first test was between 3 approaches to calculate the distance between a single set of vectors (For example given by a single matrix):</p>\n<p><a href=\"https://i.stack.imgur.com/iBCeE.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/iBCeE.png\" alt=\"enter image description here\" /></a></p>\n<p>The second test I compared 2 Row / Column variations of the algorithm above:</p>\n<p><a href=\"https://i.stack.imgur.com/zdxa9.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zdxa9.png\" alt=\"enter image description here\" /></a></p>\n<p>The Row / Column variations means I test the algorithm in 2 cases:</p>\n<ol>\n<li>Row Variation - Each data sample is a row in the data matrix (Like your data).</li>\n<li>Column Variation - Each data sample is a column in the data matrix (In MATLAB it means the sample is contiguous in memory).</li>\n</ol>\n<p>As can be seen, it is always better to have data in the column variation.</p>\n<p><strong>Remark</strong>: Pay attention that the <em>Squared Euclidean Distance</em> doesn't obey the <a href=\"https://en.wikipedia.org/wiki/Triangle_inequality\" rel=\"nofollow noreferrer\">Triangle Inequality</a> which is a requirement for a <a href=\"https://en.wikipedia.org/wiki/Metric_(mathematics)\" rel=\"nofollow noreferrer\">Metric</a>. It is used for computational efficiency as it doesn't change the <em>K-Means</em> algorithm results compared to Euclidean Distance (The L<sub>2</sub> Norm based distance).</p>\n<p>The MATLAB Code is accessible in my <a href=\"https://github.com/RoyiAvital/StackExchangeCodes/tree/master/CodeReview/Q254186\" rel=\"nofollow noreferrer\">StackExchange Code Review Q254186 GitHub Repository</a>.</p>\n<p><strong>Remark</strong>: The K-Means algorithm, as a non convex optimization, is sensitive to the initialization. In the above code I used random initialization - randomly choosing samples form data to be the initial centroids. There are better approaches out there (See <a href=\"https://en.wikipedia.org/wiki/K-means%2B%2B\" rel=\"nofollow noreferrer\">K-Means++</a> as an example for a more robust initialization).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T06:24:02.187", "Id": "501319", "Score": "0", "body": "Your answer is real good but you haven't stated where my implementation went wrong. To be clear, the code I wrote for a faster computation produced results but they were inaccurate. (That's why I added a speculation at the end of my answer). Please include that as well, thank you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T09:24:45.730", "Id": "501330", "Score": "0", "body": "I don't know what's `K` and `n` in your code. I gave you the code to do it in 3rd dimension correctly. Also, it is better to keep the distance matrix as a variable. It is useful for other parts of the K-Means algorithm." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T09:32:53.900", "Id": "501332", "Score": "0", "body": "`K` is the number of medians and `n` stands for number of dimensions (no. of columns of **X**)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T09:43:42.063", "Id": "501334", "Score": "1", "body": "Moreover, using `reapmat()` for vecotrization should be last resort. As it creates more memory allocations which is bad for performance. So I'm not sure why you insist on it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T09:58:42.977", "Id": "501335", "Score": "0", "body": "I added the reason it fails and wrote how to make it work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T10:25:48.957", "Id": "501336", "Score": "0", "body": "I insisted on it because I am familiar with numpy new axis function which can generate the differences of 2 matrices which maybe of different dimensions. i.e. row of 1st matrix minus all the rows of centroid matrix. To do that on matlab, I replicated my **X** so that the `new-axes` are manually created." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T10:50:04.917", "Id": "501338", "Score": "1", "body": "This is called Implicit Broadcasting. [MATLAB has it as well](https://www.mathworks.com/help/matlab/matlab_prog/compatible-array-sizes-for-basic-operations.html). See my code, it utilizes it." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T23:24:32.347", "Id": "254196", "ParentId": "254186", "Score": "2" } } ]
{ "AcceptedAnswerId": "254196", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T19:16:10.117", "Id": "254186", "Score": "2", "Tags": [ "performance", "mathematics", "machine-learning", "matlab", "clustering" ], "Title": "Calculation of the Distance Matrix in the K-Means Algorithm in MATLAB" }
254186
<p>I made a quick script, that inputs file paths(made for C files), function names and 2 indexes. The script goes over all of the files and switches the indexes of the 2 functions. e.g.:</p> <p>Running the following code:</p> <pre><code>python switch_args.py temp_funct 0 1 tmp.c </code></pre> <p>If <code>tmp.c</code> contains this code:</p> <pre><code>int my_func(a, b, c, d) </code></pre> <p>after the execution of the script it would have this code:</p> <pre><code>int my_func(b, a, c, d) </code></pre> <h2>Code:</h2> <p><code>https://github.com/martin-varbanov96/toolboxz/blob/master/switch_function_args/switch_args.py</code>:</p> <pre><code>import argparse import re parser = argparse.ArgumentParser() parser.add_argument(&quot;function_name&quot;, type=str, help=&quot;function name whose arguments will be switched&quot;) parser.add_argument(&quot;index&quot;, type=int, help=&quot;first argument to be switched&quot;) parser.add_argument(&quot;destination&quot;, type=int, help=&quot;second argument to be switched&quot;) parser.add_argument('files', metavar='files', type=str, nargs='+', help='files in which function arguments will be switched') args = parser.parse_args() def switch_function_args(func_name, args, index=0, destination=1, ): function_call_pattern = &quot;{}[^\)]+&quot;.format(func_name) for file in args: has_function = False file_content = &quot;&quot; with open(file, &quot;r&quot;) as f: file_content = f.read() if(func_name in file_content): has_function = True if(has_function): for current_function_structure in re.findall(function_call_pattern, file_content): current_arguments = re.split(&quot;\(&quot;, current_function_structure)[1] current_arguments = re.split(&quot;,&quot;, current_arguments) # switch arguments current_arguments[index], current_arguments[destination] = current_arguments[destination], current_arguments[index] fixed_arguments = &quot;,&quot;.join(current_arguments) fixed_function_structure = &quot;{}({}&quot;.format(func_name, fixed_arguments) old_struct_pattern = current_function_structure.replace(&quot;(&quot;, &quot;\(&quot;) file_content = re.sub(old_struct_pattern, fixed_function_structure, file_content) with open(file, &quot;w&quot;) as f: f.write(file_content) switch_function_args(args.function_name, args.files, index=args.index, destination=args.destination) </code></pre> <h2>Question:</h2> <p>How can this code be optimized for performance?</p> <h2>EDIT:</h2> <p>what is the consistency of the following code and is it a good idea to ignore it?</p> <pre><code>with open(file, &quot;r&quot;) as f_read: # code with open(file, &quot;w&quot;) as f_write: # code </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T00:28:37.120", "Id": "501305", "Score": "1", "body": "Just... why? Why are you doing this? Code generation is, on its own, rarely called for; and code _modification_ even more rare." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T07:50:52.320", "Id": "501322", "Score": "0", "body": "Imagine you are using a C function in 20 files. At some point you want your function to do more than it used to do, so you would have to change the input parameters of the function. This has happened to me a couple of times and I think that having functions which add, remove or switch arguments would be helpful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T14:45:58.837", "Id": "501347", "Score": "0", "body": "I see; so this is a refactoring tool. At this point most IDEs worth using are able to do this; see for example CLion's [signature change feature](https://www.jetbrains.com/help/clion/refactoring-source-code.html)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-03T10:46:17.567", "Id": "501427", "Score": "0", "body": "Regarding your edit, it's good practice to have something like this: `with open(file, \"r\") as f_read, open(file, \"w\") as f_write: ... # code`" } ]
[ { "body": "<h2>General</h2>\n<p>C function arguments are only passed by position and not by name. As such, any attempt to make this modify real code is likely to break callers, and it's possible for that breakage to be silent during compile-time if the exchanged parameters have the same type. That makes this kind of refactoring deeply ill-advised. You're better off using the built-in signature refactoring feature of (pick any grown-up IDE).</p>\n<h2>Early continuation</h2>\n<p>Consider rewriting</p>\n<pre><code> if(func_name in file_content):\n has_function = True\n</code></pre>\n<p>as</p>\n<pre><code>if func_name not in file_content:\n continue\n</code></pre>\n<p>Note that the parens have been dropped; you don't need a flag variable; and you can de-indent the rest of the loop.</p>\n<h2>Fragility</h2>\n<p>Before asking</p>\n<blockquote>\n<p>How can this code be optimized for performance?</p>\n</blockquote>\n<p>you need to make it correct, and it definitely isn't right now for all cases. Functions in C are easily (and fairly often) aliased by pointer, and these aliases will not be modified if the pointer doesn't have the same name as the original function. Following such aliases would only reasonably be done by calling into an existing C parser like Clang/LLVM, which you should probably be doing anyway for robustness.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-03T06:09:10.573", "Id": "501422", "Score": "0", "body": "for the \"early continuation\" what worries me is the result from `with open(file, \"r\") as f:\n with open(file, \"w\") as f:\n` Sorry I can not write proper code here. I will make an Edit. What is the consistency of the stacking 2 context managers which are opening the same file?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-08T02:15:14.513", "Id": "501786", "Score": "0", "body": "That depends. In your case you should be able to delete your second `open`, change the first to open in combined read-write mode, and after your read (and before your write), truncate the file." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T20:03:32.883", "Id": "254238", "ParentId": "254187", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T19:22:42.140", "Id": "254187", "Score": "2", "Tags": [ "python", "performance", "regex" ], "Title": "Optimizing a script that switches function arguments in code files" }
254187
<p>I'm new to Java so I have given myself small projects to help myself learn the ropes of java. My project was to create a function that would summate an expression no matter how high the degree or value of <code>n</code>.</p> <p>I ended up being able to complete it but I wanted someone who knew what they were doing to look over it and see if I was doing things the right way.</p> <p>A goal was to use no pre-built packages but I ended up using the <code>java.lang.Math.pow()</code> function (I didn't import it).</p> <p>Also, what recommendations do you have for learning for beginners? I do have some experience programming but I feel like I never learned the correct way...</p> <p>Code:</p> <pre><code>package TestSpace; public class MathClass { /* Steps: 1. Get array of any length and n 2. Reverse list so highest degree coefficients are last 3. Run for loop for each time n increases 4.Run for loop inside of that for each entry in array */ //args consists of the coefficients of x; must include all degrees of x counting down from the highest degree public static float sigma (int[] args, int n) { float value = 0; int length = args.length; //reverses list int[] reverselist = reverselist(args); for(int i = 1;i&lt;n+1;i++) { for(int v = 0; v &lt; length;v++) { // Multiplies coefficient by &quot;x&quot; raised to the power of its degree value += reverselist[v] * java.lang.Math.pow(i, v); } } return value; } //Reverses the order of the given array so that highest degree is at the end public static int[] reverselist(int[] args) { int length = args.length; int[] newint = new int[length]; for(int i = 0;i&lt;length;i++) { newint[i] = args[length - (i+1)]; } return newint; } //Makes printing simple public static void print(Object obj) { try { System.out.println(obj); }catch(Exception e){ System.out.println(e); } } //main function public static void main(String[] args) { print(sigma(new int[] {5,2,7,4},4)); } } </code></pre>
[]
[ { "body": "<ol>\n<li>Follow Java naming conventions. Your package name should be all\nlowercase - 'testspace'. 'reverselist' should be 'reverseList'.</li>\n<li>Don't use fully qualified 'java.lang.Math', just 'Math'. You don't need to import classes from the java.lang package.</li>\n<li>Indent your comments to match the code.</li>\n<li>Use descriptive variable names, e.g. 'v' could be 'exponent' or\n'power'. Why use 'i' and then describe it as 'x' in the comment? Should 'reverselist' be 'reverseArray'?</li>\n</ol>\n<p>In general your algorithms are reasonable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T22:21:45.130", "Id": "254195", "ParentId": "254190", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T20:58:16.707", "Id": "254190", "Score": "1", "Tags": [ "java", "mathematics", "calculator" ], "Title": "Java Summation Program" }
254190
<p>I created a function to give me an estimated date of hearing back from grad school applications using the median length of days between each theGradCafe submission and January 1st. I separated submissions into three categories -- general, Interview, Acceptance, Rejection.</p> <p>This is my first R project and I would love to get some criticisms on how to clean things up with it; the code is really clunky but seems to do the job.</p> <p>Here it is:</p> <pre><code>grad=function(x,y){ #just one link? if(missing(y)) { #inserting the link pat=&quot;U.*$&quot; require(rvest) require(stringr) require(dplyr) #converting link to text h=read_html(x) nodes=h %&gt;% html_nodes(&quot;.tcol3&quot;) #cleaning up text gadmin=sapply(nodes, html_text)[2:length(nodes)] gadmin=sub('.*on', '', gadmin) a=sub('.*on', '', gadmin) gadmin=sub(pat, '', gadmin) %&gt;% as.Date(&quot;%d %B %Y&quot;) #finishing gadmint_c=format(gadmin, &quot;%m-%d&quot;) %&gt;% as.Date(&quot;%m-%d&quot;) origin_date &lt;- as.Date(&quot;2021-01-01&quot;) #date estimates lengthp=as.numeric(julian(gadmint_c, origin_date)) lengthp=ifelse(lengthp &gt;=334, lengthp-365, lengthp) lengthp=ifelse(lengthp &gt; 5.5*sd(lengthp, na.rm=T) | lengthp &lt; -5.5*sd(lengthp, na.rm=T), NA, lengthp) estd=as.Date(&quot;2021-01-01&quot;)+median(lengthp, na.rm=T) estd=format(estd, format=&quot;%m-%d&quot;) print(paste(&quot;You should hear SOMETHING by&quot;, estd)) invisible(estd) #interview estimates nodes_i=nodes[which(str_extract(as.character(nodes), &quot;Interview&quot;) ==&quot;Interview&quot;)] gadmin_i=sapply(nodes_i, html_text) gadmin_i=sub('.*on', '', gadmin_i) gadmin_i= sub(pat, '', gadmin_i) %&gt;% as.Date(&quot;%d %B %Y&quot;) #finishing interviews gadmint_ci=format(gadmin_i, &quot;%m-%d&quot;) %&gt;% as.Date(&quot;%m-%d&quot;) origin_date &lt;- as.Date(&quot;2021-01-01&quot;) #interview estimates lengthpi=as.numeric(julian(gadmint_ci, origin_date)) lengthpi=ifelse(lengthpi &gt;=334, lengthpi-365, lengthpi) lengthpi=ifelse(lengthpi &gt; 5.5*sd(lengthpi, na.rm=T) | lengthpi &lt; -5.5*sd(lengthpi, na.rm=T), NA, lengthpi) estdi=as.Date(&quot;2021-01-01&quot;)+median(lengthpi, na.rm=T) estdi=format(estdi, format=&quot;%m-%d&quot;) print(paste(&quot;You should hear about Interviews by &quot;, estdi)) invisible(estdi) #acceptance/rejectance estimates nodes_r=nodes[c(which(str_extract(as.character(nodes), &quot;Rejected&quot;) ==&quot;Rejected&quot;))] nodes_a=nodes[c(which(str_extract(as.character(nodes), &quot;Accepted&quot;) ==&quot;Accepted&quot;))] gadmin_r=sapply(nodes_r, html_text) gadmin_a=sapply(nodes_a, html_text) gadmin_r=sub('.*on', '', gadmin_r) gadmin_a=sub('.*on', '', gadmin_a) gadmin_r= sub(pat, '', gadmin_r) %&gt;% as.Date(&quot;%d %B %Y&quot;) gadmin_a= sub(pat, '', gadmin_a) %&gt;% as.Date(&quot;%d %B %Y&quot;) #finishing acceptance/rejectance gadmint_car_r=format(gadmin_r, format=&quot;%m-%d&quot;) %&gt;% as.Date(&quot;%m-%d&quot;) gadmint_car_a=format(gadmin_a, format=&quot;%m-%d&quot;) %&gt;% as.Date(&quot;%m-%d&quot;) origin_date &lt;- as.Date(&quot;2021-01-01&quot;) #acceptance/rejections estimates lengthpar_r=as.numeric(julian(gadmint_car_r, origin_date)) lengthpar_a=as.numeric(julian(gadmint_car_a, origin_date)) lengthpar_r=ifelse(lengthpar_r &gt;=334, lengthpar_r-365, lengthpar_r) lengthpar_r=ifelse(lengthpar_r &gt; 5.5*sd(lengthpar_r, na.rm=T) | lengthpar_r &lt; -5.5*sd(lengthpar_r, na.rm=T), NA, lengthpar_r) lengthpar_a=ifelse(lengthpar_a &gt;=334, lengthpar_a-365, lengthpar_a) lengthpar_a=ifelse(lengthpar_a &gt; 5.5*sd(lengthpar_a, na.rm=T) | lengthpar_a &lt; -5.5*sd(lengthpar_a, na.rm=T), NA, lengthpar_a) estdar_r=as.Date(&quot;2021-01-01&quot;)+median(lengthpar_r, na.rm=T) estdar_a=as.Date(&quot;2021-01-01&quot;)+median(lengthpar_a, na.rm=T) estdar_r=format(estdar_r, format=&quot;%m-%d&quot;) estdar_a=format(estdar_a, format=&quot;%m-%d&quot;) print(paste(&quot;You should hear about Rejections by&quot;, estdar_r)) print(paste(&quot;You should hear about Acceptances by&quot;, estdar_a)) invisible(estdar_r) invisible(estdar_a) } else { #just two links? #inserting the link pat=&quot;U.*$&quot; require(rvest) require(dplyr) #converting link to text hx=read_html(x) hy=read_html(y) nodesx=hx %&gt;% html_nodes(&quot;.tcol3&quot;) nodesy=hy %&gt;% html_nodes(&quot;.tcol3&quot;) #cleaning up text gadminx=sapply(nodesx, html_text)[2:length(nodesx)] gadminy=sapply(nodesy, html_text)[2:length(nodesy)] gadminx=sub('.*on', '', gadminx) ax=sub('.*on', '', gadminx) gadminx=sub(pat, '', gadminx) %&gt;% as.Date(&quot;%d %B %Y&quot;) gadminy=sub('.*on', '', gadminy) ay=sub('.*on', '', gadminy) gadminy=sub(pat, '', gadminy) %&gt;% as.Date(&quot;%d %B %Y&quot;) gadmin=c(gadminx, gadminy) #finishing gadmint_c=format(gadmin, format=&quot;%m-%d&quot;)%&gt;% as.Date(&quot;%m-%d&quot;) origin_date &lt;- as.Date(&quot;2021-01-01&quot;) #date estimates lengthp=as.numeric(julian(gadmint_c, origin_date)) lengthp=ifelse(lengthp &gt;=334, lengthp-365, lengthp) lengthp=ifelse(lengthp &gt; 5.5*sd(lengthp, na.rm=T) | lengthp &lt; -5.5*sd(lengthp, na.rm=T), NA, lengthp) estd=as.Date(&quot;2021-01-01&quot;)+median(lengthp, na.rm=T) estd=format(estd, format=&quot;%m-%d&quot;) print(paste(&quot;You should hear SOMETHING by&quot;, estd)) invisible(estd) #interview estimates nodes_ix=nodesx[which(str_extract(as.character(nodesx), &quot;Interview&quot;) ==&quot;Interview&quot;)] nodes_iy=nodesy[which(str_extract(as.character(nodesy), &quot;Interview&quot;) ==&quot;Interview&quot;)] gadmin_ix=sapply(nodes_ix, html_text) gadmin_iy=sapply(nodes_iy, html_text) gadmin_ix=sub('.*on', '', gadmin_ix) gadmin_ix= sub(pat, '', gadmin_ix) %&gt;% as.Date(&quot;%d %B %Y&quot;) gadmin_iy=sub('.*on', '', gadmin_iy) gadmin_iy= sub(pat, '', gadmin_iy) %&gt;% as.Date(&quot;%d %B %Y&quot;) #finishing interviews gadmint_ci=c(gadmin_ix, gadmin_iy) gadmint_ci=format(gadmint_ci, &quot;%m-%d&quot;)%&gt;% as.Date(&quot;%m-%d&quot;) origin_date &lt;- as.Date(&quot;2021-01-01&quot;) #interview estimates lengthpi=as.numeric(julian(gadmint_ci, origin_date)) lengthpi=ifelse(lengthpi &gt;=334, lengthpi-365, lengthpi) lengthpi=ifelse(lengthpi &gt; 5.5*sd(lengthpi, na.rm=T) | lengthpi &lt; -5.5*sd(lengthpi, na.rm=T), NA, lengthpi) estdi=as.Date(&quot;2021-01-01&quot;)+median(lengthpi, na.rm=T) estdi=format(estdi, format=&quot;%m-%d&quot;) print(paste(&quot;You should hear about Interviews by &quot;, estdi)) invisible(estdi) #acceptance/rejectance estimates nodes_rx=nodesx[c(which(str_extract(as.character(nodesx), &quot;Rejected&quot;) ==&quot;Rejected&quot;))] nodes_ax=nodesx[which(str_extract(as.character(nodesx), &quot;Accepted&quot;) ==&quot;Accepted&quot;)] nodes_ry=nodesy[c(which(str_extract(as.character(nodesy), &quot;Rejected&quot;) ==&quot;Rejected&quot;))] nodes_ay=nodesy[which(str_extract(as.character(nodesy), &quot;Accepted&quot;) ==&quot;Accepted&quot;)] gadmin_rx=sapply(nodes_rx, html_text) gadmin_ax=sapply(nodes_ax, html_text) gadmin_ry=sapply(nodes_ry, html_text) gadmin_ay=sapply(nodes_ay, html_text) gadmin_rx=sub('.*on', '', gadmin_rx) gadmin_ax=sub('.*on', '', gadmin_ax) gadmin_ry=sub('.*on', '', gadmin_ry) gadmin_ay=sub('.*on', '', gadmin_ay) gadmin_rx= sub(pat, '', gadmin_rx) %&gt;% as.Date(&quot;%d %B %Y&quot;) gadmin_ax=sub(pat, '', gadmin_ax) %&gt;% as.Date(&quot;%d %B %Y&quot;) gadmin_ry= sub(pat, '', gadmin_ry) %&gt;% as.Date(&quot;%d %B %Y&quot;) gadmin_ay=sub(pat, '', gadmin_ay) %&gt;% as.Date(&quot;%d %B %Y&quot;) gadmin_r=c(gadmin_rx, gadmin_ry) gadmin_a=c(gadmin_ax, gadmin_ay) #finishing acceptance/rejectance gadmint_c_r=format(gadmin_r, format=&quot;%m-%d&quot;)%&gt;% as.Date(&quot;%m-%d&quot;) gadmint_c_a=format(gadmin_a, format=&quot;%m-%d&quot;) %&gt;% as.Date(&quot;%m-%d&quot;) origin_date &lt;- as.Date(&quot;2021-01-01&quot;) #acceptance/rejections estimates lengthpar_r=as.numeric(julian(gadmint_c_r, origin_date)) lengthpar_a=as.numeric(julian(gadmint_c_a, origin_date)) lengthpar_r=ifelse(lengthpar_r &gt;=334, lengthpar_r-365, lengthpar_r) lengthpar_r=ifelse(lengthpar_r &gt; 5.5*sd(lengthpar_r, na.rm=T) | lengthpar_r &lt; -5.5*sd(lengthpar_r,na.rm=T), NA, lengthpar_r) lengthpar_a=ifelse(lengthpar_a &gt;=334, lengthpar_a-365, lengthpar_a) lengthpar_a=ifelse(lengthpar_a &gt; 5.5*sd(lengthpar_a, na.rm=T) | lengthpar_a &lt; -5.5*sd(lengthpar_a, na.rm=T), NA, lengthpar_a) estd_a=as.Date(&quot;2021-01-01&quot;)+median(lengthpar_a, na.rm=T) estd_r=as.Date(&quot;2021-01-01&quot;)+median(lengthpar_r, na.rm=T) estd_r=format(estd_r, format=&quot;%m-%d&quot;) estd_a=format(estd_a, format=&quot;%m-%d&quot;) print(paste(&quot;You should hear about Acceptance by &quot;, estd_a)) print(paste(&quot;You should hear about Rejection by &quot;, estd_r)) invisible(estd_a) invisible(estd_r) } } </code></pre> <p>So for example, if I wanted to look at Stanford submissions, I would type <code>grad(&quot;https://www.thegradcafe.com/survey/index.php?q=Stanford+University&amp;t=a&amp;o=&amp;pp=250&quot;)</code> and get back:</p> <pre><code> grad(&quot;https://www.thegradcafe.com/survey/index.php?q=Stanford+University&amp;t=a&amp;o=&amp;pp=250&quot;) [1] &quot;You should hear SOMETHING by 03-21&quot; [1] &quot;You should hear about Interviews by 12-18&quot; [1] &quot;You should hear about Rejections by 02-12&quot; [1] &quot;You should hear about Acceptances by 03-20&quot; </code></pre> <p>Or, if I applied to Stanford and Harvard:</p> <pre><code> grad(&quot;https://www.thegradcafe.com/survey/index.php?q=Stanford+University&amp;t=a&amp;o=&amp;pp=250&quot;, &quot;https://www.thegradcafe.com/survey/index.php?q=harvard&amp;t=a&amp;o=&amp;pp=250&quot;) [1] &quot;You should hear SOMETHING by 03-17&quot; [1] &quot;You should hear about Interviews by 12-18&quot; [1] &quot;You should hear about Acceptance by 03-18&quot; [1] &quot;You should hear about Rejection by 03-05&quot; </code></pre> <p>The reason why SOMETHING is sometimes behind the others is because it's general, lumping everything in together, while the others are more specific.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-06T17:27:55.007", "Id": "501703", "Score": "0", "body": "This is quite a bit of code. Without reading every single line, can you advise what differs between the `if` and `else` block?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-06T18:10:04.473", "Id": "501704", "Score": "0", "body": "@Parfait Sorry about that! I was reading on Stack Overflow and that was their recommendation for specifying optional arguments in R functions. The ```if``` specifies the first link which is required, while the ```else``` specifies the second link which is optional." } ]
[ { "body": "<p>Consider breaking up your repetitive operations into separate functions. And specifically for <code>grad</code> function use R's <a href=\"https://stackoverflow.com/q/3057341/1422451\">ellipsis feature</a>, allowing you to pass many URLs with same call. Both steps will keep your code DRY (<strong>D</strong>on't <strong>R</strong>epeat <strong>Y</strong>ourself). Finally, heed R's emphasis on <em>everything that exists is an object</em> and store your results in list of data frames (one for each URL) via <code>lapply</code> iteration instead of a one-time printout without persistent data.</p>\n<h3>Functions</h3>\n<ul>\n<li>Space out your sections and operators</li>\n<li>Line break long calls</li>\n<li>Use <code>&lt;-</code> operator for object assignment</li>\n<li>Remove multiple <code>invisible</code> for single <code>return</code></li>\n<li>Avoid pipes <code>%&gt;%</code> for simple one nest like <code>as.Date</code></li>\n</ul>\n<p><strong><code>node_subset</code></strong></p>\n<pre class=\"lang-r prettyprint-override\"><code>node_subset &lt;- function(nodes, search_word=NA) { \n if(is.na(search_word)) {\n sub_nodes &lt;- nodes\n } else {\n sub_nodes &lt;- nodes[which(str_extract(as.character(nodes), search_word)==search_word)]\n }\n \n pat &lt;- &quot;U.*$&quot;\n gadmin &lt;- sapply(sub_nodes, html_text)\n gadmin &lt;- sub('.*on', '', gadmin)\n gadmin &lt;- as.Date(sub(pat, '', gadmin), format=&quot;%d %B %Y&quot;)\n gadmin_dt &lt;- as.Date(format(gadmin, &quot;%m-%d&quot;), format=&quot;%m-%d&quot;)\n \n return(gadmin_dt)\n}\n</code></pre>\n<p><strong><code>date_calc</code></strong></p>\n<pre class=\"lang-r prettyprint-override\"><code>date_calc &lt;- function(param_dt, origin_date=as.Date(&quot;2021-01-01&quot;)) { \n lengthp &lt;- as.numeric(julian(param_dt, origin_date))\n lengthp &lt;- ifelse(lengthp &gt;= 334, lengthp-365, lengthp)\n lengthp &lt;- ifelse(lengthp &gt; 5.5 * sd(lengthp, na.rm=TRUE) |\n lengthp &lt; -5.5 * sd(lengthp, na.rm=TRUE), NA, lengthp)\n estd &lt;- as.Date(&quot;2021-01-01&quot;) + median(lengthp, na.rm=TRUE)\n estd &lt;- format(estd, format=&quot;%m-%d&quot;)\n \n return(estd)\n}\n</code></pre>\n<p><strong><code>grad</code></strong></p>\n<pre class=\"lang-r prettyprint-override\"><code>grad &lt;- function(...) { \n lapply(list(...), function(x) {\n \n #inserting the link\n require(rvest)\n require(stringr)\n require(dplyr)\n \n #converting link to text\n h &lt;- read_html(x)\n nodes &lt;- html_nodes(h, &quot;.tcol3&quot;)\n \n #cleaning up text\n gadmint_c &lt;- node_subset(nodes)\n gadmint_ci &lt;- node_subset(nodes, &quot;Interview&quot;)\n gadmint_car_r &lt;- node_subset(nodes, &quot;Rejected&quot;)\n gadmint_car_a &lt;- node_subset(nodes, &quot;Accepted&quot;)\n \n #date estimates\n estd &lt;- date_calc(gadmint_c)\n print(paste(&quot;You should hear SOMETHING by&quot;, estd))\n \n #interview estimates\n estdi &lt;- date_calc(gadmint_ci)\n print(paste(&quot;You should hear about Interviews by &quot;, estdi))\n \n #acceptance/rejections estimates\n estdar_r &lt;- date_calc(gadmint_car_r)\n print(paste(&quot;You should hear about Rejections by&quot;, estdar_r))\n \n estdar_a &lt;- date_calc(gadmint_car_a)\n print(paste(&quot;You should hear about Acceptances by&quot;, estdar_a))\n\n return(data.frame(url = x, \n estd = estd, \n estdi = estdi, \n estdar_r = estdar_r, \n estdar_a = estdar_a,\n stringsAsFactors = FALSE) # ARG UNNEEDED FOR R 4.0+\n )\n })\n}\n</code></pre>\n<h3>Calls</h3>\n<pre class=\"lang-r prettyprint-override\"><code>df_list1 &lt;- grad(&quot;https://www.thegradcafe.com/survey/index.php?q=Stanford+University&amp;t=a&amp;o=&amp;pp=250&quot;)\n# [1] &quot;You should hear SOMETHING by 03-21&quot;\n# [1] &quot;You should hear about Interviews by 12-18&quot;\n# [1] &quot;You should hear about Rejections by 03-21&quot;\n# [1] &quot;You should hear about Acceptances by 03-20&quot;\n\ndf_list2 &lt;- grad(&quot;https://www.thegradcafe.com/survey/index.php?q=Stanford+University&amp;t=a&amp;o=&amp;pp=250&quot;, \n &quot;https://www.thegradcafe.com/survey/index.php?q=harvard&amp;t=a&amp;o=&amp;pp=250&quot;)\n# [1] &quot;You should hear SOMETHING by 03-21&quot;\n# [1] &quot;You should hear about Interviews by 12-18&quot;\n# [1] &quot;You should hear about Rejections by 03-21&quot;\n# [1] &quot;You should hear about Acceptances by 03-20&quot;\n# [1] &quot;You should hear SOMETHING by 03-05&quot;\n# [1] &quot;You should hear about Interviews by 12-18&quot;\n# [1] &quot;You should hear about Rejections by 03-04&quot;\n# [1] &quot;You should hear about Acceptances by 03-07&quot;\n</code></pre>\n<h3>Data</h3>\n<pre class=\"lang-r prettyprint-override\"><code>str(df_list1)\n# List of 1\n# $ :'data.frame': 1 obs. of 5 variables:\n# ..$ url : chr &quot;https://www.thegradcafe.com/survey/index.php?q=Stanford+University&amp;t=a&amp;o=&amp;pp=250&quot;\n# ..$ estd : chr &quot;03-21&quot;\n# ..$ estdi : chr &quot;12-18&quot;\n# ..$ estdar_r: chr &quot;03-21&quot;\n# ..$ estdar_a: chr &quot;03-20&quot;\n\nstr(df_list2)\n# List of 2\n# $ :'data.frame': 1 obs. of 5 variables:\n# ..$ url : chr &quot;https://www.thegradcafe.com/survey/index.php?q=Stanford+University&amp;t=a&amp;o=&amp;pp=250&quot;\n# ..$ estd : chr &quot;03-21&quot;\n# ..$ estdi : chr &quot;12-18&quot;\n# ..$ estdar_r: chr &quot;03-21&quot;\n# ..$ estdar_a: chr &quot;03-20&quot;\n# $ :'data.frame': 1 obs. of 5 variables:\n# ..$ url : chr &quot;https://www.thegradcafe.com/survey/index.php?q=harvard&amp;t=a&amp;o=&amp;pp=250&quot;\n# ..$ estd : chr &quot;03-05&quot;\n# ..$ estdi : chr &quot;12-18&quot;\n# ..$ estdar_r: chr &quot;03-04&quot;\n# ..$ estdar_a: chr &quot;03-07&quot;\n</code></pre>\n<p>Even combine list of multiple data frames into a single data frame:</p>\n<pre class=\"lang-r prettyprint-override\"><code>final_df &lt;- do.call(rbind, df_list2)\nfinal_df\n\n# url estd estdi estdar_r estdar_a\n# 1 https://www.thegradcafe.com/survey/index.php?q=Stanford+University&amp;t=a&amp;o=&amp;pp=250 03-21 12-18 03-21 03-20\n# 2 https://www.thegradcafe.com/survey/index.php?q=harvard&amp;t=a&amp;o=&amp;pp=250 03-05 12-18 03-04 03-07\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-07T20:02:15.350", "Id": "501765", "Score": "0", "body": "Thank you! :D @Parfait" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-06T19:27:58.810", "Id": "254391", "ParentId": "254193", "Score": "3" } } ]
{ "AcceptedAnswerId": "254391", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-01T22:11:46.663", "Id": "254193", "Score": "2", "Tags": [ "r" ], "Title": "How can I strengthen this function? I want it to give me an estimated date of hearing back from grad school applications" }
254193
<p>An unsigned integer version of <code>pow()</code> is fairly easy to code, yet I also wanted:</p> <ol> <li>overflow detection</li> <li>portability</li> <li>only modest performance impact due to overflow detection.</li> </ol> <p>The below codes uses a simple <code>&gt;=</code> test in the loop to see if the calculation is nearing overflow. When needed, in a 2nd loop, more expensive <code>/</code> tests are used.</p> <p>[ Code also uses a nifty <code>IMAX_BITS</code> macro to find the number of <em>value bits</em> in a <code>..._MAX</code> constant as <code>CHAR_BIT * sizeof(type)</code> fails when rare padding exist or the <code>MAX</code> value is not the <code>MAX</code> of the type, like <code>RAND_MAX</code>. ]</p> <p>Review goals:</p> <ul> <li><p>Performance improvement ideas for <code>uintmax_t pow_umax(uintmax_t base, unsigned expo)</code>, especially concerning overflow detection.</p> </li> <li><p>General review about <code>pow.h</code> and <code>pow.c</code>.</p> </li> <li><p>General review about test code functionally, not code.</p> </li> </ul> <hr /> <p><code>pow.h</code> header</p> <pre><code>#ifndef POW_H #define POW_H 1 #include &lt;inttypes.h&gt; // Return base raised to the expo power. // On overflow, set errno = ERANGE and return UINTMAX_MAX. uintmax_t pow_umax(uintmax_t base, unsigned expo); #endif </code></pre> <p><code>pow.c</code> code</p> <pre><code>#include &quot;pow.h&quot; #include &lt;errno.h&gt; #include &lt;inttypes.h&gt; #include &lt;limits.h&gt; // https://stackoverflow.com/a/4589384/2410359 /* Number of value bits in inttype_MAX, or in any (1&lt;&lt;k)-1 where 0 &lt;= k &lt; 2040 */ #define IMAX_BITS(m) ((m)/((m)%255+1) / 255%255*8 + 7-86/((m)%255+12)) // Value bit width of UINTMAX_MAX (handles padded types). #define UINTMAX_BITS IMAX_BITS(UINTMAX_MAX) // When `base &gt;= cubert(UINTMAX_MAX + 1)` potentially the next // `base *= base` and `pow *= base` may overflow. // Course lower bound cube root of (UINTMAX_MAX + 1) #define UINTMAX_MAXP1_CBRT (((uintmax_t) 1) &lt;&lt; (UINTMAX_BITS/3)) // Detect overflow in an integer pow() calculation with minimal overhead. uintmax_t pow_umax(uintmax_t base, unsigned expo) { uintmax_t pow = 1; for (;;) { if (expo % 2) { pow *= base; } expo /= 2; if (expo == 0) { return pow; } // If base is so big, it might overflow `base *= base` or `pow *= base`. if (base &gt;= UINTMAX_MAXP1_CBRT) { break; } base *= base; } // `base` is large here, add precise tests for `base *= base` and `pow *= base`. for (;;) { if (base &gt; UINTMAX_MAX / base) { break; } base *= base; if (expo % 2) { if (pow &gt; UINTMAX_MAX / base) { break; } pow *= base; } expo /= 2; if (expo == 0) { return pow; } } errno = ERANGE; return UINTMAX_MAX; } </code></pre> <p>Test code</p> <pre><code>#include &lt;assert.h&gt; #include &lt;errno.h&gt; #include &lt;inttypes.h&gt; #include &lt;limits.h&gt; #include &lt;math.h&gt; #include &lt;stdbool.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &quot;pow.h&quot; // Bit width of various ..._MAX (handles padded types). #define IMAX_BITS(m) ((m)/((m)%255+1) / 255%255*8 + 7-86/((m)%255+12)) #define UINTMAX_BITS IMAX_BITS(UINTMAX_MAX) #define RAND_MAX_BITS IMAX_BITS(RAND_MAX) #define UNSIGNED_BITS IMAX_BITS(UINT_MAX) // Random number usage on this. _Static_assert(((RAND_MAX + 1u) &amp; RAND_MAX) == 0, &quot;RAND_MAX is not a Mersenne number&quot;); // Support for failing implementations is not a review goal. // Return random number [0...UINTMAX_MAX] uintmax_t rand_umax(void) { uintmax_t u = 0; for (unsigned bits = 0; bits &lt; UINTMAX_BITS; bits += RAND_MAX_BITS) { u = (u &lt;&lt; RAND_MAX_BITS) ^ (rand() &amp; RAND_MAX); } return u; } // Return random number [0...UINT_MAX] unsigned rand_u(void) { unsigned u = 0; for (unsigned bits = 0; bits &lt; UNSIGNED_BITS; bits += RAND_MAX_BITS) { u = (u &lt;&lt; RAND_MAX_BITS) ^ (rand() &amp; RAND_MAX); } return u; } _Static_assert(sizeof(long double)*CHAR_BIT &gt;= 80, &quot;Need wider long double for verification&quot;); // Test pow_umax() for errno and return value correctness. int pow_umax_test(uintmax_t base, unsigned expo) { errno = 0; uintmax_t p = pow_umax(base, expo); if (errno &amp;&amp; p != UINTMAX_MAX) { printf(&quot;Error: %ju, %u&quot;, base, expo); exit(EXIT_FAILURE); } // Use powl() as a reference function. long double y = powl(base, expo); if ((errno == 0 &amp;&amp; y != p) || (errno &amp;&amp; y &lt;= UINTMAX_MAX)) { printf(&quot;Error: %ju, %u --&gt; p=%ju, y=%Lf&quot;, base, expo, p, y); exit(EXIT_FAILURE); } return 0; } // Perform multiple pow_umax() tests. int pow_umax_tests(void) { printf(&quot;uintmax_t bit width: %ju\n&quot;, UINTMAX_BITS); printf(&quot;unsigned bit width : %u\n&quot;, UNSIGNED_BITS); printf(&quot;RAND_MAX bit width : %u\n&quot;, RAND_MAX_BITS); printf(&quot;uintmaxp1_cbrt : 0x%jX\n&quot;, UINTMAX_MAXP1_CBRT); int err = 0; // The usual suspects. uintmax_t b[] = {0, 1, 2, UINTMAX_MAXP1_CBRT - 1, UINTMAX_MAXP1_CBRT, UINTMAX_MAXP1_CBRT + 1, UINTMAX_MAX - 1, UINTMAX_MAX}; unsigned e[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, UINT_MAX - 1, UINT_MAX}; size_t bn = sizeof b / sizeof b[0]; size_t en = sizeof e / sizeof e[0]; for (unsigned bi = 0; bi &lt; bn; bi++) { for (unsigned ei = 0; ei &lt; en; ei++) { err += pow_umax_test(b[bi], e[ei]); } } // Random tests for (unsigned long i = 0; i &lt; 10000000u; i++) { err += pow_umax_test(rand_umax(), rand_u()); } return err; } int main(void) { pow_umax_tests(); puts(&quot;Done&quot;); } </code></pre> <p>Sample result (no errors)</p> <pre><code>uintmax_t bit width: 64 unsigned bit width : 32 RAND_MAX bit width : 31 uintmaxp1_cbrt : 0x200000 Done </code></pre>
[]
[ { "body": "<p>As a discussion point (and not strictly a recommendation), I wonder how your overflow detection algorithm would compare with the following:</p>\n<p>Assuming a 64-bit integer (substituting as necessary): We know that if <span class=\"math-container\">\\$y \\ge 2^{64} \\$</span>, <span class=\"math-container\">\\$y\\$</span> has overflowed. If <span class=\"math-container\">\\$ y = x^a \\$</span>,</p>\n<p><span class=\"math-container\">$$ x^a \\lt 2^{64} $$</span>\n<span class=\"math-container\">$$ a \\log_2 x &lt; 64 $$</span></p>\n<p><span class=\"math-container\">\\$ \\log_2 \\$</span> is cheap and can be done with bit-twiddling, i.e. without using floating-point math; so this should be quick enough. For details on how to do this see <a href=\"https://stackoverflow.com/questions/11376288/fast-computing-of-log2-for-64-bit-integers\">https://stackoverflow.com/questions/11376288/fast-computing-of-log2-for-64-bit-integers</a> .</p>\n<p>This can be a quick first check before performing the full check, but cannot be a comprehensive check on its own. Take for instance</p>\n<p><span class=\"math-container\">$$ 3^{63} &gt;&gt; 2^{64} $$</span>\n<span class=\"math-container\">$$ \\left\\lfloor \\log_2 3 \\right\\rfloor = 1 $$</span>\n<span class=\"math-container\">$$ 63 \\times 1 &lt; 64$$</span></p>\n<p>The rounding error from calculating an integer logarithm can yield false negatives.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T03:24:25.237", "Id": "501312", "Score": "0", "body": "When `a*log2(x)` is close to 64, the calculation of `log2(x)` and multiplication by `a` needs to be done _very carefully_ and prone to slight errors. When that product is `64 + margin` there's overflow & `64 - margin` there's no overflow. Yet when ~64 the integer calculation remains necessary (with overflow precautions) for the remains corner cases. As for \"log2 is cheap and can be done with bit-twiddling\", (integer part certainly easy) I'd be interest in seeing that. It may need the answer calculate as not +/- 0.5 ULP, but +0/-1.0 ULP (one sided error). Still an insightful idea." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T03:26:42.553", "Id": "501313", "Score": "0", "body": "As for portability, `uintmax_t` may be more than 64-bit, so code should not assume 64." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T05:02:10.407", "Id": "501316", "Score": "0", "body": "Of course; 64 is short-hand for \"whatever your working integer size may be\", and yes, it should not be hard-coded." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T02:53:02.263", "Id": "254204", "ParentId": "254198", "Score": "1" } }, { "body": "<blockquote>\n<p>General review about pow.h and pow.c.</p>\n</blockquote>\n<p>When overflow does <em>not</em> occur, <code>pow_umax()</code> can only return <code>UINTMAX_MAX</code> with <code>pow_umax(UINTMAX_MAX, 1)</code>.</p>\n<p>There is no other <code>base, expo</code> such that <code>pow_umax(base, expo)</code> returns <code>UINTMAX_MAX</code>, regardless of the bit width of <code>uintmax_t</code> due to <a href=\"https://math.stackexchange.com/q/2352131/83175\">Mihailescu's Theorem</a>. [Just found that out today.]</p>\n<p>So setting <code>errno = ERANGE</code> is only distinctive in that one case. Otherwise code could ignore <code>errno</code> and use:</p>\n<pre><code>// Sufficient test except in one case.\nif (pow_umax(base, expo) == UINTMAX_MAX) {\n puts(&quot;Overflow&quot;);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T13:44:51.227", "Id": "254222", "ParentId": "254198", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T00:39:14.970", "Id": "254198", "Score": "2", "Tags": [ "c", "reinventing-the-wheel" ], "Title": "Unsigned integer power with overflow detection" }
254198
<p>I am currently iteratively forcing the solution by evaluating all of one elements possible coexisting elements for the closest combination to half of the initial arrays sum. Note: The initial array is assumed to be of length 8 in all cases (I'm not too sure how such an approach could be adapted to work for various array lengths without using recursion).</p> <pre><code>int target = team1.stream().mapToInt(Player::getElo).sum() / 2; int closest = Integer.MAX_VALUE; int[] best = new int[3]; ArrayList&lt;Player&gt; team2 = new ArrayList&lt;&gt;(); team2.add(team1.get(0)); team1.remove(0); for (int i = 0; i &lt; team1.size(); i++) { for (int j = 0; j &lt; team1.size(); j++) { if (team1.get(j) == team1.get(i)) continue; for (int k = 0; k &lt; team1.size(); k++) { if (team1.get(k) == team1.get(j) || team1.get(k) == team1.get(i)) continue; int elo = team2.get(0).getElo() + team1.get(i).getElo() + team1.get(j).getElo() + team1.get(k).getElo(); int dif = Math.abs(target - elo); if (dif &lt; closest) { closest = dif; best[0] = i; best[1] = j; best[2] = k; } } } } team2.add(team1.get(best[0])); team2.add(team1.get(best[1])); team2.add(team1.get(best[2])); team1.removeAll(team2); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T04:06:56.757", "Id": "501314", "Score": "2", "body": "Just for what it's worth, this is known as \"The partition problem\", and it's well known as being NP-hard. For most reasonable cases (which, I believe, should include anything that fits in a fixed-width type on a computer) you can solve it with dynamic programming in something like polynomial time. You can solve it as a variant of the subset sum problem by summing all the numbers, dividing by two, and then finding the subset closest to that. I posted a dynamic programming implementation of subset sum on SO some time ago. https://stackoverflow.com/a/10579245/179910, in case you care." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T01:03:22.710", "Id": "254199", "Score": "3", "Tags": [ "java", "array" ], "Title": "Split an even length array in two such that each sub-arrays sum is as close as possible" }
254199
<p>I have a PHP script that uploads an image file, checks it for size, extension, and type. It then converts it to png, saves it to a folder outside the web root with a randomly generated name, then moves it to a specific folder inside the web root with a new filename that matches the user's username. By default, users have a generic profile image, but if they use the script to change their picture the database is updated to reflect the new filename. So far it's working without any obvious problems, but I would just like to have the script reviewed for possible issues. Also, what changes should be made to make it more secure?</p> <pre><code> &lt;div class=&quot;formSection&quot;&gt; &lt;?php if(isset($_FILES[&quot;image&quot;][&quot;name&quot;])) { $imageFile = ($_FILES[&quot;image&quot;][&quot;name&quot;]); $imageType = ($_FILES[&quot;image&quot;][&quot;type&quot;]); $imageSize = ($_FILES[&quot;image&quot;][&quot;size&quot;]); $validext = array(&quot;jpeg&quot;,&quot;jpg&quot;,&quot;gif&quot;,&quot;png&quot;); $fileExt = pathinfo($imageFile, PATHINFO_EXTENSION); $fileExt = strtolower($fileExt); $imageErrors = array(); if($_FILES[&quot;image&quot;][&quot;size&quot;] &gt; 1048576) { $imageErrors[] = &quot;&lt;strong&gt;ERROR!&lt;/strong&gt; File size was too large! It must be under 1MB.&quot;; } if((($imageType == &quot;image/jpeg&quot;) || ($imageType == &quot;image/jpg&quot;) || ($imageType == &quot;image/gif&quot;) || ($imageType == &quot;image/png&quot;)) &amp;&amp; in_array($fileExt, $validext)) { }else{ $imageErrors[] = &quot;&lt;strong&gt;ERROR!&lt;/strong&gt; Not an image file! Only jpg, gif, and png allowed.&quot;; } if($_FILES[&quot;image&quot;][&quot;error&quot;]) { $imageErrors[] = &quot;&lt;strong&gt;ERROR!&lt;/strong&gt; Looks like there was an error. &quot; . $_FILES[&quot;image&quot;][&quot;error&quot;]; } if(empty($imageErrors)) { if(exif_imagetype($_FILES['image']['tmp_name']) == IMAGETYPE_GIF) { $newpng = 'gifto.png'; $png = imagepng(imagecreatefromgif($_FILES['image']['tmp_name']), $newpng); } elseif(exif_imagetype($_FILES['image']['tmp_name']) == IMAGETYPE_JPEG) { $newpng = 'jpgto.png'; $png = imagepng(imagecreatefromjpeg($_FILES['image']['tmp_name']), $newpng); } elseif(exif_imagetype($_FILES['image']['tmp_name']) == IMAGETYPE_PNG) { $newpng = '.png'; $png = imagepng(imagecreatefrompng($_FILES['image']['tmp_name']), $newpng); } $temporaryPath = &quot;../../images/&quot; . uniqid() . $newpng; $sourcePath = $_FILES[&quot;image&quot;][&quot;tmp_name&quot;]; move_uploaded_file($sourcePath, $temporaryPath); $profilePictureMessage = ' &lt;div class=&quot;alert alert-success&quot;&gt; &lt;strong&gt;SUCCESS!&lt;/strong&gt; Image file uploaded! &lt;/div&gt;' . chr(13) . chr(10); $finalPath = &quot;images/profilePictures/&quot; . $username . $newpng; rename($temporaryPath, $finalPath); $query = $con-&gt;prepare(&quot;UPDATE users SET profilePic = :profilePic WHERE username=:un&quot;); $query-&gt;bindParam(&quot;:profilePic&quot;, $finalPath); $query-&gt;bindParam(&quot;:un&quot;, $username); $query-&gt;execute(); unlink($newpng); }else{ foreach($imageErrors as $imageError) { $profilePictureMessage = ' &lt;div class=&quot;alert alert-danger&quot;&gt;' .$imageError. '&lt;/div&gt;' . chr(13) . chr(10); } } } ?&gt; &lt;div class=&quot;message&quot;&gt; &lt;?php echo $profilePictureMessage; ?&gt; &lt;/div&gt; &lt;form action=&quot;settings.php&quot; method=&quot;POST&quot; enctype=&quot;multipart/form-data&quot;&gt; &lt;span class=&quot;title&quot;&gt;Change profile picture&lt;/span&gt; &lt;div class=&quot;form-group&quot;&gt; &lt;input type=&quot;file&quot; class=&quot;form-control-file&quot; name=&quot;image&quot; accept=&quot;image/png, image/gif, image/jpeg&quot;&gt; &lt;/div&gt; &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot; name=&quot;saveProfilePictureButton&quot;&gt;Save&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; </code></pre> <p>I welcome any and all feedback, and thanks for your time.</p>
[]
[ { "body": "<p>The code is pretty secure, but it could use some cleanup.</p>\n<h2>Security</h2>\n<p>Regarding security, you are doing the right thing checking the file extension.</p>\n<p>Storing all images as png is a smart move, that should, in theory, prevent uploading PHP code inside files, as it <a href=\"https://github.com/dlegs/php-jpeg-injector\" rel=\"nofollow noreferrer\">can be done with jpg</a>. But I wouldn't be so sure - sooner or later there will be found a way to keep the PHP code during this transformation too. I wouldn't call it much a problem though, as long as you don't have these files executed, through a web-server of via <code>include</code>. But to be completely 100% sure, consider having a different web server for the images, either your own or a DSN.</p>\n<h2>Code structure</h2>\n<p>The biggest flaw i see in this code so far is somewhat surprising. It's its place inside HTML. But in fact, it shouldn't have such a place. Any PHP data processing should be done <em>before</em> starting any output.</p>\n<p>Moreover, when you process an HTML form, a successful processing should lead to <strong>HTTP redirect</strong>, which means there must be no HTML before form processing at all.</p>\n<h2>Storing the path</h2>\n<p>Do you really need it? given it's always constant and can be recreated from the user info, why bother storing the image path at all?</p>\n<p>What you should really do is <strong>always</strong> use the row id instead of some other information to address a row in the database. Yes, I mean the username. Everywhere where you are using the username to identify a user, it should be the id.</p>\n<h2>Testing</h2>\n<p>Regarding the code, first of all I would like to give you a simple but often overlooked advise.</p>\n<blockquote>\n<p>So far it's working without any obvious problems</p>\n</blockquote>\n<p>Most people consider such a statement after testing only the good scenarios. But the real testing actually begins when you test for the bad scenarios. Hence you should really test not only with good images but with bad uploads as well.</p>\n<p>From this point of view I would say that testing <code>$_FILES[&quot;image&quot;][&quot;error&quot;]</code> should go first and prevent all other code from the execution as it will produce many unnecessary errors.</p>\n<p>The same notion goes for the error echoed out. <code>$_FILES[&quot;image&quot;][&quot;error&quot;]</code> is actually just a <em>number</em> and could be of some use only for a sophisticated PHP dev but not for a casual site visitor. Verbal error explanations can be found in the PHP manual so consider translating at least some errors for the user.</p>\n<h2>Code repetiton</h2>\n<p>I don't see much point in getting and testing the <code>$imageType</code> - don't you have the same test later on? just add an <code>else</code> condition to your exif_imagetype test.</p>\n<p>There is also a lot of repetition inside this condition as well. I would rather create an array with function names and then just call it.</p>\n<p>I also don't see much point in moving files around. Why not to create a file in one go?</p>\n<h2>Minor inconsistencies</h2>\n<p>they are minor but a good looking code shouldn't have it anyway</p>\n<ul>\n<li>there is no use for braces when you assign a variable like this (<code>$imageFile = $_FILES[&quot;image&quot;][&quot;name&quot;];</code>)</li>\n<li>for some reason you assign every <code>$_FILES</code> array member to a distinct variable but <code>tmp_file</code>. Why such a discrimination?</li>\n<li>Avoid &quot;magic numbers&quot;. Every hardcoded value should really go into config section, so it could be easily changed in the future or assigned from some configuration setting. This is related to the max upload size and the input name</li>\n<li>HTML formatting inside error messages is actually not a minor issue but a serious design flaw. Add every decoration at the output time.</li>\n<li>inconsistent use of nested functions. <code>imagecreatefromjpeg</code> is nested but <code>strtolower</code> is not. why?</li>\n<li><code>if</code> with empty body is <em>silly</em>. Add a negation operator instead.</li>\n<li>you can safely write <code>chr(13) . chr(10)</code> as just <code>&quot;\\n&quot;</code></li>\n</ul>\n<h2>The code</h2>\n<p>could be something like this</p>\n<pre><code>if (isset($_FILES[&quot;image&quot;][&quot;name&quot;])) {\n $inputName = &quot;image&quot;;\n $imageFile = $_FILES[$inputName][&quot;name&quot;];\n $imageTmp = $_FILES[$inputName][&quot;tmp_name&quot;];\n $imageSize = $_FILES[$inputName][&quot;size&quot;];\n $imageType = exif_imagetype($imageTmp);\n $fileExt = strtolower(pathinfo($imageFile, PATHINFO_EXTENSION));\n $validext = array(&quot;jpeg&quot;, &quot;jpg&quot;, &quot;gif&quot;, &quot;png&quot;);\n $maxFileSize = 1024*1024;\n $finalPath = &quot;images/profilePictures/$userid.png&quot;;\n $functoions = [\n IMAGETYPE_GIF =&gt; 'imagecreatefromgif',\n IMAGETYPE_JPEG =&gt; 'imagecreatefromjpeg',\n IMAGETYPE_PNG =&gt; 'imagecreatefrompng',\n ];\n\n if ($_FILES[&quot;image&quot;][&quot;error&quot;]) {\n $imageError = translate_file_error($_FILES[&quot;image&quot;][&quot;error&quot;]);\n }elseif ($_FILES[&quot;image&quot;][&quot;size&quot;] &gt; 1048576) {\n $imageError = &quot;File size is too large! It must be under 1MB.&quot;;\n } elseif (!in_array($fileExt, $validext) || !isset($functoions[$imageType])) {\n $imageError = &quot;Not an image file! Only jpg, gif, and png allowed.&quot;;\n } else {\n imagepng($functoions[$imageType]($imageTmp), $finalPath);\n header(&quot;Location: &quot;.$_SERVER['REQUEST_URI']);\n exit;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T07:32:03.383", "Id": "254210", "ParentId": "254203", "Score": "3" } }, { "body": "<ul>\n<li><p>Try to keep your processing code separated from your markup printing code. When you mix the two together and obey proper code tabbing, you end up with lots of tabbing which causes &quot;arrowhead code&quot; and excessive line width (horizontal scrolling isn't fun).</p>\n</li>\n<li><p>Please read all of the <a href=\"https://www.php-fig.org/psr/psr-12/#51-if-elseif-else\" rel=\"nofollow noreferrer\">PSR-12 Coding Standards</a> -- especially about control structures. This will help you to write consistent and professional scripts.</p>\n</li>\n<li><p><code>$imageFile</code>, <code>$imageType</code>, and <code>$imageSize</code> don't need their values to be wrapped in parentheses.</p>\n</li>\n<li><p>I think you should unconditionally declare a <code>$validImageTypes</code> array which can be used to validate submissions and to populate the <code>accept</code> attribute in your form.</p>\n</li>\n<li><p>Your two-point image type check should not have an empty <code>if</code> branch and it should not have so many piped conditions -- there should be just two <code>in_array()</code> calls.</p>\n<pre><code>if (!in_array($imageType, $validImageTypes) || !in_array($fileExt, $validext)) {\n $imageErrors[] = &quot;&lt;strong&gt;ERROR!&lt;/strong&gt; Not an image file! Only jpg, gif, and png allowed.&quot;;\n}\n</code></pre>\n</li>\n<li><p>You are making repeated calls of <code>exif_imagetype($_FILES['image']['tmp_name'])</code>, but it would be better to use a <code>switch</code> to avoid redundant calls.</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T07:33:48.800", "Id": "254211", "ParentId": "254203", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T02:38:38.113", "Id": "254203", "Score": "3", "Tags": [ "php" ], "Title": "PHP Image Upload and Validation" }
254203
<p>I made a program that will take in a time and a weekday, and return which parts of the world are at times closest to the one specified. Part of the program focuses on extracting a date and country out of a user input.</p> <p>Here are some example inputs and outputs:</p> <pre><code>&quot;In what part of the world is it 4:00 PM Friday right now?&quot; (datetime.datetime(2021, 1, 1, 16, 0), 'World') &quot;Where in America is it 6:40 AM Thu?&quot; (datetime.datetime(2020, 12, 31, 6, 40), 'America') &quot;It is 10:30 pm fri in which part of Asia?&quot; (datetime.datetime(2021, 1, 1, 22, 30), 'Asia') &quot;Where would the time be 10:10 AM Sat?&quot; (datetime.datetime(2021, 1, 2, 10, 10), 'World') &quot;Which state of brazil has the time 8:30 AM Saturday now?&quot; (datetime.datetime(2021, 1, 2, 8, 30), 'Brazil') </code></pre> <p>The reason that the only part of the date that needs to be given is the weekday, is because the maximum possible days in difference between a timezone and the timezone the user is currently at is one day, either ahead or behind.</p> <p>So the program checks if the weekday given is at the current day, one day before the current day, or one day after the current day, and can return the rest of the date.</p> <p>Here is my code:</p> <pre><code>import pytz from datetime import datetime, timedelta import re def return_words(string): return re.findall(r'\b\S+\b', string.lower()) def string_to_datetime(string): weekdays = [&quot;sunday&quot;, &quot;monday&quot;, &quot;tuesday&quot;, &quot;wednesday&quot;, &quot;thursday&quot;, &quot;friday&quot;, &quot;saturday&quot;] string = string.lower() words = sorted(return_words(string), key=len)[::-1] countries = [t.split(&quot;/&quot;)[0] for t in pytz.all_timezones] for word in words: in_day = [weekday for weekday in weekdays if word in weekday] if len(in_day) == 1: # Make sure that the word found is a weekday name, not just something like &quot;day&quot; weekday = in_day[0] break else: return for word in words: if word.title() in countries: country = word.title() break else: country = &quot;World&quot; # If no country name found, use &quot;World&quot; date = datetime.now() one_day = timedelta(days=1) if (datetime.now() + one_day).strftime(&quot;%A&quot;).lower() == weekday: date += one_day elif (datetime.now() - one_day).strftime(&quot;%A&quot;).lower() == weekday: date -= one_day elif datetime.now().strftime(&quot;%A&quot;).lower() != weekday: return year, month, day = date.year, date.month, date.day hours_minutes = re.findall(&quot;\d+\:\d+&quot;, string)[0] half = re.findall(f&quot;(?&lt;={hours_minutes}).{{0,3}}[ap]m&quot;, string) # Play it safe, and only extract the am or pm that is at most 3 steps away from the hours:minutes if half: # If found an am or pm half = half[0].strip() else: # If not found when playing it safe, resort to finding any am or pm in the string half = re.findall(&quot;[ap]m&quot;, string)[0].strip() string = f&quot;{year} {month} {day} {hours_minutes} {half}&quot; try: return datetime.strptime(string, &quot;%Y %m %d %I:%M %p&quot;), country except ValueError: return while True: print(string_to_datetime(input(&quot;Input your string &gt;&gt;&gt; &quot;))) </code></pre> <p><strong>Can you show me how to improve the efficiency of my code?</strong> Also, any tips on tidying up would be of big help.</p>
[]
[ { "body": "<pre><code> in_day = [weekday for weekday in weekdays if word in weekday]\n if len(in_day) == 1:\n</code></pre>\n<p>seems odd. You make the entire list, put it in memory, take its length and then throw it away. Consider instead</p>\n<pre><code>n_matching = sum(1 for weekday in weekdays if word in weekday)\nif n_matching == 1:\n</code></pre>\n<p>This loop:</p>\n<pre><code>for word in words:\n in_day = [weekday for weekday in weekdays if word in weekday]\n if len(in_day) == 1: # Make sure that the word found is a weekday name, not just something like &quot;day&quot;\n weekday = in_day[0]\n break\n</code></pre>\n<p>can be simplified if you use set operations; <code>lower</code> everything in <code>words</code> before this:</p>\n<pre><code>countries = {t.split(&quot;/&quot;, 1)[0].lower() for t in pytz.all_timezones}\ntry:\n country = next(iter(countries &amp; set(words))).title()\nexcept StopIteration:\n country = &quot;World&quot; # If no country name found, use &quot;World&quot;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T05:19:50.820", "Id": "254207", "ParentId": "254206", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T04:06:11.507", "Id": "254206", "Score": "2", "Tags": [ "python", "performance", "strings", "datetime", "converting" ], "Title": "Input any time, output timezones that are currently that time" }
254206
<p>Next: <a href="https://codereview.stackexchange.com/q/254260/188857">Advent of Code 2020 - Day 2: validating passwords</a></p> <h1>Problem statement</h1> <p>I decided to take a shot at <a href="https://adventofcode.com/2020" rel="nofollow noreferrer">Advent of Code 2020</a> to exercise my Rust knowledge. Here's the task for Day 1:</p> <blockquote> <h2>Day 1: Report Repair</h2> <p>[...]</p> <p>Specifically, they need you to <strong>find the two entries that sum to 2020 and then multiply those two numbers together</strong>.</p> <p>For example, suppose your expense report contained the following:</p> <pre><code>1721 979 366 299 675 1456 </code></pre> <p>In this list, the two entries that sum to 2020 are 1721 and 299. Multiplying them together produces 1721 * 299 = 514579, so the correct answer is 514579.</p> <p>[...]</p> <h3>Part Two</h3> <p>[...] They offer you a second one if you can <strong>find three numbers in your expense report that meet the same criteria</strong>.</p> <p>Using the above example again, the three entries that sum to 2020 are 979, 366, and 675. Multiplying them together produces the answer, 241861950.</p> </blockquote> <p>The full story can be found on the <a href="https://adventofcode.com/2020/day/1" rel="nofollow noreferrer">website</a>.</p> <h1>My solution</h1> <p><strong>src/day_1.rs</strong></p> <pre class="lang-rust prettyprint-override"><code>use {anyhow::Result, std::io::prelude::*}; pub type Number = u64; pub fn parse_data&lt;R: BufRead&gt;(reader: R) -&gt; Result&lt;Vec&lt;Number&gt;&gt; { reader.lines().map(|line| Ok(line?.parse()?)).collect() } // Finds a pair of numbers in `data` that add up to `sum` pub fn find_pair(mut data: Vec&lt;Number&gt;, sum: Number) -&gt; Option&lt;(Number, Number)&gt; { data.sort_unstable(); find_pair_in_sorted(&amp;data, sum) } // Finds a triple of numbers in `data` that add up to `sum`. pub fn find_triple(mut data: Vec&lt;Number&gt;, sum: Number) -&gt; Option&lt;(Number, Number, Number)&gt; { data.sort_unstable(); while let Some(number) = data.pop() { let sub_sum = match sum.checked_sub(number) { Some(sub_sum) =&gt; sub_sum, None =&gt; continue, }; if let Some((a, b)) = find_pair_in_sorted(&amp;data, sub_sum) { return Some((a, b, number)); } } None } // Finds a pair of numbers in `data` that add up to `sum` // by binary searching for `sum - n` for each number `n` in `data`. // `data` must be sorted in ascending order. pub fn find_pair_in_sorted(mut data: &amp;[Number], sum: Number) -&gt; Option&lt;(Number, Number)&gt; { while let Some((&amp;number, new_slice)) = data.split_last() { data = new_slice; let target = match sum.checked_sub(number) { Some(target) =&gt; target, None =&gt; continue, }; if data.binary_search(&amp;target).is_ok() { return Some((target, number)); } } None } </code></pre> <p><strong>src/bin/day_1_1.rs</strong></p> <pre class="lang-rust prettyprint-override"><code>use { anyhow::{anyhow, Result}, aoc_2020::day_1::{self as lib, Number}, std::{fs::File, io::BufReader}, }; const PATH: &amp;str = &quot;./data/day_1/input&quot;; const SUM: Number = 2020; fn main() -&gt; Result&lt;()&gt; { let file = BufReader::new(File::open(PATH)?); let data = lib::parse_data(file)?; let (a, b) = lib::find_pair(data, SUM) .ok_or_else(|| anyhow!(&quot;cannot find pair that adds up to {}&quot;, SUM))?; println!(&quot;{} * {} = {}&quot;, a, b, a * b); Ok(()) } </code></pre> <p><strong>src/bin/day_1_2.rs</strong></p> <pre class="lang-rust prettyprint-override"><code>use { anyhow::{anyhow, Result}, aoc_2020::day_1::{self as lib, Number}, std::{fs::File, io::BufReader}, }; const PATH: &amp;str = &quot;./data/day_1/input&quot;; const SUM: Number = 2020; fn main() -&gt; Result&lt;()&gt; { let file = BufReader::new(File::open(PATH)?); let data = lib::parse_data(file)?; let (a, b, c) = lib::find_triple(data, SUM) .ok_or_else(|| anyhow!(&quot;cannot find triple that adds up to {}&quot;, SUM))?; println!(&quot;{} * {} * {} = {}&quot;, a, b, c, a * b * c); Ok(()) } </code></pre> <p>Crates used: <a href="https://docs.rs/anyhow/1.0.37/anyhow/" rel="nofollow noreferrer"><code>anyhow</code> 1.0.37</a></p> <p><code>cargo fmt</code> and <code>cargo clippy</code> have been applied.</p>
[]
[ { "body": "<p>Your code is well done and shows familiarity with Rust.</p>\n<p>The best I can do is comment on some parts of the code and provide two small, concrete pieces of advice. There is very little room for improvement in the code.</p>\n<p>I see your <code>Vec</code>s in function parameters are well motivated. The one in <code>find_triple</code> is motivated by the need to do <code>pop</code>, and the one in <code>find_pair</code> just follows the other for consistency between parts of the task.</p>\n<p>The decision to introduce <code>Number</code> as a type alias is ok, and works and looks fine, but keep in mind that it adds an extra mental hop for the reader.</p>\n<h2>Return types</h2>\n<p>Acting by intuition I'd change the return types to have const-length arrays instead of tuples. This brings attention to the fact that the array/tuple is homogeneous. I would change:</p>\n<p><code>-&gt; Option&lt;(Number, Number, Number)&gt;</code> and <code>return Some((a, b, number));</code><br />\nto<br />\n<code>-&gt; Option&lt;[Number; 3]&gt;</code> and <code>return Some([a, b, number]);</code></p>\n<h2>Typo?</h2>\n<p>It's good to be correct and consistent in naming. The function name is <code>find_triple</code> - but 'triple' is not a noun, 'triple<strong>t</strong>' is.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-17T05:49:07.387", "Id": "502567", "Score": "0", "body": "The triple one is fun - MW lists both [triple](https://www.merriam-webster.com/dictionary/triple#h2) and [triplet](https://www.merriam-webster.com/dictionary/triplet#h1) as nouns. [Wikipedia](https://en.wikipedia.org/wiki/Tuple#Names_for_tuples_of_specific_lengths) lists triple as the \"name\" and triplet under alternative names. I actually thought triplet was only for music - seems they're both acceptable anyway." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-12T12:07:00.447", "Id": "254597", "ParentId": "254209", "Score": "1" } } ]
{ "AcceptedAnswerId": "254597", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T06:13:49.480", "Id": "254209", "Score": "0", "Tags": [ "algorithm", "programming-challenge", "rust" ], "Title": "Advent of Code 2020 - Day 1: finding 2 or 3 numbers that add up to 2020" }
254209
<p>As part of my training, I implemented a dataset class in C++ that allows me to create synthetic datasets to get more familiar with features that C++ offers such as object oriented programming.</p> <p>This implementation uses a simple method to create two intertwined spirals as shown in the following image.</p> <p><a href="https://i.stack.imgur.com/a5TKs.png" rel="noreferrer"><img src="https://i.stack.imgur.com/a5TKs.png" alt="enter image description here" /></a></p> <p>The output looks as follows:</p> <pre><code>x y label -3.85616 -0.987058 0 1.16 4.6764 0 2.66279 2.13692 1 -0.643551 3.81989 0 -0.252046 -0.888411 0 </code></pre> <p>Please be as hard as possible with this implementation and give me constructive feedback.</p> <p>I would appreciate advice especially in the following areas:</p> <ul> <li>Code style (readability, naming conventions, etc...)</li> <li>Class design</li> <li>Efficiency (how to avoid unnecessary complexity)</li> <li>Reinventing the wheel (does the STL offer functionality that I should use?)</li> </ul> <p><strong>main.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &quot;data.hpp&quot; int main() { unsigned int n_points = 3000; Data data (n_points); std::vector&lt;Point&gt; d; d = data.get(); for (std::vector&lt;Point&gt;::iterator it = d.begin(); it != d.end(); ++it) { std::cout &lt;&lt; it-&gt;x &lt;&lt; &quot; &quot; &lt;&lt; it-&gt;y &lt;&lt; &quot; &quot; &lt;&lt; it-&gt;label &lt;&lt; std::endl; } return 0; } </code></pre> <p><strong>data.hpp</strong></p> <pre><code>#ifndef DATA_H #define DATA_H #include &lt;vector&gt; #include &lt;cmath&gt; #include &quot;util.hpp&quot; class Data { public: Data (unsigned int); unsigned int n_samples; unsigned int n_dims = 2; unsigned int n_classes = 2; std::vector&lt;Point&gt; get(); private: Random random; std::vector&lt;Point&gt; data; std::vector&lt;Point&gt; generate_data(); }; Data::Data (unsigned int _n_samples) { n_samples = _n_samples; } std::vector&lt;Point&gt; Data::generate_data() { std::vector&lt;Point&gt; data(n_samples); std::vector&lt;Point&gt;::iterator it; double noise = 1.0; double spread = 4.0; for (it = data.begin(); it != data.end(); ++it) { double r = 3.14 * spread * random.rand(); double r1 = -cos(r) * r + noise * random.rand(); double r2 = sin(r) * r + noise * random.rand(); if (random.rand() &lt; 0.5) { it-&gt;x = r1; it-&gt;y = r2; it-&gt;label = 1; } else { it-&gt;x = -r1; it-&gt;y = -r2; it-&gt;label = 0; } } return data; } std::vector&lt;Point&gt; Data::get() { std::vector&lt;Point&gt; data(n_samples); std::vector&lt;Point&gt;::iterator it; data = generate_data(); return data; } #endif /* DATA_H */ </code></pre> <p><strong>util.hpp</strong></p> <pre><code>#ifndef UTIL_H #define UTIL_H #include &lt;cstdlib&gt; #include &lt;ctime&gt; struct Point { double x; double y; unsigned int label; }; class Random { public: Random (); double rand(); }; Random::Random () { std::srand(static_cast&lt;unsigned int&gt;(std::time(nullptr))); } double Random::rand() { return static_cast&lt;double&gt; (std::rand()) / static_cast&lt;double&gt; (RAND_MAX + 1U); } #endif /* UTIL_H */ </code></pre>
[]
[ { "body": "<p>This is a nice, readable piece of code. I would just highlight a few things you might want to consider.</p>\n<h2>Unnecessary Class</h2>\n<p>Let's take a close look at <code>Random</code> class. It holds no state, just a member function <code>rand</code>. In addition to having just one member function, it is only used in one place, in member function <code>generate_data</code>. Classes are meant to be reusable and <code>Random</code> does not serve that purpose. A common solution is to create a free function that randomly generate numbers and returns the output.\n<code>Prefer free-functions to member-functions</code>.</p>\n<h2>Readability Review</h2>\n<p>It is nice to spell out the iterator name fully but most times, <code>auto</code> keyword looks more readable. This means this code</p>\n<pre><code>for (std::vector&lt;Point&gt;::iterator it = d.begin(); it != d.end(); ++it) {\n std::cout &lt;&lt; it-&gt;x &lt;&lt; &quot; &quot; &lt;&lt; it-&gt;y &lt;&lt; &quot; &quot; &lt;&lt; it-&gt;label &lt;&lt; std::endl;\n}\n</code></pre>\n<p>can be rewritten as</p>\n<pre><code>for(const auto&amp; point : points)\n std::cout &lt;&lt; point &lt;&lt; '\\n'\n</code></pre>\n<p>NOTE: You have to define <code>std::cout</code> that takes your class as it's second argument.</p>\n<h2>Use good namings</h2>\n<p>There is much going on in <code>generate_data</code> and can get someone easily confused. avoid one letter variable as much as possible. Anyone reading your code without proper context on what <code>r</code> and <code>x</code> means would easily get confused. Your names should carry intent and they should explain what's going at first glance.</p>\n<h2>Nitpicks</h2>\n<ol>\n<li>This piece of code looks ugly</li>\n</ol>\n<pre><code>std::vector&lt;Point&gt; Data::generate_data() {\n std::vector&lt;Point&gt; data(n_samples); \n ....\n}\n</code></pre>\n<p>which data are we really assigning to <code>member-variable</code> data or <code>local-variable</code> data? In this case, we are creating a local-variable data. Avoid shadowing your member-variables.</p>\n<ol start=\"2\">\n<li>Prefer member-initialization to assignment. This piece of code</li>\n</ol>\n<pre><code>Data::Data (unsigned int _n_samples) { // initialized in member initialization list\n n_samples = _n_samples;\n}\n</code></pre>\n<p>creates and default initializes <code>n_samples</code> and also make the assignment. This could have been simply initialized at creation time. A proper way of doing that is as follow</p>\n<pre><code>Data::Data (unsigned int _n_samples) :\n n_samples{_n_samples}\n</code></pre>\n<ol start=\"3\">\n<li>Your naming convention are inconsistent, sometimes you prefix with <code>_</code> other times you don't. Choose a style and stick with it.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T10:13:01.963", "Id": "254215", "ParentId": "254212", "Score": "8" } }, { "body": "<p><strong>Design</strong>:</p>\n<p><code>Data</code> is not a descriptive name, and also misrepresents what the class does. It's really a generator function that's triggered by calling <code>get()</code>.</p>\n<p>As such, it would be better to replace it with a function, called something like <code>generate_spirals()</code>.</p>\n<p>We should use the C++ standard library <code>random</code> header for random number generation. This gives us various random number generators, e.g. <code>std::mt19937</code>, that we could use instead of the custom <code>Random</code> class.</p>\n<p>Lastly, I'd suggest doing the labelling and inversion as separate stages. So we instead generate two spirals using the same code, and invert one of them. That way we don't need the label in the point class, we can just store two separate vectors of <code>(x, y)</code> coordinates and add the label when printing them.</p>\n<hr />\n<p>So something like:</p>\n<pre><code>#include &lt;random&gt;\n#include &lt;vector&gt;\n#include &lt;cmath&gt;\n\nstruct Point {\n double x;\n double y;\n};\n\nstd::vector&lt;Point&gt; generate_spiral(unsigned int samples, double noise, double spread, std::mt19937&amp; rng) {\n \n auto points = std::vector&lt;Point&gt;();\n points.reserve(samples);\n \n auto dist = std::uniform_real_distribution&lt;double&gt;(0.0, 1.0);\n \n for (auto n = 0u; n != samples; ++n) {\n double r = 3.14 * spread * dist(rng);\n double x = -std::cos(r) * r + noise * dist(rng);\n double y = std::sin(r) * r + noise * dist(rng);\n points.push_back({ x, y });\n }\n \n return points;\n}\n\nstd::vector&lt;Point&gt; invert_points(std::vector&lt;Point&gt; points) {\n for (auto&amp; p : points) {\n p.x = -p.x;\n p.y = -p.y;\n }\n return points;\n}\n\n#include &lt;iostream&gt;\n\nint main() {\n \n auto rng = std::mt19937(std::random_device()());\n \n auto samples = 200u;\n auto noise = 1.0;\n auto spread = 4.0;\n auto s1 = generate_spiral(samples, noise, spread, rng);\n auto s2 = invert_points(generate_spiral(samples, noise, spread, rng));\n \n for (auto const&amp; p : s1)\n std::cout &lt;&lt; p.x &lt;&lt; &quot; &quot; &lt;&lt; p.y &lt;&lt; &quot; &quot; &lt;&lt; &quot;1&quot; &lt;&lt; &quot;\\n&quot;;\n \n for (auto const&amp; p : s2)\n std::cout &lt;&lt; p.x &lt;&lt; &quot; &quot; &lt;&lt; p.y &lt;&lt; &quot; &quot; &lt;&lt; &quot;0&quot; &lt;&lt; &quot;\\n&quot;;\n}\n</code></pre>\n<p>Note the range-based for loops using <code>auto</code> make the output code much less verbose.</p>\n<p>Note that <code>&lt;&lt; std::endl</code> flushes the output as well as adding a new line. Since we don't need the flushing behavior, we should use <code>&lt;&lt; &quot;\\n&quot;</code> instead.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T10:19:15.397", "Id": "254216", "ParentId": "254212", "Score": "5" } }, { "body": "<p>Here are some things that may help you improve your program.</p>\n<h2>Separate interface from implementation</h2>\n<p>The interface goes into a header file and the implementation (that is, everything that actually emits bytes including all functions and data) should be in a separate <code>.cpp</code> file. The reason is that you might have multiple source files including the <code>.h</code> file but only one instance of the corresponding <code>.cpp</code> file. In other words, split your existing <code>data.hpp</code> and <code>util.hpp</code> files into a <code>.h</code> file and a <code>.cpp</code> file.</p>\n<h2>Understand the use of namespaces</h2>\n<p>Your code is correctly using <code>&lt;cmath&gt;</code> instead of <code>&lt;math.h&gt;</code>. The difference between the two forms is that the former defines things within the <code>std::</code> namespace versus into the global namespace. So this implies that instead of using <code>cos</code> and <code>sin</code>, the code should be using <code>std::cos</code> and <code>std::sin</code></p>\n<h2>Use <code>const</code> where practical</h2>\n<p>There are a number of named constants in the program such as <code>unsigned int n_dims = 2;</code>. It's very good practice to name these, but even better is to declare them <code>const</code> or better still <code>constexpr</code>. The reason is that it allows the compiler to perform better optimizations without sacrificing readability.</p>\n<h2>Don't use <code>std::endl</code> if you don't really need it</h2>\n<p>The difference betweeen <code>std::endl</code> and <code>'\\n'</code> is that <code>'\\n'</code> just emits a newline character, while <code>std::endl</code> actually flushes the stream. This can be time-consuming in a program with a lot of I/O and is rarely actually needed. It's best to <em>only</em> use <code>std::endl</code> when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one. Avoiding the habit of using <code>std::endl</code> when <code>'\\n'</code> will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized.</p>\n<h2>Use &quot;range <code>for</code>&quot; and simplify your code</h2>\n<p>The code currently includes these lines:</p>\n<pre><code>for (std::vector&lt;Point&gt;::iterator it = d.begin(); it != d.end(); ++it) {\n std::cout &lt;&lt; it-&gt;x &lt;&lt; &quot; &quot; &lt;&lt; it-&gt;y &lt;&lt; &quot; &quot; &lt;&lt; it-&gt;label &lt;&lt; std::endl;\n}\n</code></pre>\n<p>Since C++11, however, we have a range <code>for</code> which simplifies it to this:</p>\n<pre><code>for (const auto&amp; point : d) {\n std::cout &lt;&lt; point.x &lt;&lt; &quot; &quot; &lt;&lt; point.y &lt;&lt; &quot; &quot; &lt;&lt; point.label &lt;&lt; '\\n';\n}\n</code></pre>\n<h2>Write a stream inserter for your class</h2>\n<p>We can further refine the <code>for</code> loop above by creating a custom inserter for the <code>Point</code> class:</p>\n<pre><code>std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const Point&amp; point) {\n return out &lt;&lt; point.x &lt;&lt; &quot; &quot; &lt;&lt; point.y &lt;&lt; &quot; &quot; &lt;&lt; point.label;\n}\n</code></pre>\n<p>Now our loop in main is even simpler:</p>\n<pre><code>for (const auto&amp; point : d) {\n std::cout &lt;&lt; point &lt;&lt; '\\n';\n}\n</code></pre>\n<h2>Use standard library algorithms</h2>\n<p>We can use <code>std::copy</code> to copy from the vector to <code>std::cout</code>, replacing the loop with a single statement:</p>\n<pre><code>std::copy(d.begin(), d.end(), std::ostream_iterator&lt;Point&gt;(std::cout, &quot;\\n&quot;));\n</code></pre>\n<h2>Consider using a better random number generator</h2>\n<p>If you are using a compiler that supports at least C++11, consider using a better random number generator. In particular, instead of <code>rand</code>, you might want to look at <a href=\"http://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution\" rel=\"noreferrer\"><code>std::uniform_real_distribution</code></a> and friends in the <code>&lt;random&gt;</code> header. Also, instead of doing this:</p>\n<pre><code>if (random.rand() &lt; 0.5) {\n it-&gt;x = r1;\n it-&gt;y = r2;\n it-&gt;label = 1;\n} else {\n it-&gt;x = -r1;\n it-&gt;y = -r2;\n it-&gt;label = 0;\n}\n</code></pre>\n<p>I would suggest using a <a href=\"https://en.cppreference.com/w/cpp/numeric/random/bernoulli_distribution\" rel=\"noreferrer\"><code>std::bernoulli_distribution</code></a>.</p>\n<h2>Rethink the classes</h2>\n<p>Rather than having the vaguely named <code>Data</code> class creating <code>Point</code>s, I'd suggest moving that functionality into the <code>Point</code> class. Since this is actually creating a <code>Point</code>, it makes sense to me to create a custom constructor with this functionality:</p>\n<pre><code>Point::Point() {\n static std::random_device rd;\n static std::mt19937 gen(rd());\n static std::uniform_real_distribution&lt;&gt; spread(0.0, 4.0*3.14);\n static std::uniform_real_distribution&lt;&gt; noise(0.0, 1.0);\n static std::bernoulli_distribution type(0.5);\n static constexpr double multiplier[]{-1.0, +1.0};\n\n label = type(gen);\n double r = spread(gen);\n x = multiplier[label] * (-std::cos(r) * r + noise(gen));\n y = multiplier[label] * (+std::sin(r) * r + noise(gen));\n}\n</code></pre>\n<h2>Minimize memory use</h2>\n<p>It's not critical for this program, but rather than storing everything in a <code>vector</code> only to print it and then destroy the vector, a more memory efficient approach would be to generate each point as needed and emit it directly. Using the <code>Point</code> constructor and stream inserter as defined above, this becomes trivial.</p>\n<h2>Result</h2>\n<p>Here's the entire program as rewritten with all of these ideas:</p>\n<pre><code>#include &lt;random&gt;\n#include &lt;iostream&gt;\n#include &lt;iterator&gt;\n#include &lt;cmath&gt;\n\nstruct Point {\n Point();\n double x;\n double y;\n unsigned int label;\n};\n\nPoint::Point() {\n static std::random_device rd;\n static std::mt19937 gen(rd());\n static std::uniform_real_distribution&lt;&gt; spread(0.0, 4.0*3.14);\n static std::uniform_real_distribution&lt;&gt; noise(0.0, 1.0);\n static std::bernoulli_distribution type(0.5);\n static constexpr double multiplier[]{-1.0, +1.0};\n\n label = type(gen);\n double r = spread(gen);\n x = multiplier[label] * (-std::cos(r) * r + noise(gen));\n y = multiplier[label] * (+std::sin(r) * r + noise(gen));\n}\n\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const Point&amp; point) {\n return out &lt;&lt; point.x &lt;&lt; &quot; &quot; &lt;&lt; point.y &lt;&lt; &quot; &quot; &lt;&lt; point.label;\n}\n\nint main() {\n for (auto i{3000}; i; --i) {\n std::cout &lt;&lt; Point() &lt;&lt; '\\n';\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T23:01:11.317", "Id": "501402", "Score": "0", "body": "Rather than `for (auto i{3000}; i; --i) ...`, you could end with `std::generate_n(std::ostream_iterator<Point>(std::cout, \"\\n\"), 3000, []{ return Point(); })'`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T23:04:16.593", "Id": "501403", "Score": "0", "body": "@Caleth: True, and I considered it but opted for the simpler version shown." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-03T18:17:33.280", "Id": "501459", "Score": "0", "body": "You are seeding the pseudorandom number generator with a single `unsigned int` from the random device. The state size of `std::mt19937` is 19937 bits, so it is unlikely (although technically permitted by the standard) that a single `unsigned int` will be enough: it will work but will only allow access to a tiny subset of the possible initial states. It would be better to use a `std::seed_seq` instead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-03T18:22:47.153", "Id": "501460", "Score": "0", "body": "@antispinwards: you're right that the current seed is not very good. However, I'm not sure how to do better, even with `std::seed_seq`. See [this](https://www.pcg-random.org/posts/cpp-seeding-surprises.html) for example. Ideas on how to better address this would be most welcome!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-04T09:19:04.987", "Id": "501509", "Score": "0", "body": "@Edward - yes, `std::seed_seq` is less than ideal (barring the C++ folks having a fit of sanity and bugfixing it in a way that doing the correct thing with sufficient data is given priority over doing *something* with insufficient data), but that doesn't mean we should just throw up our hands and seed the generator in a way that can provide *at most* 2^32 possibilities (for common definitions of `unsigned int`) out of 2^19937. 2^32 isn't a particularly large number these days for this kind of thing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-04T12:45:25.673", "Id": "501514", "Score": "0", "body": "@antispinwards Please show me what you would write." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-04T18:14:57.330", "Id": "501535", "Score": "0", "body": "@Edward - it's a bit too long for comments, so I added it as a separate answer. Feel free to merge it into yours if you agree with it and I will delete my answer (which is more of a response to your answer than to the original question)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-04T18:19:06.853", "Id": "501538", "Score": "0", "body": "@antispinwards: I think your separate answer is valuable enough to stand on its own. Thanks very much for taking the time to teach me something!" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T12:47:05.190", "Id": "254218", "ParentId": "254212", "Score": "17" } }, { "body": "<h2>Perspective</h2>\n<p>The answers that were already provided are great for solving the particular problem you have. I will provide feedback based on my current workflow. I implement a tool for those who would like to make quick C++ prototypes without much regard to engineering, which I then fix and make more of a complete solution.</p>\n<h2>Underlying problem</h2>\n<p>What you want to do is a <em>language</em> to describe relation of random variables. The rest is about loops and choosing distributions, sources of random variables, etc. Embedded languages in C++ are written either using macros or expression templates. Since we don't need any source level modifications, lets stick with the latter.</p>\n<h2>The moving parts</h2>\n<p>There are already many libraries for random number generation. Some do not like standard C++ facilities for that, but might have desirable properties not provided by standard facilities (for example curand has GPU support, which is very useful in case you need to generate a lot of data). We need a way to latch onto existing libraries. The most feasible way in my opinion is to provide CRTP classes that will add the layer we need:</p>\n<ul>\n<li><p>Providing distribution support</p>\n</li>\n<li><p>Strict typing</p>\n</li>\n<li><p>Container filling (<code>std::ranges</code>, iterators)</p>\n</li>\n</ul>\n<p>Rough sketch of it would look like this:</p>\n<pre><code>template &lt;typename RandomSource, typename Distribution&gt;\nclass independent_distributed_variable {\n Distribution distribution;\npublic:\n template &lt;typename ... Args&gt;\n random_variable(Args&amp;&amp; ... args):\n distribution(std::forward&lt;Args&gt;(args)...)\n {}\n\n auto operator()() {\n auto&amp; source = static_cast&lt;RandomSource&amp;&gt;(*this);\n return distribution(source);\n }\n\n template &lt;typename OutputIterator&gt;\n void operator()(OutputIterator first, OutputIterator) {\n // use `std::generate` and delegate to singular version\n // or use batch filling \n }\n};\n</code></pre>\n<p>One might still have to write some wrapper classes (in case interfaces are not compatible). This is not the most important problem though.</p>\n<h2>The random variable description language</h2>\n<p>This is the most &quot;C++&quot; part of the problem. Lets nail down the usage first. The random variables in your case:</p>\n<p><span class=\"math-container\">\\$R \\sim N(0.5, 0.15)\\$</span></p>\n<p><span class=\"math-container\">\\$label\\ \\sim B(1, 0.5)\\$</span></p>\n<p><span class=\"math-container\">\\$X \\sim (-\\cos (4 * \\pi * R) + R) * (-1)^{label}\\$</span></p>\n<p><span class=\"math-container\">\\$Y \\sim (\\sin (4 * \\pi * R) + R) * (-1)^{label}\\$</span></p>\n<p>(Sorry if I butchered the terminology and notation, just wanted to write it down in a more readable way)</p>\n<p>The closest approximation in C++ would be (given the library namespace <code>shino</code>):</p>\n<pre><code>auto r = shino::normal_distribution(0.5, 0.15);\nauto label = shino::bernoulli_distribution(0.5);\nauto x = (-shino::cos(4 * shino::pi * r) + r) * shino::power(-1, label);\nauto y = (shino::sin(4 * shino::pi * r) + r) * shino::power(-1, label);\n</code></pre>\n<p>Then people could just fill their own struct with a loop or <code>std::generate</code> if they want. I will give motivations later on leaving this part open ended.</p>\n<h2>Implementation guidelines</h2>\n<p>The naive implementation is pretty easy. Lets consider sine expression.</p>\n<pre><code>template &lt;typename AlphaVariable&gt;\nclass sine_expression {\n AlphaVariable alpha;\npublic:\n sine_expression(AlphaVariable alpha):\n alpha(alpha)\n {}\n\n auto operator()() {\n return std::sin(alpha()); // evaluate the dependency first\n }\n};\n\ntemplate &lt;typename AlphaVariable&gt;\nsine_expression&lt;AlphaVariable&gt; sin(AlphaVariable alpha) {\n return {alpha};\n}\n</code></pre>\n<p>There is one problem that springs out: the implementer will need to differentiate between temporary expressions and expressions saved into a variable (<code>sin(x + y)</code> vs just <code>sin(x)</code>, the former will have temporary <code>plus_expression</code>, the latter will have lvalue of whatever type is <code>x</code>). The problem is definitely solvable, albeit requiring more code.</p>\n<h2>Importance of user provided data structures</h2>\n<p>In computer vision field, most trained models I encountered want tightly packed image pixels (e.g. 3 channel image of float channels will have pixels at addresses multiple of 12, not 16). By default compiler will pad the struct of 3 floats to 16 bytes, which will break the inference. As such there is sometimes a need to fill weird structs and write at unusual memory offsets.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T19:39:58.043", "Id": "501377", "Score": "0", "body": "There is also an edge case: `r` is \"rolled\" each time per usage, while `label` is not. I will try to fix that tomorrow and amend my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-03T00:03:02.443", "Id": "501407", "Score": "0", "body": "I like this approach. I had also wondered about using C++20 range adapters." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-03T23:10:46.423", "Id": "501485", "Score": "1", "body": "what's \"shino\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-05T14:50:26.180", "Id": "501585", "Score": "0", "body": "@NooneAtAll, it is the character in my avatar. I usually either call my library namespaces with strongly related words or with the nickname I like." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T19:33:20.093", "Id": "254234", "ParentId": "254212", "Score": "6" } }, { "body": "<p>This is more an amendment to Edward's answer, but it's a bit too long to do in comments.</p>\n<p>In order to seed the pseudorandom number generator (PRNG), you should provide sufficient data to initialise the PRNG state.</p>\n<p>The common (and I would argue obvious) approach of</p>\n<pre><code>std::random_device rd;\nstd::mt19937 gen(rd());\n</code></pre>\n<p>would be nice if it worked but this is C++ where the obvious way of doing things is often wrong. The reason this is insufficient is that <code>operator()</code> on <code>std::random_device</code> returns an <code>unsigned int</code>, which is permitted to be as small as 16 bits (but will probably be 32 bits on common systems). Meanwhile, the <code>std::mt19937</code> PRNG has an internal state of 19937 bits, which suggests the above approach provides much too little data.</p>\n<p>The approach the standard library takes is to use <code>std::seed_seq</code>, which takes a sequence of numbers, combining the lower 32 bits of each. In order to provide this, we can use a vector:</p>\n<pre><code>std::vector&lt;std::uint_least32_t&gt; seed_data;\n</code></pre>\n<p>We also need to get <code>std::uint_least32_t</code> out of the random device that supplies <code>unsigned int</code> (which might be only 16 bits), so we use a uniform distribution:</p>\n<pre><code>std::uniform_int_distribution&lt;std::uint_least32_t&gt; rd_dist;\n</code></pre>\n<p>As an aside: this will provide a distribution over the whole range of <code>std::uint_least32_t</code>: if you're worried about &quot;wasting entropy&quot; on a hypothetical system where this type is wider than 32 bits you could explicitly specify the range and hope that the provided implementation takes advantage of this to pull less data from the <code>std::random_device</code>:</p>\n<pre><code>std::uniform_int_distribution&lt;std::uint_least32_t&gt; rd_dist{ 0, UINT32_C(0xffffffff) };\n</code></pre>\n<p>The above is almost certainly unnecessary though.</p>\n<p>The amount of data we need to fill this vector can be determined from properties on the <code>std::mt19937</code> type. Unfortunately C++ does not directly provide a property that gets this directly, but it can be computed as follows:</p>\n<pre><code>constexpr std::size_t seed_size = std::mt19937::state_size * (std::mt19937::word_size / 32);\n</code></pre>\n<p>If you decide to replace <code>std::mt19937</code> with <code>std::mt19937_64</code> or another instantiation of the <code>std::mersenne_twister_engine</code> template, just replace the <code>std::mt19937</code> in the above line and it should still work.</p>\n<p>So we then fill the vector:</p>\n<pre><code>seed_data.reserve(seed_size);\nstd::generate_n(std::back_inserter(seed_data), seed_size, [&amp;]() { return rd_dist(rd); });\n</code></pre>\n<p>Then create the seed sequence and create the generator:</p>\n<pre><code>std::seed_seq seed(seed_data.cbegin(), seed_data.cend());\nstd::mt19937 gen{ seed };\n</code></pre>\n<p>Putting that all together:</p>\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;cstddef&gt;\n#include &lt;cstdint&gt;\n#include &lt;iterator&gt;\n#include &lt;random&gt;\n#include &lt;vector&gt;\n\n/* ... */\n\nstd::random_device rd;\nstd::uniform_int_distribution&lt;std::uint_least32_t&gt; rd_dist;\nstd::vector&lt;std::uint_least32_t&gt; seed_data;\nconstexpr std::size_t seed_size = std::mt19937::state_size * (std::mt19937::word_size / 32);\nseed_data.reserve(seed_size);\nstd::generate_n(std::back_inserter(seed_data), seed_size, [&amp;]() { return rd_dist(rd); });\nstd::seed_seq(seed_data.cbegin(), seed_data.cend());\nstd::mt19937 gen{ seed_seq };\n</code></pre>\n<p>I'm sure most people would agree that's a perfectly succinct and obvious way to initialise a PRNG. </p>\n<p>As noted by Edward in the comments to their answer, this is still not ideal due to <a href=\"https://www.pcg-random.org/posts/cpp-seeding-surprises.html\" rel=\"nofollow noreferrer\">issues in the way <code>std::seed_seq</code> combines its values</a>, and the fact that in their wisdom the C++ folks decided that it was perfectly ok to have <code>std::random_device</code> be deterministic (rather than, say, being a compile error on systems that don't provide a sufficient source of entropy, which would alert the programmers to the issue early on rather than being a potential source of runtime bugs).</p>\n<p>Nevertheless, the general principle you should follow is to provide sufficient entropy to match the state of the PRNG, rather than just a single <code>unsigned int</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-04T18:17:56.903", "Id": "501537", "Score": "1", "body": "This is a valuable contribution. I am going to see about basing a question on this in the next few days. Thanks very much for taking the time to write it up!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-04T18:11:42.753", "Id": "254319", "ParentId": "254212", "Score": "3" } } ]
{ "AcceptedAnswerId": "254218", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T07:39:55.887", "Id": "254212", "Score": "12", "Tags": [ "c++", "beginner", "c++11" ], "Title": "Simple dataset class in C++" }
254212
<p>This code is a revised version of implementation which asked for an improvement. Original question is asked here: <a href="https://codereview.stackexchange.com/questions/253891/remove-kth-last-element-from-singly-linked-list">remove kth last element from singly-linked list</a></p> <p><em>credits to: Toby, Andreas, Arkadiusz</em></p> <p>What has changed:</p> <ol> <li>remove length from <code>xllist</code> struct</li> <li>check if k is bigger than list length on the fly</li> </ol> <p><strong>Code:</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdbool.h&gt; #include &lt;stdint.h&gt; typedef struct llnode { int value; struct llnode *next; } llnode; typedef struct xllist { llnode * head; llnode * tail; } xllist; bool create_node(xllist *list, int value) { llnode *node = malloc(sizeof *node); if(!node) { return false; } node-&gt;value = value; node-&gt;next = NULL; if(!list-&gt;head) { list-&gt;head = node; list-&gt;tail = node; } list-&gt;tail-&gt;next = node; list-&gt;tail = node; return true; } bool del_element_from_last(xllist *llist, int k) { //window with 2 pointers, length of k //prev is the prev node to the window llnode *prev; llnode *last; int len; //list length if(llist-&gt;head) { last = llist-&gt;head; prev = llist-&gt;head; len = 1; } for(; last; last=last-&gt;next) { len++; if(len &gt; k+1) prev = prev-&gt;next; } if(len &lt; k) //len is smaller than k { return false; } if(len == k) //means del 1st element from the list { llist-&gt;head = llist-&gt;head-&gt;next; } //remove first node of the window printf(&quot;deleted element:%d \n&quot;, prev-&gt;next-&gt;value); prev-&gt;next = prev-&gt;next-&gt;next; return true; } int main(void) { xllist llist = {NULL, NULL}; for(int i=0; i&lt;100; i++) { if(!create_node(&amp;llist, 100+i)) printf(&quot;create fail\n&quot;); } del_element_from_last(&amp;llist, 15); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T12:39:02.677", "Id": "501343", "Score": "1", "body": "`if(!list->head) { ... list->tail = node; } list->tail->next = node;` is questionable. After the first `create_node()`, should `list->tail->next` be `NULL`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T14:19:39.353", "Id": "501345", "Score": "0", "body": "Yes, that looks like it should be `(list->head ? list->tail->next : list->head) = node; list->tail = node;`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-11T09:13:01.143", "Id": "501996", "Score": "0", "body": "@chux-ReinstateMonica good catch. Thank you." } ]
[ { "body": "<p>In the function <code>del_element_from_last</code>, when removing the first element of the list, you update <code>llist-&gt;head</code>. However, when removing the last element of the list, you do not update <code>llist-&gt;tail</code>.</p>\n<p>If keeping track of the tail of the list is only intended for building the list, and is not intended to be updated by the function <code>del_element_from_last</code>, then you should not pass the entire <code>struct xllist</code> to the function <code>del_element_from_last</code>. Rather, you should change the function signature to the following, so that the function only has access to the head:</p>\n<p><code>bool del_element_from_last( xlnode **pp_head, int k )</code></p>\n<hr />\n<p>According to the task description, <code>k</code> is guaranteed to be smaller than the list. This means that the list is guaranteed to be not empty. In that case, the line</p>\n<p><code>if(llist-&gt;head)</code></p>\n<p>in the function <code>del_element_from_last</code> is redundant, because the condition will always be true.</p>\n<p>On the other hand, defensive programming is good programming style. Therefore, it may still be appropriate to keep it.</p>\n<p>However, if you decide to keep it, your program should handle both cases properly. If the condition is false, your program will cause undefined behavior, because you read the uninitialized value of <code>last</code>. Therefore, you should probably instead immediately <code>return false</code> when the condition is false.</p>\n<p>An alternative to the <code>if</code> statement would be to use the <a href=\"https://en.cppreference.com/w/c/error/assert\" rel=\"nofollow noreferrer\">assert</a> macro, like this:</p>\n<p><code>assert( llist-&gt;head );</code></p>\n<p>That way, you don't have to provide code to handle both cases. Instead, a diagnostic error message will appear if the variable does not have the expected value (only on debug builds though, not on release builds).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-11T09:05:27.197", "Id": "501995", "Score": "0", "body": "I understood [k is guaranteed to be smaller than the length of the list] as I have to check that so. That was my mistake. Thanks for the review." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T20:01:18.197", "Id": "254237", "ParentId": "254213", "Score": "3" } }, { "body": "<ul>\n<li>You are relying on the compiler zeroing local variables. For portability initialize them as needed.</li>\n<li>Use the address of either <code>head</code> or <code>next</code> fields (<code>llnode**</code>). Then deletion will become trivial.</li>\n<li>Free the deleted node.</li>\n<li>head node deletion does not printf. As printf was probably just test code, not so important.</li>\n<li>Two loops (instead of ifs) are more readable; first one to establish the back lag, and then following with a distance of k. <em>Doing one thing at the time.</em></li>\n<li>Variable names could be more accurate. (I did not do that much better.)</li>\n</ul>\n<p>So:</p>\n<pre><code>bool del_element_from_last(xllist *llist, int k)\n{\n llnode *cur;\n int back = 0;\n for (cur = llist-&gt;head; cur &amp;&amp; back &lt; k; cur = cur-&gt;next)\n {\n ++back;\n }\n if (back &lt; k) // List too short.\n {\n return false;\n }\n\n llnode **follow = &amp;(llist-&gt;head);\n for (; cur; cur = cur-&gt;next)\n {\n follow = &amp;(*follow)-&gt;next;\n }\n\n\n if (!*follow) // k &lt;= 0.\n {\n return false;\n }\n printf(&quot;deleted element:%d \\n&quot;, (*follow)-&gt;value);\n llnode *old = *follow;\n *follow = (*follow)-&gt;next;\n free(old);\n return true;\n}\n</code></pre>\n<p>The second <em>if</em> guards the deletion naturally - no null pointer.\nThe second <em>if</em> returning false could happen when k is 0. A fallacy is to combine conditions to make the code shorter. The code above is better traceable:</p>\n<ol>\n<li>[At the second <em>if</em>] Why that null check? At the end of the list?</li>\n<li>Aha, then k must be 0 (or less).</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-04T14:37:37.990", "Id": "254307", "ParentId": "254213", "Score": "3" } } ]
{ "AcceptedAnswerId": "254307", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T08:52:34.493", "Id": "254213", "Score": "2", "Tags": [ "c", "linked-list", "interview-questions" ], "Title": "remove kth last element from singly-linked list - Follow up" }
254213
<pre><code>def alphabetlist(): print(&quot;alphabet1 = [a,b,c,d,e,f]&quot;) print(&quot;alphabet2 = [g,h,i,j,k,l]&quot;) print(&quot;alphabet3 = [m,n,o,p,q,r]&quot;) print(&quot;alphabet4 = [s,t,u,v,w,x]&quot;) print(&quot;alphabet5 = [y,z]&quot;) print(&quot;Guess a word.&quot;) print(&quot;Now i will try to figure out the word you guessed.&quot;) totalletters=int(input(&quot;total number of letters in your guessed words are: &quot;)) def chooselist(x): if x == 1: print(alphabet1) elif x == 2: print(alphabet2) elif x == 3: print(alphabet3) elif x == 4: print(alphabet4) elif x == 5: print(alphabet5) list=[ ] def listtranspose(w): if w == 1: i=int(input());list.append(alphabet1[i-1]) elif w == 2: i=int(input());list.append(alphabet2[i-1]) elif w == 3: i=int(input());list.append(alphabet3[i-1]) elif w == 4: i=int(input());list.append(alphabet4[i-1]) elif w == 5: i=int(input());list.append(alphabet5[i-1]) alphabetlist() alphabet1 = [&quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d&quot;,&quot;e&quot;,&quot;f&quot;] alphabet2 = [&quot;g&quot;,&quot;h&quot;,&quot;i&quot;,&quot;j&quot;,&quot;k&quot;,&quot;l&quot;] alphabet3 = [&quot;m&quot;,&quot;n&quot;,&quot;o&quot;,&quot;p&quot;,&quot;q&quot;,&quot;r&quot;] alphabet4 = [&quot;s&quot;,&quot;t&quot;,&quot;u&quot;,&quot;v&quot;,&quot;w&quot;,&quot;x&quot;] alphabet5 = [&quot;y&quot;,&quot;z&quot;] step_1=[ ];h=0 while totalletters&gt;h: print(&quot;your letter is from which list 1,2,3,4,5&quot;) x = int(input()) step_1.append(x);h+=1 print(&quot;***\n 1 2 3 4 5 6 &quot;) g=0 while totalletters&gt;g: chooselist(step_1[g]);g+=1 print(&quot;*******&quot;);e=0 while totalletters&gt;e: print(&quot;choose from these lists again now 1,2,3,4,5,6&quot;) listtranspose(step_1[e]);e+=1 print(&quot;the word you guessed is: &quot;,end=&quot; &quot;) for i in range(0,len(list),1): print(list[i],end=&quot;&quot;) </code></pre> <p>This program is a word guessing game. The user thinks of a word and this program guesses it. through a series of list I want to know if there are other ways to write this, more easily actually I get all the functions used but not the next part</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T11:37:37.250", "Id": "501340", "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)." } ]
[ { "body": "<p>I don't know what you mean by &quot;more easily&quot;, but here are some comments on the code:</p>\n<h2>No error handling</h2>\n<p>In many statements like <code>i=int(input());list.append(alphabet1[i-1])</code> you use user input directly to index a list, without checking if it is in range, or even if it is a number.<br />\nOne wrong keystroke from the user and the whole program crashes.</p>\n<h2>Mixed code</h2>\n<p>You mix main script code with function definitions, making it harder to follow your program flow by hand, thus making your program harder to understand.</p>\n<p>You should have your main program code follow all the functions in one coherent block, and it is even better to wrap it in its own <code>main</code> function, then use a construct like this:</p>\n<pre><code>if __name__ == '__main__':\n main()\n</code></pre>\n<h2>Repetitive code</h2>\n<p>In both <code>listtranspose</code> and <code>chooselist</code> you write the same line 5 times over, just because you used separate variables for 5 (almost) identical lists instead of a list of lists.</p>\n<h2>Naming</h2>\n<p>Do not use <code>list</code> as a variable name! It is a Python builtin for creating new lists, and while Python is nice enough to allow you to overwrite it, this can both break future code and make your code harder to understand by others.</p>\n<p>There are seemingly random one letter variables in your code <code>h, g, e</code>, it is hard to understand what they do.<br />\nPlease give them more meaningful names.</p>\n<p>Function <code>alphabetlist</code> actually prints the lists, so it would be better to name it <code>print_lists</code> or similar.\nAlso, there is no reason to hardcode the lists you print, since they already exists as list type variables.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T14:54:43.943", "Id": "501349", "Score": "1", "body": "Overall good points. For repetitive code and error handling, you should offer alternative strategies to fix the issues you've identified." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T12:33:29.897", "Id": "254217", "ParentId": "254214", "Score": "3" } }, { "body": "<p>This looks like a nice game. Let's see how we can improve your code.</p>\n<ul>\n<li><strong>we can STOP using <code>;</code>. This is Python, not C / C++ / Java etc</strong></li>\n<li>reorder your code so that it reads easier.</li>\n<li>rename your functions / variables so that the words are delimited by <code>_</code>.</li>\n<li>we can use the <code>string</code> stdlib library to generate your alphabets without repeating ourselves so much:</li>\n</ul>\n<pre><code>import string\n\nLETTERS = string.ascii_lowercase\nLETTERS = [\n list(LETTERS[letter:letter + 6])\n for letter in range(0, len(LETTERS), 6)\n]\n</code></pre>\n<p>The above will generate:</p>\n<pre><code>[['a', 'b', 'c', 'd', 'e', 'f'], ['g', 'h', 'i', 'j', 'k', 'l'], ['m', 'n', 'o', 'p', 'q', 'r'], ['s', 't', 'u', 'v', 'w', 'x'], ['y', 'z']]\n</code></pre>\n<p>Just by following the above and adapting some of the functions we'd get:</p>\n<pre><code>def alphabet_list():\n for index, letters_block in enumerate(LETTERS, start=1):\n print(&quot;alphabet{} = {}&quot;.format(index, letters_block))\n\n\ndef choose_list(choice):\n # since you wanted to count from 1, we have to do this\n # e.g. if user wants the 2nd list, we'll look at index 1\n choice = choice - 1\n\n try:\n return LETTERS[choice]\n except IndexError:\n print(&quot;Value has to be between 1 and {}&quot;.format(len(LETTERS)))\n sys.exit()\n</code></pre>\n<p>Your while loops can also be written as for loops which are more idiomatic for what you're trying to achieve. For example, the <code>step_1</code> while can be written like (not taking into account the proper exception handling):</p>\n<pre><code>step_1 = [\n int(input('What list does your letter belong to: '))\n for _ in range(user_word_length)\n]\n</code></pre>\n<p>Something that I've seen pretty often is that some are confused about the order of the execution. In Python, execution always begins at the first statement of the program. Statements are executed one at a time, in order from top to bottom. Function definitions do not alter the flow of execution of the program, but remember that statements inside the function are not executed until the function is called.</p>\n<p>That said, if you have something like this:</p>\n<pre><code>def function_1():\n print(&quot;function_1&quot;)\n\n\ndef function_2():\n print(&quot;function_2&quot;)\n</code></pre>\n<p>Nothing is going to be printed unless you call those functions. Now depending on your workflow, you can call which ever you want first.</p>\n<p>I wanted to point this because you can define all your functions at the top of your file, and then write the rest of the logic. Having statements between your functions makes your code so hard to understand.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T18:14:42.850", "Id": "501363", "Score": "0", "body": "can you please help me a bit more I'm new to programming" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T14:50:24.043", "Id": "254224", "ParentId": "254214", "Score": "2" } } ]
{ "AcceptedAnswerId": "254224", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T09:33:39.990", "Id": "254214", "Score": "3", "Tags": [ "python-3.x", "game", "functional-programming" ], "Title": "Python word guessing game" }
254214
<p>Here I'm trying to learn the Abstract factory pattern. Have referred some examples and trying to mimic the same with some dummy server examples. Please help me to review this.</p> <pre><code>package main import ( &quot;fmt&quot; &quot;io/ioutil&quot; &quot;log&quot; &quot;net/http&quot; ) type server interface { Query() GetContent() string } type google struct { URL string content string } type yahoo struct { URL string content string } func (g *google) Query() { resp, err := http.Get(g.URL) if err != nil { log.Fatal(err) } body, err := ioutil.ReadAll(resp.Body) if err != nil { panic(err) } g.content = string(body) } func (g *google) GetContent() string { return g.content } func (g *yahoo) Query() { resp, err := http.Get(g.URL) if err != nil { log.Fatal(err) } body, err := ioutil.ReadAll(resp.Body) if err != nil { panic(err) } g.content = string(body) } func (g *yahoo) GetContent() string { return g.content } func createFactory(domain string) server { switch domain { case &quot;google&quot;: return &amp;google{URL: &quot;https://www.google.com&quot;} case &quot;yahoo&quot;: return &amp;yahoo{URL: &quot;https://www.yahoo.com&quot;} default: fmt.Println(&quot;Invalid domain&quot;) return nil } } func main() { googleServer := createFactory(&quot;google&quot;) googleServer.Query() fmt.Println(googleServer.GetContent()) yahooServer := createFactory(&quot;yahoo&quot;) yahooServer.Query() fmt.Println(googleServer.GetContent()) } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T14:24:09.557", "Id": "254223", "Score": "0", "Tags": [ "go" ], "Title": "Golang - Abstract Factory" }
254223
<p>happy 2021 everyone!</p> <p>I started coding some months ago for fun and recently I challenged myself to build a JSON parser in Python (v3.8).</p> <p>The basic idea was to avoid loading the whole file at once, instead parsing a file line by line. But of course I'm still a newb, so there is probably a lot of absurdities in there. Constructive criticism is very welcome!</p> <p>The full code is here: <a href="https://pastebin.com/fEP4n9Gw" rel="nofollow noreferrer">https://pastebin.com/fEP4n9Gw</a> The sample JSON used to test it is here: <a href="https://pastebin.com/587jqziH" rel="nofollow noreferrer">https://pastebin.com/587jqziH</a></p> <p>EDIT: rewrote the main parsing function to be able to handle compact jsons. It's of course still far from optimal code, but that's not the point. :)</p> <pre><code>import re import ast class TranslateJSON(ast.NodeTransformer): ''' NodeTransformer to replace null/true/false for None, True and False before evaluating the string. ''' translate_map = {'null': None, 'true': True, 'false': False} def visit_Name(self, node): if node.id in self.translate_map.keys(): return ast.Constant(value=self.translate_map[node.id], kind=None, lineno=node.lineno, col_offset=node.col_offset, end_lineno=node.end_lineno, end_col_offset=node.end_col_offset) class JSON_parser(): ''' Class has two attributes other than its methods: 'file_path': path of the json file to parse 'map': created via the buildDict() method, which simply evaluates the json file into a dictionary. The methods that should be called directly are: read(): accepts one argument, an iterable containing the whole hierarchy of keys to to query (from the outermost to the innermost). Since this method reads the file one line at a time, it's faster when handling large files. Otherwise buildDict() should be faster. buildDict(): merely evaluates the whole JSON file into a dictionary, storing it in self.map. This method can also be used to parse JSON strings directly. ''' full_value_regex = re.compile(r'^\s*(&quot;.+&quot;|null|true|false|\d+\.?\d*)') #pattern to find a non-object, non-array value. first_char_regex = re.compile(r'^\s*([{\[]).*') #pattern to find out if a value is a JSON object or array def __init__(self, file_path): self.file_path = file_path self.map = None def cleanString(self, line): ''' Prepares a string to be parsed (spaces are stripped) ''' clean_line = line.strip() return clean_line def translate_and_eval(self, value): ''' Replaces the values null, true and false in a captured value for None, True and False. Then evaluates the string litteraly into python data types. ''' ast_obj = ast.parse(value, mode='eval') try: final_value = ast.literal_eval(ast_obj) except: try: TranslateJSON().visit(ast_obj) final_value = ast.literal_eval(ast_obj) except: raise ValueError(f&quot;JSON malformed. Error evaluating {value}&quot;) return final_value def buildDict(self, string_to_eval=''): ''' Reads the whole file and evaluates it into a dictionary, storing it in self.map. Alternatively, you can pass a JSON as a string argument. ''' if not string_to_eval: with open(self.file_path) as source: for line in source: string_to_eval += self.cleanString(line) self.map = self.translate_and_eval(string_to_eval) def read(self, keys): ''' Master method to access a value of a JSON file without loading the whole file at once. To be used for large files. For smaller files, use buildDict() instead. 'keys' has to be a list of all the keys being searched, from outer to innermost. Ex.: self.read(['outerkey','middlekey','finalkey']) The string value is evaluated literally before being returned. ''' with open(self.file_path) as file: value = self._search(keys, file) value = self.translate_and_eval(value) return value def _search(self, keys, file): ''' Iteratively finds all keys of the hierarchy that is being searched, the last of which will have its position passed to the function _getValue(). Arguments: keys: list of keys to search, from outer to innermost. file: since the function is called with the file still open, the file object has to be passed as an argument. ''' #The variables below help limit the search to a specific part of the file open_bracket_count = 0 inside_quotes = False #Toggle to ignore curly brackets inside quotes start_is_set = False #When True, the desired hierarchy depth has been reached and the search can begin end_is_set = False #Toggles off the search (when a lower/higher hierarchy level is reached) last_endpos = [0,0] #Ultimately stores the position of the last found key, from which its value can be parsed. haystack = '' file.seek(0) for key_index, key in enumerate(keys): key_regex = re.compile('(&quot;' + key + '&quot;' + r'\s*:)') match = None file.seek(0) for line_number, line in enumerate(file): if line_number &lt; last_endpos[0]: #skips previous lines continue clean_line = self.cleanString(line) if line_number == last_endpos[0]: clean_line = clean_line[last_endpos[1]:] char_index_offset = last_endpos[1] #offsets the character index with the position of the last found key. Allows for parsing the same line multiple times. else: char_index_offset = 0 for char_index, char in enumerate(clean_line): if char == '&quot;': inside_quotes = not inside_quotes elif char == '}' and not inside_quotes: if open_bracket_count-1 == key_index+1 and not start_is_set: start_is_set = True elif open_bracket_count-1 == key_index and not end_is_set: end_is_set = True open_bracket_count -= 1 elif char == '{' and not inside_quotes: if open_bracket_count+1 == key_index+1 and not start_is_set: start_is_set = True elif open_bracket_count+1 == key_index+2 and not end_is_set: end_is_set = True open_bracket_count += 1 if start_is_set: haystack += char match = key_regex.search(haystack) if match: last_endpos = [line_number, char_index+char_index_offset] start_is_set, end_is_set = False, False haystack = '' break elif end_is_set: start_is_set, end_is_set = False, False haystack = '' if match: break if not match: raise KeyError(f&quot;{key} not found in file. Last valid key found at line {last_endpos[0]+1} and endchar index {last_endpos[1]}&quot;) if match: return self._getValue(last_endpos, file) def _getValue(self, match_end, file): ''' Once the final key has been found, _getValue() is called to return the actual value of the key. The function tries to capture the value directly with a regex (when the value is null, a string or a number). If this fails, it assumes the value is either a JSON object or an array (starting with { or [ respectively) Arguments: match_end: a list containing the line where the key was found and the index of the last character of the key in that line. Parsing will start from there. file: since the function is called with the file still open, the file object has to be passed as an argument. ''' file.seek(0) #The variables below help determine which type of data is being parsed (JSON object or array), #and whether the object/array has been fully captured. open_bracket = '' bracket_map = {'{': '}', '[': ']'} open_bracket_count = 0 close_bracket_count = 0 value = '' for line_number, line in enumerate(file): if line_number &lt; match_end[0]: continue elif line_number == match_end[0]: clean_line = self.cleanString(line) clean_line = clean_line[match_end[1]+1:] #starts parsing the line after the key name else: clean_line = self.cleanString(line) if not open_bracket: full_value_match = self.full_value_regex.match(clean_line) #first try to match a simple value, instead of obj/array (string, null or number) if full_value_match: return full_value_match.group(1) #If direct match fails, look at first non-whitespace character to determine whether value is a JSON object or array first_char_match = self.first_char_regex.match(clean_line) try: open_bracket = first_char_match.group(1) except: raise ValueError(f&quot;Could not retrieve value. JSON is probably malformed. Line: {line_number}&quot;) #the loop below adds characters to the variable 'value' until the whole object/array is captured. for char in clean_line: if char == open_bracket: open_bracket_count += 1 elif char == bracket_map[open_bracket]: close_bracket_count += 1 if open_bracket_count &gt; 0: if close_bracket_count == open_bracket_count: value += char return value else: value += char if __name__ == '__main__': ''' import timeit a=&quot;&quot;&quot; pop_map = JSON_parser('pop_map.json') x = pop_map.read(['investor', 'jewellery', 'consumption']) y = pop_map.read(['worker', 'fish']) z = pop_map.read(['scholar']) &quot;&quot;&quot; b=&quot;&quot;&quot; pop_map = JSON_parser('pop_map.json') pop_map.buildDict() x = pop_map.map['investor']['jewellery']['consumption'] y = pop_map.map['worker']['fish'] z = pop_map.map['scholar'] &quot;&quot;&quot; c=&quot;&quot;&quot; pop_map = JSON_parser('pop_map_compact.json') x = pop_map.read(['investor', 'jewellery', 'consumption']) y = pop_map.read(['worker', 'fish']) z = pop_map.read(['scholar']) &quot;&quot;&quot; d=&quot;&quot;&quot; import json with open('pop_map.json') as js: data = json.load(js) x = data['investor']['jewellery']['consumption'] y = data['worker']['fish'] z = data['scholar'] &quot;&quot;&quot; print(timeit.timeit(stmt=a, setup=&quot;from __main__ import JSON_parser&quot;, number=500)) print(timeit.timeit(stmt=b, setup=&quot;from __main__ import JSON_parser&quot;, number=500)) print(timeit.timeit(stmt=c, setup=&quot;from __main__ import JSON_parser&quot;, number=500)) print(timeit.timeit(stmt=d, setup=&quot;from __main__ import JSON_parser&quot;, number=500)) ''' ''' pop_map = JSON_parser('pop_map.json') x = pop_map.read(['investor', 'jewellery', 'consumption']) y = pop_map.read(['worker', 'market']) z = pop_map.read(['scholar']) print(x,y,z, sep='\n\n', end='\n\n\n') ''' ''' pop_map = JSON_parser('pop_map.json') pop_map.buildDict() x = pop_map.map['investor']['jewellery']['consumption'] y = pop_map.map['worker']['fish'] z = pop_map.map['scholar'] print(x,y,z, sep='\n\n') ''' ''' pop_map = JSON_parser('pop_map_compact.json') x = pop_map.read(['investor', 'jewellery', 'consumption']) y = pop_map.read(['worker', 'market']) z = pop_map.read(['scholar']) print(x,y,z, sep='\n\n', end='\n\n\n') ''' </code></pre> <p>Kind regards,</p> <p>Bernardo</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T18:09:14.443", "Id": "501361", "Score": "1", "body": "To be clear, the intent is to build your own JSON parser for learning Python as opposed to using the built in `json` library?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T18:18:48.567", "Id": "501364", "Score": "1", "body": "Likewise are you optimizing to just handle pretty-printed JSON (asking given the provided example file)? JSON can also come in compact mode where everything is all on the same line. There is also Newline-Delimited-JSON." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T19:04:04.430", "Id": "501375", "Score": "1", "body": "Hi Roman, yes, I have no intent to reinvent the wheel here. It's just a good exercise.\n\nAs for your second question, I did some testing with multiple keys on the same line and it does work, but it's true that then everything will be loaded at the same time, defeating the purpose of \"one line at a time\" :/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T19:24:34.140", "Id": "501376", "Score": "1", "body": "EDIT: No, I just tested it with a completely compact JSON and it doesn't work. Sorry for that :(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-03T05:07:40.513", "Id": "501418", "Score": "0", "body": "It works with compact jsons now. It's of course still far from optimal, obviously" } ]
[ { "body": "<p>Your speed-up claim:</p>\n<blockquote>\n<p>avoid loading the whole file at once, instead parsing a file line by line, which seems to be 2x as fast according to testing</p>\n</blockquote>\n<p>seems highly unlikely, and I would like to see proof of this. A compiled-and-tuned built-in JSON parser that operates on an in-memory buffer is nearly certain to outperform a non-compiled, non-built-in, line-by-line parser. The only advantage that your code will likely have is reduced memory occupation for huge files.</p>\n<p>More important than speed is correctness, and it seems you've already discovered cases where your parser simply breaks.</p>\n<p>It's also worth calling out that your parser is call-recursive. It will be trivially easy to crash your parser by providing a sufficiently-nested JSON file that will blow its stack, and these do exist in the wild in non-malicious situations.</p>\n<p>Basically, other than for learning purposes this shouldn't really be done at all. For the 99% of cases where it works, use built-in JSON parsing. For the 1% of cases where memory concerns actually call for iterative parsing, your problem has <a href=\"https://github.com/ICRAR/ijson\" rel=\"noreferrer\">already</a> <a href=\"http://lloyd.github.io/yajl/\" rel=\"noreferrer\">been</a> solved multiple times.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T20:49:22.747", "Id": "501389", "Score": "0", "body": "Thank you very much for the input! Indeed, I hadn't initially thought about handling different formats other than pretty-printed.\n\nAs for the speed, I should have been more specific that it's 2x as faster as the other method implemented in the file, which loads everything at once. Will edit that to make it clear." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T20:53:41.530", "Id": "501390", "Score": "0", "body": "I echo this sentiment. Apart from a \"for-fun\" exercise there is not much value in creating a JSON parser from scratch. In my opinion there are a great many python tutorials better suited to learning the language and having more fun while doing so (again just my opinion). I started using python by building some pygame tutorials." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T21:06:32.050", "Id": "501394", "Score": "3", "body": "Allow me to disagree. The fun part of coding for me is trying to reimplement things with minimal use of libraries. I of course don't expect to even come close to an optimal solution, but I do learn a great bit while trying, and it's loads of fun trying to solve these problems." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T21:11:24.803", "Id": "501396", "Score": "1", "body": "Yeah. Basically: do it, have fun, learn a bunch, but don't let this hit production." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T19:38:35.570", "Id": "254235", "ParentId": "254225", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T16:00:09.757", "Id": "254225", "Score": "6", "Tags": [ "python", "python-3.x", "parsing", "reinventing-the-wheel", "json" ], "Title": "Parsing a JSON one line at a time in Python" }
254225
<p>I am currently learning React and tried building the UI of a basic minesweeper game as a first project. My goal was to write simple, re-usable components. I will go over each of them and do my best to explain the rationale behind them and, after that, explain how they are all tied together in the main <code>App</code> component. Please let me know if anything I have written can be done in a more efficient or idiomatic way.</p> <p>As said before I have built the <strong>UI</strong> using React, the game logic is separate from the the React code. The whole project can be seen on <a href="https://github.com/LouisonCalbrix/minesweeper" rel="nofollow noreferrer">github</a> and the game can be actually played on my <a href="https://louisono.neocities.org" rel="nofollow noreferrer">neocities website</a>. One last precision: for readability reasons, the following is <strong>jsx code</strong>.</p> <h2>The Picker component</h2> <p>The picker component is used to create a group of labeled radio-buttons. It comes with a function <code>checkedRadio(groupName)</code> which returns the html <code>value</code> attribute of the chosen option. Note that I render a collection of elements without using <code>key</code>, here's why:</p> <ul> <li>each radio-button has an <code>id</code> attribute to make it work with the html <code>label</code>, I feel like adding a unique <code>key</code> would be redundant</li> <li>the list of radio-button shouldn't change over time, which means no re-render, and thus no need for a <code>key</code></li> </ul> <pre><code>/* Picker component: * Return a group of radio buttons. * Expected props: * - name: the html name for the group of radio buttons * - descriptions: a sequence of strings that each describes an option in the * group * - defaultPick: the index of the description for the default option picked * - onChange: a function called when the radio button checked changes, this * function can take as an argument an object of the form * { description, indexOfDescription } * - radioClass: the class name for every option of the Picker * Additional props will be attached to the wrapping div. */ const Picker = function({name, descriptions, defaultPick, onChange, radioClass, ...rest}) { return ( &lt;div {...rest}&gt; {descriptions.map((description, i) =&gt; { return ( &lt;span className={radioClass}&gt; &lt;input type='radio' name={name} value={description} id={`${ name }-${ description }`} defaultChecked={i===defaultPick} onChange={() =&gt; onChange({description, i})} /&gt; &lt;label htmlFor={`${ name }-${ description }`}&gt;{description}&lt;/label&gt; &lt;/span&gt;); })} &lt;/div&gt; ); } /* Return the value of the radio button checked in the group of radio buttons * that is named groupName. * Will throw an error if no such group is found. */ const checkedRadio = function(groupName) { const grp = document.querySelectorAll(`input[name=${groupName}`); for (const node of grp) if (node.checked) return node.value; throw new Error(`no radio group of name ${ groupName }`); } </code></pre> <h2>The Matrix component</h2> <p>This component is used to render a rectangular 2D array of data. It uses a <code>Row</code> component to render lines of cells. How each cell is render is up to the user, and a <code>cellComponent</code> should be provided for both of these components to work as intended. Here as well, I am not using any <code>key</code>, it is up to the user to give a <code>key</code> (or not) to their cells. Given that the user can make their cells have <code>key</code>s, I figured that <code>Row</code> elements don't need any <code>key</code> of their own.</p> <pre><code>/* Matrix component: * Return a table-like element. * Expected props: * - array: the 2D array that must be translated into a pseudo-table * - rowClass: the class name for every row in the Matrix * - onClick, onContextMenu: functions to be called when a cell of the * Matrix is respectively left-clicked or right-clicked * - cellComponent: a component to be instanciated for every cell of the * given 2D array. Such a component should accept props of the form * { cell, x, y, onClick, onContextMenu } * Additional props will be attached to the wrapping div. */ const Matrix = function({array, rowClass, onClick, onContextMenu, cellComponent, ...rest}) { return ( &lt;div {...rest}&gt; {array.map((row, y) =&gt; { return ( &lt;Row className={rowClass} row={row} y={y} onClick={onClick} onContextMenu={onContextMenu} cellComponent={cellComponent} /&gt; ); })} &lt;/div&gt; ); } /* Row component: * Return a flat sequence of cells. This component is meant to be instanciated * by the Matrix component. * Expected props: * - row: the flat (1D) array that must be translated into a Row * - y: the number of the Row in the Matrix * - onClick, onContextMenu: functions to be called when a cell of the * Row is respectively left-clicked or right-clicked * - cellComponent: a component to be instanciated for every cell of the * given 2D array. Such a component should accept props of the form * { cell, x, y, onClick, onContextMenu } * Additional props will be attached to the wrapping div. */ const Row = function({row, y, onClick, onContextMenu, cellComponent, ...rest}) { return ( &lt;div {...rest}&gt; {row.map((cell, x) =&gt; cellComponent({x, y, onClick, onContextMenu, cell}))} &lt;/div&gt; ); } </code></pre> <h2>My own <code>cellComponent</code>: the mineCell component</h2> <p>This is the <code>cellComponent</code> that is meant to be called by the <code>Matrix</code> component. It is meant to represent cells in a minesweeper game, and therefore relies more on the logic part (which isn't covered here). <code>mines.UNREV</code>, <code>mines.BOMB</code> and <code>mines.FLAG</code> are constants defined in the logic part that are used to differentiate between kinds of cell, here they are used to apply different styles to different cells. Still in the logic part, each cell can be represented be a single character, which is the actual <code>cell</code> argument passed to the <code>mineCell</code> component.</p> <pre><code>// Map to determine the CSS class of a cell based on its value const cellClasses = new Map( [[mines.UNREV, 'tile-unrevealed'], [mines.BOMB, 'tile-bomb'], [mines.FLAG, 'tile-flag']] ); // Cell component for the Minesweeper game const mineCell = function({x, y, onClick, onContextMenu, cell}) { let className = cellClasses.get(cell); return ( &lt;span className={className} onClick={() =&gt; onClick(x, y)} onContextMenu={(evt) =&gt; { evt.preventDefault(); onContextMenu(x, y) }}&gt; {cell} &lt;/span&gt; ); } </code></pre> <h2>Where everything is tied together: the App component</h2> <p>Let's have a look at the <code>render</code> function. It uses a <code>Picker</code> element (with difficulties defined in the logic part as <code>descriptions</code>) to let the user choose the difficulty setting and a <code>Matrix</code> element to render all the cells of the game.</p> <pre><code>// labels for the difficulty settings const descriptions = Array.from(mines.difficulties.keys()); // Map to determine the reset button css class depending on the minefield state const resetClasses = new Map( [[mines.WON, 'reset-won'], [mines.LOST, 'reset-lost'], [mines.PLAYING, 'reset-normal']] ); App.prototype.render = function() { const minefield = this.state.minefield; let resetButtonClass = resetClasses.get(minefield.state); return ( &lt;div id='app'&gt; &lt;Picker id='picker' descriptions={descriptions} name='difficulty' defaultPick={1} onChange={() =&gt; this.changeDifficulty()} radioClass='radio-button'/&gt; &lt;button id='reset-button' className={resetButtonClass} onClick={() =&gt; this.resetGame()} alt='button to reset the game'&gt; &lt;/button&gt; &lt;Matrix id='game' array={minefield.view} rowClass='mines-row' onClick={(x, y) =&gt; this.mineviewLeftClick(x, y)} onContextMenu={(x, y) =&gt; this.mineviewRightClick(x, y)} cellComponent={mineCell}/&gt; &lt;/div&gt; ); } </code></pre> <p>Here's how the <code>App</code> component is defined. The chosen difficulty can be retrieved at any moment by finding which option is checked in the difficulty <code>Picker</code>. The <code>state</code> only contains the <code>Minefield</code> instance. (Quick precision about the <code>Minefield</code> constructor defined in the logic part: it requires a position to instantiate any object so that the first cell clicked is not a bomb. For that reason anything displayed before the first click of a game is actually a dummy minefield.)</p> <pre><code>// Dummy minefield used when the game hasn't started yet const DUMMY = 'du'; const dummyMinefield = function([width, height, _]) { return { view: Array(height).fill(Array(width).fill(mines.UNREV)), state: DUMMY }; } const App = function(props) { React.Component.call(this, props); Object.defineProperty(this, 'difficulty', { enumerable: true, get: function() { return checkedRadio('difficulty'); } }); this.state = { minefield: dummyMinefield(mines.difficulties.get(descriptions[1])), }; } App.prototype = Object.create(React.Component.prototype); App.prototype.constructor = App; </code></pre> <p>The rest is the different functions: changing difficulty, starting the game over, clicking on a cell, putting a flag on a cell.</p> <pre><code>// Change the difficulty picked App.prototype.changeDifficulty = function() { this.setState({ minefield: dummyMinefield(mines.difficulties.get(this.difficulty)), }); } // Reset the on-going game of minesweeper App.prototype.resetGame = function() { this.setState({ minefield: dummyMinefield(mines.difficulties.get(this.difficulty)), }); } // Handle click events on the Matrix component that represents the minefield /* Handle left click events * Reveal the minefield's cell at coordinates x, y if the minefield is not a dummy. * Create a minefield otherwise */ App.prototype.mineviewLeftClick = function(x, y) { if (this.state.minefield.state===DUMMY) { const [width, height, bombs] = mines.difficulties.get(this.difficulty); const minefield = new mines.Minefield(width, height, [x, y], bombs); this.setState({minefield}); } else { const minefield = this.state.minefield.reveal([x, y]); this.setState({minefield}); } } /* Handle right click events * Flag the minefield's cell at coordinates x, y if the minefield is not a dummy. */ App.prototype.mineviewRightClick = function(x, y) { if (this.state.minefield.state!==DUMMY) { const minefield = this.state.minefield.flag([x, y]); this.setState({minefield}); } } </code></pre> <p>That's it, I hope it's not to long or too vague and I am looking forward to hear advice on how to write more idiomatic React code.</p>
[]
[ { "body": "<p><strong>Use <code>class</code>es</strong> instead of creating a <code>function</code> that manually inheirts from <code>React.Component</code>. This will also allow you to more concisely define properties and methods. For example:</p>\n<pre><code>class App extends React.Component {\n state = {\n minefield: dummyMinefield(mines.difficulties.get(descriptions[1])),\n };\n get difficulty() {\n return checkedRadio('difficulty');\n }\n changeDifficulty() {\n this.setState({\n minefield: dummyMinefield(mines.difficulties.get(this.difficulty)),\n });\n }\n // ...\n</code></pre>\n<p>Classes are a lot nicer for organizing code than <code>function</code>s and assigning to the <code>.prototype</code>.</p>\n<p>Or, even better:</p>\n<p><strong>Consider functional components</strong> - React <a href=\"https://reactjs.org/docs/hooks-faq.html#do-i-need-to-rewrite-all-my-class-components\" rel=\"nofollow noreferrer\">recommends trying functional components and hooks</a> instead of class components in new code. To me, the operation and lifecycle of functional components is more intuitive than for class components. If you try them, you may find that they make maintenance easier.</p>\n<p><strong>Avoid native DOM methods</strong> when possible - with React, whenever you see the use of a native DOM method like <code>querySelector</code> (or <code>.children</code> or <code>.style</code>, etc.), take a step back and consider if there's another way. <em>Usually</em>, the use of such methods can be avoided by using React's state and render methods instead.</p>\n<p>The only part with this issue is with the difficulty picker. Ideally, the <code>checkedRadio</code> function would be removed completely. (If you decide to keep it anyway, at least change the name to something like <code>getCheckedRadioName</code> - the variable doesn't <em>hold</em> the checked radio button, it <em>returns</em> the checked radio name)</p>\n<p>Put the difficulty into the app's state instead, and make the Picker a controlled component instead (so that selection changes go into state). Pass down the difficulty value and setter into the picker. Something like this:</p>\n<pre><code>const App = () =&gt; {\n // these get passed as selectedDescription and setSelectedDescription\n const [difficulty, setDifficulty] = useState('EASY');\n</code></pre>\n<pre><code>const Picker = function({name, descriptions, selectedDescription, setSelectedDescription, radioClass, ...rest}) {\n return (\n &lt;div {...rest}&gt;\n {descriptions.map((description) =&gt; {\n return (\n &lt;span className={radioClass}&gt;\n &lt;input type='radio'\n name={name}\n value={description}\n id={`${ name }-${ description }`}\n checked={description === selectedDescription}\n onChange={() =&gt; setSelectedDescription(description)} /&gt;\n &lt;label htmlFor={`${ name }-${ description }`}&gt;{description}&lt;/label&gt;\n &lt;/span&gt;);\n })}\n &lt;/div&gt;\n );\n}\n</code></pre>\n<p><strong>Rest parameters</strong> There are a whole lot of props in the component. Rather than allowing for as many additional props as the caller wants, you might consider using a <em>single</em> prop instead of the <code>rest</code>, and give it an informative name. Maybe:</p>\n<pre><code>, radioClass, pickerContainerProps = {}}) {\n return (\n &lt;div {...pickerContainerProps}&gt;\n</code></pre>\n<p><strong>Name</strong> I don't <em>think</em> the <code>name</code> prop needs to be passed down - it's an implementation detail that only the Picker cares about, after all, and only for the purposes of grouping the radios. Maybe have Picker come up with a name instead?</p>\n<pre><code>const inputNameRef = useRef();\nif (!inputNameRef.current) {\n inputNameRef.current = makeRandomString();\n}\n// proceed to use `inputNameRef.current` instead of `name`\n</code></pre>\n<p>You can also avoid the <code>id</code>s and the <code>htmlFor</code> by making the <code>&lt;input&gt;</code> a child of the <code>&lt;label&gt;</code>.</p>\n<p><strong>JSDoc</strong> The standard way to document functions in JS is with <a href=\"https://jsdoc.app/\" rel=\"nofollow noreferrer\">JSDoc</a> or a similar format. In contrast, using something like</p>\n<pre><code>/* Picker component:\n * Return a group of radio buttons.\n * Expected props:\n * - name: the html name for the group of radio buttons\n</code></pre>\n<p>while certainly <em>useful</em>, isn't quite in the expected format for good IDEs to take advantage of it. <a href=\"https://www.javascriptjanuary.com/blog/autocomplete-in-react-using-jsdoc\" rel=\"nofollow noreferrer\">Article with examples</a>.</p>\n<p>Here's a small example of how VSCode could inform the developer of the expected props by putting your comments into JSDoc format:</p>\n<p><a href=\"https://i.stack.imgur.com/AFfNl.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/AFfNl.png\" alt=\"enter image description here\" /></a></p>\n<p><strong>Consider using plain arrow functions everywhere</strong> instead of <code>function</code>s - arrow functions alone are a much more common convention in React. They're a bit more concise, both in the lack of <code>function</code> and their ability to implicitly return.</p>\n<p><strong>Spread props</strong> and use shorthand properties, if you like - when you only have to list each prop <em>once</em> when rendering rather than twice, that's one less potential for a typo-based problem to manifest. For example, this:</p>\n<pre><code>&lt;Row\n className={rowClass}\n row={row}\n y={y}\n onClick={onClick}\n onContextMenu={onContextMenu}\n cellComponent={cellComponent}\n/&gt;\n</code></pre>\n<p>could be:</p>\n<pre><code>&lt;Row\n className={rowClass}\n {...{\n row,\n y,\n onClick,\n onContextMenu,\n cellComponent\n }}\n/&gt;\n</code></pre>\n<p>(you could also use object rest to collect all of these but <code>className</code> into a single object in the parameter list of <code>Matrix</code>)</p>\n<p><strong>Use <code>const</code> instead of <code>let</code></strong> - see <a href=\"https://softwareengineering.stackexchange.com/questions/278652/how-much-should-i-be-using-let-vs-const-in-es6\">here</a>. Especially in React, where functional programming is preferred (and sometimes necessary), it's good to indicate to the reader of the code that even the <em>possibility</em> of reassignment is impossible. Both <code>let</code> uses I see can be replaced with <code>const</code>.</p>\n<p><strong>Destructure</strong>, if you like. Hopefully you'll be using functional components instead of class components, but if not, you can change stuff like this:</p>\n<pre><code>const minefield = this.state.minefield;\n</code></pre>\n<p>to</p>\n<pre><code>const { minefield } = this.state;\n</code></pre>\n<p><strong>Cell text</strong> When there's a visible mine on a cell, the cell text becomes &quot;X&quot;. When there's a visible flag on a cell, the cell text becomes &quot;P&quot;. These texts, while invisible normally, become visible if the board is highlighted. Same for unvisited cells, which have <code>.</code>s. Consider not rendering those texts at all - only render text if the text is a number.</p>\n<p><strong>Face tooltip</strong> You have</p>\n<pre><code>alt='button to reset the game'\n</code></pre>\n<p>Some people may not be familiar with Minesweeper's UI. Consider adding a tooltip as well, so that someone hovering over the face can see that it's clickable. Maybe add a <code>:hover</code> effect as well.</p>\n<p>If you wanted to make things fancy, you could also change the face to the hesitant &quot;O&quot; face when the mouse is pressed down on a cell but not released yet.</p>\n<p><strong>Make dragging harder to do accidentally</strong> It's very, very easy to accidentally drag the main interface by clicking down <em>anywhere</em> inside the interface and then dragging. This makes it impossible to reconsider one's choice if one clicks down on a cell but hasn't released the mouse yet. Consider allowing the drag action only with the <code>.close-bar</code> at the top.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-12T19:17:44.333", "Id": "502142", "Score": "0", "body": "Thank you for your insights! I disagree with you on a few points (namely the use of classes and DOM methods), however, I strongly appreciate your answer overall and your advice will surely help me enhance the quality of my code for future projects." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T20:08:12.343", "Id": "254239", "ParentId": "254226", "Score": "4" } } ]
{ "AcceptedAnswerId": "254239", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T16:19:51.757", "Id": "254226", "Score": "3", "Tags": [ "javascript", "react.js" ], "Title": "My first React project: UI for minesweeper" }
254226
<p>So I implemented a simple console-based, offline player vs. player chess game in C++17. I am aware that there are multiple chess-specific features I have not yet added, but the core gameplay works perfectly fine. This is quite a big project for a review, but I would be very grateful for any kind of advice. The code is structured in 3 classes:</p> <ol> <li><strong>Cchess_game</strong> is responsible for the main game loop.</li> <li><strong>Cchess_board</strong> is by far the biggest class, as it is responsible for anything related to the game board, so basically the whole game logic.</li> <li><strong>Cplayer</strong> honestly just exists for possible extensions in the future, like player specific timers. At the moment it only manages the user input.</li> </ol> <p>Additionally, there is a header <em>game_constants.h</em>, which includes the global constants used in the game. This is the code:</p> <p><em>source.cpp</em></p> <pre><code>#include &quot;Cchess_game.h&quot; int main() { chess::Cchess_game chess; int32_t winner = chess.play(); std::cout &lt;&lt; &quot;\nPlayer &quot; &lt;&lt; winner &lt;&lt; &quot; won!\n&quot;; return 0; } </code></pre> <p><em>Cchess_game.h</em></p> <pre><code>#ifndef CCHESS_GAME_H #define CCHESS_GAME_H #include &quot;Cchess_board.h&quot; #include &quot;Cplayer.h&quot; namespace chess { class Cchess_game { public: Cchess_game() : m_player1{ Cplayer() }, m_player2{ Cplayer() }, m_board{ Cchess_board() }, m_player_switch{ true }{}; game_result play(); // play single game of chess and return 1,2 for winner and 0 for draw private: Cplayer m_player1; Cplayer m_player2; Cchess_board m_board; bool m_player_switch; }; #endif } </code></pre> <p><em>Cchess_game.cpp</em></p> <pre><code>#include &quot;Cchess_game.h&quot; namespace chess { game_result Cchess_game::play() { game_result result; std::pair&lt;int32_t, int32_t&gt; from_coords; std::pair&lt;int32_t, int32_t&gt; to_coords; Cplayer* player = nullptr; do { // get pointer to current player to avoid repetition if (m_player_switch) { player = &amp;m_player1; } else { player = &amp;m_player2; } // display current game state m_board.display(); std::cout &lt;&lt; &quot;\n\n&quot;; std::cout &lt;&lt; &quot;Player &quot; &lt;&lt; !m_player_switch + 1 &lt;&lt; &quot;'s turn: \n\n&quot;; // get move info until move is valid do { std::cout &lt;&lt; &quot;Please enter the position of the figure you want to move: &quot;; from_coords = player-&gt;get_pos(); std::cout &lt;&lt; &quot;Please enter the position you want your figure to move to: &quot;; to_coords = player-&gt;get_pos(); } while (!m_board.is_valid(from_coords, to_coords, m_player_switch)); // execute move and update board m_board.move(from_coords, to_coords); // switch player m_player_switch = !m_player_switch; // clear console std::cout &lt;&lt; std::flush; system(&quot;CLS&quot;); } while ((result = m_board.game_state()) == still_playing); return result; } } </code></pre> <p><em>Cchess_board.h</em></p> <pre><code>#ifndef CCHESS_BOARD_H #define CCHESS_BOARD_H #include &quot;game_constants.h&quot; #include &lt;array&gt; #include &lt;iostream&gt; #include &lt;algorithm&gt; #include &lt;unordered_map&gt; #include &lt;stdlib.h&gt; namespace chess { class Cchess_board { public: Cchess_board(); // initialise default chess board game_result game_state() const; // return current game state void display() const; // display current board in console bool is_valid(std::pair&lt;int32_t, int32_t&gt; from, std::pair&lt;int32_t, int32_t&gt; to, bool player_switch) const; // return true if move is valid void move(std::pair&lt;int32_t, int32_t&gt; from, std::pair&lt;int32_t, int32_t&gt; to); // execute move private: bool find_figure(chess_board_state figure) const; // return true if figure is in board bool is_relative_field(std::pair&lt;int32_t, int32_t&gt; from, std::pair&lt;int32_t, int32_t&gt; to, int32_t x_shift, int32_t y_shift) const; // return true if position &quot;to&quot; is relative to &quot;from&quot; with shifts bool is_mate(std::pair&lt;int32_t, int32_t&gt; field, std::pair&lt;chess_board_state, chess_board_state&gt; figure_range) const; // return true if field is mate bool check_linear_move(std::pair&lt;int32_t, int32_t&gt; from, std::pair&lt;int32_t, int32_t&gt; to) const; // return true if move is linear and valid bool check_diagonal_move(std::pair&lt;int32_t, int32_t&gt; from, std::pair&lt;int32_t, int32_t&gt; to) const; // return true if move is diagonal and valid std::array&lt;std::array&lt;chess_board_state, chess_board_width&gt;, chess_board_height&gt; m_board; int32_t m_invert_y; // help value to distract from to invert index }; #endif } </code></pre> <p><em>Cchess_board.cpp</em></p> <pre><code>#include &quot;Cchess_board.h&quot; namespace chess { Cchess_board::Cchess_board() { m_board = std::array&lt;std::array&lt;chess_board_state, chess_board_width&gt;, chess_board_height&gt;{ { { p2_rook, p2_knight, p2_bishop, p2_queen, p2_king, p2_bishop, p2_knight, p2_rook }, { p2_pawn, p2_pawn, p2_pawn, p2_pawn, p2_pawn, p2_pawn, p2_pawn, p2_pawn }, { empty, empty, empty, empty, empty, empty, empty, empty }, { empty, empty, empty, empty, empty, empty, empty, empty }, { empty, empty, empty, empty, empty, empty, empty, empty }, { empty, empty, empty, empty, empty, empty, empty, empty }, { p1_pawn, p1_pawn, p1_pawn, p1_pawn, p1_pawn, p1_pawn, p1_pawn, p1_pawn }, { p1_rook, p1_knight, p1_bishop, p1_queen, p1_king, p1_bishop, p1_knight, p1_rook } }}; m_invert_y = chess_board_height - 1; } game_result Cchess_board::game_state() const { // check for p1 win if (!find_figure(p2_king)) { return p1_win; } // check for p2 win if (!find_figure(p1_king)) { return p2_win; } return still_playing; } void Cchess_board::display() const { std::unordered_map&lt;chess_board_state, std::string&gt; figure_to_string = { {empty,&quot;empty &quot;}, {p1_pawn,&quot;white_pawn &quot;}, {p1_knight,&quot;white_knight&quot;}, {p1_bishop,&quot;white_bishop&quot;}, {p1_rook,&quot;white_rook &quot;}, {p1_queen,&quot;white_queen &quot;}, {p1_king,&quot;white_king &quot;}, {p2_pawn,&quot;black_pawn &quot;}, {p2_knight,&quot;black_knight&quot;}, {p2_bishop,&quot;black_bishop&quot;}, {p2_rook,&quot;black_rook &quot;}, {p2_queen,&quot;black_queen &quot;}, {p2_king,&quot;black_king &quot;} }; std::array&lt;int32_t, chess_board_height&gt; y_axis_descr = { 8, 7, 6, 5, 4, 3, 2, 1 }; // print x-axis description std::cout &lt;&lt; &quot; a b c d e f g h\n&quot;; // print line by line for (int32_t i = 0; i &lt; chess_board_height; i++) { std::cout &lt;&lt; static_cast&lt;int&gt;(y_axis_descr[i]) &lt;&lt; &quot; &quot;; for (chess_board_state state : m_board[i]) { std::cout &lt;&lt; figure_to_string[state].c_str() &lt;&lt; &quot; &quot;; } std::cout &lt;&lt; &quot;\n&quot;; } } bool Cchess_board::is_valid(std::pair&lt;int32_t, int32_t&gt; from, std::pair&lt;int32_t, int32_t&gt; to, bool player_switch) const { int32_t from_x = from.first; int32_t from_y = m_invert_y - from.second; int32_t to_x = to.first; int32_t to_y = m_invert_y - to.second; std::pair&lt;chess_board_state, chess_board_state&gt; figure_range; // change range of own figures depending on player switch if (player_switch) { figure_range.first = p1_pawn; figure_range.second = p1_king; } else { figure_range.first = p2_pawn; figure_range.second = p2_king; } // check if move is valid based on figure // switch statement was not possible, because it requires compile-time constants // pawn if (m_board[from_y][from_x] == figure_range.first) { if ((is_relative_field(from, to, 0, -1) &amp;&amp; m_board[to_y][to_x] == empty &amp;&amp; player_switch) || // 1 forward - player 1 (is_relative_field(from, to, 0, -2) &amp;&amp; m_board[to_y][to_x] == empty &amp;&amp; from_y == 6 &amp;&amp; player_switch) || // 2 forward from start - player 1 (is_relative_field(from, to, -1, -1) &amp;&amp; !is_mate(to, figure_range) &amp;&amp; m_board[to_y][to_x] != empty &amp;&amp; player_switch) || // attack diagonal - player 1 (is_relative_field(from, to, 1, -1) &amp;&amp; !is_mate(to, figure_range) &amp;&amp; m_board[to_y][to_x] != empty &amp;&amp; player_switch) || // attack diagonal - player 1 (is_relative_field(from, to, 0, 1) &amp;&amp; m_board[to_y][to_x] == empty &amp;&amp; !player_switch) || // 1 forward - player 2 (is_relative_field(from, to, 0, 2) &amp;&amp; m_board[to_y][to_x] == empty &amp;&amp; from_y == 1 &amp;&amp; !player_switch) || // 2 forward from start - player 2 (is_relative_field(from, to, -1, 1) &amp;&amp; !is_mate(to, figure_range) &amp;&amp; m_board[to_y][to_x] != empty &amp;&amp; !player_switch) || // attack diagonal - player 2 (is_relative_field(from, to, 1, 1) &amp;&amp; !is_mate(to, figure_range) &amp;&amp; m_board[to_y][to_x] != empty &amp;&amp; !player_switch)) // attack diagonal - player 2 { return true; } } // knight else if (m_board[from_y][from_x] == figure_range.first + 1) { if ((is_relative_field(from, to, -1, -2) &amp;&amp; !is_mate(to, figure_range)) || // 2 up, 1 left (is_relative_field(from, to, 1, -2) &amp;&amp; !is_mate(to, figure_range)) || // 2 up, 1 right (is_relative_field(from, to, -1, 2) &amp;&amp; !is_mate(to, figure_range)) || // 2 down, 1 left (is_relative_field(from, to, 1, 2) &amp;&amp; !is_mate(to, figure_range)) || // 2 down, 1 right (is_relative_field(from, to, 2, -1) &amp;&amp; !is_mate(to, figure_range)) || // 2 right, 1 up (is_relative_field(from, to, 2, 1) &amp;&amp; !is_mate(to, figure_range)) || // 2 right, 1 down (is_relative_field(from, to, -2, -1) &amp;&amp; !is_mate(to, figure_range)) || // 2 left, 1 up (is_relative_field(from, to, -2, 1) &amp;&amp; !is_mate(to, figure_range))) // 2 left, 1 down { return true; } } // bishop else if (m_board[from_y][from_x] == figure_range.first + 2) { if (check_diagonal_move(from, to) &amp;&amp; !is_mate(to, figure_range)) { return true; } } // rook else if (m_board[from_y][from_x] == figure_range.first + 3) { if (check_linear_move(from, to) &amp;&amp; !is_mate(to, figure_range)) { return true; } } // queen else if (m_board[from_y][from_x] == figure_range.first + 4) { if ((check_diagonal_move(from, to) || check_linear_move(from, to)) &amp;&amp; !is_mate(to, figure_range)) { return true; } } // king else if (m_board[from_y][from_x] == figure_range.first + 5) { if ((is_relative_field(from, to, 0, -1) &amp;&amp; !is_mate(to, figure_range)) || // 1 up (is_relative_field(from, to, 1, -1) &amp;&amp; !is_mate(to, figure_range)) || // 1 up, 1 right (is_relative_field(from, to, -1, -1) &amp;&amp; !is_mate(to, figure_range)) || // 1 up, 1 left (is_relative_field(from, to, 1, 0) &amp;&amp; !is_mate(to, figure_range)) || // 1 right (is_relative_field(from, to, -1, 0) &amp;&amp; !is_mate(to, figure_range)) || // 1 left (is_relative_field(from, to, 0, 1) &amp;&amp; !is_mate(to, figure_range)) || // 1 down (is_relative_field(from, to, 1, 1) &amp;&amp; !is_mate(to, figure_range)) || // 1 down, 1 right (is_relative_field(from, to, -1, 1) &amp;&amp; !is_mate(to, figure_range))) // 1 down, 1 left { return true; } } else { std::cout &lt;&lt; &quot;\nThis is not one of your figures.\n\n&quot;; return false; } std::cout &lt;&lt; &quot;\nNot a valid move.\n\n&quot;; return false; } bool Cchess_board::is_relative_field(std::pair&lt;int32_t, int32_t&gt; from, std::pair&lt;int32_t, int32_t&gt; to, int32_t x_shift, int32_t y_shift) const { return (m_invert_y - from.second + y_shift == m_invert_y - to.second &amp;&amp; from.first + x_shift == to.first ); } bool Cchess_board::is_mate(std::pair&lt;int32_t, int32_t&gt; field, std::pair&lt;chess_board_state, chess_board_state&gt; figure_range) const { return !(m_board[m_invert_y - field.second][field.first] &lt; figure_range.first || m_board[m_invert_y - field.second][field.first] &gt; figure_range.second); } bool Cchess_board::check_linear_move(std::pair&lt;int32_t, int32_t&gt; from, std::pair&lt;int32_t, int32_t&gt; to) const { // is linear? if (from.first == to.first || m_invert_y - from.second == m_invert_y - to.second) { int32_t temp_x = from.first; int32_t temp_y = m_invert_y - from.second; // is valid? // x-axis case while (temp_x != to.first) { if (temp_x &gt; to.first) { temp_x--; } else { temp_x++; } if (m_board[m_invert_y - from.second][temp_x] != empty &amp;&amp; temp_x != to.first) { return false; } } // y-axis case while (temp_y != m_invert_y - to.second) { if (temp_y &gt; m_invert_y - to.second) { temp_y--; } else { temp_y++; } if (m_board[temp_y][from.first] != empty &amp;&amp; temp_y != m_invert_y - to.second) { return false; } } return true; } return false; } bool Cchess_board::check_diagonal_move(std::pair&lt;int32_t, int32_t&gt; from, std::pair&lt;int32_t, int32_t&gt; to) const { int32_t temp_x = from.first; int32_t temp_y = m_invert_y - from.second; // is diagonal? if (abs((m_invert_y - from.second) - (m_invert_y - to.second)) == abs(from.first - to.first)) { // is valid? while (temp_x != to.first) { if (temp_x &gt; to.first) { temp_x--; } else { temp_x++; } if (temp_y &gt; m_invert_y - to.second) { temp_y--; } else { temp_y++; } if (m_board[temp_y][temp_x] != empty &amp;&amp; temp_x != to.first) { return false; } } return true; } return false; } void Cchess_board::move(std::pair&lt;int32_t, int32_t&gt; from, std::pair&lt;int32_t, int32_t&gt; to) { // assign figure to new position m_board[m_invert_y - to.second][to.first] = m_board[m_invert_y - from.second][from.first]; // clear old position m_board[m_invert_y - from.second][from.first] = empty; } bool Cchess_board::find_figure(chess_board_state figure) const { for (auto&amp; row : m_board) { if (std::find(row.begin(), row.end(), figure) != row.end()) { return true; } } return false; } } </code></pre> <p><em>Cplayer.h</em></p> <pre><code>#ifndef CPLAYER_H #define CPLAYER_H #include &quot;game_constants.h&quot; #include &lt;utility&gt; #include &lt;string&gt; #include &lt;iostream&gt; #include &lt;ctype.h&gt; #include &lt;unordered_map&gt; namespace chess { class Cplayer { public: std::pair&lt;int32_t, int32_t&gt; get_pos() const; }; #endif } </code></pre> <p><em>Cplayer.cpp</em></p> <pre><code>#include &quot;Cplayer.h&quot; namespace chess { std::pair&lt;int32_t, int32_t&gt; Cplayer::get_pos() const { // dictionary to convert x-axis char to integer index std::unordered_map&lt;char, int32_t&gt; convert_to_int({ {'a',0}, {'b',1}, {'c',2}, {'d',3}, {'e',4}, {'f',5}, {'g',6}, {'h',7} }); std::string pos; // get valid user input for (;;) { std::cin &gt;&gt; pos; // check for // size a-h &lt;= 8 &gt;= 1 if (pos.size() == 2 &amp;&amp; convert_to_int.find(pos[0]) != convert_to_int.end() &amp;&amp; pos[1] - '0' &lt;= 8 &amp;&amp; pos[1] - '0' &gt;= 1) { return { convert_to_int[pos[0]], pos[1] - '0' - 1 }; } std::cout &lt;&lt; &quot;\nInvalid input format.\n\n&quot;; } } } </code></pre> <p><em>game_constants.h</em></p> <pre><code>#ifndef GAME_CONSTANTS_H #define GAME_CONSTANTS_H #include &lt;stdint.h&gt; constexpr int32_t chess_board_height = 8; constexpr int32_t chess_board_width = 8; enum chess_board_state { empty = 0, p1_pawn = 1, p1_knight, p1_bishop, p1_rook, p1_queen, p1_king, p2_pawn = 11, p2_knight, p2_bishop, p2_rook, p2_queen, p2_king, }; enum game_result { draw = 0, p1_win, p2_win, still_playing }; #endif </code></pre> <p>I would especially appreciate feedback regarding <code>Cchess_board::is_valid</code> as I am really unsatisfied with my solution.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T18:47:13.827", "Id": "501366", "Score": "0", "body": "Do you have reasons for not using inheritance to represent the chess pieces?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T20:57:40.497", "Id": "501391", "Score": "0", "body": "@theProgrammer Why would I use classes at all to represent the pieces? Enum's work just fine imo" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T21:02:05.040", "Id": "501392", "Score": "0", "body": "@TomGebel Because it makes checking valid moves trivial. You simply ask the piece if it made a valid move rather than having a big switch statement. This is the classic teaching example on how to use OOD." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T21:06:00.930", "Id": "501393", "Score": "0", "body": "@MartinYork But it does not really reduce code length, does it? Couldn't one argue that it is not worth the effort just for a little bit more readability?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T21:09:14.500", "Id": "501395", "Score": "0", "body": "One could argue that the whole point of writting in a human readable language is to make it as readable as possible. The largest cost of any application is maintaining it. Thus reducing this cost is more important than any other (unless explicitly required) thus readability is the **MOST** important thing for a professional programmer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T22:06:34.033", "Id": "501399", "Score": "0", "body": "@TomGebel One of Donald Knuth quotes which I feel is meaningful here `Programs are meant to be read by humans and only incidentally for computers to execute`" } ]
[ { "body": "<h2>Design</h2>\n<p>You have two much responsibility in a single class (the board).</p>\n<ol>\n<li>Why does the board need to know how to display itself.<br />\nWould be a good idea to inject the display class into the board at construction.<br />\nThis will allow for future enhancements into the interface without having to modify the board.</li>\n</ol>\n<ul>\n<li>Separating the board and display allows for better separation of logic and thus testing.</li>\n</ul>\n<ol start=\"2\">\n<li>Player input does not need to be part of the board.<br />\nWould be a good idea to inject player objects into the board thus allowing you to specialize later.</li>\n</ol>\n<ul>\n<li>Separating the board and player allows for better separation of logic and thus testing.</li>\n<li>This will make adding the AI trivial (once you have written the AI player).</li>\n</ul>\n<p>Why not use OO design for the pieces. You could have just as easily written this implementation in C.</p>\n<p>Overall I find the coupling in the code to tight.</p>\n<h2>Code Review</h2>\n<p>Namespace <code>chess</code> implies you then don't need to keep adding `chess to everything in that namespace (we now know that everything is chess related).</p>\n<pre><code> chess::Cchess_game chess;\n ^^^^^ ^^^^^ OK. Its chesss we get it.\n</code></pre>\n<p>Why is the <code>C</code> at the front here. Are you doing reverse polish type names? <code>C=&gt;class</code>. That was sort of good style 30 years ago. Its now considered rather redundant. Not going to say bad explicitly but I think its horrible.</p>\n<hr />\n<p>You are changing the type of winner here:</p>\n<pre><code> int32_t winner = chess.play();\n\n // The interface to `plat()` is\n game_result play();\n</code></pre>\n<p>Why are you not getting a <code>game_result</code> here?</p>\n<hr />\n<p>Would be nice with a more human readable result &quot;White&quot; or &quot;Black&quot; or player name?</p>\n<pre><code> std::cout &lt;&lt; &quot;\\nPlayer &quot; &lt;&lt; winner &lt;&lt; &quot; won!\\n&quot;;\n</code></pre>\n<hr />\n<p>Redundant:</p>\n<pre><code> return 0;\n</code></pre>\n<p>Not required in C++. Most people only return a value at the end here if there is an option for failure (and thus there can be another result). If I see <code>return 0</code> at the end I start looking for the failure cases in <code>main()</code>.</p>\n<hr />\n<p>None of that is requred.</p>\n<pre><code> Cchess_game() : m_player1{ Cplayer() }, m_player2{ Cplayer() }, m_board{ Cchess_board() }, m_player_switch{ true }{};\n</code></pre>\n<p>One variable definition per line please.</p>\n<pre><code> Cchess_game() \n : m_player1{ Cplayer() } // Default Create temporary object to initialize member!!\n , m_player2{ Cplayer() }\n , m_board{ Cchess_board() }\n , m_player_switch{ true }\n {}; // Now I can see the un-needed ';' at the end.\n</code></pre>\n<p>There is no prize for using the least number of lines. The whole point is to make this as readable and understandable to the next person that comes along to fix it (which is probably going to be you). Save yourself time in the future by taking some time now.</p>\n<p>The default constructors for each member would have taken care of this. Personally I would change this so that game takes references to players and board and then passed these references to the constructor. This way my main would have looked like:</p>\n<pre><code> int main()\n {\n Chess::PlayerHuman player1;\n Chess::PlayerAI player2;\n Chess::Board board;\n Chess::Display display(board);\n\n Chess::Game game(player1, player2, board, display);\n\n game.play();\n}\n</code></pre>\n<hr />\n<p>Comments contradict the code:</p>\n<pre><code> game_result play(); // play single game of chess and return 1,2 for winner and 0 for draw\n</code></pre>\n<p>Does the maintainer fix the code to match the comment or fix the comment. Extra waisted time. This is why bad comments are worse than zero comments. Explain why you are doing something in comments not how (the code does how).</p>\n<p>Though an enum is convertible to int that is not the same as returning an int.</p>\n<hr />\n<p>This looks like a BUG:</p>\n<pre><code> };\n#endif\n}\n</code></pre>\n<hr />\n<p>Dangerous to have uninitialized variables.</p>\n<pre><code> game_result result;\n</code></pre>\n<hr />\n<p>These variables are not used until the next scope block.</p>\n<pre><code> std::pair&lt;int32_t, int32_t&gt; from_coords;\n std::pair&lt;int32_t, int32_t&gt; to_coords;\n Cplayer* player = nullptr;\n</code></pre>\n<p>Declare variables are close to the point of usage as possible.</p>\n<hr />\n<p>That's a horrible named variable (<code>m_player_switch</code>).</p>\n<pre><code> // get pointer to current player to avoid repetition\n if (m_player_switch)\n {\n player = &amp;m_player1;\n }\n else\n {\n player = &amp;m_player2;\n }\n</code></pre>\n<p>Its not about switching player. If its true then we use player one. If it is false we use player two. Why not call it player ID?</p>\n<p>I would simplify this:\nbool isWhiteTurn = true;</p>\n<pre><code> .... \n Player&amp; currentPlayer = isWhiteTurn ? m_player1 : m_player2;\n ....\n isWhiteTurn = !isWhiteTurn;\n</code></pre>\n<hr />\n<p>This loop should be part of the <code>Player Code</code>.</p>\n<pre><code> {\n std::cout &lt;&lt; &quot;Please enter the position of the figure you want to move: &quot;;\n from_coords = player-&gt;get_pos();\n std::cout &lt;&lt; &quot;Please enter the position you want your figure to move to: &quot;;\n to_coords = player-&gt;get_pos();\n\n } while (!m_board.is_valid(from_coords, to_coords, m_player_switch));\n</code></pre>\n<p>If you swap out Humans for AI then writing to the output is confusing for the player. The type of output is dependent on the type of player. So move this to the Player code.</p>\n<p>Also you don't ask a player for a position. You ask a player for a move. Ask the player for a position twice with no context is bad API choice.</p>\n<hr />\n<p>Clearing the screen is not part of the game. This should be part of the display code. Sure you should tell the dislay that the current move is over. But what the display does is not part of the game.</p>\n<pre><code> // clear console\n std::cout &lt;&lt; std::flush;\n system(&quot;CLS&quot;);\n</code></pre>\n<hr />\n<p>Seems like another BUG</p>\n<pre><code> };\n#endif\n}\n</code></pre>\n<hr />\n<p>When possible us an initializer list:</p>\n<pre><code> Cchess_board::Cchess_board() \n {\n m_board = std::array&lt;std::array&lt;chess_board_state, chess_board_width&gt;, chess_board_height&gt;{ {\n { p2_rook, p2_knight, p2_bishop, p2_queen, p2_king, p2_bishop, p2_knight, p2_rook },\n { p2_pawn, p2_pawn, p2_pawn, p2_pawn, p2_pawn, p2_pawn, p2_pawn, p2_pawn },\n { empty, empty, empty, empty, empty, empty, empty, empty },\n { empty, empty, empty, empty, empty, empty, empty, empty },\n { empty, empty, empty, empty, empty, empty, empty, empty },\n { empty, empty, empty, empty, empty, empty, empty, empty },\n { p1_pawn, p1_pawn, p1_pawn, p1_pawn, p1_pawn, p1_pawn, p1_pawn, p1_pawn },\n { p1_rook, p1_knight, p1_bishop, p1_queen, p1_king, p1_bishop, p1_knight, p1_rook }\n }};\n\n m_invert_y = chess_board_height - 1;\n }\n</code></pre>\n<hr />\n<pre><code> void Cchess_board::display() const\n {\n</code></pre>\n<p>This structure is initialized every time this function is called.</p>\n<pre><code> std::unordered_map&lt;chess_board_state, std::string&gt; figure_to_string = {\n {empty,&quot;empty &quot;}, {p1_pawn,&quot;white_pawn &quot;}, {p1_knight,&quot;white_knight&quot;}, {p1_bishop,&quot;white_bishop&quot;}, {p1_rook,&quot;white_rook &quot;}, {p1_queen,&quot;white_queen &quot;}, {p1_king,&quot;white_king &quot;},\n {p2_pawn,&quot;black_pawn &quot;}, {p2_knight,&quot;black_knight&quot;}, {p2_bishop,&quot;black_bishop&quot;}, {p2_rook,&quot;black_rook &quot;}, {p2_queen,&quot;black_queen &quot;}, {p2_king,&quot;black_king &quot;}\n };\n</code></pre>\n<p>It should be a static member (inside the function (though if you made it a static member of the class so it could be used in other functions that would not bother me)).</p>\n<hr />\n<p>Not sure this is requied (but if it was another static member):</p>\n<pre><code> std::array&lt;int32_t, chess_board_height&gt; y_axis_descr = { 8, 7, 6, 5, 4, 3, 2, 1 };\n</code></pre>\n<p>You use this below to print out the row numbers.</p>\n<pre><code> std::cout &lt;&lt; static_cast&lt;int&gt;(y_axis_descr[i]) &lt;&lt; &quot; &quot;;\n\n // Could we not just do:\n std::cout &lt;&lt; (8-i) &lt;&lt; &quot; &quot;;\n</code></pre>\n<hr />\n<p>This while section could have been simplified by using OO.</p>\n<pre><code> m_board[from_y][from_x]-&gt;isGoodMove(to_x, to_y);\n</code></pre>\n<p>But even using enum you can simplify by using s switch:</p>\n<pre><code> switch(m_board[from_y][from_x]) {\n case pawn: checkMovePawn(from_y, form_x, to_y, to_x); break;\n case castle: checkMoveCastle(from_y, form_x, to_y, to_x);break;\n ....\n }\n</code></pre>\n<hr />\n<p>You check for mate on every combination of moves (pawn/knight/king). I would rather check for mate once, after I have figured out the move is valid (bishop/rook/queen).</p>\n<hr />\n<p>Your test for &quot;White&quot; Vs Black version of pieces means the types need to be ordered. But its not very logical organized. See below. when we look at the piece enum.</p>\n<hr />\n<p>Linear and diagnoal checks are the same thing and can be much simplified.</p>\n<pre><code> xDist = to_x - from_x;\n yDist = to_y - from_y;\n\n\n if (xDist == 0 || yDist == 0 || abs(xDist) == abs(yDist)) {\n // Valid move\n xInc = xDist / abs(xDist); // 1 or -1\n yInc = yDist / abs(yDist); // 1 or -1\n \n int xStart = from_x + xInc;\n int yStart = from_y + yInc;\n for(; xStart != to_x &amp;&amp; yStart != to_y;xStart += xInc, yStart += yInc) {\n // check for empty square.\n }\n } \n</code></pre>\n<p>This will simplify all your scanning checks.</p>\n<p>Especially if your parameterize the call with if they are allowed that type of move.</p>\n<pre><code> queen: checkScanMove(true, true, 8, from, to); break;\n rook: checkScanMove(true, false,8, from, to); break;\n bishop: checkScanMove(false,true, 8, from, to); break;\n king: checkScanMove(true, true, 1, from ,to); break;\n</code></pre>\n<hr />\n<p>Its a square board?</p>\n<pre><code>constexpr int32_t chess_board_height = 8;\nconstexpr int32_t chess_board_width = 8;\n</code></pre>\n<p>These could have been done better.</p>\n<pre><code>enum chess_board_state\n{\n empty = 0,\n\n p1_pawn = 1, \n p1_knight,\n p1_bishop,\n p1_rook,\n p1_queen,\n p1_king,\n\n p2_pawn = 11, // Why 11? 9 would have been better\n p2_knight,\n p2_bishop,\n p2_rook,\n p2_queen,\n p2_king,\n};\n</code></pre>\n<p>If it was nine: Then you simply check if bit 3 (value 8) to see if it is a black or white you just test bit 3.</p>\n<p>Also rather than p1_ and p2_ why not White_ or Black_</p>\n<p>Good idea</p>\n<pre><code>enum game_result\n{\n draw = 0, p1_win, p2_win, still_playing\n};\n</code></pre>\n<p>But you never use it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T23:50:42.530", "Id": "254254", "ParentId": "254227", "Score": "2" } } ]
{ "AcceptedAnswerId": "254254", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T17:44:55.713", "Id": "254227", "Score": "1", "Tags": [ "c++", "console", "chess" ], "Title": "Simple console chess game C++" }
254227
<p>I need some review on my implementation of input iterator. I am currently re-implementing std::vector, and need input_iterator for a specific constructor.</p> <p>Any criticism is much appreciated! Thank you.</p> <pre><code>#ifndef INPUT_ITERATOR #define INPUT_ITERATOR template&lt;typename T&gt; class input_iterator { private: T* input_iter; public: using reference = T&amp;; using const_reference = const T&amp;; using value_type = T; using pointer = T*; using const_pointer = const T*; constexpr input_iterator() noexcept : input_iter{ nullptr } {} constexpr explicit input_iterator(pointer inputIter) noexcept : input_iter{ inputIter } {} constexpr explicit input_iterator(const input_iterator&amp; other) noexcept : input_iter{ other.input_iter } {} ~input_iterator() noexcept = default; constexpr reference operator=(const input_iterator&amp; other){ if (input_iter != other.input_iter) input_iter = other.input_iter; return *this; } constexpr const_reference operator*() const { return *this; } constexpr const_pointer operator-&gt;() const { return this; } constexpr input_iterator&amp; operator++() { ++input_iter; return *this; } constexpr input_iterator&amp; operator++(int) { input_iterator current{ input_iter }; ++(*this); return current; } constexpr bool operator==(const input_iterator&amp; other) const noexcept { return (input_iter == other.input_iter); } constexpr bool operator!=(const input_iterator&amp; other) const { return !(input_iter == other.input_iter); } }; #endif <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T20:11:36.700", "Id": "501380", "Score": "1", "body": "The iterator for a constructor is normally just a templated type that implements the iterator concept. All standard iterators implement this concept o why do you need a special one for your version of the vector?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T20:12:02.617", "Id": "501381", "Score": "0", "body": "Hope this series on the vector helps: https://lokiastari.com/series/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T20:29:56.720", "Id": "501385", "Score": "1", "body": "Not sure why you want this. A pointer already implements the iterator concept so you don't need to wrap it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-03T17:51:18.823", "Id": "501453", "Score": "1", "body": "I have rolled back the last edit. Please see *[What to do when someone answers](/help/someone-answers)*." } ]
[ { "body": "<h1>Use <code>default</code> constructors and assignment operators where possible</h1>\n<p>Keep the number of user-defined constructors and operators to a minimum, and use <code>= default</code> if necessary. You only need the default constructor and the one that takes a <code>pointer</code> as an argument, the other constructors, assignment operators and even the destructor will already be provided for free. So:</p>\n<pre><code>template&lt;typename T&gt;\nclass input_iterator {\n ...\npublic:\n constexpr input_iterator() noexcept : input_iter{} {}\n constexpr explicit input_iterator(pointer inputIter) noexcept : input_iter{ inputIter } {}\n\n /* no other constructors, destructors or assignment operators */\n ...\n};\n</code></pre>\n<h1>Fix the dereferencing operators</h1>\n<p>The dereferencing operators should not return <code>this</code> or <code>*this</code>, but rather <code>input_iter</code> or <code>*input_iter</code>:</p>\n<pre><code>constexpr const_reference operator*() const {\n return *input_iter;\n}\n\nconstexpr const_pointer operator-&gt;() const {\n return input_iter;\n}\n</code></pre>\n<h1>The post-increment operator is wrong</h1>\n<p>Your post-increment operator returns a reference to a local variable. This is wrong of course, you should return by value instead. Here is how to do it in a one-liner:</p>\n<pre><code>constexpr input_iterator operator++(int) {\n return input_iterator(input_iter++);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T20:34:10.047", "Id": "501387", "Score": "0", "body": "Thank you for replying quickly. I'll make sure to fix the mentioned issues ^^" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T21:39:05.747", "Id": "501397", "Score": "0", "body": "`std::input_iterator` does not require a difference operator. Only random access or better iterators require difference operators. The only difference between `std::input_iterator` and LegacyInputIterator that I’m aware of is that the former has relaxed some equality requirements since C++20 now uses an iterator/sentinel model, rather than an iterator/iterator model." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-03T00:22:20.677", "Id": "501408", "Score": "0", "body": "@indi Hm, but `std::input_iterator` requires `std::input_or_output_iterator`, which requires [`std::weakly_incrementable`](https://en.cppreference.com/w/cpp/iterator/weakly_incrementable), which in turn `requires /*is-signed-integer-like*/<std::iter_difference_t<I>>`, and I was only able to have OP's class match the concept `std::input_iterator` when using GCC 10 if it has an `operator-()`. Is there a way to add a tag or something to make it pass if there is no difference operator?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-03T00:49:23.950", "Id": "501409", "Score": "1", "body": "@G.Sliepen That type has several issues that disqualify it from `std::input_iterator`. `std::iter_difference_t<I>` only requires `iterator_traits<I>::difference_type`, not `operator-(I, I)`. It’s also not movable (required by `std::weakly_incrementable`). I can get it to pass minimally on GCC by adding `difference_type` and defaulted move construction/assignment. It’s still wrong—it won’t even compile if instantiated—but at least the concept will pass." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-03T01:04:32.583", "Id": "501412", "Score": "1", "body": "As an aside, `std::forward_iterator` is even stricter. If you want to satisfy *that*, then in addition to satisfying `std::input_iterator`, you’d need to fix the copy constructor (remove the `explicit`) and fix the return types for the assignment operator and the post-increment op. That *should* do it; that would make it a minimal iterator, in my book (at which point you can restrict it back down to `std::input_iterator` by adding the iterator category tag)." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T20:19:37.307", "Id": "254240", "ParentId": "254228", "Score": "2" } }, { "body": "<h2>Overview</h2>\n<p>Not sure why you want to wrap a point to be an iterator. A pointer already implements the iterator concept (if fact it implements the random accesses iterator concept the most advanced type of iterator). By using this wrapper you are stunting the iterator implementation used.</p>\n<h2>Code Review</h2>\n<p>A bit generic. I would be afraid that another header was using this.</p>\n<pre><code>#ifndef INPUT_ITERATOR\n#define INPUT_ITERATOR\n</code></pre>\n<p>I usually include the namespace as part of the guard macro.</p>\n<hr />\n<p>Don't think you need to be explicit here.</p>\n<pre><code> ~input_iterator() noexcept = default;\n</code></pre>\n<hr />\n<p>Don't see the need for a self assignment test!</p>\n<pre><code> constexpr reference operator=(const input_iterator&amp; other){\n if (input_iter != other.input_iter)\n input_iter = other.input_iter;\n return *this;\n }\n</code></pre>\n<p>There are no resources to worry about. Simply overwrite every time. This will prevent branch prediction failures (and ultimately be quicker).</p>\n<hr />\n<p>Close.</p>\n<pre><code>constexpr input_iterator&amp; operator++(int) {\n input_iterator current{ input_iter };\n ++(*this);\n return current;\n }\n</code></pre>\n<p>But you are returning a reference to a local here. Remove the <code>&amp;</code> from the interface. Return a copy. Iterators are supposed to be cheap to copy.</p>\n<hr />\n<p>You only have a version that returns a const reference. What about a version that returns a reference?</p>\n<pre><code> constexpr const_reference operator*() const {\n return *this;\n }\n</code></pre>\n<p>Also the thing you are returning is not the correct type. Does this even compile?</p>\n<hr />\n<p>Again only a const pointer version. Why no pointer version?</p>\n<pre><code> constexpr const_pointer operator-&gt;() const {\n return this;\n }\n</code></pre>\n<p>Also the thing you are returning is not the correct type. Does this even compile?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T20:34:37.893", "Id": "501388", "Score": "0", "body": "Thanks for the quick reply! I haven't even noticed these mistakes, so thank you a lot ^^" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T20:20:50.667", "Id": "254241", "ParentId": "254228", "Score": "6" } }, { "body": "<h1>Input iterator is an abstract concept</h1>\n<p>I think you are <em>very</em> confused.</p>\n<p>“Input iterator” is a concept. A concept is an abstract specification, not a concrete “thing”. You can’t make an “implementation of input iterator”; that’s gibberish. You can implement something that <em>satisfies</em> the input iterator concept, but you can’t implement input iterator <em>itself</em>.</p>\n<p>It’s kinda like saying: “I’m making an implementation of container”. The only valid response to that statement is a blank look and the question: “Okay… <em><strong>WHICH</strong></em> container? A linked list? A hash table? A double-ended queue?” You can’t just make ‘container’; it’s an abstract concept. You can implement something that <em>is</em> a container (that is, something that satisfies the abstract specification of “container”), but you can’t actually “implement container”… that’s gibberish.</p>\n<p>You say you “need <code>input_iterator</code> for a specific constructor”… I think you mean you need <em><strong>AN</strong></em> input iterator for a specific constructor; you need a type that satisfies the input iterator concept, not specifically a type that “is” input iterator (because that’s gibberish).</p>\n<p>If you need an input iterator, you don’t need to make one. It’s a concept. <em>Anything</em> that satisfies the concept will do. For example, in the standard library, <code>std::istream_iterator</code> is an input iterator:</p>\n<pre><code>#include &lt;forward_list&gt;\n#include &lt;iostream&gt;\n#include &lt;iterator&gt;\n#include &lt;list&gt;\n#include &lt;sstream&gt;\n#include &lt;vector&gt;\n\ntemplate &lt;typename T&gt;\nvoid foo(T, T)\n{\n std::cout &lt;&lt; &quot;foo called with some type\\n&quot;;\n}\n\ntemplate &lt;std::forward_iterator T&gt;\nvoid foo(T, T)\n{\n std::cout &lt;&lt; &quot;foo called with forward iterators (or better)\\n&quot;;\n}\n\ntemplate &lt;std::input_iterator T&gt;\nvoid foo(T, T)\n{\n std::cout &lt;&lt; &quot;foo called with input iterators\\n&quot;;\n}\n\nauto main() -&gt; int\n{\n auto vec = std::vector&lt;int&gt;{};\n auto list = std::list&lt;int&gt;{};\n auto slist = std::forward_list&lt;int&gt;{};\n\n auto iss = std::istringstream{};\n\n foo(0, 1);\n foo(vec.begin(), vec.end());\n foo(list.begin(), list.end());\n foo(slist.begin(), slist.end());\n foo(std::istream_iterator&lt;int&gt;{iss}, std::istream_iterator&lt;int&gt;{});\n}\n</code></pre>\n<p>Output:</p>\n<pre><code>$ ./a.out\nfoo called with some type\nfoo called with forward iterators (or better)\nfoo called with forward iterators (or better)\nfoo called with forward iterators (or better)\nfoo called with input iterators\n$ \n</code></pre>\n<p>I can’t quite make sense of what you think you mean when you say you “need <code>input_iterator</code> for a specific constructor”, but if you mean you need to test a specific constructor with input iterators, then you can just do:</p>\n<pre><code>auto iss = std::istringstream{&quot;5 4 3 2 1&quot;};\n\nauto v = your_vector&lt;int&gt;(std::istream_iterator&lt;int&gt;{iss}, std::istream_iterator&lt;int&gt;{});\n// If the above constructor works as expected, v should now contain: 5, 4, 3, 2, 1\n</code></pre>\n<p>If you mean you need to <em>implement</em> a specific constructor with input iterators, then that’s just:</p>\n<pre><code>template &lt;typename T&gt;\nclass your_vector\n{\n // ... [snip] ...\n\n template &lt;typename T&gt;\n constexpr your_vector(T first, T last)\n {\n while (first != last)\n this-&gt;push_back(*first++);\n }\n\n // ... [snip] ...\n};\n</code></pre>\n<p>That’s a constructor that takes input iterators.</p>\n<p>Of course, before C++20 it’s standard practice to name the type with something more descriptive than T if you’re using a concept, like:</p>\n<pre><code>template &lt;typename T&gt;\nclass your_vector\n{\n // ... [snip] ...\n\n template &lt;typename InputIterator&gt;\n constexpr your_vector(InputIterator first, InputIterator last)\n {\n while (first != last)\n this-&gt;push_back(*first++);\n }\n\n // ... [snip] ...\n};\n</code></pre>\n<p>And as of C++20, you can now actually <em>check</em> that the type satisfies the input iterator concept, because the standard library has a <code>std::input_iterator</code> concept defined already:</p>\n<pre><code>template &lt;typename T&gt;\nclass your_vector\n{\n // ... [snip] ...\n\n template &lt;std::input_iterator It&gt;\n constexpr your_vector(It first, It last)\n {\n while (first != last)\n this-&gt;push_back(*first++);\n }\n\n // ... [snip] ...\n};\n</code></pre>\n<p>That’s it. That’s all you need. That’s implementing a constructor with input iterators, and above I show you how to <em>test</em> a constructor with input iterators. You don’t need to make an “input iterator” type, because the standard library already has input iterator types (and, as of C++20, a <code>std::input_iterator</code> concept to check them, to make sure they really are valid input iterators).</p>\n<h1>Your type is dangerous and buggy</h1>\n<p>So what you’re trying to do is take a plain pointer—which is a contiguous iterator—and strip its power, to reduce its capability until it <em>looks</em> like an input iterator.</p>\n<p>In <em>VERY</em> limited circumstances, this isn’t a <em>terrible</em> idea. For example, if you’re making an algorithm that works differently with input iterators than with forward iterators or better, and you want to test that the right implementation is being used, you could use a type like this to take the pointers to an array or vector data, and forcibly pretend they’re only input iterators.</p>\n<p>Of course… you could also just use <em>actual</em> input iterators, for example, by creating an <code>istringstream</code>, and then using <code>istream_iterator</code>s. That would be less work, and zero chance of bugs and other headaches.</p>\n<p>Where this type gets <em>dangerous</em> is that it will only work for very limited circumstances… and where it <em>won’t</em> work, it will silently trigger undefined behaviour.</p>\n<p>This is okay:</p>\n<pre><code>auto data = std::vector&lt;int&gt;{};\n// fill data with values...\n\nauto first = input_iterator&lt;int&gt;(&amp;data.front());\nauto last = input_iterator&lt;int&gt;(&amp;data.front() + data.size());\n\nany_algorithm(first, last);\n</code></pre>\n<p>This is not:</p>\n<pre><code>auto data = std::deque&lt;int&gt;{};\n// fill data with values...\n\nauto first = input_iterator&lt;int&gt;(&amp;data.front());\nauto last = input_iterator&lt;int&gt;(&amp;data.front() + data.size());\n\nany_algorithm(first, last);\n</code></pre>\n<p>The only thing that changed is the type of the container. But while <code>std::deque</code> is random-access, it is <em>NOT</em> contiguous, so trying to iterate through it using pointer arithmetic (which <code>input_iterator</code> does internally) is a quick path to UB.</p>\n<p>(In fact, the code above will not work for <em>any</em> container <em>except</em> <code>std::vector</code>. Trying it with <code>std::list</code> or <em>anything else</em> is asking for UB.)</p>\n<p>Iterators are attached to specific container types for a reason; you can’t just make an iterator out of the æther with no associated container. Again, that’s nonsensical. An iterator needs to know the <em>correct</em> way to move from one element to the next… no, simply skipping to the next address in memory is <em>NOT</em> the correct way to do it, usually.</p>\n<p>It is <em>possible</em> to implement an iterator <em>adaptor</em> that can take an iterator and fake it as a more restrictive category. But if you’re going to do that, you have to do it carefully. Simply degrading to a pointer is not the right way to do it.</p>\n<h1>Your type is not an input iterator… or an iterator at all</h1>\n<p>Okay, so you can’t implement an abstract concept. But you <em>can</em> implement something that <em>models</em> the abstract concept. You can’t “implement input iterator”, but you <em>can</em> implement something that <em>models</em> input iterator. Does your class model input iterator?</p>\n<p>No. It’s closer to a forward iterator, but it isn’t even that.</p>\n<p>To see what I mean, here’s a simple program that just prints the name of an iterator’s category, tested with simple pointers, <code>std::istream_iterator</code>, and your <code>input_iterator</code>:</p>\n<pre><code>#include &lt;iostream&gt;\n#include &lt;iterator&gt;\n#include &lt;string_view&gt;\n#include &lt;type_traits&gt;\n\n#include &lt;your-input-iterator-declaration&gt;\n\nnamespace detail_ {\n\ntemplate &lt;typename T, typename = void&gt;\nstruct iter_cat_impl_2_\n{ using type = std::iterator_traits&lt;T&gt;::iterator_category; };\n#if defined(__cpp_lib_ranges) and __cpp_lib_ranges &gt;= 201911L\ntemplate &lt;typename T&gt;\nstruct iter_cat_impl_2_&lt;T, std::void_t&lt;typename std::iterator_traits&lt;T&gt;::iterator_concept&gt;&gt;\n{ using type = std::iterator_traits&lt;T&gt;::iterator_concept; };\n#endif // defined(__cpp_lib_ranges) and __cpp_lib_ranges &gt;= 201911L\n\nstruct dummy_t {};\n\ntemplate &lt;typename T, typename = void&gt;\nstruct iter_cat_impl_1_ { using type = dummy_t; };\ntemplate &lt;typename T&gt;\nstruct iter_cat_impl_1_&lt;T, std::void_t&lt;typename std::iterator_traits&lt;T&gt;::iterator_category&gt;&gt; : iter_cat_impl_2_&lt;T&gt; {};\n\nusing namespace std::string_view_literals;\n\ntemplate &lt;typename T&gt;\ninline constexpr auto iter_cat_name = &quot;&lt;not an iterator&gt;&quot;sv;\ntemplate &lt;&gt;\ninline constexpr auto iter_cat_name&lt;std::input_iterator_tag&gt; = &quot;input iterator&quot;sv;\ntemplate &lt;&gt;\ninline constexpr auto iter_cat_name&lt;std::output_iterator_tag&gt; = &quot;output iterator&quot;sv;\ntemplate &lt;&gt;\ninline constexpr auto iter_cat_name&lt;std::forward_iterator_tag&gt; = &quot;forward iterator&quot;sv;\ntemplate &lt;&gt;\ninline constexpr auto iter_cat_name&lt;std::bidirectional_iterator_tag&gt; = &quot;bidirectional iterator&quot;sv;\ntemplate &lt;&gt;\ninline constexpr auto iter_cat_name&lt;std::random_access_iterator_tag&gt; = &quot;random access iterator&quot;sv;\n#if defined(__cpp_lib_ranges) and __cpp_lib_ranges &gt;= 201911L\ntemplate &lt;&gt;\ninline constexpr auto iter_cat_name&lt;std::contiguous_iterator_tag&gt; = &quot;contiguous iterator&quot;sv;\n#endif // defined(__cpp_lib_ranges) and __cpp_lib_ranges &gt;= 201911L\n\n} // namespace detail_\n\ntemplate &lt;typename T&gt;\ninline constexpr auto iter_cat_name = detail_::iter_cat_name&lt;typename detail_::iter_cat_impl_1_&lt;T&gt;::type&gt;;\n\nauto main() -&gt; int\n{\n std::cout &lt;&lt; &quot;int* = &quot; &lt;&lt; iter_cat_name&lt;int*&gt; &lt;&lt; '\\n';\n std::cout &lt;&lt; &quot;istream_iterator&lt;int&gt; = &quot; &lt;&lt; iter_cat_name&lt;std::istream_iterator&lt;int&gt;&gt; &lt;&lt; '\\n';\n std::cout &lt;&lt; &quot;input_iterator&lt;int&gt; = &quot; &lt;&lt; iter_cat_name&lt;input_iterator&lt;int&gt;&gt; &lt;&lt; '\\n';\n}\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-shell prettyprint-override\"><code>$ ./a.out\nint* = contiguous iterator\nistream_iterator&lt;int&gt; = input iterator\ninput_iterator&lt;int&gt; = &lt;not an iterator&gt;\n$ \n</code></pre>\n<p>As you can see, your type is not an iterator.</p>\n<p>The reason your type fails to be detected as an iterator is because you are missing some key typedefs. It looks like you have confused the typedefs necessary for a <em>CONTAINER</em> with the typedefs necessary for an <em>ITERATOR</em>. An <em>ITERATOR</em> does not need <code>const_pointer</code> or <code>const_reference</code>… those make no sense for an iterator. It <em>does</em> need <code>difference_type</code> and <code>iterator_category</code>.</p>\n<p>Once you define those typedefs, this type will “work” as an input iterator. But it will also “work” as a forward iterator (though, a well-designed algorithm will still treat it as an input iterator).</p>\n<p>Okay, let’s dive into the actual code review.</p>\n<h1>The review</h1>\n<p>I’ll skip down to the typedefs, because everything prior to that is cool:</p>\n<pre><code>using reference = T&amp;;\nusing const_reference = const T&amp;; // &lt;- nonsense typedef\nusing value_type = T;\nusing pointer = T*;\nusing const_pointer = const T*; // &lt;- nonsense typedef\n</code></pre>\n<p>The two typedefs I’ve marked are nonsense for an iterator. You have confused the typedefs required for a <em>container</em> with the typedefs required for an <em>iterator</em>.</p>\n<p>To understand why those typedefs are nonsensical, consider <code>std::vector&lt;int&gt;::iterator::const_pointer</code>. What do you think that means? <code>std::vector&lt;int&gt;::iterator</code> basically means: “I want a mutable pointer to the elements of an <code>int</code> vector (treated as a plain pointer)”. So <code>std::vector&lt;int&gt;::iterator::const_pointer</code> basically means: “I want a mutable pointer to the elements of an <code>int</code> vector no wait I changed my mind I want a <code>const</code> pointer to those elements (treated as a plain pointer)”. Meanwhile, there’s <code>std::vector&lt;int&gt;::const_iterator</code>, which actually means: “I want a <code>const</code> pointer to the elements of an <code>int</code> vector (treated as a plain pointer)”.</p>\n<p>That’s another reason why <code>const_pointer</code> and <code>const_reference</code> make no sense in an iterator: that’s what <code>const_iterator</code>s are.</p>\n<p>In addition, if you want your type to work as an iterator, there are some other typedefs you need. You need to define <code>difference_type</code>, and you need to define <code>iterator_category</code>. The former could be <code>std::ptrdiff_t</code>, and the latter, since you want it to be an input iterator, should be <code>std::input_iterator_tag</code>.</p>\n<p><code>pointer</code> and <code>reference</code> should also probably be defined differently, but I’ll explain why later.</p>\n<pre><code>constexpr explicit input_iterator(const input_iterator&amp; other) noexcept : input_iter{ other.input_iter } {}\n\n~input_iterator() noexcept = default;\n</code></pre>\n<p>These are kinda pointless. If you don’t need to declare the destructor, don’t bother. And in the case of the copy constructor, defining it like this means the type is no longer trivially copyable (or movable). (The <code>explicit</code> keyword is also meaningless here, because a copy constructor is not a converting constructor. It makes no sense to “explicitly copy”.)</p>\n<pre><code>constexpr reference operator=(const input_iterator&amp; other){\n if (input_iter != other.input_iter)\n input_iter = other.input_iter;\n return *this;\n}\n</code></pre>\n<p>As above, this is kinda pointless, and it means the type is no longer trivially assignable. The implementation is also overly complicated, too, because there’s no need to check for equality before doing the assignment. What exactly would go wrong if the two pointers are the same, yet you did the assignment anyway?</p>\n<pre><code>constexpr const_reference operator*() const {\n return *this;\n}\n\nconstexpr const_pointer operator-&gt;() const {\n return this;\n}\n</code></pre>\n<p>Seems to me like all these operations, and the increment ops, too, could be <code>noexcept</code>.</p>\n<p>However, both of these are wrong. Did you test the type? I can’t imagine it compiled. The reason why is that <code>operator*</code> on an iterator is <em>supposed</em> to return a reference to whatever is being pointed to. But you return <code>*this</code>. That’s a reference <em>to the iterator</em>… not to what the iterator is pointing to.</p>\n<p>The same problem exists for <code>operator-&gt;</code>. You’re supposed to return the address the iterator is pointing… but you return the address of the iterator.</p>\n<p><code>operator*</code> should probably just be returning <code>*input_iter</code>, and <code>operator-&gt;</code> should be probably returning <code>input_iter</code> itself.</p>\n<p>But there’s a much deeper issue: you’re seeing cracks in your conceptual model. An iterator is basically a pointer—the abstraction is just to allow more powerful pointers; ones that can handle iterating in ways other than merely jumping to the next memory address. So you can mentally replace any iterator with <code>T*</code> to get a grasp on how <code>operator*</code> and <code>operator-&gt;</code> should work.</p>\n<p>So if you have <code>int*</code>, what should <code>operator*</code> return? The answer is <code>int&amp;</code>… <em>NOT</em> <code>int const&amp;</code>.</p>\n<p>If you have <code>int* const</code>, what should <code>operator*</code> return? Again, <code>int&amp;</code>… <em>NOT</em> <code>int const&amp;</code>.</p>\n<p>So with <code>input_iterator&lt;int&gt;</code>, <code>operator*</code> should return <code>int&amp;</code>… <em>NOT</em> <code>int const&amp;</code>.</p>\n<p>With <code>input_iterator&lt;int&gt; const</code>, <code>operator*</code> should <em>also</em> return <code>int&amp;</code>… <em>NOT</em> <code>int const&amp;</code>.</p>\n<p>In other words, this is the <em>correct</em> way to implement <code>operator*</code> for iterators:</p>\n<pre><code>constexpr reference operator*() const noexcept { return *input_iter; }\n</code></pre>\n<p>Note that it returns <code>reference</code>, and not <code>const_reference</code> (which is not a thing; iterators don’t have <code>const_reference</code> because it’s nonsensical). Similarly, <code>operator-&gt;</code> should return <code>pointer</code>, not <code>const_pointer</code>.</p>\n<p>Ah, but input iterators offer only read-only views of what they point to, so they <em>should</em> return <code>const</code> pointers and references. The <em>correct</em> way to handle this is to properly define <code>reference</code> and <code>pointer</code>… not to invent new typedefs.</p>\n<p><code>reference</code> should be defined as <code>T const&amp;</code>, not <code>T&amp;</code>, because if the iterator is an input iterator, a reference will be read-only. Having <code>reference</code> defined as <code>T&amp;</code> makes no sense for an input iterator. Similarly, <code>pointer</code> should be <code>T const*</code>, not <code>T*</code>. If I do <code>input_iterator&lt;int&gt;::pointer p = &amp;(*i);</code>, that should compile… that’s the point of the <code>pointer</code> typedef. It won’t if <code>pointer</code> is <code>T*</code> while <code>operator*</code> returns <code>const&amp;</code>.</p>\n<p>So your typedefs really need to be:</p>\n<pre><code>using value_type = T;\n\nusing reference = T const&amp;;\nusing pointer = T const*;\n\nusing difference_type = std::ptrdiff_t;\n\nusing iterator_category = std::input_iterator_tag;\n</code></pre>\n<p>That’s about it, except for:</p>\n<pre><code>constexpr bool operator==(const input_iterator&amp; other) const noexcept {\n return (input_iter == other.input_iter);\n}\n\nconstexpr bool operator!=(const input_iterator&amp; other) const {\n return !(input_iter == other.input_iter);\n}\n</code></pre>\n<p>You’re missing the <code>noexcept</code> for the inequality operator.</p>\n<p>Standard practice is to use non-member functions for binary operators, and to define only one operator where possible and then all others in terms of that one. So:</p>\n<pre><code>friend constexpr bool operator==(const input_iterator&amp; lhs, const input_iterator&amp; rhs) noexcept {\n return lhs.input_iter == rhs.output_iter;\n}\n\nfriend constexpr bool operator!=(const input_iterator&amp; lhs, const input_iterator&amp; rhs) noexcept {\n return not (lhs == rhs);\n}\n</code></pre>\n<p>(It’s also a good idea, even though they’re non-member functions, to define them in the class as friends. This is called the “hidden friends” pattern, and it has several benefits, but it’s too much to go into here.)</p>\n<h1>Summary</h1>\n<p>The main problem here is conceptual confusion. “Input iterator” is an abstract idea. It’s a concept. You can’t make an implementation of input iterator any more than you can make an implementation of “<a href=\"https://en.cppreference.com/w/cpp/named_req/EqualityComparable\" rel=\"noreferrer\">equality comparable</a>”. You can implement something that <em>is</em> equality comparable, but can’t implement the abstract concept “equality comparable”. (As of C++20, <a href=\"https://en.cppreference.com/w/cpp/concepts/equality_comparable\" rel=\"noreferrer\">you can <em>describe</em> the concept, and use that to check that types satisfy the concept</a>, but you still can’t implement the abstract concept as a type.)</p>\n<p>So saying you are “implementing input iterator” is gibberish. Saying that you need “input iterator” for some constructor is also gibberish. Unfortunately, that’s all you’ve given, so I’m forced to guess what you <em>really</em> mean when you’re saying these things.</p>\n<p>If you mean you need a constructor that takes input iterators… well, that’s just a template constructor, with a type that satisfies the input iterator concept. The type could be anything; it doesn’t need to be some concrete <code>input_iterator</code> type. It just needs to satisfy the concept.</p>\n<p>The standard library has a couple types that satisfy the input iterator concept: <code>istream_iterator</code> and <code>istreambuf_iterator</code> are the two that spring to mind. So if you’re making a constructor that takes input iterators, just make a constructor template, and make sure it works with <code>istream_iterator</code>s (and/or <code>istreambuf_iterator</code>s).</p>\n<p>For example, this is actually Clang 11’s implementation of <code>std::vector</code>’s input iterator constructor:</p>\n<pre><code>template &lt;class _Tp, class _Allocator&gt;\ntemplate &lt;class _InputIterator&gt;\nvector&lt;_Tp, _Allocator&gt;::vector(_InputIterator __first,\n typename enable_if&lt;__is_cpp17_input_iterator &lt;_InputIterator&gt;::value &amp;&amp;\n !__is_cpp17_forward_iterator&lt;_InputIterator&gt;::value &amp;&amp;\n is_constructible&lt;\n value_type,\n typename iterator_traits&lt;_InputIterator&gt;::reference&gt;::value,\n _InputIterator&gt;::type __last)\n{\n#if _LIBCPP_DEBUG_LEVEL &gt;= 2\n __get_db()-&gt;__insert_c(this);\n#endif\n for (; __first != __last; ++__first)\n __emplace_back(*__first);\n}\n</code></pre>\n<p>Ignoring the <code>enable_if</code> and the debug stuff, and pretending it’s defined within the class body rather than outside, that’s just:</p>\n<pre><code>template &lt;class _InputIterator&gt;\nvector(_InputIterator __first, _InputIterator __last)\n{\n for (; __first != __last; ++__first)\n __emplace_back(*__first);\n}\n</code></pre>\n<p>That’s all there is to it.</p>\n<p>(The <code>enable_if</code> just makes sure that <code>_InputIterator</code> actually satisfies the input iterator concept, but not the forward iterator concept. That’s because the forward iterator version uses <code>std::distance()</code> to figure out how many elements there are, so it can preallocate enough memory. You can’t do that with input iterators, because you only get one pass; you can’t first count the elements, allocate the size, then copy the elements, because that second pass won’t work for input iterators. It’s a neat optimization you might consider, though it’s much easier with C++20 concepts than with <code>enable_if</code>.)</p>\n<p>And you can test that constructor with input iterators like this:</p>\n<pre><code>auto iss = std::istringstream{&quot;42 69 57&quot;};\n\nauto const vec = std::vector&lt;int&gt;(std::istream_iterator&lt;int&gt;{iss}, std::istream_iterator&lt;int&gt;{});\n\nTEST(vec.size() == 3);\nTEST(vec.at(0) == 42);\nTEST(vec.at(1) == 69);\nTEST(vec.at(2) == 57);\n</code></pre>\n<p>Another issue with your design is that “generic” iterators make no sense. Iterators are tightly bound to containers (or views, or other such things). You can’t simply make an iterator that just works with any container. Indeed the <em>only</em> standard containers your iterator works with are <code>std::vector</code> and <code>std::array</code>. For all other containers, it will trigger UB.</p>\n<p>And finally, if you want this type to be an actual (input) iterator, you need to add some extra typedefs, modify the existing typedefs, and fix some problems in your dereferencing operators.</p>\n<p>But honestly, I would suggest just throwing the whole thing out, because:</p>\n<ol>\n<li>It’s poorly conceived (it is trying to be a concrete implementation of an abstract idea).</li>\n<li>It’s dangerously buggy (it only works with certain containers).</li>\n<li>It’s unnecessary (if you want an input iterator, there are already input iterators in the standard).</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T23:51:58.020", "Id": "501406", "Score": "0", "body": "Put the summary first." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-03T17:25:02.877", "Id": "501449", "Score": "0", "body": "Amazing and very deep explaination. Thank you a lot. In fact, I was very confused - and I realized (thanks to your answer) that whatever I attempted to do was actual nonsense.Thanks for your time!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-04T02:42:35.407", "Id": "501502", "Score": "0", "body": "Very nice and thorough! I'll just add to \"[an iterator] does need difference_type and iterator_category\" that these are not required in the iterator class. Pointers don't have them and still work as iterators. How? [The standard notes](http://eel.is/c++draft/iterator.requirements#general-note-1): *Either the iterator type must provide the typedef-names directly (in which case iterator_­traits pick them up automatically), or an iterator_­traits specialization must provide them.*" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-14T14:34:32.867", "Id": "525496", "Score": "0", "body": ">> In fact, the code above will not work for any container except std::vector.\nWhat about std::string, std::array and std::span?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-30T15:35:20.420", "Id": "526592", "Score": "0", "body": "`std::input_iterator` is very much a thing in the standard library - it's an implementation of the abstract concept as a C++20 concept. Doesn't change that OP is misguided, but does make the beginning of your answer false." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-08-30T20:49:05.807", "Id": "526600", "Score": "0", "body": "`std::input_iterator` is a “thing” but it is not an implementation of “input iterator”. The easiest proof of that is to ask: Does `std::input_iterator` satisfy the `std::input_iterator` concept? No? Then it is not an input iterator." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T21:35:59.653", "Id": "254244", "ParentId": "254228", "Score": "13" } } ]
{ "AcceptedAnswerId": "254244", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-02T17:48:09.180", "Id": "254228", "Score": "2", "Tags": [ "c++", "iterator" ], "Title": "Input Iterator implementation" }
254228