body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I would like to optimize the way that I save files.</p> <p>Each second I save lots of strings in different files. What I want to do is bunch up these IO tasks so they happen in bursts, instead of spread out randomly.</p> <p>I want to write files, but without performing too many IO operations at the same time, so I don't put the disk at 100% of I/O-used.<br /> (I'm specially using a Raspberry/HDD).</p> <p>Currently, I made this code :</p> <pre class="lang-java prettyprint-override"><code>public class FileSaverTimer implements Runnable { public static final int MAX_RUNNING = 10, SKIP_WHEN_ALREADY = 2; private static List&lt;FileSaverAction&gt; allActions = new ArrayList&lt;&gt;(); public static void addAction(FileSaverAction action) { allActions.add(action); } private int actionRunning = 0; @Override public void run() { if(actionRunning &gt; SKIP_WHEN_ALREADY) return; // too many already running, skipping... for(int i = actionRunning; i &lt; Math.min(MAX_RUNNING, allActions.size()); i++) { FileSaverAction action = allActions.remove(0); // removing first item actionRunning++; // adding a running task action.save(() -&gt; actionRunning--); // save, and when it's finished removing running task } } public static interface FileSaverAction { /** * Technically save the save sync with the thread which run this * * @param finished the action to run when it's finished */ void save(FileSaverFinished finished); } public static interface FileSaverFinished { /** * The action that will be called when the action is finished. */ void finish(); } } </code></pre> <p>Then, to use:</p> <pre class="lang-java prettyprint-override"><code>FileSaverTimer.addAction((finished) -&gt; { try { Files.write(file, content.getBytes(), StandardOpenOption.APPEND); } catch (IOException e) { e.printStackTrace(); } finished.finish(); }); </code></pre> <p>There is only one instance of the timer which runs asynchronously each second; it's called like this:</p> <pre class="lang-java prettyprint-override"><code>Bukkit.getScheduler().runTaskTimerAsynchronously(this, new FileSaverTimer(), 20, 20); // 20 ticks = 1 second </code></pre> <p>The objective is to add files in a queue, and wait until previous tasks are done. But I don't know how I should define limits <code>SKIP_WHEN_ALREADY</code> and <code>MAX_RUNNING</code>, or if it's really relevant.</p> <p>Some informations :</p> <ul> <li>This code works. <em>(I'm sure I can do better)</em></li> <li>Some files can be back in the queue quickly with other information. <em>(I can know which are more likely to come back.)</em></li> <li>It's not necessary to save stuff as soon as possible. <em>(Everything stays in RAM.)</em></li> </ul> <p>So, can you help me to do better? Specially to work better according to user hardware?</p> <p>Is it better to make lots of little file saves (just a few lines each), or only one big save?</p> <p>Also, I want to know if you suggest another structure. I just proposed my code as a baseline!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T19:24:19.610", "Id": "531076", "Score": "2", "body": "You're using a static, non thread safe collection across all instances of your saver class, however the actionsRunning is non-static. Are you expecting access from multiple threads/instances? How are instances of the timer being created/what is invoking the run method?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T19:33:18.863", "Id": "531077", "Score": "0", "body": "There is only one instance of the timer that is running, it's static to make is faster to register file to save. They all will be used only by one instance of this thread" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T14:56:53.303", "Id": "531143", "Score": "1", "body": "Can you share a bit more details about what kind of optimization are you looking for? Have you identified problems with your current approach, for example bottlenecks, or low throughput, or others. How would you measure the success of optimizations?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T15:44:03.877", "Id": "531144", "Score": "0", "body": "@janos I just edit my question to explain it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T16:48:26.843", "Id": "531149", "Score": "1", "body": "Welcome to Code Review! \"_without making the disk at 100%_\" - is that 100% used space? or something else?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T16:51:18.927", "Id": "531150", "Score": "1", "body": "No, 100% of used performance, not space. Not taking all power of disk and so impact other files/apps. But thanks :)" } ]
[ { "body": "<p>I'm probably not polished enough with Java to propose new code, so here are some abstract thoughts anyone else can use:</p>\n<ul>\n<li>Fewer bigger writes will generally be more efficient. Disk access is heavily optimized at the OS level, and those optimizations will work best if the <em>number</em> of things you're doing (from the disk's perspective) is smaller.</li>\n<li>It seems likely that you have more abstraction here than you need. Do you expect to need the lambdas/inversion-of-control pattern you're using? The less fancy approach would be to make <code>FileSaverAction</code> an actual class. Its constructor would take in the <code>file</code> and <code>content</code> values, its <code>save</code> method would take in the <code>FileSaverTimer</code> who's <code>actionRunning</code> needs to be decremented. This may be a little more verbose, but I think it will help with other optimizations.</li>\n<li>Reading and writing to disk is often heavy, but <em>opening</em> and <em>closing</em> files is also heavy. It sounds like you expect many of these writes to be to the same files; consider batching them. I think roughly how that would work is that you'd replace the <code>List</code> <code>allActions</code> with some kind of mapping (a default-dict?) from <code>file</code>s to lists of <code>contents</code>s. To handle an item, you'd open the file, do all of the writes, and then close it. Depending what the distribution of expected incoming file-write tasks is like, you could even maintain a pool of open file handles.</li>\n<li>Check the buffering settings on the file-manipulation methods you use. Exact tuning is probably hard, but it's worth checking if the defaults are sane for your situation.</li>\n</ul>\n<p>Some less abstract stuff:</p>\n<ul>\n<li><code>allActions</code> can and probably should be <code>final</code>. (The list can <em>change</em>, but it will always be the <em>same list</em>.)</li>\n<li>Since you're relying on there only ever being one <code>FileSaverTimer</code>, you should explicitly use the <a href=\"https://www.geeksforgeeks.org/singleton-class-java/\" rel=\"nofollow noreferrer\">Singleton</a> pattern.</li>\n<li>The <code>for</code> loop looks sketchy as written. Probably something like this would be better:</li>\n</ul>\n<pre class=\"lang-java prettyprint-override\"><code>for(int i = actionRunning; allActions.hasNext() &amp;&amp; i &lt; MAX_RUNNING); i++) {\n</code></pre>\n<p>Actually, as I think more about <code>MAX_RUNNING</code> and <code>SKIP_WHEN_ALREADY</code>, the less I like them.<br />\nAs I understand, you need <code>MAX_RUNNING</code> because you want these bursts of IO to not be too big. (It's still not clear that this should matter, but that's on you.) You need <code>SKIP_WHEN_ALREADY</code> because, if sessions of <code>run</code> are taking longer than a second, you don't want them overlapping too much.<br />\nBut any overlap is probably &quot;too much&quot;! At best, multiple sessions of <code>run</code> acting on <code>allActions</code> and <code>actionRunning</code> at the same time will be <em>redundant</em>, but depending how <code>runTaskTimerAsynchronously</code> works, you could have really bad concurrency issues.<br />\nA better approach would probably be to check if there's an active session of <code>run</code>, and if there is then somehow <em>increase</em> its &quot;burst budget&quot; and abort the new <code>run</code>.</p>\n<p>One subject I haven't gotten into, because I don't know if it'll work for your context, is parallelization of the IO tasks. If multi-threading <em>is</em> an option, that would probably let you get the same amount of IO work done in a shorter denser burst. But I don't know if that would be good for you, and it'll be an entirely different design than what you're working on now.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T15:55:58.470", "Id": "534148", "Score": "0", "body": "Thanks for your answer. It's a good idea to remove the abstract class which isn't very usefull. Also, about file handle, do you suggest to keep them for long time, or close them like each minutes to don't overflow with too many files handle ? For you final question, I don't want to make lot of thread for those type of I/O because they are not very important one. I prefer l'ose tome than make lot of thread (and my project already use lot of thread)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T23:51:48.417", "Id": "534195", "Score": "0", "body": "Having too many files open at once is a problem (what problems does it cause? I don't know. Probably just bad performance). How many is too many? I don't know. Keeping any single file handle (that you still expect to use) open for a long time probably isn't a problem, except that you can't assume the data is \"really there\" until it's closed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T23:56:48.743", "Id": "534196", "Score": "0", "body": "If you determined that recycling open file handles will be advantageous, and you figure out some number you don't want to exceed, a simple strategy (from cache theory) that would probably work would be: Have a pool of open connections. Don't close connections after you use them. When you need to open a file that's not already in the pool (and the pool has reached its max size), close the least-recently-used connection in the pool to make room. Someone else can point out all the problems with this strategy :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-29T08:00:05.937", "Id": "534202", "Score": "0", "body": "Ok thanks for all informations ! Also don't worry, I don't forget for check & bounty, I think I will apply them tomorrow (after testing what you said)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-28T04:48:46.823", "Id": "270462", "ParentId": "269206", "Score": "4" } } ]
{ "AcceptedAnswerId": "270462", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-20T18:45:53.070", "Id": "269206", "Score": "5", "Tags": [ "java", "performance", "file-system", "io" ], "Title": "Optimized way to save list of files" }
269206
<p>I am reinventing the wheel to write a function that serializes a (nested) data structure human readably. The default output is deliberately similar to that of <code>json.dumps(var, indent=4)</code>, and I did my best to mimic the format of <code>json</code>s output.</p> <p>But the output is fundamentally different from <code>json</code>. More specifically, the data types of the dictionary keys are preserved and all data types that can be valid dictionary keys are unchanged. For instance, <code>int</code> keys won't become <code>str</code> and <code>tuple</code> keys are allowed in this format whereas in <code>json</code> <code>tuple</code> keys are impossible. And dictionary keys aren't indented, because I don't use nested data structures as keys.</p> <p>And all the values and/or elements retain their data types, for instance <code>True</code>, <code>False</code>, <code>None</code> won't become <code>true</code>, <code>false</code>, <code>null</code>.</p> <p>I built my function using <code>repr</code>, but this is not <code>repr</code>. <code>repr</code> supports all data types defined in one section and the output is not indented, and the data types of the containers themselves are unchanged. But this function doesn't support all data types defined in one section and instead support only the builtin container data types <code>(dict, frozenset, list, set, tuple)</code> and their subclasses. The containers are &quot;promoted&quot; to the data type in the supported data types which they inherited from. Only the data types that aren't considered containers (the data types that can't be nested) are retained. And the output is far more human readable than <code>repr</code>.</p> <p>I wrote this function to serialize nested dictionaries with <code>int</code> and <code>tuple</code> keys human readably, to store the data on the hard drive, so that I can load them later using <code>ast.literal_eval</code>. I want to allow <code>int</code> keys and I have to store <code>dict</code>s with <code>tuple</code> keys.</p> <h2>Code</h2> <pre class="lang-py prettyprint-override"><code>from typing import Union def represent(obj: Union[dict, frozenset, list, set, tuple], indent: int=4) -&gt; str: supported = (dict, frozenset, list, set, tuple) singles = (frozenset, list, set, tuple) if not isinstance(obj, supported): raise TypeError('argument `obj` should be an instance of a built-in container data type') if not isinstance(indent, int): raise TypeError('argument `indent` should be an `int`') if indent &lt;= 0: raise ValueError('argument `indent` should be greater than 0') if indent % 4: raise ValueError('argument `indent` should be a multiple of 4') ls = list() if isinstance(obj, dict): start, end = '{}' for k, v in sorted(obj.items()): if not isinstance(v, supported): item = ' '*indent + repr(k) + ': ' + repr(v) else: item = ' '*indent + repr(k) + ': ' + represent(v, indent+4) ls.append(item) elif isinstance(obj, singles): enclosures = { 0: ('frozenset({', '})'), 1: '[]', 2: '{}', 3: '()' } index = 0 for i in singles: if isinstance(obj, i): break index += 1 start, end = enclosures[index] if index in (0, 2): obj = sorted(obj) for i in obj: if not isinstance(i, supported): item = ' '*indent + repr(i) else: item = represent(i, indent+4) ls.append(item) return start + '\n' + ',\n'.join(ls) + '\n' + ' ' * (indent - 4) + end </code></pre> <h1>Example</h1> <pre class="lang-py prettyprint-override"><code>import json var = {1: {1: {1: {1: {1: {1: 0}, 2: 0}, 2: {1: 0}, 3: 0}, 2: {1: {1: 0}, 2: 0}, 3: {1: 0}}, 2: {1: {1: {1: 0}, 2: 0}, 2: {1: 0}, 3: 0}, 3: {1: {1: 0}, 2: 0}}, 2: {1: {1: {1: {1: 0}, 2: 0}, 2: {1: 0}, 3: 0}, 2: {1: {1: 0}, 2: 0}, 3: {1: 0}}, 3: {1: {1: {1: 0}, 2: 0}, 2: {1: 0}, 3: 0}} dumped = json.dumps(var, indent=4) repred = represent(var) print('dumped:') print(dumped) print('repred:') print(repred) print(f'{(eval(dumped) == var)=}') print(f'{(eval(repred) == var)=}') var1 = {'a': {'a': {'a': [0, 0, 0], 'b': [0, 0, 1], 'c': [0, 0, 2]}, 'b': {'a': [0, 0, 1], 'b': [0, 1, 1], 'c': [0, 1, 2]}, 'c': {'a': [0, 0, 2], 'b': [0, 1, 2], 'c': [0, 2, 2]}}, 'b': {'a': {'a': [0, 0, 1], 'b': [0, 1, 1], 'c': [0, 1, 2]}, 'b': {'a': [0, 1, 1], 'b': [1, 1, 1], 'c': [1, 1, 2]}, 'c': {'a': [0, 1, 2], 'b': [1, 1, 2], 'c': [1, 2, 2]}}, 'c': {'a': {'a': [0, 0, 2], 'b': [0, 1, 2], 'c': [0, 2, 2]}, 'b': {'a': [0, 1, 2], 'b': [1, 1, 2], 'c': [1, 2, 2]}, 'c': {'a': [0, 2, 2], 'b': [1, 2, 2], 'c': [2, 2, 2]}}} print(represent(var1)) </code></pre> <pre><code>dumped: { &quot;1&quot;: { &quot;1&quot;: { &quot;1&quot;: { &quot;1&quot;: { &quot;1&quot;: { &quot;1&quot;: 0 }, &quot;2&quot;: 0 }, &quot;2&quot;: { &quot;1&quot;: 0 }, &quot;3&quot;: 0 }, &quot;2&quot;: { &quot;1&quot;: { &quot;1&quot;: 0 }, &quot;2&quot;: 0 }, &quot;3&quot;: { &quot;1&quot;: 0 } }, &quot;2&quot;: { &quot;1&quot;: { &quot;1&quot;: { &quot;1&quot;: 0 }, &quot;2&quot;: 0 }, &quot;2&quot;: { &quot;1&quot;: 0 }, &quot;3&quot;: 0 }, &quot;3&quot;: { &quot;1&quot;: { &quot;1&quot;: 0 }, &quot;2&quot;: 0 } }, &quot;2&quot;: { &quot;1&quot;: { &quot;1&quot;: { &quot;1&quot;: { &quot;1&quot;: 0 }, &quot;2&quot;: 0 }, &quot;2&quot;: { &quot;1&quot;: 0 }, &quot;3&quot;: 0 }, &quot;2&quot;: { &quot;1&quot;: { &quot;1&quot;: 0 }, &quot;2&quot;: 0 }, &quot;3&quot;: { &quot;1&quot;: 0 } }, &quot;3&quot;: { &quot;1&quot;: { &quot;1&quot;: { &quot;1&quot;: 0 }, &quot;2&quot;: 0 }, &quot;2&quot;: { &quot;1&quot;: 0 }, &quot;3&quot;: 0 } } repred: { 1: { 1: { 1: { 1: { 1: { 1: 0 }, 2: 0 }, 2: { 1: 0 }, 3: 0 }, 2: { 1: { 1: 0 }, 2: 0 }, 3: { 1: 0 } }, 2: { 1: { 1: { 1: 0 }, 2: 0 }, 2: { 1: 0 }, 3: 0 }, 3: { 1: { 1: 0 }, 2: 0 } }, 2: { 1: { 1: { 1: { 1: 0 }, 2: 0 }, 2: { 1: 0 }, 3: 0 }, 2: { 1: { 1: 0 }, 2: 0 }, 3: { 1: 0 } }, 3: { 1: { 1: { 1: 0 }, 2: 0 }, 2: { 1: 0 }, 3: 0 } } (eval(dumped) == var)=False (eval(repred) == var)=True { 'a': { 'a': { 'a': [ 0, 0, 0 ], 'b': [ 0, 0, 1 ], 'c': [ 0, 0, 2 ] }, 'b': { 'a': [ 0, 0, 1 ], 'b': [ 0, 1, 1 ], 'c': [ 0, 1, 2 ] }, 'c': { 'a': [ 0, 0, 2 ], 'b': [ 0, 1, 2 ], 'c': [ 0, 2, 2 ] } }, 'b': { 'a': { 'a': [ 0, 0, 1 ], 'b': [ 0, 1, 1 ], 'c': [ 0, 1, 2 ] }, 'b': { 'a': [ 0, 1, 1 ], 'b': [ 1, 1, 1 ], 'c': [ 1, 1, 2 ] }, 'c': { 'a': [ 0, 1, 2 ], 'b': [ 1, 1, 2 ], 'c': [ 1, 2, 2 ] } }, 'c': { 'a': { 'a': [ 0, 0, 2 ], 'b': [ 0, 1, 2 ], 'c': [ 0, 2, 2 ] }, 'b': { 'a': [ 0, 1, 2 ], 'b': [ 1, 1, 2 ], 'c': [ 1, 2, 2 ] }, 'c': { 'a': [ 0, 2, 2 ], 'b': [ 1, 2, 2 ], 'c': [ 2, 2, 2 ] } } } </code></pre> <p>I am mainly concerned about performance and memory consumption, and I want the function to execute as fast as possible while utilizing as little RAM as possible. How can it be more efficient?</p> <h2>Update</h2> <p>Actually sorting the items while serializing the dictionaries does introduce bugs that somehow change the data represented, breaking the original association between the key value pairs, and this is definitely not intended.</p> <p>Removing the <code>sorted</code> calls eliminates the bug, I have fixed my copy of the code but as this is code review and I have received answers I won't edit code posted above (lest the update be rolled back), so I decided to point this out.</p> <p>More specifically,</p> <p>This snippet:</p> <pre class="lang-py prettyprint-override"><code>if isinstance(obj, dict): start, end = '{}' for k, v in sorted(obj.items()): if not isinstance(v, supported): item = ' '*indent + repr(k) + ': ' + repr(v) else: item = ' '*indent + repr(k) + ': ' + represent(v, indent+4) ls.append(item) </code></pre> <p><em><strong>MUST</strong></em> be changed to:</p> <pre class="lang-py prettyprint-override"><code>if isinstance(obj, dict): start, end = '{}' for k, v in obj.items(): if not isinstance(v, supported): item = ' '*indent + repr(k) + ': ' + repr(v) else: item = ' '*indent + repr(k) + ': ' + represent(v, indent+4) ls.append(item) </code></pre> <p>I now think sorting the collections while serializing them to be a terrible practice, but I don't know if this bug also affects nested <code>frozenset</code>s too (<code>set</code>s can't be nested because <code>set</code>s are mutable therefore unhashable), I haven't tested yet, but I recommend dropping the <code>sorted</code> calls on <code>frozenset</code> and <code>set</code> too (<code>frozenset</code>s can be nested inside <code>set</code>s and <code>frozenset</code>s).</p> <h2>Update</h2> <hr /> <p>Please review the latest version: <a href="https://codereview.stackexchange.com/questions/269247/serializing-nested-data-structures-in-a-human-readable-format-with-all-bugs-fi">Serializing (nested) data structures in a human-readable format with all bugs fixed</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T08:15:11.377", "Id": "531181", "Score": "0", "body": "One small remark: if each level of indent has the same offset (in your case 4 characters per indent), then I would abstract that number of characters away. For example, rename the `indent` parameter of the `respresent` function to `indentLevel` or `indentCount` or something along those lines, and define a function `createIndent(indentLevel: int) -> str` which returns `' ' * 4 * indentLevel`. (Naming is perhaps not the best yet, but you get the idea). Then replace all `' '*indent` in your code by a call to that function, or call the function once and store the result in a variable." } ]
[ { "body": "<p>A few things I noticed:</p>\n<hr />\n<p>Since <code>supported</code> is a superset of <code>singles</code> I would recommend the following assignment:</p>\n<pre><code>singles = (frozenset, list, set, tuple)\nsupported = (dict, *singles)\n</code></pre>\n<p>This of course only makes sense if the two are also logically connected which I'd say is true here.</p>\n<hr />\n<p>The assignment <code>start, end = '{}'</code> seems unintuitive to me, since string-unpacking isn't commonly used as far as I know.</p>\n<p>I'd recommend <code>start, end = '{', '}'</code> if you want to stick to the one-liner or even better:</p>\n<pre><code>start = '{'\nend = '}'\n</code></pre>\n<hr />\n<p>When traversing the nested data structures you always call your function with <code>indent=indent + 4</code>, regardless of the desired indent by the user. You should probably adjust that to match the user's preference (you might also want to allow indents that are not divisible by 4, e.g. indent-increments of 2 might be sensible for data structures with a lot of layers). For this you'll need to keep track of the indent-step as well as the total indentation amount.</p>\n<hr />\n<pre><code>if isinstance(obj, dict):\n start = '{'\n end = '}'\n for k, v in sorted(obj.items()):\n if not isinstance(v, supported):\n item = ' ' * indent + repr(k) + ': ' + repr(v)\n else:\n item = ' ' * indent + repr(k) + ': ' + represent(v, indent + 4)\n ls.append(item)\n</code></pre>\n<p>I don't see a particular reason to sort the key-value-pairs from the dictionary. On the contrary, since dicts in Python now preserve insertion order, this might actually change the data. So I'd drop the call to <code>sorted()</code> if you don't have an explicit reason for it.</p>\n<hr />\n<p>I find this pattern</p>\n<pre><code>if not condition:\n # do A\nelse:\n # do B\n</code></pre>\n<p>to usually be better expressed as</p>\n<pre><code>if condition:\n # do B\nelse:\n # do A\n</code></pre>\n<p>or in your case:</p>\n<pre><code>for k, v in obj.items():\n if isinstance(v, supported):\n item = ' ' * indent + repr(k) + ': ' + represent(v, indent + 4)\n else:\n item = ' ' * indent + repr(k) + ': ' + repr(v)\n ls.append(item)\n</code></pre>\n<hr />\n<p>This whole snippet</p>\n<pre><code>enclosures = {\n 0: ('frozenset({', '})'),\n 1: '[]',\n 2: '{}',\n 3: '()'\n}\n\nindex = 0\nfor i in singles:\n if isinstance(obj, i):\n break\n index += 1\nstart, end = enclosures[index]\n</code></pre>\n<p>is unnecessarily complicated, hard to read and rather un-pythonic. I see no particular reason to use indices instead of the types themselves:</p>\n<pre><code>enclosures = {\n frozenset: ('frozenset({', '})'),\n list: ('[', ']'),\n set: ('{', '}'),\n tuple: ('(', ')')\n}\n\nstart, end = enclosures[type(obj)]\n</code></pre>\n<p>I would also remove this from the <code>elif</code>-case and add a dict-entry for <code>dict: ('{', '}')</code>, so you don't need to assign <code>start, end</code> in every case.</p>\n<p><strong>EDIT:</strong>\nAs correctly pointed out in the comments, this will not work for objects that are instances of subclasses of the supported classes.</p>\n<p>The following adaptation will work, while still getting rid of the (otherwise meaningless) indices, thereby making the approach less error-prone:</p>\n<pre><code>for cls, enclosure in enclosures.items():\n if isinstance(obj, cls):\n start, end = enclosure\n break\n\n# or\n\nfor cls in enclosures.keys():\n if isinstance(obj, cls):\n start, end = enclosures[cls]\n break\n</code></pre>\n<p>Another approach would be using</p>\n<pre><code>inspect.getmro(obj.__class__)\n</code></pre>\n<p>which returns a <code>tuple</code> of the object's class and all superclasses (in reverse hierarchical order as far as I can tell).</p>\n<hr />\n<p>This code snippet should not check magic numbers:</p>\n<pre><code>if index in (0, 2):\n obj = sorted(obj)\n</code></pre>\n<p>Instead you should have a mapping of supported datatypes to a <code>sort</code> flag, which then decides if you sort the collection. Again, you should consider whether you actually need / want to sort these collections.</p>\n<hr />\n<p>Most of your string assignments lend themselves nicely to using f-strings:</p>\n<pre><code>item = ' ' * indent + repr(k) + ': ' + represent(v, indent + 4)\n</code></pre>\n<p>becomes</p>\n<pre><code>item = f&quot;{' ' * indent}{k!r}: {represent(v, indent + 4)}&quot;\n</code></pre>\n<hr />\n<p>As of now you're explicitly checking and handling all supported datatypes in a single function. You might want to consider introducing seperate functions for different (kinds of) data types. This would make your main function more concise and easier to extend.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T11:15:39.667", "Id": "531122", "Score": "0", "body": "Your `enclosures[type(obj)]` will only work if objects are exactly the super types contained in the `dict`. Many objects are subclassed from the base classes, for instance, `Counter` and `defaultdict` objects are instances of `dict`, but they aren't of the `dict` type, so trying to get the value using the type directly will very likely raise `KeyError`. And I did mention I use this function to serialize nested data structures, most frequently nested dictionary, and I always use `defaultdict` for convenience." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T12:46:07.183", "Id": "531128", "Score": "0", "body": "Yes, good point! I added an adjusted approach to my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T22:41:02.163", "Id": "531172", "Score": "1", "body": "`f'{repr(k)}'` can be replaced with `f'{k!r}'`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T09:58:26.703", "Id": "269221", "ParentId": "269214", "Score": "10" } }, { "body": "<h1>Bugs</h1>\n<h2>Sets</h2>\n<p>Sets and dictionaries use identical delimiters: <code>{ ... }</code>. Dictionaries are distinguished from sets by the presence of colon (<code>:</code>) separated key-value pairs.</p>\n<p>Problem: Both an empty set and an empty dictionary are rendered by your code as <code>{}</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; eval(represent(set()))\n{}\n\n&gt;&gt;&gt; eval(represent(set())) == set()\nFalse\n</code></pre>\n<h2>Tuples</h2>\n<p>A tuple is a comma-separated list of values in parenthesis.</p>\n<p>Problem: <code>(1)</code> is a Python expression evaluating to <code>1</code>, not a tuple; the Python syntax requires a trailing comma <code>(1,)</code> to ensure this is interpreted as a tuple.</p>\n<pre class=\"lang-py prettyprint-override\"><code>eval(represent((1,)))\n1\n\neval(represent((1,))) == (1,)\nFalse\n</code></pre>\n<h1>Conclusion</h1>\n<p>Your test cases are large, complex objects, but are missing important edge cases like:</p>\n<ul>\n<li>empty sets,</li>\n<li>empty tuples,</li>\n<li>single element tuples,</li>\n<li>string elements containing single &amp; double quotes, backslashes,</li>\n<li>...</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T16:57:03.173", "Id": "531151", "Score": "0", "body": "Well, I have to admit these things do have a potential to cause problems, they can only cause minor problems. I can't imagine why anyone would want to use my function to dump those extremely simple objects as strings rather than use those short expressions directly, I intend my function to dump complex objects and it does that well, and clearly I can't cover all possible use cases..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T17:06:21.673", "Id": "531153", "Score": "3", "body": "A complex object may contain extremely simple elements, such as a dictionary of sets, where one of those sets happens to be empty, or a dictionary of tuples where some of those tuples might be of length 1. In these cases an empty set would become an empty dictionary, which is not a problem if the recovered value is only read/tested and never modified. The single element tuple becoming just the element is a problem, since a level of nesting has vanished, so code reading in the complex object will break using that element of the complex object." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T17:09:52.290", "Id": "531154", "Score": "4", "body": "*...clearly I can't cover all possible use cases...*. Those are not different use cases, but edge cases (as @AJNeufeld points out in his answer). Designing for certain use cases and therefore ignoring other cases is fine, while ignoring edge cases can (and will) usually lead to problems in most use cases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T17:40:03.233", "Id": "531156", "Score": "2", "body": "Simple test cases are designed to ensure a failure in an edge case is understandable. I could have given `var = {(1,2): ({\"doesn't work\": set()},)}`, and `eval(represent(var)) == var` would return `False`, but it wouldn't be clear what the problem was. Is it the tuple used as the dictionary key, the tuple value, the string key with the embedded single quote, or the set value? `len(var[1,2][0][\"doesn't work\"])` is a valid expression, but with `res = eval(represent(var))` the equivalent expression `len(res[1,2][0][\"doesn't work\"])` raises an exception: bonus points if you can guess exactly what." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T16:19:38.860", "Id": "269232", "ParentId": "269214", "Score": "5" } } ]
{ "AcceptedAnswerId": "269221", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T07:13:40.937", "Id": "269214", "Score": "4", "Tags": [ "python", "performance", "python-3.x", "reinventing-the-wheel", "serialization" ], "Title": "Serializing (nested) data structures in a human-readable format" }
269214
<p>I am/we are using the observer pattern for many things in our application. I think it's time to create a reusable base class for these situations. Most implementations I could find only do something like this:</p> <blockquote> <pre><code>class Subject { public: void AttachObserver(Observer* observer) { observers.push_back(observer); } ... }; </code></pre> </blockquote> <p>I would prefer to be able to attach a callback function instead of a class. I came up with this:</p> <pre><code>namespace Observe { using ObserverID = uint64_t; template&lt;typename... callback_arg_types&gt; class Obserable { public: using CallbackFunction = std::function&lt;void(callback_arg_types...)&gt;; public: ObserverID AttachObserver(CallbackFunction callback) { std::unique_lock&lt;std::mutex&gt; block(_mutex); const auto id = GetNewID(); _observers.emplace(id, std::move(callback)); return(id); } bool DetachObserver(ObserverID&amp; id) { std::unique_lock&lt;std::mutex&gt; block(_mutex); const auto it = _observers.find(id); if (it == _observers.end()) { return(false); } _observers.erase(it); id = ObserverID(); return(true); } protected: void NotifyAllObservers(callback_arg_types... args) { std::unique_lock&lt;std::mutex&gt; block(_mutex); for (const auto&amp; observer : _observers) { observer.second(args...); } } private: ObserverID GetNewID() { static ObserverID id = 0; return(++id); } std::mutex _mutex; std::unordered_map&lt;ObserverID, CallbackFunction&gt; _observers; }; } </code></pre> <p>Usage:</p> <pre><code>using namespace Observe; class IntPublisher : public Obserable&lt;int&gt; { public: void Publish(int number) { NotifyAllObservers(number); } }; IntPublisher publisher; ObserverID id = publisher.AttachObserver([](int number)-&gt;void{ std::cout &lt;&lt; number &lt;&lt; std::endl; }); publisher.Publish(42); publisher.DetachObserver(id); </code></pre> <p>I don't like the ObserverID. I know I will never run out of ids, but I think there must be a more elegant solution to get a reference/handle to the attached observer/callback function (so that it can be detached later).</p> <p>I would appreciate comments, corrections, criticism and suggestions.</p>
[]
[ { "body": "<p>I have mainly worked on the ObserverID part. I agree with you on one point, it is rather <em>artificial</em>, when we know that C++ functions are hashable, so you could use the hash as ID. A point we must be aware is that <code>std::function</code> objects are not hashable (do not ask me why...) or at least I cannot hash them but <a href=\"https://stackoverflow.com/q/20692790/3545273\">others could not either</a></p>\n<p>For that reason, I would advise you to use plain function pointers instead of wrapping them into <code>std::function</code> objects: they add no functionality, at least no that you currently use, nor any I can imagine, and prevent hashing.</p>\n<p>Additionaly, plain function pointers avoid the artificial by value parameter in <code>AttachObserver</code>. It was required because you wanted to be able to pass a lambda or plain function, and they have to be converted to a <code>std::function</code>. But as soon as you get a function pointer everything gets smooth. And it does not change the way the methods are used.</p>\n<p>It has an additional feature: it prevents adding the same observer function more than once. If you really wanted that, you would just have to wrap the additional calls in lambdas.</p>\n<p>You also have a useless <code>id = ObserverID();</code> in <code>DetachObserver</code>, that you should remove.</p>\n<p>Here is the changed code:</p>\n<pre><code>namespace Observe\n{\n using ObserverID = std::size_t; // the result of hashing\n\n template&lt;typename... callback_arg_types&gt;\n class Obserable\n {\n public:\n using CallbackFunction = void(*)(callback_arg_types...); // plain function pointer\n\n public:\n ObserverID AttachObserver(CallbackFunction callback)\n {\n std::unique_lock&lt;std::mutex&gt; block(_mutex);\n ObserverID id = getID(callback);\n _observers.emplace(id, callback);\n return id;\n }\n\n ...\n\n private:\n\n ObserverID getID(void (*callback)(callback_arg_types...)) {\n typedef void (*func_type) (callback_arg_types...);\n static std::hash&lt;func_type&gt; hash;\n const ObserverID id = hash(callback);\n return id;\n }\n std::mutex _mutex;\n std::unordered_map&lt;ObserverID, CallbackFunction&gt; _observers;\n };\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T07:22:33.830", "Id": "531180", "Score": "0", "body": "I don't usually like simple function pointers. But this is a really elegant way. Thanks a lot for that! As for id = ObserverID(), it's supposed to reset the ID. I use it as a kind of cleanup strategy so that the client is not left with junk." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T16:40:13.787", "Id": "531203", "Score": "0", "body": "Well, for `std::function` to be hashable, someone has to implement it, and its relationship to hashability of any kind of invokable. Then they must document it, and submit it for standardization. It would be an ABI-change if the hash-code of the invokable should be returned, as that must be retrieved, meaning one more callback." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T04:17:42.057", "Id": "531311", "Score": "0", "body": "Primary reason for `std::function` not being hashable is that it is completely meaningless. It has no equality operator! What would you ever do with hashing if there is no way to compare them in the first place? And it is impossible to implement comparison operator without adding restrictions to the wrapping capabilities of the class." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T14:54:35.190", "Id": "269225", "ParentId": "269217", "Score": "0" } }, { "body": "<p>A few minor things:</p>\n<p><code>return(false);</code> etc.<br />\nDon't put extra parens around the return value. <code>return</code> is not a function call. It is good that it looks different from a function call since it stands out better as a different kind of thing. When you start using templates and implicit types (like <code>auto</code>) and automatic move (rather than copy) of local variables, <strong>it <em>does</em> change the meaning!</strong> Get out of that habit.</p>\n<p><a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#slio50-avoid-endl\" rel=\"nofollow noreferrer\">⧺SL.io.50</a> Don't use <code>endl</code>.</p>\n<p><code>std::unique_lock&lt;std::mutex&gt; block(_mutex);</code><br />\nYou can rely on class template argument deduction and not specify the type here. This makes the code easier to maintain, as when you change the exact type of <code>_mutex</code> then you don't have to go change every single usage as well!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T15:58:14.493", "Id": "269229", "ParentId": "269217", "Score": "0" } } ]
{ "AcceptedAnswerId": "269225", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T08:37:40.330", "Id": "269217", "Score": "0", "Tags": [ "c++", "callback", "observer-pattern" ], "Title": "C++ Observer Pattern with std::function" }
269217
<p>I have been working on this question, <a href="https://open.kattis.com/problems/sequences" rel="nofollow noreferrer">https://open.kattis.com/problems/sequences</a>.</p> <blockquote> <p>You are given a sequence, in the form of a string with characters ‘0’, ‘1’, and ‘?’ only. Suppose there are <em>n</em> ‘?’s. Then there are 2ⁿ ways to replace each ‘?’ by a ‘0’ or a ‘1’, giving 2ⁿ different 0-1 sequences (0-1 sequences are sequences with only zeroes and ones).</p> <p>For each 0-1 sequence, define its number of inversions as the minimum number of adjacent swaps required to sort the sequence in non-decreasing order. In this problem, the sequence is sorted in non-decreasing order precisely when all the zeroes occur before all the ones. For example, the sequence 11010 has 5 inversions. We can sort it by the following moves: 11010 → 11001 → 10101 → 01101 → 01011 → 00111.</p> <p>Find the sum of the number of inversions of the 2ⁿ sequences, modulo 1000000007 (10⁹+7).</p> <p><strong>Input</strong><br /> The first and only line of input contains the input string, consisting of characters ‘0’, ‘1’, and ‘?’ only, and the input string has between 1 to 500000 characters, inclusive.</p> <p><strong>Output</strong><br /> Output an integer indicating the aforementioned number of inversions modulo 1000000007</p> </blockquote> <p>In summary, I am given a string of 1s, 0s, and ?s. All question marks are basically variables that can become 1s and 0s. In each case, I have to sum up the minimum number of inversions (a swap of two adjacent characters), needed to sort the string into non-decreasing order, i.e, all 0s before 1s. For example, 0?1? has four cases: 0010, 0011, 0110, and 0111, and need 1, 0, 2, and 0 inversions respectively, summing up to 3. I am able to get the answer right however my code is too slow:</p> <pre><code>string = input() zero = 0 # is the number of 0's total = 0 # total number of inversions questions = 0 # number of questions marks count = 0 # sum of indexes of questions marks for i in range(len(string)): if string[i] == '?': count = count + i questions = questions + 1 elif string[i] == '0': zero = zero + 1 total = total + i if questions != 0: total = total * 2 ** questions + count * 2 ** (questions - 1) triangular = 0 for i in range (zero): triangular = triangular + i Choosy = 1 for i in range(questions + 1): total = total - triangular * Choosy triangular = triangular + zero + i Choosy = Choosy * (questions - i) // (i + 1) print(total) </code></pre> <p>Basically, the idea of my code is that for each case, the number of inversions needed is simply the sum of all indexes of 0 takeaway the (number of 0s -1)th triangular number. Therefore, all I need to do is add up all of the indexes of 0s, times by the number of cases, and add all indexes of questions marks, times the number of cases/2, since each question mark is a 0 exactly half the time. I then calculate the number of cases that within the question marks, there are 0, 1, 2 ..., (number of question mark) 0s using combinations, times by the (number of 0s -1)th triangular number, and minus this off the total. My code works kind of quickly but as I start putting around 20,000 question marks as my input, it starts to take more than a second. However, I need it to take 500,000 question marks as input and return a value within a second. Any ideas on how to make it faster?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T13:05:10.987", "Id": "531134", "Score": "0", "body": "is the 2k or \\$ 2^k \\$?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T13:40:04.480", "Id": "531139", "Score": "0", "body": "It is 2^k or two to the power of k" } ]
[ { "body": "<p>I don't fully understand the solution, but here are some improvements for the code:</p>\n<h2>You are computing related quantities twice:</h2>\n<p>In:</p>\n<pre><code>if questions != 0:\n total = total * 2 ** questions + count * 2 ** (questions - 1)\n</code></pre>\n<p>you are computing <code>2 ** questions</code> and <code>2 ** (questions - 1)</code>. You can just compute <code>a = 2 ** (questions - 1)</code>, and then compute <code>2 ** questions</code> as <code>2 * a</code>. (This speed up may or may not be significant).</p>\n<h2>Bit shifting may be faster than <code>**</code>.</h2>\n<p>Speaking of powers of <code>2</code>... you may or may not be familiar with the fact that <code>2 ** n == 0b1 &lt;&lt; n</code>. That is, raising <code>2</code> to the power <code>n</code> is equivalent to bit shifting binary <code>1</code> to the right <code>n</code> times. This is because we're dealing with binary, i.e. base-<code>2</code>. The same is true w.r.t. to <code>10 ** n</code> being equivalent to shifting base-<code>10</code> <code>1</code> to the right <code>n</code> times.</p>\n<h2>Triangular numbers can be computed more efficiently using this formula:</h2>\n<p><a href=\"https://i.stack.imgur.com/axlTK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/axlTK.png\" alt=\"enter image description here\" /></a></p>\n<p>Use the above formula to compute <code>triangular</code> more efficiently than:</p>\n<pre><code>for i in range (zero):\n triangular = triangular + i\n</code></pre>\n<hr />\n<h2>Style suggesitons:</h2>\n<ul>\n<li><code>a = a + b</code> can be replaced with <code>a += b</code>.</li>\n<li>Likewise, <code>a = a - b</code> can be replaced with <code>a -= b</code>.</li>\n<li></li>\n</ul>\n<pre><code>for i in range(len(seq)):\n do_something(seq[i])\n</code></pre>\n<p>can be replaced with:</p>\n<pre><code>for a in seq:\n do_something(a)\n</code></pre>\n<p>If you want to learn more about iteration in Python, this is a great resource: <a href=\"https://nedbatchelder.com/text/iter.html\" rel=\"nofollow noreferrer\">https://nedbatchelder.com/text/iter.html</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T20:38:13.167", "Id": "531166", "Score": "1", "body": "Re: `for i in range(len(seq))` -> `for a in seq`. I don't see anywhere in the post where the OP is doing exactly that. They are doing `for i in range(len(string))` and using `string[i]`, but they are also using `i` inside the loop as well. The correct recommendation would be to use `for i, a in enumerate(seq)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T21:19:20.910", "Id": "531169", "Score": "0", "body": "@AJNeufeld I missed the `i`. You're right `enumerate` is more appropriate." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T16:06:58.357", "Id": "269230", "ParentId": "269223", "Score": "2" } }, { "body": "<p>Disclaimer. This ia not a proper review, but an extended comment.</p>\n<p>Nice work with understanding the core of the problem. You just need to go one extra mile to come up with the closed form solution.</p>\n<p>If you rewrite the loop as</p>\n<pre><code>Choosy = 1\nsub = 0\nfor i in range(questions + 1):\n sub += triangular * Choosy\n triangular += zero + 1\n Choosy = Choosy * (questions - i) // (i + 1)\ntotal -= sub\n</code></pre>\n<p>it becomes obvious that the value it calculates is (<span class=\"math-container\">\\$q\\$</span> and <span class=\"math-container\">\\$z\\$</span> correspond to <code>zero</code> and <code>questions</code>)</p>\n<p><span class=\"math-container\">\\$\\displaystyle \\sum_{i=0}^q \\binom{q}{i}T_{z+i} = \\sum_{i=0}^q \\binom{q}{i}\\dfrac{(z+i)(z+i+1)}{2} = \\dfrac{1}{2}\\sum_{i=0}^q \\binom{q}{i}(i^2 + (2z+1)i + z(z+1)) =\\$</span></p>\n<p><span class=\"math-container\">\\$\\displaystyle \\dfrac{1}{2}\\sum_{i=0}^q \\binom{q}{i}i^2 + \\dfrac{2z+1}{2}\\sum_{i=0}^q \\binom{q}{i}i + \\dfrac{z(z+1)}{2}\\sum_{i=0}^q \\binom{q}{i}\\$</span></p>\n<p>Each term has a closed form. You don't need to loop at all.</p>\n<p>Ironically, this problem wouldn't teach you how to iterate. Rather it teaches to <em>not</em> iterate.</p>\n<p>A word of warning. You'd have to deal with quite large powers of 2. Do not compute them naively. Check out <a href=\"https://en.wikipedia.org/wiki/Exponentiation_by_squaring\" rel=\"noreferrer\">exponentiation by squaring</a>, and take the modulo after each multiplication.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T12:17:22.737", "Id": "531189", "Score": "0", "body": "Hello is it appropriate to equate the summation symbol (the sidewards M) with a for i in range loop in python where the top value is the highest value for i and the bottom value is the starting value? Also thanks for your comment!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T12:24:30.660", "Id": "531191", "Score": "0", "body": "also i dont understand this last bit 12∑=0()2+2+12∑=0()+(+1)2∑=0(), sorry i dont know how to write with proper maths notation like you did." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T18:30:21.090", "Id": "269234", "ParentId": "269223", "Score": "6" } }, { "body": "<h4>Reduce the numbers</h4>\n<p>You compute potentially huge numbers, which is slow. And you forgot about the modulo <span class=\"math-container\">\\$10^9+7\\$</span>, you're not doing that anywhere. If you do it at each step, then you work only with small numbers, which is much faster. For example, instead of <code>2 ** questions</code> use <code>pow(2, questions, 10**9 + 7)</code>.</p>\n<p>Keeping your numbers modulo <span class=\"math-container\">\\$10^9+7\\$</span> makes your solution <span class=\"math-container\">\\$O(n)\\$</span> instead of <span class=\"math-container\">\\$O(n^2)\\$</span>, it's probably fast enough then.</p>\n<h4>Function</h4>\n<p>Another piece of advice is to put the computation into a function:</p>\n<pre><code>def inversions(string):\n ...\n return total\n\nprint(inversions(input()))\n</code></pre>\n<h4>Testing against naive reference solution</h4>\n<p>That makes it more versatile, for example for testing against a naive solution in another function:</p>\n<pre><code>from itertools import product, combinations\nfrom operator import countOf\n\ndef naive(string):\n inversions = 0\n for bits in product(*(c if c != '?' else '01' for c in string)):\n inversions += countOf(combinations(bits, 2), ('1', '0'))\n return inversions % (10**9 + 7)\n\ndef inversions(string):\n ...\n\nfor string in '?0?', '0?1?':\n expect = naive(string)\n result = inversions(string)\n print(f'{string=}: {expect=}, {result=} =&gt;',\n 'correct' if result == expect else 'wrong')\n</code></pre>\n<p>(Note that my <code>naive</code> function uses the normal (and equivalent) definition of <a href=\"https://en.wikipedia.org/wiki/Inversion_(discrete_mathematics)\" rel=\"nofollow noreferrer\">inversions</a>, i.e., the number of pairs that are out of order.)</p>\n<p>Output of that:</p>\n<pre><code>string='?0?': expect=3, result=3 =&gt; correct\nstring='0?1?': expect=3, result=3 =&gt; correct\n</code></pre>\n<p>Or more extensive testing, with all possible strings of up to nine characters (<a href=\"https://tio.run/##jVRNc9MwEL37VyzDMJIdt7XLAeiMyYEfAHeGg@OsE4EtGUkuLZn89qAvR3YaZpqLFO/bt2/fShqe9V7w9x8HeTq1UvTANEotRKeA9YOQGgYptmOjc2hEv2G81kxwlTisGFDWWsgJ2oiR669tkmyxBV6zR6RKS8Z36UMC5sf4I0pl86GCwn1qTfaGaVONT5VoRhtgLTTwpgKyJoCdQiBFSRy6sdBAG3gvuFfVpITONVNbJ4f7NAdKSpIbSpKmjkCiHiWfc7wDWhZZ9glW8CH1DcVo7Mpl/0UpbEPwFpgCvUfgY79BCaKFgiiH0ULXXQD5fcREYgf9PaLSk0kGHoEx0tfyl0e7TgNSjb3n2@ITqmsZZ8@ZdVHWfIe0Q06v@NkGk7@zH1C5QcTgvLBfV8AW0XkTcb@C8ozC7kWJ4qJEMNYt89S5oX615ZMgO5Yz56eIjMuMDO4hyxbafCchQGPkBsrUsxu1xrKxq6U7wFfcBGrVznxcpMz@nBV/2Quhnk2wvDqdhXnp/7q5mVNngfMVGoK1cXZnNWFzYQRL4e4OKHNi5lfHyUgSK97P1HZA1sXa3bN1OZ0efBqwscdm8TwEJjV2NvTyorn4YLaatuTgP1bHBzh4uuqYw8GnV0eoPpN8dlRII6Q0IGLPxlSjmoT4t@WPFHxHzJCHWincGg1tzTq3KVxP5o7s9D5OpSzCKJYN9/VACbn9KRjPz8@ZebmsCxIHrHXlmS5u2suOrcQrL@j0CzpX1eJCKVyiQhMONbn3zWcePMMRtBmueRUD9ODX4y1JT6d/\" rel=\"nofollow noreferrer\" title=\"Python 3.8 (pre-release) – Try It Online\">Try it online!</a>):</p>\n<pre><code>passed = failed = 0\nfor length in range(10):\n for string in map(''.join, product('01?', repeat=length)):\n if inversions(string) == naive(string):\n passed += 1\n else:\n failed += 1\nprint(f'Passed {passed} tests, failed {failed}.')\n</code></pre>\n<p>Output:</p>\n<pre><code>Passed 29524 tests, failed 0.\n</code></pre>\n<h4>Alternative solution</h4>\n<p>I don't really understand your solution, either, here's how I solved it. I compute the answer for every prefix of the string. For that, I keep track of three values:</p>\n<ul>\n<li><code>strings</code>: The number of possible strings (initially 1, doubles at every <code>?</code>).</li>\n<li><code>ones</code>: The total number of 1s in all those strings.</li>\n<li><code>inversions</code>: The total number of inversions in all those strings.</li>\n</ul>\n<p>Let's ignore the modulo for a moment, for a clearer view of the actual algorithm:</p>\n<pre><code>def inversions(string):\n strings = 1\n ones = 0\n inversions = 0\n for c in string:\n if c == '0':\n inversions += ones\n elif c == '1':\n ones += strings\n else:\n inversions = inversions * 2 + ones\n ones = ones * 2 + strings\n strings *= 2\n return inversions\n</code></pre>\n<p>I'm using the &quot;out-of-order pairs&quot; method of counting again. That is, when a <code>0</code> comes at some point after a <code>1</code>. So:</p>\n<ul>\n<li>Whenever I come across a <code>0</code>, the number of inversions increase by how many <code>1</code>s I have seen before. The number of strings stays the same, they all just get extended by a <code>0</code>. So the total number of <code>1</code>s also stays the same.</li>\n<li>Whenever I come across a <code>1</code>, that doesn't cause new inversions and the number of strings also stay the same, but the number of <code>1</code>s increases, one <code>1</code> for each string.</li>\n<li>Whenever I come across a <code>?</code>, all three values are affected. The number of strings doubles, half of them get extended by a <code>0</code> and half of them by a <code>1</code>. Duplicating all strings also doubles the numbers of inversions and ones in them. And then we get a few extra inversions and <code>1s</code> depending on whether we extend by <code>0</code> or <code>1</code>.</li>\n</ul>\n<h5>With modulo</h5>\n<p>Two ways to integrate the modulo (both accepted in 0.08 seconds):</p>\n<p>With code at every calculation:</p>\n<pre><code>def inversions(string):\n mod = 10**9 + 7\n strings = 1\n ones = 0\n inversions = 0\n for c in string:\n if c == '0':\n inversions = (inversions + ones) % mod\n elif c == '1':\n ones = (ones + strings) % mod\n else:\n inversions = (inversions * 2 + ones) % mod\n ones = (ones * 2 + strings) % mod\n strings = strings * 2 % mod\n return inversions\n</code></pre>\n<p>With a helper class that wraps ints, offers the operations we need, and always applies the modulo. Then the main algorithm code remains clean:</p>\n<pre><code>class ModInt:\n def __init__(self, value):\n self.value = value % (10**9 + 7)\n def __add__(self, other):\n return ModInt(self.value + int(other))\n def __mul__(self, other):\n return ModInt(self.value * int(other))\n def __int__(self):\n return self.value\n def __str__(self):\n return str(self.value)\n\ndef inversions(string):\n strings = ModInt(1)\n ones = ModInt(0)\n inversions = ModInt(0)\n for c in string:\n if c == '0':\n inversions += ones\n elif c == '1':\n ones += strings\n else:\n inversions = inversions * 2 + ones\n ones = ones * 2 + strings\n strings *= 2\n return inversions\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T03:55:32.727", "Id": "531235", "Score": "0", "body": "Wow that helps a lot thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T02:08:21.603", "Id": "269240", "ParentId": "269223", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T12:30:24.380", "Id": "269223", "Score": "5", "Tags": [ "python", "programming-challenge", "sorting", "time-limit-exceeded" ], "Title": "Counting swaps in a sequence sorting algorithm" }
269223
<p>we have a RESTful API that includes an endpoint for search</p> <p>apiserver/v5/search?q=[search text]</p> <p>for any query, it passes it off to solr and returns the result like</p> <pre><code>{code:200,results:[{..},{...}]} </code></pre> <p>if q parameter is omitted, it returns:</p> <pre><code>{code:412,message:&quot;parameter q is required&quot;} </code></pre> <p>if q parameter is EMPTY, eg <code>?q=</code> then it also returns 412: if q parameter is omitted, it returns:</p> <pre><code>{code:412,message:&quot;parameter q is empty&quot;} </code></pre> <p>The design is the the search PAGE with eg <code>example.com/search?q=</code> will show a default view and not make the query if it is empty, but instead just show a search box or default information.</p> <p>My question is, Is it poor design or very non-standard to have the API return error on empty query? ie, does it make the API very unexpected/uncomfortable, or is it quite reasonable, to enforce that &quot;you won't get results so you should be handling this in front end behavior&quot;</p> <p>Below is the relevant code.</p> <p>NOTE: search function handles all the validation and sanitation and other stuff and is outside the scope of the relevant code and question</p> <pre><code>&lt;?php require('search.php'); if(!isset($_GET['q']) echo '{&quot;code&quot;:412,&quot;message&quot;:&quot;parameter q is required&quot;}'; // should we do this to enforce they should handle front end? if(empty($_GET['q'])) echo '{&quot;code&quot;:412,&quot;message&quot;:&quot;parameter q is empty&quot;}'; echo search($_GET['q']); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T23:34:13.717", "Id": "531174", "Score": "0", "body": "https://stackoverflow.com/q/1219542/2943403" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T16:15:39.870", "Id": "531200", "Score": "1", "body": "imo you don't need both the `isset` check AND the `empty` check. The `empty` check will do the work of `isset` already. I see that your error message is slightly different for isset and empty, and if that's a need of yours for some reason then stick with it, but if it's not then I would recommend to stick with `empty`" } ]
[ { "body": "<blockquote>\n<h3>do search api endpoints typically allow you to search for nothing and just return empty</h3>\n</blockquote>\n<p>It is up to the implementors (and perhaps influenced by the stakeholders) of the API. Of the APIs I’ve looked at many disallow searching without a query/keyword. Below are a few examples:</p>\n<ul>\n<li><a href=\"https://developer.accuweather.com/accuweather-locations-api/apis/get/locations/v1/cities/autocomplete\" rel=\"nofollow noreferrer\">accuweather location autocomplete</a></li>\n<li><a href=\"https://any-api.com/owler_com/owler_com/docs/CompanyAPI/basicCompanySearch\" rel=\"nofollow noreferrer\">owler company /basicsearch</a></li>\n</ul>\n<blockquote>\n<h3>does it make the API very unexpected/uncomfortable, or is it quite reasonable, to enforce that &quot;you won't get results so you should be handling this in front end behavior&quot;</h3>\n</blockquote>\n<p>It is quite reasonable. For a REST API <a href=\"https://softwareengineering.stackexchange.com/a/270335/244085\">&quot;meaningful HTTP status codes are a must&quot;</a>. If there is a front-end then it should ensure that the request is well-formed - i.e. has all required parameters.</p>\n<p>Take for example the StackExchange API endpoint <a href=\"https://api.stackexchange.com/docs/search\"><code>/search</code></a>. If the query is missing either the <em>tagged</em> or <em>intitle</em> parameter it will return the following response:</p>\n<blockquote>\n<pre><code>{\n &quot;error_id&quot;: 400,\n &quot;error_message&quot;: &quot;one of tagged or intitle must be set&quot;,\n &quot;error_name&quot;: &quot;bad_parameter&quot;\n}\n</code></pre>\n</blockquote>\n<p>And note that the response has HTTP status 400:</p>\n<p><a href=\"https://i.stack.imgur.com/ZyktK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ZyktK.png\" alt=\"screenshot of network panel showing HTTP status\" /></a></p>\n<p>HTTP status <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/412\" rel=\"nofollow noreferrer\">412 Precondition Failed</a> likely isn't the best code to be used in such a case.</p>\n<blockquote>\n<p>The HyperText Transfer Protocol (HTTP) 412 Precondition Failed client error response code indicates that access to the target resource has been denied. This happens with conditional requests on methods <strong>other than <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET\" rel=\"nofollow noreferrer\"><code>GET</code></a> or <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD\" rel=\"nofollow noreferrer\"><code>HEAD</code></a></strong> when the condition defined by the If-Unmodified-Since or If-None-Match headers is not fulfilled. In that case, the request, usually an upload or a modification of a resource, cannot be made and this error response is sent back.</p>\n</blockquote>\n<p>(emphasis: mine)</p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400\" rel=\"nofollow noreferrer\">400 Bad Request</a> would likely be more appropriate. If a form was submitted incorrectly then <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422\" rel=\"nofollow noreferrer\">422 Unprocessable Entity</a> could be used but that might likely be more appropriate for a <code>POST</code> request.</p>\n<p>The status code can be set with an HTTP header using <a href=\"https://php.net/header\" rel=\"nofollow noreferrer\"><code>header()</code></a> and the <a href=\"https://www.php.net/manual/en/function.header.php#refsect1-function.header-parameters\" rel=\"nofollow noreferrer\"><code>response_code</code> parameter</a></p>\n<pre><code>header('Content-Type: application/json', true, 400); \n</code></pre>\n<p>If the response is JSON then it would be appropriate to <a href=\"https://stackoverflow.com/a/477819/1575353\">set the Content-Type header to <code>application/json</code></a> - as is done in the example line above.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T19:04:29.133", "Id": "531163", "Score": "0", "body": "true on the code 400.\nhowever yes q= must be 'set' but the question is can it be 'set to empty string'. it is unreasonable to search for nothing, but do search api endpoints typically allow you to search for nothing and just return empty. \nie in stackoverflow search if you search ?q= you get to a page, but this is 'front end' and we don't know if it actually passed the 'search' to the internal api it uses for searching, or if it just 'didn't search'" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T16:09:46.830", "Id": "531199", "Score": "0", "body": "Please see updated answer" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T18:34:33.980", "Id": "269235", "ParentId": "269231", "Score": "1" } }, { "body": "<p>Yes, it is absolutely ok to return error in case of empty search phrase.</p>\n<p>Returning empty set does not make much sense to me. If it were to be a success response, I'd rather expect first &quot;default limit&quot; items to be returned, that all match the condition of containing an empty string - which is basically equivalent to no condition at all.</p>\n<p>As for your code, the q parameter can come also as an array. You should check not just that it is not empty, but also that it is a string.</p>\n<p>For the response, if that's supposed to be formatted as JSON, then use proper a JSON serialization method</p>\n<pre><code>json_encode(['code' =&gt; 400, 'message' =&gt; '...']);\n</code></pre>\n<p>Your response</p>\n<pre><code>{code:412,message:&quot;parameter q is empty&quot;}\n</code></pre>\n<p>is actually not valid JSON, though it may be a valid javascript fragment. But in JSON, property names (code,message) must be also quoted.</p>\n<p>I changed the code to 400, as 412 is really not much appropriate.\nAnd this should be returned as the HTTP status code rather then part of the response body. But these were already pointed out by Sam.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T18:42:23.983", "Id": "531210", "Score": "0", "body": "copy/paste error on the json, sorry ;)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T06:43:37.893", "Id": "269241", "ParentId": "269231", "Score": "3" } } ]
{ "AcceptedAnswerId": "269235", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T16:16:19.353", "Id": "269231", "Score": "1", "Tags": [ "php", "api", "search", "rest" ], "Title": "Requiring query field to not be empty on search api" }
269231
<p>This is my first formal <code>R</code> script that reads an archive and prints its contents. It uses <a href="https://github.com/libarchive/libarchive" rel="nofollow noreferrer"><code>libarchive</code></a> <a href="https://github.com/r-lib/archive" rel="nofollow noreferrer">R-bindings</a>, which can be installed on Ubuntu like so:</p> <pre class="lang-bsh prettyprint-override"><code># install libarchive manually since libarchive-dev is at version 3.4.3 # https://github.com/libarchive/libarchive/wiki/BuildInstructions#using-configure-for-building-from-the-command-line-on-linux-freebsd-solaris-cygwin-aix-interix-mac-os-x-and-other-unix-like-systems aria2c https://github.com/libarchive/libarchive/releases/download/v3.5.2/libarchive-3.5.2.tar.gz tar xzf libarchive-3.5.2.tar.gz cd libarchive-3.5.2 ./configure make make check make install # install R libarchive bindings # https://github.com/r-lib/archive sudo apt-get install -y r-base echo 'install.packages(&quot;archive&quot;, repos=&quot;https://cloud.r-project.org/&quot;)' | R --vanilla </code></pre> <p>By default, <code>archive_read</code> seems to only read files at the top-most level in an archive, which is why specific file names can be supplied.</p> <p>All advice is welcome! Specific information on improving performance is appreciated. Feel free to use <em>any</em> external dependencies too.</p> <p><strong>print_archive.R</strong></p> <pre><code>#!/usr/bin/env Rscript library(archive) argv &lt;- commandArgs() argc &lt;- length(argv) if (argc &gt; 5) { fname &lt;- argv[6] printFile &lt;- function(conn) { lines &lt;- readLines(conn) close(conn) options(max.print=length(lines)) cat(lines, sep=&quot;\n&quot;) } if (argc &gt; 6) { files &lt;- argv[7:length(argv)] for (fpath in archive(fname)$path) { for (file in files) { if (endsWith(fpath, file)) { printFile(archive_read(fname, fpath)) } } } } else { printFile(archive_read(fname)) } } else { print(&quot;Usage: print_archive.R [archive] [...files]&quot;) } warnings() </code></pre> <p><em><strong>Example:</strong></em></p> <pre class="lang-bsh prettyprint-override"><code>./print_archive.R libarchive-3.5.2.tar.gz README.md </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-21T17:16:21.273", "Id": "269233", "Score": "0", "Tags": [ "r", "file-archive" ], "Title": "Printing file archives using R and libarchive" }
269233
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/268829/231235">Calculate distances between two multi-dimensional arrays in Matlab</a> and <a href="https://codereview.stackexchange.com/q/269052/231235">Mean and variance of element-wise distances in a set of multi-dimensional arrays in Matlab</a>. For avoiding calculating distances and average twice, I am trying to propose a different implementation which is to calculate all distances first and then calculate mean and variance.</p> <p><strong>The experimental implementation</strong></p> <ul> <li><p><code>MeanVarIntraEuclideanDistances</code> function</p> <pre><code>function [Mean, Variance] = MeanVarIntraEuclideanDistances(X1) Distances = IntraEuclideanDistances(X1); k = 2; NormalizationFactor = (1 / nchoosek(size(X1, 4), k)); Mean = sum(Distances, 'all') * NormalizationFactor; Variance = sum((Distances - Mean).^2, 'all') * NormalizationFactor; end </code></pre> </li> <li><p><code>IntraEuclideanDistances</code> function: returns the element-wise distances in an array</p> <pre><code>function Distances = IntraEuclideanDistances(X1) N = size(X1, 4); Distances = zeros(1, N * (N - 1) / 2); for i = 1:N element1 = X1(:, :, :, i); for j = i:N element2 = X1(:, :, :, j); DistIndex = (N + (N - (i - 1) + 1)) * (i - 1) / 2 + (j - i + 1); Distances(DistIndex) = EuclideanDistance(element1, element2); end end end </code></pre> </li> <li><p><code>EuclideanDistance</code> function</p> <pre><code>function [output] = EuclideanDistance(X1, X2) %EUCLIDEANDISTANCE Calculate Euclidean distance between two inputs if ~isequal(size(X1), size(X2)) error('Sizes of inputs are not equal!') end output = sqrt(SquaredEuclideanDistance(X1, X2)); end </code></pre> </li> <li><p><code>SquaredEuclideanDistance</code> function</p> <pre><code>function [output] = SquaredEuclideanDistance(X1, X2) %SQUAREDEUCLIDEANDISTANCE Calculate squared Euclidean distance between two inputs if ~isequal(size(X1), size(X2)) error('Sizes of inputs are not equal!') end output = sum((X1 - X2).^2, 'all'); end </code></pre> </li> </ul> <p><strong>Test case</strong></p> <pre><code>%% Preparing data DataCount = 10; sizex = 8; sizey = 8; sizez = 8; Collection = ones(sizex, sizey, sizez, DataCount); for i = 1:DataCount Collection(:, :, :, i) = ones(sizex, sizey, sizez) .* i; end %% Function testing [Mean, Variance] = MeanVarIntraEuclideanDistances(Collection) </code></pre> <p>The output of test case:</p> <pre><code>Mean = 82.9672 Variance = 4.0328e+03 </code></pre> <p>All suggestions are welcome.</p> <p>The summary information:</p> <ul> <li><p>Which question it is a follow-up to?</p> <p><a href="https://codereview.stackexchange.com/q/268829/231235">Calculate distances between two multi-dimensional arrays in Matlab</a> and</p> <p><a href="https://codereview.stackexchange.com/q/269052/231235">Mean and variance of element-wise distances in a set of multi-dimensional arrays in Matlab</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <p>I am trying to propose a different implementation which is to calculate all distances first and then calculate mean and variance in this post.</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": "2021-10-22T00:15:48.473", "Id": "269239", "Score": "1", "Tags": [ "performance", "algorithm", "array", "combinatorics", "matlab" ], "Title": "Mean and variance of element-wise distances in a set of multi-dimensional arrays in Matlab - follow-up" }
269239
<p>Hi I am a beginner and l would love to hear your opinion on my first C project, how can it be improved in any way, for example dynamic memory allocation isn't used in the program because I didn't quite understand where to allocate it, also I couldn't figure how to solve the problem that if input isn't an integer the program goes into an endless loop</p> <p>Thanks for anyone who helps</p> <pre><code>#include&lt;stdlib.h&gt; #include&lt;stdio.h&gt; #include&lt;stdbool.h&gt; #include&lt;ctype.h&gt; void print(); void change(int num, int a); void restart(); bool draw(); bool win(); bool check(char a[]); bool CheckInput(int num); char a[9] = {49,50,51,52,53,54,55,56,57}; void main(){ int b[9] = {1,2,1,2,1,2,1,2,1}; int num; restart(); for(int i = 0; i &lt; 9; i++) { system(&quot;cls&quot;); print(); printf(&quot;player %d enter a number option &quot;,b[i]); scanf(&quot;%d&quot;,&amp;num); change(num,b[i]); if(i == 8) { system(&quot;cls&quot;); print(); } if(win() == true) { print(); printf(&quot;payer %d wins&quot;,b[i]); return; } } printf(&quot;its a draw&quot;); return; } bool CheckInput(int num) { char (*str)[9] = &amp;a; if(num &gt; 9 || num &lt; 1) return false; else if(*(*str+(num-1)) == 79 || *(*str+(num-1)) == 88) return false; return true; } void change(int num, int p){ char (*str)[9] = &amp;a; int n = 0; if(CheckInput(num) == true) { if(p == 1) *(*str+(num-1)) = 88; else *(*str+(num-1)) = 79; return; } else printf(&quot;\nincorrect enter a new number &quot;); scanf(&quot;%d&quot;,&amp;n); change(n,p); } void print() { printf(&quot;\n&quot;); int j = 0; for (int i = 0; i &lt; 2; i++) { if(i == 1) j = 3; printf(&quot; %c | %c | %c\n&quot;,a[j],a[j+1],a[j+2]); printf(&quot;_____|_____|_____\n&quot;); printf(&quot; | |\n&quot;); } j = 6; printf(&quot; %c | %c | %c\n&quot;,a[j],a[j+1],a[j+2]); } void restart() { char (*str)[9] = &amp;a; static int j = 49; for(int i = 0; i &lt; 9; i++) { *(*str + i) = j; j++; } print(); } bool win(){ char (*str)[9] = &amp;a; char b[3]; char c[3]; for(int i = 0; i &lt; 3; i++) { for(int j = 0; j &lt; 3; j++) { b[j] = *(*str + i * 3 + j);//columns c[j] = *(*str + j * 3 + i);//rows } if(check(b) == true || check(c) == true) return true; } int j =0; for(int i =0; i&lt;3; i++) { b[i] = *(*str + i * 3 + j);//left to right across j++; } int k = 2; for(int i =0; i &lt; 3; i++) { c[i] = *(*str + i*3 + k);//right to left across k--; } if(check(b) == true || check(c) == true) return true; return false; } bool check(char a[3]){ int count = 0; int count2 = 0; for(int i =0; i&lt;3; i++) { if(a[i] == 88) count++; else if(a[i] == 79) count2++; } if(count != 3 &amp;&amp; count2 !=3) return false; return true; } </code></pre>
[]
[ { "body": "<p>Welcome to Code Review! Here's my two cents:</p>\n<h3>Magic chars</h3>\n<p>Across the entire program, you use the ASCII values of chars instead of the chars themselves. This makes the code hard to read, as the reader sees a bunch of numbers at first an then has to infer what they mean, i.e. that they are actually chars.</p>\n<p>This means, that e.g. <code>char a[9] = {49,50,51,52,53,54,55,56,57};</code><br />\nshould be written as <code>char a[9] = {'1','2','3','4','5','6','7','8','9'};</code><br />\nSimilarly, <code>88 -&gt; 'X' and 79 -&gt; 'O'</code>.</p>\n<p>In the end, this is just a different, more legible way of writing the char codes. C will happily calculate <code>'9'-'7'</code>.</p>\n<h3>Inconsistent naming</h3>\n<p><code>CheckInput</code> should be renamed to either <code>check_input</code> or <code>checkInput</code>. C doesn't have one definitive convention, but non convention I know of uses <code>PascalCase</code> for functions. Also, it's inconsistent with the rest of your functions.</p>\n<h3>Inexpressive names</h3>\n<p>A lot of the var names are one char wide (<code>a, b, i, j, ...</code>), making it hard to understand what they represent. It's fine for indexes used inside <code>for</code>-loops, but every other var should have a more descriptive name. For example, <code>a</code> should probably be named something like <code>cell_values</code>.</p>\n<p>Same goes with the functions: If <code>print()</code> prints the board, why not name the function <code>print_board()</code>? Reconsider the other function names as well.</p>\n<h3>Indentation and formatting</h3>\n<p>Consider using an editor that has an auto-formatting feature (VSCode/VSCodium, VS, Eclipse, SublimeText, ...). As is, the formatting is very inconsistent, making the code hard to read.</p>\n<h3>Fun pointer things</h3>\n<pre><code>// somewhere in change()\n\nchar (*str)[9] = &amp;a;\n// ...\n*(*str+(num-1)) = 88;\n</code></pre>\n<p>Ummm... This is something to do when you want to actively confuse whoever is trying to read your code.</p>\n<p>Since you've defined <code>a</code> outside of any function at the very top, the rest you your program can just access it as normal (read: without storing the adress in another var like <code>str</code> and dereferencing).<br />\nHence, you should delete the first line and change the other one to <code>a[num-1] = 88;</code>. Yes, in the end the compiler will interpret this as <code>*(a+(num-1)) = 88;</code>, but indexing into an array using <code>[]</code> is easier to read than pointers. Similarly, in <code>win()</code>, <code>*(*str + i * 3 + j)</code> is the same as <code>a[i * 3 + j]</code>.</p>\n<h3>Comparing to boolean</h3>\n<p><code>if (win() == true)</code> is the same as <code>if (win())</code> and for the sake of reducing visual clutter, it should be written like this. Coming back to a previous point, <code>win()</code> should have it's name chosen so that the entire line can be read as a sentence of some sort. Maybe <code>if (game_is_won())</code>? Same goes for for the use of <code>check()</code> and <code>CheckInput()</code>.</p>\n<h3>Printing the board</h3>\n<p>IMO in this case, printing the board with 9 <code>printf</code>s would also be fine. Also, currently the first and last row of the board are printed in two lines, while the second row is third lines tall.</p>\n<h3><code>static</code></h3>\n<p>In <code>restart()</code>, you have a line <code>static int j = 49;</code>. Making the variable <code>static</code> doesn't make much sense, since you neither need to limit it's scope across multiple files (there is only one file) nor re-use the value when the function gets called again (which it doesn't).</p>\n<h3><code>if</code> without curly braces</h3>\n<p>Even if the <code>if</code> only has one line, use curly braces. I find it easier to read and it prevents bugs if you want to add or remove lines from the <code>if</code>-statement.</p>\n<h3>Tip regarding newlines</h3>\n<p>I find it easier to keep track of the newlines if I put them at the end of a print statement. Also, the win/draw messages should have a trailing newline, since it messes with any text that might follow (such as a command prompt).</p>\n<h3>Hint regarding <code>system(&quot;cls&quot;)</code></h3>\n<p>This isn't portable. Also, the use of <code>system</code> is highly discouraged (apparently).</p>\n<p><strong>As you're a beginner, don't worry about any of this</strong>. Still, remember that some things might only work on windows and some on linux.</p>\n<h3>Typo</h3>\n<p><code>printf(&quot;payer %s wins&quot;, b[i]);</code>. This should be a p<strong>l</strong>ayer.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T11:21:34.903", "Id": "531186", "Score": "0", "body": "Actually, `if (win() == true)` is only the same as `if (win())` if the return is canonical boolean or `_Boolean`. Comparing against `true` is just too fragile." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T12:06:14.480", "Id": "531187", "Score": "0", "body": "Huh. I prefer to return ints, thanks for pointing that pitfall out!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T11:03:53.727", "Id": "269248", "ParentId": "269243", "Score": "4" } }, { "body": "<p>Some things to add after @mindoverflow review.</p>\n<p><strong>Enable all warnings</strong></p>\n<p>Save time, enable all warnings.</p>\n<pre><code>warning: return type of 'main' is not 'int' [-Wmain]\n 25 | void main(){\n\nIn function 'restart':\nwarning: conversion from 'int' to 'char' may change value [-Wconversion]\n 101 | *(*str + i) = j;\n\n\nwarning: argument 1 of type 'char[3]' with mismatched bound [-Warray-parameter=]\n 139 | bool check(char a[3]){\n | ~~~~~^~~~\nnote: previously declared as 'char[]'\n 20 | bool check(char a[]);\n | \n</code></pre>\n<p><strong>Error checking</strong></p>\n<p>Do not trust user to enter only numeric text</p>\n<pre><code>// scanf(&quot;%d&quot;,&amp;num);\nif (scanf(&quot;%d&quot;,&amp;num) != 1) {\n Handle_input_error(); // TBD code\n}\n</code></pre>\n<p><strong>Simplify</strong></p>\n<pre><code>//if(count != 3 &amp;&amp; count2 != 3)\n//return false;\n//return true;\n\nreturn count == 3 || count2 == 3;\n</code></pre>\n<p><strong>Missing comments</strong></p>\n<p>Add some salient comments.</p>\n<hr />\n<blockquote>\n<p>how to solve the problem that if input isn't an integer the program goes into an endless loop</p>\n</blockquote>\n<p>Avoid <code>scanf()</code>. Its error handling is very cumbersome.</p>\n<p>Use <code>fgets()</code> to read a <em>line</em> of user input into a <em>string</em>, then process the string with <code>strtol(), sscanf()</code>, etc.</p>\n<pre><code>#define NUM_MIN 1\n#define NUM_MAX 9\n#define LINE_SIZE 80 // Expected max line size\nchar buf[2*LINE_SIZE]; // Use 2x, be generous\n\ndo {\n printf(&quot;player %d enter a number option &quot;, b[i]);\n if (fgets(buf, sizeof buf, stdin) == NULL) {\n Handle_No_Input(); // Perhaps exit\n }\n} while (sscanf(buf, &quot;%d&quot;, &amp;num) != 1 || num &lt; NUM_MIN || num &gt; NUM_MAX);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T12:52:54.357", "Id": "531717", "Score": "0", "body": "fgets(buf, sizeof buf, stdin) == NULL is there a way for the someone to input NULL ? what would happen if I remove the if() will it have any affect on the program ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T13:26:40.630", "Id": "531723", "Score": "0", "body": "@BobTheCoder `NULL` is returned when there is no more input (or rare input error). `NULL` is not an _input_. Without the `if()`, code lacks this detection. What would you want code to do after `fgets()` and nothing was read?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T13:33:46.607", "Id": "531724", "Score": "0", "body": "I really don't know what to do the only thing that I can think of is to use goto and exit the function or just recall the function, what would you recommend ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T13:38:21.553", "Id": "531726", "Score": "0", "body": "@BobTheCoder For this game, I'd exit with a message about the early ending. With a proper change to `int main()`, I'd also exit with a return code of `EXIT_FAILURE` vs. the usual `EXIT_SUCCESS`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T12:24:42.740", "Id": "269249", "ParentId": "269243", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T06:58:31.487", "Id": "269243", "Score": "0", "Tags": [ "beginner", "c", "tic-tac-toe" ], "Title": "First C program - Tic Tac Toe" }
269243
<p>I have written a function to choose randomly with weights from very large data sets in which the weight of elements can be several thousands.</p> <p>The input of the function is a flat <code>dict</code>, the keys can be any object and the values must be positive <code>int</code>s, and the values represent the count of the element within the data set, the format of the input should be the same as that of <code>Counter</code>, anyway I constructed the objects using <code>Counter</code> but I manipulate them as <code>dict</code>s.</p> <p>As I wrote above, the values can be extremely large, the function returns one element. I know I can use something like this:</p> <pre class="lang-py prettyprint-override"><code>keys = dic.keys() vals = dic.values() random.choices(keys, weights=vals, k=1)[0] </code></pre> <p>Or even this:</p> <pre class="lang-py prettyprint-override"><code>random.choice(list(dic.elements())) </code></pre> <p>But I don't think these methods to be cost-effective, memory consumption is a huge problem here and these methods are slow and/or memory-intensive. And I think unpacking the data set to flatten the data set to a extremely long list of the same elements repeating countless times to be extremely dumb.</p> <p>Instead I based my function on <code>range</code>, the idea is to calculate which <code>range</code> a number must fall in in order to get the corresponding element, then generate a random number in <code>range(total)</code> and determine which sub-range the number falls in, and return the corresponding element.</p> <h2>Code</h2> <pre class="lang-py prettyprint-override"><code>import random from typing import Any def weighted_choice(dic: dict) -&gt; Any: if not isinstance(dic, dict): raise TypeError('The argument of the function should be a dictionary') keys = list(dic.keys()) vals = list(dic.values()) if set(type(i) for i in vals) != {int}: raise TypeError('The values of the argument must be integers') if 0 in vals: raise ValueError('The values of the argument shouldn\'t contain 0') total = sum(vals) stored = 0 items = list() for k, v in zip(keys, vals): items.append((range(stored, stored+v), k)) stored += v choice = random.randrange(total) for r, i in items: if choice in r: return i </code></pre> <h2>Example</h2> <pre class="lang-py prettyprint-override"><code>starting_letters = { &quot;a&quot;: 8061, &quot;b&quot;: 5413, &quot;c&quot;: 9996, &quot;d&quot;: 6328, &quot;e&quot;: 4829, &quot;f&quot;: 3846, &quot;g&quot;: 3261, &quot;h&quot;: 3928, &quot;i&quot;: 5020, &quot;j&quot;: 801, &quot;k&quot;: 890, &quot;l&quot;: 3359, &quot;m&quot;: 6032, &quot;n&quot;: 2175, &quot;o&quot;: 3068, &quot;p&quot;: 9293, &quot;q&quot;: 553, &quot;r&quot;: 4307, &quot;s&quot;: 10387, &quot;t&quot;: 5019, &quot;u&quot;: 4404, &quot;v&quot;: 1628, &quot;w&quot;: 1789, &quot;x&quot;: 144, &quot;y&quot;: 320, &quot;z&quot;: 379 } letter_frequency = { 'a': 80183, 's': 54738, 'm': 28847, 'r': 66553, 'd': 28914, 'v': 8877, 'k': 6103, 'o': 64730, 'n': 63640, 'i': 80469, 'c': 42724, 'l': 52184, 'b': 17558, 't': 63928, 'e': 100093, 'u': 34981, 'f': 11308, 'p': 29325, 'y': 19245, 'g': 20298, 'h': 24064, 'x': 2975, 'w': 6020, 'j': 1440, 'q': 1741, 'z': 2997 } print(weighted_choice(starting_letters)) print(weighted_choice(letter_frequency)) </code></pre> <h2>Output</h2> <pre><code>h e </code></pre> <h2>Performance</h2> <pre><code>In [525]: keys = list(letter_frequency.keys()) In [526]: vals = list(letter_frequency.values()) In [527]: random.choices(keys, weights=vals, k=1)[0] Out[527]: 'i' In [528]: %timeit random.choices(keys, weights=vals, k=1)[0] 2.74 µs ± 278 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [529]: %memit random.choices(keys, weights=vals, k=1)[0] peak memory: 144.55 MiB, increment: 0.00 MiB In [530]: counter = Counter(letter_frequency) In [531]: random.choice(list(counter.elements())) Out[531]: 'r' In [532]: %timeit random.choice(list(counter.elements())) 21.3 ms ± 1.84 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) In [533]: %memit random.choice(list(counter.elements())) peak memory: 162.07 MiB, increment: 17.86 MiB In [534]: weighted_choice(letter_frequency) Out[534]: 'l' In [535]: %timeit weighted_choice(letter_frequency) 16.3 µs ± 272 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) In [536]: %memit weighted_choice(letter_frequency) peak memory: 142.69 MiB, increment: 0.00 MiB </code></pre> <p>I intend to use this function in my project to generate pseudowords using Markov chain, and I want to make the function be as efficient as possible, I would like to vectorize the function using <code>pandas</code> and <code>numpy</code>, I think truth indexing would be extremely useful in this situation and vectorization would speed things up tremendously here, but I don't know if putting <code>range</code>s in a <code>DataFrame</code> column is a good idea.</p> <p>How can this script be vectorized?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T05:54:12.473", "Id": "531241", "Score": "1", "body": "Your `%memit` output shows `increment: 0.00 MiB`. I.e., pretty much *nothing*, as you'd expect from this tiny data. You call that \"memory-intensive\" and \"memory consumption is a huge problem\"?" } ]
[ { "body": "<p>Using the <a href=\"https://realpython.com/lessons/assignment-expressions/\" rel=\"nofollow noreferrer\">walrus operator</a> and a generator expression can reduce the runtime and memory-consumption of your final loop. Consider this small change:</p>\n<pre><code>stored = 0\nitems = ((range(stored, (stored := stored + v)), k) for k, v in zip(keys, vals))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T08:56:34.070", "Id": "269245", "ParentId": "269244", "Score": "1" } }, { "body": "<h2>Performance</h2>\n<ul>\n<li>If you're going to call this function with different dictionaries\neach time, then there is really not much to be done. Most of the time\nis spent creating the lists and optimizing the logic in python really\ndoesn't speed it up much from what I've tried.</li>\n<li>If you're going to call this function multiple times with the same dict, then I have quite a bit of speedup with numpy:</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>def weighted_choice_draw_n(dic: dict,n) -&gt; Any:\n if not isinstance(dic, dict):\n raise TypeError(&quot;The argument of the function should be a dictionary&quot;)\n\n keys = {}\n for i,k in enumerate((dic.keys())):\n if not isinstance(i,int):\n raise TypeError(&quot;The values of the argument must be integers&quot;)\n keys[i] = k\n\n probs = np.fromiter(dic.values(),dtype=int)\n if not np.all(probs):\n raise ValueError(&quot;The values of the argument shouldn't contain 0&quot;)\n\n choices = np.random.choice(np.arange(len(probs)), size = n, p = probs/np.sum(probs))\n\n return [keys[index] for index in choices]\n</code></pre>\n<p>100k draws:</p>\n<pre><code>function [weighted_choice_draw_n](100000,) finished in 20 ms\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T05:33:53.033", "Id": "531239", "Score": "0", "body": "I believe the start of your loop `for i,k in enumerate((dic.keys())):` contains a logical error, I think you didn't want to iterate over the `.keys()` view but rather `.items()` view, since the indexes will always be `int`s and that check is meant for values." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T14:49:23.730", "Id": "269254", "ParentId": "269244", "Score": "1" } }, { "body": "<p><code>random.choices()</code> does not unpack/flatten the data. It uses the cumulative weights. First it picks a random value from 0 - the max cumulative weight. Then uses <code>bisect.bisect()</code> to map that back to the population.</p>\n<p>If you pass in <code>weights</code>, <code>random.choices()</code> calculates the cumulative weights. If you call it many times it would be more efficient to precalculate and save the cumulative weights (see <code>itertools.accumulate()</code>) and pass that in to <code>random.choices()</code></p>\n<p>Your code implements the same idea as <code>random.choices()</code>, except the library code uses a binary search rather than a linear search like your code. It is possible for small populations the linear search might be faster because of the overhead of the binary search. For large populations the binary search should be faster.</p>\n<p>FYI near the top of the documentation for <a href=\"https://docs.python.org/3.9/library/random.html\" rel=\"nofollow noreferrer\"><code>random</code></a> is a link to the Python <a href=\"https://github.com/python/cpython/tree/3.9/Lib/random.py\" rel=\"nofollow noreferrer\">source code</a> for the <code>random</code> module. You can look at the source code for <code>choices</code> to see how it works.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T20:23:48.667", "Id": "269267", "ParentId": "269244", "Score": "4" } }, { "body": "<p>Well, I have refined my algorithm with <code>itertools.accumulate</code> and <code>bisect.bisect</code>, I am implementing exactly the same idea as the original code (and <code>random.choices</code>), the only difference is that it is much more performant now.</p>\n<p>The code:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import random\nfrom bisect import bisect\nfrom itertools import accumulate\nfrom typing import Any\n\ndef weighted_choice(dic: dict) -&gt; Any:\n if not isinstance(dic, dict):\n raise TypeError('The argument of the function should be a dictionary')\n choices, weights = zip(*dic.items())\n if set(map(type, weights)) != {int}:\n raise TypeError('The values of the argument must be integers')\n if 0 in weights:\n raise ValueError('The values of the argument shouldn\\'t contain 0')\n accreted = list(accumulate(weights))\n chosen = random.randrange(accreted[-1])\n return choices[bisect(accreted, chosen)]\n</code></pre>\n<p>Example:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from collections import Counter\nletter_frequency = {\n 'a': 80183,\n 's': 54738,\n 'm': 28847,\n 'r': 66553,\n 'd': 28914,\n 'v': 8877,\n 'k': 6103,\n 'o': 64730,\n 'n': 63640,\n 'i': 80469,\n 'c': 42724,\n 'l': 52184,\n 'b': 17558,\n 't': 63928,\n 'e': 100093,\n 'u': 34981,\n 'f': 11308,\n 'p': 29325,\n 'y': 19245,\n 'g': 20298,\n 'h': 24064,\n 'x': 2975,\n 'w': 6020,\n 'j': 1440,\n 'q': 1741,\n 'z': 2997\n}\ntest = Counter([weighted_choice(letter_frequency) for i in range(10000)])\nprint(test.most_common()) \n</code></pre>\n<p>Output</p>\n<pre><code>[('e', 1098), ('i', 899), ('a', 897), ('o', 746), ('t', 716), ('r', 710), ('n', 665), ('s', 588), ('l', 576), ('c', 483), ('u', 367), ('p', 335), ('d', 296), ('m', 290), ('h', 269), ('y', 215), ('g', 205), ('b', 177), ('f', 140), ('w', 88), ('v', 81), ('k', 73), ('z', 36), ('x', 25), ('q', 16), ('j', 9)]\n</code></pre>\n<p>Performance</p>\n<pre><code>In [137]: %load_ext memory_profiler\n\nIn [138]: %%timeit\n ...: choices, weights = zip(*letter_frequency.items())\n ...: random.choices(choices, weights, k=1)\n5.42 µs ± 345 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\nIn [139]: %%timeit\n ...: choices, weights = zip(*letter_frequency.items())\n ...: random.choices(choices, weights, k=1)\n5.51 µs ± 387 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\nIn [140]: %timeit weighted_choice(letter_frequency)\n4.85 µs ± 277 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\nIn [141]: %%timeit\n ...: choices, weights = zip(*letter_frequency.items())\n ...: random.choices(choices, weights, k=1)\n5.37 µs ± 326 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\nIn [142]: %timeit weighted_choice(letter_frequency)\n4.89 µs ± 345 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\nIn [143]: %%memit\n ...: choices, weights = zip(*letter_frequency.items())\n ...: random.choices(choices, weights, k=1)\npeak memory: 143.24 MiB, increment: 0.24 MiB\n\nIn [144]: %memit weighted_choice(letter_frequency)\npeak memory: 143.25 MiB, increment: 0.00 MiB\n\nIn [145]: %%memit\n ...: choices, weights = zip(*letter_frequency.items())\n ...: random.choices(choices, weights, k=1)\npeak memory: 143.26 MiB, increment: 0.00 MiB\n\nIn [146]: %memit weighted_choice(letter_frequency)\npeak memory: 143.26 MiB, increment: 0.00 MiB\n</code></pre>\n<p>My code manages to beat <code>random.choices</code> at speed while making three checks that literally do nothing in most cases, they just throw exceptions if anyone looking for trouble deliberately tests with edge cases, but their overhead is significant.</p>\n<p>Although it goes without saying, <code>random.choices</code> checks if the lengths of choices and weights do not match, since I am using <code>dict</code>s (actually <code>Counter</code>s generalized), the lengths will match.</p>\n<p>If I discard all the checks and just test the execution:</p>\n<pre><code>In [147]: %%timeit\n ...: choices, weights = zip(*letter_frequency.items())\n ...: accreted = list(accumulate(weights))\n ...: chosen = random.randrange(accreted[-1])\n ...: choices[bisect(accreted, chosen)]\n4.56 µs ± 325 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n</code></pre>\n<p>Exclude the unpack overhead:</p>\n<pre><code>In [148]: choices, weights = zip(*letter_frequency.items())\n\nIn [149]: %%timeit\n ...: accreted = list(accumulate(weights))\n ...: chosen = random.randrange(accreted[-1])\n ...: choices[bisect(accreted, chosen)]\n2.15 µs ± 205 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\nIn [150]: %timeit random.choices(choices, weights, k=1)\n2.9 µs ± 256 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n</code></pre>\n<p>My code beats <code>random.choices</code> at time complexity.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T12:38:59.467", "Id": "269294", "ParentId": "269244", "Score": "0" } } ]
{ "AcceptedAnswerId": "269267", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T07:02:02.147", "Id": "269244", "Score": "-1", "Tags": [ "python", "performance", "python-3.x", "random" ], "Title": "Python weighted choosing that works with very large numbers" }
269244
<p>See <a href="https://codereview.stackexchange.com/questions/269214/serializing-nested-data-structures-in-a-human-readable-format">Serializing (nested) data structures in a human-readable format</a> for more details.</p> <p>This is the latest version, I have fixed all bugs and now this piece of code works completely as intended.</p> <p>And I have added many more test cases. So far all tests are successful. I think I can't find an edge case that will cause the code to return wrong results now.</p> <p>My code is now greatly improved than the original, but I am not fully satisfied with the current code yet. As this is code review and I have already received answers I can't update the code posted in the original question so I have to post a new question.</p> <h2>Latest Version</h2> <pre class="lang-py prettyprint-override"><code>from typing import Union def represent(obj: Union[dict, frozenset, list, set, tuple], indent: int=4) -&gt; str: singles = (frozenset, list, set, tuple) supported = (dict, *singles) if not isinstance(obj, supported): raise TypeError('argument `obj` should be an instance of a built-in container data type') if not isinstance(indent, int): raise TypeError('argument `indent` should be an `int`') if indent &lt;= 0: raise ValueError('argument `indent` should be greater than 0') if indent % 2: raise ValueError('argument `indent` should be a multiple of 2') increment = indent def worker(obj, indent, add_level=True, not_value=True): ls = list() indent_level = ' '*(indent-increment) open_indent = indent_level * add_level if not isinstance(obj, supported): return indent_level * not_value + repr(obj) enclosures = { dict: ('{', '}'), frozenset: ('frozenset({', '})'), list: ('[', ']'), set: ('{', '}'), tuple: ('(', ')') } singletons = { dict: 'dict()', frozenset: 'frozenset({})', list: '[]', set: 'set()', tuple: '()' } for cls in supported: if isinstance(obj, cls): if not obj: return open_indent + singletons[cls] start, end = enclosures[cls] obj_cls = cls break start = open_indent + start if obj_cls in singles: single_tuple = (obj_cls == tuple and len(obj) == 1) for i in obj: item = worker(i, indent+increment) if single_tuple: item += ',' ls.append(item) else: for k, v in obj.items(): item = f&quot;{' '*indent}{repr(k)}: {worker(v, indent+increment, False, False)}&quot; ls.append(item) return &quot;{0}\n{1}\n{2}{3}&quot;.format(start, ',\n'.join(ls), indent_level, end) return worker(obj, indent) </code></pre> <h2>Test cases</h2> <pre class="lang-py prettyprint-override"><code>var = {1: {1: {1: {1: {1: {1: 0}, 2: 0}, 2: {1: 0}, 3: 0}, 2: {1: {1: 0}, 2: 0}, 3: {1: 0}}, 2: {1: {1: {1: 0}, 2: 0}, 2: {1: 0}, 3: 0}, 3: {1: {1: 0}, 2: 0}}, 2: {1: {1: {1: {1: 0}, 2: 0}, 2: {1: 0}, 3: 0}, 2: {1: {1: 0}, 2: 0}, 3: {1: 0}}, 3: {1: {1: {1: 0}, 2: 0}, 2: {1: 0}, 3: 0}} repred = represent(var) print(repred) print(f'{(eval(repred) == var)=}') var1 = {'a': {'a': {'a': [0, 0, 0], 'b': [0, 0, 1], 'c': [0, 0, 2]}, 'b': {'a': [0, 1, 0], 'b': [0, 1, 1], 'c': [0, 1, 2]}, 'c': {'a': [0, 2, 0], 'b': [0, 2, 1], 'c': [0, 2, 2]}}, 'b': {'a': {'a': [1, 0, 0], 'b': [1, 0, 1], 'c': [1, 0, 2]}, 'b': {'a': [1, 1, 0], 'b': [1, 1, 1], 'c': [1, 1, 2]}, 'c': {'a': [1, 2, 0], 'b': [1, 2, 1], 'c': [1, 2, 2]}}, 'c': {'a': {'a': [2, 0, 0], 'b': [2, 0, 1], 'c': [2, 0, 2]}, 'b': {'a': [2, 1, 0], 'b': [2, 1, 1], 'c': [2, 1, 2]}, 'c': {'a': [2, 2, 0], 'b': [2, 2, 1], 'c': [2, 2, 2]}}} print(represent(var1)) var2 = [[0, 1, 2], [3, 4, 5], 6, [7, 8, 9]] print(represent(var2)) print(represent(set())) print(represent(dict())) print(represent((1,))) print(represent(([1,2,3,[4,5,6,[7,8,9]]],))) print(represent([(1,),(2,),(3,),[(4,),(5,),(6,),[(7,),(8,),(9,)]]])) print(represent([{(1,),(2,),(3,)},{(4,),(5,),(6,)},{(7,),(8,),(9,)}])) print(represent({0: {0: set()}})) </code></pre> <h2>Correct output</h2> <pre><code>{ 1: { 1: { 1: { 1: { 1: { 1: 0 }, 2: 0 }, 2: { 1: 0 }, 3: 0 }, 2: { 1: { 1: 0 }, 2: 0 }, 3: { 1: 0 } }, 2: { 1: { 1: { 1: 0 }, 2: 0 }, 2: { 1: 0 }, 3: 0 }, 3: { 1: { 1: 0 }, 2: 0 } }, 2: { 1: { 1: { 1: { 1: 0 }, 2: 0 }, 2: { 1: 0 }, 3: 0 }, 2: { 1: { 1: 0 }, 2: 0 }, 3: { 1: 0 } }, 3: { 1: { 1: { 1: 0 }, 2: 0 }, 2: { 1: 0 }, 3: 0 } } (eval(repred) == var)=True { 'a': { 'a': { 'a': [ 0, 0, 0 ], 'b': [ 0, 0, 1 ], 'c': [ 0, 0, 2 ] }, 'b': { 'a': [ 0, 1, 0 ], 'b': [ 0, 1, 1 ], 'c': [ 0, 1, 2 ] }, 'c': { 'a': [ 0, 2, 0 ], 'b': [ 0, 2, 1 ], 'c': [ 0, 2, 2 ] } }, 'b': { 'a': { 'a': [ 1, 0, 0 ], 'b': [ 1, 0, 1 ], 'c': [ 1, 0, 2 ] }, 'b': { 'a': [ 1, 1, 0 ], 'b': [ 1, 1, 1 ], 'c': [ 1, 1, 2 ] }, 'c': { 'a': [ 1, 2, 0 ], 'b': [ 1, 2, 1 ], 'c': [ 1, 2, 2 ] } }, 'c': { 'a': { 'a': [ 2, 0, 0 ], 'b': [ 2, 0, 1 ], 'c': [ 2, 0, 2 ] }, 'b': { 'a': [ 2, 1, 0 ], 'b': [ 2, 1, 1 ], 'c': [ 2, 1, 2 ] }, 'c': { 'a': [ 2, 2, 0 ], 'b': [ 2, 2, 1 ], 'c': [ 2, 2, 2 ] } } } [ [ 0, 1, 2 ], [ 3, 4, 5 ], 6, [ 7, 8, 9 ] ] set() dict() ( 1, ) ( [ 1, 2, 3, [ 4, 5, 6, [ 7, 8, 9 ] ] ], ) [ ( 1, ), ( 2, ), ( 3, ), [ ( 4, ), ( 5, ), ( 6, ), [ ( 7, ), ( 8, ), ( 9, ) ] ] ] [ { ( 1, ), ( 2, ), ( 3, ) }, { ( 6, ), ( 4, ), ( 5, ) }, { ( 7, ), ( 8, ), ( 9, ) } ] { 0: { 0: set() } } </code></pre> <p>Please help me make it better!</p> <h2>Edit</h2> <p>Well, I think I have made all the improvements I can make to the script now, I think I have done all possible improvements I can to the script now, so I will not edit this question again. What other improvements can be possibly made?</p>
[]
[ { "body": "<p>This function is now considerably longer and harder to understand than before. I find nested functions (especially of this complexity) really harm readability, since you need to keep track of even more layers of context to understand the full functionality. I strongly suggest splitting this function into top-level functions to increase readability and seperate logic.</p>\n<hr />\n<p><code>singles</code>, <code>supported</code>, <code>enclosures</code>, <code>singletons</code> (not an accurate name by the way, <a href=\"https://en.wikipedia.org/wiki/Singleton_pattern\" rel=\"nofollow noreferrer\">singleton pattern on wikipedia</a>) are basically collections of different attributes that could and should be contained within a single object. I suggest using a <code>collections.namedtuple</code>, but there are other approaches as well.</p>\n<pre><code>from typing import Union \nfrom collections import namedtuple\n\nSupportedType = namedtuple(&quot;SupportedType&quot;, [&quot;base_class&quot;, &quot;enclosures&quot;, &quot;empty_repr&quot;])\n\n\ndef represent(obj: Union[dict, frozenset, list, set, tuple], indent: int = 4) -&gt; str:\n supported_types = (\n SupportedType(base_class=dict, enclosures=('{', '}'), empty_repr='dict()'),\n SupportedType(base_class=list, enclosures=('[', ']'), empty_repr='[]'),\n SupportedType(base_class=set, enclosures=('{', '}'), empty_repr='set()'),\n SupportedType(base_class=tuple, enclosures=('{', '}'), empty_repr='()'),\n SupportedType(base_class=frozenset, enclosures=('frozenset({', '})'), empty_repr='frozenset()'),\n )\n\n for supported_type in supported_types:\n if isinstance(obj, supported_type.base_class):\n supported_base_class = supported_type.base_class\n start, end = supported_type.enclosures\n empty_repr = supported_type.empty_repr\n break\n else:\n raise TypeError('argument `obj` should be an instance of a built-in container data type')\n\n ...\n</code></pre>\n<p>This way you have all the relevant information regarding your supported types in proper context and can get rid of the multiple <code>isinstance</code> checks. You could extend this to also make each instance of SupportedType contain a reference to the correct <code>represent_object_of_type</code> (or similiar) function. This lets you get rid of un-elegant (hardcoded) checks like <code>isinstance(obj, dict)</code>.</p>\n<p><code>supported_types</code> should also move to a module-level constant (if that makes sense for your project).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T12:31:16.907", "Id": "269250", "ParentId": "269247", "Score": "2" } }, { "body": "<h1>White space</h1>\n<p>53 lines without a blank line is excessive. Add vertical white-space to break the function into logical chunks. Validation, initialization, <code>worker</code>. Same thing inside the <code>worker</code>.</p>\n<h1>Type-hints</h1>\n<p>Depending on the version of Python you're targeting, you can remove <code>Unipn[...]</code>, and just use the &quot;or&quot; operator:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def represent(obj: dict | frozenset | list | set | tuple, indent: int=4) -&gt; str:\n</code></pre>\n<p>The <code>worker</code> could use type-hints too:</p>\n<pre class=\"lang-py prettyprint-override\"><code> def worker(obj, indent: int, add_level: bool = True, not_value: bool = True) -&gt; str:\n</code></pre>\n<h1>Multiplication by boolean?</h1>\n<p><code>indent_level * add_level</code> and <code>indent_level * not_value</code>? Those are booleans, not integers. Yes, they can be interpreted as 0 and 1, but yuck!</p>\n<h1>add_level and not_value?</h1>\n<p>What is <code>not_value</code>? That name is quite obfuscating. Moreover, you only ever call worker with the two parameters both defaulted to <code>True</code>, or both explicitly set to <code>False</code>. Why two parameters then?</p>\n<h1>local(local(local(local(...))))</h1>\n<pre class=\"lang-py prettyprint-override\"><code>def represent(obj: Union[dict, frozenset, list, set, tuple], indent: int=4) -&gt; str:\n ...\n supported = (dict, *singles)\n ...\n def worker(obj, indent, add_level=True, not_value=True):\n ...\n if not isinstance(obj, supported):\n ...\n enclosures = { ... }\n singletons = { ... }\n</code></pre>\n<p>You define <code>supported</code> in <code>represented</code> scope, and use it inside <code>worker</code> scope. All is good.</p>\n<p>But you <strong>redefine</strong> <code>enclosures</code> and <code>singletons</code> each and every time you recurse into a deeper level of <code>worker</code>. This creates and recreates these variables on the stack at each level. They are constants, and could easily be defined at <code>worker</code> scope, saving both execution time and memory.</p>\n<p>As @riskypenguin said, you could move these out of <code>represent()</code> to a module-level constant, so they are created once instead of each time <code>represent()</code> is called.</p>\n<h1>f-strings</h1>\n<p><code>f&quot;...{repr(k)}...&quot;</code> could be written with the <code>!r</code> format code: <code>f&quot;...{k!r}...&quot;</code></p>\n<p>Indenting may be accomplished using field width specifiers. As in <code>f&quot;{'':{indent}}...&quot;</code> instead of creating and recreating strings of spaces all the time.</p>\n<h1>String concatenation</h1>\n<p>The code is constantly creating new strings and combining them using string concatenation (<code>+</code>) or <code>.join()</code> calls. This probably has exponential time and space complexity as the nesting level increases.</p>\n<p>Instead of concatenating strings, you should accumulate the output into one <a href=\"https://docs.python.org/3/library/io.html?highlight=stringio#io.StringIO\" rel=\"nofollow noreferrer\"><code>StringIO</code></a> buffer, which is designed for constantly appending strings into a increasing blob of text.</p>\n<h2>print_stdout</h2>\n<p>If the programmer overhead of using <code>string_buf.write(...)</code> or <code>print(..., file=string_buf)</code> is too high, you could just <code>print()</code> each string line to stdout. Call that version of the function <code>print_represent(...)</code>.</p>\n<p>Then you could write a wrapper function which returns the result as string using <a href=\"https://docs.python.org/3/library/contextlib.html?highlight=stringio#contextlib.redirect_stdout\" rel=\"nofollow noreferrer\"><code>contextlib.redirect_stdout</code></a>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def represent(obj: Union[dict, frozenset, list, set, tuple], indent: int=4) -&gt; str:\n with contextlib.redirect_stdout(io.StringIO()) as string_buf:\n print_represent(obj, indent)\n return string_buf.getvalue()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T22:57:54.847", "Id": "269274", "ParentId": "269247", "Score": "1" } } ]
{ "AcceptedAnswerId": "269274", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T09:57:57.130", "Id": "269247", "Score": "2", "Tags": [ "python", "performance", "python-3.x", "reinventing-the-wheel", "serialization" ], "Title": "Serializing (nested) data structures in a human-readable format with all bugs fixed" }
269247
<p>I've ran a few tests, not extensive though, and it apparently works. Like many standard binary search algorithms, if the number returned is &lt; 0, you can take the complement (~) of the returned value to find the insert point, eg <code>const ix = bs(arr, 5); // ~ix is the insertion point</code></p> <pre><code>interface bsRange { min: number; max: number; } const bs = (arr: number[], value: number, range: bsRange | null = null): number =&gt; { if (!range) range = { min: 0, max: arr.length - 1 }; const indexToCheck = Math.floor((range.min + range.max) / 2); const iValue = arr[indexToCheck]; if (value === iValue) return indexToCheck; if (range.max === range.min) { // we're at the last element to check if (iValue &gt; value) { return ~(range.max); } else { return ~(range.max) - 1; } } if (value &lt; iValue) { range.max = indexToCheck - 1; } else if (value &gt; iValue) { range.min = indexToCheck + 1; } return bs(arr, value, range); }; <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>Your code looks good to me. I just stumbled over the <code>range</code> parameter, which feels unusual to me. But if you remove it, you have to combine the result for the upper half of the considered array.</p>\n<pre><code>const bs = (arr: number[], value: number): number =&gt; {\n const indexToCheck = Math.floor((arr.length - 1) / 2);\n const iValue = arr[indexToCheck];\n\n if (value === iValue) return indexToCheck;\n if (arr.length === 1) return (iValue &gt; value) ? ~0 : ~1;\n if (value &lt; iValue) return bs(arr.slice(0, indexToCheck), value)\n\n const subResult = bs(arr.slice(indexToCheck + 1), value);\n return subResult &gt;= 0\n ? indexToCheck + 1 + subResult\n : ~(indexToCheck + 1 + ~subResult)\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-19T12:24:34.567", "Id": "533502", "Score": "0", "body": "I suppose for me, it's one of those variables that helps me mentally keep track of what's actually going on." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T17:24:52.183", "Id": "269954", "ParentId": "269260", "Score": "2" } } ]
{ "AcceptedAnswerId": "269954", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T16:07:30.803", "Id": "269260", "Score": "2", "Tags": [ "typescript", "binary-search" ], "Title": "Recursive Binary Search in Typescript" }
269260
<p>This script is to calculate the Spearman correlation of genes that are stored in rows of a pandas dataframe. The original df has around 2000 row names. With my current code, this requires 2000*2000 iterations to compute the correlation value for each possible comparison row-wise. I would like to get some hints in order to reduce the run time of this code.</p> <pre><code>import sys import pandas as pd from scipy import stats def spearman_correlation(): script = sys.argv[0] input_f = sys.argv[1] # create a new file name... it's that easy! positive = &quot;positive_significant_pairs.csv&quot; negative = &quot;negative_significant_pairs.csv&quot; positive_f = open(positive, 'a') negative_f = open(negative, 'a') df =pd.read_csv(input_f,index_col=0) #index_col=0 makes first row as row index lst1=[] lst2=[] for i in df.T.columns: #loop on the columns (transformed df) lst1.append(i) lst2.append(i) for i in lst1: for j in lst2: if i!=j: #avoid correlation of gene1,gene1 r, p = stats.spearmanr(df.T[i], df.T[j]) if r &gt; 0 and p &lt; 0.01: positive_f.write(''.join(str(i) + ',' + str(j) + ',' + str(r) + ',' + str(p)+'\n')) if r &lt; 0 and p &lt; 0.01: negative_f.write(''.join(str(i) + ',' + str(j) + ',' + str(r) + ',' + str(p)+'\n')) if __name__ == '__main__': spearman_correlation() <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T20:45:27.793", "Id": "531213", "Score": "0", "body": "Could you please include some sample data and current output?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T21:44:49.500", "Id": "531223", "Score": "1", "body": "Do not loop. Pass the entire `df.T` at once. The first argument to `scipy.stats.spearmanr` coould be a 2D array, just for the cases like yours." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T19:06:36.830", "Id": "531362", "Score": "0", "body": "Exactly I can pass the entire ```df.T``` and it gives me r and p values in a list. But then How I can retrieve rows that have specific r and p values from the 2D array?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T19:07:35.030", "Id": "531363", "Score": "0", "body": "The output that I want to have is in this format of ```row1,row2,r-value,p-value```" } ]
[ { "body": "<p>Sorry if my comment looked too cryptic. Let's take a closer look at the Spearman statistics.</p>\n<p>The Spearman coefficient between two sets of raw data is <span class=\"math-container\">\\$\\dfrac{\\mathrm{Cov}(R(T_i), R(T_j))}{\\sigma_{R(T_i)}\\sigma_{R(T_j)}}\\$</span>. It means that each time you call <a href=\"https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html\" rel=\"nofollow noreferrer\"><code>stats.spearmanr</code></a>, it converts each row into the rank row, and computes its standard deviation.</p>\n<p>In other words, each row is converted to the rank row 2000 times, and its standard deviation is also computed 2000 times, obviously with the same result.</p>\n<p>Passing the entire dataset allows <a href=\"https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html\" rel=\"nofollow noreferrer\"><code>stats.spearmanr</code></a> to extract these repeated computations, and perform them just once per a row. Unfortunately, computing covariances is still quadratic.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T03:49:59.690", "Id": "269280", "ParentId": "269264", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T20:08:08.803", "Id": "269264", "Score": "1", "Tags": [ "python", "performance", "scipy" ], "Title": "Calculate correlation of genes stored in dataframe rows" }
269264
<p>This is my first time coding! My intent for this program was to be able to give my technicians a flash drive that will pull system info and email it to me. Currently everything is working, but I was hoping for suggestions or tips on what I can improve on or add to it. I'm sure there is a lot of messy code that I got from Googling and jamming in there to fit my needs.</p> <p>Any notes or help is super appreciated!</p> <pre><code>:: *** Get System Info.bat *** Version 1.0 *** 2021-10-22 *** Author: Boogershut *** :: This batch file uses command line and PowerShell functions to retrieve system information, place it into a text file, and email the file for documentation. :: Text file format: &quot;'Account Name' 'Folder Number' - System Info_YearMonthDay-HourMinuteSecond&quot; @echo off title Retrieving System Information :: Variables set Cur_YYYY=&amp;Rem Current Year set Cur_MM=&amp;Rem Current Month set Cur_DD=&amp;Rem Current Day set Cur_HH=&amp;Rem Current Hour set Cur_Min=&amp;Rem Current Minute set Cur_SS=&amp;Rem Current Second set Cur_Date_Time=&amp;Rem Current Date and Time set as YearMonthDay-HourMinuteSecond set AccountName=&amp;Rem Account Name - defined by user set FolderNumber=&amp;Rem Folder Number (Panel ID) - defined by user set FileName=&amp;Rem Final File Name set TotalMem=&amp;Rem Total amount of RAM installed set AvailableMem=&amp;Rem Total amount of unused RAM set UsedMem=&amp;Rem Total amount of used RAM set MemUsage=&amp;Rem RAM being used shown as a percent set Count=&amp;Rem Temporary counter variable used in Delayed Expansion set Var=&amp;Rem Temporary variable used in Delayed Expansion :: Assigning Date and Time Variables set Cur_YYYY=%date:~10,4% set Cur_MM=%date:~4,2% set Cur_DD=%date:~7,2% set Cur_HH=%time:~0,2% if %Cur_HH% lss 10 (set Cur_HH=0%time:~1,1%) set Cur_Min=%time:~3,2% set Cur_SS=%time:~6,2% set Cur_Date_Time=%Cur_YYYY%%Cur_MM%%Cur_DD%-%Cur_HH%%Cur_Min%%Cur_SS% :: Assigning User Input Variables :LoopAccountName set /p AccountName=Input Account Name: (echo %AccountName% | findstr /i /c:&quot;name&quot; /c:&quot;@&quot; /c:&quot;{&quot; /c:&quot;}&quot; /c:&quot;=&quot; &gt;nul) &amp;&amp; ((echo Account Name cannot contain &quot;name&quot; or special characters &quot;@, {}, =&quot;) &amp;&amp; (goto LoopAccountName)) || (goto LoopFolderNumber) :LoopFolderNumber set /p FolderNumber=Input Folder Number (Panel ID): (echo %FolderNumber% | findstr /i /c:&quot;name&quot; /c:&quot;@&quot; /c:&quot;{&quot; /c:&quot;}&quot; /c:&quot;=&quot; &gt;nul) &amp;&amp; ((echo Folder Number cannot contain &quot;name&quot; or special characters &quot;@, {}, =&quot;) &amp;&amp; (goto LoopFolderNumber)) || (goto LoopStop) :LoopStop set FileName=%AccountName% %FolderNumber% - System Info_%Cur_Date_Time% :: Display to user echo. echo Please wait - Retrieving &quot;%AccountName% %FolderNumber%&quot; System Information echo. :: Create text file in current directory and input label echo %FileName% &gt;&gt; &quot;%FileName%.txt&quot; :: Add date and time to file echo. &gt;&gt; &quot;%FileName%.txt&quot; echo __________________________________________________________________________________________________________________ &gt;&gt; &quot;%FileName%.txt&quot; echo. &gt;&gt; &quot;%FileName%.txt&quot; echo Info retreived on: &gt;&gt; &quot;%FileName%.txt&quot; cmd /c &quot;date /t &amp;&amp; time /t&quot; &gt;&gt; &quot;%FileName%.txt&quot; :: Run script to add Public IP Address to file echo. &gt;&gt; &quot;%FileName%.txt&quot; echo __________________________________________________________________________________________________________________ &gt;&gt; &quot;%FileName%.txt&quot; echo. &gt;&gt; &quot;%FileName%.txt&quot; if exist &quot;.\ps.ps1&quot; (PowerShell -NoProfile -ExecutionPolicy Bypass -Command &quot;&amp; '.\ps.ps1'&quot;) else ( echo Unable to get Public IP Address. Script file not found. &gt;&gt; &quot;%FileName%.txt&quot; goto SkipPS ) :SkipPS :: Add PC info to file echo __________________________________________________________________________________________________________________ &gt;&gt; &quot;%FileName%.txt&quot; echo. &gt;&gt; &quot;%FileName%.txt&quot; echo System Information: &gt;&gt; &quot;%FileName%.txt&quot; echo. &gt;&gt; &quot;%FileName%.txt&quot; echo Current User: &gt;&gt; &quot;%FileName%.txt&quot; cmd /c &quot;whoami&quot; &gt;&gt; &quot;%FileName%.txt&quot; :: Add Serial Number to file echo. &gt;&gt; &quot;%FileName%.txt&quot; echo Serial Number/Service Tag: &gt;&gt; &quot;%FileName%.txt&quot; setlocal EnableDelayedExpansion set Count=1 for /F &quot;tokens=* USEBACKQ&quot; %%F in (`cmd /c &quot;wmic bios get serialnumber&quot;`) do ( set Var!Count!=%%F set /a Count=!Count!+1 ) echo %var2% &gt;&gt; &quot;%FileName%.txt&quot; endlocal :: Add CPU load to file echo. &gt;&gt; &quot;%FileName%.txt&quot; echo CPU Load: &gt;&gt; &quot;%FileName%.txt&quot; setlocal EnableDelayedExpansion set Count=1 for /F &quot;tokens=* USEBACKQ&quot; %%F in (`cmd /c &quot;wmic cpu get loadpercentage&quot;`) do ( set Var!Count!=%%F set /a Count=!Count!+1 ) for /f &quot;tokens=* delims= &quot; %%A in ('echo %var2% ') do set var2=%%A set var2=%var2:~0,-1% echo %var2%%% &gt;&gt; &quot;%FileName%.txt&quot; endlocal :: Add Memory Usage to file setlocal EnableDelayedExpansion for /f &quot;tokens=4&quot; %%A in ('systeminfo ^| findstr Physical') do if defined TotalMem (set AvailableMem=%%A) else (set TotalMem=%%A) set TotalMem=%TotalMem:,=% set AvailableMem=%AvailableMem:,=% set /a UsedMem=TotalMem-AvailableMem set /a MemUsage=(%UsedMem%*100)/%TotalMem% echo Memory Usage: &gt;&gt; &quot;%FileName%.txt&quot; echo %MemUsage%%% &gt;&gt; &quot;%FileName%.txt&quot; endlocal :: Add CPU details to file echo. &gt;&gt; &quot;%FileName%.txt&quot; echo CPU Info: &gt;&gt; &quot;%FileName%.txt&quot; setlocal EnableDelayedExpansion set Count=1 for /F &quot;tokens=* USEBACKQ&quot; %%F in (`cmd /c &quot;wmic cpu get name, numberofcores, status&quot;`) do ( set Var!Count!=%%F set /a Count=!Count!+1 ) echo %var1% &gt;&gt; &quot;%FileName%.txt&quot; echo %var2% &gt;&gt; &quot;%FileName%.txt&quot; endlocal :: Add Video card info to file echo. &gt;&gt; &quot;%FileName%.txt&quot; echo Video Card: &gt;&gt; &quot;%FileName%.txt&quot; setlocal EnableDelayedExpansion set Count=1 for /F &quot;tokens=* USEBACKQ&quot; %%F in (`cmd /c &quot;wmic path win32_VideoController get AdapterRAM, DeviceID, DriverVersion, Name, Status&quot;`) do ( set Var!Count!=%%F set /a Count=!Count!+1 ) echo %var1% &gt;&gt; &quot;%FileName%.txt&quot; echo %var2% &gt;&gt; &quot;%FileName%.txt&quot; endlocal :: Add ram details to file echo. &gt;&gt; &quot;%FileName%.txt&quot; echo RAM Info: &gt;&gt; &quot;%FileName%.txt&quot; setlocal EnableDelayedExpansion set Count=1 for /F &quot;tokens=* USEBACKQ&quot; %%F in (`cmd /c &quot;wmic memorychip get devicelocator, manufacturer, partnumber, serialnumber, capacity, speed, memorytype, formfactor&quot;`) do ( set Var!Count!=%%F set /a Count=!Count!+1 :LoopRam if &quot;(%%F)&quot;==&quot;&quot; ( goto LoopRam ) else ( echo(%%F &gt;&gt; &quot;%FileName%.txt&quot; ) ) endlocal :: Add systeminfo to file cmd /c &quot;systeminfo&quot; &gt;&gt; &quot;%FileName%.txt&quot; :: Add local IP info to file echo __________________________________________________________________________________________________________________ &gt;&gt; &quot;%FileName%.txt&quot; echo. &gt;&gt; &quot;%FileName%.txt&quot; cmd /c &quot;ipconfig /all&quot; &gt;&gt; &quot;%FileName%.txt&quot; :: Add Drive info to file echo. &gt;&gt; &quot;%FileName%.txt&quot; echo __________________________________________________________________________________________________________________ &gt;&gt; &quot;%FileName%.txt&quot; echo. &gt;&gt; &quot;%FileName%.txt&quot; echo Drive Information: &gt;&gt; &quot;%FileName%.txt&quot; cmd /c &quot;powershell.exe -c &quot;get-psdrive -psprovider filesystem&quot;&quot; &gt;&gt; &quot;%FileName%.txt&quot; :: Run script to email file if exist &quot;.\ps2.ps1&quot; (PowerShell -NoProfile -ExecutionPolicy Bypass -Command &quot;&amp; '.\ps2.ps1'&quot;) else ( echo __________________________________________________________________________________________________________________ &gt;&gt; &quot;%FileName%.txt&quot; echo. &gt;&gt; &quot;%FileName%.txt&quot; echo Unable to send email of text file. Script file not found. &gt;&gt; &quot;%FileName%.txt&quot; goto skipPS2 ) :skipPS2 :: End of program cls echo. echo. echo. echo System information has been retrieved. echo Press any key to exit. pause &gt;nul </code></pre> <pre><code># *** ps.ps1 *** Version 1.0 *** 2021-10-22 *** Author: Boogershut *** # This script adds the Public IP to the text file created by 'Get System Info.bat'. # Tests connection if (Test-Connection 216.146.43.70 -Count 1 -Quiet) { # Remove excess garbage from filename for proper formatting $filename = gci .\ | sort LastWriteTime | select -last 1 | select Name $filename = $filename -replace 'Name' $filename = $filename -replace '\@' $filename = $filename -replace '[{}]' $filename = $filename -replace '\=' # Add html from Public IP webpage invoke-webrequest 'http://checkip.dyndns.com/' -UseBasicParsing | Add-Content $filename # Remove excess html garbage $Content = Get-Content $filename $Content.replace(&quot;&lt;html&gt;&lt;head&gt;&lt;title&gt;Current IP Check&lt;/title&gt;&lt;/head&gt;&lt;body&gt;Current&quot;,&quot;Public&quot;) | Set-Content $filename $Content = Get-Content $filename $Content.replace(&quot;&lt;/body&gt;&lt;/html&gt;&quot;,&quot;&quot;) | Set-Content $filename }else { # Remove excess garbage from filename for proper formatting $filename = gci .\ | sort LastWriteTime | select -last 1 | select Name $filename = $filename -replace 'Name' $filename = $filename -replace '\@' $filename = $filename -replace '[{}]' $filename = $filename -replace '\=' # Add text to file Add-Content $filename 'Unable to get Public IP Address. Was unable to ping webpage.' } </code></pre> <pre><code># *** ps2.ps1 *** Version 1.0 *** 2021-10-22 *** Author: Boogershut *** # This script sends an email with the text file created by 'Get System Info.bat' attached. # Tests connection if (Test-Connection 142.250.141.27 -Count 1 -Quiet) { # Remove excess garbage from filename for proper formatting $filename = gci .\ | sort LastWriteTime | select -last 1 | select Name $filename = $filename -replace 'Name' $filename = $filename -replace '\@' $filename = $filename -replace '[{}]' $filename = $filename -replace '\=' $shortname = $filename.Substring(0,$filename.Length-4) # Send email Send-MailMessage -From 'NAME &lt;EMAIL&gt;' -To 'NAME &lt;EMAIL&gt;' -Subject $shortname -Body $shortname -Attachments $filename -Priority High -SmtpServer 'smtp.google.com' }else { # Remove excess garbage from filename for proper formatting $filename = gci .\ | sort LastWriteTime | select -last 1 | select Name $filename = $filename -replace 'Name' $filename = $filename -replace '\@' $filename = $filename -replace '[{}]' $filename = $filename -replace '\=' # Add text to file Add-Content $filename '__________________________________________________________________________________________________________________' Add-Content $filename ' ' Add-Content $filename 'Unable to send email. Was unable to ping SMTP Server.' } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T20:59:06.827", "Id": "531217", "Score": "1", "body": "is there a reason to NOT use the `Get-ComputerInfo` cmdlet?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T21:27:51.030", "Id": "531221", "Score": "0", "body": "@Lee_Dailey I like the formatting of `systeminfo` a bit better. Plus, I'm not sure if `Get-ComputerInfo` has all the same info I'm pulling from the other commands." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T00:08:38.283", "Id": "531230", "Score": "0", "body": "i would try to stay in one type of scripting lingo instead of mixing .BAT and .ps1 stuff. however, if you can't ... then you can't." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T15:54:03.677", "Id": "531412", "Score": "0", "body": "@Lee_Dailey Thanks, I like that advice. This is my first time coding and I wasn't sure how to accomplish everything in one language." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T22:02:49.477", "Id": "531438", "Score": "0", "body": "you are most welcome! [*grin*] ///// as an aside ... why are you using such a strange series of replacements on your file names? plus, why are you doing it _twice_? the else test makes sense ... but grabbing the newest file, stripping out unwanted stuff looks like the same process being done 2 times." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T23:47:38.360", "Id": "531443", "Score": "0", "body": "@Lee_Dailey I'm not sure... Can you point out the specific spots and if you have a possible correction?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T12:23:18.113", "Id": "531485", "Score": "0", "body": "[1] the blocks that start with `$filename = gci .\\ |` seem to do the same thing ... so i would rewrite your code to do that only ONE time. ///// [2] also, what does the file name actually look like? ///// [3] also also, you can chain `-replace` calls. so you could do all the replacements in one chain instead of 4 independent assignments." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T16:00:28.387", "Id": "531508", "Score": "0", "body": "@Lee_Dailey\n[1, 3] This is what I came up with with those suggestions, at the top of ps.ps1 outside of the if statement and deleted the others (whole code is too big for a comment) Doing this shortened my code by 11 lines! \n`$filename = gci .\\ | sort LastWriteTime | select -last 1 | select Name\n$filename = $filename -replace 'Name' -replace '\\@' -replace '[{}]' -replace '\\='`\n[2] The filename the bat creates is \"Test 1234 - System Info_20211026-081903.txt\". The ps.ps1 turns it into \"@{Name=Test 1234 - System Info_20211026-081903.txt}\".\n///// Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T18:06:00.340", "Id": "531514", "Score": "0", "body": "this `@{Name=Test 1234 - System Info_20211026-081903.txt}` is what you get when \"stringify\" an object with a single property. what you WANT is not the object OR the property ... you want the value in that property. i think that `$FileName.Name` will give the full name of the file at text." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T19:52:25.367", "Id": "531521", "Score": "0", "body": "@Lee_Dailey I changed it to `$filename = (gci .\\ | sort LastWriteTime | select -last 1 | select Name).Name` and deleted the second line. Not sure if that is the proper way to do it but it works... Thanks for the tips!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T20:36:33.477", "Id": "531529", "Score": "0", "body": "kool! that works even better ... and you are most welcome! [*grin*]" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T20:32:32.777", "Id": "269268", "Score": "1", "Tags": [ "powershell", "batch" ], "Title": "Batch/Powershell program to retrieve system info" }
269268
<p><strong>The problem is to count number of appearence of the number k in (n*n) Multiplication table</strong></p> <p><strong>I just wrote this code to solve this problem</strong></p> <p><strong>Is there a faster way to solve this problem?</strong></p> <pre><code> long n = in.nextLong(); long k = in.nextLong(); long count = 0; for (long i = 1; i &lt;= n; i++) { if (k % i == 0 &amp;&amp; k / i &lt;= n) { count++; } } System.out.println(count); </code></pre> <p><strong>Multiplication table example</strong></p> <p><a href="https://i.stack.imgur.com/n1k5o.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/n1k5o.png" alt="Multiplication Table" /></a></p> <p><strong>thanks &lt;3</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T20:24:31.433", "Id": "531292", "Score": "2", "body": "You probably had an idea for an algorithm to code. Which you don't explicitly present in your question, let alone in above code. Did you think about using algebra beyond *counting*? Is there any symmetry?" } ]
[ { "body": "<p>I can't say for sure there is no faster way, but there is definitely a cleaner way and also one that is more complete.</p>\n<ul>\n<li>In java it will not slow down your program if you choose more <strong>descriptive names</strong>.</li>\n<li>I would also <strong>extract the function</strong> from the logic reading inputs to make it more readable.</li>\n<li>If tableSizes up to 46340 (square root of largest int) are sufficient int will work fine, but even long will only work up until 3,037,000,499. Whichever you use, you might want to <strong>throw an error when the inputs exceed these boundaries</strong>. I won't in these examples, but it is something to be considered.</li>\n</ul>\n<p>For example:</p>\n<pre class=\"lang-java prettyprint-override\"><code>private int multiplicationTableAppearancesFor(int tableSize, int targetNumber) {\n int count = 0;\n for (int i = 1; i &lt;= tableSize; i++) {\n if (targetNumber % i == 0 &amp;&amp; targetNumber / i &lt;= tableSize) {\n count++;\n }\n }\n return count;\n}\n</code></pre>\n<p>Also, your code will run needlessly when the target number is negative ,zero or bigger than tableSize². You could solve this with a <strong>check</strong>:</p>\n<pre class=\"lang-java prettyprint-override\"><code>private int multiplicationTableAppearancesFor(int tableSize, int targetNumber) {\n if (targetNumber &lt; 1 || targetNumber &gt; Math.pow(tableSize, 2)) {\n return 0;\n }\n int count = 0;\n for (int i = 1; i &lt;= tableSize; i++) {\n if (targetNumber % i == 0 &amp;&amp; targetNumber / i &lt;= tableSize) {\n count++;\n }\n }\n return count;\n}\n</code></pre>\n<p>You could however also include <strong>negative tables</strong>:</p>\n<pre class=\"lang-java prettyprint-override\"><code>private int multiplicationTableAppearancesFor(int tableSize, int targetNumber) {\n if (targetNumber == 0 || targetNumber &gt; Math.pow(tableSize, 2)) {\n return 0;\n }\n int count = 0;\n for (int i = 1; i &lt;= Math.abs(tableSize); i++) {\n if (targetNumber % i == 0 &amp;&amp;\n Math.abs(targetNumber) / i &lt;= Math.abs(tableSize)) {\n count++;\n }\n }\n return count * 2; // Times 2 if you want the occurrences in all quadrants\n}\n</code></pre>\n<p>To further clean this function you could <strong>name the checks</strong> for readability, e.g.:</p>\n<pre class=\"lang-java prettyprint-override\"><code>private static boolean divisionOfAbsoluteIsSmallerThan(int dividend, int divisor, int tableSize) {\n return Math.abs(targetNumber) / i &lt;= Math.abs(tableSize);\n}\n\nprivate static boolean isDivisibleBy(int dividend, int divisor) {\n return targetNumber % i == 0;\n}\n</code></pre>\n<p>Altogether that would leave you with this <strong>result</strong>:</p>\n<pre class=\"lang-java prettyprint-override\"><code>private int multiplicationTableAppearancesFor(int tableSize, int targetNumber) {\n if (targetNumber == 0 || targetNumber &gt; Math.pow(tableSize, 2)) {\n return 0;\n }\n int count = 0;\n for (int i = 1; i &lt;= Math.abs(tableSize); i++) {\n if (isDivisibleBy(targetNumber, i) &amp;&amp;\n divisionOfAbsoluteIsSmallerThan(targetNumber, i, tableSize)) {\n count++;\n }\n }\n return count * 2; // Times 2 if you want the occurrences in all quadrants\n}\n</code></pre>\n<p><em>There could be a faster way though. You might have noticed that <strong>when the targetNumber is smaller than or equal to the table size</strong>, it holds true that the <strong>occurrences are equal to the number of divisors</strong> of the targetNumber. I'm just not sure how to correct for the numbers falling outside of the table, and believe you would end up with similar code and similar complexities. When looking for divisors however, you could possibly get the time complexity down to O(sqrt(n)), because they come in pairs.</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T20:34:58.937", "Id": "531293", "Score": "0", "body": "it's fast but still did'n solve it fast as they want and the number can be reach 10^13\nanyway thanks for your great effort <3 i'm really grateful <3" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T21:12:34.123", "Id": "531294", "Score": "0", "body": "I think you should be thinking in the direction of getting the divisor pairs for numbers smaller than the target number, up until you reach a number you already have... For example with 12 in a 10x10... 1:12 (12 is too big), 2:6 (+1, and add 6 to a collection), 3:4 (+1, and add 4 to a collection), 4:3 (4 already in collection, break). Then you have all the pairs in the upper triangle and need to double those that aren't NxN... I will happily review your next attempt too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T21:16:42.647", "Id": "531295", "Score": "0", "body": "You could probably save even more time starting from the target number or size whichever is lower going down... And there might even be some 'magic' algebra I'm missing. People on [Mathematics](https://math.stackexchange.com/) would surely be able to help with that better than I can." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T12:10:27.763", "Id": "269292", "ParentId": "269271", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T19:59:27.083", "Id": "269271", "Score": "0", "Tags": [ "java" ], "Title": "count number of appearence of the number k in (n*n) multiplication table" }
269271
<p>I have been trying to write a small test program and I was trying to think of any potential optimization I could do, especially if there is any chance to avoid some of the for loops.</p> <p>The program has Dad class, a Child class and a DadChild class that holds the IDs of the Dad and Child objects that are associated based on their DNA.</p> <p>The requirements are:</p> <ol> <li>A Dad object can be associated with multiple Child objects</li> <li>A Child object can NOT be associated with more than 1 Dad objects</li> <li>Out of all Child objects that are associated with the a Dad object, only one has to be marked as bestMatch.</li> </ol> <p>Here is the sample code that I drafted, it works as expected, but I wondering if there is any space for optimizations.</p> <pre><code>#include&lt;iostream&gt; #include&lt;vector&gt; #include&lt;map&gt; #include &lt;algorithm&gt; #include &lt;memory&gt; class Dad { public: Dad(int a_id, int a_dna): id(a_id), DNA(a_dna) {} int id; int DNA; }; class Child { public: Child(int a_id, int a_dna): id(a_id), DNA(a_dna) {} int id; int DNA; }; class DadChild { public: DadChild(): dnaResult(-1) {} DadChild(bool a_bestMatch, int a_childID, int a_dadID, double a_dnaResult): bestMatch(a_bestMatch), childID(a_childID), dadID(a_dadID), dnaResult(a_dnaResult) {} int dadID; int childID; double dnaResult; bool bestMatch; }; double compareDNA (int a, int b) { return abs(a - b); // 0 indicates a perfect match } DadChild createDadChild(Dad d) { //Do something for single parents. Not really that important here. return DadChild(); } DadChild createDadChild(Dad d, Child c, double dnaTest) { //Construct and return DadChild Object DadChild dc; dc.bestMatch = false; dc.childID = c.id; dc.dadID = d.id; dc.dnaResult = dnaTest; return dc; } int main() { Dad d1 (1, 1); Dad d2 (2, 4); Child c0 (0, 4); Child c1 (1, 2); Child c2 (2, 3); Child c3 (3, 1); std::vector&lt;Dad&gt; dads; std::vector&lt;Child&gt; children; dads.push_back(d1); dads.push_back(d2); children.push_back(c0); children.push_back(c1); children.push_back(c2); children.push_back(c3); std::map &lt;int, DadChild&gt; assocMap; // Where the the key is the childID std::vector &lt;DadChild&gt; singleDadVector; for (auto &amp;dad : dads) { bool singleParent = true; for (auto &amp;child : children) { double dnaTest = compareDNA(dad.DNA, child.DNA); if (dnaTest &lt; 2) { // 2 here is an arbitrary threshold for the dna result singleParent = false; auto search = assocMap.find(child.id); if (search != assocMap.end()) { if (assocMap[child.id].dnaResult &gt; dnaTest) { assocMap[child.id] = createDadChild(dad, child, dnaTest); } } else { assocMap[child.id] = createDadChild(dad, child, dnaTest); } } } if (singleParent) singleDadVector.push_back(createDadChild(dad)); } // Try to find the bestMatch. // I am wondering if there is a better way to do this. for (auto const &amp;dad : dads) { DadChild dc; DadChild *bestDadChild = &amp;dc; for (auto &amp;assoc: assocMap) { if ((dad.id == assoc.second.dadID) &amp;&amp; (bestDadChild-&gt;dnaResult == -1)) { bestDadChild = &amp;assoc.second; } else if ((dad.id == assoc.second.dadID) &amp;&amp; assoc.second.dnaResult &lt; bestDadChild-&gt;dnaResult) { bestDadChild = &amp;assoc.second; } } bestDadChild-&gt;bestMatch = true; } /* // I tried to do something like this, but it didn't really work. for (auto &amp;dad : dads) { auto pr = std::min_element( std::begin(assocMap), std::end(assocMap), [dad] (const auto &amp;p1, const auto &amp;p2) { return ((dad.id == p1.second.dadID) &amp;&amp; (dad.id == p2.second.dadID) &amp;&amp; (p1.second.dnaResult &lt; p2.second.dnaResult)); }); pr-&gt;second.bestMatch = true; std::cout &lt;&lt; dad.id &lt;&lt; std::endl; std::cout &lt;&lt; &quot;Setting: &quot; &lt;&lt; pr-&gt;second.dadID &lt;&lt; std::endl; }*/ for (auto &amp;a : assocMap) { std::cout &lt;&lt; &quot;DadID: &quot; &lt;&lt; a.second.dadID &lt;&lt; std::endl; std::cout &lt;&lt; &quot;ChildID: &quot; &lt;&lt; a.second.childID &lt;&lt; std::endl; std::cout &lt;&lt; &quot;bestMatch: &quot; &lt;&lt; a.second.bestMatch &lt;&lt; std::endl; std::cout &lt;&lt; &quot;dnaResult: &quot; &lt;&lt; a.second.dnaResult &lt;&lt; std::endl; std::cout &lt;&lt; &quot;--------------&quot; &lt;&lt; std::endl; } } </code></pre> <p>Output:</p> <pre><code>DadID: 2 ChildID: 0 bestMatch: 1 dnaResult: 0 -------------- DadID: 1 ChildID: 1 bestMatch: 0 dnaResult: 1 -------------- DadID: 2 ChildID: 2 bestMatch: 0 dnaResult: 1 -------------- DadID: 1 ChildID: 3 bestMatch: 1 dnaResult: 0 -------------- </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T23:10:18.493", "Id": "531226", "Score": "1", "body": "What is the goal of this piece of code? That is, given a bunch of DNA tests, what do you want it to print out?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T23:49:22.200", "Id": "531228", "Score": "0", "body": "@ZacharyVance I replied to you below as well, but in general the goal was to just create pairs of Child and Dad objects.\n\nI was not really planning to go far with this, but rather to use this draft piece of code as a base for discussion and food for thought." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T07:52:48.293", "Id": "531244", "Score": "1", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T18:01:32.350", "Id": "531282", "Score": "0", "body": "(The pronunciation of `DadChild` is irritating.)" } ]
[ { "body": "<h2>Documentation</h2>\n<p>Add documentation.</p>\n<p>I had no idea what the goal of this program is, going in, and at the end of the review I still don't, so I can't comment on whether the code is correct or efficient.</p>\n<ul>\n<li>Do we want to output the most likely child for a father? The most likely father for a child?</li>\n<li>What does &quot;singleParent&quot; mean? Often in this context it would mean that one person is raising a child?</li>\n<li>Are higher DNA test results closer matches, or farther?</li>\n<li>What is 'bestMatch'? Is this an ID? And ID of a child or a dad? A DNA test result? What does it mean?</li>\n</ul>\n<h2>Style</h2>\n<p>Based on the names, something around paternity testing, but that's it. Is the goal to output the most likely dad for each child? The most likely child for each dad? The paternity test results for every input?</p>\n<ul>\n<li><code>DadChild</code> is a bad class name. I have no idea what it does without reading your documentation.</li>\n<li><code>assocMap</code> is a bad name, because it doesn't say what it maps between.</li>\n<li>Replace your entire inner dad loop with <code>std::max</code>. Also, <code>bestDadChild</code> should not be initialized to a bogus object. Use std::optional or a null pointer.</li>\n</ul>\n<h2>Initialization</h2>\n<ul>\n<li>Remove the DadChild empty constructor--the code you have to initialize DadChild is bad and it's because you're not using a single constructor call.</li>\n<li>Replace both versions of createDadChild by constructors.</li>\n<li>Initialize your hardcoded std::vector in <a href=\"https://stackoverflow.com/questions/2236197/what-is-the-easiest-way-to-initialize-a-stdvector-with-hardcoded-elements\">one statement</a></li>\n</ul>\n<h2>Loops</h2>\n<p>As far as loops go, the three top-level loops look fine. Don't worry about it. You can unify them but I would say that makes things <em>less</em> readable, and no faster.</p>\n<p>If you are worried about the inner loops being slow, you're correct. I don't understand what you're trying to do well enough to know if you're doing it or if there's a better way. Sorry.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T23:43:29.907", "Id": "531227", "Score": "0", "body": "Thanks for your comment @Zachary!\nI will try to do some updates accordingly.\n\nBut just to clarify, this is supposed to be a dummy program that just creates pairs of Dad and Child objects based on an arbitrary parameter like DNA. Perhaps DadChildPair would be a better name for the class?\n\nI was not planning to go far with this program, but rather to use this draft example for discussion and understand ways around unnecessary for loops.\n\nPS\nI am terrible at naming variables etc :P" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T23:16:01.013", "Id": "269277", "ParentId": "269272", "Score": "4" } }, { "body": "<h2>General points</h2>\n<ul>\n<li><p>Why does <code>compareDNA</code> return a double when the inputs are both ints and the output thus can only ever be an <code>int</code>.</p>\n</li>\n<li><p>The same function <code>compareDNA</code> seams out of place. This can be a method of a person. In rewrite see <code>Person.compareDNA</code></p>\n</li>\n<li><p>Avoid magic numbers. Use a constant to give number (strings, whatever) meaning. eg <code>const int MAX_DNA_DISTANCE{2};</code></p>\n</li>\n<li><p>Break the code into smaller functions. Having long functions doing multiple tasks makes the code hard to read and maintain. Eg your <code>main</code> function</p>\n</li>\n</ul>\n<h2>Object design</h2>\n<p><code>Dad</code> and <code>Child</code> are identical, so why create two independent classes. Both <code>Dad</code> and <code>Child</code> are people so create a class that holds a <code>Person</code>.</p>\n<p>The vectors <code>dads</code> and <code>children</code> define who is who</p>\n<p>There is a one to many link from parent to child.</p>\n<p>Move the relationship map (map of parent's children by id) to the parent object</p>\n<p>Rather than using the awkward <code>DadChild</code> object create an object called <code>Relative</code> that is derived from a <code>Person</code>. Have it hold all related children as a <code>vector</code> or <code>map</code></p>\n<p>See rewrite.</p>\n<h2>Unique identifiers</h2>\n<p>Always ensure that identifiers are unique.</p>\n<p>You are giving the same ID to both a Dad object and Child object. This will become problematic if ever a Child becomes a Dad. Even if not the case it is far easier to automatically assign IDs than needing to make them up as you go.</p>\n<p>In the rewrite the ids (<code>uid</code> for unique identifier) is generated using a function <code>GetUid</code> and is automatic when a person is created.</p>\n<h2>Protect object's state</h2>\n<p>Do not expose states that are not needed when using the object.</p>\n<p>In the rewrite example I protect states like <code>id</code> and <code>DNA</code> to ensure that outside code can not corrupt the data.</p>\n<p>In your code there is nothing stopping the code from changing the <code>id</code> or <code>DNA</code>\non purpose or by mistake. If this happens all the related data is useless, further processing will result in undefined behavior.</p>\n<p>Using methods as getters and setter helps protect state.</p>\n<h3>Simple getters</h3>\n<p>To gain access to these values I use methods so that the values can be read but not changed outside the object.</p>\n<p>examples</p>\n<ul>\n<li><p><code>Person.dna()</code> as protected methid to give access to <code>dna</code> value only to objects related to <code>Person</code>.</p>\n</li>\n<li><p><code>Person.id()</code> as private method to give access to <code>uid</code> value only to instances of person. Eg <code>Relative</code> can not change the <code>uid</code></p>\n</li>\n</ul>\n<h2>Rewrite</h2>\n<p>Rather than have the three object types <code>Dad</code>, <code>Child</code>, <code>DadChild</code> the rewrite has two, a <code>Person</code> and a <code>Relative</code>.</p>\n<p>A <code>Relative</code> is also a <code>Person</code>.</p>\n<p>The relative has methods and properties to keep track of children (closely matching DNA)</p>\n<p>Once the people are created it is then just a matter of looping over each child and checking each parent if there is a relationship <code>Relative.isRelated</code>. If so the child is added to the parents list of children.</p>\n<p>The check for closest matching DNA is done when the child is checked <code>Relative.isRelated</code></p>\n<p>The parent <code>Relative</code> has a function <code>report</code> that outputs children etc..</p>\n<pre><code>#include&lt;iostream&gt;\n#include&lt;vector&gt;\n#include&lt;map&gt;\n\nconst int MAX_DNA_DISTANCE{2};\nint GetUid() {\n static int id{1};\n return id++;\n}\n\nclass Person {\nprivate: \n int uid{GetUid()};\n int DNA;\nprotected:\n int dna() { return DNA; }\npublic:\n Person(int dna): DNA(dna) {} \n int compareDNA (int _dna) { return dna() &gt;= _dna ? dna() - _dna : _dna - dna(); }\n int id() { return uid; }\n};\n\nclass Relative: public Person {\nprivate:\n std::map&lt;int, Person *&gt; children;\n size_t childCount{0};\n Person *bestChild{nullptr};\n int bestDNA{-1};\npublic:\n Relative(int dna): Person(dna) {}\n bool isRelated(Person *child) {\n int DNA_similarity = child-&gt;compareDNA(dna());\n if (DNA_similarity &lt; MAX_DNA_DISTANCE &amp;&amp; children.find(child-&gt;id()) == children.end()) {\n if (bestChild == nullptr || bestDNA &gt; DNA_similarity) {\n bestDNA = DNA_similarity;\n bestChild = child;\n }\n childCount++;\n children[child-&gt;id()] = child;\n return true;\n }\n return false; \n }\n void report() {\n const size_t cc = childCount;\n std::cout &lt;&lt; &quot;ParentID: &quot; &lt;&lt; id() &lt;&lt; &quot; has &quot;;\n if (cc == 0) { std::cout &lt;&lt; &quot;no children :)\\n&quot;; }\n else {\n if (cc == 1) { std::cout &lt;&lt; &quot;one childID: &quot; &lt;&lt; bestChild-&gt;id() &lt;&lt; &quot; with &quot;; }\n else { std::cout &lt;&lt; cc &lt;&lt; &quot; children. Best childID: &quot; &lt;&lt; bestChild-&gt;id() &lt;&lt; &quot; having &quot;; }\n std::cout &lt;&lt; &quot;a DNA similarity of &quot; &lt;&lt; bestDNA &lt;&lt; &quot;.\\n&quot;;\n }\n }\n};\n\nstd::vector&lt;Relative *&gt; parents;\nvoid parent(int dna) { parents.push_back(new Relative(dna)); }\nstd::vector&lt;Person *&gt; children;\nvoid child(int dna) { children.push_back(new Person(dna)); }\n\nbool findChildsParent(Person *child) {\n for (auto rel: parents) {\n if (rel-&gt;isRelated(child)) { return true; }\n }\n return false; \n}\n\nint main() {\n for (auto dna: {10, 5, 33, 4, 2, 3, 1}) { child(dna); }\n for (auto dna: {1, 4, 11, 20}) { parent(dna); }\n for (auto c: children) { \n if (!findChildsParent(c)) { std::cout &lt;&lt; &quot;ChildID: &quot; &lt;&lt; c-&gt;id() &lt;&lt; &quot; has no known relatives :(\\n&quot;; }\n }\n for (auto p: parents) { p-&gt;report(); }\n return 0;\n}\n</code></pre>\n<p>Expected output</p>\n<pre><code>ChildID: 3 has no known relatives :(\nParentID: 8 has 2 children. Best childID: 7 having a DNA similarity of 0.\nParentID: 9 has 3 children. Best childID: 4 having a DNA similarity of 0.\nParentID: 10 has one childID: 1 with a DNA similarity of 1.\nParentID: 11 has no children :)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T10:19:34.487", "Id": "531255", "Score": "0", "body": "Many good points, but I see some issues with your rewrite. There is no need to have the global vectors `parents` and `children` store pointers, they can just store the objects directly. And I would not create functions `parent()` and `child()`, especially since they are only used once. Instead, just write: `for (auto dna: {...}) { parents.emplace_back(dna); }`, or just write: `std::vector<Relative> parents = {{10}, {5}, {33}, ...};`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T07:47:56.173", "Id": "269285", "ParentId": "269272", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T22:36:24.263", "Id": "269272", "Score": "2", "Tags": [ "c++", "performance", "c++11" ], "Title": "How to avoid excessive for loops in C++" }
269272
<p>There is the following method that should get record from the database, apply new data, and if at least one value has been changed, update database and send event</p> <p>We don't use EntityFramework, it uses CosmosDb SDK in the repository.</p> <p>I'm not sure how is the proper way to implement <code>hasChanges</code>.</p> <pre><code>public async Task&lt;Unit&gt; Handle(ChangeLiftStateCommand request, CancellationToken cancellationToken) { Lift lift = await _repository.Get(request.Number, cancellationToken) ?? throw new NotFoundException(request.Number); bool hasChanges = false; if (Enum.TryParse(request.HealthState, ignoreCase: true, out HealthState healthState)) { if (lift.State.HealthState != healthState) { lift.State.HealthState = healthState; hasChanges = true; } } if (lift.State.GenericState != request.GenericState) { lift.State.GenericState = request.GenericState; hasChanges = true; } if (request.CabinPosition.HasValue) { Cabin cabin = lift.Cabins.FirstOrDefault(c =&gt; c.Type == CabinType.Main); if (cabin is null) { lift.Cabins.Add(new Cabin { Deck = Deck.Lower, Position = request.CabinPosition.Value }); hasChanges = true; } else { if (cabin.Position != request.CabinPosition.Value) { cabin.Position = request.CabinPosition.Value; hasChanges = true; } } } if (hasChanges) { await _repository.Update(lift); await _eventProducer.Send(new LiftChangedEvent { Number = request.Number, CabinPosition = request.CabinPosition, HealthState = request.HealthState, GenericState = request.GenericState }); } return Unit.Value; } </code></pre> <p>Could you please advice how it can be refactored? Are there any pattern for <code>hasChanges</code> implementation? Thank you in advance</p>
[]
[ { "body": "<p>You can move <code>HealthState</code> and <code>Cabin</code> portions into separate methods as each one of them serve a single purpose for a single property. So, moving them into their own methods would give more freedom and extensibility such as adding more requirements, some other future changes .etc. Plus, it would be reusable in the current scope, and you can make it reusable into other scopes by exposing them or using extension methods.</p>\n<p>For me, I feel extension methods would be the way to go like this :</p>\n<pre><code>public static ChangeLiftStateCommandExtensions\n{\n public static bool TryUpdateHealthState(this ChangeLiftStateCommand request, Lift lift)\n {\n if (Enum.TryParse(request.HealthState, ignoreCase: true, out HealthState healthState))\n {\n if (lift.State.HealthState != healthState)\n {\n lift.State.HealthState = healthState;\n return true;\n }\n }\n \n return false;\n }\n\n public static bool TryUpdateCabin(this ChangeLiftStateCommand request, Lift lift)\n {\n Cabin cabin = lift.Cabins.FirstOrDefault(c =&gt; c.Type == CabinType.Main); \n \n if (request.CabinPosition.HasValue)\n {\n if (cabin is null)\n {\n lift.Cabins.Add(new Cabin\n {\n Deck = Deck.Lower,\n Position = request.CabinPosition.Value\n });\n \n return true;\n }\n else\n {\n if (cabin.Position != request.CabinPosition.Value)\n {\n cabin.Position = request.CabinPosition.Value;\n \n return true;\n }\n }\n }\n \n return false;\n } \n}\n</code></pre>\n<p>Then, your actual method would changed to this :</p>\n<pre><code>public async Task&lt;Unit&gt; Handle(ChangeLiftStateCommand request, CancellationToken cancellationToken)\n{\n Lift lift = await _repository.Get(request.Number, cancellationToken)\n ?? throw new NotFoundException(request.Number);\n\n \n bool isHealthStateUpdated = request.TryUpdateHealthState(lift);\n\n bool isCabinUpdated = request.TryUpdateCabin(lift);\n \n if (isHealthStateUpdated || isCabinUpdated)\n {\n await _repository.Update(lift);\n\n await _eventProducer.Send(new LiftChangedEvent\n {\n Number = request.Number,\n CabinPosition = request.CabinPosition,\n HealthState = request.HealthState,\n GenericState = request.GenericState\n });\n }\n\n return Unit.Value;\n}\n</code></pre>\n<p>you can also override the <code>Equals</code> on <code>Lift</code>, so you can make a copy of the object as source copy, and work with one copy, and when you're done, compare both versions.</p>\n<p>Something like this :</p>\n<pre><code>Lift lift = await _repository.Get(request.Number, cancellationToken); \nLift liftSource = lift;\n\n/// your work \n\n\nif(!lift.Equals(liftSource))\n{\n // object has changes\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T23:20:23.630", "Id": "531299", "Score": "0", "body": "Thanks. Do you think I should add an extension for GenericState too?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T23:22:41.900", "Id": "531301", "Score": "0", "body": "`Lift` contains man properties and those properties contain other inner properties. Very huge structure. Is it possible to override Equals in some elegant way?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T01:28:41.830", "Id": "531308", "Score": "0", "body": "use extension method on `ChangeLiftStateCommand` if you see it is not going to be used else where ! but if you think that you would do the same procedure else where then you probably need to do the methods else where. (you could add it to the `Lift` directly, or implement a `Manager` class and add all methods into it that suppose to handle `Lift` procedures." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T01:34:53.950", "Id": "531309", "Score": "0", "body": "for the equals, if the class is huge, then don't override the equals, instead, you can add the methods directly to it, or use extension methods on `Lift` directly." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T05:03:02.643", "Id": "269282", "ParentId": "269276", "Score": "1" } } ]
{ "AcceptedAnswerId": "269282", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-22T23:09:47.377", "Id": "269276", "Score": "0", "Tags": [ "c#", "database" ], "Title": "Properly implementing HasChanges pattern for model" }
269276
<p>I just asked this question over Stack Over Flow on how to improve my code and reposting it here as someone on Stack Overflow recommended this platform.</p> <p>I have written two python functions and they are correct, but I believe this is not the efficient way to write them, and I am wondering if some can give their input on how to improve them.</p> <p>The first function is the following which generates an odd number of weights that sum up to one.</p> <pre><code>import numpy as np # the argument of the following function has to an non-negative and odd # integer def weights(n_w): M = int((n_w+1)/2) j = np.arange(-M+1, M,1) w = 2.**(-j**2) w = w/w.sum() return w </code></pre> <p>If I now type</p> <pre><code>weights(5) </code></pre> <p>I get five weights, which add up to 1.</p> <pre><code>Out[442]: array([0.02941176, 0.23529412, 0.47058824, 0.23529412, 0.02941176]) </code></pre> <p>The first and last entry of the output array is the same and similarly second and the fourth are also the same.</p> <p>So, I can generate any odd number of normalized weights using the function above.</p> <p>I have used this function to write the following function which generates an n by n square matrix with each row having an odd number of weights and zeros.</p> <pre><code>def weight_matrix(n_w,n): w_matrix = np.zeros((n,n)) M = int((n_w+1)/2) W_main = weights(n_w) for m in range(1,M-1): w = weights(2*m+1) w_matrix[m,:int(len(w))] = w w_matrix += w_matrix[::-1,::-1] w_matrix[0,0], w_matrix[-1,-1] = [1,1] nn = 0 for m in range(M-1,n-M+1): w = W_main w_matrix[m,nn:nn+n_w] = w nn += 1 return w_matrix </code></pre> <p>An example of this function is</p> <pre><code>weight_matrix(5,7) </code></pre> <p>where the second argument specifies the dimension of the output matrix and the first argument decides the maximum number weights to be generated.</p> <p>Following is the output:</p> <pre><code>array([[1. , 0. , 0. , 0. , 0. , 0. , 0. ], [0.25 , 0.5 , 0.25 , 0. , 0. , 0. , 0. ], [0.02941176, 0.23529412, 0.47058824, 0.23529412, 0.02941176, 0. , 0. ], [0. , 0.02941176, 0.23529412, 0.47058824, 0.23529412, 0.02941176, 0. ], [0. , 0. , 0.02941176, 0.23529412, 0.47058824, 0.23529412, 0.02941176], [0. , 0. , 0. , 0. , 0.25 , 0.5 , 0.25 ], [0. , 0. , 0. , 0. , 0. , 0. , 1. ]]) </code></pre> <p>Each row adds up to 1</p> <p>The first element of the first row is 1 which is the only non-zero element of it.</p> <p>Similarly, the last element of the last row is 1 which is the only non-zero element of it.</p> <p>The second row and the second to the last have the same three non-zero elements but at different positions.</p> <p>From row 3 to the last row have the same five non-zero elements but at different positions.</p> <p>These five non-zero elements shift along the diagonal of the matrix.</p> <p>The second function gives me control over what size matrix to generate and how long I shall increase the number of weights.</p> <p>Any suggestion to improve these functions will be appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T04:11:48.987", "Id": "531236", "Score": "0", "body": "@Reinderien I have fixed the indentation. This script contains only these two functions, nothing else." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T08:05:34.373", "Id": "531250", "Score": "0", "body": "Can you describe the distribution you're generating? To my untrained eye, the first function looks like a Gaussian, but I'm not sure what the second one is, or what it's useful for." } ]
[ { "body": "<ul>\n<li>Type-hint your function arguments</li>\n<li>Your <code>weight_matrix</code>, when vectorised, won't be able to rely on <code>weights</code></li>\n<li>Rather than <code>int((n_w+1)/2)</code>, use <code>(n_w + 1)//2</code></li>\n<li>Add some unit tests based on your known criteria and output data</li>\n<li>It is possible to vectorise with no for-loops, which is usually preferred but I have not done detailed performance analysis. I wouldn't be able to perform such analysis unless I knew how often this function was called and with what sizes.</li>\n<li>Your function fails for me for all parameters that I tried that were not <code>(5, 7)</code>, so your index manipulation needs to be improved. If you need to impose that arguments should be odd, you should do so at the top of the function and raise if those conditions are not met.</li>\n<li>Prefer <code>n_weights</code> instead of the abbreviated <code>n_w</code></li>\n</ul>\n<p>The following example vectorisation ignores <code>weights</code>, and uses modified upper triangular indices to zero out the appropriate elements.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import numpy as np\n\n\ndef weights(n_weights: int) -&gt; np.ndarray:\n M = (n_weights + 1) // 2\n j = np.arange(1 - M, M)\n w = 2.**(-j**2)\n return w / w.sum()\n\n\ndef weight_matrix(n_weights: int, n: int) -&gt; np.ndarray:\n j = np.arange(n)[:, np.newaxis]\n w = 2. ** -(j.T - j)**2\n\n # This is a diagonally dominant matrix, but not a diagonal matrix. Moreover,\n # the zero regions do not align with diagonals. A first cut of the zero-\n # region indices comes from the upper triangle with k=1.\n i, j = np.triu_indices(n=n, k=1)\n zeros = j &gt; np.min(\n np.vstack((2*i, i + n_weights//2)),\n axis=0,\n )\n i = i[zeros]\n j = j[zeros]\n w[i, j] = 0\n w[-1-i, -1-j] = 0\n\n return w / np.sum(w, axis=1, keepdims=True)\n\n\ndef test_symmetry(w_matrix: np.ndarray) -&gt; None:\n\n # Each row adds up to 1\n row_sums = np.sum(w_matrix, axis=1)\n assert np.all(np.isclose(\n 1, row_sums, rtol=0, atol=1e-15,\n ))\n\n # The number of non-zeros per row is 2n + 1 to the middle\n nonzeros = np.sum(\n np.logical_not(np.isclose(\n w_matrix, 0, rtol=0, atol=1e-10,\n )), axis=1,\n )\n half_1 = nonzeros[:len(nonzeros)//2]\n half_2 = nonzeros[len(nonzeros)//2+1:]\n assert np.all(half_1 == half_2[::-1])\n\n\ndef test() -&gt; None:\n # Test with known output\n assert np.all(np.isclose(\n weights(5),\n np.array((0.02941176, 0.23529412, 0.47058824, 0.23529412, 0.02941176)),\n rtol=0, atol=1e-8,\n ))\n\n # Test for symmetry\n w = weights(1000)\n assert w.shape == (999,)\n assert np.all(np.isclose(w[:499], w[:499:-1], rtol=0, atol=1e-16))\n\n actual = weight_matrix(5, 7)\n expected = np.array([\n [1.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000],\n [0.25000000, 0.50000000, 0.25000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000],\n [0.02941176, 0.23529412, 0.47058824, 0.23529412, 0.02941176, 0.00000000, 0.00000000],\n [0.00000000, 0.02941176, 0.23529412, 0.47058824, 0.23529412, 0.02941176, 0.00000000],\n [0.00000000, 0.00000000, 0.02941176, 0.23529412, 0.47058824, 0.23529412, 0.02941176],\n [0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.25000000, 0.50000000, 0.25000000],\n [0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 0.00000000, 1.00000000],\n ])\n assert np.all(np.isclose(actual, expected, rtol=0, atol=1e-8))\n\n test_symmetry(actual)\n test_symmetry(weight_matrix(169, 189))\n\n\nif __name__ == '__main__':\n test()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T22:22:24.413", "Id": "531365", "Score": "0", "body": "Thank you very much! It is really helpful." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T18:39:50.647", "Id": "269305", "ParentId": "269279", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T02:18:46.940", "Id": "269279", "Score": "2", "Tags": [ "python", "performance", "numpy", "machine-learning", "numerical-methods" ], "Title": "Generating a matrix with each row having normalized weights" }
269279
<p>I recently saw a youtube video on printing even and odd numbers from 0 to 100 in Java. <a href="https://www.youtube.com/watch?v=eRNTx8k5cmA" rel="nofollow noreferrer">https://www.youtube.com/watch?v=eRNTx8k5cmA</a></p> <p>Thread 1 prints even numbers and thread 2 prints odd numbers. Both the threads print the numbers till 100.</p> <p>I tried to write something similar in C++. But C++ does not have synchronized keyword and the important sync variables are global. Is there anyway to eliminate the global variables, yet keep the code as flexible and at the same time not repeat the code ?</p> <pre><code>#include&lt;cstdio&gt; #include &lt;iostream&gt; #include &lt;array&gt; #include &lt;thread&gt; #include &lt;mutex&gt; #include &lt;condition_variable&gt; std::mutex m; std::condition_variable cv; bool isEvenGlob = true; void printNum(int initialVal, int finalVal, int step, bool isEven) { for (int i = initialVal; i &lt;= finalVal; i += step) { std::unique_lock&lt;std::mutex&gt; lk(m); cv.wait(lk, [isEven](){ return !(isEven ^ isEvenGlob); }); std::cout &lt;&lt; i &lt;&lt; ' '; isEvenGlob = !isEvenGlob; lk.unlock(); cv.notify_one(); } } int main () { std::thread thEven(printNum, 0, 100, 2, true); std::thread thOdd(printNum, 1, 100, 2, false); thEven.join(); thOdd.join(); } </code></pre> <p>I wrote another version without global variables, but I am still not sure if it is an acceptable answer, especially since isEven is repeated twice -</p> <pre><code>#include&lt;cstdio&gt; #include &lt;iostream&gt; #include &lt;array&gt; #include &lt;thread&gt; #include &lt;mutex&gt; #include &lt;condition_variable&gt; class PrintNums { public: PrintNums(std::mutex&amp; m, std::condition_variable&amp; cv, bool&amp; isEvenGlob) : cv_(cv), m_(m), isEvenGlob_(isEvenGlob) { }; void printValues(int initVal, int finalVal, int step, bool isEven) { for (int i = initVal; i &lt;= finalVal; i += step) { std::unique_lock&lt;std::mutex&gt; lk(m_); cv_.wait(lk, [this, isEven](){ return !(isEven ^ this-&gt;isEvenGlob_); }); std::cout &lt;&lt; i &lt;&lt; ' '; isEvenGlob_ = !isEvenGlob_; lk.unlock(); cv_.notify_one(); } } private: int initVal_, finalVal_, step_; std::condition_variable&amp; cv_; std::mutex&amp; m_; bool&amp; isEvenGlob_; }; int main () { std::mutex m; std::condition_variable cv; bool isEvenGlob = true; PrintNums evenObj(m, cv, isEvenGlob); PrintNums oddObj(m, cv, isEvenGlob); std::thread t1(&amp;PrintNums::printValues, &amp;evenObj, 0, 100, 2, true); std::thread t2(&amp;PrintNums::printValues, &amp;oddObj, 1, 100, 2, false); t1.join(); t2.join(); } </code></pre> <p>Both the versions are printing the correct answer</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T23:25:48.580", "Id": "531302", "Score": "0", "body": "\"Could you show me how you'd take something fast and simple, and use threads to turn it into something slow and complicated?\" Unless I was incredibly desperate for any job I could get, if somebody asked me to do this in an interview, I'd much more likely lecture them on what a bad idea this is than make any attempt at directly \"solving\" the problem." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T11:28:47.073", "Id": "531334", "Score": "0", "body": "Why did you not simply use `return isEven==isEvenGlob;`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T10:04:34.090", "Id": "531565", "Score": "0", "body": "Good idea @upkajdt. I don't know why I chose a round about way to check that. Thanks for pointing it out." } ]
[ { "body": "<h1>Answers to your questions</h1>\n<blockquote>\n<p>Is there anyway to eliminate the global variables?</p>\n</blockquote>\n<p>Yes, you can put them on the stack of a function, like you already did in your second version, or alternatively you can make those variables <code>static</code> member variables of the class.</p>\n<blockquote>\n<p>yet keep the code as flexible and at the same time not repeat the code?</p>\n</blockquote>\n<p>I don't really see any repeated code, apart from the fact that you create and destroy two threads. You could do that in a loop, but for this simple program that's more effort that it is worth.</p>\n<blockquote>\n<p>especially since <code>isEven</code> is repeated twice</p>\n</blockquote>\n<p>Maybe you meant <code>isEvenGlob</code>? One is an actual <code>bool</code> in <code>main()</code>, the other is a <em>reference</em> to a <code>bool</code> in <code>class PrintNums</code>. I wouldn't count that as repeated.</p>\n<h1>Separate the locking from the printing</h1>\n<p>I would try to separate the details of locking as much as possible from the part that prints the numbers. Ideally, you would write something like this:</p>\n<pre><code>void printNum(int initialVal, int finalVal, int step, bool isEven) {\n for (int i = initialVal; i &lt;= finalVal; i += step) {\n auto lock = getLock(isEven);\n std::cout &lt;&lt; i &lt;&lt; ' ';\n }\n}\n</code></pre>\n<p>A possible implementation of <code>getLock()</code> is like so:</p>\n<pre><code>std::unique_lock&lt;std::mutex&gt; getLock(bool isEven) {\n static bool nextIsEven = true;\n static std::mutex mtx;\n static std::condition_variable cond;\n\n // Wait until it is our turn\n std::unique_lock&lt;std::mutex&gt; lock(mtx);\n cond.wait(lock, [&amp;](){ return nextIsEven == isEven; });\n\n // Signal the next thread it is their turn\n nextIsEven = !isEven;\n cond.notify_one();\n\n // But return the lock to the caller so they can do their thing first\n return lock;\n}\n</code></pre>\n<p>If you want to avoid calling <code>notify_one()</code> while still holding the lock, you would have to implement your own lock class that has a destructor that unlocks the mutex and then notifies the condition variable, and have <code>getLock()</code> return an instance of that class.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T09:48:10.473", "Id": "269288", "ParentId": "269283", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T06:25:22.557", "Id": "269283", "Score": "1", "Tags": [ "c++", "multithreading", "interview-questions" ], "Title": "Printing odd and even numbers in separate threads C++" }
269283
<p>This is my first post here, so I apologize if anything is incorrect. I have created an endless arcade stacker game (like the stacker games at the arcade, but when you hit the top the grid resets and you continue endlessly). My intention in the code was to separate out the core game logic (i.e. the code that moves the stack, places it, and resets the grid) from the other logic (i.e. the speed at which the stack moves, the user input, the visual and sound effects) in order to have some sort of separation of concerns.</p> <p>I have made an <code>IStacker</code> interface and a <code>Stacker</code> class that has been implemented the aforementioned interface. Would anyone be able to critique the code? In particular, any logic that could be simplified, and instances where adherence to SOLID principles could be improved.</p> <p>Thanks for any help :)</p> <p>I have included the classes below, but if it is any easier to view them on github I have also provided the links to those below:</p> <p><a href="https://github.com/impojr/Stacker/blob/main/Assets/Scripts/Core/IStacker.cs" rel="nofollow noreferrer">https://github.com/impojr/Stacker/blob/main/Assets/Scripts/Core/IStacker.cs</a> <a href="https://github.com/impojr/Stacker/blob/main/Assets/Scripts/Core/Stacker.cs" rel="nofollow noreferrer">https://github.com/impojr/Stacker/blob/main/Assets/Scripts/Core/Stacker.cs</a></p> <p><strong>IStacker</strong></p> <pre><code>using System.Collections.Generic; namespace Assets.Scripts.Core { public interface IStacker { void ResetGrid(); void Tick(); List&lt;MissResult&gt; Place(); void ResetHeight(); } } </code></pre> <p><strong>Stacker</strong></p> <pre><code>using System.Collections.Generic; using System.Linq; namespace Assets.Scripts.Core { public enum MovementDirection { Left, Right } public class Stacker : IStacker { /// &lt;summary&gt; /// The width of the grid. &lt;b&gt;Not&lt;/b&gt; the width of the moving stack. /// &lt;/summary&gt; public int Width { get; } /// &lt;summary&gt; /// The height of the grid. /// &lt;/summary&gt; public int Height { get; } /// &lt;summary&gt; /// The playing grid. /// &lt;/summary&gt; public Square[,] Stack { get; private set; } /// &lt;summary&gt; /// The move direction of the stack. /// &lt;/summary&gt; public MovementDirection MoveDir { get; private set; } /// &lt;summary&gt; /// The row in the grid where the stack is currently moving. /// &lt;/summary&gt; public int ActiveRow { get; private set; } /// &lt;summary&gt; /// The width of the moving (current) stack. /// &lt;/summary&gt; public int StackWidth { get; private set; } public Stacker(int width, int height, int initialStackWidth) { Width = width; Height = height; StackWidth = initialStackWidth; ResetGrid(); } /// &lt;summary&gt; /// Resets the grid to empty. /// &lt;/summary&gt; public void ResetGrid() { Stack = new Square[Width, Height]; ActiveRow = 0; MoveDir = MovementDirection.Right; for (var i = 0; i &lt; Width; i++) { for (var j = 0; j &lt; Height; j++) { Stack[i, j] = new Square(); } } } /// &lt;summary&gt; /// Move the stack in the grid. /// This will allow move rows if the grid was placed beforehand. /// &lt;/summary&gt; public void Tick() { var cellsToSwitch = new List&lt;int&gt;(); for (var i = 0; i &lt; Width; i++) { if (Stack[i, ActiveRow].State == State.Occupied) { cellsToSwitch.Add(i); } } // If there are no cells to switch, then we are starting a new row if (!cellsToSwitch.Any()) { StartNewRow(); } else { MoveStackInRow(cellsToSwitch); } } private void StartNewRow() { // If there is no active row, it is the start of the game // Start from left if (ActiveRow == 0) { FillRow(0); } // Otherwise, start row from previous stack else { var previousRow = ActiveRow - 1; var nextRowStart = 0; for (var i = 0; i &lt; Width; i++) { if (Stack[i, previousRow].State == State.Occupied) { nextRowStart = i; break; } } FillRow(nextRowStart); } } private void MoveStackInRow(List&lt;int&gt; cellsToSwitch) { // If we are going left and the first item in list is at the beginning of the row, // Change movement direction if (MoveDir == MovementDirection.Left) { if (cellsToSwitch.First() == 0) { MoveDir = MovementDirection.Right; MoveStack(cellsToSwitch, 1); } else { MoveStack(cellsToSwitch, -1); } } else { // If we are going right and the last item in list at the end of the row, // Change movement direction if (cellsToSwitch.Last() == Width - 1) { MoveDir = MovementDirection.Left; MoveStack(cellsToSwitch, -1); } else { MoveStack(cellsToSwitch, 1); } } } /// &lt;summary&gt; /// Moves stack left or right. /// &lt;/summary&gt; /// &lt;param name=&quot;cellsToSwitch&quot;&gt;The column number of the cells that are being moved&lt;/param&gt; /// &lt;param name=&quot;increment&quot;&gt;+1 or -1&lt;/param&gt; private void MoveStack(IList&lt;int&gt; cellsToSwitch, int increment) { for (var i = 0; i &lt; cellsToSwitch.Count; i++) { cellsToSwitch[i] += increment; } for (var i = 0; i &lt; Width; i++) { Stack[i, ActiveRow].State = cellsToSwitch.Contains(i) ? State.Occupied : State.Vacant; } } /// &lt;summary&gt; /// Fills (makes squares occupied) in row in based on StackWidth /// &lt;/summary&gt; /// &lt;param name=&quot;startIndex&quot;&gt;Where in the row filling starts.&lt;/param&gt; private void FillRow(int startIndex) { for (var i = 0; i &lt; StackWidth; i++) { Stack[i + startIndex, ActiveRow].State = State.Occupied; } } /// &lt;summary&gt; /// Places the stack and goes to the next row. /// &lt;/summary&gt; /// &lt;returns&gt;A list of missed stack positions.&lt;/returns&gt; public List&lt;MissResult&gt; Place() { var misses = new List&lt;MissResult&gt;(); // If we are placing at the start of the stack there is no chance for a miss if (ActiveRow != 0) { for (var i = 0; i &lt; Width; i++) { if (Stack[i, ActiveRow].State != State.Occupied) continue; if (Stack[i, ActiveRow - 1].State != State.Vacant) continue; Stack[i, ActiveRow].State = State.Vacant; misses.Add(new MissResult(i, ActiveRow)); StackWidth--; } } IncreaseActiveRow(); return misses; } /// &lt;summary&gt; /// This will move the stack down so the game can continue endlessly. /// &lt;/summary&gt; public void ResetHeight() { // Get the top row variables var highestRow = new Square[Width]; for (var i = 0; i &lt; Width; i++) { // The active row should be increased ever time a stack is placed, // So the highest row should be 1 below the current active row highestRow[i] = Stack[i, ActiveRow - 1]; } ResetGrid(); // The active row is now 0 after being reset for (var i = 0; i &lt; Width; i++) { Stack[i, ActiveRow] = highestRow[i]; } IncreaseActiveRow(); } private void IncreaseActiveRow() { ActiveRow++; } } } </code></pre> <p><strong>MissResult</strong></p> <pre><code>public class MissResult { public int XPos { get; set; } public int YPos { get; set; } public MissResult(int x, int y) { XPos = x; YPos = y; } } </code></pre> <p><strong>Square</strong></p> <pre><code>public enum State { Occupied, Vacant } public class Square { public State State { get; set; } public Square() { State = State.Vacant; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T03:39:49.327", "Id": "531371", "Score": "1", "body": "`Stacker` does not contain \"grid\", \"stack\" and game logic objects rather `Stacker` IS all of these these objects. Next, there is no such thing as a `Grid` (upper or lower case) - I don't see a `grid` defined anywhere. Next, I cannot tell the playing board from the moving \"stack\". Then calling that moving grid thing a `Stack` adds more confusion; the game is about stacking (hence creating a stack) grids(?) so a `Stack` can't be a single moving \"grid\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T04:23:50.450", "Id": "531372", "Score": "0", "body": "@radarbob You are right, I've called the \"grid\" a \"stack\". It seems obvious now but I didn't make the connection when developing (I even used it in the summary... goodness me). I guess clearer variable names is one thing I can brush up on. `Stacker` holds the `Stack`, which should be called `Grid`. I have just realized I have left out two classes: the `MissResult` and `Square` - I will add those to the question too." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T10:11:41.207", "Id": "269289", "Score": "2", "Tags": [ "c#", "object-oriented", "game", "design-patterns" ], "Title": "Arcade Stacker Game - Core Logic" }
269289
<p>Take input n1 and n2 and check if they have the same greatest factor. If they do, print that factor. If they don't, print &quot;No&quot;. <br/></p> <p>example:<br/> input:<br/> 6<br/> 9<br/> output:<br/> 3<br/></p> <p>input:<br/> 15<br/> 27<br/> output:<br/> No<br/></p> <pre><code>n1=int(input()) n2=int(input()) l1=[] l2=[] for i in range(1,n1): if n1%i==0: l1.append(i) l1.sort(reverse=True) cf1=l1[0] for j in range(1,n2): if n2%j==0: l2.append(j) l2.sort(reverse=True) cf2=l2[0] if cf1==cf2: print(cf1) else: print(&quot;No&quot;) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T14:20:14.897", "Id": "531263", "Score": "0", "body": "Your code is not finding the greatest common factor. It's finding if the greatest factors of the two numbers are equal. The usual way to find the greatest common factor is the Euclidean algorithm." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T15:40:26.720", "Id": "531269", "Score": "0", "body": "The GCF of 15 and 27 should be 3. I've voted to close this question, since we only review code that is working correctly on this site." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T17:04:45.697", "Id": "531272", "Score": "0", "body": "@200_success no, we have to check if the greatest is same or not. for 15 it is 5 and for 27 it is 9 so not equal" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T17:05:04.947", "Id": "531273", "Score": "0", "body": "@Teepeemm how to use euclidean algorithm?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T17:11:09.640", "Id": "531276", "Score": "0", "body": "Sorry, I misinterpreted \"common greatest factor\" as \"greatest common factor\". I've edited the post to remove that confusion, and retracted my close vote." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T18:06:11.427", "Id": "531283", "Score": "0", "body": "@200_success it's okay and thank you :D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T20:08:36.790", "Id": "531289", "Score": "0", "body": "The Euclidean algorithm is usually implemented along the lines of `gcf(a,b)=gcf(b,a%b)` and then recursing (or with a while loop). But that's not what your code is doing (if that's what it's supposed to be doing, then you've misinterpreted your requirement)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T22:37:13.920", "Id": "531298", "Score": "1", "body": "(I'm somewhat ill at ease with the problem statement not explicitly excluding a natural number as its own factor.)" } ]
[ { "body": "<p>At any point, 1 is always common factor of any two numbers. Your code works perfectly. But if you want to write a shorter code, check the condition if both numbers are divisible by any number using for loop going from range 2 (1 is always factor) to min of both numbers. Take a new variable f which is <code>False</code> initially. If the condition is satisfied i.e. if both nos are divisible by a no, change f to <code>True</code>. Then, out of the loop, write an if condition, if f==True then print the number or else the condition was never satisfied and f is False and print &quot;no&quot;. Your code:</p>\n<pre><code>n1=int(input(&quot;Enter n1&quot;))\nn2=int(input(&quot;Enter n2&quot;))\nf=False\nfor i in range(2,min([n1,n2])):\n if n1%i==0 and n2%i==0:\n g=i\n f=True\nif f:\n print(g)\nelse:\n print(&quot;no&quot;)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T14:18:39.173", "Id": "531262", "Score": "2", "body": "This is a (slow) implementation of finding the greatest common factor, but that's not what OP's code dos." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T00:08:23.840", "Id": "531303", "Score": "0", "body": "(Ignoring not checking factors higher than any common ones: How about `for i in range(min([n1,n2])//2, 1, -1):` ?)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T11:18:13.443", "Id": "269291", "ParentId": "269290", "Score": "0" } }, { "body": "<p>Quick and easy changes:</p>\n<ul>\n<li><code>input</code> should prompt what it's asking for.</li>\n<li>You want to encapsulate what you're doing into a function, but the function should just return, not print. But it's strange for a function to sometimes return a string and sometimes a number, so I've made it only return a number, and saved switching to &quot;No&quot; for the main thread to decide.</li>\n<li>You should document what you're doing and why. Since there's been some confusion about the greatest common factor, you should definitely document that this isn't that. Type hints are also nice. I've also included some doctest entries, so that you could run <code>python -m doctest -v myscript.py</code> and double check that it's working.</li>\n<li>Use an <code>if __name__ == '__main__'</code> guard</li>\n<li>The only point of <code>l1</code> is to get the first number. We can skip the reversing and just get the last number: <code>cf1=l1[-1]</code>.</li>\n</ul>\n<p>A much better change comes from realizing that factors come in pairs (with a square root paired with itself). This means that the greatest factor pairs with the least factor greater than 1:<br />\n<code>cf1 = n1/next( n for n in range(2,n1+1) if n1%n==0 )</code><br />\nWe could do the same thing for <code>cf2</code>, which would make the function symmetric and easier to understand. But if we're desperate for that last performance boost, we can do a bit better:</p>\n<p>If they have a common greatest factor, then it will be the greatest common factor. The Euclidean algorithm will very quickly find this value. The only thing that could mess things up would be if there is some other factor between <code>cf</code> and <code>n</code>. That could be a lot of numbers to check, but we can do the pairing trick again, and look for other numbers between <code>1</code> and <code>n/cf</code>. If there's a factor there, then there is a greater factor than the greatest common factor, and they don't have a common greatest factor.</p>\n<pre><code>def commonGreatestFactor(n1:int,n2:int) -&gt; int:\n '''\n Finds if the greatest factor of each number is the same, and returns it.\n This is not the greatest common factor\n (although if they have the same greatest factor, then it is equal to the gcf).\n If they do not share the same greatest factor, this returns 0.\n \n &gt;&gt;&gt; commonGreatestFactor(3,6)\n 0\n &gt;&gt;&gt; commonGreatestFactor(6,9)\n 3\n &gt;&gt;&gt; commonGreatestFactor(12,18)\n 0\n &gt;&gt;&gt; commonGreatestFactor(15,27)\n 0\n '''\n gcf,other = n1,n2\n while other:\n gcf,other = other,gcf%other\n if min(n1,n2)==gcf&lt;max(n1,n2):\n return 0\n # if there's a factor of n1 between 1 and n1/gcf,\n # then the gcf is not the greatest factor of n1\n if next( (n for n in range(2,n1//gcf) if n1%n==0) , 0 ):\n return 0\n if next( (n for n in range(2,n2//gcf) if n2%n==0) , 0 ):\n return 0\n return gcf\n\nif __name__ == '__main__':\n n1=int(input('First number: '))\n n2=int(input('Second number: '))\n result = commonGreatestFactor(n1,n2)\n if result:\n print(result)\n else:\n print(&quot;No&quot;)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T21:30:06.473", "Id": "531296", "Score": "0", "body": "Let's try some more inputs - a) 6, 3 b) 12, 18." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T00:35:00.790", "Id": "531304", "Score": "0", "body": "@greybeard My comment was using `n` for `n1`, not for the index of the range (which wasn't a good idea on my part). It was getting (12,18)->0, as it should, but it was missing (3,6)->0, which I've fixed. Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T08:52:13.823", "Id": "531317", "Score": "0", "body": "(if `min(n1,n2)==gcf`, `gcf<max(n1,n2)` ↔ `n1 != n2`: `if n1 != n2 and min(n1, n2) == gcf`:) I'm not quite sure what the result of a) should be - but shouldn't it be consistent with c) 6, 6? c) seems to call for 3 (exclude n1/n2) or 6 (allow). (similarly for d) 2, 3: is \"the other trivial factor\" allowed? students' code does.) (Don't quite know what I was thinking of suggesting b) (missed 9 as a divisor).) There's [math.gcd()](https://docs.python.org/3/library/math.html#math.gcd)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T08:55:44.957", "Id": "531318", "Score": "0", "body": "Seeing several places where it would be great to know n1 was no smaller than n2, I might assure that upfront (possibly handling n1==n2 as a special case). Then, I could use `(n for n in range(2, n2//gcf) if n1%n==0 or n2%n==0)` followed by `range(n2//gcf, n1//gcf) if n1%n==0`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T21:08:16.747", "Id": "269313", "ParentId": "269290", "Score": "1" } }, { "body": "<p>&quot;The <code>sort()</code>s&quot; would work just fine called <em>once each</em> - <em>after</em> the loops.<br />\nInstead of <code>l1.sort(reverse=True)</code>, you could just use\n<code>l1 = list(reversed([1, 2]))</code>. Or omit permuting the lists and just pick the highest factor:<br />\n<code>factor1 = l1[-1]</code><br />\n(Building the lists using<br />\n<code>l1.insert(0, trial_divisor)</code> followed by <code>factor1 = l1[0]</code> is worse.)</p>\n<p>But when wanting greatest factors, only, why accumulate complete lists?</p>\n<pre><code>def greatest_factor(n):\n &quot;&quot;&quot; Given a natural number n, return its greatest factor below n.&quot;&quot;&quot;\n if n % 2 == 0:\n return n // 2\n for trial_divisor in range(3, int(math.sqrt(n)) + 1, 2):\n if n % trial_divisor == 0:\n return n // trial_divisor\n return 1\n</code></pre>\n<p>(Consider defining <code>smallest_factor()</code> (exceeding 1) and using that for <code>greatest_factor()</code>.)</p>\n<p>(For a sane way to check for a <em>common greatest factor</em> as defined in the problem statement, <a href=\"https://codereview.stackexchange.com/a/269313/93149\">Teepeemm's answer</a>'s first revision just needs a bit of tying up loose ends.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T23:51:20.673", "Id": "269314", "ParentId": "269290", "Score": "0" } } ]
{ "AcceptedAnswerId": "269291", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T10:25:00.940", "Id": "269290", "Score": "0", "Tags": [ "python", "python-3.x", "mathematics" ], "Title": "Print greatest factor if it is same for both numbers" }
269290
<p>I started my cs50 course this week and I will be trying to make little projects alongside to reaffirm what I've learned thus far. Here I have made a very basic budget and savings calculator, I am hoping to increase the complexity as I improve.</p> <p>Where could I improve this in terms of simplicity &amp; structure/slickness? Also are there ways I can make this more complex and add things into it? thanks!</p> <pre><code> #include &lt;cs50.h&gt; #include &lt;stdio.h&gt; int main(void) // Prompt for Monthly Income { int Monthly_Income; { Monthly_Income = get_int(&quot;Please enter your monthly income&quot;); } // Prompt for total Expenditure int Expenditure; { Expenditure = get_int(&quot;Please enter your monthly expenditure&quot;); } int Income_Remaining = (Monthly_Income - Expenditure); printf(&quot;Income remaining %i\n&quot;, Income_Remaining); // Prompt for savings per month int S; { S = get_int(&quot;Enter your target savings contribution per month&quot;); } // Calculate total Discretionary income int Discretionary_income = (Income_Remaining - S); printf(&quot;Discretionary income %i\n&quot;, Discretionary_income); // Calculate Savings total per month int i = 0; int Total = 0; do { Total = Total + S; i++; printf(&quot;your total savings are %i\n&quot;, Total); printf(&quot;total months %i\n&quot;, i); } while (i &lt; 24); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T19:06:55.240", "Id": "531286", "Score": "0", "body": "@G. Sliepen Ah yes I see, now declared & initialised the variables at the same time, not sure why I did it like that. The redundant comment being the // Prompt for Monthly Income or most of the // comments? I was just practicing including comments really, but fair point. That makes sense I will try splitting them up to make it more efficient. and I don't mean just for the sake of making it complex, just so that I can practice and engrain the knowledge ya know, I don't want to make an overcomplicated program if there's an easier/more efficient way however." } ]
[ { "body": "<h1>Declare and initialize variables at the same time</h1>\n<p>You can simplify the code a lot by declaring and initializing variables at the same time, like so:</p>\n<pre><code>int Monthly_Income = get_int(&quot;Please enter your monthly income&quot;);\nint Expenditure = get_int(&quot;Please enter your monthly expenditure&quot;);\n</code></pre>\n<p>You were already doing this for <code>Income_Remaining</code> and <code>Discretionary_income</code>.</p>\n<h1>Don't write redundant comments</h1>\n<p>Avoid writing comments that don't really add any new information. A lot of code is self-explanatory, for example if you see:</p>\n<pre><code>int Monthly_Income = get_int(&quot;Please enter your monthly income&quot;);\n</code></pre>\n<p>It is evident that you are prompting for the monthly income, from both the properly named variable and the text passed to <code>get_int()</code>.</p>\n<h1>Split your program into multiple functions</h1>\n<p>For larger programs it will become a necessity, but it is good practice to also see if you can split up a small program like this into multiple functions. Even if a function is only called once, it can be beneficial to make it a separate thing with its own name. For example, printing the savings over time could be split off:</p>\n<pre><code>static void print_savings_over_time(int monthly_saving) {\n int total = 0;\n\n for (int month = 1; month &lt;= 24; month++) {\n total += monthly_saving;\n printf(&quot;Total savings in month %d: %d\\n&quot;, month, total);\n }\n}\n\nint main(void) {\n ...\n int S = get_int(&quot;Enter your target savings contribution per month&quot;);\n ...\n print_monthly_savings(S);\n}\n</code></pre>\n<h1>Adding complexity</h1>\n<blockquote>\n<p>Also are there ways I can make this more complex and add things into it?</p>\n</blockquote>\n<p>Yes you can. You should not add complexity for complexity's sake though, follow the <a href=\"https://en.wikipedia.org/wiki/KISS_principle\" rel=\"nofollow noreferrer\">KISS principle</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T15:44:39.710", "Id": "269298", "ParentId": "269295", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T14:20:07.497", "Id": "269295", "Score": "2", "Tags": [ "beginner", "c", "calculator" ], "Title": "Total income program: budget and savings calculator" }
269295
<p>So I have a file of errors, there default meanings and also it's hierarchy in terms of indentation</p> <pre><code>BaseException General for all errors of any and every kind. SystemExit Called for when the system wants to exit. KeyboardInterrupt Called when an operator interrupts an action. GeneratorExit Called when the system requests a generator exit. Exception General for all non-exit errors. StopIteration Called when an iterator ended unexpectedly. StopAsyncIteration Called when an asynchronous iterator ended unexpectedly. ArithmeticError General for arithmetic errors. FloatingPointError Called when interpreting a float failed. OverflowError Called when the result was too large to be represented. ZeroDivisionError Called when dividing by zero. Contrary to belief, it does not blow up the entire system. Atleast- not all the time. AssertionError Called when an assertion fails. </code></pre> <p>And I have then converted it all into a list of tuples, with a searcher function along with it such that error(&quot;ArithmeticError&quot;), error(&quot;007&quot;) and error(7) all return</p> <pre><code>[ 1, &quot;007&quot;, &quot;ArithmeticError&quot;, &quot;General for arithmetic errors.&quot;, [ 0, &quot;004&quot;, &quot;Exception&quot;, &quot;General for all non-exit errors.&quot;, [ 0, &quot;000&quot;, &quot;BaseException&quot;, &quot;General for all errors of any and every kind.&quot; ], ] ] </code></pre> <p>Which is the data from before in the format</p> <pre><code>[ indentation (number of spaces before words), code (line it is on), name (first word), default reason (all words but the first), [ parents indentation parents code parents name parents default reason parents parent (if it exists) [ ] </code></pre> <p>All errors will have a parent apart from BaseException (000) This is the code I have done for it, but I feel like there is a more effecient method.</p> <pre><code>import os,builtlins def r(p,b=&quot;default&quot;): #r(&quot;cache/errors.log&quot;) returns path_to_project_root_folder/cache/errors.logs b,p=b.replace(&quot;\\&quot;,&quot;/&quot;),p.replace(&quot;\\&quot;,&quot;/&quot;);p=p if p.startswith(&quot;/&quot;) else f&quot;/{p}&quot; return ((resourcepath if b==&quot;default&quot; else (b[:len(b)-1] if p.startswith(&quot;/&quot;) and b.endswith(&quot;/&quot;) else b))+(p[:len(p)-1] if p.endswith(&quot;/&quot;) else p)).replace(&quot;/&quot;,&quot;\\&quot;).replace(&quot;\\\\&quot;,&quot;\\&quot;) resourcepath=os.getcwd()[:os.getcwd().find(&quot;Ancilla Project&quot;)+len(&quot;Ancilla Project&quot;)] errors=[[r[0],r[1],r[2][:r[2].find(&quot; &quot;)],r[2][r[2].find(&quot; &quot;)+1:]] for r in[(len(e[:len(e)-len(e.lstrip())]),f&quot;{'0'*(3-len(str(i)))}{i}&quot;,e[len(e)-len(e.lstrip()):],) for i,e in enumerate(open(r(&quot;cache/errors.log&quot;)).read().split(&quot;\n&quot;))]] def error(q,obj=False): a=[e for e in errors if (f&quot;{'0'*(3-len(str(q)))}{q}&quot; if isinstance(q,int) else q)==e[1 if isinstance(q,int) else 2]];return ((a[0] if a else None) if not obj else ({**globals(),**vars(builtins)}[a[0][2]] if a else None)) for i,e in enumerate(errors): errors[i]=([(*e,(*errors[int(e[1])-x-1],int(e[1])-x-1)) for x in range(0,int(e[1])) if errors[int(e[1])-x-1][0]&lt;e[0]] if e[0]!=0 else [(*e,(*error(&quot;BaseException&quot;),)),] if e[2]!=&quot;BaseException&quot; else [(*e,),])[0];e=errors[i] </code></pre> <p>If any more information or clarity is needed I will try my best to give them. And yeah, i know that the amount of PEP violation (whichever one is for python 3.8.6) is so high that it'd collapse under its own gravity and become a blackhole- so some help on that would be appreciated</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T15:38:07.857", "Id": "531267", "Score": "2", "body": "Why is your code so dense and compact? Are you aiming to code-golf?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T15:48:05.927", "Id": "531270", "Score": "0", "body": "i dont know what aiming to code-golf is but i just did it because i hate having to scroll down on the python interpreter and vertically and horizontally so i make it short enough so i wont have to scroll for a bit and just under the horizontal limit" } ]
[ { "body": "<h1>Small Things</h1>\n<ul>\n<li>Spelling error, <code>builtlins -&gt; builtins</code>.</li>\n<li>Removed commented out code you don't use, adds unnecessary clutter.</li>\n<li>Spaces before and after operators (<code>+-*/=</code>).</li>\n</ul>\n<h1>PEP-8 Stuff</h1>\n<ul>\n<li><a href=\"https://www.python.org/dev/peps/pep-0008/#maximum-line-length\" rel=\"nofollow noreferrer\">Line length should not exceed <code>79</code> characters.</a></li>\n<li><a href=\"https://www.python.org/dev/peps/pep-0008/#imports\" rel=\"nofollow noreferrer\">Imports should usually be on separate lines.</a></li>\n<li><a href=\"https://www.python.org/dev/peps/pep-0008/#whitespace-in-expressions-and-statements\" rel=\"nofollow noreferrer\">Whitespace in Expressions and Statements.</a></li>\n</ul>\n<h1>Use Meaningful Names</h1>\n<p>Almost all of your variables are one character long. As someone looking at your code for the first time, it was very hard to determine what types of variables these are. <code>p</code> and <code>b</code> as parameters? What types are passed? These should be named accordingly to what you assign to them.</p>\n<h1>Space Out Your Code</h1>\n<p>It's nearly impossible, at least for me, to read your code the way you posted it. As you pointed out in a comment, &quot;I hate having to scroll down on the python interpreter...&quot;, I edited your code using my editor and it could still fit on the entire page without scrolling. Now you may be using a smaller screen, so I'll give you the benefit of the doubt.</p>\n<p>However, I write my code enveloped around one principle: Write code that others can understand. Having a huge clump of code, while it still does what you want, will be extremely messy. It will be difficult to debug this program should something not work while you test it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T17:16:38.037", "Id": "269302", "ParentId": "269297", "Score": "0" } } ]
{ "AcceptedAnswerId": "269302", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T15:05:43.467", "Id": "269297", "Score": "0", "Tags": [ "python", "python-3.x" ], "Title": "Making list of errors from file" }
269297
<p>I made a somewhat simple vector implementation in C. Right now I only have around 5 features (making a vector, adding elements, removing elements, changing elements, deleting the vector). I'm proud of it but I know it needs a lot of work so I came here to see what you think I could improve. There are 3 files, <code>main.c</code> (tests), <code>Arr.h</code> (function definitions, macros and structs) and <code>Arr.c</code>. Here is the code for all 3 files:</p> <p>Arr.h</p> <pre class="lang-c prettyprint-override"><code>//Arr.h #ifndef ARR_H #define ARR_H #define growCapacity(capacity) \ (capacity &lt; 8) ? 8 : capacity*2 typedef struct{ int count; int capacity; int* Array; }Vect; void initVect(Vect* vect); Vect* constructVect(int array[], int count, int capacity); void addVect(Vect* vect, int data); void changeVect(int data, int index, Vect* vect); void removeVect(Vect* vect, int count); #endif </code></pre> <p>Arr.c</p> <pre class="lang-c prettyprint-override"><code>//Arr.c #include &quot;Arr.h&quot; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; void* reallocate(Vect* vect, size_t oldSize, size_t newSize){ if(newSize == 0){ free(vect-&gt;Array); return NULL; } void* result = realloc(vect-&gt;Array, newSize); if(result == NULL){ printf(&quot;There is not enough memory to reallocate array. Exiting&quot;); exit(1); } return result; } void initVect(Vect* vect){ vect-&gt;count = 0; vect-&gt;capacity = 0; vect-&gt;Array = NULL; } Vect* constructVect(int array[], int count, int capacity){ //Find a way to get the count and size of an array by using a function rather than having it as a parameter Vect* vect = (Vect*)malloc(sizeof(Vect)); vect-&gt;capacity = capacity; vect-&gt;count = count; vect-&gt;Array = (int*)malloc(capacity); memcpy(vect-&gt;Array, array, capacity); return vect; } void addVect(Vect* vect, int data){ if(vect-&gt;capacity &lt; (vect-&gt;count*4)+1){ int oldCapacity = vect-&gt;capacity; vect-&gt;capacity = growCapacity(oldCapacity); vect-&gt;Array = (int*)reallocate(vect, oldCapacity, vect-&gt;capacity); } vect-&gt;Array[vect-&gt;count] = data; vect-&gt;count++; } void changeVect(int data, int index, Vect* vect){ if(index &gt; vect-&gt;count){ fprintf(stderr, &quot;ERR: element does not exist...&quot;); exit(-1); } vect-&gt;Array[index] = data; } void removeVect(Vect* vect, int count){ vect-&gt;count -= count; //Removes amount of vectors specified in count, the data is not fully deleted but it is no longer accessible } </code></pre> <p>main.c</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &quot;Arr.h&quot; int main(){ int array[] = {1, 2, 3, 4 , 5}; int count = sizeof(array)/sizeof(array[0]); int capacity = sizeof(array); Vect* vecto = constructVect(array, count, capacity); for(int i = 0; i&lt;vecto-&gt;count; i++){ //Write elements printf(&quot;Count: %d Capacity: %d Element: %d\n&quot;, vecto-&gt;count, vecto-&gt;capacity, vecto-&gt;Array[i]); } printf(&quot;\n\n Updated after adding 2 elements\n\n&quot;); addVect(vecto, 7); addVect(vecto, 9); for(int i = 0; i&lt;vecto-&gt;count; i++){ //Write elements printf(&quot;Count: %d Capacity: %d Element: %d\n&quot;, vecto-&gt;count, vecto-&gt;capacity, vecto-&gt;Array[i]); } printf(&quot;\n\n Changed element\n\n&quot;); changeVect(54, 0, vecto); for(int i = 0; i&lt;vecto-&gt;count; i++){ //Write elements printf(&quot;Count: %d Capacity: %d Element: %d\n&quot;, vecto-&gt;count, vecto-&gt;capacity, vecto-&gt;Array[i]); } printf(&quot;\n\n Update after removing 2 elements\n\n&quot;); removeVect(vecto, 2); for(int i = 0; i&lt;vecto-&gt;count; i++){ printf(&quot;Count: %d Capacity: %d Element: %d\n&quot;, vecto-&gt;count, vecto-&gt;capacity, vecto-&gt;Array[i]); } return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T18:20:37.277", "Id": "531599", "Score": "0", "body": "Pirates would approve of your naming convention. https://www.youtube.com/watch?v=K7aM_HWMdj0" } ]
[ { "body": "<blockquote>\n<pre><code>#define growCapacity(capacity) \\\n (capacity &lt; 8) ? 8 : capacity*2\n</code></pre>\n</blockquote>\n<p>I don't think this should be in the header, as it's not useful to the <em>user</em> of our vector. Consider moving it to the implementation file.</p>\n<blockquote>\n<pre><code>int count;\nint capacity;\nint* Array;\n</code></pre>\n</blockquote>\n<p><code>count</code> and <code>capacity</code> would be better as <code>size_t</code> values - especially as we use <code>size_t</code> arithmetic with them. Converting to <code>int</code> can cause problems.</p>\n<blockquote>\n<pre><code>void* reallocate(Vect* vect, size_t oldSize, size_t newSize){\n</code></pre>\n</blockquote>\n<p>This is internal to the implementation, so declare it with <code>static</code> linkage, so that you won't get link conflicts with any other <code>reallocate()</code> declared in other files.</p>\n<p>Why do we have to pass <code>oldSize</code>? That information isn't needed.</p>\n<blockquote>\n<pre><code>void* result = realloc(vect-&gt;Array, newSize);\n</code></pre>\n</blockquote>\n<p>It looks like we're confused about number of elements and size in <code>char</code>s here - we're called with the number of elements required, so we should be allocating <code>sizeof (int) * newSize</code> here.</p>\n<blockquote>\n<pre><code>if(result == NULL){\n printf(&quot;There is not enough memory to reallocate array. Exiting&quot;);\n exit(1);\n}\n</code></pre>\n</blockquote>\n<p>It's good that you have considered what happens when allocation returns a null pointer. However, exiting the program becomes progressively less useful as program size increases, and in a library it's better to pass an error indication to the caller to decide whether to give up or to take some other action.</p>\n<p>Also, when printing, be sure to write a complete line (ending in <code>\\n</code>).</p>\n<blockquote>\n<pre><code>Vect* vect = (Vect*)malloc(sizeof(Vect));\nvect-&gt;capacity = capacity;\n</code></pre>\n</blockquote>\n<p>Oops - <code>vect</code> may be null, so we need to test for that before accessing <code>vect-&gt;capacity</code>. Also, <code>malloc()</code> returns <code>void*</code>, so there's no need to cast to <code>Vect*</code> like that:</p>\n<pre><code>Vect* vect = malloc(sizeof *vect);\nif (!vect) {\n return vect; /* caller must deal with null result */\n}\nvect-&gt;capacity = capacity;\n</code></pre>\n<blockquote>\n<pre><code>vect-&gt;Array = (int*)malloc(capacity);\nmemcpy(vect-&gt;Array, array, capacity);\n</code></pre>\n</blockquote>\n<p>Again, no need to cast <code>void*</code> to other object pointer types, and we need to check whether it was successful before writing to <code>vect-&gt;Array</code>.</p>\n<blockquote>\n<pre><code>if(vect-&gt;capacity &lt; (vect-&gt;count*4)+1){\n</code></pre>\n</blockquote>\n<p>Why are we multiplying by 4 here? If our new count is going to exceed the capacity, then we'll need to extend the allocation.</p>\n<p>Finally, we're missing a function to free the vector storage. Without that, there's no way to avoid leaking memory:</p>\n<pre class=\"lang-none prettyprint-override\"><code>184 (24 direct, 160 indirect) bytes in 1 blocks are definitely lost in loss record 2 of 2\n at 0x483877F: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n by 0x109268: constructVect (269299.c:55)\n by 0x109440: main (269299.c:99)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T19:07:41.660", "Id": "531287", "Score": "0", "body": "Thank you! I will add your suggestions. Btw, `if(vect->capacity < (vect->count*4)+1)` I multiplied `vect->count` by 4 to get the size of the array and see if adding 1 more element was too much, so then we can reallocate memory. But I see now that there are better check if `vect->capacity` needs to be resized. I will also add a freeVect function, could I just call `initVect` again and then free `vect->Array` and then call it a day?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T20:06:14.297", "Id": "531288", "Score": "5", "body": "`growCapacity()` should not even be a macro, but just a regular function." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T18:21:50.790", "Id": "269304", "ParentId": "269299", "Score": "12" } }, { "body": "<h3>Good points</h3>\n<ul>\n<li>Consistent and reasonable enough style.</li>\n<li>Includes are properly ordered: First the corresponding header, than sorted project-headers, than sorted other headers.</li>\n</ul>\n<h3>Comments</h3>\n<p>Obvious comments are useless:</p>\n<ul>\n<li><code>//Arr.h</code> Yes, the editor shows it, even if that's scrolled off the screen. No need to belabor the point.</li>\n<li><code>//Arr.c</code> Ditto.</li>\n<li><code>//Removes amount of vectors specified in count, the data is not fully deleted but it is no longer accessible</code> Aside from being wrong (it should be: &quot;Removes the number of elements specified&quot;), this looks like the alibi-comment: &quot;See! I did add a comment!&quot;</li>\n</ul>\n<p>If you add comments, they should either be doc-comments (meaning they are extracted by a tool to create (part of) the documentation), or they should describe your reasoning, why you do something non-obvious, not what exactly you do.</p>\n<h3>Interface</h3>\n<p>Your interface is inconsistent and some does not belong at all.</p>\n<ul>\n<li><p>Specifically, one constructor default-initializes a pointed-to <code>Vect</code>, the other copy-initializes a <code>Vect</code> it allocates.</p>\n</li>\n<li><p><code>changeVect()</code> is the only function not having the pointer to the vector first.</p>\n</li>\n<li><p>The macro <code>growCapacity()</code> does not belong in the interface at all.</p>\n</li>\n</ul>\n<p>Your interface also needs much expansion:</p>\n<ul>\n<li>Anywhere non-Vect code (everything else) is called, you need direct access to the managed array. That is only possible by digging in the internals.</li>\n<li>You really should provide for inserting and removing elements by index too, instead only at the end. Yes, that involves moving the tail to dig / fill the hole.</li>\n</ul>\n<h3>Preprocessor Macros</h3>\n<p>Avoid them. <code>const static</code> globals or <code>static</code> functions are nearly always preferable.</p>\n<p>If you actually have a good use for them (include-guards, conditional compilation, compile-time configuration, X-macros, ...), do your best to make them work as similar to a function as you can.</p>\n<p>Thus, make sure they are exactly one fully parenthesized expression, failing that one compound-statement which just needs a terminating semicolon, and the arguments are parenthesized too.</p>\n<h3>Types</h3>\n<p><code>size_t</code> is the dedicated type for size of objects, not <code>int</code>. The latter might be too small, or waste space, but it is certainly the wrong signedness.</p>\n<h3>Units</h3>\n<p>Are you dealing in elements (of type <code>int</code>) or bytes? Be consistent, especially internally.</p>\n<h3>Include-guard</h3>\n<p>Yes, your include-guard works, most of the time. There is a reason most IDEs put a long random string at the end when they generate them for you though:<br />\nResilience against accidentally similarly named files.</p>\n<h3>Debug-aids</h3>\n<p>Consider <a href=\"//en.cppreference.com/w/c/error/assert\" rel=\"nofollow noreferrer\"><code>assert()</code></a>-ing easily tested preconditions which are obvious bugs.</p>\n<h3>Growth-factor</h3>\n<p>A Growth-factor of two or more virtually guarantees that the array never re-uses any memory it held any number of iterations of growth earlier.<br />\nThus, try for a more modest growth-factor, maybe on the order of <code>1.6</code>.</p>\n<h3>Your internal helper</h3>\n<p>There is just too much wrong with <code>reallocate()</code>:</p>\n<ul>\n<li>Either it should work on a <code>Vect</code> directly, in which case it has to do all the bookkeeping, or it should work on raw memory, just massaging the behavior of <code>realloc()</code> into the form you need, leaving all the bookkeeping to the caller.<br />\nI suggest the former.</li>\n<li>It should be <code>static</code> as nobody else should access it, even by accident.</li>\n<li>Passing it the old size is really useless.</li>\n</ul>\n<h3>Boolean logic</h3>\n<p>Non-zero is true in C. Thus, you can simplify testing against <code>NULL</code> and <code>0</code>.</p>\n<h3>Errors</h3>\n<p>Error-output does not belong into <code>stdout</code>. <code>stderr</code> is dedicated to it.</p>\n<h3>Explicit types</h3>\n<p>Avoid <code>sizeof(TYPE)</code>, <code>sizeof *pointer</code> avoids an additional and disconnected mention of some type which is hard to verify or refactor.</p>\n<p>Casting should be minimized as it is error-prone. Specifically casting from <code>void*</code> to any other pointer-type is discouraged in C, as implicit conversion works.</p>\n<p><a href=\"//stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc\">&quot;<em>Do I cast the result of malloc?</em>&quot;</a>.</p>\n<h3>C99 features</h3>\n<ul>\n<li><code>return 0;</code> is implicit for <code>main()</code>.</li>\n<li><a href=\"//en.cppreference.com/w/c/language/compound_literal\" rel=\"nofollow noreferrer\">Compound-literals</a> would simplify <code>initVect()</code>.</li>\n<li>Compound-literals and designated initializers would simplify <code>constructVect()</code>.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T14:32:40.370", "Id": "269335", "ParentId": "269299", "Score": "5" } }, { "body": "<ul>\n<li>Consider hiding the implementation entirely by putting the struct in the implementation file.</li>\n<li>Be consistent and always pass the vector as the first argument.</li>\n<li>Consider using a namespace prefix at the front like <code>vec_init</code> instead of the other way around. That way the auto-complete is more helpful in IDEs:</li>\n<li>Instead of get/set functions, you might use a singe get function which returns a pointer to the element. That way the user can access the element as they wish.</li>\n<li>Provide a way to free the vector. Currently you are leaking the memory.</li>\n<li>Add more documentation to the header file.</li>\n</ul>\n<p>Here's how I would organize the header:</p>\n<pre><code>// Vector.h\n/*\n* An implementation of a dynamic array that resizes as needed\n*/\n\n#ifndef VECTOR_H\n#define VECTOR_H\n#pragma once\n\n#include &lt;stddef.h&gt; // size_t\n\ntypedef struct vec_impl* Vec;\n\n// Default init. No elements. \nVec vec_init();\n\n// Create a vector, copy values from the array.\n// Calls abort on allocation failure.\nVec vec_init_with(int const* array, size_t size);\n\n// Free the memory associated with the vector and all its elements.\n// NOOP if the pointer is null.\nvoid vec_deinit(Vec);\n\n// Push an element to the back of the vector.\n// Calls abort on allocation failure.\nvoid vec_append(Vec, int value);\n\n// Get the element at the provided index.\n// UB if index is out of bounds\nint* vec_get(Vec, size_t index);\n\n\n// Remove the element at the back of the vector.\n// UB if the vector is empty\nvoid vec_pop_back(Vec);\n\n// Remove `n` elements from the back of the array.\n// UB if the size of the array is less than `n`\nvoid vec_pop_back_n(Vec, size_t n);\n\n// Get number of items currently in the vector\nsize_t vec_get_size(Vec);\n\n// Get number of elements the vector can hold before\n// needing a reallocation.\nsize_t vec_get_capacity(Vec);\n\n#endif // !VECTOR_H\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T18:16:16.500", "Id": "531356", "Score": "0", "body": "Why should I put the struct into the implementation instead of the header file? Also what does UB mean?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T18:23:16.370", "Id": "531357", "Score": "2", "body": "You should put the struct in the implementation file so the implementation details don't leak into the interface. Additionally, this way no one can mess with the internal state of the struct (arbitrarily set the size, etc). It also helps with ABI compatibility." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T18:23:30.160", "Id": "531358", "Score": "0", "body": "UB means \"undefined behavior\". Google it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T10:40:46.440", "Id": "531384", "Score": "0", "body": "@dareesome Here's why & how: [How to do private encapsulation in C?](https://software.codidact.com/posts/283888)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T20:04:54.597", "Id": "531522", "Score": "0", "body": "Of course, the downside is an additional allocation. Also, the layout is extremely unlikely to ever need changing..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T16:09:01.387", "Id": "532379", "Score": "0", "body": "@Deduplicator an allocation of a couple bytes shouldn't matter considering the container will be occupying about twice as much memory as the elements. And the ABI could change if OP decided to implement \"copy on write\" semantics or possibly some other improvement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T16:38:55.280", "Id": "532386", "Score": "0", "body": "@AyxanHaqverdili That would be severely different semantics. Thus, a clean break would really be needed. Also, that allocation would mean dynamic initialization for vectors is needed, where without static initialization is sufficient." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T19:03:38.647", "Id": "532407", "Score": "0", "body": "@Deduplicator `std::string` used to allow COW, now they don't. It's not unthinkably different if need be. Besides, with the existence of `initVec` function already in OP's API, a static initialization is not enough anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T20:00:26.050", "Id": "532413", "Score": "0", "body": "@AyxanHaqverdili Allowing COW after the fact is a whole different beast than outlawing it, though both changes break binary-compatibility, the former also breaks the api. And a literal for static initialization is easily added later. Or just documenting that `{0}` works." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T17:44:29.677", "Id": "269339", "ParentId": "269299", "Score": "3" } }, { "body": "<h3>Design weakness - capacity</h3>\n<p><code>.capacity</code> is the byte size - arrgh! It took a while to see that.</p>\n<p><code>capacity</code> is more idiomatically the size in the same units as <code>.count</code>. In OP's code, <code>capacity</code> is in bytes, <code>count</code> is number of <code>int</code>.</p>\n<ul>\n<li><p>Use the same units - the number of <code>int</code>.</p>\n</li>\n<li><p>Do not use a magic 4, use <code>sizeof</code>.</p>\n</li>\n<li><p>Recommend to <em>not</em> use <code>capacity</code> in <code>constructVect()</code>, set <code>.capacity</code> same as <code>.count</code>.</p>\n</li>\n</ul>\n<p>Candidate <code>constructVect()</code> with <code>const</code>, re-ordered parameters for static code analysis, more error checking, handle 0 count:</p>\n<pre><code>Vect* constructVect(size_t count, const array[count]) {\n Vect* v = malloc(sizeof *v);\n if (v == NULL) {\n return NULL;\n }\n v-&gt;Array = malloc(sizeof vect-&gt;Array[0] * count);\n if (v-&gt;Array == NULL &amp;&amp; count &gt; 0) {\n free(v); \n return NULL;\n }\n v-&gt;capacity = capacity;\n v-&gt;count = capacity;\n return v;\n}\n</code></pre>\n<h3>Naming</h3>\n<p><code>ARR_H, growCapacity, Vect, initVect, constructVect, addVect, changeVect, removeVect</code> are added when including <code>Arr.h</code>.</p>\n<p>I recommend consistency based on the include file name.</p>\n<p>Such style issues best determined by group's coding standard.</p>\n<p><strong>Arr or Vect</strong></p>\n<p>Choose one.</p>\n<p><strong>Leading or trailing</strong></p>\n<p><code>initVect</code> or <code>Vect_init</code> or the like. (<code>VectInit</code>)</p>\n<p>I recommend a common prefix.</p>\n<p><strong>Uniqueness</strong></p>\n<p>The names <code>Arr</code> and <code>Vect</code> are common - likely to collide in a large project. I'd consider something less so. Problem remains no matter what name, just trying to reduce its possibilities.</p>\n<p><strong>Documentation</strong></p>\n<p>The .h file deserves some text describing the overall usage of <code>Vect</code>.</p>\n<p>Document (from a user point-of-view) the functions.</p>\n<p>Assume users do <strong>not</strong> have access to the .c file, nor want to see it.</p>\n<p><strong>Example</strong></p>\n<p><code>Vect_H</code> (or <code>VECT_H</code>), <code>Vect, Vect_init, Vect_construct, Vect_add, Vect_change, Vect_remove</code> in <code>Vect.h</code>.</p>\n<p><code>growCapacity</code> move to <code>Vect.c</code> as not needed by the public.</p>\n<hr />\n<p><strong>Reallocating to 0</strong></p>\n<p>Good use of <code>if(newSize == 0) { free(vect-&gt;Array);</code>. Proper return value of <code>realloc(..., 0)</code> is a head-ache.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T11:53:38.430", "Id": "269419", "ParentId": "269299", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T16:18:15.863", "Id": "269299", "Score": "13", "Tags": [ "c", "vectors" ], "Title": "Vector Implementation in C" }
269299
<p>My teacher gave us this problem to solve so basically N is the number of user names in a list T with 1&gt;N&lt;9</p> <ul> <li>Generate another list called TID containing the name of the user but changed a bit. Do the next steps for each user in the list T</li> </ul> <hr /> <ol> <li>Take the first two letters from the user's name</li> <li>The index of the user name in the list T</li> <li>the ASCII code for the first user letter and the sum of vowels in the user name if the sum is &gt; 90 we automatically go back to the letter a</li> </ol> <p>Example: T = (&quot;RAOUF&quot;.....) TID= (&quot;RA0U&quot;)</p> <ul> <li>The first two letters are &quot;RA&quot;</li> <li>the index of the item in the list is 0</li> <li>The letter &quot;R&quot; its ascii code is 82 with the string containing three vowels it becomes 85 so we put the letter &quot;U&quot;</li> </ul> <p>I apologize if there is any problem with my English, we studied all of this in french I had to translate it all. I appreciate any kind of help, thank you.</p> <p>Here is my code/</p> <pre><code>n = int(input(&quot;Entrezy les numbers de les utilisateurs (1-9): &quot;)) t = [] tid = [] def remplir_t(n, t): while True: if n &lt; 1 or n &gt; 9: n = int(input(&quot;N doix etre un valeur de 1 a 9, rentrezy N: &quot;)) else: break for i in range(n): Indentifacteur = input( F&quot;Entrezy le indentifacteur de le utilisateur {i + 1}: &quot;) t.append(Indentifacteur) def voyel_ascii(ch): v = 0 b = ord(ch[0]) voyells = (&quot;A&quot;, &quot;E&quot;, &quot;I&quot;, &quot;O&quot;, &quot;U&quot;, &quot;Y&quot;, &quot;a&quot;, &quot;e&quot;, &quot;i&quot;, &quot;o&quot;, &quot;u&quot;, &quot;y&quot;) for i in range(len(ch)): if ch[i] in voyells: v += 1 b += v if b &gt; 90: b = 97 k = chr(b) return k def remplir_tid(n, t): for i in range(n): tid.append(t[i][0:2]+str(i)+voyel_ascii(t[i])) print(tid) remplir_t(n, t) remplir_tid(n, t) print(t) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T20:16:00.613", "Id": "531290", "Score": "0", "body": "I doubt that `1>N<9` - what are the constraints that your teacher gave you?" } ]
[ { "body": "<h1>General Changes</h1>\n<ul>\n<li>Move any input code to the bottom of the file, inside a <a href=\"https://stackoverflow.com/questions/19578308/what-is-the-benefit-of-using-main-method-in-python\">main guard</a>.</li>\n<li>Avoid using <a href=\"https://stackoverflow.com/questions/484635/are-global-variables-bad\">global variables</a>, instead pass them as parameters.</li>\n<li>Variable names should be in <code>lowercase</code> or <code>snake_case</code>.</li>\n</ul>\n<h1>Type Hints</h1>\n<p>Use type hints to display what types are accepted by a function, and which are returned. It makes understanding your code a bit easier, which in turn saves time reading your program.</p>\n<h1><code>remplir_t</code></h1>\n<p>Instead of having a <code>while True</code>, evaluate the bounding condition. This way, if the user inputs a valid number, the loop won't even run. Also, I made this function return a list of inputs by the user. This allows you to avoid messing with global variables, and all around makes the code look a bit nicer.</p>\n<h1><code>voyel_ascii</code></h1>\n<p>This code can be reduced to <strong>3</strong> lines. First of all, making the vowel list a string allows you to do the same indexing operation. Next, I'll explain this bit of code:</p>\n<pre class=\"lang-py prettyprint-override\"><code>b = min(ord(ch[0]) + sum(ch[i] in voyells for i in range(len(ch))), 97)\n</code></pre>\n<p>The inside <code>sum</code> bit adds up each true result from the comparison <code>ch[I] in voyells</code>. Since <code>True</code> is 1 and <code>False</code> is 0, the <code>sum</code> function works perfectly for this. Next, the <code>min</code> acts like a boundary, preventing the resulting value from exceeding 97. If the result is greater than 97, the min function will return 97 instead of the result. It's a neat trick that makes your code a lot nicer.</p>\n<h1><code>remplir_tid</code></h1>\n<p>I've used a list comprehension to shorten this function to one line. It does the exact same thing you've written, but in a nicer fashion.</p>\n<hr>\n<p>Below is the new code I've written. Take a look, and if you have any questions put them in a comment and I'll answer them!</p>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import List\n\ndef remplir_t(n: int) -&gt; List[str]:\n inputs = []\n while n &lt; 1 or n &gt; 9:\n n = int(input(&quot;N doix etre un valeur de 1 a 9, rentrezy N: &quot;))\n for i in range(n):\n indentifacteur = input(f&quot;Entrezy le indentifacteur de le utilisateur {i + 1}: &quot;)\n inputs.append(indentifacteur)\n return inputs\n\n\ndef voyel_ascii(ch: str) -&gt; str:\n voyells = &quot;AEIOUYaeiousy&quot;\n b = min(ord(ch[0]) + sum(ch[i] in voyells for i in range(len(ch))), 97)\n return chr(b)\n\n\ndef remplir_tid(n: int, t: List[str]) -&gt; List[str]:\n return [t[i][0:2] + str(i) + voyel_ascii(t[i]) for i in range(n)]\n\n\nif __name__ == '__main__':\n num_inputs = int(input(&quot;Entrezy les numbers de les utilisateurs (1-9): &quot;))\n\n inputs = remplir_t(num_inputs)\n result = remplir_tid(num_inputs, inputs)\n\n print(result)\n print(inputs)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T20:21:19.340", "Id": "531291", "Score": "0", "body": "A small bit here `min` does not work (or at least not how you implemented it). If `b>90` then we set `b=97`. With your code `b=95` will pass through for instance. Otherwise great answer!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T16:04:27.353", "Id": "531739", "Score": "0", "body": "Truly appreciated!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T19:49:38.750", "Id": "269308", "ParentId": "269300", "Score": "1" } }, { "body": "<h3>The English language is the lingua franca of computing</h3>\n<p>I am not from an English speaking country, yet every piece of code I write is in English. Why? Because code is about communication, and being understood. The most important part of a piece of code is that it is transparent, or easy to digest and of course that it works. But how can you know that it works if you can not read it?</p>\n<p>See <a href=\"https://en.wikipedia.org/wiki/English_in_computing\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/English_in_computing</a></p>\n<h3>PEP 8</h3>\n<p>Use a common standard for your variables and naming, for the most part it is good but <code>Indentifacteur</code> should be <code>indentifacteur</code>, or as mentioned above <code>identifier</code>.</p>\n<h3>Meaningful Identifier Names</h3>\n<p>Giving identifiers in computer programs meaningful names\nis a widely accepted best practice. This is reflected both\nin coding standards and in programming teaching materials.\nFor example, the Google C++ Style Guide states</p>\n<blockquote>\n<p>&quot;Give as descriptive a name as possible, within reason. Do not worry\nabout saving horizontal space as it is far more important to make your\ncode immediately understandable by a new reader. Do not use\nabbreviations that are ambiguous or unfamiliar to readers outside your\nproject, and do not abbreviate by deleting letters within a word.&quot;</p>\n</blockquote>\n<p>See <a href=\"https://www.cs.huji.ac.il/%7Efeit/papers/SingleLetter17ICPC.pdf\" rel=\"nofollow noreferrer\">https://www.cs.huji.ac.il/~feit/papers/SingleLetter17ICPC.pdf</a> for details</p>\n<h3>Negation of expressions</h3>\n<p>This bit here is a bit cumbersome</p>\n<pre><code>while True:\n if n &lt; 1 or n &gt; 9:\n n = int(input(&quot;N doix etre un valeur de 1 a 9, rentrezy N: &quot;))\n else:\n break\n</code></pre>\n<p>It would be better stated as N should be a value of 1 to 9, return N:</p>\n<pre><code>while True:\n if 1 &lt;= n &lt;= 9:\n break\n n = int(input(&quot;N should be a value of 1 to 9, return N:&quot;))\n</code></pre>\n<p>If you are using python 3.8 or above it could also be stated as</p>\n<pre><code>username_msg = &quot;Input the number of usernames [0, 9] inclusive: &quot;\nwhile not 1 &lt;= (number_of_usernames := int(input(username_msg))) &lt;= 9:\n pass\n</code></pre>\n<p>Again it would be better to add some error checking that the input truly is an integer for instance. However, this will do for now.</p>\n<h3>Use builtins</h3>\n<pre><code>for i in range(len(ch)):\n if ch[i] in voyells:\n v += 1\n</code></pre>\n<p>This can be rewritten as</p>\n<pre><code>for char in ch:\n if char in voyells:\n v += 1\n</code></pre>\n<p>It can also be completely rewritten see bellow.</p>\n<h3>Final bits and bobs</h3>\n<p>I got tired from going through the code line by line so I did a complete rewrite.</p>\n<ul>\n<li>Everything is now in English</li>\n<li>There is no longer any global <code>t</code> or <code>tid</code> floating around. Messing with global state makes the code hard to read.</li>\n<li>Remover every piece of single letter variables and just did a complete refactor.</li>\n<li>More logical names for our function, the encoding to create the identifier is often called a transposition.</li>\n<li>Global constants should be in UPPERCASE</li>\n<li><code>voyel_ascii</code> was split into two functions and much reduced.</li>\n<li>Typing hints added to hint at what is returned and inputed into each function.</li>\n<li>An <code>if __name__ == &quot;__main__&quot;</code> guard was included so this code can be safely imported elsewhere.</li>\n</ul>\n<h4>Code</h4>\n<pre><code>from typing import Annotated\n\nMAX_ALLOWED_USERNAMES = 9\nUSERNAME_RANGE = [i for i in range(1, MAX_ALLOWED_USERNAMES)]\nUSERNAME_MSG = f&quot;Input the number of usernames ({min(USERNAME_RANGE)}, {max(USERNAME_RANGE)}) inclusive: &quot;\n\nVOWELS = [&quot;a&quot;, &quot;e&quot;, &quot;i&quot;, &quot;o&quot;, &quot;u&quot;, &quot;y&quot;]\n\nUsername = Annotated[str, &quot;An username to encode&quot;]\nUsernameEncoded = Annotated[str, &quot;An encoded username&quot;]\nIdentifier = Annotated[str, &quot;A letter identifying a particular username&quot;]\n\n\ndef vowel_counter(string: str) -&gt; int:\n return len([char for char in string if char in VOWELS])\n\n\ndef get_usernames() -&gt; list[Username]:\n while (number_of_usernames := int(input(USERNAME_MSG))) not in USERNAME_RANGE:\n pass\n return [\n input(f&quot;Write in the username ({i+1}/{number_of_usernames}): {i + 1}: &quot;)\n for i in range(number_of_usernames)\n ]\n\n\ndef transposition(username: Username) -&gt; Identifier:\n if (b := ord(username[0]) + vowel_counter(username.lower())) &gt; 90:\n b = 97\n return chr(b)\n\n\ndef encoding(username: Username, number: int) -&gt; UsernameEncoded:\n return username[0:2] + str(number) + transposition(username)\n\n\nif __name__ == &quot;__main__&quot;:\n\n usernames = get_usernames()\n encoded_usernames = [\n encoding(username, idx) for idx, username in enumerate(usernames)\n ]\n print(encoded_usernames)\n print(usernames)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T15:51:27.407", "Id": "531352", "Score": "0", "body": "I agree with you're saying, English should be used for programming except for the user prompts and interactive messages because frankly doing otherwise may not be acceptable in some settings. But I have to say the spelling of the French language (or Frenglish ?) in that code is very unusual and should be reviewed before this code is even presented." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T16:39:50.687", "Id": "531354", "Score": "0", "body": "@Anonymous I am sure you are correct. I merely put the French into google translate and tried to make sense of it. Same with the name of the functions.. It was an arduous task, as I do not speak a word French." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T16:03:55.297", "Id": "531738", "Score": "0", "body": "@N3buchadnezzar I always write code in English but my teacher told me not to I guess he is not that good anyway I appreciate everything it's really helpful!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T20:17:05.560", "Id": "269310", "ParentId": "269300", "Score": "1" } } ]
{ "AcceptedAnswerId": "269310", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T16:59:43.053", "Id": "269300", "Score": "1", "Tags": [ "python" ], "Title": "A small python identifier generator for users" }
269300
<p>I wrote a program that, given a 2D array representing pixels in a birds eye view image, it returns the number of Objects in the image.</p> <p>Pixels that are connected in the up, down, left, and right directions are a single object.</p> <p><strong>Example:</strong></p> <pre class="lang-py prettyprint-override"><code>grid = [ [0, 0, 0, 1, 0], [0, 1, 1, 0, 1], [0, 0, 1, 1, 1], [1, 1, 0, 1, 0], [1, 1, 0, 0, 0], ] The grid above visualized: we see 3 separate objects, A, B, and C | | | |A| | | |B|B| |B| | | |B|B|B| |C|C| |B| | |C|C| | | | </code></pre> <br> <p>Algorithm is expected to return the count, in this case, 3.</p> <br> <p><strong>My approach was the following:</strong></p> <ol> <li>for each pixel in the image, if it is marked as 1 and it is unvisited I would increase the connected component counter and perform initial DFS from this &quot;source&quot; pixel/vertex.</li> <li>Inside the DFS call on pixel 1 &quot;source pixel/vertex&quot; of object 1, I would mark as visited, and get the list of adjacent vertices (representation defined above). Then recursively traverse all unvisited, making sure to mark as visited either with a 2D array of booleans, or possibly, marking pixel as -1 for visited to save space... I think that may also work.</li> <li>I would then only increment the object counter, on each initial DFS call on a &quot;source&quot; pixel, aka, the first pixel encountered of an object, which will be any pixels that were not visited by previous traversals (if not reached by other traversals it means these pixels were disconnected and therefore a new object)</li> <li>return the instance variable counter which now holds the number of objects (number of different connected components)</li> </ol> <p><strong>Implementation:</strong></p> <pre class="lang-py prettyprint-override"><code>from typing import List, Tuple class ConnectedPixels: def __init__(self, image: List[List[int]]) -&gt; None: # number of objects counter self.connected_components = 0 ## visited array self.visited = [[False for c in range(len(image[0]))] for r in range(len(image))] length = len(image) width = len(image[0]) # for all pixels in image for i in range(0, length): for j in range(0, width): ij_pixel = image[i][j] # If pixel is an object, or part of an object (aka set to 1) AND has not been visited yet if ij_pixel == 1 and self.visited[i][j] == False: # increase object count and perform DFS on first pixel of object self.connected_components += 1 self.DFS(image ,i , j) def DFS(self, image: List[List[int]], row: int, col: int) -&gt; None: ## mark pixel as visited self.visited[row][col] = True ## find all contiguous pixels to pixel [row][col] aka (row, col) adjacent_pixels = self.adj_vert(image, row, col) for adjacent_px in adjacent_pixels: # find row and col of adjacent pixel row_adj_px = adjacent_px[0] col_adj_px = adjacent_px[1] # if adjacent pixel is not visited and is marked as a 1 in the image aka, it has is an object, or part of one if self.visited[row_adj_px][col_adj_px] == False and image[row_adj_px][col_adj_px] == 1: # perform DFS on the pixel self.DFS(image, row_adj_px, col_adj_px) ## TODO: VERY UGLY, CAN THIS BE IMPROVED? #aka get cardinal neighboors (top, down, left, right) def adj_vert(self,image: List[List[int]], row: int, col: int) -&gt; List[Tuple[int, int]]: adjs = [] width = len(image[0]) length = len(image) right_most_pixel = width - 1 bottom_most_pixel = length - 1 # top left corner if row == 0 and col == 0: adjs.append((1, 0)) adjs.append((0, 1)) # top right corner elif row == 0 and col == right_most_pixel: adjs.append((0, right_most_pixel - 1)) adjs.append((1, right_most_pixel)) # bottom left elif row == bottom_most_pixel and col == 0: adjs.append((bottom_most_pixel - 1, 0)) adjs.append((bottom_most_pixel, 1)) # bottom right elif row == bottom_most_pixel and col == right_most_pixel: adjs.append((bottom_most_pixel, right_most_pixel - 1)) adjs.append((bottom_most_pixel - 1, right_most_pixel)) #top border, if pixel is at the top border (excluding the corners) elif row == 0 and col &gt; 0 and col &lt; right_most_pixel: adjs.append((1, col)) adjs.append((0, col - 1)) adjs.append((0, col + 1)) # bottom border, if pixel is at the bottom border (excluding the corners) elif row == bottom_most_pixel and col &gt; 0 and col &lt; right_most_pixel: adjs.append((bottom_most_pixel - 1, col)) adjs.append((bottom_most_pixel, col - 1)) adjs.append((bottom_most_pixel, col + 1)) # left border, if pixel is at the left border (excluding the corners) elif col == 0 and row &gt; 0 and row &lt; bottom_most_pixel: adjs.append((row - 1, 0)) adjs.append((row + 1, 0)) adjs.append((row , 1)) # right border, if pixel is at the right border (excluding the corners) elif col == right_most_pixel and row &gt; 0 and row &lt; bottom_most_pixel: adjs.append((row - 1, right_most_pixel)) adjs.append((row + 1, right_most_pixel)) adjs.append((row, col - 1)) # pixel is in the middle region else: adjs.append((row - 1, col)) adjs.append((row + 1, col)) adjs.append((row, col + 1)) adjs.append((row, col - 1)) return adjs </code></pre> <p><strong>Doubts/Question:</strong></p> <ul> <li>The <code>adj_vert</code> methods to get the neighbors of a pixel is extremely ugly. Is there a cleaner way to the approach I took?</li> <li>I tested the above for some sample inputs and also stepped through the code, and so far so good, Is there a similar problem on Leetcode to test more thoroughly for correctness?</li> <li>Can I save on space by flipping each unvisited pixel marked as 1 to -1 on the same image</li> <li>I believe run time is proportinal to L x W of image, is there a way to make this more efficient?</li> <li>Any code design changes/ improvements that can be made?</li> </ul> <p><strong>Edit:</strong></p> <ul> <li>Leetcode 200 can be used for test cases</li> </ul> <p>For the function that finds the neighbors of a (row, col) of a matrix, My function was giving issues if the numbers of pixels in the image was less than a 3x3 because, for example, if image was a single pixel at (0,0), my code would say neighbors were (1,0) and (0, 1)</p> <p><strong>Better Solution:</strong></p> <pre class="lang-py prettyprint-override"><code> # get the vertical, and horizontal neighbors of cell (row, col) def adj_vert(self, row:int, col:int): #these are the diferentials from the cell that we are trying to find neighbors of, (row, col) # if we were considering all 8 neighbors, we would also have [1, 1], [-1, -1] , [1, -1], [-1, 1] for all four diagonals directions = [[1, 0], [-1, 0], [0,1], [0, -1]] adjacent_vertices = [] for dr, dc in directions: # adding the directions, to the cell we are finding the neighbors of, (row, col) r, c = row + dr, col + dc if r in range(self.total_rows) and c in range (self.total_cols): adjacent_vertices.append( (r, c) ) return adjacent_vertices </code></pre>
[]
[ { "body": "<blockquote>\n<p>The adj_vert method to get the neighbors of a pixel is extremely ugly. Is there a cleaner way to the approach I took?</p>\n</blockquote>\n<p>Yes, checking 4 conditions is enough. For example:</p>\n<pre><code>if row &gt; 0:\n adjs.append((row - 1, col))\nif row + 1 &lt; length:\n adjs.append((row + 1, col))\nif col &gt; 0:\n adjs.append((row, col - 1))\nif col + 1 &lt; width:\n adjs.append((row, col + 1))\n</code></pre>\n<blockquote>\n<p>Is there a similar problem on Leetcode to test more thoroughly for correctness?</p>\n</blockquote>\n<p>I see from your edit that you found a similar problem.</p>\n<blockquote>\n<p>Can I save on space by flipping each unvisited pixel marked as 1 to -1 on the same image?</p>\n</blockquote>\n<p>Yes, however that would change the input. If changing the input is allowed you can &quot;cancel&quot; the images flipping the 1s to 0s, so that no additional logic (to handle -1s) is needed.</p>\n<blockquote>\n<p>Any code design changes/ improvements that can be made?</p>\n</blockquote>\n<ul>\n<li>Input validation</li>\n<li>Docstrings</li>\n<li>Function instead of a class. A class seems inconvenient for this purpose. The constructor runs the algorithm directly and there is no method to get the result. The user needs to know that the attribute <code>self.connected_components</code> holds the result after creating the object. This is an unnecessary burden for the user, in my opinion, a function that returns directly the result would be enough.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T03:07:05.967", "Id": "269317", "ParentId": "269303", "Score": "2" } }, { "body": "<h3>Modifying the input</h3>\n<p>Before coding a solution that modifies the input, it's worth asking first &quot;is it ok to modify the input&quot;. If there's nobody to answer that, it's good to document it in a docstring (&quot;this solution modifies the input&quot;).</p>\n<h3>Alternatives to modifying the input</h3>\n<p>Your first solution builds a boolean matrix of the same dimensions as the input.</p>\n<p>Another way is to use a set of tuples, where each tuple is a row-column coordinate pair.</p>\n<p>Another way is to use a set of integers, where each element encodes a row-column coordinate pair using the formula: element = width * row + column.</p>\n<h3>Avoid repeated operations</h3>\n<p>The second variation of <code>adj_vert</code> recreates the <code>directions</code> list on every call. It would be better to create it in the constructor.</p>\n<p>The first variation of <code>adj_vert</code> recomputes width and length on every call. It would be better to set these in the constructor.</p>\n<h3>Avoid creating lists in a loop</h3>\n<p><code>adj_vert</code> creates a short-lived list (<code>adjs</code>) on every call. Allocating a new list repeatedly can be expensive, it would be better to refactor the code to avoid such repeated list creation.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T00:47:58.883", "Id": "531444", "Score": "0", "body": "\"Avoid repeated operations\" : If I am understanding correctly, you would recommend moving this to an \"instance variable\". so something like self.directions = [...] ? I think I like this idea if so... but, many times, it would be better to narrow the scope of the variables we create correct? even if it means re creating multiple times. @janos" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T00:51:04.573", "Id": "531445", "Score": "0", "body": "\"Avoid creating lists in loop\": How can I avoid the creation of a list, `adjs`, that will be used as the return value. I am a bit confused there. @janos" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T07:38:17.470", "Id": "531457", "Score": "1", "body": "You are right to be cautious of the scope of variables, and to limit visibility. Here, for the purposes of this class, the width and height of the input are practically constants. That makes it acceptable and useful to store them as fields. As for avoiding the short lived lists, you could inline the function, so that the caller can act directly on the computed neighbors. Or you could keep the current function, and make it act on the computed neighbors directly, rather than building a list from them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T07:50:18.590", "Id": "531458", "Score": "1", "body": "One more very simple way to avoid creating the short lived list is to make the function a generator function: instead of populating a list to return at the end, `yield` the values one by one. Since the caller iterates over the return value of the function, this change will be transparent (no other change needed in the caller)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T20:25:52.230", "Id": "269374", "ParentId": "269303", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-23T17:49:22.210", "Id": "269303", "Score": "3", "Tags": [ "python", "algorithm", "object-oriented", "graph" ], "Title": "Finding Number of Objects in Image" }
269303
<p>I learnt a function to display the imaginary part of a complex number &amp; that is <strong>.imag</strong> But when I was practising it, look what I found:</p> <pre><code>print(5-5j.imag) #&gt;&gt;&gt;0.0 print((5-5j).imag)#&gt;&gt;&gt;-5.0 print(2+4j.imag) #&gt;&gt;&gt;6.0 print((2+4j).imag)#&gt;&gt;&gt;4.0 </code></pre> <p>What's happening with the output in the 1st &amp; 2nd case?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T01:07:48.310", "Id": "531306", "Score": "2", "body": "I believe this question would be more suitable to stackoverflow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T01:11:55.930", "Id": "531307", "Score": "0", "body": "@joseville Yes but I, unfortunately, got blocked frm asking ques:(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T10:14:00.027", "Id": "531324", "Score": "1", "body": "Why are you surprised that `5 - 5j.imag` is zero?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T00:59:36.747", "Id": "531447", "Score": "0", "body": "Because I thought that it 5-5j would be considered as a whole." } ]
[ { "body": "<p>In the second and third <code>print</code> statements you're doing:</p>\n<p><code>a + bj.imag</code> = <code>a + (bj.imag)</code> = <code>a + b</code></p>\n<p>That is, you're taking the imaginary part of <code>bj</code> (which is <code>b</code>), then you're adding it to <code>a</code>. The result is that you print <code>a + b</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T10:15:49.507", "Id": "531326", "Score": "1", "body": "Please don't answer off-topic questions that are likely to get closed. This one is not asking for a code review, and this answer isn't a review of the code, so you are just wasting resources with this." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T01:06:09.923", "Id": "269316", "ParentId": "269315", "Score": "0" } } ]
{ "AcceptedAnswerId": "269316", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T00:41:11.250", "Id": "269315", "Score": "-2", "Tags": [ "python" ], "Title": ".imag Function for Complex Numbers" }
269315
<p>I'm reading &quot;Modern C++ Design&quot;(A. Alexandrescu, 2002) and practicing basic TMP in chapter 3. Typelists. Since the book is quite dated, I revised example codes in C++17-esque manner.</p> <p>Feel free to comment anything!</p> <pre><code>#include &lt;cstddef&gt; #include &lt;iostream&gt; #include &lt;utility&gt; #include &lt;type_traits&gt; // defining a typelist template &lt;typename T&gt; void printType() { std::cout &lt;&lt; __PRETTY_FUNCTION__ &lt;&lt; '\n'; } template &lt;typename...&gt; struct TypeList; template &lt;&gt; struct TypeList&lt;&gt; {}; template &lt;typename Head, typename... Tails&gt; struct TypeList&lt;Head, Tails...&gt; { using head = Head; using tails = TypeList&lt;Tails...&gt;; }; // length of a typelist template &lt;typename TList&gt; struct Length; template &lt;typename... Types&gt; struct Length&lt;TypeList&lt;Types...&gt;&gt; { static constexpr std::size_t value = sizeof...(Types); }; template &lt;typename TList&gt; inline constexpr std::size_t Length_v = Length&lt;TList&gt;::value; // indexed access template &lt;typename TList, std::size_t index&gt; struct TypeAt; template &lt;typename Head, typename... Tails&gt; struct TypeAt&lt;TypeList&lt;Head, Tails...&gt;, 0&gt; { using type = Head; }; template &lt;typename Head, typename... Tails, std::size_t index&gt; struct TypeAt&lt;TypeList&lt;Head, Tails...&gt;, index&gt; { static_assert(index &lt; sizeof...(Tails) + 1, &quot;index out of range&quot;); using type = typename TypeAt&lt;TypeList&lt;Tails...&gt;, index - 1&gt;::type; }; template &lt;typename TList, std::size_t index&gt; using TypeAt_t = typename TypeAt&lt;TList, index&gt;::type; // indexof template &lt;typename TList, typename T&gt; struct IndexOf; template &lt;typename T&gt; struct IndexOf&lt;TypeList&lt;&gt;, T&gt; { static constexpr std::size_t value = -1; }; template &lt;typename TList, typename T&gt; inline constexpr std::size_t IndexOf_v = IndexOf&lt;TList, T&gt;::value; template &lt;typename... Tails, typename T&gt; struct IndexOf&lt;TypeList&lt;T, Tails...&gt;, T&gt; { static constexpr std::size_t value = 0; }; template &lt;typename Head, typename... Tails, typename T&gt; struct IndexOf&lt;TypeList&lt;Head, Tails...&gt;, T&gt; { static constexpr std::size_t value = std::is_same_v&lt;Head, T&gt; ? 0 : (IndexOf_v&lt;TypeList&lt;Tails...&gt;, T&gt; == -1 ? -1 : IndexOf_v&lt;TypeList&lt;Tails...&gt;, T&gt; + 1); }; // appending to typelists template &lt;typename TList1, typename TList2&gt; struct Append; template &lt;typename... TList, typename T&gt; struct Append&lt;TypeList&lt;TList...&gt;, T&gt; { using result_type = TypeList&lt;TList..., T&gt;; }; template &lt;typename T, typename... TList&gt; struct Append&lt;T, TypeList&lt;TList...&gt;&gt; { using result_type = TypeList&lt;T, TList...&gt;; }; template &lt;typename... TList1, typename... TList2&gt; struct Append&lt;TypeList&lt;TList1...&gt;, TypeList&lt;TList2...&gt;&gt; { using result_type = TypeList&lt;TList1..., TList2...&gt;; }; template &lt;typename TList1, typename TList2&gt; using Append_t = typename Append&lt;TList1, TList2&gt;::result_type; // erasing a type from a typelist template &lt;typename TList1, typename T&gt; struct Erase; template &lt;typename TList1, typename T&gt; using Erase_t = typename Erase&lt;TList1, T&gt;::result_type; template &lt;typename... Tails, typename T&gt; struct Erase&lt;TypeList&lt;T, Tails...&gt;, T&gt; { using result_type = TypeList&lt;Tails...&gt;; }; template &lt;typename Head, typename... Tails, typename T&gt; struct Erase&lt;TypeList&lt;Head, Tails...&gt;, T&gt; { using result_type = Append_t&lt;Head, Erase_t&lt;TypeList&lt;Tails...&gt;, T&gt;&gt;; }; template &lt;typename TList1, typename T&gt; struct EraseAll; template &lt;typename TList1, typename T&gt; using EraseAll_t = typename EraseAll&lt;TList1, T&gt;::result_type; template &lt;typename T&gt; struct EraseAll&lt;TypeList&lt;&gt;, T&gt; { using result_type = TypeList&lt;&gt;; }; template &lt;typename... Tails, typename T&gt; struct EraseAll&lt;TypeList&lt;T, Tails...&gt;, T&gt; { using result_type = EraseAll_t&lt;TypeList&lt;Tails...&gt;, T&gt;; }; template &lt;typename Head, typename... Tails, typename T&gt; struct EraseAll&lt;TypeList&lt;Head, Tails...&gt;, T&gt; { using result_type = Append_t&lt;Head, EraseAll_t&lt;TypeList&lt;Tails...&gt;, T&gt;&gt;; }; // erasing duplicates template &lt;typename TList&gt; struct NoDuplicates; template &lt;typename TList&gt; using NoDuplicates_t = typename NoDuplicates&lt;TList&gt;::result_type; template &lt;&gt; struct NoDuplicates&lt;TypeList&lt;&gt;&gt; { using result_type = TypeList&lt;&gt;; }; template &lt;typename Head, typename... Tails&gt; struct NoDuplicates&lt;TypeList&lt;Head, Tails...&gt;&gt; { using result_type = Append_t&lt;Head, EraseAll_t&lt;NoDuplicates_t&lt;TypeList&lt;Tails...&gt;&gt;, Head&gt;&gt;; }; // replacing an element template &lt;typename TList, typename Old, typename New&gt; struct Replace; template &lt;typename TList, typename Old, typename New&gt; using Replace_t = typename Replace&lt;TList, Old, New&gt;::result_type; template &lt;typename Old, typename New&gt; struct Replace&lt;TypeList&lt;&gt;, Old, New&gt; { using result_type = TypeList&lt;&gt;; }; template &lt;typename... Tails, typename Old, typename New&gt; struct Replace&lt;TypeList&lt;Old, Tails...&gt;, Old, New&gt; { using result_type = TypeList&lt;New, Tails...&gt;; }; template &lt;typename Head, typename... Tails, typename Old, typename New&gt; struct Replace&lt;TypeList&lt;Head, Tails...&gt;, Old, New&gt; { using result_type = Append_t&lt;Head, Replace_t&lt;TypeList&lt;Tails...&gt;, Old, New&gt;&gt;; }; template &lt;typename TList, typename Old, typename New&gt; struct ReplaceAll; template &lt;typename TList, typename Old, typename New&gt; using ReplaceAll_t = typename ReplaceAll&lt;TList, Old, New&gt;::result_type; template &lt;typename Old, typename New&gt; struct ReplaceAll&lt;TypeList&lt;&gt;, Old, New&gt; { using result_type = TypeList&lt;&gt;; }; template &lt;typename... Tails, typename Old, typename New&gt; struct ReplaceAll&lt;TypeList&lt;Old, Tails...&gt;, Old, New&gt; { using result_type = ReplaceAll_t&lt;TypeList&lt;New, Tails...&gt;, Old, New&gt;; }; template &lt;typename Head, typename... Tails, typename Old, typename New&gt; struct ReplaceAll&lt;TypeList&lt;Head, Tails...&gt;, Old, New&gt; { using result_type = Append_t&lt;Head, ReplaceAll_t&lt;TypeList&lt;Tails...&gt;, Old, New&gt;&gt;; }; // partially ordering typelists template &lt;typename TList, typename Base&gt; struct MostDerived; template &lt;typename TList, typename Base&gt; using MostDerived_t = typename MostDerived&lt;TList, Base&gt;::result_type; template &lt;typename Base&gt; struct MostDerived&lt;TypeList&lt;&gt;, Base&gt; { using result_type = Base; }; template &lt;typename Head, typename... Tails, typename T&gt; struct MostDerived&lt;TypeList&lt;Head, Tails...&gt;, T&gt; { private: using cand = MostDerived_t&lt;TypeList&lt;Tails...&gt;, T&gt;; public: using result_type = std::conditional_t&lt;std::is_base_of_v&lt;cand, Head&gt;, Head, cand&gt;; }; template &lt;typename TList&gt; struct Derived2Front; template &lt;typename TList&gt; using Derived2Front_t = typename Derived2Front&lt;TList&gt;::result_type; template &lt;&gt; struct Derived2Front&lt;TypeList&lt;&gt;&gt; { using result_type = TypeList&lt;&gt;; }; template &lt;typename Head, typename... Tails&gt; struct Derived2Front&lt;TypeList&lt;Head, Tails...&gt;&gt; { private: using TheMostDerived = MostDerived_t&lt;TypeList&lt;Tails...&gt;, Head&gt;; public: using result_type = Append_t&lt;TheMostDerived, Replace_t&lt;TypeList&lt;Tails...&gt;, TheMostDerived, Head&gt;&gt;; }; class A { }; class B : public A { }; class C : public B { }; int main() { using numberList = TypeList&lt;int, double, float, uint8_t&gt;; printType&lt;numberList&gt;(); std::cout &lt;&lt; Length_v&lt;numberList&gt; &lt;&lt; '\n'; printType&lt;TypeAt_t&lt;numberList, 2&gt;&gt;(); std::cout &lt;&lt; IndexOf_v&lt;numberList, float&gt; &lt;&lt; '\n'; using charList = TypeList&lt;char, wchar_t, uint8_t&gt;; using AppendedList = Append_t&lt;numberList, charList&gt;; printType&lt;AppendedList&gt;(); printType&lt;Erase_t&lt;AppendedList, uint8_t&gt;&gt;(); printType&lt;EraseAll_t&lt;AppendedList, uint8_t&gt;&gt;(); printType&lt;NoDuplicates_t&lt;AppendedList&gt;&gt;(); printType&lt;Replace_t&lt;AppendedList, uint8_t, size_t&gt;&gt;(); printType&lt;ReplaceAll_t&lt;AppendedList, uint8_t, size_t&gt;&gt;(); using ChainList = TypeList&lt;A, B, C&gt;; printType&lt;MostDerived_t&lt;ChainList, A&gt;&gt;(); printType&lt;Derived2Front_t&lt;ChainList&gt;&gt;(); } </code></pre> <p>Test Result</p> <pre><code>void printType() [with T = TypeList&lt;int, double, float, unsigned char&gt;] 4 void printType() [with T = float] 2 void printType() [with T = TypeList&lt;int, double, float, unsigned char, char, wchar_t, unsigned char&gt;] void printType() [with T = TypeList&lt;int, double, float, char, wchar_t, unsigned char&gt;] void printType() [with T = TypeList&lt;int, double, float, char, wchar_t&gt;] void printType() [with T = TypeList&lt;int, double, float, unsigned char, char, wchar_t&gt;] void printType() [with T = TypeList&lt;int, double, float, long unsigned int, char, wchar_t, unsigned char&gt;] void printType() [with T = TypeList&lt;int, double, float, long unsigned int, char, wchar_t, long unsigned int&gt;] void printType() [with T = C] void printType() [with T = TypeList&lt;C, B, A&gt;] </code></pre>
[]
[ { "body": "<p>Overall, your code looks very good.</p>\n<h1>No need to overload for empty template parameter packs</h1>\n<p>A <code>typename...</code> parameter pack also matches zero elements, so the following overload is unnecessary:</p>\n<pre><code>template &lt;&gt;\nstruct TypeList&lt;&gt; {};\n</code></pre>\n<h1>Use <code>std::conditional</code> to avoid having to repeat code</h1>\n<p>You can use <code>std::conditional</code> to choose a type based on some condition. That allows you to merge some overloads, for example there is no longer a need to declare a <code>TypeAt&lt;..., 0&gt;</code>:</p>\n<pre><code>template &lt;typename Head, typename... Tails, std::size_t index&gt;\nstruct TypeAt&lt;TypeList&lt;Head, Tails...&gt;, index&gt; {\n static_assert(index &lt; sizeof...(Tails) + 1, &quot;index out of range&quot;);\n using type = typename std::conditional&lt;index == 0, Head, TypeAt&lt;TypeList&lt;Tails...&gt;, index - 1&gt;&gt;::type;\n};\n</code></pre>\n<h1>Missing test cases for empty typelists</h1>\n<p>When you write variadic templates, also be sure to test the cornercase where the parameter pack is empty. Your code handles empty typelists very well! Consider adding test cases like:</p>\n<pre><code>using EmptyList = TypeList&lt;&gt;;\nprintType&lt;EmptyList&gt;();\nstd::cout &lt;&lt; Length_v&lt;EmptyList&gt; &lt;&lt; '\\n';\n</code></pre>\n<p>Also test if modifying an empty typelist works as expected, and whether removing all types from a non-empty typelist results in an empty typelist.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T09:11:53.113", "Id": "269323", "ParentId": "269320", "Score": "11" } }, { "body": "<p>A minor point in the <code>main()</code> function: you have neglected to define <code>uint8_t</code>. I guess that should be <code>std::uint8_t</code> from <code>&lt;cstdint&gt;</code>, and that's leaked into global namespace from one of the other library headers - but it's not portable to rely on that!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T10:12:03.480", "Id": "269326", "ParentId": "269320", "Score": "5" } }, { "body": "<pre><code>template &lt;typename Head, typename... Tails, std::size_t index&gt;\nstruct TypeAt&lt;TypeList&lt;Head, Tails...&gt;, index&gt; {\n static_assert(index &lt; sizeof...(Tails) + 1, &quot;index out of range&quot;);\n using type = typename TypeAt&lt;TypeList&lt;Tails...&gt;, index - 1&gt;::type;\n};\n</code></pre>\n<p>static_assert is a late failure. You want to fail here early, so other code can detect this failure.</p>\n<pre><code>template &lt;typename Head, typename... Tails&gt;\nstruct TypeList&lt;Head, Tails...&gt; {\n using head = Head;\n using tails = TypeList&lt;Tails...&gt;;\n};\n</code></pre>\n<p>I'm uncertain if head/tails should be a fundamental property of the typelist.</p>\n<p>I'd write a function on typelists that returns the head and tail.</p>\n<pre><code>template&lt;class T&gt;\nstruct tails {};\ntemplate&lt;template&lt;class...&gt;class Z, class T0, class...Ts&gt;\nstruct tails&lt;Z&lt;T0, Ts...&gt;&gt; {\n using type=Z&lt;Ts...&gt;;\n};\ntemplate&lt;class T&gt;\nusing tails_t = typename tails&lt;T&gt;::type;\ntemplate&lt;class T&gt;\nstruct head {};\ntemplate&lt;template&lt;class...&gt;class Z, class T0, class...Ts&gt;\nstruct head&lt;Z&lt;T0, Ts...&gt;&gt; {\n using type=head;\n};\ntemplate&lt;class T&gt;\nusing head_t = typename head&lt;T&gt;::type;\n</code></pre>\n<p>This now works on anything (not just one <code>TypeList</code>).</p>\n<p>The syntax at point of use requires less <code>typename</code> spam as well.</p>\n<p>...</p>\n<p>The next thing to realize is that you are doing functional programming. There are better patterns than what you used.</p>\n<p>Try fmap/join/bind:</p>\n<pre><code>template&lt;template&lt;class...&gt;class F, class T&gt;\nstruct fmap {};\ntemplate&lt;template&lt;class...&gt;class F, class T&gt;\nusing fmap_t = typename fmap&lt;F,T&gt;::type;\n\ntemplate&lt;template&lt;class...&gt;class F, template&lt;class...&gt;class Z, class...Ts&gt;\nstruct fmap&lt;F, Z&lt;Ts...&gt;&gt; {\n using type=Z&lt;F&lt;Ts...&gt;&gt;;\n};\ntemplate&lt;class L&gt;\nstruct join;\ntemplate&lt;class L&gt;\nusing join_t = typename join&lt;L&gt;::type;\ntemplate&lt;template&lt;class...&gt;class Z, class... T0s, class... T1s, class..Zs&gt;\nstruct join&lt;Z&lt; Z&lt;T0s...&gt;, Z&lt;T1s...&gt;, Zs... &gt; &gt;:join&lt; Z&lt;Z&lt;T0s...&gt;, Zs... &gt; {};\ntemplate&lt;template&lt;class...&gt;class Z, class... T0s, class... T1s, class..Zs&gt;\nstruct join&lt;Z&lt; Z&lt;T0s...&gt; &gt; &gt; {\n using type=Z&lt;T0s...&gt;;\n};\ntemplate&lt;template&lt;class...&gt;class F, class T&gt;\nusing bind_t = join_t&lt; fmap_t&lt; F, T &gt; &gt;;\n</code></pre>\n<p>now we can express most of the rest of your operations using the above primitives.</p>\n<pre><code>template&lt;class Ts, class T&gt;\nusing append_t = join_t&lt; TypeList&lt; Ts, TypeList&lt;T&gt; &gt; &gt;;\n</code></pre>\n<p>Erase is just <code>bind( x-&gt;[x] except y-&gt;[], Ts )</code>. Replace is just <code>bind( x-&gt;[x] except y-&gt;[z], Ts )</code>.</p>\n<p>Now you will probably find writing these a bit annoying. Value metaprogramming to the rescue!</p>\n<p>In C++17 and later you can have constexpr lambdas. You can also write overloads of lambdas.</p>\n<pre><code>template&lt;class Match, class Replace&gt;\nconstexpr auto ReplaceAll = []( auto Types ) {\n return bind(\n overload( [](auto x){return x;}, [](tag_t&lt;Match&gt;){ return tag&lt;Replace&gt;; } ),\n Types\n );\n};\n</code></pre>\n<p>Converting TMP to this style of metaprogramming and back can be easier than writing clean TMP.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T16:54:24.193", "Id": "269367", "ParentId": "269320", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T06:08:57.263", "Id": "269320", "Score": "8", "Tags": [ "c++", "template-meta-programming" ], "Title": "C++17 : Typelist manipulation" }
269320
<p>I use the Emgu.CV wrapper to create a grayscale image. The data of this image are to be copied into a 2D byte array. Is there a more elegant solution than mine? I'm asking here at <em>CodeReview</em> because my code works and the question is therefore not suitable for <em>Stackoverflow</em>.</p> <p>If you want to reproduce this: You need the files <code>Emgu.CV</code>, <code>Emgu.CV.Bitmap</code> and <code>Emgu.CV.runtime.windows</code> from Visual Studio's own NuGet package manager.</p> <pre><code>Imports Emgu.CV Public NotInheritable Class FormMain Private Shared LoadedImage As System.Drawing.Bitmap Private Sub ButtonStart_Click(sender As Object, e As EventArgs) Handles ButtonStart.Click LoadedImage = New Drawing.Bitmap(&quot;C:\Users\Name\Desktop\test1.png&quot;) Using bgr As Emgu.CV.Image(Of Emgu.CV.Structure.Bgr, Byte) = LoadedImage.ToImage(Of Emgu.CV.Structure.Bgr, Byte) Using imgGray As Emgu.CV.Image(Of Emgu.CV.Structure.Gray, Byte) = bgr.Convert(Of Emgu.CV.Structure.Gray, Byte)() 'in ein 2D-Array kopieren Dim f(imgGray.Height - 1, imgGray.Width - 1) As Byte For y As Integer = 0 To imgGray.Height - 1 Step 1 For x As Integer = 0 To imgGray.Width - 1 Step 1 f(y, x) = imgGray.Data(y, x, 0) Next Next ' do something with f(,) End Using End Using End Sub End Class </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T11:58:26.770", "Id": "531337", "Score": "0", "body": "That's great - a good title really helps attract the right reviewers. Sorry it's not a language I've ever used, otherwise I would attempt a review myself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T12:22:21.663", "Id": "531339", "Score": "0", "body": "Would _C#_ help you?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T12:24:04.060", "Id": "531340", "Score": "0", "body": "No, I'm mainly C++, C and shell, with a sprinkling of Python and Lisp. But I do think you will get a review from someone more capable than me, so don't worry." } ]
[ { "body": "<h1>Separating UI from business logic</h1>\n<p>You have put everything into the button click event handler. This is really bad practice. Consider creating a separate class to handle the image processing:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Class ImageProcessor\n\n Public Function Process(inputFilePath As String) As String\n Dim rawData As Color(,) = LoadImage(inputFilePath)\n Dim grayData As Byte(,) = ConvertToGrayscale(rawData)\n Process = DoMagicOnImage(grayData)\n End Function\n\n Private Function LoadImage(inputFilePath As String) As Color(,)\n ... \n End Function\n\n Private Function ConvertToGrayscale(src As Color(,)) As Byte(,)\n ....\n End Function\n\n Private Function DoMagicOnImage(src As Byte(,)) As String\n ....\n End Function\n\nEnd Class\n</code></pre>\n<p>And changing <code>ButtonStart_Click</code> to the following:</p>\n<pre class=\"lang-vb prettyprint-override\"><code>Private Sub ButtonStart_Click(sender As Object, e As EventArgs) Handles ButtonStart.Click\n Dim inputFilePath As String = &quot;C:\\Users\\Name\\Desktop\\test1.png&quot;;\n Dim processor As ImageProcessor = new ImageProcessor\n Dim result As String = processor.Process(inputFilePath)\nEnd Sub\n</code></pre>\n<h1>Disposing of Disposable objects.</h1>\n<p>If you click on <code>ButtonStart</code> enough times your program is bound to crash in a bad way. You should always dispose of disposable objects such as <code>Drawing.Bitmap</code>.</p>\n<p>I see you are already disposing of <code>bgr</code> and <code>imgGray</code> so why not do the same for <code>LoadedImage</code>?</p>\n<h1>Implementation</h1>\n<p>Here you will have to excuse my rudimentary knowledge of Visual basic =)</p>\n<pre class=\"lang-vb prettyprint-override\"><code>Class ImageProcessor\n\n Public Function Process(inputFilePath As String) As String\n Dim rawData As Color(,) = LoadImage(inputFilePath)\n Dim grayData As Byte(,) = ConvertToGrayscale(rawData)\n Process = DoMagicOnImage(grayData)\n End Function\n\n Private Function LoadImage(inputFilePath As String) As Color(,)\n Using bmp As Bitmap = New Bitmap(inputFilePath)\n ' Lock the bitmap data.\n Dim bounds As Rectangle = New Rectangle(0, 0, bmp.Width, bmp.Height)\n Dim bmpData As BitmapData = bmp.LockBits(bounds, Imaging.ImageLockMode.ReadWrite, Imaging.PixelFormat.Format24bppRgb)\n ' Allocate room for the data.\n Dim total_size As Integer = bmpData.Stride * bmpData.Height\n ' Copy the data into the imageBytes array.\n Dim imageBytes As Byte()\n ReDim imageBytes(total_size)\n Marshal.Copy(bmpData.Scan0, imageBytes, 0, total_size)\n ' Copy imagesBytes into color array\n Dim multiDim As Color(,)\n ReDim multiDim(bmp.Width, bmp.Height)\n Dim x As Integer, y As Integer\n For y = 0 To bmp.Height - 1\n Dim rowIndex As Integer = y * bmpData.Stride\n For x = 0 To bmp.Width - 1\n Dim r As Integer = imageBytes(rowIndex + x * 3 + 2)\n Dim g As Integer = imageBytes(rowIndex + x * 3 + 1)\n Dim b As Integer = imageBytes(rowIndex + x * 3 + 0)\n multiDim(x, y) = Color.FromArgb(r, g, b)\n Next\n Next\n bmp.UnlockBits(bmpData)\n LoadImage = multiDim\n End Using\n End Function\n\n Private Function ConvertToGrayscale(src As Color(,)) As Byte(,)\n Dim Width As Integer = src.GetUpperBound(0)\n Dim Height As Integer = src.GetUpperBound(1)\n Dim data As Byte(,)\n ReDim data(Width, Height)\n For y As Integer = 0 To Height - 1\n For x As Integer = 0 To Width - 1\n Dim col As Color\n col = src(x, y)\n data(x, y) = (col.R * 0.3 + col.G * 0.59 + col.B * 0.11)\n Next\n Next\n ConvertToGrayscale = data\n End Function\n\n Public Sub TestFunction(inputFilePath As String, outputFile As String)\n Dim colorData As Color(,) = LoadImage(inputFilePath)\n Dim grayData As Byte(,) = ConvertToGrayscale(colorData)\n Dim Width As Integer = grayData.GetUpperBound(0)\n Dim Height As Integer = grayData.GetUpperBound(1)\n Using bmp As Bitmap = New Bitmap(Width, Height)\n For y = 0 To Height - 1\n For x = 0 To Width - 1\n Dim pixel As Byte = grayData(x, y)\n bmp.SetPixel(x, y, Color.FromArgb(pixel, pixel, pixel))\n Next\n Next\n bmp.Save(outputFile)\n End Using\n End Sub\n\nEnd Class\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T05:21:51.430", "Id": "531373", "Score": "0", "body": "In `LoadImage()` you need to call `UnlockBits()` on the bitmap. In the same method you should take into account that it is possible that `BitmapData.Stride` may be negative. For `LockBits()` you shouldn't assume the passed `PixelFormat`, just pass the `Bitmap.Pixelformat` property. Otherwise good review!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T11:58:31.723", "Id": "531394", "Score": "0", "body": "@Heslacher, good points. I have updated the answer to use `UnlockBits`. I'm not really sure how to handle a negative stride correctly, to be honest =) Also will `r`,`g`, and `b` always be in this order or could it be different depending on endianness?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T12:02:30.497", "Id": "531396", "Score": "0", "body": "@Heslacher, I should probably have stopped the review at implementation. The OP will most likely be better of using `Emgu.CV` but I always like to understand how things work under the hood." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T12:17:07.290", "Id": "531398", "Score": "0", "body": "You should use `Math.Abs()` for handling the negative `Stride`. The order of r,g,b won't be different for depending on endianness. If the loaded Bitmap isn't 24bit but 32bit you would need to change `imageBytes(rowIndex + x * 3 + 2)` e.g to `imageBytes(rowIndex + x * 4 + 2)`. While I write this, I see that you have to have `Step 3` (24bit)/`Step 4` (32bit) for the inner loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T12:31:33.480", "Id": "531399", "Score": "0", "body": "@Heslacher, I would have fought that `LockBits` thunks the data into the pixel format that you specify. I have tried the code with an 8-bit .bmp file and it seems to work. Simply using the absolute value of the stride does not make sense, why would it then be negative in the first place?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T12:37:33.650", "Id": "531400", "Score": "0", "body": "[BitmapData.Stride](https://docs.microsoft.com/en-us/dotnet/api/system.drawing.imaging.bitmapdata.stride?view=windowsdesktop-5.0) in the remarks section \"If the stride is positive, the bitmap is top-down. If the stride is negative, the bitmap is bottom-up.\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T13:27:06.017", "Id": "531406", "Score": "0", "body": "@Heslacher, does this look correct? [TIO](https://tio.run/##XYxBCsIwFAX3OcVbtkKCHkCh0IJZuNILJM1vE2hTSWK1p49ZCfbB7Gbe6uJLTVyr6HruKfFV9zm3bkZY3tIb@qCJkD7RSIHJAXp@tiopcU/BGcIFRzwseYayX3LGhsNOZd0Uaa9VxRFXcqNN4DgVtrqUN5WsaHSs/i9q1nkDOeT8BQ)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T14:17:05.933", "Id": "531408", "Score": "0", "body": "For converting the whole image to greyscale, you won't need to do this so complicated. You should just use `Math.Abs(bmpData.Stride)` instead of `bmpData.Stride`. One time for `total_size ` and one time for `rowIndex`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T14:53:00.990", "Id": "531410", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/130838/discussion-between-upkajdt-and-heslacher)." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T13:07:56.957", "Id": "269330", "ParentId": "269321", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T08:12:52.743", "Id": "269321", "Score": "4", "Tags": [ "array", "vb.net" ], "Title": "Read an image file as greyscale byte array" }
269321
<p>I made a CSV class which manages CSV files. Is this good?, I'm beginner btw. It's probably bad but can you give me some tips!</p> <p>Header file:</p> <pre><code>#include &lt;vector&gt; #include &lt;string&gt; #include &lt;fstream&gt; #include &lt;sstream&gt; #include &lt;map&gt; #pragma once class CSVFile { public: //Debug opening mode. Prints a debug message if successfully opened the file. static int debug; //Writes a new line after function static int addNewLine; //Does not write new line after function static int doNotAddLine; //Default Constructor CSVFile(const char* _name); //Create and open file with opening modes. CSVFile(const char* _name, int num); //Clear file, write a new row and end line //Opens file in write mode (fstream::out) void WriteRow(std::string txt, int num = 2); //Adds a new row to the file without clearing data and ends line //Opens file in append mode (fstream::app) void AppendRow(std::string txt, int num = 2); //Clears Data in the file void EmptyContents(); //Returns value in cell. Returns //last value if row or column is out of bounds. //Arguments: row and column of cell std::string GetCell(int row, int column); //Goes to next line by writing a newline character('\n') void NextLine(); //Deletes file void DeleteFile(); std::string operator()(int row, int column); //Overloading extraction operator for 2d vectors void operator&gt;&gt; (std::vector&lt;std::vector&lt;std::string&gt;&gt;&amp; csvVector); //Overloading insertion operator for 2d vectors void operator&lt;&lt; (std::vector&lt;std::vector&lt;std::string&gt;&gt; myVector); //Parsing from text file to map. // If first column of file is not a number, // characters from a-z or A-Z gets converted to integers from 1-26 void operator&gt;&gt; (std::map&lt;int, std::string&gt;&amp; map); //Overloading insertion operator for map&lt;int, string&gt; void operator&lt;&lt; (std::map&lt;int, std::string&gt; map); private: std::fstream file; std::string name; }; </code></pre> <p>Cpp file:</p> <pre><code>#include &quot;CSVFile.h&quot; CSVFile::CSVFile(const char* _name) : name(_name) { file.open(name, std::fstream::app); file.close(); } CSVFile::CSVFile(const char* _name, int num) : name(_name) { file.open(name, std::fstream::app); if (num == 1) { file &lt;&lt; &quot;Debug: File opened successfully\n&quot;; } file.close(); } void CSVFile::WriteRow(std::string txt, int num) { file.open(name, std::fstream::out); file.clear(); file.seekg(0); file &lt;&lt; txt; if (num == 2) { file &lt;&lt; &quot;\n&quot;; } file.close(); } void CSVFile::AppendRow(std::string txt, int num) { file.open(name, std::fstream::app); file.clear(); file.seekg(0); file &lt;&lt; txt; if (num == 2) { file &lt;&lt; &quot;\n&quot;; } file.close(); } void CSVFile::EmptyContents() { file.open(name, std::fstream::out); file.close(); } std::string CSVFile::GetCell(int row, int column) { file.open(name, std::fstream::in); file.clear(); file.seekg(0); std::string rowData; std::string cellData; for (int i = 0; i &lt; row; i++) { std::getline(file, rowData, '\n'); } std::stringstream sso; sso &lt;&lt; rowData; for (int c = 0; c &lt; column; c++) { std::getline(sso, cellData, ','); } return cellData; file.close(); } void CSVFile::NextLine() { file.open(name, std::fstream::app); file &lt;&lt; &quot;\n&quot;; file.close(); } void CSVFile::DeleteFile() { remove(name.c_str()); } std::string CSVFile::operator()(int row, int column) { return this-&gt;GetCell(row, column); } void CSVFile::operator&gt;&gt; (std::vector&lt;std::vector&lt;std::string&gt;&gt;&amp; csvVector) { std::vector&lt;std::string&gt; rows; file.open(name, std::fstream::in); file.clear(); file.seekg(0); while (file.peek() != std::fstream::traits_type::eof()) { std::string row; std::getline(file, row, '\n'); if (row != &quot;&quot;) { std::stringstream string; string &lt;&lt; row; std::string value; while (std::getline(string, value, ',')) { rows.push_back(value); } csvVector.push_back(rows); rows.clear(); } else { csvVector.push_back({ &quot;&quot; }); } } file.close(); } void CSVFile::operator&lt;&lt; (std::vector&lt;std::vector&lt;std::string&gt;&gt; myVector) { file.open(name, std::fstream::app); for (std::size_t r = 0; r &lt; myVector.size(); r++) { for (std::size_t c = 0; c &lt; myVector[r].size(); c++) { file &lt;&lt; myVector[r][c]; if (c != myVector[r].size() - 1) { file &lt;&lt; &quot;,&quot;; } else if (r != myVector.size() - 1) { file &lt;&lt; &quot;\n&quot;; } } } file.close(); } void CSVFile::operator&gt;&gt;(std::map&lt;int, std::string&gt;&amp; map) { file.open(name, std::fstream::in); file.clear(); file.seekg(0); while (file.peek() != std::fstream::traits_type::eof()) { std::string row; std::getline(file, row, '\n'); if (row != &quot;&quot;) { std::string keyString; std::string value; std::stringstream sso; sso &lt;&lt; row; std::getline(sso, keyString, ','); std::getline(sso, value); if (keyString.find_first_not_of(&quot;0123456789&quot;) == std::string::npos) { map[std::stoi(keyString)] = value; } else { char keyChar = keyString[0]; keyChar = std::tolower(keyChar); if (int(keyChar) &gt; 96 &amp;&amp; int(keyChar) &lt;= 122) { map[int(keyChar) - 96] = value; } } } } file.close(); } void CSVFile::operator&lt;&lt;(std::map&lt;int, std::string&gt; map) { file.open(name, std::fstream::app); for (auto pair : map) { file &lt;&lt; pair.first &lt;&lt; &quot;,&quot; &lt;&lt; pair.second; if (map.rbegin()-&gt;first != pair.first) { file &lt;&lt; &quot;\n&quot;; } } file.close(); } int CSVFile::debug = 1; int CSVFile::addNewLine = 2; int CSVFile::doNotAddLine = 3; </code></pre>
[]
[ { "body": "<p>This code is nicely presented, which is great for reviewing. It would have been nice to see some usage examples, or (even better) some unit tests. One of the things that makes it hard to write good unit tests is that we've chosen to represent a <em>file</em>; if we make our core code work with <code>std::istream</code> and <code>std::iostream</code>, then it will be more testable, and we can still provide wrappers that can open files to obtain streams.</p>\n<hr />\n<p>I did notice¹ in <code>GetCell()</code> this unreachable code:</p>\n<blockquote>\n<pre><code>return cellData;\nfile.close();\n</code></pre>\n</blockquote>\n<p>That last line will never be reached. It's actually not a problem here, since the <code>std::file</code> destructor will close for us anyway. I recommend only calling <code>close()</code> when we care about the result (e.g. when we write to the file).</p>\n<hr />\n<p><code>#pragma once</code> is non-standard. Prefer to use conventional <code>#ifndef</code>/<code>#define</code> include guards for portable headers.</p>\n<hr />\n<p>These three members seem never to be used:</p>\n<blockquote>\n<pre><code>//Debug opening mode. Prints a debug message if successfully opened the file.\nstatic int debug;\n\n//Writes a new line after function\nstatic int addNewLine;\n\n//Does not write new line after function\nstatic int doNotAddLine;\n</code></pre>\n</blockquote>\n<hr />\n<p>This constructor looks a little strange:</p>\n<blockquote>\n<pre><code>CSVFile::CSVFile(const char* _name, int num) : name(_name) {\n file.open(name, std::fstream::app);\n if (num == 1)\n {\n file &lt;&lt; &quot;Debug: File opened successfully\\n&quot;;\n }\n file.close();\n}\n</code></pre>\n</blockquote>\n<p>Firstly, <code>num</code> is pretty meaningless as an argument name. Is it the number of lines we're going to read? No, it seems that it's a flag to control whether we write a debug message to the end of the <em>data file</em> - that looks very wrong. Normally, debug messages should go to the <code>std::clog</code> stream.</p>\n<hr />\n<p>It certainly seems odd that almost every operation needs to open and close the file. I would expect such a class to read once into a matrix (e.g. array of arrays) when constructed or explicitly asked to read, and only write when it is asked to.</p>\n<hr />\n<p>This character-handling code looks problematic in several ways:</p>\n<blockquote>\n<pre><code> char keyChar = keyString[0];\n keyChar = std::tolower(keyChar);\n if (int(keyChar) &gt; 96 &amp;&amp; int(keyChar) &lt;= 122) {\n map[int(keyChar) - 96] = value;\n }\n</code></pre>\n</blockquote>\n<p>We don't know whether <code>keyString</code> is empty, which could make <code>keyString[0]</code> an invalid access.</p>\n<p><code>std::tolower()</code> has a problematic interface that in practice requires us to convert the argument to <code>unsigned char</code> before calling (because <code>char</code> may be signed, and we're not permitted to pass negative values other than <code>EOF</code>).</p>\n<p>Finally, comparing characters against specific numeric values isn't portable, as we don't know which character coding is in use. I'm guessing you're working on an ASCII (or similar, e.g. ISO 8859.1) platform, where those numbers represent <code>'`'</code> and <code>~</code> respectively. To make this portable, we need to do a string search like we did when we checked whether <code>keystring</code> was composed of digits, but this time testing whether the character is in <code>&quot;abcdefghijklmnopqrstuvwxyz{|}~&quot;</code>.</p>\n<hr />\n<p>We're lacking good handling of errors throughout the program. Consider which operations can fail:</p>\n<ul>\n<li><code>std::fstream::open()</code></li>\n<li><code>std::getline()</code>\nAnd some can throw exceptions:</li>\n<li><code>std::stoi()</code></li>\n</ul>\n<p>(That's not necessarily a complete list, just some functions I spotted during a skim read).</p>\n<p>Make sure your program knows what to do when (for example) the file doesn't exist, or isn't readable by the user, or isn't writable. Or if there's a numeric value too big to represent (and have we handled negative values properly?).</p>\n<p>To start with, I wouldn't even attempt to support numberic values in the files - treat everything as a string, at least until you have that robust enough to move on.</p>\n<hr />\n<p>¹ More accurately, my compiler warned me about this - and so should yours, so check that you've enabled a full set of warnings. If it helps, I used <code>g++ -std=c++20 -fanalyzer -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wconversion -Weffc++ -Wuseless-cast</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T14:07:04.517", "Id": "531346", "Score": "0", "body": "Thanks for all the help. I don't know anything about the warnings and stuff you said in the last paragraph. Also, can you explain to me whether it is possible that I can give a warning to the user if there are some errors like the ones you said?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T14:28:41.513", "Id": "531349", "Score": "0", "body": "Yes, you can write diagnostics to the standard error stream `std::cerr`. Although, as this is a library, it's usually better to find some way to inform the calling program (via an exception, or through the return value), and let that decide how (and whether) to report that to the user. In some cases, there's no need for a message; for example if we want to open a file in one location, but fall back to a different file if that one isn't present." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T14:31:00.767", "Id": "531350", "Score": "0", "body": "How to enable warnings depends completely on which compiler you're using, which is why I didn't go into detail. But do be aware that most compilers only report errors which are required by the standard unless you ask for more warnings to be reported, so we nearly always need to find how to do that." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T13:44:14.323", "Id": "269331", "ParentId": "269329", "Score": "1" } }, { "body": "<h1>Use <code>bool</code> instead of <code>int</code></h1>\n<p>Consider changing the static flags to bool:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>static bool debug;\nstatic bool addNewLine;\nstatic bool doNotAddLine;\n</code></pre>\n<p>Having both <code>addNewLine</code> and <code>doNotAddLine</code> does not make sense. Actually, since you are not using any of these flags you can simply remove them.</p>\n<h1>Multiple constructors</h1>\n<p>Instead of having multiple constructors, you could have created one with a default value:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>CSVFile(const char* _name, bool debug = false)\n{\n file.open(name, std::fstream::app);\n if (debug)\n {\n file &lt;&lt; &quot;Debug: File opened successfully\\n&quot;;\n }\n file.close();\n}\n</code></pre>\n<h1>Passing objects by reference</h1>\n<p>Every time you pass a <code>std::string</code> by value you are unnecessarily making a copy of the string. Consider changing:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>void WriteRow(std::string txt, int num = 2);\n</code></pre>\n<p>To the following:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>void WriteRow(const std::string&amp; txt, int num = 2);\n</code></pre>\n<p>I'm not sure what is going on with <code>num = 2</code>. It would be much more clear to use:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>void WriteRow(const std::string&amp; txt, bool isNumber = true);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T13:53:31.757", "Id": "531341", "Score": "0", "body": "Thank you so much for all the tips, I'll add them now itself. I know that those static flags looked weird and useless haha, I was trying to learn them so I experimented with them lol." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T14:00:11.683", "Id": "531344", "Score": "1", "body": "@ihsan, cool! Note that you should not edit your question as this will invalidate the responses. Additionally, I would advise you to not accept an answer so quickly. This may discourage people from adding additional answers that may have given you more insights =)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T14:02:06.463", "Id": "531345", "Score": "0", "body": "@upkadjt sorry my bad! im pretty new to code review" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T13:47:52.700", "Id": "269332", "ParentId": "269329", "Score": "2" } }, { "body": "<pre><code>//Default Constructor\nCSVFile(const char* _name);\n</code></pre>\n<p>That's <strong>not</strong> a default constructor, by definition. This one-argument constructor ought to be <code>explicit</code>. Why does it take a C-style string for the argument? I'll probably formulate the file name via <code>std::string</code> or <code>std::filesystem::path</code> operations. If your implementation uses low-level C library of POSIX primitives so they take C strings, extract that from the C++ type inside the function.</p>\n<p>Bottom line: use <code>filesystem::path</code> to pass file names.</p>\n<hr />\n<p><code>void WriteRow(std::string txt, int num = 2);</code><br />\nWhy does writing a row need to <strong>copy</strong> the <code>txt</code> argument locally? It is very odd to pass a <code>string</code> by value so it draws attention from reviewers even when it is a proper thing to do.</p>\n<p>I'm guessing you really want: <code>void WriteRow(std::string_view txt, int num=2)</code></p>\n<p>And what's <code>num</code> do? For that matter, just what is &quot;writing a row&quot;? This is for CSV files, so I expect a list of values, not a &quot;row&quot;. I'd better look at the implementation...</p>\n<pre><code>if (num == 2) {\n file &lt;&lt; &quot;\\n&quot;;\n</code></pre>\n<p>say what? <code>num' is a parameter that causes a newline to be automatically written after whatever was in the string, when </code>num==2`. Are you kidding me?</p>\n<p><code>//Clear file, write a new row and end line</code><br />\nwell, that's not even right (see previous paragraph)</p>\n<hr />\n<p>I see <code>file</code> is opened and closed with each call. So why does <code>file</code> need to be a member? It should be a local variable inside each function. It has no purpose as member data.</p>\n<hr />\n<p>I have no idea how this is supposed to be used or how it works. There is a function <code>NextLine</code> that appends a newline?</p>\n<p><code>GetCell</code> opens the file, reads a line at a time until if finds the right line number, then returns only one column? Can you imagine how slow this will be to read a whole record, let alone a whole file full of records?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T18:15:13.937", "Id": "269371", "ParentId": "269329", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T12:49:19.340", "Id": "269329", "Score": "2", "Tags": [ "c++", "csv" ], "Title": "Abstraction for CSV files" }
269329
<p>I want to implement a function (or several) that must run <em><strong>exactly once</strong></em> when the program terminates, no matter how this termination came about<sup>1</sup>.</p> <p>Below is my best attempt at doing this. Specifically, the code between the <code>####...####</code> dividers is the most succinct<sup>2</sup> implementation of this functionality I have managed to come up with.</p> <p>I post it here primarily because even this my &quot;most succinct&quot; implementation seems to me like way too much code for what I regard as an extremely common use-case. Can the same be achieved more simply?</p> <pre class="lang-py prettyprint-override"><code>from __future__ import print_function ############################################################################## import sys import atexit import signal @atexit.register def cleanup_1(): print2('running cleanup_1') @atexit.register def cleanup_0(): print2('running cleanup_0') def excepthook(exception_type, exception_value, traceback): # better: log the unhandled exception print2('unhandled exception: {}'.format(exception_type.__name__)) sys.excepthook = excepthook def _set_handlers(): _numbers_to_names = { int(getattr(signal, name)): name for name in dir(signal) if name.startswith('SIG') and '_' not in name } def signal_handler(signal_number, stack): signal_name = _numbers_to_names[signal_number] print2('received signal: {0} ({1})'.format(signal_number, signal_name)) sys.exit(signal_number) # The signals included in the array below are the ones that cause the # process to terminate when I run it on my system. This may need # fine-tuning for portability. to_handle = ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGIOT', 'SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGALRM', 'SIGTERM', 'SIGXCPU', 'SIGVTALRM', 'SIGPROF', 'SIGPOLL', 'SIGPWR', 'SIGSYS'] for signal_name in to_handle: signal_number = getattr(signal, signal_name) handler = signal.getsignal(signal_number) if handler is signal.SIG_DFL: signal.signal(signal_number, signal_handler) _set_handlers() del _set_handlers ############################################################################## def print2(*args, **kwargs): if 'file' in kwargs: raise TypeError(&quot;'file' is an invalid argument for print2()&quot;) print(*args, file=sys.stderr, **kwargs) def run(*args): print2('running...'.format(args[0])) if '0' in args[:1]: return if '1' in args[:1]: raise RuntimeError() while True: pass def bye(): print2('program terminates normally') sys.exit(0) def main(*args): run(*args) bye() if __name__ == '__main__': main(*sys.argv[1:]) </code></pre> <p><strong>Notes on the implementation</strong></p> <ul> <li>The code before and after the <code>####...####</code>-delimited section is there just to let me try out the implemented cleanup functionality informally on the command line. (In other words, this code is not really the primary focus of this post; feel free to comment on it if you wish, but please do not dwell on it at the expense of the code between the <code>####...####</code> dividers.)</li> <li>I wrote the code so that it is compatible with both Python 2 and Python 3.</li> <li>One problem with a short example like this one is that it does not capture the complexity of production software, where multiple libraries may independently want to register their own clean up functions and signal handlers. As I was writing this code, I tried to keep these more complex scenarios in mind, though I do not know if I succeeded. It is quite possible that, if I tried to use the code above in production, I may find that it is fundamentally unsuitable for such more complex situations. Feedback on the suitability of this code for a production setting is particularly welcome.</li> <li>If you want to run the code on the command line, an argument of <code>0</code> causes the script to terminate normally (and right away); an argument of <code>1</code> causes the script to fail with a <code>RuntimeError</code> exception; any other argument (or no argument) causes the script to enter an infinite loop (so that one can comfortably send signals to it).</li> </ul> <hr /> <p><strong>EDITS:</strong> I moved the definitions of the actual cleanup functions (<code>cleanup_1</code> and <code>cleanup_0</code>) nearer to the top, removed some comments from the <code>_set_handlers</code> function, and re-wrote the initialization of its <code>to_handle</code> variable in fewer lines.</p> <hr /> <p><sup><sup>1</sup> I realize that, as stated, this goal is not achievable (i.e., no matter what I do, my cleanup function(s) will not run if the computer crashes, for example, while the program is running). Therefore, please interpret the stated goal as &quot;an ideal to strive for&quot;.</sup></p> <p><sup><sup>2</sup> I want to stress that, although I am looking for something &quot;shorter&quot;, I do not intend this post as a &quot;code golf&quot; exercise. When I write &quot;most succinct&quot;, I take it for granted that readability and clarity remain non-negotiable requirements. Rather I am looking for standard Python facilities or idioms that achieve the same aims as my code does in much fewer lines, and yet without sacrificing readability and clarity.</sup></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T13:53:48.833", "Id": "531342", "Score": "4", "body": "Long time no see - welcome back! It's great to see code presented with such a helpful program to exercise it. I hope you get some good reviews for this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T13:56:29.007", "Id": "531343", "Score": "0", "body": "@TobySpeight: Thank you, I appreciate the encouragement!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T14:26:03.110", "Id": "531348", "Score": "0", "body": "Have you thought of using a context manager? What are the drawbacks to using a context manager? If the only issue is Python 2.x compatibility have you thought about using a context manager with a `try` `finally` instead - effectively re-writing `with`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T12:02:07.483", "Id": "531395", "Score": "0", "body": "@Peilonrayz: sorry for not asking you this earlier, but it is not clear to me how context managers address my post's question. Could you post a code sketch of what you have in mind?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T13:32:56.383", "Id": "531407", "Score": "1", "body": "Please do not incorporate answers into your question. If you have new code that you still would like to have reviewed further, please post a follow-up question instead." } ]
[ { "body": "<blockquote>\n<pre><code> sys.exit(signal_number)\n</code></pre>\n</blockquote>\n<p>This is quite different visible behaviour, as seen by the parent process. It might be better to remove the signal handler and then re-raise the signal (using <code>signal.raise_signal()</code> on ourself), so that we don't perturb the rest of the behaviour. Also, that would stop us inhibiting core dumps for the signals where that's the default response.</p>\n<hr />\n<p>I see that we use <code>signal.getsignal()</code> to avoid adding our handler for defaulted signals - that's pretty good. There's a tiny weakness when it returns <code>None</code> - we don't know whether a non-Python signal handler is going to unilaterally exit the process without returning to the interpreter, so it's impossible to know whether or not to perform the clean-up in that case. I think we'd benefit from having that in a comment.</p>\n<hr />\n<p>It's a shame we have to explicitly list the signals which normally cause program termination. It means we have to consider all platforms we could possibly run on. On Linux, we need also to catch</p>\n<ul>\n<li><code>SIGABRT</code></li>\n<li><code>SIGEMT</code></li>\n<li><code>SIGLOST</code></li>\n<li><code>SIGPIPE</code></li>\n<li><code>SIGSTKFLT</code></li>\n<li><code>SIGXFSZ</code></li>\n<li>The full set of real-time signals.</li>\n</ul>\n<p>It would be nice if there were a way to enumerate signals whose default action is to terminate the process (with or without core dump), but I'm not aware that's even possible.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T11:54:41.303", "Id": "531391", "Score": "0", "body": "Thank you for your feedback! I agree with you that having the signal handler run `sys.exit(signal_number)` is a questionable design choice. Unfortunately, the alternative design of just having the handler run `signal.raise_signal(signal_number)`, by itself, would mean that the callbacks registered with `atexit` would not run. (This is the reason for trapping the signals in the first place.) Therefore one would have to \"manually\" run those callbacks. One can do this with `atexit._run_exitfuncs()`. As one could guess from the leading underscore in its name, however, ..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T11:54:50.457", "Id": "531392", "Score": "0", "body": "...this function is not part of the [official `atexit` API](https://docs.python.org/3/library/atexit.html). Therefore, this design choice boils down to which one considers the \"lesser evil\": running `sys.exit(...)` upon receiving a terminating signal, or \"reaching behind\" `atexit`'s API. That said, on further thought, I am now inclined to opt for the latter as the lesser evil." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T11:56:30.800", "Id": "531393", "Score": "1", "body": "Oh yes, that's a dilemma! I'm glad the review helped you come to a decision on what best to do here." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T14:26:16.033", "Id": "269334", "ParentId": "269333", "Score": "1" } } ]
{ "AcceptedAnswerId": "269334", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T13:48:31.810", "Id": "269333", "Score": "2", "Tags": [ "python" ], "Title": "Implementing a clean-up function that must run at program's termination no-matter-what" }
269333
<p>As an exercise to learn more about multi-threading and atomic operations work in C++, I decided to implement a <em>latch</em> class in C++11 loosely based off of <a href="https://en.cppreference.com/w/cpp/thread/latch" rel="nofollow noreferrer"><code>std::latch</code></a> class from C++20 and would like to know whether this implementation is flawed in any sort of way or form and how I could improve upon it:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;cstdint&gt; #include &lt;atomic&gt; #include &lt;mutex&gt; class latch { std::atomic&lt;std::ptrdiff_t&gt; counter_; mutable std::mutex mut_; public: explicit latch(std::ptrdiff_t const def = 1) : counter_(def) {} void count_down(std::ptrdiff_t const n = 1) { counter_ -= n; } void wait() const { if (!counter_.load(std::memory_order_relaxed)) return; std::lock_guard&lt;std::mutex&gt; lock(mut_); while (counter_.load(std::memory_order_relaxed)); } bool try_wait() const noexcept { return !counter_.load(std::memory_order_relaxed); } void arrive_and_wait(std::ptrdiff_t const n = 1) { count_down(n); wait(); } }; </code></pre> <p>I also tried to <a href="https://godbolt.org/z/4s7TGW1h6" rel="nofollow noreferrer">test it out</a> and it <em>appears</em> to work just fine.</p>
[]
[ { "body": "<p>The only thing missing that's present in <code>std::latch</code> is the <code>max</code> constant. We can easily add that:</p>\n<pre><code>static constexpr std::ptrdiff_t max() noexcept\n{\n return std::numeric_limits&lt;std::ptrdiff_t&gt;::max();\n}\n</code></pre>\n<p>I think that <code>wait()</code> is flawed: the first thread to get here (taking the mutex) will busy-loop (<code>while</code>). Really, we should wait on a condition variable so that we're not consuming resources while the other threads are still progressing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T18:30:19.270", "Id": "531359", "Score": "0", "body": "Taking what you said into consideration, would [this](https://godbolt.org/z/bK8oq8oaE) be correct way to do it then?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T18:34:15.633", "Id": "531361", "Score": "0", "body": "I _think_ so - perhaps worth posting that as a follow-on question - link back to this one to help give context if you like." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T18:17:27.037", "Id": "269343", "ParentId": "269342", "Score": "1" } } ]
{ "AcceptedAnswerId": "269343", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T18:01:29.817", "Id": "269342", "Score": "1", "Tags": [ "c++", "multithreading", "reinventing-the-wheel", "concurrency", "atomic" ], "Title": "Implementation of a latch" }
269342
<p>This question follows up on <a href="https://codereview.stackexchange.com/questions/269342/implementation-of-a-latch">this question</a>.</p> <p>After turning the <code>while</code>-loop into a <em>conditional wait</em> using <code>std::condition_variable</code>, I would like to know if there are <em>still</em> any flaws/problems with this code which implements the <a href="https://en.cppreference.com/w/cpp/thread/latch" rel="nofollow noreferrer"><code>std::latch</code> class from C++20</a> in C++11:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;condition_variable&gt; #include &lt;cstdint&gt; #include &lt;atomic&gt; #include &lt;mutex&gt; class latch { std::atomic&lt;std::ptrdiff_t&gt; counter_; mutable std::condition_variable cv_; mutable std::mutex mut_; public: explicit latch(std::ptrdiff_t const def = 1) : counter_(def) {} void count_down(std::ptrdiff_t const n = 1) { counter_ -= n; cv_.notify_all(); } void wait() const { if (counter_.load(std::memory_order_relaxed) == 0) return; std::unique_lock&lt;std::mutex&gt; lock(mut_); cv_.wait(lock, [=] { return counter_.load(std::memory_order_relaxed) == 0; }); } bool try_wait() const noexcept { return counter_.load(std::memory_order_relaxed) == 0; } void arrive_and_wait(std::ptrdiff_t const n = 1) { count_down(n); wait(); } static constexpr std::ptrdiff_t max() noexcept { return std::numeric_limits&lt;std::ptrdiff_t&gt;::max(); } }; </code></pre>
[]
[ { "body": "<p>Some minor nitpicks about the constructor:</p>\n<ul>\n<li><p>It should be <code>constexpr</code>.</p>\n</li>\n<li><p>It shouldn't have a default argument.</p>\n</li>\n<li><p>We should check that the argument is valid (not negative, and not greater than <code>max()</code>). The standard says it's undefined behavior otherwise, so we don't technically have to, but it's nicer to <code>assert</code> than to silently carry on.</p>\n</li>\n</ul>\n<hr />\n<p>Another thing:</p>\n<pre><code> counter_ -= n;\n cv_.notify_all();\n</code></pre>\n<p><code>operator-=()</code> here is doing <code>counter.fetch_sub(n, std::memory_order_seq_cst);</code>.</p>\n<p>While this memory order will be safe, I'm not sure it's necessary. I suspect you could get away with <code>std::memory_order_release</code> (note: I'm not very familiar with <code>atomic&lt;&gt;</code>s, so you might want a second opinion).</p>\n<p>In any case, using an explicit <code>fetch_sub</code> call is clearer, and also allows us to add an assertion that the previous value of <code>counter</code> was greater than or equal to <code>n</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T10:28:28.167", "Id": "269354", "ParentId": "269344", "Score": "1" } }, { "body": "<p>The biggest offender here in terms of performance here is</p>\n<pre><code>void count_down(std::ptrdiff_t const n = 1) {\n counter_ -= n;\n cv_.notify_all();\n}\n</code></pre>\n<p>While the <code>std::memory_order_seq_cst</code> is surely too strong here, as <code>std::memory_order_release</code> should be sufficient, this is but a minor issue compared to the <code>cv_.notify_all()</code> that you trigger all the time completely unnecessarily. Think what it does: it awakens all the threads that wait for counter to reach 0 only finding out that the variable is not zero. Awakening of each thread costs thousands of cycles and you do it on all waiting thread on each count down. Then putting it to sleep also costs thousands of cycles. It is a total waste.</p>\n<p>Instead, you should trigger the <code>notify_all()</code> only when the counter reached <code>0</code>.</p>\n<p>Next: memory order bugs with <code>wait()</code> and <code>try_wait()</code>. Think what happens when counter reached <code>0</code>. You've only triggered relaxed memory order instructions. It means that whatever changes occurred on other threads on other variables they aren't necessarily synchronized with the currently running thread. You ought to trigger memory order acquire synchronization with the atomic variable when that happens.\nAlso make sure that it is triggered on the atomic variable regardless of the fact that mutex applies memory synchronization routines. They aren't necessarily the same routines or matching routines considering that you try to utilize efficiency of the <code>std::atomic</code> for lightweight operations. Mixing atomics with mutex is always problematic.</p>\n<p><code>arrive_and_wait</code> routine. You can mildly optimize it for the case when the counter reaches zero on the current thread. Just make sure you apply proper memory synchronization routines - both release and acquire on the atomic.</p>\n<p>It would be much simpler and straightforward if you were to implement all of this with mutex and non-atomic variable it guards. But it would cause <code>count_down</code> and <code>try_wait</code> to be less efficient due to unnecessary calls to acquire atomic memory instructions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T10:42:57.513", "Id": "269387", "ParentId": "269344", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T18:59:01.607", "Id": "269344", "Score": "3", "Tags": [ "c++", "multithreading", "reinventing-the-wheel", "concurrency", "atomic" ], "Title": "C++11 revised `std::latch` implementation" }
269344
<p>I'm learning PowerShell for professional development, but decided to do a bit of a silly project to help learn scripting in more depth, and chose <a href="https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life" rel="nofollow noreferrer">Conway's Game of Life</a>. This is the first PowerShell script I've written besides a small toy that I wrote for an Active Directory assignment previously.</p> <p>An example start:</p> <pre class="lang-powershell prettyprint-override"><code>PS C:\Users\user\PowershellScripts&gt; . .\gol.ps1 PS C:\Users\user\PowershellScripts&gt; Start-Main 15 15 0.3 -------------------------------------------------- █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ █ </code></pre> <p>Primarily, I'd like comments on anything stylistic or off that I'm doing so I don't develop bad habits.</p> <p>Also, I'd like to know how I could make it perform better. Obviously I wasn't expecting speed here, but it's surprisingly slow. I was originally abusing range notation to make the looping a little nicer looking, and doing things like <code>$NNeighbors -in 2..3</code> to do range checks, but ended switching those over to more traditional <code>for</code> loops and comparison checks.</p> <p>Also, I wanted to play around with defining constants using <code>New-Variable</code>, but it ended up being awkward. Whenever I reloaded the script, I'd get an error because a constant with the same name already existed. I ended up using a C-style <code>ifndef</code>-like check at the start, but this feels off.</p> <p>There's no tag for it, but in case it matters, this was written with for Powershell 7.</p> <pre class="lang-powershell prettyprint-override"><code>if ($null -eq $MOORE_NEIGHBORHOOD_DEPTH) { # Since reloading script in a shell will cause errors otherwise Set-Variable -Name MOORE_NEIGHBORHOOD_DEPTH -Value 1 -Option Constant Set-Variable -Name ALIVE_CELL_REPR -Value &quot;█&quot; -Option Constant Set-Variable -Name DEAD_CELL_REPR -Value &quot; &quot; -Option Constant } # The state holds an array of cells to read from, and an array of cells to write to. # Each cell array holds a boolean value indicating if it's alive or not. function New-State { Param($Width, $Height) $Total = $Width * $Height [PSCustomObject]@{ ReadCells = (,$false) * $Total; WriteCells = (,$false) * $Total; Width = $Width; Height = $Height; } } function New-RandomState { Param($Width, $Height, $AliveChance) $State = New-State $Width $Height for ($I = 0; $I -lt $State.ReadCells.Length; $I++) { if ((Get-Random -Minimum 0.0 -Maximum 1.0) -lt $AliveChance) { $State.ReadCells[$I] = $true } } $State } # Swaps the read and write cell arrays so the read array is written to, and the write array is read from. function Switch-Cells { Param($State) $Temp = $State.ReadCells $State.ReadCells = $State.WriteCells $State.WriteCells = $Temp } # A 1D-array is being used to emulate a 2D-array. # This calculates the index into the array to simulate X,Y coordinate access. function Get-Index { Param($State, $X, $Y) $State.Width * $Y + $X } function Confirm-Alive { Param($State, $X, $Y) $State.ReadCells[(Get-Index $State $X $Y)] } # Counts how many neighbors surrounding the given cell are alive. # Depth is how many squares in each direction from the given cell to search (1 cooresponds to a Moore neighborhood) function Find-NeighborCount { Param($State, $X, $Y, $Depth) $XMinBound = [math]::max(0, $X-$Depth) $XMaxBound = [math]::min($X+$Depth, $State.Width-1) $YMinBound = [math]::max(0, $Y-$Depth) $YMaxBound = [math]::min($Y+$Depth, $State.Height-1) $Count = 0 for ($FY = $YMinBound; $FY -le $YMaxBound; $FY++) { for ($FX = $XMinBound; $FX -le $XMaxBound; $FX++) { if ((-not ($X -eq $FX -and $Y -eq $FY)) -and (Confirm-Alive $State $FX $FY)) { $Count++ } } } $Count } # Updates the given cell according to how many of its neighbors are found to be alive. function Update-Cell { Param($State, $X, $Y) $CurrentlyAlive = Confirm-Alive $State $X $Y $NNeighbors = Find-NeighborCount $State $X $Y $MOORE_NEIGHBORHOOD_DEPTH $NewState = $CurrentlyAlive -and (2 -le $NNeighbors -and $NNeighbors -le 3) -or ((-not $CurrentlyAlive) -and $NNeighbors -eq 3) $State.WriteCells[(Get-Index $State $X $Y)] = $NewState } function Update-Cells { Param($State) for ($Y = 0; $Y -lt $State.Height; $Y++) { for ($X = 0; $X -lt $State.Width; $X++) { Update-Cell $State $X $Y } } } # Writes the state of the read cells to the screen. function Show-State { Param($State) Write-Host (&quot;-&quot; * 50) for ($Y = 0; $Y -lt $State.Height; $Y++) { for ($X = 0; $X -lt $State.Width; $X++) { Write-Host &quot;$($State.ReadCells[(Get-Index $State $X $Y)] ? $ALIVE_CELL_REPR : $DEAD_CELL_REPR) &quot; -NoNewline } Write-Host &quot;&quot; } } function Write-DebugGlider { Param($State) function cell { Param($X, $Y) $State.WriteCells[(Get-Index $State $X $Y)] = $true } cell 1 0 cell 2 1 cell 0 2 cell 1 2 cell 2 2 } function Start-Main { Param($Width, $Height, $AlivePercChance) $State = New-RandomState $Width $Height $AlivePercChance for ($N = 0; $N -lt 100; $N++) { Update-Cells $State Switch-Cells $State Show-State $State #Start-Sleep -Milliseconds 250 } } </code></pre>
[]
[ { "body": "<p>This is a fun project.\nHere are a few things I noticed:</p>\n<ol>\n<li><code>$AlivePercChance</code> implies that it's a percentage (30%) rather than a fraction (0.3). You might consider renaming it to <code>$AliveChance</code></li>\n<li>Why did you flatten the 2D array to 1D? It adds substantial overhead (2 extra function calls * $Width * $Height per screen write, way more for checking neighbors) and reduces readability compared to <code>$State.ReadCells[$x,$y]</code>.</li>\n<li>The program works in Powershell 5 except for the ternary operator on line 102, which you can change to:\n<code>Write-Host &quot;$(If($State.ReadCells[(Get-Index $State $X $Y)]){$ALIVE_CELL_REPR}Else{$DEAD_CELL_REPR}) &quot; -NoNewline</code></li>\n<li>To make it behave more like the Life implementations I've seen, you can clear the screen (<code>cls</code>) or move the cursor to the top of the console (<code>[Console]::CursorTop = 0</code>) between writes. The cursor method is faster.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T23:02:40.287", "Id": "534636", "Score": "0", "body": "Thank you. Honestly for 2., at the time, I couldn't figure out how to create a 2D array. Every attempt seemed to automatically flatten itself to 1D when I checked it, so I figured I'd just roll with it. And thanks for 4. I'll check that out." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-12-03T21:56:01.660", "Id": "270653", "ParentId": "269347", "Score": "2" } } ]
{ "AcceptedAnswerId": "270653", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T22:23:17.897", "Id": "269347", "Score": "3", "Tags": [ "beginner", "powershell", "game-of-life" ], "Title": "Conway's Game of Life in Powershell" }
269347
<p>I started to write a terminal based text RPG in python. Its mostly bug free now but I really want to know how I could improve my code and how to implement things better. I know it's a lot of code so I really want to thank you, if you're patient enough to review it.</p> <p>I uploaded the code to github. You only need classes.py and main.py to run it.</p> <p><a href="https://github.com/attax420/TextRPG" rel="nofollow noreferrer">https://github.com/attax420/TextRPG</a></p> <p>Because i have to add at least 3 lines of code to post something, here is the classes.py:</p> <pre><code>from random import choice from termcolor import colored from time import sleep import os from platform import system if system().lower() == 'windows': os.system('color') if system().lower() == 'linux': import readline # ######### MAP ######### # class GameMap: def __init__(self): self.map = [] self.map_x = 15 self.map_y = 15 self.player_pos_x = int(choice(range(self.map_x -1))) self.player_pos_y = int(choice(range(self.map_y -1))) self.boss_x = int(choice(range(self.map_x -1))) self.boss_y = int(choice(range(self.map_y -1))) for i in range(self.map_y): self.map.append([]) for j in range(self.map_x): self.map[i].append(-1) def position_update(self): run = True while run == True: if self.boss_x != self.player_pos_x or self.boss_y != self.player_pos_y: self.map[self.player_pos_y][self.player_pos_x] = colored(' ', 'green', 'on_white') run = False else: self.player_pos_x = int(choice(range(self.map_x -1))) self.player_pos_y = int(choice(range(self.map_y -1))) continue def print_map(self): for i in range(self.map_y): for j in range(self.map_x): print(self.map[i][j], ' | ', end=' ') print() print() def randomize_map(self): for i in range(self.map_y): for j in range(self.map_x): if self.map[j][i] == -1: self.map[j][i] = choice([' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', colored('E', 'green'), colored('E', 'yellow'), colored('E', 'red'), colored('+', 'red'), colored('e', 'yellow')]) self.map[self.boss_y][self.boss_x] = colored('B', 'magenta') def check_field(self): if self.map[self.player_pos_y][self.player_pos_x] == colored('X', 'blue'): return 'visited' if self.map[self.player_pos_y][self.player_pos_x] == colored('+', 'red'): return 'heal' if self.map[self.player_pos_y][self.player_pos_x] == ' ': return 'empty' if self.map[self.player_pos_y][self.player_pos_x] == colored('E', 'green'): return 'goblin' if self.map[self.player_pos_y][self.player_pos_x] == colored('e', 'yellow'): return 'dwarf' if self.map[self.player_pos_y][self.player_pos_x] == colored('E', 'yellow'): return 'troll' if self.map[self.player_pos_y][self.player_pos_x] == colored('E', 'red'): return 'ork' if self.map[self.player_pos_y][self.player_pos_x] == colored('B', 'magenta'): return 'dragon' def move_north(self): if self.player_pos_y != 0: self.map[int(self.player_pos_y)][int(self.player_pos_x)] = colored('X', 'blue') self.player_pos_y -= 1 return True else: return False def move_south(self): if self.player_pos_y != self.map_y-1: self.map[int(self.player_pos_y)][int(self.player_pos_x)] = colored('X', 'blue') self.player_pos_y += 1 return True else: return False def move_west(self): if self.player_pos_x != 0: self.map[int(self.player_pos_y)][int(self.player_pos_x)] = colored('X', 'blue') self.player_pos_x -= 1 return True else: return False def move_east(self): if self.player_pos_x != self.map_y-1: self.map[int(self.player_pos_y)][int(self.player_pos_x)] = colored('X', 'blue') self.player_pos_x += 1 return True else: return False # end MAP # enemies = ['Goblin','Troll','Ork','Dwarf'] # ######### CHARACTERS ######### # class Character(GameMap): def __init__(self): GameMap.__init__(self) self.max_hp = None self.hp = None self.mana = None self.attack_damage = None self.name = None self.spells = None self.inventory = None self.lvl = None self.xp = None self.action = None self.active_effect = None def attack(self, attacker, target): self.action = 'attack' if target.hp &gt; 0 and target.action != 'defend': target.hp -= int(attacker.attack_damage) if target.hp &gt; 0 and target.action == 'defend': target.hp -= int(attacker.attack_damage)/2 def defend(self): self.action = 'defend' class Player(Character, GameMap): def __init__(self): Character.__init__(self) self.name = 'Player' self.lvl = 1 self.attack_damage = 15 self.max_hp = 100 self.max_mp = 50 self.hp = self.max_hp self.mp = self.max_mp self.xp = 0 self.spells = ['fireball'] self.inventory = [] self.weapon = None self.gear = {'Head': 'none', 'Torso': 'none', 'Legs': 'none', 'Feet': 'none'} self.dmg_bonus = 0 def update_dmg(self): self.attack_damage = self.attack_damage + self.dmg_bonus def equip(self, item): if item in weaponlist and item in self.inventory and self.weapon == None: self.weapon = item self.inventory.remove(item) self.dmg_bonus = item.dmg_bonus self.update_dmg() return True return False def unequip(self, item): if self.weapon != None and item == self.weapon: self.dmg_bonus = 0 self.inventory.append(item) self.weapon = None self.update_dmg() return True else: return False def showspells(self): return self.spells def showxp(self): return self.xp, self.lvl def use_item(self, item): if not item.interactive: return False, 'not usable' if item not in self.inventory: return False, 'not available' if item in self.inventory: item.use(self) for i, v in enumerate(self.inventory): if v == item: self.inventory.pop(i) return True, 'success' def lvl_up(self): lvlup = False if self.lvl == 8: self.xp = 0 if self.xp &gt;= 100 and self.lvl &lt; 2: self.lvl = 2 self.max_hp += 20 self.max_mp += 30 self.mp = self.max_mp self.hp = self.max_hp if self.xp &gt;= 100: self.xp -= 100 else: self.xp = 0 self.attack_damage = self.attack_damage * 1.1 lvlup = True if self.xp &gt;= 200 and self.lvl &lt; 3: self.lvl = 3 self.max_hp += 40 self.hp = self.max_hp self.max_mp += 60 self.mp = self.max_mp if self.xp &gt;= 200: self.xp -= 200 else: self.xp = 0 self.attack_damage = self.attack_damage * 1.3 lvlup = True if self.xp &gt;= 400 and self.lvl &lt; 4: self.lvl = 4 self.max_hp += 60 self.max_mp += 80 self.mp = self.max_mp self.hp = self.max_hp if self.xp &gt;= 400: self.xp -= 400 else: self.xp = 0 self.attack_damage = self.attack_damage * 1.6 lvlup = True if self.xp &gt;= 700 and self.lvl &lt; 5: self.lvl = 5 self.max_hp += 100 self.hp = self.max_hp self.max_mp += 150 self.mp = self.max_mp if self.xp &gt;= 800: self.xp -= 800 else: self.xp = 0 self.attack_damage = self.attack_damage * 2 lvlup = True if self.xp &gt;= 1300 and self.lvl &lt; 6: self.lvl = 6 self.max_hp += 130 self.hp = self.max_hp self.max_mp += 200 self.mp = self.max_mp if self.xp &gt;= 1600: self.xp -= 1600 else: self.xp = 0 self.attack_damage = self.attack_damage * 2.5 lvlup = True if self.xp &gt;= 2000 and self.lvl &lt; 7: self.lvl = 7 self.max_hp += 180 self.max_mp += 250 self.mp = self.max_mp self.hp = self.max_hp if self.xp &gt;= 2400: self.xp -= 2400 else: self.xp = 0 self.attack_damage = self.attack_damage * 2.7 lvlup = True if self.xp &gt;= 2800 and self.lvl &lt; 8: self.lvl = 8 self.max_hp += 200 self.hp = self.max_hp self.max_mp += 300 self.mp = self.max_mp self.xp = 0 self.attack_damage = self.attack_damage * 3 + self.dmg_bonus lvlup = True if lvlup: if self.lvl == 8: return('LVL up!!! You are now on LVL 8 which is the maximum LVL!') else: return ('LVL up!!! You are now LVL ' + str(self.lvl) + '!') else: return False @staticmethod def suicide(): sleep(2) exit('exit by suicide...') @staticmethod def death(): sleep(2) exit('exit by death...') @staticmethod def run_away(e): mode_choices = ('explore', 'fight') mode = choice(mode_choices) if mode == 'fight': return False if mode == 'explore': return True class Enemy(Character): def __init__(self): Character.__init__(self) self.action = None self.xp_bonus = 0 def showhp(self): return self.name, self.hp class EnemyGoblin(Enemy): def __init__(self, p): Enemy.__init__(self) self.xp_bonus = 10 self.name = 'Goblin' self.hp = int(p.max_hp)/2 self.hp = self.hp.__round__(2) self.attack_damage = int(p.hp)/10 choices = [healthpotion,manapotion,xppotion] self.inventory = [choice(choices)] class EnemyDwarf(Enemy): def __init__(self, p): Enemy.__init__(self) self.xp_bonus = 35 self.name = 'Dwarf' self.hp = int(p.max_hp)/1.5 self.hp = self.hp.__round__(2) self.attack_damage = int(p.hp)/9 choices = (healthpotion, manapotion, xppotion, healthpotion, manapotion, xppotion, healthpotion, manapotion, xppotion, sword_bronze) self.inventory = [choice(choices)] class EnemyTroll(Enemy): def __init__(self, p): Enemy.__init__(self) self.xp_bonus = 25 self.name = 'Troll' self.hp = int(p.max_hp)/1.5 self.hp = self.hp.__round__(2) self.attack_damage = int(p.hp)/8 choices = (healthpotion, manapotion, xppotion, healthpotion, manapotion, xppotion, healthpotion, manapotion, xppotion, sword_bronze) self.inventory = [choice(choices)] class EnemyOrk(Enemy): def __init__(self, p): Enemy.__init__(self) self.xp_bonus = 50 self.name = 'Ork' self.hp = int(p.max_hp)/1 self.hp = self.hp.__round__(2) self.attack_damage = int(p.hp)/5 choices = (healthpotion, manapotion, xppotion, healthpotion, manapotion, xppotion, sword_bronze, sword_bronze, sword_bronze, sword_steel) self.inventory = [choice(choices)] class EnemyOrkGeneral(Enemy): def __init__(self, p): Enemy.__init__(self) self.xp_bonus = 75 self.name = 'Ork General' self.hp = int(p.max_hp)*1.3 self.hp = self.hp.__round__(2) self.attack_damage = int(p.hp)/3 choices = (healthpotion, manapotion, xppotion, healthpotion, manapotion, xppotion, sword_bronze, sword_bronze, sword_steel, sword_steel) self.inventory = [choice(choices)] class EnemyDragon(Enemy): def __init__(self, p): Enemy.__init__(self) self.mp = 999999 self.xp_bonus = 800 self.name = 'Dragon' self.hp = 2000 self.inventory = [sword_diamond, manapotion, manapotion, healthpotion] self.attack_damage = 30 self.spells = ['fireball'] # end CHARACTERS # # ######### ITEMS ######### # class Item: def __init__(self): self.name = None self.worth = 0 self.interactive = True self.can_use_in_fight = True self.consumable = True self.weight = 0 class Potion(Item): def __init__(self): Item.__init__(self) self.weight = 0.5 class PotionHP(Potion): def __init__(self): Potion.__init__(self) self.name = 'HP Potion' self.hp_bonus = 50 def use(self, p): p.hp = p.hp + self.hp_bonus if p.hp &gt;= p.max_hp: p.hp = p.max_hp return self.hp_bonus class PotionXP(Potion): def __init__(self): Potion.__init__(self) self.name = 'XP Potion' self.xp_bonus = 150 def use(self, p): p.xp = p.xp + self.xp_bonus p.lvl_up return self.xp_bonus class PotionMP(Potion): def __init__(self): Potion.__init__(self) self.name = 'MP Potion' self.mp_bonus = 50 def use(self, p): p.mp = p.mp + self.mp_bonus if p.mp &gt;= p.max_mp: p.mp = p.max_mp return self.mp_bonus class Weapon(Item): dmg_bonus = None pass class WeaponBronzeSword(Weapon): def __init__(self): Weapon.__init__(self) self.name = 'Bronze Sword' self.dmg_bonus = 10 class WeaponSteelSword(): def __init__(self): Weapon.__init__(self) self.name = 'Steel Sword' self.dmg_bonus = 40 class WeaponDiamondSword(): def __init__(self): Weapon.__init__(self) self.name = 'Diamond Sword' self.dmg_bonus = 160 class Armor(Item): pass # end ITEMS # # ######### SPELLS ######### # class Spell(): def __init__(self): self.name = None self.effect = None self.dmg = None self.mana_usage = None self.effect_dmg = None def cast(self, attacker, target): target.hp -= self.dmg attacker.mp -= self.mana_usage target.active_effect = self.effect return self.dmg, self.mana_usage, self.effect class SpellFireball(Spell): def __init__(self): Spell.__init__(self) self.name = 'Fireball' self.dmg = p.lvl*50 self.mana_usage = p.lvl*20/p.lvl self.effect_dmg = 5 self.effect = 'fire' class SpellBlizzard(Spell): def __init__(self): Spell.__init__(self) self.name = 'Blizzard' self.dmg = p.lvl*50 self.mana_usage = p.lvl*30/p.lvl self.effect_dmg = 0 self.effect = 'ice' # end SPELLS # # ######### Objects ######### # p = Player() healthpotion = PotionHP() manapotion = PotionMP() xppotion = PotionXP() spellfireball = SpellFireball() spellblizzard = SpellBlizzard() sword_bronze = WeaponBronzeSword() sword_steel = WeaponSteelSword() sword_diamond = WeaponDiamondSword() # ######### ITEMLISTS + SPELLLIST ######### # weaponlist = [sword_bronze, sword_steel, sword_diamond] potionlist = [healthpotion, manapotion, xppotion] spelllist = [spellfireball, spellblizzard] # end ITEMLISTS + SPELLLIST # # end OBJECTS # </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T00:05:22.123", "Id": "531367", "Score": "4", "body": "Please also include main.py verbatim in this post." } ]
[ { "body": "<p>First of all, How do expect someone to read your code? Neither type hints nor doc-strings.</p>\n<h1>Review</h1>\n<ul>\n<li>What would a <code>Player</code> or a <code>Enemy</code> inherit from a <code>GameMap</code>?</li>\n<li>I would prefer to implement a <code>.attack_player(player: Player)</code> method as it is more flexible.</li>\n<li>In <code>Player.lvl_up()</code>, you should try to form a formula.</li>\n<li>We can use <code>dicts</code> to simplify stuff For example -</li>\n</ul>\n<pre><code>enemy_types = {\n 'Goblin': {\n 'name': 'Goblin',\n 'xp_bonus': 10,\n 'hp': ...\n },\n ...\n}\n\nclass Enemy:\n def __init__(self, type: str) -&gt; None:\n self.__dict__.update(enemy_types[type])\n\n def attack_player(self, player: Player) -&gt; None:\n '''Attack the given player, returns None.'''\n player.hp -= 10\n</code></pre>\n<pre><code>def check_field():\n field_types = {\n colored('X', 'blue'): 'visited',\n ...\n }\n return field_types[self.map[self.player_pos_y][self.player_pos_x]]\n</code></pre>\n<ul>\n<li><p>We can create a list of pre-build maps and chose a random one from it, it will allow to have more appropriate maps.</p>\n</li>\n<li><p>Assume I input <code>'go north'</code>, would you want to check it with all the commands? It is only one of them. In such cases, we use an <code>elif</code>.</p>\n</li>\n<li><p>Do not do unnecessary conversions, like here - <code>int(choice(range(self.map_y -1)))</code></p>\n</li>\n<li><p>What is this <code>p</code> everywhere? Give it a more readable name such as <code>player</code>.</p>\n</li>\n</ul>\n<hr />\n<p><strong>In general, you have completely overlooked readability and performance.\nAll the best in improving your code!</strong></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T06:47:03.140", "Id": "269350", "ParentId": "269348", "Score": "0" } }, { "body": "<p>First, congratulations on writing a game that runs, and hangs together without crashing! (It's harder than you might think.)</p>\n<p>Here are some ideas on how to make it better:</p>\n<h1>Packages</h1>\n<p>If you're going to use external packages, provide some standard mechanism to install them. The most obvious would be a <code>requirements.txt</code> file generated by <code>pip</code>. If not that, you could try to be hipster and use one of the (many, many) competitors (Google is not your friend, here. Because there are so damn many...)</p>\n<h1>Classes</h1>\n<p>I don't think you've quite mastered classes, yet. You've done a lot of things mostly right, but you've done a bunch of things wrong, as well. So this is an area where you need to focus your effort.</p>\n<h2>Inheritance</h2>\n<p>The problem with how OOP and classes get taught is that most courses and most instructors focus on inheritance as a <em>characteristic</em> of OO, and teach the &quot;Java model&quot; of big tall hierarchies.</p>\n<p>The reality of modern OO thought is that inheritance is <strong>not</strong> a characteristic, but rather it is a <em>tool.</em> That is, you should default to not using inheritance until and unless you make an explicit, conscious decision that inheritance provides some specific benefit to you in a particular instance.</p>\n<p>There are a variety of benefits that you might get from inheritance. Sometimes, the benefits you get will depend on the implementation language. (For example, Python generally doesn't <em>care</em> about memory layout. So while &quot;memory layout&quot; might make sense as a benefit in Go or C++ or D, it's kind of &quot;meh&quot; in Python.)</p>\n<p>For your code, the obvious benefits are virtual behavior and common member names.</p>\n<p>That means providing a <code>.attack()</code> method that does different things for different classes. And it means providing a common attribute interface, like <code>.current_hp</code> and <code>.damage</code> attributes.</p>\n<p>You have a class <code>GameMap</code>. That's fine. The orthography is good. Some of the fields make sense (more below). <code>GameMap</code> seems like a good, solid class.</p>\n<p>Then you have <code>class Character(GameMap)</code>. Why do you think that a character derives from a game map? In what way does an IS-A relationship work here?</p>\n<p>Then you have <code>class Player(Character, GameMap)</code>. Why would you implement multiple-inheritance, especially since <code>Character</code> already inherits from <code>GameMap</code>?</p>\n<p>As far as I can see, this entire subtree of your class hierarchy is wrong. I don't see much reason for any class to inherit from <code>GameMap</code>.</p>\n<p>You have a <code>class Enemy(Character)</code> that makes just a little bit of sense. You add one method, <code>.showhp()</code>, and a <code>.xp_bonus</code> attribute. Your assignment to <code>self.action</code> appears redundant.</p>\n<p>You have classes for each enemy type (Goblin, Dwarf, etc.). This appears to be a sensible basic approach.</p>\n<h2>Encapsulation</h2>\n<p>Encapsulation is the key benefit to OO programming. Even if you are not using inheritance, or virtual dispatch, or anything else, being able to bundle up a bunch of related data and functions that will operate on that data is a big win.</p>\n<p>Whenever you write code that &quot;checks&quot; the type of an object, you are violating encapsulation. Don't do that. Code like</p>\n<pre><code>if e.name == 'Dragon':\n</code></pre>\n<p>is a total lose. You're breaking encapsulation and making your code harder to understand and harder to maintain.</p>\n<p>What you want to do is describe the behavior in abstract terms, and either write a separate driver function to handle it, or write a separate virtual method to handle it.</p>\n<p>You might write code like this to implement a special driver:</p>\n<pre><code>if enemy.is_boss:\n boss_fight()\nelse:\n basic_fight()\n</code></pre>\n<p>Or you might keep a single &quot;fight&quot; driver, and write code like:</p>\n<pre><code>if mode == 'fight':\n fight_intro()\n\n while mode == 'fight':\n show_fight_stats()\n enemy.maybe_taunts()\n enemy.turn()\n player.turn()\n enemy.update()\n player.update()\n</code></pre>\n<p>The point, though, is that you should strive to push everything down into the appropriate &quot;capsule.&quot;</p>\n<h2>Tell, don't Ask</h2>\n<p>This is one of those OO aphorisms that gets thrown around a lot. And you need to keep it in your head pretty much all the time when you're thinking about classes.</p>\n<p>Here's an example:</p>\n<pre><code># ######### ENEMY DEATH ######### # \nif e.hp &lt;= 0:\n print('You killed the '+str(e.name)+' and got '+str(e.xp_bonus)+'XP!')\n</code></pre>\n<p>This is your fight driver <em>asking</em> the enemy how many hit points it has, then making a decision about whether the enemy is dead, then <em>asking</em> the enemy for its name and EXP.</p>\n<p>What should you do differently? <strong>Tell,</strong> don't <em>ask!</em></p>\n<pre><code>if e.is_dead():\n e.award_exp(player)\n</code></pre>\n<p>Of course, it's also possible that the check-for-dead-and-award-exp could be moved into the <code>player.attack(enemy)</code> method. That's up to you.</p>\n<p>The point is that it is <strong>not</strong> the business of the fight driver function to manage either the player or the enemy. Tell those classes what to do, and let them do it for you!</p>\n<h1>Control Flow</h1>\n<p>There's a lot of code like this:</p>\n<pre><code>if condition1:\n do_stuff1()\nif condition2:\n do_stuff2()\n...\n</code></pre>\n<p>In many cases, those <code>if</code> statements are mutually exclusive: when <code>condition1</code> is true, <code>condition2</code> cannot possibly be true.</p>\n<p>You should either use <code>if ... elif ... else</code> statements, or use a dictionary of string-&gt;function mappings to dispatch to the appropriate function.</p>\n<h1>Function level of detail</h1>\n<p>Try to keep your functions at a single level of detail. If you are writing a function that dispatches to other functions, then have <em>all</em> the cases dispatch to another function. Don't mix and match dispatch to functions with code in-line.</p>\n<p>Also, try to differentiate between &quot;control flow&quot; functions and &quot;procedure&quot; functions. Instead of a &quot;giant wall of code&quot; with control flow and long blocks of instructions, put your control flow into a single function and have it dispatch to procedures for each control flow case.</p>\n<h1>Unify your code and data</h1>\n<p>Part of OO is encapsulating code and data together. This can have unexpected implications.</p>\n<p>You have a function called <code>randomize_map</code> (a method of <code>GameMap</code>) that sets the individual map cells to empty, or strings like <code>colored('E', 'green')</code>.</p>\n<p>That's a magic number. (Magic string, actually, but still...)</p>\n<p>There's another method, <code>check_field</code>, that maps those magic strings to class names:</p>\n<pre><code>if self.map[...][...] == color('E', 'green'):\n return 'goblin'\n</code></pre>\n<p>It makes a lot more sense to me to move the class into the discussion. Instead of writing:</p>\n<pre><code>self.map[j][i] = choice([\n ' ', ' ', ' ', ' ', ' ', ' ', ' ', \n ' ', ' ', ' ', colored('E', 'green'), \n colored('E', 'yellow'), colored('E', 'red'),\n colored('+', 'red'), colored('e', 'yellow')])\n</code></pre>\n<p>Why not write:</p>\n<pre><code>FIELD_LIST = ([None] * 10\n + [EnemyGoblin, EnemyTroll, EnemyOrk, \n PotionHP, EnemyDwarf])\n</code></pre>\n<p>And then:</p>\n<pre><code>occupant = choice(FIELD_LIST)\nself.map[j][i] = ' ' if occupant is None else occupant.display_string\n</code></pre>\n<p>This has the effect of moving the class-specific data (the colored display string) into the class and out of the <code>GameMap</code>.</p>\n<h2>First-class objects</h2>\n<p>In Python, classes, functions, and instances of classes are all <em>first class objects</em>. That means you can pass them around and use them in your code.</p>\n<p>Instead of returning a string like:</p>\n<pre><code>return 'goblin'\n</code></pre>\n<p>You could do:</p>\n<pre><code>return EnemyGoblin.name\n</code></pre>\n<p>But you could also just do:</p>\n<pre><code>return EnemyGoblin\n</code></pre>\n<p>(Returning the class directly, instead of a string with a description of the class in it.)</p>\n<h1>Game Play</h1>\n<p>I've played Zork, so I hate your game. I don't want to type &quot;go north&quot;. I want to type &quot;n&quot;. I certainly don't want to type &quot;cast spell&quot; and then &quot;fireball&quot;. I want to type &quot;cast fireball&quot; or even just &quot;fireball&quot; or &quot;fb&quot;.</p>\n<p>You really need to work on adding some abbreviations support to the game. You might just build a map of common abbreviations and expand them to the full commands -- that's a fairly easy way to &quot;bolt on&quot; this kind of functionality.</p>\n<p>But you could also write a full-on command parser. It depends on why you are writing the game. If it's for a class, you might be able to add the parser in a later part of the course, or as an extra credit assignment.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T20:58:29.987", "Id": "531606", "Score": "0", "body": "First of all: Thank you very much for your time and patience! \nI started this project to actually have a use case for the stuff I learn in different python video courses. I just started with programming 2-3 months ago and really appreciate your in depth analysis of my code and the errors I made. It will certainly take a few days until my slow brain processed everything you wrote, but i will do my best to improve my code based on your recommendations. I really thought I know how classes work, but you showed me that I certainly need to learn more about them." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T16:58:34.867", "Id": "269431", "ParentId": "269348", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-24T23:19:29.190", "Id": "269348", "Score": "1", "Tags": [ "python", "python-3.x" ], "Title": "TextRPG written in python" }
269348
<p>I would like a little help with the implementation of my SDL2 engine. It's actually not a real engine nor does it strive to be but I don't have a better word to describe it.</p> <p>The purpose of this project is to serve as a base for other things to be built on, like a visualization of fractals for example, so i would like to make it as optimal as possible.</p> <p>For now it just creates a window, renderer and handles basic input handling. Before I move on with it I would like to iron out any kinks there might be so any improvement suggestion would come in handy, especially when it comes to performance and future upgradability.</p> <p>engine.h</p> <pre><code>#ifndef ENGINE_H #define ENGINE_H #pragma once #include &lt;SDL2/SDL.h&gt; #include &quot;window.hpp&quot; #include &quot;renderer.hpp&quot; class Engine { private: bool running; public: Window window; Renderer renderer; Engine(); ~Engine(); //Handles input void handleInput(); //draws things onto the screen void draw(); bool isRunning(); }; #endif </code></pre> <p>engine.cpp</p> <pre><code>#include &quot;engine.h&quot; Engine::Engine(): window( 640, 480 ), renderer( window.getWindow() ) { if( window.getWindow() == NULL ) { printf(&quot;Window could not be created. \n&quot; ); running = false; } else { if( renderer.getRenderer() == NULL ) { printf(&quot;Renderer could not be created. \n&quot; ); running = false; } running = true; printf(&quot;Engine has been started successfuly \n&quot; ); } } Engine::~Engine() { running = false; window.close(); renderer.close(); } void Engine::handleInput() { SDL_Event event; while( SDL_PollEvent( &amp;event ) != 0 ) { if( event.type == SDL_QUIT ) { window.close(); } } } void Engine::draw() { SDL_RenderClear( renderer.getRenderer() ); SDL_RenderPresent( renderer.getRenderer() ); } bool Engine::isRunning() { return window.isOpen() &amp;&amp; renderer.isCreated() &amp;&amp; running; } </code></pre> <p>window.hpp</p> <pre><code>#ifndef WIDNOW_H #define WINDOW_H #pragma once #include &lt;SDL2/SDL.h&gt; class Window { private: const int SCREEN_WIDTH = 0; const int SCREEN_HEIGHT = 0; bool open = false; //Window we'll render to SDL_Window* mWindow = NULL; public: Window(); //Consturctor to initialize window Window( int SCREEN_WIDTH, int SCREEN_HEIGHT ); ~Window(); void close(); bool isOpen(); SDL_Window* getWindow(); }; #endif </code></pre> <p>window.cpp</p> <pre><code>#include &quot;window.hpp&quot; Window::Window() { } //Initialize SDL and create a window Window::Window( int SCREEN_HEIGHT, int SCREEN_WIDTH ): SCREEN_WIDTH(SCREEN_WIDTH), SCREEN_HEIGHT( SCREEN_HEIGHT) { //If SDL video was not initialize if( SDL_Init( SDL_INIT_VIDEO) &lt; 0 ) { printf( &quot;SDL could not initialize! SDL error: %s\n&quot;, SDL_GetError() ); open = false; } else { //Create window mWindow = SDL_CreateWindow( &quot;Window class&quot;, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN ); //If the window was not created if( mWindow == NULL ) { printf( &quot;Could not create window. SDL error: %s\n&quot;, SDL_GetError() ); open = false; } //Set the open flag to true after the operation completed successfuly open = true; printf(&quot;Window was created successfuly.\n&quot; ); } } void Window::close() { open = false; SDL_DestroyWindow( mWindow ); mWindow = NULL; SDL_Quit(); } Window::~Window() { printf(&quot;Window destructor was called \n&quot; ); close(); } bool Window::isOpen() { return open; } SDL_Window* Window::getWindow() { return mWindow; } </code></pre> <p>renderer.hpp</p> <pre><code>#ifndef RENDERER_H #define RENDERER_H #pragma once #include &quot;window.hpp&quot; class Renderer : public Window { private: bool created = false; SDL_Renderer* mRenderer = NULL; public: Renderer(); Renderer( SDL_Window* window ); ~Renderer(); void close(); bool isCreated(); SDL_Renderer* getRenderer(); }; #endif </code></pre> <p>renderer.cpp</p> <pre><code>#include &quot;renderer.hpp&quot; Renderer::Renderer() { } Renderer::Renderer( SDL_Window* window ) { //create the renderer mRenderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED ); //if the rendere was not created if( mRenderer == NULL ) { printf(&quot;Renderer could not be created. SDL error: %s\n&quot;, SDL_GetError() ); created = false; } else { //Set the render draw color to white SDL_SetRenderDrawColor( mRenderer, 0xFF, 0xFF, 0xFF, 0xFF ); created = true; printf(&quot;Renderer was created successfuly \n&quot; ); } } Renderer::~Renderer() { printf(&quot;Renderer desturctor was called \n&quot; ); close(); } bool Renderer::isCreated() { return created; } void Renderer::close() { SDL_DestroyRenderer( mRenderer ); mRenderer = NULL; } SDL_Renderer* Renderer::getRenderer() { return mRenderer; } </code></pre> <p>main.cpp</p> <pre><code>#include &quot;engine.h&quot; int main( int argc, char* argv[] ) { Engine engine; while( engine.isRunning() ) { engine.handleInput(); engine.draw(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T11:01:14.830", "Id": "531385", "Score": "2", "body": "Welcome to Code Review! I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Please check that I haven't misrepresented your code, and correct it if I have." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T11:02:15.163", "Id": "531386", "Score": "2", "body": "Note that general \"best practices\" questions are explicitly off-topic here, so the title edit is important to prevent your question being closed!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T15:09:15.793", "Id": "531501", "Score": "0", "body": "Have you tested this engine? Does it currently produce satisfactory output?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T15:22:33.857", "Id": "531504", "Score": "0", "body": "@Mast\n♦ The engine does create a window and renderer and handles exiting the program. I have made some improvements with the help of suggestions from here. There is also a bug where multiple instances of the window are created when inheriting from the engine class. I fixed it by implementing the window and renderer as singletons." } ]
[ { "body": "<p>Don't use the C macro <code>NULL</code>. C++ has a real null pointer named <code>nullptr</code>. Meanwhile, don't explicitly compare against <code>nullptr</code>, but rather use the convert-to-boolean truth value of the pointer (this is important when you use smart pointers, and is idiomatic for any pointer type). That is, write:</p>\n<p><code>if(p) // NOT if(p!=nullptr)</code><br />\n<code>if(!q) // NOT if(q==nullptr)</code></p>\n<p><code>ENGINE_H</code> is not unique enough to not clash with anything else. Personally I leave off the guards and use <code>#pragma once</code> and would use an automated program to put in guards <em>if</em> I ever found a platform that needed them. Use a GUID-based identifier if you must have a guard.</p>\n<p>You're using <code>printf</code> for logging, but never included the proper header for that. Consider using a standard error for such logging rather than standard output, and don't use <code>printf</code> because at some point you'll want to show class types and strings in particular. I really don't want to use a function that will compile without complaint but crash if it's passed an argument that it can't handle, <em>especially</em> on an error pathway that doesn't get tested in a normal run.</p>\n<hr />\n<pre><code>Renderer::Renderer()\n{\n\n}\n</code></pre>\n<p>Don't explicitly write empty-bodied constructors or destructors! Here, put\n<code>Renderer() = default;</code> in the class definition.</p>\n<hr />\n<pre><code>bool Renderer::isCreated()\n{\n return created;\n}\n</code></pre>\n<p>Put this inline in the class definition, and <strong>declare the function as <code>const</code></strong>.</p>\n<p>Same with <code>isOpen</code> and other <em>accessors</em>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T10:00:02.043", "Id": "531480", "Score": "0", "body": "Thank you for the feedback. By the conver-to-bool value do you mean explicitly casting the `nullptr` to `bool`, because that throws an error on my machine, or is that the same as something like `return mWindow != nullptr`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T15:22:09.890", "Id": "531503", "Score": "1", "body": "@AsmirZukić I clarified with an example. No, do not explicitly cast anything." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T13:55:18.117", "Id": "269360", "ParentId": "269355", "Score": "6" } }, { "body": "<h2>Engine:</h2>\n<pre><code>Engine::Engine(): window( 640, 480 ), renderer( window.getWindow() )\n</code></pre>\n<p>We should probably set the <code>running</code> variable to <code>false</code> here to prevent accidents. (Or we could do so in the member variable declaration like the other classes do).</p>\n<pre><code>if( window.getWindow() == NULL )\n{\n printf(&quot;Window could not be created. \\n&quot; );\n running = false;\n}\n</code></pre>\n<p>I think it's reasonable to throw an exception if something so fundamental goes wrong. It's simpler to avoid the complexity of trying to carry on running the program in an abnormal state.</p>\n<p>Note that this specific check would then be unnecessary. We could throw the exception from the <code>Window</code> constructor, and have it propagate upwards. We could do the same in the <code>Renderer</code> constructor.</p>\n<hr />\n<p>Consider adding an <code>Engine::run()</code> function to hold the main loop, so that <code>main</code> can just call <code>engine.run()</code>. But the best way of doing things rather depends on how you add the functionality for your visualization, and how it interacts with <code>Engine</code>. (i.e. will you put that code inside <code>Engine</code>, or will you pass the <code>Engine</code> to that code?)</p>\n<hr />\n<h2>Window:</h2>\n<pre><code>const int SCREEN_WIDTH = 0;\nconst int SCREEN_HEIGHT = 0;\n</code></pre>\n<p>I don't think these should be <code>const</code>. We'll probably need to make the window resizeable at some point.</p>\n<p>More importantly, we shouldn't store these variables at all. SDL will handle resizing our window, and we don't want to have to keep our own variables up to date. We should simply use <code>SDL_GetWindowSize</code> when we need the current window size.</p>\n<hr />\n<pre><code>bool open = false;\n</code></pre>\n<p>I don't think we need this variable. We can check that <code>mWindow</code> is not <code>nullptr</code> to see if the window is open.</p>\n<hr />\n<pre><code>if( SDL_Init( SDL_INIT_VIDEO) &lt; 0 )\n...\nSDL_Quit();\n</code></pre>\n<p>I'm not sure these should be inside the <code>Window</code> class, since SDL handles more than just the windowing. We also need a valid SDL context for rendering, audio, input etc. So perhaps SDL init and shutdown could be put in a separate <code>SDLContext</code> class that's created before the window.</p>\n<hr />\n<h2>Renderer:</h2>\n<pre><code>bool created = false;\nSDL_Renderer* mRenderer = NULL;\n</code></pre>\n<p>As with <code>Window::open</code>, we don't need the <code>created</code> flag. We can check <code>mRenderer</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T11:46:26.627", "Id": "531482", "Score": "2", "body": "You can, for example, have two windows, and then the asker's code initializes SDL twice." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T16:25:40.137", "Id": "269366", "ParentId": "269355", "Score": "5" } }, { "body": "<p>Its not much but note that you have a spelling mistake in windows.hpp</p>\n<p>//Consturctor to initialize window</p>\n<p>should be</p>\n<p>//Constructor to initialize window</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T22:28:25.957", "Id": "269532", "ParentId": "269355", "Score": "0" } } ]
{ "AcceptedAnswerId": "269366", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T10:45:03.963", "Id": "269355", "Score": "4", "Tags": [ "c++", "sdl2" ], "Title": "SDL2 engine base implementation" }
269355
<p>See <a href="https://codereview.stackexchange.com/questions/269214/serializing-nested-data-structures-in-a-human-readable-format">Serializing (nested) data structures in a human-readable format</a> for more details.</p> <p>In the last two days I have significantly improved my function, and wrote seven implementations of it.</p> <p>I have written an updated version of the original function, updated function with <code>list</code> appending replaced by list comprehension, and the updated version with string concatenation and joining replaced by <code>StringIO</code> operations, <code>StringIO</code> version with <code>StringIO</code> api replaced by that of <code>deque</code> and <code>list</code>.</p> <p>All the first five functions do not contain trailing commas.</p> <p>I have also written a alternate version of the <code>StringIO</code> version with recursive generator functions, and an version of the <code>deque</code> version that allows trailing commas, both of the above contain trailing commas.</p> <h2>Code</h2> <pre class="lang-py prettyprint-override"><code>import json from collections import deque from io import StringIO from typing import Any, Union SUPPORTED_TYPES = { dict: {'enclosures': ('{', '}'), 'empty_repr': 'dict()'}, list: {'enclosures': ('[', ']'), 'empty_repr': '[]'}, set: {'enclosures': ('{', '}'), 'empty_repr': 'set()'}, tuple: {'enclosures': ('(', ')'), 'empty_repr': '()'}, deque: {'enclosures': ('deque([', '])'), 'empty_repr': 'deque()'}, frozenset: {'enclosures': ('frozenset({', '})'), 'empty_repr': 'frozenset()'}, } def identify(obj: Any) -&gt; type: base = obj.__class__.__mro__[-2] if base in SUPPORTED_TYPES: return base return None def represent(obj: Union[deque, dict, frozenset, list, set, tuple], indent: int=4) -&gt; str: if not identify(obj): raise TypeError('argument `obj` should be an instance of a built-in container data type (or `deque`)') if not isinstance(indent, int): raise TypeError('argument `indent` should be an `int`') if indent &lt;= 0: raise ValueError('argument `indent` should be greater than 0') if indent % 2: raise ValueError('argument `indent` should be a multiple of 2') increment = ' '*indent def mapping_worker(obj: dict, indent: str, indent_level: str, top_indent: str) -&gt; str: ls = list() start = top_indent+'{' for k, v in obj.items(): ls.append(indent+f'{k!r}: '+overseer(v, indent+increment, indent, '')) return start+'\n'+',\n'.join(ls)+'\n'+indent_level+'}' def sequence_worker(obj: Union[deque, frozenset, list, set, tuple], indent: str, indent_level: str, top_indent: str, start: str, end: str, single_tuple: bool) -&gt; str: start = top_indent+start if single_tuple: item = overseer(obj[0], indent+increment, indent, indent) return start+'\n'+item+',\n'+indent_level+end ls = list() for i in obj: ls.append(overseer(i, indent+increment, indent, indent)) return start+'\n'+',\n'.join(ls)+'\n'+indent_level+end def overseer(obj: Any, indent: str, indent_level: str, top_indent: str) -&gt; str: identified = identify(obj) if not identified: return top_indent+f'{obj!r}' if not obj: return top_indent+SUPPORTED_TYPES[identified]['empty_repr'] if identified == dict: return mapping_worker(obj, indent, indent_level, top_indent) start, end = SUPPORTED_TYPES[identified]['enclosures'] single_tuple = (identified == tuple and len(obj) == 1) return sequence_worker(obj, indent, indent_level, top_indent, start, end, single_tuple) return overseer(obj, ' '*indent, '', '') def buffered_represent(obj: Union[deque, dict, frozenset, list, set, tuple], indent: int=4) -&gt; str: if not identify(obj): raise TypeError('argument `obj` should be an instance of a built-in container data type (or `deque`)') if not isinstance(indent, int): raise TypeError('argument `indent` should be an `int`') if indent &lt;= 0: raise ValueError('argument `indent` should be greater than 0') if indent % 2: raise ValueError('argument `indent` should be a multiple of 2') increment = ' '*indent def mapping_worker(obj: dict, indent: str, indent_level: str, top_indent: str) -&gt; str: buffer.write(top_indent+'{\n') for k, v in obj.items(): buffer.write(indent+f'{k!r}: ') overseer(v, indent+increment, indent, '') buffer.write(',\n') buffer.seek(buffer.tell() - 2) buffer.write('\n'+indent_level+'}') def sequence_worker(obj: Union[deque, frozenset, list, set, tuple], indent: str, indent_level: str, top_indent: str, start: str, end: str, single_tuple: bool) -&gt; str: buffer.write(top_indent+start+'\n') if single_tuple: overseer(obj[0], indent+increment, indent, indent) return buffer.write(',\n'+indent_level+end) for i in obj: overseer(i, indent+increment, indent, indent) buffer.write(',\n') buffer.seek(buffer.tell() - 2) buffer.write('\n'+indent_level+end) def overseer(obj: Any, indent: str, indent_level: str, top_indent: str) -&gt; str: identified = identify(obj) if not identified: return buffer.write(top_indent+f'{obj!r}') if not obj: return buffer.write(top_indent+SUPPORTED_TYPES[identified]['empty_repr']) if identified == dict: return mapping_worker(obj, indent, indent_level, top_indent) start, end = SUPPORTED_TYPES[identified]['enclosures'] single_tuple = (identified == tuple and len(obj) == 1) sequence_worker(obj, indent, indent_level, top_indent, start, end, single_tuple) with StringIO() as buffer: overseer(obj, ' '*indent, '', '') return buffer.getvalue() def deque_represent(obj: Union[deque, dict, frozenset, list, set, tuple], indent: int=4) -&gt; str: if not identify(obj): raise TypeError('argument `obj` should be an instance of a built-in container data type (or `deque`)') if not isinstance(indent, int): raise TypeError('argument `indent` should be an `int`') if indent &lt;= 0: raise ValueError('argument `indent` should be greater than 0') if indent % 2: raise ValueError('argument `indent` should be a multiple of 2') increment = ' '*indent buffer = deque() def mapping_worker(obj: dict, indent: str, indent_level: str, top_indent: str) -&gt; str: buffer.append(top_indent+'{\n') for k, v in obj.items(): buffer.append(indent+f'{k!r}: ') overseer(v, indent+increment, indent, '') buffer.append(',\n') buffer.pop() buffer.append('\n'+indent_level+'}') def sequence_worker(obj: Union[deque, frozenset, list, set, tuple], indent: str, indent_level: str, top_indent: str, start: str, end: str, single_tuple: bool) -&gt; str: buffer.append(top_indent+start+'\n') if single_tuple: overseer(obj[0], indent+increment, indent, indent) return buffer.append(',\n'+indent_level+end) for i in obj: overseer(i, indent+increment, indent, indent) buffer.append(',\n') buffer.pop() buffer.append('\n'+indent_level+end) def overseer(obj: Any, indent: str, indent_level: str, top_indent: str) -&gt; str: identified = identify(obj) if not identified: return buffer.append(top_indent+f'{obj!r}') if not obj: return buffer.append(top_indent+SUPPORTED_TYPES[identified]['empty_repr']) if identified == dict: return mapping_worker(obj, indent, indent_level, top_indent) start, end = SUPPORTED_TYPES[identified]['enclosures'] single_tuple = (identified == tuple and len(obj) == 1) sequence_worker(obj, indent, indent_level, top_indent, start, end, single_tuple) overseer(obj, ' '*indent, '', '') return ''.join(buffer) def list_represent(obj: Union[deque, dict, frozenset, list, set, tuple], indent: int=4) -&gt; str: if not identify(obj): raise TypeError('argument `obj` should be an instance of a built-in container data type (or `deque`)') if not isinstance(indent, int): raise TypeError('argument `indent` should be an `int`') if indent &lt;= 0: raise ValueError('argument `indent` should be greater than 0') if indent % 2: raise ValueError('argument `indent` should be a multiple of 2') increment = ' '*indent buffer = list() def mapping_worker(obj: dict, indent: str, indent_level: str, top_indent: str) -&gt; str: buffer.append(top_indent+'{\n') for k, v in obj.items(): buffer.append(indent+f'{k!r}: ') overseer(v, indent+increment, indent, '') buffer.append(',\n') buffer.pop(-1) buffer.append('\n'+indent_level+'}') def sequence_worker(obj: Union[deque, frozenset, list, set, tuple], indent: str, indent_level: str, top_indent: str, start: str, end: str, single_tuple: bool) -&gt; str: buffer.append(top_indent+start+'\n') if single_tuple: overseer(obj[0], indent+increment, indent, indent) return buffer.append(',\n'+indent_level+end) for i in obj: overseer(i, indent+increment, indent, indent) buffer.append(',\n') buffer.pop(-1) buffer.append('\n'+indent_level+end) def overseer(obj: Any, indent: str, indent_level: str, top_indent: str) -&gt; str: identified = identify(obj) if not identified: return buffer.append(top_indent+f'{obj!r}') if not obj: return buffer.append(top_indent+SUPPORTED_TYPES[identified]['empty_repr']) if identified == dict: return mapping_worker(obj, indent, indent_level, top_indent) start, end = SUPPORTED_TYPES[identified]['enclosures'] single_tuple = (identified == tuple and len(obj) == 1) sequence_worker(obj, indent, indent_level, top_indent, start, end, single_tuple) overseer(obj, ' '*indent, '', '') return ''.join(buffer) def listcomp_represent(obj: Union[deque, dict, frozenset, list, set, tuple], indent: int=4) -&gt; str: if not identify(obj): raise TypeError('argument `obj` should be an instance of a built-in container data type (or `deque`)') if not isinstance(indent, int): raise TypeError('argument `indent` should be an `int`') if indent &lt;= 0: raise ValueError('argument `indent` should be greater than 0') if indent % 2: raise ValueError('argument `indent` should be a multiple of 2') increment = ' '*indent def mapping_worker(obj: dict, indent: str, indent_level: str, top_indent: str) -&gt; str: start = top_indent+'{' ls = [indent+f'{k!r}: '+overseer(v, indent+increment, indent, '') for k, v in obj.items()] return start+'\n'+',\n'.join(ls)+'\n'+indent_level+'}' def sequence_worker(obj: Union[deque, frozenset, list, set, tuple], indent: str, indent_level: str, top_indent: str, start: str, end: str, single_tuple: bool) -&gt; str: start = top_indent+start if single_tuple: item = overseer(obj[0], indent+increment, indent, indent) return start+'\n'+item+',\n'+indent_level+end ls = [overseer(i, indent+increment, indent, indent) for i in obj] return start+'\n'+',\n'.join(ls)+'\n'+indent_level+end def overseer(obj: Any, indent: str, indent_level: str, top_indent: str) -&gt; str: identified = identify(obj) if not identified: return top_indent+f'{obj!r}' if not obj: return top_indent+SUPPORTED_TYPES[identified]['empty_repr'] if identified == dict: return mapping_worker(obj, indent, indent_level, top_indent) start, end = SUPPORTED_TYPES[identified]['enclosures'] single_tuple = (identified == tuple and len(obj) == 1) return sequence_worker(obj, indent, indent_level, top_indent, start, end, single_tuple) return overseer(obj, ' '*indent, '', '') def generator_represent(obj: Union[deque, dict, frozenset, list, set, tuple], indent: int=4) -&gt; str: if not identify(obj): raise TypeError('argument `obj` should be an instance of a built-in container data type (or `deque`)') if not isinstance(indent, int): raise TypeError('argument `indent` should be an `int`') if indent &lt;= 0: raise ValueError('argument `indent` should be greater than 0') if indent % 2: raise ValueError('argument `indent` should be a multiple of 2') increment = ' '*indent def mapping_worker(obj: dict, indent: str, indent_level: str, top_indent: str) -&gt; str: yield top_indent+'{\n' for k, v in obj.items(): yield indent+f'{k!r}: ' yield from overseer(v, indent+increment, indent, '') yield ',\n' yield indent_level+'}' def sequence_worker(obj: Union[deque, frozenset, list, set, tuple], indent: str, indent_level: str, top_indent: str, start: str, end: str) -&gt; str: yield top_indent+start+'\n' for i in obj: yield from overseer(i, indent+increment, indent, indent) yield ',\n' yield indent_level+end def overseer(obj: Any, indent: str, indent_level: str, top_indent: str) -&gt; str: identified = identify(obj) if not identified: return top_indent+f'{obj!r}' if not obj: return top_indent+SUPPORTED_TYPES[identified]['empty_repr'] if identified == dict: return mapping_worker(obj, indent, indent_level, top_indent) start, end = SUPPORTED_TYPES[identified]['enclosures'] return sequence_worker(obj, indent, indent_level, top_indent, start, end) return ''.join(overseer(obj, ' '*indent, '', '')) def deque_represent_with_trail(obj: Union[deque, dict, frozenset, list, set, tuple], indent: int=4) -&gt; str: if not identify(obj): raise TypeError('argument `obj` should be an instance of a built-in container data type (or `deque`)') if not isinstance(indent, int): raise TypeError('argument `indent` should be an `int`') if indent &lt;= 0: raise ValueError('argument `indent` should be greater than 0') if indent % 2: raise ValueError('argument `indent` should be a multiple of 2') increment = ' '*indent buffer = deque() def mapping_worker(obj: dict, indent: str, indent_level: str, top_indent: str) -&gt; str: buffer.append(top_indent+'{\n') for k, v in obj.items(): buffer.append(indent+f'{k!r}: ') overseer(v, indent+increment, indent, '') buffer.append(',\n') buffer.append(indent_level+'}') def sequence_worker(obj: Union[deque, frozenset, list, set, tuple], indent: str, indent_level: str, top_indent: str, start: str, end: str) -&gt; str: buffer.append(top_indent+start+'\n') for i in obj: overseer(i, indent+increment, indent, indent) buffer.append(',\n') buffer.append(indent_level+end) def overseer(obj: Any, indent: str, indent_level: str, top_indent: str) -&gt; str: identified = identify(obj) if not identified: return buffer.append(top_indent+f'{obj!r}') if not obj: return buffer.append(top_indent+SUPPORTED_TYPES[identified]['empty_repr']) if identified == dict: return mapping_worker(obj, indent, indent_level, top_indent) start, end = SUPPORTED_TYPES[identified]['enclosures'] sequence_worker(obj, indent, indent_level, top_indent, start, end) overseer(obj, ' '*indent, '', '') return ''.join(buffer) if __name__ == '__main__': var = {'a': {'a': {'a': [0, 0, 0], 'b': [0, 0, 1], 'c': [0, 0, 2]}, 'b': {'a': [0, 1, 0], 'b': [0, 1, 1], 'c': [0, 1, 2]}, 'c': {'a': [0, 2, 0], 'b': [0, 2, 1], 'c': [0, 2, 2]}}, 'b': {'a': {'a': [1, 0, 0], 'b': [1, 0, 1], 'c': [1, 0, 2]}, 'b': {'a': [1, 1, 0], 'b': [1, 1, 1], 'c': [1, 1, 2]}, 'c': {'a': [1, 2, 0], 'b': [1, 2, 1], 'c': [1, 2, 2]}}, 'c': {'a': {'a': [2, 0, 0], 'b': [2, 0, 1], 'c': [2, 0, 2]}, 'b': {'a': [2, 1, 0], 'b': [2, 1, 1], 'c': [2, 1, 2]}, 'c': {'a': [2, 2, 0], 'b': [2, 2, 1], 'c': [2, 2, 2]}}} repr0 = represent(var) print(repr0) assert eval(repr0) == var repr1 = buffered_represent(var) repr2 = deque_represent(var) repr3 = list_represent(var) repr4 = listcomp_represent(var) repr5 = generator_represent(var) repr6 = deque_represent_with_trail(var) assert len({repr0, repr1, repr2, repr3, repr4}) == 1 assert repr5 == repr6 </code></pre> <p>Output:</p> <pre class="lang-py prettyprint-override"><code>{ 'a': { 'a': { 'a': [ 0, 0, 0 ], 'b': [ 0, 0, 1 ], 'c': [ 0, 0, 2 ] }, 'b': { 'a': [ 0, 1, 0 ], 'b': [ 0, 1, 1 ], 'c': [ 0, 1, 2 ] }, 'c': { 'a': [ 0, 2, 0 ], 'b': [ 0, 2, 1 ], 'c': [ 0, 2, 2 ] } }, 'b': { 'a': { 'a': [ 1, 0, 0 ], 'b': [ 1, 0, 1 ], 'c': [ 1, 0, 2 ] }, 'b': { 'a': [ 1, 1, 0 ], 'b': [ 1, 1, 1 ], 'c': [ 1, 1, 2 ] }, 'c': { 'a': [ 1, 2, 0 ], 'b': [ 1, 2, 1 ], 'c': [ 1, 2, 2 ] } }, 'c': { 'a': { 'a': [ 2, 0, 0 ], 'b': [ 2, 0, 1 ], 'c': [ 2, 0, 2 ] }, 'b': { 'a': [ 2, 1, 0 ], 'b': [ 2, 1, 1 ], 'c': [ 2, 1, 2 ] }, 'c': { 'a': [ 2, 2, 0 ], 'b': [ 2, 2, 1 ], 'c': [ 2, 2, 2 ] } } } </code></pre> <p>Needless to say all assertions succeeded, you can also test examples from <a href="https://codereview.stackexchange.com/questions/269247/serializing-nested-data-structures-in-a-human-readable-format-with-all-bugs-fi">Serializing (nested) data structures in a human-readable format with all bugs fixed</a>.</p> <p>All the functions support <code>deque, dict, frozenset, list, set, tuple</code>, and through <code>dict</code>, <code>Counter</code>, <code>OrderedDict</code>, and <code>defaultdict</code>, and through <code>tuple</code>, support <code>namedtuple</code> to a lesser extent (<code>namedtuple</code>s are treated as base <code>tuple</code>s so field names are lost).</p> <h2>Performance</h2> <pre><code>In [2]: %timeit json.dumps(var) 27 µs ± 3.87 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) In [3]: %timeit represent(var) 123 µs ± 3.81 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) In [4]: %timeit listcomp_represent(var) 127 µs ± 3.13 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) In [5]: %timeit deque_represent(var) 125 µs ± 3.3 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) In [6]: %timeit list_represent(var) 127 µs ± 2.61 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) In [7]: %timeit buffered_represent(var) 148 µs ± 4.43 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) In [8]: %timeit generator_represent(var) 328 µs ± 31.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) In [9]: %timeit deque_represent_with_trail(var) 118 µs ± 2.45 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) </code></pre> <p>Needless to say, <code>json.dumps</code> is the fastest, and also needless to say <code>json</code> supports far less data types (more specifically, it can't serialize <code>set</code>, <code>deque</code> and <code>frozenset</code>, and after serializing and deserializing <code>tuple</code>s will become <code>list</code>s), but it is really fast.</p> <p>Of the functions that support all the data types, of the functions that eliminate trailing commas, sometimes <code>represent</code> is the fastest, sometimes <code>deque_represent</code> is as fast as represent. I can't decide which is more performant.</p> <p><code>list_represent</code> is consistently a little slower than <code>deque_represent</code>, and surprisingly, the first function with list comp is a little slower and I don't know why. I have also tried to replace the <code>list</code>s in the first version with <code>deque</code>s and strangely it slows the execution down.</p> <p>The version using <code>StringIO</code> is noticeably slower than the above functions and I really don't know why.</p> <p>The version using generators is significantly slower than all other functions and I really can't explain this, how can it be slower if it doesn't even initialize a collection variable and append strings to that collection?</p> <p>Of all functions I have written, the <code>deque</code> with trailing commas is the fastest, but it allows trailing commas and the performance gain is minimal. And removing trailing commas using <code>re</code> is not a good idea since single element <code>tuple</code>s need trailing commas the regex need to be more complex than necessary.</p> <p>Which function is the best overall? I think the <code>deque</code> version is the most performant but I am not sure. And as you can see I really do care about performance, how can I improve the functions to reach <code>json</code> level performance? And what Python collection data type appends even faster than <code>deque</code>? I tried to Google Search for this, of course, and unsurprisingly all results are completely irrelevant.</p> <h2>Update</h2> <p>I poked around the source code of <code>json</code> ('C:\Program Files\Python39\Lib\json') a bit and tried to rewrite it to modify its features and discovered that it imports the built-in module <code>_json</code>, and uses the <code>make_encoder</code> function to make a default <code>_json.Encoder</code> class object to encode objects without indentation, and it uses Python functions to serialize objects with indentation.</p> <p>The default function calls to <code>json.dump(s)</code> without specifying indent, the <code>indent</code> argument is <code>None</code> and <code>json</code> module cheats by using the <code>_json</code> module which is written in C, and C is indeed fast, being precompiled, but the output is quite ugly.</p> <p>For any function calls that specify indent, <code>json</code> instead uses the Python functions which are not as performant because of interpreted nature, and the runtime is longer.</p> <p>In short calling <code>json.dumps</code> without setting a non-zero indent, <code>json</code> cheats by use precompiled C code to leverage its speed, but it is not &quot;Pure Python&quot;, serializing objects with indentation instead makes it fall back to pure Python functions and revealing its low performance nature.</p> <p>My tests were unscientific because I didn't specify indent when calling <code>json.dumps(var)</code> and in fact only tested optimized precompiled C code, testing with indentation to test the real Python code though...</p> <pre><code>In [177]: %timeit json.dumps(var) 29 µs ± 3.58 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) In [178]: %timeit json.dumps(var,indent=4) 169 µs ± 5.95 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) </code></pre> <p>It is slower than most of my custom functions and even slower than <code>StringIO</code> version, the only custom function slower than <code>json.dumps</code> is the recursive generator version, which, to be fair, is really bad written, because I don't normally write recursive generator functions and that one is the first, not to mention I don't often use generator functions to begin with, always opting to use <code>list</code>(<code>dict</code>, <code>set</code>...) comprehension because of performance (in short I most frequently use generator expressions in quotes and don't use the <code>yield</code> keyword as often).</p> <p>So my functions indeed beat <code>json</code> at performance.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T03:46:10.133", "Id": "531689", "Score": "0", "body": "add a timeit response for `prettyprint`?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T11:59:28.243", "Id": "269357", "Score": "1", "Tags": [ "python", "performance", "python-3.x", "programming-challenge", "serialization" ], "Title": "Python functions to serialize nested data structures human readably" }
269357
<p>I try to block all websites in Hebrew because I want to give more time on websites in other languages.</p> <p>Given that many webmasters don't add <code>&lt;meta name=&quot;language&quot; content=&quot;Hebrew&quot;&gt;</code> meta attribute to all webpages of their websites I can't use it to block websites which appear in a certain language.</p> <p>According to one work <a href="https://he.wikipedia.org/wiki/%D7%A9%D7%9B%D7%99%D7%97%D7%95%D7%AA_%D7%90%D7%95%D7%AA%D7%99%D7%95%D7%AA_%D7%91%D7%A2%D7%91%D7%A8%D7%99%D7%AA" rel="nofollow noreferrer">the most common letter in Hebrew</a> is <em>Yod</em> (<code>'</code>), parallel to the Arabic <em>Ya</em> (<code>ي</code>) and common in all Semitic languages, so what I try to do is to just block any webpage that has <em>Yod</em> in it:</p> <pre class="lang-js prettyprint-override"><code>const [...elements] = document.getElementsByTagName(&quot;*&quot;); elements.forEach((element) =&gt; { if (element.textContent.includes(&quot;י&quot;)) { window.open(&quot;https://google.com/&quot;, &quot;_self&quot;); } }); </code></pre> <p>In my tests the code works on Hebrew-appearing-websites and doesn't work on non-Hebrew-appearing-websites, but maybe there is something to improve?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T16:02:32.830", "Id": "531413", "Score": "0", "body": "I don't understand the downvotes. If you think there is anything to improve please comment or suggest an edit (which I will gladly examine ASAP)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T16:04:48.433", "Id": "531414", "Score": "4", "body": "What prompted you to write this and what does the rest of the program look like?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T23:03:08.983", "Id": "531441", "Score": "0", "body": "@Mast I don't understand the first clarification question ; that's all my code in this context, there is no other code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T23:20:13.697", "Id": "531442", "Score": "0", "body": "@Mast I have edited; is that better?" } ]
[ { "body": "<p>Your script will only work correctly if it is placed after the Yod character. Consider adding an event listener for <code>window.load</code> to only call it when all the content is loaded:</p>\n\n<pre class=\"lang-javascript prettyprint-override\"><code>addEventListener(&quot;load&quot;, () =&gt; {\n ...\n});\n</code></pre>\n<p>There is no need to iterate through all the elements. You could have simply used <code>document.documentElement.innerHTML</code>. The only problem with this is that it will find the character in the script itself. To fix this we can use <code>String.fromCharCode</code>:</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>if (document.documentElement.innerHTML.indexOf(String.fromCharCode(1497)) &gt;= 0)\n document.location = 'https://he.wikipedia.org/';\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T23:31:37.523", "Id": "531537", "Score": "0", "body": "Using `window.onload` does not guarantee it will be call as it can easily be over written by other code/extensions, Always use `addEventListener` to add listeners to ensure that they are called. `window` is the default `this`, it use is redundant (ie you don't use for `window.document`) thus `window.onload = function () {` becomes `addEventListener(\"load\", () => {`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T12:22:14.097", "Id": "531574", "Score": "0", "body": "@Blindman67, thanks. jQuery has made me stupid =)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T16:37:37.087", "Id": "269397", "ParentId": "269359", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T13:49:11.203", "Id": "269359", "Score": "1", "Tags": [ "javascript", "userscript" ], "Title": "Check if a website is in a certain language and if so, block it" }
269359
<p>I was assigned the following problem:</p> <blockquote> <p>You've gone back in time to 500BC Athens and Socrates wants you to build him an app to help classify animals.</p> <ol> <li>Build the classes <code>Animal</code>, <code>Cat</code>, and <code>Bug</code>.</li> <li>Define the properties <code>color</code> and <code>leg_number</code> on the relevant and necessary classes. Have them be initialized within a constructor.</li> <li>Add the functionality that would allow us to call a method <code>move</code> with the <code>Cat</code> and <code>Bug</code> classes. Have the method return a string <code>&quot;I'm moving with &quot; + leg_number + &quot; legs!&quot;</code>, with the <code>leg_number</code> being <code>leg_number</code> as set on the class.</li> <li>Add a new class called <code>Bird</code>. Add the property <code>wing_number</code>. Add the functionality that would allow us to call a method <code>move</code> with the <code>Bird</code> class. Have the method return the string <code>&quot;I'm moving with &quot; + leg_number + &quot; legs!&quot;</code> if <code>wing_number</code> doesn't have an applicable value. If <code>wing_number</code> does have an applicable value, return the string <code>&quot;I'm flying&quot;</code>.</li> </ol> </blockquote> <p>My code for that is as follows:</p> <pre><code>public class SocratesApp { public static void main(String[] args) { // TODO Auto-generated method stub Cat myCat = new Cat(&quot;orange&quot;, 4); int catLegs = myCat.leg_number; myCat.move(catLegs); Bug myBug = new Bug(&quot;green&quot;, 16); int bugLegs = myBug.leg_number; myBug.move(bugLegs); Bird bird1 = new Bird(&quot;yellow&quot;, 2, 2); int bird1Legs = bird1.leg_number; int bird1Wings = bird1.wing_number; bird1.move(bird1Legs, bird1Wings); Bird bird2 = new Bird(&quot;brown&quot;, 2, 0); int bird2Legs = bird2.leg_number; int bird2Wings = bird2.wing_number; bird1.move(bird2Legs, bird2Wings); } } class Animal { private String color; private int leg_number; public Animal(String color, int leg_number) { this.color = color; this.leg_number = leg_number; } public void move(int leg_number) { System.out.println(&quot;I'm moving with &quot; + leg_number + &quot; legs!&quot;); } } class Cat extends Animal { String color; int leg_number; public Cat(String color, int leg_number) { super(color, leg_number); this.color = color; this.leg_number = leg_number; } @Override public void move(int leg_number) { System.out.println(&quot;I'm moving with &quot; + leg_number + &quot; legs!&quot;); } } class Bug extends Animal { String color; int leg_number; public Bug(String color, int leg_number) { super(color, leg_number); this.color = color; this.leg_number = leg_number; } @Override public void move(int leg_number) { System.out.println(&quot;I'm moving with &quot; + leg_number + &quot; legs!&quot;); } } class Bird extends Animal { String color; int leg_number; int wing_number; public Bird(String color, int leg_number, int wing_number) { super(color, leg_number); this.color = color; this.leg_number = leg_number; this.wing_number = wing_number; } public void move(int leg_number, int wing_number) { if (wing_number &gt; 0) { System.out.println(&quot;I'm flying&quot;); } else { System.out.println(&quot;I'm moving with &quot; + leg_number + &quot; legs!&quot;); } } } </code></pre> <p>The code works fine. However, I am concerned about whether I should have used an interface or an abstract class instead of a super class. I'm not sure I understand how to determine which to use when. If I should have used something different, can you explain and tell me how I should be implementing the move method or the properties?</p> <p>I am also concerned about my use/lack of use of public and private in different places. I'm a little confused about if and where I should have used those.</p> <p>Of course, I am open to comments on anything else that I could have/should have done better and/or more concisely.</p> <p>I appreciate the feedback everyone!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T16:14:44.900", "Id": "531416", "Score": "0", "body": "Welcome to Code Review! I'm tempted to vote to close, since your code does not appear to have implemented the `move` method the way the problem requires. Can you clarify the requirements, or update the code to state the correct requirements?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T16:18:46.670", "Id": "531417", "Score": "0", "body": "Why would you vote to close? That's exactly the reason I'm asking for help, to learn what I need to do differently. If I've done something wrong, the answer is to tell me what I've done wrong, not close the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T16:20:49.327", "Id": "531418", "Score": "0", "body": "On Code Review, we require that code be functional and working as intended. In this case, I think there is an argument that \"not doing what you were asked to do\" counts as not working as intended. Notably, I _didn't_ vote to close, because I was unsure and was interested in getting input from other reviewers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T16:24:26.170", "Id": "531419", "Score": "0", "body": "So you're saying if I didn't understand something correctly I can't get any help? No offense, but that seems rather stupid. Why would I ask for help if I've done everything right?\n\nI posted the question on Stack Overflow also. They told me that I needed to post it here. If they won't help and you won't help, where do I go for help?\n\nI would note that you have answered twice, and you apparently know what I've done wrong, and you have not helped. So tell me, where do I go where someone will tell me what I've done wrong?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T16:43:28.380", "Id": "531423", "Score": "0", "body": "I don't know if this is what you were talking about when you said I didn't implement the move function correctly, but when I reread the problem I noticed a few words were missing. I believe this is because in the problem text the writers used greater than and less than signs for a variable. I have edited the question, but to summarize the problem says I must return \"I'm moving with \" + leg_number + \" legs!\" I have to include the leg number in the return statement. \n\nIf this is not what you meant by \"not doing what I was asked to do,\" then PLEASE explain what you mean." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T07:59:06.723", "Id": "531461", "Score": "1", "body": "This should be tagged as [tag:homework]. Apart from that, I'd leave this open as the requirement for `move()` seems poorly written to me and one could argue that this fulfills it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T14:17:50.870", "Id": "531497", "Score": "0", "body": "It's not actually homework. It's an interview question. I'm doing interview practice problems so I'm ready when job hunting. I'm finding out that I'm still very weak in many areas and need to do lots of review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T16:05:29.110", "Id": "531509", "Score": "0", "body": "It's still a situation where you are likely to learn more by being guided in what you need to review than by being given detailed explanations and replacement code, in my view." } ]
[ { "body": "<p>I'm not sure how to approach this. You say you've been assigned a problem, so this feels very much like coursework/homework.</p>\n<p>Assuming this homework is to be assessed, it's more helpful for the assessor to see your work than mine - they will then know how successful the tuition has been, and where your understanding needs more work.</p>\n<p>On that basis I'm not going to give an alternative solution, but will make some general comments.</p>\n<p>The intent of the question is clearly for you to show that you've grasped Object-oriented concepts, in Java terms, such as encapsulation, inheritance, polymorphism and so on. The assignment naturally lends itself to such an approach, but your solution largely misses the point in so many ways that I wonder whether you've been taught anything at all about these concepts.</p>\n<p>Here's a few points to think about, and review in your learning material.</p>\n<ol>\n<li>An instance of an Animal knows how what color it is. It also knows many legs (and possibly wings) it has. What does that tell you about the move() method? (Keyword: Encapsulation.)</li>\n<li>Any Animal - whether Cat, Bug or Bird - has legs and a color. (Keyword: Inheritance - you probably should also review the concept of public/protected/private fields and methods.).</li>\n<li>Cats, Bugs and wingless Birds all move in the same way, but Birds with wings move differently. (Keyword: Polymorphism)</li>\n<li>What does &quot;return a string&quot; mean? Is that what you are doing?</li>\n</ol>\n<p>I would suggest you review these points, and rework your code in line with your (hopefully improved) understanding of them. If you'd care to show us your revised code, please don't edit the original post but instead post your updated code as an answer or perhaps a new question.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T07:56:40.030", "Id": "531460", "Score": "0", "body": "+1 According to the description of the [tag:homework] tag, this is how you are approach such questions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T13:54:12.213", "Id": "531496", "Score": "0", "body": "Agree with your answer without code for the OP's homework." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T07:50:40.120", "Id": "269382", "ParentId": "269362", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T15:32:53.770", "Id": "269362", "Score": "1", "Tags": [ "java", "object-oriented", "interview-questions", "classes", "inheritance" ], "Title": "Model animals using inheritance in Java" }
269362
<p>So a little context to understand the code:</p> <ol> <li>This is a helper function to solve a bigger problem <a href="https://leetcode.com/problems/dungeon-game/" rel="nofollow noreferrer">here</a></li> <li>Quick summary: A Knight is in a dungeon/2D grid of Ints, starts at 0,0 and must reach the last cell at the bottom right to find the princess</li> <li>The purpose of this helper function is to return all neighbors of a given starting point, given some constraints:</li> </ol> <ul> <li>The knight's starting point is always upper-left - 0,0</li> <li>The knight can only travel right or down, 1 cell at a time</li> <li>The target / base case is bottom right of the grid/dungeon where the princess is</li> </ul> <p><strong>Code below</strong></p> <pre><code>def get_neighbors(d, x, y, coll): # d == abbr. for dungeon is our board # For example: #[-8, -13, -8] #[-24, 28, 28] #[-13, -13, -30] # coll == abbr. for collection, how I keep track of all returned neighbors # We start our knight in the upper left hand corner row_length = len(d) col_length = len(d[0]) if (x,y) == (row_length - 1, col_length - 1): # Once we reach the bottom right corner we are done return coll for dx in range(0, 2): for dy in range(0, 2): if dx == 0 and dy == 0 or dx == 1 and dy == 1: # If cell is not to the bottom or to the right, skip it continue if x + dx &gt; len(d[x]) - 1 or y + dy &gt; len(d) - 1: # Out of bounds check continue neighbor = (x + dx, y + dy) # I'm wondering why I even need this line, if I am only going to the right and to the bottom each time # Why do I need to guard against duplicates if neighbor not in coll: coll.append(neighbor) get_neighbors(d, x + dx, y + dy, coll) return coll </code></pre> <p>Is there anything I should do differently?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T17:37:45.560", "Id": "531426", "Score": "0", "body": "Travel \"right and down\" diagonally, or \"either right or down\"?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T17:41:25.787", "Id": "531427", "Score": "0", "body": "@Reinderien Right or down, no diagonal, good point" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T17:49:04.823", "Id": "531428", "Score": "0", "body": "I think you need to show much more of your code, not just this function - because some of the issues with this code, when fixed, will require a different calling convention." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T17:50:36.563", "Id": "531429", "Score": "0", "body": "@Reinderien Ok duly noted. I'll return with the rest of the code once I have it done, thanks for the input." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T20:18:18.453", "Id": "531435", "Score": "0", "body": "@SergioBost Don't you end up with all the cells (i,j) with i and/or j >= than x,y in your collection?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T20:22:24.350", "Id": "531436", "Score": "0", "body": "@kubatucka If you're referring to dx, dy, then yes, since I'm only moving forward (right or down) never backwards (left or up)" } ]
[ { "body": "<p>Welcome to CodeReview!</p>\n<p>Disclaimer: As noted in the comments, a review of this code is limited since I don't know the entire codebase / algorithmic approach. So this review is limited to this function's current implementation.</p>\n<hr />\n<p><strong>Naming</strong></p>\n<p><code>d</code> and <code>coll</code> are hard-to-understand names, <code>dungeon</code> and <code>collection</code> are already an improvement. <code>collection</code> however is almost meaningless, as it says nothing about the data stored in the variable. Since the function is called <code>get_neighbors</code>, the return value should probably be called <code>neighbors</code> (<code>coll.append(neighbor)</code> is another hint). If you find yourself needing comments to explain your variable names, you should change them. Reading this line <code># d == abbr. for dungeon is our board</code> is already a lot of unnecessary work compared to simply reading <code>dungeon</code> in the first place. Stick to meaningful and readable variable names, that do not require further explanation.</p>\n<hr />\n<p><strong>Type annotations</strong></p>\n<p>Including type annotations significantly increases the readability of your code. It also allows for better error-checking:</p>\n<pre><code>def get_neighbors(dungeon: list[list[int]], x: int, y: int, neighbors: list[tuple[int, int]])\\\n -&gt; list[tuple[int, int]]:\n</code></pre>\n<hr />\n<p><strong>Miscellaneous</strong></p>\n<hr />\n<p>You might have rows and columns the wrong way round. I would expect <code>dungeon</code> to be a list of rows, <code>y</code> to indicate the row and <code>x</code> to indicate the column. Your current implementation handles <code>dungeon</code> like a list of columns.</p>\n<hr />\n<p><code>if x + dx &gt; len(d[x]) - 1 or y + dy &gt; len(d) - 1: # Out of bounds check</code>:</p>\n<ul>\n<li>You don't need to access <code>len(d[x])</code> (<code>d[x]</code> should also be <code>d[y]</code> by the way), as <code>dungeon</code> is a rectangle, simply use <code>len(d[0])</code></li>\n<li>You already calculated and stored <code>row_length</code> &amp; <code>col_length</code>, use them</li>\n</ul>\n<hr />\n<pre><code>for dx in range(0, 2):\n for dy in range(0, 2):\n if dx == 0 and dy == 0 or dx == 1 and dy == 1:\n continue\n</code></pre>\n<p>should be way simpler:</p>\n<pre><code>for dx, dy in ((1, 0), (0, 1)):\n</code></pre>\n<p>While this might be fine for only two directions, a module- or class-level constant <code>DIRECTIONS = ((1, 0), (0, 1))</code> would be even better, especially once the number of directions increases.</p>\n<pre><code>for dx, dy in DIRECTIONS:\n</code></pre>\n<hr />\n<pre><code># I'm wondering why I even need this line, if I am only going to the right and to the bottom each time\n# Why do I need to guard against duplicates\nif neighbor not in coll:\n coll.append(neighbor)\n</code></pre>\n<p>In you current implementation you need to perform this check, because different paths can lead to the same cell. Consider the simplest example of the two paths (1. DOWN -&gt; 2. RIGHT) and (1. RIGHT-&gt; 2. DOWN).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T18:42:51.620", "Id": "531434", "Score": "0", "body": "Very clear explanation, thanks. I'll make sure to be more thorough next time around." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T17:54:18.770", "Id": "269369", "ParentId": "269364", "Score": "1" } } ]
{ "AcceptedAnswerId": "269369", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T15:54:58.540", "Id": "269364", "Score": "1", "Tags": [ "python", "recursion", "depth-first-search" ], "Title": "Helper get_all_neighbors (in a grid) function - python" }
269364
<p>I've been working on a program that should find the color red on the screen and then send out an alert. The issue is that the red color moves around a lot and the color finder moves too slow on the screen to find the color accuritely and in time before the color dissapears to another location on the screen.</p> <p>Is there a way to speed up this color finding process so that it is practically instant?</p> <p>Here is the code:</p> <p>ColorFinder.java</p> <pre><code>import java.awt.AWTException; import java.awt.Robot; import java.awt.event.KeyEvent; import java.awt.Color; import java.util.Scanner; import java.awt.geom.*; import java.awt.event.*; import java.awt.*; public class ColorFinder { public static void main(String[] args) throws AWTException { //Create memories Scanner scanner = new Scanner(System.in); Robot robot = new Robot(); String ans; int red; int green; int blue; int x=535; int y=168; //Prints instructions System.out.println(&quot;Type 'p' to start.&quot;); System.out.println(&quot;&quot;); //Waits for start input ans = scanner.nextLine(); if(ans.equals(&quot;p&quot;)) { //Starts loop for(int i=0; i&lt;100; i++) { i=0; System.out.println(&quot;&quot;); //Color searcher x=x+1; if(x&gt;1378 &amp;&amp; y&gt;468) //reset on highest values x &amp; y { x=535; y=168; } if(x&gt;1378) //step down by one pixel with y { y=y+1; x=535; } //Get RGB value on screen coords System.out.println(&quot;x:&quot;+x+&quot; y:&quot;+y);//this part is not needed, it's only for visualising if it's working or at what speed it moves Color color = robot.getPixelColor(x, y); red=color.getRed(); green=color.getGreen(); blue=color.getBlue(); /* System.out.println(&quot;Red = &quot; + red); System.out.println(&quot;Green = &quot; + green); System.out.println(&quot;Blue = &quot; + blue); */ //Remove the note marks below to see how fast it moves /* robot.mouseMove(x, y); if(x==1000) {break;} */ //if it finds the specific red color it stops the loop and prints out &quot;Found red color!&quot; if(red==255 &amp;&amp; green==20 &amp;&amp; blue==25) { System.out.println(&quot;Found red color!&quot;); break; } } } } } </code></pre> <p>I will gladly answer any questions. Any kind of solution that does the same thing but way faster is good, many thanks in advance!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T06:47:12.647", "Id": "531455", "Score": "0", "body": "Is the red region you trying to find exactly 1 pixel? If not, you don't need to scan every pixel. For example, if you have a 10px red square somewhere on the screen, you only need to scan every 10th pixel at x and y. And I don't know how java handles console output but on other languages I saw a pretty big slowdown if I tryed to write at a very high speed to the console." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T18:28:14.250", "Id": "531516", "Score": "0", "body": "It has to read basically every single pixel in an area, I will add more shades of red and also white shades once the color searching stuff is complete. I actually had the same idea, I tried it and it didnt find the right color or shade of red, it basically skipped over it on a still image." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T21:46:42.580", "Id": "531534", "Score": "0", "body": "I have rolled back Rev 2 → 1. Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers)." } ]
[ { "body": "<p>The bottleneck in your code is mostly because you use a method (<code>java.awt.Robot#getPixelColor</code>) in a loop to fetch the color pixel by pixel; this method uses lower system API to fetch the color and that takes more time.</p>\n<p>You could make the code faster by using the <code>java.awt.Robot#createScreenCapture</code> to create a screenshot of a certain region and then, iterate on the colors by using the <code>java.awt.image.BufferedImage#getRGB</code>. The only downside is that the method returns an integer containing the <a href=\"https://en.wikipedia.org/wiki/RGB_color_model\" rel=\"nofollow noreferrer\">RGB</a> instead of a color object, you will need to convert it to a color.</p>\n<p>To convert the RGB to single color, you can use the <code>java.awt.image.ColorModel</code> to read the RGB value and choose the different color individually.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T00:59:23.037", "Id": "531446", "Score": "0", "body": "Thank you for the great answer! I have three questions though, does this screenshot get saved somewhere or is it literally just faster? Second question would be: How would this be done with the code I posted here? Third question would be: How fast is it really? Since I need it to be basically detecting every movement of the color it has to be really fast (under a second)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T01:01:31.233", "Id": "531448", "Score": "1", "body": "The screenshot is kept in memory; the code will be faster, since you won’t be using the IO to fetch the values (only one time, for the screenshot)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T01:13:44.457", "Id": "531450", "Score": "0", "body": "I'm not sure how I could implement that into the code I have, could you give an example. Having a hard time finding out how to actually implement it into my code." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T00:51:51.617", "Id": "269378", "ParentId": "269375", "Score": "3" } }, { "body": "<p>This question brings back memories from 2010 when I asked how to draw constantly changing grapics\n<a href=\"https://stackoverflow.com/questions/3742731/java-how-to-draw-constantly-changing-graphics\">https://stackoverflow.com/questions/3742731/java-how-to-draw-constantly-changing-graphics</a></p>\n<p>The idea is that you prepare a location rectangle of the area you want to capture and ask the robot to fill it:</p>\n<pre><code>Rectangle rect = new Rectangle(p.x - 4, p.y - 4, 8, 8);\nfinal BufferedImage capture = robot.createScreenCapture(rect);\n</code></pre>\n<p>then you loop over the area checking for the match</p>\n<pre><code>for (int x = 0; x &lt; 8; x++) {\n for (int y = 0; y &lt; 8; y++) {\n final Color pixelColor = new Color(capture.getRGB(x, y));\n\n if (!pixelColor.equals(view.getColorAt(x, y))) {\n // do something\n }\n }\n}\n</code></pre>\n<p>Typically my computer vision AI's does not use 64-pixel area, but 64*64=4096, but you can use 4k screenshot has 3840x2160=8294400 pixels and a minimum of 8 million comparisons will actually take some time unless you parallelize the work.</p>\n<hr />\n<p>I write c#, so this is written from the head as I remember Java +10 years ago.</p>\n<pre><code>Color red = new Color(255, 20, 25); \nRectangle rect = new Rectangle(535, 168, 843, 300);\nfinal BufferedImage capture = robot.createScreenCapture(rect);\nPair&lt;String, Integer&gt; location = FindColor(capture, red);\nif(location != null){\n System.out.printf(&quot;Found red color at (x:{%s}, y: {%s})%n&quot;, \n location.getValue(0), \n location.getValue(1));\n</code></pre>\n<p>where FindColor is something in the lines of:</p>\n<pre><code>public Pair&lt;String, Integer&gt; FindColor(BufferedImage capture, Color color){\n if (capture == null || color == null) \n return null; \n for (int x = 0; x &lt; capture.getWidth(); x++)\n for (int y = 0; y &lt; capture.getHeight(); y++)\n if (new Color(capture.getRGB(x, y)).equals(color)) \n return Pair.with(x, y); \n return null;\n}\n</code></pre>\n<p>instead of tuple-like Pair&lt;&gt;, you can use point2d or a similar struct just likely you do not need the null checks.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T14:35:22.143", "Id": "531498", "Score": "0", "body": "You can use a punch of tricks if you just have to quickly find 64x64 rows and columns from a solid background where it is. For example, if you \"binary and\" all row pixels together they will be your background unless the object is in one of them. Loop itself should be simple and index cached. So complexity O(n^2) is reduced to O(2n)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T18:57:24.190", "Id": "531519", "Score": "0", "body": "Could you please change the code I posted to make it work? I'm just so frusturated because I don't understand how to implement this screenCapture thing. I just want it to be in that same rectangle where it is in my code and not the entire screen." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T20:27:45.947", "Id": "531527", "Score": "1", "body": "@Golden The Rectangle class gives you the possibility of specifying the [`x`, `y`, `width` & `height`](https://docs.oracle.com/en/java/javase/16/docs/api/java.desktop/java/awt/Rectangle.html#%3Cinit%3E(int,int,int,int)) as shown in Margus's example. To replicate the same example with your code, you need to changes / adapt the indexes `x` & `y` to iterate within the `width` & `height` of the `Rectangle` / `ScreenCapture`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T21:04:13.150", "Id": "531531", "Score": "0", "body": "@Doi9t I managed to make it work now but it seems like it only takes one screenshot, I need it to take every frame. Even if the color dissapears from the rectangle now it still says \"Found red color!\". How do I make it take another capture and forget the old one?\nI basically want it to update with a new capture every frame." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T21:13:43.020", "Id": "531532", "Score": "1", "body": "@Golden You can recreate a new capture by recalling the `variable = robot.createScreenCapture(rect);` method at the end of the scan, and restart the loop." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T14:25:36.193", "Id": "269393", "ParentId": "269375", "Score": "2" } } ]
{ "AcceptedAnswerId": "269393", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T21:39:53.150", "Id": "269375", "Score": "3", "Tags": [ "java", "performance", "beginner" ], "Title": "How do I increase the speed of this loop or pixel color finding process?" }
269375
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/a/269309/231235">A recursive_count Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++</a>. A function <code>recursive_depth</code> for calculating depth of nested iterables is mentioned in <a href="https://codereview.stackexchange.com/a/269309/231235">G. Sliepen's answer</a>. I am trying to implement <code>recursive_depth</code> function in this post.</p> <ul> <li><p>Given non-nested types <code>char</code>, <code>int</code>, the outputs of <code>recursive_depth</code> template function are <code>0</code>.</p> </li> <li><p>Given nested types such as <code>std::vector&lt;int&gt;</code>, <code>std::deque&lt;int&gt;</code> and <code>std::list&lt;int&gt;</code>, the outputs of <code>recursive_depth</code> template function are <code>1</code>.</p> </li> <li><p>Given nested types such as <code>std::vector&lt;std::vector&lt;int&gt;&gt;</code>, <code>std::deque&lt;std::deque&lt;int&gt;&gt;</code> and <code>std::list&lt;std::list&lt;int&gt;&gt;</code>, the outputs of <code>recursive_depth</code> template function are <code>2</code>.</p> </li> </ul> <p><strong>The experimental implementation</strong></p> <ul> <li><p><code>recursive_depth</code> function implementation</p> <pre><code>// recursive_depth function implementation template&lt;typename T&gt; constexpr std::size_t recursive_depth() { return 0; } template&lt;std::ranges::input_range Range&gt; constexpr std::size_t recursive_depth() { return recursive_depth&lt;std::ranges::range_value_t&lt;Range&gt;&gt;() + 1; } </code></pre> </li> </ul> <p><strong>The testing code</strong></p> <p>The non-nested type <code>char</code>, non-nested type <code>int</code>, <code>std::vector&lt;int&gt;</code>, <code>std::vector&lt;std::vector&lt;int&gt;&gt;</code>, <code>std::deque&lt;int&gt;</code>, <code>std::deque&lt;std::deque&lt;int&gt;&gt;</code>, <code>std::list&lt;int&gt;</code> and <code>std::list&lt;std::list&lt;int&gt;&gt;</code> are tested.</p> <pre><code>void recursive_depth_test(); int main() { recursive_depth_test(); } void recursive_depth_test() { // non-nested type `char` char test_char = 'A'; std::cout &lt;&lt; recursive_depth&lt;decltype(test_char)&gt;() &lt;&lt; '\n'; // non-nested type `int` int test_int = 100; std::cout &lt;&lt; recursive_depth&lt;decltype(test_int)&gt;() &lt;&lt; '\n'; // std::vector&lt;int&gt; std::vector&lt;int&gt; test_vector{ 5, 7, 4, 2, 8, 6, 1, 9, 0, 3 }; std::cout &lt;&lt; recursive_depth&lt;decltype(test_vector)&gt;() &lt;&lt; '\n'; // std::vector&lt;std::vector&lt;int&gt;&gt; std::vector&lt;decltype(test_vector)&gt; test_vector2{ test_vector , test_vector , test_vector }; std::cout &lt;&lt; recursive_depth&lt;decltype(test_vector2)&gt;() &lt;&lt; '\n'; // 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); std::cout &lt;&lt; recursive_depth&lt;decltype(test_deque)&gt;() &lt;&lt; '\n'; // 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); std::cout &lt;&lt; recursive_depth&lt;decltype(test_deque2)&gt;() &lt;&lt; '\n'; // std::list&lt;int&gt; std::list&lt;int&gt; test_list = { 1, 2, 3, 4, 5, 6 }; std::cout &lt;&lt; recursive_depth&lt;decltype(test_list)&gt;() &lt;&lt; '\n'; // 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 }; std::cout &lt;&lt; recursive_depth&lt;decltype(test_list2)&gt;() &lt;&lt; '\n'; } </code></pre> <p>The output of the testing code above:</p> <pre><code>0 0 1 2 1 2 1 2 </code></pre> <p><a href="https://godbolt.org/z/jTb9jWbca" 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/a/269309/231235">A recursive_count Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <p>The experimental implementation of <code>recursive_depth</code> function is proposed here.</p> </li> <li><p>Why a new review is being asked for?</p> <p>What would you expect the output of <code>std::vector&lt;std::string&gt;</code> case? In this experimental implementation, the output would be <code>2</code>. If there is any possible improvement, please let me know.</p> </li> </ul>
[]
[ { "body": "<p>The implementation is straightforward and correct as far as I can tell.</p>\n<blockquote>\n<p>What would you expect the output of <code>std::vector&lt;std::string&gt;</code> case?</p>\n</blockquote>\n<p>I expect it to be 2, as both <code>std::vector</code> and <code>std::string</code> are ranges. We have had this discussion <a href=\"https://codereview.stackexchange.com/a/252154/129343\">before</a>, and in case you want to have recursion stop when reaching a certain type, you might want to introduce another template, perhaps named <code>recursive_depth_until</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T18:03:20.673", "Id": "269399", "ParentId": "269376", "Score": "1" } } ]
{ "AcceptedAnswerId": "269399", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-25T23:56:04.777", "Id": "269376", "Score": "2", "Tags": [ "c++", "recursion", "template", "c++20" ], "Title": "A recursive_depth function for calculating depth of nested types implementation in C++" }
269376
<p>Created a MongoDB client which is handling the retry in case of server connection failure. Please review and how I can improve further.</p> <pre><code>package db import ( &quot;context&quot; &quot;errors&quot; &quot;log&quot; &quot;time&quot; &quot;go.mongodb.org/mongo-driver/event&quot; &quot;go.mongodb.org/mongo-driver/mongo&quot; &quot;go.mongodb.org/mongo-driver/mongo/options&quot; ) const SupplyReportDB = &quot;abc&quot; const SupplyAlertsCollection = &quot;abc&quot; type MongoDB struct { client *mongo.Client uri string } func NewMongoDBCon(context context.Context, uri string) (*MongoDB, error) { var conn = &amp;MongoDB{uri: uri} client, err := conn.Connect(context) if err != nil { return conn, err } conn.client = client return conn, err } func (m *MongoDB) Connect(context context.Context) (*mongo.Client, error) { serverMonitor := &amp;event.ServerMonitor{ ServerHeartbeatFailed: m.serverHandler, } client, err := mongo.Connect( context, options.Client(). ApplyURI(m.uri). SetHeartbeatInterval(5*time.Second). SetServerMonitor(serverMonitor), ) if err != nil { return client, err } if err := client.Ping(context, nil); err != nil { return client, errors.New(&quot;not connected&quot;) } return client, nil } func (m *MongoDB) Close(context context.Context) error { if err := m.client.Disconnect(context); err != nil { return err } return nil } func (m *MongoDB) GetSupplyAlertCollection() *mongo.Collection { collection := m.client.Database(SupplyReportDB).Collection(SupplyAlertsCollection) return collection } func (m *MongoDB) reconnect() { count := 1 for { if count == 3{ log.Fatal(&quot;Problem in connecting MongoDB.. exiting..&quot;) } log.Println(&quot;Retrying for the &quot;, count, &quot;time&quot;) client, err := m.Connect(context.TODO()) if err != nil { time.Sleep(4 * time.Second) } else { log.Println(&quot;Reconnected successfully.&quot;) m.client = client break } count++ } } func (m *MongoDB)serverHandler(evt *event.ServerHeartbeatFailedEvent) { m.reconnect() } </code></pre>
[]
[ { "body": "<p>I would think about replacing the &quot;for loop&quot; with a retry package <a href=\"https://github.com/avast/retry-go\" rel=\"nofollow noreferrer\">https://github.com/avast/retry-go</a>. Should be a little bit cleaner.</p>\n<pre><code>func (m *MongoDB) reconnect() {\nerr := retry.Do(func() error {\n client, err := mongo.Connect(context.TODO(), m.uri, mongo.ConnectTimeout(5*time.Second))\n if err != nil {\n log.Printf(&quot;Failed to connect to MongoDB at %s: %s&quot;, m.uri, err)\n return err\n }\n log.Println(&quot;Reconnected successfully.&quot;)\n m.client = client\n return nil\n},\n retry.Attempts(3),\n retry.Delay(4*time.Second),\n retry.OnRetry(func(n uint, err error) {\n log.Printf(&quot;Retry %d: %s&quot;, n, err)\n }),\n)\nif err != nil {\n log.Fatal(&quot;Problem in connecting MongoDB.. exiting..&quot;)\n}}\n</code></pre>\n<p>Also using exponential backoff (in the delay) could be an option.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T15:07:08.030", "Id": "269823", "ParentId": "269379", "Score": "2" } } ]
{ "AcceptedAnswerId": "269823", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T05:09:10.803", "Id": "269379", "Score": "0", "Tags": [ "go", "mongodb" ], "Title": "Mongodb connection retry" }
269379
<p>I am attempting to re-implement a <a href="//stackoverflow.com/a/10733621">postponed sieve algorithm </a> for generating prime numbers in Rust. I am able to make a solution that works, but I have to use a couple of <code>.clone()</code> calls which I believe are killing my performance (the Rust solution ends up ~8x slower than the Python solution).</p> <p>I would love some advice on how I can avoid the <code>.clone()</code> calls while avoiding errors from the borrow checker.</p> <pre><code>use std::collections::HashMap; #[derive(Debug, Clone)] struct Primes { i: usize, curr_candidate: u64, next_relevant_prime: u64, next_relevant_prime_squared: u64, sieve: HashMap&lt;u64, u64&gt;, initial_primes: Vec&lt;u64&gt;, internal_primes: Box&lt;Option&lt;Primes&gt;&gt;, } impl Primes { fn new() -&gt; Primes { Primes { i: 0, curr_candidate: 7, next_relevant_prime: 0, next_relevant_prime_squared: 0, sieve: HashMap::new(), initial_primes: vec![2, 3, 5, 7], internal_primes: Box::new(None), } } } impl Iterator for Primes { type Item = u64; fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt; { let len = self.initial_primes.len(); let mut internal_primes; if self.i &lt; len { self.i += 1; return Some(self.initial_primes[self.i - 1]); } else if self.i == len { self.i += 1; internal_primes = Primes::new(); self.internal_primes = Box::new(Some(internal_primes.clone())); internal_primes.next(); // skip 2 self.next_relevant_prime = internal_primes.next().unwrap(); self.next_relevant_prime_squared = self.next_relevant_prime.pow(2); } else { internal_primes = self.internal_primes.clone().unwrap(); } let mut i = self.curr_candidate; loop { i += 2; let step; if self.sieve.contains_key(&amp;i) { // composite step = self.sieve.remove(&amp;i).unwrap(); } else if i &lt; self.next_relevant_prime_squared { // prime // save state for next round self.curr_candidate = i; self.internal_primes = Box::new(Some(internal_primes)); return Some(i); } else { // i == next_relevant_prime_squared step = 2 * self.next_relevant_prime; self.next_relevant_prime = internal_primes.next().unwrap(); self.next_relevant_prime_squared = self.next_relevant_prime.pow(2); } let mut j = i; j += step; while self.sieve.contains_key(&amp;j) { j += step; } self.sieve.insert(j, step); } } } fn main() { let mut primes = Primes::new(); for _i in 0..99_999 { primes.next(); } println!(&quot;The 100,000th prime is {}&quot;, primes.next().unwrap()) } </code></pre>
[]
[ { "body": "<p>A normal Sieve of Eratosthenes would look like:</p>\n<pre><code>fn primes(n: usize) -&gt; impl Iterator&lt;Item = usize&gt; {\n const START: usize = 2;\n if n &lt; START {\n Vec::new()\n } else {\n let mut is_prime = vec![true; n + 1 - START];\n let limit = (n as f64).sqrt() as usize;\n for i in START..limit + 1 {\n let mut it = is_prime[i - START..].iter_mut().step_by(i);\n if let Some(true) = it.next() {\n it.for_each(|x| *x = false);\n }\n }\n is_prime\n }\n .into_iter()\n .enumerate()\n .filter_map(|(e, b)| if b { Some(e + START) } else { None })\n}\n</code></pre>\n<blockquote>\n<ol>\n<li>Starting at an offset of 2 means that an <code>n &lt; 2</code> input requires zero allocations because <code>Vec::new()</code> doesn't allocate memory until elements are pushed into it.</li>\n<li>Using Vec as an output to the <code>if .. {} else {}</code> condition means the output is statically deterministic, avoiding the need for a boxed trait object.</li>\n<li>Iterating is_prime with <code>.iter_mut()</code> and then using <code>.step_by(i)</code> makes all the optimizations required, and removes a lot of tediousness.</li>\n<li>Returning <code>impl Iterator</code> allows for static dispatching instead of dynamic dispatching, which is possible because the type is now statically known at compile-time, making the zero input/output condition order of magnitude faster.</li>\n</ol>\n</blockquote>\n<p>If you need to calculate primes as the range increases above 10's of millions then check out <a href=\"https://rosettacode.org/wiki/Sieve_of_Eratosthenes#Unbounded_Page-Segmented_bit-packed_odds-only_version_with_Iterator\" rel=\"nofollow noreferrer\">https://rosettacode.org/wiki/Sieve_of_Eratosthenes#Unbounded_Page-Segmented_bit-packed_odds-only_version_with_Iterator</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T15:59:10.647", "Id": "531507", "Score": "2", "body": "Thank you for the answer Margus. I know that what you posted is the more standard sieve, however, I think you'll find the algorithm I posted about is more memory efficient, and faster (at least in python and Julia) than the standard sieve. I am implementing it mainly as an exercise in Rust, so I am more interested in an answer which helps me understand how to implement the algorithm I shared rather than how to implement a totally different algorithm." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T14:01:45.070", "Id": "269392", "ParentId": "269380", "Score": "0" } }, { "body": "<p>I was able to avoid the calls to <code>.clone()</code> with two changes.</p>\n<p>First, we can avoid setting</p>\n<pre><code>self.internal_primes = Box::new(Some(internal_primes.clone()));\n</code></pre>\n<p>at all, and instead delay assigning <code>internal_primes</code> to <code>self.internal_primes</code> until right before the function returns. This avoids having multiple mutable references to the same <code>Primes</code> instance.</p>\n<p>Second, we can use the other <code>.clone()</code> call by using <code>mem::replace</code>:</p>\n<pre><code>internal_primes = mem::replace(&amp;mut self.internal_primes, Box::new(None)).unwrap();\n</code></pre>\n<p>I also realized that <code>cargo run</code> is running in debug mode (at least for my project), which is much slower than I would have though. Compiling for release mode ends up being much faster regardless of whether we use <code>.clone()</code> (although it's still about 2x faster to avoid them):</p>\n<pre><code>$ cargo build --release\n$ time ./target/release/primes\nThe 100,000th prime is 1299709\n./target/release/primes 0.07s user 0.00s system 34% cpu 0.216 total\n</code></pre>\n<p>The final version of the code:</p>\n<pre><code>use std::collections::HashMap;\nuse std::mem;\n\n#[derive(Debug, Clone)]\nstruct Primes {\n i: usize,\n curr_candidate: u64,\n next_relevant_prime: u64,\n next_relevant_prime_squared: u64,\n sieve: HashMap&lt;u64, u64&gt;,\n initial_primes: Vec&lt;u64&gt;,\n internal_primes: Box&lt;Option&lt;Primes&gt;&gt;,\n}\n\nimpl Primes {\n fn new() -&gt; Primes {\n Primes {\n i: 0,\n curr_candidate: 7,\n next_relevant_prime: 0,\n next_relevant_prime_squared: 0,\n sieve: HashMap::new(),\n initial_primes: vec![2, 3, 5, 7],\n internal_primes: Box::new(None),\n }\n }\n}\n\nimpl Iterator for Primes {\n type Item = u64;\n\n fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt; {\n let len = self.initial_primes.len();\n let mut internal_primes;\n if self.i &lt; len {\n self.i += 1;\n return Some(self.initial_primes[self.i - 1]);\n } else if self.i == len {\n self.i += 1;\n internal_primes = Primes::new();\n internal_primes.next(); // skip 2\n self.next_relevant_prime = internal_primes.next().unwrap();\n self.next_relevant_prime_squared = self.next_relevant_prime.pow(2);\n } else {\n internal_primes = mem::replace(&amp;mut self.internal_primes, Box::new(None)).unwrap();\n }\n let mut i = self.curr_candidate;\n loop {\n i += 2;\n let step;\n if self.sieve.contains_key(&amp;i) {\n // composite\n step = self.sieve.remove(&amp;i).unwrap();\n } else if i &lt; self.next_relevant_prime_squared {\n // prime\n // save state for next round\n self.curr_candidate = i;\n self.internal_primes = Box::new(Some(internal_primes));\n return Some(i);\n } else {\n // i == next_relevant_prime_squared\n step = 2 * self.next_relevant_prime;\n self.next_relevant_prime = internal_primes.next().unwrap();\n self.next_relevant_prime_squared = self.next_relevant_prime.pow(2);\n }\n let mut j = i;\n j += step;\n while self.sieve.contains_key(&amp;j) {\n j += step;\n }\n self.sieve.insert(j, step);\n }\n }\n}\n\nfn main() {\n let mut primes = Primes::new();\n for _i in 0..99_999 {\n primes.next();\n }\n println!(&quot;The 100,000th prime is {}&quot;, primes.next().unwrap())\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T19:15:38.610", "Id": "531676", "Score": "0", "body": "One more idiomatic thing would be to do `primes.nth(10_000).unwrap()` to get the 10,000th prime, rather than the useless loop." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T01:55:15.843", "Id": "269405", "ParentId": "269380", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T05:39:00.437", "Id": "269380", "Score": "2", "Tags": [ "performance", "primes", "rust", "memory-management" ], "Title": "Generating prime numbers quickly in rust" }
269380
<p>This is a <a href="https://fiks.fit.cvut.cz/files/tasks/season8/round1/sponzori.pdf" rel="nofollow noreferrer">programming challenge</a> in Czeck. My translation follows.</p> <p><strong>Does anyone know what the time complexity of my code is?</strong></p> <p><strong>Input:</strong> The first line contains 2 integers: the number of animals 1 ≤N ≤100 and the number of their potential sponsors 1 ≤M ≤200. The following are N lines with information about each animal: the unique integer ID of the nth animal 0 ≤In &lt;N and its one-word name. Animal names are also unique. Behind them are M lines with information about potential sponsors. Each line begins with the first name of the m-th sponsor and the number of animals 1 ≤Pm≤N, one of which is one willing to sponsor. The Pm ID of these animals follows. The first name of each sponsor is always unique.</p> <p><strong>Output:</strong> On the first line, write Yes, if all the animals find a sponsor, No otherwise. For all the animals for which you have found a sponsor, write the name of the animal on a separate line and the name of his sponsor separated by a space. Sort the rows in ascending alphabetical order by name animal. The task can have more than one correct solution, write any of them.</p> <p><strong>Example:</strong></p> <pre><code>input: 7 8 1 cow 0 elephant 3 pig 2 gorilla 5 rhinoceros 6 tapir 4 kangaroo Celestin 3 0 1 3 Hubert 2 4 5 Emma 2 4 6 Felix 1 6 Bert 4 0 1 2 6 Anna 5 0 2 3 4 5 Denis 1 6 Gustav 1 6 Output: No gorilla Bert kangaroo Emma elephant Celestina pig Anna rhinoceros Hubert tapir Felix </code></pre> <p><strong>Code:</strong></p> <pre class="lang-java prettyprint-override"><code>import java.util.*; class Animals { //S is number of sponsors, A is number of animals static int S = 0; static int A = 0; //DFS boolean bpm(boolean bpGraph[][], int u, boolean seen[], int matchR[]){ for (int v = 0; v &lt; A; v++){ //does the sponsor want to sponsor this animal? if (bpGraph[u][v] &amp;&amp; !seen[v]) { seen[v] = true; if (matchR[v] &lt; 0 || bpm(bpGraph, matchR[v], seen, matchR)){ matchR[v] = u; return true; } } } return false; } // returns an array of which sponsor sponsors what animal int[] maxBPM(boolean bpGraph[][]) { int matchR[] = new int[A]; for(int i = 0; i &lt; A; ++i) matchR[i] = -1; for (int a = 0; a &lt; S; a++){ //indicate that no animal have been seen yet boolean seen[] =new boolean[A]; for(int i = 0; i &lt; A; ++i) seen[i] = false; //find if animal &quot;a&quot; can get sponsor bpm(bpGraph, a, seen, matchR); } return matchR; } public static void main (String[] args){ //input Scanner scn = new Scanner(System.in); List&lt;Animal&gt; animalsID = new ArrayList&lt;&gt;(); System.out.println(&quot;Input: &quot;); A = scn.nextInt(); S = scn.nextInt(); scn.nextLine(); boolean bpGraph[][] = new boolean[S][A]; //load animals for (int i = 0; i &lt; A; i++) { int id = scn.nextInt(); String name = scn.next(); scn.nextLine(); animalsID.add(new Animal(id, name)); } //load sponsors String namesSponsors[] = new String[S]; for (int i = 0; i &lt; S; i++) { namesSponsors[i] = scn.next(); int numberCanSponsor = scn.nextInt(); for (int j = 0; j &lt; numberCanSponsor; j++) { bpGraph[i][scn.nextInt()] = true; } scn.nextLine(); } //BPM Animals a = new Animals(); int[] result = a.maxBPM(bpGraph); //output System.out.println(&quot;\Output:&quot;); boolean allAnimalsAreSponsored = true; for (int i : result) { if (i == -1){ allAnimalsAreSponsored = false; } } if (allAnimalsAreSponsored){ System.out.println(&quot;Yes&quot;); }else{ System.out.println(&quot;No&quot;); } for (int i = 0; i &lt; A; i++) { if (result[i] != -1){ for (Animal animal : animalsID) { if (animal.getId() == i) { System.out.print(animal.getName() + &quot; &quot;); } } System.out.println(namesSponsors[result[i]]); } } } } public class Animal { private int id; private String name; Animal(int id, String name){ this.id = id; this.name = name; } int getId(){ return id; } String getName(){ return name; } } </code></pre> <p>I'm a beginner, so the code looks awful. But I tried to make some comments.</p> <p>Do you have any suggestions on how to simplify the script?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T12:09:31.143", "Id": "531484", "Score": "2", "body": "Welcome to Code Review. Can you include the class Animal, please? Even if very simple, it is better to include the complete code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T12:35:32.667", "Id": "531487", "Score": "0", "body": "ok, i included the animal class" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T12:36:11.097", "Id": "531488", "Score": "0", "body": "The problem description is written in different language." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T12:37:06.750", "Id": "531489", "Score": "0", "body": "Google translate should be adequate..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T12:38:49.847", "Id": "531490", "Score": "0", "body": "ok, here is the problem description, but you need to use translator: https://fiks.fit.cvut.cz/files/tasks/season8/round1/sponzori.pdf" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T14:41:10.240", "Id": "531499", "Score": "0", "body": "There are other important problem constraints that you have not included: for a compliant solution, every sponsor must have between 0 and 1 assigned animals. Try to connect sponsors and animals to have as many animals as possible sponsored. Every animal only needs one sponsor." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T15:30:38.370", "Id": "531505", "Score": "0", "body": "I generated all the possible combinations that could potentially occur and then I looked for the largest possible combination. I can't think of another way of connecting animals with sponsors." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T16:21:31.387", "Id": "531511", "Score": "2", "body": "[This](https://en.wikipedia.org/wiki/Maximum_cardinality_matching) may be of interest." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T16:48:41.773", "Id": "531512", "Score": "0", "body": "Thank you so much for that algorithm. I will try to implement it and post it here tommorow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T07:24:12.477", "Id": "531555", "Score": "0", "body": "I have updated the code. Now i am using Ford-Fulkerson Algorithm. If you have any more suggestions how to improve the code please write it." } ]
[ { "body": "<p>My Java is rusty so I spent (a lot of!) time brushing up on some OpenJDK 16 topics. Starting with your existing program,</p>\n<ul>\n<li><code>Animals</code> is not really a good representation of a class. It's non-reentrant, since <code>S</code> and <code>A</code> are statics, so it will be difficult to test.</li>\n<li>Your variable names <code>S</code>, <code>A</code>, <code>v</code>, <code>u</code> etc. are very difficult to understand and shouldn't be so abbreviated. Prefer instead something like <code>nSponsors</code> etc.</li>\n<li>If I understand your algorithm correctly, you're assuming that the animal IDs are contiguous integers starting at 0. This does seem to be guaranteed by the specification but you haven't included it in your translation.</li>\n<li>You have a class for <code>Animal</code> but not for <code>Sponsor</code> - this seems inconsistent.</li>\n<li>Overall your <code>main</code> does way too much, and needs to be split out into multiple separate methods and classes.</li>\n<li>There are some places where this program can make use of Java streams - for example, you can write a parser for animals like</li>\n</ul>\n<pre><code> private static final Collector&lt;Animal, ?, Map&lt;Integer, Animal&gt;&gt;\n mapCollector = Collectors.toUnmodifiableMap(v -&gt; v.id, v -&gt; v);\n\n public static Map&lt;Integer, Animal&gt; parseAll(Scanner in, int n) {\n /* Parse n animals from n lines of the input stream.\n Validate that each line is well-formed and that the IDs are unique.\n */\n return Stream\n .generate(() -&gt; parse(in))\n .limit(n)\n .collect(mapCollector);\n }\n</code></pre>\n<p>and so on.</p>\n<ul>\n<li>Add some Jupiter unit tests. This program should be testable and tested and it doesn't currently seem like either is true.</li>\n<li>It will be a challenge, but I encourage you to attempt a custom <code>Spliterator</code> implementation of your algorithm. Spliterators are a simple but powerful concept - choose an algorithm that can be segmented, and then tell Java how to segment it and let it run on multiple cores. The basic class signature can look like</li>\n</ul>\n<pre><code>public class Solver implements Spliterator&lt;Solution&gt; {\n protected final List&lt;List&lt;Sponsor&gt;&gt; sponsorOptions;\n\n @Override\n public int characteristics() {\n return DISTINCT | NONNULL | IMMUTABLE;\n }\n\n @Override\n public long estimateSize() {\n /* For each animal: combinations with no repetition, with some\n simplifying assumptions like: All sponsors are available for\n selection at a given animal, regardless of previous selections.\n This is an upper bound.\n */\n long upper = sponsorOptions.stream()\n .mapToLong(Collection::size)\n .reduce(1, (x, y) -&gt; x*y);\n return upper;\n }\n\n @Override\n public boolean tryAdvance(Consumer&lt;? super Solution&gt; consumer) {\n // Call consumer() with the next possible solution value and return true\n }\n\n @Override\n public Spliterator&lt;Solution&gt; trySplit() {\n // Reduce the search space of this instance by half, and return the second half in a new instance of this class\n }\n}\n</code></pre>\n<p>When I used your sample input problem and wrote a (brute-force, not Ford-Fulkerson) implementation, it shows how the Java reference <code>StreamSupport</code> segments your search space:</p>\n<pre><code>Split at depth 0, 4 -&gt; 2, 2\nSplit at depth 0, 2 -&gt; 1, 1\nSplit at depth 0, 2 -&gt; 1, 1\nSplit at depth 1, 3 -&gt; 1, 2\nSplit at depth 1, 3 -&gt; 1, 2\nSplit at depth 1, 3 -&gt; 1, 2\nSplit at depth 2, 3 -&gt; 1, 2\nSplit at depth 1, 3 -&gt; 1, 2\nSplit at depth 2, 3 -&gt; 1, 2\nSplit at depth 1, 2 -&gt; 1, 1\nSplit at depth 1, 2 -&gt; 1, 1\nSplit at depth 1, 2 -&gt; 1, 1\nSplit at depth 2, 3 -&gt; 1, 2\nSplit at depth 2, 2 -&gt; 1, 1\nSplit at depth 2, 3 -&gt; 1, 2\nSplit at depth 2, 3 -&gt; 1, 2\nSplit at depth 2, 2 -&gt; 1, 1\nSplit at depth 2, 2 -&gt; 1, 1\nSplit at depth 2, 2 -&gt; 1, 1\nSplit at depth 2, 3 -&gt; 1, 2\nSplit at depth 2, 2 -&gt; 1, 1\nSplit at depth 2, 2 -&gt; 1, 1\nSplit at depth 2, 3 -&gt; 1, 2\nSplit at depth 2, 2 -&gt; 1, 1\nSplit at depth 2, 3 -&gt; 1, 2\nSplit at depth 2, 3 -&gt; 1, 2\nSplit at depth 2, 2 -&gt; 1, 1\nSplit at depth 2, 2 -&gt; 1, 1\nSplit at depth 1, 2 -&gt; 1, 1\nSplit at depth 2, 3 -&gt; 1, 2\nSplit at depth 2, 3 -&gt; 1, 2\nSplit at depth 2, 2 -&gt; 1, 1\nSplit at depth 2, 3 -&gt; 1, 2\nSplit at depth 2, 2 -&gt; 1, 1\nSplit at depth 2, 2 -&gt; 1, 1\nSplit at depth 3, 3 -&gt; 1, 2\nSplit at depth 4, 4 -&gt; 2, 2\nSplit at depth 3, 2 -&gt; 1, 1\nSplit at depth 4, 2 -&gt; 1, 1\nSplit at depth 4, 4 -&gt; 2, 2\nSplit at depth 4, 2 -&gt; 1, 1\nSplit at depth 5, 3 -&gt; 1, 2\nSplit at depth 5, 3 -&gt; 1, 2\nSplit at depth 4, 2 -&gt; 1, 1\nSplit at depth 5, 2 -&gt; 1, 1\nSplit at depth 5, 2 -&gt; 1, 1\nSplit at depth 5, 3 -&gt; 1, 2\nSplit at depth 5, 2 -&gt; 1, 1\nSplit at depth 5, 3 -&gt; 1, 2\nSplit at depth 5, 3 -&gt; 1, 2\nSplit at depth 4, 4 -&gt; 2, 2\nSplit at depth 5, 3 -&gt; 1, 2\nSplit at depth 4, 2 -&gt; 1, 1\nSplit at depth 5, 2 -&gt; 1, 1\nSplit at depth 5, 2 -&gt; 1, 1\nSplit at depth 5, 2 -&gt; 1, 1\nSplit at depth 4, 2 -&gt; 1, 1\nSplit at depth 5, 3 -&gt; 1, 2\nSplit at depth 4, 2 -&gt; 1, 1\nSplit at depth 5, 3 -&gt; 1, 2\nSplit at depth 5, 3 -&gt; 1, 2\nSplit at depth 5, 2 -&gt; 1, 1\nSplit at depth 5, 2 -&gt; 1, 1\nSplit at depth 5, 2 -&gt; 1, 1\nSplit at depth 5, 3 -&gt; 1, 2\nSplit at depth 5, 2 -&gt; 1, 1\nSplit at depth 5, 3 -&gt; 1, 2\nSplit at depth 5, 3 -&gt; 1, 2\nSplit at depth 5, 2 -&gt; 1, 1\nSplit at depth 5, 2 -&gt; 1, 1\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T02:53:15.167", "Id": "269486", "ParentId": "269388", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T10:45:32.683", "Id": "269388", "Score": "3", "Tags": [ "java", "beginner", "algorithm", "programming-challenge" ], "Title": "Find potentional sponsor for every animal" }
269388
<p>I am new to using interfaces and abstract classes. The team I am working with came up with an implementation of what they call a base class that will be implemented by all view model classes. This is what they came up with:</p> <pre><code> public interface IBaseViewModel&lt;T&gt; { #region public properties string Message { get; set; } string SaveType { get; set; } bool IsVisibleMessage { get; set; } bool IsVisibleDecision { get; set; } bool IsApiSuccess { get; set; } Guid EntityId { get; set; } string EntityQDSId { get; set; } string EntityType { get; set; } #endregion #region public methods Task Init(); Task Init(Guid Id); Task&lt;T&gt; Create(); Task&lt;T&gt; Get(Guid Id); Task&lt;T&gt; Get(string Id); Task&lt;IEnumerable&lt;T&gt;&gt; GetList(Guid Id); Task&lt;IEnumerable&lt;T&gt;&gt; GetList(string Id); Task&lt;T&gt; Insert(T t); Task&lt;T&gt; Update(Guid Id, T t); Task&lt;T&gt; Delete(Guid Id); void Dispose(); #endregion } public abstract class BaseViewModel&lt;T&gt; : IBaseViewModel&lt;T&gt;, IDisposable { public Guid EntityId { get; set; } public string EntityQDSId { get; set; } public string EntityType { get; set; } public string Message { get; set; } public string SaveType { get; set; } public bool IsVisibleMessage { get; set; } public bool IsVisibleDecision { get; set; } public bool IsApiSuccess { get; set; } public virtual Task Init() { return Task.FromResult&lt;T&gt;(default); } public virtual Task Init(Guid Id) { return Task.FromResult&lt;T&gt;(default); } public virtual Task&lt;T&gt; Create() { return Task.FromResult&lt;T&gt;(default); } public virtual Task&lt;T&gt; Get(Guid Id) { return Task.FromResult&lt;T&gt;(default); } public virtual Task&lt;T&gt; Get(string Id) { return Task.FromResult&lt;T&gt;(default); } public virtual Task&lt;IEnumerable&lt;T&gt;&gt; GetList(Guid Id) { return Task.FromResult&lt;IEnumerable&lt;T&gt;&gt;(default); } public virtual Task&lt;IEnumerable&lt;T&gt;&gt; GetList(string Id) { return Task.FromResult&lt;IEnumerable&lt;T&gt;&gt;(default); } public virtual Task&lt;IEnumerable&lt;T&gt;&gt; GetForGrid(Guid Id) { return Task.FromResult&lt;IEnumerable&lt;T&gt;&gt;(default); } public virtual Task&lt;T&gt; Insert(T t) { return Task.FromResult&lt;T&gt;(default); } public virtual Task&lt;T&gt; Update(Guid Id, T t) { return Task.FromResult&lt;T&gt;(default); } public virtual Task&lt;T&gt; Delete(Guid Id) { return Task.FromResult&lt;T&gt;(default); } public virtual void ProcessDto(T t) { } public virtual void Dispose() { } } public interface IAccountBillViewModel&lt;T&gt; : IBaseViewModel&lt;AccountBillGroup&gt; { } </code></pre> <p>Below is the implementation:</p> <pre><code> public class AccountBillViewModel&lt;T&gt; : BaseViewModel&lt;AccountBillGroup&gt;, IAccountBillViewModel&lt;AccountBillGroup&gt; { } </code></pre> <p>In researching this question I found several comments like the one below</p> <p><a href="https://stackoverflow.com/a/479154">https://stackoverflow.com/a/479154</a> [@Alex][1]</p> <p>My points:</p> <p>Since there was only code signatures and no implementations of any code in the abstract class and because you can inherit from multiple interfaces, why use an abstract class instead of a interface? The inheritance slot will be left open in case we wanted to inherit from another class in the future. Their points:</p> <p>The properties only need to be implemented in the base class and those properties will be available in all implementations without declaring the properties again. Only those methods that need to be used in the implementation need to be overridden. If an interface was used all the methods would have to be implemented in every implementation. Is there value in choosing to go with an abstract base class when there is not implementations, only method signatures?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T13:15:56.720", "Id": "531494", "Score": "3", "body": "Rather than a review of the existing code, you appear to be looking for a discussion around the relative merits of interfaces Vs abstract base classes..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T13:26:48.137", "Id": "531495", "Score": "0", "body": "_\"Since there was only code signatures and no implementations of any code in the abstract class and because you can inherit from multiple interfaces, why use an abstract class instead of a interface?\"_ This question used to be easy to answer (abstract classes can have default implementations), but since the advent of default implementations being allowed on interfaces, I get the feeling that the distinction between abstract classes and interfaces has mostly faded, in favor of interfaces. I have not found a conventionally agreed upon update to this advice since this feature has been introduced." } ]
[ { "body": "<p>The implementation must not have the generic type parameter <code>T</code>, because it is implementing <code>BaseViewModel&lt;T&gt;</code> with the concrete type <code>AccountBillGroup</code> supplemented for <code>T</code>. The same holds for the interface <code>IAccountBillViewModel</code>.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public interface IAccountBillViewModel : IBaseViewModel&lt;AccountBillGroup&gt;\n{\n}\n\npublic class AccountBillViewModel : \n BaseViewModel&lt;AccountBillGroup&gt;, IAccountBillViewModel\n{\n}\n</code></pre>\n<p>So, what the interface <code>IAccountBillViewModel</code> and the class <code>AccountBillViewModel</code> really do, is to nail down the generic type parameter <code>AccountBillGroup</code>.</p>\n<p>Now, in the class <code>AccountBillViewModel</code> the methods are implemented with all the <code>T</code>s substiuted by <code>AccountBillGroup</code></p>\n<pre class=\"lang-cs prettyprint-override\"><code>public virtual Task&lt;AccountBillGroup&gt; Insert(AccountBillGroup t)\n{\n return Task.FromResult&lt;AccountBillGroup&gt;(default);\n}\n</code></pre>\n<p>You don't see this implementation which is done automatically in the background, but IntelliSense will show you the signatures of these methods with this substitution applied.</p>\n<p>The <code>T</code> in <code>class AccountBillViewModel&lt;T&gt;</code> is unrelated to the <code>T</code> in the interface and introduces a new type parameter which remains unused in your implementation. Therefore, e.g., <code>AccountBillViewModel&lt;int&gt;</code> would still implement <code>BaseViewModel&lt;AccountBillGroup&gt;</code>! <code>T</code> is not only obsolete, it is misleading and wrong.</p>\n<hr />\n<blockquote>\n<p>Since there was only code signatures and no implementations of any code in the abstract class ...</p>\n</blockquote>\n<p>This is a wrong statement. The abstract class does implement the properties and the methods. If it wouldn't, these members would have to be marked as <code>abstract</code>.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public abstract class BaseViewModel&lt;T&gt; : IBaseViewModel&lt;T&gt;, IDisposable\n{\n public abstract string Message { get; set; }\n\n public abstract Task Init();\n\n ...\n}\n</code></pre>\n<p>The properties are implemented as auto-properties. This means that the compiler is providing the implementation.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>// In a class this ...\npublic string Message { get; set; }\n\n// ...is equivalent to\nprivate string _message;\npublic string Message {\n get { return _message; }\n set { _message = value; }\n}\n</code></pre>\n<p>Some of the methods have an empty body. This does not mean that they are not implemented. It means that the implementation consists of doing nothing. E.g. it makes sense to implement <code>void Dispose()</code> with an empty body, when there is nothing to be disposed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T13:14:32.747", "Id": "269391", "ParentId": "269390", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T12:35:12.037", "Id": "269390", "Score": "-1", "Tags": [ "c#", "interface" ], "Title": "implementing abstract classes vs interfaces" }
269390
<p>So I'm making a utility class to find resources and read them as JSON objects using the GSON library, the code below is working good but I don't really know how good it is, so I would like to get opinions about it and maybe some things I can improve and make it more efficient?</p> <pre><code>public abstract class ResourceManager { private final String resourcesDirectoryName; public ResourceManager(String resourcesDirectoryName) { this.resourcesDirectoryName = resourcesDirectoryName; } public void findAndReadResources() { Map&lt;String, JsonElement&gt; loader = new HashMap&lt;&gt;(); InputStream resourcesDirectoryStream = this.getClass().getClassLoader().getResourceAsStream(resourcesDirectoryName); if(resourcesDirectoryStream != null) { Scanner resourcesDirectoryReader = new Scanner(resourcesDirectoryStream); while(resourcesDirectoryReader.hasNextLine()) { String resourceFileName = resourcesDirectoryReader.nextLine(); InputStream resourceFileStream = JTasks.class.getClassLoader().getResourceAsStream( resourcesDirectoryName + &quot;\\&quot; + resourceFileName); if(resourceFileStream != null) { Reader resourceFileReader = new InputStreamReader(resourceFileStream); loader.put(resourceFileName, JsonParser.parseReader(resourceFileReader)); } } this.readResources(loader); } } protected abstract void readResources(Map&lt;String, JsonElement&gt; loader); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T15:53:43.503", "Id": "531506", "Score": "1", "body": "Could you please provide a class that inherits from this class as well?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T16:10:23.400", "Id": "531510", "Score": "0", "body": "```\npublic class JsonsResourceManager extends ResourceManager {\n\n public JsonsResourceManager() {\n super(\"jsons\");\n }\n\n @Override\n protected void readResources(Map<String, JsonElement> loader) {\n loader.forEach((string, jsonElement) -> {\n System.out.println(string);\n System.out.println(jsonElement);\n });\n }\n}\n```\nDon't really know how it'll help you, but here's an example." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T19:50:25.680", "Id": "531520", "Score": "0", "body": "I meant that you should add the code to the question. When we are asked to make code more efficient, the more code there is to review the better we can help with efficiency." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T09:02:02.860", "Id": "531633", "Score": "0", "body": "The names like `resourcesDirectoryName` imply that the resources are plain files in the filesystem. On the other hand, `getResourceAsStream()` often accesses e.g. Jar file contents. What is your use case?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T14:52:27.377", "Id": "269394", "Score": "0", "Tags": [ "java", "json", "gson" ], "Title": "Resource manager code improvement" }
269394
<p>Yesterday I posted my first solution to an interview problem here. I am now aware that I have many weak spots in Java and need to do extensive review before tackling any more interviews. Having said that, piecing together what people on here mentioned, I have come to what I hope is a good solution, and am asking to have it reviewed again.</p> <p>Here is the problem:</p> <blockquote> <p>You've gone back in time to 500BC Athens and Socrates wants you to build him an app to help classify animals.</p> <ol> <li>Build the classes <code>Animal</code>, <code>Cat</code>, and <code>Bug</code>.</li> <li>Define the properties &quot;<code>color</code>&quot; and &quot;<code>leg_number</code>&quot; on the relevant and necessary classes. Have them be initialized within a constructor.</li> <li>Add the functionality that would allow us to call a method &quot;<code>move</code>&quot; with the <code>Cat</code> and <code>Bug</code> classes. Have the method return a string &quot;I'm moving with <code>&lt;number of legs&gt;</code> legs!&quot;, with the &quot;<code>&lt;number of legs&gt;</code>&quot; being <code>leg_number</code> as set on the class.</li> <li>Add a new class called <code>Bird</code>. Add the property &quot;<code>wing_number</code>&quot;. Add the functionality that would allow us to call a method &quot;<code>move</code>&quot; with the <code>Bird</code> class. Have the method return the string &quot;I'm moving with <code>&lt;number of legs&gt;</code> legs!&quot; if <code>wing_number</code> doesn't have an applicable value. If <code>wing_number</code> does have an applicable value, return the string &quot;I'm flying&quot;.</li> </ol> </blockquote> <p>Here was my final solution that I submitted:</p> <pre><code>public class SocratesApp { public static void main(String[] args) { Cat myCat = new Cat(); System.out.println(myCat.move()); Bug myBug = new Bug(); System.out.println(myBug.move()); Bird myBird1 = new Bird(2); System.out.println(myBird1.move()); Bird myBird2 = new Bird(0); System.out.println(myBird2.move()); } } class Animal { protected String color; protected int leg_number; public Animal() { } public String move() { return &quot;I'm walking with &quot; + leg_number + &quot; legs!&quot;; } } class Cat extends Animal { public Cat() { color = &quot;orange&quot;; leg_number = 4; } } class Bug extends Animal { public Bug() { color = &quot;green&quot;; leg_number = 6; } } class Bird extends Animal { private int wing_number; public Bird(int wing_number) { color = &quot;yellow&quot;; leg_number = 2; this.wing_number = wing_number; } // @Override public String move() { if (this.wing_number &gt; 0) { return &quot;I'm flying&quot;; } else { return &quot;I'm walking with &quot; + leg_number + &quot; legs!&quot;; } } } </code></pre> <p>A couple of observations of my one:</p> <p>First, since this consists of a superclass and subclasses, I thought I was required to reference the superclass constructor in my subclass constructors with super(). However, I found out the code worked without it. I don't know if I was wrong about this requirement or if it was an old requirement that changed with the evolution of Java.</p> <p>Second, I thought that the @Override decoration was required for the move() method in the Bird class due to the move() method in the Animal superclass. However, the code works without it. I'm thinking now that because the move() method in Bird has a parameter and the one in Animal does not, the Bird one does not constitute a true override of the Animal one.</p> <p>Third, I was sure that to instantiate my different objects, the instantiation would somehow have to include the Animal superclass. When reviewing code examples on the web, I would see superclasses referenced like <code>Animal myCat = new Cat()</code> or, I think, <code>Cat myCat = new Animal()</code>, maybe one other way of referencing Animal that I don't remember. It turns out that <code>Cat myCat = new Cat()</code> was the only one that worked correctly. I'm not sure what the difference is between the code examples I saw on the Internet and my code, but I went with what worked.</p> <p>Any comments on my observations as well as my code are welcome.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T05:35:56.423", "Id": "531542", "Score": "0", "body": "I am so glad I never had to do a code interview. I have been writing code since the '70s (and still am). Solving problems is a worthwhile skill to test, checking your skills as a compiler is a waste of time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T08:06:47.733", "Id": "531558", "Score": "0", "body": "OT, but Socrates won't be born for another 30 years in 500 BC" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T08:26:49.907", "Id": "531559", "Score": "0", "body": "The fourth requirement is weird to me. As far as I know, all birds have two wings (unless they have a birth defect, mutation, or are mutilated). Not all birds fly, though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T08:55:24.417", "Id": "531563", "Score": "0", "body": "I'd find somewhere else to apply to. Animal inheritance is a very poor fit for Java inheritance and is a terrible programming challenge to give to candidates. Only birds without wings walk? Penguins and ostriches have wings, they just don't use them to fly!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T14:46:43.217", "Id": "531584", "Score": "0", "body": "_\"However, the code works without it. I'm thinking now that because the move() method in Bird has a parameter and the one in Animal does not\"_ Was this edited out? Because both methods have no parameters." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T15:26:59.787", "Id": "531589", "Score": "0", "body": "Having Bird extend Animal is a violation of the liskov substitution principle. The interview's purpose probably was to find out, whether you realize this. To actually solve this properly, you have to extract the move method to a common interface, which is not bound to Animal." } ]
[ { "body": "<p>This is better, but you are still missing a lot of basic ideas. I'm going to continue to approach the code review by looking at concepts and suggesting what you need to consider and what you should probably review in your learning, rather than by doing line-wise analysis and suggesting alternatives.</p>\n<ol>\n<li>Will you ever want to instantiate a generic Animal object? I don't think so. So what should you do about the Animal class?</li>\n<li>Are all cats orange, all bugs green and all birds yellow?</li>\n<li>Do all cats have 4 legs? I've encountered 3-legged cats before.</li>\n<li>I assume bugs includes ants, spiders and millipedes. They don't all have 6 legs.</li>\n<li>The <code>move()</code> method in Bird doesn't have a parameter. You should review your understanding of Java terminology, or you won't look very clever in an interview.</li>\n<li>Wingless birds walk like the other Animals. So what does that suggest about the &quot;zero wings&quot; path in the <code>move()</code> method?</li>\n</ol>\n<p>Regarding calling the constructor of the superclass - given that the Animal constructor does nothing, what value would calling it serve? An empty constructor may as well be omitted, if it is the only constructor for a class.</p>\n<p>The Animal constructor could serve more purpose if you made the color and number of legs fields private, and set them in the Animal constructor. (Incidentally, calling it <code>legNumber</code> would be more in keeping with Java conventions, while calling it <code>numberOfLegs</code> might be more expressive. The same applies to number of wings. However, if that's the way the exercise was worded, I suppose you should follow the direction given - though it makes me less confident about the Java expertise of the assignment setter.)</p>\n<p>The <code>@Override</code> annotation is documentation, and if omitted may lead to compiler warnings. Leaving it out won't cause your code to fail.</p>\n<p>Your third question shows a lack of understanding of polymorphism in Java. All Cats are Animals in your example (all instances of subclasses are instances of their superclass) but the converse isn't true (instances of a superclass aren't instances of any of its subclasses). You can say</p>\n<pre><code>Animal myCat = new Cat();\n</code></pre>\n<p>but you can't say</p>\n<pre><code>Cat myCat = new Animal();\n</code></pre>\n<p>I think you need to spend more time studying the language, as these are fairly basic concepts.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T01:15:02.387", "Id": "531538", "Score": "0", "body": "Questions #1 and #5 are valid ones to pose to OP. The rest of them I would argue are overly cryptic as phrased. For example, from what I can tell, OP likely lacks the context necessary to understand what you are trying to get at by asking whether all cats are orange and have four legs or what to do when birds walk like other animals." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T07:22:04.170", "Id": "531554", "Score": "0", "body": "@Albion47 my response was based on my having read and responded to OP's previous post. He's already used constuctors with parameters for color and legs, so points 2, 3 and 4 shouldn't be too difficult for him to understand. He's also shown he's aware of calling superclass methods (at least the superclass constructor) so point 6 shouldn't be too much trouble either. My aim is to get him thinking, and learning, but not to think that CodeReview is the place to learn Java from scratch." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T16:03:52.877", "Id": "269396", "ParentId": "269395", "Score": "6" } }, { "body": "<p>First, responding to your observations:</p>\n<p>All subclass constructors implicitly start with <code>super();</code> if they do not have an explicit superclass constructor call. However, if the superclass does not have a (non-<code>private</code>) constructor with no parameters, then the implicit <code>super()</code> would be calling a constructor that does not exist. In this situation, and only in this situation, you must always explicitly invoke a superclass constructor, because the compiler cannot deduce what the arguments of the call should be.</p>\n<p>The <code>@Override</code> annotation (that's the official term in Java, not &quot;decoration&quot;) is partly documentation and partly an optional protection against certain kinds of mistakes. It was not present in the original version of the language, and for backwards compatibility it was not made required when it was added. The optional protection part is that, if the override's method signature does not match any superclass method, then <code>@Override</code> will cause a compile error to draw attention to the mismatch.</p>\n<p><code>Animal myCat = new Cat()</code> should work, because all cats are animals, as indicated by the subclass relationship. <code>Cat myCat = new Animal()</code> is a compile error, because the subclass relationship is in the wrong direction for that. <code>Cat myCat = new Cat()</code> works because all cats, obviously, are cats. In any case, the <code>Animal</code> superclass is involved indirectly by the fact that the <code>Cat()</code> constructor, whether explicitly written to do so or not, calls the <code>Animal()</code> constructor.</p>\n<p>Now, on to commenting about your code:</p>\n<p>In general, <code>protected</code> should only be used when there is a reason for subclasses to have to do something directly with the <code>protected</code> thing. One common reason is when a method is declared for the specific purpose of allowing subclasses to add their own behavior to a certain point. For example, consider how to alter this to make <code>cleanup()</code> do its job properly:</p>\n<pre><code>class Superclass {\n // various other stuff\n\n public void cleanup() {\n // clean up superclass stuff that needs it\n // should also cleanup subclass stuff, but doesn't know how\n }\n}\n\nclass Subclass extends Superclass {\n // various subclass stuff, some of which needs cleaning up\n}\n</code></pre>\n<p>You could modify <code>Subclass</code> like this:</p>\n<pre><code>class Subclass extends Superclass {\n // various subclass stuff, some of which needs cleaning up\n\n @Override\n public void cleanup() {\n super.cleanup();\n // clean up the subclass stuff\n }\n}\n</code></pre>\n<p>That approach works, but there's a problem with it: it's really easy to just forget to put the <code>super.cleanup();</code> call in, and omitting that prevents the superclass cleanup from happening. Or, if this is in library code that might be extended by other people, the users of your library can modify how cleaning up the superclass stuff is done for objects of their subclass, and may break important parts of your library's functionality by doing so, potentially even in some intentionally malicious way.</p>\n<p>This solution avoids that problem:</p>\n<pre><code>class Superclass {\n // various other stuff\n\n public final void cleanup() {\n // clean up superclass stuff that needs it\n subCleanup();\n }\n\n protected void subCleanup() {}\n}\n\nclass Subclass extends Superclass {\n // various subclass stuff, some of which needs cleaning up\n\n @Override\n protected void subCleanup() {\n // clean up subclass stuff that needs it\n }\n}\n</code></pre>\n<p>With this approach, subclasses cannot prevent or alter how the superclass gets cleaned up because <code>cleanup()</code> is <code>final</code> and thus cannot be overridden. Despite that, subclasses can get their own stuff cleaned up whenever <code>cleanup()</code> is called by overriding <code>subCleanup()</code> instead because <code>cleanup()</code> calls that.</p>\n<p>In conclusion of this point, <code>color</code> and <code>leg_number</code> should be <code>private</code>, not <code>protected</code>. Note that this will require the <code>Animal</code> constructor to initialize them. It can handle the different values by adding parameters to the constructor, and then having subclasses call it like this: <code>super(&quot;orange&quot;, 4);</code></p>\n<p>If you simply make that change and try to compile, you will get a compile error for the <code>Bird</code> override of <code>move()</code> attempting to access a superclass <code>private</code> field. This does not mean that <code>leg_number</code> needs to be <code>protected</code> after all, however. Notice that, in the case where <code>leg_number</code> gets used, the returned value is identical to the superclass version of the method. You can simultaneously eliminate this code duplication (which would be worthwhile as its own point anyway) and resolve the compile error by replacing that line with <code>return super.move();</code>. This will invoke the <code>Animal</code> superclass version of <code>move()</code>, which does have access to <code>private</code> fields of <code>Animal</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T01:18:38.690", "Id": "269404", "ParentId": "269395", "Score": "1" } }, { "body": "<p>This is not a bad overall attempt, but there are some issues you should pick up further. I'm going to avoid giving you the straight answer where possible, as the true value is found in finding the answers yourself:</p>\n<ul>\n<li>Not every cat has 4 legs. Not every bug has 6 legs. If my cat only has 3 legs, how could this code facilitate my cat, who should be walking on 3 legs? It seems safest to not hardcode this number. Same thing applies to the color of the animals.\n<ul>\n<li>Interestingly, you've already fixed it for the number of wings a bird has. The same solution applies for legs and color too.</li>\n</ul>\n</li>\n<li>Rather than have each subtype set all of its fields, you should consider making the setting of the <code>Animal</code> fields reusable. Instead of each subtype doing the same thing, how about you delegate this job down to the <code>Animal</code> constructor itself.</li>\n<li>The bird's <code>move</code> method correctly allows for the &quot;flying&quot; message to be given instead. However, when you <em>don't</em> want to return the &quot;flying&quot; message, you've hardcoded the same response that your <code>Animal</code> class already implemented. Instead of hardcoding this message a second time, try to find out if there is a way that the <code>Bird.move</code> method is able to just reuse the base <code>Animal.move</code> output (when the bird does not have sufficient wings).\n<ul>\n<li>This solution entails having a proper override, so make sure that <code>Bird.move</code> overrides <code>Animal.move</code> before you tackle this.</li>\n</ul>\n</li>\n<li>After all these things are tackled, reconsider the access modifiers you use on <code>leg_number</code>, <code>color</code> and <code>wing_number</code>.\n<ul>\n<li>It should be <code>private</code> when you want no one other than the class itself to make use of it. You should use this as the <strong>default</strong> option. Only use the other access modifiers when you have a genuine need for them. Try to start by keeping everything private, and whenever you feel like something shouldn't be private, consider if you need to open this up to others or not.</li>\n<li>It should only be <code>protected</code> if subtypes should be able to make use of it, but not other external code.</li>\n<li>It should only be <code>public</code> when external code should be able to make use of it.</li>\n</ul>\n</li>\n</ul>\n<p>Note that if you want to test if your inheritance was properly implemented, you should try to work with your objects by using the base class:</p>\n<pre><code>Animal myCat = new Cat(); \nAnimal myBug = new Bug();\nAnimal myBird1 = new Bird(2);\nAnimal myBird2 = new Bird(0);\n</code></pre>\n<p>If you did everything right, your code should behave the same way (and compile, for starters) when you change all these variable types to <code>Animal</code>. If your code does not behave the same way, then you've not properly implemented your inheritance.</p>\n<hr />\n<p>As an aside, unrelated to your actual code, this exercise sets you up for some bad coding standards. <code>leg_number</code> and <code>wing_number</code> should be <code>legCount</code> and <code>wingCount</code>, in keeping with the naming conventions.</p>\n<p>&quot;number of legs&quot; would be correct English, but &quot;leg count&quot; is more idiomatic to a programmer and shout therefore be favored.</p>\n<p>&quot;leg number&quot; doesn't mean what this exercise think it does. A &quot;leg number&quot; is the number given to a specific leg, e.g. &quot;this is leg 5&quot; (similar to &quot;player 1&quot;, &quot;aisle 5&quot;, &quot;Apollo 13&quot;). The number does not denote a total amount, it denotes a specific number given to a specific instance. There can be more players, more aisles, and more Apollo missions than the number indicates.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T14:57:26.940", "Id": "269424", "ParentId": "269395", "Score": "0" } }, { "body": "<p>Use a strategy to implement the diverging behaviour in the animals:\n<a href=\"https://refactoring.guru/design-patterns/strategy\" rel=\"nofollow noreferrer\">https://refactoring.guru/design-patterns/strategy</a></p>\n<p>I added a Java scratch file that you can peruse for further insights.\nIf someone other finds the code teaches wrongly, please let me know so I will myself be reviewed.</p>\n<pre><code>class Scratch {\n public static void main(String[] args) {\n // abstract Animal\n Animal abstractCat = new Cat(&quot;abstract and a bit of red&quot;);\n abstractCat.move();\n // concrete Animal\n Cat concreteCat = new Cat(&quot;concrete and tigerlike&quot;);\n concreteCat.move();\n // change bug behaviour (move()) whilst program is running by assigning new AnimalBehaviour interface.\n new Bug(&quot;iridium&quot;).move().setAnimalBehaviour(new AnimalMoveBehaviour()).move();\n //as AnimalBehaviour is an interface resp. a SAM, we can define its functionality via a lambda.\n new Bug(5, 3, &quot;chaotic&quot;, animal -&gt; System.out.println(animal.color +&quot; colored animal moves with &quot; +animal.legs + &quot; legs and flies with &quot; +animal.wings + &quot;wings&quot;)).move();\n }\n}\n// define what functionality / behaviour an object should fulfil.\ninterface AnimalBehaviour {\n void move(Animal animal);\n}\n\n// one could think of a ProtoAnimal, which then is divided into Flying and Walking, or both, or even Swimming.\nabstract class Animal {\n int legs, wings;\n String color;\n // inject behaviour (which is basically a contract) into class\n AnimalBehaviour animalBehaviour;\n public Animal(int legs, int wings, String color, AnimalBehaviour animalBehaviour) {\n this.legs = legs;\n this.color = color;\n this.wings = wings;\n this.animalBehaviour = animalBehaviour;\n }\n\n // setAnimalBehaviour enables changing the behaviour during runtime.\n // see main method for example.\n\n public Animal setAnimalBehaviour(AnimalBehaviour animalBehaviour) {\n this.animalBehaviour = animalBehaviour;\n // fluent interface to return instance so method-chaining becomes possible.\n return this;\n }\n\n // delegate Animal's move method (AnimalBehaviour) to interface.\n public Animal move(){\n this.animalBehaviour.move(this);\n\n // fluent interface to return instance so method-chaining becomes possible.\n return this;\n }\n}\n\nclass Cat extends Animal {\n // standard cat\n public Cat(String color) {\n super(4, 0, color, new AnimalMoveBehaviour());\n }\n\n // cat whose parameters can be passed during instantiation\n public Cat(int legs, int wings, String color, AnimalBehaviour ab) {\n super(legs, wings, color, ab);\n }\n\n}\n\nclass Bug extends Animal {\n // standard bug\n public Bug(String color) {\n super(6, 4, color, new AnimalFlyBehaviour());\n }\n\n // bug whose parameters can be passed during instantiation\n public Bug(int legs, int wings, String color, AnimalBehaviour ab) {\n super(legs, wings, color, ab);\n }\n}\n\nclass AnimalMoveBehaviour implements AnimalBehaviour {\n\n @Override\n public void move(Animal animal) {\n System.out.println(animal.color + &quot; colored animal is moving with &quot; + animal.legs + &quot; legs&quot;);\n }\n}\n\nclass AnimalFlyBehaviour implements AnimalBehaviour {\n\n @Override\n public void move(Animal animal) {\n System.out.println(animal.color + &quot; colored animal is flying with &quot; + animal.legs + &quot; wings&quot;);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T21:48:34.257", "Id": "531610", "Score": "1", "body": "Whilst you've provided an alternative implementation, you don't appear to have reviewed the existing code. You also haven't explained why you've deviated from the assignment brief (no leg_number property). Whilst not following the interviewers instructions can be the correct choice, they would usually expect a rationale as to why you've decided not to." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T11:26:29.100", "Id": "531645", "Score": "0", "body": "I have not added review remarks as they have been already made by others. \nI wanted to provide an alternative to the pure inheritance approach, which is often a bad idea. Getting to grips with a strategy pattern might be beneficial for OP.\n\nHowever, the variables \"leg_number\" and \"wing_number\" are wrong in regards to the assignment. In Java-lingo I would argue that underscored variable names are not a practice that one should pick up. Consequently, the vars should be named \"wingNumber\" and \"legNumber\". As we can see from the type (int), the pseudo-suffix (number) should not even be needed." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T16:42:50.457", "Id": "269430", "ParentId": "269395", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T15:15:04.647", "Id": "269395", "Score": "4", "Tags": [ "java", "interview-questions", "inheritance", "polymorphism" ], "Title": "Model animals using inheritance in Java, revised" }
269395
<p>I'm relatively new to Python have been writing for a few months now. I've started a Pandas Numpy project that starts with parsing large and somewhat sloppy formatted textfile, its not exactly csv but its pretty close.</p> <pre><code>... Basetime: 2021102206Z Forecast Hours: 0hr 1hr... 144hr Sfc Prs(mb): 1002.83, 1002.62,... ... Dry Microburst: 0.00, 0,... ###UA SECTION### 1000mb GPH (m): 166.88,... ... #END LINE 861 </code></pre> <h2>create instance from file</h2> <ul> <li>pd.DataFrame</li> <li>numpy.ndarray</li> </ul> <pre class="lang-py prettyprint-override"><code>with open('data/2021102206Z.txt', 'r') as f: tp = Tarp(f) df = tp.asDataFrame() print(type(df)) #&lt;class 'pandas.core.frame.DataFrame'&gt; m = tp.asMatrix() print(type(m)) #&lt;class 'numpy.ndarray'&gt; </code></pre> <h2><strong>init</strong></h2> <p>Tarp class parses the applicable data into a Object subclass</p> <p><code>list(map(self._series, f))</code> parse -&gt; reject -&gt; reformat -&gt; setatt</p> <pre class="lang-py prettyprint-override"><code> class Tarp(object): def __init__(self, f): self.props = Object() self.models = Object() # itterate f as pd.Series def _series(self, f): # split series at : or , or whitespace s = pd.Series(f).str.split(r&quot;:\s*|,\s*&quot;).squeeze() # pop key from series to reformat, returns False if key invalid k = _pythonic_keys(s.pop(0)) v = _pythonic_vals(s) try: if k and v:# k &amp; v = model data # force ValueError on non dtype float val = np.array(v, dtype=float) self.models.keys.append(k) setattr(self.models, k, val) pass elif k:# k not v = station properties v = s[0].rstrip() if k == &quot;basetime&quot;: val = datetime.strptime(v, &quot;%Y%m%d%HZ&quot;) else: val = v self.props.keys.append(k) setattr(self.props, k, val) except ValueError:# occurs on int array vals pass except IndexError:# occurs on blank lines pass </code></pre> <h2>Methods</h2> <pre class="lang-py prettyprint-override"><code> def getmodels(self, key): return getattr(self.models, key) def getprops(self, key): return getattr(self.props, key) def zip_props(self): vals = list(map(self.getprops, self.props.keys)) return dict(zip(self.props.keys, vals)) def zip_models(self): vals = list(map(self.getmodels, self.models.keys)) return dict(zip(self.models.keys, vals)) def asMatrix(self): return np.array( list(map(self.getmodels, self.models.keys))) def asDataFrame(self): return pd.DataFrame(self.zip_models()) </code></pre> <h2>misc</h2> <pre><code>class Object: def __init__(self): self.keys = list() pass _wspace = re.compile(r'\s+') _units = re.compile(r'(?=\s*\(.*)') _only_wspace = re.compile(r&quot;^\s*$&quot;) def _pythonic_keys(s): if bool(_only_wspace.search(s)): return False else: return _wspace.sub(&quot;_&quot;, _units.split(s)[0]).lower() def _pythonic_vals(a): if len(a) &gt; 0: return a[:-1] else: return False </code></pre> <h2>full code</h2> <pre class="lang-py prettyprint-override"><code>import numpy as np import pandas as pd import re from datetime import datetime _wspace = re.compile(r'\s+') _units = re.compile(r'(?=\s*\(.*)') _only_wspace = re.compile(r&quot;^\s*$&quot;) def _pythonic_keys(s): if bool(_only_wspace.search(s)): return False else: return _wspace.sub(&quot;_&quot;, _units.split(s)[0]).lower() def _pythonic_vals(a): if len(a) &gt; 0: return a[:-1] else: return False class Object: def __init__(self): self.keys = list() pass class Tarp(object): def getmodels(self, key): return getattr(self.models, key) def getprops(self, key): return getattr(self.props, key) def zip_props(self): vals = list(map(self.getprops, self.props.keys)) return dict(zip(self.props.keys, vals)) def zip_models(self): vals = list(map(self.getmodels, self.models.keys)) return dict(zip(self.models.keys, vals)) def asMatrix(self): return np.array( list(map(self.getmodels, self.models.keys))) def asDataFrame(self): return pd.DataFrame(self.zip_models()) def __init__(self, f): self.props = Object() self.models = Object() # itterate f as pd.Series list(map(self._series, f)) def _series(self, f): # split series at : or , or whitespace s = pd.Series(f).str.split(r&quot;:\s*|,\s*&quot;).squeeze() # pop key from series to reformat, returns False if key invalid k = _pythonic_keys(s.pop(0)) v = _pythonic_vals(s) try: if k and v: # force ValueError on non dtype float val = np.array(v, dtype=float) self.models.keys.append(k) setattr(self.models, k, val) pass elif k: v = s[0].rstrip() if k == &quot;basetime&quot;: val = datetime.strptime(v, &quot;%Y%m%d%HZ&quot;) else: val = v self.props.keys.append(k) setattr(self.props, k, val) except ValueError: pass except IndexError: pass def run_test(): with open('data/2021102206Z.txt', 'r') as f: tp = Tarp(f) df = tp.asDataFrame() print(type(df)) m = tp.asMatrix() print(type(m)) </code></pre> <h2>more data</h2> <p>the file is a 144hr forecast by hour for several different values</p> <p>at line 160 is there a break and the values are upper level values</p> <pre><code> Basetime: 2021102206Z Spacing: 1/4 Degree Region: Worldwide StationID: TEST Station Name: TEST DATA Latitude: 50.55 Longitude: -100.84 Elevation: 139.9 Forecast Hours: 0hr 1hr 2hr 3hr 4hr 5hr 6hr 7hr 8hr 9hr 10hr 11hr 12hr 13hr 14hr 15hr 16hr 17hr 18hr 19hr 20hr 21hr 22hr 23hr 24hr 25hr 26hr 27hr 28hr 29hr 30hr 31hr 32hr 33hr 34hr 35hr 36hr 37hr 38hr 39hr 40hr 41hr 42hr 43hr 44hr 45hr 46hr 47hr 48hr 49hr 50hr 51hr 52hr 53hr 54hr 55hr 56hr 57hr 58hr 59hr 60hr 61hr 62hr 63hr 64hr 65hr 66hr 67hr 68hr 69hr 70hr 71hr 72hr 73hr 74hr 75hr 76hr 77hr 78hr 79hr 80hr 81hr 82hr 83hr 84hr 85hr 86hr 87hr 88hr 89hr 90hr 91hr 92hr 93hr 94hr 95hr 96hr 97hr 98hr 99hr 100hr 101hr 102hr 103hr 104hr 105hr 106hr 107hr 108hr 109hr 110hr 111hr 112hr 113hr 114hr 115hr 116hr 117hr 118hr 119hr 120hr 121hr 122hr 123hr 124hr 125hr 126hr 127hr 128hr 129hr 130hr 131hr 132hr 133hr 134hr 135hr 136hr 137hr 138hr 139hr 140hr 141hr 142hr 143hr 144hr Sfc Prs(mb): 1002.83, 1002.62, 1002.33, 1001.96, 1002.13, 1002.10, 1002.16, 1002.59, 1002.68, 1002.58, 1002.44, 1002.31, 1001.81, 1001.26, 1000.83, 1000.46, 1000.30, 1000.26, 1000.34, 1000.17, 1000.31, 1000.38, 1000.18, 1000.07, 1000.18, 1000.17, 1000.01, 999.85, 999.90, 1000.10, 1000.22, 1000.38, 1000.66, 1000.65, 1000.32, 999.84, 999.16, 998.25, 997.31, 996.85, 996.56, 996.46, 996.74, 996.60, 996.46, 996.32, 995.94, 995.55, 995.17, 994.58, 994.00, 993.41, 993.15, 992.90, 992.64, 992.88, 993.11, 993.34, 992.44, 991.53, 990.63, 989.95, 989.27, 988.59, 988.02, 987.45, 986.88, 986.61, 986.33, 986.06, 985.86, 985.67, 985.48, 985.51, 985.54, 985.56, 986.08, 986.60, 987.12, 987.67, 988.23, 988.79, 988.84, 988.89, 988.95, 989.69, 990.43, 991.18, 992.38, 993.59, 994.79, 995.47, 996.14, 996.81, 997.15, 997.50, 997.84, 997.99, 998.14, 998.30, 998.73, 999.17, 999.61, 999.81, 1000.01, 1000.22, 999.47, 998.73, 997.99, 997.28, 996.57, 995.86, 995.74, 995.63, 995.52, 994.82, 994.11, 993.41, 992.59, 991.77, 990.95, 990.60, 990.26, 989.91, 988.19, 986.47, 984.76, 983.96, 983.17, 982.37, 981.11, 979.84, 978.57, 978.14, 977.71, 977.28, 977.57, 977.85, 978.13, 978.46, 978.79, 979.12, 979.30, 979.49, 979.68, Mean SLP (mb): 1019.73, 1019.50, 1019.19, 1018.83, 1019.03, 1019.02, 1019.09, 1019.54, 1019.60, 1019.49, 1019.34, 1019.21, 1018.73, 1018.18, 1017.73, 1017.35, 1017.21, 1017.19, 1017.27, 1017.07, 1017.23, 1017.32, 1017.14, 1017.05, 1017.20, 1017.17, 1016.98, 1016.80, 1016.77, 1016.92, 1017.03, 1017.19, 1017.46, 1017.49, 1017.15, 1016.69, 1016.00, 1015.07, 1014.09, 1013.56, 1013.25, 1013.14, 1013.41, 1013.26, 1013.12, 1012.97, 1012.56, 1012.16, 1011.76, 1011.15, 1010.54, 1009.92, 1009.64, 1009.35, 1009.06, 1009.29, 1009.51, 1009.73, 1008.81, 1007.88, 1006.96, 1006.29, 1005.62, 1004.95, 1004.36, 1003.76, 1003.16, 1002.92, 1002.68, 1002.44, 1002.27, 1002.10, 1001.93, 1001.99, 1002.04, 1002.09, 1002.67, 1003.24, 1003.81, 1004.37, 1004.92, 1005.48, 1005.50, 1005.53, 1005.55, 1006.30, 1007.06, 1007.81, 1009.03, 1010.25, 1011.47, 1012.14, 1012.81, 1013.48, 1013.81, 1014.15, 1014.49, 1014.61, 1014.74, 1014.87, 1015.31, 1015.75, 1016.19, 1016.39, 1016.60, 1016.81, 1016.05, 1015.28, 1014.52, 1013.80, 1013.08, 1012.35, 1012.23, 1012.12, 1012.00, 1011.26, 1010.51, 1009.77, 1008.95, 1008.13, 1007.31, 1006.99, 1006.68, 1006.36, 1004.63, 1002.89, 1001.16, 1000.39, 999.61, 998.84, 997.59, 996.35, 995.10, 994.70, 994.30, 993.90, 994.18, 994.47, 994.76, 995.10, 995.44, 995.79, 995.99, 996.20, 996.41, Altimeter (in. Hg): 30.10, 30.09, 30.09, 30.07, 30.08, 30.08, 30.08, 30.09, 30.10, 30.09, 30.09, 30.08, 30.07, 30.05, 30.04, 30.03, 30.02, 30.02, 30.03, 30.02, 30.02, 30.03, 30.02, 30.02, 30.02, 30.02, 30.02, 30.01, 30.01, 30.02, 30.02, 30.03, 30.04, 30.04, 30.03, 30.01, 29.99, 29.96, 29.93, 29.92, 29.91, 29.91, 29.92, 29.91, 29.91, 29.91, 29.89, 29.88, 29.87, 29.85, 29.84, 29.82, 29.81, 29.80, 29.80, 29.80, 29.81, 29.82, 29.79, 29.76, 29.74, 29.71, 29.69, 29.67, 29.66, 29.64, 29.62, 29.61, 29.61, 29.60, 29.59, 29.59, 29.58, 29.58, 29.58, 29.58, 29.60, 29.61, 29.63, 29.65, 29.66, 29.68, 29.68, 29.68, 29.68, 29.71, 29.73, 29.75, 29.79, 29.82, 29.86, 29.88, 29.90, 29.92, 29.93, 29.94, 29.95, 29.96, 29.96, 29.96, 29.98, 29.99, 30.00, 30.01, 30.02, 30.02, 30.00, 29.98, 29.96, 29.93, 29.91, 29.89, 29.89, 29.88, 29.88, 29.86, 29.84, 29.82, 29.79, 29.77, 29.74, 29.73, 29.72, 29.71, 29.66, 29.61, 29.56, 29.54, 29.51, 29.49, 29.45, 29.41, 29.37, 29.36, 29.35, 29.34, 29.34, 29.35, 29.36, 29.37, 29.38, 29.39, 29.40, 29.40, 29.41, Press Alt (ft): 285.78, 291.39, 299.50, 309.49, 304.92, 305.71, 304.16, 292.24, 289.64, 292.43, 296.33, 300.04, 313.61, 328.87, 340.80, 350.93, 355.33, 356.43, 354.22, 359.08, 355.09, 353.16, 358.68, 361.81, 358.63, 358.82, 363.37, 367.77, 366.37, 360.80, 357.50, 353.13, 345.54, 345.62, 354.75, 367.99, 386.75, 411.88, 438.08, 450.74, 458.64, 461.38, 453.69, 457.56, 461.43, 465.29, 475.92, 486.54, 497.17, 513.43, 529.69, 545.96, 553.06, 560.16, 567.26, 560.77, 554.29, 547.81, 572.92, 598.05, 623.21, 642.09, 660.98, 679.89, 695.76, 711.65, 727.54, 735.22, 742.90, 750.58, 755.95, 761.32, 766.69, 765.90, 765.11, 764.31, 749.87, 735.44, 721.01, 705.45, 689.90, 674.36, 672.92, 671.48, 670.04, 649.34, 628.65, 607.97, 574.49, 541.04, 507.62, 489.00, 470.38, 451.77, 442.24, 432.72, 423.20, 419.04, 414.88, 410.72, 398.59, 386.46, 374.33, 368.79, 363.24, 357.69, 378.18, 398.68, 419.19, 438.83, 458.49, 478.17, 481.28, 484.40, 487.51, 506.98, 526.46, 545.95, 568.71, 591.48, 614.27, 623.91, 633.55, 643.19, 691.02, 738.91, 786.87, 809.08, 831.29, 853.53, 888.99, 924.49, 960.03, 972.11, 984.19, 996.27, 988.33, 980.39, 972.45, 963.21, 953.97, 944.74, 939.51, 934.28, 929.05, Density Alt (ft): -55.22, -88.18, -135.38, -186.09, -235.12, -262.16, -312.89, -296.80, -142.70, -0.45, 88.61, 172.51, 274.47, 348.90, 398.48, 378.66, 356.46, 249.88, 90.22, -10.37, -101.92, -182.53, -205.18, -231.41, -338.80, -394.94, -419.42, -427.96, -418.72, -433.90, -436.02, -374.09, -103.15, 200.48, 426.54, 563.89, 643.07, 731.70, 768.59, 851.75, 836.91, 774.23, 678.68, 684.24, 689.77, 695.11, 705.35, 715.59, 725.83, 742.34, 758.67, 775.21, 850.91, 926.88, 1003.14, 1132.49, 1262.30, 1392.82, 1523.68, 1654.20, 1784.81, 1877.47, 1969.33, 2060.37, 2037.23, 2014.25, 1991.25, 1945.64, 1899.72, 1853.71, 1794.06, 1734.05, 1673.69, 1599.03, 1524.64, 1450.48, 1272.28, 1095.99, 921.63, 829.19, 736.56, 643.31, 710.27, 777.51, 845.04, 795.05, 744.84, 694.83, 596.17, 497.41, 398.98, 341.93, 284.85, 227.93, 189.31, 150.86, 112.19, 91.00, 70.00, 48.99, 26.97, 4.95, -16.86, 24.73, 66.02, 107.24, 197.02, 286.22, 374.83, 445.25, 515.60, 585.66, 529.25, 472.31, 415.02, 406.81, 398.58, 390.32, 383.68, 377.02, 370.56, 363.20, 355.83, 348.45, 419.28, 490.17, 561.13, 643.70, 726.36, 808.92, 948.00, 1087.20, 1226.51, 1339.39, 1451.95, 1564.38, 1478.83, 1393.31, 1307.80, 1265.79, 1224.16, 1182.28, 1137.12, 1091.92, 1046.88, 2 m agl Tmp (K): 283.50, 283.17, 282.70, 282.18, 281.82, 281.59, 281.20, 281.43, 282.70, 283.86, 284.59, 285.24, 285.94, 286.41, 286.71, 286.48, 286.27, 285.40, 284.10, 283.22, 282.52, 281.89, 281.62, 281.34, 280.52, 280.08, 279.82, 279.69, 279.76, 279.70, 279.71, 280.24, 282.49, 284.96, 286.70, 287.66, 288.10, 288.54, 288.53, 289.02, 288.78, 288.20, 287.45, 287.42, 287.39, 287.36, 287.35, 287.33, 287.32, 287.31, 287.29, 287.28, 287.77, 288.26, 288.75, 289.78, 290.81, 291.85, 292.62, 293.40, 294.18, 294.80, 295.41, 296.03, 295.72, 295.42, 295.12, 294.66, 294.20, 293.74, 293.18, 292.61, 292.05, 291.51, 290.97, 290.44, 289.30, 288.16, 287.02, 286.41, 285.80, 285.19, 285.68, 286.16, 286.64, 286.45, 286.27, 286.08, 285.64, 285.21, 284.77, 284.53, 284.29, 284.05, 283.83, 283.61, 283.39, 283.26, 283.12, 282.99, 282.92, 282.86, 282.80, 283.19, 283.59, 283.99, 284.55, 285.12, 285.68, 286.07, 286.45, 286.84, 286.33, 285.81, 285.30, 285.01, 284.72, 284.44, 284.16, 283.88, 283.60, 283.42, 283.24, 283.06, 283.12, 283.19, 283.25, 283.67, 284.09, 284.51, 285.23, 285.95, 286.68, 287.46, 288.23, 289.01, 288.43, 287.85, 287.27, 287.05, 286.84, 286.62, 286.34, 286.06, 285.78, 2 m agl Temp-D (K): -4.09, -4.41, -4.86, -5.36, -5.73, -5.96, -6.36, -6.16, -4.89, -3.72, -2.99, -2.32, -1.60, -1.10, -0.78, -0.99, -1.18, -2.06, -3.36, -4.23, -4.94, -5.57, -5.83, -6.11, -6.92, -7.37, -7.62, -7.74, -7.67, -7.75, -7.74, -7.22, -4.98, -2.51, -0.76, 0.23, 0.71, 1.19, 1.24, 1.76, 1.53, 0.95, 0.19, 0.17, 0.14, 0.12, 0.13, 0.14, 0.14, 0.16, 0.18, 0.20, 0.71, 1.21, 1.71, 2.73, 3.75, 4.77, 5.60, 6.43, 7.26, 7.91, 8.56, 9.21, 8.94, 8.67, 8.40, 7.96, 7.51, 7.07, 6.51, 5.96, 5.41, 4.87, 4.33, 3.79, 2.62, 1.46, 0.29, -0.35, -0.99, -1.63, -1.15, -0.67, -0.19, -0.42, -0.65, -0.88, -1.38, -1.88, -2.38, -2.66, -2.94, -3.22, -3.46, -3.69, -3.93, -4.07, -4.22, -4.36, -4.45, -4.53, -4.62, -4.23, -3.85, -3.46, -2.86, -2.25, -1.65, -1.22, -0.80, -0.37, -0.88, -1.39, -1.90, -2.15, -2.39, -2.64, -2.88, -3.11, -3.34, -3.50, -3.67, -3.83, -3.67, -3.51, -3.35, -2.89, -2.42, -1.96, -1.17, -0.37, 0.42, 1.22, 2.02, 2.82, 2.23, 1.63, 1.03, 0.80, 0.57, 0.34, 0.04, -0.25, -0.54, 2 m agl Dpt (K): 279.93, 279.97, 279.84, 279.84, 279.86, 279.92, 279.81, 280.17, 280.44, 280.24, 279.96, 280.01, 280.18, 280.19, 280.06, 279.51, 279.16, 278.73, 278.60, 278.48, 278.28, 278.02, 278.45, 278.95, 278.42, 278.22, 278.45, 278.63, 278.90, 278.83, 278.83, 279.16, 279.91, 280.54, 281.34, 282.05, 282.45, 283.00, 283.46, 284.32, 284.71, 284.89, 285.10, 285.45, 285.78, 286.12, 286.01, 285.91, 285.80, 285.62, 285.44, 285.26, 286.00, 286.73, 287.46, 288.58, 289.70, 290.82, 291.36, 291.90, 292.43, 292.36, 292.25, 292.11, 291.65, 291.18, 290.72, 290.58, 290.43, 290.27, 290.19, 290.10, 290.00, 289.28, 288.56, 287.84, 285.82, 283.78, 281.69, 281.59, 281.47, 281.33, 282.44, 283.53, 284.61, 284.41, 284.22, 284.03, 283.56, 283.09, 282.62, 282.14, 281.67, 281.19, 281.13, 281.08, 281.03, 281.07, 281.11, 281.15, 281.23, 281.31, 281.39, 281.43, 281.45, 281.47, 281.14, 280.74, 280.28, 280.28, 280.26, 280.23, 280.30, 280.36, 280.39, 280.62, 280.84, 281.03, 280.88, 280.72, 280.57, 280.84, 281.10, 281.34, 281.71, 282.08, 282.44, 282.87, 283.31, 283.74, 284.50, 285.26, 286.01, 286.48, 286.94, 287.38, 286.83, 286.27, 285.72, 285.31, 284.90, 284.49, 284.02, 283.56, 283.10, 2 m agl WBT (K): 281.58, 281.48, 281.17, 280.96, 280.76, 280.76, 280.45, 280.76, 281.48, 281.94, 282.09, 282.40, 282.81, 283.01, 283.12, 282.71, 282.50, 281.89, 281.27, 280.76, 280.35, 279.94, 280.04, 280.14, 279.48, 279.12, 279.12, 279.12, 279.32, 279.22, 279.27, 279.73, 281.17, 282.60, 283.73, 284.45, 284.86, 285.32, 285.58, 286.19, 286.35, 286.19, 286.04, 286.25, 286.40, 286.60, 286.50, 286.50, 286.40, 286.30, 286.19, 286.09, 286.71, 287.32, 287.94, 289.01, 290.09, 291.17, 291.78, 292.40, 292.96, 293.12, 293.22, 293.32, 292.91, 292.50, 292.14, 291.88, 291.68, 291.42, 291.17, 290.91, 290.70, 290.04, 289.42, 288.76, 287.17, 285.58, 284.04, 283.73, 283.43, 283.07, 283.83, 284.65, 285.48, 285.27, 285.06, 284.86, 284.45, 283.99, 283.53, 283.22, 282.81, 282.50, 282.40, 282.25, 282.09, 282.09, 282.04, 281.99, 281.99, 281.99, 282.04, 282.19, 282.40, 282.60, 282.71, 282.71, 282.76, 282.91, 283.12, 283.22, 283.01, 282.81, 282.60, 282.60, 282.60, 282.60, 282.40, 282.19, 281.99, 281.99, 282.09, 282.09, 282.35, 282.60, 282.81, 283.22, 283.63, 284.04, 284.81, 285.53, 286.30, 286.86, 287.42, 287.99, 287.42, 286.86, 286.30, 285.99, 285.68, 285.37, 284.96, 284.60, 284.25, Convect. Temp (K): 303.57, 303.13, 303.20, 304.07, 303.98, 303.92, 304.01, 284.02, 283.59, 283.42, 283.80, 285.06, 285.45, 285.68, 286.01, 299.96, 299.77, 300.60, 301.14, 301.41, 301.44, 301.63, 301.08, 300.05, 297.39, 299.94, 300.80, 301.56, 301.54, 301.51, 301.55, 301.72, 302.09, 302.26, 302.30, 302.74, 302.65, 300.64, 299.55, 300.21, 301.11, 302.01, 302.01, 302.06, 302.12, 302.16, 302.32, 302.49, 302.63, 300.58, 300.13, 299.93, 300.10, 299.93, 299.32, 298.63, 297.88, 297.02, 296.63, 296.30, 296.06, 296.56, 296.92, 297.16, 297.80, 299.29, 302.04, 302.33, 302.37, 302.27, 300.75, 298.96, 297.27, 295.20, 293.51, 292.06, 290.58, 289.07, 287.64, 287.07, 286.42, 285.40, 285.87, 286.42, 286.81, 286.53, 286.27, 285.99, 285.79, 285.59, 285.40, 285.15, 284.89, 284.62, 284.51, 284.40, 284.27, 284.27, 284.27, 284.26, 284.12, 284.00, 283.89, 283.84, 283.66, 283.64, 284.14, 320.35, 320.32, 319.86, 319.53, 319.29, 319.07, 318.87, 318.69, 317.98, 317.16, 316.15, 315.87, 315.60, 315.35, 311.88, 309.30, 284.72, 285.32, 284.17, 284.02, 284.41, 284.82, 285.21, 285.91, 286.59, 287.26, 288.94, 289.49, 289.80, 289.48, 289.14, 288.80, 288.46, 288.12, 287.76, 287.43, 287.09, 286.73, Heat Index (F): 50.62, 50.01, 49.18, 48.24, 47.60, 47.17, 46.47, 46.88, 49.17, 51.27, 52.57, 53.75, 55.01, 55.85, 56.39, 55.97, 55.60, 54.03, 51.69, 50.11, 48.84, 47.71, 47.22, 46.72, 45.26, 44.45, 43.98, 43.75, 43.88, 43.77, 43.80, 44.75, 48.80, 53.25, 56.37, 58.10, 58.89, 59.68, 59.67, 60.55, 60.11, 59.07, 57.72, 57.67, 57.61, 57.56, 57.54, 57.51, 57.49, 57.46, 57.44, 57.42, 58.30, 59.18, 60.06, 61.91, 63.77, 65.63, 67.04, 68.44, 69.84, 70.95, 72.05, 73.69, 73.37, 73.12, 72.95, 72.05, 69.87, 69.04, 68.03, 67.01, 66.00, 65.03, 64.06, 63.10, 61.05, 59.00, 56.95, 55.85, 54.76, 53.66, 54.53, 55.40, 56.26, 55.93, 55.59, 55.25, 54.47, 53.69, 52.90, 52.47, 52.03, 51.59, 51.20, 50.81, 50.41, 50.17, 49.93, 49.69, 49.57, 49.46, 49.35, 50.06, 50.78, 51.49, 52.51, 53.52, 54.53, 55.23, 55.93, 56.62, 55.70, 54.77, 53.85, 53.33, 52.81, 52.29, 51.79, 51.29, 50.79, 50.47, 50.14, 49.81, 49.93, 50.05, 50.16, 50.92, 51.67, 52.43, 53.73, 55.03, 56.33, 57.73, 59.13, 60.53, 59.48, 58.44, 57.39, 57.01, 56.62, 56.23, 55.73, 55.22, 54.71, Wind Chill (F): 50.62, 50.01, 49.18, 48.24, 47.60, 47.17, 46.47, 46.88, 49.17, 51.27, 52.57, 53.75, 55.01, 55.85, 56.39, 55.97, 55.60, 54.03, 51.69, 50.11, 48.84, 47.71, 47.22, 46.72, 45.26, 44.45, 43.98, 43.75, 43.88, 43.77, 43.80, 44.75, 48.80, 53.25, 56.37, 58.10, 58.89, 59.68, 59.67, 60.55, 60.11, 59.07, 57.72, 57.67, 57.61, 57.56, 57.54, 57.51, 57.49, 57.46, 57.44, 57.42, 58.30, 59.18, 60.06, 61.91, 63.77, 65.63, 67.04, 68.44, 69.84, 70.95, 72.05, 73.16, 72.62, 72.07, 71.53, 70.70, 69.87, 69.04, 68.03, 67.01, 66.00, 65.03, 64.06, 63.10, 61.05, 59.00, 56.95, 55.85, 54.76, 53.66, 54.53, 55.40, 56.26, 55.93, 55.59, 55.25, 54.47, 53.69, 52.90, 52.47, 52.03, 51.59, 51.20, 50.81, 50.41, 50.17, 49.93, 49.69, 49.57, 49.46, 49.35, 50.06, 50.78, 51.49, 52.51, 53.52, 54.53, 55.23, 55.93, 56.62, 55.70, 54.77, 53.85, 53.33, 52.81, 52.29, 51.79, 51.29, 50.79, 50.47, 50.14, 49.81, 49.93, 50.05, 50.16, 50.92, 51.67, 52.43, 53.73, 55.03, 56.33, 57.73, 59.13, 60.53, 59.48, 58.44, 57.39, 57.01, 56.62, 56.23, 55.73, 55.22, 54.71, FITS (F): 60.81, 60.34, 59.57, 58.79, 58.27, 57.96, 57.30, 57.87, 59.94, 61.55, 62.45, 63.46, 64.61, 65.31, 65.68, 64.98, 64.45, 62.87, 60.85, 59.47, 58.29, 57.19, 57.06, 56.96, 55.41, 54.61, 54.37, 54.30, 54.58, 54.44, 54.46, 55.46, 59.30, 63.38, 66.48, 68.36, 69.27, 70.28, 70.57, 71.85, 71.73, 70.98, 70.00, 70.18, 70.34, 70.52, 70.43, 70.34, 70.25, 70.12, 69.98, 69.85, 71.05, 72.25, 73.44, 75.70, 77.95, 80.21, 81.71, 83.22, 84.72, 85.59, 86.44, 87.26, 86.52, 85.77, 85.02, 84.25, 83.47, 82.68, 81.79, 80.89, 79.98, 78.72, 77.46, 76.20, 73.21, 70.21, 67.18, 66.21, 65.23, 64.23, 65.66, 67.07, 68.48, 68.07, 67.67, 67.27, 66.32, 65.37, 64.43, 63.76, 63.10, 62.43, 62.06, 61.71, 61.35, 61.17, 61.00, 60.82, 60.78, 60.74, 60.69, 61.31, 61.92, 62.52, 63.15, 63.74, 64.28, 64.86, 65.42, 65.98, 65.26, 64.53, 63.78, 63.50, 63.21, 62.91, 62.40, 61.88, 61.37, 61.27, 61.17, 61.05, 61.38, 61.71, 62.04, 62.94, 63.85, 64.75, 66.31, 67.87, 69.43, 70.89, 72.34, 73.78, 72.56, 71.34, 70.12, 69.54, 68.96, 68.38, 67.66, 66.94, 66.23, 2 m agl RH (%): 78.52, 80.53, 82.33, 85.25, 87.44, 89.24, 90.92, 91.78, 85.81, 78.26, 73.18, 70.31, 67.95, 65.96, 64.10, 62.67, 62.01, 63.72, 68.82, 72.37, 74.81, 76.64, 80.45, 84.87, 86.47, 87.96, 90.96, 92.91, 94.26, 94.21, 94.08, 92.82, 83.92, 74.29, 70.00, 69.04, 68.95, 69.56, 71.75, 73.64, 76.72, 80.61, 85.75, 87.91, 90.06, 92.22, 91.68, 91.14, 90.59, 89.61, 88.62, 87.63, 89.11, 90.59, 92.06, 92.62, 93.18, 93.74, 92.40, 91.05, 89.70, 85.99, 82.29, 78.58, 77.76, 76.93, 76.10, 77.56, 79.02, 80.49, 82.95, 85.42, 87.88, 86.82, 85.76, 84.70, 79.88, 75.06, 70.24, 72.57, 74.90, 77.23, 80.66, 84.08, 87.50, 87.45, 87.40, 87.36, 87.11, 86.86, 86.61, 85.24, 83.87, 82.51, 83.42, 84.34, 85.25, 86.28, 87.30, 88.32, 89.19, 90.05, 90.92, 88.76, 86.60, 84.44, 79.51, 74.57, 69.63, 67.86, 66.08, 64.31, 66.85, 69.39, 71.92, 74.47, 77.02, 79.57, 80.21, 80.85, 81.48, 84.02, 86.55, 89.08, 90.95, 92.82, 94.69, 94.81, 94.93, 95.05, 95.29, 95.52, 95.76, 93.86, 91.96, 90.06, 90.16, 90.27, 90.38, 89.22, 88.06, 86.90, 85.84, 84.78, 83.72, 10 m agl Dir: 298.95, 302.50, 308.79, 299.63, 292.80, 286.98, 268.80, 267.70, 268.67, 280.31, 288.14, 292.69, 297.80, 302.88, 311.08, 319.73, 325.41, 345.53, 14.91, 55.37, 85.08, 111.53, 154.23, 180.59, 139.45, 94.70, 99.73, 76.02, 82.79, 98.78, 110.05, 119.49, 125.92, 125.22, 131.40, 135.67, 143.81, 156.04, 149.98, 151.57, 138.75, 125.78, 126.24, 115.52, 106.67, 99.56, 108.58, 117.48, 125.86, 141.16, 155.55, 167.60, 169.99, 172.00, 173.71, 173.77, 173.84, 173.91, 173.34, 172.80, 172.27, 176.46, 180.11, 183.29, 181.13, 179.30, 177.74, 178.17, 178.56, 178.91, 178.99, 179.09, 179.20, 192.90, 211.74, 233.35, 238.35, 243.32, 248.17, 248.51, 248.85, 249.21, 256.61, 264.64, 273.04, 282.95, 290.69, 296.70, 304.82, 313.55, 322.54, 324.25, 326.27, 328.69, 326.94, 325.09, 323.14, 325.79, 328.76, 332.07, 332.09, 332.12, 332.14, 343.91, 357.24, 10.88, 25.49, 47.55, 73.75, 86.61, 98.64, 109.03, 114.34, 119.20, 123.59, 120.95, 119.13, 117.81, 119.46, 121.32, 123.43, 124.21, 125.26, 126.74, 130.31, 132.09, 133.15, 135.12, 137.25, 139.57, 143.71, 148.38, 153.60, 176.75, 205.49, 228.70, 232.07, 234.95, 237.43, 249.01, 259.06, 267.38, 268.20, 269.05, 269.92, 10 m agl Spd (kt): 4.00, 4.00, 4.00, 4.00, 4.00, 4.00, 4.00, 4.00, 5.00, 7.00, 7.00, 7.00, 7.00, 7.00, 7.00, 6.00, 5.00, 4.00, 4.00, 3.00, 2.00, 3.00, 3.00, 4.00, 1.00, 3.00, 3.00, 3.00, 3.00, 4.00, 4.00, 4.00, 6.00, 6.00, 6.00, 6.00, 6.00, 6.00, 6.00, 7.00, 5.00, 5.00, 5.00, 5.00, 5.00, 6.00, 6.00, 6.00, 6.00, 6.00, 7.00, 8.00, 8.00, 9.00, 10.00, 10.00, 10.00, 10.00, 10.00, 10.00, 10.00, 11.00, 12.00, 13.00, 14.00, 15.00, 16.00, 17.00, 18.00, 19.00, 18.00, 17.00, 15.00, 13.00, 11.00, 11.00, 11.00, 11.00, 11.00, 11.00, 11.00, 11.00, 10.00, 10.00, 10.00, 11.00, 13.00, 14.00, 14.00, 13.00, 13.00, 12.00, 11.00, 10.00, 10.00, 10.00, 9.00, 9.00, 8.00, 8.00, 7.00, 7.00, 6.00, 6.00, 6.00, 6.00, 5.00, 4.00, 4.00, 4.00, 4.00, 5.00, 5.00, 5.00, 5.00, 6.00, 8.00, 9.00, 8.00, 8.00, 7.00, 6.00, 6.00, 5.00, 7.00, 9.00, 12.00, 11.00, 11.00, 10.00, 10.00, 9.00, 9.00, 7.00, 7.00, 9.00, 9.00, 10.00, 11.00, 11.00, 12.00, 14.00, 14.00, 13.00, 13.00, ###....line 160UA SECTION### 1000mb GPH (m): 166.88, 165.16, 162.34, 159.50, 161.16, 160.70, 161.16, 164.98, 165.70, 164.82, 163.34, 162.34, 158.34, 153.52, 150.18, 147.18, 145.72, 145.72, 145.84, 144.54, 146.00, 146.76, 144.64, 144.12, 144.90, 144.54, 143.18, 141.84, 142.66, 143.94, 144.94, 146.66, 148.78, 148.96, 145.84, 141.84, 136.12, 128.66, 120.44, 116.66, 114.50, 113.42, 116.02, 114.77, 113.53, 112.28, 109.00, 105.72, 102.44, 97.50, 92.56, 87.62, 85.30, 82.99, 80.68, 82.66, 84.64, 86.62, 78.45, 70.28, 62.12, 55.95, 49.78, 43.62, 38.65, 33.68, 28.71, 26.56, 24.41, 22.25, 20.78, 19.30, 17.82, 18.34, 18.86, 19.38, 24.23, 29.07, 33.92, 39.10, 44.28, 49.46, 49.72, 49.99, 50.26, 56.58, 62.90, 69.22, 79.36, 89.50, 99.64, 105.31, 110.98, 116.64, 119.50, 122.35, 125.20, 126.42, 127.64, 128.86, 132.69, 136.51, 140.34, 142.01, 143.67, 145.34, 139.01, 132.67, 126.34, 120.35, 114.37, 108.38, 107.47, 106.57, 105.66, 99.96, 94.27, 88.58, 81.61, 74.65, 67.68, 64.92, 62.16, 59.39, 44.82, 30.25, 15.68, 8.73, 1.77, -5.18, -16.35, -27.52, -38.68, -42.91, -47.13, -51.36, -48.50, -45.64, -42.78, -39.97, -37.16, -34.34, -32.48, -30.62, -28.76, 1000mb GPH DVal(m): 56.00, 54.28, 51.46, 48.62, 50.28, 49.82, 50.28, 54.09, 54.82, 53.93, 52.46, 51.46, 47.46, 42.64, 39.30, 36.30, 34.84, 34.84, 34.96, 33.66, 35.12, 35.87, 33.75, 33.23, 34.02, 33.66, 32.30, 30.96, 31.77, 33.05, 34.05, 35.77, 37.89, 38.07, 34.96, 30.96, 25.23, 17.77, 9.55, 5.77, 3.61, 2.53, 5.14, 3.89, 2.64, 1.40, -1.88, -5.17, -8.45, -13.39, -18.33, -23.27, -25.58, -27.89, -30.21, -28.23, -26.25, -24.27, -32.43, -40.60, -48.77, -54.94, -61.10, -67.27, -72.24, -77.20, -82.17, -84.33, -86.48, -88.63, -90.11, -91.59, -93.07, -92.55, -92.02, -91.50, -86.66, -81.81, -76.97, -71.79, -66.61, -61.43, -61.16, -60.89, -60.63, -54.30, -47.98, -41.66, -31.52, -21.38, -11.24, -5.58, 0.09, 5.76, 8.61, 11.46, 14.32, 15.54, 16.76, 17.98, 21.80, 25.63, 29.46, 31.12, 32.79, 34.46, 28.12, 21.79, 15.46, 9.47, 3.48, -2.50, -3.41, -4.32, -5.23, -10.92, -16.61, -22.31, -29.27, -36.24, -43.20, -45.97, -48.73, -51.49, -66.06, -80.63, -95.20, -102.16, -109.11, -116.07, -127.23, -138.40, -149.57, -153.79, -158.02, -162.25, -159.39, -156.53, -153.67, -150.85, -148.04, -145.23, -143.37, -141.51, -139.65, 1000mb Temp (K): 283.88, 283.48, 283.09, 282.57, 282.16, 281.83, 281.51, 281.33, 282.10, 282.98, 283.56, 284.11, 284.78, 285.36, 285.80, 285.93, 285.93, 285.70, 284.88, 284.21, 283.76, 283.39, 282.76, 282.08, 281.82, 281.54, 281.03, 280.67, 280.38, 280.28, 280.23, 280.44, 282.13, 284.26, 285.90, 286.92, 287.64, 288.15, 288.42, 288.76, 288.83, 288.58, 288.07, 287.99, 287.90, 287.81, 287.87, 287.93, 287.98, 288.04, 288.09, 288.15, 288.63, 289.10, 289.58, 290.41, 291.24, 292.07, 292.93, 293.79, 294.66, 295.37, 296.08, 296.79, 296.65, 296.51, 296.37, 295.86, 295.34, 294.83, 294.26, 293.69, 293.13, 292.67, 292.20, 291.74, 290.46, 289.18, 287.91, 287.13, 286.35, 285.57, 286.00, 286.42, 286.84, 286.70, 286.56, 286.43, 285.97, 285.52, 285.07, 284.78, 284.49, 284.20, 283.95, 283.70, 283.45, 283.31, 283.17, 283.03, 282.94, 282.84, 282.75, 283.01, 283.27, 283.53, 284.01, 284.50, 284.98, 285.48, 285.98, 286.48, 286.25, 286.02, 285.79, 285.50, 285.22, 284.93, 284.73, 284.53, 284.34, 284.12, 283.91, 283.70, 283.85, 284.01, 284.16, 284.62, 285.07, 285.52, 286.27, 287.02, 287.77, 288.59, 289.41, 290.24, 289.73, 289.22, 288.72, 288.49, 288.27, 288.05, 287.72, 287.40, 287.07, 1000mb Temp DVal(K): -3.56, -3.96, -4.35, -4.87, -5.28, -5.61, -5.93, -6.11, -5.34, -4.46, -3.88, -3.33, -2.66, -2.08, -1.64, -1.51, -1.51, -1.74, -2.56, -3.23, -3.68, -4.05, -4.68, -5.36, -5.62, -5.90, -6.41, -6.77, -7.06, -7.15, -7.21, -7.00, -5.31, -3.17, -1.53, -0.51, 0.20, 0.71, 0.98, 1.32, 1.39, 1.14, 0.63, 0.55, 0.46, 0.37, 0.43, 0.49, 0.55, 0.60, 0.65, 0.71, 1.19, 1.67, 2.14, 2.97, 3.80, 4.63, 5.49, 6.35, 7.22, 7.93, 8.64, 9.36, 9.21, 9.07, 8.93, 8.42, 7.90, 7.39, 6.82, 6.26, 5.69, 5.23, 4.76, 4.30, 3.02, 1.74, 0.47, -0.31, -1.09, -1.87, -1.44, -1.02, -0.60, -0.74, -0.88, -1.01, -1.47, -1.92, -2.37, -2.66, -2.95, -3.24, -3.49, -3.74, -3.99, -4.13, -4.27, -4.41, -4.50, -4.59, -4.68, -4.43, -4.17, -3.91, -3.43, -2.94, -2.45, -1.96, -1.46, -0.96, -1.19, -1.42, -1.65, -1.94, -2.22, -2.51, -2.71, -2.91, -3.10, -3.32, -3.53, -3.74, -3.59, -3.43, -3.28, -2.82, -2.37, -1.92, -1.17, -0.42, 0.33, 1.15, 1.97, 2.80, 2.29, 1.78, 1.28, 1.06, 0.83, 0.61, 0.28, -0.04, -0.37, </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T17:58:34.783", "Id": "531513", "Score": "1", "body": "Is all your Python in one file? Could you format it as such here? Could you give a few more lines of your text file, so that we could copy and paste it into our own copy of the text file to run your script?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T18:19:04.967", "Id": "531515", "Score": "0", "body": "I updated the code with the full context, you should be able to save that text file in a folder called data/2021102206Z.txt and call run_test()" } ]
[ { "body": "<ul>\n<li><code>pass</code> is for when Python requires you to have <em>something</em>, but there's nothing else to have. So it works in the <code>except</code> clauses, but otherwise isn't necessary.</li>\n<li>But catching an exception without doing anything else is usually a bad idea. You want to know that something happened, especially if you're dealing with sloppy data. The only occurrence I ran into was an IndexError on the <code>###</code> line. I added a conditional to avoid that, and removed the <code>except</code> clauses.</li>\n<li>Classes automatically inherit from object; you don't need to do so explicitly.</li>\n<li>Don't use <code>list(map)</code> instead of a for loop in <code>Tarp.__init__</code>. Generally, comprehensions are better than <code>map</code>.</li>\n<li>Having <code>_pythonic_keys</code> sometimes return a str and sometimes False is a bit odd. Since you're testing its truthiness, lets return None instead of False.</li>\n<li>But actually, it turns out that <code>_pythonic_key</code> doesn't need its <code>if</code> check. If the string is only whitespace, then (formerly) <code>v</code> ended up empty which caused an IndexError and nothing happened. Now, <code>key</code> ends up empty for a quick return.</li>\n<li>I find it much easier to read a simple regular expression than to remember what it's doing from the variable name. One could argue that compiling them gives a bit of efficiency, but (1) that's way too premature of an optimization and (2) Python caches its regexs, so it doesn't end up being an optimization anyway.</li>\n<li><code>Object</code> is a terrible name for a class. Maybe <code>KeysList</code>? But for that matter, the only point of the <code>props</code> and <code>models</code> property is for the key/value object that it's keeping. Python already does that with dicts, so lets use dicts instead. (If you really needed a key/value object, a <a href=\"https://docs.python.org/3/library/collections.html#collections.namedtuple\" rel=\"nofollow noreferrer\">Named Tuple</a> could do the job.)</li>\n<li>Now we realize that the zip functions are really just returning the dicts, so lets do that instead. Also, you never used <code>zip_props</code>. And <code>asMatrix</code> is just using the dict values. This eliminates the need for <code>getmodels</code> and <code>getprops</code>.</li>\n<li>You ended up with <code>forecast_hours</code> in <code>props</code> with a value that was everything else. I assume that was a bug, and moved it to <code>models</code>.</li>\n<li>Single letter variables are ok for a short time and if their meaning is clear. <code>k</code> and <code>v</code> (kind of) pass this test, but <code>s</code> and <code>f</code> don't.</li>\n<li>Overwriting <code>v</code> makes it a bit harder to debug. But <code>val</code> doesn't gain you much, so I repurposed <code>val</code> to be the new <code>v</code> (and got rid of the old <code>val</code>).</li>\n<li><code>_pythonic_vals</code> does not behave like <code>_pythonic_keys</code>. It seems that the main purpose is to remove the final entry. But it shouldn't unilaterally do that without looking at that final entry.</li>\n<li><code>_series</code> takes a line of text, constructs a length 1 series, and then splits it. Don't go through pandas just to split. I had a hard time understanding this method in general, as it had several of these items that I changed.</li>\n<li>In a similar spirit of avoiding unnecessary methods, I would avoid using regex when you can do the same thing with string methods (eg, <code>_only_wspace</code> and <code>_units</code>).</li>\n<li>Your comment says that <code>_series</code> splits on : or , or whitespace, but it's really : or , and strips whitespace after that. I would consider that statement too obvious to comment, and you definitely don't want a comment to be in conflict with the code.</li>\n<li><code>_pythonic_key</code> is only called from within <code>Tarp</code>, so I moved it there. I also made it a <a href=\"https://docs.python.org/3/library/functions.html#staticmethod\" rel=\"nofollow noreferrer\">staticmethod</a>.</li>\n<li>I added type hints, so that you can run <code>python -m mypy thisfile.py</code>.</li>\n<li>I added a <code>__main__</code> guard, so that this could end up in its own package. I also added a few more <code>print</code> statements to <code>run_test()</code>.</li>\n<li>You switch between &quot; and '. If there's a reason for that, that would be fine. If not, you should be more consistent.</li>\n</ul>\n<pre><code>import numpy as np # type: ignore\nimport pandas as pd # type: ignore\nimport re\nfrom datetime import datetime\nfrom typing import Dict,List,TextIO,Union\n\nclass Tarp:\n def __init__(self, filein: TextIO):\n self.props: Dict[str,Union[str,datetime]] = {}\n self.models: Dict[str,np.array] = {}\n for line in filein:\n self._series(line)\n @staticmethod\n def _pythonic_key(s:str) -&gt; str:\n return re.sub(r'\\s+','_',s.split('(',1)[0].rstrip()).lower()\n def _series(self, line: str) -&gt; None:\n rowentries: List[str] = re.split(r':\\s*|,\\s*',line)\n key: str = self._pythonic_key(rowentries.pop(0))\n if rowentries:\n if not re.search(r'\\S',rowentries[-1]):\n rowentries.pop()\n if not key or not rowentries:\n return\n if len(rowentries)&gt;1:\n self.models[key] = np.array(rowentries, dtype=float)\n else:\n val: str = rowentries[0].rstrip()\n if key == 'basetime':\n self.props[key] = datetime.strptime(val, '%Y%m%d%HZ')\n elif key == 'forecast_hours':\n self.models[key] = np.array( [ t.rstrip('hr') for t in val.split() ] ,\n dtype=int)\n else:\n self.props[key] = val\n def asMatrix(self) -&gt; np.array:\n return np.array( self.models.values() )\n def asDataFrame(self) -&gt; pd.DataFrame:\n return pd.DataFrame(self.models)\n\ndef run_test():\n with open('data/2021102206Z.txt', 'r') as filein:\n tp = Tarp(filein)\n print('props:',tp.props)\n df = tp.asDataFrame()\n print(df.shape)\n print(df.dtypes)\n print(type(df))\n print(df)\n m = tp.asMatrix()\n print(type(m))\n\nif __name__ == '__main__':\n run_test()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T02:10:44.200", "Id": "269482", "ParentId": "269398", "Score": "0" } } ]
{ "AcceptedAnswerId": "269482", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T17:52:22.150", "Id": "269398", "Score": "1", "Tags": [ "python", "parsing", "regex", "numpy", "pandas" ], "Title": "using pandas and numpy to parse dirty .csv" }
269398
<p>I'm new to programming and have been teaching myself to code for about 6 months. Since I have no one to ask about any of coding-related questions, I may have developed bad habits in the meantime, but I can't tell myself. As such, I wrote a simple blackjack game in Python, to demonstrate how I usually code, and to find out if there is something I should've done (or I shouldn't have done).</p> <p>This is the start of the code.</p> <pre><code>from random import shuffle, uniform from os import system, name, get_terminal_size as tsize from time import sleep </code></pre> <p>This is <code>Card</code> class. I don't like <code>display()</code> method, because it's too ugly (especially with some fonts that breaks the shape). But I'm not sure how to improve this. I'm also not sure where should I place <code>sdict</code> and <code>color</code>. Currently, it's a class variable. Should I pull these out of <code>Card</code> class and put it on top? And I don't know when exactly I should implement those getters/setters. I just make them every time. Is this a bad practice? Lastly, <code>uid</code> is doing nothing currently but I put it there just in case. Should I remove such useless things on main branch and only leave it on test/dev branch?</p> <pre><code>class Card(object): sdict = {'S': '♤', 'H': '♡', 'D': '♢', 'C': '♧'} color = {'r': '\033[1;31;49m', 'w': '\033[1;37;49m'} def __init__(self, suit, rank, uid): self.suit = suit self.symbol = Card.sdict[suit[0]] self.rank = rank self.uid = uid self.is_red = self.suit[0] in 'HD' self.value = 10 + (rank[0] == 'A') if rank.isalpha() else int(rank) def __str__(self): r = self.get_rank() if self.is_red: return Card.color['r'] + self.symbol + r + Card.color['w'] return self.symbol + r def get_suit(self, colored=0) -&gt; str: if colored and self.is_red: return Card.color['r'] + self.suit + Card.color['w'] return self.suit def get_symbol(self, colored=0) -&gt; str: if colored and self.is_red: return Card.color['r'] + self.symbol + Card.color['w'] return self.symbol def get_rank(self, colored=0) -&gt; str: r = self.rank[0] if self.rank != '10' else self.rank if colored and self.is_red: return Card.color['r'] + r + Card.color['w'] return r def get_uid(self) -&gt; int: return self.uid def get_value(self) -&gt; int: return self.value def display(self, hide=0) -&gt; list[str]: if hide: lines = ['┏━━━━━━━━━━━┓' if not i else '┃███████████┃' if i != 10 else '┗━━━━━━━━━━━┛' for i in range(11)] return lines pad = ' ' * (self.get_rank() != '10') is_alpha = self.get_rank().isalpha() sym, val = self.get_symbol(1) + ' ', self.get_value() mid_cen = (sym * (val in (1, 3, 5, 9) or is_alpha)).ljust(2) midside = (sym * (5 &lt; val &lt; 9)).ljust(2) rdiff_1 = (sym * (val in (9, 10) and not is_alpha)).ljust(2) row_2up = (sym * (val in (7, 8, 10) and not is_alpha)).ljust(2) row_2dn = (sym * (val in (8, 10) and not is_alpha)).ljust(2) corners = (sym * (val &gt; 3 and not is_alpha)).ljust(2) top_bot = (sym * (val in (2, 3))).ljust(2) lines = [ '┏━━━━━━━━━━━┓', '┃{} ┃'.format(self.get_rank(1) + pad), '┃ {} {} {} ┃'.format(corners, top_bot, corners), '┃ {} ┃'.format(row_2up), '┃ {} {} ┃'.format(rdiff_1, rdiff_1), '┃ {} {} {} ┃'.format(midside, mid_cen, midside), '┃ {} {} ┃'.format(rdiff_1, rdiff_1), '┃ {} ┃'.format(row_2dn), '┃ {} {} {} ┃'.format(corners, top_bot, corners), '┃ {}┃'.format(pad + self.get_rank(1)), '┗━━━━━━━━━━━┛' ] return lines </code></pre> <p>This is <code>Shoe</code> class, which doesn't do much. I could just handle the job on <code>Blackjack</code> class, or merge this into <code>Card</code> class, or separate the job into many classes. I'm not sure which task deserves its own class. And should I avoid using the <code>print</code> on <code>__init__</code>? Also, is there any way to use type hint with the default parameter value (like <code>num_decks=6</code> and <code>vb=False</code>)?</p> <pre><code>class Shoe(object): def __init__(self, num_decks=6, vb=False): print(f'Generating a dealing shoe with {num_decks} decks', end='') self.shoe = self.build_shoe(num_decks) print('\nShuffling the cards...' if vb else '', end='') shuffle(self.shoe) print('\nGenerating a random cut' if vb else '', end='') self.shoe = self.cut_deck(self.shoe) print(f'\nRemoved {52 * num_decks - len(self.shoe)} cards ' f'({len(self.shoe)} cards remaining)' if vb else '', end='') print() @staticmethod def build_shoe(num_decks: int) -&gt; list[Card]: suits = 'Spade Heart Diamond Club'.split() ranks = 'Ace 2 3 4 5 6 7 8 9 10 Jack Queen King'.split() shoe = [] for _ in range(num_decks): for suit in suits: for rank in ranks: shoe.append(Card(suit, rank, len(shoe))) return shoe @staticmethod def cut_deck(shoe: list[Card], minimum=0.30, maximum=0.50) -&gt; list[Card]: cut = uniform(minimum, maximum) del shoe[:int(len(shoe) * cut)] return shoe def get_shoe(self) -&gt; list[Card]: return self.shoe def get_length(self) -&gt; int: return len(self.shoe) def deal(self, num_cards=1) -&gt; list[Card]: cards = [] for _ in range(num_cards): cards.append(self.shoe.pop(0)) return cards </code></pre> <p>This is <code>Hand</code> class. Should I always try to reduce the number of iterations? For example, <code>self.total_value</code>, <code>self.num_aces</code> and <code>self.hand_value</code> can be calculated in one sweep, but it will result in vertically longer code (though shorter horizontally). Even if the expected number of iterations is low, should I try to reduce it? Also, should I strictly limit the number of characters to 79? or is it merely a suggestion?</p> <pre><code>class Hand(object): def __init__(self, hand=None): self.hand = [] if hand is None else hand self.total_value = sum(c.get_value() for c in self.hand) if self.hand else 0 self.num_aces = sum(c.get_value() == 11 for c in self.hand) if self.hand else 0 self.hand_value = 0 self.set_hand_value() self.decision = '' def add_cards(self, cards: list[Card]) -&gt; None: for card in cards: self.hand.append(card) self.total_value += (v := card.get_value()) self.num_aces += 1 if v == 11 else 0 self.set_hand_value() def get_hand(self) -&gt; list[Card]: return self.hand def get_printable(self, reveal=22) -&gt; list[str]: cards = [c.display() if reveal &gt; i else c.display(hide=True) for i, c in enumerate(self.hand)] return [' '.join(c[i] for c in cards) for i in range(len(cards[0]))] def get_hand_value(self) -&gt; int: return self.hand_value def set_hand_value(self) -&gt; None: if self.total_value &lt;= 21: self.hand_value = self.total_value t, n = self.total_value, self.num_aces while n and t &gt; 21: n -= 1 t -= 10 self.hand_value = t def get_decision(self) -&gt; str: return self.decision def set_decision(self, decision: str) -&gt; None: self.decision = decision def length(self) -&gt; int: return len(self.hand) def is_busted(self) -&gt; bool: return self.get_hand_value() &gt; 21 def is_blackjack(self) -&gt; bool: return self.length() == 2 and self.hand_value == 21 def is_playable(self) -&gt; bool: return not (self.get_hand_value() &gt;= 21 or self.decision in ('s', 'dd')) def is_splittable(self) -&gt; bool: return self.length() == 2 and self.hand[0].get_value() == self.hand[1].get_value() </code></pre> <p>and lastly, <code>Blackjack</code> class and <code>if __name__ == '__main__':</code> thingy. It is very messy but I always ended up like this somehow. Maybe it's because I usually don't plan anything ahead and just dive right into coding, but then again, I don't know what exactly I should plan ahead.</p> <pre><code>class Blackjack(object): def __init__(self): self.nt = name == 'nt' self.cls() print('\033[1;37;49mWelcome to the game of Blackjack', end='') self.shoe = self.generate_shoe() self.bankroll = self.get_int_input( f'\nEnter your bankroll [$100-$100m] (Default: ${50_000:,}): ', int(1e8), 100, 50_000) self.min_bet = max(5, self.bankroll // 1000 // 1000 * 1000) self.dealer = Hand() self.player = [Hand()] self.bet = 0 self.initial_bet = 0 self.num_round = 0 self.play() def generate_shoe(self) -&gt; Shoe: d = 6 msg = f'\nEnter the number of decks [2-12] (Default: {d}): ' return Shoe(self.get_int_input(msg, 12, 2, d), vb=True) @staticmethod def get_int_input(msg: str, hi=6, lo=2, default=6) -&gt; int: user_input = lo - 1 while user_input &lt; lo or user_input &gt; hi: try: tmp = input(msg) user_input = int(tmp) if tmp != '' else default if not (lo &lt;= user_input &lt;= hi): print('Input out of range. Please try again.') except ValueError: print('Invalid input. Please try again.') return user_input @staticmethod def get_bool_input(msg: str, opt='YN') -&gt; bool: user_input = '1' while user_input.upper()[0] not in opt: user_input = input(msg) if user_input == '': user_input = opt[0] return user_input.upper().startswith('Y') @staticmethod def take_decision(hand: Hand, msg: str, possibles: list[str]) -&gt; None: decision = '' if hand.length() &gt; 2: del possibles[2:] elif not hand.is_splittable(): del possibles[3:] opt = '/'.join(c if i else c.upper() for i, c in enumerate(possibles)) while decision[:2].lower() not in possibles: decision = input(msg + '[' + opt + ']: ') decision = possibles[0] if decision == '' else decision hand.set_decision(decision) def take_bet(self) -&gt; None: d = max(self.min_bet, self.bankroll // 1000 // 1000 * 10) msg = f'Place your bet (Default: ${d}): ' self.bet = self.get_int_input(msg, hi=self.bankroll, lo=self.min_bet, default=d) self.initial_bet = self.bet self.bankroll -= self.bet def get_insurance_premium(self) -&gt; int: premium = 0 if self.dealer.get_hand()[0].get_rank().startswith('A'): if self.get_bool_input('Do you want to take an insurance [y/N]? ', 'NY'): premium = self.initial_bet // 2 self.bankroll -= premium return premium def print_board(self, rv=22) -&gt; None: self.cls() width = tsize()[0] print(f'Bet: {self.bet:,}'.ljust((w := width // 3)) + f'Round {self.num_round}'.center(w) + f'Bankroll: {self.bankroll:,}'.rjust(w)) print(f'\n\nDealer' + (rv &gt; 0) * f': {&quot; &quot;.join([str(c) for c in self.dealer.get_hand()][:rv])}' + (rv &gt; 1) * f' ({self.dealer.get_hand_value()})') print('\n'.join([line for line in self.dealer.get_printable(rv)])) for i, h in enumerate(self.player): n = f'{(&quot; (Hand &quot; + str(i + 1) + &quot;)&quot;) * (len(self.player) &gt; 1)}' print(f'\nPlayer{n}: {&quot; &quot;.join([str(card) for card in h.get_hand()])}' f' ({h.get_hand_value()})') print('\n'.join([line for line in h.get_printable()])) def get_payout(self) -&gt; int: payout, dv, lp = 0, self.dealer.get_hand_value(), len(self.player) for i, h in enumerate(self.player): n = f'Hand {i + 1}' if lp &gt; 1 else 'You' hv, dd = h.get_hand_value(), 1 + (1 * (h.get_decision() == 'dd')) if h.is_busted() or hv &lt; dv &lt;= 21: print(f'{n} lose') continue if dv &gt; 21 or hv &gt; dv: print('Dealer busted. ' * (dv &gt; 21) + f'{n} win') payout += self.initial_bet * (2.5 if h.is_blackjack() else 2) * dd elif dv == hv: print('Tie') payout += self.initial_bet * dd return payout def cls(self) -&gt; None: if self.nt: system('cls') else: system('clear') def round(self) -&gt; None: self.cls() self.take_bet() self.dealer.__init__(self.shoe.deal(2)) self.player = [Hand(self.shoe.deal(2))] if not self.player[0].is_blackjack(): while any(h.is_playable() for h in self.player): for i, hand in enumerate(self.player): if not hand.is_playable(): continue self.print_board(rv=0) s = f'(Hand {i + 1}) ' * (len(self.player) &gt; 1) self.take_decision(hand, f'Enter your decision {s}', 'h s dd sp'.split()) if (d := hand.get_decision()) != 's': self.bankroll -= self.initial_bet if d in ('dd', 'sp') else 0 self.bet += self.initial_bet if d in ('dd', 'sp') else 0 if d == 'sp': self.player += [Hand([hand.get_hand()[0]]), Hand([hand.get_hand()[1]])] del self.player[i] break hand.add_cards(self.shoe.deal(1)) in_play = not all(h.is_busted() for h in self.player) self.print_board(rv=1) sleep(0.5) premium = self.get_insurance_premium() if in_play else 0 self.print_board() while self.dealer.get_hand_value() &lt; 17 and in_play: self.dealer.add_cards(self.shoe.deal(1)) sleep(0.5) self.print_board() payout = self.get_payout() self.bankroll += payout print(f'You received a payout of ${payout}') if premium and self.dealer.get_hand()[1].get_value() == 10: self.bankroll += premium * 2 print(f'You received an insurance payout of ${premium * 2}') def play(self) -&gt; None: more = True while more and self.bankroll &gt;= self.min_bet: self.num_round += 1 self.round() more = self.get_bool_input('Do you want to play more rounds [Y/n]? ', 'YN') if (ls := self.shoe.get_length()) &lt; 15: msg = f&quot;Only {ls} cards left in dealer's shoe. &quot; msg += &quot;Do you want to replenish the shoe [Y/n]? &quot; if self.get_bool_input(msg, 'YN'): self.shoe = self.generate_shoe() else: print(&quot;Game Over (too few cards remaining)&quot;) break if __name__ == '__main__': Blackjack() </code></pre> <p>Feel free to tell me anything that I could improve my code, style, etc, and anything I should, or shouldn't have done. Lastly, I'd like to know what kind of speed I should aim for. This took some hours for me to code (1 &lt; h &lt; 10). Should I aim for &lt; 60 minutes? or &lt; 30 mins? Thank you in advance.</p> <p><strong>EDIT</strong>: <a href="https://github.com/e1630m/blackjack/blob/main/blackjack.py" rel="nofollow noreferrer">this</a> is a link to the most recent version of my blackjack code for anyone who is interested.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T03:49:32.343", "Id": "531539", "Score": "0", "body": "is the program exclusive to unix runtime?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T06:41:02.687", "Id": "531548", "Score": "0", "body": "@hjpotter92 No. AFAIK, it works everywhere. But it may not run on vanilla PyCharm due to `os.system()` and `os.get_terminal_size()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T06:55:35.433", "Id": "531550", "Score": "0", "body": "it won't work on windows/powershell too, due to the color code and symbols." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T07:25:31.087", "Id": "531556", "Score": "0", "body": "Strange because I've tested on 3 different Windows environments. [1](https://i.imgur.com/77wpdg4.png) [2](https://i.imgur.com/EvgQs60.png) [3](https://i.imgur.com/0o8bh0k.png)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T08:47:02.757", "Id": "531560", "Score": "0", "body": "https://i.stack.imgur.com/pq8XA.png this is in the plain powershell provided and is not the fluent based windows terminal" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T09:00:26.443", "Id": "531564", "Score": "0", "body": "I believe that's just a font-related problem as some fonts don't have the `♤♡♢♧` unicode characters. If you use `sdict = {'S': '♠', 'H': '♥', 'D': '♦', 'C': '♣'}`, it'll work on [pwsh.exe](https://i.imgur.com/ekxbE6y.png) as well as [powershell.exe](https://i.imgur.com/Ej6VrEB.png)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T08:48:52.270", "Id": "531833", "Score": "0", "body": "I don't understand where is defined variable `list`? Because `def display(self, hide=0) -> list[str]:` gives error `TypeError: 'type' object is not subscriptable`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T20:36:37.340", "Id": "531889", "Score": "0", "body": "@JosefZ I have the same problem. I believe this might be a python-version issue, since I think the type-weenies are pushing to get things like this to work. `list` is, of course, a built-in function when it's not being treated as a Subscriptable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T09:35:03.743", "Id": "532241", "Score": "0", "body": "@JosefZ That's type hints. You can either a) remove `list[str]` and `list[Card]` thing everywhere, or b) use python 3.9 or above, or c) use python 3.5 or above and do this `from typing import List` and change `list[str]` to `List[str]`." } ]
[ { "body": "<h3>Planning ahead</h3>\n<blockquote>\n<p>It is very messy but I always ended up like this somehow. Maybe it's because I usually don't plan anything ahead and just dive right into coding, but then again, I don't know what exactly I should plan ahead.</p>\n</blockquote>\n<p>I recommend to work in baby steps.\nThink of the next valuable feature, in its simplest form,\nand implement just that.\nWhen you are done with a baby step, pause and take a step back,\nreview what you did considering the bigger picture of your ultimate goal,\nand verify that you're still going in the right direction, or else revert.</p>\n<p>For example here, I would first implement the most basic game possible,\nwithout many of the features you currently have:</p>\n<ul>\n<li>no fancy output, no colors</li>\n<li>no shoe feature</li>\n<li>play just one game</li>\n<li>implement the essential rules only, without payout, insurance, etc</li>\n<li>... and so on ...</li>\n</ul>\n<p>If that had been your first post,\nreviewers could have focused on the high level design,\nand could have provided early guidance to prevent going down paths that are not very useful and time consuming.</p>\n<h3>Keeping things simple</h3>\n<p>Every piece of code is a burden.\nIt has to be understood and maintained.\nTherefore it's important that every piece of code is useful.</p>\n<p>If you don't fully understand why something is there, I suggest to delete it.\nIf the program doesn't work without it, try to understand why.</p>\n<hr />\n<blockquote>\n<p><code>uid</code> is doing nothing currently but I put it there just in case.</p>\n</blockquote>\n<p>Drop it. It's not useful. The reader has to understand it, and in fact there's nothing to understand, because it really has no purpose right now.\nIt's a friction for the reader at every occurrence of <code>uid</code> in this program.\nFor example:</p>\n<ul>\n<li>When reading the constructor of <code>Card</code>, I'm wondering what is this for.</li>\n<li>When trying to create a <code>Card</code>, I'm wondering what value I should pass, and what will be the consequences.</li>\n</ul>\n<p>If it's not there, I save many unnecessary mental cycles.</p>\n<hr />\n<p>Remove anything that is not used.\nFor example <code>Card.get_suit</code>.</p>\n<p>Another example is the <code>colored</code> parameter of <code>get_symbol</code>: the function is only ever called with <code>colored=1</code>, so the parameter is not useful.</p>\n<p>Do this recursively, after you removed something,\ncheck what else has become unused.\nFor example, after removing <code>Card.get_suit</code>,\nit turns out that <code>self.suit</code> is also not used.</p>\n<p>If you had built up the code from scratch only adding what is absolutely necessary in each step,\nthen there would be less to remove now,\nless code to review and to understand,\ntherefore less mental burden.</p>\n<hr />\n<p><code>Card.display</code> is extremely hard to understand and to maintain.\nIf there was a separate template for each card,\nthat would be easy to understand and to maintain,\neven if that will make the program longer,\nit would be a good tradeoff.</p>\n<p>Optimize code for reading, first.\nIf there are problems with that,\nfix it in a later step, if really important.</p>\n<h3>Avoid recomputing values that are not supposed to change</h3>\n<p>For example <code>Card.get_symbol</code> will recompute the symbol on every call,\nbased on values that never change after the card is created.\nIt would be better to compute this only once,\nat the time the card is created.\nThe same goes for <code>Card.get_rank</code>, <code>Card.__str__</code>.</p>\n<h3>Avoid duplicated logic</h3>\n<p>This code pattern appears in many places in <code>Card</code>:</p>\n<blockquote>\n<pre><code>Card.color['r'] + something + Card.color['w']\n</code></pre>\n</blockquote>\n<p>It would be better to extract this logic to a common function with a descriptive name.\nIt will make it easier to understand the code,\nand if you need adjust the logic in the future,\nyou will be able to do it in one place.</p>\n<h3>Hide implementation details</h3>\n<p><code>Hand.set_hand_value</code> is only used internally within <code>Hand</code>.\nIt should not never be called from outside.\nTo signal this to readers, rename with a single underscore <code>_</code> prefix.</p>\n<h3>Consider real life objects to guide your design</h3>\n<p><code>Hand.add_cards</code> looks strange, because the name is plural.\nWhen in a game of Blackjack do we ever add more than one card to the hand?\nI think never, so this is confusing.</p>\n<p>An <code>add_card</code> function that takes a single <code>Card</code> parameter would be natural.</p>\n<h3>Other technical Python coding issues</h3>\n<p>Several methods in <code>Card</code> take a <code>colored</code> parameter with values 0 or 1, and used in boolean context. The parameter should be a proper boolean.</p>\n<hr />\n<p>The <code>if self.hand else 0</code> is unnecessary:</p>\n<blockquote>\n<pre><code>self.hand = [] if hand is None else hand\nself.total_value = sum(c.get_value() for c in self.hand) if self.hand else 0\nself.num_aces = sum(c.get_value() == 11 for c in self.hand) if self.hand else 0\n</code></pre>\n</blockquote>\n<p>You asked if it would be better to make only one pass over <code>self.hand</code>,\nand compute <code>total_value</code> and <code>num_aces</code> in that loop.\nYes, one pass is usually better than 2.</p>\n<hr />\n<p>Instead of the many <code>get_</code> methods,\nconsider using <a href=\"https://realpython.com/python-property/\" rel=\"noreferrer\">properties</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T23:44:26.193", "Id": "532423", "Score": "0", "body": "`Hand.add_cards`: I'm not familiar with blackjack, and I thought they initially deal 2 cards at once and then start to deal one card (just like I did on `Blackjack.round`). After watching a few blackjack tournament videos, I realized that's not the case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T23:46:56.007", "Id": "532424", "Score": "0", "body": "`if self.hand else 0`: I put it there because `sum(None)` will break when `hand is None` (this happens on `Blackjack.__init__`). I could just start with something like `hand = [] if hand is None else hand` and remove `if else` for those three variables, or change `self.dealer` and `self.player` on `Blackjack.__init__` to be initialized with a dummy card, or remove the `self.dealer` and `self.player` from `Blackjack.__init__` altogether and call new instance of `Hand` with a card every round. I'm going to modify my code for the last option." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T05:31:58.707", "Id": "532446", "Score": "0", "body": "@e1630m `self.hand = [] if hand is None else hand` makes sure that `self.hand` is not `None`, and that's why you don't need the `if self.hand else 0` on the next two lines" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T07:47:58.270", "Id": "532448", "Score": "0", "body": "Oops. I mistakenly wrote the comment after checking the slightly modified version that does the job in one sweep but iterates over `hand` not `self.hand`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T15:10:10.727", "Id": "269586", "ParentId": "269400", "Score": "5" } }, { "body": "<ul>\n<li>Don't inherit from <code>(object)</code>; Python 2 needs to die (and you already rely on Python 3 given your current code)</li>\n<li>An OO approach would have a <code>Suit</code> class (even if it's a lightweight named tuple) with properties of, perhaps: symbol, name, letter, colour. This is a little less awkward than <code>is_red</code>. These properties can then be factored away from <code>Card</code>, and only a reference to a suit object kept for each card.</li>\n<li>Having the <code>color</code> dictionary on <code>Card</code> doesn't make much sense; you'll want to have a module or class that takes care of screen operations such as clear, and ANSI escape sequences for colour etc.</li>\n<li>The pattern <code>Card.color['r'] + self.symbol + r + Card.color['w']</code> calls out for a utility or two. One pattern you could follow is a <code>@contextmanager</code> that sets the colour, runs the inner code, and then clears the colour after (even if an exception is thrown).</li>\n<li>You have some typehints - good! But they're inconsistent. For instance,</li>\n</ul>\n<pre><code> def get_symbol(self, colored=0) -&gt; str:\n</code></pre>\n<p>needs a hint for <code>colored</code>. Since you asked, your <code>hand=None</code> should be <code>hand: Optional[List[Card]] = None</code>.</p>\n<ul>\n<li>Your <code>Blackjack</code> constructor shouldn't be responsible for running the entire game; just initialisation.</li>\n<li>The call <code>self.dealer.__init__()</code> is concerning. Presumably that object is already initialised via <code>Hand()</code>, so - calling it again is surprising. If you just want to replace the instance, replace the instance.</li>\n<li><code>length</code>, <code>is_busted</code> etc. are a good fit to be <code>@property</code>s. The purpose of a property is not particularly to do a character-by-character code length trade; it's to communicate to callers of your class that certain values from your class are available without needing to pass parameters, ideally without mutating the class, and without a whole lot of computation. Properties are also convenient when using modern debuggers as they appear without having to be explicitly called.</li>\n<li>You have some manually-formatted currency strings. <a href=\"https://docs.python.org/3.8/library/locale.html#locale.currency\" rel=\"nofollow noreferrer\">locale.currency</a> is made for this.</li>\n<li><code>self.bankroll // 1000 // 1000 * 1000</code> seems like you're doing a little bit of trickery to get a round effect. That's less obvious than just calling <a href=\"https://docs.python.org/3/library/functions.html#round\" rel=\"nofollow noreferrer\">round</a>. You say <em>I was trying to give two different <code>min_bet</code> for users. $5 for someone with less than $1 million bankroll, and roughly 0.1% of bankroll rounded down to a thousand dollars for someone with a million or above bankroll.</em> Clear code for this behaviour is important (also, don't name a variable <code>d</code>):</li>\n</ul>\n<pre><code>if self.bankroll &lt; 1e6:\n default = self.min_bet\nelse:\n default = round(self.bankroll/1000, -3)\n</code></pre>\n<ul>\n<li><code>user_input &lt; lo or user_input &gt; hi</code> is equivalent to <code>not (lo &lt;= user_input &lt;= hi)</code></li>\n<li>Apparently this is <a href=\"https://meta.stackexchange.com/questions/87251/use-m-for-million-instead-of-m\">controversial</a>, but my opinion is that $100m is ten cents. $100M is 100 million dollars.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T23:34:02.743", "Id": "532420", "Score": "0", "body": "`(object)`: Thanks. I didn't know `(object)` was a Python 2 thing. I saw some classes have these bits, while some don't, and started to put it everywhere without any understanding." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T23:34:25.723", "Id": "532421", "Score": "0", "body": "**Type hints**: I didn't know how to use type hints with default parameters. Hence, `colored=0` as well as `opt='YN'`, `rv=22`, `hi=6`, `minimum=0.30`, etc. Now I figured it out how to use it (for example, `opt: str = 'YN'`), but still `Hand.__init__` kinda bugs me, since `hand: list = None` looks somewhat weird to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T00:05:52.760", "Id": "532425", "Score": "0", "body": "`@property decorator`: Is there a reason to use this? It would add one line for each `is_something()` and remove two characters `()` when I call it, which doesn't sound like a good trade to me. If I replace getters, I would earn 4 more spaces on each time I call it (by removing `get_`), but still doesn't look like a sweet deal. Is it primarily used to narrow down multiple options (to access attribute) to one? Or is there a way to merge multiple getters into one universal getter?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T00:34:20.340", "Id": "532427", "Score": "0", "body": "`self.bankroll // 1000 // 1000 * 1000`: I was trying to give two different `min_bet` for users. $5 for someone with less than $1 million bankroll, and roughly 0.1% of bankroll rounded down to a thousand dollars for someone with a million or above bankroll. I could achieve the same outcome with `__import__('math').floor(self.bankroll // 1e6 * 1e3)` or `int(self.bankroll // 1e6 * 1e3)`, but opted for that one. Maybe I should just settle for universal 0.1% minimum bet with an absolute minimum of $5 (something like `min(5, round(self.bet // 1000)`)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-06T12:34:19.420", "Id": "532456", "Score": "0", "body": "_[it] doesn't sound like a good trade to me_ - because counting individual characters like that is not really the overriding criterion. I've edited my answer with a little more explanation. _Is it primarily used to narrow down multiple options (to access attribute) to one? Or is there a way to merge multiple getters into one universal getter?_ No, and 'technically yes but it would be more work than benefit'." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T02:23:26.720", "Id": "269752", "ParentId": "269400", "Score": "3" } } ]
{ "AcceptedAnswerId": "269586", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-26T19:45:52.383", "Id": "269400", "Score": "6", "Tags": [ "python", "algorithm", "object-oriented", "game", "playing-cards" ], "Title": "ASCII-based OOP blackjack game in Python" }
269400
<p>The task is to test the the benefits of a Move-To-Front Linked List vs. a standard Linked List. It was also meant to practice inheritance and pointers.</p> <p>The standard functionality is in <code>LinkedList</code>, the derived <code>MTFList</code> replaces <code>contains()</code> to move the target to the front.</p> <p>As I was late submitting my solution, I am not sure whether the poor grade is just for missing the deadline given in class, or reflects on my solution. Anyway, I don't know which errors I might have made.</p> <p>I am hoping that some more experienced eyes can evaluate my use of pointers. Whether my constructors and destructors work appropriately or if I am allowing for memory links.</p> <p><strong>LinkedListStats.cpp</strong></p> <pre><code>// Brandon Hoffman // 10-21-2021 // Test program to evaluate linked list performance // Written 10/4/19 by Michael Stiber // #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;random&gt; #include &lt;vector&gt; #include &lt;cassert&gt; // Replace the following include with alternative linked list class //#include &quot;LinkedList.h&quot; #include &quot;MTFList.h&quot; using namespace std; int main() { // Alter the following declaration to change the linked list class // name. MTFList theList; const int numValues = 1000; const int numAccesses = 100000; // Create a linked list of the numbers 0..numValues-1 for (int i = numValues-1; i &gt;= 0; i--) theList.add(i); // Reset the traversal counter, just in case theList.resetTraverseCount(); // Now, access the elements randomly many times int theNumber; default_random_engine generator; uniform_int_distribution&lt;int&gt; uniform(0, numValues-1); normal_distribution&lt;double&gt; normal(numValues/2.0, numValues/5.0); // As the statistic of comparison, we use a uniform // distribution. For sequential search, even a &quot;smart&quot; algorithm // shouldn't be able to improve performance. for (int i = 0; i &lt; numAccesses; i++) { // Access a random item by value theNumber = uniform(generator); assert(theList.contains(theNumber)); } cout &lt;&lt; &quot;Average number of nodes traversed per access (uniform): &quot; &lt;&lt; theList.getTraverseCount()/double(numAccesses) &lt;&lt; endl; // Reset the traversal counter. theList.resetTraverseCount(); // We use a normal distribution so that some values are accessed // much more frequently. It will be peaked around numValues/2 and fall off // rapidly above and below. Note that there is some chance of // generating a number outside the legal range, so we test and get a // new number if that happens (this is because a uniform // distribution goes to +/- infinity). A smart algorithm could in // principle take advantage of the higher frequency of access of // certain items to lower the average access time. On the other hand, // without any &quot;smarts&quot;, the mean number of nodes traversed should still // be the mean of the distribution, the same as for the uniform distribution. for (int i = 0; i &lt; numAccesses; i++) { theNumber = 0; do { theNumber = int(normal(generator)); } while ((theNumber&lt;0) || (theNumber&gt;=numValues)); assert(theList.contains(theNumber)); } cout &lt;&lt; &quot;Average number of nodes traversed per access (normal): &quot; &lt;&lt; theList.getTraverseCount()/double(numAccesses) &lt;&lt; endl; } // end LinkedListStats </code></pre> <p><strong>MTFList.cpp</strong></p> <pre><code>// LinkedList.cpp // Brandon Hoffman // 10-21-2021 // Contains all of the functionality from members of MTFList.h #include &quot;MTFList.h&quot; //Returns true if anEntry is found in the List, otherwise returns false. For every Node traversed in //search of anEntry, increases traverseCount by 1. Overwites functionality from Linked List //Now moves node with first occurrence of anEntry match to become new first node bool MTFList::contains(int anEntry) { Node *p = first; Node *q = nullptr; while(p != nullptr) { this-&gt;incrementTraverseCount(); if(anEntry == p -&gt; data) { if (q != nullptr) { q -&gt; next = p -&gt; next; p -&gt; next = first; first = p; } return true; } q = p; p = p -&gt; next; } return false; } </code></pre> <p><strong>MTFList.h</strong></p> <pre><code>// LinkedList.h // Brandon Hoffman // 10-21-2021 // Contains the declarations for the MTFList.h class inheriteing from LinkedList.h #ifndef MTF_LIST_ #define MTF_LIST_ #include &quot;LinkedList.h&quot; class MTFList : public LinkedList { public: //Returns true if anEntry is found in the List, otherwise returns false. For every Node traversed in //search of anEntry, increases traverseCount by 1. Overwites functionality from Linked List //Now moves node with first occurrence of anEntry match to become new first node virtual bool contains(int anEntry); }; #endif </code></pre> <p><strong>LinkedList.cpp</strong></p> <pre><code>// LinkedList.cpp // Brandon Hoffman // 10-21-2021 // Contains all of the functionality from members of LinkedList.h #include &lt;iostream&gt; #include &lt;string&gt; #include &quot;LinkedList.h&quot; //constructor //takes an array an int n to denote the length of the array //this is for manual testing purposes only LinkedList::LinkedList(int A[], int n) { Node *t; int i = 0; first = new Node; first -&gt; data = A[0]; first -&gt; next = nullptr; last = first; for(i = 1; i &lt; n; i++) { t = new Node; t -&gt; data = A[i]; t -&gt; next = nullptr; last -&gt; next = t; last = t; } }; //destructor //The destructor deallocates all of the dynamic storage (each Node) and deletes the Node. LinkedList::~LinkedList() { this-&gt;clear(); } //displays data in each Node for manual testing purposes void LinkedList::display() { Node *p = first; while(p) { std::cout &lt;&lt; p -&gt; data &lt;&lt; &quot; &quot;; p = p -&gt; next; } std::cout &lt;&lt; std::endl; } // Returns currentSize, the current number of nodes in the linked List. int LinkedList::getCurrentSize() const { return currentSize; } //returns True if LinkedList is empty i.e. first is pointed nullptr bool LinkedList::isEmpty() const { if (first == nullptr) { return true; } else { return false; } } //Creates a new Node (dynamically allocated) with data = newEntry, adds it to the back of the //List, and increases currentSize by 1.Returns true if the new Node with newEntry was added //successfully, otherwise returns false. bool LinkedList::add(int newEntry) { Node *temporary; temporary = new Node; temporary -&gt; data = newEntry; temporary -&gt; next = nullptr; if (first==nullptr) { first = last = temporary; } else { last -&gt; next = temporary; last = temporary; } this -&gt; incrementCurrentSize(); return true; } //Searches and removes the first occurrence of anEntry in the List and decreases numItems by 1. //Deallocates memory for the removed Node. Returns true if anEntry was removed successfully, //otherwise returns false (if anEntry was not found in the List or the List was empty). //calls decrementCurrentSize method to reduce currentSize by 1 bool LinkedList::remove(int anEntry) { Node *p = first; Node *q = nullptr; while (p != nullptr) { if(anEntry == p -&gt; data){ if (q == nullptr) { q = first; first = first -&gt; next; delete q; } else { q -&gt; next = p -&gt; next; delete p; } this-&gt;decrementCurrentSize(); return true; ; } q = p; p = p -&gt; next; } return false; } //Removes all items from the List and resets currentSize to 0. Deallocates memory for each Node removed. void LinkedList::clear() { Node *p = first; while (first) { first = first -&gt; next; delete p; p = first; } this-&gt;resetCurrentSize(); } //Returns true if anEntry is found in the List, otherwise returns false. For every Node traversed in //search of anEntry, increases traverseCount by 1. bool LinkedList::contains(int anEntry) { Node *p = first; while(p != nullptr) { this-&gt;incrementTraverseCount(); if(anEntry == p -&gt; data) { return true; } p = p -&gt; next; } return false; } </code></pre> <p><strong>LinkedList.h</strong></p> <pre><code>// LinkedList.h // Brandon Hoffman // 10-21-2021 // Contains the declarations for the LinkedList class #ifndef LINKED_LIST_ #define LINKED_LIST_ #include &quot;IList.h&quot; class LinkedList: public IList { public: //constructor //The constructor initializes an empty LinkedList by setting both currentSize and traverseCount to //0 and setting first and lst to nullptr. //two constructors, first is standard for assignment, 2nd takes an array for testing purposes LinkedList(){first=nullptr; last=nullptr; traverseCount=0; currentSize=0;} LinkedList(int A[], int n); //destructor //The destructor deallocates all of the dynamic storage (each Node) and deletes the Node. virtual ~LinkedList(); //accessors //displays data in each Node for manual testing purposes void display(); // Returns currentSize, the current number of nodes in the linked List. virtual int getCurrentSize() const; //mutators //Sets traverseCount to 0. void resetTraverseCount() {traverseCount=0;} //Creates a new Node (dynamically allocated) with data = newEntry, adds it to the back of the //List, and increases currentSize by 1.Returns true if the new Node with newEntry was added //successfully, otherwise returns false. virtual bool add(int newEntry); //Searches and removes the first occurrence of anEntry in the List and decreases numItems by 1. //Deallocates memory for the removed Node. Returns true if anEntry was removed successfully, //otherwise returns false (if anEntry was not found in the List or the List was empty). //calls decrementCurrentSize method to reduce currentSize by 1 virtual bool remove(int anEntry); //Removes all items from the List and resets currentSize to 0. Deallocates memory for each Node removed. virtual void clear(); //Returns true if anEntry is found in the List, otherwise returns false. For every Node traversed in //search of anEntry, increases traverseCount by 1. virtual bool contains(int anEntry); //returns True if LinkedList is empty i.e. first is pointed nullptr virtual bool isEmpty() const; protected: //standard Node structure struct Node { int data; struct Node *next; }; struct Node *first, *last; int currentSize = 0; //mutators void incrementCurrentSize() {currentSize++;} void decrementCurrentSize() {currentSize--;} void resetCurrentSize() {currentSize=0;} void incrementTraverseCount() {traverseCount++;} bool isValidEntry(); }; #endif </code></pre> <p><strong>IList.h</strong></p> <pre><code>//  Modified from code created by Frank M. Carrano and Timothy M. Henry. //  Copyright (c) 2017 Pearson Education, Hoboken, New Jersey. #ifndef I_LIST_ #define I_LIST_ class IList { public: /** Constructor */ IList () : traverseCount(0) { } /** Destroys object and frees memory allocated by object. (See C++ Interlude 2) */ virtual ~IList () { } /** Gets the current number of entries in this list. @return The integer number of entries currently in the list. */ virtual int getCurrentSize() const = 0; /** Sees whether this list is empty. @return True if the list is empty, or false if not. */ virtual bool isEmpty() const = 0; /** Adds a new entry to this list. @post If successful, newEntry is stored in the list and the count of items in the list has increased by 1. @param newEntry The object to be added as a new entry. @return True if addition was successful, or false if not. */ virtual bool add(int newEntry) = 0; /** Removes one occurrence of a given entry from this list, if possible. @post If successful, anEntry has been removed from the list and the count of items in the list has decreased by 1. @param anEntry The entry to be removed. @return True if removal was successful, or false if not. */ virtual bool remove(int anEntry) = 0; /** Removes all entries from this list. @post List contains no items, and the count of items is 0. */ virtual void clear() = 0; /** Tests whether this list contains a given entry. @param anEntry The entry to locate. @return True if list contains anEntry, or false otherwise. */ virtual bool contains(int anEntry) = 0; /** Get the count of number of nodes traversed. @return The integer number of nodes traversed since last time the count was reset. */ virtual int getTraverseCount() const { return traverseCount; } /** Reset the count of nodes traversed to zero. */ virtual void resetTraverseCount() { traverseCount = 0; } protected: int traverseCount; }; // end IList #endif </code></pre>
[]
[ { "body": "<ul>\n<li><p>The</p>\n<pre><code> if (first == nullptr) {\n return true;\n } \n else {\n return false;\n }\n</code></pre>\n<p>is a very long way to say</p>\n<pre><code> return first == nullptr;\n</code></pre>\n</li>\n<li><p>When you add a new entry to the list, it becomes <code>last</code> no matter what. Be explicit:</p>\n<pre><code> if (first==nullptr) {\n first = temporary;\n } else { \n last -&gt; next = temporary;\n }\n last = temporary;\n</code></pre>\n</li>\n<li><p>Ditto for <code>remove</code>. The <code>p/q</code> deletion logic looks convoluted. We only want to delete the node we found, that is <code>p</code>, right? Consider instead</p>\n<pre><code> if (p == first) {\n first = first -&gt; next;\n } else {\n q -&gt; next = p -&gt; next;\n }\n delete p;\n</code></pre>\n</li>\n<li><p>The lines</p>\n<pre><code> temporary -&gt; data = newEntry;\n temporary -&gt; next = nullptr;\n</code></pre>\n<p>scream to be in the <code>Node</code> constructor.</p>\n</li>\n<li><p>An introductory comment to <code>add</code> is misleading. It claims that the method returns <code>false</code> on a failure to add. I don't see it returning <code>false</code>. I also don't see the possibility of a failure, unless <code>new Node</code> throws a <code>bad_alloc</code>, but then all bets are off anyway.</p>\n</li>\n<li><p><code>remove</code> and <code>contains</code> (especially <code>MTFList::contains</code>) share a lot of functionality. You be in a better shape having a helper method, say <code>Node * detach</code>. Consider</p>\n<pre><code> LinkedList::remove(int entry)\n {\n Node * r = detach(entry);\n if (r) {\n delete r;\n }\n return r != nullptr;\n }\n\n MTFList::contains(int entry)\n {\n Node * r = detach(entry);\n if (r) {\n r-&gt;next = first;\n first = r;\n incrementCurrentSize();\n }\n return r != nullptr;\n }\n</code></pre>\n<p>Of course, <code>incrementCurrentSize</code> looks out of place here. It is a strong indication that a <code>prepend</code> method wants to be implemented.</p>\n<p>Another very helpful helper method would be <code>findPredecessor</code>. It will let you consolidate <code>remove</code> and <code>LinkedList::contains</code>.</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T06:57:03.473", "Id": "531551", "Score": "1", "body": "And `return first == nullptr;` is a slightly long way to write `return !first;`..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T06:58:45.737", "Id": "531552", "Score": "0", "body": "@TobySpeight Thanks, missed that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T06:11:04.433", "Id": "269410", "ParentId": "269406", "Score": "3" } }, { "body": "<p><a href=\"https://stackoverflow.com/questions/1452721\">Don’t</a> write <code>using namespace std;</code>.</p>\n<p>You can, however, in a CPP file (not H file) or inside a function put individual <code>using std::string;</code> etc. (See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#sf7-dont-write-using-namespace-at-global-scope-in-a-header-file\" rel=\"nofollow noreferrer\">SF.7</a>.)</p>\n<hr />\n<p><code> const int numValues = 1000;</code></p>\n<p>Remember &quot;<code>constexpr</code> is the new <code>static const</code>.&quot; This should be <code>constexpr</code>. And what type should you be using?</p>\n<hr />\n<p><code>for (int i = numValues-1; i &gt;= 0; i--)</code><br />\nThat brutal just to loop <em>n</em> times. Do you know about <code>iota</code>? See <a href=\"https://www.codeproject.com/Articles/1245139/DIY-range\" rel=\"nofollow noreferrer\">this article</a> for counting, and note that <a href=\"https://en.cppreference.com/w/cpp/ranges/iota_view\" rel=\"nofollow noreferrer\"><code>std::ranges::iota_view</code></a> is supplied with the standard library as of C++20.</p>\n<p>In general, you should not write explicit loops; you should <em>use algorithms</em>.</p>\n<hr />\n<p><code>while(p != nullptr) {</code><br />\nDon't write explicit tests against <code>nullptr</code>. You'll work with <em>smart pointers</em> of various kinds, not just raw pointers (hopefully, usually not raw pointers) and these have an <em>efficient</em> <code>explicit operator bool</code>. It is highly idiomatic to use the truth value of a pointer directly in C++, even though it is no longer as inefficient (since C++11) to write an explicit comparison.</p>\n<p><code>this-&gt;incrementTraverseCount();</code><br />\nDon't explicitly use <code>this-&gt;</code>. In member functions, the other members are in scope.</p>\n<hr />\n<pre><code>#ifndef MTF_LIST_\n#define MTF_LIST_\n</code></pre>\n<p>These names are too short and to-the-point so they may collide in a real project that uses multiple libraries by different authors. Just use <code>#pragma once</code>, and if you must use the <code>#define</code> mechanism, generate a UUID. You'll probably have stopped using <code>#include</code> before you ever see a compiler that doesn't accept <code>#pragma once</code>. Modules don't have the same issues as classic <code>#include</code> files.</p>\n<hr />\n<p><a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#slio50-avoid-endl\" rel=\"nofollow noreferrer\">⧺SL.io.50</a> Don't use <code>endl</code>.</p>\n<hr />\n<p><code> IList () : traverseCount(0) { }</code></p>\n<p>This is better written to give an inline initializer to the <code>traverseCount</code> member, and then don't implement the default constructor yourself at all. That is,</p>\n<pre><code> ⋮\n int traverseCount { 0 };\n ⋮\n IList() = default;\n</code></pre>\n<hr />\n<p><code>LinkedList::LinkedList(int A[], int n)</code></p>\n<ul>\n<li><p><a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#i13-do-not-pass-an-array-as-a-single-pointer\" rel=\"nofollow noreferrer\">⧺I.13</a> Do not pass an array as a single pointer (includes pointer and count parameters in the discussion)</p>\n</li>\n<li><p><a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#r14-avoid--parameters-prefer-span\" rel=\"nofollow noreferrer\">⧺R.14</a> Avoid <code>[]</code> parameters, prefer <code>span</code></p>\n</li>\n<li><p><a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#f24-use-a-spant-or-a-span_pt-to-designate-a-half-open-sequence\" rel=\"nofollow noreferrer\">⧺F.24</a> Use a <code>span&lt;T&gt;</code> or a <code>span_p&lt;T&gt;</code> to designate a half-open sequence</p>\n</li>\n</ul>\n<p>In real code, you don't want to be limited to an <em>array</em> of values, but should be able to feed it any kind of range. Look at how standard library functions take their arguments. I admit generic programming might be beyond what you've covered so far, but you should not get in the habit of doing things in <em>weird</em> or <em>bad</em> ways. Here, you should be using <code>std::span</code>.</p>\n<hr />\n<p>Put simple function implementations directly in the header file. For example, your destructor should be defined inside the class:</p>\n<pre><code> ⋮\n virtual ~LinkedList() { clear(); }\n ⋮\n int getCurrentSize() const { return currentSize; }\n bool isEmpty() const { return !first; }\n \n</code></pre>\n<p>Why is the size an <code>int</code> instead of <code>size_t</code>? For that matter, nothing is named according to convention! Look at the standard library: <code>size</code>, <code>empty</code>. Name things what people expect so others will know how to use it without having to learn your own special vocabulary.</p>\n<p>I see more examples of &quot;fat interface&quot;. Why is <code>display</code> a member function? It should be a non-member that uses the <em>general purpose</em> ability to traverse the list and do whatever code needs to do with each value in the collection.</p>\n<hr />\n<p>I'm not sure why you made things <code>virtual</code> and added a function in a derived class. I don't know how well that would work if you really were using polymorphism for the nodes.</p>\n<blockquote>\n<p>The assignment was meant to practice inheritance and pointers.</p>\n</blockquote>\n<p>It doesn't seem to be a good example for having anything to do with inheritance.</p>\n<blockquote>\n<p>So the standard functionality is in the LinkedList class and then a MTFList class inherits that functionality and changes the contains method to move a node to the front when a particular integer value is searched and found.</p>\n</blockquote>\n<p>The <em>search</em> features does not need to be a member of the list. It can be a non-member that operates on a list using only public functionality. You can have an ordinary <code>find</code>, and another function that does find-and-move-to-front.</p>\n<p>If you look at the standard library, you'll see that the <a href=\"https://en.cppreference.com/w/cpp/container/list\" rel=\"nofollow noreferrer\">linked list</a> (which is almost never used, BTW) does not have any kind of <em>find</em> member function.</p>\n<p>Searching a container — <em>any</em> container — is done with the <a href=\"https://en.cppreference.com/w/cpp/algorithm/find\" rel=\"nofollow noreferrer\">find</a> <em>algorithm</em>.</p>\n<h1>editorial</h1>\n<p>I don't know exactly what your course is all about and what the outline is or what level of proficiency the student needs to have already. But I have some general thoughts on the subject of teaching C++ in 2021.</p>\n<p>One of the &quot;normal&quot; rules is <em><a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c149-use-unique_ptr-or-shared_ptr-to-avoid-forgetting-to-delete-objects-created-using-new\" rel=\"nofollow noreferrer\">⧺C.149</a> — no naked <code>new</code> or <code>delete</code></em>. Similarly, you should use standard containers for normal coding, don't use raw pointers, use the standard algorithms, etc. Implementing a container is an <strong>advanced</strong> topic.</p>\n<p>Understanding how linked lists, trees, hash tables, and whatnot work and how they can be written is a <em>different class</em> than learning a programming language. A <em>Data Structures and Algorithms</em> class will indeed have you write primitive implementations of basic container-like data collections, and implement code to do bread &amp; butter stuff like sorting and finding an element in a collection. The student in this class should be able to concentrate on these details without also having to learn a language or gather basic coding proficiency.</p>\n<p>Likewise, in a class on the C++ language and/or learning to write code in general, you <strong>should not</strong> be asked to write code that is atypical, bizzare, or flagrantly opposing Best Practices. It should not require you to make naive use of what should be advanced topics. It should prepare you for writing real-world code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T14:52:31.533", "Id": "269423", "ParentId": "269406", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T04:13:11.417", "Id": "269406", "Score": "3", "Tags": [ "c++", "linked-list", "pointers" ], "Title": "Testing MRU-list vs. standard list" }
269406
<p>I have a function that takes a specific number and a range, and re-scales it to the corresponding number in a different range.</p> <pre><code>/** * @param int number The number to adjust. * @param int oldMin The old minimum value. * @param int oldMax The old maximum value. * @param int newMin The new minimum value to convert to. * @param int newMax The new maximium value to convert to. * * @returns int The original number converted to the new boundary. */ function convertValueToBoundary(number, oldMin, oldMax, newMin, newMax) { return (((number - oldMin) * (newMax - newMin)) / (oldMax - oldMin)) + newMin } </code></pre> <h3>Formula</h3> <pre><code>newValue = (((oldValue - oldMinimum) * (newMaximum - newMinimum)) / (oldMaximum - oldMinimum)) + newMinimum </code></pre> <h3>Example</h3> <p>For instance, given the number <code>5</code> within a range of <code>0-10</code>, we want to increase the numerical range to be between <code>0-100</code> instead.</p> <pre><code>convertValueToBoundary(5, 0, 10, 0, 100) // Output -&gt; 50 </code></pre> <h3>Optimization &amp; Improvements</h3> <p>Is this the optimal way to conduct this calculation? After a number of different attempts the above formula is the best I could come up with. Given a scenario where this needs to execute multiple times in rapid succession, it would be ideal to have this execute with the least amount of arithmetic operations required.</p> <p>The conversion should be conducted <strong>without the use of any native language functions</strong> as I plan to use the same formula across different languages and platforms.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T05:54:22.847", "Id": "531546", "Score": "1", "body": "some languages implement faster/easier methods to do certain computations, although not really necessary in your case, but for eg. you can check matrix operations in APL." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T06:50:21.397", "Id": "531549", "Score": "2", "body": "This could still do with additional context. For example, if we're rescaling lots of numbers between the same two ranges, we might want to save the subtractions somewhere (and perhaps take a functional approach, where we return a function that performs one particular rescale). When you port to different languages, it may well be worth having the new implementations reviewed - especially if you might be using integers, which behave very differently to Javascript's floating-point numbers." } ]
[ { "body": "<h2>Code noise</h2>\n<p>Your naming and code style make the code very noisy.</p>\n<p>The function name is too long <code>convertValueToBoundary</code> the conversion is implied and value is commonly shortened to val so <code>valToBoundary</code> is less noisy. However I would never guess what this function did without some extra information</p>\n<p>Maybe <code>rescale</code> would be more appropriate.</p>\n<p>You have too many brackets. You have...</p>\n<pre><code>return (((number - oldMin) * (newMax - newMin)) / (oldMax - oldMin)) + newMin\n</code></pre>\n<p>is identical to...</p>\n<pre><code>return (number - oldMin) * (newMax - newMin) / (oldMax - oldMin) + newMin;\n</code></pre>\n<p>To further remove code noise use an arrow function and shorten the argument names</p>\n<pre><code>const rescale = (val, oMin, oMax, min, max)=&gt;(val - oMin) * (max - min) / (oMax - oMin) + min;\n</code></pre>\n<h2>Optimization</h2>\n<p>The only optimization possible is to remove the division (multiplication is quicker than division). This would improve the performance if you were converting many values from the same range...</p>\n<pre><code>const rescale = (val, oMin, invRange, min, max)=&gt;(val - oMin) * (max - min) * invRange + min;\n\n// Your example convertValueToBoundary(5, 0, 10, 0, 100) // Output -&gt; 50\n// would be\nrescale(5, 0, 0.1, 0, 100); // result 50; is quicker\n// or\nrescale(5, 0, 1 / 10, 0, 100); // result 50; is slower as need the / and *\n\n</code></pre>\n<p>However if each range is different this would make the operation slower as you need to calculate the inverse range each time you call the function.</p>\n<p>You could also use two ranges to remove the subtraction making it even quicker</p>\n<pre><code>const rescale = (val, oMin, invRange, min, range)=&gt;(val - oMin) * range * invRange + min;\n\nrescale(5, 0, 0.1, 0, 100); // result 50\n\n</code></pre>\n<h2>Guard</h2>\n<p>If you keep the function with the division you need to guard against divide by zero. In JS <code>convertValueToBoundary(5, 0, 0, 0, 100)</code> will result in <code>NaN</code> rather than the expected <code>0</code> and in some languages it will throw an error.</p>\n<p>Thus you should have the guard <code>oMin === oMax</code> to prevent the divide by zero.</p>\n<pre><code>const rescale = (val, oMin, oMax, min, max) =&gt; \n (oMin === oMax ? 0 : (val - oMin) * (max - min) / (oMax - oMin)) + min;\n</code></pre>\n<p>If you use inverse range there is no need for the guard.</p>\n<pre><code>const rescale = (val, oMin, invRange, min, max)=&gt;(val - oMin) * (max - min) * invRange + min;\n\n// or\n\nconst rescale = (val, oMin, invRange, min, range)=&gt;(val - oMin) * range * invRange + min;\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T18:25:18.603", "Id": "531600", "Score": "0", "body": "Thanks for the feedback, especially regarding the division!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T10:04:58.267", "Id": "269416", "ParentId": "269408", "Score": "2" } } ]
{ "AcceptedAnswerId": "269416", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T05:48:28.450", "Id": "269408", "Score": "3", "Tags": [ "javascript", "performance", "mathematics" ], "Title": "Convert number from old range to new numeric range" }
269408
<p>See this method:</p> <pre><code>HRESULT CChristianLifeMinistryHtmlView::CustomContextMenu(const POINT* ppt, IUnknown* pcmdtReserved) { IOleWindow* oleWnd = nullptr; HWND hwnd = nullptr; HMENU hMainMenu = nullptr; HMENU hPopupMenu = nullptr; HRESULT hr = 0; INT iSelection = 0; bool bContinue = true; if ((ppt == nullptr) || (pcmdtReserved == nullptr)) bContinue = false; if (bContinue) { hr = pcmdtReserved-&gt;QueryInterface(IID_IOleWindow, reinterpret_cast&lt;void**&gt;(&amp;oleWnd)); if ((hr != S_OK) || (oleWnd == nullptr)) bContinue = false; } if (bContinue) { hr = oleWnd-&gt;GetWindow(&amp;hwnd); if ((hr != S_OK) || (hwnd == nullptr)) bContinue = false; } if (bContinue) { hMainMenu = LoadMenu(AfxGetResourceHandle(), MAKEINTRESOURCE(IDR_MENU_HTML_POPUP)); if (hMainMenu == nullptr) bContinue = false; } if (bContinue) { hPopupMenu = GetSubMenu(hMainMenu, 0); if (hPopupMenu == nullptr) bContinue = false; } if (!bContinue) { if (hMainMenu != nullptr) ::DestroyMenu(hMainMenu); return S_OK; } ::SetMenuItemBitmaps(hPopupMenu, IDM_PAGESETUP, MF_BYCOMMAND, (HBITMAP)m_bmpPageSetup, (HBITMAP)m_bmpPageSetup); ::SetMenuItemBitmaps(hPopupMenu, IDM_PRINTPREVIEW, MF_BYCOMMAND, (HBITMAP)m_bmpPrintPreview, (HBITMAP)m_bmpPrintPreview); ::SetMenuItemBitmaps(hPopupMenu, IDM_REFRESH, MF_BYCOMMAND, (HBITMAP)m_bmpRefresh, (HBITMAP)m_bmpRefresh); // Show shortcut menu iSelection = ::TrackPopupMenu(hPopupMenu, TPM_LEFTALIGN | TPM_RIGHTBUTTON | TPM_RETURNCMD, ppt-&gt;x, ppt-&gt;y, 0, hwnd, (RECT*)nullptr); // Send selected shortcut menu item command to shell if (iSelection != 0) { if (iSelection == IDM_PRINTPREVIEW) { ::SendMessage(GetParent()-&gt;GetSafeHwnd(), WM_COMMAND, ID_FILE_PRINT_PREVIEW, NULL); } else if (iSelection == CUSTOM_MENU_EXPORT) { ::SendMessage(GetParent()-&gt;GetSafeHwnd(), WM_COMMAND, ID_FILE_EXPORT, NULL); } else if (iSelection == IDM_REFRESH) { ::SendMessage(GetParent()-&gt;GetSafeHwnd(), WM_COMMAND, ID_VIEW_REFRESH, NULL); } else { ::SendMessage(hwnd, WM_COMMAND, iSelection, NULL); } } return S_OK; } </code></pre> <p>Why is it that Visual Studion 2022 Preview 7 (x86 build) is reporting:</p> <ul> <li>warning C26430: Symbol <code>pcmdtReserved</code> is not tested for nullness on all paths (f.23).</li> <li>warning C26430: Symbol <code>oleWnd</code> is not tested for nullness on all paths (f.23).</li> </ul> <p>By my use of the <code>bool bContinue</code> flag I have taken into account all pointers and tested them for nullness.</p> <p>What changes can be made to this function to prevent these warnings?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T08:50:09.850", "Id": "531561", "Score": "0", "body": "You could simply disable the warnings, what is it you're really after?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T08:53:43.210", "Id": "531562", "Score": "0", "body": "@Mast I know I can disable them. What I want to know is *why* it thinks I have not covered all paths. Is my logic flawed somehow?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T11:29:12.303", "Id": "531567", "Score": "2", "body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T13:28:00.170", "Id": "531577", "Score": "1", "body": "The question doesn't really belong on Code Review, it seems to me it would be more appropriate on Stack Overflow, however the answer is good so I'm voting to leave open." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T15:34:29.030", "Id": "531590", "Score": "3", "body": "If you have any questions about the scope of the site, the [help/on-topic] would be a good place to start. If you happen to have additional questions after that, feel free to drop by [in chat](//chat.stackexchange.com/rooms/8595/)." } ]
[ { "body": "<h2>variable initialization:</h2>\n<p>Don't declare all the variables at the top of functions. Declare them at the point of first use, and initialize them to meaningful values.</p>\n<hr />\n<h2>return early on failure:</h2>\n<pre><code>bool bContinue = true;\n\nif ((ppt == nullptr) || (pcmdtReserved == nullptr))\n bContinue = false;\n</code></pre>\n<p>This could be more succinctly written as:</p>\n<pre><code>bool bContinue = (ppt != nullptr) &amp;&amp; (pcmdtReserved != nullptr);\n</code></pre>\n<p>which might help the static analysis tool.</p>\n<p>However, we can avoid the need for this variable, and the added complexity it introduces by returning early on failure:</p>\n<pre><code>if (ppt == nullptr || pcmdtReserved == nullptr)\n return S_OK; // ?!?! see below...\n</code></pre>\n<hr />\n<h2>do we really want to ignore errors?</h2>\n<pre><code>if (!bContinue)\n{\n if (hMainMenu != nullptr)\n ::DestroyMenu(hMainMenu);\n\n return S_OK;\n}\n</code></pre>\n<p>Do we really want to return <code>S_OK</code> on failure? Perhaps we should return the relevant failing <code>HRESULT</code>?</p>\n<p>The calling code can choose to ignore the failure if it wants to, but if we don't pass the error on it removes any option to do something else, like log the failure.</p>\n<hr />\n<h2>use assert to avoid extra complexity:</h2>\n<pre><code> hr = pcmdtReserved-&gt;QueryInterface(IID_IOleWindow, reinterpret_cast&lt;void**&gt;(&amp;oleWnd));\n if ((hr != S_OK) || (oleWnd == nullptr))\n bContinue = false;\n</code></pre>\n<p>MSDN says:</p>\n<blockquote>\n<p>Upon successful return, *ppvObject (the dereferenced address) contains\na pointer to the requested interface. If the object doesn't support\nthe interface, the method sets *ppvObject (the dereferenced address)\nto nullptr.</p>\n</blockquote>\n<p>So we don't need to check <code>oleWnd</code> if <code>hr</code> is <code>S_OK</code>. We could, however, use an <code>assert()</code> to demonstrate that we're relying on that fact.</p>\n<p>This means that we can return early with a failing <code>HRESULT</code>, but we don't have to invent a failing HRESULT if <code>oleWnd</code> is <code>nullptr</code>, e.g.:</p>\n<pre><code>if (auto hr = pcmdtReserved-&gt;QueryInterface(IID_IOleWindow, reinterpret_cast&lt;void**&gt;(&amp;oleWnd)); hr != S_OK) {\n return hr;\n}\n\nassert(oldWnd != nullptr);\n</code></pre>\n<hr />\n<h2>check return values:</h2>\n<pre><code>::SetMenuItemBitmaps(hPopupMenu, IDM_PAGESETUP, MF_BYCOMMAND,\n (HBITMAP)m_bmpPageSetup, (HBITMAP)m_bmpPageSetup);\n::SetMenuItemBitmaps(hPopupMenu, IDM_PRINTPREVIEW, MF_BYCOMMAND,\n (HBITMAP)m_bmpPrintPreview, (HBITMAP)m_bmpPrintPreview);\n::SetMenuItemBitmaps(hPopupMenu, IDM_REFRESH, MF_BYCOMMAND,\n (HBITMAP)m_bmpRefresh, (HBITMAP)m_bmpRefresh);\n</code></pre>\n<p>These can also fail, we might check for that. (If we expect them to never fail, we can <code>assert</code> on the return value. If we want to ignore errors, we can cast the return value to void to explicitly show that we don't care).</p>\n<pre><code> ::SendMessage(GetParent()-&gt;GetSafeHwnd(), WM_COMMAND, ID_FILE_PRINT_PREVIEW, NULL);\n</code></pre>\n<p>Again, we might want to check the return value.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T11:48:32.973", "Id": "531569", "Score": "0", "body": "Thanks for your answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T10:08:50.573", "Id": "269417", "ParentId": "269411", "Score": "2" } } ]
{ "AcceptedAnswerId": "269417", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T08:40:40.587", "Id": "269411", "Score": "-1", "Tags": [ "c++", "visual-studio" ], "Title": "What changes are required to this function to suppress C26430 code analysis warnings?" }
269411
<p>I solve problems to prepare for interviews. Now I have written the algorithm of finding K largest numbers in array. Various solutions are described here: <a href="https://www.geeksforgeeks.org/k-largestor-smallest-elements-in-an-array/" rel="nofollow noreferrer">https://www.geeksforgeeks.org/k-largestor-smallest-elements-in-an-array/</a>. Initially, I came up with the solution myself and looks my solution corresponds to that described as <strong>Method 2</strong> on the site, with the difference that I additionally use the &quot;old minimum&quot; to cut off unnecessary steps along the nested loop.</p> <p>What could be written better in my code? What could be used instead of <code>pmin</code>?</p> <p>Here is my implementation:</p> <pre><code>using namespace std; vector&lt;int&gt; largest_part_of_vector(const vector&lt;int&gt;&amp; vec, int K_PartSize) { assert(K_PartSize &lt; vec.size()); vector&lt;int&gt; ret(K_PartSize); // Initial filling of temporary vector int ind = 0; // main end-to-end index int* pmin = const_cast&lt;int*&gt;(&amp;vec[0]); // current minimum // How `pmin` could be declared and used better? for (auto&amp; elemRef : ret) { elemRef = vec[ind]; if (elemRef &lt; *pmin) { pmin = &amp;elemRef; // pmin is from `vecPart` now and will not modify `vec` } ind++; } // the rest part auto oldMin = *pmin; for (; ind &lt; vec.size(); ind++) { auto v = vec[ind]; if (v &gt; oldMin) // preliminary check to avoid unnecessary checks { for (auto&amp; elemRef : ret) { if (elemRef &lt; *pmin) { pmin = &amp;elemRef; } } if (v &gt; * pmin) { oldMin = *pmin; *pmin = v; } } /*else { savedIterations++; }*/ } return ret; // As I understand, moving operator=( vector&amp;&amp; other ) will be used here } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T14:23:52.963", "Id": "531582", "Score": "1", "body": "Of course, the real answer to such an interview question is to just call `std::partial_sort_copy`." } ]
[ { "body": "<p><code>using namespace std;</code> is poor practice - don't do that.</p>\n<p><code>K_PartSize</code> should probably be a <code>std::size_t</code>.</p>\n<p><code>assert()</code> is not a good way to validate arguments - it's intended for making claims about invariants in the logic. It won't be present in non-debug builds, and when it is present, it can abort the program, without running destructors or any other cleanup.</p>\n<p>Instead, implement some useful behaviour:</p>\n<pre><code>if (!partsize) {\n return {};\n}\nif (partsize &gt;= vec.size()) {\n return vec;\n}\n</code></pre>\n<p>I dislike the <code>const_cast</code> for <code>pmin</code>. I think it would be better to construct <code>ret</code> from the beginning part of the input vector, and start <code>pmin</code> pointing to the first element of that:</p>\n<pre><code>std::vector&lt;int&gt; ret(vec.begin(), vec.begin()+partsize);\nint* pmin = &amp;ret[0];\n</code></pre>\n<p>I'd suggest that this would be better as an iterator than a pointer:</p>\n<pre><code>auto pmin = ret.begin();\n</code></pre>\n<p>I'd swap round the test of <code>(v &gt; oldMin)</code>:</p>\n<pre><code>if (v &lt;= oldMin) {\n continue;\n}\nfor (auto&amp; elemRef : ret)\n</code></pre>\n<p>I don't think we need both <code>pmin</code> and <code>oldMin</code>, certainly if we use the standard <code>min_element</code> algorithm:</p>\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;vector&gt;\n\nstd::vector&lt;int&gt; largest_part_of_vector(const std::vector&lt;int&gt;&amp; vec, std::size_t partsize)\n{\n if (!partsize) {\n return {};\n }\n if (partsize &gt;= vec.size()) {\n return vec;\n }\n\n std::vector&lt;int&gt; ret(vec.begin(), vec.begin()+partsize);\n auto pmin = std::min_element(ret.begin(), ret.end());\n\n // the rest part\n for (auto ind = vec.begin() + ret.size(); ind != vec.end(); ++ind)\n {\n auto const v = *ind;\n\n if (v &lt;= *pmin) { continue; }\n\n *pmin = v;\n pmin = std::min_element(ret.begin(), ret.end());\n }\n\n return ret;\n}\n</code></pre>\n<p>Test program:</p>\n<pre><code>#include &lt;iostream&gt;\n\ntemplate&lt;typename V&gt;\nclass printable_vector\n{\n V const&amp; v;\npublic:\n explicit printable_vector(const V&amp; v) : v{v} {}\n friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const printable_vector&amp; p) {\n os &lt;&lt; '{';\n char const* sep = &quot;&quot;;\n for (auto const&amp; e: p.v) {\n os &lt;&lt; sep &lt;&lt; e;\n sep = &quot;, &quot;;\n }\n return os &lt;&lt; '}';\n }\n};\n\nint main()\n{\n auto const a = std::vector{ 1, 2, 12, 3, 2, 6 };\n\n for (auto k: {0, 1, 4, 5, 9}) {\n std::cout &lt;&lt; printable_vector{largest_part_of_vector(a, k)} &lt;&lt; '\\n';\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T09:56:16.873", "Id": "269415", "ParentId": "269413", "Score": "1" } } ]
{ "AcceptedAnswerId": "269415", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T09:15:38.237", "Id": "269413", "Score": "1", "Tags": [ "c++", "array" ], "Title": "K largest elements in an array" }
269413
<p>I'm wondering if the nested &quot;try/except/else&quot; structure (in the main function) is a good practice in Python. Right now, the structure is not that deep but I could continue on and on with additional conditions in the &quot;else&quot; part. Is there a better way to implement this ?</p> <p>My code written in <code>main.py</code>:</p> <pre><code>import logging import traceback import flask from google.cloud import firestore class DocumentDoesNotExist(Exception): &quot;&quot;&quot; Exception raised when there is no document corresponding to a given token in Firestore/collectionA nor Firestore/collectionB. &quot;&quot;&quot; class DocumentExistElsewhere(Exception): &quot;&quot;&quot; Exception raised when there is no document corresponding to a given token in Firestore/collectionA but there is one in Firestore/collectionB. &quot;&quot;&quot; def get_patient_info(token): db = firestore.Client() document = db.collection(u'collectionA').document(token).get() if document.exists: return document.to_dict() else: document = db.collection(u'collectionB').document(token).get() if document.exists: raise DocumentExistElsewhere else: raise DocumentDoesNotExist app = flask.Flask(__name__) @app.route(&quot;/&lt;request&gt;&quot;) def main(request: flask.Request): headers = { 'Access-Control-Allow-Methods': 'OPTIONS, GET', 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Max-Age': '9600' } allowed_origins = [ &quot;http://localhost:5000&quot; ] origin = flask.request.headers.get('Origin') or flask.request.headers.get('origin') if origin in allowed_origins: headers['Access-Control-Allow-Origin'] = origin if flask.request.method == 'OPTIONS': return '', 204, headers if flask.request.method == 'GET': try: request_json = flask.request.get_json(force=True, silent=True) # Returns None if fails. token = request_json['token'] except (TypeError, KeyError): logging.error(traceback.format_exc()) return &quot;Cannot retrieve token from request&quot;, 400, headers else: try: info = get_patient_info(token) except DocumentDoesNotExist: return &quot;Token provided does not correspond to any document in Firestore/collectionA nor in &quot; \ &quot;collectionB.&quot;, 404, headers except DocumentExistElsewhere: return &quot;Token provided corresponds to a document in Firestore/collectionB but none in &quot; \ &quot;Firestore/collectionA.&quot;, 404, headers else: return info, 200, headers if __name__ == &quot;__main__&quot;: app.run(debug=True) </code></pre> <p>You can run the Flask app like this <code>python3 main.py</code> and then testing with a curl <code> curl -H &quot;Origin: http://localhost:5000&quot; -X GET -d '{&quot;token&quot;:&quot;06sr1&quot;}' -i http://localhost:5000/test</code></p> <p>Also, if you can see any problem with my implementation I'm open to any tips :)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T10:55:40.447", "Id": "531566", "Score": "1", "body": "I'm curious to hear how you expect the code to be used in the future. In particular I have 2 questions. Are you going to have many collections or will it be limited to these 2? What should a user do on a DocumentExistElsewhere response?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T11:53:55.313", "Id": "531571", "Score": "0", "body": "@IvoMerchiers only 2 collections. But generally speaking it could expand. When DocumentExistElsewhere, I actually send a message to the front to display something." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T11:59:22.237", "Id": "531573", "Score": "0", "body": "Would you then expect the user to retry the query but for collectionB or is the access model more complicated?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T12:48:32.590", "Id": "531575", "Score": "0", "body": "Every time the user do the query, it has to check collectionA before collectionB" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T13:57:52.203", "Id": "531580", "Score": "2", "body": "Please [edit] your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!" } ]
[ { "body": "<p>The <code>try ... except ... else ...</code> construct works as follows.</p>\n<pre class=\"lang-py prettyprint-override\"><code>try:\n print(&quot;Code protected by the try-statement&quot;)\nexcept AnException:\n print(&quot;Exception handling code - not protected by try-statement&quot;)\nelse:\n print(&quot;No exception occurred code - not protected by try-statement&quot;)\n\nprint(&quot;Common code executed whether or not an exception occurred.&quot;)\n</code></pre>\n<p>Now let's add in a bit of your exception handling code...</p>\n<pre class=\"lang-py prettyprint-override\"><code>try:\n print(&quot;Code protected by the try-statement&quot;)\nexcept AnException:\n print(&quot;Exception handling code - not protected by try-statement&quot;)\n return\nelse:\n print(&quot;No exception occurred code - not protected by try-statement&quot;)\n\nprint(&quot;Common code executed whether or not an exception occurred ...&quot;)\nprint(&quot;except if an exception occurs, the code returns and won't get here!&quot;)\n</code></pre>\n<p>It should become obvious that the only way to get to the last two <code>print()</code> statements is if the <code>print()</code> statement in the <code>else:</code> clause is executed. If an exception occurs, the function exits via the <code>return</code> statement. Therefore, the <code>else:</code> clause is unnecessary.</p>\n<pre class=\"lang-py prettyprint-override\"><code>try:\n print(&quot;Code protected by the try-statement&quot;)\nexcept AnException:\n print(&quot;Exception handling code - not protected by try-statement&quot;)\n return\n\nprint(&quot;No exception occurred code - not protected by try-statement&quot;)\nprint(&quot;Common code executed whether or not an exception occurred ...&quot;)\nprint(&quot;except if an exception occurs, the code returns and won't get here!&quot;)\n</code></pre>\n<p>This means there is no need to have nested <code>try ... except ... else ...</code> statements. Simply omit the <code>else:</code> clauses.</p>\n<pre class=\"lang-py prettyprint-override\"><code> try:\n request_json = flask.request.get_json(force=True, silent=True) # Returns None if fails.\n token = request_json['token']\n except (TypeError, KeyError):\n logging.error(traceback.format_exc())\n return &quot;Cannot retrieve token from request&quot;, 400, headers\n\n # No else-clause here\n\n try:\n info = get_patient_info(token)\n except DocumentDoesNotExist:\n return &quot;Token provided does not correspond to any document in Firestore/collectionA nor in &quot; \\\n &quot;collectionB.&quot;, 404, headers\n except DocumentExistElsewhere:\n return &quot;Token provided corresponds to a document in Firestore/collectionB but none in &quot; \\\n &quot;Firestore/collectionA.&quot;, 404, headers\n\n # No else-clause here either\n\n return info, 200, headers\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T15:28:46.867", "Id": "269426", "ParentId": "269418", "Score": "3" } } ]
{ "AcceptedAnswerId": "269426", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T10:11:13.360", "Id": "269418", "Score": "-1", "Tags": [ "python", "error-handling" ], "Title": "Nested try-except for raising exceptions in Python" }
269418
<p>I have a <code>ListView</code> that displays every customer (class <code>Cliente</code> in my code) of a company. Every <code>Cliente</code> object has a specific id (<code>piva</code> in my code) that is necessary to make a third party API call. My goal was to press a button in the template that makes an API call for every <code>Cliente</code> object in my <code>ListView</code> queryset.</p> <p>To accomplish this I overwrite the <code>get_context_data</code> method in the <code>ListView</code> to include a tuple of <code>piva</code>:</p> <pre><code>def get_context_data(self, *, object_list=None, **kwargs): ctx = super().get_context_data() pive = pive_extraction(self.get_queryset()) # pive_extraction(qs: QuerySet[Cliente]) -&gt; tuple[str] ctx['pive'] = pive return ctx </code></pre> <p>In my <code>ListView</code> template I have this form:</p> <pre><code>&lt;form action=&quot;{% url 'crm:cerved-multiple-api-call' %}&quot; method=&quot;POST&quot;&gt; {% csrf_token %} &lt;input hidden name=&quot;ricerca&quot; id=&quot;ricerca&quot; value=&quot;{{pive}}&quot;&gt; &lt;button&gt;Arricchimento Cerved di tutti i clienti&lt;/button&gt; &lt;/form&gt; </code></pre> <p>Pressing the button perform the action on this view:</p> <pre><code>def cerved_multiple_api_call_view(request): if request.POST: pive = eval(request.POST['ricerca']) for piva in pive: data = cerved_api_call(piva) # third party API call # some non-relevant code where I work with 'data' return redirect('crm:cliente-list') </code></pre> <p>The code works fine and an API call is done for every <code>Cliente</code> in my <code>ListView</code> queryset; But inserting a tuple of <code>piva</code> ids in the context, pass it as <code>request.POST</code> data, getting it <code>eval()</code> back into a <code>tuple[str]</code> (because it becomes a single <code>str</code> when passed in <code>request.POST</code>) and then performing an API call for every 'str' in my <code>tuple</code> smells like bad code. Any response is appreciated.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T12:56:09.850", "Id": "269420", "Score": "1", "Tags": [ "python", "django" ], "Title": "Execute a third party API call for every object in my queryset in a Django ListView" }
269420
<p>One of the most exciting new functions in C++20 is <code>std::format</code>. I have never liked the ways that strings are formatted in C++ and have been guilty many times of using <code>sprintf</code> and such.</p> <p>Since <code>std::format</code> is not implemented by any of the major compilers at this time, I thought I would try out my own very basic implementation and this is what I have come up with:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;string_view&gt; #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;sstream&gt; #include &lt;stdexcept&gt; void format_helper(std::ostringstream&amp; oss, std::string_view str) // base function { oss &lt;&lt; str; } template&lt;typename T, typename... Targs&gt; void format_helper(std::ostringstream&amp; oss, std::string_view str, T value, Targs... args) { std::size_t openBracket = str.find_first_of('{'); if (openBracket != std::string::npos) { std::size_t closeBracket = str.find_first_of('}', openBracket + 1); if (closeBracket == std::string::npos) throw std::runtime_error(&quot;missing closing bracket.&quot;); oss &lt;&lt; str.substr(0, openBracket); oss &lt;&lt; value; format_helper(oss, str.substr(closeBracket + 1), args...); return; } oss &lt;&lt; str; } std::string format(std::string_view str) { return std::string(str); } template&lt;typename T, typename... Targs&gt; std::string format(std::string_view str, T value, Targs...args) { std::ostringstream oss; format_helper(oss, str, value, args...); return oss.str(); } int main() { int a = 5; double b = 3.14; std::string c(&quot;hello&quot;); // correct number of arguments std::cout &lt;&lt; format(&quot;a = {}, b = {}, c = {}&quot;, a, b, c) &lt;&lt; &quot;\n&quot;; // too few arguments std::cout &lt;&lt; format(&quot;a = {}, b = {}, c = {}&quot;, a, b) &lt;&lt; &quot;\n&quot;; // too many arguments std::cout &lt;&lt; format(&quot;a = {}, b = {}, c = {}&quot;, a, b, c, 12.4) &lt;&lt; &quot;\n&quot;; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T16:51:38.670", "Id": "531596", "Score": "2", "body": "Funny how you didn't put the `\\n` in the format string :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T17:44:14.510", "Id": "531598", "Score": "1", "body": "@G.Sliepen yeah that is a bit ironic :-)" } ]
[ { "body": "<p>Library includes are almost sorted, but <code>&lt;string_view&gt;</code> is out of place - perhaps an oversight?</p>\n<p>We can use a fold-expression to avoid having to write specific recursion in <code>format_helper()</code> (yes, I know that's usually not a recursive <em>call</em>, just template expansion). See below.</p>\n<p><code>format_helper()</code> should be in an implementation namespace, where it's less visible to client code.</p>\n<p>I wouldn't throw an exception for the unterminated <code>{}</code> in the format string. At first glance, this looks like it's a programming error, but consider that in a production program, the format string probably comes from a translation database. It's probably more useful to translators to see the unreplaced part of the string than to get a much more vague exception message (that doesn't even indicate which format string caused it).</p>\n<p>There's no reason to use <code>find_first_of(char)</code> rather than the shorter <code>find(char)</code>. In fact, I'm not sure why the latter is provided.</p>\n<hr />\n<h2>Fold-expression version</h2>\n<p>From C++17 onwards, we have <em>fold expressions</em>, which make variadic templates much, much simpler to write and to reason about. For us, it means only one version of each function.</p>\n<p>The key here is that we want to pass the string view by reference, so that printing each argument adjusts the format string seen by the remaining ones.</p>\n<pre><code>template&lt;typename T&gt;\nvoid format_helper(std::ostringstream&amp; oss,\n std::string_view&amp; str, const T&amp; value)\n{\n std::size_t openBracket = str.find('{');\n if (openBracket == std::string::npos) { return; }\n std::size_t closeBracket = str.find('}', openBracket + 1);\n if (closeBracket == std::string::npos) { return; }\n oss &lt;&lt; str.substr(0, openBracket) &lt;&lt; value;\n str = str.substr(closeBracket + 1);\n}\n\ntemplate&lt;typename... Targs&gt;\nstd::string format(std::string_view str, Targs...args)\n{\n std::ostringstream oss;\n (format_helper(oss, str, args),...);\n oss &lt;&lt; str;\n return oss.str();\n}\n</code></pre>\n<p>At this point, we could (arguably should) bring the helper inside <code>format</code> as a named lambda, so we define only a single function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T16:34:27.770", "Id": "531595", "Score": "0", "body": "If you just use it to find a single `char`, then `find_first_of()` would indeed be redundant, but if you pass it a string then `find_first_of()` and `find()` do something different." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T19:10:31.543", "Id": "531603", "Score": "0", "body": "@G.Sliepen: yes, that's why I was specific about the overload that takes a `char`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T21:06:19.813", "Id": "531607", "Score": "0", "body": "Symmetry I guess? It would be weird if it accepts everything that `find()` does *except* a `char`. But `find()` indeed makes more sense here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T13:05:47.460", "Id": "531649", "Score": "0", "body": "Thanks for your review, especially re. fold expressions! Is there any benefit over using a named lambda over simply `static void format_helper`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T13:14:20.700", "Id": "531650", "Score": "0", "body": "One benefit is almost the same as we could get by writing `namespace format_detail { template<⋯> void format_helper(⋯); }`: it's not polluting the client code's namespace (remember that, being a template, the name must be visible in every TU that instantiates `format()`; we don't gain much from `static` linkage). The other benefit, and this one is more subjective, is that it's declared right by its only use, so everything is in one place in the source. That's only a slight benefit, especially when the source file comprises just those two functions." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T16:31:54.907", "Id": "269429", "ParentId": "269425", "Score": "5" } }, { "body": "<p>If you pass a string with no arguments, it will not do any checking for embedded control sequences and will print the string as-is without any error and without handling escaped out sequences.</p>\n<p>You should break out the brace finding into separate functions to make it easier to extend, such as adding <code>&quot;{{&quot;</code> to mean a literal open-brace character, and make the contents inside the braces available as formatting options.</p>\n<p>The error should mention &quot;}&quot; rather than just &quot;closing bracket&quot; since someone reading this error might not realize you're referring to the curly brace. For that matter, it should indicate the fact that the error comes from the formatting code, and ought to show the bad string.</p>\n<hr />\n<p>You should use a single character rather than a nul-terminated character string when you only have a single character. <code>cout &lt;&lt; '\\n';</code> will be more efficient and generate less code than using <code>&quot;\\n&quot;</code>.</p>\n<hr />\n<p>All in all, it's good and simple. Something like this was an early example for the power for variadic templates and how that could replace the ostream paradigm.\nFor your own stuff, you don't have to make it look somewhat similar to the <code>fmt</code> library, but could use your own (simple) conventions for indicating replacements and how they can themselves be escaped out.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T18:52:40.617", "Id": "269437", "ParentId": "269425", "Score": "6" } } ]
{ "AcceptedAnswerId": "269429", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T15:11:59.270", "Id": "269425", "Score": "7", "Tags": [ "c++" ], "Title": "Implementing std::format" }
269425
<p>Hello I have this method that returns an IEnumerable list , it takes 5 seconds to execute , so I want to know how can I optimize it side performance time of response.</p> <pre><code>private IEnumerable&lt;dynamic&gt; GetData(IEnumerable&lt;dynamic&gt; listD) { List&lt;dynamic&gt; data = new List&lt;dynamic&gt;(); foreach (var item in listD) { var allPro = item?.Pro?.Select(x =&gt; new RepHelper { Res = x.Rep, Title = x.Title }); string allRep = &quot;&quot;; if (allPro.Any()) { allRep = JsonConvert.SerializeObject(allPro); } data.Add(new { Id = item.Id, Auteur = item?.AspNetUsers?.Init ?? &quot;&quot;, NiveauCode = item?.Niveau?.Code ?? &quot;&quot;, NiveauTextColeur = item?.Niveau?.TextColeur ?? &quot;&quot;, Rep = item?.Pro?.FirstOrDefault(p =&gt; p.Rep == true)?.Title ?? &quot;&quot;, IdParent = item?.Id_Parent ?? -1, allReponse = allRep, }); } return data; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T16:24:06.357", "Id": "531593", "Score": "6", "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 [ask] for examples, and revise the title accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-09T16:06:19.470", "Id": "532711", "Score": "0", "body": "I have rolled back Rev 2 → 1. Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-10T03:45:39.233", "Id": "532762", "Score": "0", "body": "I would start by not ever using `dynamic` in performance-sensitive code." } ]
[ { "body": "<p>Other than the general rule of &quot;don't use <code>dynamic</code> if you don't have to&quot;, there's not much to optimize here. The serialization to JSON is probably your hot spot. However, you can pre-allocate your final list size like so:</p>\n<p><code>List&lt;dynamic&gt; data = new List&lt;dynamic&gt;(listD.Count());</code></p>\n<p>and that will buy you fewer reallocations, depending on the number of items you're passing in.</p>\n<p>However, back to &quot;Don't use <code>dynamic</code>: your anonymous type is all <code>dynamic</code>s due to the nature of the assignment, but it seems that you know most of them are <code>string</code>s while a couple are (probably) <code>int</code>s. So define a type:</p>\n<pre><code>public class FinalData\n{\n public int Id { get; set; }\n\n public string Auteur { get; set; }\n\n public string NiveauCode { get; set; }\n\n public string NiveauTextColeur { get; set; }\n\n public string Rep { get; set; }\n\n public int IdParent { get; set; }\n\n public string allReponse { get; set; }\n}\n</code></pre>\n<p>And it can still be assigned to a <code>dynamic</code> member of the <code>List&lt;dynamic&gt;</code> as you do. So here is the following code (note, I also combined your <code>if</code> into a ternary in the assignment to tighten things up:</p>\n<pre><code> private IEnumerable&lt;dynamic&gt; GetData(IEnumerable&lt;dynamic&gt; listD)\n {\n List&lt;dynamic&gt; data = new List&lt;dynamic&gt;(listD.Count());\n\n foreach (var item in listD)\n {\n var allPro = ((IEnumerable&lt;dynamic&gt;)item?.Pro)?.Select(x =&gt; new RepHelper\n {\n Res = x.Rep,\n Title = x.Title\n });\n\n data.Add(new FinalData\n {\n Id = item?.Id ?? -1,\n Auteur = item?.AspNetUsers?.Init ?? string.Empty,\n NiveauCode = item?.Niveau?.Code ?? string.Empty,\n NiveauTextColeur = item?.Niveau?.TextColeur ?? string.Empty,\n Rep = ((IEnumerable&lt;dynamic&gt;)item?.Pro)?.FirstOrDefault(p =&gt; p.Rep)?.Title ?? string.Empty,\n IdParent = item?.Id_Parent ?? -1,\n allReponse = allPro?.Any() == true ? JsonConvert.SerializeObject(allPro) : string.Empty,\n });\n }\n\n return data;\n }\n</code></pre>\n<p>Now, important most of all: <strong>You</strong> need to define what is acceptable performance of the method. Five seconds is too slow. Measure twice, cut once is an old adage which applies quite well to software development.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T09:08:17.493", "Id": "531635", "Score": "1", "body": "I have tested the line of initialisation of the list data with pre allocation size listD.Count() this is take 1174 ms but without specifying the size it takes only 1 ms I have tested with PerfTips in visual studio , so here pre allocation list size dosn't speed up the method note that my count list is only 20 element what do you think ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T07:38:18.967", "Id": "531767", "Score": "0", "body": "@mecab95 Make an interface out of the object type and have that be the list type. Returning `List<IDataItem>` is fine. Also, only reason I'm not upvoting is `== true`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T09:58:09.033", "Id": "531839", "Score": "0", "body": "@T145 what is the advantage of using an interface here over a class type for DataItem in thé side of thé performance ?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T17:09:31.803", "Id": "269432", "ParentId": "269427", "Score": "1" } }, { "body": "<p>Linq <code>Select</code> and <code>FirstOrDefault(Func)</code> both have internal iterators, as well as <code>JsonConvert.SerializeObject</code>. So, if you count them, then you have at least 4 iterators going inside your method. You can at reduce that by combining <code>Select</code> and <code>FirstOrDefault(Func)</code> with a single iterator something like :</p>\n<pre><code>private IEnumerable&lt;dynamic&gt; GetData(IEnumerable&lt;dynamic&gt; listD)\n{\n List&lt;dynamic&gt; data = new List&lt;dynamic&gt;();\n \n foreach (var item in listD)\n {\n if(item == null) continue;\n\n var responseList = new List&lt;RepHelper&gt;();\n\n string repTitle; \n \n if(item?.Pro != null)\n {\n foreach(var pro in item.Pro)\n {\n if(pro == null) continue;\n \n var rep = new RepHelper { Res = pro.Rep, Title = pro.Title };\n \n if(repTitle == null &amp;&amp; rep.Res == true)\n { \n repTitle = rep.Title; \n } \n \n responseList.Add(rep);\n }\n } \n \n data.Add(new\n {\n Id = item.Id,\n Auteur = item?.AspNetUsers?.Init ?? string.Empty,\n NiveauCode = item?.Niveau?.Code ?? string.Empty,\n NiveauTextColeur = item?.Niveau?.TextColeur ?? string.Empty,\n Rep = repTitle ?? string.Empty,\n IdParent = item?.Id_Parent ?? -1,\n allReponse = responseList.Count &gt; 0 ? JsonConvert.SerializeObject(responseList) : string.Empty,\n });\n }\n \n return data;\n}\n</code></pre>\n<p>Now, since you're returning <code>IEnumerable</code>, why not use <code>yield return</code> instead of initializing a <code>List&lt;dynamic&gt;</code> ? so your work would be like :</p>\n<pre><code>private IEnumerable&lt;dynamic&gt; GetData(IEnumerable&lt;dynamic&gt; listD)\n{\n foreach (var item in listD)\n {\n // same code here ....\n \n \n yield return new\n {\n Id = item.Id,\n Auteur = item?.AspNetUsers?.Init ?? string.Empty,\n NiveauCode = item?.Niveau?.Code ?? string.Empty,\n NiveauTextColeur = item?.Niveau?.TextColeur ?? string.Empty,\n Rep = repTitle ?? string.Empty,\n IdParent = item?.Id_Parent ?? -1,\n allReponse = responseList.Count &gt; 0 ? JsonConvert.SerializeObject(responseList) : string.Empty,\n };\n }\n}\n</code></pre>\n<p>You can also go <code>IEnumerable</code> all the way, with something like this :</p>\n<pre><code>private string _repTitle; \nprivate bool _hasRepHelperCollection;\n\nprivate IEnumerable&lt;dynamic&gt; GetData(IEnumerable&lt;dynamic&gt; source)\n{\n foreach (var item in source)\n { \n if(item != null)\n {\n _hasRepHelperCollection = false;\n _repTitle = null;\n \n var allPro = GetRepHelper(item?.Pro);\n\n yield return new\n {\n Id = item.Id,\n Auteur = item?.AspNetUsers?.Init ?? string.Empty,\n NiveauCode = item?.Niveau?.Code ?? string.Empty,\n NiveauTextColeur = item?.Niveau?.TextColeur ?? string.Empty,\n Rep = _repTitle ?? string.Empty,\n IdParent = item?.Id_Parent ?? -1,\n allReponse = _hasRepHelperCollection ? JsonConvert.SerializeObject(allPro) : string.Empty\n };\n \n }\n }\n}\n\nprivate IEnumerable&lt;RepHelper&gt; GetRepHelper(IEnumerable&lt;dynamic&gt; source)\n{\n if(source == null)\n yield break;\n \n foreach(var item in source)\n {\n if(item != null)\n {\n var rep = new RepHelper { Res = response.Rep, Title = response.Title };\n \n if(_repTitle == null &amp;&amp; rep.Rep)\n { \n _repTitle = rep.Title;\n } \n \n if(!hasRepHelperCollection)\n _hasRepHelperCollection = true;\n \n yield return rep;\n } \n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T02:00:26.670", "Id": "269535", "ParentId": "269427", "Score": "1" } } ]
{ "AcceptedAnswerId": "269535", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T15:56:48.007", "Id": "269427", "Score": "0", "Tags": [ "c#", ".net" ], "Title": "How can I make this faster" }
269427
<p>I am testing captcha setups with Fastapi. Currently, I am using an in-memory session (stored in a dictionary. Seems to not be a problem as there is no load balancing, etc...).</p> <p>To fill out the contact form the frontend app makes a request to start a session (thus retrieving the captcha image and setting an opaque (really just a random UUID) session cookie (expiration. Of course, the id references the in-memory session that contains the captcha answer, which is checked at the time of submission. If the captcha answer doesn't match the session's captcha is cleared and a new captcha is set in the user's session.</p> <p>My question is this enough to mitigate automation attacks (I know you can pay for services etc... to get around captcha but I am trying to see what loop holes lie in this code)?</p> <p>Here is my code thus far:</p> <pre><code>from captcha.image import ImageCaptcha from fastapi import FastAPI, Request, Response, HTTPException, status def captcha_generator(size: int): return ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(size)) def generate_captcha(): captcha: str = captcha_generator(5) image = ImageCaptcha() data = image.generate(captcha) data = base64.b64encode(data.getvalue()) return {&quot;data&quot;: data, &quot;captcha&quot;: captcha} @app.get('/') def main(request: Request): return templates.TemplateResponse(&quot;index.html&quot;, {&quot;request&quot;: request}) @app.get('/start-session') def start_session(request: Request): captcha = generate_captcha() request.session[&quot;captcha&quot;] = captcha['captcha'] captcha_image = captcha[&quot;data&quot;].decode(&quot;utf-8&quot;) return StreamingResponse(io.BytesIO(base64.b64decode(captcha_image)), media_type=&quot;image/png&quot;) @app.post('/contact-submission') def submission( request: Request ,response: Response ,data # This includes the captcha answer provided by user ): if request.session.get(&quot;captcha&quot;, uuid.uuid4()) == data.captcha: return status.HTTP_200_OK else: request.session[&quot;captcha&quot;] = str(uuid.uuid4()) raise HTTPException(status.HTTP_403_FORBIDDEN, detail=&quot;Captcha Does not Match&quot;) </code></pre> <p>Here is what the cookie looks like:</p> <p><img src="https://i.stack.imgur.com/9q1Ve.png" alt="Session Cookie" /></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T16:19:28.047", "Id": "269428", "Score": "0", "Tags": [ "python", "session", "captcha" ], "Title": "Fastapi Session Captcha" }
269428
<p>Im using a bunch of ACF fields for my WooCommerce email templates and for this example Im calling these in my email_header template. Im using this with WPML, and need to call each language settings. The code works, but seems like it should be a way to write this better.</p> <p>This is used to set and fetch the correct language based on meta data on orders. Works well. For this I created an array to shorten it down for each if/else statement. NL is the default language.</p> <pre><code>$language = get_post_meta( get_the_ID(), 'wpml_language', true ); if ($language == 'en') { </code></pre> <p>For the front, this is used to fetch the right language:</p> <pre><code>} elseif (ICL_LANGUAGE_CODE=='en') { </code></pre> <p>For this statement to get the correct language, I need to ad a language prefix to each ACF variable, so it doesn't work to use the variable from the array, it defaults to NL then:</p> <pre><code>$sitelogo = get_field('en_logo', 'options'); </code></pre> <p>How can I shorten this down? full code:</p> <pre><code> $header_variabls_one = $sitelogo = get_field('logo', 'options'); $header_variabls_two = $emailLogoLink = get_field('email_logo_link', 'options'); $header_variabls_three = $sitelogo = get_field('logo', 'options'); $header_variabls_four = $header_link_one = get_field('header_links_link_one', 'options'); $header_variabls_five = $header_link_one_url = get_field('header_links_link_one_url', 'options'); $header_variabls_six = $header_link_two = get_field('header_links_link_two', 'options'); $header_variabls_seven = $header_link_two_url = get_field('header_links_link_two_url', 'options'); $header_variabls_eight = $header_link_three = get_field('header_links_link_three', 'options'); $header_variabls_nine = $header_link_three_url = get_field('header_links_link_three_url', 'options'); $header_variabls_ten = $header_link_four = get_field('header_links_link_four', 'options'); $header_variabls_eleven = $header_link_four_url = get_field('header_links_link_four_url', 'options'); $header_variabls_twelve = $ups1 = get_field('header_usps_usp_1', 'options'); $header_variabls_thirteen = $ups2 = get_field('header_usps_usp_2', 'options'); $header_variabls_fourtneen = $ups3 = get_field('header_usps_usp_3', 'options'); $header_variabls = array ( $header_variabls_one, $header_variabls_two, $header_variabls_three, $header_variabls_four, $header_variabls_five, $header_variabls_six, $header_variabls_seven, $header_variabls_eight, $header_variabls_nine, $header_variabls_ten, $header_variabls_eleven, $header_variabls_twelwe, $header_variabls_thirteen, $header_variabls_fourteen, ); global $post; global $sitepress; $postid = $post-&gt;ID; $language = get_post_meta( get_the_ID(), 'wpml_language', true ); if ($language == 'en') { add_filter('acf/settings/current_language', function(){return 'en';}); $header_variabls; } elseif ($language == 'nl') { add_filter('acf/settings/current_language', function(){return 'nl';}); $header_variabls; } elseif ($language == 'de') { add_filter('acf/settings/current_language', function(){return 'de';}); $header_variabls; } elseif (ICL_LANGUAGE_CODE=='en') { $sitepress-&gt;switch_lang( 'en', true ); do_action( 'wpml_switch_language', &quot;en&quot; ); $sitelogo = get_field('en_logo', 'options'); $emailLogoLink = get_field('en_email_logo_link', 'options'); $sitelogo = get_field('en_logo', 'options'); $header_link_one = get_field('en_header_links_link_one', 'options'); $header_link_one_url = get_field('en_header_links_link_one_url', 'options'); $header_link_two = get_field('en_header_links_link_two', 'options'); $header_link_two_url = get_field('en_header_links_link_two_url', 'options'); $header_link_three = get_field('en_header_links_link_three', 'options'); $header_link_three_url = get_field('en_header_links_link_three_url', 'options'); $header_link_four = get_field('en_header_links_link_four', 'options'); $header_link_four_url = get_field('en_header_links_link_four_url', 'options'); $ups1 = get_field('en_header_usps_usp_1', 'options'); $ups2 = get_field('en_header_usps_usp_2', 'options'); $ups3 = get_field('en_header_usps_usp_3', 'options'); } elseif (ICL_LANGUAGE_CODE=='de') { $sitelogo = get_field('de_logo', 'options'); $emailLogoLink = get_field('de_email_logo_link', 'options'); $sitelogo = get_field('de_logo', 'options'); $header_link_one = get_field('de_header_links_link_one', 'options'); $header_link_one_url = get_field('de_header_links_link_one_url', 'options'); $header_link_two = get_field('de_header_links_link_two', 'options'); $header_link_two_url = get_field('de_header_links_link_two_url', 'options'); $header_link_three = get_field('de_header_links_link_three', 'options'); $header_link_three_url = get_field('de_header_links_link_three_url', 'options'); $header_link_four = get_field('de_header_links_link_four', 'options'); $header_link_four_url = get_field('de_header_links_link_four_url', 'options'); $ups1 = get_field('de_header_usps_usp_1', 'options'); $ups2 = get_field('de_header_usps_usp_2', 'options'); $ups3 = get_field('de_header_usps_usp_3', 'options'); } elseif (ICL_LANGUAGE_CODE=='nl') { $sitepress-&gt;switch_lang( 'nl', true ); do_action( 'wpml_switch_language', &quot;nl&quot; ); $header_variabls; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T20:06:28.033", "Id": "531604", "Score": "1", "body": "A CodeReview title must not include the kind of review that you are seeking. The title must only describe what your script does. You might like to add a `wordpress` tag to you question. Please take the [tour] and [edit] your question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T20:16:54.930", "Id": "531605", "Score": "0", "body": "Welcome to Code Review! Is `$header_variabls_fourtneen` (on the 14th line) supposed to be `$header_variabls_fourteen` (like it is on the 31st line)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T07:28:38.333", "Id": "531631", "Score": "0", "body": "Yes! Miss-spelled. Thanks!" } ]
[ { "body": "<p>Although I am pretty new to PHP/WordPress myself, one item I saw right away to make your code prettier is spacing.</p>\n<p>From the <a href=\"https://developer.wordpress.org/coding-standards/wordpress-coding-standards/php/#indentation\" rel=\"nofollow noreferrer\">WordPress PHP Coding Standards section on indentation</a></p>\n<blockquote>\n<p>Your indentation should always reflect logical structure. Use <strong>real tabs</strong> and <strong>not spaces</strong>, as this allows the most flexibility across clients.</p>\n<p>Exception: if you have a block of code that would be more readable if things are aligned, use spaces:</p>\n<pre><code>[tab]$foo = 'somevalue';\n[tab]$foo2 = 'somevalue2';\n[tab]$foo34 = 'somevalue3';\n[tab]$foo5 = 'somevalue4';\n</code></pre>\n</blockquote>\n<p>Also for prettiness you should have a lot more spaces:\nAlways put spaces after commas, and on both sides of logical, comparison, string and assignment operators. (from that same page from WordPress)</p>\n<p>Another quick win is 'options' is repeated throughout the page. You can set a variable at the top to repeat this.</p>\n<p>I also removed the double variable as it didn't seem necessary but I may not know something there so have caution. It just didn't seem necessary.</p>\n<p>Lastly, you spelled out numbers instead of writing them, this was a lot of extra characters you could have just used numbers in.</p>\n<pre><code>&lt;?php\n\n$o = 'options';\n\n$sitelogo = get_field( 'logo', $o ); \n$emailLogoLink = get_field( 'email_logo_link', $o );\n$sitelogo = get_field( 'logo', $o ); \n$header_link_1 = get_field( 'header_links_link_1', $o );\n$header_link_1_url = get_field( 'header_links_link_1_url', $o );\n$header_link_2 = get_field( 'header_links_link_2', $o );\n$header_link_2_url = get_field( 'header_links_link_2_url', $o );\n$header_link_3 = get_field( 'header_links_link_3', $o );\n$header_link_3_url = get_field( 'header_links_link_3_url', $o );\n$header_link_4 = get_field( 'header_links_link_4', $o );\n$header_link_4_url = get_field( 'header_links_link_4_url', $o );\n$ups1 = get_field( 'header_usps_usp_1', $o );\n$ups2 = get_field( 'header_usps_usp_2', $o );\n$ups3 = get_field( 'header_usps_usp_3', $o ); \n \n \n$header_variabls = array (\n $sitelogo, \n $emailLogoLink, \n $sitelogo, \n $header_link_1, \n $header_link_1_url, \n $header_link_2, \n $header_link_2_url, \n $header_link_3, \n $header_link_3_url,\n $header_link_4, \n $header_link_4_url, \n $ups1, \n $ups2, \n $ups3, \n);\n \n \n global $post;\n global $sitepress;\n $postid = $post-&gt;ID; \n $language = get_post_meta( get_the_ID(), 'wpml_language', true );\n if ( $language == 'en' ) {\n add_filter( 'acf/settings/current_language', function(){ return 'en'; } );\n $header_variabls;\n } elseif ( $language == 'nl' ) {\n add_filter( 'acf/settings/current_language', function(){ return 'nl'; } );\n $header_variabls;\n } elseif ( $language == 'de' ) {\n add_filter( 'acf/settings/current_language', function(){ return 'de'; } );\n $header_variabls;\n } elseif ( ICL_LANGUAGE_CODE=='en' ) {\n $sitepress-&gt;switch_lang( 'en', true );\n do_action( 'wpml_switch_language', &quot;en&quot; );\n $sitelogo = get_field('en_logo', $o); \n $emailLogoLink = get_field('en_email_logo_link', $o);\n $sitelogo = get_field('en_logo', $o); \n $header_link_1 = get_field('en_header_links_link_1', $o);\n $header_link_1_url = get_field('en_header_links_link_1_url', $o);\n $header_link_2 = get_field('en_header_links_link_2', $o);\n $header_link_2_url = get_field('en_header_links_link_2_url', $o);\n $header_link_3 = get_field('en_header_links_link_3', $o);\n $header_link_3_url = get_field('en_header_links_link_3_url', $o);\n $header_link_4 = get_field('en_header_links_link_4', $o);\n $header_link_4_url = get_field('en_header_links_link_4_url', $o);\n $ups1 = get_field('en_header_usps_usp_1', $o);\n $ups2 = get_field('en_header_usps_usp_2', $o);\n $ups3 = get_field('en_header_usps_usp_3', $o); \n } elseif ( ICL_LANGUAGE_CODE=='de' ) {\n $sitelogo = get_field('de_logo', $o); \n $emailLogoLink = get_field('de_email_logo_link', $o);\n $sitelogo = get_field('de_logo', $o);\n $header_link_1 = get_field('de_header_links_link_1', $o);\n $header_link_1_url = get_field('de_header_links_link_1_url', $o);\n $header_link_2 = get_field('de_header_links_link_2', $o);\n $header_link_2_url = get_field('de_header_links_link_2_url', $o);\n $header_link_3 = get_field('de_header_links_link_3', $o);\n $header_link_3_url = get_field('de_header_links_link_3_url', $o);\n $header_link_4 = get_field('de_header_links_link_4', $o);\n $header_link_4_url = get_field('de_header_links_link_4_url', $o);\n $ups1 = get_field('de_header_usps_usp_1', $o);\n $ups2 = get_field('de_header_usps_usp_2', $o);\n $ups3 = get_field('de_header_usps_usp_3', $o); \n } elseif ( ICL_LANGUAGE_CODE=='nl' ) {\n $sitepress-&gt;switch_lang( 'nl', true );\n do_action( 'wpml_switch_language', &quot;nl&quot; ); \n $header_variabls;\n }\n\n ?&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T19:49:43.243", "Id": "531748", "Score": "2", "body": "I'd highly suggest using [PSR](https://www.php-fig.org/psr/) instead of WP's code standards. At the end of the day you are writing code in PHP regardless of what framework or alike you are using. You never know, a piece of code you used in a WP project, you might use it somewhere else not to mention actually following PHP / Core language standards should always be preferred." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T06:10:02.020", "Id": "269491", "ParentId": "269433", "Score": "3" } }, { "body": "<p>Some points to consider:</p>\n<ul>\n<li>You have a duplicate header value, site logo appears twice</li>\n<li>Inconsistent variable names: you are using sitelogo, emailLogoLink, and header_link_one</li>\n<li>It might be worth considering checking lowercase values of strings in case you get 'NL' instead of 'nl'</li>\n</ul>\n<p>You can also use the header variables to store the name of the field, and then grab them later. This lets you prepend the language code to them to make it more DRY.</p>\n<p>I used a switch statement for the check for <code>$ICL_LANGUAGE_CODE</code> as I can take advantage of fall-through to not update header fields for NL.</p>\n<p>Note: the code below is untested, and may very well not work.</p>\n<pre><code>$headerVariables = [\n 'logo',\n 'email_logo_link',\n 'logo',\n 'header_links_link_one',\n 'header_links_link_one_url',\n 'header_links_link_two',\n 'header_links_link_two_url',\n 'header_links_link_three',\n 'header_links_link_three_url',\n 'header_links_link_four',\n 'header_links_link_four_url',\n 'header_usps_usp_1',\n 'header_usps_usp_2',\n 'header_usps_usp_3'];\n\nglobal $post;\nglobal $sitepress;\n$postid = $post-&gt;ID;\n$language = get_post_meta( get_the_ID(), 'wpml_language', true );\nif (in_array($language, ['en', 'nl', 'de'])) {\n add_filter('acf/settings/current_language', function(){return $language;});\n} else {\n switch ($ICL_LANGUAGE_CODE) {\n case 'en':\n case 'de':\n foreach ($headerVariables as $key =&gt; $value) {\n $headerVariables[$key] = $ICL_LANGUAGE_CODE . '_' . $value;\n }\n case 'nl':\n $sitepress-&gt;switch_lang( $ICL_LANGUAGE_CODE, true );\n do_action( 'wpml_switch_language', $ICL_LANGUAGE_CODE);\n }\n}\n\n// Get all header variables\nforeach ($headerVariables as $key =&gt; $value) {\n $headerVariables[$key] = get_field($value, 'options');\n}\n\n// set variables in case we need them later\n$sitelogo = $headerVariables[0];\n$emailLogoLink = $headerVariables[1];\n$sitelogo = $headerVariables[2];\n$header_link_one = $headerVariables[3];\n$header_link_one_url = $headerVariables[4];\n$header_link_two = $headerVariables[5];\n$header_link_two_url = $headerVariables[6];\n$header_link_three = $headerVariables[7];\n$header_link_three_url = $headerVariables[8];\n$header_link_four = $headerVariables[9];\n$header_link_four_url = $headerVariables[10];\n$ups1 = $headerVariables[11];\n$ups2 = $headerVariables[12];\n$ups3 = $headerVariables[13];\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T04:23:34.407", "Id": "531824", "Score": "0", "body": "Are you sure about that `switch()` block? I don't see any `break`s. I think I'd use a `default` case instead of having to maintain an `in_array()` function and a `switch()` block." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T01:33:33.973", "Id": "531896", "Score": "0", "body": "@mickmackusa taken from the [PHP manual](https://www.php.net/manual/en/control-structures.switch.php): `If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case.`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T01:38:53.713", "Id": "531897", "Score": "0", "body": "So you mean that `en` and `de` should also fall through to `nl`? If so, then I don't see any need to write the two lines of code under `nl` -- just write them after the `switch` block." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T01:49:06.310", "Id": "531898", "Score": "0", "body": "As far as what I'd use there. I'm not 100% sure I'd use what I put either. But either way multiple if or switch statements are needed as you need to check multiple variables. I think it's a matter of preference, and if working with a team would try to align my code with existing code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T01:51:41.057", "Id": "531900", "Score": "0", "body": "@mickmackusa Yeah, they should also fall through to `nl` but `nl` language should not run the code for `en` and `de`. So we have the `nl` in there to show where the `nl` code should start from." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T02:05:44.313", "Id": "531901", "Score": "0", "body": "I guess what I mean to say is if this is what you mean https://3v4l.org/qiDbY, then `case 'nl':` doesn't need to be in the `switch` at all. I just feel like it is trying to trick my eyes with multiple cases and no breaks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T17:17:36.470", "Id": "531972", "Score": "0", "body": "@mickmackusa the main issue with that is that what's in the `nl` section would then be executed for all languages. But based on the code given, the code should only execute for `en`, `de`, and `nl`. So I do understand your aversion to the switch with no breaks, a number of people don't like it, and it could be broken into multiple if statements instead with slightly more code needed. See https://3v4l.org/bliTB for an example." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T16:32:54.390", "Id": "269515", "ParentId": "269433", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T17:49:29.040", "Id": "269433", "Score": "2", "Tags": [ "php" ], "Title": "Calling multiple ACF field - how do I write my code prettier?" }
269433
<p>First things first, I made a DatabaseConnection-class which connects to the database like so:</p> <pre><code>public class DatabaseConnection { private Connection con; public Connection getConnection() { try { con = DriverManager.getConnection(&quot;jdbc:mysql://localhost:3306/todolistdb&quot;, &quot;root&quot;, &quot;x&quot;); } catch (SQLException e) { e.printStackTrace(); System.out.println(&quot;Failed to create database connection!&quot;); } return con; } </code></pre> <p>And then I have this in my main class:</p> <pre><code>public static void main(String args[]) throws SQLException { DatabaseConnection dbConn = new DatabaseConnection(); new UI(dbConn).start(); </code></pre> <p>I did it like so, because I had a previous iteration of this app where I had to use a Storage-class in multiple places and I implemented it like so. (Passing the DBConn as a parameter to UI.)</p> <p>All in all I’d like to get some feedback on the ToDoListDAO class and how I dealt with the database connection as a whole. This is my first time connecting to a database and I am quite proud of myself, but I want to know what can be done to improve it.</p> <p>Also I am updating the database right after the user enters a new item to be added to the to-do list. Would I be better off gathering them to a data structure, e.g. a list, and update the database when the program is quit?</p> <p><strong>Everything aside from what I’ve specifically asked about is more than welcome as well!</strong></p> <p>ToDoListDAO:</p> <pre><code>public class ToDoListDAO { private ToDoList list = new ToDoList(); private ArrayList&lt;String&gt; fromDB; private Connection con; private PreparedStatement stmt; private ResultSet rs; private DatabaseConnection dbCon; public ToDoListDAO(DatabaseConnection DBConn) throws SQLException { this.dbCon = DBConn; this.fromDB = new ArrayList&lt;&gt;(); this.fromDB = getFromDB(); } public ToDoList returnList() { for (String line : fromDB) { ToDo todo = new ToDo(line); list.addToDo(todo); } return this.list; } public ArrayList&lt;String&gt; getFromDB() throws SQLException { try { this.con = dbCon.getConnection(); this.stmt = con.prepareStatement(&quot;select * from todolist&quot;); this.rs = stmt.executeQuery(); while (rs.next()) { fromDB.add(rs.getString(&quot;task&quot;)); } } finally { rs.close(); stmt.close(); con.close(); } return fromDB; } public void addToDB(String task) { try { this.con = dbCon.getConnection(); this.stmt = con.prepareStatement(&quot;INSERT INTO todolist(task) VALUES &quot; + &quot;(&quot; + &quot;\&quot;&quot; + task +&quot;\&quot;)&quot;); stmt.executeUpdate(); stmt.close(); con.close(); } catch (SQLException SQLe) { SQLe.printStackTrace(); } } public void deleteFromDB(String task) { try { this.con = dbCon.getConnection(); this.stmt = con.prepareStatement(&quot;DELETE FROM todolist WHERE task = &quot; + &quot;\&quot;&quot; + task + &quot;\&quot;&quot;); stmt.executeUpdate(); stmt.close(); con.close(); } catch (SQLException SQLe) { SQLe.printStackTrace(); } } </code></pre> <p>And finally here's the current UI:</p> <pre><code>public class UI { private final Scanner reader; private ToDoList list; private ToDoListDAO tdldao; public UI(DatabaseConnection DBConn) throws SQLException { this.tdldao = new ToDoListDAO(DBConn); this.reader = new Scanner(System.in); this.list = tdldao.returnList(); } public void start() { this.list.printToDoList(); while (true) { System.out.println(&quot;&quot;); System.out.println(&quot;1: Add a to-do item.&quot;); System.out.println(&quot;2. Remove a to-do item.&quot;); System.out.println(&quot;3. Print a list of my to-do items.&quot;); System.out.println(&quot;4. Quit and save&quot;); System.out.print(&quot;Type the number of desired action: &quot;); String input = reader.nextLine(); if (input.equals(&quot;4&quot;)) { System.out.println(&quot;Quitting!&quot;); break; } else if (input.equals(&quot;1&quot;)) { System.out.println(&quot;What would you like to add?&quot;); String add = reader.nextLine(); ToDo item = new ToDo(add); this.list.addToDo(item); this.tdldao.addToDB(item.toString()); } else if (input.equals(&quot;2&quot;)) { if (this.list.getList().size() &lt; 1) { System.out.println(); System.out.println(&quot;Nothing to delete!&quot;); } else { System.out.print(&quot;Type the index of the item you wish to remove: &quot;); try { int remove = Integer.parseInt(reader.nextLine()); this.tdldao.deleteFromDB(this.list.getList().get(remove - 1).toString()); this.list.removeToDo(remove); } catch (NumberFormatException nfe) { System.out.println(&quot;Please enter a number.&quot;); } catch (IndexOutOfBoundsException ib) { System.out.println(&quot;Please enter a number between or equal to 1 or &quot; + this.list.getList().size() + &quot;.&quot;); } } } else if (input.equals(&quot;3&quot;)) { System.out.println(&quot;&quot;); this.list.printToDoList(); } } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T17:51:28.757", "Id": "269434", "Score": "0", "Tags": [ "java", "design-patterns", "jdbc" ], "Title": "Java database connection and DAO implementation feedback" }
269434
<p>So the kata/problem was: &quot;Simple, given a string of words, return the length of the shortest word(s).&quot;</p> <p>Example test: findShort(&quot;Bitcoin will maybe save the world&quot;)</p> <p>And my solution was:</p> <pre><code> function findShort(s){ // convert string to array const strArr = s.split(' '); // loop through array and find length const lengthOfWords = strArr.map(string =&gt; { return (string.length); }) // output length of shortest string return Math.min(...lengthOfWords); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T18:39:28.130", "Id": "531601", "Score": "4", "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 [ask] for examples, and revise the title accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T08:58:10.270", "Id": "531632", "Score": "2", "body": "There are some edge cases you may want to consider: Will input always contain at least 1 word? Will input only contains letters and spaces, will there be any hyphen or punctuation marks? And what does a \"word\" mean in the question? What about input contains 2 continuing spaces?" } ]
[ { "body": "<p>As far as implementation goes, it looks generally good to me (though arguably you should be splitting on any whitespace character, not just spaces). However I do feel that the function name (<code>findShort</code>) is unclear, and additionally those comments do not offer any benefit. Indeed, the second one is perhaps even misleading.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T13:46:26.583", "Id": "269771", "ParentId": "269435", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T17:52:37.193", "Id": "269435", "Score": "2", "Tags": [ "javascript", "array" ], "Title": "Is this a good solution to \"Shortest Word\" kata on codewars?" }
269435
<ul> <li><p>x and y are two-dimensional arrays with dimensions (AxN) and (BxN), i.e. they have the same number of columns.</p> </li> <li><p>I need to get a matrix of Euclidean distances between each pair of rows from x and y.</p> </li> </ul> <p>I have already written four different methods that give equally good results. But the first three methods are not fast enough, and the fourth method consumes too much memory.</p> <p>1:</p> <pre><code>from scipy.spatial import distance def euclidean_distance(x, y): return distance.cdist(x, y) </code></pre> <p>2:</p> <pre><code>import numpy as np import math def euclidean_distance(x, y): res = [] one_res = [] for i in range(len(x)): for j in range(len(y)): one_res.append(math.sqrt(sum(x[i] ** 2) + sum(y[j] ** 2) - 2 * np.dot(x[i], np.transpose(y[j])))) res.append(one_res) one_res = [] return res </code></pre> <p>3:</p> <pre><code>import numpy as np def euclidean_distance(x, y): distances = np.zeros((x.T[0].shape[0], y.T[0].shape[0])) for x, y in zip(x.T, y.T): distances = np.subtract.outer(x, y) ** 2 + distances return np.sqrt(distances) </code></pre> <p>4:</p> <pre><code>import numpy as np def euclidean_distance(x, y): x = np.expand_dims(x, axis=1) y = np.expand_dims(y, axis=0) return np.sqrt(((x - y) ** 2).sum(-1)) </code></pre> <p>It looks like the second way could still be improved, and it also shows the best timing. Can you help me with the optimization, please?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T01:40:57.547", "Id": "531616", "Score": "1", "body": "Welcome to Code Review@SE. Time allowing, (re?)visit [How to get the best value out of Code Review](https://codereview.meta.stackexchange.com/q/2436). As per [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask), the title of a CR question (*and*, preferably, [the code itself](https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring)) should state what the code is to accomplish." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T02:04:43.513", "Id": "531619", "Score": "2", "body": "It may help the non-mathheads if you added why&how 2-4 compute the distances. Please add how the result is going to be used - e.g, for comparisons, you don't need sqrt (`cdist(x, y, 'sqeuclidean')`). Do you need all values at once/as a matrix? Otherwise, a *generator* may help. What are typical dimensions of `x` and `y`?" } ]
[ { "body": "<p>Ideas for <code>2</code>:</p>\n<ul>\n<li>preallocate <code>res</code></li>\n<li>don't use <code>one_res</code>, just a comprehensions</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T03:05:11.170", "Id": "531626", "Score": "0", "body": "(There's [`_cdist_callable()`](https://github.com/scipy/scipy/blob/master/scipy/spatial/distance.py).)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T02:10:51.593", "Id": "269445", "ParentId": "269436", "Score": "1" } }, { "body": "<h3>Performance:</h3>\n<p>A way to use broadcasting but avoid allocating the 3d array is to separate the distance formula into $(x - y) ** 2 = x^2 + y^2 - 2xy$.</p>\n<pre><code>squared_matrix = np.sum(A ** 2,axis=1 )[:,np.newaxis] - 2 * (A@B.T) + np.sum(B ** 2,axis=1 )[np.newaxis,:]\ndistance_matrix = np.sqrt(squared_matrix)\n</code></pre>\n<p>Check:</p>\n<pre><code>np.allclose(distance_matrix,euclidean_distance(A,B))\n&gt;&gt;&gt; True\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T12:46:06.953", "Id": "531716", "Score": "1", "body": "You can probably write this with np.einsum in a more succinct way but einsum makes my head hurt." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T12:41:55.283", "Id": "269504", "ParentId": "269436", "Score": "1" } } ]
{ "AcceptedAnswerId": "269504", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T18:14:16.877", "Id": "269436", "Score": "2", "Tags": [ "python", "performance", "comparative-review", "numpy" ], "Title": "How can I optimize this pairwise Euclidean distance search algorithm?" }
269436
<p>Items.cs, Creates dictionaries, enumerators, and classes for every type of item.</p> <pre><code>using System; using System.Collections.Generic; public class Item { // Medical public static Dictionary &lt; Medical, ItemMedical &gt; Medicals = new Dictionary&lt;Medical, ItemMedical&gt;() { { Medical.bandage, new ItemMedical() { name = &quot;bandage&quot;, healing = 15, weight = 0.2f, value = 75, description = &quot;Simple bandage to dress minor injuries. For patching up boo boos when you fall off your bicycle, won't save you from a gunshot.&quot; }}, { Medical.tourniquet, new ItemMedical() { name = &quot;tourniquet&quot;, healing = 25, weight = 0.7f, value = 225, description = &quot;A device that tightly wraps around a limb near the wound to stop the flow of blood, more importantly, it stops blood from flowing OUT.&quot; }} }; // Weapon public static Dictionary &lt; Weapon, ItemWeapon &gt; Weapons = new Dictionary &lt; Weapon, ItemWeapon &gt; () { { Weapon.shortsword, new ItemWeapon() { name = &quot;shortsword&quot;, Damage = 25, weight = 4, value = 750, description = &quot;A relatively short sword, hence the very creative name \&quot;Shortsword\&quot;.&quot; }}, { Weapon.longsword, new ItemWeapon() { name = &quot;longsword&quot;, Damage = 40, weight = 6, value = 950, description = &quot;A relatively long sword, hence the very creative name \&quot;Longsword\&quot;.&quot; }} }; // Armor public static Dictionary &lt; Armor, ItemArmor &gt; Armors = new Dictionary &lt; Armor, ItemArmor &gt; () { { Armor.police_vest, new ItemArmor() { name = &quot;police vest&quot;, Resistance = 25, Durability = 15, weight = 5, value = 1200, description = &quot;A pistol grade body armor used by police forces.&quot; }}, { Armor.military_vest, new ItemArmor() { name = &quot;military vest&quot;, Resistance = 60, Durability = 40, weight = 8, value = 2400, description = &quot;A heavy military vest capable of withstanding some rifle rounds.&quot; }} }; public static ItemMedical Get(Medical key) =&gt; Medicals[key]; public static ItemWeapon Get(Weapon key) =&gt; Weapons[key]; public static ItemArmor Get(Armor key) =&gt; Armors[key]; } public enum Medical { bandage, tourniquet } public enum Weapon { shortsword, longsword } public enum Armor { police_vest, military_vest } public class ItemMedical: ItemBase { public float healing = 0; } public class ItemWeapon: ItemBase { private float damage = 0; public float Damage { get =&gt; damage; set =&gt; damage = value; } } public class ItemArmor: ItemBase { // Damage required to penetrate armor public float Resistance = 0; // &quot;health&quot; of the armor, damaged much more if penetrated private float durability = 0; public float Durability { get =&gt; durability; set =&gt; durability = Math.Clamp(value, 0, value); } } public class ItemBase { public string name = &quot;No name&quot;; public string description = &quot;No description&quot;; public float weight = 0; public float value = 0; } </code></pre> <p>Inventory.cs, equipment is an array because the slots never change, but backpack is a list because i dont know how many items will be in there.</p> <pre><code> public static ItemBase[] equipment = new ItemBase[4] { // Primary weapon Item.Get(Weapon.longsword), // Secondary weapon Item.Get(Weapon.shortsword), // Body armor Item.Get(Armor.police_vest), // Rig null }; public static List&lt;ItemBase&gt; backpack = new List&lt;ItemBase&gt;() { Item.Get(Medical.bandage), Item.Get(Medical.bandage), }; } </code></pre> <p>Usage</p> <pre><code>class Program { static void Main(string[] args) { Console.WriteLine(&quot;Items in inventory:&quot;); foreach(ItemBase item in Inventory.equipment) { if (item != null) Console.WriteLine(item.name); else Console.WriteLine(&quot;Nothing&quot;); } Console.WriteLine(&quot;\nItems in backpack:&quot;); foreach(ItemBase item in Inventory.backpack) { Console.WriteLine(item.name); } } } </code></pre> <p>Output:</p> <p><code>Items in inventory:</code> <code>longsword</code> <code>shortsword</code> <code>police vest</code> <code>Nothing</code></p> <p><code>Items in backpack:</code> <code>bandage</code> <code>bandage</code></p>
[]
[ { "body": "<p>First of all, congratulation it is a great first attempt. Even though it does not contain too much functionality rather structure and data.</p>\n<p>Most of my recommendation will be related to C# coding conventions. Some of my suggestions are taking advantage of C# 9's new features so I'll share some links about them.</p>\n<h3>Enums</h3>\n<pre><code>public enum Medical { Bandage, Tourniquet }\npublic enum Weapon { ShortSword, LongSword }\npublic enum Armor { PoliceVest, MilitaryVest }\n</code></pre>\n<ul>\n<li>In C# we usually use PascalCasing for enum members\n<ul>\n<li>In your <code>Weapon</code> enum you have used lower casing</li>\n<li>whereas in your <code>Armor</code> enum you have used snake_casing</li>\n<li>Please try to chase consistency across your domain model</li>\n</ul>\n</li>\n<li>Most of the time when the enum contains less than 5 members (and they are not overwriting default values) C# developers tend to define the enum in a single line</li>\n</ul>\n<h3>Base class</h3>\n<pre><code>public abstract class ItemBase\n{\n public string Name { get; init; } = &quot;No name&quot;;\n public string Description { get; init; } = &quot;No description&quot;;\n public float Weight { get; init; }\n public float Value { get; init; }\n}\n</code></pre>\n<ul>\n<li>This class is used to define common properties that's why it is advisable to mark it as <code>abstract</code>\n<ul>\n<li>That prevents the consumer of this class to instantiate an object from it</li>\n<li>You want to allow to be able to create only derived classes</li>\n</ul>\n</li>\n<li>C# developers are preferring properties over fields whenever they are public\n<ul>\n<li>That's why I've changed all the base class members to properties</li>\n<li>I've also changed their name since in C# we normally use Pascal Casing for properties</li>\n<li>I've used <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/init\" rel=\"nofollow noreferrer\"><code>init</code></a> instead of <code>set</code>, because it only allows initialization (via constructor or via object initializer)\n<ul>\n<li>So, after an item is created with a specified values it can't be changed later on</li>\n</ul>\n</li>\n<li>Since C# 6 you can define <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties\" rel=\"nofollow noreferrer\">default value for auto generated fields</a></li>\n</ul>\n</li>\n</ul>\n<h3>Derived classes</h3>\n<pre><code>public class ItemMedical : ItemBase\n{\n public float Healing { get; init; }\n}\n\npublic class ItemWeapon : ItemBase\n{\n public float Damage { get; init; }\n}\n\npublic class ItemArmor : ItemBase\n{\n public float Resistance { get; init; }\n private float durability;\n public float Durability\n {\n get =&gt; durability;\n set =&gt; durability = Math.Clamp(value, 0, value);\n }\n}\n</code></pre>\n<ul>\n<li>Please prefer auto-generated properties over manually creating backing fields and defining getter and setter methods\n<ul>\n<li>The only exception is whenever you have custom logic either inside the getter or inside the setter (like <code>Durability</code>)</li>\n</ul>\n</li>\n<li>I've get rid of the <code>= 0</code> initial value assignments since these are their <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/default-values\" rel=\"nofollow noreferrer\">default values</a></li>\n</ul>\n<h3>The Item class #1</h3>\n<p>This <em>constant data</em> class can be implemented in several ways. One way to achieve it as you have done it.</p>\n<ul>\n<li>In this case you can mark the class itself as <code>static</code> since all of its member is <code>static</code> as well</li>\n<li>If you expose the dictionaries (<code>public</code>) then you should consider to make them <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.immutable.immutabledictionary-2?view=net-5.0\" rel=\"nofollow noreferrer\">immutable</a> to prevent further element removal or addition after intialization</li>\n</ul>\n<pre><code>public static class Item\n{\n public static readonly ImmutableDictionary&lt;Medical, ItemMedical&gt; Medicals = new Dictionary&lt;Medical, ItemMedical&gt;\n {\n {\n Medical.Bandage,\n new()\n {\n Name = &quot;bandage&quot;,\n Healing = 15,\n Weight = 0.2f,\n Value = 75,\n Description = &quot;Simple bandage to dress minor injuries. For patching up boo boos when you fall off your bicycle, won't save you from a gunshot.&quot;\n }\n },\n {\n Medical.Tourniquet,\n new()\n {\n Name = &quot;tourniquet&quot;,\n Healing = 25,\n Weight = 0.7f,\n Value = 225,\n Description = &quot;A device that tightly wraps around a limb near the wound to stop the flow of blood, more importantly, it stops blood from flowing OUT.&quot;\n }\n }\n }.ToImmutableDictionary();\n\n ...\n\n public static ItemMedical Get(Medical key) =&gt; Medicals[key];\n public static ItemWeapon Get(Weapon key) =&gt; Weapons[key];\n public static ItemArmor Get(Armor key) =&gt; Armors[key];\n}\n</code></pre>\n<ul>\n<li>I've marked the collections as <code>readonly</code> to prevent overwriting with another collection or null by the consumer of the class</li>\n<li>I've used <code>new()</code> (<a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/target-typed-new\" rel=\"nofollow noreferrer\">target typed new expression</a>) to avoid repeating the class names over and over again\n<ul>\n<li>It can be inferred from the Dictionary type parameter</li>\n</ul>\n</li>\n</ul>\n<h3>The Item class #2</h3>\n<p>Let me show you an alternative approach:</p>\n<pre><code>public class Item\n{\n private static readonly Lazy&lt;Item&gt; singleton = new Lazy&lt;Item&gt;(new Item());\n public static Item Instance =&gt; singleton.Value;\n\n private Item() { }\n\n private readonly Dictionary&lt;Medical, ItemMedical&gt; Medicals = new ()\n {\n {\n Medical.Bandage,\n new ()\n {\n Name = &quot;bandage&quot;,\n Healing = 15,\n Weight = 0.2f,\n Value = 75,\n Description = &quot;Simple bandage to dress minor injuries. For patching up boo boos when you fall off your bicycle, won't save you from a gunshot.&quot;\n }\n },\n {\n Medical.Tourniquet,\n new ()\n {\n Name = &quot;tourniquet&quot;,\n Healing = 25,\n Weight = 0.7f,\n Value = 225,\n Description = &quot;A device that tightly wraps around a limb near the wound to stop the flow of blood, more importantly, it stops blood from flowing OUT.&quot;\n }\n }\n };\n\n ...\n\n public ItemMedical this[Medical key] =&gt; Medicals[key];\n public ItemWeapon this[Weapon key] =&gt; Weapons[key];\n public ItemArmor this[Armor key] =&gt; Armors[key];\n}\n</code></pre>\n<ul>\n<li>Here I've made the dictionaries <code>private</code> so they became <strong>implementation details</strong></li>\n<li>I've replaced the <code>Get</code> methods to <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/indexers/using-indexers\" rel=\"nofollow noreferrer\">index operators</a> to make the item retrieval a bit more convenient\n<ul>\n<li>See next section for usage</li>\n<li>The index operators can't be defined as <code>static</code> so we have to make a little trick here to make the usage easy</li>\n</ul>\n</li>\n<li>We use the <a href=\"https://csharpindepth.com/articles/singleton#lazy\" rel=\"nofollow noreferrer\">singleton pattern</a> to expose a single instance to the consumers of the class\n<ul>\n<li>Here I've implemented this pattern with a <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.lazy-1?redirectedfrom=MSDN&amp;view=net-5.0\" rel=\"nofollow noreferrer\"><code>Lazy</code></a> to make sure that the instance is created only when it is first accessed but in a thread safe manner</li>\n</ul>\n</li>\n</ul>\n<p>These changes allow us to define the <code>Equipments</code> and <code>Backpack</code> like this:</p>\n<pre><code>public ItemBase[] Equipments = new []\n{\n Item.Instance[Weapon.LongSword],\n Item.Instance[Weapon.ShortSword],\n Item.Instance[Armor.PoliceVest],\n (ItemBase)null\n};\n\npublic List&lt;ItemBase&gt; Backpack = new ()\n{\n Item.Instance[Medical.Bandage],\n Item.Instance[Medical.Bandage],\n};\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T16:51:56.373", "Id": "269467", "ParentId": "269439", "Score": "4" } } ]
{ "AcceptedAnswerId": "269467", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T19:42:33.103", "Id": "269439", "Score": "3", "Tags": [ "c#", "beginner", "game" ], "Title": "Simple item and inventory system in C#, my first actually competant looking piece of code as a beginner. Really proud of it" }
269439
<p>I have been writing this piece of code for a while now, and I was wondering, is it possible to run this code multiple times on my pc? For example could I make the code solve all the numbers from 1 to 1000 and all from 1001 to 2000 at the same time? And, if this is possible, could I use multiple computers to solve it in this way (just with bigger numbers)?</p> <p>Heres the Code:</p> <pre><code>#(n*3)+1 = if odd #else n/2 = if even import time import sys def progress(count, total, status=''): bar_len = 60 filled_len = int(round(bar_len * count / float(total))) percents = round(100.0 * count / float(total), 1) bar = '█' * filled_len + '-' * (bar_len - filled_len) sys.stdout.write('[%s] %s%s ...%s\r' % (bar, percents, '%', status)) sys.stdout.flush() one = &quot;nothing&quot; while one != &quot;n&quot;: if one == &quot;n&quot;: break else: total = input(&quot;what is the limit number?:&quot;) total = int(total) total = total+1 highest_step = 0 highest_num = 0 for x in range(0,total): n = x steps = 0 print(end=&quot;\r&quot;) progress(n, total, status='Doing very long job, current Num:'+str(n))# emulating long-playing job #print(&quot;----IMPOSSIBLE MATH SOLUTION------&quot;) #print() #print (&quot;staring number is:(&quot;,n,&quot;)&quot;) #print() while n != 0: if n != 1: if (n%2) == 0: #print( eval(&quot;n/2&quot;) n = eval(&quot;n/2&quot;) steps = steps+1 else: #print ( eval(&quot;(n*3)+1&quot;) n = eval(&quot;(n*3)+1&quot;) steps = steps+1 else: #print (&quot;amount of steps it took to solve:&quot;,steps) if (highest_step &lt;= steps): highest_step = steps highest_num = x break else: break print() print() print (&quot;the number with most steps&quot;,highest_num) print (&quot;amount of steps:&quot;,highest_step) one = input(&quot;congrats!, do it again? (y/n)&quot;) </code></pre> <p>This would be a great help, thanks</p> <p>(Also, I am still a beginner coder in python3.)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T23:20:15.837", "Id": "531614", "Score": "6", "body": "Your existing code is fine to review, but this site isn't really well suited to tell you how to rewrite this from scratch in a distributed manner." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T03:19:23.353", "Id": "531627", "Score": "0", "body": "`1 to 1000 [/] 1001 to 2000` Given the relation between argument and run time, that division of labour may need to be refined. There is [Python concurrency](https://docs.python.org/3/library/concurrency.html) with modules/packages like [concurrent](https://docs.python.org/3/library/concurrent.html), [threading](https://docs.python.org/3/library/threading.html), [multiprocessing](https://docs.python.org/3/library/multiprocessing.html)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T10:11:18.387", "Id": "531638", "Score": "0", "body": "I'm not sure that distributing the calculation on multiple computers would be faster than running the code with memoization of the previous results. Especially checking for powers of 2 should speed up the calculation. As is you're redoing at least the 8 - 4 - 2 -1 sequence for every number >4. Ideally you'd run it on multiple processes with a shared dictionnary [num] -> steps." } ]
[ { "body": "<p>Not exactly sure what your goal is. If your primary goal is just getting the <code>highest_step</code> and <code>highest_num</code> a lot faster than your current code does, then you could achieve the goal without any of that. As an example, when I run the following code (basically your code that calculates to 99,999 without taking input or displaying the progress bar) on my machine,</p>\n<pre><code>from time import perf_counter_ns as ns\n\n\nstart = ns()\nlimit = 100_000\nhighest_step = 0\nhighest_num = 0 \n\nfor x in range(limit):\n n = x\n steps = 0\n\n while n != 0:\n if n != 1:\n if (n%2) == 0:\n n = eval(&quot;n/2&quot;)\n steps = steps+1\n else:\n n = eval(&quot;(n*3)+1&quot;)\n steps = steps+1\n else:\n if (highest_step &lt;= steps):\n highest_step = steps\n highest_num = x\n break\n else:\n break\nprint(&quot;the number with most steps&quot;,highest_num)\nprint(&quot;amount of steps:&quot;,highest_step)\nprint(f'it took {(ns() - start)/1e6:,.0f}ms')\n</code></pre>\n<p>it prints this.</p>\n<pre><code>the number with most steps 77031\namount of steps: 350\nit took 28,098ms\n</code></pre>\n<p>However, the same code without the useless <code>eval()</code> prints this (18x speed).</p>\n<pre><code>the number with most steps 77031\namount of steps: 350\nit took 1,562ms\n</code></pre>\n<p>If I run the that code with pypy 3.8 instead of python 3.10, then this (49x speed).</p>\n<pre><code>the number with most steps 77031\namount of steps: 350\nit took 569ms\n</code></pre>\n<p>And when I run the following code on the same machine with pypy3.8,</p>\n<pre><code>from time import perf_counter_ns as ns\n\n\nstart = ns()\nlimit = 100_000\nmemo = {i: 0 for i in range(limit)}\nfor i in range(3):\n memo[i] = i\nfor i in range(3, limit):\n counter = 0\n cur = i\n while i &gt; 1:\n if i &lt; cur:\n memo[cur] = memo[i] + counter\n break\n if not i % 2:\n i /= 2\n counter += 1\n else:\n i *= 3\n i += 1\n counter += 1\nprint(f'the number with most steps: {max(memo, key=memo.get)}')\nprint(f'amount of steps: {max(memo.values()) - 1}')\nprint(f'it took {(ns() - start)/1e6:,.0f}ms')\n</code></pre>\n<p>it prints this (375x speed), even though this is probably not the most efficient way to do it, and Python usually take a considerably longer time to compute the same task, compare to many other languages like C++.</p>\n<pre><code>the number with most steps: 77031\namount of steps: 350\nit took 75ms\n</code></pre>\n<p><strong>EDIT</strong>: Added some more benchmark results (limit is now 1 million, instead of 100k shown above)</p>\n<ol>\n<li><p>only removed two <code>input()</code>s from your original code (all four <code>eval()</code>s intact):</p>\n<ul>\n<li>python3.10: <code>771,214ms</code></li>\n</ul>\n</li>\n<li><p>the 28 seconds code above (two <code>eval()</code>s remaining, progress bar removed):</p>\n<ul>\n<li>python3.10: <code>344,444ms</code> (2.2x speed)</li>\n</ul>\n</li>\n<li><p>without <code>eval()</code>:</p>\n<ul>\n<li>python3.10: <code>19,238ms</code> (40x speed)</li>\n<li>pypy3.8: <code>6,937ms</code> (111x speed)</li>\n</ul>\n</li>\n<li><p>using <code>dict</code> memo:</p>\n<ul>\n<li>python3.10: <code>1,078ms</code> (715x speed)</li>\n<li>pypy3.8: <code>732ms</code> (1,054x speed)</li>\n</ul>\n</li>\n<li><p>using <code>list</code> memo (shown below):</p>\n<ul>\n<li>python3.10: <code>805ms</code> (950x speed)</li>\n<li>pypy3.8: <code>50ms</code> (15,424x speed)</li>\n</ul>\n</li>\n</ol>\n<pre><code>from time import perf_counter_ns as ns\n\n\nstart = ns()\nlimit = 1_000_000\nmemo = [0] * limit\nmemo[1], memo[2] = 1, 2\nfor i in range(3, limit):\n counter = 0\n cur = i\n while i &gt; 1:\n if i &lt; cur:\n memo[cur] = memo[i] + counter\n break\n if not i % 2:\n i //= 2\n counter += 1\n else:\n i *= 3\n i += 1\n counter += 1\nprint(f'the number with most steps: {memo.index((m := max(memo)))}')\nprint(f'amount of steps: {m - 1}')\nprint(f'it took {(ns() - start)/1e6:,.0f}ms')\n</code></pre>\n<ol start=\"6\">\n<li><code>list</code> variant above vs C++ vector variant (1.96x over pypy, 30,231x speed overall)</li>\n</ol>\n<pre><code>pypy: 0.08s user 0.02s system 94% cpu 0.102 total (when it prints 51ms)\ng++: 0.05s user 0.00s system 98% cpu 0.052 total\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T15:49:12.307", "Id": "269465", "ParentId": "269443", "Score": "6" } } ]
{ "AcceptedAnswerId": "269465", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T23:00:56.223", "Id": "269443", "Score": "2", "Tags": [ "python", "python-3.x", "collatz-sequence" ], "Title": "How to make my Collatz Conjecture code run a lot faster? (and even better, how do I implement it into multiple computers?) Python" }
269443
<p>putting the if-else block outside of a function looks clutter to me, should I just put it inside a function and then inside the useEffect ?</p> <p><strong>Purpose of the if-else block</strong>: Render the cards base on the value pass from index.js</p> <p>Below is my displayItem code</p> <p>displayItem.js</p> <pre><code>import React, { useState } from &quot;react&quot;; import { Card } from &quot;antd&quot;; import { data } from &quot;./data.js&quot;; export default function DisplayItem(props) { let [minValue, setMinValue] = useState(0); let [maxValue, setMaxValue] = useState(0); let [columnStyle, setColumn] = useState({}); let [update, setUpdate] = useState(true); if (props.value === 6 &amp;&amp; update) { setColumn({ float: &quot;left&quot;, width: &quot;30%&quot;, padding: &quot;5px&quot; }); setMaxValue(props.value); setUpdate(false); } else if (props.value === 4 &amp;&amp; update) { setColumn({ float: &quot;left&quot;, width: &quot;40%&quot;, padding: &quot;5px&quot; }); setMaxValue(props.value); setUpdate(false); } const createCards = (i, item) =&gt; { console.log(&quot;maxValue &quot;, props.value); return ( &lt;div key={i} style={columnStyle}&gt; &lt;Card className=&quot;custom-card&quot; bodyStyle={{ padding: 0 }}&gt; &lt;div className=&quot;custom-card-content&quot; style={{ backgroundColor: &quot;green&quot;, color: &quot;white&quot; }} &gt; &lt;label&gt; Name: {item.name} &lt;/label&gt; &lt;br /&gt; &lt;label&gt; Check IN: {item.checkin} &lt;/label&gt; &lt;br /&gt; &lt;label&gt; Check Out: {item.checkout} &lt;/label&gt; &lt;/div&gt; &lt;/Card&gt; &lt;/div&gt; ); }; return ( &lt;div&gt; &lt;div&gt; {data.slice(minValue, maxValue).map((item, i) =&gt; { return i &gt;= minValue &amp;&amp; i &lt;= maxValue &amp;&amp; createCards(i, item); })} &lt;/div&gt; &lt;/div&gt; ); } </code></pre> <p>This is my <a href="https://codesandbox.io/s/purple-http-84bh1?file=/src/displayItems.js" rel="nofollow noreferrer">codesandbox</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T05:23:05.200", "Id": "531629", "Score": "1", "body": "Welcome to Code Review! I [changed the title](https://codereview.stackexchange.com/revisions/269444/5) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate." } ]
[ { "body": "<p><a href=\"https://en.m.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">Don't repeat yourself</a>:</p>\n<pre><code>if (update &amp;&amp; (props.value === 6 || props.value === 4) {\n setColumn({ float: &quot;left&quot;, width: \n (props.value === 6 ? &quot;30%&quot; : &quot;40%&quot;), padding: &quot;5px&quot; });\n setMaxValue(props.value);\n setUpdate(false);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T02:30:27.970", "Id": "269446", "ParentId": "269444", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T01:55:41.407", "Id": "269444", "Score": "0", "Tags": [ "react.js", "jsx" ], "Title": "Check in/out cards" }
269444
<h3>Orcish</h3> <p>Large volumes of unlabelled data are hard to visualize when debugging; I find it difficult to keep track of the pointers in memory. I have used this code to assign Orcish names, (it's a name because I capitalized the first letter.) I use it initialized in the data type itself (<code>orcish</code>), or based on a pointer value (<code>orcify</code>).</p> <h2><code>orcish.h</code></h2> <pre><code>#include &lt;stddef.h&gt; /* size_t */ void orcish(char *, size_t); void orcish_ptr(char *, const size_t, const void *); const char *orcify(const void *); </code></pre> <h2><code>orcish.c</code></h2> <pre><code>/** @license 2014, 2021 Neil Edelman, distributed under the terms of the [MIT License](https://opensource.org/licenses/MIT). Contains some syllables from [SMAUG](http://www.smaug.org/), which is a derivative of [Merc](http://dikumud.com/Children/merc2.asp), and [DikuMud](http://dikumud.com/); used under fair-use. Contains [MurmurHash](https://github.com/aappleby/smhasher)-derived code, placed in public domain by Austin Appleby. @subtitle Name Generator Orcish names originate or are inspired by [JRR Tolkien's Orcish ](http://en.wikipedia.org/wiki/Languages_constructed_by_J._R._R._Tolkien). @std C89 */ #include &lt;stdlib.h&gt; /* rand */ #include &lt;stdio.h&gt; /* strlen */ #include &lt;ctype.h&gt; /* toupper */ #include &lt;string.h&gt; /* memcpy */ #include &lt;assert.h&gt; /* assert */ #include &quot;orcish.h&quot; static const char *syllables[] = { &quot;ub&quot;, &quot;ul&quot;, &quot;uk&quot;, &quot;um&quot;, &quot;uu&quot;, &quot;oo&quot;, &quot;ee&quot;, &quot;uuk&quot;, &quot;uru&quot;, &quot;ick&quot;, &quot;gn&quot;, &quot;ch&quot;, &quot;ar&quot;, &quot;eth&quot;, &quot;ith&quot;, &quot;ath&quot;, &quot;uth&quot;, &quot;yth&quot;, &quot;ur&quot;, &quot;uk&quot;, &quot;ug&quot;, &quot;sna&quot;, &quot;or&quot;, &quot;ko&quot;, &quot;uks&quot;, &quot;ug&quot;, &quot;lur&quot;, &quot;sha&quot;, &quot;grat&quot;, &quot;mau&quot;, &quot;eom&quot;, &quot;lug&quot;, &quot;uru&quot;, &quot;mur&quot;, &quot;ash&quot;, &quot;goth&quot;, &quot;sha&quot;, &quot;cir&quot;, &quot;un&quot;, &quot;mor&quot;, &quot;ann&quot;, &quot;sna&quot;, &quot;gor&quot;, &quot;dru&quot;, &quot;az&quot;, &quot;azan&quot;, &quot;nul&quot;, &quot;biz&quot;, &quot;balc&quot;, &quot;balc&quot;, &quot;tuo&quot;, &quot;gon&quot;, &quot;dol&quot;, &quot;bol&quot;, &quot;dor&quot;, &quot;luth&quot;, &quot;bolg&quot;, &quot;beo&quot;, &quot;vak&quot;, &quot;bat&quot;, &quot;buy&quot;, &quot;kham&quot;, &quot;kzam&quot;, &quot;lg&quot;, &quot;bo&quot;, &quot;thi&quot;, &quot;ia&quot;, &quot;es&quot;, &quot;en&quot;, &quot;ion&quot;, &quot;mok&quot;, &quot;muk&quot;, &quot;tuk&quot;, &quot;gol&quot;, &quot;fim&quot;, &quot;ette&quot;, &quot;moor&quot;, &quot;goth&quot;, &quot;gri&quot;, &quot;shn&quot;, &quot;nak&quot;, &quot;ash&quot;, &quot;bag&quot;, &quot;ronk&quot;, &quot;ask&quot;, &quot;mal&quot;, &quot;ome&quot;, &quot;hi&quot;, &quot;sek&quot;, &quot;aah&quot;, &quot;ove&quot;, &quot;arg&quot;, &quot;ohk&quot;, &quot;to&quot;, &quot;lag&quot;, &quot;muzg&quot;, &quot;ash&quot;, &quot;mit&quot;, &quot;rad&quot;, &quot;sha&quot;, &quot;saru&quot;, &quot;ufth&quot;, &quot;warg&quot;, &quot;sin&quot;, &quot;dar&quot;, &quot;ann&quot;, &quot;mor&quot;, &quot;dab&quot;, &quot;val&quot;, &quot;dur&quot;, &quot;dug&quot;, &quot;bar&quot;, &quot;ash&quot;, &quot;krul&quot;, &quot;gakh&quot;, &quot;kraa&quot;, &quot;rut&quot;, &quot;udu&quot;, &quot;ski&quot;, &quot;kri&quot;, &quot;gal&quot;, &quot;nash&quot;, &quot;naz&quot;, &quot;hai&quot;, &quot;mau&quot;, &quot;sha&quot;, &quot;akh&quot;, &quot;dum&quot;, &quot;olog&quot;, &quot;lab&quot;, &quot;lat&quot; }; static const unsigned syllables_size = sizeof syllables / sizeof *syllables; static const unsigned syllables_max_length = 4; static const char *suffixes[] = { &quot;at&quot;, &quot;ob&quot;, &quot;agh&quot;, &quot;uk&quot;, &quot;uuk&quot;, &quot;um&quot;, &quot;uurz&quot;, &quot;hai&quot;, &quot;ishi&quot;, &quot;ub&quot;, &quot;ull&quot;, &quot;ug&quot;, &quot;an&quot;, &quot;hai&quot;, &quot;gae&quot;, &quot;-hai&quot;, &quot;luk&quot;, &quot;tz&quot;, &quot;hur&quot;, &quot;dush&quot;, &quot;ks&quot;, &quot;mog&quot;, &quot;grat&quot;, &quot;gash&quot;, &quot;th&quot;, &quot;on&quot;, &quot;gul&quot;, &quot;gae&quot;, &quot;gun&quot;, &quot;dan&quot;, &quot;og&quot;, &quot;ar&quot;, &quot;meg&quot;, &quot;or&quot;, &quot;lin&quot;, &quot;dog&quot;, &quot;ath&quot;, &quot;ien&quot;, &quot;rn&quot;, &quot;bul&quot;, &quot;bag&quot;, &quot;ungol&quot;, &quot;mog&quot;, &quot;nakh&quot;, &quot;gorg&quot;, &quot;-dug&quot;, &quot;duf&quot;, &quot;ril&quot;, &quot;bug&quot;, &quot;snaga&quot;, &quot;naz&quot;, &quot;gul&quot;, &quot;ak&quot;, &quot;kil&quot;, &quot;ku&quot;, &quot;on&quot;, &quot;ritz&quot;, &quot;bad&quot;, &quot;nya&quot;, &quot;durbat&quot;, &quot;durb&quot;, &quot;kish&quot;, &quot;olog&quot;, &quot;-atul&quot;, &quot;burz&quot;, &quot;puga&quot;, &quot;shar&quot;, &quot;snar&quot;, &quot;hai&quot;, &quot;ishi&quot;, &quot;uruk&quot;, &quot;durb&quot;, &quot;krimp&quot;, &quot;krimpat&quot;, &quot;zum&quot;, &quot;gimb&quot;, &quot;-gimb&quot;, &quot;glob&quot;, &quot;-glob&quot;, &quot;sharku&quot;, &quot;sha&quot;, &quot;-izub&quot;, &quot;-izish&quot;, &quot;izg&quot;, &quot;-izg&quot;, &quot;ishi&quot;, &quot;ghash&quot;, &quot;thrakat&quot;, &quot;thrak&quot;, &quot;golug&quot;, &quot;mokum&quot;, &quot;ufum&quot;, &quot;bubhosh&quot;, &quot;gimbat&quot;, &quot;shai&quot;, &quot;khalok&quot;, &quot;kurta&quot;, &quot;ness&quot;, &quot;funda&quot; }; static const unsigned suffixes_size = sizeof suffixes / sizeof *suffixes; static const unsigned suffixes_max_length = 7; static const unsigned max_name_size = 256; /** Fills `name` with a random Orcish name. Potentially up to `name_size` - 1, (if zero, does nothing) then puts a null terminator. Uses `r` plugged into `recur` to generate random values in the range of `RAND_MAX`. */ static void orcish_recur(char *const name, size_t name_size, unsigned long r, unsigned (*recur)(unsigned long *)) { char *n = name; const char *part; size_t part_len; assert(name); if(!name_size) { return; } else if(name_size == 1) { *n = '\0'; return; } else if(name_size &gt; max_name_size) { name_size = max_name_size; } /* Now `name_size \in [2, max_name_size]`. */ if(name_size &lt;= syllables_max_length + suffixes_max_length) { part = syllables[recur(&amp;r) / (RAND_MAX / syllables_size + 1)]; part_len = strlen(part); if(part_len &gt;= name_size) part_len = name_size - 1; memcpy(n, part, part_len), n += part_len, name_size -= part_len; if(name_size &gt; suffixes_max_length) { part = suffixes[recur(&amp;r) / (RAND_MAX / suffixes_size + 1)]; part_len = strlen(part); memcpy(n, part, part_len), n += part_len, name_size -= part_len; } } else { unsigned no_syllables = ((unsigned)name_size - 1 - suffixes_max_length) / syllables_max_length; while(no_syllables) { part = syllables[recur(&amp;r) / (RAND_MAX / syllables_size +1)]; part_len = strlen(part); memcpy(n, part, part_len), n += part_len, name_size -= part_len; no_syllables--; } part = suffixes[recur(&amp;r) / (RAND_MAX / suffixes_size + 1)]; part_len = strlen(part); memcpy(n, part, part_len), n += part_len, name_size -= part_len; } *n = '\0'; *name = (char)toupper(*name); } /** &lt;https://github.com/aappleby/smhasher&gt; `src/MurmurHash3.cpp fmix64`. @return Recurrence on `k`. */ static unsigned long fmix_long(unsigned long k) { k ^= k &gt;&gt; 33; k *= 0xff51afd7ed558ccd; k ^= k &gt;&gt; 33; k *= 0xc4ceb9fe1a85ec53; k ^= k &gt;&gt; 33; return k; } /* Advances `r`. @return Number in `[0, RAND_MAX]`. @implements `orcish_recur` */ static unsigned murmur_recur(unsigned long *const r) { return (*r = fmix_long(*r)) % (1lu + RAND_MAX); } /** Uses `rand`; ignores `r` and uses a global variable set by `srand`. @return Number in `[0, RAND_MAX]`. @implements `orcish_recur` */ static unsigned rand_recur(unsigned long *const r) { (void)r; return (unsigned)rand(); } /** Fills `name` with a random Orcish name. Potentially up to `name_size` - 1, then puts a null terminator. Uses `rand` from `stdlib.h`. @param[name_size] If zero, does nothing. */ void orcish(char *const name, const size_t name_size) { orcish_recur(name, name_size, 0, &amp;rand_recur); } /** Fills `name` with a deterministic Orcish name based on `p`. Potentially up to `name_size` - 1, then puts a null terminator. @param[name_size] If zero, does nothing. */ void orcish_ptr(char *const name, const size_t name_size, const void *const p) { assert(name); if(!p) { if(!name_size) return; switch(name_size) { default: case 5: name[3] = 'l'; case 4: name[2] = 'l'; case 3: name[1] = 'u'; case 2: name[0] = 'n'; case 1: break; } name[name_size &lt; 5 ? name_size - 1 : 4] = '\0'; } else { orcish_recur(name, name_size, (unsigned long)p, &amp;murmur_recur); } } /** A convenient way to call &lt;fn:orcish_ptr&gt; with `p`. @return A string in a small temporary buffer that can handle four names at a time. */ const char *orcify(const void *const p) { static char strs[4][12]; static unsigned str; str %= sizeof strs / sizeof *strs; orcish_ptr(strs[str], sizeof *strs, p); return strs[str++]; } </code></pre> <p>Using a <code>MurmerHash3</code> 64-bit mixer has been good on all the computers I've tested it on; I don't know what happens if <code>size_t</code> is smaller; I don't want to include the C99 <code>stdint.h</code>. How hard would multi-threaded support be? I'm also wondering about the copyright: can I take out a portion of GPL code and say that it's now covered in a more permissive MIT license? (The syllables are mostly GPL, as far as I could tell, but they probably came from Tolkien; is it <em>fair use</em> as I have claimed?)</p> <h2><code>main</code></h2> <p>I wrote up <code>main</code> that shows <code>orcify</code> in a real situation. Linking it gives a whole program, but it's example code. It outputs in <a href="https://www.graphviz.org/" rel="nofollow noreferrer">GraphViz</a> which has an <a href="http://magjac.com/graphviz-visual-editor/" rel="nofollow noreferrer">on-line editor</a>: <code>./orc &gt; orc.gv</code>.</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;assert.h&gt; #include &quot;orcish.h&quot; enum order { PRE, POST }; struct tree { struct node *root; }; struct node { size_t edges; struct node *edge[3]; }; struct visit { void (*f)(struct node *); enum order order; }; /** Non-zero parameter set by the `node.edge` count, and number of nodes. */ static const size_t max_edges = sizeof ((struct node *)0)-&gt;edge / sizeof *((struct node *)0)-&gt;edge, max_nodes = max_edges * 5; /** Inverse bushiness, `[0, RAND_MAX]`. */ static int straightness = (int)(RAND_MAX * 0.08); static struct node *node(void) { struct node *n = malloc(sizeof *n); if(!n) return 0; n-&gt;edges = 0; return n; } /** One must set the order to `POST`, otherwise undefined. @implements `visit` */ static void node_(struct node *const n) { assert(n); free(n); } /** @implements `visit` */ static void out(struct node *const n) { size_t e = 0; assert(n); printf(&quot;\tn%p [label=\&quot;%s\&quot;];\n&quot;, (void *)n, orcify(n)); while(e &lt; n-&gt;edges) printf(&quot;\tn%p -&gt; n%p;\n&quot;, (void *)n, (void *)n-&gt;edge[e++]); } static void node_edge(struct node *const n, struct node *const edge) { assert(n &amp;&amp; edge &amp;&amp; n-&gt;edges &lt; max_edges); n-&gt;edge[n-&gt;edges++] = edge; } static struct node *node_rand_edge(const struct node *const n) { assert(n); return n-&gt;edges ? n-&gt;edge[(size_t)rand() / (RAND_MAX / n-&gt;edges + 1)] : 0; } static void visit_node(struct node *const n, const struct visit *const v) { size_t e; assert(v &amp;&amp; v-&gt;f); if(!n) return; if(v-&gt;order == PRE) v-&gt;f(n); for(e = 0; e &lt; n-&gt;edges; e++) visit_node(n-&gt;edge[e], v); if(v-&gt;order == POST) v-&gt;f(n); } static void visit(struct tree *const g, const enum order order, void (*const f)(struct node *)) { struct visit v; assert(g &amp;&amp; f); v.f = f; v.order = order; visit_node(g-&gt;root, &amp;v); } int main(void) { struct tree t = { 0 }; struct node *n, *m; size_t i; int success = 0; for(i = 0; i &lt; max_nodes; i++) { size_t e; int acc; if(!(n = node())) goto catch; if(!t.root) { t.root = n; continue; } m = t.root; /* Knuth's Poisson distribution with fixed point, RAND_MAX ~ 1. */ for(acc = rand(); e = m-&gt;edges; m = node_rand_edge(m)) { if(e == max_edges) continue; if(acc &lt;= straightness) break; acc = (int)((long)rand() * acc / (1l + RAND_MAX)); } node_edge(m, n); } printf(&quot;digraph {\n&quot; &quot;\tnode [shape=box, style=filled, fillcolor=Grey95];\n&quot;); visit(&amp;t, PRE, &amp;out); printf(&quot;}\n&quot;); fprintf(stderr, &quot;Random path from the root: { &quot;); for(n = t.root; n; n = node_rand_edge(n)) fprintf(stderr, &quot;%s%s&quot;, n == t.root ? &quot;&quot; : &quot;, &quot;, orcify(n)); fprintf(stderr, &quot; }.\n&quot;); { success = 1; goto finally; } catch: perror(&quot;graph&quot;); finally: visit(&amp;t, POST, &amp;node_); return success; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T03:29:12.773", "Id": "531688", "Score": "1", "body": "DikuMud .. now theres a name I haven't heard in a long time" } ]
[ { "body": "<p>Header needs an include guard.</p>\n<hr />\n<p><code>orcish_ptr()</code> is defined with a <code>const size_t</code> argument, but the <code>const</code> plays no part in the signature, so omit that.</p>\n<hr />\n<p>It's a good practice for <code>orcish.c</code> to include <code>&quot;orcish.h&quot;</code> as its very first header. This helps detect any inadvertent dependencies, and ensures that the header is self-sufficient.</p>\n<hr />\n<blockquote>\n<pre><code> switch(name_size) {\n default:\n case 5: name[3] = 'l';\n case 4: name[2] = 'l';\n case 3: name[1] = 'u';\n case 2: name[0] = 'n';\n case 1: break;\n }\n</code></pre>\n</blockquote>\n<p>We probably want to label the fall-through at the end of each <code>case</code> here, to prevent someone &quot;fixing&quot; it (and to suppress compiler warnings).</p>\n<p>Actually, the <code>switch</code> might be better replaced with a call to <code>strncpy()</code>:</p>\n<pre><code>if (p) {\n orcish_recur(name, name_size, (unsigned long)p, &amp;murmur_recur);\n} else if (name_size) {\n strncpy(name, &quot;null&quot;, name_size-1);\n name[name_size-1] = '\\0';\n}\n/* else there's nothing we can do here */\n</code></pre>\n<p>If we targeted C99 or later, <code>snprintf(name, name_size, &quot;null&quot;)</code> would be better, as that writes the necessary terminating null char, unlike <code>strncpy()</code>.</p>\n<hr />\n<p>Other than that, I got no compiler warnings, and Valgrind gives full marks for the test program.</p>\n<hr />\n<blockquote>\n<pre><code> { success = 1; goto finally; }\n</code></pre>\n</blockquote>\n<p>I think we have success and failure the wrong way around here - we should return zero to indicate successful execution. More clearly, use <code>EXIT_SUCCESS</code> here, and <code>EXIT_FAILURE</code> otherwise.</p>\n<hr />\n<p>The helper functions in <code>orcify.c</code> (that are not mentioned in the header) are all declared with <code>static</code> linkage so they don't pollute the program's namespace. That's good.</p>\n<p>There's no need to write <code>static</code> for the file-scope variable names (since that's the default), but it does no harm and is arguably helpful to readers.</p>\n<hr />\n<p>I keep getting distracted by the function names ending in <code>_recur</code>. That suggests recursion, but the functions are not recursive - they are just alternative implementations.</p>\n<hr />\n<blockquote>\n<pre><code> *name = (char)toupper(*name);\n</code></pre>\n</blockquote>\n<p>Best practice is to <em>always</em> convert the argument to <code>toupper()</code> into <code>unsigned char</code>, even if you believe that it can only ever be positive (I don't know of EBCDIC systems with signed <code>char</code>, but it's at least theoretically possible):</p>\n<pre><code> *name = (char)toupper((unsigned char)*name);\n</code></pre>\n<hr />\n<blockquote>\n<pre><code>static void orcish_recur(char *const name, … {\n ⋮\n assert(name);\n</code></pre>\n</blockquote>\n<p>I don't think that assertion is correct, because <code>name</code> comes unchecked from the user code, via</p>\n<blockquote>\n<pre><code>void orcish(char *const name, const size_t name_size)\n { orcish_recur(name, name_size, 0, &amp;rand_recur); }\n</code></pre>\n</blockquote>\n<p>Similarly, <code>orcish_ptr</code> cannot assert <code>name</code> either - that has come from outside our code.</p>\n<hr />\n<p>There is a lot of repetition of this pattern:</p>\n<blockquote>\n<pre><code> part = syllables[recur(&amp;r) / (RAND_MAX / syllables_size + 1)];\n</code></pre>\n</blockquote>\n<p>Consider abstracting that into a function or perhaps a macro:</p>\n<pre><code>#define RANDOM_MEMBER(set)\\\n set[recur(&amp;r) / (RAND_MAX / set ## _size + 1)];\n\nstatic void orcish_recur(char *const name, size_t name_size,\n ⋮\n}\n\n#undef RANDOM_MEMBER\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T20:33:46.143", "Id": "531684", "Score": "0", "body": "`recur` in a sense that it's a recurrence relation; `callback` would probably be a more descriptive name." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T07:37:47.050", "Id": "269450", "ParentId": "269448", "Score": "6" } }, { "body": "<p>in addition to Toby Speight's answer:</p>\n<h2>C89 compliance / platform independence:</h2>\n<blockquote>\n<pre><code>static unsigned long fmix_long(unsigned long k)\n{\n k ^= k &gt;&gt; 33;\n k *= 0xff51afd7ed558ccd;\n k ^= k &gt;&gt; 33;\n k *= 0xc4ceb9fe1a85ec53;\n k ^= k &gt;&gt; 33;\n return k;\n}\n</code></pre>\n</blockquote>\n<p>An <code>unsigned long</code> is only guaranteed to be at least 32 bits (e.g. the 64-bit MSVC compiler has only 32 bit <code>unsigned long</code>s), so shifting by 33 may be undefined behavior. The constants may also be truncated to 32 bits.</p>\n<p>We should use a 32 bit hash and/or add platform-dependent typedefs for integer types that we expect to be a specific size (a union can be used to check type sizes as <a href=\"https://barrgroup.com/embedded-systems/how-to/c-fixed-width-integers-c99\" rel=\"noreferrer\">at the bottom of this article</a>).</p>\n<p>(Or we could just use <code>stdint.h</code>).</p>\n<hr />\n<blockquote>\n<pre><code>static const size_t max_edges\n = sizeof ((struct node *)0)-&gt;edge / sizeof *((struct node *)0)-&gt;edge,\n max_nodes = max_edges * 5;\n</code></pre>\n</blockquote>\n<p>Technically <code>max_edges</code> isn't a &quot;constant&quot; (in C89), so <code>max_nodes</code> can't be initialized like this.</p>\n<p>We need to use a <code>#define</code> or an <code>enum</code>.</p>\n<hr />\n<h2>algorithm:</h2>\n<blockquote>\n<pre><code>if(name_size &lt;= syllables_max_length + suffixes_max_length) {\n ... add syllable\n if(name_size &gt; suffixes_max_length) {\n ... add suffix\n }\n } else {\n unsigned no_syllables = ((unsigned)name_size - 1 - suffixes_max_length)\n / syllables_max_length;\n while(no_syllables) {\n ... add syllable\n no_syllables--;\n }\n ... add suffix\n }\n</code></pre>\n</blockquote>\n<p>Besides abstracting the &quot;add foo&quot; parts to a separate function, I think we can simplify the logic a bit here by calculating the number of syllables first, roughly:</p>\n<pre><code>num_syllables = ... (has space for suffix) ? (subtract and divide, min value 1) : 1;\n\nfor (; num_syllables; --num_syllables)\n ... add syllable\n\nif (still has space for suffix)\n ... add suffix\n</code></pre>\n<hr />\n<h2>documentation:</h2>\n<p>It would probably be a good idea to document locally how the algorithm works, instead of only referring people to other sources (links can die). This could include pointing out the effects of a small or large <code>name_size</code> on the number of syllables and suffix.</p>\n<p>(It looks like people passing in a large <code>name_size</code> will always get long(er) names, whether they want them or not... which isn't necessarily intuitive).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T18:26:59.400", "Id": "531672", "Score": "2", "body": "Unfortunately, we can't just use `<stdint.h>` in C89..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T18:33:54.200", "Id": "531674", "Score": "0", "body": "I didn't know what would happen if I compiled it on a 32-bit machine, but that makes perfect sense. I don't suppose there is a `UINTPTR_MAX` that's not part of `stdint.h`? I cap it at `max_name_size`, but you are right, that should probably go in the documentation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T18:52:57.793", "Id": "531675", "Score": "0", "body": "Well, MSVC has `unsigned __int64`. `unsigned long long` might also work on certain compilers, but isn't technically C89. AFAIK, any 64 bit type in C89 is going to be platform dependent, and there are no (platform independent) fixed size types." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T03:54:24.907", "Id": "531690", "Score": "0", "body": "I see what you mean on the algorithm; in fact, that would probably be improved with a Poisson distribution, like I did in the example. I could have `#if ULONG_MAX` to choose between 32 and 64 bit finalizers." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T11:07:20.920", "Id": "269454", "ParentId": "269448", "Score": "5" } } ]
{ "AcceptedAnswerId": "269450", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T05:02:22.853", "Id": "269448", "Score": "7", "Tags": [ "c", "strings", "random", "c89" ], "Title": "Assign determisitic Orcish names for debugging" }
269448
<p>Just a toy project to learn typescript. I haven't made it interactive in any way, though I think I've programmed it in a way where making it interactive should be fairly straight forward:</p> <pre><code>// Any live cell with two or three live neighbours survives. // Any dead cell with three live neighbours becomes a live cell. // All other live cells die in the next generation. Similarly, all other dead cells stay dead. class Game { private board: Cell[][]; private boards: Cell[][][]; private width: number; private height: number; constructor(x: number, y: number) { // i want a grid of x width and y height this.width = x; this.height = y; const rows = []; for (let row = 0; row &lt; y; row++) { const rowCells = []; for (let col = 0; col &lt; x; col++) { rowCells.push(new Cell(false, col, row, this)); } rows.push(rowCells); } this.board = rows; this.boards = [this.board]; } tick(): void { const rows = []; for (let row = 0; row &lt; this.height; row++) { const rowCells = []; for (let col = 0; col &lt; this.width; col++) { let cell = this.board[row][col]; rowCells.push(cell.getNextCell()); } rows.push(rowCells); } this.board = rows; this.saveState(); } print(): void { for (let row of this.board) { let rowText = &quot;&quot;; for (let cell of row) { rowText += cell.getState() ? &quot;8&quot; : &quot;.&quot;; } console.log(rowText); } } getNeighbors(x: number, y: number): Cell[] { const cells = []; for (let dx = -1; dx &lt;= 1; dx++) { for (let dy = -1; dy &lt;= 1; dy++) { if (dx === 0 &amp;&amp; dy === 0) continue; let ny = y + dy; let nx = x + dx; if (ny === -1) ny = this.height - 1; if (nx === -1) nx = this.width - 1; if (ny === this.height) ny = 0; if (nx === this.width) nx = 0; cells.push(this.board[ny][nx]); } } return cells; } saveState(): void { this.boards.push(this.board); } toggleCell(x: number, y: number): void { const rows = []; for (let row = 0; row &lt; this.height; row++) { const rowCells = []; for (let col = 0; col &lt; this.width; col++) { let cell = this.board[row][col]; if (col === x &amp;&amp; row === y) { cell = new Cell(!cell.getState(), col, row, this); } rowCells.push(cell); } rows.push(rowCells); } this.board = rows; this.saveState(); } } class Cell { private readonly state: boolean; private readonly x: number; private readonly y: number; private readonly game: Game; constructor(state: boolean, x: number, y: number, game: Game) { this.state = state; this.x = x; this.y = y; this.game = game; } getState(): boolean { return this.state; } getNextCell(): Cell { const neighbors = game.getNeighbors(this.x, this.y); const liveCellCount = neighbors.reduce((acc, cell) =&gt; acc + (cell.getState() ? 1 : 0), 0); let newState; if (this.state) { // this is alive // Any live cell with two or three live neighbours survives. // All other live cells die in the next generation. newState = liveCellCount === 2 || liveCellCount === 3; } else { // this cell is dead // Any dead cell with three live neighbours becomes a live cell. newState = liveCellCount === 3; } return new Cell(newState, this.x, this.y, this.game); } } const game = new Game(15, 15); game.print(); console.log(&quot;after toggle:&quot;); game.toggleCell(1, 0); game.toggleCell(2, 1); game.toggleCell(2, 2); game.toggleCell(1, 2); game.toggleCell(0, 2); game.print(); for (let tickCount = 0; tickCount &lt; 100; tickCount++) { console.log(&quot;after tick:&quot;); game.tick(); game.print(); } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T09:42:13.260", "Id": "269452", "Score": "0", "Tags": [ "typescript", "game-of-life" ], "Title": "Game of Life in Typescript" }
269452
<p>Here is my wheel. <code>strmap</code> - C string hash map.</p> <p>Main goal - create usable and simple alternative to <code>hcreate_r</code>, <code>hdestroy_r</code>, <code>hsearch_r</code> GNU extensions.</p> <p>I am looking for general review of my code. But any other suggestion and criticism (functionality, usability, code style, performance, memory usage, ...) are welcome.</p> <p>Compile test&amp;benchmark - <code>g++ -O2 -Wall -Wextra -pedantic -o ht ht.cc strmap.c</code></p> <p><strong>strmap.h</strong></p> <pre><code>/** @file strmap.h @brief STRMAP - simple alternative to hcreate_r, hdestroy_r, hsearch_r GNU extensions @date 2021 @license Public Domain */ #ifndef _STRMAP_H #define _STRMAP_H typedef struct STRMAP strmap; #ifdef __cplusplus extern &quot;C&quot; { #endif /** @brief Create a string map which can contain at least `size` elements */ strmap *sm_create(uint32_t size); /** @brief Retrieves user associated data for given key */ bool sm_lookup(strmap *sm, const char *key, void **data); /** @brief Insert key (if not exists) and user data */ bool sm_insert(strmap *sm, const char *key, const void *data); /** @brief Update user data for given key */ bool sm_update(strmap *sm, const char *key, const void *data); /** @brief Update user data for given key or insert if key not exists */ bool sm_upsert(strmap *sm, const char *key, const void *data); /** @brief Remove key Based on M. A. Kolosovskiy, &quot;Simple implementation of deletion from open-address hash table&quot; https://arxiv.org/ftp/arxiv/papers/0909/0909.2547.pdf */ bool sm_remove(strmap *sm, const char *key); /** @brief Remove all keys */ void sm_clear(strmap *sm); /** @brief Return number of keys */ uint32_t sm_size(strmap *sm); /** @brief Remove all keys and free memory allocated for the map structure */ void sm_free(strmap *sm); #ifdef __cplusplus } #endif #endif </code></pre> <p><strong>strmap.c</strong></p> <pre><code>/** @file strmap.c @brief STRMAP - simple alternative to hcreate_r, hdestroy_r, hsearch_r GNU extensions @date 2021 @license Public Domain */ #include &lt;stdint.h&gt; #include &lt;string.h&gt; #include &lt;stdbool.h&gt; #include &lt;stdlib.h&gt; #include &lt;assert.h&gt; #include &quot;strmap.h&quot; #define MIN_SIZE 9 /** Daniel Lemire, A fast alternative to the modulo reduction https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/ */ #define FAST_REDUCE32(x, r) (uint32_t)(((uint64_t)(x) * (uint64_t)(r)) &gt;&gt; 32) #ifdef USE_FAST_REDUCE #define POSITION(x, r) FAST_REDUCE32((x), (r)) #else #define POSITION(x, r) ((x) % (r)) #endif #define DISTANCE(from, to, r) ((to) &gt;= (from) ? (to) - (from) : (r) - ((from) - (to))) struct SLOT { const char *key; // C null terminated string const void *data; // user data uint32_t hash; // key hash value }; struct STRMAP { uint32_t capacity; // number of allocated slots uint32_t size; // number of keys in map struct SLOT *ht; }; static uint32_t FNV_1a(const char *key); static void compress(strmap *sm, struct SLOT *slot); static struct SLOT * find(strmap *sm, const char *key, uint32_t hash); strmap * sm_create(uint32_t size) { struct SLOT *ht; struct STRMAP *sm; uint32_t capacity; capacity = 4 * ((size &gt;= MIN_SIZE ? size : MIN_SIZE) / 3); if (!(ht = (struct SLOT *)calloc(capacity, sizeof (struct SLOT)))) { return NULL; } if ((sm = (struct STRMAP *)calloc(1, sizeof (struct STRMAP)))) { sm-&gt;size = 0; sm-&gt;capacity = capacity; sm-&gt;ht = ht; } else { free(ht); } return sm; } bool sm_insert(strmap *sm, const char *key, const void *data) { struct SLOT *slot; uint32_t hash; assert(sm); assert(key); if (sm-&gt;size == sm-&gt;capacity - 1) { return false; } hash = FNV_1a(key); slot = find(sm, key, hash); if (!(slot-&gt;key)) { slot-&gt;key = key; slot-&gt;data = data; slot-&gt;hash = hash; ++(sm-&gt;size); return true; } return false; } bool sm_update(strmap *sm, const char *key, const void *data) { struct SLOT *slot; uint32_t hash; assert(sm); assert(key); hash = FNV_1a(key); slot = find(sm, key, hash); if (slot-&gt;key) { slot-&gt;data = data; return true; } return false; } bool sm_upsert(strmap *sm, const char *key, const void *data) { struct SLOT *slot; uint32_t hash; assert(sm); assert(key); hash = FNV_1a(key); slot = find(sm, key, hash); if (slot-&gt;key) { slot-&gt;data = data; return true; } if (sm-&gt;size == sm-&gt;capacity - 1) { return false; } slot-&gt;key = key; slot-&gt;data = data; slot-&gt;hash = hash; ++(sm-&gt;size); return true; } bool sm_lookup(strmap *sm, const char *key, void **data) { struct SLOT *slot; uint32_t hash; assert(sm); assert(key); hash = FNV_1a(key); slot = find(sm, key, hash); if (slot-&gt;key) { *data = (void *)slot-&gt;data; return true; } return false; } bool sm_remove(strmap *sm, const char *key) { struct SLOT *slot; uint32_t hash; assert(sm); assert(key); hash = FNV_1a(key); slot = find(sm, key, hash); if (slot-&gt;key) { slot-&gt;key = 0; --(sm-&gt;size); compress(sm, slot); return true; } return false; } void sm_clear(strmap *sm) { assert(sm); for (uint32_t i = 0; i &lt; sm-&gt;capacity; ++i) { (sm-&gt;ht)[i].key = 0; } sm-&gt;size = 0; } uint32_t sm_size(strmap *sm) { assert(sm); return sm-&gt;size; } void sm_free(strmap *sm) { assert(sm); free(sm-&gt;ht); free(sm); } /* private static functions */ /* find slot with given key and hash in collision chain or return first empty */ struct SLOT * find(strmap *sm, const char *key, uint32_t hash) { struct SLOT *slot, *htEnd; slot = sm-&gt;ht + POSITION(hash, sm-&gt;capacity); htEnd = sm-&gt;ht + sm-&gt;capacity; while (slot-&gt;key) { if (hash == slot-&gt;hash) { if (!strcmp(key, slot-&gt;key)) { return slot; } } if (++slot == htEnd) { slot = sm-&gt;ht; } } return slot; } void compress(strmap *sm, struct SLOT *slot) { struct SLOT *empty = slot, *htEnd; struct SLOT *root; htEnd = sm-&gt;ht + sm-&gt;capacity; if (++slot == htEnd) { slot = sm-&gt;ht; } while (slot-&gt;key) { root = sm-&gt;ht + POSITION(slot-&gt;hash, sm-&gt;capacity); if (DISTANCE(root, slot, sm-&gt;capacity) &gt;= DISTANCE(empty, slot, sm-&gt;capacity)) { // swap current slot with empty empty-&gt;key = slot-&gt;key; empty-&gt;data = slot-&gt;data; empty-&gt;hash = slot-&gt;hash; slot-&gt;key = 0; empty = slot; } if (++slot == htEnd) { slot = sm-&gt;ht; } } } #define FNV_PRIME 16777619UL #define FNV_OFFSET 2166136261UL uint32_t FNV_1a(const char *key) { uint32_t h = FNV_OFFSET; while (*key) { h ^= (unsigned char)*key; h *= FNV_PRIME; ++key; } return h; } #undef FNV_PRIME #undef FNV_OFFSET </code></pre> <p><strong>ht.cc</strong></p> <pre><code>#include &lt;algorithm&gt; #include &lt;vector&gt; #include &lt;unordered_set&gt; #include &lt;iostream&gt; #include &lt;chrono&gt; #define USE_FAST_REDUCE 1 #include &quot;strmap.h&quot; typedef std::chrono::high_resolution_clock Clock; using namespace std; int main() { string str = &quot;abcdefghijklmnopqrstuvwxyz&quot;; string xstr = &quot;Zbcdefghijklmnopqrstuvwxyz&quot;; std::chrono::duration&lt;double&gt; elapsed; // keys to insert vector&lt;string&gt; keys; // not existing keys vector&lt;string&gt; xkeys; // key value int val = 1551; // key value for update and upsert int uval = 7117; // pointer for lookup int *data; strmap *ht = sm_create(3700000); auto t1 = Clock::now(); for (int i=0; i&lt;3700000; i++) { random_shuffle(str.begin(), str.end()); keys.push_back(str); } auto t2 = Clock::now(); elapsed = t2 - t1; cout &lt;&lt; &quot;Generate keys: &quot; &lt;&lt; elapsed.count() &lt;&lt; '\n'; t1 = Clock::now(); for (int i=0; i&lt;3700000; i++) { random_shuffle(xstr.begin(), xstr.end()); xkeys.push_back(xstr); } t2 = Clock::now(); elapsed = t2 - t1; cout &lt;&lt; &quot;Generate not existing keys: &quot; &lt;&lt; elapsed.count() &lt;&lt; '\n'; cout &lt;&lt; &quot;*** strmap test ***\n&quot;; t1 = Clock::now(); for (int i=0; i&lt;3700000; i++) { if (!sm_insert(ht, keys[i].c_str(), &amp;val)) { cout &lt;&lt; &quot;Error: &quot; &lt;&lt; keys[i].c_str() &lt;&lt; '\n'; break; } } t2 = Clock::now(); elapsed = t2 - t1; cout &lt;&lt; &quot;Insert: &quot; &lt;&lt; elapsed.count() &lt;&lt; '\n'; t1 = Clock::now(); for (int i=0; i&lt;3700000; i++) { if (!sm_lookup(ht, keys[i].c_str(), (void **)&amp;data)) { cout &lt;&lt; &quot;Error: &quot; &lt;&lt; keys[i] &lt;&lt; '\n'; break; } if (*data != 1551) { cout &lt;&lt; &quot;Error: &quot; &lt;&lt; keys[i] &lt;&lt; &quot; Data:&quot; &lt;&lt; *data &lt;&lt; '\n'; break; } } t2 = Clock::now(); elapsed = t2 - t1; cout &lt;&lt; &quot;Lookup existing: &quot; &lt;&lt; elapsed.count() &lt;&lt; '\n'; t1 = Clock::now(); for (int i=0; i&lt;3700000; i++) { if (!sm_update(ht, keys[i].c_str(), &amp;uval)) { cout &lt;&lt; &quot;Error: &quot; &lt;&lt; keys[i].c_str() &lt;&lt; '\n'; break; } } t2 = Clock::now(); elapsed = t2 - t1; cout &lt;&lt; &quot;Update existing: &quot; &lt;&lt; elapsed.count() &lt;&lt; '\n'; t1 = Clock::now(); for (int i=0; i&lt;3700000; i++) { if (!sm_lookup(ht, keys[i].c_str(), (void **)&amp;data)) { cout &lt;&lt; &quot;Error: &quot; &lt;&lt; keys[i] &lt;&lt; '\n'; break; } if (*data != 7117) { cout &lt;&lt; &quot;Error: &quot; &lt;&lt; keys[i] &lt;&lt; &quot; Data:&quot; &lt;&lt; *data &lt;&lt; '\n'; break; } } t2 = Clock::now(); elapsed = t2 - t1; cout &lt;&lt; &quot;Lookup updated: &quot; &lt;&lt; elapsed.count() &lt;&lt; '\n'; t1 = Clock::now(); for (int i=0; i&lt;3700000; i++) { if (sm_lookup(ht, xkeys[i].c_str(), (void **)&amp;data)) { cout &lt;&lt; &quot;Error: &quot; &lt;&lt; xkeys[i] &lt;&lt; '\n'; ; break; } } t2 = Clock::now(); elapsed = t2 - t1; cout &lt;&lt; &quot;Lookup not existing: &quot; &lt;&lt; elapsed.count() &lt;&lt; '\n'; t1 = Clock::now(); for (int i=0; i&lt;3000000; i++) { if (!sm_remove(ht, keys[i].c_str())) cout &lt;&lt; keys[i]; } t2 = Clock::now(); elapsed = t2 - t1; cout &lt;&lt; &quot;Remove: &quot; &lt;&lt; elapsed.count() &lt;&lt; '\n'; t1 = Clock::now(); for (int i=0; i&lt;3000000; i++) { if (!sm_upsert(ht, keys[i].c_str(), (void *)&amp;uval)) { cout &lt;&lt; &quot;Error: &quot; &lt;&lt; keys[i].c_str() &lt;&lt; '\n'; break; } } t2 = Clock::now(); elapsed = t2 - t1; cout &lt;&lt; &quot;Upsert removed: &quot; &lt;&lt; elapsed.count() &lt;&lt; '\n'; t1 = Clock::now(); for (int i=0; i&lt;3700000; i++) { if (!sm_lookup(ht, keys[i].c_str(), (void **)&amp;data)) { cout &lt;&lt; &quot;Error: &quot; &lt;&lt; keys[i] &lt;&lt; '\n'; break; } if (*data != 7117) { cout &lt;&lt; &quot;Error: &quot; &lt;&lt; keys[i] &lt;&lt; &quot; Data:&quot; &lt;&lt; *data &lt;&lt; '\n'; break; } } t2 = Clock::now(); elapsed = t2 - t1; cout &lt;&lt; &quot;Lookup: &quot; &lt;&lt; elapsed.count() &lt;&lt; '\n'; sm_free(ht); cout &lt;&lt; &quot;*** STL unordered_set test ***\n&quot;; unordered_set&lt;string&gt; strset; strset.reserve(3700000); t1 = Clock::now(); for (int i=0; i&lt;3700000; i++) { strset.insert(keys[i]); } t2 = Clock::now(); elapsed = t2 - t1; cout &lt;&lt; &quot;Insert STL unordered_set: &quot; &lt;&lt; elapsed.count() &lt;&lt; '\n'; t1 = Clock::now(); for (int i=0; i&lt;3700000; i++) { strset.find(keys[i]); } t2 = Clock::now(); elapsed = t2 - t1; cout &lt;&lt; &quot;Lookup existing STL unordered_set: &quot; &lt;&lt; elapsed.count() &lt;&lt; '\n'; t1 = Clock::now(); for (int i=0; i&lt;3700000; i++) { strset.find(xkeys[i]); } t2 = Clock::now(); elapsed = t2 - t1; cout &lt;&lt; &quot;Lookup not existing STL unordered_set: &quot; &lt;&lt; elapsed.count() &lt;&lt; '\n'; t1 = Clock::now(); for (int i=0; i&lt;3000000; i++) { strset.erase(keys[i]); } t2 = Clock::now(); elapsed = t2 - t1; cout &lt;&lt; &quot;Remove: &quot; &lt;&lt; elapsed.count() &lt;&lt; '\n'; } </code></pre>
[]
[ { "body": "<h1>Use <code>size_t</code> for sizes</h1>\n<p>Use <a href=\"https://en.cppreference.com/w/c/types/size_t\" rel=\"nofollow noreferrer\"><code>size_t</code></a> consistently for sizes and array and loop indices. I recommend doing that even if you only store hashes internally as <code>uint32_t</code>.</p>\n<h1>Missing <code>const</code></h1>\n<p>You are using <code>const</code> already in some places, but you should also pass <code>sm</code> as a <code>const strmap *</code> in those functions that do not modify the map, such as <code>sm_lookup()</code>, <code>sm_size()</code> and <code>find()</code>.</p>\n<h1>Typedefs can have exactly the same name as structs</h1>\n<p>Instead of using upper case for the name of a struct and lower case for the corresponding typedef, you can just give both the same (preferrably lower case) name:</p>\n<pre><code>typedef struct strmap strmap;\n</code></pre>\n<p>You can also typedef anonymous structs, which you could use for <code>struct SLOT</code>:</p>\n<pre><code>typedef struct {\n const char *key;\n const char *data;\n uint32_t hash;\n} slot;\n</code></pre>\n<h1>Avoid macros</h1>\n<p>Macros are often not necessary, and can be replaced by static constants and functions. For example:</p>\n<pre><code>static const size_t min_size = 9;\n\nstatic uint32_t fast_reduce32(uint32_t x, uint32_t r) {\n return ((uint64_t)x * r) &gt;&gt; 32;\n}\n</code></pre>\n<p>Macros have all sorts of pitfalls. You are already putting everything inside parentheses, which is good, but even then there are issues. Consider writing:</p>\n<pre><code>if (DISTANCE(root, slot++, sm-&gt;capacity) ...) {...}\n</code></pre>\n<p>The macro expansion will evaluate <code>slot++</code> multiple times, which leads to unexpected results. Better to just make it a function:</p>\n<pre><code>size_t distance(slot *from, slot *to, size_t capacity) {\n return to &gt;= from ? to - from : r - (from - to);\n}\n</code></pre>\n<h1>Consider always using a power-of-two size</h1>\n<p>If you round up the requested size to the next power of two, you can avoid using the modulo operation.</p>\n<h1>Missing assert</h1>\n<p>You are using <code>assert()</code> in the public API function to validate the arguments. That's great! You missed an <code>assert(data)</code> in <code>sm_lookup()</code> though.</p>\n<h1>Consider adding a way to iterate over the hash map</h1>\n<p>Something missing from both the POSIX and GNU hash map functions is a way to iterate over all elements stored in the map. This makes it hard to put dynamically allocated data into a hash map, as at the end you have no way to free all the items stored in it. Adding a function which iterates over the map and calls a callback function for each item would help:</p>\n<pre><code>void sm_foreach(const strmap *sm, void (*action)(const char *key, void *data));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T13:26:10.803", "Id": "531722", "Score": "0", "body": "What about return values - bool vs enum vs int ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T13:39:32.097", "Id": "531727", "Score": "0", "body": "`bool` for yes/no or success/failure, `enum` if there are multiple possibilities, `int` if you return a count of something (but prefer `size_t`). Apart from changing `uint32_t` to `size_t` for `sm_size()`, I think the return types you chose are perfectly fine." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T09:41:26.110", "Id": "269498", "ParentId": "269453", "Score": "3" } } ]
{ "AcceptedAnswerId": "269498", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T10:04:42.940", "Id": "269453", "Score": "5", "Tags": [ "c", "hash-map" ], "Title": "Open addressing linear probing hash map" }
269453
<p>I'm pretty new to learning Python. I wrote a very basic script that takes your pizza order and recites it back when you're done placing your order:</p> <pre><code>available_toppings = ['mushrooms', 'onions', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese','sausage','spinach'] requested_toppings = [] size = input(&quot;Would you like a large, medium, or small pizza? &quot;) ordering = True while ordering == True: topping = input(&quot;What topping would you like on your pizza? &quot;) if topping.lower() in available_toppings: print(&quot;Yes, we have that.&quot;) requested_toppings.append(topping) elif topping not in available_toppings: print(&quot;Sorry, we do not have &quot; + topping + &quot;.&quot;) add_more = False while add_more == False: answer = input(&quot;Would you like to add another topping? Yes or no? &quot;) if answer.lower() == &quot;y&quot; or answer.lower() == &quot;yes&quot;: add_more = True elif answer.lower() == &quot;n&quot; or answer.lower() == &quot;no&quot;: print(&quot;Ok, you ordered a {} &quot;.format(size) + &quot;pizza with:&quot;) for requested_topping in requested_toppings: print(requested_topping) add_more = True ordering = False elif answer.lower() != &quot;n&quot; or answer.lower() != &quot;no&quot; or answer.lower() != &quot;y&quot; or answer.lower() != &quot;yes&quot;: print(&quot;Sorry, I didn't catch that.&quot;) continue </code></pre> <p>I was just wondering if anyone has any tips to clean up the code a bit. I'm sure there is an easier way to accomplish what this script can do and would love to learn some tricks. I would also like to add that while loops still confuse me a bit and even though I got this to run, I really don't know if I did them right.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T04:14:07.690", "Id": "531640", "Score": "0", "body": "You don't need `elif topping not in available_toppings:`. It's fine with just `else:`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T04:16:24.670", "Id": "531641", "Score": "0", "body": "`print(\"Ok, you ordered a {} \".format(size) + \"pizza with:\")` can be `print(f\"Ok, you ordered a {size} pizza with:\")`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T04:20:02.833", "Id": "531642", "Score": "0", "body": "bro your code act weird when you do not provide topping it goes in endless loop it will keep on asking would you like another topping again and again as you give no to it as input" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T04:23:24.003", "Id": "531643", "Score": "0", "body": "and print the list of topping as user will chose from them" } ]
[ { "body": "<p>Firstly, you should add <code>else</code> instead of elif in -</p>\n<pre><code>elif topping not in available_toppings:\n print(&quot;Sorry, we do not have &quot; + topping + &quot;.&quot;)\n</code></pre>\n<p>You can use</p>\n<pre><code>else:\n print(&quot;Sorry, we do not have &quot; + topping + &quot;.&quot;)\n</code></pre>\n<p>And instead of</p>\n<pre><code>elif answer.lower() != &quot;n&quot; or answer.lower() != &quot;no&quot; or answer.lower() != &quot;y&quot; or answer.lower() != &quot;yes&quot;:\n print(&quot;Sorry, I didn't catch that.&quot;)\n continue\n</code></pre>\n<p>You should use</p>\n<pre><code>else:\n print(&quot;Sorry, I didn't catch that.&quot;)\n continue\n</code></pre>\n<p>And you should also check if the size of the pizza is correct, it can be invalid. You should also print the topping list, as it will help user pick.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T04:52:06.643", "Id": "531644", "Score": "0", "body": "You can even add a few functions if you want." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T04:16:48.990", "Id": "269456", "ParentId": "269455", "Score": "1" } }, { "body": "<pre><code>elif answer.lower() == &quot;n&quot; or answer.lower() == &quot;no&quot;:\n print(&quot;Ok, you ordered a {} &quot;.format(size) + &quot;pizza with:&quot;)\n for requested_topping in requested_toppings:\n print(requested_topping)\n add_more = True\n ordering = False\n</code></pre>\n<p>keep them out of the for loop and rest other things avi mentioned</p>\n<p>and print the list of topping</p>\n<p>can you clear your problem related to not understanding while loop</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T04:27:38.303", "Id": "269457", "ParentId": "269455", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-27T04:07:30.663", "Id": "269455", "Score": "1", "Tags": [ "python" ], "Title": "Cleaning up a basic Python script that takes and recites a pizza order" }
269455
<p>I need to check if <strong>times A</strong> cross with <strong>times B</strong> using integers and a 24hour clock. Times that are the same don't count as crossing, but meeting.</p> <p>For example: <strong>16, 20 and 14, 18</strong> (startA, endA and startB and endB) would <strong>return true</strong> as these times do cross, however, <strong>14, 16 and 16, 20</strong> meet but don't cross so they would <strong>return false</strong>. Any other combination that does not cross would return false.</p> <p>Assuming that the times don't go past midnight I can just do this:</p> <pre><code>static boolean Cross(int startPeriod1, int endPeriod1, int startPeriod2, int endPeriod2) { return startPeriod1 &lt; endPeriod2 &amp;&amp; endPeriod1 &gt; startPeriod2; } </code></pre> <p>However, to include times that do go past midnight (e.g 16, 2 and 14, 2 which would return true) I used this solution:</p> <pre><code>static boolean timesCrossLate(int startPeriod1, int endPeriod1, int startPeriod2, int endPeriod2) { List&lt;Integer&gt; rangePeriod1; List&lt;Integer&gt; rangePeriod2; if (startPeriod1 &gt; endPeriod1) { List&lt;Integer&gt; rangeStartPeriod1 = IntStream.range(startPeriod1 + 1, 25).boxed().collect(Collectors.toList()); List&lt;Integer&gt; rangeEndPeriod1 = IntStream.range(0, endPeriod1).boxed().collect(Collectors.toList()); rangePeriod1 = Stream.concat(rangeStartPeriod1.stream(), rangeEndPeriod1.stream()).collect(Collectors.toList()); } else { rangePeriod1 = IntStream.range(startPeriod1 + 1, endPeriod1).boxed().collect(Collectors.toList()); } if (startPeriod2 &gt; endPeriod2) { List&lt;Integer&gt; rangeStartPeriod2 = IntStream.range(startPeriod2 + 1, 25).boxed().collect(Collectors.toList()); List&lt;Integer&gt; rangeEndPeriod2 = IntStream.range(0, endPeriod2).boxed().collect(Collectors.toList()); rangePeriod2 = Stream.concat(rangeStartPeriod2.stream(), rangeEndPeriod2.stream()).collect(Collectors.toList()); } else { rangePeriod2 = IntStream.range(startPeriod2 + 1, endPeriod2).boxed().collect(Collectors.toList()); } if (!Collections.disjoint(rangePeriod1, rangePeriod2)) { return true; } else { return false; } } </code></pre> <p>Here I make a list of the range of times and compare the two lists to see if any elements are shared, I of course don't include the start and end numbers as that would meant that the numbers meet and not cross.</p> <p>I wanted to know if there is a better/ cleaner way of doing this (apart from making the list creation part into a separate method).</p> <p>Thanks :)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T14:25:32.950", "Id": "531651", "Score": "1", "body": "Welcome to Code Review! could you take a look at [this](https://www.online-java.com/No9zTx6u3F)? To me it seems like your second solution doesn't work correctly. In any case, writing some simple unit tests is a good idea here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T15:08:20.383", "Id": "531653", "Score": "1", "body": "Hello, the clock range is 0-23 and then restarts with 0 ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T15:25:27.733", "Id": "531657", "Score": "3", "body": "Please clarify how the start and end times are to be interpreted. I have understood it as follows: If startPeriod <= endPeriod then both numbers specify hours for today. If startPeriod > endPeriod then startPeriod is an hour today, and endPeriod is an hour tomorrow. Is that correct?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T15:36:33.803", "Id": "531660", "Score": "5", "body": "Concretely: Should `timesCrossLate(20, 6, 2, 8)` return true or false, and why?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T16:02:15.947", "Id": "531664", "Score": "0", "body": "Hi, thanks for the feedback, when I tested it using code provided they all passed so I missed many of the potential bugs. I have fixed everything. Thanks again!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T04:32:51.453", "Id": "531692", "Score": "3", "body": "Would 'overlap' be a better word than 'cross'? When you were talking about times, I immediately thought of 'cross product'." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T09:38:55.487", "Id": "531704", "Score": "0", "body": "Why not just use a DateTime library?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T11:43:16.093", "Id": "531709", "Score": "0", "body": "@AJD: Yes, that was my thought as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T16:52:35.217", "Id": "531742", "Score": "0", "body": "It occurs to me that this is a problem that would benefit from test-driven development. Expressing the requirements as tests and then getting them to pass, one-by-one, seems like it would be a particularly good approach here." } ]
[ { "body": "<p>I think the comparison logic can be simplified considerably. If the last hour of a period is numerically less than the first hour, it is to be interpreted as the corresponding hour on the next day. We can add the value 24 to the last hour in that case, so that the “simple” comparison for overlapping intervals gives the correct result:</p>\n<pre><code>static boolean timesCrossLate(int startPeriod1, int endPeriod1, int startPeriod2, int endPeriod2) {\n if (endPeriod1 &lt; startPeriod1) {\n endPeriod1 += 24;\n }\n if (endPeriod2 &lt; startPeriod2) {\n endPeriod2 += 24;\n }\n return startPeriod1 &lt; endPeriod2 &amp;&amp; endPeriod1 &gt; startPeriod2;\n}\n</code></pre>\n<p>No lists are needed for this implementation.</p>\n<p>A better <em>name</em> for the function might be <code>periodsOverlap</code> or something like that.</p>\n<p>If <code>endPeriod &lt; startPeriod</code> is to be interpreted as two time intervals on the <em>same</em> day then it is still possible to compute the result without using lists, e.g. by recursive calls of the function until the “simple” case is reached:</p>\n<pre><code>static boolean timesCrossLate(int startPeriod1, int endPeriod1, int startPeriod2, int endPeriod2) {\n if (endPeriod1 &lt; startPeriod1) {\n return timesCrossLate(startPeriod1, 23, startPeriod2, endPeriod2) \n || timesCrossLate(0, endPeriod1, startPeriod2, endPeriod2);\n } else if (endPeriod2 &lt; startPeriod2) {\n return timesCrossLate(startPeriod1, endPeriod1, startPeriod2, 23) \n || timesCrossLate(startPeriod1, endPeriod1, 0, endPeriod2);\n } else {\n return startPeriod1 &lt; endPeriod2 &amp;&amp; endPeriod1 &gt; startPeriod2;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T15:14:48.267", "Id": "531654", "Score": "1", "body": "This is a step in the right direction, but isn't complete. Consider the times **20** to **6** and **2** to **8**, which overlap from **2** to **6**. Your test of `20 < 8 && 30 > 2` which clearly fails, but `20 - 24 < 8 && 30 - 24 > 2` would pass." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T15:17:12.993", "Id": "531655", "Score": "2", "body": "@AJNeufeld: Do they really overlap? As I interpret it, “20 to 6” is from 20:00 today until 06:00 tomorrow, and “2 to 8” is from 02:00 today until 08:00 today, and those periods do not overlap. (Of course my interpretation might be wrong.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T15:29:25.323", "Id": "531658", "Score": "1", "body": "Well, if \"20 to 6\" is 20:00 yesterday until 06:00 today, that does overlap with 02:00 today until 08:00 today. The OP's solution tests if `[21, 22, 23, 24, 1, 2, 3, 4, 5]` is disjoint from `[3, 4, 5, 6, 7]`, so it suggests the OP is not concerned with yesterday/tomorrow distinctions, but rather with the time irrespective of days." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T15:32:50.020", "Id": "531659", "Score": "2", "body": "@AJNeufeld: I have left a comment at the question, asking for clarification. Depending on the response, I will fix or delete my answer, if appropriate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T15:55:13.147", "Id": "531661", "Score": "0", "body": "\"OP is not concerned with yesterday/tomorrow distinctions, but rather with the time irrespective of days.\" Yep, exactly,, thank you so much for the feedback. (to everyone)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T09:51:26.180", "Id": "531705", "Score": "0", "body": "@AJNeufeld: I guess you are right. I have added another implementation which (hopefully) treats those cases correctly. Thanks for your feedback!" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T14:36:32.753", "Id": "269459", "ParentId": "269458", "Score": "8" } }, { "body": "<ul>\n<li><p><strong>Missing input validation</strong>: the user could pass invalid periods, including negative numbers. One validation is to check that each argument is in the range 0-23.</p>\n</li>\n<li><p><strong>Simplification</strong>: this part:</p>\n<pre class=\"lang-java prettyprint-override\"><code>if (!Collections.disjoint(rangePeriod1, rangePeriod2)) {\n return true;\n}\nelse {\n return false;\n}\n</code></pre>\n<p>Can be simplified to:</p>\n<pre><code>return !Collections.disjoint(rangePeriod1, rangePeriod2);\n</code></pre>\n</li>\n<li><p><strong>Bug</strong>: for input [16,17], [14,17] the first function returns true, while the second function returns false. Adding <a href=\"https://junit.org/junit5/\" rel=\"nofollow noreferrer\">Junit</a> tests you can easily spot these issues and refactor your code safely.</p>\n</li>\n<li><p><strong>Documentation</strong>: as @Martin and @AJNeufeld have noticed in the comments, handling periods between two days can be confusing, consider documenting how to interpret periods in your context including edge cases.</p>\n</li>\n<li><p><strong>Design</strong>: as clear as the function is, it will still take a moment for the user to figure out that four integers represent two periods. A class can help to make it clearer. For example:</p>\n<pre class=\"lang-java prettyprint-override\"><code>class Period {\n private int start;\n private int end; \n\n public Period(int start, int end){... /* validation */ }\n\n public boolean overlaps(Period other){...}\n\n // Getters, toString, etc. \n} \n</code></pre>\n<p>And use it like this:</p>\n<pre><code>Period p1 = new Period(16,20);\nPeriod p2 = new Period(14,18);\nboolean overlap = p1.overlaps(p2);\n</code></pre>\n<p>The class name tells the user that it's a period and the method <code>overlaps</code> suggests that it's an operation between periods.</p>\n</li>\n<li><p><strong>Possible extension</strong>: representing a period with integers can be enough for your use case, but has its limitations. For example, in your model the longest period can be of two days. Why not three days or one month? Two periods of one month might overlap by one day.</p>\n<p>To support that, <code>java.time</code> would be a reasonable choice, especially the class <a href=\"https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html\" rel=\"nofollow noreferrer\">LocalDateTime</a>. After replacing <code>int</code> with <code>LocalDateTime</code> in the class <code>Period</code>, the method overlap could become:</p>\n<pre><code>public boolean overaps(Period other) {\n return this.start.isBefore(other.getEnd()) &amp;&amp; this.end.isAfter(other.getStart());\n}\n</code></pre>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T15:56:57.563", "Id": "531662", "Score": "1", "body": "Thanks a lot for your answer, I will definitely take these into consideration for next time. (I've done very little of java but I'm slowly but surely improving)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T06:09:08.640", "Id": "531695", "Score": "1", "body": "@Dom I am glad I could help. FYI, I added a couple of sections about design and possible extension." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T15:48:20.620", "Id": "269464", "ParentId": "269458", "Score": "6" } }, { "body": "<h1>Bugs</h1>\n<pre class=\"lang-java prettyprint-override\"><code> rangePeriod1 = IntStream.range(startPeriod1 + 1, endPeriod1).boxed().collect(Collectors.toList());\n</code></pre>\n<p>Consider the period from 2 until 4. It fully encompasses 2:00-2:59 and 3:00-3:59. However, <code>rangePeriod1</code> would be filled with just <code>{3}</code>. This is forgetting the entire starting hour.</p>\n<p>If you compared this with 1 until 3, which will similarly populate <code>rangePeriod2</code> with <code>{1}</code>, you will conclude they do not overlap, but we know they do.</p>\n<p>You should not be using <code>+ 1</code> on the starting times. If you omitted the <code>+ 1</code>, then 2 until 4 would produce <code>{2, 3}</code>, and 1 until 3 would produce <code>{1, 2}</code>, which have the common hour <code>{2}</code>.</p>\n<h1>Inconsistencies</h1>\n<pre class=\"lang-java prettyprint-override\"><code> List&lt;Integer&gt; rangeStartPeriod1 = IntStream.range(startPeriod1 + 1, 25).boxed().collect(Collectors.toList());\n List&lt;Integer&gt; rangeEndPeriod1 = IntStream.range(0, endPeriod1).boxed().collect(Collectors.toList());\n rangePeriod1 = Stream.concat(rangeStartPeriod1.stream(), rangeEndPeriod1.stream()).collect(Collectors.toList());\n</code></pre>\n<p>If you consider the times 16 until 2, you produce <code>rangeStartPeriod1</code> as <code>{17, 18, 19, 20, 21, 22, 23, 24}</code> and <code>rangeEndPeriod1</code> as <code>{0, 1}</code>. You add these lists together to form <code>rangePeriod1</code>.</p>\n<p>Why does the list contain both <code>0</code> and <code>24</code>? The time period 24:00-24:59 should be considered to be 00:00-00:59; these should not be distinct time periods.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T15:55:35.490", "Id": "269466", "ParentId": "269458", "Score": "4" } }, { "body": "<h1>Simplification</h1>\n<p>If what you want is a shorter code, the function can be simplified to this;</p>\n<pre><code>static boolean overlap(int s1, int e1, int s2, int e2) {\n List&lt;Integer&gt; f = IntStream.range(s1, s1 &gt; e1 ? e1 + 24 : e1).map(i -&gt; i % 24).boxed().collect(Collectors.toList());\n List&lt;Integer&gt; s = IntStream.range(s2, s2 &gt; e2 ? e2 + 24 : e2).map(i -&gt; i % 24).boxed().collect(Collectors.toList());\n return f.stream().filter(s::contains).collect(Collectors.toSet()).size() &gt; 0;\n}\n</code></pre>\n<p>I'll add Python version, because I'm not familiar with Java and this is what I tried to write.</p>\n<pre><code>def overlap(s1, e1, s2, e2):\n return len({i % 24 for i in range(s1, e1 + 24 * (s1 &gt; e1))}.intersection(\n {i % 24 for i in range(s2, e2 + 24 * (s2 &gt; e2))})) &gt; 0\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T06:05:34.067", "Id": "269490", "ParentId": "269458", "Score": "0" } } ]
{ "AcceptedAnswerId": "269459", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T12:10:57.547", "Id": "269458", "Score": "5", "Tags": [ "java" ], "Title": "Check if time intervals overlap using integers" }
269458
<p>I tried to write a simple entity component system for my game engine. Each scene will have an EntityManager. It will create entities and add or remove components from them. An entity will be destroyed if its <code>isAlive</code> flag is set to false.</p> <h2>Example usage</h2> <pre class="lang-cpp prettyprint-override"><code>class Position : public Component { Position(float x, float y, float z) : x(x) , y(y) , z(z) {} float x, y, z; } EntityManager manager; Entity&amp; entity = manager.addEntity(); manager.entityAddComponent&lt;Position&gt;(entity, 1.0f, 2.0f, 3.0f); auto&amp; positions = manager.getComponentPool&lt;Position&gt;(); for (Position&amp; pos : positions) { // update } manager.removeDeadEntities(); </code></pre> <hr /> <p>Here is the code.</p> <h2>component id generator</h2> <pre class="lang-cpp prettyprint-override"><code>static size_t registeredComponentCount = 0; template &lt;typename T&gt; size_t getComponentId() { static const size_t id = registeredComponentCount++; return id; } </code></pre> <h2><code>Entity</code></h2> <pre class="lang-cpp prettyprint-override"><code>class Entity { friend EntityManager; template &lt;typename T&gt; friend class ComponentPool; public: static constexpr size_t MAX_COMPONENTS = 32; private: Entity(size_t id) : m_components({ nullptr }) , m_id(id) , isAlive(true) {} Entity(const Entity&amp;) = delete; Entity&amp; operator= (const Entity&amp;) = delete; public: bool isAlive; private: std::array&lt;Component*, MAX_COMPONENTS&gt; m_components; size_t m_id; }; </code></pre> <h2><code>Component</code></h2> <pre class="lang-cpp prettyprint-override"><code>struct Component { friend EntityManager; template &lt;typename T&gt; friend class ComponentPool; public: template&lt;typename T&gt; T&amp; getComponent() { return reinterpret_cast&lt;T&gt;(m_entity-&gt;m_components[getComponentId&lt;T&gt;]); } Entity&amp; getEntity() { return *m_entity; } Entity&amp; getEntity(); private: Entity* m_entity; }; </code></pre> <h2><code>EntityManager</code> class</h2> <pre class="lang-cpp prettyprint-override"><code>class EntityManager { public: static constexpr size_t MAX_ENTITES = 1024; public: EntityManager(); ~EntityManager(); EntityManager(const EntityManager&amp;) = delete; EntityManager&amp; operator= (const EntityManager&amp;) = delete; Entity&amp; addEntity(); void removeDeadEntities(); template&lt;typename T, typename ...Args&gt; void entityAddComponent(Entity&amp; entity, Args&amp;&amp;... args) { T* component = getComponentPool&lt;T&gt;().addComponent(std::forward&lt;Args&gt;(args)...); component-&gt;m_entity = &amp;entity; entity.m_components[getComponentId&lt;T&gt;()] = reinterpret_cast&lt;Component*&gt;(component); } template&lt;typename T&gt; void entityRemoveComponent(Entity&amp; entity) { getComponentPool&lt;T&gt;().removeComponent(entity.m_components[getComponentId&lt;T&gt;()]); } template&lt;typename T&gt; ComponentPool&lt;T&gt;&amp; getComponentPool() { size_t id = getComponentId&lt;T&gt;(); if (m_initializedComponentPools.test(id) == false) { m_componentPools[id] = reinterpret_cast&lt;BaseComponentPool*&gt;(new ComponentPool&lt;T&gt;()); m_initializedComponentPools.set(id, true); } return *reinterpret_cast&lt;ComponentPool&lt;T&gt;*&gt;(m_componentPools[id]); } private: UninitializedArray&lt;Entity, MAX_ENTITES&gt; m_entites; size_t m_entityCount; size_t m_createdEntityCount; BaseComponentPool* m_componentPools[Entity::MAX_COMPONENTS]; std::bitset&lt;Entity::MAX_COMPONENTS&gt; m_initializedComponentPools; }; </code></pre> <h2><code>ComponentPool</code> class</h2> <pre><code>class BaseComponentPool { public: virtual ~BaseComponentPool() {}; virtual void removeComponent(Component* component) = 0; }; template&lt;typename T&gt; class ComponentPool : BaseComponentPool { public: ComponentPool() : m_size(0) {} ~ComponentPool() override { for (size_t i = 0; i &lt; m_size; i++) { m_data[i].~T(); } } ComponentPool(const ComponentPool&amp;) = delete; ComponentPool&amp; operator= (const ComponentPool&amp;) = delete; template&lt;typename ...Args&gt; T* addComponent(Args &amp;&amp; ...args) { T* component = &amp;m_data[m_size]; new (&amp;m_data[m_size]) T(std::forward&lt;Args&gt;(args)...); m_size++; return component; } void removeComponent(T* component) { component-&gt;~T(); if (component != &amp;m_data[m_size - 1]) { new (component) T(std::move(m_data[m_size - 1])); component-&gt;m_entity-&gt;m_components[getComponentId&lt;T&gt;()] = component; } m_size--; } void removeComponent(Component* component) override { removeComponent(reinterpret_cast&lt;T*&gt;(component)); } T* begin() { return m_data.data(); } T* end() { return m_data.data() + m_size; } const T* cbegin() const { return m_data(); } const T* cend() const { return m_data() + m_size; } private: UninitializedArray&lt;T, EntityManager::MAX_ENTITES&gt; m_data; size_t m_size; }; </code></pre> <h2><code>System</code> class</h2> <pre class="lang-cpp prettyprint-override"><code>class System { public: virtual ~System() = 0; virtual void update(Scene&amp; scene) = 0; }; </code></pre> <h2>Helper class <code>UninitializedArray</code></h2> <pre class="lang-cpp prettyprint-override"><code>template &lt;typename T, size_t size&gt; class UninitializedArray { public: T&amp; operator[](size_t index) { return reinterpret_cast&lt;T*&gt;(m_data)[index]; } T* data() { return reinterpret_cast&lt;T*&gt;(m_data); } private: alignas(alignof(T)) unsigned char m_data[sizeof(T) * size]; }; </code></pre> <hr /> <p>Is there a better way to implement removing components without using virtual function calls?</p> <p>Does the <code>m_initializedComponentPools</code> bitset in <code>EntityManager</code> make sense or would it be better to just set the uninitialized pools to <code>nullptr</code>?</p> <p>Would it be better to register what types of components are going to be used so the component pools are initialized before the game loop starts?</p> <p>Any tips on how to improve the code would be appreciated.</p>
[]
[ { "body": "<h1>Answers to your questions</h1>\n<blockquote>\n<p>Is there a better way to implement removing components without using virtual function calls?</p>\n</blockquote>\n<p>You have to have some way to call the right <code>ComponentPool&lt;T&gt;::removeComponent()</code> corresponding to the component type. With virtual functions, this is handled for you by the language. If you want to do it without a virtual function call, then you'd need some way to store the component type in a <code>BaseComponentPool</code> and then dispatch the right version of <code>removeComponent()</code> based on it. It's going to be more work for little to no gain.</p>\n<p>Also, there is actually no virtual function call being done in your code: you already explicitly pass the desired type to <code>EntityManager::entityRemoveComponent()</code>, and then it will call <code>getComponentPool&lt;T&gt;</code>, which will return a <code>ComponentPool&lt;T&gt; &amp;</code>, not a <code>BaseComponentPool &amp;</code>, so it can directly call the right <code>removeComponent()</code>. You can remove <code>removeComponent()</code> from <code>BaseComponentPool</code> and your code should still compile and run fine. You should keep the virtual destructor though.</p>\n<blockquote>\n<p>Does the <code>m_initializedComponentPools</code> bitset in <code>EntityManager</code> make sense or would it be better to just set the uninitialized pools to <code>nullptr</code>?</p>\n</blockquote>\n<p>I would just set them to <code>nullptr</code>, or better yet make it an array of <a href=\"https://en.cppreference.com/w/cpp/memory/unique_ptr\" rel=\"nofollow noreferrer\"><code>std::unique_ptr</code></a>s:</p>\n<pre><code>std::array&lt;std::unique_ptr&lt;BaseComponentPool&gt;, Entity::MAX_COMPONENTS&gt; m_componentPools;\n</code></pre>\n<blockquote>\n<p>Would it be better to register what types of components are going to be used so the component pools are initialized before the game loop starts?</p>\n</blockquote>\n<p>If you can do that, yes. Not only allows it to have the pools be initialized beforehand, it also ensures you know exactly the right size of <code>EntityManager::m_componentPools</code>. You could even consider making <code>m_componentPools</code> a <a href=\"https://en.cppreference.com/w/cpp/utility/tuple\" rel=\"nofollow noreferrer\"><code>std::tuple</code></a> of component pool types then, so you don't need a virtual base class anymore:</p>\n<pre><code>template&lt;typename... Ts&gt;\nclass EntityManager\n{\n ...\n template&lt;typename T&gt;\n ComponentPool&lt;T&gt;&amp; getcomponentPool()\n {\n return std::get&lt;ComponentPool&lt;T&gt;&gt;(m_componentPools);\n }\n ...\n std::tuple&lt;ComponentPool&lt;Ts&gt;...&gt; m_componentPools;\n}\n</code></pre>\n<h1>Simplify <code>entityAddComponent()</code></h1>\n<p>Instead of making <code>entityAddComponent()</code> be a variadic template that takes all the arguments necessary to construct a new component, consider having it take a single parameter for the component, like so:</p>\n<pre><code>template&lt;typename T&gt;\nvoid entityAddComponent(Entity&amp; entity, T&amp;&amp; component)\n{\n T* component = getComponentPool&lt;T&gt;().addComponent(std::forward&lt;T&gt;(component));\n ...\n}\n</code></pre>\n<p>This way, <code>addComponent</code> can copy or move-construct a new component. The main benefit it that this now allows the compiler to deduce <code>T</code> automatically, so you can write:</p>\n<pre><code>manager.entityAddComponent(entity, Position{1.0f, 2.0f, 3.0f});\n</code></pre>\n<p>This becomes especially helpful if you already have the position in a variable, in which case you can do:</p>\n<pre><code>Position position{1.0f, 2.0f, 3.0f};\nmanager.entityAddComponent(entity, position);\n</code></pre>\n<p>Instead of:</p>\n<pre><code>manager.entityAddComponent&lt;Position&gt;(entity, position.x, position.y, position.z);\n</code></pre>\n<p>Of course, this won't work if the component type doesn't have copy or move constructors.</p>\n<h1>Make IDs <code>const</code></h1>\n<p>The ID of an entity is set a construction time and should never change afterwards, so make it <code>const</code>.</p>\n<h1>Consider storing entities and components in <code>std::deque</code>s</h1>\n<p>The <code>UninitializedArray</code> is indeed a good way to avoid default-constructing a large number of components, but you still need to specify the maximum number of elements you want it to hold up-front. There is a standard container that you can use instead: <a href=\"https://en.cppreference.com/w/cpp/container/deque\" rel=\"nofollow noreferrer\"><code>std::deque</code></a>. It provides fast index-based access, pointers to elements are stable, and it grows as required.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T21:58:46.110", "Id": "269477", "ParentId": "269461", "Score": "2" } } ]
{ "AcceptedAnswerId": "269477", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T15:02:37.980", "Id": "269461", "Score": "2", "Tags": [ "c++", "game", "c++17", "entity-component-system" ], "Title": "Implementation of an entity component system in c++" }
269461
<p>I'm implementing something of a thread janitor in modern C++. What I've got works, and while it's not organized in the way I'd like yet, I'd like some feedback on the fundamentals. Thank you in advance for any and all pointers. =)</p> <p>All of the threads (including <code>main()</code> in order to signal program end) share data via this:</p> <pre><code>#ifndef SHAREDDATA_HPP #define SHAREDDATA_HPP #include &lt;condition_variable&gt; #include &lt;thread&gt; class SharedData { public: std::mutex keypress_mutex; std::condition_variable keypress_cv; bool keypress_flag; std::mutex thread_count_mutex; std::condition_variable thread_count_cv; unsigned int thread_count; std::mutex thread_kill_mutex; std::condition_variable thread_kill_cv; bool thread_kill_flag; SharedData(): keypress_flag{false}, thread_count{0}, thread_kill_flag{false} { } ~SharedData() = default; }; #endif // SHAREDDATA_HPP </code></pre> <p>Then we've got a little RAII guy to help keep track of thread count:</p> <pre><code>#ifndef THREADCOUNTER_HPP #define THREADCOUNTER_HPP #include &lt;thread&gt; class SharedData; class ThreadCounter { public: explicit ThreadCounter(SharedData *share); ~ThreadCounter(); private: SharedData *_share; }; #endif // THREADCOUNTER_HPP //-------------------------- #include &quot;ThreadCounter.hpp&quot; #include &quot;SharedData.hpp&quot; ThreadCounter::ThreadCounter(SharedData *share) : _share{share} { std::lock_guard&lt;std::mutex&gt; _lock(_share-&gt;thread_count_mutex); share-&gt;thread_count++; } ThreadCounter::~ThreadCounter() { std::lock_guard&lt;std::mutex&gt; _lock(_share-&gt;thread_count_mutex); _share-&gt;thread_count--; if(_share-&gt;thread_count == 0) { _share-&gt;thread_count_cv.notify_one(); } } </code></pre> <p>Next, the <code>ManagedThread</code> class itself:</p> <pre><code>#ifndef MANAGEDTHREAD_HPP #define MANAGEDTHREAD_HPP #include &lt;thread&gt; class SharedData; class ManagedThread { public: void launch(); explicit ManagedThread(SharedData *share); ~ManagedThread(); ManagedThread() = delete; void operator()(); private: SharedData *_share; std::thread _thread; }; #endif // MANAGEDTHREAD_HPP //-------------------------- #include &quot;ManagedThread.hpp&quot; #include &quot;SharedData.hpp&quot; #include &quot;ThreadCounter.hpp&quot; #include &lt;chrono&gt; #include &lt;iostream&gt; #include &lt;cassert&gt; using namespace std::chrono_literals; void ManagedThread::launch() { if(!_thread.joinable()) { _thread = std::thread(std::ref(*this)); } else { assert((false) &amp;&amp; &quot;Managed Thread not launchable!&quot;); } } ManagedThread::ManagedThread(SharedData *share) : _share{share}, _thread{std::thread()} { } ManagedThread::~ManagedThread() { if(_thread.joinable()) { _thread.join(); } } void ManagedThread::operator()() { ThreadCounter tc(_share); while(true) { std::this_thread::sleep_for(250ms); std::cout &lt;&lt; &quot;Whee!&quot; &lt;&lt; std::endl; std::unique_lock&lt;std::mutex&gt; kill_lock(_share-&gt;thread_kill_mutex); if(_share-&gt;thread_kill_cv.wait_for(kill_lock, 100ms, [&amp;](){ return _share-&gt;thread_kill_flag; })) { break; } } } </code></pre> <p>And <code>ThreadManager</code> who does the cleanup coordination:</p> <pre><code>#ifndef THREADMANAGER_HPP #define THREADMANAGER_HPP class SharedData; class ThreadManager { public: explicit ThreadManager(SharedData *share) : _share{share} { }; ~ThreadManager() = default; void operator()(); private: SharedData *_share; }; #endif // THREADMANAGER_HPP //-------------------------- #include &quot;ThreadManager.hpp&quot; #include &quot;SharedData.hpp&quot; #include &lt;chrono&gt; using namespace std::chrono_literals; void ThreadManager::operator()() { std::this_thread::sleep_for(25ms); std::unique_lock&lt;std::mutex&gt; keypress_lock(_share-&gt;keypress_mutex); _share-&gt;keypress_cv.wait(keypress_lock, [&amp;](){ return _share-&gt;keypress_flag; }); keypress_lock.unlock(); { std::lock_guard&lt;std::mutex&gt; kill_lock(_share-&gt;thread_kill_mutex); _share-&gt;thread_kill_flag = true; } _share-&gt;thread_kill_cv.notify_all(); std::unique_lock&lt;std::mutex&gt; count_lock(_share-&gt;thread_count_mutex); _share-&gt;thread_count_cv.wait(count_lock, [&amp;](){ return _share-&gt;thread_count == 0; }); } </code></pre> <p>And, finally, a <code>main.cpp</code> to tie it all together.</p> <pre><code>#include &quot;SharedData.hpp&quot; #include &quot;ThreadManager.hpp&quot; #include &quot;ManagedThread.hpp&quot; #include &lt;iostream&gt; #include &lt;future&gt; int main() { SharedData share; ThreadManager tm(&amp;share); ManagedThread t0(&amp;share); t0.launch(); std::future&lt;void&gt; cf = std::async(std::launch::async, std::move(tm)); int input; std::cin &gt;&gt; input; { std::lock_guard&lt;std::mutex&gt; lock(share.keypress_mutex); share.keypress_flag = true; } share.keypress_cv.notify_one(); cf.get(); return 0; } </code></pre> <p>What I know I don't really like is that <code>ThreadManager</code> doesn't own <code>SharedData</code>. I'd also like <code>ThreadManager</code> to generically manage any <code>ManagedThread</code> and perhaps overload <code>operator()</code> in an inherited thread of some sort so callable can do anything but still be &quot;managed&quot;.</p> <p>At this point, those are just musings, though - what I'd really like to know is how well or poorly the system has been implemented thus far. =)</p> <p>Again, thanks for your feedback; I look forward to improving this setup and utilizing it in future.</p>
[]
[ { "body": "<h1>Pass arguments by reference</h1>\n<p>You are passing <code>SharedData</code> by a pointer. It would have been much cleaner to pass it by reference:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>class ThreadCounter {\npublic:\n explicit ThreadCounter(SharedData&amp; share);\n ~ThreadCounter();\nprivate:\n SharedData&amp; _share;\n};\n</code></pre>\n<h1>Use atomic variables instead of <code>lock</code>.</h1>\n<p>Locking is costly and overly complicated when you could have simply used atomic variables:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>struct SharedData\n{\n std::atomic&lt;bool&gt; keypress_flag = false;\n}\n\nint main() {\n SharedData share;\n // start threads\n int input;\n std::cin &gt;&gt; input;\n share.keypress_flag = true;\n // join threads\n}\n</code></pre>\n<h1>Don't use std::endl</h1>\n<p><code>std::endl</code> Flushes the output. You don't have to, simply use <code>\\n</code>:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>std::cout &lt;&lt; &quot;Whee!\\n&quot;;\n</code></pre>\n<h1>Final thoughts</h1>\n<p>I'm not really sure what you are trying to accomplish. It seems to me that you could have replaced all your code with something as simple as the following:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;atomic&gt;\n#include &lt;iostream&gt;\n#include &lt;thread&gt;\n\nstd::atomic_bool running = true;\n\nvoid func()\n{\n using namespace std::chrono_literals;\n while (running)\n {\n std::this_thread::sleep_for(250ms);\n std::cout &lt;&lt; &quot;Whee!\\n&quot;;\n }\n}\n\nint main()\n{\n std::thread thread(func);\n int input;\n std::cin &gt;&gt; input;\n running = false;\n thread.join();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T18:23:39.527", "Id": "269469", "ParentId": "269462", "Score": "2" } }, { "body": "<h1>Thread management in C++20</h1>\n<p>In C++20 (which you mention in the title of the question), there is <a href=\"https://en.cppreference.com/w/cpp/thread/jthread\" rel=\"nofollow noreferrer\"><code>std::jthread</code></a> which basically does most of what you are doing in your classes: it handles joining a thread in its destructor, and there is a way to request a thread to stop what it is doing, which is also automatically called in the destructor. Your example could be rewritten like so in C++20:</p>\n<pre><code>#include &lt;chrono&gt;\n#include &lt;iostream&gt;\n#include &lt;thread&gt;\n\nusing namespace std::chrono_literals;\n\nint main() {\n std::jthread whee([](std::stop_token stoken){\n while (!stoken.stop_requested()) {\n std::this_thread::sleep_for(250ms);\n std::cout &lt;&lt; &quot;Whee!\\n&quot;;\n }\n });\n\n int input;\n std::cin &gt;&gt; input;\n\n // Unnecessary since the thread object is destroyed anyway:\n whee.request_stop();\n}\n</code></pre>\n<p>If you have multiple <code>std::jthreads</code> and you want them all to stop at the same time, just let all the thread objects go out of scope simultaneously, or put them in a container that can be <a href=\"https://en.cppreference.com/w/cpp/container/vector/clear\" rel=\"nofollow noreferrer\"><code>clear()</code></a>ed. For example:</p>\n<pre><code>int main() {\n std::vector&lt;std::jthread&gt; threads;\n \n for (auto i: {1, 2, 3}) {\n threads.emplace_back([i](std::stop_token stoken){\n while (!stoken.stop_requested()) {\n std::this_thread::sleep_for(250ms);\n std::cout &lt;&lt; &quot;Whee &quot; &lt;&lt; i &lt;&lt; &quot;!\\n&quot;;\n }\n });\n }\n\n int input;\n std::cin &gt;&gt; input;\n\n std::cout &lt;&lt; &quot;Stopping all threads...\\n&quot;;\n threads.clear();\n std::cout &lt;&lt; &quot;Done.\\n&quot;;\n}\n</code></pre>\n<p>Basically, <code>std::vector&lt;std::jthread&gt;</code> replaces your whole thread manager.</p>\n<h1>Sharing state amonst threads</h1>\n<p>Your idea to have some shared state that indicates whether threads should stop has merit. You only need to update one variable to send a signal to all of them, whereas with the <code>std::jthread</code> solution I mentioned, each <code>std::jthread</code> object has its own stop token. As upkajdt mentioned in his answer though, you can simplify things a lot by just using a <code>std::atomic&lt;bool&gt;</code> as a flag. In his answer, he declared this as a global variable. In case you don't want or can't use a global variable, and you want some state shared amongst multiple threads, then indeed you want to manage this state in a thread-safe way. Most importantly, it shouldn't be destroyed before every thread using it is done with it. This is a large part of what your code tries to do. However, there is already functionality in the standard library that allows you to do this: <a href=\"https://en.cppreference.com/w/cpp/memory/shared_ptr\" rel=\"nofollow noreferrer\"><code>std::shared_ptr</code></a>. Your code could be rewritten like so:</p>\n<pre><code>#include &lt;atomic&gt;\n#include &lt;chrono&gt;\n#include &lt;iostream&gt;\n#include &lt;memory&gt;\n#include &lt;thread&gt;\n\nusing namespace std::chrono_literals;\n\nint main() {\n auto kill_flag = std::make_shared&lt;std::atomic&lt;bool&gt;&gt;(false);\n\n std::thread whee([kill_flag](){\n while (!*kill_flag) {\n std::this_thread::sleep_for(250ms);\n std::cout &lt;&lt; &quot;Whee!\\n&quot;;\n }\n });\n\n int input;\n std::cin &gt;&gt; input;\n\n *kill_flag = true;\n whee.join();\n}\n</code></pre>\n<p>Here the <code>kill_flag</code> is passed <em>by value</em> to the thread. This uses the copy-constructor of <code>std::shared_ptr</code>, which will increase the reference count of the atomic bool, and once the thread stops it will call the destructor of its copy of <code>kill_flag</code>, which will in turn decrease the reference count. So this replaces your <code>ThreadCounter</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T12:15:57.393", "Id": "531714", "Score": "0", "body": "Good and detailed review as always! I wasn’t even aware of the existence of `std::jthread`, actually two weeks back I did not know about `std::string_view`. Do you have any recommendations on how to stay up to date with all the developments while still having time to do your day job?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T13:34:13.133", "Id": "531725", "Score": "1", "body": "@upkajdt [cppreference.com](https://en.cppreference.com/w/) is a great resource. At the top of that page it lists the versions of the C++ standard, you can click on them and get a page that describes what is new in that standard. There's also one for C++23, which is a work in progress of course, but check it now and then to know what's going to come. Also great is to follow talks from [C++ conferences](https://isocpp.org/wiki/faq/conferences-worldwide). There are also various [YouTube channels](https://www.youtube.com/user/lefticus1), [blogs](https://quuxplusone.github.io/blog/) and so on." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T20:52:31.047", "Id": "531751", "Score": "1", "body": "A shared pointer seems unnecessary just for the purpose of having a thread-safe “done” flag. All you need to do is put the flag in the same place as whatever is managing the threads, and pass it by reference; so long as it’s constructed first, it will outlast the threads. Or, for a more complicated setup, instead of a shared pointer to a plain atomic `bool`, use a `std::stop_source` and get `std::stop_token`s from that to pass to each thread function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T01:35:46.053", "Id": "531759", "Score": "0", "body": "@indi Yes, in the above example it is unnecessary, but if threads are created and signalled from various functions with less well-determined lifetimes it migh be necessary. Also, `std::stop_source` is C++20, if you cannot use that yet then I think the atomic `bool` is a reasonable equivalent." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T20:15:58.257", "Id": "269473", "ParentId": "269462", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T15:34:03.717", "Id": "269462", "Score": "3", "Tags": [ "c++", "c++11", "multithreading" ], "Title": "C++11(14/17/20) Thread Management" }
269462
<p>First let's introduce the problem:</p> <p>I have a list like <code>[{10,18}, {19,25}, {26,50}]</code> and i have an input (n), when (n) inside one of objects in a list i will get this object and when (n) not higher then all objects in a list I want to get the higher object.</p> <p>Take this list for example <code>List&lt;MyObject&gt; list = [{10,18}, {19,25}, {26,50}]</code>;</p> <pre><code>when (n) = 5 ==&gt; I will get {} when (n) = 10 ==&gt; I will get {10,18} when (n) = 18 ==&gt; I will get {10,18} when (n) = 23 ==&gt; I will get {19,25} when (n) = 45 ==&gt; I will get {26,50} when (n) = 52 ==&gt; I will get {26,50} </code></pre> <p>My code works fine, and I want a review.</p> <p>I have a class <code>Demo</code>:</p> <pre><code>public class Demo { int age1; int age2; //getters and setters and constr } </code></pre> <p>And a list of demos like</p> <pre><code>List&lt;Demo&gt; demos = new ArrayList&lt;&gt;(); demos.add(new Demo(11, 12)); demos.add(new Demo(13, 15)); </code></pre> <p>I want to get demo object by value inside interval.</p> <p>For example, <code>int result = 13;</code> I get first object.</p> <p>When I have value higher then all the objects in the list, then I should get the object containing the highest value.</p> <p>I have the logic in an interface with implementation.</p> <pre><code>public interface MyDemo { Function&lt;Integer, Predicate&lt;Demo&gt;&gt; checkBetweenInterval = value -&gt; o -&gt; value &gt;= o.getAge1() &amp;&amp; value &lt;= o.getAge2(); List&lt;Demo&gt; toListTraitement(List&lt;Demo&gt; demos, int number); default Optional&lt;Demo&gt; getDemo(List&lt;Demo&gt; demos, int number){ return toListTraitement(demos, number).stream().filter(checkBetweenInterval.apply(number)).findFirst(); } default Optional&lt;Demo&gt; getIfInLastObject(List&lt;Demo&gt; demos, int number){ Demo last = demos.get(demos.size() - 1); if(number &gt;= last.getAge2()) { return Optional.of(last); } else { return null; } } default Optional&lt;Demo&gt; getFinalResult(List&lt;Demo&gt; demos, int number) { Optional&lt;Demo&gt; demo = getDemo(demos, number); if(demo.isPresent()) { return demo; } else { return getIfInLastObject(demos, number); } } } </code></pre> <p>Is this the right approach? Can I do better?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T17:50:16.567", "Id": "531666", "Score": "0", "body": "Welcome to Code Review! I think a few more examples would help understanding what you need to do. For example given the list `[{11, 12}, {13, 15}]` what should be the answer for inputs 5, 11, 12, 13, 15, 55? (Some of them I already understood, I'm saying if you add these examples into your question, it will be helpful.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T18:21:48.317", "Id": "531669", "Score": "0", "body": "Thank you @janos I edit my answer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T18:24:54.173", "Id": "531671", "Score": "0", "body": "I was most interested in what is returned when `n` is on interval boundaries, and when `n` is lower than all intervals. So in your example of `[{10,18}, {19,25}, {26,50}]`, what will be the answer for 5, 10, 18 ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T18:29:03.717", "Id": "531673", "Score": "0", "body": "Ok, so when n = 5 I will get nothing and when n = 10 I will get {10,18} and when n = 18 I will get {10,18}, thank you a lot @janos" } ]
[ { "body": "<p>Firstly, if you're going to implement all the methods in an interface just make a class. A better way to structure this would be to have an <code>IDemo</code> with just the interface method definitions, then implement it with a <code>MyDemo</code> class. If you have multiple <code>Demo</code> instances that share the logic presently implemented, discard the interface and just use a <code>Demo</code> class.</p>\n<p>Secondly, you're not using <code>Optional</code> to its fullest potential. You should <strong>never</strong> be returning <code>null</code> if <code>Optional</code> is an expected return type. <code>Optional.empty()</code> is the functional replacement. Honestly, for this application (which I'm assuming is in some kind of backend context) just work with truthy operations on <code>null</code>. Also, you can get those if-else blocks on one line.</p>\n<p>Lastly, the method naming needs some work. I'm guessing English is not your first language (and congrats on speaking it better than most people who use it natively), but what is <code>toListTraitement()</code>? There are no comments defining the broader context, what a <code>Demo</code> even is, etc.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T17:26:41.000", "Id": "531875", "Score": "0", "body": "Thank @T145 for your answer, for structure i prefer to use default method feature for JAVA 8 that why I don't want to implement unnecessary methods. Sorry for the naming of methods and class that because I need just the idea to avoid added unnecessary code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T22:45:57.950", "Id": "269533", "ParentId": "269463", "Score": "1" } } ]
{ "AcceptedAnswerId": "269533", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T15:38:46.673", "Id": "269463", "Score": "1", "Tags": [ "java", "search" ], "Title": "Get Interval by specific value from List using JAVA 8" }
269463
<p>Given a list of strings <code>paragraphs</code> and <code>words</code>. Check each <code>paragraphs</code>'s item for containing <code>words</code>'s item as a substring. In the case of positive, replace all characters of this substring on 'x'.</p> <p>I do it in the following way:</p> <pre><code>// In production, words.Length ~500 var words = new List&lt;string&gt; { &quot;technology&quot;, &quot;word&quot;, &quot;IBM&quot;, // ... }; // In production, paragraphs.Length ~10,000 and paragraphs[i].Length ~200 var paragraphs = new List&lt;string&gt; { &quot;Microsoft Corporation is an American multinational technology corporation which produces computer software...&quot;, &quot;Microsoft (the word being a portmanteau of \&quot;microcomputer software\&quot;) was founded by Bill Gates and&quot;, &quot;As of 2015, Microsoft is market-dominant in the IBM PC compatible operating system market and the office software&quot;, // ... }; for (int i = 0; i &lt; paragraphs.Count; i++) { foreach (string word in words) { var template = new string('x', word.Length); paragraphs[i] = paragraphs[i].Replace(word, template); } } foreach (string para in paragraphs) { Console.WriteLine(para); } </code></pre> <p><a href="https://i.stack.imgur.com/dwlS3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dwlS3.png" alt="enter image description here" /></a></p> <hr /> <p>I think that using algorithms is very bad since there is much <code>String.Replace()</code> calling. As you know, the <code>string</code> type is immutable and each <code>String.Replace()</code> allocates a new space in memory.</p> <p>Please, review my implementation and help to improve.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T20:11:58.810", "Id": "531679", "Score": "0", "body": "Please [edit] your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T07:18:10.083", "Id": "531698", "Score": "0", "body": "This is generally called [redaction](https://dictionary.cambridge.org/dictionary/english/redaction) just FYI." } ]
[ { "body": "<p>Use <strong>StringBuilder</strong>.</p>\n<p>When adding <code>string</code>s into <code>StringBuilder</code> it allows you to work with their characters without adding extra allocations, and whenever you're done, you can call <code>ToString()</code> to get the immutable string representation of it.</p>\n<p><code>StringBuilder</code> is often used when there is some repetitive executions on string/s or when the string that is going to be manipulated has a large size.</p>\n<p>So, your work can be changed to this :</p>\n<pre><code>var builder = new StringBuilder();\n\nfor (int i = 0; i &lt; paragraphs.Count; i++)\n{\n builder.Append(paragraphs[i]);\n \n for(int x = 0; x &lt; words.Count; x++)\n {\n builder.Replace(words[x], new string('x', word[x].Length)); \n }\n\n paragraphs[i] = builder.ToString();\n \n builder.Clear();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T20:10:26.210", "Id": "269472", "ParentId": "269470", "Score": "5" } } ]
{ "AcceptedAnswerId": "269472", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T18:49:47.063", "Id": "269470", "Score": "1", "Tags": [ "c#", "performance", "algorithm", ".net" ], "Title": "Find and replace all substrings in a string" }
269470
<p>We have a list of string arrays i.e. List&lt;String[]&gt; (which we got from a csv) which follows the hierarchy:</p> <pre><code>0000 3000 5000 5000 5000 . . . 3900 3000 5000 5000 5000 . . . 3900 . . . 9999 </code></pre> <p>As you can see, it will always start with 0000 and end with 9999 (think of them as header and footer respectively)</p> <p>Furthermore, it has equal numbers of 3000 and 3900, with zero to many 5000 records in between.</p> <p>Input Example:</p> <pre><code>{ [&quot;0000&quot;,&quot;entry A&quot;, entry B&quot;, &quot;entry C&quot;....], [&quot;3000&quot;,&quot;entry1&quot;, entry2&quot;, &quot;entry3&quot;....], --- [&quot;5000&quot;, &quot;entry4&quot;, entry 5&quot;, &quot;entry 6&quot;...], | [&quot;5000&quot;, &quot;entry 7&quot;, entry 8&quot;, &quot;entry 9&quot;...], | [&quot;5000&quot;, &quot;entry 10&quot;, entry 11&quot;, &quot;entry 12&quot;...], | -&gt; This is one group [&quot;5000&quot;, &quot;entry 13&quot;, entry 14&quot;, &quot;entry 15&quot;.....], | [&quot;3900&quot;, &quot;entry 16&quot;, entry 17&quot;, &quot;entry 18&quot;....], --- [&quot;3000&quot;,&quot;entry19&quot;, entry20&quot;, &quot;entry 21&quot;....], [&quot;5000&quot;, &quot;entry 22&quot;, entry 23&quot;, &quot;entry 24&quot;...], [&quot;3900&quot;, &quot;entry 25&quot;, entry 26&quot;, &quot;entry 27&quot;...], [&quot;3000&quot;,&quot;entry 28&quot;, entry 29&quot;, &quot;entry 30&quot;...], [&quot;3900&quot;, &quot;entry 31&quot;, entry 32&quot;, &quot;entry 33&quot;...], [&quot;9999&quot;, &quot;entry X&quot;, entry Y&quot;, &quot;entry Z&quot;...] } </code></pre> <p>The first and last row (i.e. 0000 and 9999) are useless and will not be used.</p> <p>we have to split this List&lt;String[]&gt; into List&lt;List&lt;String[]&gt;&gt; such that it contains rows from 3000 to 3900</p> <p>Output:</p> <pre><code>{ { [&quot;3000&quot;,&quot;entry1&quot;, entry2&quot;, &quot;entry3&quot;, ...], [&quot;5000&quot;, &quot;entry4&quot;, entry 5&quot;, &quot;entry 6&quot;, ...], [&quot;5000&quot;, &quot;entry 7&quot;, entry 8&quot;, &quot;entry 9&quot;, ...], [&quot;5000&quot;, &quot;entry 10&quot;, entry 11&quot;, &quot;entry 12&quot;, ...], [&quot;5000&quot;, &quot;entry 13&quot;, entry 14&quot;, &quot;entry 15&quot;, ...], [&quot;3900&quot;, &quot;entry 16&quot;, entry 17&quot;, &quot;entry 18&quot;, ...], }, { [&quot;3000&quot;,&quot;entry19&quot;, entry20&quot;, &quot;entry 21&quot;, ...], [&quot;5000&quot;, &quot;entry 22&quot;, entry 23&quot;, &quot;entry 24&quot;, ...], [&quot;3900&quot;, &quot;entry 25&quot;, entry 26&quot;, &quot;entry 27&quot;, ...], }, { [&quot;3000&quot;,&quot;entry 28&quot;, entry 29&quot;, &quot;entry 30&quot;, ...], [&quot;3900&quot;, &quot;entry 31&quot;, entry 32&quot;, &quot;entry 33&quot;, ...], } } </code></pre> <p>This is my code so far:</p> <pre><code> private List&lt;List&lt;String[]&gt;&gt; splitIntoBlocks(List&lt;String[]&gt; rows) { //get all position of 3000 List&lt;Integer&gt; l1 = IntStream.range(0,rows.size()) .filter(i-&gt;rows.get(i)[0].equals(&quot;3000&quot;)) .boxed() .collect(Collectors.toList()); //get all position of 3900 List&lt;Integer&gt; l2 = IntStream.range(0,rows.size()) .filter(i-&gt;rows.get(i)[0].equals(&quot;3900&quot;)) .boxed() .collect(Collectors.toList()); List&lt;List&lt;String[]&gt;&gt; res=null; //split list&lt;string[]&gt; rows into blocks that start with 3000 and end with 3900 and store it in a list if(l1.size() == l2.size()) { res = IntStream.range(0, l1.size()) .mapToObj(i-&gt;rows.subList(l1.get(i),l2.get(i)+1)) .collect(Collectors.toList()); } return res; } </code></pre> <p>As you can see, I have solved it using streams in roughly 3 stream statements, but I'm not very good at java 8 features. I'm looking for someone to solve this in perhaps 1 or 2 statements. I feel that it is very much possible</p> <p>P.S. - This is not an interview question, but something I will be using at work.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T20:56:47.697", "Id": "531685", "Score": "1", "body": "is there a performance reason to be using stream? The way you're using them seems odd, and IDK if it's for contextual reasons of if this just the first way you found of iterating." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T04:23:57.547", "Id": "531691", "Score": "2", "body": "Why would you not use a `BufferedReader` and keep a state where a `3` has been seen and if not skip any line that doesn’t start with a `3`? Is efficiency not a factor?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T04:34:56.763", "Id": "531693", "Score": "0", "body": "Also, your *input* and *output* look ill-formed" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T11:08:21.293", "Id": "531707", "Score": "0", "body": "@ShapeOfMatter The reason for using stream was to do it using functional programming. I wanted a solution that uses functional programming rather than for loop with if else (which I was initially using and is also suggested in janos's answer). I'm quite aware that the time complexity of my code is very bad. Therefore, I was hoping whether this question can be solved with a good tradeoff between using functional programming and code efficiency. If not, then I'll be happy to proceed with the code suggested by janos." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T14:28:58.757", "Id": "531728", "Score": "2", "body": "@HarshitDang I think you've fallen prey to the allure of streams. The whole point of them is to allow for independent parallel processing. That's only really appropriate when the data to be processed doesn't have internal dependencies. With your data, the internal ordering is a crucial part of the data structure, so (in my opinion at least) streams are not an appropriate approach." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T13:38:47.220", "Id": "531796", "Score": "0", "body": "I understand. Thank you!" } ]
[ { "body": "<h1>Low hanging fruit</h1>\n<p><code>l1</code> and <code>l2</code> are very opaque variable names. <code>start_indices</code> and <code>end_indices</code> would be much more descriptive.</p>\n<hr />\n<pre class=\"lang-java prettyprint-override\"><code> //get all position of 3000\n List&lt;Integer&gt; l1 = IntStream.range(0,rows.size())\n .filter(i-&gt;rows.get(i)[0].equals(&quot;3000&quot;))\n .boxed()\n .collect(Collectors.toList());\n</code></pre>\n<p>This code takes <code>int</code> indices, boxes them into <code>Integer</code> indices, and collects them into a <code>List&lt;Integer&gt;</code>. This results in many small objects in memory.</p>\n<p>We can avoid the boxing, by replacing <code>.boxed().collect(Collectors.toList())</code> with <code>.toArray()</code> and changing the variable type to <code>int[]</code>.</p>\n<pre class=\"lang-java prettyprint-override\"><code> // get positions of all &quot;3000&quot;'s\n int[] start_indices = IntStream.range(0,rows.size())\n .filter(i-&gt;rows.get(i)[0].equals(&quot;3000&quot;))\n .toArray();\n</code></pre>\n<p>Apply similar change to the group end indices, and corresponding changes to the final <code>res</code> construction.</p>\n<h1>Single Pass</h1>\n<p>The above is still passing over the <code>rows</code> input 3 times; the first to collect the starting indices, the second to collect the ending indices, and the third time to assemble the result. Three passes means you cannot apply this grouping operation on an ephemeral stream; it requires a concrete collection that can be repeatedly iterated over.</p>\n<p>Moreover, an <code>IntStream</code> is being used to generate indices into the <code>rows</code> list -- a hack -- which requires an <code>ArrayList</code> or similar <span class=\"math-container\">\\$O(1)\\$</span>-indexable collection to avoid quadratic time complexity.</p>\n<p>It would be much better to perform a single pass over the stream of data, and collecting the required groups along the way:</p>\n<pre class=\"lang-java prettyprint-override\"><code>private List&lt;List&lt;String[]&gt;&gt; splitIntoBlocks(List&lt;String[]&gt; rows) {\n return rows.stream().collect(Block.collector());\n}\n</code></pre>\n<p>Well, the above clearly solves the &quot;<em>looking for someone to solve this in perhaps 1 or 2 statements</em>&quot; request, but clearly additional work is still required. The <code>Block.collector()</code> class is required, writing of which (to handle possible splitting &amp; parallel stream handling) is a non-trivial exercise. See <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collector.html#of-java.util.function.Supplier-java.util.function.BiConsumer-java.util.function.BinaryOperator-java.util.stream.Collector.Characteristics...-\" rel=\"nofollow noreferrer\"><code>Collector.of(...)</code></a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T16:36:28.523", "Id": "531740", "Score": "0", "body": "I think the approach of writing a custom collector is a very good one." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T21:21:53.057", "Id": "269474", "ParentId": "269471", "Score": "4" } }, { "body": "<h3>Motivations for improvement</h3>\n<p>I think &quot;solving in 1 or 2 statements&quot; is not a good target. Aiming for Java 8 features for the sake of using Java 8 features is also not a good target. A better target would be a combination of:</p>\n<ul>\n<li>correct and reasonably robust</li>\n<li>easy to understand</li>\n<li>reasonably efficient</li>\n</ul>\n<p>Here's a bit shorter and more efficient, but pretty bad solution:</p>\n<pre><code>private List&lt;List&lt;String[]&gt;&gt; splitIntoBlocks(List&lt;String[]&gt; rows) {\n List&lt;List&lt;String[]&gt;&gt; blocks = new ArrayList&lt;&gt;();\n\n int start = 0;\n for (int index = 0; index &lt; rows.size(); index++) {\n String marker = rows.get(index)[0];\n if (marker.equals(&quot;3000&quot;)) {\n start = index;\n } else if (marker.equals(&quot;3900&quot;)) {\n int end = index + 1;\n blocks.add(rows.subList(start, end));\n }\n }\n\n return blocks;\n}\n</code></pre>\n<p>This is bad (as bad as the original code), because it doesn't validate the input. It will only work correctly with input in the assumed format, which it doesn't verify, and it doesn't detect or signal when something is wrong, which could lead to nasty bugs.</p>\n<h3>Validating inputs</h3>\n<p>The posted code assumes the input follows a certain format. It should at least document the assumptions, and state if the caller can be trusted to enforce those assumptions.</p>\n<p>As you mentioned, the input comes from CSV files. Since the expected format is not captured by the <code>List&lt;String[]&gt;</code> type, I would be very cautious. A verification is needed somewhere to avoid bugs or undefined behavior, for example the following checks come to mind:</p>\n<ul>\n<li>There are the same number of START and END markers (you already did this one)</li>\n<li>The START and END markers don't overlap</li>\n<li>(optional?) There are no garbage records after an END and before the next START</li>\n<li>The rows are not empty (avoid crashing due to index out of bounds exceptions)</li>\n</ul>\n<p>When any of these assumptions fail, I would either raise a custom exception that the caller can handle, or else throw <code>IllegalArgumentException</code> to fail fast.</p>\n<p>So in fact, instead of making the posted code shorter, I'm suggesting to actually make it longer, by adding more validation logic.</p>\n<h3>Making the code easier to understand</h3>\n<p>Another answer already mentioned to improve the variable names. (I suggest following Java conventions with <code>camelCase</code> names, so <code>startIndices</code> and <code>endIndices</code>.)</p>\n<p>The values &quot;3000&quot; and &quot;3900&quot; are magic strings. It would be better to use <code>private static final</code> constants for such values, so that they stand out, and with a descriptive name.</p>\n<p>Building the lists of <code>startIndices</code> and <code>endIndices</code> use the same logic, duplicated. It would be good to extract to a helper method.</p>\n<p>When returning a container type, it's usually more practical to return an empty container instead of <code>null</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T07:48:22.797", "Id": "531699", "Score": "0", "body": "Thank you for the suggestions on validation part. I had skipped the validation logic for now to keep the focus of this question on the main logic of splitting. My bad. Let's say that we add the validation logic in the code that you've provided, would that turn this \"bad\" code into \"good\" code? Furthermore, is the code provided by you the most efficient when it comes to \"splitting\" logic?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T07:55:55.970", "Id": "531700", "Score": "1", "body": "The bad code I provided is efficient because it splits the list in a single pass. I don't think it can be more efficient. It's also easy to read, for now. If you implement validation in that same method, I think it will become complex and hard to read, because the validation itself will be an added responsibility. I think a good tradeoff is to have a separate method that performs validation, and call that function at the top of this one. It won't be the most efficient solution, because it will mean 2 passes over the input. But readability is important, so I think that will be a good tradeoff." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T14:30:40.200", "Id": "531729", "Score": "1", "body": "@janos - I don't see any need for a 2 pass approach. At each \"row\" of input you can firstly determine whether the input constraints have been met, then process the row appropriately." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T14:46:14.663", "Id": "531731", "Score": "1", "body": "@MarkBluemel I think that's opinionated. It certainly can be done in a single pass, which will do validation and splitting. Doing 2 things at the same time adds mental burden, and it's probably difficult to write in a way that's as easy to understand as when separated. Since we're on the same order of complexity regardless of 1 or 2 passes, I would first write it so it's easiest to read, and if later it's identified as a bottleneck, it could be merged into one. If the author insists on combining, and it's reasonably easy to read, I would not object." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T14:51:20.783", "Id": "531735", "Score": "1", "body": "@janos We're all opinionated ;-) My sample solution is in my answer to the OP's post and I don't think it's particularly difficult to understand, and I do think it's fairly robust, and well-suited to subsequent amendment. For me, the key thing was to regard the input processing more like reading a file than like making passes over an array - as I remark in my answer, if the structure had been any more complicated I'd probably have used a Finite State Machine - my current solution is only a little different from one, in that the states are more or less implicit." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T21:34:41.447", "Id": "269475", "ParentId": "269471", "Score": "6" } }, { "body": "<ul>\n<li>The input data seems to me to naturally fit a sequential process, and\nall the processing can be achieved in a single pass, so I fail to see\nhow using streams and making 3 passes is a sensible approach,\nespecially with the amount of boxing used</li>\n<li>The approach taken assumes, rather than checks, that the input data\nis well-formed, which seems a little optimistic. Defensive\nprogramming principles suggest that you should check the data meets\nexpectations.</li>\n<li>The naming issues have already been addressed. There's little\nrestriction on variable names, and the typing saved in naming a\nvariable &quot;l1&quot; is a poor exchange for readability against\n&quot;subListStartOffsets&quot; or something similar.</li>\n</ul>\n<p>For this sort of processing, I'd often write a little Finite State Machine, but this exercise doesn't seem quite to warrant it. The natural processing pattern seems to me to be this.</p>\n<p>For the first array, check that it starts with &quot;0000&quot;. If not, throw an Exception as the input is badly-formed.</p>\n<p>Assign a List&lt;List&lt;String[]&gt;&gt; for the result. Let's call this <code>outputList</code>.</p>\n<p>Also allocate an int to hold the start of the current subList. Let's just call this <code>subListStart</code>. Initialise it to a &quot;flag&quot; value, say <code>-1</code>. (This probably should be a constant).</p>\n<p>Now process a row at a time.</p>\n<ul>\n<li>If it starts with &quot;3000&quot; it marks the start of a subList. Check <code>subListStart</code>, if it is -1 then store the current offset in it, if not the input data is badly formed, and you should throw an Exception.</li>\n<li>If it starts with &quot;3900&quot; it marks the end of a subList. Extract the subList from <code>subListStart</code> to the current offset, and add it to your <code>outputList</code>. Set <code>subListStart</code> to -1 again, to indicate we're looking for a new start...</li>\n<li>If it starts with &quot;5000&quot; it's just data, but you should check that you've seen a start of list marker, so if <code>subListStart</code> is -1 you should throw an Exception.</li>\n<li>If it starts with &quot;9999&quot; it marks the end of the input data. You should check that the last subList was closed, by checking subListStart is -1.</li>\n</ul>\n<p>Here's an example of how I might implement this (far from fully tested, I must point out).</p>\n<pre><code>import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Iterator;\nimport java.util.List;\n\npublic class SubListProcessor {\n\n private static final String HEADER = &quot;0000&quot;;\n private static final String START_OF_SUBLIST = &quot;3000&quot;;\n private static final String END_OF_SUBLIST = &quot;3900&quot;;\n private static final String FOOTER = &quot;9999&quot;;\n private static final String PLAIN_DATA = &quot;5000&quot;;\n\n public class BadlyFormedListException extends IllegalArgumentException {\n\n public BadlyFormedListException(String message) {\n super(message);\n }\n }\n\n public List&lt;List&lt;String[]&gt;&gt; processList(List&lt;String[]&gt; inputList) {\n List&lt;List&lt;String[]&gt;&gt; outputList = new ArrayList&lt;&gt;();\n\n int subListStart = -1; // Magic number, could/should make this a constant\n int currentOffset = 0;\n boolean seenFooter = false;\n Iterator&lt;String[]&gt; inputListIterator = inputList.iterator();\n\n String[] firstLine = inputListIterator.next();\n if (firstLine == null) {\n throw new BadlyFormedListException(&quot;Input List is empty&quot;);\n }\n if (firstLine.length == 0) {\n throw new BadlyFormedListException(&quot;Empty line at offset &quot; + currentOffset);\n }\n if (!firstLine[0].equals(HEADER)) {\n throw new BadlyFormedListException(&quot;No header in input List&quot;);\n }\n\n while (inputListIterator.hasNext()) {\n String[] inputLine = inputListIterator.next();\n currentOffset += 1;\n if (inputLine.length == 0) {\n throw new BadlyFormedListException(&quot;Empty line at offset &quot; + currentOffset);\n }\n switch (inputLine[0]) {\n case (START_OF_SUBLIST) : {\n if (subListStart == -1) {\n subListStart = currentOffset;\n }\n else {\n throw new BadlyFormedListException(&quot;Unclosed sub-list at offset &quot; + currentOffset);\n }\n break;\n }\n case (PLAIN_DATA) : {\n if (subListStart == -1) {\n throw new BadlyFormedListException(&quot;Unopened sub-list at offset &quot; + currentOffset);\n }\n break;\n }\n case (END_OF_SUBLIST) : {\n if (subListStart == -1) {\n throw new BadlyFormedListException(&quot;Unopened sub-list at offset &quot; + currentOffset);\n }\n outputList.add(inputList.subList(subListStart, currentOffset + 1));\n subListStart = -1;\n break;\n }\n case (FOOTER) : {\n if (subListStart != -1) {\n throw new BadlyFormedListException(&quot;Unclosed sub-list at offset &quot; + currentOffset);\n }\n seenFooter = true;\n break;\n }\n default :\n throw new BadlyFormedListException(&quot;Unrecognised line at offset &quot; + currentOffset);\n\n }\n }\n\n if (!seenFooter) {\n throw new BadlyFormedListException(&quot;No footer in input list&quot;);\n }\n\n return outputList;\n }\n\n public static void main(String[] args) {\n List&lt;String[]&gt; inputList = Arrays.asList(\n new String[]{&quot;0000&quot;, &quot;entry A&quot;, &quot;entry B&quot;, &quot;entry C&quot;},\n new String[]{&quot;3000&quot;, &quot;entry1&quot;, &quot;entry2&quot;, &quot;entry3&quot;},\n new String[]{&quot;5000&quot;, &quot;entry4&quot;, &quot;entry 5&quot;, &quot;entry 6&quot;},\n new String[]{&quot;5000&quot;, &quot;entry 7&quot;, &quot;entry 8&quot;, &quot;entry 9&quot;},\n new String[]{&quot;5000&quot;, &quot;entry 10&quot;, &quot;entry 11&quot;, &quot;entry 12&quot;},\n new String[]{&quot;5000&quot;, &quot;entry 13&quot;, &quot;entry 14&quot;, &quot;entry 15&quot;},\n new String[]{&quot;3900&quot;, &quot;entry 16&quot;, &quot;entry 17&quot;, &quot;entry 18&quot;},\n new String[]{&quot;3000&quot;, &quot;entry19&quot;, &quot;entry20&quot;, &quot;entry 21&quot;},\n new String[]{&quot;5000&quot;, &quot;entry 22&quot;, &quot;entry 23&quot;, &quot;entry 24&quot;},\n new String[]{&quot;3900&quot;, &quot;entry 25&quot;, &quot;entry 26&quot;, &quot;entry 27&quot;},\n new String[]{&quot;3000&quot;, &quot;entry 28&quot;, &quot;entry 29&quot;, &quot;entry 30&quot;},\n new String[]{&quot;3900&quot;, &quot;entry 31&quot;, &quot;entry 32&quot;, &quot;entry 33&quot;},\n new String[]{&quot;9999&quot;, &quot;entry X&quot;, &quot;entry Y&quot;, &quot;entry Z&quot;});\n\n List&lt;List&lt;String[]&gt;&gt; result = new SubListProcessor().processList(inputList);\n\n for (List&lt;String[]&gt; subList : result) {\n System.out.println(&quot;&lt;&quot;);\n for (String[] value : subList) {\n System.out.format(&quot;\\t%s%n&quot;, Arrays.toString(value));\n }\n System.out.println(&quot;&gt;&quot;);\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T08:25:15.597", "Id": "269495", "ParentId": "269471", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T19:39:43.097", "Id": "269471", "Score": "3", "Tags": [ "java" ], "Title": "Split List<String[]> into List<List<String[]>>" }
269471
<p><strong>This script is designed to help solve sequences in Sudoku puzzles with variant constraints (ex: Thermometer, Renban, etc.).</strong></p> <hr /> <h2>Summary</h2> <p>The user specifies the constraints they want applied as well as the sequence length.</p> <p>All sequences of that length are then generated and the code eliminates the ones which violate any of the constraints.</p> <p>Finally, the user is presented with a list of valid sequences as well as a breakdown of valid digits for each position in the sequence.</p> <hr /> <h2>Background</h2> <p>I come from an academic research background where code often ends up as <em>kinda-works-duck-taped-spaghetti</em>, rather than well-organized and maintainable and I'd like to do better.</p> <p>I'm looking for feedback mainly on code organisation and general architecture, rather than performance (Even in the worst case scenario, the code takes at most ~1s to run, so it's not very critical).</p> <p>I'm especially interested in the following areas:</p> <ul> <li>How constraints are selected and applied at runtime.</li> <li>How to implement a new constraint (and its user input code) more easily.</li> <li>Interactions between the different classes and what they contain.</li> </ul> <p>Any other general comments are more than welcome.</p> <hr /> <h2>The code</h2> <p><code>UserInput</code> serves purely to get basic parameters that the other classes use (so the user doesn't have to input them twice). I'm certain there's a better way to do it, but I'm not sure how.</p> <p><code>Constraints</code> implements and checks the different constraints that can be applied. The main issues I see here is how the user must know what constraints are available, and that when implementing a new constraint, it's necessary to add user input code in the <code>get_user_constraints()</code> method too, which seems like a source of problems further down the line.</p> <p>I'd like to have the user input code in <code>UserInput</code> rather than here, but I'm not sure how to do that while avoiding tightly coupling the two classes together (since some constraints require additional parameters rather than just Y/N).</p> <p><code>SequenceCandidates</code> generates and holds the potential sequences. I'm not sure there's something wrong here, perhaps it should be split into two (for generating and holding)?</p> <p><strong>I removed specific implementation details for constraints since they don't really impact the overall code architecture and make it harder to read. The code still runs, but with hardcoded constraint return values.</strong></p> <pre><code>import itertools import numpy as np class UserInput: def __init__(self): &quot;&quot;&quot;Gets and holds basic information from the user.&quot;&quot;&quot; print(&quot;Please input the following information:&quot;) self.sequence_length = int(input(&quot;- What is the length of the desired sequence? &quot;)) self.digits = list(range(1, 10)) # Could be user specified if needed for different size puzzles. class Constraints: &quot;&quot;&quot;Manages the different constraints that can be applied to a sequence.&quot;&quot;&quot; def __init__(self, sequence_length): self.sequence_length = sequence_length self.active_constraints = [] self.sequence = None # Other parameters relevant to specific constraints removed for simplicity. self.get_user_constraints() def get_user_constraints(self): &quot;&quot;&quot;Asks the user what constraints should be applied to the sequence.&quot;&quot;&quot; if input(&quot;- Position constraints? &quot;): self.add_restriction(Constraints.invalid_digit_position) # Removed specific implementation details. if input(&quot;- Thermometer constraint? &quot;): self.add_restriction(Constraints.invalid_thermometer) if input(&quot;- Arrow constraint? &quot;): self.add_restriction(Constraints.invalid_arrow) # Removed specific implementation details. if input(&quot;- Renban constraint? &quot;): self.add_restriction(Constraints.invalid_renban) def add_restriction(self, constraint): &quot;&quot;&quot;Adds a constraint to the list of constraints that will be tested.&quot;&quot;&quot; self.active_constraints.append(constraint) def sequence_is_valid(self, sequence): &quot;&quot;&quot;Validate a sequence against the selected constraints.&quot;&quot;&quot; self.sequence = sequence for constraint in self.active_constraints: if constraint(self): return False return True # Implementation details for the constraints removed for simplicity. # They all check self.sequence against the constraint and return a bool. def invalid_duplicate_digits(self): return False def invalid_digit_position(self): return False def invalid_arrow(self): return True def invalid_thermometer(self): return True def invalid_renban(self): return True class SequenceCandidates: def __init__(self, digits, sequence_length): self.sequence_length = sequence_length self.valid = [] # Generate all sequences. Not very efficient, but even with 362880 (9!) sequences, its quick enough. self.unchecked = list(itertools.permutations(digits, sequence_length)) def add_to_valid(self, sequence): self.valid.append(sequence) def display_valid_sequences(self): &quot;&quot;&quot;Display valid sequences as well as valid digits for each position in the sequence.&quot;&quot;&quot; self.valid = np.asarray(self.valid) if self.valid.size &gt; 0: print(f&quot;\n{self.valid.shape[0]} valid candidates: \n{self.valid}&quot;) for column in range(self.valid.shape[-1]): possible_digits = np.unique(self.valid[:, column]) print(f&quot;Valid digits for position {column + 1}: {possible_digits}&quot;) else: print(&quot;No valid candidates found.&quot;) if __name__ == &quot;__main__&quot;: user_input_parameters = UserInput() constraints = Constraints(user_input_parameters.sequence_length) candidates = SequenceCandidates(user_input_parameters.digits, user_input_parameters.sequence_length) for sequence in candidates.unchecked: if constraints.sequence_is_valid(sequence): candidates.add_to_valid(sequence) candidates.display_valid_sequences() </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-28T22:06:33.310", "Id": "269478", "Score": "3", "Tags": [ "python", "python-3.x", "object-oriented", "design-patterns" ], "Title": "Sudoku sequence solver for non-standard constraints" }
269478
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/269376/231235">A recursive_depth function for calculating depth of nested types implementation in C++</a> and <a href="https://codereview.stackexchange.com/a/269309/231235">A recursive_count Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++</a>. I am trying to follow <a href="https://codereview.stackexchange.com/a/269309/231235">G. Sliepen's answer</a> to implement another version of <code>recursive_count</code> function using <code>recursive_depth</code> for unwrap_level checking.</p> <p><strong>The experimental implementation</strong></p> <ul> <li><p><code>recursive_count</code> function:</p> <pre><code>// recursive_count implementation // recursive_count implementation (the version with unwrap_level) template&lt;std::size_t unwrap_level, class T&gt; constexpr auto recursive_count(const T&amp; input, const auto&amp; target) { if constexpr (unwrap_level &gt; 0) { static_assert(unwrap_level &lt;= recursive_depth&lt;T&gt;(), &quot;unwrap level higher than recursion depth of input&quot;); return std::transform_reduce(std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus&lt;std::size_t&gt;(), [&amp;target](auto&amp;&amp; element) { return recursive_count&lt;unwrap_level - 1&gt;(element, target); }); } else { if (input == target) { return 1; } else { return 0; } } } // recursive_count implementation (the version without unwrap_level) template&lt;std::ranges::input_range Range&gt; constexpr auto recursive_count(const Range&amp; input, const auto&amp; target) { return recursive_count&lt;recursive_depth&lt;Range&gt;()&gt;(input, target); } </code></pre> </li> <li><p><code>recursive_depth</code> function:</p> <pre><code>// recursive_depth function implementation template&lt;typename T&gt; constexpr std::size_t recursive_depth() { return 0; } template&lt;std::ranges::input_range Range&gt; constexpr std::size_t recursive_depth() { return recursive_depth&lt;std::ranges::range_value_t&lt;Range&gt;&gt;() + 1; } </code></pre> </li> </ul> <p><strong>The testing code</strong></p> <pre><code>void recursive_count_test() { std::vector&lt;int&gt; test_vector{ 5, 7, 4, 2, 8, 6, 1, 9, 0, 3 }; std::cout &lt;&lt; recursive_count&lt;1&gt;(test_vector, 5) &lt;&lt; '\n'; // std::vector&lt;std::vector&lt;int&gt;&gt; std::vector&lt;decltype(test_vector)&gt; test_vector2{ test_vector , test_vector , test_vector }; std::cout &lt;&lt; recursive_count&lt;2&gt;(test_vector2, 5) &lt;&lt; '\n'; // std::vector&lt;std::string&gt; std::vector&lt;std::string&gt; test_string_vector{ &quot;0&quot;, &quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;, &quot;5&quot;, &quot;6&quot;, &quot;7&quot;, &quot;8&quot;, &quot;9&quot;, &quot;10&quot;, &quot;11&quot;, &quot;12&quot;, &quot;13&quot;, &quot;14&quot;, &quot;15&quot;, &quot;16&quot;, &quot;17&quot;, &quot;18&quot;, &quot;19&quot;, &quot;20&quot; }; std::cout &lt;&lt; recursive_count&lt;1&gt;(test_string_vector, &quot;0&quot;) &lt;&lt; '\n'; // std::vector&lt;std::vector&lt;std::string&gt;&gt; std::vector&lt;decltype(test_string_vector)&gt; test_string_vector2{ test_string_vector , test_string_vector , test_string_vector }; std::cout &lt;&lt; recursive_count&lt;2&gt;(test_string_vector2, &quot;0&quot;) &lt;&lt; '\n'; // 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); std::cout &lt;&lt; recursive_count&lt;1&gt;(test_deque, 1) &lt;&lt; '\n'; // 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); std::cout &lt;&lt; recursive_count&lt;2&gt;(test_deque2, 1) &lt;&lt; '\n'; // std::list&lt;int&gt; std::list&lt;int&gt; test_list = { 1, 2, 3, 4, 5, 6 }; std::cout &lt;&lt; recursive_count&lt;1&gt;(test_list, 1) &lt;&lt; '\n'; // 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 }; std::cout &lt;&lt; recursive_count&lt;2&gt;(test_list2, 1) &lt;&lt; '\n'; std::cout &lt;&lt; recursive_count&lt;11&gt;( n_dim_container_generator&lt;10, std::list&gt;(test_list, 3), 1 ) &lt;&lt; '\n'; } </code></pre> <p><strong>Full Testing Code</strong></p> <p>The full testing code:</p> <pre><code>#include &lt;algorithm&gt; #include &lt;array&gt; #include &lt;concepts&gt; #include &lt;deque&gt; #include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;list&gt; #include &lt;numeric&gt; #include &lt;string&gt; #include &lt;type_traits&gt; #include &lt;utility&gt; #include &lt;vector&gt; #include &lt;ranges&gt; // recursive_depth function implementation template&lt;typename T&gt; constexpr std::size_t recursive_depth() { return 0; } template&lt;std::ranges::input_range Range&gt; constexpr std::size_t recursive_depth() { return recursive_depth&lt;std::ranges::range_value_t&lt;Range&gt;&gt;() + 1; } // recursive_count implementation // recursive_count implementation (the version with unwrap_level) template&lt;std::size_t unwrap_level, class T&gt; constexpr auto recursive_count(const T&amp; input, const auto&amp; target) { if constexpr (unwrap_level &gt; 0) { static_assert(unwrap_level &lt;= recursive_depth&lt;T&gt;(), &quot;unwrap level higher than recursion depth of input&quot;); return std::transform_reduce(std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus&lt;std::size_t&gt;(), [&amp;target](auto&amp;&amp; element) { return recursive_count&lt;unwrap_level - 1&gt;(element, target); }); } else { if (input == target) { return 1; } else { return 0; } } } // recursive_count implementation (the version without unwrap_level) template&lt;std::ranges::input_range Range&gt; constexpr auto recursive_count(const Range&amp; input, const auto&amp; target) { return recursive_count&lt;recursive_depth&lt;Range&gt;()&gt;(input, target); } template&lt;std::size_t dim, class T&gt; constexpr auto n_dim_vector_generator(T input, std::size_t times) { if constexpr (dim == 0) { return input; } else { auto element = n_dim_vector_generator&lt;dim - 1&gt;(input, times); std::vector&lt;decltype(element)&gt; output(times, element); return output; } } template&lt;std::size_t dim, std::size_t times, class T&gt; constexpr auto n_dim_array_generator(T input) { if constexpr (dim == 0) { return input; } else { auto element = n_dim_array_generator&lt;dim - 1, times&gt;(input); std::array&lt;decltype(element), times&gt; output; std::fill(std::begin(output), std::end(output), element); return output; } } template&lt;std::size_t dim, class T&gt; constexpr auto n_dim_deque_generator(T input, std::size_t times) { if constexpr (dim == 0) { return input; } else { auto element = n_dim_deque_generator&lt;dim - 1&gt;(input, times); std::deque&lt;decltype(element)&gt; output(times, element); return output; } } template&lt;std::size_t dim, class T&gt; constexpr auto n_dim_list_generator(T input, std::size_t times) { if constexpr (dim == 0) { return input; } else { auto element = n_dim_list_generator&lt;dim - 1&gt;(input, times); std::list&lt;decltype(element)&gt; output(times, element); return output; } } template&lt;std::size_t dim, template&lt;class...&gt; class Container = std::vector, class T&gt; constexpr auto n_dim_container_generator(T input, std::size_t times) { if constexpr (dim == 0) { return input; } else { return Container(times, n_dim_container_generator&lt;dim - 1, Container, T&gt;(input, times)); } } void recursive_depth_test(); void recursive_count_test(); int main() { recursive_count_test(); } void recursive_depth_test() { // non-nested type `char` char test_char = 'A'; std::cout &lt;&lt; recursive_depth&lt;decltype(test_char)&gt;() &lt;&lt; '\n'; // non-nested type `int` int test_int = 100; std::cout &lt;&lt; recursive_depth&lt;decltype(test_int)&gt;() &lt;&lt; '\n'; // std::vector&lt;int&gt; std::vector&lt;int&gt; test_vector{ 5, 7, 4, 2, 8, 6, 1, 9, 0, 3 }; std::cout &lt;&lt; recursive_depth&lt;decltype(test_vector)&gt;() &lt;&lt; '\n'; // std::vector&lt;std::vector&lt;int&gt;&gt; std::vector&lt;decltype(test_vector)&gt; test_vector2{ test_vector , test_vector , test_vector }; std::cout &lt;&lt; recursive_depth&lt;decltype(test_vector2)&gt;() &lt;&lt; '\n'; // 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); std::cout &lt;&lt; recursive_depth&lt;decltype(test_deque)&gt;() &lt;&lt; '\n'; // 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); std::cout &lt;&lt; recursive_depth&lt;decltype(test_deque2)&gt;() &lt;&lt; '\n'; // std::list&lt;int&gt; std::list&lt;int&gt; test_list = { 1, 2, 3, 4, 5, 6 }; std::cout &lt;&lt; recursive_depth&lt;decltype(test_list)&gt;() &lt;&lt; '\n'; // 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 }; std::cout &lt;&lt; recursive_depth&lt;decltype(test_list2)&gt;() &lt;&lt; '\n'; } void recursive_count_test() { std::vector&lt;int&gt; test_vector{ 5, 7, 4, 2, 8, 6, 1, 9, 0, 3 }; std::cout &lt;&lt; recursive_count&lt;1&gt;(test_vector, 5) &lt;&lt; '\n'; // std::vector&lt;std::vector&lt;int&gt;&gt; std::vector&lt;decltype(test_vector)&gt; test_vector2{ test_vector , test_vector , test_vector }; std::cout &lt;&lt; recursive_count&lt;2&gt;(test_vector2, 5) &lt;&lt; '\n'; // std::vector&lt;std::string&gt; std::vector&lt;std::string&gt; test_string_vector{ &quot;0&quot;, &quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;, &quot;5&quot;, &quot;6&quot;, &quot;7&quot;, &quot;8&quot;, &quot;9&quot;, &quot;10&quot;, &quot;11&quot;, &quot;12&quot;, &quot;13&quot;, &quot;14&quot;, &quot;15&quot;, &quot;16&quot;, &quot;17&quot;, &quot;18&quot;, &quot;19&quot;, &quot;20&quot; }; std::cout &lt;&lt; recursive_count&lt;1&gt;(test_string_vector, &quot;0&quot;) &lt;&lt; '\n'; // std::vector&lt;std::vector&lt;std::string&gt;&gt; std::vector&lt;decltype(test_string_vector)&gt; test_string_vector2{ test_string_vector , test_string_vector , test_string_vector }; std::cout &lt;&lt; recursive_count&lt;2&gt;(test_string_vector2, &quot;0&quot;) &lt;&lt; '\n'; // 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); std::cout &lt;&lt; recursive_count&lt;1&gt;(test_deque, 1) &lt;&lt; '\n'; // 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); std::cout &lt;&lt; recursive_count&lt;2&gt;(test_deque2, 1) &lt;&lt; '\n'; // std::list&lt;int&gt; std::list&lt;int&gt; test_list = { 1, 2, 3, 4, 5, 6 }; std::cout &lt;&lt; recursive_count&lt;1&gt;(test_list, 1) &lt;&lt; '\n'; // 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 }; std::cout &lt;&lt; recursive_count&lt;2&gt;(test_list2, 1) &lt;&lt; '\n'; std::cout &lt;&lt; recursive_count&lt;11&gt;( n_dim_container_generator&lt;10, std::list&gt;(test_list, 3), 1 ) &lt;&lt; '\n'; } </code></pre> <p><a href="https://godbolt.org/z/3b96j5haM" 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/269376/231235">A recursive_depth function for calculating depth of nested types implementation in C++</a> and</p> <p><a href="https://codereview.stackexchange.com/a/269309/231235">A recursive_count Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <p>I am trying to implement another version of <code>recursive_count</code> function using <code>recursive_depth</code> for unwrap_level checking.</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": "<h1>Missing test cases</h1>\n<p>I don't see any test cases being added for the version of <code>recursive_count()</code> that doesn't take an unwrap level. Also, add test cases for corner cases, most importantly trying to apply <code>recursive_count&lt;0&gt;()</code> on ranges and applying <code>recursive_count()</code> on non-ranges. For example, consider adding the following test cases:</p>\n<pre><code>assert(recursive_count&lt;0&gt;(1, 2) == 0);\nassert(recursive_count&lt;0&gt;(0, 0) == 1);\n</code></pre>\n<p>This will compile and run correctly. However, the following does not:</p>\n<pre><code>assert(recursive_count(1, 2) == 0);\nassert(recursive_count(0, 0) == 1);\n</code></pre>\n<p>This will fail to compile with your code because your <code>recursive_count()</code> without an unwrap level only works on ranges. The fix is to make it <code>template&lt;typename T&gt;</code> instead of <code>template&lt;std::ranges::input_range Range&gt;</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T07:27:52.553", "Id": "269493", "ParentId": "269479", "Score": "2" } }, { "body": "<pre><code> if (input == target)\n {\n return 1;\n }\n else\n {\n return 0;\n }\n</code></pre>\n<p>Write this clearly as:<br />\n<code>return (input == target) ? 1 : 0;</code></p>\n<p>The cognitive overhead of what you wrote is quite high: the reader sees an <code>if</code> statement so the code does two different things. Then, each thing is a return statement. Ah, it returns either way, you <em>always</em> want to return -- you just want to condition to specify <em>which value</em> is returned.</p>\n<p>So write it directly, rather than making the reader reverse-engineer that meaning.</p>\n<p>I want to impress that it's not just &quot;terse&quot; for its own sake. The single statement is easier to read and understand, since it directly states the intent. In general, don't duplicate more than necessary in your conditional branches. If the condition is just to affect some values, don't repeat the function calls and unaffected values.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T14:42:47.810", "Id": "269509", "ParentId": "269479", "Score": "1" } } ]
{ "AcceptedAnswerId": "269493", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T00:13:02.717", "Id": "269479", "Score": "1", "Tags": [ "c++", "recursion", "template", "c++20" ], "Title": "A recursive_count function with recursive_depth for unwrap_level checking in C++" }
269479
<p>I am doing the codecademy course and had to do a rock paper scissors game as a project. Rather than following the instructions I tried Doing it on my own. How I could make the code more efficient?</p> <pre><code>//Only outputs 1-3 const COMPUTERCHOICE = (min=1, max=4) =&gt; { return Math.floor(Math.random() * (max - min) + min); }; //Establishes a relation between the numbers and items console.log('1 = Scissors, 2 = Paper, 3 = Rock\n') function game(userChoice, computer) { if (userChoice === 3 &amp;&amp; computer === 1){ return `User chose ${userChoice}, Computer chose ${computer}, user Wins!` }else if (computer === 3 &amp;&amp; userChoice === 1){ return `User chose ${userChoice}, computer chose ${computer}, Computer Wins!` }else if (userChoice &lt; computer){ return `Player chose ${userChoice}, Computer Chose ${computer} User Wins! :D`; } else if (userChoice === computer) { return `It's a draw!` }else { return `Player chose ${userChoice}, Computer Chose ${computer} Computer wins :(`; }; } console.log(game(3, COMPUTERCHOICE())) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T21:35:30.133", "Id": "532101", "Score": "1", "body": "I like to make a whatBeatsWhat mapping for this scenario. player1 wins if `whatBeatsWhat[p1Choice] === p2Choice`. player2 wins if `whatBeatsWhat[p2Choice] === p1Choice`. Otherwise, it's a tie. I find this to be a simple, readable solution." } ]
[ { "body": "<p>The best way to improve this would be to somehow use a <a href=\"https://www.w3schools.com/js/js_switch.asp\" rel=\"nofollow noreferrer\"><code>switch</code></a> statement in the <code>game</code> logic rather than an excessive if-else chain. The <code>return</code> statements would replace your <code>break</code> statements.</p>\n<p>Another small tip would be to use a more descriptive function name like <code>checkChoice</code> over <code>game</code>. Think about writing code for humans first and computer second. Believe that in a professional environment someone else will eventually look at and maintain your code, and the best way to help them do their job is to make nothing ambiguous.</p>\n<p>Finally, reference and use a JavaScript style guide, like <a href=\"https://google.github.io/styleguide/jsguide.html\" rel=\"nofollow noreferrer\">Google's</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T04:09:45.333", "Id": "531762", "Score": "0", "body": "How should this code be changed to `switch` statements? Do you mean something like `switch (true) { case userChoice === 3 && computer === 1: ... }`? Could you show the refactored code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T07:25:38.300", "Id": "531766", "Score": "0", "body": "There are several options, which is why one specific solution is not showcased. This question is also asked in an academic context, so it's best for the student to think and implement rather than copy-paste code that could potentially have bugs." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T02:51:38.093", "Id": "269485", "ParentId": "269483", "Score": "4" } }, { "body": "<p>If you just <code>return (userChoice % 3 - computer % 3 + 3) % 3</code> on valid inputs;</p>\n<ul>\n<li><p>In case of tie, you always get <code>0</code></p>\n<ul>\n<li><code>(0 - 0 + 3) % 3</code></li>\n<li><code>(1 - 1 + 3) % 3</code></li>\n<li><code>(2 - 2 + 3) % 3</code></li>\n</ul>\n</li>\n<li><p>In case <code>userChoice</code> loses, you always get <code>1</code></p>\n<ul>\n<li><code>(1 - 0 + 3) % 3</code></li>\n<li><code>(2 - 1 + 3) % 3</code></li>\n<li><code>(0 - 2 + 3) % 3</code></li>\n</ul>\n</li>\n<li><p>In case <code>userChoice</code> wins, you always get <code>2</code></p>\n<ul>\n<li><code>(1 - 2 + 3) % 3</code></li>\n<li><code>(2 - 0 + 3) % 3</code></li>\n<li><code>(0 - 1 + 3) % 3</code></li>\n</ul>\n</li>\n</ul>\n<p>You can use the returned value (<code>0</code>, <code>1</code>, <code>2</code>) to determine which messages to print. You can also use the similar logic on other types of inputs (such as <code>String</code>), since <code>'p' &lt; 'r' &lt; 's'</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T11:12:31.893", "Id": "269501", "ParentId": "269483", "Score": "4" } } ]
{ "AcceptedAnswerId": "269485", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T02:15:42.303", "Id": "269483", "Score": "2", "Tags": [ "javascript", "game", "rock-paper-scissors" ], "Title": "Rock Paper Scissors Game using if statements" }
269483
<p>There is a sequence of integer values, and a separate integer.</p> <p>I was required to write a method to get all numbers from the given number sequence which can be divided exactly by the given separate integer.</p> <h2>Example</h2> <p>number sequence = 6, 12, 34, 96, 72, 16<br /> separate integer = 8<br /> result = 96, 72, 16</p> <h2>The code</h2> <pre><code>/******************************************************************************* * Program *******************************************************************************/ #include &lt;stdio.h&gt; void get_devidable_int(int array_data[], int seperate_value, int *array_length); void get_devidable_int(int array_data[], int seperate_value, int *array_length) { int *array_data2 = array_data; int new_lenght = 0; int *ptr = NULL; for (int x = 0; x &lt; *array_length; x++) { if (array_data[x] % seperate_value == 0) { ptr = &amp;array_data[x]; array_data[new_lenght] = array_data[x]; new_lenght++; ptr++; } } *array_length = new_lenght; } int main() { int value = 8; int dataset[6] = { 4, 16, 12, 64, 54, 33 }; int length = sizeof(dataset) / sizeof(*dataset); printf(&quot;INPUT**********************************\n&quot;); for (int y = 0; y &lt; 6; y++) { printf(&quot;data[%x]:%d\n&quot;, y, dataset[y]); } printf(&quot;seperate number: %d\n&quot;, value); get_devidable_int(dataset, value, &amp;length); printf(&quot;OUTPUT*********************************\n&quot;); printf(&quot;New length *******:%d\n&quot;, length); for (int x = 0; x &lt; length; x++) { printf(&quot;return data [%d] : %d\n&quot;, x, dataset[x]); } printf(&quot;END************************************\n&quot;); return 0; } </code></pre> <p>Please help with reviewing to begin my C programming :)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T15:16:34.133", "Id": "532282", "Score": "0", "body": "Do you have to use C? The algorithm `std::partition` comes in the C++ standard library, ready to use." } ]
[ { "body": "<p>First, a minor point: various misspelt words - correct versions are <code>separate</code>, <code>length</code>, <code>divisible</code>. Although this is a minor point, it can be important in larger programs, as incorrect and inconsistent spellings make searching within the code more difficult.</p>\n<hr />\n<blockquote>\n<pre><code>void get_devidable_int(int array_data[], int seperate_value, int *array_length);\n\nvoid get_devidable_int(int array_data[], int seperate_value, int *array_length)\n{\n</code></pre>\n</blockquote>\n<p>Although it's not wrong to provide a separate declaration, it's not necessary here, as the definition also acts as a declaration.</p>\n<hr />\n<p>While <code>int</code> mostly works for short arrays, the correct type for an array size is <code>size_t</code></p>\n<hr />\n<blockquote>\n<pre><code>int *array_data2 = array_data;\n</code></pre>\n</blockquote>\n<p>This variable seems unused.</p>\n<blockquote>\n<pre><code>int *ptr = NULL;\n</code></pre>\n</blockquote>\n<p>We only ever write to this variable, so we can remove that one, too.</p>\n<hr />\n<h1>Modified function</h1>\n<p>Applying these observations, we get:</p>\n<pre><code>void filter_multiples(int array_data[], int factor,\n size_t *array_length)\n{\n size_t new_length = 0;\n for (size_t x = 0; x &lt; *array_length; ++x)\n {\n if (array_data[x] % factor == 0)\n {\n array_data[new_length] = array_data[x];\n ++new_length;\n }\n }\n\n *array_length = new_length;\n}\n</code></pre>\n<hr />\n<p>Minor improvements to <code>main()</code>:</p>\n<ul>\n<li><p>Don't declare functions taking _unspecified_arguments:</p>\n<pre><code> int main(void)\n</code></pre>\n</li>\n<li><p>I think we should by using <code>length</code> rather than <code>6</code> here:</p>\n<pre><code> for (int y = 0; y &lt; 6; y++)\n</code></pre>\n</li>\n<li><p><code>main()</code> is a special function: we're allowed to omit the final <code>return 0;</code> and the compiler will insert that for us.</p>\n</li>\n<li><p>The printing loop is written twice - we could make a function to save repeating that.</p>\n</li>\n</ul>\n<p>Here's how I would write the array-printing function:</p>\n<pre><code>static void print_array(const char *title,\n const int *array, size_t length)\n{\n for (size_t i = 0; i &lt; length; ++i) {\n printf(&quot;%s[%zu]: %d\\n&quot;, title, i, array[i]);\n }\n}\n</code></pre>\n<p>Then in <code>main()</code>, we can replace the loops, like this:</p>\n<pre><code> print_array(&quot;data&quot;, dataset, length);\n</code></pre>\n\n<pre><code> print_array(&quot;return data&quot;, dataset, length);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T07:16:25.150", "Id": "531911", "Score": "1", "body": "@chux Fixed that - thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T05:56:24.803", "Id": "269489", "ParentId": "269484", "Score": "5" } }, { "body": "<p>In addition to <a href=\"https://codereview.stackexchange.com/a/269489/29485\">@Toby Speight</a> good answer:</p>\n<p><strong>Parameter order</strong></p>\n<p>Leading with the array size allows for better static code analysis and is self documenting.</p>\n<pre><code>// void get_devidable_int(int array_data[], int seperate_value,\n// int *array_length);\nvoid get_dividable_int(int *array_length, int array_data[*array_length],\n int separate_value);\n</code></pre>\n<p><strong>Error checks</strong></p>\n<p>I'd use the return value to indicate parameter problems:</p>\n<pre><code>// Return error flag\nint get_dividable_int(int *array_length, int array_data[*array_length],\n int separate_value) {\n if (array_length == NULL) return 1;\n if (*array_length &lt; 0) return 1; // Not needed with size_t *array_length\n if (*array_length &gt; 0 &amp;&amp; array_data == NULL) return 1;\n if (separate_value == 0) return 1;\n ...\n return 0;\n}\n</code></pre>\n<p><strong>Pathologically case: <code>separate_value == -1</code></strong></p>\n<p><code>INT_MIN % -1</code> is UB, yet mathematically <code>INT_MIN mod -1</code> is 0. A simple fix prevents that issue:</p>\n<pre><code> if (separate_value == -1) separate_value = 1;\n // or \n if (separate_value == -1) return 0; // As the array will not change.\n</code></pre>\n<p>I would not code <code>separate_value == abs(separate_value)</code> as that is UB with <code>separate_value == INT_MIN</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T04:55:19.760", "Id": "269597", "ParentId": "269484", "Score": "1" } }, { "body": "<h2>Comments</h2>\n<pre><code>/*******************************************************************************\n* Program\n*******************************************************************************/\n</code></pre>\n<p>Ask yourself, why is this comment necessary?</p>\n<p>On the other hand, look at just the (superfluous) declaration of</p>\n<pre><code>void get_devidable_int(int array_data[], int seperate_value, int *array_length);\n</code></pre>\n<p>What is missing here is info what this does and how to correctly use this function. Make it clear what the parameters mean and how they are used. Write a few sentences as comment to answer these questions. Make sure you write complete sentences! This makes sure the info is better and not just fragments of words that only help you and only at this moment to understand what this does. More an some of these aspects below.</p>\n<h2>Parameter <code>int seperate_value</code></h2>\n<p>The name for this is &quot;divisor&quot;, which tells everyone what this value is used for. It also suggests that it must not be zero.</p>\n<h2>Parameter <code>int array_data[]</code></h2>\n<p>This is actually the same as <code>int* array_data</code>, which makes it clear that this is a pointer to non-const data which is modified. This isn't immediately obvious when you call a function that's named &quot;get_...&quot;. Just for brevity, I'd also call this <code>numbers</code> and the according size just <code>length</code>. In general, &quot;data&quot; and similar things are rarely useful in a name.</p>\n<h2>Magic Numbers</h2>\n<pre><code>int dataset[6] = { 4, 16, 12, 64, 54, 33 };\nint length = sizeof(dataset) / sizeof(*dataset);\n</code></pre>\n<p>If you add an element, you will have to adjust the <code>6</code> as well. Just drop that value so that the compiler determines the size from the number of elements in the initializer list.\nIf you want a fixed size instead, declare the size as a constant up front and then use that to declare the array.</p>\n<h2>Sizeof Operator</h2>\n<p>There are two forms how <code>sizeof</code> is used:</p>\n<ul>\n<li>Applied to a type like <code>sizeof (type)</code>. The type (e.g. <code>int</code>) is put in parentheses here.</li>\n<li>Applied to an object like <code>sizeof object</code>. No need for parentheses here.</li>\n</ul>\n<p>I'd use <code>(sizeof array) / (sizeof *array)</code> to compute the size of an array.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T11:48:44.800", "Id": "269634", "ParentId": "269484", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T02:51:09.200", "Id": "269484", "Score": "3", "Tags": [ "c", "array" ], "Title": "Filter a list of integers to exact multiples of a given factor" }
269484
<p>This is my best attempt so far at a bash script argument parser written without GNU <code>getopt</code> or bash <code>getopts</code></p> <p>the first two functions, <code>usage</code> and <code>err</code> can be more or less ignored, but I plan on adding the ability to specify an exit code when calling <code>err</code>.</p> <p>Now for the first section of code in the <code>main</code> function:</p> <pre><code>shopt -s extglob args=() for (( i = 1; i &lt;= &quot;$#&quot;; i++ )); do arg=&quot;${!i}&quot; case &quot;${arg}&quot; in -[[:alpha:]?]+([[:alpha:]?])) for (( j = 1; j &lt; &quot;${#arg}&quot;; j++ )); do args+=(&quot;-${arg:j:1}&quot;) done ;; -[[:alpha:]]=*|--*=*) args+=(&quot;${arg%%=*}&quot;) args+=(&quot;${arg#*=}&quot;) ;; *) args+=(&quot;${arg}&quot;) ;; esac done set -- &quot;${args[@]}&quot; shopt -u extglob </code></pre> <p>This section de-concatenates flags and separates flags joined to their values with an <code>=</code>. as an example, <code>./script -xYz --test=value</code> would pop out as <code>./script -x -Y -z --test value</code>. Most of this could likely have been combined with the second part, but I think there's at least a little value in being able to access/save the intermediate form, and it made debugging easier. Single letter flags with <code>=</code> can also be processed, but as I understand it, this isn't an extremely common thing to see anyway. Flags that are already in the correct format, flags that could not be reformatted due to user error (<code>./script -xYz=value</code>, for instance), and positional parameters would both be passed to the second part without any modification. This hasn't caused any issues yet, but I am considering trying to further differentiate between good/bad input. at the very end, the reformatted args are <code>set</code> for later use.</p> <p>Part two of the <code>main</code> function:</p> <pre><code> args=() for (( i = 1; i &lt;= &quot;$#&quot;; i++ )); do arg=&quot;${!i}&quot; case &quot;${arg}&quot; in --) break ;; -*) case &quot;${arg}&quot; in -h|--help|-\?) usage ;; -x|-Y|-z) ;; -t|--type) arg2=&quot;${!i+1}&quot; if [[ -n &quot;${arg2}&quot; ]] &amp;&amp; [[ &quot;${arg2:0:1}&quot; != &quot;-&quot; ]]; then type=&quot;${arg2}&quot; (( i++ )) else err &quot;Invalid option: ${arg} requires an argument&quot; fi ;; -*) err &quot;Invalid option: ${arg}&quot; ;; esac ;; *) args+=(&quot;${arg}&quot;) esac done set -- &quot;${args[@]}&quot; </code></pre> <p>This is where flags and their values actually get processed. Flags (and their arguments, if applicable) are checked one at a time, but only unused positional parameters are put back in the array to be set once again. For example <code>./script -x -Y -z --test value hello world</code> would pop out as <code>./script hello world</code></p> <p>I did what I could to prevent any special cases slipping through, and to account for as many common formats as possible, but I couldn't find a list of either, so I'd really appreciate advice on both of those issues.</p> <p>I also have very little experience writing bash scripts, so general bash scripting advice would also be greatly appreciated.</p> <p>Full code:</p> <pre><code>#!/bin/bash usage() { echo &quot;help me&quot; exit 0 } err() { echo &quot;$*&quot; &gt;&amp;2 exit 1 } shopt -s extglob main() { shopt -s extglob args=() for (( i = 1; i &lt;= &quot;$#&quot;; i++ )); do arg=&quot;${!i}&quot; case &quot;${arg}&quot; in -[[:alpha:]?]+([[:alpha:]?])) for (( j = 1; j &lt; &quot;${#arg}&quot;; j++ )); do args+=(&quot;-${arg:j:1}&quot;) done ;; -[[:alpha:]]=*|--*=*) args+=(&quot;${arg%%=*}&quot;) args+=(&quot;${arg#*=}&quot;) ;; *) args+=(&quot;${arg}&quot;) ;; esac done set -- &quot;${args[@]}&quot; shopt -u extglob echo &quot;$0 $@&quot; args=() for (( i = 1; i &lt;= &quot;$#&quot;; i++ )); do arg=&quot;${!i}&quot; case &quot;${arg}&quot; in --) break ;; -*) case &quot;${arg}&quot; in -h|--help|-\?) usage ;; -x|-Y|-z) ;; -t|--type) arg2=&quot;${!i+1}&quot; if [[ -n &quot;${arg2}&quot; ]] &amp;&amp; [[ &quot;${arg2:0:1}&quot; != &quot;-&quot; ]]; then type=&quot;${arg2}&quot; (( i++ )) else err &quot;Invalid option: ${arg} requires an argument&quot; fi ;; -*) err &quot;Invalid option: ${arg}&quot; ;; esac ;; *) args+=(&quot;${arg}&quot;) esac done set -- &quot;${args[@]}&quot; echo &quot;$0 ${@:-No positional parameters set}&quot; echo &quot;test: ${test:-Test not set}&quot; } shopt -u extglob main &quot;$@&quot; </code></pre>
[]
[ { "body": "<p>I think this is pretty nicely written Bash.</p>\n<p>I see the parsing happens in two passes:</p>\n<ul>\n<li>Convert the argument list to some sort of canonical form</li>\n<li>Validate the argument list</li>\n</ul>\n<p>This is easy to understand and I think it makes sense.</p>\n<h3>Handling arguments after <code>--</code></h3>\n<p>As written, the program ignores all further arguments after <code>--</code>.</p>\n<p>The common practice is to take all arguments after <code>--</code> verbatim, without further parsing.\nFor example this behavior makes it possible to use the <code>rm</code> command to delete a file named <code>-f</code> if you ever need it. You would do that with <code>rm -- -f</code> instead of <code>rm -f</code> (which usually does nothing).</p>\n<h3>Keeping things &quot;simple&quot;</h3>\n<p>I'm not a fan of advanced features of Bash. I think they are pushing the limits of the language, and a common source of bugs, and code that's difficult to understand.</p>\n<p>Look at what <code>extglob</code> forces you to do:</p>\n<ul>\n<li><code>shopt -s extglob</code> before the declaration of <code>main</code> and cleaning up with <code>shopt -u extglob</code> after it, so that <code>main</code> can be parsed</li>\n<li>Then inside <code>main</code>, again <code>shopt -s extglob</code> before you need it, and cleaning up with <code>shopt -u extglob</code> when you no longer need it</li>\n</ul>\n<p>I find this double activation / deactivation dirty.</p>\n<p>If you gotta use it, you gotta use it. If I have a chance to do without it, I would. And here I see an opportunity. By reorganizing the conditions, you could achieve something similar:</p>\n<pre><code>args=()\nfor (( i = 1; i &lt;= $#; i++ )); do\n arg=&quot;${!i}&quot;\n case &quot;${arg}&quot; in\n -[[:alpha:]]=*|--*=*)\n args+=(&quot;${arg%%=*}&quot;)\n args+=(&quot;${arg#*=}&quot;) ;;\n --)\n for (( j = i; j &lt;= $#; j++ )); do\n args+=(&quot;${!j}&quot;)\n done\n break ;;\n --*)\n args+=(&quot;${arg}&quot;) ;;\n -*)\n for (( j = 1; j &lt; &quot;${#arg}&quot;; j++ )); do\n args+=(&quot;-${arg:j:1}&quot;)\n done ;;\n *)\n args+=(&quot;${arg}&quot;) ;;\n esac\ndone\nset -- &quot;${args[@]}&quot;\n</code></pre>\n<p>The difference from your original is that <code>-[[:alpha:]?]+([[:alpha:]?])</code> is replaced with simply <code>-*</code>. To put it simply, I think the practical implication is that an argument like <code>-c9</code> would be converted to <code>-c -9</code> instead of keeping it as <code>-c9</code>.</p>\n<p>I don't know if this would be acceptable to you. If yes, then you could get rid of all the <code>shopt</code>, and I think that would be a good thing.</p>\n<h3>shellcheck</h3>\n<p>As you are new to Bash, it's probably good to point out <a href=\"https://shellcheck.net\" rel=\"nofollow noreferrer\">shellcheck.net</a> (also available as a command line tool), a nice tool to check Bash code against common mistakes and bad practices.\nIt finds just a minor issue about <code>echo &quot;$0 $@&quot;</code>, where the recommended usage would be <code>echo &quot;$0 $*&quot;</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T19:04:25.513", "Id": "531745", "Score": "1", "body": "so instead of just ending the parse loop, everything after `--` should be just be passed without modification to be used as a positional parameter? That makes sense, and explains why `set --` behaves the way it does. That should also let me remove the nested case in part 2. are there any other special cases (like `--`) I may have missed?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T14:39:59.350", "Id": "269508", "ParentId": "269488", "Score": "1" } } ]
{ "AcceptedAnswerId": "269508", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T05:18:45.557", "Id": "269488", "Score": "3", "Tags": [ "parsing", "bash" ], "Title": "Bash argument parser with support for concatenated flags and '=' or ' ' between arguments and values" }
269488
<p>I'm learning and want to improve as much as possible. In doing so I have written this custom block that has an image on one side and an inner block on the other. It's using ACF to get the variables and comments should state most of the items.</p> <p>I'm looking for recommendations to improve, readability, functionality, or security issues I may not have addressed. I made an image function that should be responsive. Everything functions fine but I'd like to make it cleaner and <strong>faster</strong>.</p> <p>Looking forward to seeing recommendations - I want to improve in any way possible!</p> <p>First off the block file</p> <pre><code>&lt;?php /** * Two Column Block with Image &amp; Innerblock * * A two column block with innerblock on one side and image on the other * options of 50/50 and 40/60 sizes available * Can switch content sides and image is always on top * * @param function wg_child_acf_image_block() to return images output * @author Andrew */ $padding = get_field( 'padding' ); //Padding $top = get_field( 'top' ); //Custom padding top $bottom = get_field( 'bottom' ); //Custom Padding bottom $image = get_field( 'image' ); //Image field $sizing = get_field( 'sizing' ) ?: 'fiftyFifty'; //Select field that sets sizes to 50/50 or 40/60 $side = get_field( 'side' ) ?: 'normal'; //Switch Content Sides $combined = $sizing . ' ' . $side; //Combined for output $image_fallback = 'wg-align-image-left'; //Set Default Image alignment $inlineStyle = ''; //Create variable for optional custom padding $anchor = ''; //Create variable for custom anchor option $center = ''; //Create variable for align-self innerblock //Change default image alignment if reversed if( $side == 'reverse' ) { $image_fallback = 'wg-align-image-right'; } //Alignment of image w/ fallback $align_image = get_field( 'alignimage' ) ?: $image_fallback; //Determining Padding For Block - default is else if( 'narrow' == $padding ) { $padding = 'blockPadding-narrow'; } elseif( 'none' == $padding ) { $padding = 'blockPadding-none'; } elseif( 'custom' == $padding ) { $inlineStyle = 'style=&quot;padding-top: ' . $top . 'vh; padding-bottom: ' . $bottom . 'vh;&quot;'; $padding = false; } else { $padding = 'blockPadding'; } //Determines if padding is a class or inline and created classes array if( $padding ) { $classes = [$padding]; } else { $classes = []; } //Adds custom class if provided if( !empty( $block['className'] ) ) $classes = array_merge( $classes, explode( ' ', $block['className'] ) ); //Adds custom anchor if provided if( !empty( $block['anchor'] ) ) $anchor = ' id=&quot;' . sanitize_title( $block['anchor'] ) . '&quot;'; //Default data that goes inside innerblock when created but can be removed $template = array( array('core/heading', array( 'content' =&gt; 'Title Text Goes Here', )), array( 'core/paragraph', array( 'content' =&gt; 'Enter in your paragraph text here for further information', ) ) ); //Option to turn off align-self: center; if( get_field( 'center' ) == false ) { $center = ' center-self'; } //Opening Div - determines if class or inline for padding if( $inlineStyle ) { echo '&lt;section class=&quot;' . join( ' ', $classes ) . '&quot;' . esc_attr($anchor) . ' ' . esc_attr($inlineStyle) . '&gt;'; } else { echo '&lt;section class=&quot;' . join( ' ', $classes ) . '&quot;' . esc_attr($anchor) . '&gt;'; } ?&gt; &lt;div class=&quot;wrapper&quot;&gt; &lt;div class=&quot;twoColumns &lt;?php echo esc_attr($combined); ?&gt;&quot;&gt; &lt;div class=&quot;leftSide&quot;&gt; &lt;div class=&quot;imageWrap&quot;&gt; &lt;?php //arguments are image array, optional image class, optional image size ?&gt; &lt;?php wg_child_acf_image_block( $image, $align_image ); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class=&quot;rightSide&lt;?php if($center) { echo esc_attr($center); } ?&gt;&quot;&gt; &lt;?php echo '&lt;InnerBlocks template=&quot;' . esc_attr( wp_json_encode( $template ) ) . '&quot; /&gt;'; ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php //closing div echo '&lt;/section&gt;'; ?&gt; </code></pre> <p>Next is the image function which is used in the above file:</p> <pre><code>&lt;?php /** * Function to call ACF Image array and convert it to a SEO friendly image result * * Image function that takes an image array from ACF (or other similiar plugins) and * converts it into a responsive image. * Required argument of $image which is the array * Optional argument of $imageClass to pass an optional class * Optional argument of $imgsize that passes a different size iamge * * @param array $image uses ACF image array * @since 1.0.0 * @author: Andrew */ function wg_child_acf_image_block($image, $imageClass = '', $imgsize = 'large') { if( $image ) { // Image attribuates. $url = $image['url']; $title = $image['title']; $alt = $image['alt'] ?: $title; $caption = $image['caption']; $imgsize = 'large'; //adds w on the end of sizes $w = 'w'; // Image sizes and src sets. $thumb = $image['sizes'][ $imgsize ]; $width = $image['sizes'][ $imgsize . '-width' ]; $height = $image['sizes'][ $imgsize . '-height' ]; $medlg = $image['sizes']['medium_large']; $medlg_width = $image['sizes']['medium_large-width'] . $w; $med = $image['sizes']['medium']; $med_width = $image['sizes']['medium-width'] . $w; $tn = $image['sizes']['thumbnail']; $tn_width = $image['sizes']['thumbnail-width'] . $w; //Returned Result $result = ''; // Begin caption wrap. if( $caption ): $result .= '&lt;div class=&quot;wp-caption&quot;&gt;'; endif; //img item $result .= '&lt;img src=&quot;' . esc_url($thumb) . '&quot; srcset=&quot;' . esc_url($medlg) .' '. esc_attr($medlg_width) . ', ' . esc_url($med) . ' ' . esc_attr($med_width) . ', ' . esc_url($tn) . ' ' . esc_attr($tn_width) . '&quot; alt=&quot;' . esc_attr($alt) . '&quot; width=&quot;' . esc_attr($width) . '&quot; height=&quot;' . esc_attr($height) . '&quot; title=&quot;' . esc_attr($title) . '&quot; class=&quot;' . esc_attr($imageClass) . ' wg-image-class&quot; /&gt;'; // End caption wrap. if( $caption ): $result .= '&lt;p class=&quot;wp-caption-text&quot;&gt;' . esc_html($caption) . '&lt;/p&gt;'; $result .= '&lt;/div&gt;'; ?&gt; &lt;?php endif; ?&gt; &lt;?php //end if($image) statement } else { //Fallback image if no image $result = '&lt;img src=&quot;' . get_stylesheet_directory_uri() . '/assets/images/filler.jpg' . '&quot; alt=&quot;Filler Image&quot; class=&quot;' . esc_attr($imageClass) . ' wg-image-class&quot;&gt;'; } //Output the image echo $result; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T09:25:33.533", "Id": "532539", "Score": "0", "body": "it would be nice to group code into functions or into classes to make it easier to understand what is going on." } ]
[ { "body": "<ol>\n<li>Imagine, instead of having a long list of code within the block file, to read:</li>\n</ol>\n<pre><code>setDefaultImage()\nsetAlignment()\nsetPadding()\n\n//...\n</code></pre>\n<p>As a reviewer, I would see the key parts of what is happening without having to think about specific code. Should I want to know what specific function does, I can click into it.</p>\n<ol start=\"2\">\n<li>The long list of variables can also be extracted into parameter objects. Which can then be re-used in other files</li>\n</ol>\n<p>i.e.</p>\n<pre><code>$padding = get_field( 'padding' ); //Padding \n$top = get_field( 'top' ); //Custom padding top\n$bottom = get_field( 'bottom' ); \n\n// ...\n</code></pre>\n<p>Alternative</p>\n<pre><code>class ComponentParameters {\n string $padding;\n string $top;\n string $bottom;\n\n pubilc function toArray(): array {\n // ...\n }\n}\n\n</code></pre>\n<p>You can use php's built in function to extract array keys to variables.</p>\n<ol start=\"3\">\n<li><p>You keep mixing html and php in the code, I am referring to use of <code>&lt;?php endif; ?&gt;</code></p>\n</li>\n<li><p>How do you know that $image will have correct array format? What if someone makes a typo when calling that function?</p>\n</li>\n<li><p>The code under <code>//img item</code> is a very long string. Which requires reviewer to scroll to the right to see what's happening further on the right. This slows reviewer down by getting reviewer to think about scrolling to the right instead of building logic in the head.</p>\n</li>\n<li><p>How do you know that this code works? I dont know if you have it already, but it would be worth adding one to make your code future proof. Just check for inputs and outputs would make it easier to refactor and more stable.</p>\n</li>\n<li><p>You can use early returns to prevent arrow pattern</p>\n</li>\n</ol>\n<p>i.e.</p>\n<pre><code>\nfunction wg_child_acf_image_block(...) { \n if (!$image) {\n return '&lt;img src=&quot;' . get_stylesheet_directory_uri() . '/assets/images/filler.jpg' . '&quot; alt=&quot;Filler Image&quot; class=&quot;' . esc_attr($imageClass) . ' wg-image-class&quot;&gt;';\n }\n\n // ...\n}\n</code></pre>\n<hr />\n<p>Those are just some suggestions. The scale of refactoring is dependant on the scale of your application. If it's a large scale critical code, you may want to refactor even further. However, majority of WordPress packages look similar to what you've sent.</p>\n<p>Also, wordpress is not so friendly towards latest practices on how to do both OOP and Functional code nor does it support the latest PHP functionality due to it's core, still stuck within PHP 5.*. There are some hacky ways around it, maybe there are now out of the box solutions for this (the last time I worked with WordPress was over a year ago)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-07T09:52:44.997", "Id": "269843", "ParentId": "269492", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T06:24:54.827", "Id": "269492", "Score": "1", "Tags": [ "php", "wordpress" ], "Title": "Custom Block with ACF in WordPress" }
269492
<p>The goal is to write a decorator that allows you to define &quot;indexer proxies&quot;, which define properties with <code>__getindex__</code> instead of normal method calls, like <code>loc</code> and <code>iloc</code> in <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer">Pandas dataframes</a>.</p> <p>To that end I ended up with a descriptor constructing an inner class with the transformed <code>__getindex__</code>, an instance of which is then constructed in <code>__get__</code>:</p> <pre class="lang-py prettyprint-override"><code>from functools import wraps class locator: def __init__(self, getter): class LocatorProxy: def __init__(self, obj): self.obj = obj @wraps(getter) def __getitem__(self, key): return getter(self.obj, key) self.proxy_class = LocatorProxy def __get__(self, obj, objtype=None): return self.proxy_class(obj) </code></pre> <p>Example usage:</p> <pre class="lang-py prettyprint-override"><code>In [41]: class Foo: ...: def __init__(self, **vals): ...: self.vals = vals ...: @locator ...: def loc(self, key): ...: &quot;&quot;&quot;Return important stuff&quot;&quot;&quot; ...: return self.vals[key] ...: In [42]: Foo(x = 1, y = 10).loc[&quot;y&quot;] Out[42]: 10 In [43]: Foo(x = 1, y = 10).loc[&quot;z&quot;] --------------------------------------------------------------------------- KeyError Traceback (most recent call last) &lt;ipython-input-43-d91ef97fd1fe&gt; in &lt;module&gt; ----&gt; 1 Foo(x = 1, y = 10).loc[&quot;z&quot;] &lt;ipython-input-40-ca29fed22d1f&gt; in __getitem__(self, key) 9 @wraps(getter) 10 def __getitem__(self, key): ---&gt; 11 return getter(self.obj, key) 12 13 self.proxy_class = LocatorProxy &lt;ipython-input-41-fb4c4b7f731c&gt; in loc(self, key) 5 def loc(self, key): 6 &quot;&quot;&quot;Return important stuff&quot;&quot;&quot; ----&gt; 7 return self.vals[key] 8 KeyError: 'z' In [44]: Foo(x = 1, y = 10).loc[&quot;x&quot;] Out[44]: 1 </code></pre> <p>I'd like to know whether this is an idiomatic usage of descriptors. Is this the right way to avoid unnecessary allocations/definitions of the inner class as much as possible? <em>Does</em> <code>@wraps</code> do the right thing? Can I do anything useful with <code>__set_name__</code>?</p> <p>Only the getters are needed in my case, so no <code>.setter</code> thing like <code>property</code> has it is necessary for now, although it would be nice to see how it's done.</p>
[]
[ { "body": "<blockquote>\n<p>Is this the right way to avoid unnecessary allocations/definitions of the inner class as much as possible?</p>\n</blockquote>\n<p>This smells like premature optimization. If you actually care about every microsecond, you shouldn't be doing any of this, and should just have regular class methods.</p>\n<p>That said, no, your approach doesn't avoid as many allocations as it could. Rather than one allocation per <code>__get__</code>, you can restructure your code to have one allocation per <code>@locator</code> decorator instance.</p>\n<blockquote>\n<p>Does <code>@wraps</code> do the right thing?</p>\n</blockquote>\n<p>Probably, but it isn't strictly needed.</p>\n<p>The following suggested code has no nested class definitions, no class definitions in closure scope, no <code>@wraps</code> calls, and attempts to brow-beat mypy into understanding your types. This last part is only partially successful.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import Any, Callable, Generic, Optional, Type, TypeVar\n\nInstanceType = Any # mypy is too stupid to infer this type as a generic\nKeyType = TypeVar('KeyType')\nValueType = TypeVar('ValueType')\nLocatorCallback = Callable[[InstanceType, KeyType], ValueType]\n\n\nclass LocatorProxy(Generic[KeyType, ValueType]):\n __slots__ = ('method', 'instance')\n\n def __init__(self, method: 'LocatorCallback'):\n self.method = method\n self.instance: Optional[InstanceType] = None\n\n def __getitem__(self, item: KeyType) -&gt; ValueType:\n assert self.instance is not None\n return self.method(self.instance, item)\n\n\nclass locator(Generic[KeyType, ValueType]):\n __slots__ = ('proxy_class',)\n\n def __init__(self, method: LocatorCallback) -&gt; None:\n self.proxy_class = LocatorProxy[KeyType, ValueType](method)\n\n def __get__(\n self,\n instance: InstanceType,\n owner: Optional[Type[InstanceType]] = None,\n ) -&gt; LocatorProxy:\n self.proxy_class.instance = instance\n return self.proxy_class\n\n\nclass Foo:\n def __init__(self, **vals: int) -&gt; None:\n self.vals = vals\n\n loc: LocatorProxy[str, int]\n\n @locator # type: ignore # you really need to shoehorn this thing in\n def loc(self, key: str) -&gt; int:\n return self.vals[key]\n\n\ndef test() -&gt; None:\n foo = Foo(x=1, y=10)\n l = foo.loc\n assert l[&quot;y&quot;] == 10\n\n try:\n l[&quot;z&quot;]\n raise AssertionError()\n except KeyError:\n pass\n\n\nif __name__ == '__main__':\n test()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T09:35:03.287", "Id": "531770", "Score": "0", "body": "Is the apparently superfluous `loc: LocatorProxy[str, int]` in `Foo` also there only to satisfy mypy?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T14:06:12.400", "Id": "531798", "Score": "0", "body": "@phipsgabler Basically yes. In the end it is handy to have this even if you don't use mypy - for example, PyCharm can then successfully statically analyse your code, meaningfully offer member dropdowns, etc." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T16:34:57.113", "Id": "269516", "ParentId": "269496", "Score": "2" } } ]
{ "AcceptedAnswerId": "269516", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T09:00:39.863", "Id": "269496", "Score": "2", "Tags": [ "python", "properties" ], "Title": "Pandas-style \"indexer proxy\" descriptor" }
269496
<p>I created a service for Connection Pooling. And PluginAuth Class will handle those transaction to be send in the server. Is my code structure correct?</p> <pre><code>public class ConnectionPoolingService { private static final Logger LOGGER = LoggerFactory.getLogger(ConnectionPoolingService.class); public static final String CONTENT_TYPE = &quot;Content-Type&quot;; private static CloseableHttpClient client; private static final CookieStore commonCookieStore = new BasicCookieStore(); private static final ScheduledExecutorService cleanUpThread = MDScheduledExecutorService.wrap( new ScheduledThreadPoolExecutor(1), &quot;connection-pool-cleanup-thread-%d&quot;); public ConnectionPoolingServiceImpl(String keyStoreId) { init(keyStoreId); } private void init(String keyStoreId) { try { if (client == null) { if (!Util.isNullEmptyOrWhitespace(keyStoreId)) { SSLConnectionSocketFactory sslConSocFactory = new SSLConnectionSocketFactory(TLSSocketFactoryCache.getInstance().get(keyStoreId), SSLConnectionSocketFactory.getDefaultHostnameVerifier()); Registry&lt;ConnectionSocketFactory&gt; socketFactoryRegistry = RegistryBuilder.&lt;ConnectionSocketFactory&gt;create() .register(&quot;https&quot;, sslConSocFactory).build(); RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(1000) .setConnectionRequestTimeout(1000) .setSocketTimeout(1000) .build(); ConnectionKeepAliveStrategy keepAliveStrategy = new ConnectionKeepAliveStrategy() { public long getKeepAliveDuration(HttpResponse response, HttpContext context) { // Honor 'keep-alive' header HeaderElementIterator it = new BasicHeaderElementIterator( response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); String param = he.getName(); String value = he.getValue(); if (value != null &amp;&amp; param.equalsIgnoreCase(&quot;timeout&quot;)) { try { return Long.parseLong(value) * 1000; } catch(NumberFormatException ignore) { // ignore } } } try { return 60000; } catch(NumberFormatException ignore) { // ignore } // otherwise keep alive for 60 seconds return 60 * 1000; } }; PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); connectionManager.setDefaultMaxPerRoute(200); connectionManager.setMaxTotal(200); connectionManager.setValidateAfterInactivity(60000); client = HttpClients.custom().setConnectionManager(connectionManager) .setConnectionManagerShared(true) .setDefaultRequestConfig(requestConfig) .setKeepAliveStrategy(keepAliveStrategy) .setConnectionReuseStrategy(new DefaultConnectionReuseStrategy()) .setUserTokenHandler(context -&gt; null) .setMaxConnTotal(200) .setMaxConnPerRoute(200) .setConnectionTimeToLive(60000, TimeUnit.MILLISECONDS) .build(); int closeIdle = 60000; cleanUpThread.scheduleAtFixedRate(() -&gt; { try { connectionManager.closeExpiredConnections(); connectionManager.closeIdleConnections(closeIdle, TimeUnit.MILLISECONDS); } catch (Exception ex) { LOGGER.error(&quot;Exception on SGW clean up thread&quot;, ex); } }, closeIdle, closeIdle, TimeUnit.MILLISECONDS); } else { LOGGER.error(&quot;Error! No keystore specified, auth param: {}&quot;, AuthParamNames.SSL_KEY_TRUST_STORE_ID); } } } catch (Exception e) { LOGGER.error(&quot;Encountered exception during retrieval of SSL Context&quot;, e); } } public Either&lt;String, String&gt; sendRequest(String request, String url) throws IOException { String responseString = &quot;&quot;; try { HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new StringEntity(request)); httpPost.setHeader(CONTENT_TYPE, &quot;application/xml&quot;); HttpClientContext context = HttpClientContext.create(); context.setCookieStore(commonCookieStore); CloseableHttpResponse response = client.execute(httpPost, context); LOGGER.info(&quot;Request sent to {}&quot;, url); int responseStatus = response.getStatusLine().getStatusCode(); HttpEntity respEntity = response.getEntity(); responseString = EntityUtils.toString(respEntity); if (HttpStatusCodes.STATUS_CODE_OK == responseStatus) { LOGGER.debug(&quot;Response received from background auth server.&quot;); return Either.left(responseString); } else { return Either.right(String.valueOf(responseStatus)); } } catch (Exception e) { throw e; } } public static void cleanup() { cleanUpThread.shutdownNow(); } } public class PluginAuth { private ConnectionPoolingServiceImpl connectionPoolingService; public PluginAuth(String keyStoreId) { initAuth(keyStoreId); } private void initAuth(String keyStoreId) { connectionPoolingService = new ConnectionPoolingServiceImpl(keyStoreId); } private String processTransaction(String request, String url) { String responseString = &quot;&quot;; try { Either&lt;String, String&gt; result = connectionPoolingService.sendRequest(request, url); if (result.isLeft()) { responseString = result.left().value(); LOGGER.debug(&quot;Response received from server.&quot;); } else if (result.isRight()) { //throw exeception? } } catch (Exception e) { throw e; } return responseString; } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T09:31:49.377", "Id": "269497", "Score": "1", "Tags": [ "java" ], "Title": "Connection pooling service using PoolingHttpClientConnectionManager" }
269497
<p>This is the code I came across in our repository. This performs search in-memory and is invoked on service layer code.</p> <p>In our front end operators like <code>EQUAL_TO</code> and so on are passed with field name and field values are passed as list of parameters in the query.</p> <p>This is autowired and passed in the service calls like so</p> <pre><code>return paginate(SearchEngine.search(pgRatingResponses, operator, fieldName, fieldValues), pageable); </code></pre> <pre><code> public class SearchEngine { /** * Valid pattern. */ private static final String REGEX = &quot;^[A-Z_a-z0-9 ]*$&quot;; /** * Searches of records. * * @param records * @param operator * @param fieldName * @param fieldValues * @param &lt;T&gt; * @return */ public &lt;T&gt; List&lt;T&gt; search(final List&lt;T&gt; records, final SearchOperator operator, final String fieldName, final List&lt;String&gt; fieldValues) { List&lt;T&gt; results = new ArrayList&lt;&gt;(); if (Objects.nonNull(records) &amp;&amp; Objects.nonNull(operator) &amp;&amp; Objects.nonNull(fieldName) &amp;&amp; StringUtils.hasLength(fieldName) &amp;&amp; Objects.nonNull(fieldValues) &amp;&amp; !fieldValues.isEmpty() &amp;&amp; !records.isEmpty()) { switch (operator) { case EQUAL_TO: results = records.stream() .filter(record -&gt; fieldValues.stream().filter(Objects::nonNull).map(String::trim) .filter(StringUtils::hasLength).distinct() .filter(fieldValue -&gt; Pattern.matches(REGEX, fieldValue)) .anyMatch(fieldValue -&gt; isEqual(fieldName.trim(), fieldValue, record))) .collect(Collectors.toList()); break; case NOT_EQUAL_TO: results = records.stream() .filter(record -&gt; fieldValues.stream().filter(Objects::nonNull).map(String::trim) .filter(StringUtils::hasLength).distinct() .filter(fieldValue -&gt; Pattern.matches(REGEX, fieldValue)) .allMatch(fieldValue -&gt; !isEqual(fieldName.trim(), fieldValue, record))) .collect(Collectors.toList()); break; case CONTAINS: results = records.stream() .filter(record -&gt; fieldValues.stream().filter(Objects::nonNull).map(String::trim) .filter(StringUtils::hasLength).distinct() .filter(fieldValue -&gt; Pattern.matches(REGEX, fieldValue)) .anyMatch(fieldValue -&gt; contains(fieldName.trim(), fieldValue, record))) .collect(Collectors.toList()); break; case DOES_NOT_CONTAIN: results = records.stream() .filter(record -&gt; fieldValues.stream().filter(Objects::nonNull).map(String::trim) .filter(StringUtils::hasLength).distinct() .filter(fieldValue -&gt; Pattern.matches(REGEX, fieldValue)) .allMatch(fieldValue -&gt; !contains(fieldName.trim(), fieldValue, record))) .collect(Collectors.toList()); break; default: throw new IllegalArgumentException(ErrorConstants.PARAMETER_VALUE_MISMATCHING); } } else if (Objects.nonNull(records)) { results = records; } return results; } /** * Checks for equality. * * @param &lt;T&gt; * @param fieldName * @param fieldValue * @param record * @return */ private &lt;T&gt; boolean isEqual(final String fieldName, final String fieldValue, final T record) { try { for (Field field : record.getClass().getDeclaredFields()) { field.setAccessible(true); if (field.getName().equals(fieldName) &amp;&amp; Objects.nonNull(field.get(record))) { if (field.getType().equals(String.class)) { return field.get(record).toString().trim().equalsIgnoreCase(fieldValue); } else { return field.get(record).equals(fieldValue); } } } } catch (IllegalArgumentException | IllegalAccessException e) { log.error(ErrorConstants.PARAMETER_VALUE_MISMATCHING + e.getLocalizedMessage()); } return false; } /** * Checks for pattern matchings. * * @param &lt;T&gt; * @param fieldName * @param fieldValue * @param record * @return */ private &lt;T&gt; boolean contains(final String fieldName, final String fieldValue, final T record) { try { for (Field field : record.getClass().getDeclaredFields()) { field.setAccessible(true); if (field.getName().equals(fieldName) &amp;&amp; Objects.nonNull(field.get(record))) { return Pattern.matches(&quot;.*&quot; + fieldValue.toLowerCase() + &quot;.*&quot;, field.get(record).toString().trim().toLowerCase()); } } } catch (IllegalArgumentException | IllegalAccessException e) { log.error(ErrorConstants.PARAMETER_VALUE_MISMATCHING + e.getLocalizedMessage()); } return false; } } </code></pre>
[]
[ { "body": "<p>Welcome to Stack Review, the first thing I noticed in your <code>search</code> function code is the <em>if else</em> chain (note: I reduced all present conditions to the first two) :</p>\n<pre><code>List&lt;T&gt; results = new ArrayList&lt;&gt;();\nif (Objects.nonNull(records) &amp;&amp; Objects.nonNull(operator)) { \n /* here the switch code that calculates results*/\n} else if (Objects.nonNull(records)) {\n results = records;\n }\nreturn results;\n</code></pre>\n<p>This can be expressed in a more comfortable way like below :</p>\n<pre><code>if (Objects.nonNull(records) &amp;&amp; Objects.nonNull(operator)) { /* here the switch code */\n}\n\nif (Objects.nonNull(records)) { \n return records;\n}\nreturn Collections.emptyList();\n</code></pre>\n<p>Your switch code can be refactored isolating the common stream part like below:</p>\n<pre><code>Stream&lt;String&gt; stream = fieldValues.stream()\n .filter(Objects::nonNull).map(String::trim)\n .filter(StringUtils::hasLength).distinct()\n .filter(fieldValue -&gt; Pattern.matches(REGEX, fieldValue));\n</code></pre>\n<p>Then you can switch over the <code>.anyMatch</code>and <code>allMatch</code>, applying them and return directly your list result.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T15:52:39.203", "Id": "269514", "ParentId": "269499", "Score": "1" } }, { "body": "<h3>Surprising behavior</h3>\n<p>The <code>search</code> function does some validations up front.\nIf any of the validation fails, then it will return <code>records</code> if it's not null, or else a new empty list.\nReturning <code>records</code> practically means that everything is matched.\nSo everything will be returned when for example:</p>\n<ul>\n<li>operator is null</li>\n<li>the field name is null</li>\n<li>the field name is empty</li>\n<li>the field values list is null</li>\n<li>the field values list is empty</li>\n</ul>\n<p>I find this surprising behavior.\nI would have expected either an empty list (no matches), or <code>IllegalArgumentException</code> in these cases.</p>\n<h3>Contradiction in the logic</h3>\n<p>As mentioned earlier, when the field values list is empty,\nit's considered that everything matched.\nHowever, when this list is not empty but contains only null, empty, or blank strings, then when the operator is applied using <code>anyMatch</code> filters,\nthen nothing will match.</p>\n<p>This seems to contradict the intention of the initial validations.\nI think the initial validation should be improved to make the logic more consistent,\nbut beware, this will change the behavior.</p>\n<h3>Avoid duplicated logic</h3>\n<p>As another answer already pointed out,\nthe cases of the switch statement have a lot of duplicated logic,\nwhich should be eliminated.\nGoing a bit further as the other answer,\nI would write like this:</p>\n<pre><code>String trimmedFieldName = fieldName.trim();\n\nStream&lt;String&gt; stream = fieldValues.stream()\n .filter(Objects::nonNull)\n .map(String::trim)\n .filter(StringUtils::hasLength)\n .distinct()\n .filter(fieldValue -&gt; VALID_VALUE_PATTERN.matcher(fieldValue).matches());\n\nPredicate&lt;T&gt; predicate = switch (operator) {\n case EQUAL_TO -&gt; record -&gt; stream.anyMatch(fieldValue -&gt; isEqual(trimmedFieldName, fieldValue, record));\n case NOT_EQUAL_TO -&gt; record -&gt; stream.noneMatch(fieldValue -&gt; isEqual(trimmedFieldName, fieldValue, record));\n case CONTAINS -&gt; record -&gt; stream.anyMatch(fieldValue -&gt; contains(trimmedFieldName, fieldValue, record));\n case DOES_NOT_CONTAIN -&gt; record -&gt; stream.noneMatch(fieldValue -&gt; contains(trimmedFieldName, fieldValue, record));\n default -&gt; throw new IllegalArgumentException(ErrorConstants.PARAMETER_VALUE_MISMATCHING);\n};\n\nreturn records.stream()\n .filter(predicate)\n .collect(Collectors.toList());\n</code></pre>\n<h3>Do not create <code>ArrayList</code> for nothing</h3>\n<p>The <code>search</code> method creates an <code>ArrayList</code> up front.\nThis <code>ArrayList</code> is returned in the case when a validation fails and <code>records</code> is <code>null</code>, otherwise it's not used in any of the execution paths.\nUse <code>Collections.emptyList()</code> instead of creating <code>ArrayList</code>.</p>\n<h3>Use <code>Pattern.compile</code> instead of <code>Pattern.matches</code></h3>\n<p>When matching a pattern repeatedly, it's good to compile it, so that the matching can be performed faster. So instead of:</p>\n<blockquote>\n<pre><code>private static final String REGEX = &quot;^[A-Z_a-z0-9 ]*$&quot;;\n\n// ...\n\nfieldValue -&gt; Pattern.matches(REGEX, fieldValue)\n</code></pre>\n</blockquote>\n<p>Do like this:</p>\n<pre><code>private static final Pattern VALID_VALUE_PATTERN = Pattern.compile(&quot;^[A-Z_a-z0-9 ]*$&quot;);\n\n// ...\n\nfieldValue -&gt; VALID_VALUE_PATTERN.matcher(fieldValue).matches()\n</code></pre>\n<p>Notice that I also took this opportunity to use a name to describe the purpose of the pattern.</p>\n<h3>Consider <code>noneMatch</code></h3>\n<p>Instead of:</p>\n<blockquote>\n<pre><code>stream().allMatch(x -&gt; !foo(x, y))\n</code></pre>\n</blockquote>\n<p>It's more natural to write:</p>\n<pre><code>stream().noneMatch(x -&gt; foo(x, y))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T19:24:53.000", "Id": "269523", "ParentId": "269499", "Score": "2" } } ]
{ "AcceptedAnswerId": "269523", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T09:50:36.130", "Id": "269499", "Score": "3", "Tags": [ "java", "search", "reflection", "spring" ], "Title": "Search code that performs in-memory search" }
269499
<p>I want to read <code>\n</code> terminated, UTF-8 encoded lines from a network connection and process each full line. I cannot use <code>fgets</code>, because that function does not support nonblocking IO, which I want to use.</p> <p>I currently have the following code, but it looks a bit too confusing to me. Some tips on how to simplify the code would be appreciated.</p> <pre><code>#include &lt;array&gt; #include &lt;string.h&gt; // Read lines from a non-blocking reader (e.g. an O_NONBLOCK socket). // Every complete line is sent to a consumer function, without a newline or null terminator. // Lines larger than BufSize are silently discarded. // // Reader should have approximately this signature: // ssize_t reader(void *buffer, size_t maxSize); // Should return 0 on EOF, -1 on error, otherwise the number of read bytes. // In practice, this should just call read() on a file descriptor. // Consumer should have approximately this signature: // void consumer(const char *start, size_t size); template&lt;size_t BufSize&gt; class LineBuffer { std::array&lt;char, BufSize&gt; _buffer; size_t _bytesBuffered {0}; size_t _bytesConsumed {0}; bool _discardLine {false}; public: template&lt;typename Reader, typename Consumer&gt; size_t readLines(const Reader&amp; reader, const Consumer&amp; consumer) { char *buf = _buffer.data(); while (true) { auto bytesRead = reader(buf + _bytesBuffered, _buffer.size() - _bytesBuffered); if (bytesRead &lt;= 0) { return bytesRead; } _bytesBuffered += bytesRead; char* separator = nullptr; do { char* lineStart = buf + _bytesConsumed; separator = static_cast&lt;char*&gt;(memchr( lineStart, '\n', _bytesBuffered - _bytesConsumed)); if (separator) { size_t lineLength = separator - lineStart; if (!_discardLine) { consumer(lineStart, lineLength); } _bytesConsumed += lineLength + 1; _discardLine = false; } } while (separator); resetBuffer(); } } private: void resetBuffer() { size_t bytesRemaining = _bytesBuffered - _bytesConsumed; if (bytesRemaining == _buffer.size()) { // line too long _discardLine = true; _bytesBuffered = 0; _bytesConsumed = 0; } else if (bytesRemaining &gt; 0 &amp;&amp; _bytesConsumed &gt; 0) { // move the last partial message to the front of the buffer, so a full-sized // message will fit memmove(_buffer.data(), _buffer.data() + _bytesConsumed, bytesRemaining); _bytesBuffered = bytesRemaining; _bytesConsumed = 0; } } }; // Small test #include &lt;iostream&gt; #include &lt;string&gt; LineBuffer&lt;16&gt; buffer; void feed(const char *testData) { auto end = testData + strlen(testData); buffer.readLines( [&amp;](void *buf, size_t maxSize) { auto size = std::min((ssize_t) maxSize, end - testData); memcpy(buf, testData, size); testData += size; return size; }, [](const char *line, size_t size) { std::cout &lt;&lt; std::string {line, size} &lt;&lt; std::endl; }); } int main() { // expected output: one, two, three, four, five, 0123456789abcde. feed(&quot;one\ntwo\n&quot;); feed(&quot;thr&quot;); feed(&quot;ee\n&quot;); feed(&quot;four\nThis line should be discarded, because it is too long.\n&quot;); feed(&quot;five\n0123456789abcde\n&quot;); } </code></pre>
[]
[ { "body": "<pre><code> if (bytesRead &lt;= 0) {\n return bytesRead;\n }\n</code></pre>\n<p>How can an unsigned type be less than zero?</p>\n<pre><code>static_cast&lt;char*&gt;(memchr(\n</code></pre>\n<p>Why aren't you using std algorithms? You want to find the '\\n' character in the text, right? That just <code>std::find(begin_iterator, end_iterator, '\\n')</code>. No casting.</p>\n<pre><code>memmove(_buffer.data(), _buffer.data() + _bytesConsumed, bytesRemaining);\n</code></pre>\n<p>again, use <code>std::copy</code> or <code>copy_n</code>, not <code>memmove</code>.</p>\n<p>For whatever functions you do use, include the proper headers for them. I see you have <code>&lt;string.h&gt;</code> but you should not use the C headers in C++. Use <code>&lt;cstring&gt;</code> instead.</p>\n<p><a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#slio50-avoid-endl\" rel=\"nofollow noreferrer\">⧺SL.io.50</a> Don't use <code>endl</code>.</p>\n<p>If you are expecting this to be launched using <code>async</code> or similar, and it runs until the stream is closed or errored or whatever, then returning a value is not very useful: who are you returning it to? As noted earlier, it will <em>always</em> return 0, so it's useless to have this return value.</p>\n<hr />\n<p>I don't understand how your loop works.</p>\n<pre><code>do {\n // read stuff\n if (separator) { ... }\nwhile (separator);\n</code></pre>\n<p>I thought it would keep reading until it found the end-of-line, but this keeps looping until it <em>doesn't</em> read something with a linebreak.</p>\n<p>I agree it's complex, because of your looping and condition structure. You have state variables that need to be understood in order to understand the flow. It could be written in a simpler way as a single loop with clearer conditions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T14:50:50.263", "Id": "531734", "Score": "0", "body": "As I understand it from the comments at the start of the program, `auto bytesRead = reader(...)` is expected to return a `ssize_t` which is a signed type and can be negative." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T14:53:51.570", "Id": "531736", "Score": "0", "body": "So the return type of readLines should match that, since it's the only return statement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T14:57:25.123", "Id": "531737", "Score": "0", "body": "Yes, that is correct. (It was not apparent to me if your point is about the signed-ness of `bytesRead` or about the signed-ness of the return type of the function.)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T14:24:36.433", "Id": "269507", "ParentId": "269503", "Score": "2" } } ]
{ "AcceptedAnswerId": "269507", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T11:29:20.037", "Id": "269503", "Score": "2", "Tags": [ "c++" ], "Title": "Reading lines from a non-blocking reader" }
269503
<p>Would love some feedback on this simple API implementation with Ruby on Rails. Have I used proper naming conventions, readable/manageable code, optimal approaches, etc? As I'm still learning Ruby on rails, I'd love to hear what other fellow engineers have to say about this :)</p> <p><strong>A simple Register API:</strong></p> <pre><code>require 'net/http' require 'uri' require 'json' class V1::UsersController &lt; ApplicationController protect_from_forgery with: :null_session def register name = params[:name] email = params[:email] password = params[:password] @existing_user = User.find_by(email: params[:email]) if @existing_user == nil @user = User.new( name: name, email: email, password: password, plan: &quot;FREE&quot; ) #save user if @user.save! #generate auth token @auth = save_new_auth @user.id render :json =&gt; { :user =&gt; @user.as_json(:except =&gt; [:created_at, :updated_at, :password, :stripe_id, :subscription_id, :id, :email]), :auth =&gt; @auth } else render json: {&quot;error&quot; =&gt; &quot;Unprocessable Entity&quot;} end else render json: { error: { type: &quot;UNAUTHORIZED&quot;, message: &quot;Looks like you already have an account. Please login &quot; } }, status: 403 end end </code></pre> <p><strong>Login API:</strong></p> <pre class="lang-rb prettyprint-override"><code>def login email = params[:email] password = params[:password] @auth = nil @user = User.find_by(email: params[:email], password: password) if @user == nil render json: { error: { type: &quot;UNAUTHORIZED&quot;, message: &quot;Invalid Login Credentials &quot; } }, status: 401 else @auth = UserAuth.find_by(user_id: @user.id) if @auth == nil @auth = save_new_auth @user.id end render :json =&gt; { :user =&gt; @user.as_json(:except =&gt; [:created_at, :updated_at, :password, :stripe_id, :subscription_id, :id, :email]), :auth =&gt; @auth } end end </code></pre> <p><strong>Access token Generator:</strong></p> <pre class="lang-rb prettyprint-override"><code>def save_new_auth (user_id) @auth = UserAuth.new( access_token: generate_token, user_id: user_id, status: true ) @auth.save return @auth end def generate_token(size = 28) charset = %w{ 2 3 4 6 7 9 A C D E F G H J K M N P Q R T V W X Y Z} (0...size).map{ charset.to_a[rand(charset.size)] }.join end </code></pre>
[]
[ { "body": "<p>Here are a couple of suggestions</p>\n<h1>Non default CRUD action in Controller</h1>\n<p>It's generally recommended to only have CRUD actions <code>index, show, new, edit, create, update, destroy</code> in your controllers. So e.g. you should think about renaming your <code>register</code> and <code>login</code> actions and extract according controllers.</p>\n<p>For example you could have a <code>UserRegistrationsController</code> and a <code>UserLoginsController</code> which each have a <code>create</code> action.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class V1::UserRegistrationsController &lt; ApplicationController\n def create\n end\nend\n\nclass V1::UserLoginsController &lt; ApplicationController\n def create\n end\nend\n</code></pre>\n<p>Here is a good blog article explaining this concept\n<a href=\"http://jeromedalbert.com/how-dhh-organizes-his-rails-controllers/\" rel=\"nofollow noreferrer\">http://jeromedalbert.com/how-dhh-organizes-his-rails-controllers/</a></p>\n<h1>Handling user not found</h1>\n<p>Instead of using <code>find_by</code> you could use the bang method <code>find_by!</code> which will raise a <code>RecordNotFound </code> error.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>User.find_by!(email: params[:email])\n</code></pre>\n<p>Now <code>RecordNotFound</code> errors will get automatically translated to a 404 response code. But you could overwrite the default behaviour as well with your own exception app or <code>rescue_from</code></p>\n<p><a href=\"https://github.com/rails/rails/blob/main/actionpack/lib/action_dispatch/middleware/public_exceptions.rb#L14\" rel=\"nofollow noreferrer\">https://github.com/rails/rails/blob/main/actionpack/lib/action_dispatch/middleware/public_exceptions.rb#L14</a>\n<a href=\"https://stackoverflow.com/questions/62843373/how-to-deal-with-general-errors-in-rails-api/62846970#62846970\">https://stackoverflow.com/questions/62843373/how-to-deal-with-general-errors-in-rails-api/62846970#62846970</a></p>\n<p>Another possibility is to add a validation with scope so you can only have one email address.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class V1::UserRegistrationsController &lt; ApplicationController\n def create\n @user = User.new(\n name: name,\n email: email,\n password: password,\n plan: &quot;FREE&quot;\n )\n\n if @user.save\n render @user\n else\n render @user.errors\n end\n end\n</code></pre>\n<h1>Strong parameters</h1>\n<p>User strong parameters instead of plucking the values from the params hash.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>der user_params\n params.require(:user).permit(:email, :password, :name)\nend\n</code></pre>\n<p><a href=\"https://edgeguides.rubyonrails.org/action_controller_overview.html#strong-parameters\" rel=\"nofollow noreferrer\">https://edgeguides.rubyonrails.org/action_controller_overview.html#strong-parameters</a></p>\n<h1>Use a PORO or Service object</h1>\n<p>A lot of people will have different opinions of using a Plain Old Ruby Object vs a Service object etc. But I think a lot of people would agree that it's a good idea to move logic from the controller to a dedicated object.</p>\n<p>Example</p>\n<pre><code>class UserRegistration\n def self.create(params)\n new(params).save\n end\n\n def initialize(params)\n @params = params\n end\n\n def save\n user = create_user\n auth = UserAuth.new(\n access_token: generate_token,\n user_id: user.id,\n status: true\n )\n auth if auth.save\n end\n\n private\n\n attr_reader :params\n\n def create_user\n User.create(\n name: params[:name],\n email: params[:email],\n password: params[:password],\n plan: &quot;FREE&quot;\n )\n end\n\n def generate_token(size = 28)\n charset = %w{ 2 3 4 6 7 9 A C D E F G H J K M N P Q R T V W X Y Z}\n (0...size).map{ charset.to_a[rand(charset.size)] }.join\n end\nend\n</code></pre>\n<p>And then you can just do in your controller</p>\n<pre class=\"lang-rb prettyprint-override\"><code>class V1::UserRegistrationsController &lt; ApplicationController\n def create\n if (auth = UserRegistration.create(params))\n render auth\n else\n render :error\n end\n end\nend\n</code></pre>\n<p>Generally speaking I think there is too much logic in your controllers which makes it hard to read and test.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T11:45:53.040", "Id": "531926", "Score": "0", "body": "This is very useful. Thank you so much for taking the time Christian! I appreciate it! :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T22:46:36.173", "Id": "532003", "Score": "0", "body": "If you like the answer, please consider to accept it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T19:53:01.590", "Id": "269560", "ParentId": "269506", "Score": "1" } } ]
{ "AcceptedAnswerId": "269560", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T13:08:22.157", "Id": "269506", "Score": "0", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "User registration API" }
269506
<p>So I am using i3 an Linux window manager to manage my windows. In addition this is run on a laptop that is frequently mounted to several output-displays. This is handled by the following lines in my i3 config file</p> <pre><code>set $firstMonitor DP-2-1 set $secondMonitor DP-1-2 set $laptop eDP-1 workspace 1 output $firstMonitor $laptop workspace 2 output $firstMonitor $laptop workspace 3 output $firstMonitor $laptop workspace 4 output $firstMonitor $laptop workspace 5 output $secondMonitor $laptop workspace 6 output $secondMonitor $laptop workspace 7 output $secondMonitor $laptop workspace 8 output $secondMonitor $laptop workspace 9 output $secondMonitor $laptop workspace 10 output $laptop $laptop </code></pre> <p>For convience we can define variables in the config file using set and prefix them with $. The lines above tells my window manager I would like <code>workspace 1</code> to <code>4</code> on <code>$firstMonitor</code> if it exists. Otherwise fall back to <code>$laptop</code>.</p> <p>I am using this for various scripts and therefore need to extract this information from my config file, and store it somewhere. For instance it could look like this</p> <pre class="lang-json prettyprint-override"><code>[ { 'DP-2-1': ['1', '2', '3', '4'], 'DP-1-2': ['5', '6', '7', '8', '9'], 'eDP-1': ['10'] }, { 'eDP-1': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10' } ] </code></pre> <p>parsed. To do so I wrote the following Python code to extract which output each workspace is assigned to. Note that the i3 file is picky about whitespaces, meaning the line <code>set$firstMonitor DP-2-1</code> will not compile.</p> <pre><code>from pathlib import Path import collections CONFIG = Path.home() / &quot;.config&quot; / &quot;i3&quot; / &quot;config&quot; def read_config(config=CONFIG): with open(config, &quot;r&quot;) as f: return f.readlines() def read_workspace_outputs(lines=read_config()): &quot;&quot;&quot;Reads an i3 config, returns which output each workspaces is assigned to Example: set $firstMonitor DP-2-1 set $secondMonitor DP-1-2 set $laptop eDP-1 set $browser 1 workspace $browser output $firstMonitor $laptop workspace 2 output $firstMonitor $laptop workspace 3 output $firstMonitor $laptop workspace 4 output $firstMonitor $laptop workspace 5 output $secondMonitor $laptop workspace 6 output $secondMonitor $laptop workspace 7 output $secondMonitor $laptop workspace 8 output $secondMonitor $laptop workspace 9 output $secondMonitor $laptop workspace 10 output $laptop $laptop Will return [ { 'DP-2-1': ['1', '2', '3', '4'], 'DP-1-2': ['5', '6', '7', '8', '9'], 'eDP-1': ['10'] }, { 'eDP-1': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10' } ] &gt;&gt;&gt; read_workspace_outputs(lines=['workspace 1 output eDP-1']) [defaultdict(&lt;class 'list'&gt;, {'eDP-1': ['1']})] &gt;&gt;&gt; read_workspace_outputs(lines=['set $laptop eDP-1','workspace 1 output eDP-1']) [defaultdict(&lt;class 'list'&gt;, {'eDP-1': ['1']})] &gt;&gt;&gt; read_workspace_outputs(lines=['set $browser 1','workspace $browser output eDP-1']) [defaultdict(&lt;class 'list'&gt;, {'eDP-1': ['1']})] &gt;&gt;&gt; read_workspace_outputs(lines=[ ... &quot;set $firstMonitor DP-2-1&quot;, ... &quot;set $secondMonitor DP-1-2&quot;, ... &quot;set $laptop eDP-1&quot;, ... &quot;&quot;, ... &quot;workspace 1 output $firstMonitor $laptop&quot;, ... &quot;workspace 3 output $secondMonitor $laptop&quot;, ... &quot;workspace 5 output $laptop $laptop&quot;, ... ]) [defaultdict(&lt;class 'list'&gt;, {'DP-2-1': ['1'], 'DP-1-2': ['3'], 'eDP-1': ['5']}), defaultdict(&lt;class 'list'&gt;, {'eDP-1': ['1', '3', '5']})] &quot;&quot;&quot; # Extract workspaces and variables [set $name command] from file def get_workspaces_and_variables(lines): workspaces = [] variables_2_commands = dict() for line in lines: if line.startswith(&quot;workspace&quot;): workspaces.append(line.strip()) elif line.startswith(&quot;set&quot;): _, variable, *command = line.split() variables_2_commands[variable] = &quot; &quot;.join(command) return workspaces, variables_2_commands # Convert back $name to command for outputs and workspaces def workspaces_without_variables(workspaces, variables): workspace_outputs = [] for workspace in workspaces: workspace_str, output_str = workspace.split(&quot;output&quot;) workspace, variable = workspace_str.split() workspace_number = ( variables[variable] if variable.startswith(&quot;$&quot;) else variable ) outputs = [ variables[output] if output.startswith(&quot;$&quot;) else output for output in output_str.split() ] workspace_outputs.append([workspace_number, outputs]) return workspace_outputs # Currently things are stored as workspaces = [[output1, output 2], ...] # This flips the order and stores it as a dict with outputs as keys and values workspaces def workspaces_2_outputs(workspaces): output_workspaces = [ collections.defaultdict(list) for _ in range(len(max((x[1] for x in workspaces), key=len))) ] for (workspace_number, outputs) in workspaces: for j, output in enumerate(outputs): output_workspaces[j][output].append(workspace_number) return output_workspaces workspaces_w_variables, variables = get_workspaces_and_variables(lines) variable_free_workspaces = workspaces_without_variables( workspaces_w_variables, variables ) return workspaces_2_outputs(variable_free_workspaces) if __name__ == &quot;__main__&quot;: import doctest import yaml from yaml.representer import Representer doctest.testmod() OUTPUT_WORKSPACE_CONFIG = ( Path.home() / &quot;.config&quot; / &quot;i3&quot; / &quot;oisov-scripts&quot; / &quot;i3-output-workspace-2.yaml&quot; ) yaml.add_representer(collections.defaultdict, Representer.represent_dict) with open(OUTPUT_WORKSPACE_CONFIG, &quot;w&quot;) as file: yaml.dump(read_workspace_outputs(), file) </code></pre> <p>The <code>output.yaml</code> file looks like this</p> <pre><code>- DP-1-2: - '5' - '6' - '7' - '8' - '9' DP-2-1: - '1' - '2' - '3' - '4' eDP-1: - '10' - eDP-1: - '1' - '2' - '3' - '4' - '5' - '6' - '7' - '8' - '9' - '10' </code></pre> <p>I will add some typing hints in the future, but for now I was wondering if this is the best approach to extract this information. The code feels a bit clunky, even if it does that I want it to.</p> <p>For testing one can use the first code block in this example. A longer i3 example file can for instance be <a href="https://github.com/sainathadapa/i3-wm-config/blob/master/i3-default-config-backup" rel="nofollow noreferrer">https://github.com/sainathadapa/i3-wm-config/blob/master/i3-default-config-backup</a>, due note that this does not set the workspaces to specific outputs.</p>
[]
[ { "body": "<p>As far as coding in Python, I think this is nicely done,\nwith good style, comments, and testing included.\nI agree with you it's a bit clunky, and I have some other minor comments too.</p>\n<h3>What's clunky</h3>\n<p>I have some ideas why it might feel a bit clunky.</p>\n<p><code>get_workspaces_and_variables</code> could return more useful objects. The <code>workspaces</code> are raw lines, not yet parsed. The <code>variables</code> is already good, it's a dictionary ready to use to substitute symbols with actual values. As I try to build a mental model of the program in my head, I feel a heavy burden here, having to remember about two kinds of objects, where one of them needs more work. I would prefer a <code>parse_workspaces</code> function that returns workspaces in an intuitive format.</p>\n<p><code>workspaces_without_variables</code> takes raw workspace lines and variable mappings, and returns workspaces in an intuitive format, with all variables resolved.\nAnd that's fine, it just looks kind of a lot of code.\nIt would be good to extract to a function the duplicated <code>variables[name] if name.startswith(&quot;$&quot;) else name</code>.\nAlso, I think the parsing could be done a bit simpler.\nIn a code comment, an example raw line would be helpful too.</p>\n<p>Finally, <code>workspaces_2_outputs</code> creates the final desired mapping, I just find this line a little bit cryptic:</p>\n<blockquote>\n<pre><code>for _ in range(len(max((x[1] for x in workspaces), key=len)))\n</code></pre>\n</blockquote>\n<p>That is, it finds the max entry by length, and then takes the length as the limit of the range. I would find it more natural to take the lengths, and then find the max of them. And instead of numeric indexing, I would use descriptive names. Like this:</p>\n<pre><code>for _ in range(max(len(outputs) for _, outputs in workspaces))]\n</code></pre>\n<p>Putting the above comments together, consider this alternative implementation:</p>\n<pre><code>def parse_variable(line):\n # example line: &quot;set $firstMonitor DP-2-1&quot;\n _, name, value = line.split()\n return name, value\n\ndef parse_workspace(line, variables):\n def resolve(name):\n return variables[name] if name.startswith('$') else name\n\n # example line: &quot;workspace 1 output $firstMonitor $laptop&quot;\n _, workspace, _, *devices = line.split()\n return resolve(workspace), [resolve(device) for device in devices]\n\ndef outputs_to_workspaces(workspaces):\n mappings = [collections.defaultdict(list)\n for _ in range(max(len(outputs) for _, outputs in workspaces))]\n\n for workspace, outputs in workspaces:\n for index, output in enumerate(outputs):\n mappings[index][output].append(workspace)\n\n return mappings\n\ndef parse_workspaces():\n variables = {}\n workspaces = []\n\n for line in lines:\n if line.startswith('set'):\n name, value = parse_variable(line)\n variables[name] = value\n\n elif line.startswith('workspace'):\n workspaces.append(parse_workspace(line, variables))\n\n return workspaces\n\nreturn outputs_to_workspaces(parse_workspaces())\n</code></pre>\n<p>This passes the original test cases, so I think the behavior is preserved, even though the parsing uses a bit simplified logic.</p>\n<p>Note that for <code>parse_workspaces</code> to work like this it's important that all the variables needed to parse a workspace line have already been defined. I don't know the i3 format, and if this is a safe assumption or not. If not, then indeed a 2nd pass would be needed, similar to the way you did.</p>\n<p>Notice that the scope of <code>variables</code> is much more limited than in the posted code. I think this helps reducing mental burden.</p>\n<h3>Shadowing names from outer scope</h3>\n<p>In the posted code, some names shadow names from outer scope, for example:</p>\n<blockquote>\n<pre><code>def get_workspaces_and_variables(lines):\n ^^^^^\n\ndef workspaces_without_variables(workspaces, variables):\n ^^^^^^^^^\n</code></pre>\n</blockquote>\n<p>I've experienced nasty bugs in the past due to this, I suggest to avoid such shadowing.</p>\n<h3>Usability</h3>\n<p>I would have liked to play around with the program,\nbut with the input and output file paths hardcoded,\nthis was not easy enough.\nIt would be good to accept these as command line arguments,\nand perhaps use the current values as default.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T18:14:48.503", "Id": "269518", "ParentId": "269510", "Score": "3" } }, { "body": "<p>You have doctests - good; keep that up.</p>\n<p>Where this falls over, mostly, is that you have untyped data soup. Internal data representations should not look like JSON. Python (and in particular <code>dataclass</code>) makes it easy to spin up lightweight models so that you gain some assurance of correctness, particularly if you use mypy.</p>\n<p>Assigning a parameter default of <code>lines=read_config()</code> is a bad idea. This default is going to be applied on module load. If the default file is huge module load will be slow, and if the default file changes after some time from module load has passed, the default will be stale. Having default filenames is fine, but I wouldn't have an entire default config like this.</p>\n<p>Your <code>startswith</code> parsing can be simplified by the use of regular expressions.</p>\n<p>Having a function <code>read_workspace_outputs</code> with a collection of nested functions on the inside, apart from doctests, makes unit testing impossible.</p>\n<p>I don't understand much about the <code>yaml</code> module, and the yaml format is trivial enough that it's not difficult to just produce the markup directly. I don't have a strong opinion on this point, but the suggested code below shows direct markup generation.</p>\n<p>Your output format is a little strange; how much control do you have over it? It looks like you're implying the outermost tree level to be the index within the workspace monitor list, but it would be less confusing if you also showed the numerical index itself. That said, the example code below abides by your existing output structure.</p>\n<h2>Suggested</h2>\n<pre><code>import re\nfrom dataclasses import dataclass, field\nfrom pathlib import Path\nfrom string import Template\nfrom typing import Iterator, Iterable, Tuple, Dict, List, Collection\n\nCONFIG = Path.home() / &quot;.config&quot; / &quot;i3&quot; / &quot;config&quot;\n\n\n@dataclass(frozen=True)\nclass Monitor:\n name: str\n workspaces: Dict[int, 'Workspace'] = field(default_factory=dict)\n\n\n@dataclass(frozen=True)\nclass Workspace:\n id: int\n monitors: List[Monitor] = field(default_factory=list)\n\n\nWorkspaceDefinition = Tuple[\n int, # Workspace ID\n Tuple[str], # monitors\n]\n\n\ndef read_config(config: Path = CONFIG) -&gt; Iterator[WorkspaceDefinition]:\n variables: Dict[str, str] = {}\n var_pat = re.compile(\n r'^set'\n r' \\$(?P&lt;key&gt;\\S+)'\n r' (?P&lt;value&gt;.*)'\n r'\\n$'\n )\n work_pat = re.compile(\n r'^workspace'\n r' (?P&lt;id&gt;\\S+)'\n r' output'\n r' (?P&lt;monitors&gt;.+)'\n r'\\n$'\n )\n\n with config.open() as f:\n for line in f:\n var = var_pat.match(line)\n if var:\n variables[var['key']] = var['value']\n continue\n\n filled = Template(line).substitute(variables)\n workspace = work_pat.match(filled)\n if workspace:\n yield int(workspace['id']), workspace['monitors'].split(' ')\n\n\ndef load_workspaces(work_defs: Iterable[WorkspaceDefinition]) -&gt; Tuple[\n Tuple[Workspace],\n Tuple[Monitor],\n]:\n monitors = {}\n workspaces = {}\n\n for work_id, monitor_names in work_defs:\n workspace = Workspace(id=work_id)\n workspaces[work_id] = workspace\n\n for monitor_name in monitor_names:\n monitor = monitors.get(monitor_name)\n if monitor is None:\n monitor = Monitor(name=monitor_name)\n monitors[monitor_name] = monitor\n monitor.workspaces[work_id] = workspace\n workspace.monitors.append(monitor)\n\n return tuple(workspaces.values()), tuple(monitors.values())\n\n\n@dataclass(frozen=True)\nclass MonitorPosition:\n index: int\n workspaces_by_monitor: Dict[str, List[Workspace]]\n\n @classmethod\n def all(\n cls,\n workspaces: Collection[Workspace],\n monitors: Collection[Monitor],\n ) -&gt; Iterator['MonitorPosition']:\n monitor_positions = max(\n len(workspace.monitors)\n for workspace in workspaces\n )\n\n for index in range(monitor_positions):\n yield cls(\n index,\n dict(cls.for_index(workspaces, monitors, index)),\n )\n\n @classmethod\n def for_index(\n cls,\n workspaces: Collection[Workspace],\n monitors: Collection[Monitor],\n index: int,\n ) -&gt; Iterator[Tuple[str, List[Workspace]]]:\n for monitor in monitors:\n workspaces_used = [\n workspace for workspace in workspaces\n if len(workspace.monitors) &gt; index\n and workspace.monitors[index] is monitor\n ]\n if workspaces_used:\n yield monitor.name, workspaces_used\n\n\ndef to_yaml(\n positions: Iterable[MonitorPosition],\n filename: Path,\n) -&gt; None:\n with filename.open('w') as yaml:\n for position in positions:\n group_prefix = '-'\n for monitor_name, workspaces in position.workspaces_by_monitor.items():\n yaml.write(f'{group_prefix:&lt;2}{monitor_name}:\\n')\n yaml.write('\\n'.join(\n f&quot; - '{workspace.id}'&quot;\n for workspace in workspaces\n ))\n yaml.write('\\n')\n group_prefix = ' '\n\n\ndef test() -&gt; None:\n workspaces, monitors = load_workspaces(read_config(Path('config')))\n positions = MonitorPosition.all(workspaces, monitors)\n to_yaml(positions, Path('i3-output-workspace-2.yaml'))\n\n\nif __name__ == '__main__':\n test()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T19:06:28.583", "Id": "269521", "ParentId": "269510", "Score": "2" } } ]
{ "AcceptedAnswerId": "269518", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T14:52:20.247", "Id": "269510", "Score": "4", "Tags": [ "python", "python-3.x", "parsing" ], "Title": "i3 config file parser" }
269510
<p>I have <a href="https://codereview.stackexchange.com/q/269243">already posted this program and got some good recommendations on how it can be improved</a> but I would like to further know what can be improved for example:</p> <ol> <li>Should dynamic memory allocation be used and if yes, where should I allocate it ?</li> <li>How can I replace system(&quot;cls&quot;) in the program ?</li> <li>Should I get rid the global variable ?</li> <li>I got recommend to enable all warnings I couldn't figure out how to do that</li> </ol> <pre><code>#include&lt;stdlib.h&gt; #include&lt;stdio.h&gt; #include&lt;stdbool.h&gt; #define NUM_MIN 1 #define NUM_MAX 9 #define LINE_SIZE 80 void print_board(); int get_input(int player); bool check_input(int user_input); void change_board(int user_input, int player); bool check_win(char arr_values[3]); bool player_has_won(); char g_cell_values[9] = {'1','2','3','4','5','6','7','8','9'}; int main(){ int players_turn[9] = {1,2,1,2,1,2,1,2,1}; int cell_num = 0; for(int i = 0; i &lt; 9; i++) { system(&quot;cls&quot;); print_board(); cell_num = get_input(players_turn[i]); change_board(cell_num,players_turn[i]); if(i == 8) { system(&quot;cls&quot;); print_board(); } if(player_has_won()) { system(&quot;cls&quot;); print_board(); printf(&quot;player %d wins \n&quot;,players_turn[i]); return 0; } } printf(&quot;its a draw\n&quot;); return 1; } void print_board(){ printf(&quot;\n&quot;); int j = 0; for (int i = 0; i &lt; 2; i++) { if(i == 1) { j = 3; } printf(&quot; %c | %c | %c\n&quot;,g_cell_values[j],g_cell_values[j+1],g_cell_values[j+2]); printf(&quot;_____|_____|_____\n&quot;); printf(&quot; | |\n&quot;); } j = 6; printf(&quot; %c | %c | %c\n&quot;,g_cell_values[j],g_cell_values[j+1],g_cell_values[j+2]); } int get_input(int player){ int num = 0; char buf[2*LINE_SIZE]; do { printf(&quot;player %d enter a number option &quot;, player); if(fgets(buf, sizeof buf, stdin) == NULL) { printf(&quot;error occurred\n&quot;); exit(EXIT_FAILURE); } } while (sscanf(buf, &quot;%d&quot;, &amp;num) != 1 || num &lt; NUM_MIN || num &gt; NUM_MAX); return num; } bool check_input(int user_input){ if(g_cell_values[user_input-1] == 'O' || g_cell_values[user_input-1] == 'X') { return false; } else { return true; } } void change_board(int user_input, int player){ int new_input = 0; if(check_input(user_input)) { if(player == 1) { g_cell_values[user_input-1] = 'X'; } else { g_cell_values[user_input-1] = 'O'; } return; } else { new_input = get_input(player); change_board(new_input,player); } } bool check_win(char arr_values[3]){ int count = 0; int count2 = 0; for(int i =0; i&lt;3; i++) { if(arr_values[i] == 'X') { count++; } else if(arr_values[i] == 'O') { count2++; } } if(count == 3 || count2 == 3) { return true; } else { return false; } } bool player_has_won(){ char cell_values[3]; char cell_values2[3]; for(int i = 0; i &lt; 3; i++) { for(int j = 0; j &lt; 3; j++) { cell_values[j] = g_cell_values[i * 3 + j];//rows cell_values2[j] =g_cell_values[j * 3 + i];//columns } if(check_win(cell_values) || check_win(cell_values2)) { return true; } } int j =0; for(int i =0; i&lt;3; i++) { cell_values[i] = g_cell_values[i * 3 + j];//left to right across j++; } int k = 2; for(int i =0; i &lt; 3; i++) { cell_values2[i] = g_cell_values[i*3 + k];//right to left across k--; } if(check_win(cell_values) || check_win(cell_values2)) { return true; } else { return false; } } </code></pre>
[]
[ { "body": "<p><b>1. Dynamic memory allocation</b></p>\n<p>There is no need to dynamically allocate memory for the application.</p>\n<p><b>2. Clearing the screen </b></p>\n<p>There is no portable way to clear the screen. The following works on most operating systems:</p>\n<pre><code>system(&quot;cls||clear&quot;);\n</code></pre>\n<p>I would recommend creating a separate function to handle this so that if you need to change it, you would only need to do so in one location:</p>\n<pre><code>void clear_screen() {\n system(&quot;clear||cls&quot;);\n}\n</code></pre>\n<p><b>3. Global variables</b></p>\n<p>I think that using global variables for this specific solution is fine. You could pass <code>cell_values</code> to the functions directly if you did not want to have one:</p>\n<pre><code>int get_input(char cell_values[9], int player);\n\nint main() {\n char cell_values[9] = { '1','2','3','4','5','6','7','8','9' };\n int players_turn[9] = { 1,2,1,2,1,2,1,2,1 };\n\n int cell_num = get_input(cell_values, players_turn[i]);\n}\n</code></pre>\n<p><b>4. Enabling warnings</b></p>\n<p>This will really depend on what compiler you are using.</p>\n<p><b> More notes </b></p>\n<p>You should call <code>check_input</code> from <code>get_input</code> instead of recursively calling <code>change_board</code>:</p>\n<pre><code>int get_input(int player) {\n int num = 0;\n char buf[2 * LINE_SIZE];\n do {\n printf(&quot;player %d enter a number option &quot;, player);\n if (fgets(buf, sizeof buf, stdin) == NULL) {\n printf(&quot;error occurred\\n&quot;);\n exit(EXIT_FAILURE);\n }\n } while (sscanf(buf, &quot;%d&quot;, &amp;num) != 1 || check_input(num) == false);\n return num;\n}\n\nbool check_input(int user_input) {\n if (user_input &lt; NUM_MIN || user_input &gt; NUM_MAX)\n return false;\n char cell_value = g_cell_values[user_input - 1];\n return cell_value == 'O' || cell_value == 'X' ? false : true;\n}\n\nvoid change_board(int user_input, int player) {\n g_cell_values[user_input - 1] = player == 1 ? 'X' : 'O';\n}\n</code></pre>\n<p>You do not need an <code>if</code> statement if you are simply going to return a <code>bool</code>. In the last part of <code>check_win</code> you could have simply used:</p>\n<pre><code>return count == 3 || count2 == 3;\n</code></pre>\n<p>The same applies to <code>player_has_won</code>:</p>\n<pre><code>return check_win(cell_values) || check_win(cell_values2);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T18:16:26.567", "Id": "531743", "Score": "0", "body": "I am using mingw gcc compiler if it helps, but do you think its a good idea to enable all warnings ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T18:49:05.460", "Id": "531744", "Score": "0", "body": "@BobTheCoder, I really don't know gcc well enough to help." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T17:18:45.440", "Id": "269517", "ParentId": "269512", "Score": "2" } }, { "body": "<h3>Enabling warnings</h3>\n<p>I mostly see and use <code>-Wall -Wextra</code>. Is it a good idea? Yes, I think so. More often than not, the warnings turn out to be inaccuracies that cause bugs. Be sure to read and understand them, as in some cases the warning is a false alarm. As an example, I've had gcc complain about <code>gethostname</code> being undefined while <code>unistd.h</code> was included and the program still worked fine.</p>\n<p>I don't recommend using <code>-Werror</code>, especially while initially writing the program. gcc will then throw every warning as an error, so you won't be able to ignore some warnings that you know are fine when you want to test something quickly (e.g. unused functions).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T10:09:21.540", "Id": "269607", "ParentId": "269512", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T15:38:14.550", "Id": "269512", "Score": "2", "Tags": [ "beginner", "c", "tic-tac-toe" ], "Title": "First C program - Tic Tac Toe 2" }
269512
<p>I'm not familiar with how data transmission works, but I gave my best shot trying to code a server and client-side JSON packet transmitter via Python. Essentially <strong>client.py</strong> generates random JSON packets and sends them to <strong>server.py</strong> which binds a port using a socket and listens for a JSON packet, which then stores the JSON packet as a file to prove the transmission was successful.</p> <p>One problem I am aware of is that within my <strong>client.py</strong>, the <code>sock</code> class is kept being created and closed through each cycle. Though, if I write it like</p> <pre><code> while True: json_packet = generate_json_packet() send_json_packet(sock, json_packet) time.sleep(1) </code></pre> <p>Python emits the following: <code>ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine</code> after the first successful received packet.</p> <p><strong>Server.py</strong></p> <pre><code># Server-Side that receives json packets from client over the network using port 5000. Then it saves the json packet to a file with the filename of current time. import socket import json import random import string # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Bind the socket to the port server_address = ('localhost', 5000) print('starting up on {} port {}'.format(*server_address)) sock.bind(server_address) # Listen for incoming connections sock.listen(1) # Function to receive json packets from client def receive_json(conn): data = conn.recv(1024) data = data.decode('utf-8') data = json.loads(data) return data # Saves json packets to file and name it with id def save_json(data): filename = ''.join(random.choice( string.digits) for _ in range(3)) filename = filename + '.json' with open(filename, 'w') as f: json.dump(data, f) if __name__ == '__main__': while True: # Wait for a connection print('waiting for a connection') connection, client_address = sock.accept() try: print('connection from', client_address) # Receive the data in json format data = receive_json(connection) print('received {!r}'.format(data)) # Save the json packet to a file filename = save_json(data) print('saved to', filename) finally: # Clean up the connection connection.close() </code></pre> <pre><code># Sends random json packets to server over port 5000 import socket import json import random import time def generate_json_packet(): # Generate random json packet with hashed data bits return { &quot;id&quot;: random.randint(1, 100), &quot;timestamp&quot;: time.time(), &quot;data&quot;: hash(str(random.randint(1, 100))) } # Send json packet to server def send_json_packet(sock, json_packet): sock.send(json.dumps(json_packet).encode()) ip = &quot;127.0.0.1&quot; port = &quot;5000&quot; if __name__ == &quot;__main__&quot;: while True: # Create socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect to server sock.connect((ip, int(port))) # Generate random json packet json_packet = generate_json_packet() # Send json packet to server send_json_packet(sock, json_packet) time.sleep(1) sock.close() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T12:11:28.267", "Id": "531785", "Score": "0", "body": "Your edit invalidated an answer, which breaks the question-and-answer nature of this site. See [What should I do when someone answers my question?](/help/someone-answers)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T20:29:25.390", "Id": "531816", "Score": "1", "body": "[`JSON`](https://en.wikipedia.org/wiki/JSON), not `json` or `Json`." } ]
[ { "body": "<p>Your implementation is fatally flawed, and this is mostly not your fault: sockets are non-intuitive. First, when you say</p>\n<blockquote>\n<p>receives json packets</p>\n</blockquote>\n<p>that's not in the slightest what you're doing. You're sending JSON <em>messages</em> that happen to <em>usually</em> fit in one packet, and this coincidence is unreliable and will break under many, many common conditions. This trips up nearly every beginner socket programmer. You need to almost forget about packets entirely, assume that your message may be segmented into an arbitrary number of packets returned to the listener in a series of arbitrarily-sized byte buffers. This in turn means that you cannot rely on packet boundaries to be message boundaries. You need to define your own message boundary. One easy message boundary is a newline, and Python makes it easy to use a <code>StreamRequestHandler</code> that listens for a newline <em>regardless of how many packets were received</em>. So, to stabilise your implementation,</p>\n<ul>\n<li>Call them JSON messages, not JSON packets</li>\n<li>Use <code>sendall</code>, not <code>send</code></li>\n<li>Don't use <code>socket</code> at all on the server side; instead use <code>StreamRequestHandler</code> and <code>TCPServer</code></li>\n<li>Use <code>rfile.readline()</code> to guarantee a stable message boundary</li>\n</ul>\n<p>Other assorted points:</p>\n<ul>\n<li><em>file with the filename of current time</em> is a lie</li>\n<li>The server should not need to go through a JSON round-trip, and can just write the bytes out to a file - if you don't care about validating the data</li>\n<li>You should be using <code>with</code> context management to guarantee socket closure</li>\n</ul>\n<h2>Suggested</h2>\n<p>Server:</p>\n<pre class=\"lang-py prettyprint-override\"><code>&quot;&quot;&quot;\nServer-Side that receives json packets from client over the network using port\n5000. Then it saves the json packet to a file with the filename of current time.\n&quot;&quot;&quot;\nimport random\nimport string\nfrom socketserver import StreamRequestHandler, TCPServer\n\n\ndef save_json(data: bytes) -&gt; None:\n &quot;&quot;&quot;Saves json packets to file and name it with id&quot;&quot;&quot;\n filename = ''.join(\n random.choice(string.digits)\n for _ in range(3)\n ) + '.json'\n with open(filename, 'wb') as f:\n f.write(data)\n print('saved to', filename)\n\n\nclass DumpHandler(StreamRequestHandler):\n def handle(self) -&gt; None:\n &quot;&quot;&quot;receive json packets from client&quot;&quot;&quot;\n print('connection from {}:{}'.format(*self.client_address))\n try:\n while True:\n data = self.rfile.readline()\n if not data:\n break\n print('received', data.decode().rstrip())\n save_json(data)\n finally:\n print('disconnected from {}:{}'.format(*self.client_address))\n\n\ndef main() -&gt; None:\n server_address = ('localhost', 5000)\n print('starting up on {}:{}'.format(*server_address))\n with TCPServer(server_address, DumpHandler) as server:\n print('waiting for a connection')\n server.serve_forever()\n\n\nif __name__ == '__main__':\n try:\n main()\n except KeyboardInterrupt:\n pass\n</code></pre>\n<p>Client:</p>\n<pre class=\"lang-py prettyprint-override\"><code>&quot;&quot;&quot;Sends random json packets to server over port 5000&quot;&quot;&quot;\n\nimport socket\nimport json\nfrom random import randint\nfrom time import time, sleep\nfrom typing import Dict, Any\n\nIP = &quot;127.0.0.1&quot;\nPORT = 5000\n\n\ndef generate_json_message() -&gt; Dict[str, Any]:\n # &quot;&quot;&quot;Generate random json packet with hashed data bits&quot;&quot;&quot;\n return {\n &quot;id&quot;: randint(1, 100),\n &quot;timestamp&quot;: time(),\n &quot;data&quot;: hash(str(randint(1, 100)))\n }\n\n\ndef send_json_message(\n sock: socket.socket,\n json_message: Dict[str, Any],\n) -&gt; None:\n &quot;&quot;&quot;Send json packet to server&quot;&quot;&quot;\n message = (json.dumps(json_message) + '\\n').encode()\n sock.sendall(message)\n print(f'{len(message)} bytes sent')\n\n\ndef main() -&gt; None:\n with socket.socket() as sock:\n sock.connect((IP, PORT))\n while True:\n json_message = generate_json_message()\n send_json_message(sock, json_message)\n sleep(1)\n\n\nif __name__ == &quot;__main__&quot;:\n try:\n main()\n except KeyboardInterrupt:\n pass\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T01:54:37.923", "Id": "531760", "Score": "0", "body": "Why should the program ignore keyboard interruptions?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T02:24:15.997", "Id": "531761", "Score": "1", "body": "@MiguelAlorda Because that's the typical way to cancel a program - Ctrl+C. There's no value in showing the stack trace." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T07:59:00.457", "Id": "531768", "Score": "0", "body": "Thank you @Reinderien! I do have some convention question that I want to ask you: why have you enunciated `-> Dict[str, Any]` or `-> None` for specific functions? I also see you skipping parsing raw data to json and directly saved it into a file. Does this work on every filetype?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T17:17:51.467", "Id": "531801", "Score": "1", "body": "@Joe Those are type hints compliant with https://www.python.org/dev/peps/pep-0484/. They are very useful to tell yourself and other programmers the types of your variables, method parameters and returns; and to verify the correctness of your program using tools like mypy." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T17:19:20.513", "Id": "531802", "Score": "1", "body": "@Joe Yes, skipping a parse & re-serialize is possible for all data formats so long as they can enter and exit in `bytes` format and so long as you don't care to validate the data." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T21:53:06.717", "Id": "269529", "ParentId": "269519", "Score": "6" } } ]
{ "AcceptedAnswerId": "269529", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T18:17:19.727", "Id": "269519", "Score": "3", "Tags": [ "python", "socket" ], "Title": "JSON packet transmitter" }
269519
<p>I have created a program where it contains the IP of the user and uses it to connect to a Philips Hue Bridge. I've just recently started python so I understand my code may be terrible.</p> <pre><code>from phue import Bridge from tkinter import * import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect((&quot;8.8.8.8&quot;, 80)) ip = s.getsockname()[0] s.close() b = Bridge(ip) b.connect() def startup(): start = Tk() start.config(bg=&quot;black&quot;) start.geometry(&quot;1000x500&quot;) hue = Label(start, text=&quot;hue&quot;, font=&quot;Serif 30&quot;, fg=&quot;white&quot;, bg=&quot;black&quot;) hue.place(x=450, y=200) def on(): start.config(bg=&quot;#e6cf00&quot;) hue.config(bg=&quot;#e6cf00&quot;) def app(): root.destroy() lights = b.get_light_objects('name') count = 0 for i in range(0, len(lights) - 1): count += 1 for i in range(0, count): light = Button(root, text=str(lights[count])) start.after(2000, app) start.after(2000, on) root = Tk() root.config(bg=&quot;#bfd8ff&quot;) root.geometry(&quot;1000x500&quot;) # Defaulting Variables light_num = 0 action = '' # on or off ipc = Label(root, text=&quot;Completed Automatic Setup&quot;, font=&quot;Sans 30&quot;, fg=&quot;white&quot;, bg=&quot;#bfd8ff&quot;) ipc.place(x=225, y=200) root.after(5000, startup) def light(): b.get_api() b.set_light(light_num, action, True) root.mainloop() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T20:17:38.593", "Id": "531750", "Score": "0", "body": "Welcome to Code Review! It would benefit reviewers to have a bit more information about the code in the description. From [the help center page _How to ask_](https://codereview.stackexchange.com/help/how-to-ask): \"_You will get more insightful reviews if you not only provide your code, but also give an explanation of what it does. The more detail, the better._\"" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T19:04:24.203", "Id": "269520", "Score": "2", "Tags": [ "python", "beginner" ], "Title": "Philips Hue Light Controller" }
269520
<p>Given a real number <em>a</em> and a natural <em>n</em>, calculate the sum 1 + a + a² + … + aⁿ, without using the formula for the sum of a geometric progression. The running time of the program must be proportional to <em>n</em>.</p> <p>My solution:</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main() { int s = 1, i, n, m; double a; cin &gt;&gt; a &gt;&gt; n; while (n &lt;= 0) { cin &gt;&gt; n; } m = a; for (i = 1; i &lt;= n; i++) { s += m; m *= a; } cout &lt;&lt; s &lt;&lt; endl; return 0; } </code></pre> <p>Input data:<br /> Enter 2 numbers - a and n.</p> <p>Output:<br /> The sum of powers of a: <span class="math-container">\$\sum_{i=0}^n a^i\$</span></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T22:27:30.380", "Id": "531754", "Score": "3", "body": "If you're experiencing problems, post on StackOverflow. On CodeReview, please include functional code with example inputs and outputs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T06:57:54.010", "Id": "531765", "Score": "0", "body": "Code Review is for working code.\nAlso check variable types." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T08:31:57.130", "Id": "531769", "Score": "0", "body": "@Pavlo - what do you think is non-working? This certainly produces the correct output for small numbers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T10:27:07.807", "Id": "531772", "Score": "1", "body": "@TobySpeight Only for integers, and according to the problem it should work for real numbers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T10:37:23.487", "Id": "531773", "Score": "2", "body": "@G.Sliepen, I didn't test non-integers until I was already most of the way through answering - not sure whether to keep this one open, as it's likely that Jim also tested only with integers and so was unaware of the bug." } ]
[ { "body": "<p>Avoid <code>using namespace std;</code>. Although it's unlikely to be a problem in a small program such as this, you're better off developing the good habit of using properly qualified names, only bringing in specific identifiers where necessary, not whole namespaces (excepting namespaces such as <code>std::literals</code> which are designed for it).</p>\n<p>We don't need to declare all our variables at the beginning of the function. It's generally better to keep variables' scope to a minimum - e.g. <code>for (int i = 1; …)</code>.</p>\n<p>When dealing with user input, remember that any invalid input will prevent conversion. The easy way to test for that is to check whether the stream is &quot;bad&quot; after the conversion:</p>\n<pre><code>std::cin &gt;&gt; a &gt;&gt; n;\nif (!std::cin) {\n std::cerr &lt;&lt; &quot;Invalid input values&quot;;\n return 1;\n}\n</code></pre>\n<p>This next code seems to be asking for valid input, but there's no prompting for a user to understand what's going on:</p>\n<blockquote>\n<pre><code>while (n &lt;= 0)\n{\n cin &gt;&gt; n;\n}\n</code></pre>\n</blockquote>\n<p>I don't see why <code>0</code> shouldn't be allowed for <em>n</em>. It certainly seems reasonable that we should output <code>1</code> in that case. And since negative numbers don't make sense, perhaps <code>n</code> should be an unsigned type?</p>\n<blockquote>\n<pre><code>m = a;\n</code></pre>\n</blockquote>\n\n<blockquote>\n<pre><code> s += m;\n</code></pre>\n</blockquote>\n<p><code>a</code> is a double, but here we're truncating to <code>int</code>. That's probably not what we want (and will give the wrong output for fractional or large values).</p>\n<p>Instead of introducing the index variable <code>i</code> that we don't use within the body of the loop, we could use <code>n</code> itself for the index variable, using <code>while</code> and <code>--n</code>.</p>\n<p>Avoid <code>std::endl</code>. If you really need to flush after writing <code>\\n</code>, it's probably better to use <code>std::flush</code> so it's obviously intentional.</p>\n<p>We can use the standard macros <code>EXIT_FAILURE</code> and <code>EXIT_SUCCESS</code> (defined in <code>&lt;cstdlib&gt;</code>) for our return value.</p>\n<hr />\n<h1>Modified code</h1>\n<p>Taking the above improvements into account:</p>\n<pre><code>#include &lt;cstdlib&gt;\n#include &lt;iostream&gt;\n\nint main()\n{\n double a;\n unsigned n;\n std::cin &gt;&gt; a &gt;&gt; n;\n if (!std::cin) {\n std::cerr &lt;&lt; &quot;Invalid input values&quot;;\n return EXIT_FAILURE;\n }\n\n double s = 1.0;\n double m = 1.0;\n\n while (n-- &gt; 0) {\n m *= a;\n s += m;\n }\n\n std::cout &lt;&lt; s &lt;&lt; '\\n';\n return EXIT_SUCCESS;\n}\n</code></pre>\n<h3>Note</h3>\n<p>We could have combined the loop body as <code>s += m *= a;</code> - but I think the two separate statements are clearer to readers.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T10:10:00.953", "Id": "531771", "Score": "0", "body": "`s += m *= a` - \"Clearer to readers\" and would the compiler generate the same output anyway? So there is really zero benefit (other than understanding it can be done and may be useful in other situations?)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T10:39:33.057", "Id": "531774", "Score": "2", "body": "Yes, the final binary should be the same (try it over on Compiler Explorer if you're really interested). I only mentioned it to make the point that \"clever\" code isn't necessarily better than \"simple\" code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T09:00:56.033", "Id": "269539", "ParentId": "269522", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T19:23:22.823", "Id": "269522", "Score": "3", "Tags": [ "c++" ], "Title": "Compute 1 + a + a² + … + aⁿ" }
269522
<p>I'm writing Minesweeper implementation in Java. I have little experience yet, so I need some advices:</p> <ul> <li>about improving code, making it more readable and flexible</li> <li>about coding style</li> <li>about common mistakes that newbies usually do (I suspect I have some in my code)</li> <li>about code structure (for example, I'm not sure about where and how it would be better to store information about neighbour cells)</li> <li>about choosing best data structure for storing the minefield (currently I use simple 2D array, but I think it won't be suitable if I want non-square cells, for example)</li> <li>about optimization and rewriting some functions if needed</li> </ul> <p>Cell.java</p> <pre><code>// represents single cell public class Cell { public enum Type { MINED,EMPTY } public enum State { COVERED,UNCOVERED,FLAGGED,FLAGGED_DEFUSED } public int nColIndex,nRowIndex; // cell position inside the grid public int nMinesAround; // total number of mines in nearby cells protected Type type; protected State state; public Cell(int row, int col) { // by default cell is clear and covered this.nColIndex=col; this.nRowIndex=row; this.type = Type.EMPTY; this.state = State.COVERED; } public boolean isCovered() { return (this.state==State.COVERED || this.state==State.FLAGGED); } } </code></pre> <p>Game.java</p> <pre><code>import java.util.ArrayList; import java.util.List; import java.util.Stack; import java.util.concurrent.ThreadLocalRandom; import javax.swing.JPanel; //responsible for game logic public class Game extends JPanel { public enum GameStatus { LOST,VICTORY,RUNNING; } protected Cell[][] minefield; // 2d array representing a minefield protected int nCols, nRows, nMines, nUncoveredClearCells=0; protected GameStatus status; // state of the current game (running, lost or won) public Game(int cols, int rows, int mines) { // start a new game this.nCols=cols; this.nRows=rows; this.nMines=mines; this.status=GameStatus.RUNNING; field_init(); } protected void field_init() { // initialize an array by filling it with cell objects this.minefield = new Cell[nRows][nCols]; for (int i = 0; i &lt; nRows; i++) { for (int j = 0; j &lt; nCols; j++) { minefield[i][j] = new Cell(i, j); } } } public void plantMines(Cell firstClickedCell) { // randomly plant mines by generating random coords in 2d array // (like if it was one-dimensional) int nMinesPlanted=0; int nPos=0,nColIndex=0,nRowIndex=0; Cell currentCell; ThreadLocalRandom rnd = ThreadLocalRandom.current(); List&lt;Cell&gt; nearbyCells; while(nMinesPlanted&lt;nMines) { nPos = rnd.nextInt(0, nCols*nRows); nRowIndex = nPos/nCols; // get Y cell coord (row index) nColIndex = nPos%nCols; // get X cell coord (column index) currentCell=minefield[nRowIndex][nColIndex]; if(currentCell.type!=Cell.Type.MINED &amp;&amp; currentCell!=firstClickedCell) { currentCell.type=Cell.Type.MINED; nearbyCells = getCellNeighbours(currentCell); for(Cell nearbyCell : nearbyCells) nearbyCell.nMinesAround++; // notify cell neighbours about new mine nMinesPlanted++; } } } protected List&lt;Cell&gt; getCellNeighbours(Cell myCell) { // find neighbours of current cell // and add them to the list List&lt;Cell&gt; cells = new ArrayList&lt;Cell&gt;(); if(myCell.nColIndex-1&gt;=0) cells.add(minefield[myCell.nRowIndex][myCell.nColIndex-1]); // left neighbour if(myCell.nColIndex+1&lt;nCols) cells.add(minefield[myCell.nRowIndex][myCell.nColIndex+1]); //right neighbour if(myCell.nRowIndex-1&gt;=0) cells.add(minefield[myCell.nRowIndex-1][myCell.nColIndex]); // top neighbour if(myCell.nRowIndex+1&lt;nRows) cells.add(minefield[myCell.nRowIndex+1][myCell.nColIndex]); // bottom neighbour if(myCell.nRowIndex+1&lt;nRows &amp;&amp; myCell.nColIndex+1&lt;nCols) // bottom-right neighbour cells.add(minefield[myCell.nRowIndex+1][myCell.nColIndex+1]); if(myCell.nRowIndex-1&gt;=0 &amp;&amp; myCell.nColIndex-1&gt;=0) // top-left neighbour cells.add(minefield[myCell.nRowIndex-1][myCell.nColIndex-1]); if(myCell.nRowIndex+1&lt;nRows &amp;&amp; myCell.nColIndex-1&gt;=0) // bottom-left neighbour cells.add(minefield[myCell.nRowIndex+1][myCell.nColIndex-1]); if(myCell.nRowIndex-1&gt;=0 &amp;&amp; myCell.nColIndex+1&lt;nCols) // top-right neighbour cells.add(minefield[myCell.nRowIndex-1][myCell.nColIndex+1]); return cells; } public void clickCell(Cell selectedCell) { // Trying to open a mined cell - the game is lost if(selectedCell.type==Cell.Type.MINED) { status=GameStatus.LOST; uncoverAllMines(); } else { // Clicked cell is clear uncoverCells(selectedCell); if(isVictory()) { // Check if there are any covered cells without mines status=GameStatus.VICTORY; // there aren't)) flagAllMines(); } } } protected void uncoverCells(Cell selectedCell) { // Uncover a clear cell. If it has no mines around // we also open all its nearby cells // Then do the same for their neighbours and so on... Stack&lt;Cell&gt; stack = new Stack&lt;Cell&gt;(); List&lt;Cell&gt; nearbyCells; stack.push(selectedCell); while(!stack.isEmpty()) // expand area around clicked cell while possible { Cell currentCell = stack.pop(); if(currentCell.state!=Cell.State.UNCOVERED) // skip already uncovered cells { currentCell.state=Cell.State.UNCOVERED; nUncoveredClearCells++; if(currentCell.nMinesAround==0) // if ALL neighbours are clear, we open them too { nearbyCells = getCellNeighbours(currentCell); for(Cell nearbyCell : nearbyCells) { if(nearbyCell.isCovered()) { // skip already uncovered cells (x2) stack.push(nearbyCell); } } } } } } protected void uncoverAllMines() { // If we open a mined cell, the game is lost // In such situation other mined cells are opened automatically // If some of them were previously flagged then they are shown as defused Cell currentCell; for (int i = 0; i &lt; nRows; i++) for (int j = 0; j &lt; nCols; j++) { currentCell=minefield[i][j]; if(currentCell.type==Cell.Type.MINED) { if(currentCell.state==Cell.State.FLAGGED) currentCell.state=Cell.State.FLAGGED_DEFUSED; else currentCell.state=Cell.State.UNCOVERED; } } } protected boolean isVictory() { // Check if we haven't opened all the clear cells yet // If it's already done - it's a victory. Otherwise we continue the game return (nCols*nRows-nMines==nUncoveredClearCells); } protected void flagAllMines() { // If there are no clear covered cells left then the game is won // Mined cells are automatically marked with flags Cell currentCell; for (int i = 0; i &lt; nRows; i++) for (int j = 0; j &lt; nCols; j++) { currentCell=minefield[i][j]; if(currentCell.type==Cell.Type.MINED) { currentCell.state=Cell.State.FLAGGED; } } } public void restartGame() { // If user wants to restart existing game // we just cover any open cells Cell currentCell; nUncoveredClearCells=0; status=GameStatus.RUNNING; for (int i = 0; i &lt; nRows; i++) for (int j = 0; j &lt; nCols; j++) { currentCell=minefield[i][j]; currentCell.state=Cell.State.COVERED; } } public void setFlag(Cell selectedCell) { // Sets a flag on covered cell (or removes it if it's already present) if(selectedCell.state==Cell.State.COVERED) selectedCell.state=Cell.State.FLAGGED; else if(selectedCell.state==Cell.State.FLAGGED) selectedCell.state=Cell.State.COVERED; } } </code></pre> <p>GameGrid.java</p> <pre><code>import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.io.IOException; import java.util.HashMap; import javax.imageio.ImageIO; // Responsible for painting the minefield public class GameGrid extends Game { final static int CELL_WIDTH=20; // cell width in pixels final static int CELL_HEIGHT=20; // cell height in pixels HashMap&lt;String,Image&gt; icons; public void paint(Graphics graphics) { for (int i = 0; i &lt; nRows; i++) for (int j = 0; j &lt; nCols; j++) { Image currentCellImage=null; switch(minefield[i][j].state) { case COVERED: { // cell is covered currentCellImage = icons.get(&quot;covered&quot;); break; } case UNCOVERED: { if(minefield[i][j].type==Cell.Type.MINED) { currentCellImage = icons.get(&quot;mined&quot;); // cell is open and contains a mine } else currentCellImage = icons.get(Integer.toString(minefield[i][j].nMinesAround)); // cell is open and clear break; } case FLAGGED: { // cell is covered and flagged currentCellImage = icons.get(&quot;covered_flagged&quot;); break; } case FLAGGED_DEFUSED: { // cell is open, mined and was previously marked with a flag currentCellImage = icons.get(&quot;mined_flagged&quot;); break; } default: break; } if(currentCellImage!=null) graphics.drawImage(currentCellImage, j*CELL_WIDTH, i*CELL_HEIGHT, CELL_WIDTH, CELL_HEIGHT,null); // draw current cell } } @Override public Dimension getPreferredSize() { // report grid dimensions in order to adjust parent's size return new Dimension(CELL_WIDTH*nCols, CELL_HEIGHT*nRows); }; public GameGrid(int cols, int rows, int mines) { super(cols, rows, mines); icons_init(); } private void icons_init() { // load icons that represent different cell types and states icons = new HashMap&lt;String,Image&gt;(); try { for(int i=0; i&lt;=8; i++) { // Current cell is open and has N (0-8) mines around (horiz., vert. and diag.) icons.put(Integer.toString(i), ImageIO.read(GameGrid.class.getResource(&quot;images/&quot;+Integer.toString(i)+&quot;.png&quot;))); } icons.put(&quot;covered&quot;, ImageIO.read(GameGrid.class.getResource(&quot;images/coveredCell.png&quot;))); // cell is covered (and has no flag) icons.put(&quot;covered_flagged&quot;, ImageIO.read(MainWindow.class.getResource(&quot;images/coveredFlaggedCell.png&quot;))); // cell is covered and has a flag icons.put(&quot;mined&quot;, ImageIO.read(GameGrid.class.getResource(&quot;images/minedCell.png&quot;))); // cell is open and mined icons.put(&quot;mined_flagged&quot;, ImageIO.read(GameGrid.class.getResource(&quot;images/minedFlaggedCell.png&quot;))); // cell is open, mined and was previously marked with a flag } catch(IOException ex) { ex.printStackTrace(); // could not load icon(s) for some reason } } public Cell getCellFromCoords(int x, int y) { return minefield[y/CELL_HEIGHT][x/CELL_WIDTH]; // get cell from it's coords } } </code></pre> <p>GamePanel.java</p> <pre><code>import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.Timer; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingUtilities; public class GamePanel extends JPanel { final int ONE_SECOND=1000; // 1 s = 1000 ms JPanel pnlProgress; JLabel lblTime,lblMines; // elapsed time in seconds and mines count JButton btnRestart; // &quot;Restart&quot; button GameGrid myGame; ActionListener updateCurrentTime = new ActionListener() { public void actionPerformed(ActionEvent evt) { int nCurrentTime=Integer.parseInt(lblTime.getText()); if(nCurrentTime&gt;=999) { tmGame.stop(); return; } lblTime.setText(String.format(&quot;%03d&quot;, nCurrentTime+1)); // increase time counter by one } }; Timer tmGame = new Timer(ONE_SECOND, updateCurrentTime); // game timer boolean bFirstClick = true; // mines are planted after first click MouseAdapter userClickHandler = new MouseAdapter() { public void mousePressed(MouseEvent me) { int x = me.getX(); int y = me.getY(); Cell requestedCell = myGame.getCellFromCoords(x,y); // get cell under mouse cursor if(SwingUtilities.isLeftMouseButton(me) &amp;&amp; requestedCell.state==Cell.State.COVERED) // open cell on left-click { if(bFirstClick) { // first click is always safe (impossible to lose) myGame.plantMines(requestedCell); tmGame.start(); bFirstClick=false; } myGame.clickCell(requestedCell); if(myGame.status!=Game.GameStatus.RUNNING) endGame(myGame.status); // check game result } else if(SwingUtilities.isRightMouseButton(me)) myGame.setFlag(requestedCell); // set or remove flag on right-click invalidate(); repaint(); } }; public void startGame(Level lvl, boolean bRestartExisting) { tmGame.stop(); if(bRestartExisting) { myGame.restartGame(); tmGame.start(); } else { if(myGame!=null) remove(myGame); myGame=new GameGrid(lvl.nCols, lvl.nRows, lvl.nTotalMines); add(myGame); bFirstClick=true; } btnRestart.setText(&quot;Restart&quot;); if(myGame.getMouseListeners().length==0) myGame.addMouseListener(userClickHandler); // enable mouse input if it's disabled lblMines.setText(String.format(&quot;%03d&quot;, myGame.nMines)); lblTime.setText(&quot;000&quot;); myGame.invalidate(); myGame.repaint(); } public void endGame(Game.GameStatus state) { tmGame.stop(); if(state==Game.GameStatus.VICTORY) btnRestart.setText(&quot;You Win!&quot;); else btnRestart.setText(&quot;You Lose!&quot;); myGame.removeMouseListener(userClickHandler); // disable mouse input } public GamePanel() { this.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS)); lblTime=new JLabel(&quot;000&quot;); lblMines=new JLabel(&quot;000&quot;); btnRestart=new JButton(&quot;Restart&quot;); pnlProgress=new JPanel(); pnlProgress.setLayout(new BoxLayout(pnlProgress, BoxLayout.X_AXIS)); pnlProgress.add(lblTime); pnlProgress.add(Box.createGlue()); pnlProgress.add(btnRestart); btnRestart.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { startGame(null, true); // restart existing game } }); pnlProgress.add(Box.createGlue()); pnlProgress.add(lblMines); add(pnlProgress); startGame(Level.arrPredefinedLevels[0],false); // &quot;Beginner&quot; level is default } public void paintComponent(Graphics g) { super.paintComponent(g); } } </code></pre> <p>GameParamsWindow.java</p> <pre><code>import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.WindowEvent; import java.awt.event.WindowAdapter; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.text.DocumentFilter; import javax.swing.text.AbstractDocument; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; public class GameParamsWindow extends JDialog { JComboBox&lt;Level&gt; cbDifficulty; JLabel lblDifficulty,lblCols,lblRows,lblMines; JNumericTextField txtCols,txtRows,txtMines; JButton btnStart; JPanel pnlCommon,pnlBasic,pnlCustomize; JFrame frmParent; boolean bCancelled=false; public class JNumericTextField extends JTextField { JNumericTextField(int nMaxLength) { setPreferredSize(new Dimension(40,20)); AbstractDocument doc=(AbstractDocument) getDocument(); addFocusListener(new FocusAdapter() { public void focusGained(FocusEvent e) { SwingUtilities.invokeLater(new Runnable() { public void run() { ((JNumericTextField)e.getSource()).selectAll(); } }); } }); doc.setDocumentFilter(new DocumentFilter() { public void replace(FilterBypass fb, int offset, int len, String str, AttributeSet a) throws BadLocationException { // JNumericTextField allows only digits String sNumericOnly=str.replaceAll(&quot;[^0-9]&quot;, &quot;&quot;); super.replace(fb, offset,len, sNumericOnly ,a); // restrict text length if(doc.getLength()&gt;nMaxLength) doc.replace(0, doc.getLength(), doc.getText(0, doc.getLength()).substring(0,nMaxLength),a); } }); } public int getNumber() { // get integer from JNumericTextField instance if(getText().isEmpty()) return 0; return Integer.parseInt(getText()); } public void setNumber(int num) { setText(Integer.toString(num)); } } public void setCustomValuesAllowed(boolean bFlag) { //(dis)allow setting custom values txtCols.setEditable(bFlag); txtRows.setEditable(bFlag); txtMines.setEditable(bFlag); } public GameParamsWindow() { initSettingsUI(); setModal(true); // this is a dialog window } Level showDialog(JFrame frmParent) { Level selectedLevel; bCancelled=false; this.frmParent=frmParent; setLocationRelativeTo(this.frmParent); cbDifficulty.setSelectedItem(cbDifficulty.getSelectedItem()); // refresh text fields setVisible(true); if(bCancelled) { return null; } // dialog was closed with &quot;X&quot; button selectedLevel=((Level)cbDifficulty.getSelectedItem()); // get selected level selectedLevel.setParameters(txtCols.getNumber(), txtRows.getNumber(), txtMines.getNumber()); // update level info return selectedLevel; } private void initSettingsUI() { setTitle(&quot;New Game&quot;); setResizable(false); pnlCommon=new JPanel(); pnlCommon.setLayout(new BoxLayout(pnlCommon, BoxLayout.Y_AXIS)); pnlBasic = new JPanel(new FlowLayout()); pnlCustomize = new JPanel(new FlowLayout()); lblDifficulty= new JLabel(&quot;Difficulty level&quot;); cbDifficulty = new JComboBox&lt;Level&gt;(); txtCols = new JNumericTextField(2); // number of cols txtRows = new JNumericTextField(2); // number of rows txtMines = new JNumericTextField(3); // number of mines cbDifficulty.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { Level selectedLevel=(Level)((JComboBox&lt;Level&gt;)e.getSource()).getSelectedItem(); txtCols.setNumber(selectedLevel.nCols); txtRows.setNumber(selectedLevel.nRows); txtMines.setNumber(selectedLevel.nTotalMines); setCustomValuesAllowed(selectedLevel.sName==&quot;Custom&quot;); } }); for(Level lvl: Level.arrPredefinedLevels) cbDifficulty.addItem(lvl); // push predefined levels to combobox lblCols = new JLabel(&quot;Columns:&quot;); lblRows = new JLabel(&quot;Rows:&quot;); lblMines = new JLabel(&quot;Mines:&quot;); btnStart = new JButton(&quot;Start&quot;); btnStart.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setVisible(false); // &quot;Start&quot; button is pressed - dialog should be closed // Now parent window will get the selected level and we are ready to start the game } }); pnlBasic.add(lblDifficulty); pnlBasic.add(cbDifficulty); pnlBasic.add(btnStart); pnlCustomize.add(lblCols); pnlCustomize.add(txtCols); pnlCustomize.add(lblRows); pnlCustomize.add(txtRows); pnlCustomize.add(lblMines); pnlCustomize.add(txtMines); pnlCommon.add(pnlBasic); pnlCommon.add(pnlCustomize); add(pnlCommon); pack(); getRootPane().setDefaultButton(btnStart); addWindowListener( new WindowAdapter() { @Override public void windowClosing(WindowEvent we) { bCancelled=true; // &quot;X&quot; button was clicked // Dialog is cancelled and game won't be started } @Override public void windowActivated(WindowEvent we) { // if dialog is activated - make it's parent visible too frmParent.setVisible(true); } } ); } } </code></pre> <p>Level.java</p> <pre><code>public class Level { static Level[] arrPredefinedLevels = { new Level(&quot;Beginner&quot;,9,9,10), new Level(&quot;Medium&quot;, 16,16,40), new Level(&quot;Expert&quot;, 30,16,99), new Level(&quot;Custom&quot;, 9,9,10) }; String sName; public int nCols,nRows,nTotalMines; final private int MIN_ROWS=9,MAX_ROWS=30,MIN_COLS=9,MAX_COLS=24,MIN_MINES=10; // limits Level(String name, int cols,int rows, int mines) { sName=name; setParameters(cols,rows,mines); } public void setParameters(int cols,int rows, int mines) { // Assign values and make sure they aren't out of range (otherwise correct them) nCols=cols; nRows=rows; nTotalMines=mines; if(nCols&lt;MIN_COLS) nCols=MIN_COLS; else if(nCols&gt;MAX_COLS) nCols=MAX_COLS; if(nRows&lt;MIN_ROWS) nRows=MIN_ROWS; else if(nRows&gt;MAX_ROWS) nRows=MAX_ROWS; if(nTotalMines&lt;MIN_MINES) nTotalMines=MIN_MINES; else if(nTotalMines&gt;(nRows-1)*(nCols-1)) nTotalMines=(nRows-1)*(nCols-1); } public String toString() { return sName; } } </code></pre> <p>MainWindow.java</p> <pre><code>import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import java.awt.FlowLayout; import java.awt.Image; import javax.imageio.ImageIO; import javax.swing.BoxLayout; import javax.swing.ImageIcon; public class MainWindow { private JFrame frame; GamePanel pnlGameUI=new GamePanel(); GameParamsWindow dlgNewGame = new GameParamsWindow(); static Image appIcon; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { appIcon=ImageIO.read(getClass().getResource(&quot;images/appIcon.png&quot;)); MainWindow window = new MainWindow(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public MainWindow() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(&quot;Minesweeper&quot;); frame.setIconImage(appIcon); frame.setBounds(100, 100, 450, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS)); frame.setResizable(false); JMenuBar tbMenu = new JMenuBar(); tbMenu.setLayout(new FlowLayout(FlowLayout.LEFT,0,0)); JMenu mnuGame = new JMenu (&quot;Game&quot;); JMenu mnuAbout = new JMenu (&quot;About&quot;); JMenuItem itemNewGame = new JMenuItem(&quot;New Game&quot;); JMenuItem itemExit = new JMenuItem(&quot;Exit&quot;); itemNewGame.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { Level lvlChosen = dlgNewGame.showDialog(frame); if(lvlChosen!=null) // if dialog was just closed with &quot;X&quot; button - do nothing { pnlGameUI.startGame(lvlChosen, false); // start a new game (level was set inside the dialog) frame.pack(); } } }); itemExit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ev) { System.exit(0); } }); mnuAbout.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { JOptionPane.showMessageDialog(frame,&quot;Minesweeper 1.0, 2021&quot;, &quot;About&quot;,JOptionPane.INFORMATION_MESSAGE,new ImageIcon(appIcon)); } }); mnuGame.add(itemNewGame); mnuGame.add(itemExit); tbMenu.add(mnuGame); tbMenu.add(mnuAbout); frame.getContentPane().add(tbMenu); frame.getContentPane().add(pnlGameUI); frame.pack(); } } </code></pre>
[]
[ { "body": "<p>Very nice piece of code, thank you very musch for sharing your work with us!</p>\n<p>i tried to list the issued order by severity.</p>\n<h2>segregation of concerns / composition over inheritance / MVC</h2>\n<p>Your displaying class <code>GameGrid</code> <strong>extends</strong> from <code>Game</code>. That violates all principles in different ways. It would be easy to <strong>increase loose coupling</strong> by defining an interface in the game that provides all content, that needs to be drawn.</p>\n<pre><code>interface ContentProvider{\n Set&lt;Cell&gt; getMinefield(); \n}\n</code></pre>\n<p>assuming <code>Cell</code> provides a method <code>getLocation()</code>.</p>\n<p>The purpose of <code>GameGrid</code> is to paint a Minefiled (a <code>Set&lt;Cell&gt;</code>), so you should give it a proper name.</p>\n<p>And since <code>paint</code> is very specific on <code>java.awt...</code> and you treat it as a component (see <code>GamePanel</code>: <code>GameGrid.invalidate();</code> and <code>GameGrid.repaint();</code>) it <strong>should be</strong> a component. (i think your legacy annotations (<code>@Override getPrefferedSize()</code>) - even though there is no proper super class) show, that you already had this idea, btw, remove them or change hierarchy towards component).</p>\n<h2>complexity / object orientated design / testability</h2>\n<p>these three issues go hand in hand. Lots of your code is complex to read and it would help to create methods to simplify the code - and increase testability. its easier to test small methods rather than the whole class.</p>\n<p>unluckily the complexity is distributed, so i can only pick some examples in detail.</p>\n<p><strong>example: GameGrid.paint(Graphics graphics)</strong><br></p>\n<pre><code>paint(Graphics graphics){\n for (int i = 0; i &lt; nRows; i++){\n for (int j = 0; j &lt; nCols; j++){\n ...\n //ok, here we should break complexity:\n Cell cell = minefield[i][j];\n paintCell(cell, graphics);\n }\n }\n} \n</code></pre>\n<p>stop complexity by calling a method <code>paintCell</code> on <code>Cell</code> level.</p>\n<p><strong>example: Game.uncoverCells(Cell selectedCell)</strong><br></p>\n<pre><code>protected void uncoverCells(Cell selectedCell){\n // Uncover a clear cell. If it has no mines around\n // we also open all its nearby cells\n // Then do the same for their neighbours and so on...\n Stack&lt;Cell&gt; stack = new Stack&lt;Cell&gt;();\n List&lt;Cell&gt; nearbyCells;\n stack.push(selectedCell);\n while(!stack.isEmpty()) {// expand area around clicked cell while possible\n Cell currentCell = stack.pop();\n if(currentCell.state!=Cell.State.UNCOVERED){ // skip already uncovered cells \n ...\n //stop here\n expandCell(currentCell);\n }\n }\n}\n</code></pre>\n<p>again, stop complexity by calling a method instead of digging deeper and deeper.</p>\n<p><strong>example: Game.getCellNeighbours()</strong><br></p>\n<p>here is a good example, where you missed an opportunity to use object-orientated code</p>\n<p>instead of providing a method on the board to check if a cell is inside the board, you directly add the logic into the method.</p>\n<p>In an object orientatded design our cell would have a <code>Location</code> instead of primitive coordinates. and a cell would know its neighbour locations</p>\n<pre><code>class Cell{\n private final Location location;//injected on constructor\n List&lt;Location&gt; getSurroundedLocations(){//...returns eight locations}\n}\n</code></pre>\n<p>and our board would know if a location is inside the board</p>\n<pre><code>class Board{\n boolean isInside(Location location){//you know when its inside}\n Cell getCellAt(Location location){//again: trivial};\n}\n</code></pre>\n<p>that would reduce complexity of your method (and increase readability strongly)</p>\n<pre><code>protected List&lt;Cell&gt; getCellNeighbours(Cell myCell){\n List&lt;Cell&gt; cells = new ArrayList&lt;Cell&gt;();\n for (Location location: myCell.getSurroundedLocations()){\n if(isInside(location)){\n cells.add(getCell(location);\n }\n }\n}\n</code></pre>\n<p><strong>Note:</strong> that would also reduce the duplicated code: <code>(if cell.nColIndex &gt;= 0)</code> that is called 3 times, as well as on row index...</p>\n<p><strong>example: primitives instead of behaviour (methods)</strong><br>\nwhat is see all across your code is a direct check on status. that is a poor design and adds complexity and violates the object-orientated design.</p>\n<ul>\n<li>here: <code>Game.clickCell</code>: <code>if(selectedCell.type==Cell.Type.MINED)</code> should be <code>if(selectedCell.isMined()){...}</code></li>\n<li>here: <code>Game.uncoverCells</code>: <code>if(currentCell.state!=Cell.State.UNCOVERED)</code> should be <code>if(currentCell.isCovered())</code></li>\n<li>here: <code>Game.uncoverCells</code>: <code>currentCell.state=Cell.State.UNCOVERED;</code> should be <code>currentCell.setCovered();</code></li>\n<li>here: <code>GamePanel.endGame</code>: <code>if(state==Game.GameStatus.VICTORY)</code> should be <code>if(game.isVictory()){...}</code></li>\n<li>here: ...the list is long</li>\n</ul>\n<p><strong>Note:</strong> one thing was astounding me: you did the oop approach on your method <code>Cell.isCovered()</code>. but here you violated the naming convention, the method does not return waht is expected: it has some hidden logic inside. that's no good idea, the method name should be adjusted to properly express the behaviour.</p>\n<p><strong>example:Cell iteration</strong></p>\n<pre><code>for (int i = 0; i &lt; nRows; i++){\n for (int j = 0; j &lt; nCols; j++){\n currentCell=minefield[i][j];\n }\n}\n</code></pre>\n<p>since you use this code quite often, you should consider using a more proper type of data<br>\n<code>Set&lt;Cell&gt; minefield</code> maybe (or a map), and instead of accessing the array directly(see <code>Locaction</code>) you could get Cells with a proper method: getCellAt(Location location).</p>\n<pre><code>for(Cell currentCell: mineField){...}\n</code></pre>\n<h2>naming issues</h2>\n<p>some examples where you should provide better names for variables:</p>\n<ul>\n<li><code>Cell.nColIndex,nRowIndex;</code> (aside from using a <code>Location</code> class), the proper names would be <code>column</code> and <code>row</code> (what is that <strong>n</strong> for? and the usage of <code>Index</code> should have been an alarm signal for unclean design</li>\n<li>a never-ending story: <br>\n<pre><code>for (int i = 0; i &lt; nRows; i++){\n for (int j = 0; j &lt; nCols; j++){}\n}\n</code></pre>\n<code>i</code> and <code>j</code> should be <code>row</code> and <code>column</code>, or maybe <code>x</code>and <code>y</code> (my personal all time issue)</li>\n<li><code>GamePanel</code>, where are the vocal? <code>pnlProgress</code>, <code>lblTime</code>, <code>lblMines</code> (and many many more)?</li>\n<li><code>ONE_SECOND </code> is really <code>SECOND_IN_MILLIS</code> to avoid misunderstandings.</li>\n</ul>\n<h2>code convention</h2>\n<ol>\n<li>Method names are CamelCase, in java we don't use underscore.</li>\n</ol>\n<ul>\n<li><code>field_init();</code> would be <code>fieldInit();</code></li>\n<li><code>icons_init();</code> would be <code>iconsInit();</code></li>\n</ul>\n<ol start=\"2\">\n<li>brackets are at the end of the statement</li>\n</ol>\n<pre><code>if(condition){\n ...\n}\n</code></pre>\n<ol start=\"3\">\n<li>Always use braces for control flow structure</li>\n</ol>\n<ul>\n<li><code>GameParamsWindow.getNumber</code>: <code>if(getText().isEmpty()) return 0;</code></li>\n</ul>\n<h2>improved programm flow</h2>\n<p>avoid complicated if/else structure, <code>Game</code>:</p>\n<pre><code>public void clickCell(Cell selectedCell){ \n if(selectedCell.type==Cell.Type.MINED) {\n status=GameStatus.LOST;\n uncoverAllMines();\n //remove complicated else trail here!\n return;\n }\n \n // Clicked cell is clear\n uncoverCells(selectedCell);\n if(isVictory()) { // Check if there are any covered cells without mines\n status=GameStatus.VICTORY; // there aren't))\n flagAllMines(); \n }\n}\n</code></pre>\n<h2>provide tests</h2>\n<p>sadly i do not see any tests, i would apprechiate to see those too... in goodwill i think you just didn't post them ;-)</p>\n<h2>use an IDE</h2>\n<p>the way your code is formatted shows that you don't use an IDE for Developement - or at least you do not use its fully potential. An IDE would help you to handle naming conventions and code formatting just by pressing one key.</p>\n<h2>summary</h2>\n<p>the whole code is full of shadows of procedural legacy ^_ ^. whenever you do any primitive access you should stop and think: why do i access primitives directly, why do i not use a proper method? methods are the heart of object orientated programming. the less you use them the further away you are from oop.</p>\n<h2>update - details on oop cell</h2>\n<p>how could an implementation of the neighbour-hood relation look like?</p>\n<pre><code>class Cell{\n private final Location location;\n\n Cell(Location location){\n this.location = location;\n }\n\n Set&lt;Location&gt; getSurroundedLocations(){\n return location.getSourroundingLocations();\n }\n}\n</code></pre>\n<pre><code>class Location{\n final int x;\n final int y;\n\n Location(int x, int y){\n this.x = x;\n this.y = y;\n }\n\n Set&lt;Location&gt; getSourroundingLocations(){\n return new HashSet&lt;&gt;(Arrays.asList(\n new Location(x-1, y-1),\n new Location(x-1, y),\n new Location(x-1, y+1),\n new Location(x, y-1),\n new Location(x, y+1),\n new Location(x+1, y-1),\n new Location(x+1, y),\n new Location(x+1, y+1));\n }\n}\n</code></pre>\n<pre><code>class Game{\n\n Set&lt;Cell&gt; minefield; \n\n protected Set&lt;Cell&gt; getCellNeighbours(Cell myCell){\n return minefield.stream().\n filter(c -&gt; myCell.getSourroundingLocations.contains(c.location)).\n collect(Collectors.toSet());\n }\n}\n</code></pre>\n<h2>update - details on <a href=\"https://clean-code-developer.com/grades/grade-2-orange/#Separation_of_Concerns_SoC\" rel=\"nofollow noreferrer\">&quot;seperation of concerns&quot;</a></h2>\n<p>The Separation of Concerns principle is closely connected to the <a href=\"https://clean-code-developer.com/grades/grade-2-orange/#Single_Responsibility_Principle_SRP\" rel=\"nofollow noreferrer\">Single Responsibility principle</a>.</p>\n<p>TL'DR\nput Things where they belong to - as a car, motor stuff comes to the motor class, gear stuff to the gear class.</p>\n<p><strong>part <code>Cell</code></strong><br>\nA <code>Cell</code> has attributes and behaviour - and they should be placed within the <code>Cell</code> class. A <code>Cell</code> is responsible to hold (or not) hold a mine. Its state can be covered, uncovered, flagged (and defused?). That is greatly solved by your model (attributes &amp; enums are very nice).</p>\n<p>But to work with this <code>Cell</code> there might be <strong>methods</strong> required. E.g. for getting the state (not the <code>State</code> enum) of the <code>Cell</code>. So if you want to handle a click on the <code>Cell</code> you might want to know if this <code>Cell</code> is not yet handled. so you would provide the specific method <code>Cell.isUnhandled()</code>, which returns true if it is either/or, otherwise returns false;</p>\n<p>Another Example: To reveal the board you might want to reveal each <code>Cell</code>, so there might be a method <code>uncover()</code> which does exactly that. it does <em>the magic of uncovering</em>, where it happens. And it does even handle the fact, that a <code>Cell</code> might already have been uncovered. this is called single responsibility and the method is on the right place (Separation of concerns).</p>\n<p>Bonus: Your cell is very testable now. Invovoke <code>Cell.unCover()</code> on different <code>Cells</code> and see if the uncover behaviour is as expected.</p>\n<p><strong>part <code>Board</code></strong><br>\na <code>Board</code>is responsible to assemble <code>Cells</code>. (no - it is <strong>not responsible</strong> to assemble <code>Cells</code> in <strong>Rows and Columns</strong> - Rows and Columns are never used on any action).</p>\n<p><strong>SideNote</strong><br>\nYou decided to abuse the <code>Board</code> as <code>Game</code>, something i'm not 100% in with. It violates the Single responsibility, a board is single/only responsible to manage the cells in a form of grid - nothing more, nothing less.</p>\n<p>When you create or re-create your board have to distribute <code>Cells</code> on the <code>Board</code>. According to the <em><a href=\"https://clean-code-developer.com/grades/grade-3-yellow/#Principle_of_Least_Astonishment\" rel=\"nofollow noreferrer\">principle of least astonishment</a></em> i would expect to have a method <code>setup()</code> on the <code>Board</code> that does exactly that. Again, by doing the <em>setup Board Magic</em> on the Board we follow the Single Responsibility Principle and the Separation of Concerns.</p>\n<p>If you think that the <code>Board.setup()</code> method does more than merely distribute the covered/uncovered <code>Cells</code> randomly over the board... then you might have an idea of a <code>BoardGenerator</code> in mind? In this case: do it! create a class <code>BoardGenerator</code> and add the <code>BoardGenerator</code> to the the Board and delegate the <code>setup</code> call to the Generator.</p>\n<p><strong>Delegation example:</strong></p>\n<pre><code>class Board{//Game\n\n BoardGenerator generator;\n Set&lt;Cell&gt; cells;\n\n void setup(SetupParameters parameters){\n cells = generator.setup(parameters);\n }\n}\ncalls \n</code></pre>\n<p><strong>already done nicely</strong><br>\nyou did very well on injection the setup Parameters. That part was done good in your code!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T12:10:36.653", "Id": "531930", "Score": "0", "body": "Please, tell me, how should the direction object work? (for getting neighbour cells)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T15:12:44.617", "Id": "531951", "Score": "0", "body": "i have updated my answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T17:19:39.797", "Id": "531973", "Score": "0", "body": "Thank you. P.S. Should I use separate getter and setter functions for cell properties like \"mined\", \"flagged\", etc? Or it might be a good idea to store all the such properties in single data structure (and use single getter and setter function passing parameter name to them))?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T19:21:21.663", "Id": "531980", "Score": "0", "body": "P.S. I've just noticed that I have to rewrite plantMines too, but I have to pick random elements from set (that might be too slow). What could I do here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T07:12:11.823", "Id": "532017", "Score": "0", "body": "i tried to point out that you don't have to write getters&setters, but instead write methods that provide the desired information" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T08:43:25.560", "Id": "532023", "Score": "1", "body": "`return minefield.stream().filter(c -> myCell.getSourroundingLocations.contains(c.location))` will call rows*cols times `myCell.getSurroundingLocations()`. Each time building the same HashSet with 9 elements ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T08:54:51.420", "Id": "532024", "Score": "0", "body": "@Holger see [beware of optimization](https://clean-code-developer.com/grades/grade-1-red/#Beware_of_Optimizations) - value readability (KISS) over performance... yes, imaging a field of 10000x10000 - it would take you ~3 years to solve it, when you are able to check one cell/second" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T08:56:39.160", "Id": "532025", "Score": "0", "body": "@Holger point taken, you can create a final field of the surrounding locations, to prevent a new generation every time..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T17:19:38.363", "Id": "532072", "Score": "1", "body": "@MartinFrank, could I also show you changed source code, please? I'll update the post soon. I've tried to take your remarks into account" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T17:54:18.160", "Id": "532078", "Score": "0", "body": "it is very important to **not change the current review!!** these are the rules of codereview.stackexchange. But i would be really glad to see your progress! If you have any updates, please open a new question. Its a good idea to make up a follow up question!!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T17:55:00.627", "Id": "532079", "Score": "0", "body": "your question makes me want to write my own version of MineSweeper^^" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T18:27:29.103", "Id": "532086", "Score": "0", "body": "P.S. This: filter(x->myCell.getNearbyLocations().contains(x.location)) part is VERY slow even on 9 x 9 board" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T18:29:04.093", "Id": "532087", "Score": "0", "body": "yes - i guess you are right, my eye was not so strong on performance ..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T18:29:41.240", "Id": "532088", "Score": "0", "body": "can you notify me when you have updates on your project, please?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T18:30:00.107", "Id": "532089", "Score": "0", "body": "Do you know is something could be done here? P.S. Yes, I'll notify you" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T18:31:20.947", "Id": "532090", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/131085/discussion-between-maxim-voloshin-and-martin-frank)." } ], "meta_data": { "CommentCount": "16", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T09:42:56.073", "Id": "269603", "ParentId": "269524", "Score": "4" } } ]
{ "AcceptedAnswerId": "269603", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T19:25:47.433", "Id": "269524", "Score": "9", "Tags": [ "java", "object-oriented", "minesweeper" ], "Title": "Minesweeper implementation java" }
269524
<p>This is following up on this <a href="https://codereview.stackexchange.com/questions/269425/implementing-stdformat">question</a></p> <p>In this part, I wanted to be able to choose arguments by index and have a placeholder for the format of the argument. As usually happens, my initial implementation was pretty much straightforward. Unfortunately, things get a bit ugly from here…</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;charconv&gt; #include &lt;iostream&gt; #include &lt;limits&gt; #include &lt;sstream&gt; #include &lt;string&gt; #include &lt;string_view&gt; #include &lt;vector&gt; namespace jdt { struct Segment { Segment(std::size_t offset, std::size_t count, std::size_t argument = std::numeric_limits&lt;std::size_t&gt;::max(), bool braceError = false) : offset{ offset }, count{ count }, argument{ argument }, braceError{ braceError } { } std::size_t offset; std::size_t count; std::size_t argument; bool braceError; }; struct Argument { Argument(const std::string&amp; format) : format{ format }, handled{ false } { } std::string format; std::string text; bool handled; }; template&lt;typename T&gt; void format_helper(std::vector&lt;Argument&gt;&amp; arguments, std::size_t&amp; index, const T&amp; value) { if (index &lt; arguments.size()) { Argument&amp; arg = arguments[index]; std::ostringstream oss; oss &lt;&lt; value; arg.text = oss.str(); arg.handled = true; index++; } } template&lt;typename... Targs&gt; std::string format(std::string_view str, Targs...args) { // PHASE 1 - parse format string std::vector&lt;Segment&gt; segments; std::vector&lt;Argument&gt; arguments; std::size_t offset = 0; std::size_t index = str.find('{'); while (index != std::string::npos) { // check for literal open-braces character if (str[index + 1] == '{') { segments.emplace_back(offset, index - offset + 1); offset = index + 2; } else { // check if the next part is an argument index std::size_t argindex = arguments.size(); std::size_t startOfArg = index; auto ret = std::from_chars(str.data() + index + 1, str.data() + str.size(), argindex); index = ret.ptr - str.data(); // find closing brace bool braceError = false; std::size_t closeBrace = str.find('}', index); if (closeBrace == std::string::npos) { braceError = true; closeBrace = str.size(); } // check for format specifier if (str[index] == ':') index++; // add to vectors arguments.emplace_back(std::string(str.substr(index, closeBrace - index))); segments.emplace_back(offset, startOfArg - offset, argindex, braceError); offset = closeBrace + 1; } index = str.find('{', offset); } // PHASE 2 - Recursive variadic template index = 0; (format_helper(arguments, index, args), ...); // PHASE 3 - Stich the string back together std::ostringstream oss; for (auto&amp; segment : segments) { oss &lt;&lt; str.substr(segment.offset, segment.count); if (segment.braceError == true) { oss &lt;&lt; &quot;{ error: no matching '}' found&quot;; } else { if (segment.argument != std::numeric_limits&lt;std::size_t&gt;::max()) { if (segment.argument &lt; arguments.size() &amp;&amp; arguments[segment.argument].handled) oss &lt;&lt; arguments[segment.argument].text; else oss &lt;&lt; format(&quot;{{ error: invalid arg index: {} }&quot;, segment.argument); } } } if (offset &lt; str.size()) oss &lt;&lt; str.substr(offset); return oss.str(); } } int main() { int a = 5; double b = 3.14; std::string c(&quot;hello&quot;); // simple arguments std::cout &lt;&lt; jdt::format(&quot;a = {}, b = {}, c = {}\n&quot;, a, b, c); // arguments with indexes std::cout &lt;&lt; jdt::format(&quot;a = {2}, b = {1}, c = {0}\n&quot;, a, b, c); // literal open-braces character std::cout &lt;&lt; jdt::format(&quot;let object = {{\&quot;a\&quot;: {0}, \&quot;b\&quot;: {1}, \&quot;c\&quot;: \&quot;{2}\&quot;};\n&quot;, a, b, c); // too few arguments std::cout &lt;&lt; jdt::format(&quot;a = {0}, b = {1}, c = {2}\n&quot;, a, b); // invalid argument indexes std::cout &lt;&lt; jdt::format(&quot;a = {0}, b = {10}, c = {2}\n&quot;, a, b, c); // too many arguments std::cout &lt;&lt; jdt::format(&quot;a = {2}, b = {1}, c = {0}\n&quot;, a, b, c, 3, 4, 5); // missing closing brace } std::cout &lt;&lt; jdt::format(&quot;a = {2}, b = {1}, c = {0\n&quot;, a, b, c); } </code></pre>
[]
[ { "body": "<h1>Throw exceptions on format errors</h1>\n<p>In your code, an error in the format string or the number of arguments will cause <code>jdt::format()</code> to return a valid string anyway, just with the error message inside the returned string. This is very bad, as it will just let the program continue with incorrect output without the program being able to notice or handle the error in any way.</p>\n<p>Since the intended usage is to be able to write code like <code>std::cout &lt;&lt; jdt::format(...)</code>, the best way to report an error is to throw an exception, just like <code>std::format()</code> does.</p>\n<h1>Fail fast</h1>\n<p>While scanning the format string for opening and closing braces, the moment you know you are missing a closing brace you can throw an exception. Furthermore, before calling <code>format_helper()</code>, you can check that <code>sizeof...(Targs) &gt;= arguments.size()</code>, and if that is <code>false</code>, again throw an exception.</p>\n<h1>Pass format arguments by <code>const</code> reference</h1>\n<p>To avoid making copies of the arguments, make sure they are passed by <code>const</code> reference, like so:</p>\n<pre><code>template&lt;typename... Targs&gt;\nstd::string format(std::string_view str, const Targs&amp;... args) {\n ...\n}\n</code></pre>\n<h1>Avoid the stiching phase</h1>\n<p>In your code, in phase 2 you are converting all the arguments to <code>std::string</code>s, and then in phase 3 you are building the final output. This might save some effort in the rare case that you are referencing the same argument multiple times in the format string, but now you are using more memory since you have to first store the literal parts of the format string and the converted arguments in vectors. I would rewrite the code so that you build the final result in one go, by alternatively adding a literal section of the format string, then format an argument, then the next literal section, and so on.</p>\n<p>Also note that your approach of first building the vector <code>arguments</code> will no longer work as soon as you start implementing <a href=\"https://en.cppreference.com/w/cpp/utility/format/formatter#Standard_format_specification\" rel=\"nofollow noreferrer\">format specifiers</a>, as then you can have the same argument formatted twice but with different format specifiers.</p>\n<p>The problem, as you've already noticed of course, is how to be able to do random access to the parameter pack <code>args</code>. This can be solved in a different way:</p>\n<h1>Run-time indexing of arguments</h1>\n<p>You might have a look at how <code>std::format</code> handles this problem. In particular, it introduces the class <a href=\"https://en.cppreference.com/w/cpp/utility/format/basic_format_args\" rel=\"nofollow noreferrer\"><code>std::format_args</code></a> to store the arguments <em>before</em> they are converted to strings, and provides a <code>get()</code> member function to access them by index. There is also a helper function <a href=\"https://en.cppreference.com/w/cpp/utility/format/make_format_args\" rel=\"nofollow noreferrer\"><code>std::make_format_args()</code></a> that you can pass <code>args...</code> and which will return a <code>std::format_args</code> object. But if you actually look at the <a href=\"https://github.com/fmtlib/fmt/blob/master/include/fmt/core.h\" rel=\"nofollow noreferrer\">implementation</a>, you'll see that this is a rabbit hole that goes very deep.</p>\n<p>A simpler solution that will do for now is to use fold expressions again, but now use it to build the equivalent of a <code>for</code>-loop to visit each argument until we reach the desired one, and then write it to the output. For example:</p>\n<pre><code>template&lt;typename... Targs&gt;\nstatic bool format_one(std::ostream &amp;out, size_t i, const Targs&amp;... args) {\n auto visitor = [&amp;](const auto&amp; arg) {\n if (!i--) {\n out &lt;&lt; arg;\n return true;\n } else {\n return false;\n }\n };\n\n return (visitor(args) || ...);\n}\n</code></pre>\n<p>Then you could call it like so:</p>\n<pre><code>template&lt;typename... Targs&gt;\nstd::string format(std::string_view str, const Targs&amp;... args) {\n std::ostringstream oss;\n ...\n for (/* each format specifier in str */) {\n std::size_t argindex = /* get the argument's index */;\n ...\n if (!format_one(oss, argindex, args...)) {\n /* handle the argument not being found */\n }\n }\n ...\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T12:04:47.167", "Id": "531781", "Score": "2", "body": "In the first iteration, I advised _against_ erroring with incorrect format, because the format string may well come from a translation database, rather than from a programmer. If we throw an exception, its content needs to be specific enough to identify the faulty string and the actual problem detected." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T14:06:14.123", "Id": "531799", "Score": "1", "body": "My initial thought was also to simply throw an exception and be done with it but @TobySpeight had a valid point. I’m not sure which way will be best. Perhaps having two different functions, one throwing and one not? Re. Run-time indexing of arguments, in hindsight that makes much more sense than my halve baked stitching scheme =)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T17:07:24.167", "Id": "531800", "Score": "0", "body": "I think that two different functions would be the worst of all worlds! One thing you might do is have one function whose behaviour can be changed at run-time (e.g. via environment variables) for translators' convenience. But exception might be a good way to go, _if_ there's sufficient information conveyed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T19:10:19.770", "Id": "531807", "Score": "0", "body": "I recommend failing hard if there is a format string error. This is both the right thing for translators and for end-users. Consider that someone who doesn't speak English and depending on the translation might not understand an English error message being inserted into the output. They are then left with a partial message in their own language, which might be confusing. Consider seeing *\"Press OK { fout: geen corresponderende '}' gevonden }\"* when the message should have been *\"Press OK to delete all data\"*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T22:55:53.720", "Id": "532006", "Score": "0", "body": "I agree that throwing an exception on a format error is problematic in real life. Consider a Warning log message that isn't normally executed. A mistake there will turn the warning into a fatal error. And, it was not detected right away because the unit tests don't provide coverage for every single warning case. I've gone to some effort to re-wrap or alter formatting libraries to _not_ have this behavior." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T07:22:53.613", "Id": "532018", "Score": "0", "body": "The best would be to have [compile-time format string checking](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2021/p2216r3.html) if possible, and then let run-time format strings somehow give a warning instead of throwing if they are not correct." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T11:54:56.937", "Id": "269543", "ParentId": "269526", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T20:50:28.143", "Id": "269526", "Score": "3", "Tags": [ "c++", "c++20" ], "Title": "Implementing std::format - Part 2" }
269526
<p>I am learning Vue.JS and I'm creating a simple todo app, where each list has a unique id. I am iterating through all of the list to create a Vue instance:</p> <pre class="lang-html prettyprint-override"><code>&lt;div id=&quot;todo-list-1&quot; class=&quot;todo-list&quot;&gt;...&lt;/div&gt; &lt;div id=&quot;todo-list-2&quot; class=&quot;todo-list&quot;&gt;...&lt;/div&gt; &lt;div id=&quot;todo-list-3&quot; class=&quot;todo-list&quot;&gt;...&lt;/div&gt; </code></pre> <pre class="lang-js prettyprint-override"><code>// main.js document.querySelectorAll('.todo-list').forEach(list =&gt; { new Vue({ el: `#${list.id}`, render: h =&gt; h(App) }) }) </code></pre> <p>I want to create a &quot;completed&quot; state, which would be true when all items in a list are completed. So <code>#todo-list-1</code> has a completed state, same with <code>#todo-list-2</code> and <code>#todo-list-3</code>.</p> <p>What would be a good approach to this problem? how can I handle the state for individual vue instances?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T22:54:47.997", "Id": "531755", "Score": "0", "body": "You're essentially just asking us to review a for-loop. CodeReview is about reviewing code, not Grisham novel recommendations. https://vuejsexamples.com/a-todo-list-app-using-vuejs/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T23:00:55.223", "Id": "531756", "Score": "0", "body": "thanks, I am asking for recommendation on how to approach this problem, I cant get my head around how to set a simple state for each instance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T23:06:50.157", "Id": "531757", "Score": "0", "body": "The answer to your question is in here: https://next.vuex.vuejs.org/ This kind of question does not belong on this StackExchange." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T23:08:33.580", "Id": "531758", "Score": "0", "body": "I checked the docs there already, looks like multiple store is not well supported https://github.com/vuejs/vuex/issues/414" } ]
[ { "body": "<p>I consider Vuex advanced state management, and for the sake of your simple application I, personally, would value a simpler data-centric approach.</p>\n<p>To this end, I propose you focus on creating a single instance that can have multiple todo-lists inside it represented as components.</p>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;div id=&quot;app&quot;&gt;\n &lt;TodoList v-for=&quot;list in lists&quot; :key=&quot;list.id&quot; /&gt;\n&lt;/div&gt;\n</code></pre>\n<pre class=\"lang-js prettyprint-override\"><code>data() {\n return {\n lists: [\n {\n id: 1,\n todos: []\n },\n // ...\n ]\n }\n}\n</code></pre>\n<p>Obviously, you'd need to represent your todos as a list of todo lists (with todos inside). You'll also need to ensure correct state management but JavaScripts pass-by-reference for objects will save you time here.</p>\n<p>In order to detect if all todos are completed you could add a getter into the root instance to detect them all, or in the component to detect them per-instance.</p>\n<p>I hope this helps set you on the right path, the best thing to do in most cases is start with your data-model as Vue is a data-centric framework.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T22:14:59.657", "Id": "531752", "Score": "0", "body": "thanks, the thing is that react has this useState hook which I used before, I need to have different instances because I am passing different api endpoints for each todo list." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T22:26:47.720", "Id": "531753", "Score": "0", "body": "If they fundamentally behave in the same way, they are the same component. If you are passing different bits of data, you can still do that. `:list=\"list\"` will pass the entire list object to the component. You could just as easily pass config for the APIs." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T22:08:49.783", "Id": "269530", "ParentId": "269527", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T21:08:09.217", "Id": "269527", "Score": "0", "Tags": [ "javascript", "vue.js" ], "Title": "Good approach to simple state management in vuejs for multiple instances" }
269527
<h1>C++ Event class</h1> <p>From the desire of having a callback function which includes a void* userdata argument, I've made this generic event class.</p> <p><strong>It is tested and working, but some desired features are missing</strong></p> <ul> <li>Allow to have a parameter less event with no userdata</li> <li>Allow to specify a TResult template argument, for example to have operator() returns bool instead of void.</li> </ul> <p><strong>Also I do not like the fact that</strong></p> <ul> <li>TUserData is turned into a pointer for _userdata and into a reference for the callback function argument. It does not seems intuitive enough to use.</li> </ul> <p><strong>The problem with adding a TResult, is that the operator() function will</strong></p> <ul> <li>Not compile, either because TResult is void and it tries to return a value, or because TResult is not void and it does try to return something.</li> <li>Have to return a default value when _func is null.</li> </ul> <p>I've looked into template partial specialization but it does not seem to be a solution. Or does it?<br /> Would using concepts be of any help?<br /> Any generic improvements to be made?</p> <h2>event.hpp</h2> <pre><code>#pragma once namespace shoujin { template&lt;typename TUserData, typename... TArguments&gt; class Event { using TFunc = void (*)(TArguments..., TUserData&amp;); TFunc _func; TUserData* _userdata; public: Event() : _func{}, _userdata{} {} Event(TFunc func, TUserData&amp; userdata) { _func = func; _userdata = &amp;userdata; } Event&amp; operator=(const Event&amp; rhs) { _func = rhs._func; _userdata = rhs._userdata; return *this; } ~Event() { _func = nullptr; _userdata = nullptr; } void operator()(TArguments... args) const { if(_func) _func(args..., *_userdata); } operator bool() const { return _func != nullptr; } }; } </code></pre> <h2>event_test.cpp</h2> <pre><code>#include &quot;CppUnitTest.h&quot; using namespace Microsoft::VisualStudio::CppUnitTestFramework; #define WIN32_LEAN_AND_MEAN #include &lt;Windows.h&gt; #include &lt;tchar.h&gt; #include &lt;shoujin/event.hpp&gt; using namespace shoujin; TEST_CLASS(EventTest) { static void OnEventTwoParam(int x, int y, int&amp; value) { value = x + y; } public: TEST_METHOD(Event_IsCopyConstructible) { Assert::IsTrue(std::is_copy_constructible_v&lt;Event&lt;void*&gt;&gt;); } TEST_METHOD(Event_IsCopyAssignable) { Assert::IsTrue(std::is_copy_assignable_v&lt;Event&lt;void*&gt;&gt;); } TEST_METHOD(Event_IsMoveConstructible) { Assert::IsTrue(std::is_move_constructible_v&lt;Event&lt;void*&gt;&gt;); } TEST_METHOD(Event_IsMoveAssignable) { Assert::IsTrue(std::is_move_assignable_v&lt;Event&lt;void*&gt;&gt;); } TEST_METHOD(Event_WhenTwoParam_EventRaised) { //Arrange int value; Event&lt;int, int, int&gt; event_two_param(OnEventTwoParam, value); int x{3}, y{2}; //Act event_two_param(x, y); //Assert Assert::AreEqual(x + y, value); } TEST_METHOD(Event_CopyAssignment_EventRaised) { //Arrange int value; Event&lt;int, int, int&gt; event_two_param; int x{3}, y{2}; event_two_param = {OnEventTwoParam, value}; //Act event_two_param(x, y); //Assert Assert::AreEqual(x + y, value); } TEST_METHOD(Event_OperatorBool_EventRaised) { //Arrange int value; Event&lt;int, int, int&gt; event_two_param; int x{3}, y{2}; //Act bool before = event_two_param; event_two_param = {OnEventTwoParam, value}; bool after = event_two_param; //Assert Assert::IsFalse(before); Assert::IsTrue(after); } }; </code></pre> <p><strong>All criticism is much appreciated.</strong></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T18:08:49.987", "Id": "531804", "Score": "0", "body": "A custom concept was added to force TUserData to be a pointer, and a UserDataEvent class was made with it. The Event class not no longer have any userdata support." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T18:12:40.153", "Id": "531805", "Score": "0", "body": "Making UserData a template instead of a void* does not seem to be good, because the component who declare and raise the event does not know what kind of user data the listeners will need, and the listeners do not declare anything. This is why using void* is more flexible. In C language, the listener can simply define his OnEvent function to receive the right userdata type, and C will allow it, but C++ won't implicitly convert void* to another pointer type, so the listener function has to receive void* and reinterpret_cast it." } ]
[ { "body": "<p>Since C++11, the standard library provides <a href=\"https://en.cppreference.com/w/cpp/utility/functional/function\" rel=\"nofollow noreferrer\"><code>std::function</code></a>, which basically does what your <code>Event</code> class does: store a function and any associated data you want captured. For example, your <code>Event_CopyAssignment_EventRaised</code> test can be rewritten like so:</p>\n<pre><code>#include &lt;functional&gt;\n...\nTEST_METHOD(Event_CopyAssignment_EventRaised) {\n int value;\n std::function&lt;void(int, int)&gt; event_two_param;\n int x{3}, y{2};\n\n using namespace std::placeholders;\n bool before = (bool)event_two_param;\n event_two_param = std::bind(OnEventTwoParam, _1, _2, std::ref(value));\n bool after = (bool)event_two_param;\n\n event_two_param(x, y);\n Assert::AreEqual(x + y, value);\n Assert::IsFalse(before);\n Assert::IsTrue(after);\n}\n</code></pre>\n<p>Assigning the function to <code>event_two_param</code> such that it captures the reference to <code>value</code> is a bit awkward that way, but you can also use a lambda to do the same:</p>\n<pre><code>event_two_param = [&amp;](int x, int y){ OnEventTwoParam(x, y, value); };\n</code></pre>\n<p>Or just use a lambda expression directly to sum two values:</p>\n<pre><code>event_two_param = [&amp;](int x, int y){ value = x + y; };\n</code></pre>\n<p>Note that <code>std::function</code> also has an <a href=\"https://en.cppreference.com/w/cpp/utility/functional/function/operator_bool\" rel=\"nofollow noreferrer\"><code>operator bool()</code></a>, but it is marked <code>explicit</code> to avoid accidental conversion to <code>bool</code>, so you have to explicitly cast it if you want to use it like in your test. But you can use it without casting in an <code>if</code>-statement:</p>\n<pre><code>if (event_two_param) {\n /* event_two_param has a function associated with it */\n ...\n}\n</code></pre>\n<p><code>std::function</code> also solves all the issues you have mentioned: you can also use it for functions that don't take a pointer to userdata, and you can have it store functions that return a value:</p>\n<pre><code>std::function&lt;int()&gt; event_no_param;\nevent_no_param = []{ return 42; };\nint value = event_no_param();\nAssert::AreEqual(value, 42);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T21:27:49.557", "Id": "531820", "Score": "0", "body": "Very informative, and your answer gives me leads into learning more about std::function, and also about the fact that a template parameter can be a function signature such as void(int, int). Thank you for your answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T19:48:40.150", "Id": "269559", "ParentId": "269531", "Score": "1" } } ]
{ "AcceptedAnswerId": "269559", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-29T22:12:58.103", "Id": "269531", "Score": "2", "Tags": [ "c++", "template", "event-handling", "callback", "c++20" ], "Title": "Generic Event class" }
269531
<p>I wrote this basic CRUD app + simple report so I could practice talking to a db directly. I purposefully avoided repository pattern and Entity Framework and only used a library to show the coming data a bit more readable.</p> <p>Having that in mind, I'd love to get some feedback, particularly in regards to bad practices that I should avoid in my professional career as developer. You can be brutal, I take criticism well. :)</p> <p>I'll post just the code for my controller and the rest in this link to my repo:</p> <p>Here's the link to my repo. <a href="https://github.com/cappuccinocodes/CodeTracker1" rel="nofollow noreferrer">https://github.com/cappuccinocodes/CodeTracker1</a></p> <pre><code>using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using ConsoleTableExt; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore.Migrations.Operations; namespace CodeTracker1 { internal static class CodingController { static readonly string connectionString = ConfigurationManager.AppSettings.Get(&quot;ConnectionString&quot;); internal static void GetUserCommand() { Console.WriteLine(&quot;\n\nMAIN MENU&quot;); Console.WriteLine(&quot;\nWhat would you like to do?&quot;); Console.WriteLine(&quot;\nType 0 to Close Application.&quot;); Console.WriteLine(&quot;Type 1 to View All Records.&quot;); Console.WriteLine(&quot;Type 2 to Insert Records.&quot;); Console.WriteLine(&quot;Type 3 to Delete Records.&quot;); Console.WriteLine(&quot;Type 4 to Update Records.&quot;); Console.WriteLine(&quot;Type 5 to Generate Reports.&quot;); string commandInput = Console.ReadLine(); if (string.IsNullOrEmpty(commandInput)) { Console.WriteLine(&quot;\nInvalid Command. Please choose an option\n&quot;); GetUserCommand(); } int command = Convert.ToInt32(commandInput); switch (command) { case 0: Environment.Exit(0); break; case 1: Get(); break; case 2: Post(); break; case 3: Delete(); break; case 4: Update(); break; case 5: Reports.GetReportCommand(); break; default: Console.WriteLine(&quot;\nInvalid Command. Please type a number from 0 to 5.\n&quot;); GetUserCommand(); break; } } internal static void Post() { long date = GetDateInput(); long duration = GetDurationInput(); using (var connection = new SqliteConnection(connectionString)) { connection.Open(); var tableCmd = connection.CreateCommand(); tableCmd.CommandText = $&quot;INSERT INTO coding (date, duration) VALUES ({date}, {duration})&quot;; tableCmd.ExecuteNonQuery(); connection.Close(); } string inputDate = new DateTime(date).ToString(&quot;dd-MM-yy&quot;); string inputDuration = new DateTime(duration).ToString(&quot;HH:mm&quot;); Console.WriteLine($&quot;\n\nYour time was logged. Date: {inputDate}; Duration: {inputDuration}.\n\n&quot;); GetUserCommand(); } internal static void Delete() { Console.WriteLine(&quot;\n\nPlease type the Id of the record would like to delete. Type 0 to return to main menu.\n\n&quot;); string commandInput = Console.ReadLine(); if (string.IsNullOrEmpty(commandInput)) { Console.WriteLine(&quot;\nYou have to type an Id.\n&quot;); Delete(); } var Id = Int32.Parse(Console.ReadLine()); if (Id == 0) GetUserCommand(); using (var connection = new SqliteConnection(connectionString)) { connection.Open(); var tableCmd = connection.CreateCommand(); tableCmd.CommandText = $&quot;DELETE from coding WHERE Id = '{Id}'&quot;; int rowCount = tableCmd.ExecuteNonQuery(); while (rowCount == 0) { Console.WriteLine($&quot;\n\nRecord with Id {Id} doesn't exist. Try Again or type 0 to return to main menu. \n\n&quot;); Id = Int32.Parse(Console.ReadLine()); if (Id == 0) GetUserCommand(); if (rowCount != 0) break; } } GetUserCommand(); } internal static void Get() { using (var connection = new SqliteConnection(connectionString)) { connection.Open(); var tableCmd = connection.CreateCommand(); tableCmd.CommandText = &quot;SELECT * FROM coding&quot;; List&lt;Coding&gt; tableData = new List&lt;Coding&gt;(); SqliteDataReader reader = tableCmd.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { tableData.Add( new Coding { Id = reader.GetInt32(0), Date = new DateTime(reader.GetInt64(1)).ToShortDateString(), Duration = new TimeSpan(reader.GetInt64(2)).ToString() }); } } else { Console.WriteLine(&quot;\n\nNo rows found.\n\n&quot;); } reader.Close(); Console.WriteLine(&quot;\n\n&quot;); ConsoleTableBuilder .From(tableData) .ExportAndWriteLine(); Console.WriteLine(&quot;\n\n&quot;); GetUserCommand(); } } internal static void Update() { Console.WriteLine(&quot;\n\nPlease type Id of the record would like to update. Type 0 to return to main manu.\n\n&quot;); string commandInput = Console.ReadLine(); if (string.IsNullOrEmpty(commandInput)) { Console.WriteLine(&quot;\nYou have to type an Id.\n&quot;); Update(); } var Id = Int32.Parse(commandInput); if (Id == 0) GetUserCommand(); using (var connection = new SqliteConnection(connectionString)) { connection.Open(); var checkCmd = connection.CreateCommand(); checkCmd.CommandText = $&quot;SELECT EXISTS(SELECT 1 FROM coding WHERE Id = {Id})&quot;; int checkQuery = Convert.ToInt32(checkCmd.ExecuteScalar()); if (checkQuery == 0) { Console.WriteLine($&quot;\n\nRecord with Id {Id} doesn't exist.\n\n&quot;); GetUserCommand(); } long date = GetDateInput(); long duration = GetDurationInput(); var tableCmd = connection.CreateCommand(); tableCmd.CommandText = $&quot;UPDATE coding SET date = {date}, duration = {duration} WHERE Id = {Id}&quot;; tableCmd.ExecuteNonQuery(); string inputDate = new DateTime(date).ToString(&quot;dd-MM-yy&quot;); string inputDuration = new DateTime(duration).ToString(&quot;HH:mm&quot;); Console.WriteLine($&quot;\n\nYour time was logged: date({inputDate}), duration({inputDuration}).\n\n&quot;); connection.Close(); } GetUserCommand(); } internal static long GetDateInput() { Console.WriteLine(&quot;\n\nPlease insert the date: (Format: dd-mm-yy). Type 0 to return to main manu.\n\n&quot;); DateTime result; string dateInput = Console.ReadLine(); if (dateInput == &quot;0&quot;) GetUserCommand(); bool success = DateTime.TryParseExact(dateInput, &quot;dd-MM-yy&quot;, new CultureInfo(&quot;en-US&quot;), DateTimeStyles.None, out result); if (success) { var parsedDate = DateTime.ParseExact(dateInput, &quot;dd-MM-yy&quot;, new CultureInfo(&quot;en-US&quot;)); long date = parsedDate.Ticks; return date; } Console.WriteLine(&quot;\n\nNot a valid date. Please insert the date with the format: dd-mm-yy.\n\n&quot;); return GetDateInput(); } internal static long GetDurationInput() { Console.WriteLine(&quot;\n\nPlease insert the duration: (Format: hh:mm). Type 0 to return to main manu.\n\n&quot;); TimeSpan timeSpan; string durationInput = Console.ReadLine(); if (durationInput == &quot;0&quot;) GetUserCommand(); bool success = TimeSpan.TryParseExact(durationInput, &quot;h\\:mm&quot;, CultureInfo.InvariantCulture, out timeSpan); if (success) { var parsedDuration = TimeSpan.Parse(durationInput); long date = parsedDuration.Ticks; if (date &lt; 0) { Console.WriteLine(&quot;\n\nNegative Time Not allowed.\n\n&quot;); GetDurationInput(); } return date; } Console.WriteLine(&quot;\n\nNot a valid time.\n\n&quot;); return GetDurationInput(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T08:05:29.573", "Id": "531913", "Score": "1", "body": "My advice: use Dapper instead of ADO.NET: https://dapper-tutorial.net/" } ]
[ { "body": "<p>Your code is very neat, and I see that you tried to take care of the basics like disposing of the connection. My main concern is the recursive call to <code>GetUserCommand</code>.</p>\n<p><b>Do not use recursion where you could have a simple loop!</b></p>\n<p>I would suggest that you change <code>GetUserCommand</code> to the following:</p>\n<pre><code>internal static void GetUserCommand()\n{\n bool closeApp = false;\n while (closeApp == false)\n {\n Console.WriteLine(&quot;\\n\\nMAIN MENU&quot;);\n Console.WriteLine(&quot;\\nWhat would you like to do?&quot;);\n Console.WriteLine(&quot;\\nType 0 to Close Application.&quot;);\n Console.WriteLine(&quot;Type 1 to View All Records.&quot;);\n // ...\n Console.WriteLine(&quot;Type 5 to Generate Reports.&quot;);\n\n string commandInput = Console.ReadLine();\n if (string.IsNullOrEmpty(commandInput))\n {\n Console.WriteLine(&quot;\\nInvalid Command. Please choose an option\\n&quot;);\n continue;\n }\n\n int command = Convert.ToInt32(commandInput);\n switch (command)\n {\n case 0:\n closeApp = true;\n break;\n case 1:\n Get();\n break;\n // ...\n default:\n Console.WriteLine(&quot;\\nInvalid Command. Please type a number from 0 to 5.\\n&quot;);\n break;\n }\n }\n}\n</code></pre>\n<p>In <code>Get()</code> you have a ticking time bomb:</p>\n<pre><code>internal static void Get()\n{\n using (var connection = new SqliteConnection(connectionString))\n {\n connection.Open();\n ...\n GetUserCommand();\n }\n}\n</code></pre>\n<p>This sort of thing has spoiled many good programmers' weekends/sanity. Here you never dispose of the connection and can eventually either run out of stack space or database handles / resources.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T13:30:03.027", "Id": "531938", "Score": "1", "body": "@BCdotWEB, That is correct, the problem in `Get()` is the recursive call to `GetUserCommand` before `using (var connection…` is out of the scope." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T14:36:35.867", "Id": "531948", "Score": "0", "body": "@BCdotWEB, see what happens in this example: [TIO](https://tio.run/##jZLbasJAEIbv9ylGryKixFtDC9JaKERarNDrdTOVgWQ37K5pQ/HZ081BcxDbzu38880/B2FmwoiiOBqSB3jLjcUkYEzE3BjY5A9KShSWlIQlPD@SSZXh@xjZNwMX6XEfk@jpvEmVqfNlqBRlmzbTaXBJ0Qd4gzTcw8KfXBQtpgynMyrG@bsmiyFJ9MZPq90qhPV2@7Jdwk4pSLjMq54gWupoNJ4EPdRaZqSVTFDa@fqLrOd3BCf2S8dN3iGD0MgtRmf8iXX3kimKoF4aXu3lT3RUF0Zd64NtzWb9tpoy5waM5da1J2mHBXAHfsBO5wO/anXQPGmu2ZRVrndorFcCYsww/of3sNQ5/BimTU3run4uL@O6nM@JJH7C4Gtu3bwyUgEdeHF1pGbyrvUNp@svrDD@5UqurCh@AA)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T14:53:30.157", "Id": "531949", "Score": "1", "body": "In this example [TIO](https://tio.run/##hZFbS8NAEIXf91dM@5QQUtLXBoWiEYQWJQZ83q5jGUh2w@42GiS/PeZSc1NwHkLgzPl25owwvjCiri@G5BleSmMxCxkTKTcGjuWdkhKFJSVhB4/3ZHJl@ClF9sWgqfxySknM@hy3U3q9LZWjHGXjeeEg0Ts4CxluYRu4Q8eIaavpMyrFzasmiweS6Kwf9sn@AFEcP8U7SJSCjMuyexPESF2t1m44Q0WyIK1khtJuok@yTjBpqFj/ne5YKHqDPgD8b0ffD2cETQW3CMZy25BI2qUBbiAIWfWT@7NWZ82za8hXWzdAgsY6LSDFAtPlGP0RnYLrdvkGKvFjcZy/oq2Gvw7focGDrTvbYjrGkdPvQ3fmYDA1trr@Bg), the connection object is disposed of properly, but the unchecked recursive call still leads to a stack overflow." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-04T09:06:27.887", "Id": "532239", "Score": "0", "body": "Thanks a lot for your feedback! I'll have a closer look." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-05T02:58:02.807", "Id": "532318", "Score": "1", "body": "Holy ghost! You have just changed my life. Haha. I finally understand the importance of while loops " } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T01:46:16.350", "Id": "269595", "ParentId": "269534", "Score": "1" } } ]
{ "AcceptedAnswerId": "269595", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T02:00:19.553", "Id": "269534", "Score": "1", "Tags": [ "c#", "sql", "console", "asp.net", "sqlite" ], "Title": "Beginner CRUD Console Application" }
269534
<h2>Problem Statement:</h2> <p>I am working on this simple dataset from <a href="https://www.kaggle.com/patrickb1912/ipl-complete-dataset-20082020" rel="nofollow noreferrer">Kaggle</a>. I have provided a snippet of data with only required columns in below table. Dataset is quite simple, it has all IPL (cricket) matches listed with teams who played each match (team1 and team2) along with winner of that match.</p> <p>Now I am trying to get total matches played by all teams along with matches won by each team, I have again provided a snippet of output below the code. Same can be performed by &quot;finding all occurrences of a particular team in column team1&quot; + &quot;finding all occurrences of a particular team in column team2&quot;.</p> <p>While the code does give proper result, I can sense this is not the best approach. I would like to know some better way to do it along with good practices and naming conventions to follow.</p> <h2>Dataset:</h2> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>team1</th> <th>team2</th> <th>winner</th> </tr> </thead> <tbody> <tr> <td>Royal Challengers Bangalore</td> <td>Kolkata Knight Riders</td> <td>Kolkata Knight Riders</td> </tr> <tr> <td>Kings XI Punjab</td> <td>Chennai Super Kings</td> <td>Chennai Super Kings</td> </tr> <tr> <td>Delhi Daredevils</td> <td>Rajasthan Royals</td> <td>Delhi Daredevils</td> </tr> <tr> <td>Mumbai Indians</td> <td>Royal Challengers Bangalore</td> <td>Royal Challengers Bangalore</td> </tr> <tr> <td>Kolkata Knight Riders</td> <td>Deccan Chargers</td> <td>Kolkata Knight Riders</td> </tr> <tr> <td>Rajasthan Royals</td> <td>Kings XI Punjab</td> <td>Rajasthan Royals</td> </tr> </tbody> </table> </div><h2>Code:</h2> <pre class="lang-sql prettyprint-override"><code>SELECT t1.team1 AS team, c_t1 + c_t2 AS played, c_w AS won, CAST(c_w AS FLOAT) / (c_t1 + c_t2) * 100 AS won_percentage FROM (SELECT team1, count(team1) AS c_t1 FROM ipl_m GROUP BY team1) AS t1 JOIN (SELECT team2, count(team2) AS c_t2 FROM ipl_m GROUP BY team2) AS t2 ON t1.team1 = t2.team2 JOIN (SELECT winner, count(winner) AS c_w FROM ipl_m GROUP BY winner) AS w ON t1.team1 = w.winner OR t2.team2 = w.winner ORDER BY won_percentage DESC; </code></pre> <h2>Resulting Table:</h2> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>team</th> <th>played</th> <th>won</th> <th>won_percentage</th> </tr> </thead> <tbody> <tr> <td>Chennai Super Kings</td> <td>178</td> <td>106</td> <td>59.55056179775281</td> </tr> <tr> <td>Mumbai Indians</td> <td>203</td> <td>120</td> <td>59.11330049261084</td> </tr> <tr> <td>Delhi Capitals</td> <td>33</td> <td>19</td> <td>57.57575757575758</td> </tr> <tr> <td>Sunrisers Hyderabad</td> <td>124</td> <td>66</td> <td>53.2258064516129</td> </tr> <tr> <td>Kolkata Knight Riders</td> <td>192</td> <td>99</td> <td>51.5625</td> </tr> </tbody> </table> </div><h2>Table Definition:</h2> <pre class="lang-sql prettyprint-override"><code>CREATE TABLE ipl_m ( id integer PRIMARY KEY, match_id integer NOT NULL, city VARCHAR(20) NOT NULL, date DATE NOT NULL, player_of_match VARCHAR(50), venue VARCHAR(75) NOT NULL, neutral_venue BOOLEAN NOT NULL, team1 VARCHAR(50) NOT NULL, team2 VARCHAR(50) NOT NULL, toss_winner VARCHAR(50) NOT NULL, toss_decision VARCHAR(5) NOT NULL, winner VARCHAR(50), result VARCHAR(10), result_margin float, eliminator CHAR(1) NOT NULL, method VARCHAR(3), umpire1 VARCHAR(50), umpire2 VARCHAR(50) ); </code></pre>
[]
[ { "body": "<p>Each row in <code>ipl_m</code> table has one <em>winner</em> and one <em>loser</em>.\nSo first extract <em>winners</em> and set field <code>result</code> (it will be used in counting) to <code>1</code>:</p>\n<pre><code>SELECT \n winner AS team,\n 1 as result\nFROM ipl_m\n</code></pre>\n<p>Next extract <em>losers</em> and set field <code>result</code> to <code>0</code>:</p>\n<pre><code>SELECT\n CASE\n WHEN team1 = winner THEN team2\n ELSE team1\n AS team,\n 0 as result\nFROM ipl_m\n</code></pre>\n<p>Combine two sets with <code>UNION</code>. Now <code>SELECT</code> from resulting set grouping by <code>team</code> column.</p>\n<pre><code>SELECT t.team AS team\n, COUNT(*) AS played\n, SUM(t.result) AS won\nFROM (\nSELECT \n winner AS team,\n 1 as result\nFROM ipl_m\nUNION\nSELECT\n CASE\n WHEN team1 = winner THEN team2\n ELSE team1\n AS team,\n 0 as result\nFROM ipl_m\n) AS t\nGROUP BY t.team\n</code></pre>\n<p>Your solution uses 4 <code>SELECT</code> and 2 <code>JOIN</code> operators. Mine uses 3 <code>SELECT</code> and 1 <code>UNION</code>. Using fewer operations is usually preferred.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T11:13:28.713", "Id": "532032", "Score": "0", "body": "Thanks for the answer. Initially your code didn't work as is, just needed to add an END to that CASE statement. Also UNION removes duplicates, so UNION ALL should be used instead. After making those changes, things work perfectly!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-02T11:43:14.533", "Id": "532035", "Score": "0", "body": "CASE ... END - my bad. UNION ALL - you are right !" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T19:32:34.400", "Id": "269557", "ParentId": "269536", "Score": "3" } } ]
{ "AcceptedAnswerId": "269557", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T04:21:38.087", "Id": "269536", "Score": "5", "Tags": [ "sql", "postgresql" ], "Title": "PostgreSQL: Grouping and Aggregating on multiple columns" }
269536
<p>It's an exercise from a RSpec-course, which I'm currently doing.</p> <p><strong>Task:</strong></p> <ul> <li><p>Create a compound expectation, which asserts the string sportscar starts with the substring &quot;sports&quot; and ends with the substring &quot;car&quot;.</p> </li> <li><p>Create a compound expectation, which asserts that the number 30 is even and that it responds to the times method.</p> </li> <li><p>Create a compound expectation, which asserts that the array [2, 4, 8, 16, 32, 64] includes the element 32 and starts with the elements 2, 4, and 8.</p> </li> </ul> <p><strong>My solution:</strong></p> <pre><code>RSpec.describe &quot;sportscar&quot; do it &quot;should start with 'sports' and end with 'car'&quot; do expect(subject).to start_with(&quot;sports&quot;).and end_with(&quot;car&quot;) end it &quot;30 is even and responds to the times-method&quot; do numb = 30 expect(numb.even?).to be true and numb.respond_to? :times end it &quot;shall include 32 and start with the values 2, 4, 8&quot; do arr = [2, 4, 8, 16, 32, 64] expect(arr).to include(32) and start_with(2, 4, 8) end end </code></pre> <p>Could it become improved? Perhaps more written in a Ruby-Idiomatic way?</p> <p>Are my message-strings (it &quot;should start with ...&quot; etc.) done in a good way? Or should it be written in a different way and if so: How?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T03:25:19.253", "Id": "531823", "Score": "0", "body": "Your second and third examples are not compound rspec expressions. You should either use `.and` (dot and) or `&` (single ampersand) cf https://relishapp.com/rspec/rspec-expectations/docs/compound-expectations" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T06:27:07.673", "Id": "531829", "Score": "0", "body": "@MarcRohloff Thanks a lot for your hint and the link." } ]
[ { "body": "<p>I don't know what the exercise says exactly but your describe does not match the two last expectations. You should have 3 describes because you describe three different things (a sportscar, number 30 and an array).</p>\n<pre><code>RSpec.describe &quot;sportscar&quot; do\n it &quot;should start with 'sports' and end with 'car'&quot; do\n expect(subject).to start_with(&quot;sports&quot;).and end_with(&quot;car&quot;)\n end\nend\n\nRSpec.describe 30 do\n it &quot;is even and responds to the times-method&quot; do\n numb = 30\n expect(numb.even?).to be true and numb.respond_to? :times\n end\nend\n\nRSpec.describe Array do\n it &quot;includes 32 and starts with the values 2, 4, 8&quot; do\n arr = [2, 4, 8, 16, 32, 64]\n expect(arr).to include(32) and start_with(2, 4, 8)\n end\nend\n</code></pre>\n<p>This sentence also does not make sense</p>\n<pre><code>it 30 is even and responds to the times-method\n</code></pre>\n<p>So it should be something like</p>\n<pre><code>it is even and responds to the times-method\n</code></pre>\n<p>I would also not test the implementation but functionality</p>\n<p>Instead of <code>responds_to</code> execute the function</p>\n<pre class=\"lang-rb prettyprint-override\"><code>count = 0\n30.times do { count += 1 }\nexpect(count).to eq(30)\n</code></pre>\n<p>Generally I would advice to split distinct functionality into it's own it block. <code>and</code>, <code>or</code> etc are usually a sign that there is more than one functionality. Not sure if this is part of the exercise though.</p>\n<pre class=\"lang-rb prettyprint-override\"><code>it &quot;should start with 'sports'&quot; do\n expect(subject).to start_with(&quot;sports&quot;)\nend\n\nit &quot;should end with 'car'&quot; do\n expect(subject).to end_with(&quot;car&quot;)\nend\n\n</code></pre>\n<p>To be fair, all these examples don't feel very natural.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T20:03:55.830", "Id": "269562", "ParentId": "269537", "Score": "1" } } ]
{ "AcceptedAnswerId": "269562", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T06:29:23.737", "Id": "269537", "Score": "0", "Tags": [ "ruby", "unit-testing", "rspec" ], "Title": "RSpec: Compound Expectations" }
269537
<p>I wrote a simple linear/polynomial regressor based on my previous matrix project (<a href="https://github.com/frozenca/Ndim-Matrix" rel="nofollow noreferrer">https://github.com/frozenca/Ndim-Matrix</a>).</p> <pre><code>#include &lt;Matrix.h&gt; #include &lt;algorithm&gt; #include &lt;concepts&gt; #include &lt;cctype&gt; #include &lt;functional&gt; #include &lt;stdexcept&gt; #include &lt;numeric&gt; #include &lt;ranges&gt; #include &lt;string&gt; #include &lt;vector&gt; namespace frozenca { class LinearRegression { private: std::vector&lt;float&gt; theta_; std::vector&lt;std::vector&lt;std::size_t&gt;&gt; monomials_; enum class Penalty { None, L1, L2 }; public: void fit(const std::vector&lt;std::vector&lt;float&gt;&gt;&amp; X, const std::vector&lt;float&gt;&amp; y, const std::pair&lt;std::string, float&gt;&amp; penalty = {}, std::size_t degree = 1, std::size_t batch_size = 0) { if (X.empty() || y.empty()) { throw std::invalid_argument(&quot;Data set is empty&quot;); } if (X.size() != y.size()) { throw std::invalid_argument(&quot;Data set sizes do not match&quot;); } const std::size_t n = X[0].size(); if (std::ranges::any_of(X, [&amp;n](const auto&amp; row) { return row.size() != n;})) { throw std::invalid_argument(&quot;Feature set sizes are not equal&quot;); } auto [p_type, alpha] = penalty; Penalty penalty_type = Penalty::None; std::ranges::transform(p_type, p_type.begin(), [](auto c){ return std::tolower(c);}); if (p_type == &quot;&quot;) { penalty_type = Penalty::None; alpha = 0.0f; } else if (p_type == &quot;l1&quot; || p_type == &quot;lasso&quot;) { penalty_type = Penalty::L1; if (!batch_size) { batch_size = 1; // L1 regression only can be fit via gradient descent } } else if (p_type == &quot;l2&quot; || p_type == &quot;ridge&quot;) { penalty_type = Penalty::L2; } else { throw std::invalid_argument(&quot;Unknown penalty type&quot;); } if (alpha &lt; 0.0f) { throw std::invalid_argument(&quot;Alpha value must be non-negative&quot;); } if (degree == 0) { throw std::invalid_argument(&quot;Degree must be nonzero&quot;); } const std::size_t num_samples = X.size(); if (batch_size &amp;&amp; num_samples % batch_size) { throw std::invalid_argument(&quot;Batch size must divide number of samples&quot;); } std::size_t num_features = 1; for (std::size_t k = 1; k &lt;= degree; ++k) { num_features *= (n + k); num_features /= k; } monomials_ = get_monomials(n, degree); Mat&lt;float&gt; M(num_samples, num_features); for (std::size_t i = 0; i &lt; num_samples; ++i) { auto m_i = M.row(i); construct_features(m_i, X[i], monomials_); } Vec&lt;float&gt; Y(num_samples); for (std::size_t i = 0; i &lt; num_samples; ++i) { Y[i] = y[i]; } fit_theta(M, Y, penalty_type, alpha, batch_size); } [[nodiscard]] std::vector&lt;float&gt; getTheta() { return theta_; } float predict(const std::vector&lt;float&gt;&amp; x) { if (theta_.empty()) { throw std::runtime_error(&quot;The model has not been fit yet!&quot;); } auto res = 0.0f; for (std::size_t i = 0; i &lt; theta_.size(); ++i) { res += theta_[i] * eval_monomial(x, monomials_[i]); } return res; } private: void fit_theta(const Mat&lt;float&gt;&amp; X, const Vec&lt;float&gt;&amp; Y, const Penalty&amp; penalty_type, float alpha, std::size_t batch_size) { const std::size_t num_samples = X.dims(0); const std::size_t num_features = X.dims(1); Vec&lt;float&gt; Theta (num_features); if (!batch_size) { Mat&lt;float&gt; l2_pen = identity&lt;float&gt;(num_features); l2_pen *= alpha; Theta = dot(dot(inv(dot(transpose(X), X) + l2_pen), transpose(X)), Y); } else { // gradient descent // random initialization std::mt19937 gen(std::random_device{}()); std::uniform_real_distribution&lt;float&gt; dist(-1.0f, 1.0f); for (std::size_t i = 0; i &lt; num_features; ++i) { Theta[i] = dist(gen); } constexpr std::size_t n_epochs = 100; constexpr float tolerance = 1e-7; std::size_t num_batches = num_samples / batch_size; assert(!(num_samples % batch_size)); std::vector&lt;std::size_t&gt; batch_indices (num_batches); std::iota(batch_indices.begin(), batch_indices.end(), 0lu); std::ranges::shuffle(batch_indices, gen); bool converged = false; for (std::size_t i = 0; i &lt; n_epochs; ++i) { if (converged) { break; } for (std::size_t b = 0; b &lt; num_batches; ++b) { auto xi = X.submatrix({batch_indices[b] * batch_size, 0}, {(batch_indices[b] + 1) * batch_size, num_features}); auto yi = Y.submatrix(batch_indices[b] * batch_size, (batch_indices[b] + 1) * batch_size); auto gradient = dot(transpose(xi), dot(xi, Theta) - yi); float lr = 0.1f * n_epochs * num_batches / (n_epochs + i) / (num_batches + b); gradient *= lr; if (penalty_type == Penalty::None) { Theta = Theta - gradient; } else if (penalty_type == Penalty::L2) { auto pen = Theta; pen *= lr * alpha; Theta = Theta - gradient - pen; } else if (penalty_type == Penalty::L1) { Vec&lt;float&gt; pen (num_features); for (std::size_t f = 0; f &lt; num_features; ++f) { if (Theta[f] &gt; 0.0f) { pen[f] = 1.0f; } else if (Theta[f] &lt; 0.0f) { pen[f] = -1.0f; } } pen *= lr * alpha; Theta = Theta - gradient - pen; } if (norm(gradient) &lt; tolerance) { converged = true; break; } } } } theta_.clear(); for (std::size_t i = 0; i &lt; num_features; ++i) { theta_.push_back(Theta[i]); } } // for n = 2 and degree 2, // 1, x, y, x^2, xy, y^2 // {(0, 0), (1, 0), (0, 1), (2, 0), (1, 1), (0, 2)} static std::vector&lt;std::vector&lt;std::size_t&gt;&gt; get_monomials(std::size_t n, std::size_t deg) { std::vector&lt;std::vector&lt;std::size_t&gt;&gt; d_monomials; d_monomials.push_back({0}); construct_monomials(d_monomials, n, deg); std::ranges::sort(d_monomials); return d_monomials; } // recursive construct. // 0 -&gt; 0 // -&gt; 1 // -&gt; 2 // 1 -&gt; 0 // -&gt; 1 // 2 -&gt; 0 static void construct_monomials(std::vector&lt;std::vector&lt;std::size_t&gt;&gt;&amp; d_monomials, std::size_t n, std::size_t deg) { if (!n) { return; } std::vector&lt;std::vector&lt;std::size_t&gt;&gt; new_monomials; while (!d_monomials.empty()) { auto back = d_monomials.back(); std::size_t s = back[0]; d_monomials.pop_back(); for (std::size_t d = 0; d &lt;= deg - s &amp;&amp; d &lt;= deg; ++d) { new_monomials.push_back(back); new_monomials.back().push_back(d); new_monomials.back()[0] += d; } } d_monomials = new_monomials; construct_monomials(d_monomials, n - 1, deg); } static float eval_monomial(const std::vector&lt;float&gt;&amp; sample, const std::vector&lt;std::size_t&gt;&amp; monomial) { return std::inner_product(sample.begin(), sample.end(), monomial.begin() + 1, 0.0f, std::plus&lt;&gt;(), [](auto s, auto exp) { return std::pow(s, 1.0f * exp); }); } static void construct_features(VecView&lt;float&gt;&amp; row, const std::vector&lt;float&gt;&amp; sample, const std::vector&lt;std::vector&lt;std::size_t&gt;&gt;&amp; monomials) { const std::size_t num_features = row.dims(0); const std::size_t n = sample.size(); for (std::size_t i = 0; i &lt; num_features; ++i) { row[i] = eval_monomial(sample, monomials[i]); } } }; </code></pre> <p>Test code:</p> <pre><code> std::mt19937 gen(std::random_device{}()); // linear regression example constexpr std::size_t num_samples = 100; std::uniform_real_distribution&lt;float&gt; noise(-1.0f, 1.0f); { std::vector&lt;std::vector&lt;float&gt;&gt; X; std::vector&lt;float&gt; y; // y = 3x + 4 for (std::size_t i = 0; i &lt; num_samples; ++i) { X.push_back({2.0f + noise(gen)}); y.push_back(4.0f + X.back()[0] * 3.0f + noise(gen)); } fc::LinearRegression linreg; linreg.fit(X, y); auto theta = linreg.getTheta(); for (auto t: theta) { std::cout &lt;&lt; t &lt;&lt; ' '; } std::cout &lt;&lt; '\n'; std::cout &lt;&lt; linreg.predict({1.0}) &lt;&lt; '\n'; } { std::vector&lt;std::vector&lt;float&gt;&gt; X; std::vector&lt;float&gt; y; // y = a^2 + 2ab + 3b^2 + 4a + 5b + 6 for (std::size_t i = 0; i &lt; num_samples; ++i) { auto a = 0.0f + noise(gen); auto b = 0.0f + noise(gen); X.push_back({a, b}); y.push_back(a * a + 2.0f * a * b + 3.0f * b * b + 4.0f * a + 5.0f * b + 6.0f + noise(gen)); } fc::LinearRegression linreg; linreg.fit(X, y, {}, 2); auto theta = linreg.getTheta(); for (auto t: theta) { std::cout &lt;&lt; t &lt;&lt; ' '; } std::cout &lt;&lt; '\n'; } { std::vector&lt;std::vector&lt;float&gt;&gt; X; std::vector&lt;float&gt; y; // y = a^2 + 2ab + 3b^2 + 4a + 5b + 6 // L1 regression for (std::size_t i = 0; i &lt; num_samples; ++i) { auto a = 0.0f + noise(gen); auto b = 0.0f + noise(gen); X.push_back({a, b}); y.push_back(a * a + 2.0f * a * b + 3.0f * b * b + 4.0f * a + 5.0f * b + 6.0f + noise(gen)); } fc::LinearRegression linreg; linreg.fit(X, y, {&quot;L1&quot;, 0.1f}, 2); auto theta = linreg.getTheta(); for (auto t: theta) { std::cout &lt;&lt; t &lt;&lt; ' '; } std::cout &lt;&lt; '\n'; } </code></pre> <p>Result</p> <pre><code>3.78924 3.12022 6.90945 -1.13539 4.26815 2.09389 2.83393 0.149067 0.781616 0.327844 1.17 0.244501 2.76427 3.45505 0.812552 </code></pre> <p>Feel free to comment anything!</p>
[]
[ { "body": "<p>My first thought is to change the <code>LinearRegression::fit()</code> method into a constructor called with the same arguments--that is, rename <code>void fit()</code> to <code>LinearRegression()</code>. The entire point of this class is to create a fit for data, so have the class create the fit when it is first created. As it is now, you need to lines to set up the class:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>fc::LinearRegression linreg;\nlinreg.fit(X, y);\n</code></pre>\n<p>Before the call to <code>fit()</code>, <code>linreg</code> is in a useless zombie state where none of its methods return anything useful. By making the constructor create the fit, these two lines become</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>fc::LinearRegression linreg(X, y);\n</code></pre>\n<p>Now, there's no chance of trying to use the linear regression before feeding it the data. Plus, <code>linreg</code> can be declared <code>const</code> if needed. Speaking of which, ...</p>\n<hr />\n<p>All of the other non-static classes methods should be marked with <code>const</code> because they do not change the member variable data. This will allow these methods to be called when a user creates a <code>const</code> instance of <code>LinearRegression</code> or passes an instance to a function as a <code>const LinearRegression&amp;</code> or other parameter with <code>const</code>.</p>\n<hr />\n<pre class=\"lang-cpp prettyprint-override\"><code>bool converged = false;\nfor (std::size_t i = 0; i &lt; n_epochs; ++i) {\n if (converged) {\n break;\n }\n // ...\n}\n</code></pre>\n<p>This can also be written as</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>bool converged = false;\nfor (std::size_t i = 0; i &lt; n_epochs &amp;&amp; !converged; ++i) {\n // ...\n}\n</code></pre>\n<hr />\n<p>Put an empty line before a new <code>if() block</code>. Otherwise, a reader might suspect that the <code>if()</code> should have been an <code>else if()</code> since it is grouped with the previous <code>if()</code> block.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T09:55:07.990", "Id": "269540", "ParentId": "269538", "Score": "5" } }, { "body": "<h1>Separate fitting from storing the result of the fit</h1>\n<p>Mark H already pointed out in his answer that it weird to have a class that you first have to construct, then have to call the member function <code>fit()</code> for it to store the result, and the suggestion was to make the constructor do the fitting. I would go further than that, and split up <code>class LinearRegression</code> into a free function <code>fit()</code>, and a class that holds the result of the fit. However, the result of a polynomial fit is just a polynomial. So I would create a <code>class Polynomial</code> that stores the result of the fit, so that you could write:</p>\n<pre><code>std::vector&lt;std::vector&lt;float&gt;&gt; X = {...};\nstd::vector&lt;float&gt; y = {...};\n\nPolynomial polynomial = fc::fit(X, y);\n\nfor (auto coeff: polynomial.getCoeffs())\n std::cout &lt;&lt; coeff &lt;&lt; '\\n';\n\nstd::cout &lt;&lt; polynomial({1.0}) &lt;&lt; '\\n';\n</code></pre>\n<p>It would be really nice if <code>Polynomial</code> behaved like an arithmetic type, so you could add two polynomials together for example using <code>+</code>, and so on.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T12:24:00.060", "Id": "269546", "ParentId": "269538", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T06:29:36.170", "Id": "269538", "Score": "4", "Tags": [ "c++", "machine-learning", "numerical-methods" ], "Title": "C++: Linear Regression and Polynomial Regression" }
269538
<p>I've created a simple score game. The goal is improving my knowledge about OOP.</p> <p>This is my <code>Main</code> method:</p> <pre><code>using System; namespace Snake { class Program { static void Main() { while (true) { Process.UI(); } } } } </code></pre> <p>It's very simple and just calls a method named <code>UI</code>.</p> <p>This is my <code>Snake</code> method (I named it <code>Snake</code> because it's like a snake game):</p> <pre><code>using System; using System.Collections.Generic; using System.Threading; namespace Snake { class Snake { static int headOfSnake; public static int Score { get; set; } public static void GenericRandomCircle() { Random test = new Random(); int index = test.Next(Process.ListOfDots.Count); Process.ListOfDots[index] = '■'; } public static void PositionOfSnake() { Random test = new Random(); headOfSnake = test.Next(Process.ListOfDots.Count); Process.ListOfDots[headOfSnake] = '▒'; } public static void Move(string move, int Step) { switch (move) { case &quot;w&quot;: ChangeSnakePosition(Step, -20); break; case &quot;s&quot;: ChangeSnakePosition(Step, 20); break; case &quot;a&quot;: ChangeSnakePosition(Step, -1); break; case &quot;d&quot;: ChangeSnakePosition(Step, 1); break; default: break; } } static void ChangeSnakePosition(int Step, int WhereToWhere) { try { int Counter = headOfSnake; for (int i = 0; i &lt; Step; i++) { Thread.Sleep(200); if (Process.ListOfDots[Counter + WhereToWhere] == '■') { Score++; GenericRandomCircle(); } Process.ListOfDots[Counter] = '∙'; Counter = Counter + WhereToWhere; Process.ListOfDots[Counter] = '▒'; RefreshGameBoard(); } headOfSnake = Counter; } catch { Console.ForegroundColor = ConsoleColor.Red; RefreshGameBoard(); Console.WriteLine(&quot;YOU LOSE!!! START GAME AGAIN&quot;); Environment.Exit(0); } } static void RefreshGameBoard() { Process.GameBoard(); } } } </code></pre> <p>And this is the last class called <code>Process</code> to process the game:</p> <pre><code>using System; using System.Collections.Generic; namespace Snake { class Process { static List&lt;char&gt; _listOfDots = new List&lt;char&gt;(); static bool isGenerate; static string userMove; static int userStep; public static List&lt;char&gt; ListOfDots { get { return _listOfDots; } set { _listOfDots = value; } } public static void GameBoard() { Console.Clear(); Console.WriteLine(&quot;╔═════════════════════════════════════════╗&quot;); for (int i = 0; i &lt; ListOfDots.Count; i++) { if (i % 20 == 0 &amp;&amp; i == 0) { Console.Write(&quot;║ {0} &quot;, ListOfDots[i]); continue; } else if (i % 20 == 0) { Console.Write(&quot;║\n║ {0} &quot;, ListOfDots[i]); continue; } Console.Write(&quot;{0} &quot;, ListOfDots[i]); if (i == ListOfDots.Count - 1) { Console.Write(&quot;║&quot;); } } Console.WriteLine(); Console.Write(&quot;╚═════════════════════════════════════════╝&quot;); Console.WriteLine(); } public static void ShowGuide() { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(&quot;Your Score: {0}&quot;, Snake.Score); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(&quot;up: W \t down: S \t right: D \t left: A&quot;); } public static void UI() { if (!isGenerate) { FirstGenerate(); } MoveChecks(&quot;Enter W S D A&quot;, &quot;Put numbers&quot;); Snake.Move(userMove, userStep); } static void MoveChecks(string wasdMessage, string stepMessage) { while (true) { GameBoard(); ShowGuide(); userMove = GetString(&quot;Enter W S D A to move: &quot;); if (userMove != &quot;w&quot; &amp;&amp; userMove != &quot;a&quot; &amp;&amp; userMove != &quot;s&quot; &amp;&amp; userMove != &quot;d&quot;) { GetError(String.Format(&quot;▌ {0} ▐&quot;, wasdMessage)); Console.ReadLine(); continue; } try { userStep = Convert.ToInt32(GetString(&quot;How Many Step: &quot;)); break; } catch { GetError(String.Format(&quot;▌ {0} ▐&quot;, stepMessage)); Console.ReadLine(); continue; } } } static void FirstGenerate() { while (true) { string userInput = GetString(&quot;Please Enter a number can be divided by 100 to play the game (less than 400) :&quot;); if (ListOfDots.Count &gt; 0) { GetError(&quot;You Can't Insert to the BoardGame.&quot;); return; } try { if (Convert.ToInt32(userInput) % 100 == 0 &amp;&amp; Convert.ToInt32(userInput) &lt;= 400) { for (int i = 0; i &lt; Convert.ToInt32(userInput); i++) { ListOfDots.Add('∙'); } Snake.GenericRandomCircle(); Snake.PositionOfSnake(); GameBoard(); Snake.Score = 0; isGenerate = true; break; } else { GetError(&quot;Please Enter a number divided by 100 and less than 400.&quot;); } } catch { Console.WriteLine(&quot;Please enter a number&quot;); } } } // STATIC METHODS - Once Write * EveryWhere Use. public static string GetString(string message) { Console.ForegroundColor = ConsoleColor.Cyan; Console.Write(message.ToLower()); Console.ForegroundColor = ConsoleColor.White; return Console.ReadLine(); } public static void GetError(string message) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(message); Console.ForegroundColor = ConsoleColor.White; } } } </code></pre> <p>How do you think this program can be made more object-oriented and expanded? Please tell me the problems of this program so that I can improve my knowledge. Thanks.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T20:00:20.633", "Id": "531888", "Score": "2", "body": "I was busy writing an answer and realized that I was drifting far from the topic. I decided to rather post my solution as a new [question](https://codereview.stackexchange.com/questions/269591/c-console-snake-game). No offence meant and I liked the way you formatted the output =)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T08:43:57.563", "Id": "531914", "Score": "0", "body": "@upkajdt No problem my friend. I will learn a lot from your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T12:01:25.307", "Id": "531928", "Score": "0", "body": "Cool! When you create games it is always good to split your concerns into `GameState`, `Rendering`, `HandleUserInput`, `UpdateState`, and `StateEvaluation`. A good exercise would be to take my code and see if you can add internal walls or a computer-based snake opponent. Next step, console-based PacMan / Astroids =). Please let me know if you have any questions about my code." } ]
[ { "body": "<p>Few tips:</p>\n<ol>\n<li><code>Process</code> name is conflicting with <code>System.Diagnostics.Process</code> the conflict may appear in the further development. Avoid using .NET class names. For example <code>Game</code> instead of <code>Process</code></li>\n<li>Give methods names which state what the method do e.g. <code>Game.Run()</code> instead of <code>Game.UI()</code> or <code>DrawGameBoard</code> instead of <code>GameBoard</code>.</li>\n<li>Same for variable neames <code>Random rnd</code> instead of <code>Random test</code>.</li>\n<li>To introduce OOP make everything non-<code>static</code>, then create objects using <code>new</code> keyword.</li>\n<li>A lot of <code>public</code> methods which isn't used outside of the class, make it private.</li>\n<li>Infinite, never ending loop <code>while(true)</code>. I suggest to find a way to exit the app.</li>\n</ol>\n<p>I'll show some simple example.</p>\n<p>Here's implementation via <code>static</code>.</p>\n<pre><code>public class Parent\n{\n public static Run()\n {\n Child.Go();\n }\n\n public static DoCommonJob()\n {\n }\n}\n\npublic class Child()\n{\n public static Go()\n {\n Parent.DoCommonJob();\n }\n}\n\nclass Program\n{\n static void Main()\n {\n Parent.Run();\n }\n}\n</code></pre>\n<p>That's how it looks now.</p>\n<p>The following example avoids <code>static</code> starting using objects.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class Parent\n{\n private Child child;\n\n public Parent()\n {\n child = new Child(this);\n }\n\n public Run()\n {\n child.Go();\n }\n\n public DoCommonJob()\n {\n }\n}\n\npublic class Child()\n{\n private Parent parent;\n\n public Child(Parent parent)\n {\n this.parent = parent;\n }\n\n public Go()\n {\n parent.DoCommonJob();\n }\n}\n\nclass Program\n{\n static void Main()\n {\n Parent parent = new Parent();\n parent.Run();\n }\n}\n</code></pre>\n<p>But here's obvious not good solution, cyclic dependency: Parent depends on Child, while Child depends on Parent. It commonly acceptable but can cause problems in future development.</p>\n<p>This can be solved by introducing 3rd class where's common method located.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class Common\n{\n public DoCommonJob()\n {\n }\n}\n\npublic class Parent\n{\n private Child child;\n private Common common;\n\n public Parent(Common common)\n {\n this.common = new Common();\n this.child = new Child(common);\n }\n\n public Run()\n {\n child.Go();\n }\n}\n\npublic class Child()\n{\n private Common common;\n\n public Child(Common common)\n {\n this.common = common;\n }\n\n public Go()\n {\n common.DoCommonJob();\n }\n}\n\nclass Program\n{\n static void Main()\n {\n Parent parent = new Parent();\n parent.Run();\n }\n}\n</code></pre>\n<p>Both <code>Parent</code> and <code>Child</code> depends on <code>Common</code> while there's no cyclic dependency. Now it looks fine.</p>\n<p>Note: <code>new</code> keyword creates new instance of the class every time you call it.</p>\n<p>For example, this one won't work as expected according to current logic</p>\n<pre class=\"lang-cs prettyprint-override\"><code>while(true)\n{\n Game game = new Game();\n game.Run();\n}\n</code></pre>\n<p>But this one will</p>\n<pre class=\"lang-cs prettyprint-override\"><code>Game game = new Game();\nwhile(true)\n{\n game.Run();\n}\n</code></pre>\n<p>Feel the difference.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T08:44:35.863", "Id": "531915", "Score": "0", "body": "Thank you very much for taking the time to analyze my code. It is very valuable to me. A question about Part 4: So when do we need to use static methods and members of the class?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T10:32:04.387", "Id": "531917", "Score": "1", "body": "@CarlJohnson for example Singleton pattern implementation `SomeClass.Instance`, named constructors pattern `SomeClass.Create()`, and a lot more useful patterns." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T12:08:09.463", "Id": "531929", "Score": "1", "body": "@CarlJohnson, Static variables/methods belong to the class definition itself. A good example of this is `DateTime.Now`. Non-static variables/methods belong to the objects created from a class definition for instance `var date = new DateTime(); date.AddDays(5);`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-31T10:58:46.170", "Id": "269576", "ParentId": "269541", "Score": "2" } }, { "body": "<p>in the method <code>ChangeSnakePosition(int Step, int WhereToWhere)</code> the variable <code>WhereToWhere</code> should not be int, instead you can create enum called Direction</p>\n<pre><code>public enum Direction\n{\n up,\n down,\n left,\n right,\n}\n</code></pre>\n<p>then the method signature will be</p>\n<pre><code>ChangeSnakePosition(int Step, Direction direction)\n</code></pre>\n<p>this will help in better reading in calling</p>\n<pre><code>ChangeSnakePosition(Step, -20);\n</code></pre>\n<p>instead of a crapy number, it will become a readable value</p>\n<pre><code>ChangeSnakePosition(Step, Direction.up);\n</code></pre>\n<hr>\n<p>beside @aepot mentions that you don't have to use static everywhere, your methods should be return what it tries to calculate,\nfor example in <code>Process</code> class the following method</p>\n<pre><code>void MoveChecks(string wasdMessage, string stepMessage)\n</code></pre>\n<p>should return a <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-tuples\" rel=\"nofollow noreferrer\">tuple</a> with direction and steps as following</p>\n<pre><code>(Direction dir,int step) MoveChecks(string wasdMessage, string stepMessage)\n// you should rename this method to be getDirectionFromUser instead of indescribable MoveChecks\n</code></pre>\n<p>Then you can safely delete unnecessary property <code>int userStep</code> and <code>string userMove</code>. The calling will be as following</p>\n<pre><code>var result = MoveChecks(&quot;Enter W S D A&quot;, &quot;Put numbers&quot;);\nSnake.Move(result.dir, result.step); // to do: don't use statics \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T16:21:02.750", "Id": "531959", "Score": "0", "body": "Thank you very much for your reply. It's very valuable to me. \nnow I have a clear idea of ​​where I can use enum." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-01T11:02:58.667", "Id": "269609", "ParentId": "269541", "Score": "2" } } ]
{ "AcceptedAnswerId": "269576", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-30T10:45:49.863", "Id": "269541", "Score": "3", "Tags": [ "c#", "game", "console", "visual-studio" ], "Title": "I made a Simple Score Game in C# Console" }
269541